# Passkey management

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

- Apply the mixin and create the tables it needs
- Register passkeys for a signed-in user
- Sign users in with a passkey
- List, rename, and remove passkeys
- Keep password managers in sync using the Signal API
- Customize passkey names and account details

## Overview

A passkey is a key pair created by the user's device (Touch ID, Windows Hello, a YubiKey) or their password manager (iCloud Keychain, Google Password Manager, 1Password). The private key never leaves the device. Your application stores only the public key and verifies signatures made with it. Your database holds only public keys, and a public key cannot sign anyone in.

Passkeys use the **WebAuthn** standard. Both registering a passkey and signing in with one follow the same three steps:

1. The server issues a random **challenge** along with options for the browser.
2. The browser asks the device to sign the challenge. The user confirms with a fingerprint, face scan, or device PIN.
3. The server verifies the signed response against the challenge it issued.

Registration creates a new passkey. Login proves possession of an existing one. The `withPasskeyManagement` mixin implements both flows on top of [SimpleWebAuthn](https://simplewebauthn.dev), and stores passkeys and challenges in two dedicated tables. Each challenge is stored in the database with an expiry, and deleted in the same query that looks it up. Replaying a response, or submitting the same response twice in parallel, fails.

A challenge is bound to a purpose and a user. A login challenge cannot complete a registration, and a registration challenge issued to one user cannot be used by another.

Registration and login both require the device to verify the user (biometrics or PIN), not only their presence. A passkey counts as a complete sign-in on its own.

Passkeys are created as discoverable credentials. The user clicks "Sign in with a passkey" without typing an email, and the device lists the accounts it holds for your site.

The mixin covers passkeys as a sign-in alternative to passwords. Using passkeys as a second factor after a password is not covered by this module.

### Relying party

WebAuthn calls your application the **relying party**. Passkeys are bound to its id (`rpId`), which is your domain. A passkey created for `example.com` works on `example.com` and its subdomains, and nowhere else. This is what makes passkeys phishing resistant, since a lookalike domain cannot use them.

> [!WARNING]
> Choose the `rpId` carefully. Changing it later makes every registered passkey unusable, and users must register them again.

## Setup

The `withPasskeyManagement` mixin needs a column on the users table, two new tables, and must be applied to your User model.

::steps

### Install peer dependencies
The `withPasskeyManagement` mixin requires `@simplewebauthn/server` to generate and verify WebAuthn registration and login responses. Your frontend needs `@simplewebauthn/browser` to talk to the device.

```bash
npm install @simplewebauthn/server @simplewebauthn/browser
```

### Add the user handle column to users
Every user with passkeys gets a **user handle**, a random identifier the device stores inside each passkey. During login, the device sends it back so the server can confirm the passkey belongs to the right account. The handle is created on the first passkey registration and never changes.

Generate a migration to add a `webauthn_user_handle` column to your existing `users` table. The handle is 64 random bytes encoded as base64url, which is 86 characters long.

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

```ts [database/migrations/xxxx_add_webauthn_user_handle_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.string('webauthn_user_handle', 86).nullable().unique()
    })
  }

  async down() {
    this.schema.alterTable(this.tableName, (table) => {
      table.dropUnique(['webauthn_user_handle'])
      table.dropColumn('webauthn_user_handle')
    })
  }
}

```

### Create the passkeys table
Generate a migration for the `passkeys` table. Each row stores the public key of a passkey along with metadata reported by the device.

```bash
node ace make:migration create_passkeys
```

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

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

  async up() {
    this.schema.createTable(this.tableName, (table) => {
      table.increments('id')
      table
        .integer('user_id')
        .unsigned()
        .notNullable()
        .references('id')
        .inTable('users')
        .onDelete('CASCADE')
        .index()
      table.text('credential_id').notNullable()
      table.string('credential_id_hash', 64).notNullable().unique()
      table.text('public_key').notNullable()
      table.bigInteger('counter').notNullable().defaultTo(0)
      table.text('transports').nullable()
      table.string('device_type', 16).notNullable()
      table.boolean('backed_up').notNullable()
      table.string('aaguid', 36).nullable()
      table.string('name', 100).notNullable()
      table.timestamp('last_used_at', { precision: 6, useTz: true }).nullable()
      table.timestamp('created_at', { precision: 6, useTz: true }).notNullable()
      table.timestamp('updated_at', { precision: 6, useTz: true }).notNullable()
    })
  }

  async down() {
    this.schema.dropTable(this.tableName)
  }
}

