fix(opencode): do not break every request when the proxy URL is empty or invalid (#4750)

## Description

Part of #4746

The OpenCode plugin resolved the proxy URL with `??`, so an empty
`HEADROOM_PROXY_URL` (or `HEADROOM_BASE_URL`, or `proxyUrl` option) won
over the default. The transport then called `new URL(state.proxyUrl)` in
the patched `fetch` and in the http(s) wrapper before it decided whether
a request should be routed, so `new URL("")` or `new
URL("127.0.0.1:8787")` threw on every outbound request in the host
(WebFetch, registries, MCP), although non-LLM traffic is meant to be
left untouched.

This PR treats an empty value as unset, and when the URL still does not
parse, lets the request go to the original function and logs one fixed
warning per value that never contains the value itself (it can carry
credentials); a value with a non-http(s) scheme such as
`user:pass@host:8787` counts as unusable too.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `plugins/opencode/src/plugin.ts`, `plugins/opencode/src/retrieve.ts`:
`??` becomes `||` in the proxy URL resolution chain and in
`getDefaultProxyUrl`.
- `plugins/opencode/src/transport.ts`: new `usableProxyUrl` (parse, or
warn once per value and return nothing). The patched `fetch` and the
http(s) wrapper call the original function when it returns nothing.
`modelBaseRoutesThroughProxy` already catches the parse error and is
unchanged.
- `plugins/opencode/src/plugin.test.ts`: an empty `HEADROOM_PROXY_URL`
falls through to `HEADROOM_BASE_URL`; an empty `proxyUrl` option with
both variables empty gives the default `http://localhost:8787`.
- `plugins/opencode/src/transport.test.ts`: for `""` and
`"127.0.0.1:8787"`, `fetch` (an LLM path and a plain one) is passed
through unchanged, `http.request`/`https.request` do not throw, and
`console.warn` is called once.

## Testing

- [ ] Unit tests pass (`pytest`)
- [ ] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

This is a TypeScript change in `plugins/opencode`, so the Python checks
above do not apply. The package's own checks were run instead: `vitest
run` and `tsc --noEmit` (`node node_modules/@typescript/native/bin/tsc
--noEmit`, no output). The package has no lint or format script and the
root ruff config covers Python only, so none was run.

### Test Output

Fail before (`transport.ts`, `plugin.ts`, `retrieve.ts` from
`origin/main` `1da8930a`, new tests kept; `npx vitest run` in
`plugins/opencode`, Ubuntu on WSL2, Node v24.22.2):

```text
FAIL plugin.test.ts > treats an empty HEADROOM_PROXY_URL as unset and falls through to HEADROOM_BASE_URL
AssertionError: expected '' to be 'http://127.0.0.1:9999'
FAIL plugin.test.ts > treats an empty proxyUrl option as unset
AssertionError: expected '' to be 'http://localhost:8787'
FAIL transport.test.ts > leaves all traffic alone when the proxy URL is unusable ("")
FAIL transport.test.ts > leaves all traffic alone when the proxy URL is unusable ("127.0.0.1:8787")
TypeError: Invalid URL
 ❯ normalizeProxyUrl src/transport.ts:219:10
 Test Files  2 failed | 2 passed (4)
      Tests  4 failed | 66 passed (70)
```

Pass after (this branch):

```text
 Test Files  4 passed (4)
      Tests  71 passed (71)
```

## Real Behavior Proof

- Environment: Ubuntu on WSL2 (Windows 11 host), Node v24.22.2, vitest
and TypeScript from `plugins/opencode/package-lock.json` (`npm ci
--ignore-scripts`), no network (`fetch` is a recorder).
- Exact command / steps: `npx vitest run` in `plugins/opencode`; the
transport tests install it with `proxyUrl: ""` and `"127.0.0.1:8787"`,
then call `fetch` for `https://api.anthropic.com/v1/messages` (POST) and
`https://registry.npmjs.org/left-pad`, and create an `http.request` and
an `https.request`.
- Observed result: see Test Output; on `origin/main` the install
succeeds and the first request throws `TypeError: Invalid URL`; with
this change both `fetch` calls reach the original function with their
own URL and no routing headers, and one fixed warning is logged (the
value is never logged; a follow-up commit added a test that a
credential-like value does not appear in it: that test fails on the
previous head, 3 failed and 68 passed of 71 with the new tests on the
old source).
- Not tested: the real OpenCode host; Windows; whether the child-process
shim (which receives the same unusable value through its environment) is
affected beyond what the same `usableProxyUrl` guard covers.

## Runtime Rollout Safety

- Rollout-managed feature(s): none changed.
- Minimum rollout channel: n/a (no new feature)
- Stable/default behavior changed: yes, narrowly: an empty proxy URL
setting now means "use the next source / the default" instead of an
empty URL, and an unparsable proxy URL disables routing instead of
throwing on every request. A valid URL behaves as before.
- Kill switch / disable path: none added.
- Unsafe override required: no
- Qualification impact: none expected.
- 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 of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes (see
Testing)
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

- Whitespace-only values are not treated as unset by the resolution;
they reach the transport, which now ignores them with the warning.
- The warning goes to `console.warn`; the plugin has no other logger.

Produced with AI assistance (Claude Code) operated by me (HetCreep); the
tests and proof above were run on my machine against a clone of the
repository.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
HetCreep
2026-11-10 08:19:38 -06:00
committed by GitHub
co-authored by Claude Sonnet 5.5
parent 62f2a2decd
commit 318e8e0808
7 changed files with 165 additions and 12 deletions
+24 -4
View File
@@ -19730,7 +19730,7 @@ tool.schema = external_exports;
// src/retrieve.ts
var _proxyUrlCache = null;
function getDefaultProxyUrl() {
return _proxyUrlCache ?? process.env.HEADROOM_BASE_URL ?? "http://localhost:8787";
return _proxyUrlCache || process.env.HEADROOM_BASE_URL || "http://localhost:8787";
}
function trimTrailingSlashes(value) {
let end = value.length;
@@ -19919,6 +19919,20 @@ function wrapFork(originalFork) {
function normalizeProxyUrl(proxyUrl) {
return new URL(proxyUrl);
}
var reportedProxyUrls = /* @__PURE__ */ new Set();
function usableProxyUrl(proxyUrl) {
try {
const proxy = normalizeProxyUrl(proxyUrl);
if (proxy.protocol !== "http:" && proxy.protocol !== "https:") throw new TypeError("unsupported scheme");
return proxy;
} catch {
if (!reportedProxyUrls.has(proxyUrl)) {
reportedProxyUrls.add(proxyUrl);
console.warn(`headroom: the configured proxy URL is ${proxyUrl === "" ? "empty" : "not a valid http(s) URL"}; requests are not routed`);
}
return void 0;
}
}
function isLoopback(hostname3) {
const normalized = hostname3.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
@@ -20136,7 +20150,10 @@ function wrapRequest(originalHttpRequest, originalHttpsRequest, originalRequest)
if (!state) {
return Reflect.apply(originalRequest, this, args);
}
const proxy = normalizeProxyUrl(state.proxyUrl);
const proxy = usableProxyUrl(state.proxyUrl);
if (!proxy) {
return Reflect.apply(originalRequest, this, args);
}
const parts = splitNodeArgs(args);
const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts, state.sessionToken);
if (!nextOptions) {
@@ -20198,7 +20215,10 @@ function installHeadroomTransport(options) {
if (!current) {
return state.originalFetch(...args);
}
const proxy = normalizeProxyUrl(current.proxyUrl);
const proxy = usableProxyUrl(current.proxyUrl);
if (!proxy) {
return state.originalFetch(...args);
}
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts, current.sessionToken);
return state.originalFetch(nextInput, nextInit);
};
@@ -20245,7 +20265,7 @@ function normalizeProxyUrl2(url2) {
}
function resolveProxyUrl(options) {
return normalizeProxyUrl2(
options?.proxyUrl ?? process.env.HEADROOM_PROXY_URL ?? process.env.HEADROOM_BASE_URL ?? getDefaultProxyUrl()
options?.proxyUrl || process.env.HEADROOM_PROXY_URL || process.env.HEADROOM_BASE_URL || getDefaultProxyUrl()
);
}
function resolveSessionToken(options) {
@@ -134,6 +134,20 @@ function wrapFork(originalFork) {
function normalizeProxyUrl(proxyUrl2) {
return new URL(proxyUrl2);
}
var reportedProxyUrls = /* @__PURE__ */ new Set();
function usableProxyUrl(proxyUrl2) {
try {
const proxy = normalizeProxyUrl(proxyUrl2);
if (proxy.protocol !== "http:" && proxy.protocol !== "https:") throw new TypeError("unsupported scheme");
return proxy;
} catch {
if (!reportedProxyUrls.has(proxyUrl2)) {
reportedProxyUrls.add(proxyUrl2);
console.warn(`headroom: the configured proxy URL is ${proxyUrl2 === "" ? "empty" : "not a valid http(s) URL"}; requests are not routed`);
}
return void 0;
}
}
function isLoopback(hostname) {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
@@ -344,7 +358,10 @@ function wrapRequest(originalHttpRequest, originalHttpsRequest, originalRequest)
if (!state) {
return Reflect.apply(originalRequest, this, args);
}
const proxy = normalizeProxyUrl(state.proxyUrl);
const proxy = usableProxyUrl(state.proxyUrl);
if (!proxy) {
return Reflect.apply(originalRequest, this, args);
}
const parts = splitNodeArgs(args);
const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts, state.sessionToken);
if (!nextOptions) {
@@ -406,7 +423,10 @@ function installHeadroomTransport(options) {
if (!current) {
return state.originalFetch(...args);
}
const proxy = normalizeProxyUrl(current.proxyUrl);
const proxy = usableProxyUrl(current.proxyUrl);
if (!proxy) {
return state.originalFetch(...args);
}
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts, current.sessionToken);
return state.originalFetch(nextInput, nextInit);
};
+32
View File
@@ -116,6 +116,38 @@ describe("HeadroomPlugin", () => {
});
});
it("treats an empty HEADROOM_PROXY_URL as unset and falls through to HEADROOM_BASE_URL", async () => {
vi.stubEnv("HEADROOM_PROXY_URL", "");
vi.stubEnv("HEADROOM_BASE_URL", "http://127.0.0.1:9999");
try {
const plugin = await HeadroomPlugin(pluginInput(), {});
const output = { env: {} as Record<string, string> };
await plugin["shell.env"]?.({ cwd: "/repo" }, output);
await plugin.dispose?.();
expect(output.env.HEADROOM_PROXY_URL).toBe("http://127.0.0.1:9999");
} finally {
vi.unstubAllEnvs();
}
});
it("treats an empty proxyUrl option as unset", async () => {
vi.stubEnv("HEADROOM_PROXY_URL", "");
vi.stubEnv("HEADROOM_BASE_URL", "");
try {
const plugin = await HeadroomPlugin(pluginInput(), { proxyUrl: "" });
const output = { env: {} as Record<string, string> };
await plugin["shell.env"]?.({ cwd: "/repo" }, output);
await plugin.dispose?.();
expect(output.env.HEADROOM_PROXY_URL).toBe("http://localhost:8787");
} finally {
vi.unstubAllEnvs();
}
});
it("exposes a headroom_retrieve tool backed by the proxy", async () => {
const fetchMock = vi.fn(async () => ({
ok: true,
+3 -3
View File
@@ -36,9 +36,9 @@ function normalizeProxyUrl(url: string): string {
function resolveProxyUrl(options?: HeadroomOpenCodePluginOptions): string {
return normalizeProxyUrl(
options?.proxyUrl ??
process.env.HEADROOM_PROXY_URL ??
process.env.HEADROOM_BASE_URL ??
options?.proxyUrl ||
process.env.HEADROOM_PROXY_URL ||
process.env.HEADROOM_BASE_URL ||
getDefaultProxyUrl(),
);
}
+1 -1
View File
@@ -8,7 +8,7 @@ export function setDefaultProxyUrl(url: string): void {
}
export function getDefaultProxyUrl(): string {
return _proxyUrlCache ?? process.env.HEADROOM_BASE_URL ?? "http://localhost:8787";
return _proxyUrlCache || process.env.HEADROOM_BASE_URL || "http://localhost:8787";
}
export interface RetrieveToolConfig {
+54
View File
@@ -1110,4 +1110,58 @@ describe("Headroom OpenCode transport", () => {
firstDispose();
globalThis.fetch = originalFetch;
});
it.each(["", "127.0.0.1:8787"])("leaves all traffic alone when the proxy URL is unusable (%j)", async (proxyUrl) => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
installHeadroomTransport({ proxyUrl });
// Neither an LLM endpoint nor a plain download may throw or be rewritten.
await fetch("https://api.anthropic.com/v1/messages", { method: "POST" });
await fetch("https://registry.npmjs.org/left-pad");
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(fetchMock.mock.calls[0][0]).toBe("https://api.anthropic.com/v1/messages");
expect(fetchMock.mock.calls[1][0]).toBe("https://registry.npmjs.org/left-pad");
expect(new Headers(fetchMock.mock.calls[0][1]?.headers).get("x-headroom-base-url")).toBeNull();
for (const [request, scheme] of [[http.request, "http"], [https.request, "https"]] as const) {
const req = request(`${scheme}://registry.npmjs.org/left-pad`, { method: "POST" });
req.on("error", () => {});
expect(req.host).toBe("registry.npmjs.org");
req.destroy();
}
// The problem is reported once, not once per request.
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
`headroom: the configured proxy URL is ${proxyUrl === "" ? "empty" : "not a valid http(s) URL"}; requests are not routed`,
);
} finally {
globalThis.fetch = originalFetch;
warn.mockRestore();
}
});
it("does not log any part of an unusable proxy URL that carries credentials", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = vi.fn(async (..._args: FetchCall) => new Response("ok")) as unknown as typeof fetch;
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
installHeadroomTransport({ proxyUrl: "user:secretpass@host:8787" });
await fetch("https://api.anthropic.com/v1/messages", { method: "POST" });
expect(warn).toHaveBeenCalledTimes(1);
const logged = warn.mock.calls.flat().join(" ");
expect(logged).not.toContain("secretpass");
expect(logged).not.toContain("host:8787");
} finally {
globalThis.fetch = originalFetch;
warn.mockRestore();
}
});
});
+29 -2
View File
@@ -219,6 +219,27 @@ function normalizeProxyUrl(proxyUrl: string): URL {
return new URL(proxyUrl);
}
// A proxy URL that does not parse must not break traffic that is not LLM
// traffic: the caller falls through to the original function. Reported once
// per value, not once per request.
const reportedProxyUrls = new Set<string>();
function usableProxyUrl(proxyUrl: string): URL | undefined {
try {
const proxy = normalizeProxyUrl(proxyUrl);
// "user:pass@host:8787" parses with scheme "user:"; only http(s) can be routed to.
if (proxy.protocol !== "http:" && proxy.protocol !== "https:") throw new TypeError("unsupported scheme");
return proxy;
} catch {
if (!reportedProxyUrls.has(proxyUrl)) {
reportedProxyUrls.add(proxyUrl);
// The value is never logged: a malformed URL can still carry user:password@.
console.warn(`headroom: the configured proxy URL is ${proxyUrl === "" ? "empty" : "not a valid http(s) URL"}; requests are not routed`);
}
return undefined;
}
}
function isLoopback(hostname: string): boolean {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
@@ -527,7 +548,10 @@ function wrapRequest(
return Reflect.apply(originalRequest, this, args);
}
const proxy = normalizeProxyUrl(state.proxyUrl);
const proxy = usableProxyUrl(state.proxyUrl);
if (!proxy) {
return Reflect.apply(originalRequest, this, args);
}
const parts = splitNodeArgs(args);
const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts, state.sessionToken);
if (!nextOptions) {
@@ -599,7 +623,10 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
if (!current) {
return state.originalFetch(...args);
}
const proxy = normalizeProxyUrl(current.proxyUrl);
const proxy = usableProxyUrl(current.proxyUrl);
if (!proxy) {
return state.originalFetch(...args);
}
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts, current.sessionToken);
return state.originalFetch(nextInput, nextInit);
};