Skip to content

Email change

The core has four flows for changing the account’s email: requestEmailChange, confirmEmailChangeCode (or confirmEmailChangeLink), and revertEmailChange. Why each rule is there is in Email change. This guide builds on A Node server with Redis and Prisma.

  • A user store with changeEmail. PrismaUserStore and MemoryUserStore have it. The method is optional on the UserStore port so older adapters still compile, and the email change flows throw an AuthConfigError without it. A store of your own must keep the email column unique and pass the changeEmail cases of userStoreConformance (see Writing a store adapter).
  • urls.revertEmailChange. The link mailed to the old address. The flows throw an AuthConfigError without it. Put the token in the fragment, as the node-server sample does, and send Referrer-Policy: no-referrer.
  • Templates for four mail events: email-change-confirm, email-change-in-use, email-changed and email-change-reverted (Mail).

No new table: the code, the revert link, the hold on the old address, the block after a revert and the lockout after a refused revert are rows of the one-time token table you already have, under their own purposes. Every row is filed under a real user id, so the user relation that auth.prisma suggests for cascading deletes works; the hold is found by the SHA-256 of its address in the hash column.

The library holds the old address for its owner while the revert link lives, and its own sign-up, invitation sign-up (invitations.register) and email change flows refuse a held address as taken. Paths your app owns do not go through those flows: an admin “create user”, a first sign-in through SSO, imports. The library’s flows do not all read the hold the same way: sign-up, invitation sign-up and auth.isAddressHeld ignore a hold whose holder is gone, while email change requests and confirms use a stricter raw lookup that still refuses it. Each of your paths must call auth.isAddressHeld(email) and refuse a held address the way it refuses a taken one, before it creates the user or gives an account that address. If one of them does not, the old address can get an account, and the owner’s revert cannot finish (below).

src/routes/email.ts
import type { RequestMeta, StoredSession } from '@noctcore/auth';
import type { AppAuth } from '../node-server/auth';
type Session = StoredSession<Record<string, never>>;
/**
* Step 1, from the settings page. The answer is the same whether or not the
* address has an account: show "check the new address" either way.
*/
export async function requestChange(
auth: AppAuth,
session: Session,
body: { newEmail: string; code?: string },
meta: RequestMeta,
) {
const requested = await auth.requestEmailChange({
session,
newEmail: body.newEmail,
// With the two-factor plugin: a code, unless the session holds a step-up.
...(body.code ? { secondFactor: body.code } : {}),
meta,
});
// fresh_auth_required: ask for the password (auth.reauthenticate), then retry.
// second_factor_required: ask for a code, then retry with it.
if (!requested.ok) return { status: 403, body: { error: requested.code } };
return { status: 202, body: { expiresAt: requested.value.expiresAt } };
}
/** Step 2: the code from the new address, typed in the same signed-in session. */
export async function confirmChange(
auth: AppAuth,
session: Session,
code: string,
meta: RequestMeta,
) {
const confirmed = await auth.confirmEmailChangeCode({ session, code, meta });
if (!confirmed.ok) return { status: 400, body: { error: confirmed.code } };
// Every other session was signed out; this one was re-issued under a new cookie.
return { status: 200, cookies: [confirmed.value.session.cookie], body: { changed: true } };
}
/**
* The page behind the revert link in the old address's mail. No session: the
* person clicking it may be locked out. Read the token from the fragment in the
* browser and POST it here, so it never reaches a server log or a Referer.
*/
export async function revertChange(auth: AppAuth, token: string, meta: RequestMeta) {
const reverted = await auth.revertEmailChange({ token, meta });
if (!reverted.ok) return { status: 400, body: { error: reverted.code } };
// The password is gone too: send the user to "forgot password" for the restored address.
return { status: 200, body: { next: '/forgot-password' } };
}

Request. The session must be live and its last credential proof, read from the stored session, younger than session.freshAuthAge (10 minutes by default), or the answer is fresh_auth_required: send the user through auth.reauthenticate and retry. With the two-factor plugin on and a factor confirmed, the request also needs a step-up held by the session or a code in secondFactor, or it answers second_factor_required. A new address that already has an account gets the same success answer and the same expiresAt as a free one, and its owner gets email-change-in-use instead of a code, so show “check the new address” either way. A new request replaces a pending one; a password change or reset, or signing out of other devices or everywhere, voids it. While the revert link of an earlier change is live, a new request answers forbidden (reason email_change_pending_revert in the audit row): tell the user they can change the address again once the link sent to their old address expires. Requests are limited per account (3 an hour) and per new address (3 an hour, from every account).

Confirm. The code is typed in a live signed-in session of the same account; in link mode (emailChange.kind: 'link', with urls.confirmEmailChange) the link works only in such a session too, and is left unspent anywhere else, a revoked session included. On success the account moves to the new address, which is marked verified; every session of the account is revoked and the caller’s is re-issued, so set the cookie of the session it returns. Reset and verification tokens mailed to the old address die, and the old address gets email-changed at once. If another account took the new address after the request, the answer is email_in_use; the confirmer has just proved that mailbox, so the answer tells them nothing about anyone else.

Revert. The old address’s mail carries a link valid for 7 days (emailChange.revertTtl, which cannot be shorter). It needs no session. It moves the account back to the old address and removes the password in one write, then revokes every session, voids every reset, verification and pending change token. Second factors stay: a revert cannot tell the owner’s factor from one an intruder enrolled, and whoever reads the old mailbox must not be able to strip the owner’s (A063). The next sign-in therefore fails until the user resets the password, and the reset goes to the restored address: tell them so on the page. The address the account lost is blocked for this account for 30 days (emailChange.blockAfterRevert), and the audit row email.change_reverted carries review: true. Route it to whoever looks at suspicious accounts.