```

The mixin reads four of these columns in a particular way.

::::field-group

:::field{name="credential_id_hash" type="string(64)"}
The sha256 hash of `credential_id`. A credential id can be up to 1023 bytes long, which is too long to index on every database. The mixin uses the hash for lookups and the unique constraint.
:::

:::field{name="counter" type="bigint"}
The signature counter reported by the device. It is checked on every login to detect cloned authenticators. Synced passkeys always report `0`.
:::

:::field{name="device_type and backed_up" type="string, boolean"}
Whether the passkey can be synced across devices, and whether it currently is. `backed_up` is refreshed on every login.
:::

:::field{name="aaguid" type="string(36), nullable"}
Identifies the authenticator model, for example Google Password Manager. The mixin uses it to name new passkeys.
:::

::::


### Create the passkey challenges table
Generate a migration for the `passkey_challenges` table. It stores issued challenges until they are used or expire.

```bash
node ace make:migration create_passkey_challenges
```

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

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

  async up() {
    this.schema.createTable(this.tableName, (table) => {
      table.increments('id')
      table.string('challenge', 128).notNullable().unique()
      table.string('purpose', 16).notNullable()
      table
        .integer('user_id')
        .unsigned()
        .nullable()
        .references('id')
        .inTable('users')
        .onDelete('CASCADE')
      table.timestamp('expires_at', { precision: 6, useTz: true }).notNullable().index()
      table.timestamp('created_at', { precision: 6, useTz: true }).notNullable()
    })
  }

  async down() {
    this.schema.dropTable(this.tableName)
  }
}

```

The `user_id` column is set for registration challenges and left `null` for login challenges, since the user is not known until the device responds.


### Apply the mixin
Apply the `withPasskeyManagement` mixin to your User model using `compose`, and define the `passkeys` provider as a static property. The mixin accepts the relying party details as a config object.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import hash from '@adonisjs/core/services/hash'
import { compose } from '@adonisjs/core/helpers'
import { withAuthFinder } from '@adonisjs/auth/mixins/lucid'
import { DbPasskeysProvider, withPasskeyManagement } from '@adonisplus/persona/passkeys' // [!code ++]

export default class User extends compose(
  UserSchema,
  withAuthFinder(hash),
  // [!code ++:5]
  withPasskeyManagement({
    rpName: 'My App',
    rpId: 'example.com',
    origins: ['https://example.com'],
  })
) {
  static passkeys = DbPasskeysProvider.forModel(User) // [!code ++]
}

```

::::field-group

:::field{name="rpName" type="string" required}
The name of your application. Shown by the browser and the password manager when creating a passkey.
:::

:::field{name="rpId" type="string" required}
The domain passkeys are bound to. A passkey created for `example.com` works on `example.com` and its subdomains. Must be the domain of the page, or a parent of it. Use `localhost` during development.
:::

:::field{name="origins" type="string[]" required}
The origins allowed to register passkeys and sign in with them, e.g. `https://example.com`. The browser writes the page origin into the signed response, and the mixin compares it against this list. It never trusts the request `Host` header.
:::

::::

The provider queries the database with your model's connection and primary key. It must be bound to the final `User` class, which a mixin cannot reference.

You can customize the provider by passing a config object as the second argument.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { DbPasskeysProvider, withPasskeyManagement } from '@adonisplus/persona/passkeys'

export default class User extends compose(
  UserSchema,
  withPasskeyManagement({
    rpName: 'My App',
    rpId: 'example.com',
    origins: ['https://example.com'],
  })
) {
  // [!code ++:4]
  static passkeys = DbPasskeysProvider.forModel(User, {
    passkeysTable: 'user_passkeys',
    challengeTtl: '2 minutes',
  })
}

