Implement password reset tokens with expiry
Create a password reset link with a random token that is stored hashed, expires in an hour and works once.
A reset link is a temporary password sent over email. Treat it like one: random, short-lived and used once.
import { randomBytes, createHash } from 'node:crypto';
const sha = (v) => createHash('sha256').update(v).digest('hex');
export async function requestReset(db, email) {
const user = await db.findUserByEmail(email);
if (user) {
const token = randomBytes(32).toString('base64url');
await db.saveReset({ userId: user.id, hash: sha(token), expires: Date.now() + 60 * 60 * 1000 });
await mail(user.email, `https://example.com/reset?token=${token}`);
}
return { message: 'If that address exists, we sent a link.' };
}
export async function applyReset(db, token, newPassword) {
const reset = await db.findReset(sha(token));
if (!reset || reset.expires < Date.now()) return false;
await db.setPassword(reset.userId, await argon2.hash(newPassword));
await db.deleteResetsFor(reset.userId);
await db.deleteSessionsFor(reset.userId);
return true;
}The response is the same whether or not the email exists, so the form does not reveal accounts. Only the hash is stored, so a database leak does not give out working links. After use, delete every reset token and every session for the user. See the OWASP forgot password cheat sheet.
Send the link over HTTPS only, set Referrer-Policy: no-referrer on the reset page so the token does not leak to third parties, and rate limit the request route.