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, and this page is available as Markdown at https://dotpress.dev/auth/passkeys.md.

Passkeys

passkeys adds the passkeys (WebAuthn): a login without password, a second factor of MFA, and a step-up. It checks the responses with @simplewebauthn/server, an optional peer dependency, and needs the passkeys, tokens and users.findAccount() stores.

pnpm add @simplewebauthn/server
import { createPasskeys } from '@dotpress/auth/passkeys'

createAuth({
  // …
  passkeys: createPasskeys({
    rpName: 'Notes',
    rpId: 'example.com',
    origins: ['https://app.example.com'],
  }),
})
OptionDefaultDescription
rpName—Name of the app, shown by the authenticators. Required.
rpId—Domain the passkeys belong to, without scheme nor port: example.com covers its subdomains. Required.
origins—Origins of the pages that use the passkeys: ['https://app.example.com']. Required.
userVerification'required''required': the authenticator checks the user (biometrics, PIN), and a passkey counts as two factors. 'preferred': a passkey without user verification is a first factor only.
residentKey'required''required', 'preferred' or 'discouraged': discoverable credentials, for the login without username.
attestation'none''none' or 'direct'. With 'direct', no trust anchor nor AAGUID policy applies: to accept only some authenticators, check the aaguid of the passkeys in the app.
maxPerUser10Passkeys per user.
passwordlesstrueThe login with a passkey (/auth/passkeys/login). false keeps the passkeys for the second factor and the step-up.
challengeTtl'5m'Lifetime of a challenge, 30 seconds at least.

createPasskeys() throws a TypeError or a RangeError for an invalid option, at startup.

In the browser

Each flow has two requests. The first returns { challengeToken, expiresAt, options }: the options go to the browser, and its response comes back with the challengeToken, which works once.

const { challengeToken, options } = await post('/auth/passkeys/login/options', {})
const credential = await navigator.credentials.get({
  publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options),
})
await post('/auth/passkeys/login', { challengeToken, response: credential.toJSON() })

The registration uses PublicKeyCredential.parseCreationOptionsFromJSON() and navigator.credentials.create(). startRegistration() and startAuthentication() of @simplewebauthn/browser do the same, for the browsers without these methods.

Login

With passwordless, a passkey starts a session without username nor password:

RouteBodyAnswer
POST /auth/passkeys/login/options—{ challengeToken, expiresAt, options }: a challenge for any passkey of the site. 30 per 15 minutes per IP (rateLimits.passkeys.ip).
POST /auth/passkeys/login{ challengeToken, response, mode?, trustedDeviceToken? }The answer of a login.

An invalid response, or an unknown, expired or used challenge, answers 401 PASSKEY_VERIFICATION_FAILED; so does a response whose userHandle is not the owner of the passkey. The account gate and beforeSession run as for a password login. With mode: 'cookie', a login from an untrusted origin answers 403 CROSS_ORIGIN_REQUEST.

The amr of the session is hwk for a passkey bound to its device, swk for a synced passkey (iCloud Keychain, Google Password Manager…), with user and mfa when the authenticator verified the user: requireMfa() accepts it, and mfa asks no second factor. A passkey without user verification (userVerification: 'preferred') is a first factor only: with mfa, the login answers mfa_required without offering the passkeys, and a user with no other factor gets 403 MFA_ENROLLMENT_REQUIRED.

Managing the passkeys

RouteBodyAnswer
POST /auth/passkeys/registration/options—{ challengeToken, expiresAt, options }. The options exclude the passkeys of the user.
POST /auth/passkeys/registration{ challengeToken, response, name? }{ passkeyId, recoveryCodes? }
GET /auth/passkeys—{ passkeys }: id, name, deviceType (singleDevice, multiDevice), backedUp, transports, createdAt, lastUsedAt. Never the public key.
PATCH /auth/passkeys/:id{ name }{ status: 'renamed' }
DELETE /auth/passkeys/:id—{ status: 'removed' }

The registration and the removal require an authentication of less than 10 minutes (403 REAUTHENTICATION_REQUIRED, see step-up), and refuse impersonations (403 IMPERSONATION_FORBIDDEN); the rename refuses impersonations too. With mfa, a user with a verified factor or a passkey also needs a second factor within the last 10 minutes: 403 MFA_REQUIRED, with data.maxAgeSeconds: 600. A passkey gets the name given, or Passkey 1, Passkey 2…

  • A user has maxPerUser passkeys at most: 409 PASSKEY_LIMIT_REACHED. A passkey already stored answers 409 PASSKEY_ALREADY_REGISTERED.
  • The first second factor of a user, passkey or factor, gets the recovery codes (with mfa.recoveryCodes), shown once. The codes stay while a factor or a passkey remains; removing the last one takes them with it.
  • With mfa, the first passkey of a user without factor revokes the other sessions (reason mfa_enabled); the session that registers it goes on.
  • A new or removed passkey revokes the trusted devices of the user.
  • A passkey that is the last way to log in of an account (no password, no other passkey nor linked identity) cannot be removed: 409 LAST_LOGIN_METHOD.
  • An unknown passkey, or a passkey of another user, answers 404 PASSKEY_NOT_FOUND.

