fix(opencode): keep custom /api gateways routed, and fix the Node test

Review findings on #4758.

`/api/chat/completions` regressed: the wire-root rule required a version
segment before the endpoint and treated "api" as an unknown segment, so a
compatible provider with a base URL of `https://gateway.example/api` stopped
reaching the proxy and lost compression. "api" is now an accepted immediate
root. It counts only when it abuts the endpoint, which is what keeps Discord's
`/api/v10/channels/123/messages` out: its immediate segment is "123", not
"api". A new assertion covers the base-URL shape and fails without the fix.

The Node loopback test asserted an `http://` URL against a spy on
`https.request`, which real Node rejects, so it never exercised HTTP
passthrough. It now spies on both and uses `http.request` for `http://`. It
fails against `upstream/main` transport.ts, where 127.0.0.2 was proxied.
This commit is contained in:
Parideboy
2026-11-10 19:09:21 +01:00
parent db66400a25
commit b695e69744
4 changed files with 41 additions and 16 deletions
+2 -1
View File
@@ -19976,13 +19976,14 @@ function isExcludedHost(hostname3, excludeHosts) {
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
var NAMED_WIRE_ROOTS = /* @__PURE__ */ new Set(["backend-api", "codex", "openai", "anthropic", "zen"]);
var IMMEDIATE_WIRE_ROOTS = /* @__PURE__ */ new Set(["api"]);
function isVersionSegment(segment) {
return /^v\d+[a-z0-9]*$/i.test(segment);
}
function hasWireRootBefore(body) {
const segments = body.split("/").filter(Boolean);
const last = segments.at(-1);
return last === void 0 || isVersionSegment(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) {
if (pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent")) {
@@ -191,13 +191,14 @@ function isExcludedHost(hostname, excludeHosts) {
return excludeHosts.some((host) => normalized === host || normalized.endsWith(`.${host}`));
}
var NAMED_WIRE_ROOTS = /* @__PURE__ */ new Set(["backend-api", "codex", "openai", "anthropic", "zen"]);
var IMMEDIATE_WIRE_ROOTS = /* @__PURE__ */ new Set(["api"]);
function isVersionSegment(segment) {
return /^v\d+[a-z0-9]*$/i.test(segment);
}
function hasWireRootBefore(body) {
const segments = body.split("/").filter(Boolean);
const last = segments.at(-1);
return last === void 0 || isVersionSegment(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) {
if (pathname.endsWith(":generateContent") || pathname.endsWith(":streamGenerateContent")) {
+15 -8
View File
@@ -302,12 +302,13 @@ describe("Headroom OpenCode transport", () => {
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(6);
expect(fetchMock).toHaveBeenCalledTimes(7);
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();
@@ -344,24 +345,30 @@ describe("Headroom OpenCode transport", () => {
globalThis.fetch = originalFetch;
});
it("keeps loopback spellings and a trailing-dot excluded host off the proxy for Node https.request (#4747)", () => {
it("keeps loopback spellings and a trailing-dot excluded host off the proxy for Node http/https.request (#4747)", () => {
const fakeRequest = { on: vi.fn(), end: vi.fn(), destroy: vi.fn() };
const requestSpy = vi.spyOn(https, "request").mockImplementation(() => fakeRequest as never);
const httpsSpy = vi.spyOn(https, "request").mockImplementation(() => fakeRequest as never);
const httpSpy = vi.spyOn(http, "request").mockImplementation(() => fakeRequest as never);
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["api.x.example"] });
const options = { method: "POST" };
try {
// http:// goes through http.request: real https.request rejects that
// protocol, so asserting it against the https spy would prove nothing.
http.request("http://127.0.0.2:11434/v1/chat/completions", options);
http.request("http://[::ffff:127.0.0.2]:11434/v1/chat/completions", options);
https.request("https://api.x.example./v1/chat/completions", options);
https.request("http://127.0.0.2:11434/v1/chat/completions", options);
https.request("https://discord.com/api/v10/channels/123/messages", options);
expect(requestSpy.mock.calls[0][0]).toBe("https://api.x.example./v1/chat/completions");
expect(requestSpy.mock.calls[1][0]).toBe("http://127.0.0.2:11434/v1/chat/completions");
expect(requestSpy.mock.calls[2][0]).toBe("https://discord.com/api/v10/channels/123/messages");
expect(httpSpy.mock.calls[0][0]).toBe("http://127.0.0.2:11434/v1/chat/completions");
expect(httpSpy.mock.calls[1][0]).toBe("http://[::ffff:127.0.0.2]:11434/v1/chat/completions");
expect(httpsSpy.mock.calls[0][0]).toBe("https://api.x.example./v1/chat/completions");
expect(httpsSpy.mock.calls[1][0]).toBe("https://discord.com/api/v10/channels/123/messages");
} finally {
uninstallHeadroomTransport();
requestSpy.mockRestore();
httpsSpy.mockRestore();
httpSpy.mockRestore();
}
});
+22 -6
View File
@@ -312,9 +312,11 @@ function isExcludedHost(hostname: string, excludeHosts: string[]): boolean {
// caller's Authorization header - to the proxy (#4747). A path therefore also
// has to be rooted where providers mount a wire:
//
// * the segment right before the endpoint is a version ("v1", "v1beta", "v4"),
// * the segment right before the endpoint is a version ("v1", "v1beta", "v4")
// or a base a compatible gateway mounts the wire directly under ("api"),
// which keeps prefixed gateways working (/api/coding/paas/v4/chat/completions,
// /base/v1/messages, /zen/v1/responses), or
// /base/v1/messages, /zen/v1/responses, and a custom base URL of
// https://gateway.example/api), or
// * the path contains a named wire root, which is what Azure OpenAI needs: its
// deployment name sits between /openai/ and the endpoint
// (/openai/deployments/{name}/chat/completions).
@@ -322,12 +324,21 @@ function isExcludedHost(hostname: string, excludeHosts: string[]): boolean {
// A bare /messages or /responses on a provider origin still counts: there is no
// segment at all.
//
// A version segment anywhere would be too weak - Discord's /api/v10/... has
// one. So the residual over-match is narrower but real: /api/v2/messages still
// routes. Telling that apart from a provider needs the host or the body;
// 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.
const NAMED_WIRE_ROOTS = new Set(["backend-api", "codex", "openai", "anthropic", "zen"]);
// Custom OpenAI-compatible gateways commonly mount the wire directly under one
// of these, with no version segment: a model base URL of `.../api` plus
// `/chat/completions` is a real configuration (#4747 review).
const IMMEDIATE_WIRE_ROOTS = new Set(["api"]);
function isVersionSegment(segment: string): boolean {
return /^v\d+[a-z0-9]*$/i.test(segment);
}
@@ -335,7 +346,12 @@ function isVersionSegment(segment: string): boolean {
function hasWireRootBefore(body: string): boolean {
const segments = body.split("/").filter(Boolean);
const last = segments.at(-1);
return last === undefined || isVersionSegment(last) || segments.some((s) => NAMED_WIRE_ROOTS.has(s));
return (
last === undefined ||
isVersionSegment(last) ||
IMMEDIATE_WIRE_ROOTS.has(last) ||
segments.some((s) => NAMED_WIRE_ROOTS.has(s))
);
}
// Native Gemini model-generation endpoints use colon-action suffixes