From f9ebdfabcb6421f4644275b05f4b3d3daf356dfa Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 11 Nov 2026 02:49:59 +0000 Subject: [PATCH] Prove Codex ChatGPT subscription protocol adapter --- .../gen-2825-codex-subscription-protocol.md | 90 +++++++++ packages/api/src/codex-subscription-proof.ts | 178 ++++++++++++++++++ .../api/test/codex-subscription-proof.test.ts | 160 ++++++++++++++++ 3 files changed, 428 insertions(+) create mode 100644 docs/decisions/gen-2825-codex-subscription-protocol.md create mode 100644 packages/api/src/codex-subscription-proof.ts create mode 100644 packages/api/test/codex-subscription-proof.test.ts diff --git a/docs/decisions/gen-2825-codex-subscription-protocol.md b/docs/decisions/gen-2825-codex-subscription-protocol.md new file mode 100644 index 00000000..0c160e5e --- /dev/null +++ b/docs/decisions/gen-2825-codex-subscription-protocol.md @@ -0,0 +1,90 @@ +# GEN-2825: Codex subscription protocol proof + +**Decision:** a narrow credential proxy can translate a local OpenAI Responses +provider into the Codex ChatGPT subscription protocol observed in the pinned +Codex source. Keep OAuth credentials and refresh state in the proxy. Give Codex +only the proxy's local credential. This is protocol feasibility evidence, not +production account management or a live subscription compatibility claim. + +## Evidence and version + +This proof targets **Codex CLI `@openai/codex` 0.167.1**, published on npm and +tagged in OpenAI's source as `rust-v0.167.1` at commit +[`0a94398fa60c4fac0e7659e4213a0a36e613dd46`](https://github.com/openai/codex/commit/0a94398fa60c4fac0e7659e4213a0a36e613dd46). +The official [Codex authentication guide](https://developers.openai.com/codex/auth) +documents signing in with ChatGPT and using a supported ChatGPT plan. The +official [Codex CLI README](https://github.com/openai/codex/blob/rust-v0.167.1/README.md) +also describes subscription sign-in. + +The tagged source provides the wire details absent from the user-facing guide: + +- Device authorization starts at `POST https://auth.openai.com/api/accounts/deviceauth/usercode`, polls `POST .../deviceauth/token`, then exchanges the code at `POST https://auth.openai.com/oauth/token` with the device callback URI and PKCE verifier. The device-code flow has a 15 minute bound. +- The token identity object at `https://api.openai.com/auth` contains `chatgpt_account_id`, which binds refresh and inference to one ChatGPT account. Codex sends `Authorization: Bearer ` and `chatgpt-account-id: ` upstream. +- The Codex Responses origin is `https://chatgpt.com/backend-api/codex`; model discovery uses its `/models` endpoint and inference uses `/responses`. Inference is streamed as server-sent events. The proxy must translate model discovery into the local provider's `/v1/models` response shape and relay `/v1/responses` streams unchanged. +- Refresh uses `POST https://auth.openai.com/oauth/token` with `grant_type=refresh_token`; Codex retains and refreshes the rotated token pair. This proof assigns that ownership to the proxy instead. + +Source references: [`device_code_auth.rs`](https://github.com/openai/codex/blob/rust-v0.167.1/codex-rs/login/src/device_code_auth.rs), [`server.rs`](https://github.com/openai/codex/blob/rust-v0.167.1/codex-rs/login/src/server.rs), [`auth/manager.rs`](https://github.com/openai/codex/blob/rust-v0.167.1/codex-rs/login/src/auth/manager.rs), [`model_provider_info`](https://github.com/openai/codex/blob/rust-v0.167.1/codex-rs/model-provider-info/src/lib.rs), and [`models_endpoint.rs`](https://github.com/openai/codex/blob/rust-v0.167.1/codex-rs/model-provider/src/models_endpoint.rs). These are implementation details, not a public OAuth or subscription API contract. + +## Proof boundary + +`packages/api/src/codex-subscription-proof.ts` owns the synthetic account tokens +and translates device login, refresh, model discovery, and streaming requests. +The local client authenticates with a separate proxy key; neither account token +nor account identity is present in responses returned to that client. This +module is isolated and does not execute Codex or any other agent workload. The +fake authorization, token, and model server in +`packages/api/test/codex-subscription-proof.test.ts` checks successful login, +expiry and refresh, account separation, upstream URL/headers, model discovery, +SSE relay, and token non-disclosure. + +Focused command: `npm test --workspace=factorize -- test/codex-subscription-proof.test.ts`. + +The fixture uses synthetic tokens and local ephemeral HTTP only. **It does not +prove compatibility with a live ChatGPT subscription.** No live account or +credentials were available for this run, so the real-account gate remains. + +## Unsupported assumptions and constraints + +- OpenAI's subscription OAuth and `/backend-api/codex` routes are private + implementation details. Their behavior, availability, terms, and response + schemas can change without notice; no public compatibility guarantee was + found. Pin and re-audit Codex before widening support beyond 0.167.1. +- The proof assumes the subscription continues to permit proxy-mediated use + and that the proxy can securely retain/rotate tokens. The fixtures do not + establish either policy or live service behavior. +- A local custom provider must use the Codex Responses wire format and model + metadata expected by Codex. Generic OpenAI-compatible chat completions are + insufficient. Account tokens must be confined to the credential proxy. +- Refresh rotation races, durable encrypted persistence, revocation, multiple + concurrent requests, browser account management, and production deployment + are outside this proof and remain separate work. + +## Optional bounded live smoke + +Prerequisites: a running authorized Factorize proxy with a named ChatGPT account +already connected, a proxy-local key (not an OpenAI or ChatGPT token), the +proxy's local `/v1` URL, and a model exposed by that proxy. This command invokes +Codex against the proxy; it does not log in to ChatGPT on the agent VM. It is +opt-in, takes at most five minutes, and is not part of `npm test`: + +```sh +set -eu +test -n "${CODEX_PROXY_URL:-}" # e.g. http://127.0.0.1:8787 +test -n "${CODEX_PROXY_LOCAL_KEY:-}" # proxy-local credential only +test -n "${CODEX_PROXY_MODEL:-}" +CODEX_HOME="$(mktemp -d)" +trap 'rm -rf "$CODEX_HOME"' EXIT +CODEX_HOME="$CODEX_HOME" OPENAI_API_KEY="$CODEX_PROXY_LOCAL_KEY" \ + timeout --signal=TERM --kill-after=5s 300s \ + npx --yes @openai/codex@0.167.1 \ + --config 'model_provider="factorize-proof"' \ + --config 'model_providers.factorize-proof.name="Factorize subscription proxy"' \ + --config "model_providers.factorize-proof.base_url=\"$CODEX_PROXY_URL/v1\"" \ + --config 'model_providers.factorize-proof.env_key="OPENAI_API_KEY"' \ + --model "$CODEX_PROXY_MODEL" exec --skip-git-repo-check \ + 'Reply with exactly CODEX_PROXY_SMOKE_OK' +``` + +Passing this command would establish compatibility only for the configured live +proxy/account/model at that time. A fixture pass is not a substitute for this +gate. diff --git a/packages/api/src/codex-subscription-proof.ts b/packages/api/src/codex-subscription-proof.ts new file mode 100644 index 00000000..1ac1ec20 --- /dev/null +++ b/packages/api/src/codex-subscription-proof.ts @@ -0,0 +1,178 @@ +/** + * Isolated protocol proof for a Codex-compatible credential proxy. This is not + * production account storage or an agent runtime: callers keep account tokens + * behind this adapter and present only the proxy's local key. + */ +export type CodexProofAccount = { + accessToken: string; + refreshToken: string; + expiresAt: number; + accountId: string; +}; + +type ProofOptions = { + authOrigin: string; + upstreamOrigin: string; + clientId: string; + localApiKey: string; + now?: () => number; + wait?: (milliseconds: number) => Promise; + fetch?: typeof fetch; +}; + +const DEVICE_TIMEOUT_MS = 15 * 60 * 1000; +const REQUEST_TIMEOUT_MS = 5_000; + +function decodeAccountId(idToken: string): string { + const payload = idToken.split(".")[1]; + if (!payload) throw new Error("Token response has no identity token payload"); + const base64 = payload.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(payload.length / 4) * 4, "="); + const claims = JSON.parse(atob(base64)) as { + "https://api.openai.com/auth"?: { chatgpt_account_id?: unknown }; + }; + const accountId = claims["https://api.openai.com/auth"]?.chatgpt_account_id; + if (typeof accountId !== "string" || accountId.length === 0) { + throw new Error("Token identity has no ChatGPT account id"); + } + return accountId; +} + +function tokenForm(values: Record): URLSearchParams { + return new URLSearchParams(values); +} + +/** Keeps OAuth tokens in the proxy-side closure; responses expose only model data. */ +export function createCodexSubscriptionProof(options: ProofOptions) { + const accounts = new Map(); + const now = options.now ?? Date.now; + const wait = options.wait ?? ((milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds))); + const fetchImpl = options.fetch ?? fetch; + const authOrigin = options.authOrigin.replace(/\/$/, ""); + const upstreamOrigin = options.upstreamOrigin.replace(/\/$/, ""); + + async function fetchBounded(input: string, init?: RequestInit): Promise { + return fetchImpl(input, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }); + } + + async function exchangeToken(body: URLSearchParams): Promise { + const response = await fetchBounded(`${authOrigin}/oauth/token`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body, + }); + if (!response.ok) throw new Error(`OAuth token exchange failed (${response.status})`); + const tokens = await response.json() as { + access_token?: unknown; + refresh_token?: unknown; + expires_in?: unknown; + id_token?: unknown; + }; + if (typeof tokens.access_token !== "string" || typeof tokens.refresh_token !== "string" + || typeof tokens.expires_in !== "number" || typeof tokens.id_token !== "string") { + throw new Error("OAuth token response is incomplete"); + } + return { + accessToken: tokens.access_token, + refreshToken: tokens.refresh_token, + expiresAt: now() + tokens.expires_in * 1000, + accountId: decodeAccountId(tokens.id_token), + }; + } + + async function login(name: string): Promise<{ accountId: string; verificationUrl: string; userCode: string }> { + const start = await fetchBounded(`${authOrigin}/api/accounts/deviceauth/usercode`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ client_id: options.clientId }), + }); + if (!start.ok) throw new Error(`Device authorization failed (${start.status})`); + const device = await start.json() as { + device_auth_id: string; + user_code: string; + interval?: string | number; + }; + if (!device.device_auth_id || !device.user_code) throw new Error("Device authorization response is incomplete"); + + const interval = Number(device.interval ?? 5) * 1000; + const deadline = now() + DEVICE_TIMEOUT_MS; + let grant: { authorization_code: string; code_verifier: string } | undefined; + while (now() < deadline) { + const poll = await fetchBounded(`${authOrigin}/api/accounts/deviceauth/token`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ device_auth_id: device.device_auth_id, user_code: device.user_code }), + }); + if (poll.ok) { + grant = await poll.json() as { authorization_code: string; code_verifier: string }; + break; + } + if (poll.status !== 403 && poll.status !== 404) throw new Error(`Device authorization poll failed (${poll.status})`); + await poll.body?.cancel(); + if (now() + interval >= deadline) throw new Error("Device authorization timed out"); + await wait(interval); + } + if (!grant?.authorization_code || !grant.code_verifier) throw new Error("Device authorization timed out"); + + const account = await exchangeToken(tokenForm({ + grant_type: "authorization_code", + client_id: options.clientId, + code: grant.authorization_code, + code_verifier: grant.code_verifier, + redirect_uri: `${authOrigin}/deviceauth/callback`, + })); + accounts.set(name, account); + return { + accountId: account.accountId, + verificationUrl: `${authOrigin}/codex/device`, + userCode: device.user_code, + }; + } + + async function currentAccount(name: string): Promise { + const account = accounts.get(name); + if (!account) throw new Error(`Unknown account: ${name}`); + if (account.expiresAt > now()) return account; + const refreshed = await exchangeToken(tokenForm({ + grant_type: "refresh_token", + client_id: options.clientId, + refresh_token: account.refreshToken, + })); + if (refreshed.accountId !== account.accountId) throw new Error("Refresh changed the ChatGPT account identity"); + accounts.set(name, refreshed); + return refreshed; + } + + async function request(name: string, localKey: string, path: "/v1/models" | "/v1/responses", body?: BodyInit): Promise { + if (localKey !== options.localApiKey) throw new Error("Invalid local proxy key"); + const account = await currentAccount(name); + const suffix = path === "/v1/models" ? "/models" : "/responses"; + const upstream = await fetchBounded(`${upstreamOrigin}${suffix}`, { + method: path === "/v1/models" ? "GET" : "POST", + headers: { + authorization: `Bearer ${account.accessToken}`, + "chatgpt-account-id": account.accountId, + ...(path === "/v1/responses" ? { "content-type": "application/json", accept: "text/event-stream" } : {}), + }, + body: path === "/v1/responses" ? body : undefined, + redirect: "error", + }); + if (path === "/v1/responses" || !upstream.ok) return upstream; + const catalog = await upstream.json() as { models?: Array<{ slug?: unknown; supported_in_api?: unknown }> }; + if (!Array.isArray(catalog.models)) throw new Error("Codex model catalog response is invalid"); + const data = catalog.models + .filter((model) => model.supported_in_api === true && typeof model.slug === "string") + .map((model) => ({ id: model.slug as string, object: "model" })); + return Response.json({ object: "list", data }, { headers: { "content-type": "application/json" } }); + } + + return { + login, + request, + /** Test-only metadata; token values remain inaccessible to the simulated agent. */ + inspectAccount(name: string): Readonly> | undefined { + const account = accounts.get(name); + if (!account) return undefined; + return { accountId: account.accountId, expiresAt: account.expiresAt }; + }, + }; +} diff --git a/packages/api/test/codex-subscription-proof.test.ts b/packages/api/test/codex-subscription-proof.test.ts new file mode 100644 index 00000000..165d3a00 --- /dev/null +++ b/packages/api/test/codex-subscription-proof.test.ts @@ -0,0 +1,160 @@ +import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; +import { afterEach, describe, expect, it } from "vitest"; +import { createCodexSubscriptionProof } from "../src/codex-subscription-proof.js"; + +function jwt(accountId: string): string { + const payload = Buffer.from(JSON.stringify({ + "https://api.openai.com/auth": { chatgpt_account_id: accountId }, + })).toString("base64url"); + return `synthetic.${payload}.signature`; +} + +async function bodyOf(request: IncomingMessage): Promise { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(Buffer.from(chunk)); + return Buffer.concat(chunks).toString("utf8"); +} + +function reply(response: ServerResponse, status: number, value: unknown): void { + response.writeHead(status, { "content-type": "application/json" }); + response.end(JSON.stringify(value)); +} + +describe("Codex subscription protocol proof", () => { + let closeServer: (() => Promise) | undefined; + afterEach(async () => closeServer?.()); + + it("owns device login and refresh, isolates accounts, discovers models, and relays SSE without exposing account tokens", async () => { + let now = 10_000; + const deviceStarts = new Map(); + const upstreamRequests: Array<{ path: string; authorization?: string; accountId?: string; body: string }> = []; + const server = createServer(async (request, response) => { + const body = await bodyOf(request); + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + if (url.pathname.slice(1) === "api/accounts/deviceauth/usercode") { + const ordinal = deviceStarts.size + 1; + const deviceId = `device-${ordinal}`; + deviceStarts.set(deviceId, 0); + reply(response, 200, { device_auth_id: deviceId, user_code: `USER-${ordinal}`, interval: 1 }); + return; + } + if (url.pathname.slice(1) === "api/accounts/deviceauth/token") { + const poll = JSON.parse(body) as { device_auth_id: string; user_code: string }; + const count = deviceStarts.get(poll.device_auth_id); + if (count === undefined || poll.user_code !== `USER-${Number(poll.device_auth_id.slice(-1))}`) { + reply(response, 400, { error: "invalid_device" }); + return; + } + if (count === 0) { + deviceStarts.set(poll.device_auth_id, 1); + reply(response, 403, { error: "authorization_pending" }); + return; + } + reply(response, 200, { + authorization_code: `code-${poll.device_auth_id}`, + code_verifier: `verifier-${poll.device_auth_id}`, + code_challenge: "synthetic-challenge", + }); + return; + } + if (url.pathname === "/oauth/token") { + const form = new URLSearchParams(body); + if (form.get("grant_type") === "authorization_code") { + const accountId = form.get("code")?.endsWith("device-1") ? "account-a" : "account-b"; + reply(response, 200, { + access_token: `synthetic-access-${accountId}-v1`, + refresh_token: `synthetic-refresh-${accountId}-v1`, + expires_in: accountId === "account-a" ? 2 : 20, + id_token: jwt(accountId), + }); + return; + } + if (form.get("grant_type") === "refresh_token") { + const accountId = form.get("refresh_token")?.includes("account-a") ? "account-a" : "account-b"; + reply(response, 200, { + access_token: `synthetic-access-${accountId}-v2`, + refresh_token: `synthetic-refresh-${accountId}-v2`, + expires_in: 20, + id_token: jwt(accountId), + }); + return; + } + reply(response, 400, { error: "unsupported_grant" }); + return; + } + if (url.pathname === "/backend-api/codex/models" || url.pathname === "/backend-api/codex/responses") { + const accountHeader = request.headers["chatgpt-account-id"]; + upstreamRequests.push({ + path: url.pathname, + authorization: request.headers.authorization, + accountId: Array.isArray(accountHeader) ? accountHeader[0] : accountHeader, + body, + }); + if (url.pathname.endsWith("/models")) { + reply(response, 200, { models: [ + { slug: "gpt-5-codex", display_name: "GPT-5 Codex", supported_in_api: true }, + { slug: "hidden-preview", display_name: "Hidden preview", supported_in_api: false }, + ] }); + return; + } + response.writeHead(200, { "content-type": "text/event-stream" }); + response.write('data: {"type":"response.output_text.delta","delta":"synthetic stream"}\n\n'); + response.end('data: {"type":"response.completed"}\n\n'); + return; + } + reply(response, 404, { error: "not_found" }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Fixture server did not bind TCP"); + const origin = `http://127.0.0.1:${address.port}`; + closeServer = () => new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + + const adapter = createCodexSubscriptionProof({ + authOrigin: origin, + upstreamOrigin: `${origin}/backend-api/codex`, + clientId: "synthetic-codex-client", + localApiKey: "local-agent-key", + now: () => now, + wait: async (milliseconds) => { now += milliseconds; }, + }); + + const loginA = await adapter.login("work"); + const loginB = await adapter.login("personal"); + expect(loginA).toMatchObject({ accountId: "account-a", verificationUrl: `${origin}/codex/device`, userCode: "USER-1" }); + expect(loginB.accountId).toBe("account-b"); + expect(adapter.inspectAccount("work")).toMatchObject({ accountId: "account-a" }); + expect(adapter.inspectAccount("work")).not.toHaveProperty("accessToken"); + + const models = await adapter.request("work", "local-agent-key", "/v1/models"); + const modelResult = await models.json(); + expect(modelResult).toMatchObject({ data: [{ id: "gpt-5-codex" }] }); + + now += 3_000; + const stream = await adapter.request("work", "local-agent-key", "/v1/responses", JSON.stringify({ model: "gpt-5-codex", stream: true })); + const streamedText = await stream.text(); + expect(streamedText).toContain('"delta":"synthetic stream"'); + expect(streamedText).toContain('"type":"response.completed"'); + + await adapter.request("personal", "local-agent-key", "/v1/models"); + expect(upstreamRequests.map(({ accountId }) => accountId)).toEqual(["account-a", "account-a", "account-b"]); + expect(upstreamRequests[0]?.authorization).toBe("Bearer synthetic-access-account-a-v1"); + expect(upstreamRequests[1]?.authorization).toBe("Bearer synthetic-access-account-a-v2"); + expect(upstreamRequests[2]?.authorization).toBe("Bearer synthetic-access-account-b-v1"); + expect(upstreamRequests[1]?.path).toBe("/backend-api/codex/responses"); + expect(upstreamRequests[1]?.body).toContain('"stream":true'); + + // The simulated agent sees only the local result. Upstream synthetic OAuth tokens + // are neither response headers nor body content, and the local key is not forwarded. + for (const responseForAgent of [models, stream]) { + expect(responseForAgent.headers.get("authorization")).toBeNull(); + expect(responseForAgent.headers.get("chatgpt-account-id")).toBeNull(); + } + expect(JSON.stringify(modelResult) + streamedText).not.toContain("synthetic-access-"); + expect(JSON.stringify(upstreamRequests)).not.toContain("local-agent-key"); + await expect(adapter.request("work", "wrong-key", "/v1/models")).rejects.toThrow("Invalid local proxy key"); + }, 10_000); +});