Repository Public
1import { execFileSync, spawn } from "node:child_process";2import { openSync, readFileSync, writeFileSync } from "node:fs";3import { join } from "node:path";4import { expect, type Browser, type BrowserContext, type CDPSession, type Page } from "@playwright/test";56export interface E2EState {7 origin: string;8 db: string;9 dbUrl: string;10 ownerSetupUrl: string;11 apiPid: number;12 apiBin: string;13 apiEnv: Record<string, string>;14 logDir: string;15 /** exported virtual-authenticator credentials, by user handle */16 credentials?: Record<string, VirtualCredential[]>;17 /** number of browser contexts created so far (each gets its own client address) */18 clients?: number;19}20export interface VirtualCredential {21 credentialId: string;22 isResidentCredential: boolean;23 rpId?: string;24 privateKey: string;25 userHandle?: string;26 signCount: number;27}2829const SUITE_EPOCH = Date.UTC(2026, 10, 18);3031const stateFile = (): string => {32 const f = process.env.MCC_E2E_STATE;33 if (!f) throw new Error("run the suite with `pnpm e2e` (MCC_E2E_STATE is not set)");34 return f;35};36export const readState = (): E2EState => JSON.parse(readFileSync(stateFile(), "utf8")) as E2EState;37export const writeState = (patch: Partial<E2EState>): void => writeFileSync(stateFile(), JSON.stringify({ ...readState(), ...patch }, null, 2), { mode: 0o600 });3839/** Runs SQL in the e2e database (fixtures, ageing a session…). Returns unaligned tuples. */40export function sql(query: string): string {41 return execFileSync("psql", ["-h", "127.0.0.1", "-d", readState().db, "-v", "ON_ERROR_STOP=1", "-AtX", "-c", query], { encoding: "utf8" }).trim();42}4344/**45 * The API limits passkey ceremonies and invitation exchanges per client IP (in memory). The suite performs far more46 * of them than one person would, so every browser context is a distinct client: it presents its own address in47 * `X-Forwarded-For`, which control-api trusts from 127.0.0.1 exactly as it trusts the public gateway in production.48 * The limiter itself is exercised on purpose in 03-security.49 */50export async function newClient(browser: Browser, opts: { locale?: string; conditional?: boolean } = {}): Promise<BrowserContext> {51 const n = (readState().clients ?? 0) + 1;52 writeState({ clients: n });53 const context = await browser.newContext({54 ...(opts.locale ? { locale: opts.locale } : {}),55 extraHTTPHeaders: { "X-Forwarded-For": `198.51.100.${(n % 250) + 1}` },56 });57 if (!opts.conditional) await withoutConditionalMediation(context);58 return context;59}6061/** Waits until the screen has finished its initial loading (no skeleton left). `networkidle` cannot be used: the event stream stays open. */62export async function settled(page: Page): Promise<void> {63 await page.waitForFunction(() => document.querySelector(".mcc-skel") === null, undefined, { timeout: 15_000 });64 await page.waitForTimeout(150);65}6667/** Stops control-api (by PID) and starts it again after `downMs`. */68export async function restartApi(downMs: number, whileDown?: () => Promise<void>): Promise<void> {69 const s = readState();70 process.kill(s.apiPid, "SIGTERM");71 await new Promise((r) => setTimeout(r, downMs));72 if (whileDown) await whileDown();73 const out = openSync(join(s.logDir, "control-api.log"), "a");74 const child = spawn(s.apiBin, [], { env: { ...process.env, ...s.apiEnv }, stdio: ["ignore", out, out], detached: true });75 child.unref();76 if (!child.pid) throw new Error("control-api did not restart");77 writeState({ apiPid: child.pid });78 for (let i = 0; i < 120; i++) {79 try {80 if ((await fetch(`${s.origin}/api/v1/health/ready`)).ok) return;81 } catch { /* not yet */ }82 await new Promise((r) => setTimeout(r, 250));83 }84 throw new Error("control-api did not come back");85}8687export interface Authenticator {88 cdp: CDPSession;89 id: string;90 credentials: () => Promise<VirtualCredential[]>;91 add: (c: VirtualCredential) => Promise<void>;92 /** false: ceremonies stay pending until presence is enabled again (a user who has not touched the key yet). */93 presence: (on: boolean) => Promise<void>;94}9596/** CDP virtual authenticator: internal transport, resident keys, user verification always succeeding. */97export async function addAuthenticator(page: Page, credentials: VirtualCredential[] = []): Promise<Authenticator> {98 const cdp = await page.context().newCDPSession(page);99 await cdp.send("WebAuthn.enable");100 const { authenticatorId } = await cdp.send("WebAuthn.addVirtualAuthenticator", {101 options: { protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true },102 });103 const auth: Authenticator = {104 cdp,105 id: authenticatorId,106 credentials: async () => (await cdp.send("WebAuthn.getCredentials", { authenticatorId })).credentials as VirtualCredential[],107 add: async (c) => {108 await cdp.send("WebAuthn.addCredential", { authenticatorId, credential: { ...c, rpId: c.rpId ?? "localhost" } });109 },110 presence: async (on) => {111 await cdp.send("WebAuthn.setAutomaticPresenceSimulation", { authenticatorId, enabled: on });112 },113 };114 for (const c of credentials) await auth.add(c);115 return auth;116}117118/** Remember the passkeys of a user so other specs can sign in as them. */119export async function saveCredentials(handle: string, auth: Authenticator): Promise<void> {120 const s = readState();121 writeState({ credentials: { ...(s.credentials ?? {}), [handle]: await auth.credentials() } });122}123export function savedCredentials(handle: string): VirtualCredential[] {124 const c = readState().credentials?.[handle];125 if (!c?.length) throw new Error(`no saved passkey for ${handle}: the identity spec must run first`);126 // The server refuses a signature counter that goes backwards (cloned-key detection). A copy of the key loaded127 // into a new virtual authenticator therefore starts from a counter above anything used so far (10 per second128 // since the suite started is far more than the ceremonies it runs).129 const base = Math.floor((Date.now() - SUITE_EPOCH) / 100) + 1000;130 return c.map((k) => ({ ...k, signCount: base }));131}132133export interface Problems {134 csp: string[];135 console: string[];136 /** Failures the current test expects (for example the 401 after a revocation). */137 allow: (pattern: RegExp) => void;138 assertClean: () => void;139}140141/**142 * Collects Content-Security-Policy violations and console errors of every page of a context. Each spec calls143 * `assertClean()` at the end: any violation fails the suite.144 */145export async function watch(context: BrowserContext): Promise<Problems> {146 const csp: string[] = [];147 const cons: string[] = [];148 const allowed: RegExp[] = [/Failed to load resource: the server responded with a status of (401|403|404|409|410|422|429|501|503)/, /net::ERR_(CONNECTION_REFUSED|EMPTY_RESPONSE|ABORTED|INCOMPLETE_CHUNKED_ENCODING|CONNECTION_RESET)/];149 await context.exposeBinding("__mccCsp", (_src, v: string) => { csp.push(v); });150 await context.addInitScript(() => {151 document.addEventListener("securitypolicyviolation", (e) => {152 (window as unknown as { __mccCsp: (v: string) => void }).__mccCsp(`${e.violatedDirective} blocked ${e.blockedURI || "inline"} on ${location.pathname} (${e.sourceFile ?? ""}:${e.lineNumber})`);153 });154 });155 const hook = (page: Page) => {156 page.on("console", (m) => {157 if (m.type() !== "error") return;158 const text = m.text();159 if (/Content Security Policy|Refused to (load|execute|apply)/i.test(text)) csp.push(text);160 else cons.push(text);161 });162 page.on("pageerror", (e) => cons.push(`pageerror: ${e.message}`));163 };164 context.pages().forEach(hook);165 context.on("page", hook);166 return {167 csp,168 console: cons,169 allow: (p) => allowed.push(p),170 assertClean: () => {171 expect(csp, "CSP violations").toEqual([]);172 expect(cons.filter((t) => !allowed.some((p) => p.test(t))), "console errors").toEqual([]);173 },174 };175}176177/**178 * The virtual authenticator answers an autofill-assisted (conditional) request by itself, which would sign the page179 * in before the button is pressed. Contexts that test the explicit button report conditional mediation as absent.180 */181export async function withoutConditionalMediation(context: BrowserContext): Promise<void> {182 await context.addInitScript(() => {183 if (typeof PublicKeyCredential !== "undefined") {184 (PublicKeyCredential as unknown as { isConditionalMediationAvailable: () => Promise<boolean> }).isConditionalMediationAvailable = async () => false;185 }186 });187}188189/** New context signed in as a saved user (passkey ceremony through the sign-in button). */190export async function signedIn(browser: Browser, handle: string, opts: { locale?: string } = {}): Promise<{ context: BrowserContext; page: Page; auth: Authenticator; problems: Problems }> {191 const context = await newClient(browser, opts);192 const problems = await watch(context);193 const page = await context.newPage();194 const auth = await addAuthenticator(page, savedCredentials(handle));195 await signIn(page);196 return { context, page, auth, problems };197}198199export async function signIn(page: Page): Promise<void> {200 await page.goto("/signin");201 await page.getByTestId("signin-button").click();202 await expect(page.getByTestId("account-menu")).toBeVisible();203}204205/** Whether an API group is live (200) or still answering 501 / 503: specs for real data skip themselves until then. */206export async function endpointLive(page: Page, path: string): Promise<boolean> {207 const status = await page.evaluate(async (p) => (await fetch(`/api/v1${p}`, { credentials: "same-origin" })).status, path);208 return status === 200;209}210