diff --git a/e2e/tests/2fa.spec.ts b/e2e/tests/2fa.spec.ts index 8d4dc0f..eab11f0 100644 --- a/e2e/tests/2fa.spec.ts +++ b/e2e/tests/2fa.spec.ts @@ -327,6 +327,20 @@ test("WebAuthn - login triggers the passkey ceremony", async ({ browserName }) = await expect(page).not.toHaveURL(/\/login/, { timeout: 15000 }); }); +test("WebAuthn - signs in with the passkey alone (no email or password)", async ({ browserName }) => { + test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); + await logout(page); + await page.goto("/login"); + const finish = page.waitForResponse(r => r.url().includes("/api/webauthn/auth/passkey/finish") && r.request().method() === "POST"); + + // Empty allowCredentials: the virtual authenticator answers with the + // discoverable credential registered above, which names the account. + await page.getByRole("button", { name: "Sign in with a passkey" }).click(); + + expect((await finish).ok()).toBe(true); + await expect(page).not.toHaveURL(/\/login/, { timeout: 15000 }); +}); + test("WebAuthn - removes the passkey (requires WebAuthn confirmation)", async ({ browserName }) => { test.skip(browserName !== "chromium", "CDP (WebAuthn virtual authenticator) is only available in Chromium"); await page.goto("/settings"); diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts index ff78a1f..3743285 100644 --- a/packages/auth/src/index.ts +++ b/packages/auth/src/index.ts @@ -24,6 +24,8 @@ import { handleWebauthnRegisterStart } from "./routes/webauthn-register-start"; import { handleWebauthnRegisterFinish } from "./routes/webauthn-register-finish"; import { handleWebauthnAuthStart } from "./routes/webauthn-auth-start"; import { handleWebauthnAuthFinish } from "./routes/webauthn-auth-finish"; +import { handlePasskeyAuthStart } from "./routes/passkey-auth-start"; +import { handlePasskeyAuthFinish } from "./routes/passkey-auth-finish"; import { handleWebauthnCredentialsList } from "./routes/webauthn-credentials-list"; import { handleWebauthnCredentialsDelete } from "./routes/webauthn-credentials-delete"; import { handleTotpBackupCodesGenerate } from "./routes/totp-backup-codes-generate"; @@ -255,6 +257,14 @@ export default { const { success } = await env.RATE_LIMITER_AUTH.limit({ key: ip }); if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); response = await handleWebauthnAuthFinish(request, env); + } else if (url.pathname === "/webauthn/auth/passkey/start" && request.method === "POST") { + const { success } = await env.RATE_LIMITER_AUTH.limit({ key: ip }); + if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); + response = await handlePasskeyAuthStart(request, env); + } else if (url.pathname === "/webauthn/auth/passkey/finish" && request.method === "POST") { + const { success } = await env.RATE_LIMITER_AUTH.limit({ key: ip }); + if (!success) return addCorsHeaders(errorResponse(Errors.RATE_LIMITED), corsOrigin); + response = await handlePasskeyAuthFinish(request, env); } else if (url.pathname === "/webauthn/credentials" && request.method === "POST") { response = await handleWebauthnCredentialsList(request, env); } else if (url.pathname === "/webauthn/credentials/delete" && request.method === "POST") { diff --git a/packages/auth/src/routes/login.ts b/packages/auth/src/routes/login.ts index df74dba..b77e205 100644 --- a/packages/auth/src/routes/login.ts +++ b/packages/auth/src/routes/login.ts @@ -156,13 +156,14 @@ async function handlePreAuthContinuation( return issueSessionOrForceChange(request, env, row); } -// Post-2FA tail shared by the password path and the pre-auth continuation: -// force-change branch, otherwise issue a session. Assumes the caller has -// already verified credentials (password or pre-auth token) and any 2FA. -async function issueSessionOrForceChange( +// Post-2FA tail shared by the password path, the pre-auth continuation, and +// passkey sign-in: force-change branch, otherwise issue a session. Assumes the +// caller has already verified credentials (password, pre-auth token, or +// passkey), any 2FA, and the moderation / email-verification gates. +export async function issueSessionOrForceChange( request: Request, env: Env, - row: LoginUserRow, + row: Pick, ): Promise { if (row.force_password_change) { // Pre-session token: short-lived, no `sid`. Only valid against diff --git a/packages/auth/src/routes/passkey-auth-finish.test.ts b/packages/auth/src/routes/passkey-auth-finish.test.ts new file mode 100644 index 0000000..6a06125 --- /dev/null +++ b/packages/auth/src/routes/passkey-auth-finish.test.ts @@ -0,0 +1,116 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../webauthn", () => ({ + verifyDiscoverableAssertion: vi.fn(), + verifyWebauthnAssertion: vi.fn(), +})); +vi.mock("../verification", () => ({ + isEmailVerificationEnabled: vi.fn(), +})); +vi.mock("../jwt", () => ({ + signJwt: vi.fn(async () => "signed.jwt"), + verifyJwt: vi.fn(), +})); +vi.mock("../sessions", () => ({ + createSession: vi.fn(async () => "session-1"), + SESSION_TTL_MS: 7 * 24 * 60 * 60 * 1000, +})); + +import { handlePasskeyAuthFinish } from "./passkey-auth-finish"; +import { verifyDiscoverableAssertion } from "../webauthn"; +import { isEmailVerificationEnabled } from "../verification"; +import { createSession } from "../sessions"; + +function request(body: Record = { challengeId: "challenge-1", response: { id: "credential-1" } }) { + return new Request("http://localhost/webauthn/auth/passkey/finish", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +function makeEnv(overrides: Record = {}) { + const user = { + id: "user-1", + email: "user@example.com", + name: "User", + created_at: "2026-01-01", + moderation: 0, + force_password_change: 0, + is_admin: 0, + email_verified: 1, + ...overrides, + }; + const first = vi.fn().mockResolvedValue(user); + const run = vi.fn().mockResolvedValue({ meta: { changes: 1 } }); + const bind = vi.fn().mockReturnValue({ first, run }); + const prepare = vi.fn().mockReturnValue({ bind }); + return { + env: { DB: { prepare }, JWT_SECRET: "secret" } as unknown as Parameters[1], + bind, + }; +} + +beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(verifyDiscoverableAssertion).mockResolvedValue({ userId: "user-1" }); + vi.mocked(isEmailVerificationEnabled).mockResolvedValue(false); +}); + +describe("handlePasskeyAuthFinish", () => { + it("rejects a request without a challenge or assertion", async () => { + const { env } = makeEnv(); + const response = await handlePasskeyAuthFinish(request({ challengeId: "c" }), env); + expect(response.status).toBe(400); + expect(verifyDiscoverableAssertion).not.toHaveBeenCalled(); + }); + + it("issues a session for the account the verified passkey belongs to", async () => { + const { env, bind } = makeEnv(); + const response = await handlePasskeyAuthFinish(request(), env); + + expect(response.status).toBe(200); + expect(await response.json()).toMatchObject({ ok: true, data: { token: "signed.jwt", user: { id: "user-1" } } }); + expect(bind).toHaveBeenCalledWith("user-1"); + expect(createSession).toHaveBeenCalledOnce(); + }); + + it("passes a failed assertion through without loading the account", async () => { + vi.mocked(verifyDiscoverableAssertion).mockResolvedValue( + Response.json({ ok: false, error: "unauthorized" }, { status: 401 }), + ); + const { env, bind } = makeEnv(); + const response = await handlePasskeyAuthFinish(request(), env); + + expect(response.status).toBe(401); + expect(bind).not.toHaveBeenCalled(); + expect(createSession).not.toHaveBeenCalled(); + }); + + it("refuses a disabled account", async () => { + const { env } = makeEnv({ moderation: -1 }); + const response = await handlePasskeyAuthFinish(request(), env); + + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: "account_disabled" }); + expect(createSession).not.toHaveBeenCalled(); + }); + + it("gates an unverified account and returns its email for the resend prompt", async () => { + vi.mocked(isEmailVerificationEnabled).mockResolvedValue(true); + const { env } = makeEnv({ email_verified: 0 }); + const response = await handlePasskeyAuthFinish(request(), env); + + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: "email_not_verified", email: "user@example.com" }); + expect(createSession).not.toHaveBeenCalled(); + }); + + it("routes a forced password change to the change-token flow instead of a session", async () => { + const { env } = makeEnv({ force_password_change: 1 }); + const response = await handlePasskeyAuthFinish(request(), env); + + expect(await response.json()).toMatchObject({ error: "password_change_required", changeToken: "signed.jwt" }); + expect(createSession).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/auth/src/routes/passkey-auth-finish.ts b/packages/auth/src/routes/passkey-auth-finish.ts new file mode 100644 index 0000000..c4ff040 --- /dev/null +++ b/packages/auth/src/routes/passkey-auth-finish.ts @@ -0,0 +1,42 @@ +import { errorResponse, Errors } from "../lib"; +import { verifyDiscoverableAssertion } from "../webauthn"; +import { checkModeration, issueSessionOrForceChange } from "./login"; +import { isEmailVerificationEnabled } from "../verification"; +import type { Env } from "../index"; + +// Completes a usernameless passkey sign-in. A user-verifying passkey is a +// complete login on its own (possession + PIN/biometric), the same standing it +// already has as the second step of password login, so no TOTP is asked for. +// +// Unlike /webauthn/auth/finish, the account is only known once the assertion +// verifies, so the account gates run after the challenge is consumed. That's +// deliberate: checking them first would let anyone holding a credential id +// learn its account's moderation / verification state without the passkey. +// The user just retries the ceremony - there's nothing to retype. +export async function handlePasskeyAuthFinish(request: Request, env: Env): Promise { + const body = await request.json<{ challengeId?: string; response?: Record }>(); + if (!body.challengeId || !body.response || typeof body.response !== "object") { + return errorResponse(Errors.BAD_REQUEST); + } + + const result = await verifyDiscoverableAssertion(env, body.challengeId, body.response); + if (result instanceof Response) return result; + + const user = await env.DB.prepare( + "SELECT id, email, name, created_at, moderation, force_password_change, is_admin, email_verified FROM users WHERE id = ?", + ) + .bind(result.userId) + .first<{ id: string; email: string; name: string; created_at: string; moderation: number; force_password_change: number; is_admin: number; email_verified: number }>(); + if (!user) return errorResponse(Errors.UNAUTHORIZED); + + const moderationResponse = checkModeration(user.moderation); + if (moderationResponse) return moderationResponse; + + if (!user.email_verified && await isEmailVerificationEnabled(env, user.id)) { + // The caller proved control of the account, and the client never typed an + // email on this path, so hand it back for the "resend verification" button. + return Response.json({ ok: false, error: "email_not_verified", email: user.email }, { status: 403 }); + } + + return issueSessionOrForceChange(request, env, user); +} diff --git a/packages/auth/src/routes/passkey-auth-start.ts b/packages/auth/src/routes/passkey-auth-start.ts new file mode 100644 index 0000000..737c792 --- /dev/null +++ b/packages/auth/src/routes/passkey-auth-start.ts @@ -0,0 +1,11 @@ +import { okResponse } from "../lib"; +import { createDiscoverableAuthenticationOptions } from "../webauthn"; +import type { Env } from "../index"; + +// Starts a usernameless passkey sign-in. No identity in, so nothing to leak: +// the browser offers whichever passkeys it holds for this RP ID. IP-rate-limited +// in index.ts (RATE_LIMITER_AUTH), which bounds the challenge rows it writes. +export async function handlePasskeyAuthStart(_request: Request, env: Env): Promise { + const { options, challengeId } = await createDiscoverableAuthenticationOptions(env); + return okResponse({ options, challengeId }); +} diff --git a/packages/auth/src/webauthn-assertion.test.ts b/packages/auth/src/webauthn-assertion.test.ts index e83fabd..1f6f4e6 100644 --- a/packages/auth/src/webauthn-assertion.test.ts +++ b/packages/auth/src/webauthn-assertion.test.ts @@ -9,7 +9,7 @@ vi.mock("@simplewebauthn/server", () => ({ })); import { verifyAuthenticationResponse } from "@simplewebauthn/server"; -import { verifyWebauthnAssertion } from "./webauthn"; +import { verifyDiscoverableAssertion, verifyWebauthnAssertion } from "./webauthn"; // verifyWebauthnAssertion runs: consumeChallenge (DELETE ... RETURNING .first), // credential SELECT (.first), then the counter UPDATE (.run). @@ -63,3 +63,67 @@ describe("verifyWebauthnAssertion signature counter", () => { expect(run).not.toHaveBeenCalled(); }); }); + +// verifyDiscoverableAssertion runs: consumeChallenge (.first), credential +// SELECT by id only (.first), then the shared verify + counter UPDATE (.run). +function makeDiscoverableEnv(cred: Record | null) { + const binds: unknown[][] = []; + const firsts: unknown[] = [{ challenge: "chal", created_at: Date.now() }, cred]; + const first = vi.fn(async () => firsts.shift() ?? null); + const run = vi.fn(async () => ({ meta: { changes: 1 } })); + const prepare = vi.fn(() => ({ + bind: vi.fn((...args: unknown[]) => { + binds.push(args); + return { first, run }; + }), + })); + return { + env: { DB: { prepare }, WEBAUTHN_ORIGIN: "https://x", WEBAUTHN_RP_ID: "x" } as unknown as Env, + binds, + }; +} + +const storedCred = { id: "AQID", user_id: "user-1", public_key: "AQID", counter: 0 }; + +describe("verifyDiscoverableAssertion", () => { + it("consumes only a user-less passkey challenge", async () => { + verified(0); + const { env, binds } = makeDiscoverableEnv(storedCred); + await verifyDiscoverableAssertion(env, "c1", { id: "AQID", response: { userHandle: "user-1" } }); + // consumeChallenge binds (id, user_id, type): sentinel user + its own type, + // so a user-bound authentication challenge can't be redeemed here. + expect(binds[0]).toEqual(["c1", "", "passkey"]); + }); + + it("resolves the account from the credential when userHandle matches", async () => { + verified(0); + const { env } = makeDiscoverableEnv(storedCred); + const result = await verifyDiscoverableAssertion(env, "c1", { id: "AQID", response: { userHandle: "user-1" } }); + expect(result).toEqual({ userId: "user-1" }); + }); + + it.each([ + ["names another account", "user-2"], + ["is missing", undefined], + ])("rejects when userHandle %s, before verifying the signature", async (_label, userHandle) => { + verified(0); + const { env } = makeDiscoverableEnv(storedCred); + const result = await verifyDiscoverableAssertion(env, "c1", { id: "AQID", response: { userHandle } }); + expect((result as Response).status).toBe(401); + expect(verifyAuthenticationResponse).not.toHaveBeenCalled(); + }); + + it("rejects an unknown credential", async () => { + verified(0); + const { env } = makeDiscoverableEnv(null); + const result = await verifyDiscoverableAssertion(env, "c1", { id: "nope", response: { userHandle: "user-1" } }); + expect((result as Response).status).toBe(401); + }); + + it("rejects a failed signature", async () => { + vi.mocked(verifyAuthenticationResponse).mockResolvedValue({ verified: false } as unknown as Awaited>); + const { env } = makeDiscoverableEnv(storedCred); + const result = await verifyDiscoverableAssertion(env, "c1", { id: "AQID", response: { userHandle: "user-1" } }); + expect((result as Response).status).toBe(401); + }); +}); diff --git a/packages/auth/src/webauthn.ts b/packages/auth/src/webauthn.ts index a37de48..21faf7c 100644 --- a/packages/auth/src/webauthn.ts +++ b/packages/auth/src/webauthn.ts @@ -131,6 +131,32 @@ export async function createAuthenticationOptions(env: Env, userId: string) { return { options, challengeId }; } +// Discoverable ("usernameless") passkey sign-in: the user isn't known until the +// authenticator picks a credential, so the challenge row carries this sentinel +// in its NOT NULL user_id column, under its own ceremony type so it can never +// be redeemed by (or redeem) a user-bound ceremony. +const DISCOVERABLE_CHALLENGE_USER = ""; +const DISCOVERABLE_CHALLENGE_TYPE = "passkey"; + +export async function createDiscoverableAuthenticationOptions(env: Env) { + // Unauthenticated row creation - same bound as createAuthenticationOptions. + await deleteExpiredWebauthnChallenges(env); + + // No allowCredentials: the browser offers every discoverable credential it + // holds for this RP ID and the chosen one names the account. + const options = await generateAuthenticationOptions({ + rpID: env.WEBAUTHN_RP_ID, + userVerification: "required", + }); + + const challengeId = crypto.randomUUID(); + await env.DB.prepare( + "INSERT INTO webauthn_challenges (id, user_id, challenge, type, created_at) VALUES (?, ?, ?, ?, ?)", + ).bind(challengeId, DISCOVERABLE_CHALLENGE_USER, options.challenge, DISCOVERABLE_CHALLENGE_TYPE, Date.now()).run(); + + return { options, challengeId }; +} + export async function consumeChallenge( env: Env, challengeId: string, @@ -169,9 +195,54 @@ export async function verifyWebauthnAssertion( const responseId = (response as { id: string }).id; const storedCred = await env.DB.prepare( "SELECT id, public_key, counter FROM webauthn_credentials WHERE id = ? AND user_id = ?", - ).bind(responseId, userId).first<{ id: string; public_key: string; counter: number }>(); + ).bind(responseId, userId).first(); if (!storedCred) return errorResponse(Errors.UNAUTHORIZED); + return verifyAgainstCredential(env, challenge, storedCred, response, logPrefix); +} + +/** + * Verifies a discoverable-credential (usernameless passkey) assertion: consumes + * the user-less challenge, resolves the account from the credential the + * authenticator chose, and requires the returned userHandle to name that same + * account (WebAuthn ยง7.2 step 6 - mandatory when allowCredentials was empty). + * + * Returns the authenticated user id, or an error Response. + */ +export async function verifyDiscoverableAssertion( + env: Env, + challengeId: string, + response: Record, +): Promise<{ userId: string } | Response> { + const challenge = await consumeChallenge(env, challengeId, DISCOVERABLE_CHALLENGE_USER, DISCOVERABLE_CHALLENGE_TYPE); + if (!challenge) return errorResponse(Errors.BAD_REQUEST); + + const responseId = response.id; + if (typeof responseId !== "string" || !responseId) return errorResponse(Errors.UNAUTHORIZED); + + const storedCred = await env.DB.prepare( + "SELECT id, user_id, public_key, counter FROM webauthn_credentials WHERE id = ?", + ).bind(responseId).first(); + if (!storedCred) return errorResponse(Errors.UNAUTHORIZED); + + // @simplewebauthn/browser v9 decodes userHandle to the UTF-8 user id we + // registered with (createRegistrationOptions passes userID: userId). + const userHandle = (response.response as { userHandle?: unknown } | undefined)?.userHandle; + if (userHandle !== storedCred.user_id) return errorResponse(Errors.UNAUTHORIZED); + + const error = await verifyAgainstCredential(env, challenge, storedCred, response, "passkey-auth-finish"); + return error ?? { userId: storedCred.user_id }; +} + +type StoredCredential = { id: string; public_key: string; counter: number }; + +async function verifyAgainstCredential( + env: Env, + challenge: string, + storedCred: StoredCredential, + response: Record, + logPrefix: string, +): Promise { let verification: Awaited>; try { verification = await verifyAuthenticationResponse({ diff --git a/packages/frontend/src/components/AuthForm.tsx b/packages/frontend/src/components/AuthForm.tsx index 285eb15..4c06977 100644 --- a/packages/frontend/src/components/AuthForm.tsx +++ b/packages/frontend/src/components/AuthForm.tsx @@ -64,6 +64,9 @@ interface AuthFormProps { // signed out because your account was disabled." Distinct from `error`, // which uses destructive styling for action failures. header?: React.ReactNode; + // Alternative sign-in actions rendered under the form (outside it, so they + // never submit it), e.g. "Sign in with a passkey". + alternate?: React.ReactNode; devPanel?: React.ReactNode; } @@ -80,6 +83,7 @@ export function AuthForm({ hideSubmit, wordmark, header, + alternate, devPanel, }: AuthFormProps) { return ( @@ -124,7 +128,18 @@ export function AuthForm({ )} - {footer &&

{footer}

} + {alternate && ( +
+ + {alternate} +
+ )} + + {footer &&

{footer}

} {/* Dev builds only: quick-login shortcuts, framed as a labelled panel on the form's own 384px column. */} diff --git a/packages/frontend/src/pages/LoginPage.tsx b/packages/frontend/src/pages/LoginPage.tsx index 7722e3a..ad27a25 100644 --- a/packages/frontend/src/pages/LoginPage.tsx +++ b/packages/frontend/src/pages/LoginPage.tsx @@ -264,6 +264,74 @@ export function LoginPage() { // eslint-disable-next-line react-hooks/exhaustive-deps }, [email, navigate]); + // Usernameless passkey sign-in: no email or password typed. The browser + // offers the passkeys it holds for this site and the server resolves the + // account from the one chosen. A user-verifying passkey is a full login on + // its own, so there's no 2FA step after it (same as webauthn_required). + async function handlePasskeySignIn() { + if (loading) return; + setLoading(true); + setError(null); + try { + const startRes = await fetch("/api/webauthn/auth/passkey/start", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: "{}", + }); + const startJson = await startRes.json() as { + ok: boolean; + data?: { options: Record; challengeId: string }; + }; + if (!startJson.ok || !startJson.data) { + setError(startRes.status === 429 + ? "Too many attempts. Please wait a moment and try again." + : "Failed to start passkey sign-in."); + return; + } + + const { options, challengeId } = startJson.data; + let assertion; + try { + assertion = await startWebauthnAuth(options); + } catch { + setError("No passkey was used. Try again, or sign in with your email and password."); + return; + } + + const finishRes = await fetch("/api/webauthn/auth/passkey/finish", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ challengeId, response: assertion }), + }); + const finishJson = await finishRes.json() as { + ok: boolean; + data?: { token: string }; + error?: string; + until?: number; + changeToken?: string; + email?: string; + }; + + if (finishJson.ok && finishJson.data) { + await completeAuthentication(finishJson.data.token); + } else if (finishJson.error === "password_change_required" && finishJson.changeToken) { + setChangeToken(finishJson.changeToken); + setStep("force_password_change"); + } else if (finishJson.error === "email_not_verified") { + if (finishJson.email) setEmail(finishJson.email); + setStep("email_unverified"); + } else if (finishRes.status === 403) { + setError(moderationMessage(finishJson.error, finishJson.until)); + } else { + setError("That passkey isn't registered to an Annex account. Sign in with your email and password, then add it in Settings."); + } + } catch { + setError("Could not connect to the server. Please try again."); + } finally { + setLoading(false); + } + } + async function handleResendVerification() { if (!email || resendState === "sending") return; setResendState("sending"); @@ -715,6 +783,18 @@ export function LoginPage() { {reasonNotice} ) : null} + alternate={ + + } footer={ adminReturnTo ? "Your admin session will continue after sign-in." : ( <> diff --git a/packages/frontend/src/pages/UserSettingsPage.tsx b/packages/frontend/src/pages/UserSettingsPage.tsx index f1594c4..6b7db63 100644 --- a/packages/frontend/src/pages/UserSettingsPage.tsx +++ b/packages/frontend/src/pages/UserSettingsPage.tsx @@ -2557,7 +2557,7 @@ export function UserSettingsPage() { status={!webauthnLoading && ( 0} on="Enabled" off="Not set up" title={webauthnCredentials.length > 0 ? "Passkey or security key registered" : "No passkeys registered"} /> )} - description="Use a hardware security key (YubiKey, etc.) or platform passkey as a second factor." + description="Sign in with a passkey instead of your password, or use a hardware security key (YubiKey, etc.) as a second factor." action={webauthnLoading ? ( ) : !addingKey ? (