Second factor

With mfa, the passkeys of a user count as enrolled factors: mfa.required: 'when_enrolled' asks a second factor to a user with a passkey, and mfa accepts the passkeys as its only factor (no totp, email nor sms). The mfa_required answer has passkey: true when the user has passkeys:

RouteBodyAnswer
POST /auth/mfa/passkey/options{ challengeToken }{ options }: the passkeys of the user of the challenge (404 PASSKEY_NOT_FOUND without one)
POST /auth/mfa/verify{ challengeToken, method: 'passkey', response, rememberDevice?, mode? }The answer of a login

A wrong passkey counts a wrong attempt of the challenge (400 INVALID_CODE).

The passkeys stay enrolled factors when passkeys is removed from the settings while mfa stays, as long as the data provider keeps its passkeys store: their user is not let in with one factor. The login asks another factor or a recovery code, and without one answers 403 MFA_ENROLLMENT_REQUIRED. Before removing passkeys, have these users enroll another factor, or delete their passkeys.

Step-up

RouteBodyAnswer
POST /auth/step-up/passkey/options—{ challengeToken, expiresAt, options } (404 PASSKEY_NOT_FOUND without passkey)
POST /auth/step-up{ method: 'passkey', challengeToken, response, mode? }A new token pair, reauthenticatedAt, mfaVerifiedAt

A passkey step-up is a second factor when the authenticator verified the user, or in a session not opened by a passkey: the session records mfaVerifiedAt, and its amr adds hwk or swk and mfa. See Step-up.

Cloned passkeys

An authenticator increments a signature counter at each use. A response whose counter is not above the stored one comes from a copy of the passkey: the login, second factor or step-up answers 401 PASSKEY_COUNTER_INVALID, and the passkey.counter_invalid event is recorded. The authenticators without counter always send 0, accepted.

The passkeys store

dataProvider.passkeys keeps a passkey as { id, userId, credentialId, publicKey, counter, transports, deviceType, backedUp, name, aaguid, createdAt, lastUsedAt }:

interface PasskeyStore {
  list(userId: string): Promise<StoredPasskey[]> // oldest first
  findByCredentialId(credentialId: string): Promise<StoredPasskey | undefined>
  create(input: NewPasskey): Promise<{ id: string } | 'taken'> // 'taken': credential ID already stored
  updateUsage(id: string, input: { counter: number; lastUsedAt: Date; backedUp: boolean }): Promise<void>
  rename(id: string, name: string): Promise<void>
  delete(id: string): Promise<void>
}

credentialId and publicKey are base64url. Put a unique constraint on credentialId. The challenges live in the tokens store.

Services

auth.passkeys.login.options(), login.verify(), registration.options(), registration.verify(), list(), rename() and remove() do the same outside the routes, and throw an AuthError. With mfa, registration.options(), registration.verify() and remove() take mfaVerifiedAt, the last second factor of the session, and registration.verify() takes the sessionId of the registering session.

In tests

createVirtualAuthenticator() of @dotpress/auth/testing creates and signs passkeys in memory, without browser:

import { createVirtualAuthenticator } from '@dotpress/auth/testing'

const authenticator = createVirtualAuthenticator({ rpId: 'example.com', origin: 'https://app.example.com' })

const created = await (await post('/auth/passkeys/registration/options', {}, accessToken)).json()
const response = await authenticator.createCredential(created.options)
await post('/auth/passkeys/registration', { challengeToken: created.challengeToken, response }, accessToken)

const login = await (await post('/auth/passkeys/login/options', {})).json()
const assertion = await authenticator.getAssertion(login.options)
await post('/auth/passkeys/login', { challengeToken: login.challengeToken, response: assertion })

userVerification: false and backedUp: true change the flags of the authenticator; the second argument of getAssertion() ({ credentialId?, origin?, rpId?, userVerification? }) forges an invalid response, and setCounter(credentialId, counter) a cloned one.

Errors

StatusCodeWhen
401PASSKEY_VERIFICATION_FAILEDAn invalid response, or an unknown, expired or used challenge
401PASSKEY_COUNTER_INVALIDA cloned passkey
409PASSKEY_ALREADY_REGISTEREDA passkey already stored
409PASSKEY_LIMIT_REACHEDmaxPerUser reached
404PASSKEY_NOT_FOUNDAn unknown passkey, or a user without passkey
409LAST_LOGIN_METHODThe last way to log in of the account: no password, no other passkey nor identity