Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions docs/decisions/gen-2825-codex-subscription-protocol.md
Original file line number Diff line number Diff line change
@@ -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 <access token>` and `chatgpt-account-id: <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.
178 changes: 178 additions & 0 deletions packages/api/src/codex-subscription-proof.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
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<string, string>): 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<string, CodexProofAccount>();
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<Response> {
return fetchImpl(input, { ...init, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
}

async function exchangeToken(body: URLSearchParams): Promise<CodexProofAccount> {
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<CodexProofAccount> {
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<Response> {
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<Omit<CodexProofAccount, "accessToken" | "refreshToken">> | undefined {
const account = accounts.get(name);
if (!account) return undefined;
return { accountId: account.accountId, expiresAt: account.expiresAt };
},
};
}
Loading
Loading