```

::::field-group

:::field{name="passkeysTable" type="string"}
The database table used to store passkeys.

Defaults to `"passkeys"`.
:::

:::field{name="challengesTable" type="string"}
The database table used to store challenges.

Defaults to `"passkey_challenges"`.
:::

:::field{name="challengeTtl" type="string | number"}
How long an issued challenge remains valid. Accepts a number in seconds or a time expression string like `'5 minutes'`. The user must confirm the browser prompt within this window.

Defaults to `'5 minutes'`.
:::

::::

::

## Registering a passkey

Users add passkeys from their account settings while signed in. Registration takes two requests. The first creates a challenge and returns the options for the browser as JSON. The second submits the device's response for verification.

The `createChallengeForRegistration` method creates the user handle on first use, issues a challenge bound to the user, and returns the options for `navigator.credentials.create`. The options list the user's existing passkeys under `excludeCredentials`. A device refuses to create a second passkey for the same account.

Every challenge request stores a row. The challenge controller throttles requests per user with `@adonisjs/limiter`, whose `consume` method throws a `ThrottleException` (a 429 response) once the limit is reached.

The `registerPasskey` method verifies the response, consumes the challenge, and stores the passkey. The passkey is stored only after verification passes. It returns the stored [Passkey](#passkey-properties), which you can use to send a notification email or show the default name.

```ts [app/controllers/passkey_registration_challenges_controller.ts]
import User from '#models/user'
import type { HttpContext } from '@adonisjs/core/http'
import limiter from '@adonisjs/limiter/services/main'

export default class PasskeyRegistrationChallengesController {
  async store({ auth }: HttpContext) {
    const user = auth.getUserOrFail()

    await limiter
      .use({ requests: 10, duration: '1 minute' })
      .consume(`passkey_registration_challenges_${user.id}`)

    await User.passkeys.clearExpiredChallenges()
    return user.createChallengeForRegistration()
  }
}

```

```ts [app/controllers/passkeys_controller.ts]
import type { HttpContext } from '@adonisjs/core/http'
import { passkeyRegistrationValidator } from '#validators/passkey'

export default class PasskeysController {
  async store({ auth, request, response, session }: HttpContext) {
    const user = auth.getUserOrFail()
    const payload = await request.validateUsing(passkeyRegistrationValidator)

    await user.registerPasskey(payload.response)

    session.flash('success', 'Passkey added')
    return response.redirect().back()
  }
}

```

On the frontend, pass the options returned by the challenge endpoint to `startRegistration` from `@simplewebauthn/browser`, and submit its result as `response` to the `store` endpoint. `startRegistration` throws a `NotAllowedError` when the user dismisses the browser prompt. Treat it as a cancellation rather than an error.

### Validating the response

SimpleWebAuthn verifies the browser response. Your validator only checks its shape. Browsers add new fields over time, and VineJS strips unknown properties instead of rejecting them. Verification only reads the fields listed below.

```ts [app/validators/passkey.ts]
import vine from '@vinejs/vine'

export const passkeyNameValidator = vine.create({
  name: vine.string().trim().minLength(1).maxLength(100),
})

export const passkeyRegistrationValidator = vine.create({
  response: vine.object({
    id: vine.string().maxLength(1364),
    rawId: vine.string().maxLength(1364),
    type: vine.literal('public-key'),
    response: vine.object({
      clientDataJSON: vine.string(),
      attestationObject: vine.string(),
      transports: vine.array(vine.string()).optional(),
    }),
    clientExtensionResults: vine.object({}),
  }),
})
```

The `1364` limit is the maximum credential id length of 1023 bytes, encoded as base64url. Do not restrict `transports` to known values. The WebAuthn spec asks servers to ignore unknown transports rather than reject them.

## Signing in with a passkey

Login also takes two requests, and both run for guests. The user is not known until the device responds. The challenge is anonymous, and the device lists the accounts it holds for your site. Anyone can request a login challenge. The controller throttles requests per IP address.

The `verifyPasskeyLogin` method performs the following checks before returning the owner of the passkey.

1. Finds the stored passkey by the credential id in the response.
2. Confirms the user handle in the response belongs to the owner of that passkey.
3. Verifies the signature, the challenge, the origin, the relying party id, and user verification.
4. Records the new signature counter and the last used time. The update applies only if the stored counter is unchanged. Of two responses verified in parallel, only one succeeds.

Every failure throws `E_INVALID_PASSKEY` with the same generic message. A passkey that no longer exists on the server throws `E_UNKNOWN_PASSKEY`, covered in [Removing stale passkeys from devices](#removing-stale-passkeys-from-devices).

```ts [app/controllers/passkey_login_challenges_controller.ts]
import User from '#models/user'
import type { HttpContext } from '@adonisjs/core/http'
import limiter from '@adonisjs/limiter/services/main'

