feat: customer password reset via email round-trip (#32)
SonarQube Analysis / sonarqube (pull_request) Successful in 2m57s
Tests / backend-unit (pull_request) Successful in 53s
Tests / frontend-e2e (pull_request) Failing after 7m40s
Tests / backend-integration (pull_request) Failing after 3h14m41s

Adds "Forgot password?" to the login page, a request page, and a reset
page reached by a one-hour, single-use token delivered by email. Reuses
customer_tokens with a new password_reset kind alongside verify_email.

The request endpoint always answers 200, whether or not the address has
an account, so it cannot be used to test addresses for membership. Note
/register still reveals existence through its 409 on a duplicate, so this
protection is currently partial; closing that is its own change.

Completing a reset deletes every session for that customer. A reset
prompted by a compromise has to evict the intruder, and leaving a 30-day
cookie alive would defeat the point. It also marks the address verified,
since receiving the mail is exactly what verification proves, and
supersedes any outstanding token so an older link in the inbox cannot be
resurrected.

Introduces the first rate limiting in the codebase, on the request
endpoint only. The limiter is keyed on caller *and* submitted address:
keying on IP alone would let one person lock out everyone behind the same
proxy, and everything arrives via Nginx Proxy Manager. Applying that same
limiter to the reset endpoint, which carries no address, collapsed every
caller into one shared bucket -- so that endpoint is deliberately
unlimited instead, protected by a 32-byte single-use token whose bcrypt
work only runs after the token matches.

The e2e tests read the issued token directly from Postgres rather than
through a test-support endpoint. An endpoint returning a reset token for
an arbitrary address is account takeover for every customer if it is ever
reachable, and an environment gate is thin protection against that.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-17 17:36:19 -05:00
co-authored by Claude Opus 5
parent c04f4a1370
commit db7c61c89d
13 changed files with 946 additions and 24 deletions
+35
View File
@@ -0,0 +1,35 @@
import rateLimit from 'express-rate-limit';
import { Request } from 'express';
// First rate limiting in the codebase. The password-reset endpoints need it
// most: without one, anyone can make the server send unlimited mail to any
// address. Login and registration are the obvious next candidates.
//
// The default in-memory store suits a single-instance deployment, which this
// is. Running more than one app container would need a shared store, or each
// instance would enforce its own separate allowance.
const WINDOW_MS = 15 * 60 * 1000;
const MAX_REQUESTS = 5;
// Keyed on caller *and* address rather than caller alone. Keying on IP only
// would let one person's reset attempts lock out everyone behind the same
// NAT or reverse proxy — and everything here arrives via Nginx Proxy Manager,
// so a great many customers share an apparent address.
//
// This key only makes sense on a request that carries an email. Applying the
// same limiter to an endpoint without one collapses every caller into a single
// `ip:` bucket, which is a shared allowance rather than a per-caller one.
function keyByCallerAndEmail(req: Request): string {
const email = typeof req.body?.email === 'string' ? req.body.email.toLowerCase().trim() : '';
return `${req.ip}:${email}`;
}
export const passwordResetRequestLimiter = rateLimit({
windowMs: WINDOW_MS,
limit: MAX_REQUESTS,
keyGenerator: keyByCallerAndEmail,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: { error: 'too many attempts, please try again later' }
});
+94
View File
@@ -5,6 +5,8 @@ import { pool } from '../db';
import { requireCustomer } from '../middleware/customerAuth';
import { sendMail } from '../mailer';
import { MARKETING_CONSENT_TEXT, isValidEmail } from '../utils';
import { asyncRoute } from '../asyncRoute';
import { passwordResetRequestLimiter } from '../rateLimit';
const router = Router();
@@ -93,6 +95,98 @@ router.post('/verify-email', async (req: Request, res: Response) => {
res.json({ status: 'verified' });
});
const RESET_TOKEN_TTL_MS = 60 * 60 * 1000;
// Always answers 200, whether or not the address has an account. A response
// that differed would let anyone test addresses for membership.
//
// Note /register still reveals existence via its 409 on a duplicate address,
// so this protection is currently partial — closing that is its own change.
router.post('/request-password-reset', passwordResetRequestLimiter, asyncRoute(async (req: Request, res: Response) => {
const email = String(req.body?.email || '').toLowerCase().trim();
if (!email || !isValidEmail(email)) {
return res.status(400).json({ error: 'a valid email is required' });
}
const { rows } = await pool.query(`SELECT * FROM customers WHERE email = $1`, [email]);
const customer = rows[0];
if (customer) {
// Supersede any outstanding token, so a link cannot be resurrected later
// from an older message in the customer's inbox.
await pool.query(`DELETE FROM customer_tokens WHERE customer_id = $1 AND kind = 'password_reset'`, [customer.id]);
const token = crypto.randomBytes(32).toString('hex');
await pool.query(
`INSERT INTO customer_tokens (token, customer_id, kind, expires_at) VALUES ($1, $2, 'password_reset', $3)`,
[token, customer.id, new Date(Date.now() + RESET_TOKEN_TTL_MS)]
);
const resetUrl = `${process.env.PUBLIC_URL}/reset-password?token=${token}`;
sendMail(
customer.email,
'Reset your Redefined Designs password',
`<p>Someone asked to reset the password for this account.</p>
<p><a href="${resetUrl}">Choose a new password</a>. This link expires in one hour.</p>
<p>If this wasn't you, you can ignore this email — your password has not changed.</p>`
).catch(err => console.error('password reset email send failed', err));
}
res.json({ status: 'sent' });
}));
// Deliberately not rate limited. The limiter above is keyed on the submitted
// email, which this endpoint does not carry, so reusing it would put every
// customer completing a reset into one shared bucket. Nor is a limit needed
// here: the token is 32 random bytes, single-use, and expires in an hour, and
// the expensive bcrypt hash only runs *after* the token has been matched, so
// invalid guesses cost a single indexed lookup.
router.post('/reset-password', asyncRoute(async (req: Request, res: Response) => {
const { token, password } = req.body || {};
if (!password || String(password).length < 8) {
// Checked before the token is looked at, so a rejected attempt does not
// consume the customer's only reset link.
return res.status(400).json({ error: 'password must be at least 8 characters' });
}
const { rows } = await pool.query(
`SELECT * FROM customer_tokens WHERE token = $1 AND kind = 'password_reset' AND expires_at > now()`,
[token]
);
if (!rows.length) return res.status(400).json({ error: 'invalid or expired token' });
const customerId = rows[0].customer_id;
const passwordHash = await bcrypt.hash(String(password), 12);
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(
// The customer has demonstrably received mail at this address, which is
// exactly what verification proves, so an unverified address becomes
// verified here.
`UPDATE customers SET password_hash = $1, email_verified = true WHERE id = $2`,
[passwordHash, customerId]
);
// Every existing session goes, including any an attacker holds. Without
// this, a reset prompted by a compromise leaves the intruder signed in for
// up to 30 days.
await client.query(`DELETE FROM customer_sessions WHERE customer_id = $1`, [customerId]);
await client.query(`DELETE FROM customer_tokens WHERE customer_id = $1 AND kind = 'password_reset'`, [customerId]);
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
const { rows: fresh } = await pool.query(`SELECT * FROM customers WHERE id = $1`, [customerId]);
const sessionToken = await createSession(customerId);
setSessionCookie(res, sessionToken);
res.json(publicCustomer(fresh[0]));
}));
router.post('/login', async (req: Request, res: Response) => {
const { email, password } = req.body;
const { rows } = await pool.query(`SELECT * FROM customers WHERE email = $1`, [String(email || '').toLowerCase().trim()]);