Multi-factor authentication
mfa adds a second step to the logins: a code of an authenticator app (TOTP), a code sent by email or SMS, a passkey, or a recovery code. It needs the mfa, tokens (with recordFailedAttempt() and update()) and sessions stores, users.findAccount(), secrets.keys for TOTP and the recovery codes, and messages for email and SMS. With passkeys, the passkeys can be its only factor: totp, email and sms are then optional. createAuth() throws without one factor at least.
required: 'when_enrolled' asks a second factor to the users who enrolled one. With 'always' or a function that returns true, a user without factor gets a code at the verified address of the account, or 403 MFA_ENROLLMENT_REQUIRED without one (with mfa.email off, or an unverified address). beforeSession can ask it for one login: return { requireMfa: true }.
Login
Every login (password, magic link, handoff code, passkey, social login, SSO) that needs a second factor answers 200 without session (the redirect flows redirect with ?challenge=<challengeToken>):
passkey is true for a user with passkeys: they count as enrolled factors. A login opened by a passkey without user verification is not offered the passkeys again: such a user needs another factor, or gets 403 MFA_ENROLLMENT_REQUIRED. Passkeys stored count also once passkeys is removed from the settings, as long as the data provider keeps its passkeys store: their user is not let in with one factor, but offered the recovery codes and the other factors, or refused with 403 MFA_ENROLLMENT_REQUIRED. Delete these passkeys, or have their users enroll another factor, before removing passkeys.
The challenge lives 10 minutes and accepts 5 tries (challenge.maxAttempts): each try takes an attempt atomically, so parallel requests get no more. A wrong code answers 400 INVALID_CODE; the exhausted challenge 401 INVALID_MFA_CHALLENGE. rateLimits.mfa.verify also counts the codes of a user on /auth/mfa/verify and /auth/step-up, across challenges: 10 failures and 30 attempts per 15 minutes, then 429 TOO_MANY_REQUESTS. The failures counter is read before the check and written after it (it needs a rate limit store with peek()), so parallel wrong codes can exceed it; the attempts counter is atomic: of parallel guesses, 30 at most are checked. With mode: 'cookie', /auth/mfa/verify from an untrusted origin answers 403 CROSS_ORIGIN_REQUEST. The account gate and beforeSession run again before the session. Its amr gets the method (otp for TOTP and the recovery codes, email, sms, hwk or swk for a passkey) and mfa: requireMfa() accepts it.
A TOTP code is accepted once, in its period or the adjacent ones (window: 1, from 0 to 3). The TOTP secrets are encrypted with secrets.keys, the recovery codes stored as keyed hashes: each works once, even with two parallel logins.
Factors
The routes that change the factors and the recovery codes require an authentication of less than 10 minutes (403 REAUTHENTICATION_REQUIRED, see step-up), and refuse impersonations (403 IMPERSONATION_FORBIDDEN). A user with a verified factor or a passkey also needs a second factor within the last 10 minutes, at login or by step-up: 403 MFA_REQUIRED, with data.maxAgeSeconds: 600. A stolen password alone does not replace the factors.
A user has one factor of each type (one per phone number for SMS: 409 MFA_FACTOR_ALREADY_ENROLLED), and maxFactors at most (409 MFA_FACTOR_LIMIT_REACHED). A factor not confirmed within 24 hours is ignored. The email and SMS factors need a verified address of the account (403 EMAIL_NOT_VERIFIED); phone numbers are E.164 (+33612345678). mfa.sms.allow(phoneNumber) (SmsNumberFilter) decides which numbers may be enrolled, a country allow-list or a carrier lookup: a refused one answers 403 PHONE_NUMBER_NOT_ALLOWED. POST /auth/mfa/factors is limited to 10 enrollments per hour per IP address (rateLimits.mfa.enrollIp). Against SMS pumping, every code sent to a phone number counts in rateLimits.mfa.phoneNumber, 3 per hour per number, whatever the account: the enrollment, the codes of a login (/auth/mfa/send) and of a step-up (/auth/step-up/send).
The first second factor of a user (a factor, or a passkey with mfa) revokes the other sessions (reason mfa_enabled): a session opened with the password alone does not outlive it. The session that enrolls it goes on, with mfaVerifiedAt. A verified factor of a type the settings do not offer still counts as enrolled: its user is asked for a second factor, and cannot pass it with that factor.
Codes by email or SMS
A code sent by email or SMS belongs to a challengeToken: a random token of 256 bits that the API returns when it sends the code. The client keeps it, and sends it back with the code the user types. The server stores neither the token nor the code: it keeps the hash of the challengeToken, and the code as an HMAC keyed by the challengeToken, which the store alone cannot reverse. It finds the pending code by the hash of the challengeToken, checks that it belongs to the user (and to the factor, or to the session), then compares the code.
The challengeToken alone opens nothing: the code is still needed, wrong codes are counted (rateLimits.stepUp.user, rateLimits.mfa.verify, and 5 per login challenge), and a code works once. Sending a new code replaces the previous one. Keep the challengeToken in the memory of the page, like the code: no need to store it.
The codes reach the user as mfa_code messages, with channel: 'email' or channel: 'sms'. createAuthMessages() sends the email codes with the mailer, and the SMS codes with its sms sender:
Without an sms sender, createAuth() refuses mfa.sms at startup.
Trusted devices
With trustedDevices and the trustedDevices store, rememberDevice: true on POST /auth/mfa/verify returns a trustedDeviceToken (in body mode), or sets the cookie cookies.trustedDeviceName (in cookie mode, sent to the auth routes only). The logins that present it, as trustedDeviceToken in the body or the cookie, skip the second factor of an enrolled user for 30 days: their amr has no mfa. A trusted device never skips the second factor asked by required: 'always' or by beforeSession ({ requireMfa: true }).
The cookie is SameSite=Lax (None with cookies.refreshTokenSameSite: 'none'), so that the callbacks of the social login and of OpenID Connect SSO, reached by a top-level redirect, receive it. A SAML response is a cross-site POST, which a Lax cookie does not follow: SAML logins still ask the second factor.
A new or removed factor, and a password change or reset, revoke the devices of the user. GET /auth/trusted-devices, DELETE /auth/trusted-devices/:id and DELETE /auth/trusted-devices list and revoke them; the revocations refuse impersonations (403 IMPERSONATION_FORBIDDEN).
Password change
With mfa, a user with factors or passkeys changes the password within 10 minutes of a second factor, at login or by step-up, else 403 MFA_REQUIRED. password.changeRequiresMfa: false turns it off.
Services
auth.mfa.challenge.send(), auth.mfa.challenge.verify(), auth.mfa.factors.list(), startEnrollment(), confirm(), setPrimary(), remove(), auth.mfa.recoveryCodes.regenerate({ userId, mfaVerifiedAt? }) and auth.trustedDevices do the same outside the routes, and throw an AuthError. startEnrollment(), confirm(), setPrimary(), remove() and regenerate() take mfaVerifiedAt, the last second factor of the session (ctx.auth.session.mfaVerifiedAt): without a recent one, a user with factors gets MFA_REQUIRED. Server code that acts for an admin passes mfaVerifiedAt: new Date() once it has checked the admin itself. confirm() takes the sessionId of the enrolling session, kept by the revocation of the first factor. A login service (auth.magicLink.verify(), auth.handoff.exchange()) returns { status: 'mfa_required', challenge }.
In tests
generateTotp(secret, at?) of @dotpress/auth/testing computes the code an authenticator app shows, and createMessageOutbox() keeps the mfa_code messages.