export default class PasskeyLoginChallengesController {
  async store({ request }: HttpContext) {
    await limiter
      .use({ requests: 10, duration: '1 minute' })
      .consume(`passkey_login_challenges_${request.ip()}`)

    await User.passkeys.clearExpiredChallenges()
    return User.createChallengeForLogin()
  }
}

```

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

export default class PasskeySessionController {
  async store({ auth, request, response }: HttpContext) {
    const payload = await request.validateUsing(passkeyAuthenticationValidator)
    const user = await User.verifyPasskeyLogin(payload.response)

    await auth.use('web').login(user)
    return response.redirect().toRoute('dashboard')
  }
}

```

On the frontend, the "Sign in with a passkey" button follows the same steps as registration, using `startAuthentication` instead.

The authentication validator follows the same approach as the registration one. The `userHandle` is optional, matching the browser's types. Passkeys created by the mixin always return it, and `verifyPasskeyLogin` rejects a response without one.

```ts [app/validators/passkey.ts]
import vine from '@vinejs/vine'

export const passkeyAuthenticationValidator = vine.create({
  response: vine.object({
    id: vine.string().maxLength(1364),
    rawId: vine.string().maxLength(1364),
    type: vine.literal('public-key'),
    response: vine.object({
      clientDataJSON: vine.string(),
      authenticatorData: vine.string(),
      signature: vine.string(),
      userHandle: vine.string().optional(),
    }),
    clientExtensionResults: vine.object({}),
  }),
})
```

Brute forcing the verify endpoints is not a concern. Without the private key, no amount of attempts produces a valid signature.

### Clearing expired challenges

When a user closes the browser prompt without responding, their challenge is never consumed. Call `clearExpiredChallenges` to delete them. The challenge controllers above call it before issuing a new challenge, which keeps the table small without a scheduled job. If you prefer, run it from a scheduled command instead.

```ts
const expiredChallengesCount = await User.passkeys.clearExpiredChallenges()
```

## Managing passkeys

Use the `passkeys` provider to list, rename, and remove a user's passkeys. Every method takes the user as the first argument and scopes the query to that user. One user cannot read or change another user's passkeys.

### Listing passkeys

The `all` method returns the user's passkeys, oldest first.

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

export default class SecurityController {
  async show({ auth, inertia }: HttpContext) {
    const user = auth.getUserOrFail()
    const passkeys = await User.passkeys.all(user)

    return inertia.render('account/security', {
      passkeys: passkeys.map((passkey) => ({
        id: String(passkey.identifier),
        name: passkey.name,
        backedUp: passkey.backedUp,
        createdAt: passkey.createdAt,
        lastUsedAt: passkey.lastUsedAt,
      })),
    })
  }
}

```

The [Passkey](#passkey-properties) object includes the public key and credential id. Pick the fields your view needs instead of serializing the whole object.

### Renaming a passkey

New passkeys are named after the authenticator model, e.g. "Google Password Manager" or "1Password". Let users rename them to tell devices apart. The `rename` method returns the number of affected rows, which is `0` when the passkey does not exist or belongs to another user.

```ts [app/controllers/passkeys_controller.ts]
import User from '#models/user'
import type { HttpContext } from '@adonisjs/core/http'
import { passkeyNameValidator } from '#validators/passkey'
import { errors } from '@adonisjs/lucid'

