Files
headroom/plugins/opencode/scripts/live-proof-4781.mjs
ParideboyandJerrettDavis 87c12931fb fix(opencode): stop routing a host's bare /messages or /responses to the proxy (#4781) (#4791)
## Description

A `POST` whose path ends in a wire endpoint but that sits at a host's
origin root (`/messages`, `/responses`, `/chat/completions`) is no
longer routed to the proxy unless that origin is a configured provider
base URL.

Closes #4781.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `plugins/opencode/src/transport.ts` — `hasWireRootBefore` no longer
treats "no segment before the endpoint" as a wire root, so a bare
`/messages` at an unknown host goes direct.
- `plugins/opencode/src/transport.test.ts` — the bare-endpoint
assertions from #4758 move into a #4781 case that pins both directions:
direct by default, routed once the base is registered; the #4758 case
keeps the prefixes that still route.
- `plugins/opencode/README.md` — states the actual routing rule, and the
two shapes that still route without a configured base.
- `headroom/providers/opencode/_dist/index.js`,
`headroom/providers/opencode/hook-shim/handler.js` — rebuilt, since the
`opencode-plugin` gate compares bytes against `dist-standalone`.
- `plugins/opencode/scripts/live-proof-4781.mjs` — the live proof below,
committed so it can be rerun.

## Why

