Password reset
In short
- The threat
Whoever can reset a password owns the account, so a careless reset flow is a second login form with weaker defences.
- The rule
Answer every request the same, spend the token once and only at the write, and end every session when the password changes.
- In the package
flows/password-reset.ts, configured underpasswordReset.
What goes wrong
Section titled “What goes wrong”Whoever can reset a password owns the account, so the reset flow is a second login form with weaker defences unless it is built as carefully as the first. It can go wrong four ways:
- it can leak which addresses exist;
- its links can be replayed or leak through a
Refererheader; - two tabs can race the same link;
- a reset that leaves old sessions alive does not remove an intruder who already got in.
A reset link lives 1 h, and issuing a new one replaces the old. Applying it runs in order: peek at the token without spending it, check the new password against the policy and the breach check, run the hooks (a second-factor plugin asks for its code here), hash the new password, consume the token atomically, and write the new hash. A password the policy refuses stops at the check with weak_password, and the link still works. Two tabs with the same link both get as far as consume, and only one gets past it: the other is refused because the link is already spent, so exactly one write wins. A completed reset revokes every session, voids every outstanding reset token, lifts the lockout, marks the address verified unless that is turned off, and mails the owner that the password changed. No session is issued.
Text version
The rule
Section titled “The rule”Treat a reset as a login by mailbox: quiet on the way in, spent once, thorough on the way out.
The request is uniform and does nothing on the response path
Section titled “The request is uniform and does nothing on the response path”requestPasswordReset validates the input, applies the per-IP limit and hands a job to your queue (or runs it detached). The job looks the account up, checks the per-account mail limit (3 an hour) and mails the link. Known and unknown addresses get the same answer in the same time.
The job carries the IP and user agent of the request, so wherever it runs, the password.reset_issued audit row (written once the link or code is stored, before its mail is handed over, with data.kind link or code) and the mail’s meta name the request that asked. A request that sends nothing writes password.reset_request_ignored instead.
One live token, spent once
Section titled “One live token, spent once”A reset link is 32 random bytes, stored only as its SHA-256, valid for an hour. Issuing a new one replaces the old. Applying it runs in this order:
- Peek: look the token up without spending it, so a typo in the new password does not burn the link.
- Check the new password against the policy and the breach check.
- Hooks: run them; a second-factor plugin asks for its code here (A044).
- Hash the new password.
- Consume the token atomically. Of two concurrent resets with the same link, exactly one gets past this step (A007).
- Void every other reset link, code and ticket of the account, and an email change started under the old password.
- Write the new hash.
Voiding comes before the write, so a crash before the write or a refused write leaves the old password and no live link, and the user asks again (a write that throws is the exception below); it never leaves a ticket or a link requested meanwhile that could still set a password (A007). A password change does the same.
Checking a link when the page loads
Section titled “Checking a link when the page loads”auth.inspectPasswordReset({ token, meta }) looks the link (the ticket in code mode) up without spending it and without mailing anything. A live one answers { userId, email, expiresAt, secondFactorRequired } (only the account’s id and address: anyone holding the link sees the answer), so the page can show the code field up front when resetPassword will ask for a second factor. An unknown, expired or spent one answers invalid_token whichever it is, and the audit row (password.reset_inspect_failed) names no account for an unknown token. Inspections count on the same password-reset door as resets, so checking a link gives no more guesses than applying it. A page that checks its link and then resets spends two hits of that door (10 a minute per IP by default); raise throttle.doors['password-reset'] if many of your users share an IP. Post the token from the page as you post the reset itself; never put it in a query string.
secondFactorRequired comes from the passwordResetRequirements hooks: the two-factor plugin answers it for a confirmed factor, and an app that demands its own factor in beforePasswordReset answers it there too. Any hook that says secondFactor: true wins. A hook can also return the refusal its beforePasswordReset would give (an account your app closed), and the check answers it; an account in an email revert lockout answers invalid_token, as its reset does.
Codes become tickets
Section titled “Codes become tickets”With passwordReset.kind: 'code' the mail carries 8 digits instead. A correct code is exchanged for a ticket valid for 10 minutes, and only the ticket can set the password. The code is checked once and never authorises the write itself. Two caps stand in front of it (A013):
| Cap | Default | Counts |
|---|---|---|
| Per code | 5 wrong guesses | At the code that was mailed |
| Per address | 5 guesses per 15 minutes per address | From every network, known address or not, code outstanding or not |
A completed reset cleans up
Section titled “A completed reset cleans up”- Every session is revoked, so an intruder who already got in is signed out (A010).
- Every outstanding reset token is voided, before the write and once more right after it, so a link requested while the write ran dies too, even when ending the sessions fails.
- The lockout is lifted: the mailbox was proved.
- The address is marked verified unless you turn that off.
- The owner gets a “password changed” mail.
Once the hash is written the password has changed, so a failure to lift the lockout or mark the address verified is logged (Step after a password write failed, with the step and the user id) and the reset still answers ok. Both fail closed: the lock stays until it ends or an admin clears it. A failure to end the sessions still fails the reset, since a session it could not end may be the intruder’s. So does a sweep after the write that fails twice in a row, and then a link requested during the write may stay live until it expires. Neither stops the other: the sessions end even when the sweep failed. Either way the password has changed, so the password.reset event is written and the “password changed” mail is sent before the reset throws.
A write that throws is the one case where the reset cannot know: a store can commit the new hash and then lose the connection before it answers. So the reset ends every session as it does after a write (and sweeps the links again), writes password.reset_failed with reason write_failed, and throws. The link is spent, and the account may have either password. Tell the user to try the new one, and to ask for another reset if it does not work.
No session is issued: the user signs in with the new password.
A password change (changePassword) closes the same way, and a failure to end the sessions or of the sweep after the write throws there too, after the password.changed event and the mail. The password has changed and the caller’s own session may already be revoked, but no new session is issued. A write that throws ends every session the same way, writes password.change_failed with reason write_failed and throws; then the password may or may not have changed. Treat any throw from changePassword as signed out: send the user to sign in (with the new password, or the old one if that fails) rather than retrying the change.
Voiding resets from your own code
Section titled “Voiding resets from your own code”The package voids an account’s reset tokens itself whenever it writes a password or confirms an email change. A change your own code makes needs the same: an email change you run yourself, an admin moving the account to a new address, a support “secure this account” action. A link mailed to an address the account no longer uses lets whoever reads that mailbox take the account. Call auth.revokePasswordResets({ userId, meta }) right after the change:
- it deletes the account’s reset links, and in code mode its codes and tickets, so each answers
invalid_tokenfrom then on; a link requested after the call works as usual; - it touches nothing else: a pending email change, a revert link and a verification link stay live;
- it never mails, and it is safe to repeat: an account with nothing to void succeeds the same;
- it answers
{ revoked }and writespassword.reset_revoked({ userId }, withmetawhen you pass it) only when it removed a live link, code or ticket.
It does not end sessions or change the password: pair it with auth.context.revokeAllSessions when the change should also sign the account out.
Keep the token out of logs and referrers
Section titled “Keep the token out of logs and referrers”Put it in the URL fragment or path, not the query string, and serve the page with Referrer-Policy: no-referrer.
In code
Section titled “In code”The defaults written out, and the two routes a reset needs.
import type { AuthConfig, AuthUser } from '@noctcore/auth';
type AppConfig = AuthConfig<AuthUser, unknown, []>;type PasswordResetOptions = NonNullable<AppConfig['passwordReset']>;
// The defaults, written out. Pass them as `passwordReset` to createAuth, or// leave the option out for the same values.export const passwordReset = { // A link: 32 random bytes, stored only as its SHA-256. kind: 'link', ttl: '1h', // With kind: 'code', the mail carries digits instead (ttl then defaults // to 15m), and a correct code becomes a ticket that sets the password. digits: 8, maxAttempts: 5, ticketTtl: '10m', // A completed reset proves the mailbox. markEmailVerified: true,} satisfies PasswordResetOptions;import { toPublicError, type RequestMeta } from '@noctcore/auth';import type { AppAuth } from '../build/node-server/auth';
/** "Forgot password": the same answer for every address, at once. */export async function forgotPassword(auth: AppAuth, input: { email: string; meta: RequestMeta }) { const result = await auth.requestPasswordReset(input);
if (!result.ok) return { error: toPublicError(result) };
// The lookup, the per-account mail limit and the mail run off this path. return { status: 'check-your-email' as const };}
/** * The reset page POSTs the token from the URL fragment as it loads: a dead * link gets its own page, and a reset that will ask for a second factor shows * the code field before the user types a new password. Nothing is spent. */export async function checkResetLink(auth: AppAuth, input: { token: string; meta: RequestMeta }) { const result = await auth.inspectPasswordReset(input);
// Unknown, expired and spent links answer the same `invalid_token`. if (!result.ok) return { error: toPublicError(result) };
return { status: 'live' as const, expiresAt: result.value.expiresAt, secondFactorRequired: result.value.secondFactorRequired, };}
/** The reset page POSTs the token it read from the URL fragment. */export async function setNewPassword( auth: AppAuth, input: { token: string; password: string; meta: RequestMeta },) { // Peek, check the password, run the hooks, hash, consume, void every // other reset token, write. // A refused password leaves the link unspent. const result = await auth.resetPassword(input);
if (!result.ok) return { error: toPublicError(result) };
// Every session was revoked and none is issued: sign in again. return { status: 'password-changed' as const };}Where the package and the guide differ
Section titled “Where the package and the guide differ”The guide does not prescribe a reset flow in detail; the package follows the original production flow and adds the stricter pieces:
- no work on the request path;
- peek before consume, and a link check on page load that spends nothing;
- every reset token voided before the password is written;
- revocation of every session;
- a mandatory notification mail.
Apps whose invitation logic depends on emailVerified can set passwordReset.markEmailVerified: false.
Attack tests
Section titled “Attack tests”| Test | Attack | Stopped by |
|---|---|---|
| A007 | Reusing a password reset token | tokens/one-time-tokens.ts, flows/password-reset.ts |
| A010 | A stolen session cookie outliving a password change | flows/password-change.ts, flows/password-reset.ts, session/session-manager.ts |
| A013 | Guessing a short code | tokens/one-time-tokens.ts, flows/password-reset.ts |
| A044 | Resetting the password of a two-factor account without the factor | plugins/two-factor/hooks.ts, flows/password-reset.ts |
Further reading
Section titled “Further reading”- Auth sessions in Pilcrow’s auth guide, on invalidating sessions after credential changes.
- OWASP Forgot Password Cheat Sheet.