export default class PasskeysController {
  async update({ auth, params, request, response }: HttpContext) {
    const user = auth.getUserOrFail()
    const { name } = await request.validateUsing(passkeyNameValidator)

    if (!(await User.passkeys.rename(user, params.id, name))) {
      throw new errors.E_ROW_NOT_FOUND()
    }

    return response.redirect().back()
  }
}

```

### Removing a passkey

The `delete` method also returns the number of affected rows. When you send a notification email after removal, check this count. A double click or a second tab can send two requests, and only the one that deleted the row should notify the user.

```ts [app/controllers/passkeys_controller.ts]
import type { HttpContext } from '@adonisjs/core/http'
import User from '#models/user'
import mail from '@adonisjs/mail/services/main'
import PasskeyRemovedNotification from '#mails/passkey_removed_notification'
import { errors } from '@adonisjs/lucid'

export default class PasskeysController {
  async destroy({ auth, params, response }: HttpContext) {
    const user = auth.getUserOrFail()
    const passkey = await User.passkeys.findById(user, params.id)
    if (!passkey) {
      throw new errors.E_ROW_NOT_FOUND()
    }

    if (!(await User.passkeys.delete(user, passkey.identifier))) {
      throw new errors.E_ROW_NOT_FOUND()
    }

    await mail.sendLater(new PasskeyRemovedNotification(user, passkey.name))
    return response.redirect().back()
  }
}

```

> [!WARNING]
> Removing a passkey on the server does not remove it from the user's device or password manager. See [Keeping password managers in sync](#keeping-password-managers-in-sync) to hide removed passkeys from the device.

> [!TIP]
> Adding or removing a passkey changes how someone can sign in to the account. Notify the user by email in both cases. A user who did not make the change can then react.

## Routes

Register the login routes for guests, and the registration and management routes for signed-in users.

```ts [start/routes.ts]
import router from '@adonisjs/core/services/router'
import { middleware } from '#start/kernel'
import { controllers } from '#generated/controllers'

router
  .group(() => {
    router.post('login/passkey/challenge', [controllers.PasskeyLoginChallenges, 'store'])
    router.post('login/passkey', [controllers.PasskeySession, 'store'])
  })
  .use(middleware.guest())

router
  .group(() => {
    router.post('account/passkeys/challenge', [controllers.PasskeyRegistrationChallenges, 'store'])
    router.post('account/passkeys', [controllers.Passkeys, 'store'])
    router.put('account/passkeys/:id', [controllers.Passkeys, 'update'])
    router.delete('account/passkeys/:id', [controllers.Passkeys, 'destroy'])
  })
  .use(middleware.auth())
```

## Keeping password managers in sync

Passkeys live on the user's devices, and your server cannot delete them. When a user removes a passkey from your app, or changes their email, the password manager still shows the old passkey or the old account name.

The WebAuthn **Signal API** tells the password manager what changed. The server tells the browser which passkeys are still valid and which account details to display, and the browser forwards this to the password manager. The mixin generates the signals, and your frontend passes them to `sendSignal` from `@simplewebauthn/browser`.

### Syncing after sign-in

After a successful sign-in (with a passkey or a password), flash the signals returned by `getPasskeySignals`. They list the user's current passkeys (so removed ones get hidden) and their current account details. The method returns an empty array until the user has requested a registration challenge.

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

export default class PasskeySessionController {
  async store({ auth, request, response, session }: HttpContext) {
    const payload = await request.validateUsing(passkeyAuthenticationValidator)
    const user = await User.verifyPasskeyLogin(payload.response)

    await auth.use('web').login(user)
    session.flash('passkeySignals', await user.getPasskeySignals()) // [!code ++]
    return response.redirect().toRoute('dashboard')
  }
}

```

For API clients, return the signals in the login response instead, and let the client pass them to the browser.