If the old address has an account again (an app path that skipped isAddressHeld, a race with sign-up, or a direct store write), the revert answers email_in_use with reason email_revert_address_taken. It has still removed the password and revoked every session and pending token, and the email.change_revert_failed row carries review: true and lockedOut: true. Tell the user to contact support.

The lockout after a refused revert. The account still names the intruder’s address, so the revert also locks it out. The lockout never lapses on its own. While it lives, no session is issued for the account by any flow or plugin (your own SSO through issueSession included; a login answers like a wrong password), a reset request for it sends nothing (the request answers as always), and a reset link for it answers invalid_token (refused before the new password is hashed, so it costs what a dead link costs). The owner’s revert link lives as long as the lockout (it is extended only while it still exists and has not expired, so a link spent by a concurrent click is not written back and one that expired meanwhile is not revived). Both are stored to expire at the start of 9999-12-31 UTC rather than renewed, because a renewal would depend on something running in time; every SQL date column (MySQL’s DATETIME included) and a Redis TTL can hold that value, and the token store conformance suite checks it. If your own token store sweeps rows by expiresAt, it keeps these. It ends in one of two ways:

  • the owner clicks the same link again once the old address is free, which restores it and ends the lockout;
  • support calls auth.clearEmailRevertLockout({ userId, meta }), which writes email.revert_lockout_cleared with review: true and also voids the owner’s revert link and the hold on the old address. Do this only once the account is on an address its owner controls: clearing it while the account still names the intruder’s address hands that address a working reset.

For support: find the account from the email.change_revert_failed row, free the old address (it belongs to whoever created the account on it), and send the owner back to their link. If the old address cannot be freed, move the account to an address the owner controls in your store, then clear the lockout and have the owner reset the password. Always clear once the account is settled: the clear is what kills the revert link, which was stretched to the lockout’s expiry. A revert link also refuses (invalid_token, reason email_revert_address_moved) as soon as the account no longer names the address the change moved it to, so moving the account is safe even before the clear, but a stale link and hold should not be left in the store.

An address change your own code makes. Moving an account to a new address outside these flows (a migration, an admin tool, support) skips the cleanup a confirm does. Call auth.revokePasswordResets({ userId, meta }) with it, so a reset link mailed to the old address dies; see Voiding resets from your own code.

What is not atomic. Each flow is a series of store calls, not a transaction. Confirm writes the revert link and the hold before it moves the address, and revokes sessions after; a store error between leaves at worst an unmailed revert link for an address that did not move, which blocks nothing. Revert removes the password in the same write as the restore, sets the lockout if the restore was refused, and revokes sessions right after; a store error after the restore leaves the link unspent, and clicking it again runs every step again.

Code From Show
fresh_auth_required request the password prompt, then retry
second_factor_required, invalid_second_factor request the code prompt, then retry
invalid_email request “enter a valid address” (also for the account’s current address)
email_not_ascii request “use an address without accents or non-Latin letters” (only with email.normalize: 'ascii')
forbidden request an earlier change can still be reverted, the address was blocked after a revert, or one of your hooks refused
invalid_token confirm, revert “the code or link is wrong or expired”
email_in_use confirm, revert the address was taken meanwhile
session_expired any sign in again
rate_limited any “try again later”, with retryAfterSeconds
Option Default
emailChange.kind 'code' 'link' needs urls.confirmEmailChange.
emailChange.ttl '15m' for codes, '1h' for links
emailChange.digits 8 6 to 9.
emailChange.maxAttempts 5 Wrong guesses per code, counted before each comparison.
emailChange.revertTtl '7d' The minimum; a shorter value is refused at startup.
emailChange.blockAfterRevert '30d'

Your own beforeEmailChange hook runs after the fresh-auth check and before anything is issued. It is given the normalised new address; refuse with a code that does not reveal whether that address is taken.

  • One change per revert window. While a revert link is live the account cannot start another change, even when the user made the first one themselves. A typo the user noticed late waits for the link to expire, or for support.
  • The hold covers the library’s flows only. Sign-up, invitation sign-up, change requests and confirms refuse a held address. Your own user-creating paths must call isAddressHeld; the library cannot see them. Sign-up also checks the hold before its insert, so a race can slip through. When the old address gets an account anyway, the revert cannot restore it: the account is locked out (no session, no reset) until the owner finishes or support clears it, however long that takes.
  • Sign-up on a held address is matched in answer and round-trip count, not in timing. It gives the taken-address answer and mail, and its answer waits on the same number of store round trips (three: the request limit, the hold lookup every sign-up makes, then one more). That last one is a read of the holder where a taken or new address does its insert, so a held address answers faster by the difference between a read and an insert. The owner lookup and the mail run after the answer on every path. Every sign-up checks the hold before its insert, so the check adds one indexed read to every sign-up once your store has changeEmail.
  • Deleting and restoring an account. auth.isAddressHeld answers false once the holding account is gone, matching the revert, which refuses a missing account. An app that soft deletes an account and restores it while its revert link is still live may find the old address registered by someone else in the meantime, and the revert then answers email_in_use with reason email_revert_address_taken.
  • A revert keeps every second factor, the intruder’s too. If the intruder enrolled a factor while they held the account, the owner’s reset after the revert asks for it and the owner cannot pass it. For that case support verifies the owner outside the account (the old mailbox alone proves nothing: the intruder may read it too), then resets the factor with auth.twoFactor.reset({ userId, actor, meta }) (factor, recovery codes and trusted devices, audited and mailed) and has the owner reset the password. The email.change_reverted row (review: true) is where to start.
  • A new address’s request limit can be spent by others. email-change-address (3 an hour) counts requests to an address from every account, so anyone signed in who knows it can stall changes to it for an hour.