Sign in with a passkey
For: an app developer who wants people to sign in with the fingerprint, the face, or the PIN of their device.
What it does: core runs the two WebAuthn ceremonies, and the client package runs the browser side of each.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
- A registrable domain that the API and the app share, such as
example.com. It ispasskey.rpIDin Passkeys.
- Set
passkey.rpIDto the registrable domain. - Set
passkey.originsto the web origins where the ceremonies run. Add each of them totrustedOriginstoo.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
export function createPasskeyAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", appURL: "https://app.example.com", // Each passkey origin must be baseURL or a trusted origin, or the router refuses its posts. trustedOrigins: ["https://app.example.com"], secret: deps.secret, storage: deps.storage, mail: deps.mail, passkey: { // The registrable domain that the passkeys bind to. Every origin must be on it. rpID: "example.com", // The name that the device shows. rpName: "Example", // The web origins where the ceremonies run. origins: ["https://app.example.com"], }, });}- Call
supportsPasskeys()before you show a passkey button. - On “Add a passkey”, call
client.passkey.register({ name }). The person must be signed in with a verified address. - On “Sign in with a passkey”, call
client.passkey.signIn(). - Treat the code
cancelledas a normal event. Show no error. - On a settings page, call
client.passkeys.rename({ id, name })to rename a passkey. The rename needs a session, not a fresh session.
import { type Client, supportsPasskeys } from "@authtempo/client";
/** The "Add a passkey" button. The person must be signed in with a verified address. */export async function addPasskey(client: Client, name: string): Promise<string> { if (!supportsPasskeys()) return "This browser has no passkeys."; const r = await client.passkey.register({ name }); if (r.ok) return `Passkey ${r.value.name ?? name} added.`; // A dismissed prompt is a normal event. Show nothing. return r.code === "cancelled" ? "" : `The passkey was not added: ${r.code}.`;}
/** The "Sign in with a passkey" button. The device offers its discoverable passkeys. */export async function signInWithPasskey(client: Client): Promise<string> { const r = await client.passkey.signIn(); if (r.ok) return `Signed in as ${r.value.user.email}.`; return r.code === "cancelled" ? "" : `The sign-in failed: ${r.code}.`;}import { describe, expect, it } from "vitest";import { call, harness } from "../support/harness.ts";import { createPasskeyAuth } from "./passkeys.ts";
describe("sign in with a passkey", () => { it("answers request options for a discoverable passkey on the relying party", async () => { const auth = createPasskeyAuth(harness()); const res = await call(auth, "POST", "/auth/passkey/authenticate/options", {}); expect(res.status).toBe(200); const options = (await res.json()) as { rpId: string; challenge: string; userVerification: string; }; expect(options.rpId).toBe("example.com"); expect(options.userVerification).toBe("required"); expect(options.challenge.length).toBeGreaterThan(40); });
it("refuses a registration with no session", async () => { const res = await call( createPasskeyAuth(harness()), "POST", "/auth/passkey/register/options", {}, ); expect(res.status).toBe(401); });});How it behaves
Section titled “How it behaves”- A challenge is 32 random bytes, valid for five minutes and for one use. A replayed answer fails on the spent challenge.
- Both ceremonies require user verification. Registration asks for a discoverable passkey, so the sign-in options list no passkey.
- The client converts the options itself when the browser has no
parseCreationOptionsFromJSON. @authtempo/core/testingexportsSoftAuthenticator, a software authenticator, so a test runs both ceremonies with no browser.- An Electron or Expo app runs the ceremonies in the system browser through the handoff.
- The options have the limit
passkey-options:ip:<ip>30 per 15 minutes. The verify haspasskey-verify:ip:<ip>20 per 15 minutes. - A passkey sign-in has no second factor gate. A passkey can also be a method of the second factor after a password.
- The register and the delete need a fresh session. A stale one answers
session_not_fresh. Wrap the call inclient.withFresh. api.passkeyRegistrationOptionstakes the session, andapi.deletePasskeytakes a user. Neither applies the fresh rule. Callapi.session.requireFreshfirst.- A passkey name has 1 to 64 characters, with no control or format character except the zero-width joiners. The rename refuses a name that breaks this rule. The register keeps the passkey and stores no name.
- The rename has the limit
passkey-rename:user:<userId>30 per 15 minutes. It sends no notice mail.
Related origins
Section titled “Related origins”WebAuthn Level 3 lets a passkey of one RP ID work on other sites, such as example.com and example.net. Use one passkey on related sites gives the steps.
- Set
passkey.relatedOrigins: true, and add each origin topasskey.originsand totrustedOrigins. passkey.originsmay then hold at most five origins outside the domain tree ofrpID. A browser must accept at least five labels, such asexampleofexample.net.- Core has no public suffix list, so it counts each origin outside the tree as one label. Two origins of one label count twice, so core can refuse a config that a browser accepts.
- Mount
auth.wellKnownat the origin root of therpIDhost. It answersGET /.well-known/webauthnwith{ origins }there, and 404 on any other host. - The document lists only the origins outside the domain tree of
rpID, in config order. An origin on the tree needs no document, so it takes no label. - Each ceremony still checks the origin of the browser against
passkey.origins. An origin outside the list never passes.
Hints and the Signal API
Section titled “Hints and the Signal API”passkey.hints.registerandpasskey.hints.signIngive the browser a preference:security-key,client-device, orhybrid. A hint is advice and filters no authenticator.- A
hintsfield in the body of an options request replaces the list for that ceremony. - A sign-in by a credential that the site does not store answers
passkey_unknown. CallPublicKeyCredential.signalUnknownCredentialwith it, so the device removes the passkey. The client’spasskey.signInmakes that call for you where the browser has it. - Only the passkey sign-in answers
passkey_unknown. The re-authentication and the second factor keep their codes:passkey_failed, andinvalid_codeat the challenge verify. GET /passkeysanswersrpIdanduserHandle. Pass them with the credential ids toPublicKeyCredential.signalAllAcceptedCredentials. The client’spasskeys.sync()does this.GET /passkeysalso answersuserNameanduserDisplayName, the names of a new registration. Pass them toPublicKeyCredential.signalCurrentUserDetailsafter a change of name. The client’spasskeys.signalDetails()does this.- Only the holder of the credential sees
passkey_unknown: the credential id is random, and the person’s own device gives it.
If it fails
Section titled “If it fails”unauthorized: a registration needs a session.email_unverified: a registration needs a verified address.passkey_failed: a bad signature, an origin outsidepasskey.origins, or a passkey that is already registered.passkey_unknown: the site stores no passkey with this credential id.invalid_tokenandtoken_expired: the challenge is spent or older than five minutes. Start again.rate_limited: too many ceremonies from the IP.invalid_body: at the rename, a passkey name that breaks the name rule. At an options request, a hint that is not known, or a hint twice.not_found: the passkey to delete or to rename does not belong to the caller.session_not_fresh: the session is older than the fresh window. Re-authenticate, then send it again.