```ts [app/controllers/api_passkey_sessions_controller.ts]
import User from '#models/user'
import UserTransformer from '#transformers/user_transformer'
import type { HttpContext } from '@adonisjs/core/http'
import { passkeyAuthenticationValidator } from '#validators/passkey'

export default class ApiPasskeySessionsController {
  async store({ request, serialize }: HttpContext) {
    const { response } = await request.validateUsing(passkeyAuthenticationValidator)
    const user = await User.verifyPasskeyLogin(response)

    return serialize({
      user: UserTransformer.transform(user),
      passkeySignals: await user.getPasskeySignals(),
    })
  }
}

```

### Removing stale passkeys from devices

When a user signs in with a passkey that no longer exists on the server, `verifyPasskeyLogin` throws `E_UNKNOWN_PASSKEY`. The error carries an `unknownCredential` signal. The password manager uses it to remove the passkey from the device. The signal is available on the `error.signal` property, and the error sends it along with its response.

For an HTML request, the signal is flashed under the `passkeySignals` key. A JSON response adds `passkeySignals: [...]` next to `errors`, and a JSON:API response puts it in `meta.passkeySignals`.

### Sending signals from the frontend

Pass each signal to `sendSignal` from `@simplewebauthn/browser`, reading them from the flash messages on the page that follows, or from the response body for API clients. Signals are best effort. Browsers without the Signal API throw, which is safe to ignore. Use the `PasskeySignal` type from `@adonisplus/persona/passkeys/types` to type the signals shared with your frontend.

## Customization

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

### Account details

The device stores an account name and display name inside each passkey and shows them when the user picks a passkey. By default, the mixin uses the user's `email` for both. Override `getPasskeyUserDetails` to use different values.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { DbPasskeysProvider, withPasskeyManagement } from '@adonisplus/persona/passkeys'

export default class User extends compose(
  UserSchema,
  withPasskeyManagement({
    rpName: 'My App',
    rpId: 'example.com',
    origins: ['https://example.com'],
  })
) {
  static passkeys = DbPasskeysProvider.forModel(User)

  getPasskeyUserDetails() {
    return { name: this.email, displayName: this.fullName ?? this.email }
  }
}

```

The mixin throws a `RuntimeException` if your model has no `email` property and you have not overridden this method.

### Default passkey names

New passkeys are named after the authenticator model, looked up by its AAGUID. Unknown models, and devices that report an all-zero AAGUID, are named "Passkey". A number is appended when the user already has a passkey with the same name, e.g. "Passkey 2".

Override `getDefaultPasskeyName` to change the naming. It receives the AAGUID and the names of the user's existing passkeys.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { DbPasskeysProvider, withPasskeyManagement } from '@adonisplus/persona/passkeys'

export default class User extends compose(
  UserSchema,
  withPasskeyManagement({
    rpName: 'My App',
    rpId: 'example.com',
    origins: ['https://example.com'],
  })
) {
  static passkeys = DbPasskeysProvider.forModel(User)

  getDefaultPasskeyName(_aaguid: string, existingNames: string[]) {
    return `Passkey ${existingNames.length + 1}`
  }
}

```

### Additional verification checks

The `verifyPasskeyRegistration` instance method and the `verifyPasskeyAuthentication` static method perform the WebAuthn verification. Override them to add checks, e.g. allowing only specific authenticator models. Call `super` first, then throw `E_INVALID_PASSKEY` to reject.

```ts [app/models/user.ts]
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { DbPasskeysProvider, withPasskeyManagement } from '@adonisplus/persona/passkeys'

import { errors } from '@adonisplus/persona/passkeys'
import type { RegistrationResponseJSON } from '@simplewebauthn/server'

const ALLOWED_AAGUIDS = ['ea9b8d66-4d01-1d21-3ce4-b6b48cb575d4']

export default class User extends compose(
  UserSchema,
  withPasskeyManagement({
    rpName: 'My App',
    rpId: 'example.com',
    origins: ['https://example.com'],
  })
) {
  static passkeys = DbPasskeysProvider.forModel(User)

  async verifyPasskeyRegistration(response: RegistrationResponseJSON) {
    const info = await super.verifyPasskeyRegistration(response)
    if (!ALLOWED_AAGUIDS.includes(info.aaguid)) {
      throw new errors.E_INVALID_PASSKEY()
    }
    return info
  }
}

```

