Two-factor
The two-factor plugin, @noctcore/auth/two-factor, adds a TOTP second factor with recovery codes, trusted devices and step-up. Why each rule is there is in Second factors. Like the core, it has no HTTP endpoints: its flows live under auth.twoFactor, and your routes call them. This guide builds on A Node server with Redis and Prisma.
The store and the cipher
Section titled “The store and the cipher”The plugin needs a TwoFactorStore and a SecretCipher.
- Store.
PrismaTwoFactorStorefrom@noctcore/auth-prisma(copy the four two-factor models from itsprisma/auth.prismaand migrate) orRedisTwoFactorStorefrom@noctcore/auth-redis. The factor and the recovery codes are account data, so on Redis keep them only with persistence on.MemoryTwoFactorStorefrom@noctcore/auth/testingis for tests. Your own store must passtwoFactorStoreConformance(see Writing a store adapter). - Cipher. The plugin never sees a key. TOTP secrets are encrypted by the cipher you hand it, and only its output is stored. This one uses AES-256-GCM with the user id as associated data, and names its key in each ciphertext so you can rotate:
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';import type { SecretCipher } from '@noctcore/auth';
const IV_BYTES = 12;const TAG_BYTES = 16;
/** * AES-256-GCM with the user id as associated data, so a ciphertext copied onto * another user's row fails to decrypt. Each ciphertext names its key, so a new * key can be added (and made current) without re-encrypting the old rows. * * keys: key id -> 32 random bytes, from your KMS or secret store, never the repo. */export function aesGcmCipher(keys: ReadonlyMap<string, Uint8Array>, currentKeyId: string): SecretCipher { const key = (id: string) => { const bytes = keys.get(id);
if (!bytes || bytes.length !== 32) throw new Error(`No 32-byte key ${id}`);
return bytes; };
key(currentKeyId);
return { async encrypt(secret, { userId }) { const iv = randomBytes(IV_BYTES); const cipher = createCipheriv('aes-256-gcm', key(currentKeyId), iv, { authTagLength: TAG_BYTES });
cipher.setAAD(Buffer.from(userId, 'utf8'));
const body = Buffer.concat([cipher.update(secret), cipher.final()]); const parts = [iv, body, cipher.getAuthTag()].map((part) => part.toString('base64url'));
return `${currentKeyId}.${parts.join('.')}`; },
async decrypt(ciphertext, { userId }) { const [keyId = '', ivText = '', body = '', tagText = ''] = ciphertext.split('.'); const iv = Buffer.from(ivText, 'base64url'); const tag = Buffer.from(tagText, 'base64url');
// A short tag would make forgery cheaper: refuse anything but the full 16 bytes. if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) throw new Error('Malformed ciphertext');
const decipher = createDecipheriv('aes-256-gcm', key(keyId), iv, { authTagLength: TAG_BYTES });
decipher.setAAD(Buffer.from(userId, 'utf8')); decipher.setAuthTag(tag);
return new Uint8Array(Buffer.concat([decipher.update(Buffer.from(body, 'base64url')), decipher.final()])); }, };}Generate each key with openssl rand -base64 32 and keep it with your other secrets, not in the database the ciphertexts live in. To rotate, add a key, make it current, and the old rows keep decrypting with the old one.
Wiring the plugin
Section titled “Wiring the plugin”import { createAuth, type Mailer } from '@noctcore/auth';import { argon2id } from '@noctcore/auth/argon2';import { prismaStores, PrismaTwoFactorStore } from '@noctcore/auth-prisma';import { redisStores } from '@noctcore/auth-redis';import { twoFactor } from '@noctcore/auth/two-factor';import { Redis } from 'ioredis';import { aesGcmCipher } from './cipher';import { prisma } from '../node-server/db';
const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379');
const cipher = aesGcmCipher( new Map([['k1', Buffer.from(process.env.TOTP_KEY_K1 ?? '', 'base64')]]), 'k1',);
export function buildAuth(mailer: Mailer) { return createAuth({ stores: { ...prismaStores({ delegate: prisma.user, tokenDelegate: prisma.authToken }), ...redisStores(redis, { prefix: 'auth:' }), }, password: { hasher: argon2id() }, secret: process.env.AUTH_SECRET ?? '', urls: { resetPassword: (token) => `https://app.example/reset-password#${token}` }, mailer, plugins: [ twoFactor({ store: new PrismaTwoFactorStore({ factor: prisma.authTwoFactor, recoveryCodes: prisma.authRecoveryCodes, trustedDevice: prisma.authTrustedDevice, stepUp: prisma.authStepUp, }), cipher, issuer: 'Acme', // Who must have a factor: admins here. Without one they get an enrollment challenge. required: ({ user }) => user.email.endsWith('@acme.example'), }), ], });}
export type AppAuth = ReturnType<typeof buildAuth>;| Option | Default | |
|---|---|---|
store, cipher |
required | |
issuer |
required | The name the authenticator app shows. |
required |
never | ({ user }) => boolean: users who must have a factor. Without one they get an enrollment challenge at login, never a session. |
enforcement |
off | ({ user }) => { required, graceEndsAt? }: a requirement with a grace window, checked on every request; see Enforcement with a grace period. Pass it or required, not both. |
enforcementStanding |
'live' |
'at-issue' (or { mode: 'at-issue', version?, maxAge? }): with enforcement, a session issued unrestricted skips the per-request reads for maxAge (default '1d'); see Standing decided at issue. |
enrollmentWindow |
'10m' |
How long a pending secret from enroll accepts its confirmation code; positive, at most '24h'. See Settings and step-up. |
stepUpWindow |
'10m' |
How long a code proved in a session counts for sensitive actions. |
trustedDevices |
{ ttl: '30d', maxPerUser: 5 } |
false turns “remember this device” off (and stops honouring devices trusted before). ttl must be at least a minute (the allowed clock skew) shorter than the session store’s epochTtlMs (the Redis store’s epochTtl). |
attempts |
5 per '15m' |
Code checks per user, from every IP together, before the factor locks. |
perIp |
10 per '1m' |
Code checks per IP. |
importedRecoveryCodes |
none | { hash }: accept recovery codes carried over from your earlier scheme. See Moving existing TOTP users over. |
Turning a factor on or off and spending a recovery code each send a mail event (two-factor-enabled, two-factor-disabled, recovery-code-used), so add them to your templates (Mail).
With the plugin on, auth.login answers { kind: 'challenge', challenge, methods } for a user with a factor, after a correct password and without a session. The challenge lasts 5 minutes and takes 5 codes; it is bound to the browser’s user agent. The browser sends it back with a code, a recovery code, or nothing but the trusted-device cookie:
import type { RequestMeta } from '@noctcore/auth';import type { AppAuth } from './auth';
/** POST /login: a session, or a challenge the browser answers on the next screen. */export async function login(auth: AppAuth, body: { email: string; password: string }, meta: RequestMeta) { const result = await auth.login({ email: body.email, password: body.password, meta });
if (!result.ok) return { status: 401, body: { error: result.code } };
if (result.value.kind === 'challenge') { // `methods` is ['enroll'] for a user the app requires a factor of who has none yet. return { status: 200, body: { challenge: result.value.challenge, methods: result.value.methods } }; }
return { status: 200, cookies: [result.value.session.cookie], body: { ok: true } };}
/** POST /login/second-factor: a code, a recovery code, or the trusted-device cookie. */export async function secondFactor( auth: AppAuth, body: { challenge: string; code?: string; recoveryCode?: string; rememberDevice?: boolean }, cookieHeader: string | null, meta: RequestMeta,) { const device = auth.twoFactor.readTrustedDeviceToken(cookieHeader); const proof = body.recoveryCode ? ({ kind: 'recovery-code', code: body.recoveryCode } as const) : body.code ? ({ kind: 'totp', code: body.code } as const) : ({ kind: 'trusted-device', token: device } as const);
const result = await auth.twoFactor.verifyChallenge({ challenge: body.challenge, proof, rememberDevice: body.rememberDevice === true, meta, });
// One answer for every refusal: the reason is in your audit log, not the response. if (!result.ok) return { status: 401, body: { error: result.code } };
const { session, trustedDevice, recoveryCodes } = result.value; const cookies = trustedDevice ? [session.cookie, trustedDevice.cookie] : [session.cookie];
// recoveryCodes is set only when this challenge was an enrollment: show them once. return { status: 200, cookies, body: { ok: true, recoveryCodes } };}Every refusal answers invalid_second_factor (or rate_limited); the reason, such as wrong_code, code_replayed or factor_locked, is only in the audit row. Show the same message for all of them.
Your beforeSessionCreate hooks run after a correct password, before any challenge is made (via: 'password', beforeChallenge: true), and again for the session (via: 'second-factor', or 'password' when no challenge is due). An account they refuse gets invalid_credentials, counted as a wrong password in the lockout, and no challenge, so keep your sign-in refusals there and leave code at its default. With the plugin on, every password login runs them twice.
If your app re-issues the caller’s session from a flow of its own (a password change, “sign out everywhere else”), issue it through a plugin’s context.issueSession(user, { via: 'my-flow', inherit: session, authenticatedAt: session.authenticatedAt, meta }); pass authenticatedAt unless the flow just proved the password, or the old session comes back as freshly authenticated. For a user with a factor, it goes through only when session is live and was created after the enrollment window closed, or holds an open step-up (ask for one with stepUp otherwise). That is a best effort with known gaps (see Learn: Second factors), so turn the factor on with revokeOtherSessions: true. If the flow ends sessions first, call context.confirmLiveSession(session) before that and pass what it returns as inherit.
When methods is ['enroll'], the user is one you require a factor of and has none yet. Pass the challenge to auth.twoFactor.enroll({ challenge, meta }) to get a secret, show it, and send the first code to verifyChallenge as a TOTP proof: it turns the factor on and returns the session with the recovery codes.
Sign-ins and checks your app runs itself
Section titled “Sign-ins and checks your app runs itself”A sign-in your app authenticated itself (an identity provider’s callback, a magic link of its own) gets the same challenge through auth.twoFactor.challenge({ userId, rememberMe?, epoch?, meta }). It answers null when no factor is due (the user has no confirmed factor and none is required, or there is no such user): issue your own session then. Otherwise it answers { challenge, methods }, exactly as auth.login does, and verifyChallenge finishes it with a second-factor session that carries rememberMe; a trusted-device cookie passes it as after a password. Read epoch with context.sessions.readEpoch(userId) before your own credential check, so a revocation during it voids the session; without it the epoch is read when the challenge starts. Each call counts on the plugin’s perIp limit, and the codes are counted at the verify on the factor’s own budget. It does not run your beforeSessionCreate hooks before the challenge, since your own flow decided the user may sign in; they run for the session.
A second factor without a session (an app-owned reset, an invitation that overwrites an existing account’s password) is checked with auth.twoFactor.verifyProof({ userId, proof?, action, meta }). Call it, with or without a proof, only for someone who already proved control of the account (a mailbox link, say, as inspectPasswordReset does), never on a form that names any account. Without proof it answers ok({ proved: false }) when the user has no confirmed factor (or there is no such user) and second_factor_required when it has one: show the code field then. That answer reveals whether the account has a factor, and it writes no audit row. With proof it answers ok({ proved: true }) for a right code and invalid_second_factor for anything else, a user with no factor or no user included, after the same store calls; show the code, not the reason. A right or wrong code for a user with a confirmed factor uses the challenge’s budget, so wrong codes lock that factor (and climb the permanent lockout tier when you turned it on) just as at login: the reason to keep the call behind proof of control. A code for a user without one is counted on a key of its own and never locks the account or climbs the tier. It uses the challenge’s replay guard and recovery-code spend (with its mail), writes two_factor.verified or two_factor.failed with your action, and never issues or touches a session. Every call, with or without a proof, counts on the plugin’s perIp limit.
An admin reset of another user’s factor is auth.twoFactor.reset({ userId, actor?, meta }), for a support agent who verified a locked-out user out of band. Call it only after your own checks: it trusts the caller. It deletes the factor (pending or confirmed), the recovery codes and the trusted devices, and answers { reset: true }, or { reset: false } with nothing done when there was no factor. A reset writes two_factor.reset (userId the user, data.confirmed, and data.actor your admin’s id when you pass it), and a confirmed factor’s owner gets two-factor-disabled with reset: true. The user’s next login gets no challenge (or an enrollment challenge when you require a factor). Ending the user’s sessions stays your call (context.revokeAllSessions(userId, reason)), except with enforcement on, where resetting a confirmed factor ends them itself (see Standing decided at issue). A step-up proof a session already holds survives the reset until that session ends, so after a takeover revoke the sessions too. The mail is the same two-factor-disabled the owner gets for turning the factor off: make your template read reset, or it tells the user they turned it off themselves.
Enforcement with a grace period
Section titled “Enforcement with a grace period”required is checked once, at login: a user without a factor never gets a session. When you turn the requirement on for users who already have accounts (a tenant that starts requiring a factor, say), give them a grace window with enforcement instead. Your policy answers per user, so the tenant, role or plan it hangs on stays in your app:
- In the window, sign-in works as usual and every validated session carries
twoFactor: { state: 'grace', graceEndsAt }(milliseconds since the epoch). Show a reminder. - After the window, the user still signs in, but the session is
twoFactor: { state: 'enrollment-only' }: it reaches only the routes you mark for enrollment. Everything else answers403withtwo_factor_enrollment_required. Enrolling is the settings flow above (fresh password proof,enroll,confirmEnrollment); once the factor is confirmed the standing is gone on the next request. - Checked live. The standing is computed on every request, never stored in the session, so a policy change or a closing window applies on the next request, without a new sign-in. The policy runs only for users without a confirmed factor (an enrolled user costs one store read), but it runs on each of their requests: cache your tenant rules (the example below expires and bounds its cache), and expect a change to apply once that cache does.
statusasks the policy once per call. - Or decided at issue. With
enforcementStanding: 'at-issue'the standing is also computed when a session is issued, and a session issued unrestricted is stamped and validates without any read. See Standing decided at issue. - Fail closed. A policy that throws, or answers nothing, reads as required with the window over (enrollment-only), and is logged by the error’s name only. An unreadable
graceEndsAtmeans no grace. - The sweep.
auth.twoFactor.sweepUnenrolled({ userIds })revokes every session of each listed user who is required, past the window and still without a confirmed factor, with reasontwo-factor-required(youronSessionsRevokedhook hears it). Each user is read again right before the revocation, so one who enrolled (or whose rule changed) during the sweep keeps their sessions. Users in the window, users with a factor and unknown ids are skipped; a user whose policy throws is skipped and counted infailed, since validation already confines that session. Pass any iterable or async iterable, so a large tenant can be paged from your database, and run it from your scheduler.
import { createAuth, type AuthUser, type Mailer, type ValidatedSession } from '@noctcore/auth';import { argon2id } from '@noctcore/auth/argon2';import { prismaStores, PrismaTwoFactorStore } from '@noctcore/auth-prisma';import { redisStores } from '@noctcore/auth-redis';import { twoFactor, type TwoFactorPolicy } from '@noctcore/auth/two-factor';import { Redis } from 'ioredis';import { aesGcmCipher } from './cipher';import { prisma } from '../node-server/db';
const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379');
const cipher = aesGcmCipher( new Map([['k1', Buffer.from(process.env.TOTP_KEY_K1 ?? '', 'base64')]]), 'k1',);
/** Your tenant's rule: since when it requires a factor, and how long existing members get. */export interface TenantRule { readonly requiredSince: Date | null; readonly graceDays: number;}
const DAY = 24 * 60 * 60 * 1000;
const RULE_TTL = 30_000;const MAX_CACHED_RULES = 10_000;
/** * The policy is asked on every request of a member without a factor: cache the * rule briefly. An entry is written on a miss only, so it expires after * `RULE_TTL` however active the user is, and the map never holds more than * `MAX_CACHED_RULES` entries. */function tenantPolicy(loadRule: (user: AuthUser) => Promise<TenantRule>) { const cache = new Map<string, { rule: TenantRule; until: number }>();
return async ({ user }: { readonly user: AuthUser }): Promise<TwoFactorPolicy> => { const now = Date.now(); const hit = cache.get(user.id); let rule = hit && hit.until > now ? hit.rule : undefined;
if (!rule) { rule = await loadRule(user);
if (cache.size >= MAX_CACHED_RULES) { for (const [id, entry] of cache) if (entry.until <= now) cache.delete(id); }
// Still full of live entries: drop the oldest (a Map keeps insertion order). if (cache.size >= MAX_CACHED_RULES) cache.delete(cache.keys().next().value as string);
cache.set(user.id, { rule, until: now + RULE_TTL }); }
if (!rule.requiredSince) return { required: false };
return { required: true, graceEndsAt: rule.requiredSince.getTime() + rule.graceDays * DAY }; };}
export function buildAuth(mailer: Mailer, loadRule: (user: AuthUser) => Promise<TenantRule>) { return createAuth({ stores: { ...prismaStores({ delegate: prisma.user, tokenDelegate: prisma.authToken }), ...redisStores(redis, { prefix: 'auth:' }), }, password: { hasher: argon2id() }, secret: process.env.AUTH_SECRET ?? '', urls: { resetPassword: (token) => `https://app.example/reset-password#${token}` }, mailer, plugins: [ twoFactor({ store: new PrismaTwoFactorStore({ factor: prisma.authTwoFactor, recoveryCodes: prisma.authRecoveryCodes, trustedDevice: prisma.authTrustedDevice, stepUp: prisma.authStepUp, }), cipher, issuer: 'Acme', // In place of `required`: checked on every request, with a grace window. enforcement: tenantPolicy(loadRule), }), ], });}
export type AppAuth = ReturnType<typeof buildAuth>;
/** Without an adapter: what each route does with the standing validation attached. */export function gate(session: ValidatedSession<Record<string, never>>, enrollmentRoute: boolean) { const standing = session.twoFactor;
if (standing?.state === 'enrollment-only' && !enrollmentRoute) return { status: 403, body: { error: 'two_factor_enrollment_required' } };
// In the grace window: let it through, and show a banner until graceEndsAt. return { status: 200, banner: standing?.state === 'grace' ? standing.graceEndsAt : null };}
/** From your scheduler, once a day: sign out the members who let the grace window pass. */export async function sweepTenant(auth: AppAuth, memberIds: AsyncIterable<string>) { const { checked, revoked, failed } = await auth.twoFactor.sweepUnenrolled({ userIds: memberIds });
return { checked, revoked: revoked.length, failed };}With an adapter, mark what an enrollment-only session may reach: @TwoFactorEnrollment() on a NestJS route or controller (NestJS), or meta: { twoFactorEnrollment: true } on a tRPC procedure (tRPC). Mark the enrollment routes, status, re-authentication and sign out; the marker opens nothing else, so roles and fresh-auth still apply. Public routes and procedures run for anyone, so they ignore the standing: do not hand account data out of one. status reports the standing too, as enforcement (null when the factor is on or none is required).
Standing decided at issue
Section titled “Standing decided at issue”The live check costs a factor read on every request of every user, and a user read and a policy call for each user without a factor. If most of your users are never required, enforcementStanding: 'at-issue' (with enforcement) keeps that cost off their requests. The object form is { mode: 'at-issue', version?, maxAge? }: version defaults to '1', maxAge to '1d' (positive, at most '30d').
Which sessions skip the read. A session issued while the user had a confirmed factor, or while your policy answered not required, carries a stamp in the twoFactorStanding session attribute and validates without reading the factor, the user or the policy. The stamp is a keyed hash, under a key derived from your server secret, of the user, the version, the user’s revocation epoch read before the answer, and the time of issue. A session skips only while its stamp verifies for its own user and epoch under the current version and is younger than maxAge. A copied stamp (an app hook, a legacy store, another user’s session) does not verify, and a stamp past maxAge is checked live, so even a change nobody signalled reaches every session within maxAge.
Which sessions are read live. Every other session, exactly as with 'live': one issued in the grace window or enrollment-only (so the window closing, enrolling or the policy lifting applies on the next request), one whose stamp is older than maxAge, one issued before you turned the option on or under another version, and one whose stamp your attribute schema dropped.
How a change reaches a stamped session. Nothing about the user is read on a stamped session’s requests, so every change that could restrict it ends it instead:
- You require a factor of a user, or change their policy: call
auth.twoFactor.refreshStanding({ userId }). It ends the user’s sessions (reasontwo-factor-standing, exported asTWO_FACTOR_STANDING_REVOCATION; the epoch also voids their trusted devices), and their next sign-in is stamped from the new answer, so a user moved into a grace window signs in again to a grace session. It revokes wheneverenforcementis on, under'live'too: a stamp issued during an earlier spell under'at-issue'(a rollback, a rolling deploy with both modes running) would otherwise count again when the option comes back. Withoutenforcementit does nothing (revoked: false). - A policy change for many users (a tenant that starts requiring a factor): pass a new
version. Sessions stamped under the old one are read live again, and the grace and enrollment-only standings apply on their next request. - An admin resets the factor (
twoFactor.reset): withenforcementon, in either mode, resetting a confirmed factor ends the user’s sessions (reasontwo-factor-reset, exported asTWO_FACTOR_RESET_REVOCATION). - A sign-in that read the old answer just before a refresh cannot keep a stamp: the stamp carries the epoch read before the answer, so a session minted after the refresh either loses the core’s epoch fence or carries a stamp of the old epoch (read live).
- A re-issue (a password change, or your own via with
inherit) is stamped again from a fresh read at that moment, with a new issue time, never from the stamp it inherits. A session whosetwoFactorStandingone of your ownsessionAttributeshooks replaced (one that spreadsinherited, say) is refused (forbidden, reasontwo_factor_standing_replaced, logged).
A change you neither refresh nor version reaches a stamped session within maxAge, or when it ends; sweepUnenrolled still revokes the sessions of required users past their window, so keep running it. A policy whose answer changes with time by itself (required from a date) needs a refresh or a new version at that date to apply sooner. A deleted user’s stamped session is not read either, where 'live' reads it as enrollment-only: end the sessions when you delete the user.
Your attribute schema. With session.attributes, let twoFactorStanding through as an optional string. createAuth probes the schema: one that accepts {} but refuses the stamp fails with an AuthConfigError, and one that drops it logs a warning (it only costs the reads). A schema that requires keys of its own cannot be probed this way; check it yourself.
Settings and step-up
Section titled “Settings and step-up”Turning the factor on from the settings page needs a fresh password proof (session.freshAuthAge, 10 minutes by default; send the user through auth.reauthenticate if it is older). enroll returns the base32 secret and an otpauth:// uri to show as a QR code. The secret becomes active only when a code from it comes back within enrollmentWindow (10 minutes by default, at most 24 hours; expiresAt follows it). A longer window helps users who set the authenticator up on another device or with help, but confirming still needs a fresh password proof, so past session.freshAuthAge send them through auth.reauthenticate first. An enrollment challenge (a required user at login) still ends with the challenge, 5 minutes, whatever the window. The window also dates when a factor counts as set up for your own re-issue of a session (a session created after it closed passes): shrinking it while enrollments are pending lets a session created between the new and the old end pass, so turn factors on with revokeOtherSessions: true if you shrink it.
import type { RequestMeta, StoredSession } from '@noctcore/auth';import type { AppAuth } from './auth';
type Session = StoredSession<Record<string, never>>;
/** Settings, step 1: a pending secret to show as a QR code (from `uri`) and as text. */export async function startEnrollment(auth: AppAuth, session: Session, meta: RequestMeta) { const started = await auth.twoFactor.enroll({ session, meta });
if (!started.ok) return { status: 403, body: { error: started.code } };
return { status: 200, body: { uri: started.value.uri, secret: started.value.secret } };}
/** Settings, step 2: the first code turns it on and returns the recovery codes, once. */export async function confirmEnrollment(auth: AppAuth, session: Session, code: string, meta: RequestMeta) { const confirmed = await auth.twoFactor.confirmEnrollment({ session, code, revokeOtherSessions: true, meta, });
if (!confirmed.ok) return { status: 400, body: { error: confirmed.code } };
const cookies = confirmed.value.session ? [confirmed.value.session.cookie] : [];
return { status: 200, cookies, body: { recoveryCodes: confirmed.value.recoveryCodes } };}
/** Any sensitive action of your own: fresh authentication plus a recent second-factor proof. */export async function deleteProject(auth: AppAuth, session: Session, projectId: string) { const allowed = await auth.twoFactor.requireStepUp(session);
// The client asks for the password (fresh_auth_required) or a code (second_factor_required), then retries. if (!allowed.ok) return { status: 403, body: { error: allowed.code } };
return { status: 200, body: { deleted: projectId } };}
/** The code prompt behind that 403. */export async function stepUp(auth: AppAuth, session: Session, code: string, meta: RequestMeta) { const proved = await auth.twoFactor.stepUp({ session, proof: { kind: 'totp', code }, meta });
return proved.ok ? { status: 200, body: { until: proved.value.expiresAt } } : { status: 401, body: { error: proved.code } };}requireStepUp is the guard for your own sensitive actions, such as deleting a project. Turning the factor off and new recovery codes already use it. A password change and an email change request accept the step-up held by the session, or a code with the request; you do not need to guard email change yourself. Pass revokeOtherSessions: true to confirmEnrollment to sign out every other session when the factor goes on; set the cookie of the session it returns.
An email change revert never removes a factor: it cannot tell the owner’s from one an intruder enrolled. An owner who cannot pass a factor the intruder enrolled needs support: 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. See Email change.
Other flows: status(session) (on, pending, required, recovery codes left), regenerateRecoveryCodes, disable, and revokeTrustedDevices. Password changes, resets and email change requests of a user with a factor take the code in secondFactor (six digits are read as a TOTP code, anything else as a recovery code); a password change or an email change request can skip it when the session holds a step-up. A reset page can learn before the user types anything whether the reset will ask for the code: auth.inspectPasswordReset answers secondFactorRequired: true for an account with a confirmed factor.
Moving existing TOTP users over
Section titled “Moving existing TOTP users over”If your users already have TOTP seeds, move each one into the store already confirmed, so their authenticator apps keep working. Their unused recovery codes can come along too (below):
import type { SecretCipher, TwoFactorStore } from '@noctcore/auth';import { importedRecoveryCodeHashes } from '@noctcore/auth/two-factor';
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
/** Decodes an RFC 4648 base32 TOTP seed, the form authenticator apps were given. */function decodeBase32(seed: string): Uint8Array { const bytes: number[] = []; let buffer = 0; let bits = 0;
for (const char of seed.toUpperCase().replace(/[\s=]/g, '')) { const value = BASE32.indexOf(char);
if (value === -1) throw new Error('Not a base32 seed');
buffer = (buffer << 5) | value; bits += 5;
if (bits >= 8) { bits -= 8; bytes.push((buffer >> bits) & 0xff); } }
return new Uint8Array(bytes);}
/** * Moves one user's existing TOTP seed into the plugin's store, already * confirmed, so their authenticator app keeps working. Run it once per user, * from a script, before you turn the plugin on. */export async function migrateTotpSeed( store: TwoFactorStore, cipher: SecretCipher, user: { id: string; totpSeed: string },): Promise<void> { const secret = await cipher.encrypt(decodeBase32(user.totpSeed), { userId: user.id });
if (!(await store.putPendingFactor({ userId: user.id, secret, createdAt: Date.now() }))) return;
// The last accepted step starts two steps back, so the code on the user's // phone right now is accepted at their next login. const step = Math.floor(Date.now() / 30_000) - 2;
await store.confirmFactor(user.id, secret, step);}
/** * Carries one user's unused recovery codes over as the old app stored them * (here the hex SHA-256 of each code), replacing whatever set the store held. * The plugin accepts them only with its `importedRecoveryCodes` option. */export async function migrateRecoveryCodes( store: TwoFactorStore, user: { id: string; recoveryCodeHashes: string[] },): Promise<void> { await store.replaceRecoveryCodes(user.id, importedRecoveryCodeHashes(user.recoveryCodeHashes));}Carrying recovery codes over
Section titled “Carrying recovery codes over”The plugin’s own codes are stored as an HMAC keyed by your auth secret, so your old hashes cannot become plugin codes. They can still be accepted as they are, each once, if your old scheme hashed a code the same way every time (an unsalted or peppered SHA-256, an HMAC, a hash salted per user):
- In the migration script, store each user’s unused hashes with
importedRecoveryCodeHashes(migrateRecoveryCodesabove). It marks them as imported, so the plugin never confuses them with its own. - Tell the plugin how a typed code was hashed.
hash(code, { userId })gets the input as typed (at most 64 characters) and returns the stored hash, or null when the input cannot be one of your codes. Normalise the way your old app did:
import { createHash } from 'node:crypto';
twoFactor({ store, cipher, issuer: 'Acme', importedRecoveryCodes: { hash: (code) => { const compact = code.replace(/[\s-]/g, '').toUpperCase();
return /^[0-9A-HJKMNP-TV-Z]{16}$/.test(compact) ? createHash('sha256').update(compact).digest('hex') : null; }, },});Two things the hash has to live with:
- It runs on every recovery-code proof, also one that is going to be refused. A blocked or locked challenge, or a login for an unknown user, still hashes the input, so a refusal costs what a wrong code costs. On those paths
userIdisNO_SUCH_USER_ID, an id no store issues: do not assume the user exists, and do not look up anything that fails for an unknown id. - It should not throw. A throw is logged (the error’s name only) and read as no match, so the code is refused like a wrong one and the public answer is the same. The audit reason is not: when the input is not in the plugin’s own code format either, the refusal is recorded as
malformed_recovery_coderather thanwrong_recovery_code.
An imported code is spent like any recovery code: by one atomic delete, counted in the factor budget, mailed to the owner (the audit row carries imported: true). When one passes the login challenge and the session is issued, the plugin replaces the user’s whole set with ten new codes and verifyChallenge returns them in recoveryCodes: show them once, as after an enrollment. The mail and the audit row then count the new set (ten), not the old one. Of two logins at once with two different imported codes, only one replaces the set and shows it; the other gets its session with recoveryCodes: null, so no shown set is dead. If replacing the set fails (the store is down), the session stands, recoveryCodes is null and the failure is logged; the user can generate a new set from the settings page. If the login is refused after the code passed (a concurrent redemption of the challenge, a password change during it, one of your session hooks), the code is spent but the rest of the imported set stays and no new set is made. From then on the user is on the plugin’s codes and the old hashes are gone from the store. An imported code spent on a step-up, a password change or a reset is spent without a new set (nothing there could show one); the user moves over at the next login that uses one, or by generating a new set from the settings page. Turning the option off later voids every imported code still in the store, so keep it until the users who have not moved yet are expected to re-enroll.
If your old codes were hashed with a per-code salt (bcrypt, Argon2), they cannot be looked up, so they cannot be carried over. Re-enroll those users instead: migrate the TOTP seed without recovery codes, and after their next sign-in send them to generate a new set from the settings page, where status shows recoveryCodesRemaining: 0. Until they do, the TOTP code is their only way through the challenge.
Limits
Section titled “Limits”TOTP does not stop a phishing page that relays the code in real time, and it does not protect a session cookie that was already stolen. See Second factors for what the plugin does and does not cover.