# TOTP management

This guide covers the `withTotpManagement` mixin from `@adonisplus/persona/totp`. You will learn how to:

- Apply the mixin and understand the two-column secret pattern
- Enroll users in two-factor authentication with QR codes
- Verify TOTP codes during login
- Generate and verify recovery codes
- Customize TOTP parameters

## Overview

Two-factor authentication (2FA) adds a second verification step after the user enters their password. The user opens an authenticator app (Google Authenticator, Authy, 1Password, etc.), reads a six-digit code, and enters it into your application. The code changes every 30 seconds.

The `withTotpManagement` mixin implements this using the **Time-based One-Time Password (TOTP)** standard (RFC 6238). It encrypts secrets at rest, generates QR codes for authenticator app setup, and tracks consumed time steps to prevent replay attacks.

The mixin uses a **two-column secret pattern**. Your `users` table stores a `totp_pending_secret` (the secret being enrolled) and a `totp_secret` (the confirmed, active secret). The confirmed secret keeps working while the user sets up a new authenticator app. The pending secret is only promoted to the confirmed slot after the user proves they can generate valid codes from it.

## Setup

The `withTotpManagement` mixin needs columns on the users table for storing secrets, timestamps, and recovery codes, and must be applied to your User model.

::steps

### Install peer dependencies
The `withTotpManagement` mixin requires `otpauth` for TOTP code generation and `qrcode` for QR code rendering. Install them as production dependencies, and install `@types/qrcode` as a dev dependency.

```bash
npm install otpauth qrcode
npm install -D @types/qrcode
```

### Add TOTP columns to users
Generate a migration to add five columns to your existing `users` table:

::::field-group

:::field{name="totp_pending_secret" type="text, nullable"}
The encrypted secret during enrollment.
:::

:::field{name="totp_secret" type="text, nullable"}
The encrypted confirmed secret.
:::

:::field{name="totp_enabled_at" type="timestamp, nullable"}
When 2FA was activated.
:::

:::field{name="totp_last_consumed_timestep" type="bigint, nullable"}
The last verified time step, for replay prevention.
:::

:::field{name="recovery_codes" type="text, nullable"}
A JSON array of hashed recovery codes.
:::

::::

Both secret columns use `text` because encrypted values are longer than the original secret. The `totp_last_consumed_timestep` column uses `bigInteger` to store Unix-derived time step values without overflow.

```bash
node ace make:migration add_totp_columns_to_users --alter=users
```

```ts [database/migrations/xxxx_add_totp_columns_to_users.ts]
import { BaseSchema } from '@adonisjs/lucid/schema'

export default class extends BaseSchema {
  protected tableName = 'users'

  async up() {
    this.schema.alterTable(this.tableName, (table) => {
      table.text('totp_pending_secret').nullable()
      table.text('totp_secret').nullable()
      table.timestamp('totp_enabled_at', { precision: 6, useTz: true }).nullable()
      table.bigInteger('totp_last_consumed_timestep').nullable()
      table.text('recovery_codes').nullable()
    })
  }

  async down() {
    this.schema.alterTable(this.tableName, (table) => {
      table.dropColumn('totp_pending_secret')
      table.dropColumn('totp_secret')
      table.dropColumn('totp_enabled_at')
      table.dropColumn('totp_last_consumed_timestep')
      table.dropColumn('recovery_codes')
    })
  }
}

```

### Apply the mixin
The `withTotpManagement` mixin requires an `encryption` instance to encrypt secrets at rest and a `hash` instance to hash recovery codes. You can pass either a factory function or a service manager for each.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import hash from '@adonisjs/core/services/hash'
import encryption from '@adonisjs/core/services/encryption'
import { withTotpManagement } from '@adonisplus/persona/totp' // [!code ++]

export default class User extends compose(
  UserSchema,
  withTotpManagement(encryption, hash) // [!code ++]
) {}

```

You can customize the mixin by passing a config object as the third argument.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withTotpManagement } from '@adonisplus/persona/totp'
import hash from '@adonisjs/core/services/hash'
import encryption from '@adonisjs/core/services/encryption'

export default class User extends compose(
  UserSchema,
  // [!code ++:4]
  withTotpManagement(encryption, hash, {
    issuer: 'My App',
    recoveryCodesCount: 8,
  })
) {}

```

::::field-group

