Implement remember me tokens safely
Implement a remember-me login with a separate long-lived selector and validator token, stored hashed, that is replaced each time it is used.
A remember-me cookie is a second password with a longer life. Split it in two so a database lookup is fast, and the secret half is never stored.
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
const hash = (v) => createHash('sha256').update(v).digest();
export async function issue(db, userId) {
const selector = randomBytes(9).toString('base64url');
const validator = randomBytes(32).toString('base64url');
await db.insert({ selector, validatorHash: hash(validator), userId, expires: Date.now() + 30 * 864e5 });
return `${selector}.${validator}`;
}
export async function redeem(db, cookie) {
const [selector, validator] = cookie.split('.');
const row = await db.findBySelector(selector);
if (!row || row.expires < Date.now()) return null;
if (!timingSafeEqual(hash(validator ?? ''), row.validatorHash)) {
await db.deleteAllFor(row.userId); // a wrong validator for a real selector means theft
return null;
}
await db.delete(row.selector);
return { userId: row.userId, next: await issue(db, row.userId) };
}The selector finds the row, so you never compare a secret in a query, and the validator is compared in constant time against a stored hash. Each use deletes the old token and issues a new one. If someone presents a correct selector with a wrong validator, the token was probably stolen, so every remember-me token for that user is deleted. This is the scheme from Paragon Initiative's write-up.
Require the password again for sensitive actions such as changing the email, even when someone arrived through this cookie.