Guide

Passkeys

Sign in with the device's fingerprint, face or PIN, with no password to leak. ascua-passkey does the browser ceremony and the server verification, with no dependencies.

What they are

A passkey is a key pair the device creates for one site. The private key never leaves it —or the synced keychain of iCloud, Google or the password manager—; the server only stores the public one. To sign in, the device signs a challenge with the private key after the user unlocks it, and the server checks the signature.

There is nothing to steal from the database and nothing to type into a fake site: the passkey is bound to the domain, and on evil.example it does not exist.

sh
stil add ascua-passkey

ascua-passkey has two parts: the browser one (1.8 kB gzip) and ascua-passkey/server, which verifies with Web Crypto on Node 20+, Deno, Bun and a worker. Both speak the standard WebAuthn JSON, so the client works just the same against a server in another language.

The two ceremonies

Registering, with the user already identified —after signing in with their password, for example—:

  1. The server creates the options with registrationOptions() and stores the challenge.
  2. The browser calls register(options): the user confirms and the device creates the passkey.
  3. The server verifies it with verifyRegistration() and stores id, publicKey and counter.

Signing in:

  1. The server creates the options with authenticationOptions() and stores the challenge.
  2. The browser calls authenticate(options): the user picks their passkey.
  3. The server looks up the passkey by id, verifies it with verifyAuthentication(), updates the counter and opens the session.

The challenge is single-use. It is stored where it cannot be reused —a signed cookie deleted on verification, a row with an expiry— and discarded after the first verification, whether it succeeds or fails.

With the site kit

On a site with mode: "server", the actions store the challenge in a signed cookie and the island calls them with fetch, just as enhance() does.

ts
// src/routes/login.ts
import { authenticationOptions, verifyAuthentication } from "ascua-passkey/server";
import { fail, redirect, type ActionContext } from "vite-plugin-ascua/site";
import { PasskeyLoginIsland } from "../islands/passkey-login.js";

const RP_ID = "example.com";
const ORIGIN = "https://www.example.com";

export const actions = {
  async options({ cookies }: ActionContext) {
    const { options, challenge } = authenticationOptions({ rpId: RP_ID });
    await cookies.setSigned("passkey-challenge", challenge, { maxAge: 300 });
    return options;
  },

  async login({ formData, cookies }: ActionContext) {
    const challenge = await cookies.getSigned("passkey-challenge");
    cookies.delete("passkey-challenge"); // single use, whether it succeeds or fails
    if (!challenge) return fail(401, { error: "Challenge expired" });

    const response = JSON.parse(String(formData.get("credential")));
    const passkey = await findPasskey(response.id);
    if (!passkey) return fail(401, { error: "Unknown passkey" });

    try {
      const { counter } = await verifyAuthentication(response, {
        challenge, origin: ORIGIN, rpId: RP_ID, credential: passkey,
      });
      await updateCounter(passkey.id, counter);
    } catch {
      return fail(401, { error: "Could not verify" });
    }
    await cookies.setSigned("session", passkey.userId, { maxAge: 60 * 60 * 24 * 7 });
    throw redirect("/dashboard");
  },
};

export default function Login() {
  return view`<main><PasskeyLoginIsland/></main>`;
}
ts
// src/islands/passkey-login.ts
import { defineIsland, signal } from "ascua";
import { authenticate, PasskeyError, supported } from "ascua-passkey";

/** Calls an action of the page and returns what it responded. */
async function action(name: string, fields: Record<string, string> = {}) {
  const body = new FormData();
  for (const [key, value] of Object.entries(fields)) body.set(key, value);
  const res = await fetch(`?/${name}`, { method: "POST", headers: { "x-ascua-action": "1" }, body });
  return res.json();
}

function PasskeyLogin() {
  const error = signal("");

  async function signIn() {
    error.set("");
    try {
      const options = await action("options");
      const credential = await authenticate(options.data);
      const result = await action("login", { credential: JSON.stringify(credential) });
      if (result.type === "redirect") location.assign(result.location);
      else error.set(result.data?.error ?? "Could not sign in");
    } catch (e) {
      if (e instanceof PasskeyError && e.code === "cancelled") return;
      error.set(e instanceof Error ? e.message : String(e));
    }
  }

  return view`
    <div>
      <button type="button" disabled=${!supported()} onclick=${signIn}>Sign in with a passkey</button>
      <p class="error">${() => error()}</p>
    </div>`;
}

export const PasskeyLoginIsland = defineIsland("passkey-login", {}, PasskeyLogin);

The action responds in JSON because the request carries x-ascua-action: 1: { type: "success", data }, { type: "failure", status, data } or { type: "redirect", location }. The kit's origin check applies to these requests just the same.

Registering is the same with registrationOptions() and verifyRegistration(), on a page you can only reach with a session. user.id is an opaque, stable identifier —not the email—, and exclude carries the passkeys the user already has, so the browser does not create another one on the same device:

ts
async registerOptions({ cookies, locals }: ActionContext) {
  const user = locals.user;
  const { options, challenge } = registrationOptions({
    rp: { id: RP_ID, name: "Example" },
    user: { id: user.id, name: user.email },
    exclude: (await passkeysOf(user.id)).map((p) => p.id),
  });
  await cookies.setSigned("passkey-challenge", challenge, { maxAge: 300 });
  return options;
},

In the browser

ts
supported(): boolean
conditionalSupported(): Promise<boolean>
register(options, { signal? }): Promise<RegistrationResponseJSON>
authenticate(options, { signal?, conditional? }): Promise<AuthenticationResponseJSON>

The options go in as they come from the server, with or without { publicKey } around them. Where the browser has parseCreationOptionsFromJSON and toJSON(), they are used; where it does not —Safari before 17.4, Firefox before 119—, the base64url conversion is done by hand.

With conditional: true, authenticate does not open the dialog: it waits for the user to pick their passkey in the autofill of a field with autocomplete="username webauthn". It is started when the page loads, with an AbortController to cancel it if the user goes with the password, and only if conditionalSupported().

A failure is a PasskeyError with a code:

code What happened
cancelled The user closed the dialog, or it did not complete. No message needed.
exists That passkey is already registered on this device.
timeout The options' time ran out.
security The domain is not the passkey's, or the page is not secure.
unsupported The browser does not support passkeys.
unknown Anything else: the original error is in cause.

The message comes out in the language of <html lang>, Spanish or English.

Two rules the package does not enforce

They belong to the application, not to the ceremony, and skipping them opens a hole:

  • Confirm before registering. A passkey is a way in that outlasts the session. If registering one only requires being signed in, whoever steals a session leaves their own and comes back whenever they want. Ask for the current password (or a passkey the user already has) in the step that generates the registration options.
  • Revoke on account recovery. Changing the password on suspicion is useless if the passkey someone else left still works. When changing it, and when deactivating a user, delete their passkeys.

What it does not do

It does not verify the manufacturer's attestation. The options ask for attestation: "none" and the none and self-attested packed formats are accepted. For signing in to a site that is enough: what matters is that whoever signs in has the private key, not what brand of key holds it. If you need to restrict to keys from one manufacturer —a bank, a regulated environment—, you need another library.

It does not store anything. Where passkeys and challenges live is up to the application: the reference says what to store for each one.