:::field{name="issuer" type="string"}
The issuer name displayed in the authenticator app when the user scans the QR code. Helps users identify which service the code belongs to.

Defaults to `"AdonisJS App"`.
:::

:::field{name="window" type="number"}
The number of time steps before and after the current one that `enableTwoFactor` accepts. A window of `1` accepts the codes of the previous, current and next 30-second periods. `verifyTotpForLogin` always uses a window of `1`.

Defaults to `1`.
:::

:::field{name="recoveryCodesCount" type="number"}
The number of recovery codes to generate when calling `generateRecoveryCodes()`. Each code is a single-use backup that can verify identity when the authenticator device is unavailable.

Defaults to `10`.
:::

::::

::

## Enrollment

Enrollment is a multi-step process. You generate a secret, show the user a QR code to scan with their authenticator app, and then ask them to enter a code to prove the setup worked. Only after verification does 2FA become active.

### Generate the secret and show the QR code

```ts [app/controllers/two_factor_controller.ts]
import type { HttpContext } from '@adonisjs/core/http'
import { twoFactorCodeValidator } from '#validators/two_factor'

export default class TwoFactorController {
  async create({ auth, inertia }: HttpContext) {
    const user = auth.getUserOrFail()

    // Generates and encrypts a new pending secret
    await user.generateSecret()

    return inertia.render('account/two_factor', {
      // A base64 data URL, for an <img> tag
      qrCode: await user.generateQRCode(),
      // For manual entry when the user cannot scan the QR code
      manualSecret: user.getEnrollmentSecret().release(),
    })
  }

  async store({ auth, request, inertia }: HttpContext) {
    const user = auth.getUserOrFail()
    const { code } = await request.validateUsing(twoFactorCodeValidator)

    await user.enableTwoFactor(code)

    // Shown once. The plain codes cannot be read again
    const recoveryCodes = await user.generateRecoveryCodes()
    return inertia.render('account/recovery_codes', { recoveryCodes })
  }

  async destroy({ auth, response }: HttpContext) {
    // Confirm the password or a TOTP code before this action
    await auth.getUserOrFail().disableTwoFactor()
    return response.redirect().back()
  }
}

```

Calling `generateSecret()` is safe during re-enrollment. It overwrites any existing pending secret without touching the confirmed one. Login keeps working with the old authenticator app.

### Verify and activate

After the user scans the QR code, ask them to enter the six-digit code from their authenticator app. The `enableTwoFactor` method verifies the code against the pending secret and promotes it to the confirmed slot. It throws `E_INVALID_TOTP_TOKEN` for a wrong code, and `E_TOTP_ENROLLMENT_NOT_STARTED` when there is no pending secret. Once it succeeds, `user.isTwoFactorEnabled` is `true`.

### Multiple devices

When `enableTwoFactor` promotes the pending secret, it replaces the previous confirmed secret. Devices that use the old secret stop generating valid codes.

If a user wants to set up multiple authenticator devices, they must scan the QR code from all devices during the same enrollment session, before calling `enableTwoFactor`. Since all devices share the same secret, they will all generate identical codes at any given time. Verifying with a code from any one of them completes the enrollment for all.

## Verifying TOTP during login

Once 2FA is enabled, verify a TOTP code as part of your login flow. The typical approach is a two-step login: first verify the password, then check `isTwoFactorEnabled` and prompt for a code.

```ts
// After password verification
if (user.isTwoFactorEnabled) {
  // Redirect to TOTP challenge page
}
```

When the user submits their code, verify it with `verifyTotpForLogin`. This method validates the code against the confirmed secret and prevents replay attacks by tracking the last consumed time step.

```ts [app/controllers/two_factor_challenge_controller.ts]
import User from '#models/user'
import type { HttpContext } from '@adonisjs/core/http'
import { twoFactorChallengeValidator } from '#validators/two_factor'

export default class TwoFactorChallengeController {
  async store({ auth, request, response, session }: HttpContext) {
    const { code, recoveryCode } = await request.validateUsing(twoFactorChallengeValidator)

    // Set by the login action after the password was verified
    const user = await User.findOrFail(session.get('two_factor_user_id'))

    if (recoveryCode) {
      await user.verifyRecoveryCode(recoveryCode)
      if (user.remainingRecoveryCodesCount <= 2) {
        // Ask the user to generate new recovery codes
      }
    } else {
      await user.verifyTotpForLogin(code!)
    }

    session.forget('two_factor_user_id')
    await auth.use('web').login(user)
    return response.redirect('/dashboard')
  }
}

```

