4 ms·
> If your app has a server component that acts on this state, be super careful about acting on it and treat it as you would any other input under user control.
by typingerror 4y ago
> If your app has a server component that acts on this state, be super careful about acting on it and treat it as you would any other input under user control.
I would recommend signing it if it's generated by the server component, and checking the signature when the server component is provided this signed state.
For example to do this in Node is quite straightforward.
Key generation:
const crypto = require('crypto');
crypto.generateKeyPair('ed25519', (e, pubkey, privkey) => {
// save pubkey and privkey somewhere
// ...
}
Signing:
const data = Buffer.from(JSON.stringify(state));
const signature = crypto.sign(null, data, privkey);
const signeddata = `${data.toString('base64')}.${signature.toString('base64')}`.replace(/=/g,'');
Verification:
const parts = signeddata.split('.');
const data = Buffer.from(parts[0], 'base64');
const signature = Buffer.from(parts[1], 'base64');
if (crypto.verify(null, data, pubkey, signature)) {
// signature not verified, throw or return
// ...
}
const state = JSON.parse(data);
As the above uses Ed25519 the signatures are quite small too. It needs a bit more error checking, and might need extras like expiry time and such, but should be roughly sufficient.
- AndrewStephens 4y agoGood advice. For some apps you might also need to protect against replay attacks to prevent the user from reverting to a previous state in a way that you app should not allow (undo'ing a change of bank balance, etc). But if your state is so important it is probably better to not uses these techniques at all and just store the state on the server.
- awb 4y agoThis technique is client-side data only, so updating a client-side state would only appear to revert your bank balance on the UI, but wouldn’t trigger any server-side functions to do so. If you sent the client state to the server for some type of CRUD action or persistence, you’d need to sanitize and validate it first. And at that point like you said, why not just keep the state secure server-side and not trust the client.
- ivanhoe 4y agoExcellent idea for those apps that need that type of protection. For many apps however ability to manually edit the link to get to the different state is actually a free bonus feature. I've built a CRM/Cases management app for the client that stores data filters in the url, and while there's a nice UI to control filters, we observed that lots of users simply go and edit the url directly to quickly get what they need.
- Brometheus 4y agoI did this for passing parameter to a twitter card generator php script :joy: