Skip to content

Commit 787db40

Browse files
committed
fix(auth): pin forwarded Codex credentials to ChatGPT
1 parent 4988765 commit 787db40

14 files changed

Lines changed: 224 additions & 24 deletions

‎src/adapters/openai-responses.ts‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { COMPACT_PROMPT, decodeCompactionSummary, SUMMARY_PREFIX } from "../resp
66
import { collectResponsesToolGroups } from "../responses/tool-groups";
77
import { isHostedToolUnsupportedForModel } from "../responses/hosted-tool-policy";
88
import { decodeServerSentEvents } from "../lib/sse-decoder";
9-
import { isCanonicalOpenAiForwardProvider } from "../providers/openai-tiers";
9+
import { CODEX_FORWARD_BASE_URL, isCanonicalOpenAiForwardProvider } from "../providers/openai-tiers";
1010
import { OCX_REASONING_PREFIX } from "../responses/reasoning-envelope";
1111
import { modelRecordValue } from "../reasoning-effort";
1212
import type { TranslatorBudget } from "../lib/translator-budget";
@@ -1213,22 +1213,32 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
12131213
let url: string;
12141214

12151215
if (provider.authMode === "forward") {
1216+
const mayForwardCallerCredentials = isCanonicalOpenAiForwardProvider(provider);
12161217
// OAuth passthrough: ChatGPT backend path is `${baseUrl}/responses` (no /v1).
1217-
url = `${provider.baseUrl}/responses`;
1218+
const baseUrl = mayForwardCallerCredentials
1219+
? CODEX_FORWARD_BASE_URL
1220+
: provider.baseUrl.replace(/\/+$/, "");
1221+
url = `${baseUrl}/responses`;
12181222
if (provider.headers) Object.assign(headers, provider.headers); // static headers first…
12191223
const runtimeProvider = provider as {
12201224
_codexAccountOverride?: { accessToken: string; chatgptAccountId: string };
12211225
_codexAccountRequired?: boolean;
12221226
};
1223-
if (runtimeProvider._codexAccountRequired && !runtimeProvider._codexAccountOverride) {
1227+
if (
1228+
mayForwardCallerCredentials
1229+
&& runtimeProvider._codexAccountRequired
1230+
&& !runtimeProvider._codexAccountOverride
1231+
) {
12241232
throw new Error("Codex pool account auth is required but unavailable");
12251233
}
1226-
for (const h of FORWARD_HEADERS) {
1227-
const v = incoming?.headers.get(h);
1228-
if (v) headers[h] = v; // …so forwarded auth always wins.
1234+
if (mayForwardCallerCredentials) {
1235+
for (const h of FORWARD_HEADERS) {
1236+
const v = incoming?.headers.get(h);
1237+
if (v) headers[h] = v; // …so forwarded auth always wins.
1238+
}
12291239
}
12301240
const override = runtimeProvider._codexAccountOverride;
1231-
if (override) {
1241+
if (override && mayForwardCallerCredentials) {
12321242
headers["authorization"] = `Bearer ${override.accessToken}`;
12331243
headers["chatgpt-account-id"] = override.chatgptAccountId;
12341244
}

‎src/providers/openai-sidecar.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { extractAccountId } from "../oauth/chatgpt";
1313
import { ForwardAdmissionCredentialError, validateForwardAdmissionCredential } from "../server/auth-cors";
1414
import type { CodexAccountMode, OcxConfig, OcxProviderConfig } from "../types";
1515
import {
16+
CODEX_FORWARD_BASE_URL,
1617
isCanonicalOpenAiForwardProvider,
1718
OPENAI_API_PROVIDER_ID,
1819
OPENAI_CODEX_PROVIDER_ID,
@@ -62,10 +63,16 @@ export function listOpenAiForwardSidecarCandidates(config: OcxConfig): OpenAiFor
6263
? { ...provider, authMode: "forward" as const }
6364
: provider;
6465
if (!isCanonicalOpenAiForwardProvider(canonicalProvider)) return [];
66+
// The predicate accepts harmless trailing-slash variants. Pin the provider returned
67+
// to credential-bearing sidecars so every consumer builds one exact ChatGPT path
68+
// instead of independently concatenating the operator's equivalent spelling.
69+
const pinnedProvider = canonicalProvider.baseUrl === CODEX_FORWARD_BASE_URL
70+
? canonicalProvider
71+
: { ...canonicalProvider, baseUrl: CODEX_FORWARD_BASE_URL };
6572
return [{
6673
providerName: OPENAI_CODEX_PROVIDER_ID,
67-
provider: canonicalProvider,
68-
accountMode: providerCodexAccountMode(OPENAI_CODEX_PROVIDER_ID, canonicalProvider) ?? "pool",
74+
provider: pinnedProvider,
75+
accountMode: providerCodexAccountMode(OPENAI_CODEX_PROVIDER_ID, pinnedProvider) ?? "pool",
6976
}];
7077
}
7178

‎src/server/live.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ export function keyedLiveUrl(baseUrl: string): string {
168168
}
169169

170170
export function forwardLiveUrl(baseUrl: string, usesBackendShape: boolean): string {
171-
const root = baseUrl.replace(/\/$/, "");
171+
const root = baseUrl.replace(/\/+$/, "");
172172
if (usesBackendShape) return withAvasQuery(`${root}/realtime/calls`);
173173
// Frameless API shape posts to /live without the AVAS query (codex RealtimeCallClient).
174174
return `${root}/live`;

‎src/server/responses/compact.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ import {
8282
} from "../../codex/upstream-host-health";
8383
import { ForwardAdmissionCredentialError, validateForwardAdmissionCredential } from "../auth-cors";
8484
import { listOpenAiForwardSidecarCandidates, resolveFirstUsableOpenAiSidecar, type ResolvedOpenAiForwardSidecar } from "../../providers/openai-sidecar";
85-
import { isCanonicalOpenAiForwardProvider, supportsNativeResponsesCompactEndpoint } from "../../providers/openai-tiers";
85+
import { CODEX_FORWARD_BASE_URL, isCanonicalOpenAiForwardProvider, supportsNativeResponsesCompactEndpoint } from "../../providers/openai-tiers";
8686
import { slugsEquivalent } from "../../providers/slug-codec";
8787
import { applyOpenAiVirtualModel, resolveOpenAiCompactModel } from "../../providers/openai-virtual-models";
8888
import { isUsageDebugEnabled } from "../../usage/debug";
@@ -390,7 +390,9 @@ export async function handleResponsesCompact(
390390
}
391391
throw err;
392392
}
393-
const base = (compactProvider.baseUrl ?? "").replace(/\/$/, "");
393+
const base = isCanonicalOpenAiForwardProvider(compactProvider)
394+
? CODEX_FORWARD_BASE_URL
395+
: (compactProvider.baseUrl ?? "").replace(/\/+$/, "");
394396
if (compactProvider.authMode !== "forward" && compactProvider.apiKey) {
395397
headers.set("authorization", `Bearer ${resolveEnvValue(compactProvider.apiKey)}`);
396398
}

‎tests/claude-messages-endpoint.test.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -649,11 +649,19 @@ test("native openai-responses route carries prompt_cache_key + synthesized sessi
649649
return new Response(frames.join(""), { headers: { "Content-Type": "text/event-stream" } });
650650
},
651651
});
652+
globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
653+
const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
654+
const url = new URL(requestUrl);
655+
if (url.origin === "https://chatgpt.com" && url.pathname === "/backend-api/codex/responses") {
656+
return originalFetch(new URL("/responses", upstream.url), init);
657+
}
658+
return originalFetch(input, init);
659+
}) as typeof fetch;
652660
saveConfig({
653661
port: 0,
654662
defaultProvider: "native",
655663
providers: {
656-
native: { adapter: "openai-responses", baseUrl: `${upstream.url.toString().replace(/\/$/, "")}/v1`, authMode: "forward", allowPrivateNetwork: true },
664+
native: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" },
657665
},
658666
} as OcxConfig);
659667
const server = startServer(0);
@@ -681,6 +689,7 @@ test("native openai-responses route carries prompt_cache_key + synthesized sessi
681689
expect(capture.body?.reasoning?.effort).toBe("high");
682690
expect(capture.headers?.["session_id"]).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-8[0-9a-f]{3}-[0-9a-f]{12}$/);
683691
} finally {
692+
globalThis.fetch = originalFetch;
684693
await server.stop(true);
685694
upstream.stop(true);
686695
}

