import { cleanupProbe, runCleanupTimeout, registerCleanupProbe, } from "./fixtures/native-cleanup-probe.mjs"; import { NativeFixtureLifetime } from "./fixtures/native-fixture-lifetime.mjs"; import { BridgeHttpDiagnostics } from "./fixtures/bridge-http-diagnostics.mjs"; import * as Effect from "effect/Effect"; import assert from "node:assert/strict"; import { randomBytes, generateKeyPairSync, sign, createHash, } from "node:crypto"; import { mkdtemp, readFile, writeFile, rm } from "node:fs/promises"; import { createServer as netServer } from "node:net"; import { createServer as httpsServer } from "node:https"; import { request as httpRequest } from "node:http"; import { execFileSync } from "node:child_process"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { test } from "node:test"; import { unstable_dev } from "wrangler"; import { chromium } from "playwright"; import { parse } from "jsonc-parser"; import { oauthBindings, oauthConfig } from "./fixtures/oauth-config.mjs"; import { customerBindings } from "./fixtures/config.mjs"; import { parseInstallationConfig } from "../configuration/customer.ts"; import { parseControlPlaneConfig } from "../configuration/control-plane.ts"; import { LOGIN_PURPOSE, HEALTH_PURPOSE, PROVIDER_PURPOSE, DOMAIN_CONFIGURATION_PURPOSE, DOMAIN_HEALTH_PURPOSE, } from "../shared/bridge.ts"; import { verifyAssertion } from "../server/bridge.ts"; const id = () => randomBytes(32).toString("base64url"); const pair = generateKeyPairSync("ed25519"); const bridgeKey = { keyId: "fixture-key", publicKey: pair.publicKey.export({ format: "jwk" }).x, }; const privateKey = pair.privateKey .export({ type: "pkcs8", format: "der" }) .toString("base64url"); const I = "0123456789abcdef0123456789abcdef"; const CP = "https://publisher.test"; const CUSTOMER = `https://flarebot-${I}.bridgefixture.workers.dev`; const OWNER = "verified-userinfo-subject"; const release = { version: "0.1.0-dev.1", artifactDigest: "d".repeat(64), operationId: "e".repeat(32), }; const claims = { iss: CP, aud: CUSTOMER, sub: OWNER, installationId: I, purpose: LOGIN_PURPOSE, state: id(), challenge: id(), }; function token( value, header = { alg: "EdDSA", kid: bridgeKey.keyId, typ: "JWT" }, key = pair.privateKey, ) { const payload = [header, value] .map((v) => Buffer.from(JSON.stringify(v)).toString("base64url")) .join("."); return `${payload}.${sign(null, Buffer.from(payload), key).toString("base64url")}`; } test("pinned bridge assertion validates every exact claim and separates purposes", async () => { const now = Math.floor(Date.now() / 1000); const value = { ...claims, iat: now, exp: now + 60, jti: id() }; assert.deepEqual( await Effect.runPromise(verifyAssertion(token(value), bridgeKey, claims)), value, ); for (const field of [ "iss", "aud", "sub", "installationId", "purpose", "state", "challenge", ]) { await assert.rejects( Effect.runPromise( verifyAssertion( token({ ...value, [field]: "wrong" }), bridgeKey, claims, ), ), ); } // A future `iat` must be rejected, but `now` is recomputed inside // verifyAssertion. A one-second offset can be swallowed when the wall clock // advances between capture and verification, so use a margin that cannot. for (const change of [ { iat: now + 30 }, { exp: now }, { exp: now + 61 }, { jti: "short" }, { extra: "hidden" }, { iat: 1.1 }, { purpose: HEALTH_PURPOSE }, ]) await assert.rejects( Effect.runPromise( verifyAssertion(token({ ...value, ...change }), bridgeKey, claims), ), ); for (const header of [ { alg: "HS256", kid: bridgeKey.keyId, typ: "JWT" }, { alg: "EdDSA", kid: "rotated", typ: "JWT" }, { alg: "EdDSA", kid: bridgeKey.keyId, typ: "JWT", jwk: pair.publicKey.export({ format: "jwk" }), }, ]) await assert.rejects( Effect.runPromise( verifyAssertion(token(value, header), bridgeKey, claims), ), ); await assert.rejects( Effect.runPromise( verifyAssertion( token(value, undefined, generateKeyPairSync("ed25519").privateKey), bridgeKey, claims, ), ), ); }); test("bridge pins and deployment markers preserve strict secret-free configuration", () => { const installation = { schemaVersion: 1, installationId: I, ownerSubject: OWNER, runtimeOrigin: CUSTOMER, controlPlaneOrigin: CP, bridge: bridgeKey, release, }; assert.deepEqual(parseInstallationConfig(installation), installation); assert.deepEqual( parseControlPlaneConfig({ ...oauthConfig(CP), bridge: bridgeKey }).bridge, bridgeKey, ); for (const change of [ { bridge: { ...bridgeKey, privateKey } }, { bridge: { ...bridgeKey, keyId: "../key" } }, { bridge: { ...bridgeKey, publicKey: "short" } }, { release: { ...release, sessionSecret: "secret" } }, { release: { ...release, operationId: "not-an-operation" } }, { release: { ...release, artifactDigest: "bad" } }, ]) assert.throws(() => parseInstallationConfig({ ...installation, ...change }), ); assert.throws(() => parseControlPlaneConfig({ ...oauthConfig(CP), bridge: { ...bridgeKey, privateKey }, }), ); }); async function freePort(lifetime) { const server = lifetime.own( "port reservation", netServer(), (server) => new Promise((resolve) => server.close(() => resolve())), ); await new Promise((done) => server.listen(0, "127.0.0.1", done)); const port = server.address().port; await new Promise((done) => server.close(done)); return port; } const cookie = (response, name) => response.headers .getSetCookie() .find((value) => value.startsWith(`${name}=`)) ?.split(";")[0]; test( "native two-site HTTPS owner login, atomic replay retention, encrypted operation and native health", { timeout: 360_000 }, async (t) => { const lifetime = new NativeFixtureLifetime(t, "bridge"); const temporary = await lifetime.start( "directory", () => mkdtemp(join(tmpdir(), "flarebot-bridge-")), (path) => rm(path, { recursive: true, force: true }), true, ); const cpPort = await freePort(lifetime), customerPort = await freePort(lifetime); const installation = { schemaVersion: 1, installationId: I, ownerSubject: OWNER, runtimeOrigin: CUSTOMER, controlPlaneOrigin: CP, bridge: bridgeKey, release, }; const config = oauthConfig(CP); config.bridge = bridgeKey; const cpBindings = { ...oauthBindings(CP), FLAREBOT_CONTROL_PLANE: JSON.stringify(config), FLAREBOT_BRIDGE_SIGNING_KEY: privateKey, TEST_CUSTOMER_PORT: String(customerPort), }; const baseCP = parse( await readFile("wrangler.control-plane.jsonc", "utf8"), ); const baseCustomer = parse(await readFile("wrangler.jsonc", "utf8")); const cpPath = join(temporary, "cp.json"), customerPath = join(temporary, "customer.json"); await writeFile( cpPath, JSON.stringify({ ...baseCP, name: "flarebot-bridge-cp", main: resolve("tests/fixtures/bridge-control-worker.ts"), assets: { directory: resolve("dist/control-plane/client"), binding: "ASSETS", }, }), ); await writeFile( customerPath, JSON.stringify({ ...baseCustomer, name: "flarebot-bridge-customer", main: resolve("tests/fixtures/bridge-customer-worker.ts"), assets: { directory: resolve("dist/client"), binding: "ASSETS" }, }), ); const options = (config, port, vars, containers = false) => ({ config, vars, local: true, ip: "127.0.0.1", port, inspectorPort: 0, persist: true, persistTo: join(temporary, String(port)), logLevel: "error", experimental: { disableExperimentalWarning: true, watch: false, enableContainers: containers, }, }); const startCP = () => lifetime.start( "control Worker", () => unstable_dev( "tests/fixtures/bridge-control-worker.ts", options(cpPath, cpPort, cpBindings), ), (worker) => worker.stop(), ); const startCustomer = () => lifetime.start( "customer Worker", () => unstable_dev( "tests/fixtures/bridge-customer-worker.ts", options( customerPath, customerPort, { ...customerBindings, FLAREBOT_INSTALLATION: JSON.stringify(installation), TEST_CP_PORT: String(cpPort), }, true, ), ), (worker) => worker.stop(), ); let cp, customer, browser, proxy; let mode = "normal", oauthVisits = 0; const visited = []; let holdHTTP = false; const responseHeld = Promise.withResolvers(); const httpDiagnostics = new BridgeHttpDiagnostics((facts) => t.diagnostic(`Native bridge HTTP failed: ${JSON.stringify(facts)}`), ); const nativeCall = (port, path, init = {}) => lifetime.wait( "native HTTP", new Promise((resolve, reject) => { lifetime.signal.throwIfAborted(); const body = init.body === undefined ? undefined : String(init.body); const req = httpRequest( { hostname: "127.0.0.1", port, path, method: init.method ?? "GET", signal: lifetime.signal, headers: { "Sec-Fetch-Mode": "navigate", ...init.headers }, }, (incoming) => { if (holdHTTP) { incoming.pause(); responseHeld.resolve(); return; } const chunks = []; incoming.on("data", (chunk) => chunks.push(chunk)); incoming.on("end", () => { const headers = new Headers(); for (let i = 0; i < incoming.rawHeaders.length; i += 2) headers.append( incoming.rawHeaders[i], incoming.rawHeaders[i + 1], ); resolve( new Response(Buffer.concat(chunks), { status: incoming.statusCode, headers, }), ); }); }, ); lifetime.own("HTTP request", req, (request) => request.destroy()); httpDiagnostics.watch( req, { role: port === cpPort ? "publisher" : "customer", path, method: init.method ?? "GET", }, reject, ); req.end(body); }), ); const callCP = (path, init = {}) => nativeCall(cpPort, path, init); const callCustomer = (path, init = {}) => nativeCall(customerPort, path, init); const post = (call, path, body, headers = {}) => call(path, { method: "POST", headers: { "Content-Type": "application/json", ...headers }, body: JSON.stringify(body), }); const now = Date.now(); const record = { schemaVersion: 1, installationId: I, ownerSubject: OWNER, accountId: "a".repeat(32), createdAt: now, updatedAt: now, revision: 3, resources: { workerName: `flarebot-${I}`, sandboxApplicationName: `flarebot-shell-${I}`, runtimeOrigin: CUSTOMER, personalAgentNamespaceId: "1".repeat(32), sandboxNamespaceId: "2".repeat(32), sandboxApplicationId: "3".repeat(32), }, desiredRelease: { version: release.version, artifactDigest: release.artifactDigest, sourceRevision: "4".repeat(40), }, installedRelease: { version: release.version, artifactDigest: release.artifactDigest, sourceRevision: "4".repeat(40), installedAt: now, }, status: "ready", errorCode: null, operationId: release.operationId, }; try { cp = await startCP(); customer = await startCustomer(); assert.equal( (await post(callCP, "/__bridge__/seed", record)).status, 200, ); // A real TLS reverse proxy preserves browser-origin, Cookie and WebSocket headers. execFileSync( "openssl", [ "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", join(temporary, "key.pem"), "-out", join(temporary, "cert.pem"), "-days", "1", "-subj", "/CN=publisher.test", "-addext", `subjectAltName=DNS:publisher.test,DNS:${new URL(CUSTOMER).hostname}`, ], { stdio: "ignore" }, ); const target = (req) => req.headers.host === "publisher.test" ? cpPort : customerPort; const tls = { key: await readFile(join(temporary, "key.pem")), cert: await readFile(join(temporary, "cert.pem")), }; lifetime.signal.throwIfAborted(); proxy = httpsServer(tls, async (req, res) => { if (lifetime.signal.aborted) { res.destroy(); return; } if (req.headers.host === "dash.cloudflare.com") { const url = new URL(req.url, "https://dash.cloudflare.com"); if (url.pathname !== "/oauth2/auth") { res.writeHead(404); res.end(); return; } oauthVisits++; const code = id(); assert.equal(url.searchParams.get("code_challenge_method"), "S256"); await post(callCP, "/__test__/code", { code, challenge: url.searchParams.get("code_challenge"), mode, }); const callback = new URL(url.searchParams.get("redirect_uri")); callback.search = new URLSearchParams({ code, state: url.searchParams.get("state"), }); res.writeHead(303, { location: callback.href, "cache-control": "no-store", "referrer-policy": "no-referrer", }); res.end(); return; } const headers = { ...req.headers, "x-fixture-origin": `https://${req.headers.host}`, }; delete headers.host; const outgoing = httpRequest( { host: "127.0.0.1", port: target(req), path: req.url, method: req.method, signal: lifetime.signal, headers, }, (incoming) => { res.writeHead(incoming.statusCode, incoming.headers); incoming.pipe(res); }, ); lifetime.own("proxy HTTP request", outgoing, (request) => request.destroy(), ); outgoing.on("error", () => { if (!res.destroyed) { if (!res.headersSent) res.writeHead(502); res.end(); } }); req.pipe(outgoing); }); lifetime.own("HTTPS proxy", proxy, (server) => { server.closeAllConnections(); return new Promise((resolve) => server.close(() => resolve())); }); proxy.on("connection", (socket) => { if (lifetime.signal.aborted) socket.destroy(); else lifetime.own("proxy socket", socket, (socket) => socket.destroy()); }); proxy.on("upgrade", (req, socket, head) => { if (lifetime.signal.aborted) { socket.destroy(); return; } const headers = { ...req.headers, "x-fixture-origin": `https://${req.headers.host}`, }; delete headers.host; const outgoing = httpRequest({ host: "127.0.0.1", port: target(req), path: req.url, method: "GET", signal: lifetime.signal, headers, }); lifetime.own("proxy upgrade request", outgoing, (request) => request.destroy(), ); outgoing.on("upgrade", (incoming, upstream, upgradeHead) => { if (lifetime.signal.aborted) { upstream.destroy(); socket.destroy(); return; } lifetime.own("upgraded socket", upstream, (socket) => socket.destroy(), ); socket.write( `HTTP/1.1 101 Switching Protocols\r\n${incoming.rawHeaders.reduce((s, v, i) => s + (i % 2 ? `${v}\r\n` : `${v}: `), "")}\r\n`, ); if (head.length) upstream.write(head); if (upgradeHead.length) socket.write(upgradeHead); upstream.pipe(socket); socket.pipe(upstream); upstream.on("error", () => socket.destroy()); socket.on("error", () => upstream.destroy()); }); outgoing.on("response", (incoming) => { socket.end( `HTTP/1.1 ${incoming.statusCode} Denied\r\nConnection: close\r\n\r\n`, ); }); outgoing.on("error", () => socket.destroy()); outgoing.end(); }); await new Promise((done) => proxy.listen(0, "127.0.0.1", done)); const tlsPort = proxy.address().port; browser = await lifetime.start( "browser", () => chromium.launch({ headless: true, args: [ "--no-proxy-server", `--host-resolver-rules=MAP dash.cloudflare.com 127.0.0.1:${tlsPort}, MAP publisher.test 127.0.0.1:${tlsPort}, MAP ${new URL(CUSTOMER).hostname} 127.0.0.1:${tlsPort}`, ], }), (browser) => browser.close(), ); const context = await browser.newContext({ ignoreHTTPSErrors: true }); if (cleanupProbe === "bridge") { holdHTTP = true; const pending = callCustomer("/agents/personal-agent/personal"); void pending.catch(() => {}); await responseHeld.promise; await runCleanupTimeout(t, lifetime, pending); return; } context.on("request", (request) => { if (request.isNavigationRequest()) visited.push(request.url()); }); const page = await context.newPage(); page.on("response", (r) => { if (new URL(r.url()).pathname.startsWith("/auth/")) console.log( "Bridge navigation", new URL(r.url()).host, new URL(r.url()).pathname, r.status(), ); }); await page.goto(`${CUSTOMER}/auth/login`); assert.equal(new URL(page.url()).pathname, "/"); assert.equal( oauthVisits, 1, "fresh OAuth continuation completed on a distinct site", ); const cookies = await context.cookies(); const ownerCookie = cookies.find( (c) => c.name === "__Host-flarebot-session", ); assert.ok( ownerCookie?.httpOnly && ownerCookie.secure && ownerCookie.sameSite === "Lax", ); assert.ok( cookies.find((c) => c.name === "__Host-flarebot-control-session") ?.httpOnly, ); assert.ok(!cookies.some((c) => c.name === "__Host-flarebot-login")); assert.ok( !visited.some( (url) => url.includes("assertion") || url.includes("oauth-secret") || url.includes("verifier"), ), ); const callback = visited.find((url) => url.startsWith(`${CUSTOMER}/auth/callback`), ); assert.ok(callback); assert.equal( ( await callCustomer( new URL(callback).pathname + new URL(callback).search, ) ).status, 403, ); assert.equal( await page.evaluate( async () => (await fetch("/agents/personal-agent/personal")).status, ), 200, ); const cpCookie = cookies.find( (c) => c.name === "__Host-flarebot-control-session", ); const inspected = await ( await callCP("/__test__/inspect", { headers: { Cookie: `${cpCookie.name}=${cpCookie.value}` }, }) ).json(); await post(callCP, "/__test__/expire", { kind: "grant", ref: inspected.principal.grantRef, }); await context.clearCookies({ name: "__Host-flarebot-session" }); await page.goto(`${CUSTOMER}/auth/login`); assert.equal(new URL(page.url()).pathname, "/"); assert.equal( oauthVisits, 1, "identity-only login succeeds after deployment grant expires", ); // Native owner socket works; server-only methods remain inaccessible to browser RPC. const rpc = await page.evaluate(async () => { const ws = new WebSocket( `${location.origin.replace("https:", "wss:")}/agents/personal-agent/personal`, ); const replies = {}; return new Promise((resolve, reject) => { const timeout = setTimeout(() => { ws.close(); reject(new Error("Socket timeout")); }, 15000); ws.onopen = () => { for (const [id, method] of [ ["public", "getRuntimeInfo"], ["private", "createLoginChallenge"], ["health", "bootstrapHealth"], ["save", "setProviderKey"], ["enable", "enableOpenRouter"], ["disabled", "updateModelSettings"], ]) ws.send( JSON.stringify({ type: "rpc", id, method, args: id === "save" ? ["anthropic", "sk-ant-fixture-preserved-key-sentinel"] : id === "disabled" ? [ { provider: "openrouter", model: "openai/gpt-5.6-luna", }, ] : [], }), ); }; ws.onmessage = (event) => { const frame = JSON.parse(event.data); if ( [ "public", "private", "health", "save", "enable", "disabled", ].includes(frame.id) ) { replies[frame.id] = frame; if (Object.keys(replies).length === 6) { clearTimeout(timeout); ws.close(); resolve(replies); } } }; ws.onerror = () => reject(new Error("Socket denied")); }); }); assert.ok(rpc.public.success); assert.equal(rpc.private.success, false); assert.equal(rpc.health.success, false); assert.ok(rpc.save.success); assert.equal( rpc.enable.success, false, "browser RPC cannot enable a provider", ); assert.equal( rpc.disabled.success, false, "model selection requires enablement", ); const providerEndpoint = `/api/installations/${I}/providers/openrouter`; assert.equal((await callCP(providerEndpoint)).status, 401); assert.equal( (await callCP(providerEndpoint, { method: "POST" })).status, 403, ); assert.equal( ( await callCP(providerEndpoint, { method: "POST", headers: { Origin: CP, Cookie: `${cpCookie.name}=${cpCookie.value}`, "Content-Type": "application/x-www-form-urlencoded", }, body: "", }) ).status, 401, "expired deployment grants require reconnect", ); const enabled = async () => (await (await callCustomer("/__bridge__/inspect")).json()).models .providers["openrouter"]; assert.equal(await enabled(), false); const receiptTime = Math.floor(Date.now() / 1000); const receipt = { ...claims, purpose: PROVIDER_PURPOSE, state: "openrouter", challenge: "enabled", iat: receiptTime, exp: receiptTime + 60, jti: id(), }; for (const change of [ { sub: "wrong-owner" }, { aud: "https://other.example" }, { purpose: LOGIN_PURPOSE }, { state: "opencode-go" }, { exp: receiptTime - 1 }, ]) { assert.equal( ( await callCustomer("/auth/provider-enabled", { method: "POST", headers: { Authorization: `Bearer ${token({ ...receipt, ...change })}`, }, }) ).status, 403, ); } assert.equal( await enabled(), false, "invalid receipts never enable a provider", ); const setupContext = await browser.newContext({ ignoreHTTPSErrors: true, }); await setupContext.addCookies( (await context.cookies()).filter( (c) => c.name === "__Host-flarebot-session", ), ); const setupPage = await setupContext.newPage(); const setupErrors = []; setupPage.on("pageerror", (error) => setupErrors.push(error.message)); await setupPage.goto(`${CUSTOMER}/settings`); const chooseOpenRouter = async () => { await setupPage .getByRole("combobox", { name: "Provider", exact: true }) .click(); await setupPage .getByRole("option", { name: "OpenRouter", exact: true }) .click(); }; await chooseOpenRouter(); await setupPage .getByRole("link", { name: "Enable OpenRouter", exact: true }) .click(); await setupPage .getByRole("button", { name: "Reconnect Cloudflare" }) .click(); await setupPage .getByRole("button", { name: "Enable OpenRouter", exact: true }) .waitFor() .catch(async (error) => { throw new Error( `${error.message}\nPage errors: ${JSON.stringify(setupErrors)}\nProvider setup: ${await setupPage.locator("body").innerText()}`, ); }); assert.equal( new URL(setupPage.url()).searchParams.get("installationId"), I, ); assert.equal(await enabled(), false, "GET and reconnect do not enable"); let providerCommands = 0; setupPage.on("request", (request) => { if ( request.url() === CP + providerEndpoint && request.method() === "POST" ) providerCommands++; }); await setupPage.route(CP + providerEndpoint, (route) => route.request().method() === "GET" ? route.abort("failed") : route.continue(), ); try { await setupPage.clock.setFixedTime(Date.now() + 31_000); await setupPage.evaluate(() => window.dispatchEvent(new Event("focus")), ); await setupPage .getByRole("alert") .filter({ hasText: "temporarily unavailable" }) .waitFor(); assert.equal( await setupPage .getByRole("button", { name: "Enable OpenRouter", exact: true }) .isVisible(), true, "A failed background read retains the verified installation", ); } finally { await setupPage.unrouteAll({ behavior: "wait" }); } await setupPage .getByRole("button", { name: "Retry", exact: true }) .click(); await setupPage .getByRole("alert") .filter({ hasText: "temporarily unavailable" }) .waitFor({ state: "hidden" }); assert.equal(providerCommands, 0, "Read retries never enable providers"); assert.equal(await enabled(), false); await setupPage.screenshot({ path: "/tmp/flarebot-openrouter-setup.png", fullPage: true, }); await post(callCP, "/__bridge__/provider", { failNotification: true }); await setupPage .getByRole("button", { name: "Enable OpenRouter", exact: true }) .click(); await setupPage .getByRole("alert") .filter({ hasText: "temporarily unavailable" }) .waitFor(); assert.equal( await enabled(), false, "runtime acknowledgment is required", ); await setupPage.screenshot({ path: "/tmp/flarebot-openrouter-setup-error.png", fullPage: true, }); await post(callCP, "/__bridge__/provider", { failNotification: false }); await setupPage .getByRole("button", { name: "Retry", exact: true }) .click(); await setupPage.waitForURL(`${CUSTOMER}/settings`); assert.equal(await enabled(), true); await chooseOpenRouter(); await setupPage .getByText("OpenRouter is enabled for this installation.", { exact: true, }) .waitFor(); assert.equal( await setupPage .getByRole("link", { name: "Enable OpenRouter", exact: true }) .count(), 0, ); assert.equal( await setupPage.getByLabel("API key", { exact: true }).isEnabled(), true, ); await setupPage.setViewportSize({ width: 1280, height: 1600 }); await setupPage .locator("section[aria-labelledby='model-heading']") .screenshot({ path: "/tmp/flarebot-openrouter-enabled.png" }); await setupPage .locator("section[aria-labelledby='domain-heading']") .screenshot({ path: "/tmp/flarebot-domain-settings.png" }); assert.ok( !visited.some( (url) => url.includes("assertion") || url.includes("oauth-secret"), ), ); await setupContext.close(); const cpIdentity = { Cookie: `${cpCookie.name}=${cpCookie.value}` }; // The custom hostname is a separate browser origin, not a cookie alias. { const customOrigin = "https://bot.example.com"; const domain = await ( await post(callCP, "/__bridge__/domain", { owner: OWNER, id: I }) ).json(); const domainToken = (revision, origin, changes = {}) => token({ ...claims, purpose: DOMAIN_CONFIGURATION_PURPOSE, state: String(revision), challenge: origin ?? "", iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 60, jti: id(), ...changes, }); const configure = (signed) => callCustomer("/auth/domain-configuration", { method: "POST", headers: { Authorization: `Bearer ${signed}` }, }); for (const changes of [ { sub: "not-owner" }, { aud: customOrigin }, { purpose: LOGIN_PURPOSE }, ]) assert.equal( ( await configure( domainToken(domain.revision, customOrigin, changes), ) ).status, 403, ); const configured = domainToken(domain.revision, customOrigin); assert.deepEqual(await (await configure(configured)).json(), { revision: domain.revision, origin: customOrigin, }); assert.equal( (await configure(configured)).status, 200, "same signed revision is idempotent", ); assert.equal( ( await configure( domainToken(domain.revision, "https://other.example.com"), ) ).status, 403, ); const customHeaders = { "x-fixture-origin": customOrigin }; const customBegin = await callCustomer("/auth/login", { headers: customHeaders, }); assert.equal(customBegin.status, 303); const customDestination = new URL(customBegin.headers.get("location")); assert.equal( customDestination.searchParams.get("audience"), customOrigin, ); const customCode = await callCP( customDestination.pathname + customDestination.search, { headers: cpIdentity }, ); assert.equal(customCode.status, 303); const customCallback = new URL(customCode.headers.get("location")); assert.equal(customCallback.origin, customOrigin); const loginCookie = cookie(customBegin, "__Host-flarebot-login"); assert.equal( ( await callCustomer( customCallback.pathname + customCallback.search, { headers: { Cookie: loginCookie }, }, ) ).status, 403, "challenge cannot be consumed on workers.dev", ); const customSession = await callCustomer( customCallback.pathname + customCallback.search, { headers: { ...customHeaders, Cookie: loginCookie } }, ); assert.equal(customSession.status, 303); const ownerCookie = cookie(customSession, "__Host-flarebot-session"); assert.ok(ownerCookie); assert.equal( ( await callCustomer("/api/domain", { headers: { ...customHeaders, Cookie: ownerCookie }, }) ).status, 200, ); assert.equal( ( await callCustomer("/api/domain", { headers: { Cookie: ownerCookie }, }) ).status, 401, "sessions cannot cross approved origins", ); assert.equal( ( await callCustomer("/api/domain", { headers: { ...customHeaders, Cookie: ownerCookie, Origin: CUSTOMER, }, }) ).status, 403, ); const forgedDestination = new URL(customDestination); forgedDestination.searchParams.set( "audience", "https://attacker.example", ); assert.equal( ( await callCP( forgedDestination.pathname + forgedDestination.search, { headers: cpIdentity, }, ) ).status, 403, ); const probeClaims = { ...claims, purpose: DOMAIN_HEALTH_PURPOSE, aud: customOrigin, iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 60, jti: id(), }; const health = await callCustomer("/auth/domain-health", { method: "POST", headers: { ...customHeaders, Authorization: `Bearer ${token(probeClaims)}`, }, }); assert.deepEqual(await health.json(), { installationId: I, origin: customOrigin, state: claims.state, challenge: claims.challenge, }); await lifetime.release(customer); customer = await startCustomer(); assert.equal( ( await callCustomer("/api/domain", { headers: { ...customHeaders, Cookie: ownerCookie }, }) ).status, 200, "custom domain survives native restart", ); const removedDomain = await ( await post(callCP, "/__bridge__/domain", { owner: OWNER, id: I, remove: true, }) ).json(); assert.equal( (await configure(domainToken(removedDomain.revision, null))).status, 200, ); assert.equal( (await configure(configured)).status, 403, "stale receipt cannot resurrect removed domain", ); assert.equal( ( await callCustomer("/api/domain", { headers: { ...customHeaders, Cookie: ownerCookie }, }) ).status, 403, ); assert.equal( ( await callCP( customDestination.pathname + customDestination.search, { headers: cpIdentity, }, ) ).status, 403, "removed origin cannot receive login codes", ); } async function pendingLogin() { const begin = await callCustomer("/auth/login"); assert.equal(begin.status, 303); assert.equal(begin.headers.get("referrer-policy"), "no-referrer"); assert.equal(begin.headers.get("cache-control"), "no-store"); const destination = new URL(begin.headers.get("location")); const issued = await callCP(destination.pathname + destination.search, { headers: cpIdentity, }); assert.equal(issued.status, 303); assert.match( issued.headers.get("content-security-policy"), /form-action 'self' https:\/\/dash.cloudflare.com/, ); const callback = new URL(issued.headers.get("location")); const saved = ( await (await callCustomer("/__bridge__/inspect")).json() ).challenges.find( (row) => row.state === callback.searchParams.get("state"), ); return { callback, saved, binding: cookie(begin, "__Host-flarebot-login"), }; } const first = await pendingLogin(); const callbackPath = (item) => item.callback.pathname + item.callback.search; assert.equal( ( await callCustomer(callbackPath(first), { headers: { Cookie: "__Host-flarebot-login=" + id() }, }) ).status, 403, ); assert.equal( ( await callCustomer(callbackPath(first) + "&state=" + id(), { headers: { Cookie: first.binding }, }) ).status, 403, ); const callbackRace = await Promise.all( Array.from({ length: 8 }, () => callCustomer(callbackPath(first), { headers: { Cookie: first.binding }, }), ), ); assert.equal( callbackRace.filter((r) => r.status === 303).length, 1, "one concurrent callback issues a cookie", ); const expired = await pendingLogin(); await post(callCustomer, "/__bridge__/expire", {}); assert.equal( ( await callCustomer(callbackPath(expired), { headers: { Cookie: expired.binding }, }) ).status, 403, ); const lost = await pendingLogin(); await post(callCustomer, "/__bridge__/exchange-mode", { mode: "lost" }); assert.equal( ( await callCustomer(callbackPath(lost), { headers: { Cookie: lost.binding }, }) ).status, 403, ); assert.equal( ( await callCustomer(callbackPath(lost), { headers: { Cookie: lost.binding }, }) ).status, 403, "lost exchange never reopens local challenge", ); const direct = await pendingLogin(); const exchangeBody = { code: direct.callback.searchParams.get("code"), verifier: direct.saved.verifier, installationId: I, audience: CUSTOMER, state: direct.saved.state, }; const exchange = (body) => callCP("/auth/bridge/exchange", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body), }); for (const change of [ { verifier: id() }, { audience: "https://other.example" }, { installationId: "f".repeat(32) }, { state: id() }, ]) assert.equal( (await exchange({ ...exchangeBody, ...change })).status, 403, ); const codeRace = await Promise.all( Array.from({ length: 8 }, () => exchange(exchangeBody)), ); assert.equal( codeRace.filter((r) => r.status === 200).length, 1, "one concurrent PKCE exchange consumes a code", ); assert.equal((await exchange(exchangeBody)).status, 403); const expiredCode = await pendingLogin(); await post(callCP, "/__test__/expire", { kind: "code", ref: createHash("sha256") .update(expiredCode.callback.searchParams.get("code")) .digest("base64url"), }); assert.equal( ( await callCustomer(callbackPath(expiredCode), { headers: { Cookie: expiredCode.binding }, }) ).status, 403, ); const wrong = await browser.newContext({ ignoreHTTPSErrors: true }); mode = "second-owner"; const wrongPage = await wrong.newPage(); await wrongPage.goto(`${CUSTOMER}/auth/login`); await wrongPage.waitForURL(`${CP}/connect?error=forbidden`); assert.ok( !(await wrong.cookies()).some( (c) => c.name === "__Host-flarebot-session", ), ); await wrong.close(); // Parallel native SQLite claims have one winner and survive a Worker restart. const challenge = { state: id(), bindingHash: id(), verifier: id(), challenge: id(), expiresAt: Date.now() + 600_000, }; assert.equal( (await post(callCustomer, "/__bridge__/create", challenge)).status, 200, ); const claimed = await Promise.all( Array.from({ length: 8 }, () => post(callCustomer, "/__bridge__/claim", challenge).then((r) => r.json(), ), ), ); assert.equal(claimed.filter(Boolean).length, 1); await lifetime.release(customer); customer = await startCustomer(); assert.equal( await enabled(), true, "provider enablement survives native restart", ); assert.equal( await (await post(callCustomer, "/__bridge__/claim", challenge)).json(), null, ); assert.equal( await (await callCustomer("/__bridge__/key-survived")).json(), true, "encrypted provider key survives unchanged session secret and native restart", ); await post(callCustomer, "/__bridge__/expire", {}); for (let i = 0; i < 128; i++) assert.equal( ( await post(callCustomer, "/__bridge__/create", { ...challenge, state: id(), }) ).status, 200, ); assert.equal( ( await post(callCustomer, "/__bridge__/create", { ...challenge, state: id(), }) ).status, 429, ); await post(callCustomer, "/__bridge__/expire", {}); assert.equal( ( await post(callCustomer, "/__bridge__/create", { ...challenge, state: id(), }) ).status, 200, ); assert.equal( (await (await callCustomer("/__bridge__/inspect")).json()).challenges .length, 1, ); // Encrypted bootstrap create/replay preserves the original secret across restart. const operation = { subject: OWNER, accountId: "a".repeat(32), installationId: I, operationId: "9".repeat(32), grantRef: id(), expiresAt: Date.now() + 120000, bootstrapSecret: id(), }; const expected = Object.fromEntries( ["subject", "accountId", "installationId", "operationId"].map((k) => [ k, operation[k], ]), ); await post(callCP, "/__bridge__/operation", { action: "grant", value: operation, grantExpiresAt: operation.expiresAt + 1000, }); assert.deepEqual( await ( await post(callCP, "/__bridge__/operation", { action: "create", value: operation, }) ).json(), operation, ); await lifetime.release(cp); cp = await startCP(); assert.deepEqual( await ( await post(callCP, "/__bridge__/operation", { action: "create", value: { ...operation, bootstrapSecret: id() }, }) ).json(), operation, ); assert.equal( (await exchange(exchangeBody)).status, 403, "consumed code survives native CP restart", ); assert.equal( ( await post(callCP, "/__bridge__/operation", { action: "create", value: { ...operation, accountId: "b".repeat(32) }, }) ).status, 409, ); assert.equal( await ( await post(callCP, "/__bridge__/operation", { action: "get", expected: { ...expected, subject: "other" }, }) ).json(), null, ); assert.equal( await ( await post(callCP, "/__bridge__/operation", { action: "retire", expected, }) ).json(), true, ); assert.equal( ( await ( await post(callCP, "/__bridge__/operation", { action: "get", expected, }) ).json() ).bootstrapSecret, null, ); // Signed metadata-only health exercises actual native Sandbox launch and destroy. const healthClaims = { aud: CUSTOMER, sub: OWNER, installationId: I, purpose: HEALTH_PURPOSE, state: id(), challenge: id(), ...release, }; const signHealth = async () => ( await ( await post(callCP, "/__bridge__/sign", { ...healthClaims, state: id(), challenge: id(), }) ).json() ).assertion; const assertion = await signHealth(); const health = await callCustomer("/auth/bootstrap-health", { method: "POST", headers: { Authorization: `Bearer ${assertion}` }, }); assert.equal(health.status, 200, await health.clone().text()); assert.equal( (await post(callCP, "/__bridge__/health", record)).status, 200, "production CP helper verifies native runtime health", ); assert.equal( ( await post(callCP, "/__bridge__/health", { ...record, operationId: "f".repeat(32), }) ).status, 403, ); const ready = await health.json(); assert.equal(ready.sandbox, "booted-and-destroyed"); assert.equal(ready.nativeParent, "ready"); assert.ok(!JSON.stringify(ready).includes("stdout")); assert.equal( ( await callCustomer("/auth/bootstrap-health", { method: "POST", headers: { Authorization: `Bearer ${assertion}` }, }) ).status, 403, ); const state = await (await callCustomer("/__bridge__/inspect")).json(); assert.equal(state.probes.length, 1); assert.equal(state.probes[0].status, "complete"); assert.equal(state.conversations.length, 0); await lifetime.release(customer); customer = await startCustomer(); assert.equal( ( await callCustomer("/auth/bootstrap-health", { method: "POST", headers: { Authorization: `Bearer ${assertion}` }, }) ).status, 403, ); assert.equal( ( await callCustomer("/auth/bootstrap-health", { method: "POST", headers: { Authorization: `Bearer ${await signHealth()}` }, }) ).status, 200, ); assert.equal( (await (await callCustomer("/__bridge__/inspect")).json()).probes .length, 1, "lost health reply reconciles completed probe", ); assert.equal( (await callCustomer("/agents/personal-agent/personal")).status, 401, ); lifetime.complete(); } finally { await lifetime.cleanup(); } }, ); registerCleanupProbe(import.meta.url, "bridge");