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>
This commit is contained in:
Parideboy
2026-11-17 02:36:58 +05:30
committed by GitHub
co-authored by JerrettDavis
parent 5023c84e52
commit 87c12931fb
6 changed files with 169 additions and 16 deletions
+1 -1
View File
@@ -20026,7 +20026,7 @@ function isVersionSegment(segment) {
function hasWireRootBefore(body) {
const segments = body.split("/").filter(Boolean);
const last = segments.at(-1);
return last === void 0 || isVersionSegment(last) || IMMEDIATE_WIRE_ROOTS.has(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s));
return last !== void 0 && (isVersionSegment(last) || IMMEDIATE_WIRE_ROOTS.has(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s)));
}
function isLlmEndpointPath(pathname, origin = "", wireRoots = []) {
if (pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent")) {
@@ -241,7 +241,7 @@ function isVersionSegment(segment) {
function hasWireRootBefore(body) {
const segments = body.split("/").filter(Boolean);
const last = segments.at(-1);
return last === void 0 || isVersionSegment(last) || IMMEDIATE_WIRE_ROOTS.has(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s));
return last !== void 0 && (isVersionSegment(last) || IMMEDIATE_WIRE_ROOTS.has(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s)));
}
function isLlmEndpointPath(pathname, origin = "", wireRoots = []) {
if (pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent")) {
+2
View File
@@ -75,6 +75,8 @@ The default export is `{ id: "headroom", server, setup }`. OpenCode 1.x calls `s
- skip routing for hosts listed in `excludeHosts` (or `HEADROOM_OPENCODE_EXCLUDE_HOSTS`); those requests go straight upstream with no compression or telemetry.
- route the provider base URLs configured in OpenCode, so a compatible gateway with an arbitrary path prefix is still compressed. Only wire endpoints (`/chat/completions`, `/responses`, `/messages`) under a configured base route; other paths on that host pass through.
Routing is decided by method, path shape, and configured bases, never by host identity. A `POST` routes when its path ends in a wire endpoint *and* the segment before that endpoint is a version (`/v1`, `/v1beta`, `/v4`), `api`, or a recognised root (`backend-api`, `codex`, `openai`, `anthropic`, `zen`) — or when it sits under one of OpenCode's configured provider base URLs. Everything else goes direct, including a bare `/messages` on an unknown host: that is the same shape as a messaging API, so becoming the bare path is not evidence of a provider. Two shapes still route without a configured base, because no path can tell them from a gateway: `/api/v2/messages` and `/v2/responses`. List the host in `excludeHosts` if one of your own services has that shape.
On 2.x, setup returns a cleanup that releases the transport, so hot reloads do not stack interceptors.
OpenCode 2.x keeps its own reference to `fetch` from before plugins load, so patching `fetch` alone does not catch its model traffic. For models with a resolved `baseURL`, the plugin also rewrites OpenAI chat-completions, Responses, and Anthropic Messages traffic so that it points at the proxy — including GitHub Copilot's Claude models. Anthropic Messages base URLs with a path prefix (for example a gateway rooted at `/api/...`) stay on their own base URL, because the proxy's Messages route ignores the original-path header and cannot preserve that prefix. Headers name the real upstream and request path, as the transport does, and authentication settings are retained. Local, excluded, and unsupported-protocol models are left alone. `headroom wrap opencode` routes native Anthropic and OpenAI through the proxy separately, via their `baseURL`.
@@ -0,0 +1,110 @@
// 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);
+42 -5
View File
@@ -7,7 +7,7 @@ import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { installHeadroomTransport, uninstallHeadroomTransport } from "./transport.js";
import { installHeadroomTransport, setHeadroomWireRoots, uninstallHeadroomTransport } from "./transport.js";
afterEach(() => {
uninstallHeadroomTransport();
@@ -294,7 +294,7 @@ describe("Headroom OpenCode transport", () => {
globalThis.fetch = originalFetch;
});
it("still routes provider-rooted wire paths, including a bare endpoint and other version prefixes (#4747)", async () => {
it("still routes provider-rooted wire paths and other version prefixes (#4747)", async () => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
@@ -302,15 +302,13 @@ describe("Headroom OpenCode transport", () => {
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
const init = { method: "POST" };
await fetch("https://api.example.com/messages", init);
await fetch("https://api.example.com/responses", init);
await fetch("https://gateway.example.com/api/chat/completions", init);
await fetch("https://gateway.example.com/api/v2/chat/completions", init);
await fetch("https://gateway.example.com/openai/deployments/x/chat/completions", init);
await fetch("https://opencode.ai/zen/v1/responses", init);
await fetch("https://cloud.example.com/backend-api/codex/responses", init);
expect(fetchMock).toHaveBeenCalledTimes(7);
expect(fetchMock).toHaveBeenCalledTimes(5);
for (const call of fetchMock.mock.calls as FetchCall[]) {
expect(call[0]).toBeInstanceOf(URL);
expect(new Headers(call[1]?.headers).get("x-headroom-base-url")).not.toBeNull();
@@ -319,6 +317,45 @@ describe("Headroom OpenCode transport", () => {
globalThis.fetch = originalFetch;
});
it("leaves a POST to a host's bare /messages or /responses alone unless that base is configured (#4781)", async () => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
globalThis.fetch = fetchMock as unknown as typeof fetch;
// MessageBird's legacy SMS API is POST https://rest.messagebird.com/messages
// with `Authorization: AccessKey ...`: a non-LLM credential that must not
// travel to the proxy. No base URL is configured for these origins.
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
const init = { method: "POST", headers: { authorization: "AccessKey FAKE-TEST-VALUE" }, body: "{}" };
await fetch("https://rest.messagebird.com/messages", init);
await fetch("https://api.example.com/messages", init);
await fetch("https://api.example.com/responses", init);
await fetch("https://api.example.com/chat/completions", init);
expect(fetchMock).toHaveBeenCalledTimes(4);
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();
expect(headers.get("x-headroom-original-path")).toBeNull();
}
// A provider mounted at the origin root is still routed, because the base
// URL itself is the configured wire root.
setHeadroomWireRoots("https://rest.messagebird.com");
await fetch("https://rest.messagebird.com/messages", init);
expect(fetchMock).toHaveBeenCalledTimes(5);
expect(fetchMock.mock.calls[4][0]).toEqual(new URL("http://127.0.0.1:8787/messages"));
expect(new Headers(fetchMock.mock.calls[4][1]?.headers).get("x-headroom-base-url")).toBe(
"https://rest.messagebird.com",
);
uninstallHeadroomTransport();
globalThis.fetch = originalFetch;
});
it("keeps every loopback spelling and a trailing-dot excluded host off the proxy (#4747)", async () => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
+13 -9
View File
@@ -398,17 +398,23 @@ function isConfiguredWireRoot(origin: string, pathname: string, wireRoots: WireR
// deployment name sits between /openai/ and the endpoint
// (/openai/deployments/{name}/chat/completions).
//
// A bare /messages or /responses on a provider origin still counts: there is no
// segment at all.
// An endpoint with NO segment before it (/messages on the origin root) does not
// count on its own: that is the same shape as a real non-LLM API, and becoming
// the bare path is not evidence of a provider. MessageBird's legacy SMS API is
// POST https://rest.messagebird.com/messages (#4781). A provider mounted at an
// origin root is still routable, because it is a configured wire root: the base
// URL carries no path, so isConfiguredWireRoot matches every path on that
// origin. Unknown bare-path hosts go direct.
//
// The immediate segment is what keeps this tight. "api" is a root only when it
// abuts the endpoint, so /api/chat/completions routes while Discord's
// /api/v10/channels/123/messages (immediate segment "123") does not. For the
// same reason a version segment counts only in that position, not anywhere.
//
// The residual over-match is documented, not solved: /api/v2/messages still
// routes. Telling that apart from a provider needs the host or the body, and
// excludeHosts already covers any host a user controls.
// The residual over-match is documented, not solved: /api/v2/messages and
// /v2/responses still route. No path shape separates those from a gateway;
// only the host or the body could, and excludeHosts already covers any host a
// user controls.
const NAMED_WIRE_ROOTS = new Set(["backend-api", "codex", "openai", "anthropic", "zen"]);
// Custom OpenAI-compatible gateways commonly mount the wire directly under one
@@ -424,10 +430,8 @@ function hasWireRootBefore(body: string): boolean {
const segments = body.split("/").filter(Boolean);
const last = segments.at(-1);
return (
last === undefined ||
isVersionSegment(last) ||
IMMEDIATE_WIRE_ROOTS.has(last) ||
segments.some((s) => NAMED_WIRE_ROOTS.has(s))
last !== undefined &&
(isVersionSegment(last) || IMMEDIATE_WIRE_ROOTS.has(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s)))
);
}