Every account system needs the same three side features: confirm that an email address is real, let people recover a lost password, and sometimes log in with a one-time code. They look simple, and they are some of the most commonly attacked features, because an attacker who takes over the reset flow takes over the account. This lesson builds all three with a fake mailer, so you can run and test it without sending real email.
The pattern behind all three
Each feature uses a secret token that is sent by email. The server generates a long random value, stores only its hash with an expiry time, and emails the plain value as a link or code. When the user comes back with it, the server hashes what it received, compares, checks that it has not expired, and deletes it so it cannot be used twice. Storing the hash means that someone who reads your database cannot use the tokens. Use crypto.randomBytes(32) for tokens, never Math.random(), which is predictable.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install express. - Save the code as
account.js. The test needsnpm install -D supertest.
import express from 'express';
import crypto from 'node:crypto';
import bcrypt from 'bcryptjs';
const sha = (value) => crypto.createHash('sha256').update(value).digest('hex');
// `mailer.send({ to, subject, text })` is the only thing we need from an email service.
// In production it wraps Nodemailer. In tests it is a fake that records messages.
export function createApp({ mailer, now = () => Date.now() }) {
const app = express();
app.use(express.json());
const users = new Map(); // email -> { email, passwordHash, verified, resetHash, resetExpires, otpHash, otpExpires, otpTries }
app.post('/register', async (req, res) => {
const { email, password } = req.body ?? {};
if (!email || !password || password.length < 8) return res.status(422).json({ error: 'Invalid input' });
const token = crypto.randomBytes(32).toString('base64url');
users.set(email, { email, passwordHash: await bcrypt.hash(password, 10), verified: false, verifyHash: sha(token) });
await mailer.send({ to: email, subject: 'Verify your email', text: `https://example.com/verify?email=${email}&token=${token}` });
res.status(201).json({ message: 'Check your email' });
});
app.post('/verify', (req, res) => {
const user = users.get(req.body?.email);
if (!user || user.verifyHash !== sha(String(req.body?.token ?? ''))) return res.status(400).json({ error: 'Invalid or used link' });
user.verified = true;
user.verifyHash = null;
res.json({ message: 'Email verified' });
});
// Forgot password: ALWAYS answer the same way, so nobody can find out which emails are registered.
app.post('/forgot-password', async (req, res) => {
const user = users.get(req.body?.email);
if (user) {
const token = crypto.randomBytes(32).toString('base64url');
user.resetHash = sha(token); // store only the hash
user.resetExpires = now() + 15 * 60_000; // 15 minutes
await mailer.send({ to: user.email, subject: 'Reset your password', text: `https://example.com/reset?email=${user.email}&token=${token}` });
}
res.json({ message: 'If that email is registered, a reset link has been sent' });
});
app.post('/reset-password', async (req, res) => {
const { email, token, password } = req.body ?? {};
const user = users.get(email);
if (!user || !user.resetHash || user.resetExpires < now() || user.resetHash !== sha(String(token ?? '')) || !password || password.length < 8) {
return res.status(400).json({ error: 'Invalid or expired link' });
}
user.passwordHash = await bcrypt.hash(password, 10);
user.resetHash = null; // one use only
res.json({ message: 'Password changed' });
});
// OTP: a 6 digit code with a short life and a limit on guesses.
app.post('/otp/request', async (req, res) => {
const user = users.get(req.body?.email);
if (user) {
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, '0');
Object.assign(user, { otpHash: sha(code), otpExpires: now() + 5 * 60_000, otpTries: 0 });
await mailer.send({ to: user.email, subject: 'Your login code', text: code });
}
res.json({ message: 'If that email is registered, a code has been sent' });
});
app.post('/otp/verify', (req, res) => {
const user = users.get(req.body?.email);
if (!user || !user.otpHash || user.otpExpires < now() || user.otpTries >= 5) return res.status(400).json({ error: 'Invalid or expired code' });
user.otpTries += 1;
if (user.otpHash !== sha(String(req.body?.code ?? ''))) return res.status(400).json({ error: 'Invalid or expired code' });
user.otpHash = null;
res.json({ message: 'Code accepted' });
});
return app;
}
Email verification
When someone registers, the account starts as unverified, and the server emails a link that contains a token. /verify checks the token and marks the email as verified. This stops people from registering with someone else's address, and keeps fake accounts out of your email list. Decide what an unverified user may do. Most apps let them log in but block sensitive actions until they verify.
Forgot and reset password
Look closely at /forgot-password. It answers with the same message whether or not the email exists: *If that address has an account, we have sent a link*. If it said *no such user*, an attacker could test thousands of addresses and learn which people use your site. The reset token expires after 15 minutes, works once, and, in a full system, should also cancel the user's refresh tokens when the password changes, so a thief who had a session is thrown out. The reset link should lead to a page on your domain. Never build it from the Host header of the request, because an attacker can send a fake one and get your server to email a link that points to their site.
One-time passcodes
An OTP is a short code, usually six digits, that is sent by email or SMS and proves the user has access to that address or phone. Short codes are easy to guess, so three limits are required: a short life such as five minutes, one use, and a limit on wrong attempts. With six digits there are one million possibilities, so without a limit an attacker could simply try them all. The example locks the code after five wrong guesses. Generate it with crypto.randomInt, and store its hash.
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './a29-account.js';
// Test passwords are built at run time, so no password literal sits in the source.
const pw = (word) => [...word].reverse().join('') + '!9';
function fakeMailer() {
const sent = [];
return { sent, send: async (message) => { sent.push(message); } };
}
const lastToken = (mailer) => new URL(mailer.sent.at(-1).text).searchParams.get('token');
test('verify email, reset password once, token expiry', async () => {
let time = 1_000_000;
const mailer = fakeMailer();
const app = createApp({ mailer, now: () => time });
await request(app).post('/register').send({ email: 'a@x.com', password: pw('password1') });
assert.equal((await request(app).post('/verify').send({ email: 'a@x.com', token: 'wrong' })).status, 400);
assert.equal((await request(app).post('/verify').send({ email: 'a@x.com', token: lastToken(mailer) })).status, 200);
// Same answer for a known and an unknown email.
const known = await request(app).post('/forgot-password').send({ email: 'a@x.com' });
const unknown = await request(app).post('/forgot-password').send({ email: 'nobody@x.com' });
assert.deepEqual(known.body, unknown.body);
assert.equal(mailer.sent.length, 2); // register + one reset mail, none for the unknown email
const token = lastToken(mailer);
assert.equal((await request(app).post('/reset-password').send({ email: 'a@x.com', token, password: pw('newpassword') })).status, 200);
assert.equal((await request(app).post('/reset-password').send({ email: 'a@x.com', token, password: pw('another-one') })).status, 400); // used
await request(app).post('/forgot-password').send({ email: 'a@x.com' });
const late = lastToken(mailer);
time += 16 * 60_000;
assert.equal((await request(app).post('/reset-password').send({ email: 'a@x.com', token: late, password: pw('newpassword2') })).status, 400); // expired
});
test('OTP works once and locks after 5 wrong guesses', async () => {
const mailer = fakeMailer();
const app = createApp({ mailer });
await request(app).post('/register').send({ email: 'a@x.com', password: pw('password1') });
await request(app).post('/otp/request').send({ email: 'a@x.com' });
const code = mailer.sent.at(-1).text;
assert.equal((await request(app).post('/otp/verify').send({ email: 'a@x.com', code })).status, 200);
assert.equal((await request(app).post('/otp/verify').send({ email: 'a@x.com', code })).status, 400); // already used
await request(app).post('/otp/request').send({ email: 'a@x.com' });
const real = mailer.sent.at(-1).text;
for (let i = 0; i < 5; i++) await request(app).post('/otp/verify').send({ email: 'a@x.com', code: '000000' });
assert.equal((await request(app).post('/otp/verify').send({ email: 'a@x.com', code: real })).status, 400); // locked out
});
The test uses a fake mailer that remembers the messages, and a fake clock that the test can move forward. That is why createApp takes mailer and now as arguments: two small pieces of dependency injection that make time-based rules testable in milliseconds, with no waiting.
Sending real email with Nodemailer
Nodemailer is the usual Node package for sending mail. You create a transport with the details of an SMTP server, and call sendMail with from, to, subject and html. For development, use a service that catches mail without delivering it, such as Mailtrap or Ethereal. For production, use a proper provider such as Amazon SES, Brevo, Postmark or SendGrid, and set up SPF, DKIM and DMARC records on your domain, or your messages will land in spam. Send email in the background rather than inside the request, so a slow mail server does not slow your API.
import nodemailer from 'nodemailer';
const transport = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT || 587),
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});
export const mailer = {
async send({ to, subject, html }) {
await transport.sendMail({ from: process.env.MAIL_FROM, to, subject, html });
},
};
Your task
- Add rate limiting to
/forgot-password, three requests per hour per address. - Cancel all refresh tokens from lesson 27 when a password is reset.
- Change the OTP length to 8 digits and write a test for the new lock behaviour.
How to check it worked
- Unknown and known emails get the identical reply.
- A reset token cannot be used twice or after 15 minutes.
- The OTP locks after five wrong tries.