> [!NOTE]
> The mixin requests attestation `none`. The device reports the AAGUID, but nothing proves it. Use it for convenience features, not as a security boundary.

## Errors

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

`E_INVALID_PASSKEY` and `E_UNKNOWN_PASSKEY` have the same message. `E_UNKNOWN_PASSKEY` also sends the signal described below. When the WebAuthn verification fails, the underlying error is on `error.cause`.

::::field-group

:::field{name="E_INVALID_PASSKEY" type="status 400"}
Thrown by `registerPasskey` and `verifyPasskeyLogin` when the response cannot be verified. This covers an expired or already used challenge, a wrong origin or relying party, a bad signature, missing user verification, a user handle that does not match, and a signature counter that did not increase.
:::

:::field{name="E_UNKNOWN_PASSKEY" type="status 400"}
Thrown by `verifyPasskeyLogin` when the passkey does not exist on the server, e.g. the user removed it from their account. Carries an `unknownCredential` signal on `error.signal`, flashed under the `passkeySignals` key for HTML requests and included in the response body for JSON and JSONAPI requests.
:::

:::field{name="E_PASSKEY_ALREADY_REGISTERED" type="status 422"}
Thrown by `registerPasskey` when the passkey is already registered, for the same or another user.
:::

::::

## Instance properties and methods

The `withPasskeyManagement` mixin adds the following to model instances.

::::field-group

:::field{name="webauthnUserHandle" type="string | null"}
The WebAuthn user handle shared by all passkeys of the user. Mapped to the `webauthn_user_handle` database column. Created by the first `createChallengeForRegistration` call and never rotated. Excluded from serialization.
:::

:::field{name="createChallengeForRegistration" type="method"}
Issues a registration challenge bound to the user and returns the options for `navigator.credentials.create`. Creates the user handle on first use.

```ts
const registrationOptions = await user.createChallengeForRegistration()
```

:::

:::field{name="registerPasskey" type="method"}
Verifies the browser's registration response and stores the passkey. Returns the stored `Passkey`. Throws `E_INVALID_PASSKEY` when verification fails and `E_PASSKEY_ALREADY_REGISTERED` for a known passkey.

```ts
const registeredPasskey = await user.registerPasskey(registrationResponse)
```

:::

:::field{name="verifyPasskeyRegistration" type="method"}
Verifies the browser's registration response and returns the verified credential info from SimpleWebAuthn, without storing anything. Called by `registerPasskey`. Override to add checks.

```ts
const registrationInfo = await user.verifyPasskeyRegistration(registrationResponse)
```

:::

:::field{name="getPasskeySignals" type="method"}
Returns the `allAcceptedCredentials` and `currentUserDetails` signals for the user. Returns an empty array until the user has requested a registration challenge.

```ts
const signals = await user.getPasskeySignals()
```

:::

:::field{name="getPasskeyUserDetails" type="method"}
Returns the `{ name, displayName }` stored inside a passkey. Defaults to `this.email` for both. Override to customize.

```ts
user.getPasskeyUserDetails()
```

:::

:::field{name="getDefaultPasskeyName" type="method"}
Returns the name for a new passkey from the authenticator AAGUID and the names of existing passkeys. Override to customize.

```ts
user.getDefaultPasskeyName(aaguid, ['Google Password Manager'])
```

:::

::::

## Static properties and methods

::::field-group

:::field{name="passkeys" type="DbPasskeysProvider"}
The provider instance defined on your model. The mixin methods delegate to it, and you use it directly to manage passkeys and clear challenges.

```ts
const passkeys = await User.passkeys.all(user)
const passkey = await User.passkeys.findById(user, id)
const renamedCount = await User.passkeys.rename(user, id, 'Work laptop')
const deletedCount = await User.passkeys.delete(user, id)
await User.passkeys.clearExpiredChallenges()
```

:::

