> For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt.

# 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](https://dotpress.dev/auth/passkeys.md#second-factor), or a recovery code. It needs the `mfa`, `tokens` (with `recordFailedAttempt()` and `update()`) and `sessions` [stores](https://dotpress.dev/auth/data-provider.md#the-stores), `users.findAccount()`, `secrets.keys` for TOTP and the recovery codes, and [messages](https://dotpress.dev/auth/messages.md) 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.

```ts
createAuth({
  // …
  secrets: { keys: [{ id: '2030-01', key: process.env.SECRET_KEY! }] },
  messages: { send }, // emails and SMS: see "Codes by email or SMS"
  mfa: {
    required: 'when_enrolled', // 'always', or ({ userId, account, status }) => boolean
    totp: { issuer: 'Notes' }, // digits: 6, period: 30, window: 1
    email: true, // { ttl: '10m' }
    sms: true, // { ttl: '10m', allow: (phoneNumber) => phoneNumber.startsWith('+33') }
    recoveryCodes: true, // { count: 10 }
    trustedDevices: true, // { ttl: '30d' }, needs the trustedDevices store
    maxFactors: 5,
    challenge: { ttl: '10m', maxAttempts: 5 },
  },
})
```

`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`](https://dotpress.dev/reference/auth.md#createauth) can ask it for one login: `return { requireMfa: true }`.

## Login

Every login (password, [magic link, handoff code](https://dotpress.dev/auth/magic-link.md), [passkey](https://dotpress.dev/auth/passkeys.md), [social login](https://dotpress.dev/auth/oauth.md), [SSO](https://dotpress.dev/auth/sso.md)) that needs a second factor answers `200` without session (the redirect flows redirect with `?challenge=<challengeToken>`):

```json
{
  "status": "mfa_required",
  "challengeToken": "…",
  "expiresAt": "2030-01-01T10:10:00.000Z",
  "factors": [{ "id": "f1", "type": "totp", "label": null, "primary": true }],
  "recoveryCode": true,
  "passkey": false
}
```

| Route                            | Body                                                                              | Answer                                                                                                                                                                                                                                                             |
| -------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `POST /auth/mfa/send`            | `{ challengeToken, factorId? }`                                                   | `{ factorId, expiresAt }`: a code sent by email or SMS (the primary factor by default). A new code replaces the previous one. 5 per 15 minutes per user (`rateLimits.mfa.sendCode`), and a code by SMS 3 per hour per phone number (`rateLimits.mfa.phoneNumber`). |
| `POST /auth/mfa/verify`          | `{ challengeToken, method, code?, response?, factorId?, rememberDevice?, mode? }` | The answer of a login. `method`: `totp`, `email`, `sms`, `recovery_code`, or `passkey` with the `response` of the browser.                                                                                                                                         |
| `POST /auth/mfa/passkey/options` | `{ challengeToken }`                                                              | `{ options }` for the browser, with `passkeys`: see [Passkeys](https://dotpress.dev/auth/passkeys.md#second-factor).                                                                                                                                               |

`passkey` is `true` for a user with [passkeys](https://dotpress.dev/auth/passkeys.md): 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()`](https://dotpress.dev/auth/protecting-routes.md) 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](https://dotpress.dev/auth/step-up.md)), and refuse [impersonations](https://dotpress.dev/auth/sessions.md#impersonation) (`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.

| Route                                | Body                             | Answer                                                                                                                                  |
| ------------------------------------ | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /auth/mfa/factors`              | —                                | The factors, without their secrets: `id`, `type`, `label`, `primary`, `verified`, `phoneNumber` (masked), `createdAt`, `lastUsedAt`     |
| `POST /auth/mfa/factors`             | `{ type, label?, phoneNumber? }` | `{ factorId, secret, otpauthUri }` for TOTP (show the URI as a QR code), `{ factorId, challengeToken }` for email and SMS (a code sent) |
| `POST /auth/mfa/factors/:id/confirm` | `{ code, challengeToken? }`      | `{ status: 'enrolled', recoveryCodes? }`: the first factor gets the recovery codes, shown once                                          |
| `POST /auth/mfa/factors/:id/primary` | —                                | `{ status: 'primary' }`                                                                                                                 |
| `DELETE /auth/mfa/factors/:id`       | —                                | `{ status: 'removed' }`: the last factor takes the recovery codes with it, unless passkeys remain                                       |
| `POST /auth/mfa/recovery-codes`      | —                                | `{ recoveryCodes }`: new codes, the previous ones stop working (`409 MFA_NOT_ENABLED` without factor nor passkey)                       |

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.

| Flow                                            | The code is sent by                                   | Answer                                    | Then                                                                                                             |
| ----------------------------------------------- | ----------------------------------------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Login                                           | `POST /auth/mfa/send { challengeToken }`              | `{ factorId, expiresAt }`                 | `POST /auth/mfa/verify { challengeToken, method, code }`, with the `challengeToken` of the `mfa_required` answer |
| Enrollment                                      | `POST /auth/mfa/factors { type: 'sms', phoneNumber }` | `{ factorId, challengeToken }`            | `POST /auth/mfa/factors/:id/confirm { code, challengeToken }`                                                    |
| [Step-up](https://dotpress.dev/auth/step-up.md) | `POST /auth/step-up/send { factorId? }`               | `{ challengeToken, factorId, expiresAt }` | `POST /auth/step-up { method, code, challengeToken }`                                                            |

```ts
// Enrollment of a phone number.
const { factorId, challengeToken } = await post('/auth/mfa/factors', { type: 'sms', phoneNumber: '+33612345678' })
const code = await askUser('The code received by SMS')
await post(`/auth/mfa/factors/${factorId}/confirm`, { code, challengeToken })
```

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](https://dotpress.dev/auth/messages.md), with `channel: 'email'` or `channel: 'sms'`. [`createAuthMessages()`](https://dotpress.dev/auth/messages.md#with-createauthmessages) sends the email codes with the mailer, and the SMS codes with its `sms` sender:

```ts
import { createAuthMessages } from '@dotpress/auth/messages'

createAuth({
  // …
  messages: createAuthMessages({
    mailer,
    sms: { send: ({ to, text }) => smsProvider.send(to, text) }, // Twilio, Telnyx…
  }),
  mfa: { sms: true },
})
```

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](https://dotpress.dev/auth/oauth.md) and of OpenID Connect [SSO](https://dotpress.dev/auth/sso.md), 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](https://dotpress.dev/auth/sessions.md#impersonation) (`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](https://dotpress.dev/auth/step-up.md), 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.

```ts
const { factorId, secret } = await (await post('/auth/mfa/factors', { type: 'totp' })).json()
await post(`/auth/mfa/factors/${factorId}/confirm`, { code: await generateTotp(secret) })
```
