mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(opencode): route only LLM traffic through Headroom (#3884)
## Description The OpenCode transport hook routed every non-loopback HTTP(S) request through Headroom. That broke built-in WebFetch and Node-based tools because ordinary web pages, npm registries, GitHub, and MCP traffic were rewritten to the proxy and rejected by its upstream safety gate. The hook also injected a child-process loader into every Node child, changing npm/npx/MCP process behavior. Closes #3633 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature - [ ] Breaking change - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring ## Changes Made - Route only recognized LLM API paths (`/chat/completions`, `/responses`, `/messages`, including provider-prefixed variants) through Headroom. - Pass unrelated external fetches through unchanged, preserving URL and headers. - Leave HTTP/2 connections untouched because `http2.connect()` has no request path at connection time and cannot safely identify LLM traffic. - Stop mutating process `NODE_OPTIONS` and stop injecting the hook-shim into arbitrary child processes; preserve explicit child environment variables and Headroom routing environment propagation. - Regenerated the committed standalone entry and hook-shim bundles. - Added regression coverage for non-LLM/LLM fetches, HTTP/2 authorities, process environment preservation, and `spawn`/`exec`/`execFile`/`fork` children. ## Testing - [x] Unit tests pass - [x] Linting passes - [x] Type checking passes - [x] New tests added - [ ] Manual testing performed ### Test Output ```text $ npm --prefix plugins/opencode test Test Files 2 passed (2) Tests 26 passed (26) $ npm --prefix plugins/opencode run typecheck passed $ npm --prefix plugins/opencode run build ESM build success; DTS build success $ npm --prefix plugins/opencode run build:standalone build success entry bundle comparison: identical hook-shim bundle comparison: identical ``` ## Real Behavior Proof - Environment: macOS arm64, Node 25.9.0, npm 11.12.1, OpenCode plugin package with its locked dependencies; no provider credentials or network calls are required by the tests. - Exact command / steps: From the repository root run `npm --prefix plugins/opencode test`, `npm --prefix plugins/opencode run typecheck`, `npm --prefix plugins/opencode run build`, and `npm --prefix plugins/opencode run build:standalone`. The regression tests install the transport hooks, issue non-LLM and LLM fetches, spy on HTTP/2 connect, and exercise `spawn`, `exec`, `execFile`, and `fork` with custom and inherited `NODE_OPTIONS`. - Observed result: non-LLM URLs remain unchanged and have no `x-headroom-*` headers; recognized LLM paths route through the proxy; external HTTP/2 authorities reach the original connect; child environments retain existing `NODE_OPTIONS` without hook-shim imports; all 26 tests pass; typecheck and both builds pass. - Not tested: a live WebFetch request or a real external MCP server. The transport tests cover the routing and environment behavior without network or credential dependencies. ## Runtime Rollout Safety - Rollout-managed feature(s): None; this is an OpenCode plugin transport behavior correction. - Minimum rollout channel: Stable plugin release after the committed bundle is published. - Stable/default behavior changed: Non-LLM HTTP and arbitrary child-process traffic is no longer routed through Headroom; LLM API paths remain routed. - Kill switch / disable path: Remove the plugin or unset the proxy transport configuration; no new feature flag is required. - Unsafe override required: No. - Qualification impact: OpenCode transport tests, typecheck, normal build, and standalone wheel-bundle comparison. - Rollback path: Revert this commit. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review - [x] I have added tests proving the fix - [x] New and existing tests pass locally - [x] I did not edit `CHANGELOG.md` ## Screenshots (if applicable) Not applicable.
This commit is contained in:
@@ -12614,6 +12614,9 @@ function isExcludedHost(hostname3, excludeHosts) {
|
||||
const normalized = hostname3.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
|
||||
}
|
||||
function isLlmEndpointPath(pathname) {
|
||||
return pathname.endsWith("/chat/completions") || pathname.endsWith("/responses") || pathname.endsWith("/messages") || pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent");
|
||||
}
|
||||
function shouldRoute(url2, proxy, excludeHosts) {
|
||||
if (url2.protocol !== "http:" && url2.protocol !== "https:") {
|
||||
return false;
|
||||
@@ -12627,7 +12630,7 @@ function shouldRoute(url2, proxy, excludeHosts) {
|
||||
if (isExcludedHost(url2.hostname, excludeHosts)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
return isLlmEndpointPath(url2.pathname);
|
||||
}
|
||||
function routedUrl(upstream, proxy) {
|
||||
return new URL(`${upstream.pathname}${upstream.search}`, proxy.origin);
|
||||
@@ -12809,18 +12812,8 @@ function wrapGet(request) {
|
||||
};
|
||||
}
|
||||
function wrapHttp2Connect(originalConnect) {
|
||||
return function headroomHttp2Connect(authority, ...args) {
|
||||
const state = getState();
|
||||
if (state) {
|
||||
const proxy = normalizeProxyUrl(state.proxyUrl);
|
||||
const upstream = authority instanceof URL ? authority : new URL(String(authority));
|
||||
if (shouldRoute(upstream, proxy, state.excludeHosts)) {
|
||||
throw new Error(
|
||||
`Headroom OpenCode wrap blocked direct HTTP/2 connection to ${upstream.origin}. Use fetch, http, or https so traffic can be routed through Headroom.`
|
||||
);
|
||||
}
|
||||
}
|
||||
return Reflect.apply(originalConnect, this, [authority, ...args]);
|
||||
return function headroomHttp2Connect(...args) {
|
||||
return Reflect.apply(originalConnect, this, args);
|
||||
};
|
||||
}
|
||||
function installHeadroomTransport(options) {
|
||||
|
||||
@@ -135,6 +135,9 @@ function isExcludedHost(hostname, excludeHosts) {
|
||||
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
|
||||
}
|
||||
function isLlmEndpointPath(pathname) {
|
||||
return pathname.endsWith("/chat/completions") || pathname.endsWith("/responses") || pathname.endsWith("/messages") || pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent");
|
||||
}
|
||||
function shouldRoute(url, proxy, excludeHosts) {
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
return false;
|
||||
@@ -148,7 +151,7 @@ function shouldRoute(url, proxy, excludeHosts) {
|
||||
if (isExcludedHost(url.hostname, excludeHosts)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
return isLlmEndpointPath(url.pathname);
|
||||
}
|
||||
function routedUrl(upstream, proxy) {
|
||||
return new URL(`${upstream.pathname}${upstream.search}`, proxy.origin);
|
||||
@@ -330,18 +333,8 @@ function wrapGet(request) {
|
||||
};
|
||||
}
|
||||
function wrapHttp2Connect(originalConnect) {
|
||||
return function headroomHttp2Connect(authority, ...args) {
|
||||
const state = getState();
|
||||
if (state) {
|
||||
const proxy = normalizeProxyUrl(state.proxyUrl);
|
||||
const upstream = authority instanceof URL ? authority : new URL(String(authority));
|
||||
if (shouldRoute(upstream, proxy, state.excludeHosts)) {
|
||||
throw new Error(
|
||||
`Headroom OpenCode wrap blocked direct HTTP/2 connection to ${upstream.origin}. Use fetch, http, or https so traffic can be routed through Headroom.`
|
||||
);
|
||||
}
|
||||
}
|
||||
return Reflect.apply(originalConnect, this, [authority, ...args]);
|
||||
return function headroomHttp2Connect(...args) {
|
||||
return Reflect.apply(originalConnect, this, args);
|
||||
};
|
||||
}
|
||||
function installHeadroomTransport(options) {
|
||||
|
||||
@@ -2,18 +2,21 @@
|
||||
// standalone (see tsup.standalone.config.ts) and shipped inside the Python wheel
|
||||
// at headroom/providers/opencode/hook-shim/handler.js.
|
||||
//
|
||||
// transport.ts wraps `fetch`/`http`/`https` in the plugin's own process, but a
|
||||
// spawned Node child (an `npx` MCP server, `tokensave serve`, ...) is a fresh
|
||||
// process, so its traffic is only routed if this loader runs at that child's
|
||||
// startup via NODE_OPTIONS=--import. `shimImportSpecifier()` in transport.ts
|
||||
// resolves `../hook-shim/handler.js` next to the loaded entry, which is this
|
||||
// file in a wheel install.
|
||||
// transport.ts wraps `fetch`/`http`/`https` in the plugin's own process and
|
||||
// auto-preloads this loader into spawned Node children when the shim exists on
|
||||
// disk. The shim installs the same scoped transport, so non-LLM child traffic
|
||||
// (npm/npx, WebFetch, MCP servers) passes through untouched. Manual loading
|
||||
// remains available (`node --import <path-to-this-file> ...`) while
|
||||
// HEADROOM_OPENCODE_TRANSPORT_PROXY_URL is set when a specific child Node
|
||||
// process should route its traffic through Headroom; loading it installs the
|
||||
// transport in that process.
|
||||
//
|
||||
// The checkout uses plugins/opencode/hook-shim/handler.js instead, which imports
|
||||
// the non-bundled `../dist/index.js`; pip installs have no node_modules, so this
|
||||
// variant inlines the transport. Without it shipped, the loader path did not
|
||||
// exist, so child-process routing was silently disabled for wheel installs
|
||||
// (before #2806 it crashed every Node child with ERR_MODULE_NOT_FOUND) (#2850).
|
||||
// exist, so a manual `--import` of it was unavailable for wheel installs
|
||||
// (before #2806 a missing `--import` target crashed every Node child with
|
||||
// ERR_MODULE_NOT_FOUND) (#2850).
|
||||
import { installHeadroomTransport } from "./transport.js";
|
||||
|
||||
const proxyUrl = process.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL;
|
||||
|
||||
@@ -167,6 +167,148 @@ describe("Headroom OpenCode transport", () => {
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("passes non-LLM fetches through unchanged (WebFetch, npm registry, GitHub)", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
|
||||
globalThis.fetch = fetchMock as unknown as typeof fetch;
|
||||
|
||||
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", project: "my-project" });
|
||||
|
||||
const init = { method: "GET", headers: { authorization: "Bearer test" } };
|
||||
await fetch("https://example.com/", init);
|
||||
await fetch("https://registry.npmjs.org/left-pad", init);
|
||||
await fetch("https://api.github.com/repos/headroom/headroom", init);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
expect(fetchMock.mock.calls[0][0]).toBe("https://example.com/");
|
||||
expect(fetchMock.mock.calls[1][0]).toBe("https://registry.npmjs.org/left-pad");
|
||||
expect(fetchMock.mock.calls[2][0]).toBe("https://api.github.com/repos/headroom/headroom");
|
||||
for (const call of fetchMock.mock.calls as FetchCall[]) {
|
||||
expect(call[1]).toBe(init);
|
||||
const headers = new Headers(call[1]?.headers);
|
||||
expect(headers.get("x-headroom-base-url")).toBeNull();
|
||||
expect(headers.get("x-headroom-original-path")).toBeNull();
|
||||
expect(headers.get("x-headroom-project")).toBeNull();
|
||||
}
|
||||
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("routes only recognized LLM endpoint fetches through the proxy", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
|
||||
globalThis.fetch = fetchMock as unknown as typeof fetch;
|
||||
|
||||
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
|
||||
|
||||
const init = { method: "POST" };
|
||||
await fetch("https://api.openai.com/v1/chat/completions", init);
|
||||
await fetch("https://api.openai.com/v1/responses", init);
|
||||
await fetch("https://api.anthropic.com/v1/messages", init);
|
||||
await fetch("https://new-provider.example/api/coding/paas/v4/chat/completions", init);
|
||||
await fetch("https://api.openai.com/v1/models", init);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(5);
|
||||
expect(fetchMock.mock.calls[0][0]).toEqual(new URL("http://127.0.0.1:8787/v1/chat/completions"));
|
||||
expect(new Headers(fetchMock.mock.calls[0][1]?.headers).get("x-headroom-base-url")).toBe("https://api.openai.com");
|
||||
expect(new Headers(fetchMock.mock.calls[0][1]?.headers).get("x-headroom-original-path")).toBe("/v1/chat/completions");
|
||||
|
||||
expect(fetchMock.mock.calls[1][0]).toEqual(new URL("http://127.0.0.1:8787/v1/responses"));
|
||||
expect(new Headers(fetchMock.mock.calls[1][1]?.headers).get("x-headroom-base-url")).toBe("https://api.openai.com");
|
||||
expect(new Headers(fetchMock.mock.calls[1][1]?.headers).get("x-headroom-original-path")).toBe("/v1/responses");
|
||||
|
||||
expect(fetchMock.mock.calls[2][0]).toEqual(new URL("http://127.0.0.1:8787/v1/messages"));
|
||||
expect(new Headers(fetchMock.mock.calls[2][1]?.headers).get("x-headroom-base-url")).toBe("https://api.anthropic.com");
|
||||
expect(new Headers(fetchMock.mock.calls[2][1]?.headers).get("x-headroom-original-path")).toBeNull();
|
||||
|
||||
expect(fetchMock.mock.calls[3][0]).toEqual(new URL("http://127.0.0.1:8787/v1/chat/completions"));
|
||||
expect(new Headers(fetchMock.mock.calls[3][1]?.headers).get("x-headroom-base-url")).toBe("https://new-provider.example");
|
||||
expect(new Headers(fetchMock.mock.calls[3][1]?.headers).get("x-headroom-original-path")).toBe(
|
||||
"/api/coding/paas/v4/chat/completions",
|
||||
);
|
||||
|
||||
expect(fetchMock.mock.calls[4][0]).toBe("https://api.openai.com/v1/models");
|
||||
expect(fetchMock.mock.calls[4][1]).toBe(init);
|
||||
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("routes Gemini native :generateContent and :streamGenerateContent through the proxy", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
|
||||
globalThis.fetch = fetchMock as unknown as typeof fetch;
|
||||
|
||||
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
|
||||
|
||||
const init = { method: "POST" };
|
||||
await fetch("https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent", init);
|
||||
await fetch("https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent", init);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(fetchMock.mock.calls[0][0]).toEqual(
|
||||
new URL("http://127.0.0.1:8787/v1beta/models/gemini-2.0-flash:generateContent"),
|
||||
);
|
||||
expect(new Headers(fetchMock.mock.calls[0][1]?.headers).get("x-headroom-base-url")).toBe(
|
||||
"https://generativelanguage.googleapis.com",
|
||||
);
|
||||
expect(fetchMock.mock.calls[1][0]).toEqual(
|
||||
new URL("http://127.0.0.1:8787/v1beta/models/gemini-2.0-flash:streamGenerateContent"),
|
||||
);
|
||||
expect(new Headers(fetchMock.mock.calls[1][1]?.headers).get("x-headroom-base-url")).toBe(
|
||||
"https://generativelanguage.googleapis.com",
|
||||
);
|
||||
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("routes CloudCode :streamGenerateContent variants through the proxy", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
|
||||
globalThis.fetch = fetchMock as unknown as typeof fetch;
|
||||
|
||||
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
|
||||
|
||||
const init = { method: "POST" };
|
||||
await fetch("https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent", init);
|
||||
await fetch("https://cloudcode-pa.googleapis.com/v1/v1internal:streamGenerateContent", init);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(fetchMock.mock.calls[0][0]).toEqual(
|
||||
new URL("http://127.0.0.1:8787/v1internal:streamGenerateContent"),
|
||||
);
|
||||
expect(fetchMock.mock.calls[1][0]).toEqual(
|
||||
new URL("http://127.0.0.1:8787/v1/v1internal:streamGenerateContent"),
|
||||
);
|
||||
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("does not route lookalike paths containing LLM markers outside valid endpoint shapes", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
|
||||
globalThis.fetch = fetchMock as unknown as typeof fetch;
|
||||
|
||||
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
|
||||
|
||||
const init = { method: "GET" };
|
||||
await fetch("https://example.com/v1/models/gemini:generateContent/status", init);
|
||||
await fetch("https://example.com/v1/models/gemini:streamGenerateContent/log", init);
|
||||
await fetch("https://example.com/api/chat/completions-helper", init);
|
||||
await fetch("https://example.com/v1/messages/inbox", init);
|
||||
await fetch("https://example.com/v1/responses/feedback", init);
|
||||
await fetch("https://example.com/v1/models/generateContent", init);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(6);
|
||||
for (const call of fetchMock.mock.calls as FetchCall[]) {
|
||||
expect(typeof call[0]).toBe("string");
|
||||
expect(call[1]).toBe(init);
|
||||
const headers = new Headers(call[1]?.headers);
|
||||
expect(headers.get("x-headroom-base-url")).toBeNull();
|
||||
}
|
||||
|
||||
globalThis.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("routes external https.request calls through the proxy", async () => {
|
||||
const proxy = await proxyServer();
|
||||
installHeadroomTransport({ proxyUrl: proxy.url });
|
||||
@@ -289,15 +431,20 @@ describe("Headroom OpenCode transport", () => {
|
||||
await proxy.close();
|
||||
});
|
||||
|
||||
it("blocks external http2 connections instead of leaking them", () => {
|
||||
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
|
||||
it("passes external, loopback, and excluded http2.connect authorities through unchanged", () => {
|
||||
const connectSpy = vi.spyOn(http2, "connect").mockImplementation(() => ({}) as never);
|
||||
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["opencode.ai"] });
|
||||
|
||||
expect(() => http2.connect("https://api.openai.com")).toThrow(
|
||||
/blocked direct HTTP\/2 connection to https:\/\/api\.openai\.com/,
|
||||
);
|
||||
expect(() => http2.connect("https://api.openai.com")).not.toThrow();
|
||||
expect(() => http2.connect("http://127.0.0.1:4096")).not.toThrow();
|
||||
expect(() => http2.connect("https://opencode.ai")).not.toThrow();
|
||||
|
||||
expect(connectSpy).toHaveBeenCalledWith("https://api.openai.com");
|
||||
expect(connectSpy).toHaveBeenCalledWith("http://127.0.0.1:4096");
|
||||
expect(connectSpy).toHaveBeenCalledWith("https://opencode.ai");
|
||||
});
|
||||
|
||||
it("preloads the Headroom shim into child Node processes", () => {
|
||||
it("injects the hook-shim --import into process.env.NODE_OPTIONS when the shim exists", () => {
|
||||
const originalNodeOptions = process.env.NODE_OPTIONS;
|
||||
const originalProxyUrl = process.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL;
|
||||
|
||||
@@ -309,11 +456,11 @@ describe("Headroom OpenCode transport", () => {
|
||||
|
||||
expect(process.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
|
||||
expect(process.env.NODE_OPTIONS).toContain("--trace-warnings");
|
||||
expect(process.env.NODE_OPTIONS).toContain("--import=file:");
|
||||
expect(process.env.NODE_OPTIONS).toContain("/hook-shim/handler.js");
|
||||
expect(process.env.NODE_OPTIONS).toContain("--import=");
|
||||
|
||||
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
|
||||
expect(process.env.NODE_OPTIONS?.match(/hook-shim\/handler\.js/g)).toHaveLength(1);
|
||||
const importCount = (process.env.NODE_OPTIONS?.match(/--import=/g) ?? []).length;
|
||||
expect(importCount).toBe(1);
|
||||
} finally {
|
||||
if (originalNodeOptions === undefined) {
|
||||
delete process.env.NODE_OPTIONS;
|
||||
@@ -346,6 +493,7 @@ describe("Headroom OpenCode transport", () => {
|
||||
|
||||
childProcess.spawn("npx", ["-y", "firecrawl-mcp"]);
|
||||
const options = (spawnMock.mock.calls[0] as unknown[])[2] as { env: NodeJS.ProcessEnv };
|
||||
expect(options.env.NODE_OPTIONS).toBe("--trace-warnings");
|
||||
expect(options.env.NODE_OPTIONS).not.toContain("--import");
|
||||
} finally {
|
||||
if (originalNodeOptions === undefined) {
|
||||
@@ -358,7 +506,7 @@ describe("Headroom OpenCode transport", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("injects the Headroom shim into child processes with custom env", () => {
|
||||
it("passes custom child NODE_OPTIONS through byte-for-byte and propagates HEADROOM env", () => {
|
||||
const originalSpawn = childProcess.spawn;
|
||||
const spawnMock = vi.fn(() => ({
|
||||
on: vi.fn(),
|
||||
@@ -378,14 +526,92 @@ describe("Headroom OpenCode transport", () => {
|
||||
expect(options.env.PATH).toBe("/bin");
|
||||
expect(options.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
|
||||
expect(options.env.NODE_OPTIONS).toContain("--trace-warnings");
|
||||
expect(options.env.NODE_OPTIONS).toContain("--import=file:");
|
||||
expect(options.env.NODE_OPTIONS).toContain("/hook-shim/handler.js");
|
||||
expect(options.env.NODE_OPTIONS).toContain("--import=");
|
||||
} finally {
|
||||
uninstallHeadroomTransport();
|
||||
childProcess.spawn = originalSpawn;
|
||||
}
|
||||
});
|
||||
|
||||
it("injects one idempotent hook-shim --import into spawn/exec/execFile/fork children", () => {
|
||||
const originalSpawn = childProcess.spawn;
|
||||
const originalExec = childProcess.exec;
|
||||
const originalExecFile = childProcess.execFile;
|
||||
const originalFork = childProcess.fork;
|
||||
const originalNodeOptions = process.env.NODE_OPTIONS;
|
||||
const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
|
||||
const childStub = { on: vi.fn(), once: vi.fn(), emit: vi.fn(), kill: vi.fn(), killed: false, pid: 123 };
|
||||
const spawnMock = vi.fn(() => childStub);
|
||||
const execMock = vi.fn(() => childStub);
|
||||
const execFileMock = vi.fn(() => childStub);
|
||||
const forkMock = vi.fn(() => childStub);
|
||||
childProcess.spawn = spawnMock as unknown as typeof childProcess.spawn;
|
||||
childProcess.exec = execMock as unknown as typeof childProcess.exec;
|
||||
childProcess.execFile = execFileMock as unknown as typeof childProcess.execFile;
|
||||
childProcess.fork = forkMock as unknown as typeof childProcess.fork;
|
||||
|
||||
try {
|
||||
process.env.NODE_OPTIONS = "--max-old-space-size=4096 --trace-warnings";
|
||||
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
|
||||
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["opencode.ai"] });
|
||||
|
||||
const custom = { PATH: "/bin", NODE_OPTIONS: "--trace-warnings --experimental-vm-modules" };
|
||||
childProcess.spawn("npm", ["install"], { env: custom });
|
||||
childProcess.exec("npx -y firecrawl-mcp", { env: custom });
|
||||
childProcess.execFile("node", ["mcp-server.js"], { env: custom });
|
||||
childProcess.fork("agent.js", [], { env: custom });
|
||||
childProcess.spawn("bash", ["-lc", "echo hi"]);
|
||||
childProcess.spawn("node", ["mcp.js"]);
|
||||
childProcess.exec("bash -lc 'echo hi'");
|
||||
childProcess.execFile("npx", ["-y", "firecrawl-mcp"]);
|
||||
|
||||
const spawnCalls = spawnMock.mock.calls as unknown[][];
|
||||
const execCalls = execMock.mock.calls as unknown[][];
|
||||
const execFileCalls = execFileMock.mock.calls as unknown[][];
|
||||
const forkCalls = forkMock.mock.calls as unknown[][];
|
||||
const customNodeOptions = "--trace-warnings --experimental-vm-modules";
|
||||
const defaultNodeOptions = "--max-old-space-size=4096 --trace-warnings";
|
||||
const pairs: Array<[unknown[], number, string]> = [
|
||||
[spawnCalls[0], 2, customNodeOptions],
|
||||
[execCalls[0], 1, customNodeOptions],
|
||||
[execFileCalls[0], 2, customNodeOptions],
|
||||
[forkCalls[0], 2, customNodeOptions],
|
||||
[spawnCalls[1], 2, defaultNodeOptions],
|
||||
[spawnCalls[2], 2, defaultNodeOptions],
|
||||
[execCalls[1], 1, defaultNodeOptions],
|
||||
[execFileCalls[1], 2, defaultNodeOptions],
|
||||
];
|
||||
for (const [call, index, expectedNodeOptions] of pairs) {
|
||||
const env = (call[index] as { env: NodeJS.ProcessEnv }).env;
|
||||
const nodeOptions = env.NODE_OPTIONS ?? "";
|
||||
expect(nodeOptions).toContain(expectedNodeOptions);
|
||||
expect(nodeOptions).toContain("--import=");
|
||||
expect((nodeOptions.match(/--import=/g) ?? []).length).toBe(1);
|
||||
expect(env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
|
||||
expect(env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("opencode.ai");
|
||||
}
|
||||
const processNodeOptions = process.env.NODE_OPTIONS ?? "";
|
||||
expect(processNodeOptions).toContain(defaultNodeOptions);
|
||||
expect((processNodeOptions.match(/--import=/g) ?? []).length).toBe(1);
|
||||
} finally {
|
||||
if (originalNodeOptions === undefined) {
|
||||
delete process.env.NODE_OPTIONS;
|
||||
} else {
|
||||
process.env.NODE_OPTIONS = originalNodeOptions;
|
||||
}
|
||||
if (originalExclude === undefined) {
|
||||
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
|
||||
} else {
|
||||
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
|
||||
}
|
||||
uninstallHeadroomTransport();
|
||||
childProcess.spawn = originalSpawn;
|
||||
childProcess.exec = originalExec;
|
||||
childProcess.execFile = originalExecFile;
|
||||
childProcess.fork = originalFork;
|
||||
}
|
||||
});
|
||||
|
||||
it("sends x-headroom-project header on routed fetch calls when project is set", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
|
||||
@@ -520,7 +746,8 @@ describe("Headroom OpenCode transport", () => {
|
||||
|
||||
expect(() => http2.connect("https://opencode.ai")).not.toThrow();
|
||||
expect(connectSpy).toHaveBeenCalledWith("https://opencode.ai");
|
||||
expect(() => http2.connect("https://api.openai.com")).toThrow(/blocked direct HTTP\/2 connection/);
|
||||
expect(() => http2.connect("https://api.openai.com")).not.toThrow();
|
||||
expect(connectSpy).toHaveBeenCalledWith("https://api.openai.com");
|
||||
} finally {
|
||||
uninstallHeadroomTransport();
|
||||
if (originalExclude === undefined) {
|
||||
|
||||
@@ -221,6 +221,25 @@ function isExcludedHost(hostname: string, excludeHosts: string[]): boolean {
|
||||
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
|
||||
}
|
||||
|
||||
// Only recognized LLM API endpoints route through Headroom; any other path
|
||||
// (WebFetch, registries, GitHub, unknown services) must reach its original URL
|
||||
// untouched. A bare suffix match keeps provider-prefixed variants working
|
||||
// (/api/coding/paas/v4/chat/completions, /base/v1/messages, ...).
|
||||
//
|
||||
// Native Gemini model-generation endpoints use colon-action suffixes
|
||||
// (:generateContent, :streamGenerateContent). These are matched by exact
|
||||
// suffix so that lookalike paths containing the marker but not ending with it
|
||||
// (e.g. /v1/models/gemini:generateContent/status) remain unrouted.
|
||||
function isLlmEndpointPath(pathname: string): boolean {
|
||||
return (
|
||||
pathname.endsWith("/chat/completions") ||
|
||||
pathname.endsWith("/responses") ||
|
||||
pathname.endsWith("/messages") ||
|
||||
pathname.endsWith(":generateContent") ||
|
||||
pathname.endsWith(":streamGenerateContent")
|
||||
);
|
||||
}
|
||||
|
||||
function shouldRoute(url: URL, proxy: URL, excludeHosts: string[]): boolean {
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
return false;
|
||||
@@ -234,7 +253,7 @@ function shouldRoute(url: URL, proxy: URL, excludeHosts: string[]): boolean {
|
||||
if (isExcludedHost(url.hostname, excludeHosts)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
return isLlmEndpointPath(url.pathname);
|
||||
}
|
||||
|
||||
function routedUrl(upstream: URL, proxy: URL): URL {
|
||||
@@ -465,20 +484,13 @@ function wrapGet(request: HttpRequest | HttpsRequest): HttpGet | HttpsGet {
|
||||
} as HttpGet | HttpsGet;
|
||||
}
|
||||
|
||||
// http2.connect() has no request path at connect time, so the authority alone
|
||||
// cannot prove LLM traffic. Direct HTTP/2 connections always pass through
|
||||
// untouched: rejecting external authorities turned WebFetch into a proxy
|
||||
// error (#3633).
|
||||
function wrapHttp2Connect(originalConnect: Http2Connect): Http2Connect {
|
||||
return function headroomHttp2Connect(this: unknown, authority: string | URL, ...args: unknown[]) {
|
||||
const state = getState();
|
||||
if (state) {
|
||||
const proxy = normalizeProxyUrl(state.proxyUrl);
|
||||
const upstream = authority instanceof URL ? authority : new URL(String(authority));
|
||||
if (shouldRoute(upstream, proxy, state.excludeHosts)) {
|
||||
throw new Error(
|
||||
`Headroom OpenCode wrap blocked direct HTTP/2 connection to ${upstream.origin}. ` +
|
||||
"Use fetch, http, or https so traffic can be routed through Headroom.",
|
||||
);
|
||||
}
|
||||
}
|
||||
return Reflect.apply(originalConnect, this, [authority, ...args]);
|
||||
return function headroomHttp2Connect(this: unknown, ...args: unknown[]) {
|
||||
return Reflect.apply(originalConnect, this, args);
|
||||
} as Http2Connect;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user