feat(opencode): exclude hosts from transport plugin routing (#3668)

## Description

The OpenCode transport plugin rewrites every non-loopback HTTP(S)
request to the Headroom proxy, both in the OpenCode process and in every
spawned Node child via the hook-shim. When a provider validates the
client on the wire and rejects the proxy hop (OpenCode Zen free tier,
some enterprise gateways), the only way to keep that provider working is
to unload the plugin, which drops Headroom for every other provider too.

This adds an exclude list to `shouldRoute()`. Hosts come from the
`excludeHosts` plugin option, or from `HEADROOM_OPENCODE_EXCLUDE_HOSTS`
(comma-separated) when the option is absent, with the same
option-over-env precedence `proxyUrl` already uses. An entry matches the
host and all of its subdomains (`example.com`, `.example.com` and
`*.example.com` are equivalent). Excluded requests go straight upstream
with their original URL, init and headers: no `x-headroom-base-url`, no
compression, no telemetry. The effective list is exported to
`process.env` and to spawned child env so the hook-shim copy of the
transport makes the same decision. Default is empty, so nothing changes
for existing installs.

Root cause: `shouldRoute()` (unchanged since #1105) only checked scheme,
loopback and the proxy origin; it had no configuration input at all, and
the child-process shim configures itself purely from env, so any opt-out
has to be env-readable and exported by `withShimEnv`/`installProcessEnv`
or children silently diverge from the parent (#3633 points this out).

Considered and not done here: path-level globs (both reported cases are
host-level; can be layered on later as a separate variable), proxy-side
passthrough (still a proxy hop, which is what the Zen gate rejects), and
a default exclusion for `registry.npmjs.org` (a separate decision; this
keeps zero behavior change by default). The Zen `/responses` bug itself
is #3656 / #3659.

Closes #3657
Refs #3633

Note: #3657 is a feature request and did not yet have a maintainer 👍
when I opened this, so I am keeping it small and happy to change the
surface: drop the plugin option and ship env-only, rename the variable
to #3633's `HEADROOM_OPENCODE_ROUTE_EXCLUDE`, or hold until the surface
is agreed.

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] 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/transport.ts`: `normalizeExcludeHosts` /
`isExcludedHost`; `shouldRoute` takes the list and returns `false` on a
match (fetch, `http`/`https.request`/`get`, and `http2.connect`, which
is now allowed for excluded hosts instead of blocked);
`installHeadroomTransport` resolves `options.excludeHosts ??
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS`; `installProcessEnv` and
`withShimEnv` export the **effective** list through
`withExcludeHostsEnv` — set when non-empty, deleted when empty — so an
explicit `excludeHosts: []` clears a pre-existing variable for the
process and for every spawned child (review finding, second commit).
- `plugins/opencode/src/plugin.ts`: `excludeHosts?: string[]` on
`HeadroomOpenCodePluginOptions`, passed through.
- `plugins/opencode/src/transport.test.ts`: six tests — env var with
subdomain/case/`.`/`*.` forms and non-matching hosts still routed;
option precedence over env; Node `https.request` and `http2.connect` on
excluded hosts; child env propagation (and no variable set when nothing
is excluded); explicit empty override clears a pre-existing variable
in-process, in `process.env`, and in default/custom/stale-carrying child
env; the variable tracks each re-install's resolved list.
- `headroom/providers/opencode/_dist/entry.opencode.js`,
`headroom/providers/opencode/hook-shim/handler.js`: rebuilt with `npm
run build:standalone`.
- `plugins/opencode/README.md`, `docs/content/docs/opencode.mdx`:
document the option, the variable and the matching rule.

## Testing

- [ ] Unit tests pass (`pytest`) — not run in full locally;
`tests/test_providers_opencode_plugin_path.py` and
`tests/test_providers_opencode_config.py` give the same result as `main`
on my Windows checkout (44 passed, 1 pre-existing Windows-only
path-escaping failure in `test_build_launch_env_with_project`). No
Python source changed.
- [ ] Linting passes (`ruff check .`) — no Python changed.
- [ ] Type checking passes (`mypy headroom`) — no Python changed.
- [x] New tests added for new functionality
- [x] Manual testing performed

Plugin CI sequence from `.github/workflows/opencode-plugin.yml`, run
after rebasing onto `main` (`67eb910e`): typecheck, build, test,
standalone build, bundle parity, plus commitlint and `npm audit`.

### Test Output

```text
$ cd plugins/opencode && npm ci && npm run typecheck && npm run build && npm test
found 0 vulnerabilities
typecheck exit=0
 Test Files  2 passed (2)
      Tests  23 passed (23)

$ npm run build:standalone && cmp dist-standalone/entry.opencode.js ../../headroom/providers/opencode/_dist/entry.opencode.js && cmp dist-standalone/hook-shim/handler.js ../../headroom/providers/opencode/hook-shim/handler.js
entry.opencode.js: IDENTICAL
handler.js: IDENTICAL

# the four new tests against unpatched transport.ts (fix stashed, tests kept):
 ❯ src/transport.test.ts (19 tests | 4 failed)
     × keeps HEADROOM_OPENCODE_EXCLUDE_HOSTS hosts and their subdomains off the proxy (#3657)
     × prefers the excludeHosts option over HEADROOM_OPENCODE_EXCLUDE_HOSTS
     × leaves excluded hosts alone for Node https.request and http2.connect
     × propagates excluded hosts into child process env so the hook-shim matches
AssertionError: expected URL { href: 'http://127.0.0.1:8787/v1/responses', ... } to be 'https://opencode.ai/zen/v1/responses'

$ npx commitlint --config .commitlintrc.json --edit <msg>   # exit 0
$ npm audit --package-lock-only --audit-level=low            # found 0 vulnerabilities
```

## Real Behavior Proof

- Environment: Windows 11, Node v24.13.0, plugin built from this branch
(`npm run build` for the in-process check, the committed wheel
`hook-shim/handler.js` from this branch for the child-process check),
fake proxy on `127.0.0.1` recording `x-headroom-base-url`.
`HEADROOM_OPENCODE_EXCLUDE_HOSTS=opencode.ai`.
- Exact command / steps: (1) import `dist/index.js`, install the
transport with `excludeHosts: ["opencode.ai"]`,
`fetch("https://opencode.ai/zen/v1/responses")` then
`fetch("https://api.anthropic.com/v1/messages")`, record what the
original `fetch` received; (2) spawn `node
--import=<hook-shim/handler.js>` with
`HEADROOM_OPENCODE_TRANSPORT_PROXY_URL=<fake proxy>` and the variable
above, `fetch("https://opencode.ai/zen/v1/responses")` from the child,
watch the fake proxy; (3) same two scripts on unpatched `main` as the
control.
- Observed result: (1)
`{"url":"https://opencode.ai/zen/v1/responses","base":null}` then
`{"url":"http://127.0.0.1:8787/v1/messages","base":"https://api.anthropic.com"}`
— excluded host untouched, Anthropic still routed; (2) `child: fetch
resolved status 401 from https://opencode.ai/zen/v1/responses` / `fake
proxy saw: []` — the child went direct to the real host (401 is
opencode.ai answering an unauthenticated request) and the proxy never
saw it; (3) on `main` both scripts route `opencode.ai` to the proxy with
`base: https://opencode.ai`, and on this branch the same happens when
the variable is spelled wrong (`HEADROOM_OPENCODE_ROUTE_EXCLUDE`), i.e.
an unknown variable changes nothing.
- Empty-override check (review finding): parent env
`HEADROOM_OPENCODE_EXCLUDE_HOSTS=api.anthropic.com`, transport installed
with `excludeHosts: []`, a child spawned through the wrapped
`child_process.spawn` preloaded with the committed hook-shim, both fetch
`api.anthropic.com`: on the reviewed head the child inherited
`"api.anthropic.com"` and went direct; on this head `child env var:
undefined` and the fake proxy saw `x-headroom-base-url:
["https://api.anthropic.com","https://api.anthropic.com"]` — parent and
child agree.
- Not tested: a live OpenCode session against the real Zen free-tier
model (I don't have OpenCode Zen credentials); macOS/Linux; Bun-spawned
children (they inherit `process.env`, which `installProcessEnv` now
sets, same path as `NODE_OPTIONS`); the full Python suite (CI).

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: n/a.
- Stable/default behavior changed: no. With no `excludeHosts` option and
no `HEADROOM_OPENCODE_EXCLUDE_HOSTS`, `shouldRoute()` is unchanged and
the variable is never written. Only configured hosts bypass the proxy;
for them `http2.connect` is now allowed instead of throwing.
- Kill switch / disable path: unset the variable / remove the option;
excluded traffic goes back through the proxy on next launch.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this commit (source and the two committed
bundles change together).

## 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
- [x] 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
- [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

Start reading at `shouldRoute()` and `normalizeExcludeHosts()` in
`plugins/opencode/src/transport.ts`, then `installHeadroomTransport` for
the option/env resolution and the two env exports. The bundle diffs are
the same hunks compiled. The one decision I'd most like challenged is
shipping both a plugin option and an env var: the env var is required
regardless (it is the only surface that reaches `headroom wrap
opencode`, which registers the plugin as a bare path, and the hook-shim
in child processes), and the option mirrors the reporter's proposed API;
dropping the option is a six-line change if you'd rather keep one
surface.

Known limits: entries are bare hosts (no scheme, port or path), IDN
entries must be given in punycode, and like
`HEADROOM_OPENCODE_TRANSPORT_PROXY_URL` the exported variable is not
removed from `process.env` on dispose.

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Ayush Kumar Jha
2026-09-24 22:03:28 -05:00
committed by GitHub
co-authored by JD Davis
parent b9ded1ae55
commit 0024b57405
7 changed files with 402 additions and 54 deletions
+14
View File
@@ -69,6 +69,7 @@ The default model is `headroom/claude-sonnet-4-6`. Change it in `opencode.json`
|---|---|
| `OPENCODE_CONFIG_CONTENT` | JSON payload with provider, plugin, and optional local MCP config injected by `wrap` |
| `HEADROOM_PROXY_URL` | Proxy URL passed to Headroom MCP when a non-default port is used, and to the native plugin when configured |
| `HEADROOM_OPENCODE_EXCLUDE_HOSTS` | Comma-separated hosts (and their subdomains) the native plugin sends straight upstream instead of through the proxy, for example `opencode.ai,.corp.internal` |
## Failure Learning
@@ -110,6 +111,15 @@ export default async function plugin(input) {
Use this plugin when OpenCode should intercept provider traffic in-process. Use `headroom wrap opencode` when you want the CLI to manage the proxy, config injection, MCP registration, backups, and unwrap behavior.
The plugin routes every external HTTP(S) request through the proxy. To keep a provider or gateway off the proxy while leaving the plugin loaded, pass `excludeHosts` in the plugin options or set `HEADROOM_OPENCODE_EXCLUDE_HOSTS` before launching OpenCode. An entry matches the host and all of its subdomains; excluded requests are sent as-is, with no compression or telemetry.
```jsonc
// opencode.json
{
"plugin": [["/path/to/headroom/providers/opencode/_dist/entry.opencode.js", { "excludeHosts": ["opencode.ai"] }]]
}
```
## Programmatic Config Helpers
The package also exports helpers for custom integrations:
@@ -149,6 +159,10 @@ Check that `OPENCODE_CONFIG_CONTENT` is set and contains the `provider.headroom`
Set `HEADROOM_PROXY_URL` to the running proxy URL, for example `http://127.0.0.1:8787`.
**One provider rejects requests only while the plugin is loaded.**
Some gateways validate the client on the wire and reject the proxy hop. Exclude that host with `HEADROOM_OPENCODE_EXCLUDE_HOSTS=<host>` (or the `excludeHosts` plugin option); Headroom keeps routing every other provider.
**Provider not found after unwrap.**
If unwrap left the provider configured, run `headroom unwrap opencode` again, or manually restore from `~/.config/opencode/opencode.json.headroom-backup`.
@@ -12489,6 +12489,7 @@ var BASE_URL_HEADER = "x-headroom-base-url";
var ORIGINAL_PATH_HEADER = "x-headroom-original-path";
var PROJECT_HEADER = "x-headroom-project";
var PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
var EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
var STATE_KEY = /* @__PURE__ */ Symbol.for("headroom.opencode.transport");
function getState() {
return globalThis[STATE_KEY];
@@ -12510,17 +12511,26 @@ function withNodeImportOption(existing, shim) {
}
return parts.join(" ");
}
function withShimEnv(env, proxyUrl) {
function withExcludeHostsEnv(env, excludeHosts) {
if (excludeHosts.length > 0) {
env[EXCLUDE_HOSTS_ENV] = excludeHosts.join(",");
} else {
delete env[EXCLUDE_HOSTS_ENV];
}
}
function withShimEnv(env, proxyUrl, excludeHosts) {
const nextEnv = { ...env ?? process.env };
nextEnv[PROXY_ENV] = proxyUrl;
withExcludeHostsEnv(nextEnv, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
nextEnv.NODE_OPTIONS = withNodeImportOption(nextEnv.NODE_OPTIONS, shim);
}
return nextEnv;
}
function installProcessEnv(proxyUrl) {
function installProcessEnv(proxyUrl, excludeHosts) {
process.env[PROXY_ENV] = proxyUrl;
withExcludeHostsEnv(process.env, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
process.env.NODE_OPTIONS = withNodeImportOption(process.env.NODE_OPTIONS, shim);
@@ -12529,11 +12539,11 @@ function installProcessEnv(proxyUrl) {
function isOptions(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof URL);
}
function injectOptionsEnv(args, optionIndex, proxyUrl) {
function injectOptionsEnv(args, optionIndex, state) {
const nextArgs = [...args];
const callback = typeof nextArgs.at(-1) === "function" ? nextArgs.pop() : void 0;
const existing = isOptions(nextArgs[optionIndex]) ? { ...nextArgs[optionIndex] } : {};
existing.env = withShimEnv(existing.env, proxyUrl);
existing.env = withShimEnv(existing.env, state.proxyUrl, state.excludeHosts);
if (isOptions(nextArgs[optionIndex])) {
nextArgs[optionIndex] = existing;
} else {
@@ -12551,7 +12561,7 @@ function wrapSpawn(originalSpawn) {
return Reflect.apply(originalSpawn, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state));
};
}
function wrapExec(originalExec) {
@@ -12560,7 +12570,7 @@ function wrapExec(originalExec) {
if (!state) {
return Reflect.apply(originalExec, this, args);
}
return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state.proxyUrl));
return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state));
};
}
function wrapExecFile(originalExecFile) {
@@ -12570,7 +12580,7 @@ function wrapExecFile(originalExecFile) {
return Reflect.apply(originalExecFile, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state));
};
}
function wrapFork(originalFork) {
@@ -12580,7 +12590,7 @@ function wrapFork(originalFork) {
return Reflect.apply(originalFork, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state));
};
}
function normalizeProxyUrl(proxyUrl) {
@@ -12590,7 +12600,21 @@ function isLoopback(hostname3) {
const normalized = hostname3.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
}
function shouldRoute(url2, proxy) {
function normalizeExcludeHosts(entries) {
const hosts = /* @__PURE__ */ new Set();
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
const host = String(entry).trim().toLowerCase().replace(/^(\*\.|\.)/, "");
if (host) {
hosts.add(host);
}
}
return [...hosts];
}
function isExcludedHost(hostname3, excludeHosts) {
const normalized = hostname3.toLowerCase().replace(/^\[|\]$/g, "");
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
function shouldRoute(url2, proxy, excludeHosts) {
if (url2.protocol !== "http:" && url2.protocol !== "https:") {
return false;
}
@@ -12600,6 +12624,9 @@ function shouldRoute(url2, proxy) {
if (url2.origin === proxy.origin) {
return false;
}
if (isExcludedHost(url2.hostname, excludeHosts)) {
return false;
}
return true;
}
function routedUrl(upstream, proxy) {
@@ -12653,9 +12680,9 @@ function mergeFetchHeaders(input, init, upstream, originalPath = void 0, project
}
return headers;
}
function withRoutedFetchInput(input, init, proxy, project) {
function withRoutedFetchInput(input, init, proxy, project, excludeHosts) {
const upstream = requestUrl(input);
if (!shouldRoute(upstream, proxy)) {
if (!shouldRoute(upstream, proxy, excludeHosts)) {
return [input, init];
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(upstream, proxy);
@@ -12723,8 +12750,8 @@ function headersForNodeRequest(options, upstream, originalPath, project) {
});
return result;
}
function routedNodeOptions(parts, proxy, project) {
if (!parts.url || !shouldRoute(parts.url, proxy)) {
function routedNodeOptions(parts, proxy, project, excludeHosts) {
if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts)) {
return void 0;
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(parts.url, proxy);
@@ -12765,7 +12792,7 @@ function wrapRequest(originalHttpRequest, originalHttpsRequest, originalRequest)
}
const proxy = normalizeProxyUrl(state.proxyUrl);
const parts = splitNodeArgs(args);
const nextOptions = routedNodeOptions(parts, proxy, state.project);
const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts);
if (!nextOptions) {
return Reflect.apply(originalRequest, this, args);
}
@@ -12787,7 +12814,7 @@ function wrapHttp2Connect(originalConnect) {
if (state) {
const proxy = normalizeProxyUrl(state.proxyUrl);
const upstream = authority instanceof URL ? authority : new URL(String(authority));
if (shouldRoute(upstream, proxy)) {
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.`
);
@@ -12797,19 +12824,22 @@ function wrapHttp2Connect(originalConnect) {
};
}
function installHeadroomTransport(options) {
const excludeHosts = normalizeExcludeHosts(options.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
const existing = getState();
if (existing) {
existing.refs += 1;
existing.proxyUrl = options.proxyUrl;
existing.project = options.project;
existing.excludeHosts = excludeHosts;
existing.debug = Boolean(options.debug);
installProcessEnv(options.proxyUrl);
installProcessEnv(options.proxyUrl, excludeHosts);
return () => uninstallHeadroomTransport();
}
const state = {
refs: 1,
proxyUrl: options.proxyUrl,
project: options.project,
excludeHosts,
debug: Boolean(options.debug),
originalFetch: globalThis.fetch,
originalHttpRequest: http.request,
@@ -12823,14 +12853,14 @@ function installHeadroomTransport(options) {
originalChildFork: childProcess.fork
};
setState(state);
installProcessEnv(options.proxyUrl);
installProcessEnv(options.proxyUrl, excludeHosts);
globalThis.fetch = async (...args) => {
const current = getState();
if (!current) {
return state.originalFetch(...args);
}
const proxy = normalizeProxyUrl(current.proxyUrl);
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project);
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts);
return state.originalFetch(nextInput, nextInit);
};
http.request = wrapRequest(state.originalHttpRequest, state.originalHttpsRequest, state.originalHttpRequest);
@@ -12885,6 +12915,7 @@ var HeadroomPlugin = async (input, options = {}) => {
const uninstallTransport = installHeadroomTransport({
proxyUrl,
project,
excludeHosts: pluginOptions.excludeHosts,
debug: pluginOptions.debug
});
return {
@@ -10,6 +10,7 @@ var BASE_URL_HEADER = "x-headroom-base-url";
var ORIGINAL_PATH_HEADER = "x-headroom-original-path";
var PROJECT_HEADER = "x-headroom-project";
var PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
var EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
var STATE_KEY = /* @__PURE__ */ Symbol.for("headroom.opencode.transport");
function getState() {
return globalThis[STATE_KEY];
@@ -31,17 +32,26 @@ function withNodeImportOption(existing, shim) {
}
return parts.join(" ");
}
function withShimEnv(env, proxyUrl2) {
function withExcludeHostsEnv(env, excludeHosts) {
if (excludeHosts.length > 0) {
env[EXCLUDE_HOSTS_ENV] = excludeHosts.join(",");
} else {
delete env[EXCLUDE_HOSTS_ENV];
}
}
function withShimEnv(env, proxyUrl2, excludeHosts) {
const nextEnv = { ...env ?? process.env };
nextEnv[PROXY_ENV] = proxyUrl2;
withExcludeHostsEnv(nextEnv, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
nextEnv.NODE_OPTIONS = withNodeImportOption(nextEnv.NODE_OPTIONS, shim);
}
return nextEnv;
}
function installProcessEnv(proxyUrl2) {
function installProcessEnv(proxyUrl2, excludeHosts) {
process.env[PROXY_ENV] = proxyUrl2;
withExcludeHostsEnv(process.env, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
process.env.NODE_OPTIONS = withNodeImportOption(process.env.NODE_OPTIONS, shim);
@@ -50,11 +60,11 @@ function installProcessEnv(proxyUrl2) {
function isOptions(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof URL);
}
function injectOptionsEnv(args, optionIndex, proxyUrl2) {
function injectOptionsEnv(args, optionIndex, state) {
const nextArgs = [...args];
const callback = typeof nextArgs.at(-1) === "function" ? nextArgs.pop() : void 0;
const existing = isOptions(nextArgs[optionIndex]) ? { ...nextArgs[optionIndex] } : {};
existing.env = withShimEnv(existing.env, proxyUrl2);
existing.env = withShimEnv(existing.env, state.proxyUrl, state.excludeHosts);
if (isOptions(nextArgs[optionIndex])) {
nextArgs[optionIndex] = existing;
} else {
@@ -72,7 +82,7 @@ function wrapSpawn(originalSpawn) {
return Reflect.apply(originalSpawn, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state));
};
}
function wrapExec(originalExec) {
@@ -81,7 +91,7 @@ function wrapExec(originalExec) {
if (!state) {
return Reflect.apply(originalExec, this, args);
}
return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state.proxyUrl));
return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state));
};
}
function wrapExecFile(originalExecFile) {
@@ -91,7 +101,7 @@ function wrapExecFile(originalExecFile) {
return Reflect.apply(originalExecFile, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state));
};
}
function wrapFork(originalFork) {
@@ -101,7 +111,7 @@ function wrapFork(originalFork) {
return Reflect.apply(originalFork, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state));
};
}
function normalizeProxyUrl(proxyUrl2) {
@@ -111,7 +121,21 @@ function isLoopback(hostname) {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
}
function shouldRoute(url, proxy) {
function normalizeExcludeHosts(entries) {
const hosts = /* @__PURE__ */ new Set();
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
const host = String(entry).trim().toLowerCase().replace(/^(\*\.|\.)/, "");
if (host) {
hosts.add(host);
}
}
return [...hosts];
}
function isExcludedHost(hostname, excludeHosts) {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
function shouldRoute(url, proxy, excludeHosts) {
if (url.protocol !== "http:" && url.protocol !== "https:") {
return false;
}
@@ -121,6 +145,9 @@ function shouldRoute(url, proxy) {
if (url.origin === proxy.origin) {
return false;
}
if (isExcludedHost(url.hostname, excludeHosts)) {
return false;
}
return true;
}
function routedUrl(upstream, proxy) {
@@ -174,9 +201,9 @@ function mergeFetchHeaders(input, init, upstream, originalPath = void 0, project
}
return headers;
}
function withRoutedFetchInput(input, init, proxy, project) {
function withRoutedFetchInput(input, init, proxy, project, excludeHosts) {
const upstream = requestUrl(input);
if (!shouldRoute(upstream, proxy)) {
if (!shouldRoute(upstream, proxy, excludeHosts)) {
return [input, init];
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(upstream, proxy);
@@ -244,8 +271,8 @@ function headersForNodeRequest(options, upstream, originalPath, project) {
});
return result;
}
function routedNodeOptions(parts, proxy, project) {
if (!parts.url || !shouldRoute(parts.url, proxy)) {
function routedNodeOptions(parts, proxy, project, excludeHosts) {
if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts)) {
return void 0;
}
const { url: nextUrl, originalPath } = routedUrlForOpenCode(parts.url, proxy);
@@ -286,7 +313,7 @@ function wrapRequest(originalHttpRequest, originalHttpsRequest, originalRequest)
}
const proxy = normalizeProxyUrl(state.proxyUrl);
const parts = splitNodeArgs(args);
const nextOptions = routedNodeOptions(parts, proxy, state.project);
const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts);
if (!nextOptions) {
return Reflect.apply(originalRequest, this, args);
}
@@ -308,7 +335,7 @@ function wrapHttp2Connect(originalConnect) {
if (state) {
const proxy = normalizeProxyUrl(state.proxyUrl);
const upstream = authority instanceof URL ? authority : new URL(String(authority));
if (shouldRoute(upstream, proxy)) {
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.`
);
@@ -318,19 +345,22 @@ function wrapHttp2Connect(originalConnect) {
};
}
function installHeadroomTransport(options) {
const excludeHosts = normalizeExcludeHosts(options.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
const existing = getState();
if (existing) {
existing.refs += 1;
existing.proxyUrl = options.proxyUrl;
existing.project = options.project;
existing.excludeHosts = excludeHosts;
existing.debug = Boolean(options.debug);
installProcessEnv(options.proxyUrl);
installProcessEnv(options.proxyUrl, excludeHosts);
return () => uninstallHeadroomTransport();
}
const state = {
refs: 1,
proxyUrl: options.proxyUrl,
project: options.project,
excludeHosts,
debug: Boolean(options.debug),
originalFetch: globalThis.fetch,
originalHttpRequest: http.request,
@@ -344,14 +374,14 @@ function installHeadroomTransport(options) {
originalChildFork: childProcess.fork
};
setState(state);
installProcessEnv(options.proxyUrl);
installProcessEnv(options.proxyUrl, excludeHosts);
globalThis.fetch = async (...args) => {
const current = getState();
if (!current) {
return state.originalFetch(...args);
}
const proxy = normalizeProxyUrl(current.proxyUrl);
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project);
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts);
return state.originalFetch(nextInput, nextInit);
};
http.request = wrapRequest(state.originalHttpRequest, state.originalHttpsRequest, state.originalHttpRequest);
+17
View File
@@ -53,6 +53,22 @@ export default async function plugin(input) {
- exposes the `headroom_retrieve` tool.
- publishes `HEADROOM_PROXY_URL` in the plugin output env.
- defaults to `http://127.0.0.1:8787` when no proxy URL is supplied.
- skips routing for hosts listed in `excludeHosts` (or `HEADROOM_OPENCODE_EXCLUDE_HOSTS`); those requests go straight upstream with no compression or telemetry.
To keep a provider off the proxy, list its host. An entry matches the host and all of its subdomains, and `.example.com` / `*.example.com` are accepted as spellings of `example.com`:
```jsonc
// opencode.json
{
"plugin": [["/path/to/headroom/providers/opencode/_dist/entry.opencode.js", { "excludeHosts": ["opencode.ai"] }]]
}
```
or, for `headroom wrap opencode` and spawned Node child processes, set the environment variable before launching:
```bash
HEADROOM_OPENCODE_EXCLUDE_HOSTS="opencode.ai,.corp.internal" headroom wrap opencode
```
## Retrieve Tool
@@ -100,6 +116,7 @@ The provider config exposes these as `headroom/<model>` and defaults to `headroo
| Variable | Used by | Description |
|---|---|---|
| `HEADROOM_PROXY_URL` | Native plugin | Proxy URL used by `HeadroomPlugin` |
| `HEADROOM_OPENCODE_EXCLUDE_HOSTS` | Native plugin | Comma-separated hosts (and their subdomains) that bypass the proxy; the `excludeHosts` plugin option takes precedence |
| `OPENCODE_CONFIG_CONTENT` | OpenCode wrapper | Generated OpenCode provider, model, and MCP config |
## License
+2
View File
@@ -8,6 +8,7 @@ import { installHeadroomTransport } from "./transport.js";
export interface HeadroomOpenCodePluginOptions {
proxyUrl?: string;
project?: string;
excludeHosts?: string[];
backend?: string;
debug?: boolean;
}
@@ -36,6 +37,7 @@ export const HeadroomPlugin: Plugin = async (input, options = {}) => {
const uninstallTransport = installHeadroomTransport({
proxyUrl,
project,
excludeHosts: pluginOptions.excludeHosts,
debug: pluginOptions.debug,
});
+195
View File
@@ -438,6 +438,201 @@ describe("Headroom OpenCode transport", () => {
await proxy.close();
});
it("keeps HEADROOM_OPENCODE_EXCLUDE_HOSTS hosts and their subdomains off the proxy (#3657)", async () => {
const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
try {
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = " opencode.ai, .corp.internal ,, *.Gateway.Example ";
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
const init = { method: "POST", headers: { authorization: "Bearer test" } };
await fetch("https://opencode.ai/zen/v1/responses", init);
await fetch("https://API.OpenCode.AI/zen/v1/chat/completions", init);
await fetch("https://llm.corp.internal/v1/chat/completions", init);
await fetch("https://gateway.example/v1/responses", init);
await fetch("https://notopencode.ai/v1/responses", init);
await fetch("https://api.anthropic.com/v1/messages", init);
for (const index of [0, 1, 2, 3]) {
expect(typeof fetchMock.mock.calls[index][0]).toBe("string");
expect(fetchMock.mock.calls[index][1]).toBe(init);
}
expect(fetchMock.mock.calls[0][0]).toBe("https://opencode.ai/zen/v1/responses");
expect(fetchMock.mock.calls[4][0]).toEqual(new URL("http://127.0.0.1:8787/v1/responses"));
expect(new Headers(fetchMock.mock.calls[4][1]?.headers).get("x-headroom-base-url")).toBe(
"https://notopencode.ai",
);
expect(fetchMock.mock.calls[5][0]).toEqual(new URL("http://127.0.0.1:8787/v1/messages"));
expect(new Headers(fetchMock.mock.calls[5][1]?.headers).get("x-headroom-base-url")).toBe(
"https://api.anthropic.com",
);
} finally {
globalThis.fetch = originalFetch;
if (originalExclude === undefined) {
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
} else {
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
}
}
});
it("prefers the excludeHosts option over HEADROOM_OPENCODE_EXCLUDE_HOSTS", async () => {
const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
try {
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = "api.anthropic.com";
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["opencode.ai"] });
await fetch("https://opencode.ai/zen/v1/responses", { method: "POST" });
await fetch("https://api.anthropic.com/v1/messages", { method: "POST" });
expect(fetchMock.mock.calls[0][0]).toBe("https://opencode.ai/zen/v1/responses");
expect(fetchMock.mock.calls[1][0]).toEqual(new URL("http://127.0.0.1:8787/v1/messages"));
expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("opencode.ai");
} finally {
globalThis.fetch = originalFetch;
if (originalExclude === undefined) {
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
} else {
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
}
}
});
it("leaves excluded hosts alone for Node https.request and http2.connect", () => {
const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
const fakeRequest = { on: vi.fn(), end: vi.fn() };
const requestSpy = vi.spyOn(https, "request").mockImplementation(() => fakeRequest as never);
const connectSpy = vi.spyOn(http2, "connect").mockImplementation(() => ({}) as never);
try {
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["opencode.ai"] });
const options = { method: "POST", headers: { authorization: "Bearer test" } };
expect(https.request("https://opencode.ai/zen/v1/responses", options)).toBe(fakeRequest);
expect(requestSpy).toHaveBeenCalledWith("https://opencode.ai/zen/v1/responses", options);
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/);
} finally {
uninstallHeadroomTransport();
if (originalExclude === undefined) {
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
} else {
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
}
}
});
it("propagates excluded hosts into child process env so the hook-shim matches", () => {
const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
const originalSpawn = childProcess.spawn;
const spawnMock = vi.fn(() => ({ on: vi.fn(), kill: vi.fn(), pid: 123 }));
childProcess.spawn = spawnMock as unknown as typeof childProcess.spawn;
try {
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
childProcess.spawn("node", ["agent.js"], { env: { PATH: "/bin" } });
uninstallHeadroomTransport();
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["*.opencode.ai", "corp.internal"] });
childProcess.spawn("node", ["agent.js"], { env: { PATH: "/bin" } });
const plain = (spawnMock.mock.calls[0] as unknown[])[2] as { env: NodeJS.ProcessEnv };
const excluded = (spawnMock.mock.calls[1] as unknown[])[2] as { env: NodeJS.ProcessEnv };
expect(plain.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBeUndefined();
expect(excluded.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("opencode.ai,corp.internal");
expect(excluded.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
} finally {
uninstallHeadroomTransport();
childProcess.spawn = originalSpawn;
if (originalExclude === undefined) {
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
} else {
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
}
}
});
it("clears a pre-existing HEADROOM_OPENCODE_EXCLUDE_HOSTS when excludeHosts is explicitly empty", async () => {
const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
const originalFetch = globalThis.fetch;
const originalSpawn = childProcess.spawn;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
const spawnMock = vi.fn(() => ({ on: vi.fn(), kill: vi.fn(), pid: 123 }));
childProcess.spawn = spawnMock as unknown as typeof childProcess.spawn;
try {
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = "api.anthropic.com";
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: [] });
// The option wins in-process: the host is routed, not excluded.
await fetch("https://api.anthropic.com/v1/messages", { method: "POST" });
expect(fetchMock.mock.calls[0][0]).toEqual(new URL("http://127.0.0.1:8787/v1/messages"));
// ...and the exported variable mirrors that, so the hook-shim in a child
// (default env, custom env, or a custom env carrying the stale value)
// resolves the same empty list instead of the pre-existing one.
expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBeUndefined();
childProcess.spawn("node", ["agent.js"]);
childProcess.spawn("node", ["agent.js"], { env: { PATH: "/bin" } });
childProcess.spawn("node", ["agent.js"], {
env: { PATH: "/bin", HEADROOM_OPENCODE_EXCLUDE_HOSTS: "api.anthropic.com" },
});
for (const call of spawnMock.mock.calls as unknown[][]) {
const options = call[2] as { env: NodeJS.ProcessEnv };
expect(options.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBeUndefined();
expect(options.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
}
} finally {
globalThis.fetch = originalFetch;
childProcess.spawn = originalSpawn;
if (originalExclude === undefined) {
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
} else {
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
}
}
});
it("keeps the exported variable in step with each re-install's resolved list", () => {
const originalExclude = process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
try {
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
const first = installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["opencode.ai"] });
expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("opencode.ai");
// A second install (refs = 2) that resolves to an empty list clears it...
const second = installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: [] });
expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBeUndefined();
// ...and one that resolves to a list sets it again.
const third = installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["corp.internal"] });
expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("corp.internal");
third();
second();
first();
} finally {
uninstallHeadroomTransport();
if (originalExclude === undefined) {
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
} else {
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = originalExclude;
}
}
});
it("restores patched transports only after the final disposer", () => {
const originalFetch = globalThis.fetch;
const originalHttpRequest = http.request;
+77 -18
View File
@@ -11,6 +11,7 @@ const BASE_URL_HEADER = "x-headroom-base-url";
const ORIGINAL_PATH_HEADER = "x-headroom-original-path";
const PROJECT_HEADER = "x-headroom-project";
const PROXY_ENV = "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL";
const EXCLUDE_HOSTS_ENV = "HEADROOM_OPENCODE_EXCLUDE_HOSTS";
const STATE_KEY = Symbol.for("headroom.opencode.transport");
type FetchArgs = Parameters<typeof fetch>;
@@ -27,6 +28,7 @@ type ChildFork = typeof childProcess.fork;
interface InstallOptions {
proxyUrl: string;
project?: string;
excludeHosts?: string[];
debug?: boolean;
}
@@ -34,6 +36,7 @@ interface TransportState {
refs: number;
proxyUrl: string;
project: string | undefined;
excludeHosts: string[];
debug: boolean;
originalFetch: typeof fetch;
originalHttpRequest: HttpRequest;
@@ -87,9 +90,26 @@ function withNodeImportOption(existing: string | undefined, shim: string): strin
return parts.join(" ");
}
function withShimEnv(env: NodeJS.ProcessEnv | Record<string, unknown> | undefined, proxyUrl: string): NodeJS.ProcessEnv {
// The exported variable mirrors the EFFECTIVE list, not merely a non-empty
// one: an explicit `excludeHosts: []` overrides a pre-existing variable for
// this process, so a child that inherited the stale value would bypass hosts
// the parent routes. Delete it when the resolved list is empty.
function withExcludeHostsEnv(env: NodeJS.ProcessEnv, excludeHosts: string[]): void {
if (excludeHosts.length > 0) {
env[EXCLUDE_HOSTS_ENV] = excludeHosts.join(",");
} else {
delete env[EXCLUDE_HOSTS_ENV];
}
}
function withShimEnv(
env: NodeJS.ProcessEnv | Record<string, unknown> | undefined,
proxyUrl: string,
excludeHosts: string[],
): NodeJS.ProcessEnv {
const nextEnv = { ...(env ?? process.env) } as NodeJS.ProcessEnv;
nextEnv[PROXY_ENV] = proxyUrl;
withExcludeHostsEnv(nextEnv, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
nextEnv.NODE_OPTIONS = withNodeImportOption(nextEnv.NODE_OPTIONS, shim);
@@ -97,8 +117,9 @@ function withShimEnv(env: NodeJS.ProcessEnv | Record<string, unknown> | undefine
return nextEnv;
}
function installProcessEnv(proxyUrl: string): void {
function installProcessEnv(proxyUrl: string, excludeHosts: string[]): void {
process.env[PROXY_ENV] = proxyUrl;
withExcludeHostsEnv(process.env, excludeHosts);
const shim = shimImportSpecifier();
if (shim) {
process.env.NODE_OPTIONS = withNodeImportOption(process.env.NODE_OPTIONS, shim);
@@ -109,11 +130,11 @@ function isOptions(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value) && !(value instanceof URL);
}
function injectOptionsEnv(args: unknown[], optionIndex: number, proxyUrl: string): unknown[] {
function injectOptionsEnv(args: unknown[], optionIndex: number, state: TransportState): unknown[] {
const nextArgs = [...args];
const callback = typeof nextArgs.at(-1) === "function" ? nextArgs.pop() : undefined;
const existing = isOptions(nextArgs[optionIndex]) ? { ...(nextArgs[optionIndex] as Record<string, unknown>) } : {};
existing.env = withShimEnv(existing.env as NodeJS.ProcessEnv | undefined, proxyUrl);
existing.env = withShimEnv(existing.env as NodeJS.ProcessEnv | undefined, state.proxyUrl, state.excludeHosts);
if (isOptions(nextArgs[optionIndex])) {
nextArgs[optionIndex] = existing;
@@ -134,7 +155,7 @@ function wrapSpawn(originalSpawn: ChildSpawn): ChildSpawn {
return Reflect.apply(originalSpawn, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state));
} as ChildSpawn;
}
@@ -144,7 +165,7 @@ function wrapExec(originalExec: ChildExec): ChildExec {
if (!state) {
return Reflect.apply(originalExec, this, args);
}
return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state.proxyUrl));
return Reflect.apply(originalExec, this, injectOptionsEnv(args, 1, state));
} as ChildExec;
}
@@ -155,7 +176,7 @@ function wrapExecFile(originalExecFile: ChildExecFile): ChildExecFile {
return Reflect.apply(originalExecFile, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state));
} as ChildExecFile;
}
@@ -166,7 +187,7 @@ function wrapFork(originalFork: ChildFork): ChildFork {
return Reflect.apply(originalFork, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state.proxyUrl));
return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state));
} as ChildFork;
}
@@ -179,7 +200,28 @@ function isLoopback(hostname: string): boolean {
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
}
function shouldRoute(url: URL, proxy: URL): boolean {
// "example.com", ".example.com" and "*.example.com" all mean the host itself
// plus every subdomain. Entries are bare hosts: no scheme, port, or path. A
// string is the comma-separated env form; plugin options arrive from untyped
// JSON, so a lone string there is treated the same way instead of iterated
// character by character.
function normalizeExcludeHosts(entries: string | Iterable<unknown>): string[] {
const hosts = new Set<string>();
for (const entry of typeof entries === "string" ? entries.split(",") : entries) {
const host = String(entry).trim().toLowerCase().replace(/^(\*\.|\.)/, "");
if (host) {
hosts.add(host);
}
}
return [...hosts];
}
function isExcludedHost(hostname: string, excludeHosts: string[]): boolean {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
function shouldRoute(url: URL, proxy: URL, excludeHosts: string[]): boolean {
if (url.protocol !== "http:" && url.protocol !== "https:") {
return false;
}
@@ -189,6 +231,9 @@ function shouldRoute(url: URL, proxy: URL): boolean {
if (url.origin === proxy.origin) {
return false;
}
if (isExcludedHost(url.hostname, excludeHosts)) {
return false;
}
return true;
}
@@ -255,9 +300,15 @@ function mergeFetchHeaders(
return headers;
}
function withRoutedFetchInput(input: RequestInfo | URL, init: RequestInit | undefined, proxy: URL, project: string | undefined): FetchArgs {
function withRoutedFetchInput(
input: RequestInfo | URL,
init: RequestInit | undefined,
proxy: URL,
project: string | undefined,
excludeHosts: string[],
): FetchArgs {
const upstream = requestUrl(input);
if (!shouldRoute(upstream, proxy)) {
if (!shouldRoute(upstream, proxy, excludeHosts)) {
return [input, init];
}
@@ -340,8 +391,13 @@ function headersForNodeRequest(
return result;
}
function routedNodeOptions(parts: NodeRequestParts, proxy: URL, project: string | undefined): Record<string, unknown> | undefined {
if (!parts.url || !shouldRoute(parts.url, proxy)) {
function routedNodeOptions(
parts: NodeRequestParts,
proxy: URL,
project: string | undefined,
excludeHosts: string[],
): Record<string, unknown> | undefined {
if (!parts.url || !shouldRoute(parts.url, proxy, excludeHosts)) {
return undefined;
}
@@ -390,7 +446,7 @@ function wrapRequest(
const proxy = normalizeProxyUrl(state.proxyUrl);
const parts = splitNodeArgs(args);
const nextOptions = routedNodeOptions(parts, proxy, state.project);
const nextOptions = routedNodeOptions(parts, proxy, state.project, state.excludeHosts);
if (!nextOptions) {
return Reflect.apply(originalRequest, this, args);
}
@@ -415,7 +471,7 @@ function wrapHttp2Connect(originalConnect: Http2Connect): Http2Connect {
if (state) {
const proxy = normalizeProxyUrl(state.proxyUrl);
const upstream = authority instanceof URL ? authority : new URL(String(authority));
if (shouldRoute(upstream, proxy)) {
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.",
@@ -427,13 +483,15 @@ function wrapHttp2Connect(originalConnect: Http2Connect): Http2Connect {
}
export function installHeadroomTransport(options: InstallOptions): () => void {
const excludeHosts = normalizeExcludeHosts(options.excludeHosts ?? process.env[EXCLUDE_HOSTS_ENV] ?? "");
const existing = getState();
if (existing) {
existing.refs += 1;
existing.proxyUrl = options.proxyUrl;
existing.project = options.project;
existing.excludeHosts = excludeHosts;
existing.debug = Boolean(options.debug);
installProcessEnv(options.proxyUrl);
installProcessEnv(options.proxyUrl, excludeHosts);
return () => uninstallHeadroomTransport();
}
@@ -441,6 +499,7 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
refs: 1,
proxyUrl: options.proxyUrl,
project: options.project,
excludeHosts,
debug: Boolean(options.debug),
originalFetch: globalThis.fetch,
originalHttpRequest: http.request,
@@ -455,14 +514,14 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
};
setState(state);
installProcessEnv(options.proxyUrl);
installProcessEnv(options.proxyUrl, excludeHosts);
globalThis.fetch = async (...args: FetchArgs) => {
const current = getState();
if (!current) {
return state.originalFetch(...args);
}
const proxy = normalizeProxyUrl(current.proxyUrl);
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project);
const [nextInput, nextInit] = withRoutedFetchInput(args[0], args[1], proxy, current.project, current.excludeHosts);
return state.originalFetch(nextInput, nextInit);
};