From f6e90cfc641d20656ffbc2926d7b7666ba6520a0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 12:38:55 +0000 Subject: [PATCH 1/2] fix(ui-react): start passkey autofill only beside a password field (#2555) Conditional UI attaches to the password input's `webauthn` autocomplete token, and a passkey-only login screen renders no password input. The screen still started the ceremony on every load: it spent a token of the host's login-options budget (10 per IP per minute), left an unused challenge, and logged a [passkeys] warning when @simplewebauthn found no input. The ceremony now starts only when the methods report a password. The explicit passkey button is unchanged. A render test counts login-options requests on both screens. A real Chrome runtime test with a CDP virtual authenticator proves the passkey-only screen asks for none and its button signs in, and that conditional mediation still starts once beside the password field. Co-Authored-By: Claude Opus 5.5 --- .changeset/2555-passkey-conditional-gate.md | 5 + .../components/connectivity/login-screen.tsx | 5 + .../tests/fixtures/passkey-login-client.ts | 21 +++ .../tests/passkey-login-runtime.test.ts | 173 ++++++++++++++++++ .../tests/render/render-smoke.test.tsx | 18 ++ 5 files changed, 222 insertions(+) create mode 100644 .changeset/2555-passkey-conditional-gate.md create mode 100644 packages/ui-react/tests/fixtures/passkey-login-client.ts create mode 100644 packages/ui-react/tests/passkey-login-runtime.test.ts diff --git a/.changeset/2555-passkey-conditional-gate.md b/.changeset/2555-passkey-conditional-gate.md new file mode 100644 index 0000000000..30d09f50d2 --- /dev/null +++ b/.changeset/2555-passkey-conditional-gate.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-react": patch +--- + +A passkey-only login screen no longer starts the passkey autofill ceremony. That ceremony attaches to the password field's autofill, and a passkey-only screen has no password field. Every load used to spend one of the host's ten login-options requests per minute, leave an unused challenge behind and log a `[passkeys]` warning, so a few reloads could lock out the "Sign in with a passkey" button. The button works as before, and screens with a password field still offer the passkey in its autofill. diff --git a/packages/ui-react/src/components/connectivity/login-screen.tsx b/packages/ui-react/src/components/connectivity/login-screen.tsx index 6a9cdb2fc2..e3b47cd655 100644 --- a/packages/ui-react/src/components/connectivity/login-screen.tsx +++ b/packages/ui-react/src/components/connectivity/login-screen.tsx @@ -86,6 +86,11 @@ export function LoginScreen({ reauth, onLocalCapture }: { reauth?: { revoked: bo setPasskeyAvailable(true); // Conditional UI (progressive enhancement): surface passkeys in the // password input's autofill. Runs once; a user cancel is not an error. + // It needs that input (`autoComplete="... webauthn"`), which renders + // only beside a password: without it the ceremony could never show and + // would only spend a login-options token and a challenge (#2555). The + // explicit passkey button is unaffected. + if (!methods.password) return; if (!(await supportsAutofill()) || signal.aborted) return; let finish = () => {}; const conditionalApi = new Proxy(api, { get(target, property) { diff --git a/packages/ui-react/tests/fixtures/passkey-login-client.ts b/packages/ui-react/tests/fixtures/passkey-login-client.ts new file mode 100644 index 0000000000..62beecfddd --- /dev/null +++ b/packages/ui-react/tests/fixtures/passkey-login-client.ts @@ -0,0 +1,21 @@ +import { createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { BrainUiProvider, ConnectionGate, createBrainUiRoot } from "../../src/index.ts"; +import { registerPasskey } from "../../src/lib/passkeys.ts"; + +// The passkey login screen (#2555), in the real app: the public ConnectionGate +// shows LoginScreen until the host says this browser is signed in. +const root = createBrainUiRoot({ storagePrefix: "odysseus-passkey-login", config: { appName: "Odysseus’s notebook", assistantName: "Brain" } }); +const mount = document.getElementById("app"); +if (!mount) throw new Error("Passkey login fixture mount is missing"); +createRoot(mount).render(createElement(BrainUiProvider, { root, children: createElement(ConnectionGate, { children: createElement("p", { id: "signed-in" }, "Signed in to Ithaca") }) })); + +Object.assign(window, { + __passkey: { + /** Signs in with the password, then registers one passkey on the virtual authenticator. */ + async register(password: string) { + await root.api.login(password); + await registerPasskey(root.api, "Ithaca key"); + }, + }, +}); diff --git a/packages/ui-react/tests/passkey-login-runtime.test.ts b/packages/ui-react/tests/passkey-login-runtime.test.ts new file mode 100644 index 0000000000..65c5a90901 --- /dev/null +++ b/packages/ui-react/tests/passkey-login-runtime.test.ts @@ -0,0 +1,173 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { statSync } from "node:fs"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { resolve } from "node:path"; +import { chromium, type Browser, type BrowserContext, type CDPSession, type Page } from "playwright"; +import { createRecordingObservability, createStaticBackendRegistry, resolveServerConfig } from "@schlessera/brain-ui-server"; +import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; +import { createFixtureApp as createApp } from "../../ui-server/tests/helpers/native-app-fixture.js"; +import { createFixtureBrain } from "../../../scripts/captures/core-fixture.ts"; +import { runtimePackageBuild } from "./fixtures/runtime-package-build"; +import { runtimeHookPhases } from "./fixtures/runtime-hook-phases.ts"; + +// The passkey login screen in real Chrome against real ui-server routes +// (#2555). Conditional UI attaches to the password field's `webauthn` +// autofill. On a passkey-only deployment there is no such field, so the +// screen must not spend a login-options token (10 per IP per minute) or leave +// a challenge behind, while the explicit "Sign in with a passkey" button still +// signs in. Beside a password field, conditional UI still starts once. +const candidates = [process.env.PUPPETEER_EXECUTABLE_PATH, "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]; +const executablePath = candidates.find((path) => path && statSync(path, { throwIfNoEntry: false })?.isFile()); +if (!executablePath && process.env.BRAIN_REQUIRE_CHROME === "1") throw new Error("Passkey login runtime proof requires real Chrome"); +if (!executablePath) console.warn("SKIPPING passkey login runtime proof: no Chrome; the passkey login screen is unverified in a browser locally."); + +const repo = resolve(import.meta.dir, "../../.."); +const PASSWORD = "the bow only Odysseus can string"; +let browser: Browser | undefined; +let scratch = ""; +let brain = ""; +let assets = ""; +let passwordHash = ""; +let port = 0; +type Host = { app: Awaited>; server: ReturnType }; +let host: Host | undefined; + +const backend: AgentBackend = { + id: "local-scripted", capabilities: { resume: true, permissions: false, thinking: false, attachments: false, askUser: false, costReporting: false, concurrentSessions: true, followUp: false }, + listProfiles: () => [{ id: "local-scripted", label: "Local fixture" }], + listSessions: async () => [], + getHistory: async () => [], + async startTurn() {}, +}; + +/** One host on the shared database and port; `allowPassword` keeps password login beside a passkey. */ +async function startHost(allowPassword: boolean): Promise { + const app = await createApp({ + config: resolveServerConfig({ + BRAIN_PATH: brain, DB_PATH: resolve(scratch, "ithaca.db"), AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: passwordHash, + COOKIE_SECRET: "odysseus-passkey-login-cookie-secret-0123456789", HOST: "127.0.0.1", NODE_ENV: "test", + BRAIN_UI_PRICING_DISCOVERY: "0", BRAIN_UI_MODEL_DISCOVERY: "0", ...(allowPassword ? { BRAIN_UI_ALLOW_PASSWORD: "1" } : {}), + }), + staticRoot: assets, registry: createStaticBackendRegistry([backend], backend.id), observability: createRecordingObservability(), turnTimeoutMs: 60_000, + }); + const server = Bun.serve({ hostname: "127.0.0.1", port, fetch: app.fetch, websocket: app.websocket }); + port = server.port!; + return { app, server }; +} +async function stopHost(h: Host | undefined) { + if (!h) return; + h.server.stop(true); + h.app.cancelActiveTurns(); + await h.app.close(); +} +// `localhost`, not 127.0.0.1: an IP address is not a valid WebAuthn RP ID. +const origin = () => `http://localhost:${port}`; + +const hook = runtimeHookPhases("passkey-login-runtime"); + +beforeAll(async () => { + if (!executablePath) return; + // The browser bundle resolves the workspace packages' built output. + const [out, err, code] = await runtimePackageBuild(repo, ["ui-react", "ui-server", "core"], hook); + if (code !== 0) throw new Error(`Passkey login fixture package build failed (${code}): ${out}\n${err}`); + scratch = await mkdtemp(resolve(tmpdir(), "odysseus-passkey-login-")); + brain = resolve(scratch, "brain"); + await createFixtureBrain(repo, brain); + assets = resolve(scratch, "client"); + await mkdir(assets); + const result = await Bun.build({ entrypoints: [resolve(import.meta.dir, "fixtures/passkey-login-client.ts")], target: "browser", outdir: assets, naming: "client.js" }); + if (!result.success) throw new Error(`Passkey login client build failed: ${result.logs.join("\n")}`); + await writeFile(resolve(assets, "index.html"), '
'); + passwordHash = await Bun.password.hash(PASSWORD); + host = await startHost(false); + browser = await chromium.launch({ executablePath, headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"], timeout: 120_000 }); +}, 180_000); + +afterAll(async () => { + await browser?.close(); + await stopHost(host); + if (scratch) await rm(scratch, { recursive: true, force: true }); +}); + +/** A page with a CDP virtual authenticator that answers with user verification, and a log of what it asked. */ +async function passkeyPage(context: BrowserContext): Promise<{ page: Page; cdp: CDPSession; options: string[]; warnings: string[] }> { + // Record each credentials.get mediation, so "conditional UI started" is the + // browser's own fact, and each conditional-mediation probe: the screen runs + // that probe in the same tick that draws its passkey button, just before it + // would ask for login options. + await context.addInitScript(() => { + const seen = window as unknown as { __mediations: string[]; __probes: number }; + seen.__mediations = []; seen.__probes = 0; + const get = navigator.credentials.get.bind(navigator.credentials); + navigator.credentials.get = (request?: CredentialRequestOptions) => { + seen.__mediations.push(String(request?.mediation ?? "optional")); + return get(request); + }; + const probe = PublicKeyCredential.isConditionalMediationAvailable.bind(PublicKeyCredential); + PublicKeyCredential.isConditionalMediationAvailable = () => { seen.__probes++; return probe(); }; + }); + const page = await context.newPage(); + const cdp = await context.newCDPSession(page); + await cdp.send("WebAuthn.enable"); + await cdp.send("WebAuthn.addVirtualAuthenticator", { options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } }); + const options: string[] = [], warnings: string[] = []; + page.on("request", (request) => { if (new URL(request.url()).pathname === "/api/auth/passkey/login-options") options.push(request.method()); }); + page.on("console", (message) => { if (message.type() === "warning" && message.text().startsWith("[passkeys]")) warnings.push(message.text()); }); + return { page, cdp, options, warnings }; +} + +const methods = (page: Page) => page.evaluate(async () => (await fetch("/api/auth/methods", { cache: "no-store" })).json()); +/** Waits until the login screen has the methods answer and has drawn its passkey button. */ +const loginScreenSettled = (page: Page) => page.getByRole("button", { name: "Sign in with a passkey" }).waitFor({ state: "visible", timeout: 15_000 }); + +test.skipIf(!executablePath)("a passkey-only screen asks for no login options, and its passkey button still signs in", async () => { + const context = await browser!.newContext(); + try { + const { page, options, warnings } = await passkeyPage(context); + await page.goto(origin()); + // No credential yet: the password signs in, and the passkey is registered. + await page.getByPlaceholder("Password").waitFor({ timeout: 15_000 }); + await page.evaluate((password) => (window as unknown as { __passkey: { register(p: string): Promise } }).__passkey.register(password), PASSWORD); + expect(await methods(page), "one passkey and no password override: passkey-only").toEqual({ password: false, passkey: true }); + + await context.clearCookies(); + options.length = 0; + await page.reload(); + await loginScreenSettled(page); + expect(await page.getByPlaceholder("Password").count(), "no password field, so no webauthn autofill input").toBe(0); + // The causal barrier: the screen decides in the same tick that draws the + // button, so a conditional ceremony would already have probed. Then the + // page's network goes idle, so a login-options request would have left. + expect(await page.evaluate(() => (window as unknown as { __probes: number }).__probes), "conditional UI never probed").toBe(0); + await page.waitForLoadState("networkidle"); + expect(options, "PASSKEY_ONLY_NO_LOGIN_OPTIONS").toEqual([]); + expect(warnings, "no [passkeys] warning").toEqual([]); + expect(await page.evaluate(() => (window as unknown as { __mediations: string[] }).__mediations)).toEqual([]); + + // The explicit button: one login-options request, then a signed-in app. + await page.getByRole("button", { name: "Sign in with a passkey" }).click(); + await page.locator("#signed-in").waitFor({ timeout: 15_000 }); + expect(options, "the button asked once").toEqual(["POST"]); + expect(warnings).toEqual([]); + } finally { await context.close(); } +}, 90_000); + +test.skipIf(!executablePath)("beside a password field, conditional UI starts once and offers the passkey in the field's autofill", async () => { + await stopHost(host); + host = await startHost(true); + const context = await browser!.newContext(); + try { + const { page, options, warnings } = await passkeyPage(context); + await page.goto(origin()); + expect(await methods(page)).toEqual({ password: true, passkey: true }); + await loginScreenSettled(page); + expect(await page.getByPlaceholder("Password").getAttribute("autocomplete")).toBe("current-password webauthn"); + expect(await page.evaluate(() => (window as unknown as { __probes: number }).__probes), "positive control for the probe barrier (startAuthentication probes again)").toBeGreaterThan(0); + await page.waitForFunction(() => (window as unknown as { __mediations: string[] }).__mediations.length > 0, undefined, { timeout: 15_000 }); + expect(await page.evaluate(() => (window as unknown as { __mediations: string[] }).__mediations), "the browser was asked for a conditional (autofill) passkey").toEqual(["conditional"]); + await page.waitForLoadState("networkidle"); + expect(options, "exactly one login-options request on load").toEqual(["POST"]); + expect(warnings).toEqual([]); + } finally { await context.close(); } +}, 90_000); diff --git a/packages/ui-react/tests/render/render-smoke.test.tsx b/packages/ui-react/tests/render/render-smoke.test.tsx index 1a76251d7c..445b30ab23 100644 --- a/packages/ui-react/tests/render/render-smoke.test.tsx +++ b/packages/ui-react/tests/render/render-smoke.test.tsx @@ -3538,6 +3538,24 @@ describe("authentication and passkey root ownership", () => { } finally { view.unmount(); reload.mockRestore(); a.root.dispose(); b.root.dispose(); } }); + // Conditional UI attaches to the password field's `webauthn` autofill; with + // no field it would spend a login-options token for nothing (#2555). + for (const [methods, expected] of [[{ passkey: true, password: false }, 0], [{ passkey: true, password: true }, 1]] as const) { + test(`conditional UI asks for login options ${expected === 0 ? "never on a passkey-only screen" : "once beside the password field"}`, async () => { + const platform = browser(async () => true); const a = transport("alpha"); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + const view = render(login(a.root)); + try { + await reply(a.requests[0], methods); + await act(async () => { await flushPromises(); }); + expect(a.matching("/auth/passkey/login-options", "POST")).toHaveLength(expected); + expect(view.queryByPlaceholderText("Password") !== null, "the webauthn field renders exactly when the ceremony starts").toBe(expected === 1); + expect(view.getByRole("button", { name: /passkey/i }), "the explicit passkey button stays").toBeTruthy(); + expect(warn.mock.calls.filter((call) => String(call[0]).startsWith("[passkeys]"))).toEqual([]); + } finally { warn.mockRestore(); view.unmount(); platform.restore(); a.root.dispose(); } + }); + } + test("late autofill support cannot start a ceremony after switching roots", async () => { const support = deferred(); const platform = browser(() => support.promise); const a = transport("alpha"); const b = transport("beta"); From 3623d7e30c56fa99023e9f8482bf6643171bec52 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 13:20:54 +0000 Subject: [PATCH 2/2] test(ui-react): prove the passkey autofill sign-in and inventory the runtime test (#2555) The passkey registered in the first runtime case now moves to the second case's virtual authenticator, taken after the button sign-in so its signature counter is current. The field's conditional request then signs the app in through autofill with no button pressed, instead of only showing that a conditional request was made. Probes and mediations are recorded through an exposed binding, because that sign-in reloads the page. The new runtime file is listed in the runtime build inventory, and the inventory test's count is raised to 25. Co-Authored-By: Claude Opus 5.5 --- .../tests/passkey-login-runtime.test.ts | 73 +++++++++++++------ scripts/runtime-test-builds.ts | 2 +- tests/runtime-build-selection.test.ts | 2 +- 3 files changed, 51 insertions(+), 26 deletions(-) diff --git a/packages/ui-react/tests/passkey-login-runtime.test.ts b/packages/ui-react/tests/passkey-login-runtime.test.ts index 65c5a90901..dac9b72c16 100644 --- a/packages/ui-react/tests/passkey-login-runtime.test.ts +++ b/packages/ui-react/tests/passkey-login-runtime.test.ts @@ -32,6 +32,8 @@ let passwordHash = ""; let port = 0; type Host = { app: Awaited>; server: ReturnType }; let host: Host | undefined; +/** The passkey the first test registers, carried to the second test's authenticator. */ +let registered: Record | undefined; const backend: AgentBackend = { id: "local-scripted", capabilities: { resume: true, permissions: false, thinking: false, attachments: false, askUser: false, costReporting: false, concurrentSessions: true, followUp: false }, @@ -91,30 +93,36 @@ afterAll(async () => { }); /** A page with a CDP virtual authenticator that answers with user verification, and a log of what it asked. */ -async function passkeyPage(context: BrowserContext): Promise<{ page: Page; cdp: CDPSession; options: string[]; warnings: string[] }> { +interface Seen { probes: number; mediations: string[] } +async function passkeyPage(context: BrowserContext): Promise<{ page: Page; cdp: CDPSession; authenticatorId: string; options: string[]; warnings: string[]; seen: Seen }> { // Record each credentials.get mediation, so "conditional UI started" is the // browser's own fact, and each conditional-mediation probe: the screen runs // that probe in the same tick that draws its passkey button, just before it - // would ask for login options. + // would ask for login options. Recorded here, in the test, because a + // sign-in reloads the page. + const seen: Seen = { probes: 0, mediations: [] }; + await context.exposeBinding("__seen", (_source, kind: string, value?: string) => { + if (kind === "probe") seen.probes++; + else seen.mediations.push(String(value)); + }); await context.addInitScript(() => { - const seen = window as unknown as { __mediations: string[]; __probes: number }; - seen.__mediations = []; seen.__probes = 0; + const record = (window as unknown as { __seen(kind: string, value?: string): Promise }).__seen; const get = navigator.credentials.get.bind(navigator.credentials); navigator.credentials.get = (request?: CredentialRequestOptions) => { - seen.__mediations.push(String(request?.mediation ?? "optional")); + void record("mediation", String(request?.mediation ?? "optional")); return get(request); }; const probe = PublicKeyCredential.isConditionalMediationAvailable.bind(PublicKeyCredential); - PublicKeyCredential.isConditionalMediationAvailable = () => { seen.__probes++; return probe(); }; + PublicKeyCredential.isConditionalMediationAvailable = () => { void record("probe"); return probe(); }; }); const page = await context.newPage(); const cdp = await context.newCDPSession(page); await cdp.send("WebAuthn.enable"); - await cdp.send("WebAuthn.addVirtualAuthenticator", { options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } }); + const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", { options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } }); const options: string[] = [], warnings: string[] = []; page.on("request", (request) => { if (new URL(request.url()).pathname === "/api/auth/passkey/login-options") options.push(request.method()); }); page.on("console", (message) => { if (message.type() === "warning" && message.text().startsWith("[passkeys]")) warnings.push(message.text()); }); - return { page, cdp, options, warnings }; + return { page, cdp, authenticatorId, options, warnings, seen }; } const methods = (page: Page) => page.evaluate(async () => (await fetch("/api/auth/methods", { cache: "no-store" })).json()); @@ -124,7 +132,7 @@ const loginScreenSettled = (page: Page) => page.getByRole("button", { name: "Sig test.skipIf(!executablePath)("a passkey-only screen asks for no login options, and its passkey button still signs in", async () => { const context = await browser!.newContext(); try { - const { page, options, warnings } = await passkeyPage(context); + const { page, cdp, authenticatorId, options, warnings, seen } = await passkeyPage(context); await page.goto(origin()); // No credential yet: the password signs in, and the passkey is registered. await page.getByPlaceholder("Password").waitFor({ timeout: 15_000 }); @@ -132,42 +140,59 @@ test.skipIf(!executablePath)("a passkey-only screen asks for no login options, a expect(await methods(page), "one passkey and no password override: passkey-only").toEqual({ password: false, passkey: true }); await context.clearCookies(); - options.length = 0; + options.length = 0; seen.probes = 0; seen.mediations.length = 0; await page.reload(); await loginScreenSettled(page); expect(await page.getByPlaceholder("Password").count(), "no password field, so no webauthn autofill input").toBe(0); - // The causal barrier: the screen decides in the same tick that draws the - // button, so a conditional ceremony would already have probed. Then the - // page's network goes idle, so a login-options request would have left. - expect(await page.evaluate(() => (window as unknown as { __probes: number }).__probes), "conditional UI never probed").toBe(0); + // The causal barriers: the screen decides in the same tick that draws the + // button, so a conditional ceremony would already have probed; and once + // the page's network is idle, a login-options request would have left. await page.waitForLoadState("networkidle"); + expect(seen.probes, "conditional UI never probed").toBe(0); expect(options, "PASSKEY_ONLY_NO_LOGIN_OPTIONS").toEqual([]); expect(warnings, "no [passkeys] warning").toEqual([]); - expect(await page.evaluate(() => (window as unknown as { __mediations: string[] }).__mediations)).toEqual([]); + expect(seen.mediations).toEqual([]); // The explicit button: one login-options request, then a signed-in app. await page.getByRole("button", { name: "Sign in with a passkey" }).click(); await page.locator("#signed-in").waitFor({ timeout: 15_000 }); expect(options, "the button asked once").toEqual(["POST"]); expect(warnings).toEqual([]); + // The passkey as it stands now (its signature counter included), for the next test. + const { credentials } = await cdp.send("WebAuthn.getCredentials", { authenticatorId }); + expect(credentials).toHaveLength(1); + registered = credentials[0] as unknown as Record; } finally { await context.close(); } }, 90_000); -test.skipIf(!executablePath)("beside a password field, conditional UI starts once and offers the passkey in the field's autofill", async () => { +// The page's authenticator holds the host's registered passkey, and its +// simulated user presence answers the field's conditional (autofill) request +// with it: the app signs in through autofill, with no button pressed. +test.skipIf(!executablePath)("beside a password field, conditional UI starts once and its autofill signs in with the passkey", async () => { + expect(registered, "the first test registered a passkey").toBeDefined(); await stopHost(host); host = await startHost(true); const context = await browser!.newContext(); try { - const { page, options, warnings } = await passkeyPage(context); + const { page, cdp, authenticatorId, options, warnings, seen } = await passkeyPage(context); + // The same passkey, on this page's authenticator: the one the host knows. + await cdp.send("WebAuthn.addCredential", { authenticatorId, credential: registered as never }); + const answered = page.waitForResponse((response) => new URL(response.url()).pathname === "/api/auth/passkey/login-options"); + // The field the autofill attaches to; the sign-in below reloads the page. + const field = page.waitForFunction(() => document.querySelector("input[autocomplete='current-password webauthn']") !== null, undefined, { timeout: 15_000 }); await page.goto(origin()); - expect(await methods(page)).toEqual({ password: true, passkey: true }); - await loginScreenSettled(page); - expect(await page.getByPlaceholder("Password").getAttribute("autocomplete")).toBe("current-password webauthn"); - expect(await page.evaluate(() => (window as unknown as { __probes: number }).__probes), "positive control for the probe barrier (startAuthentication probes again)").toBeGreaterThan(0); - await page.waitForFunction(() => (window as unknown as { __mediations: string[] }).__mediations.length > 0, undefined, { timeout: 15_000 }); - expect(await page.evaluate(() => (window as unknown as { __mediations: string[] }).__mediations), "the browser was asked for a conditional (autofill) passkey").toEqual(["conditional"]); + await field; + // A usernameless request for this RP, which the stored passkey answers. + const request = await (await answered).json() as { rpId?: string; allowCredentials?: unknown[] }; + expect(request.rpId).toBe("localhost"); + expect(request.allowCredentials ?? []).toEqual([]); + // The app signs in through the autofill request, with no button pressed. + await page.locator("#signed-in").waitFor({ timeout: 15_000 }); await page.waitForLoadState("networkidle"); - expect(options, "exactly one login-options request on load").toEqual(["POST"]); + expect(seen.probes, "positive control for the probe barrier (startAuthentication probes again)").toBeGreaterThan(0); + expect(seen.mediations, "the browser was asked for a conditional (autofill) passkey, and only that").toEqual(["conditional"]); + expect(options, "exactly one login-options request, and none for the sign-in itself").toEqual(["POST"]); expect(warnings).toEqual([]); + expect(await methods(page)).toEqual({ password: true, passkey: true }); } finally { await context.close(); } }, 90_000); diff --git a/scripts/runtime-test-builds.ts b/scripts/runtime-test-builds.ts index d21af7694b..aaf83ea1e4 100644 --- a/scripts/runtime-test-builds.ts +++ b/scripts/runtime-test-builds.ts @@ -4,7 +4,7 @@ import { isAbsolute, join, resolve } from "node:path"; export const runtimeTestBuilds: Readonly> = Object.fromEntries([ "answer-delivery", "approval-recovery", "artifact-recovery", "attachment-read", "association-signout", "auth-expiry", "chat-focus", - "connection-continuity", "dictation-selection", "draft", "ended-question", "external-speech", "html-preview", "live-service", "local-work", "parallel-sessions", "persona-settings", "scratch-links", "start-card", "tracker", "turn-journal", "untrusted-marks", + "connection-continuity", "dictation-selection", "draft", "ended-question", "external-speech", "html-preview", "live-service", "local-work", "parallel-sessions", "passkey-login", "persona-settings", "scratch-links", "start-card", "tracker", "turn-journal", "untrusted-marks", ].map(name => [`packages/ui-react/tests/${name}-runtime.test.ts`, ["ui-react", "ui-server", "core"]])); const special: Readonly> = { "packages/ui-react/tests/haiku-model-runtime.test.ts": ["ui-react"], diff --git a/tests/runtime-build-selection.test.ts b/tests/runtime-build-selection.test.ts index 37607aa478..eefc8f4c1e 100644 --- a/tests/runtime-build-selection.test.ts +++ b/tests/runtime-build-selection.test.ts @@ -9,7 +9,7 @@ const root = resolve(import.meta.dir, ".."); test("every runtime package hook has one inventoried actual forward closure and no boolean bypass", async () => { const directory = join(root, "packages/ui-react/tests"); const hooks = readdirSync(directory).filter(name => name.endsWith(".test.ts") && readFileSync(join(directory, name), "utf8").includes("runtimePackageBuild(")); - expect(hooks).toHaveLength(24); + expect(hooks).toHaveLength(25); expect(hooks.map(name => `packages/ui-react/tests/${name}`).sort()).toEqual(Object.keys(runtimeBuildInventory).sort()); for (const file of hooks) { const text = readFileSync(join(directory, file), "utf8");