Something went wrong. Try again.
This repository has no description
Something went wrong. Try again.
JavaScript
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278import assert from "node:assert/strict";import { test } from "node:test";import { mkdtemp, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { build } from "esbuild";import { Miniflare, convertV4MiniflareOptions } from "miniflare";
test( "native MCP secret headers stay private, scoped and restartable", { timeout: 60000 }, async () => { const bundle = await build({ entryPoints: ["tests/fixtures/mcp-runtime-worker.ts"], alias: { path: "node:path" }, bundle: true, write: false, format: "esm", platform: "neutral", conditions: ["workerd", "worker", "browser"], mainFields: ["module", "main"], external: ["cloudflare:*", "node:*"], }); const persistence = await mkdtemp(join(tmpdir(), "flarebot-mcp-headers-")); const token = "Bearer private-header-token-12345", apiKey = "private-api-key-67890"; let calls = 0, foreignCalls = 0, redirect = false, reject = false, protocolError = false; const options = { ...convertV4MiniflareOptions({ modules: true, script: bundle.outputFiles[0].text, compatibilityDate: "2026-09-04", compatibilityFlags: ["nodejs_compat"], durableObjects: { MODEL: { className: "McpRuntimeFixture", useSQLite: true }, }, async outboundService(request) { if (new URL(request.url).hostname !== "headers.example.com") { foreignCalls++; return new Response(null, { status: 500 }); } calls++; assert.equal(request.headers.get("Authorization"), token); assert.equal(request.headers.get("X-Api-Key"), apiKey); if (redirect) return new Response(null, { status: 307, headers: { Location: "https://other.example.com/stolen" }, }); if (reject) return new Response(`Invalid credential ${apiKey}`, { status: 403, }); if (request.method !== "POST") return new Response(null, { status: 405 }); const body = await request.json(); if (!("id" in body)) return new Response(null, { status: 202 }); if (protocolError && body.method === "tools/list") return Response.json({ jsonrpc: "2.0", id: body.id, error: { code: -32000, message: `API key ${apiKey} rejected`, data: { credential: token }, }, }); const result = { initialize: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "Headers fixture", version: "1" }, }, "tools/list": { tools: [{ name: "lookup", inputSchema: { type: "object" } }], }, }[body.method]; return Response.json({ jsonrpc: "2.0", id: body.id, ...(result ? { result } : { error: { code: -32601, message: "Method not found" } }), }); }, }), resourcePersistencePath: persistence, }; let worker = new Miniflare(options); const request = async (action, args = {}) => ( await worker.dispatchFetch("https://fixture.example", { method: "POST", body: JSON.stringify({ action, ...args }), }) ).json(); const call = async (action, args = {}) => { const result = await request(action, args); assert.equal(result.ok, true, JSON.stringify(result)); return result.value; }; const settled = async (id) => { for (let i = 0; i < 100; i++) { const item = (await call("list")).connections.find( (row) => row.id === id, ); if (item?.state !== "connecting") return item; await new Promise((resolve) => setTimeout(resolve, 30)); } assert.fail("Header connection did not settle"); }; const privateStorage = async () => (await worker.dispatchFetch("https://fixture.example/__storage")).json(); const values = [ { name: "Authorization", value: token }, { name: "X-Api-Key", value: apiKey }, ]; try { let item = await call("add", { value: { name: "Headers", endpoint: "https://headers.example.com/mcp", authMode: "headers", }, }); item = await settled(item.id); assert.equal(item.state, "authenticating"); assert.equal( calls, 0, "no credential-free probe for a secret connection", ); for (const invalid of [ [{ name: "Authorization", value: "" }], [{ name: "Host", value: "other.example.com" }], [{ name: "x-api-key", value: "private\r\nInjected: true" }], [ { name: "Authorization", value: "one" }, { name: "authorization", value: "two" }, ], ]) assert.deepEqual( await request("headers", { ...item, value: invalid }), { ok: false, error: "mcp_headers_invalid" }, ); item = await call("headers", { ...item, value: values }); assert.equal(item.state, "connecting"); item = await settled(item.id); assert.equal(item.state, "ready", JSON.stringify(item)); assert.deepEqual(item.headerNames, ["authorization", "x-api-key"]); assert.equal(item.capabilities[0].name, "lookup"); assert.ok(calls > 0); const catalog = await ( await worker.dispatchFetch("https://fixture.example/__catalog") ).json(); assert.deepEqual( catalog.native, [], "secret connection uses no persistent native registration", ); const publicText = JSON.stringify({ item, catalog }); for (const secret of [token, apiKey]) assert.ok(!publicText.includes(secret)); const storage = await privateStorage(); const encrypted = Object.entries(storage).filter(([key]) => key.startsWith("flarebot/mcp-headers/v1/"), ); assert.equal(encrypted.length, 1); for (const secret of [token, apiKey]) assert.ok(!JSON.stringify(storage).includes(secret)); assert.equal(JSON.parse(encrypted[0][1]).version, 1); await worker.dispose(); worker = new Miniflare(options); item = await settled(item.id); assert.equal( item.state, "ready", "native connection rehydrates from encrypted references", ); item = await call("enable", { ...item, value: false }); await new Promise((resolve) => setTimeout(resolve, 50)); const afterDisable = calls; await worker.dispose(); worker = new Miniflare(options); item = await settled(item.id); assert.equal(item.state, "disabled"); assert.equal( calls, afterDisable, "disabled secrets are not resolved or transmitted on wake", ); item = await call("enable", { ...item, value: true }); item = await settled(item.id); assert.equal(item.state, "ready"); reject = true; item = await call("connect", item); item = await settled(item.id); assert.equal(item.state, "error"); assert.equal(item.lastError, "authentication_failed"); assert.ok(!JSON.stringify(item).includes(apiKey)); reject = false; protocolError = true; item = await call("connect", item); item = await settled(item.id); assert.equal(item.state, "error"); const events = await ( await worker.dispatchFetch("https://fixture.example/__events") ).json(); assert.ok( events.some( (event) => event.type === "mcp:client:discover" && event.payload.error === "MCP discovery failed", ), ); for (const secret of [token, apiKey]) assert.ok( !JSON.stringify(events).includes(secret), "credential must not reach native diagnostics", ); protocolError = false; redirect = true; item = await call("connect", item); item = await settled(item.id); assert.equal(item.state, "error"); assert.equal( foreignCalls, 0, "custom headers never follow cross-origin redirects", ); redirect = false; const previousRevision = item.revision; item = await call("headers", { ...item, value: [] }); item = await settled(item.id); assert.equal(item.state, "authenticating"); assert.deepEqual(item.headerNames, []); assert.deepEqual( await request("headers", { id: item.id, revision: previousRevision, value: values, }), { ok: false, error: "mcp_conflict" }, ); for (let i = 0; i < 100; i++) { if ( !Object.keys(await privateStorage()).some((key) => key.startsWith("flarebot/mcp-headers/v1/"), ) ) break; if (i === 99) assert.fail("Removal or rejected update retained credentials"); await new Promise((resolve) => setTimeout(resolve, 20)); } item = await call("headers", { ...item, value: values }); item = await settled(item.id); await call("remove", item); await worker.dispose(); worker = new Miniflare(options); assert.deepEqual((await call("list")).connections, []); assert.ok( !Object.keys(await privateStorage()).some((key) => key.startsWith("flarebot/mcp-headers/v1/"), ), "startup prunes removed credential references", ); } finally { await worker.dispose(); await rm(persistence, { recursive: true, force: true }); } },);