If the code is invalid or has already been used, the method throws `E_INVALID_TOTP_TOKEN`.

## Disabling two-factor authentication

Call `disableTwoFactor` to clear all TOTP columns and recovery codes.

You should require the user to re-authenticate (password confirmation or a valid TOTP code) before allowing them to disable 2FA. Without this check, an attacker with access to an active session can silently disable 2FA.

## Recovery codes

Recovery codes are single-use backup codes that let users regain access when they lose their authenticator device. Each code is a 10-character alphanumeric string in `xxxxx-xxxxx` format, hashed before storage.

Recovery codes are independent from the TOTP secret lifecycle. Generating recovery codes does not affect the TOTP secret, and re-enrolling does not clear existing recovery codes. However, `disableTwoFactor` clears both.

### Generating recovery codes

After the user completes 2FA enrollment, generate recovery codes and display them once. The plaintext codes cannot be retrieved again.

> [!WARNING]
> Calling `generateRecoveryCodes` again replaces any existing recovery codes. The old codes will no longer work.

### Verifying recovery codes

When a user cannot provide a TOTP code, allow them to enter a recovery code instead. The `verifyRecoveryCode` method finds and consumes the matching code in a single step.

If the code is invalid, already consumed, or no recovery codes exist, the method throws `E_INVALID_RECOVERY_CODE`.

Check the remaining codes right after a successful `verifyRecoveryCode` call, since the count has just gone down. Ask the user to generate new codes when few are left.

### Checking remaining codes

Use `remainingRecoveryCodesCount` to check how many recovery codes the user has left.

The challenge controller above checks this count after it consumes a recovery code.

## Customization

You can override several methods on the model to customize the TOTP behavior without changing the mixin configuration.

### Custom label

By default, the mixin uses the user's `email` property as the TOTP label shown in authenticator apps. Override `getTotpLabel` to use a different value.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withTotpManagement } from '@adonisplus/persona/totp'
import hash from '@adonisjs/core/services/hash'
import encryption from '@adonisjs/core/services/encryption'

export default class User extends compose(UserSchema, withTotpManagement(encryption, hash)) {
  getTotpLabel(): string {
    return this.fullName ?? this.email
  }
}

```

### Custom TOTP instance

Override `createTotp` to change the TOTP algorithm or the number of digits. Keep `period: 30`, since the replay check counts 30-second time steps. Most authenticator apps support only SHA1 and 6 digits. Change these values only for apps you know support them.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withTotpManagement } from '@adonisplus/persona/totp'
import hash from '@adonisjs/core/services/hash'
import encryption from '@adonisjs/core/services/encryption'

import { TOTP } from 'otpauth'

export default class User extends compose(
  UserSchema,
  withTotpManagement(encryption, hash, { issuer: 'My App' })
) {
  createTotp(secret?: string): TOTP {
    return new TOTP({
      issuer: 'My App',
      label: this.getTotpLabel(),
      algorithm: 'SHA1',
      digits: 6,
      period: 30,
      secret,
    })
  }
}

```

### Custom recovery code format

Override `seedRecoveryCode` to customize the format or generation strategy.

```ts [app/models/user.ts]
import { randomBytes } from 'node:crypto'
import { UserSchema } from '#database/schema'
import hash from '@adonisjs/core/services/hash'
import { compose } from '@adonisjs/core/helpers'
import encryption from '@adonisjs/core/services/encryption'
import { withTotpManagement } from '@adonisplus/persona/totp'

export default class User extends compose(UserSchema, withTotpManagement(encryption, hash)) {
  seedRecoveryCode(): string {
    return randomBytes(8).toString('hex')
  }
}

```

## Errors