:::field{name="createChallengeForLogin" type="static method"}
Issues an anonymous login challenge and returns the options for `navigator.credentials.get`. The options have an empty `allowCredentials` list. The device offers every passkey it holds for your site.

```ts
const loginOptions = await User.createChallengeForLogin()
```

:::

:::field{name="verifyPasskeyLogin" type="static method"}
Verifies the browser's authentication response and returns the owner of the passkey. Records the new signature counter and last used time. Throws `E_UNKNOWN_PASSKEY` for a passkey missing on the server and `E_INVALID_PASSKEY` for any other failure.

```ts
const signedInUser = await User.verifyPasskeyLogin(authenticationResponse)
```

:::

:::field{name="verifyPasskeyAuthentication" type="static method"}
Verifies the browser's authentication response against a stored passkey and returns the authentication info from SimpleWebAuthn. Called by `verifyPasskeyLogin`. Override to add checks.

```ts
const authenticationInfo = await User.verifyPasskeyAuthentication(registeredPasskey, authenticationResponse)
```

:::

::::

## DbPasskeysProvider methods

The following methods are available on the `User.passkeys` provider. Methods that take a user inherit the user's transaction.

::::field-group

:::field{name="all" type="method"}
Returns all passkeys of a user, oldest first.

```ts
const providerPasskeys = await User.passkeys.all(user)
```

:::

:::field{name="findById" type="method"}
Returns a passkey by its primary key, scoped to the user. Returns `null` when no row matches.

```ts
const foundPasskey = await User.passkeys.findById(user, id)
```

:::

:::field{name="findByCredentialId" type="method"}
Returns a passkey by its credential id, regardless of the user. Returns `null` when no row matches.

```ts
const credentialPasskey = await User.passkeys.findByCredentialId(credentialId)
```

:::

:::field{name="rename" type="method"}
Renames a passkey owned by the user. Returns the number of affected rows.

```ts
const providerRenamedCount = await User.passkeys.rename(user, id, 'Work laptop')
```

:::

:::field{name="delete" type="method"}
Deletes a passkey owned by the user. Returns the number of affected rows.

```ts
const providerDeletedCount = await User.passkeys.delete(user, id)
```

:::

:::field{name="clearExpiredChallenges" type="method"}
Deletes expired challenges. Returns the number of deleted rows.

```ts
const clearedChallengesCount = await User.passkeys.clearExpiredChallenges()
```

:::

::::

The provider also exposes `create`, `touchPasskey`, `issueChallenge`, and `consumeChallenge`. The mixin calls them during registration and login, and you do not need to call them directly.

## Passkey properties

Each `Passkey` object returned by the provider and by `registerPasskey` contains the following properties.

::::field-group

:::field{name="identifier" type="string | number | BigInt"}
The primary key of the passkey row.
:::

:::field{name="userId" type="string | number | BigInt"}
The user this passkey belongs to.
:::

:::field{name="credentialId" type="string"}
The base64url credential id generated by the device.
:::

:::field{name="publicKey" type="Uint8Array"}
The COSE encoded public key used to verify signatures.
:::

:::field{name="counter" type="number"}
The last recorded signature counter. Always `0` for synced passkeys.
:::

:::field{name="transports" type="string[] | null"}
How the browser can reach the authenticator (`internal`, `hybrid`, `usb`, `nfc`, `ble`), as reported during registration.
:::

:::field{name="deviceType" type="'singleDevice' | 'multiDevice'"}
Whether the passkey is bound to one device or can be synced across devices.
:::

:::field{name="backedUp" type="boolean"}
Whether the passkey is currently synced. Refreshed on every sign-in.
:::

:::field{name="aaguid" type="string | null"}
The authenticator model id. All zeros for devices that do not disclose it.
:::

:::field{name="name" type="string"}
The user-facing name of the passkey.
:::

:::field{name="lastUsedAt" type="Date | null"}
When the passkey was last used to sign in. `null` if never used.
:::

:::field{name="createdAt" type="Date"}
When the passkey was registered.
:::

:::field{name="updatedAt" type="Date"}
When the passkey was last updated.
:::

::::
