Something went wrong. Try again.
This repository has no description
Something went wrong. Try again.
JavaScript
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162import 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 { verifyAssertion, LOGIN_PURPOSE, HEALTH_PURPOSE, PROVIDER_PURPOSE,} from "../shared/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 verifyAssertion(token(value), bridgeKey, claims), value, ); for (const field of [ "iss", "aud", "sub", "installationId", "purpose", "state", "challenge", ]) { await assert.rejects( verifyAssertion(token({ ...value, [field]: "wrong" }), bridgeKey, claims), ); } for (const change of [ { iat: now + 1 }, { exp: now }, { exp: now + 61 }, { jti: "short" }, { extra: "hidden" }, { iat: 1.1 }, { purpose: HEALTH_PURPOSE }, ]) await assert.rejects( 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( verifyAssertion(token(value, header), bridgeKey, claims), ); await assert.rejects( 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() { const server = netServer(); 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 () => { const temporary = await mkdtemp(join(tmpdir(), "flarebot-bridge-")); const cpPort = await freePort(), customerPort = await freePort(); 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 = () => unstable_dev( "tests/fixtures/bridge-control-worker.ts", options(cpPath, cpPort, cpBindings), ); const startCustomer = () => unstable_dev( "tests/fixtures/bridge-customer-worker.ts", options( customerPath, customerPort, { ...customerBindings, FLAREBOT_INSTALLATION: JSON.stringify(installation), TEST_CP_PORT: String(cpPort), }, true, ), ); let cp, customer, browser, proxy; let mode = "normal", oauthVisits = 0; const visited = []; const nativeCall = (port, path, init = {}) => new Promise((resolve, reject) => { const body = init.body === undefined ? undefined : String(init.body); const req = httpRequest( { hostname: "127.0.0.1", port, path, method: init.method ?? "GET", headers: { "Sec-Fetch-Mode": "navigate", ...init.headers }, }, (incoming) => { 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, }), ); }); }, ); req.on("error", 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; proxy = httpsServer( { key: await readFile(join(temporary, "key.pem")), cert: await readFile(join(temporary, "cert.pem")), }, async (req, res) => { 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, headers, }, (incoming) => { res.writeHead(incoming.statusCode, incoming.headers); incoming.pipe(res); }, ); outgoing.on("error", () => { res.writeHead(502); res.end(); }); req.pipe(outgoing); }, ); proxy.on("upgrade", (req, socket, head) => { 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", headers, }); outgoing.on("upgrade", (incoming, upstream, upgradeHead) => { 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 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}`, ], }); const context = await browser.newContext({ ignoreHTTPSErrors: true }); 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(); 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(); assert.equal( new URL(setupPage.url()).searchParams.get("installationId"), I, ); assert.equal(await enabled(), false, "GET and reconnect do not enable"); 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" }); assert.ok( !visited.some( (url) => url.includes("assertion") || url.includes("oauth-secret"), ), ); await setupContext.close(); const cpIdentity = { Cookie: `${cpCookie.name}=${cpCookie.value}` }; 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 customer.stop(); 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 cp.stop(); 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 customer.stop(); 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, ); } finally { await browser?.close(); proxy?.closeAllConnections(); await new Promise((done) => (proxy ? proxy.close(done) : done())); await customer?.stop(); await cp?.stop(); await rm(temporary, { recursive: true, force: true }); } },);