The TOTP module throws three errors, each with status 400. See [Errors](/docs/packages/persona/introduction#errors) for the response of each request type.

::::field-group

:::field{name="E_TOTP_ENROLLMENT_NOT_STARTED"}
Thrown when calling a method that requires an active enrollment (like `getSecretUri` or `getEnrollmentSecret`) but no pending secret exists. Also thrown by `verifyTotpForLogin` and `verifyRecoveryCode` when 2FA is not enabled.
:::

:::field{name="E_INVALID_TOTP_TOKEN"}
Thrown when the TOTP code is invalid, expired, or has already been used (replay attack).
:::

:::field{name="E_INVALID_RECOVERY_CODE"}
Thrown when the recovery code is invalid, already consumed, or no recovery codes exist.
:::

::::

## Instance properties and methods

::::field-group

:::field{name="totpPendingSecret" type="string | null"}
The encrypted pending TOTP secret during enrollment. Set by `generateSecret()`, cleared by `enableTwoFactor()` or `disableTwoFactor()`.
:::

:::field{name="totpSecret" type="string | null"}
The encrypted confirmed TOTP secret. Set by `enableTwoFactor()` when the pending secret is promoted.
:::

:::field{name="totpEnabledAt" type="Date | null"}
The timestamp when 2FA was activated.
:::

:::field{name="totpLastConsumedTimestep" type="number | null"}
The last verified TOTP time step. Used for replay attack prevention.
:::

:::field{name="recoveryCodes" type="string | null"}
Hashed recovery codes stored as a JSON array. Set by `generateRecoveryCodes()`, cleared by `disableTwoFactor()`.
:::

:::field{name="isTwoFactorEnabled" type="boolean"}
`true` when both `totpSecret` and `totpEnabledAt` are present.
:::

:::field{name="hasPendingTwoFactor" type="boolean"}
`true` when `totpPendingSecret` is present (enrollment in progress).
:::

:::field{name="remainingRecoveryCodesCount" type="number"}
The number of remaining unconsumed recovery codes. Returns `0` when none have been generated.
:::

:::field{name="generateSecret" type="method"}
Generates a new TOTP secret, encrypts it, and saves it to `totpPendingSecret`. Does not touch the confirmed secret.

```ts
await user.generateSecret()
```

:::

:::field{name="getSecretUri" type="method"}
Returns the `otpauth://` URI from the pending secret. Throws `E_TOTP_ENROLLMENT_NOT_STARTED` if no pending secret exists.

```ts
const uri = user.getSecretUri()
```

:::

:::field{name="generateQRCode" type="method"}
Returns a QR code as a base64-encoded data URL from the pending secret. Throws `E_TOTP_ENROLLMENT_NOT_STARTED` if no pending secret exists.

```ts
const dataUrl = await user.generateQRCode()
```

:::

:::field{name="getEnrollmentSecret" type="method"}
Returns the decrypted pending secret wrapped in the `Secret` class. For manual entry when the user cannot scan the QR code. Throws `E_TOTP_ENROLLMENT_NOT_STARTED` if no pending secret exists.

```ts
const secret = user.getEnrollmentSecret().release()
```

:::

:::field{name="enableTwoFactor" type="method"}
Verifies the code against the pending secret, promotes it to confirmed, and activates 2FA.

```ts
await user.enableTwoFactor(code)
```

:::

:::field{name="disableTwoFactor" type="method"}
Clears all TOTP columns and recovery codes.

```ts
await user.disableTwoFactor()
```

:::

:::field{name="verifyTotpForLogin" type="method"}
Validates a TOTP code against the confirmed secret with replay attack prevention.

```ts
await user.verifyTotpForLogin(code)
```

:::

:::field{name="getTotpLabel" type="method"}
Returns the account label for authenticator apps. Defaults to `this.email`. Override to customize.

```ts
user.getTotpLabel()
```

:::

:::field{name="createTotp" type="method"}
Creates a TOTP instance from the `otpauth` library. Override to customize algorithm, digits, or period.

```ts
const totp = user.createTotp()
const existingTotp = user.createTotp(existingSecret)
```

:::

:::field{name="seedRecoveryCode" type="method"}
Generates a single recovery code in `xxxxx-xxxxx` format. Override to customize.

```ts
const generatedRecoveryCode = user.seedRecoveryCode()
```

:::

:::field{name="generateRecoveryCodes" type="method"}
Generates recovery codes, hashes and stores them, returns the plaintext codes. Replaces any existing codes.

```ts
const codes = await user.generateRecoveryCodes()
```

:::

:::field{name="verifyRecoveryCode" type="method"}
Verifies a recovery code and consumes it on match.

```ts
await user.verifyRecoveryCode(code)
```

:::

::::
