Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Credential broker: a saved key Node cannot send fails its request, not the server
milind-soni88a28594564a
diff --git a/server/bot-box/broker-env.ts b/server/bot-box/broker-env.tsindex ea68d29a9c..7dafedbc20 100644--- a/server/bot-box/broker-env.ts+++ b/server/bot-box/broker-env.ts@@ -66,7 +66,8 @@ export function brokerRewrite(env: Record<string, string>, token: string, port:// later one adds its header there (an endpoint may answer only one of them) and is replaced too, never left raw.const routed: Record<string, string> = {};for (const provider of BROKERED_PROVIDERS) {- const key = out[provider.keyEnv];+ // Trimmed: a pasted key's trailing newline cannot go in a header (the broker would refuse it), and is no part of the key.+ const key = out[provider.keyEnv]?.trim();if (!key || isToken(key)) continue;const shared = routed[provider.baseUrlEnv];if (shared) {diff --git a/server/bot-box/broker-headers.test.ts b/server/bot-box/broker-headers.test.tsnew file mode 100644index 0000000000..e2f7575542--- /dev/null+++ b/server/bot-box/broker-headers.test.ts@@ -0,0 +1,168 @@+import { spawn, type ChildProcess } from "node:child_process";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { createServer, request, type Server } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it } from "vitest";++import { parseConfigPatch } from "../config.ts";+import { parseMcpServerMutation, parseStoredMcpServer } from "../mcp-registry.ts";+import { startFakeHttpMcp, type FakeHttpMcp } from "../testing/fake-http-mcp-server.ts";+import { openCredentialBroker, type CredentialBroker } from "./broker.ts";+import { brokerRewrite } from "./broker-env.ts";+import { guardedHandler, trimmedHeaderValues, unsendableHeader, UNUSABLE_CREDENTIAL } from "./broker-headers.ts";++const KEY = "sk-real-key-0123456789abcdef";+/** As an earlier version saved them: a paste's trailing newline, a control character, a curly quote (beyond Latin-1). */+const NEWLINE = `Bearer ${KEY}\n`, CONTROL = `Bearer ${KEY}\u0001`, CURLY = `Bearer “${KEY}”`;++function call(socketPath: string, path: string, init: { method?: string; headers?: Record<string, string>; body?: string; port?: number } = {}) {+ return new Promise<{ status: number; body: string }>((resolve, reject) => {+ const req = request({ ...(init.port ? { host: "127.0.0.1", port: init.port } : { socketPath }), path, method: init.method ?? "GET", headers: init.headers ?? {} }, (res) => {+ let text = "";+ res.on("data", (chunk) => { text += chunk; });+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body: text }));+ });+ req.on("error", reject);+ req.end(init.body);+ });+}++describe("header values the box's gates send", () => {+ it("trims a key's surrounding whitespace and names the header Node would refuse, never its value", () => {+ expect(trimmedHeaderValues({ authorization: NEWLINE, "x-api-key": " k " })).toEqual({ authorization: `Bearer ${KEY}`, "x-api-key": "k" });+ expect(unsendableHeader({ authorization: `Bearer ${KEY}` })).toBeNull();+ expect(unsendableHeader({ "x-ok": "café", authorization: CONTROL })).toBe("authorization");+ expect(unsendableHeader({ authorization: CURLY })).toBe("authorization");+ expect(unsendableHeader({ "bad name": "x" })).toBe("bad name");+ });++ it("a provider key saved with a trailing newline becomes a clean header", () => {+ const rewrite = brokerRewrite({ OPENAI_API_KEY: `${KEY}\n` }, "omb_t0_token", 18080);+ expect(rewrite.grants.openai!.headers.authorization).toBe(`Bearer ${KEY}`);+ });++ it("a saved key is trimmed on save; an MCP header that still cannot be sent is refused on save and read as it is", () => {+ expect(parseConfigPatch({ openai: { key: `${KEY}\n` }, tts: { key: ` ${KEY}` } })).toMatchObject({ openai: { key: KEY }, tts: { key: KEY } });+ const remote = (authorization: string) => ({ type: "http", url: "https://mcp.example.com/mcp", headers: { authorization } });+ expect(parseMcpServerMutation("docs", remote(NEWLINE))).toMatchObject({ ok: true, server: { headers: { authorization: `Bearer ${KEY}` } } });+ const refused = parseMcpServerMutation("docs", remote(CURLY));+ expect(refused).toMatchObject({ ok: false, error: expect.stringContaining("not allowed") });+ expect(JSON.stringify(refused)).not.toContain(KEY);+ expect(parseStoredMcpServer("docs", { ...remote(NEWLINE), enabled: true })).toMatchObject({ ok: true, server: { headers: { authorization: `Bearer ${KEY}` } } });+ expect(parseStoredMcpServer("docs", { ...remote(CURLY), enabled: true })).toMatchObject({ ok: true });+ });++ it("a handler that throws fails that request (502) and the server keeps answering", async () => {+ const lines: string[] = [];+ const server = createServer(guardedHandler("test gate", (req, res) => {+ if (req.url === "/throw") throw Object.assign(new TypeError(`Invalid character in header content ["authorization"] ${KEY}`), { code: "ERR_INVALID_CHAR" });+ if (req.url === "/reject") return Promise.reject(new Error("later"));+ res.writeHead(200).end("ok");+ }, (line) => lines.push(line)));+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const port = (server.address() as { port: number }).port;+ try {+ expect(await call("", "/throw", { port })).toMatchObject({ status: 502 });+ expect(await call("", "/reject", { port })).toMatchObject({ status: 502 });+ expect(await call("", "/", { port })).toEqual({ status: 200, body: "ok" });+ expect(lines.join("\n")).toContain("ERR_INVALID_CHAR");+ expect(lines.join("\n"), "the log never quotes the message, which may hold the value").not.toContain(KEY);+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });+});++// The broker listens on a unix socket, which Windows refuses at a file path; the box runs only on a Linux Cloud home.+describe.skipIf(process.platform === "win32")("the credential broker with a saved key it cannot send", () => {+ let upstream: Server | undefined, broker: CredentialBroker | undefined, dir = "", child: ChildProcess | undefined, mcp: FakeHttpMcp | undefined;+ const seen: string[] = [];+ afterEach(async () => {+ child?.kill("SIGKILL");+ child = undefined;+ await broker?.close();+ await mcp?.close();+ if (upstream) await new Promise<void>((resolve) => upstream!.close(() => resolve()));+ broker = undefined; upstream = undefined; mcp = undefined;+ if (dir) rmSync(dir, { recursive: true, force: true });+ seen.length = 0;+ });++ async function start(): Promise<number> {+ // A real upstream and node's own request function: the throw happens where node builds the request.+ upstream = createServer((req, res) => {+ seen.push(String(req.headers.authorization));+ res.writeHead(req.headers.authorization === `Bearer ${KEY}` ? 200 : 401, { "content-type": "application/json" }).end("{}");+ });+ await new Promise<void>((resolve) => upstream!.listen(0, "127.0.0.1", resolve));+ dir = mkdtempSync(join(tmpdir(), "omb-broker-headers-"));+ broker = await openCredentialBroker({ socketPath: join(dir, "b.sock") });+ return (upstream.address() as { port: number }).port;+ }++ it("sends a key saved with a trailing newline, trimmed", async () => {+ const port = await start();+ const { token } = broker!.mintForProcess({ grants: { openai: { upstream: `http://127.0.0.1:${port}/v1`, headers: { authorization: NEWLINE } } } });+ expect(await call(broker!.socketPath, `/b/${token}/openai/models`)).toMatchObject({ status: 200 });+ expect(seen).toEqual([`Bearer ${KEY}`]);+ });++ for (const [what, value] of [["a control character", CONTROL], ["a character beyond Latin-1", CURLY]] as const) {+ it(`fails only the request carrying a key with ${what}, ten times over, and keeps forwarding the others`, async () => {+ const port = await start();+ const { token } = broker!.mintForProcess({ grants: {+ openai: { upstream: `http://127.0.0.1:${port}/v1`, headers: { authorization: value } },+ anthropic: { upstream: `http://127.0.0.1:${port}/v1`, headers: { authorization: `Bearer ${KEY}` } },+ } });+ for (let attempt = 0; attempt < 10; attempt += 1) {+ const answer = await call(broker!.socketPath, `/b/${token}/openai/models`, { method: "POST", body: "{}" });+ expect(answer.status).toBe(502);+ expect(JSON.parse(answer.body)).toMatchObject({ error: UNUSABLE_CREDENTIAL, credential: "openai", header: "authorization" });+ expect(answer.body, "the answer never carries the value").not.toContain(KEY);+ }+ expect(seen, "nothing went upstream for the bad key").toEqual([]);+ expect(await call(broker!.socketPath, `/b/${token}/anthropic/models`)).toMatchObject({ status: 200 });+ expect(broker!.stats()).toMatchObject({ forwarded: 1, refused: 10 });+ });+ }++ it("names the MCP server whose saved header cannot be sent", async () => {+ const port = await start();+ const { token } = broker!.mintForThread({ threadId: "t1", grants: { "mcp-docs": { upstream: `http://127.0.0.1:${port}/mcp`, headers: { authorization: CURLY }, mcpServer: "docs" } } });+ const answer = await call(broker!.socketPath, `/b/${token}/mcp-docs`, { method: "POST", body: "{}" });+ expect(answer.status).toBe(502);+ expect(JSON.parse(answer.body)).toMatchObject({ error: UNUSABLE_CREDENTIAL, credential: "the MCP server docs", header: "authorization" });+ });++ it("a home started with bad keys already saved on disk checks its servers at start without crashing, and keeps answering", async () => {+ mcp = await startFakeHttpMcp({ requireHeaders: { authorization: `Bearer ${KEY}` } });+ dir = mkdtempSync(join(tmpdir(), "omb-saved-keys-"));+ // config.json exactly as an earlier version left it: the values were never trimmed or checked beyond CR/LF.+ const server = (authorization: string) => ({ type: "http", url: mcp!.url, headers: { authorization }, enabled: true });+ writeFileSync(join(dir, "config.json"), JSON.stringify({ mcpServers: { pasted: server(NEWLINE), control: server(CONTROL), curly: server(CURLY) } }));+ const host = fileURLToPath(new URL("../testing/saved-key-broker-host.ts", import.meta.url));+ const proc = spawn(process.execPath, ["--experimental-strip-types", host, dir], { env: { ...process.env, OMB_DATA_DIR: dir }, stdio: ["ignore", "pipe", "pipe"] });+ child = proc;+ let stderr = "";+ proc.stderr!.on("data", (chunk) => { stderr += chunk; });+ const exited = new Promise<number | null>((resolve) => proc.once("exit", (code) => resolve(code)));+ const ready = await Promise.race([+ new Promise<{ port: number; answers: Record<string, boolean> }>((resolve) => {+ let out = "";+ proc.stdout!.on("data", (chunk) => { out += chunk; const line = out.split("\n").find((entry) => entry.startsWith("{")); if (line) resolve(JSON.parse(line)); });+ }),+ exited.then((code) => { throw new Error(`the home exited (${code}) at start:\n${stderr.slice(-2000)}`); }),+ ]);+ expect(ready.answers).toEqual({ pasted: true, control: false, curly: false });+ for (let attempt = 0; attempt < 10; attempt += 1) {+ const again = await call("", "/check", { port: ready.port, method: "POST" });+ expect(JSON.parse(again.body)).toEqual({ pasted: true, control: false, curly: false });+ expect(await call("", "/health", { port: ready.port })).toEqual({ status: 200, body: "ok" });+ }+ expect(proc.exitCode, "the home is still running").toBeNull();+ expect(stderr).not.toContain("ERR_INVALID_CHAR");+ expect(stderr).not.toContain(KEY);+ }, 60_000);+});diff --git a/server/bot-box/broker-headers.ts b/server/bot-box/broker-headers.tsnew file mode 100644index 0000000000..48d8d9081e--- /dev/null+++ b/server/bot-box/broker-headers.ts@@ -0,0 +1,63 @@+// Saved values the box's gates put in request headers, and what a gate does when one cannot be sent. Node refuses a+// header holding a control character (a pasted key's newline) or a character beyond Latin-1 (a smart quote) by throwing+// where the request is built, inside the gate's request handler: unguarded, that one saved key took the whole server+// down at every start. Here a key's surrounding whitespace is dropped so it simply works, what still cannot be sent+// fails only the request that carries it with words naming the credential (never its value), and anything else a+// gate's handler throws fails that request, not the process.+import { validateHeaderName, validateHeaderValue, type IncomingMessage, type ServerResponse } from "node:http";++/** A credential header's value as a gate sends it: the whitespace a paste leaves around a key (a trailing newline) dropped. */+export function trimmedHeaderValues(headers: Record<string, string>): Record<string, string> {+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, typeof value === "string" ? value.trim() : value]));+}++/** The name of the first header Node would refuse to send, or null when every one can go. Never its value. */+export function unsendableHeader(headers: Record<string, string | string[]>): string | null {+ for (const [name, value] of Object.entries(headers)) {+ try {+ validateHeaderName(name);+ for (const one of Array.isArray(value) ? value : [value]) validateHeaderValue(name, one);+ } catch {+ return name;+ }+ }+ return null;+}++export const UNUSABLE_CREDENTIAL = "unusable_credential";++/** What a gate answers for a saved credential it cannot send: which one (the grant and the header), never the value. */+export function unusableCredentialBody(credential: string, header: string): string {+ return JSON.stringify({+ error: UNUSABLE_CREDENTIAL,+ credential,+ header,+ message: `The saved key for ${credential} cannot be used: it contains characters that are not allowed. Save it again.`,+ });+}++/** A gate's request handler whose throw (or rejection) fails that request with a 502, never the process. */+export function guardedHandler(+ name: string,+ handler: (req: IncomingMessage, res: ServerResponse) => unknown,+ log: (line: string) => void = (line) => console.warn(line),+): (req: IncomingMessage, res: ServerResponse) => void {+ const fail = (req: IncomingMessage, res: ServerResponse, error: unknown) => {+ // The code only (ERR_INVALID_CHAR, ...): a message may quote the header value it refused.+ const code = (error as { code?: unknown } | null)?.code;+ log(`${name}: a request failed${typeof code === "string" ? ` [${code}]` : ""}; the gate keeps serving`);+ try {+ if (!res.headersSent) res.writeHead(502, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify({ error: "gate_error" }));+ else res.destroy();+ } catch { res.destroy(); }+ req.resume();+ };+ return (req, res) => {+ try {+ const result = handler(req, res);+ if (result instanceof Promise) result.catch((error: unknown) => fail(req, res, error));+ } catch (error) {+ fail(req, res, error);+ }+ };+}diff --git a/server/bot-box/broker.ts b/server/bot-box/broker.tsindex 33427166c3..4de9b2492f 100644--- a/server/bot-box/broker.ts+++ b/server/bot-box/broker.ts@@ -8,6 +8,7 @@ import { createServer, request as httpRequest, type IncomingMessage, type Serverimport { request as httpsRequest } from "node:https";import type { Socket } from "node:net";+import { guardedHandler, trimmedHeaderValues, unsendableHeader, unusableCredentialBody } from "./broker-headers.ts";import { MAX_REFUSABLE_CALL_BYTES, refusedCallAnswer } from "./broker-mcp-refusal.ts";import type { McpServerApp } from "../mcp-server-app.ts";@@ -137,7 +138,7 @@ export function openCredentialBroker(options: CredentialBrokerOptions): Promise<for (const name of Object.keys(input.grants)) if (!GRANT.test(name)) throw new Error(`Not a grant name: ${name.slice(0, 40)}`);const token = `${BROKER_TOKEN_PREFIX}${randomBytes(24).toString("hex")}`;const expiresAt = now() + (input.ttlMs ?? (bound === "process" ? BROKER_PROCESS_TTL_MS : BROKER_THREAD_TTL_MS));- const grants = Object.fromEntries(Object.entries(input.grants).map(([name, grant]) => [name, { upstream: grant.upstream, headers: { ...grant.headers }, ...(grant.mcpServer ? { mcpServer: grant.mcpServer } : {}), ...(grant.mcpApp ? { mcpApp: { ...grant.mcpApp } } : {}), ...(grant.serve ? { serve: grant.serve } : {}) }]));+ const grants = Object.fromEntries(Object.entries(input.grants).map(([name, grant]) => [name, { upstream: grant.upstream, headers: trimmedHeaderValues(grant.headers), ...(grant.mcpServer ? { mcpServer: grant.mcpServer } : {}), ...(grant.mcpApp ? { mcpApp: { ...grant.mcpApp } } : {}), ...(grant.serve ? { serve: grant.serve } : {}) }]));tokens.set(hashToken(token).toString("hex"), { hash: hashToken(token), botId: input.botId ?? null, threadId: input.threadId ?? null, expiresAt, grants, bound });return { token, botId: input.botId ?? null, threadId: input.threadId ?? null, expiresAt, grants };};@@ -153,7 +154,7 @@ export function openCredentialBroker(options: CredentialBrokerOptions): Promise<};const requestFn = options.request;- const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => {+ const server: Server = createServer(guardedHandler("credential broker", (req: IncomingMessage, res: ServerResponse) => {const refuse = (status: number, error: string) => { res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify({ error })); req.resume(); };const inPath = /^\/b\/([^/]+)\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(req.url ?? "");const inHeader = inPath ? null : /^\/g\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(req.url ?? "");@@ -169,34 +170,48 @@ export function openCredentialBroker(options: CredentialBrokerOptions): Promise<}const upstream = upstreamUrl(verdict.grant.upstream, path, query);if (!upstream) return refuse(502, "bad_upstream");+ // A saved key Node cannot put in a header (a control character, a character beyond Latin-1) fails this request+ // with words naming it, never the process: the request would throw where it is built.+ const unsendable = unsendableHeader(verdict.grant.headers);+ const unusable = (header: string) => {+ stats.refused += 1;+ res.writeHead(502, { "content-type": "application/json", "cache-control": "no-store" }).end(unusableCredentialBody(verdict.grant.mcpServer ? `the MCP server ${verdict.grant.mcpServer}` : grant, header));+ req.resume();+ };+ if (unsendable) return unusable(unsendable);const headers = forwardableHeaders(req.headers);for (const [name, value] of Object.entries(verdict.grant.headers)) headers[name.toLowerCase()] = value;headers.host = upstream.host;const send = requestFn ?? (upstream.protocol === "https:" ? httpsRequest : httpRequest);const relay = (answer: IncomingMessage) => {- res.writeHead(answer.statusCode ?? 502, relayableHeaders(answer.headers));+ try { res.writeHead(answer.statusCode ?? 502, relayableHeaders(answer.headers)); } catch { answer.resume(); res.destroy(); return; }answer.pipe(res);};const mcpServer = req.method === "POST" ? verdict.grant.mcpServer : undefined;const sent: Buffer[] = [];let sentBytes = 0;if (mcpServer) req.on("data", (chunk: Buffer) => { sentBytes += chunk.length; if (sentBytes <= MAX_REFUSABLE_CALL_BYTES) sent.push(chunk); });- const forwarded = send({ protocol: upstream.protocol, host: upstream.hostname, port: upstream.port || (upstream.protocol === "https:" ? 443 : 80), method: req.method, path: `${upstream.pathname}${upstream.search}`, headers }, (answer) => {- if (!mcpServer || answer.statusCode !== 401) return relay(answer);- const decide = () => {- const sentCredentials = Object.values(verdict.grant.headers).some((value) => value !== "");- const refusal = sentBytes <= MAX_REFUSABLE_CALL_BYTES ? refusedCallAnswer(mcpServer, sentCredentials, Buffer.concat(sent).toString("utf8"), verdict.grant.mcpApp) : null;- if (refusal === null) return relay(answer);- answer.resume();- res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(refusal);- };- if (req.readableEnded) decide(); else req.once("end", decide);- });+ let forwarded: ReturnType<typeof httpRequest>;+ try {+ forwarded = send({ protocol: upstream.protocol, host: upstream.hostname, port: upstream.port || (upstream.protocol === "https:" ? 443 : 80), method: req.method, path: `${upstream.pathname}${upstream.search}`, headers }, (answer) => {+ if (!mcpServer || answer.statusCode !== 401) return relay(answer);+ const decide = () => {+ const sentCredentials = Object.values(verdict.grant.headers).some((value) => value !== "");+ const refusal = sentBytes <= MAX_REFUSABLE_CALL_BYTES ? refusedCallAnswer(mcpServer, sentCredentials, Buffer.concat(sent).toString("utf8"), verdict.grant.mcpApp) : null;+ if (refusal === null) return relay(answer);+ answer.resume();+ res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(refusal);+ };+ if (req.readableEnded) decide(); else req.once("end", decide);+ });+ } catch {+ return unusable(unsendableHeader(headers) ?? "a header");+ }stats.forwarded += 1;forwarded.on("error", () => { if (!res.headersSent) res.writeHead(502, { "content-type": "application/json" }).end(JSON.stringify({ error: "upstream_unreachable" })); else res.destroy(); });req.pipe(forwarded);res.on("close", () => forwarded.destroy());- });+ }));server.on("connection", (socket) => {sockets.add(socket);socket.once("close", () => sockets.delete(socket));diff --git a/server/bot-box/egress-gate.ts b/server/bot-box/egress-gate.tsindex cf98c8adc1..302afcc550 100644--- a/server/bot-box/egress-gate.ts+++ b/server/bot-box/egress-gate.ts@@ -8,6 +8,7 @@ import type { Duplex } from "node:stream";import { resolveTarget, type ResolvedAddress } from "../browser/egress/gate.ts";import { refusalFor, type EgressRules } from "../browser/egress/policy.ts";+import { guardedHandler } from "./broker-headers.ts";export interface EgressGateOptions {socketPath: string;@@ -69,7 +70,7 @@ export function openBoxEgressGate(options: EgressGateOptions): Promise<BoxEgressconst pinnedLookup = (addresses: ResolvedAddress[]) => (_host: string, lookupOptions: { all?: boolean }, callback: (...args: any[]) => void) =>lookupOptions.all ? callback(null, addresses) : callback(null, addresses[0]!.address, addresses[0]!.family);- const server: Server = createServer(async (req: IncomingMessage, res: ServerResponse) => {+ const server: Server = createServer(guardedHandler("box network gate", async (req: IncomingMessage, res: ServerResponse) => {let url: URL;try {url = new URL(req.url ?? "");@@ -95,7 +96,7 @@ export function openBoxEgressGate(options: EgressGateOptions): Promise<BoxEgressres.on("close", () => { if (!res.writableFinished) upstream.destroy(); });upstream.on("error", () => { if (!res.headersSent) res.writeHead(502, { "content-type": "text/plain" }).end("The connection failed.\n"); else res.destroy(); });req.pipe(upstream);- });+ }));server.on("connection", track);server.on("connect", async (req: IncomingMessage, client: Duplex, head: Buffer) => {const target = parseConnectTarget(req.url);diff --git a/server/bot-box/harness-gate.ts b/server/bot-box/harness-gate.tsindex 3489bbbcc5..eeb2418829 100644--- a/server/bot-box/harness-gate.ts+++ b/server/bot-box/harness-gate.ts@@ -4,6 +4,7 @@// other route of the server answers 403 here before it is ever asked.import { createServer, request as httpRequest, type IncomingMessage, type Server, type ServerResponse } from "node:http";import type { Socket } from "node:net";+import { guardedHandler } from "./broker-headers.ts";export const HARNESS_GATE_PREFIX = "/api/internal/";@@ -41,7 +42,7 @@ export function openHarnessGate(options: HarnessGateOptions): Promise<HarnessGatconst allow = options.allow ?? [HARNESS_GATE_PREFIX];const sockets = new Set<Socket>();const gate = { socketPath: options.socketPath, refused: 0 } as HarnessGate;- const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => {+ const server: Server = createServer(guardedHandler("harness gate", (req: IncomingMessage, res: ServerResponse) => {const target = harnessTarget(req.url ?? "", allow);if (target === null) {gate.refused += 1;@@ -64,7 +65,7 @@ export function openHarnessGate(options: HarnessGateOptions): Promise<HarnessGat});req.pipe(upstream);res.on("close", () => upstream.destroy());- });+ }));server.on("connection", (socket) => {sockets.add(socket);socket.once("close", () => sockets.delete(socket));diff --git a/server/config.ts b/server/config.tsindex d19315ff5d..51cd8fd04d 100644--- a/server/config.ts+++ b/server/config.ts@@ -37,7 +37,7 @@ import { localVmConfigSchema } from "./local-vm-settings.ts";export * from "./local-vm-settings.ts";export * from "./vps-config.ts";-const optionalText = z.string().optional();+const optionalText = z.string().optional(), secretText = z.string().trim().optional(); // secretText: a saved key without a paste's surrounding whitespace (a trailing newline), so it can go in a header.const LEGACY_BROWSER_PROFILE_ID = /^[A-Za-z0-9_-]{1,40}$/;const BROWSER_PROFILE_ID = /^[a-z0-9_-]{1,40}$/;@@ -301,19 +301,19 @@ const appConfigSchema = z.object({publicUrl: z.string().url().optional(),phone: z.enum(["ios", "android"]).optional(),}).optional(),- mistral: z.object({ key: optionalText }).optional(),- cerebras: z.object({ key: optionalText }).optional(), treg: z.object({ key: optionalText }).optional(), postiz: z.object({ key: optionalText, url: optionalText }).optional(),- groq: z.object({ key: optionalText, url: optionalText }).optional(),- greenference: z.object({ key: optionalText }).optional(), modelgo: z.object({ key: optionalText }).optional(),- meta: z.object({ key: optionalText, url: optionalText }).optional(),- deepseek: z.object({ key: optionalText }).optional(),- xai: z.object({ key: optionalText, url: optionalText }).optional(),+ mistral: z.object({ key: secretText }).optional(),+ cerebras: z.object({ key: secretText }).optional(), treg: z.object({ key: secretText }).optional(), postiz: z.object({ key: secretText, url: optionalText }).optional(),+ groq: z.object({ key: secretText, url: optionalText }).optional(),+ greenference: z.object({ key: secretText }).optional(), modelgo: z.object({ key: secretText }).optional(),+ meta: z.object({ key: secretText, url: optionalText }).optional(),+ deepseek: z.object({ key: secretText }).optional(),+ xai: z.object({ key: secretText, url: optionalText }).optional(),/** Anthropic API key for Claude Code billed per token; `url` is for a proxy or test double. Never a login OAuth token. */- anthropic: z.object({ key: optionalText, url: optionalText, everyClaudeBot: z.boolean().optional() }).optional(),+ anthropic: z.object({ key: secretText, url: optionalText, everyClaudeBot: z.boolean().optional() }).optional(),/** OpenAI API key for the `openai` instance only; Codex keeps its own login. */- openai: z.object({ key: optionalText }).optional(),+ openai: z.object({ key: secretText }).optional(),/** OpenRouter key, for the `openrouter` instance only. */- openrouter: z.object({ key: optionalText }).optional(),+ openrouter: z.object({ key: secretText }).optional(),/** Workspace monthly spend limit; enforced only with the `budgets` entitlement. */budgets: z.object({@@ -339,20 +339,20 @@ const appConfigSchema = z.object({.optional(),/** `model` seeds the default selection; `provider` pins an OpenRouter upstream (e.g. "fireworks"). */openaiCompat: z- .object({ key: optionalText, url: optionalText, model: optionalText, provider: optionalText })+ .object({ key: secretText, url: optionalText, model: optionalText, provider: optionalText }).optional(),/** Composio project key; `userId`/`sessionId` reuse one Composio Session. */- composio: z.object({ apiKey: optionalText, userId: optionalText, sessionId: optionalText }).optional(),- box: z.object({ token: optionalText }).optional(),+ composio: z.object({ apiKey: secretText, userId: optionalText, sessionId: optionalText }).optional(),+ box: z.object({ token: secretText }).optional(),vps: vpsConfigSchema.optional(),vpsServers: vpsServersSchema.optional(),/** OpenCode key, plus `providerKeys` for its other providers by the env name OpenCode reads; both write-only and only for its child. */- opencodeGo: z.object({ apiKey: optionalText, providerKeys: z.record(z.string(), z.string()).optional() }).optional(),+ opencodeGo: z.object({ apiKey: secretText, providerKeys: z.record(z.string(), z.string()).optional() }).optional(),/** `provider`: "elevenlabs" (default, `key`), "fish" (`fishKey`, `fishModel`), "system", "xai" (`xai.key`), "gemini" (`geminiKey`, `model`), "openai" (`openai.key`), "deepseek" (`deepseek.key`; it also hears dictation) or "chatterbox" (local; `baseUrl`, `model`). */tts: z.object({- key: optionalText,- fishKey: optionalText,- geminiKey: optionalText,+ key: secretText,+ fishKey: secretText,+ geminiKey: secretText,voice: optionalText,provider: z.enum(["elevenlabs", "fish", "system", "chatterbox", "xai", "gemini", "openai", "deepseek"]).optional(),baseUrl: z@@ -404,7 +404,7 @@ const storedAppConfigSchema = appConfigSchema.extend(helperStoredShape).extend({browserProfiles: storedBrowserProfilesSchema.optional(),/** Loose like mcpServers: a bad provider key is dropped later, never the whole file. */opencodeGo: z.object({- apiKey: optionalText,+ apiKey: secretText,providerKeys: z.record(z.string(), z.unknown()).catch({}).transform((keys) => Object.fromEntries(Object.entries(keys).filter((entry): entry is [string, string] => typeof entry[1] === "string"))).optional(),diff --git a/server/mcp-registry.ts b/server/mcp-registry.tsindex b8026e9e41..d1295ba21d 100644--- a/server/mcp-registry.ts+++ b/server/mcp-registry.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { RESERVED_MCP_NAMES, slugMcpName } from "../shared/mcp-name.ts";import type { McpServerSpec, RemoteMcpSpec, StdioMcpSpec } from "./contracts.ts";import { MCP_RESTART_ENV } from "./mcp-app-catalog.ts";+import { trimmedHeaderValues, unsendableHeader } from "./bot-box/broker-headers.ts";export { importedMcpServerName } from "../shared/mcp-name.ts";@@ -200,6 +201,10 @@ function headerError(name: string, value: string): string | null {return null;}+function unsendableHeaderError(name: string, value: string): string | null {+ return unsendableHeader({ [name]: value }) ? `Header “${name}” has characters that are not allowed in a header (such as a curly quote or a control character).` : null;+}+/** Credentials belong in a write-only header, not in the address the listing shows. */function urlError(value: string): string | null {let parsed: URL;@@ -385,7 +390,10 @@ function parseRemote(raw: unknown, mutation: boolean, existing?: StoredMcpServer}const headers = resolveSecrets(incoming, existing && isRemoteMcpServer(existing) ? existing.headers : undefined);if (!headers.ok) return headers;- const invalidHeader = Object.entries(headers.values).map(([name, value]) => headerError(name, value)).find((error) => error !== null);+ // The whitespace a paste leaves around a value (a trailing newline) is dropped, on a save and on a read of what an earlier+ // version saved. A save refuses what still cannot be sent; a stored one is read as it is, and the broker refuses only its request.+ headers.values = trimmedHeaderValues(headers.values);+ const invalidHeader = Object.entries(headers.values).map(([name, value]) => headerError(name, value) ?? (mutation ? unsendableHeaderError(name, value) : null)).find((error) => error !== null);if (invalidHeader) return { ok: false, error: invalidHeader };const oauth = resolveOAuthClient(parsed.data.oauth, existing && isRemoteMcpServer(existing) ? existing.oauth : undefined);if (!oauth.ok) return oauth;diff --git a/server/testing/saved-key-broker-host.ts b/server/testing/saved-key-broker-host.tsnew file mode 100644index 0000000000..79184cede3--- /dev/null+++ b/server/testing/saved-key-broker-host.ts@@ -0,0 +1,44 @@+// A stand-in for a Cloud home's start, run as its own process by broker-headers.test.ts: the credential broker opens, a+// health route answers, and every enabled URL MCP server in config.json, read as it is saved on disk, is checked through+// the broker the way mcp-servers-host.ts checks them at boot (the request a bad saved key crashed the home with). It+// prints its addresses as one JSON line, then serves until killed: POST /check runs the start check again.+import { readFileSync } from "node:fs";+import { createServer } from "node:http";+import { join } from "node:path";++import { openCredentialBroker } from "../bot-box/broker.ts";+import { brokeredServer } from "../bot-box/broker-probe.ts";+import type { AppConfig } from "../config.ts";+import { enabledUrlServers } from "../host/mcp-servers-host.ts";+import { initializeAnswer } from "../host/mcp-url-checks.ts";++const dataDir = process.argv[2]!;+const cfg = JSON.parse(readFileSync(join(dataDir, "config.json"), "utf8")) as AppConfig;+const credentials = await openCredentialBroker({ socketPath: join(dataDir, "broker.sock") });+const path = { broker: { port: 18080, mintForThread: credentials.mintForThread, revokeThread: credentials.revokeThread }, socketPath: credentials.socketPath };++async function startCheck(): Promise<Record<string, boolean>> {+ const answers: Record<string, boolean> = {};+ for (const [name, server] of Object.entries(enabledUrlServers(cfg))) {+ const brokered = brokeredServer(path, name, server);+ try {+ answers[name] = (await initializeAnswer({ ...server, url: brokered.url, headers: {} }, { fetch: brokered.fetch, timeoutMs: 10_000 })).ok;+ } finally {+ await brokered.done();+ }+ }+ return answers;+}++const first = startCheck();+const health = createServer((req, res) => {+ if (req.url === "/health") { res.writeHead(200, { "content-type": "text/plain" }).end("ok"); return; }+ if (req.url === "/check" && req.method === "POST") {+ void startCheck().then((answers) => res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(answers)));+ return;+ }+ res.writeHead(404).end();+});+health.listen(0, "127.0.0.1", () => {+ void first.then((answers) => console.log(JSON.stringify({ port: (health.address() as { port: number }).port, answers })));+});