Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions e2e/tests/2fa.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
10 changes: 10 additions & 0 deletions packages/auth/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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") {
Expand Down
11 changes: 6 additions & 5 deletions packages/auth/src/routes/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<LoginUserRow, "id" | "email" | "name" | "created_at" | "force_password_change" | "is_admin">,
): Promise<Response> {
if (row.force_password_change) {
// Pre-session token: short-lived, no `sid`. Only valid against
Expand Down
116 changes: 116 additions & 0 deletions packages/auth/src/routes/passkey-auth-finish.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = { 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<string, unknown> = {}) {
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<typeof handlePasskeyAuthFinish>[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();
});
});
42 changes: 42 additions & 0 deletions packages/auth/src/routes/passkey-auth-finish.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
const body = await request.json<{ challengeId?: string; response?: Record<string, unknown> }>();
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);
}
11 changes: 11 additions & 0 deletions packages/auth/src/routes/passkey-auth-start.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
const { options, challengeId } = await createDiscoverableAuthenticationOptions(env);
return okResponse({ options, challengeId });
}
66 changes: 65 additions & 1 deletion packages/auth/src/webauthn-assertion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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<string, unknown> | 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<ReturnType<typeof verifyAuthenticationResponse>>);
const { env } = makeDiscoverableEnv(storedCred);
const result = await verifyDiscoverableAssertion(env, "c1", { id: "AQID", response: { userHandle: "user-1" } });
expect((result as Response).status).toBe(401);
});
});
Loading
Loading