> ## Documentation Index
> Fetch the complete documentation index at: https://docs.frogbot.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Two-factor sign-in

> Ask for an authenticator or recovery code after the password or sign-in provider with the two-factor plugin.

The two-factor plugin adds a second step to sign-in. After the password or a [sign-in method](https://docs.frogbot.ai/authentication/sign-in.md) such as Google, a user with two-factor sign-in on enters a 6-digit code from an authenticator app, or one of their recovery codes, before FrogBot issues a session. No session exists until the code is accepted.

## Install

```bash theme={"theme":"tokyo-night"}
pnpm add @frogbotai/plugin-two-factor
```

## Configure

```ts theme={"theme":"tokyo-night"}
import { twoFactor } from '@frogbotai/plugin-two-factor'
import { buildConfig } from 'frogbot'

export default buildConfig({
  collections: [{ slug: 'users', auth: true, fields: [{ name: 'role', type: 'text' }] }],
  plugins: [
    twoFactor({
      issuer: 'Acme',
      require: ({ user }) => user.role === 'admin',
      canReset: ({ req, user }) => req.user?.role === 'admin' && user.role !== 'owner',
    }),
  ],
})
```

The plugin adds four fields to the auth collection: `twoFactorEnabled`, a read-only checkbox that carries the account section, and three hidden fields for the encrypted secret, the hashed recovery codes and the last accepted time step. Run `frogbot generate:importmap` after adding the plugin in build-only workflows; `frogbot dev` does it for you.

## Turn it on

Each user turns two-factor sign-in on from the **Two-factor sign-in** section of their own account:

1. **Turn on** shows a QR code and the key as text. The user scans it with an authenticator app (1Password, Google Authenticator, Authy and others) and types the 6-digit code it shows.
2. FrogBot shows 10 recovery codes once, with **Copy** and **Download**. Each one signs in once when the authenticator is lost.
3. Every other session of that user ends; the current one stays. With [`auth.useSessions: false`](https://docs.frogbot.ai/authentication/overview) there are no sessions to end, and tokens already issued stay valid until they expire.

**New recovery codes** needs a current code and voids the old set. **Turn off** needs a code or a recovery code and keeps the user's sessions. API keys aren't affected by two-factor sign-in: they keep working without a code.

Codes follow RFC 6238: SHA-1, 30-second steps, one step of drift either way. A code works once, and so does each recovery code. Five wrong codes in 10 minutes lock code entry for that user for 10 minutes, however they signed in; a right code clears the count. The code page never says which part was wrong.

## Require it

`require` returns true for users who must have two-factor sign-in.

* A required user without it is sent to setup at their next sign-in, before any session exists.
* A required user can't turn it off. The account section hides **Turn off**, and the API refuses with `403`.
* When `require` stops returning true for a user, they can turn it off with a code. This happens, for example, when an admin turns a workspace's requirement off and `require` reads that setting.

When `require` covers the first user, `POST /api/<collection>/first-register` creates the account and answers the same `202` as password login instead of signing them in. The admin's create-first-user form doesn't follow that answer, so after registering there, sign in with the new password to reach setup.

## Sign-in flow

* **Sign-in methods.** After the provider confirms the user, the plugin's [`beforeSignIn`](https://docs.frogbot.ai/hooks/collections#beforesignin) hook pauses the sign-in and redirects to the code page at `/api/<collection>/two-factor`, which continues to `returnTo` once the code is accepted.
* **Password, admin.** The plugin replaces the admin login view, unless your config sets `admin.components.views.login`, with one that renders the same logo, `beforeLogin`, form and `afterLogin` components. A correct password for a user who needs a code goes to the code page, which continues into the admin.
* **Password, API.** `POST /api/<collection>/login` answers `202` for a user who needs a code, with no token and a short-lived, HttpOnly cookie scoped to the code endpoints:

  ```json theme={"theme":"tokyo-night"}
  { "message": "Enter the code from your authenticator app.", "twoFactor": "code", "url": "/api/users/two-factor" }
  ```

  `twoFactor` is `'setup'` for a required user without it. Send the code to `POST <url>/verify` with that cookie as `{ "code": "123456" }` to get the normal login response, token included. Add `returnTo` (a path on your server) to the login body and the code page continues there instead.
* **Reset password.** For a user with two-factor sign-in on or required, the new password is saved and every session ends, but nobody is signed in: REST answers `{ message, twoFactor: 'signIn' }`, GraphQL and the Local API return no token, and the person signs in with the new password and a code.

The pending sign-in lives in FrogBot's KV store for 10 minutes, is bound to its cookie and works once. On its own it grants nothing: the API, the admin and `refresh-token` refuse it.

## Reset

A user who loses both their authenticator and their recovery codes needs an admin. When `canReset` allows it, another user's document shows **Reset two-factor sign-in**. A reset does this:

* It removes their secret and recovery codes.
* It ends every session. With `auth.useSessions: false`, issued tokens stay valid until they expire.
* It clears the code lock.

`canReset` is asked only for a user that the admin can read and update under the collection's access rules. Nobody can reset their own. A still-required user is sent to setup at their next sign-in.

## Endpoints

All live under `/api/<collection>` and answer errors as `{ errors: [{ message }] }`. A refused code, here and on `/two-factor/verify` and `/two-factor/setup`, also carries `data.code`, so a client branches on that rather than the message:

| `data.code` | Status | Means |
| - | - | - |
| `wrong_code` | `401` | The code didn't match. On `verify`, `recovery-codes` and `disable` it counts toward the lock; on `setup` and `enable` it doesn't. |
| `locked` | `429` | Five wrong codes locked code entry. `Retry-After` gives the seconds left. |
| `code_missing` | `400` | `code` is missing, empty, or not a string or a whole number of up to six digits. It doesn't count. |
| `body_unreadable` | `400` | The body isn't a JSON object or a URL-encoded form. It doesn't count. |
| `pending_missing` | `400` | The request didn't send the pending sign-in cookie. |
| `expired` | `400` | The pending sign-in, or the start of turning it on, expired or was used. Sign in, or start, again. |

| Endpoint | Body | Answer |
| - | - | - |
| `POST /two-factor/enable/start` | — | `{ secret, uri, qrCode }`. `403` when `canEnable` refuses, `409` when it is already on. |
| `POST /two-factor/enable` | `{ code }` | `{ message, recoveryCodes }` |
| `POST /two-factor/recovery-codes` | `{ code }` | `{ message, recoveryCodes }` |
| `POST /two-factor/disable` | `{ code }`, an authenticator or recovery code | `{ message }`. `403` while `require` is true. |
| `POST /two-factor/reset` | `{ id }` | `{ message }`. `404` for a user you can't read; `403` for yourself, a user your update access excludes, or without `canReset`. |

The first four act on the signed-in user. `hasTwoFactor(user)` tells whether a user has it on.

## Emails

The plugin emails the user through your [email adapter](https://docs.frogbot.ai/email/overview.md) when two-factor sign-in is turned on or off, a recovery code is used, new codes are created, and an admin resets it. Replace one with `emails.<event>` returning `{ subject, text, html? }`, or turn it off with `false`. A failed send is logged and never fails the request.

## Limits

* GraphQL `loginUser` and the Local API `login` don't have a code step, so they fail for users who need a code or setup. Use the REST login.
* `canReset` defaults to nobody, so without it a user who loses their authenticator and recovery codes can't get back in.
* Another `beforeSignIn` hook that pauses sign-in, such as a terms step, can't be combined with two-factor sign-in. When it resumes with `finishSignIn` for a user who needs a code, the sign-in is refused with `403` rather than skip the code.
* Passkeys, security keys and per-tenant two-factor settings aren't supported.

## Options

```ts theme={"theme":"tokyo-night"}
twoFactor({
  collection: 'members',
  issuer: 'Acme',
  require: ({ user }) => user.role === 'admin',
  canEnable: ({ user }) => user.role !== 'guest',
  canReset: ({ req, user }) => req.user?.role === 'admin' && user.role !== 'owner',
  emails: { recoveryCodeUsed: false },
})
```

| Option | Type | Default | Description |
| - | - | - | - |
| `collection` | `string` | `admin.user` | Auth collection that gets two-factor sign-in. The plugin throws at startup if it is missing or doesn't have auth enabled. The login view is replaced only when this is the admin's user collection. |
| `require` | `(args: { req, user }) => boolean \| Promise<boolean>` | nobody | Users who must have two-factor sign-in. They set it up at their next sign-in and can't turn it off. |
| `canEnable` | `(args: { req, user }) => boolean \| Promise<boolean>` | everyone | Users who may turn it on. `false` hides **Turn on** and refuses with `403`. |
| `canReset` | `(args: { req, user }) => boolean \| Promise<boolean>` | nobody | Whether the signed-in user may reset `user`'s two-factor sign-in. Asked only for a user they can read and update. |
| `issuer` | `string` | `'FrogBot'` | Name authenticator apps show beside the account. |
| `emails` | `Partial<Record<'enabled' \| 'disabled' \| 'recoveryCodeUsed' \| 'recoveryCodesCreated' \| 'reset', ((args: { req, user }) => { subject, text, html? }) \| false>>` | built-in emails | Replaces an event's email, or turns it off with `false`. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.