What's the need so that some dapp websites ask you to sign messages
It establishes that the signer knows the private key for a given ethereum address. For example, Etherscan will let you configure the website, social media links, logo, etc., for a given contract, but first you have to show that it's your contract by signing a message from the same account that deployed the contract, to show that you can.
can this message that you sign be anything as long as it's not the hack transaction?
I'm not sure what "as long as it's not the hack transaction" means.
A common pattern is to create a hash of an arbitrarily long message and sign that. Consider an API endpoint that uses Ethereum signing to authenticate users. The POST might look something like:
// arbitrarily long
signature: <short string>
- Sign the hash
- Send the package
On the receiving side:
- sender = ECRecover(messageHash, signature)
where does the signature that metamask gets after we sign the message go
does the website store it ? or does the website just wait if the signature was generated and if so, what does it do so that for each next request, it thinks that user is already authenticated ?
Whatever it wants to do. See the previous answer for a possibility. As a caution item it is usually a good idea to add some kind of replay protection to the overall scheme so a signed message can't be used more than once. For example, Ethereum uses
nonce so "send money" can't be sent repeatedly once people see the signature.
for the second and 3rd and so on requests, how does user stay authenticated
This all depends on what the app is using signatures for. It could, for example, authenticate once and set a persistent session state. Or, it would work on the basis of signing every message, i.e. every interaction with an API is authenticated.
Hope it helps.