Skip to content

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 under passwordReset.

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 Referer header;
  • two tabs can race the same link;
  • a reset that leaves old sessions alive does not remove an intruder who already got in.

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.

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:

  1. Peek: look the token up without spending it, so a typo in the new password does not burn the link.
  2. Check the new password against the policy and the breach check.
  3. Hooks: run them; a second-factor plugin asks for its code here (A044).
  4. Hash the new password.
  5. Consume the token atomically. Of two concurrent resets with the same link, exactly one gets past this step (A007).
  6. Void every other reset link, code and ticket of the account, and an email change started under the old password.
  7. 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.

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.

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
  • 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.

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_token from 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 writes password.reset_revoked ({ userId }, with meta when 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.

Put it in the URL fragment or path, not the query string, and serve the page with Referrer-Policy: no-referrer.

The defaults written out, and the two routes a reset needs.

password-reset.ts
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;

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.

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