#4758 stopped a suffix match from routing non-LLM hosts, but kept bare
endpoints routable "because compatible gateways use those paths". That
left exactly one non-LLM shape still leaking: `POST
https://rest.messagebird.com/messages` with `Authorization: AccessKey
...` went to the proxy, carrying a non-LLM credential (#4781).

Becoming the bare path is not evidence of a provider — it is equally the
shape of a messaging API. A provider mounted at an origin root is still
routed, because its base URL *is* a configured wire root
(`isConfiguredWireRoot` matches every path on that origin when the base
path is empty), which is how OpenCode reports
`provider.<id>.options.baseURL`.

```ts
return (
  last !== undefined &&
  (isVersionSegment(last) || IMMEDIATE_WIRE_ROOTS.has(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s)))
);
```

Everything else is untouched: version prefixes (`/v1`, `/v1beta`,
`/v4`), immediate `api`, named roots (`backend-api`, `codex`, `openai`,
`anthropic`, `zen`), Gemini colon actions, configured bases,
`excludeHosts`, and the method gate.

## Testing

- [x] New tests added for new functionality
- [x] Manual testing performed

`plugins/opencode` is a TypeScript package, so its gates are npm scripts
rather than `pytest` / `ruff` / `mypy`; `npm audit` and the rest run in
the repo's own CI.

### Test Output

```text
> vitest run
Test Files  4 passed (4)
     Tests  80 passed (80)

> node node_modules/@typescript/native/bin/tsc --noEmit
(clean, no output)

> node scripts/live-proof-4781.mjs
=== decisions (real sockets, real fetch, real built plugin) ===
PASS  MessageBird-shaped  POST /messages             -> left alone
PASS  MessageBird batches  POST /messages/batches    -> left alone
PASS  LLM control         POST /v1/messages          -> REROUTED to proxy
PASS  LLM control         POST /v1/chat/completions  -> REROUTED to proxy

=== what reached the proxy ===
  POST /v1/messages  x-headroom-base-url=http://localtest.me:8899  original-path=null
  POST /v1/chat/completions  x-headroom-base-url=http://localtest.me:8899  original-path=/v1/chat/completions

=== MessageBird-shaped requests that reached the proxy: 0 ===
=== what reached the upstream directly ===
  POST /messages  auth=AccessKey FAKE-TEST-VALUE  (no proxy headers: true)
  POST /messages/batches  auth=AccessKey FAKE-TEST-VALUE  (no proxy headers: true)

ALL CASES PASS
```

Before the fix, same script, source reverted to `HEAD~1` and the bundle
rebuilt:

```text
=== decisions (real sockets, real fetch, real built plugin) ===
FAIL  MessageBird-shaped  POST /messages             -> REROUTED to proxy
PASS  MessageBird batches  POST /messages/batches    -> left alone
PASS  LLM control         POST /v1/messages          -> REROUTED to proxy
PASS  LLM control         POST /v1/chat/completions  -> REROUTED to proxy

=== what reached the proxy ===
  POST /messages  x-headroom-base-url=http://localtest.me:8899  original-path=null
```

Reverting only `src/transport.ts` also fails the unit test (`1 failed |
79 passed`), satisfying "a test that fails before your fix and passes
after".

## Real Behavior Proof

- Environment: Windows 11 (win32), Node v26.10.0, this branch of
`plugins/opencode`, committed wheel bundle
`headroom/providers/opencode/_dist/index.js` loaded via
`plugin.server(...)` as `headroom wrap opencode` does; upstream and
proxy are local HTTP fixtures on real TCP sockets and `globalThis.fetch`
is Node's undici, not a stub.
- Exact command / steps: `cd plugins/opencode && npm ci && npm run
build:standalone && node scripts/live-proof-4781.mjs`, which POSTs a
MessageBird-shaped SMS payload and two LLM control requests to
`http://localtest.me:8899` (resolves to 127.0.0.1 but is not a loopback
spelling, so traffic really leaves the process) and records which server
received each one.
- Observed result: after the patch `POST /messages` and `POST
/messages/batches` reach the upstream directly with no
`x-headroom-base-url` header and the proxy receives zero
MessageBird-shaped requests, while `/v1/messages` and
`/v1/chat/completions` still reach the proxy with the upstream origin
header; with `src/transport.ts` reverted to `HEAD~1` the same run
reroutes `POST /messages` to the proxy, reproducing the reported leak
over a real socket (full output in `Testing` → `Test Output`).
- Not tested: a real MessageBird account and the real
`rest.messagebird.com` host, since the payload and `AccessKey` are fake
and routing is decided before DNS; the proxy's handling of an SMS body,
which never arrives after this change; and a live OpenCode host process,
since the fixture drives the plugin's own `server()` entry rather than
an OpenCode session.

## Runtime Rollout Safety

- Rollout-managed feature(s): none, no feature flag is involved.
- Minimum rollout channel: next released `headroom-opencode` / wheel.
- Stable/default behavior changed: yes, deliberately — a `POST` to
`/messages`, `/responses` or `/chat/completions` at a host's origin root
now goes direct unless that origin is a configured provider base URL;
users whose gateway is configured via `provider.<id>.options.baseURL`
are unaffected.
- Kill switch / disable path: `excludeHosts` /
`HEADROOM_OPENCODE_EXCLUDE_HOSTS` forces a host direct, and configuring
the base URL or listing it in `wireRoots` forces a bare-path provider
through the proxy.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert the commits; the transport and the committed
bundle revert 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

## Additional Notes

Residual, deliberately not solved and now stated in the README:
`/api/v2/messages` and `/v2/responses` still route. No path shape
separates those from a gateway rooted at `/api` or `/v2`; only the host
or the request body could, and reading the body inside a sync `fetch`
wrapper buys a new class of failure for a shape `excludeHosts` already
covers. I did not add a known-host allowlist either: it can only
recognise hosts someone already thought of, and it regresses compatible
gateways silently — the failure mode #4747 was filed about.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-17 02:36:58 +05:30

111 lines
4.7 KiB
JavaScript

// Live proof for #4781: real Node process, real sockets, real built plugin.
// Nothing in the process under test is stubbed - globalThis.fetch is undici's.
// The upstream API and the Headroom proxy are local HTTP fixtures, because the
// issue's repro touches no provider account (a MessageBird request carries only
// a fake AccessKey). Both fixtures record what actually arrives.
import http from "node:http";
import { fileURLToPath, pathToFileURL } from "node:url";
// Resolve the committed wheel bundle relative to this script, not the cwd.
const BUNDLE = fileURLToPath(new URL("../../../headroom/providers/opencode/_dist/index.js", import.meta.url));
const UPSTREAM_PORT = 8899;
const PROXY_PORT = 8790;
// localtest.me resolves to 127.0.0.1 but is not a loopback spelling, so the
// transport treats it as a routable upstream and the request really leaves the
// process over TCP.
const HOST = "localtest.me";
const seen = { upstream: [], proxy: [], proxyRaw: [] };
function record(bucket, req, payload) {
bucket.push({
method: req.method,
url: req.url,
host: req.headers.host,
auth: req.headers.authorization,
baseUrl: payload.baseUrl,
originalPath: payload.originalPath,
body: payload.body,
});
}
async function listen(name, port, bucket) {
const server = http.createServer((req, res) => {
let body = "";
req.setEncoding("utf8");
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
record(bucket, req, { body, baseUrl: req.headers["x-headroom-base-url"], originalPath: req.headers["x-headroom-original-path"] });
if (name === "proxy") seen.proxyRaw.push({ url: req.url, headers: req.headers });
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ servedBy: name, path: req.url }));
});
});
await new Promise((resolve) => server.listen(port, "127.0.0.1", resolve));
return server;
}
const upstream = await listen("upstream", UPSTREAM_PORT, seen.upstream);
const proxy = await listen("proxy", PROXY_PORT, seen.proxy);
const mod = await import(pathToFileURL(BUNDLE).href);
const plugin = mod.default ?? mod;
const hooks = await plugin.server(
{ directory: process.cwd(), project: { id: "proof-4781" } },
{ proxyUrl: `http://127.0.0.1:${PROXY_PORT}`, debug: true },
);
const post = (path) =>
fetch(`http://${HOST}:${UPSTREAM_PORT}${path}`, {
method: "POST",
headers: { authorization: "AccessKey FAKE-TEST-VALUE", "content-type": "application/json" },
body: JSON.stringify({ originator: "+390000000000", recipients: ["+391111111111"], body: "hi" }),
});
const cases = [
["MessageBird-shaped POST /messages", "/messages", "upstream"],
["MessageBird batches POST /messages/batches", "/messages/batches", "upstream"],
["LLM control POST /v1/messages", "/v1/messages", "proxy"],
["LLM control POST /v1/chat/completions", "/v1/chat/completions", "proxy"],
];
const table = [];
for (const [label, path, expected] of cases) {
const before = { upstream: seen.upstream.length, proxy: seen.proxy.length };
const response = await post(path);
const payload = await response.json();
const landed = seen.proxy.length > before.proxy ? "proxy" : "upstream";
table.push({
label,
path,
"served by": payload.servedBy,
verdict: landed === "proxy" ? "REROUTED to proxy" : "left alone",
expected,
pass: landed === expected,
});
}
console.log("\n=== decisions (real sockets, real fetch, real built plugin) ===");
for (const row of table) console.log(`${row.pass ? "PASS" : "FAIL"} ${row.label.padEnd(46)} -> ${row.verdict}`);
const routed = seen.proxy.filter((r) => r.url.includes("/messages") || r.url.includes("/chat/completions"));
const smsAtProxy = seen.proxy.filter((r) => r.url === "/messages" && r.baseUrl === `http://${HOST}:${UPSTREAM_PORT}`);
console.log("\n=== what reached the proxy ===");
for (const r of routed) console.log(` ${r.method} ${r.url} x-headroom-base-url=${r.baseUrl ?? "null"} original-path=${r.originalPath ?? "null"}`);
console.log("\n=== full headers seen by the proxy ===");
for (const r of seen.proxyRaw) console.log(` ${r.url} :: ${JSON.stringify(r.headers)}`);
console.log("\n=== MessageBird-shaped requests that reached the proxy: " + smsAtProxy.length + " ===");
console.log("=== what reached the upstream directly ===");
for (const r of seen.upstream) console.log(` ${r.method} ${r.url} auth=${r.auth} (no proxy headers: ${r.baseUrl === undefined})`);
await hooks.dispose(async () => {});
upstream.close();
proxy.close();
const failed = table.filter((row) => !row.pass);
console.log(`\n${failed.length === 0 ? "ALL CASES PASS" : failed.length + " CASE(S) FAILED"}`);
process.exit(failed.length === 0 ? 0 : 1);