‎tests/codex-metadata-integrity.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ describe("Codex metadata integrity", () => {
117117
_codexAccountRequired: boolean;
118118
} = {
119119
adapter: "openai-responses",
120-
baseUrl: "https://chatgpt.test/backend-api/codex",
120+
baseUrl: "https://chatgpt.com/backend-api/codex",
121121
authMode: "forward",
122122
_codexAccountRequired: true,
123123
_codexAccountOverride: {
@@ -142,7 +142,7 @@ describe("Codex metadata integrity", () => {
142142
test("adapter forward mode preserves genuine client metadata", () => {
143143
const provider: OcxProviderConfig = {
144144
adapter: "openai-responses",
145-
baseUrl: "https://chatgpt.test/backend-api/codex",
145+
baseUrl: "https://chatgpt.com/backend-api/codex",
146146
authMode: "forward",
147147
};
148148
const adapter = createResponsesPassthroughAdapter(provider);

‎tests/openai-responses-passthrough.test.ts‎

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,107 @@ const createResponsesPassthroughAdapter = (...args: Parameters<typeof createResp
1111

1212
const provider = {
1313
adapter: "openai-responses",
14-
baseUrl: "https://chatgpt.example/backend-api/codex",
14+
baseUrl: "https://chatgpt.com/backend-api/codex",
1515
authMode: "forward" as const,
1616
};
1717

18+
test("noncanonical forward providers cannot receive caller or runtime credentials", () => {
19+
const userInfoUrl = new URL("https://chatgpt.com/backend-api/codex");
20+
userInfoUrl.username = "user";
21+
userInfoUrl.password = "secret";
22+
for (const baseUrl of [
23+
"https://provider.example/v1/",
24+
"https://chatgpt.com/backend-api/not-codex",
25+
"https://chatgpt.example/backend-api/codex",
26+
"https://chatgpt.com/backend-api/codex?target=custom",
27+
"https://chatgpt.com/backend-api/codex#custom",
28+
userInfoUrl.toString(),
29+
]) {
30+
const adapter = createResponsesPassthroughAdapter({
31+
adapter: "openai-responses",
32+
baseUrl,
33+
authMode: "forward",
34+
headers: { "x-provider-option": "enabled" },
35+
_codexAccountRequired: true,
36+
_codexAccountOverride: {
37+
accessToken: "runtime-secret",
38+
chatgptAccountId: "runtime-account",
39+
},
40+
} as Parameters<typeof createResponsesPassthroughAdapter>[0]);
41+
const request = adapter.buildRequest({
42+
modelId: "test-model",
43+
context: { messages: [] },
44+
stream: true,
45+
options: {},
46+
_rawBody: { model: "test-model", input: "ping" },
47+
}, {
48+
headers: new Headers({
49+
authorization: "Bearer caller-secret",
50+
"chatgpt-account-id": "caller-account",
51+
session_id: "caller-session",
52+
}),
53+
});
54+
55+
expect(request.url).toBe(`${baseUrl.replace(/\/+$/, "")}/responses`);
56+
expect(request.headers["x-provider-option"]).toBe("enabled");
57+
expect(request.headers.authorization).toBeUndefined();
58+
expect(request.headers["chatgpt-account-id"]).toBeUndefined();
59+
expect(request.headers.session_id).toBeUndefined();
60+
}
61+
});
62+
63+
test("canonical forward providers normalize trailing slashes and let the pool override win", () => {
64+
const adapter = createResponsesPassthroughAdapter({
65+
...provider,
66+
baseUrl: "https://chatgpt.com/backend-api/codex///",
67+
_codexAccountRequired: true,
68+
_codexAccountOverride: {
69+
accessToken: "runtime-secret",
70+
chatgptAccountId: "runtime-account",
71+
},
72+
} as Parameters<typeof createResponsesPassthroughAdapter>[0]);
73+
const request = adapter.buildRequest({
74+
modelId: "test-model",
75+
context: { messages: [] },
76+
stream: true,
77+
options: {},
78+
_rawBody: { model: "test-model", input: "ping" },
79+
}, { headers: new Headers({ authorization: "Bearer caller-secret" }) });
80+
81+
expect(request.url).toBe("https://chatgpt.com/backend-api/codex/responses");
82+
expect(request.headers.authorization).toBe("Bearer runtime-secret");
83+
expect(request.headers["chatgpt-account-id"]).toBe("runtime-account");
84+
});
85+
86+
test("noncanonical pool-required providers use only their configured static credentials", () => {
87+
const adapter = createResponsesPassthroughAdapter({
88+
adapter: "openai-responses",
89+
baseUrl: "https://provider.example/v1/",
90+
authMode: "forward",
91+
headers: { authorization: "Bearer provider-static", "x-provider-option": "enabled" },
92+
_codexAccountRequired: true,
93+
} as Parameters<typeof createResponsesPassthroughAdapter>[0]);
94+
const request = adapter.buildRequest({
95+
modelId: "test-model",
96+
context: { messages: [] },
97+
stream: true,
98+
options: {},
99+
_rawBody: { model: "test-model", input: "ping" },
100+
}, {
101+
headers: new Headers({
102+
authorization: "Bearer caller-secret",
103+
"chatgpt-account-id": "caller-account",
104+
session_id: "caller-session",
105+
}),
106+
});
107+
108+
expect(request.url).toBe("https://provider.example/v1/responses");
109+
expect(request.headers["x-provider-option"]).toBe("enabled");
110+
expect(request.headers.authorization).toBe("Bearer provider-static");
111+
expect(request.headers["chatgpt-account-id"]).toBeUndefined();
112+
expect(request.headers.session_id).toBeUndefined();
113+
});
114+
18115
test("passthrough serialized-body observation releases after the request settles", () => {
19116
const budget = createTranslatorBudget();
20117
const request = createResponsesPassthroughAdapter(provider).buildRequest({

‎tests/passthrough-override.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { withTestTranslatorBudget } from "./helpers/translator-budget";
66
const createResponsesPassthroughAdapter = (...args: Parameters<typeof createResponsesPassthroughAdapterProduction>) =>
77
withTestTranslatorBudget(createResponsesPassthroughAdapterProduction(...args));
88

9-
const forwardProvider = { adapter: "openai-responses", baseUrl: "https://chat.openai.com/backend-api/codex", authMode: "forward" as const };
9+
const forwardProvider = { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" as const };
1010

1111
describe("passthrough token override", () => {
1212
test("buildRequest uses original auth when no override", () => {

‎tests/responses-compaction-routing.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,30 @@ describe("compact alternate-account attempt (#913)", () => {
626626
});
627627
}
628628

629+
test("canonical trailing slashes are pinned before native compact sends pool credentials", async () => {
630+
await withPoolEnv("ocx-compact-canonical-url-", async config => {
631+
config.providers.openai!.baseUrl = "https://chatgpt.com/backend-api/codex///";
632+
let observedUrl = "";
633+
let observedHeaders = new Headers();
634+
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
635+
observedUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
636+
observedHeaders = new Headers(init?.headers);
637+
return jsonResponse(completedPayload("canonical compact response"));
638+
}) as typeof fetch;
639+
640+
const res = await handleResponsesCompact(
641+
compactionRequest(baseCompactionBody({ model: "gpt-5.5" })),
642+
config,
643+
{ model: "", provider: "" },
644+
);
645+
646+
expect(res.status).toBe(200);
647+
expect(observedUrl).toBe("https://chatgpt.com/backend-api/codex/responses/compact");
648+
expect(observedHeaders.get("authorization")).toBe("Bearer pool-a-access-token");
649+
expect(observedHeaders.get("chatgpt-account-id")).toBe("pool_acc_a");
650+
});
651+
});
652+
629653
for (const rejection of [429, 402] as const) {
630654
test(`a pre-body ${rejection} tries exactly one alternate account`, async () => {
631655
await withPoolEnv(`ocx-compact-alt-${rejection}-`, async config => {

‎tests/responses-custom-tool-repair.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,7 @@ describe("routed Responses custom-tool compatibility", () => {
706706
const savedFetch = globalThis.fetch;
707707
let outboundBody: Record<string, unknown> | undefined;
708708
let outboundAuthorization: string | null = null;
709+
let outboundUrl = "";
709710
const upstreamItem = {
710711
type: "function_call",
711712
id: "fc_exec",
@@ -714,7 +715,8 @@ describe("routed Responses custom-tool compatibility", () => {
714715
arguments: "{\"input\":\"native\"}",
715716
status: "completed",
716717
};
717-
globalThis.fetch = (async (_input, init) => {
718+
globalThis.fetch = (async (input, init) => {
719+
outboundUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
718720
outboundBody = JSON.parse(String(init?.body)) as Record<string, unknown>;
719721
outboundAuthorization = new Headers(init?.headers).get("authorization");
720722
return new Response(JSON.stringify({ id: "resp_forward", status: "completed", output: [upstreamItem] }), {
@@ -727,7 +729,7 @@ describe("routed Responses custom-tool compatibility", () => {
727729
providers: {
728730
fixture: {
729731
adapter: "openai-responses",
730-
baseUrl: "https://forward.fixture.test",
732+
baseUrl: "https://chatgpt.com/backend-api/codex",
731733
authMode: "forward",
732734
},
733735
},
@@ -747,6 +749,7 @@ describe("routed Responses custom-tool compatibility", () => {
747749
const clientBody = await response.json() as { output: Array<Record<string, unknown>> };
748750
const outboundTools = outboundBody?.tools as Array<Record<string, unknown>> | undefined;
749751

752+
expect(outboundUrl).toBe("https://chatgpt.com/backend-api/codex/responses");
750753
expect(outboundAuthorization).toBe("Bearer caller-token");
751754
expect(outboundTools?.[0]).toMatchObject({ type: "custom", name: "exec" });
752755
expect(clientBody.output[0]).toMatchObject({ type: "function_call", name: "exec" });

0 commit comments

Comments
 (0)