xonecas.io
64875
Mc

mini-coder / commit 980bc9c

feat: add OpenAI Codex OAuth login support

- OAuth PKCE flow against auth.openai.com with public Codex client ID
- Fetch models dynamically from chatgpt.com/backend-api/codex/models
- Custom fetch wrapper transforms requests for Codex backend:
  - Moves system/developer message to top-level `instructions`
  - Strips `max_output_tokens` (unsupported)
  - Forces `store: false` and `stream: true` (required by Codex)
- JWT decoding to extract chatgpt-account-id header
- Token refresh support
- Provider auto-discovery for OpenAI OAuth

Sean2026-03-25 980bc9cdff57c3345f8d8f0eb5c2efc9f8b5e617 parent 66d4a36

7 files changed

src/llm-api/model-info-fetch.ts+55−15
@@ -128,21 +128,61 @@ async function fetchZenModels(): Promise<ProviderModelCandidate[] | null> {
128128 }
129129
130130 async function fetchOpenAIModels(): Promise<ProviderModelCandidate[] | null> {
131- const key = process.env.OPENAI_API_KEY;
132- if (!key) return null;
133- return fetchPaginatedModelsList(
134- `${OPENAI_BASE}/v1/models`,
135- { headers: { Authorization: `Bearer ${key}` } },
136- 6_000,
137- "data",
138- "id",
139- (_item, modelId) => ({
140- providerModelId: modelId,
141- displayName: modelId,
142- contextWindow: null,
143- free: false,
144- }),
145- );
131+ const envKey = process.env.OPENAI_API_KEY;
132+ if (envKey) {
133+ return fetchPaginatedModelsList(
134+ `${OPENAI_BASE}/v1/models`,
135+ { headers: { Authorization: `Bearer ${envKey}` } },
136+ 6_000,
137+ "data",
138+ "id",
139+ (_item, modelId) => ({
140+ providerModelId: modelId,
141+ displayName: modelId,
142+ contextWindow: null,
143+ free: false,
144+ }),
145+ );
146+ }
147+ if (isLoggedIn("openai")) {
148+ const token = await getAccessToken("openai");
149+ if (!token) return null;
150+ return fetchCodexOAuthModels(token);
151+ }
152+ return null;
153+}
154+
155+const CODEX_MODELS_URL =
156+ "https://chatgpt.com/backend-api/codex/models?client_version=1.0.0";
157+
158+async function fetchCodexOAuthModels(
159+ token: string,
160+): Promise<ProviderModelCandidate[] | null> {
161+ try {
162+ const res = await fetch(CODEX_MODELS_URL, {
163+ headers: { Authorization: `Bearer ${token}` },
164+ signal: AbortSignal.timeout(6_000),
165+ });
166+ if (!res.ok) return null;
167+ const data = (await res.json()) as {
168+ models: Array<{
169+ slug: string;
170+ display_name: string;
171+ context_window: number | null;
172+ visibility: string;
173+ }>;
174+ };
175+ return (data.models ?? [])
176+ .filter((m) => m.visibility === "list")
177+ .map((m) => ({
178+ providerModelId: m.slug,
179+ displayName: m.display_name || m.slug,
180+ contextWindow: m.context_window,
181+ free: false,
182+ }));
183+ } catch {
184+ return null;
185+ }
146186 }
147187
148188 async function getAnthropicAuth(): Promise<{
src/llm-api/model-info.test.ts+6−1
@@ -37,11 +37,16 @@ describe("provider sync policy", () => {
3737 });
3838
3939 test("snapshot visibility tracks configured providers", () => {
40- expect(isProviderVisibleInSnapshot("openai", {})).toBe(false);
40+ // openai visibility depends on env key OR active OAuth login
4141 expect(isProviderVisibleInSnapshot("openai", { OPENAI_API_KEY: "x" })).toBe(
4242 true,
4343 );
4444 expect(isProviderVisibleInSnapshot("ollama", {})).toBe(true);
45+ // Without env or OAuth, zen should not be visible (zen has no OAuth)
46+ expect(isProviderVisibleInSnapshot("zen", {})).toBe(false);
47+ expect(isProviderVisibleInSnapshot("zen", { OPENCODE_API_KEY: "x" })).toBe(
48+ true,
49+ );
4550 });
4651 });
4752
src/llm-api/model-info.ts+5−3
@@ -33,7 +33,7 @@ import {
3333 const MODELS_DEV_SYNC_KEY = "last_models_dev_sync_at";
3434 const PROVIDER_SYNC_KEY_PREFIX = "last_provider_sync_at:";
3535 const CACHE_VERSION_KEY = "model_info_cache_version";
36-const CACHE_VERSION = 3;
36+const CACHE_VERSION = 5;
3737 export const MODEL_INFO_TTL_MS = 24 * 60 * 60 * 1000;
3838
3939 export {
@@ -117,8 +117,10 @@ export function getRemoteProvidersFromEnv(
117117 ).map((entry) => entry.provider);
118118
119119 // Include providers with OAuth login even without env keys
120- if (!providers.includes("anthropic") && isLoggedIn("anthropic")) {
121- providers.push("anthropic");
120+ for (const p of ["anthropic", "openai"] as const) {
121+ if (!providers.includes(p) && isLoggedIn(p)) {
122+ providers.push(p);
123+ }
122124 }
123125
124126 return providers;
src/llm-api/providers.ts+84−3
@@ -4,6 +4,7 @@ import { createOpenAI } from "@ai-sdk/openai";
44 import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
55 import type { LanguageModel } from "ai";
66 import { getAccessToken, isLoggedIn } from "../session/oauth/auth-storage.ts";
7+import { extractAccountId } from "../session/oauth/openai.ts";
78 import {
89 type AvailableModelsSnapshot,
910 fetchAvailableModelsSnapshot,
@@ -163,7 +164,79 @@ function resolveZenModel(modelId: string): LanguageModel {
163164 return ZEN_BACKEND_RESOLVERS[getZenBackend(modelId)](modelId);
164165 }
165166
166-function resolveOpenAIModel(modelId: string): LanguageModel {
167+function createOAuthOpenAIProvider(token: string): OpenAIProvider {
168+ const accountId = extractAccountId(token);
169+ return createOpenAI({
170+ apiKey: "oauth",
171+ baseURL: OPENAI_CODEX_BASE_URL,
172+ fetch: ((
173+ input: Parameters<ProviderFetch>[0],
174+ init?: Parameters<ProviderFetch>[1],
175+ ) => {
176+ const h = new Headers(
177+ init?.headers as ConstructorParameters<typeof Headers>[0],
178+ );
179+ h.delete("OpenAI-Organization");
180+ h.delete("OpenAI-Project");
181+ h.set("Authorization", `Bearer ${token}`);
182+ if (accountId) h.set("chatgpt-account-id", accountId);
183+
184+ // Transform request body for Codex backend compatibility:
185+ // 1. Move developer/system message from input[] to top-level `instructions`
186+ // 2. Strip unsupported parameters (max_output_tokens, store)
187+ let body = init?.body;
188+ if (typeof body === "string") {
189+ try {
190+ const parsed = JSON.parse(body);
191+ if (parsed.input && Array.isArray(parsed.input)) {
192+ if (!parsed.instructions) {
193+ const sysIdx = parsed.input.findIndex(
194+ (m: Record<string, string>) =>
195+ m.role === "developer" || m.role === "system",
196+ );
197+ if (sysIdx !== -1) {
198+ const sysMsg = parsed.input[sysIdx];
199+ parsed.instructions =
200+ typeof sysMsg.content === "string"
201+ ? sysMsg.content
202+ : JSON.stringify(sysMsg.content);
203+ parsed.input.splice(sysIdx, 1);
204+ }
205+ }
206+ delete parsed.max_output_tokens;
207+ parsed.store = false;
208+ parsed.stream = true;
209+ body = JSON.stringify(parsed);
210+ }
211+ } catch {
212+ // not JSON, pass through
213+ }
214+ }
215+
216+ return fetch(input, {
217+ ...init,
218+ body,
219+ headers: Object.fromEntries(h.entries()),
220+ });
221+ }) as ProviderFetch,
222+ });
223+}
224+
225+async function resolveOpenAIModel(modelId: string): Promise<LanguageModel> {
226+ // OAuth token takes priority over env var
227+ if (isLoggedIn("openai")) {
228+ const token = await getAccessToken("openai");
229+ if (token) {
230+ if (!oauthOpenAICache || oauthOpenAICache.token !== token) {
231+ oauthOpenAICache = {
232+ token,
233+ provider: createOAuthOpenAIProvider(token),
234+ };
235+ }
236+ return oauthOpenAICache.provider.responses(modelId);
237+ }
238+ }
239+ // Fallback to OPENAI_API_KEY env var
167240 return modelId.startsWith("gpt-")
168241 ? directProviders.openai().responses(modelId)
169242 : directProviders.openai()(modelId);
@@ -173,10 +246,15 @@ type AsyncModelResolver = (
173246 modelId: string,
174247 ) => LanguageModel | Promise<LanguageModel>;
175248
249+const OPENAI_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex";
250+
176251 /** Cache the OAuth-backed Anthropic provider keyed by access token. */
177252 let oauthAnthropicCache: { token: string; provider: AnthropicProvider } | null =
178253 null;
179254
255+/** Cache the OAuth-backed OpenAI Codex provider keyed by access token. */
256+let oauthOpenAICache: { token: string; provider: OpenAIProvider } | null = null;
257+
180258 function createOAuthAnthropicProvider(token: string): AnthropicProvider {
181259 return createAnthropic({
182260 // Use empty apiKey + custom fetch (like opencode) instead of authToken.
@@ -261,7 +339,9 @@ export function discoverConnectedProviders(): ConnectedProvider[] {
261339 if (isLoggedIn("anthropic")) result.push({ name: "anthropic", via: "oauth" });
262340 else if (process.env.ANTHROPIC_API_KEY)
263341 result.push({ name: "anthropic", via: "env" });
264- if (process.env.OPENAI_API_KEY) result.push({ name: "openai", via: "env" });
342+ if (isLoggedIn("openai")) result.push({ name: "openai", via: "oauth" });
343+ else if (process.env.OPENAI_API_KEY)
344+ result.push({ name: "openai", via: "env" });
265345 if (process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY)
266346 result.push({ name: "google", via: "env" });
267347 if (process.env.OLLAMA_BASE_URL) result.push({ name: "ollama", via: "env" });
@@ -272,7 +352,8 @@ export function autoDiscoverModel(): string {
272352 if (process.env.OPENCODE_API_KEY) return "zen/claude-sonnet-4-6";
273353 if (process.env.ANTHROPIC_API_KEY || isLoggedIn("anthropic"))
274354 return "anthropic/claude-sonnet-4-6";
275- if (process.env.OPENAI_API_KEY) return "openai/gpt-5.4";
355+ if (process.env.OPENAI_API_KEY || isLoggedIn("openai"))
356+ return "openai/gpt-5.4";
276357 if (process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY)
277358 return "google/gemini-3.1-pro";
278359 return "ollama/llama3.2";
src/session/oauth/auth-storage.ts+2−0
@@ -6,6 +6,7 @@
66
77 import { getDb } from "../db/connection.ts";
88 import { anthropicOAuth } from "./anthropic.ts";
9+import { openaiOAuth } from "./openai.ts";
910 import type {
1011 OAuthCredentials,
1112 OAuthLoginCallbacks,
@@ -22,6 +23,7 @@ interface OAuthTokenRow {
2223
2324 const PROVIDERS: ReadonlyMap<string, OAuthProviderConfig> = new Map([
2425 [anthropicOAuth.id, anthropicOAuth],
26+ [openaiOAuth.id, openaiOAuth],
2527 ]);
2628
2729 export function getOAuthProviders(): OAuthProviderConfig[] {
src/session/oauth/openai.test.ts+29−0
@@ -0,0 +1,29 @@
1+import { describe, expect, test } from "bun:test";
2+import { extractAccountId } from "./openai.ts";
3+
4+describe("extractAccountId", () => {
5+ test("extracts account ID from a valid JWT", () => {
6+ const payload = {
7+ "https://api.openai.com/auth": {
8+ chatgpt_account_id: "acct_abc123",
9+ },
10+ };
11+ const header = btoa(JSON.stringify({ alg: "RS256" }));
12+ const body = btoa(JSON.stringify(payload));
13+ const token = `${header}.${body}.fake-sig`;
14+ expect(extractAccountId(token)).toBe("acct_abc123");
15+ });
16+
17+ test("returns null for a JWT without the claim", () => {
18+ const payload = { sub: "user123" };
19+ const header = btoa(JSON.stringify({ alg: "RS256" }));
20+ const body = btoa(JSON.stringify(payload));
21+ const token = `${header}.${body}.fake-sig`;
22+ expect(extractAccountId(token)).toBeNull();
23+ });
24+
25+ test("returns null for non-JWT strings", () => {
26+ expect(extractAccountId("sk-abc123")).toBeNull();
27+ expect(extractAccountId("")).toBeNull();
28+ });
29+});
src/session/oauth/openai.ts+207−0
@@ -0,0 +1,207 @@
1+/**
2+ * OpenAI Codex OAuth flow (ChatGPT Plus/Pro subscription).
3+ *
4+ * Uses Authorization Code + PKCE against auth.openai.com.
5+ * Starts a local HTTP callback server for the redirect.
6+ * Tokens are used against chatgpt.com/backend-api/codex (Responses API).
7+ */
8+
9+import { createServer, type Server } from "node:http";
10+import { generatePKCE } from "./pkce.ts";
11+import type {
12+ OAuthCredentials,
13+ OAuthLoginCallbacks,
14+ OAuthProviderConfig,
15+} from "./types.ts";
16+
17+const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
18+const AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";
19+const TOKEN_URL = "https://auth.openai.com/oauth/token";
20+const CALLBACK_HOST = "127.0.0.1";
21+const CALLBACK_PORT = 1455;
22+const CALLBACK_PATH = "/auth/callback";
23+const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
24+const SCOPES = "openid profile email offline_access";
25+
26+const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
27+
28+const SUCCESS_HTML = `<!doctype html>
29+<html lang="en"><head><meta charset="utf-8"><title>Authenticated</title></head>
30+<body><p>OpenAI authentication successful. Return to your terminal.</p></body></html>`;
31+
32+function createState(): string {
33+ const bytes = new Uint8Array(16);
34+ crypto.getRandomValues(bytes);
35+ let hex = "";
36+ for (const b of bytes) hex += b.toString(16).padStart(2, "0");
37+ return hex;
38+}
39+
40+function startCallbackServer(expectedState: string): Promise<{
41+ server: Server;
42+ waitForCode: () => Promise<{ code: string } | null>;
43+ cancel: () => void;
44+}> {
45+ return new Promise((resolve, reject) => {
46+ let result: { code: string } | null = null;
47+ let cancelled = false;
48+
49+ const server = createServer((req, res) => {
50+ const url = new URL(req.url ?? "", "http://localhost");
51+ if (url.pathname !== CALLBACK_PATH) {
52+ res.writeHead(404).end("Not found");
53+ return;
54+ }
55+
56+ const code = url.searchParams.get("code");
57+ const state = url.searchParams.get("state");
58+ const error = url.searchParams.get("error");
59+
60+ if (error || !code || !state || state !== expectedState) {
61+ res.writeHead(400).end("Authentication failed.");
62+ return;
63+ }
64+
65+ res.writeHead(200, { "Content-Type": "text/html" }).end(SUCCESS_HTML);
66+ result = { code };
67+ });
68+
69+ server.on("error", reject);
70+ server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
71+ resolve({
72+ server,
73+ cancel: () => {
74+ cancelled = true;
75+ },
76+ waitForCode: async () => {
77+ const deadline = Date.now() + LOGIN_TIMEOUT_MS;
78+ while (!result && !cancelled && Date.now() < deadline) {
79+ await new Promise((r) => setTimeout(r, 100));
80+ }
81+ return result;
82+ },
83+ });
84+ });
85+ });
86+}
87+
88+async function postTokenRequest(
89+ body: URLSearchParams,
90+ label: string,
91+): Promise<OAuthCredentials> {
92+ const res = await fetch(TOKEN_URL, {
93+ method: "POST",
94+ headers: {
95+ "Content-Type": "application/x-www-form-urlencoded",
96+ },
97+ body,
98+ signal: AbortSignal.timeout(30_000),
99+ });
100+
101+ if (!res.ok) {
102+ const text = await res.text();
103+ throw new Error(`${label} failed (${res.status}): ${text}`);
104+ }
105+
106+ const data = (await res.json()) as {
107+ access_token: string;
108+ refresh_token: string;
109+ expires_in: number;
110+ };
111+
112+ return {
113+ access: data.access_token,
114+ refresh: data.refresh_token,
115+ // Expire 5 minutes early to avoid edge cases
116+ expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,
117+ };
118+}
119+
120+function exchangeCode(
121+ code: string,
122+ verifier: string,
123+): Promise<OAuthCredentials> {
124+ return postTokenRequest(
125+ new URLSearchParams({
126+ grant_type: "authorization_code",
127+ client_id: CLIENT_ID,
128+ code,
129+ code_verifier: verifier,
130+ redirect_uri: REDIRECT_URI,
131+ }),
132+ "Token exchange",
133+ );
134+}
135+
136+function refreshOpenAIToken(refreshToken: string): Promise<OAuthCredentials> {
137+ return postTokenRequest(
138+ new URLSearchParams({
139+ grant_type: "refresh_token",
140+ refresh_token: refreshToken,
141+ client_id: CLIENT_ID,
142+ }),
143+ "Token refresh",
144+ );
145+}
146+
147+async function loginOpenAI(
148+ callbacks: OAuthLoginCallbacks,
149+): Promise<OAuthCredentials> {
150+ const { verifier, challenge } = await generatePKCE();
151+ const state = createState();
152+ const cb = await startCallbackServer(state);
153+
154+ try {
155+ const params = new URLSearchParams({
156+ response_type: "code",
157+ client_id: CLIENT_ID,
158+ redirect_uri: REDIRECT_URI,
159+ scope: SCOPES,
160+ code_challenge: challenge,
161+ code_challenge_method: "S256",
162+ state,
163+ id_token_add_organizations: "true",
164+ codex_cli_simplified_flow: "true",
165+ originator: "mc",
166+ });
167+
168+ callbacks.onOpenUrl(
169+ `${AUTHORIZE_URL}?${params}`,
170+ "Complete login in your browser.",
171+ );
172+
173+ const result = await cb.waitForCode();
174+ if (!result) throw new Error("Login cancelled or no code received");
175+
176+ callbacks.onProgress("Exchanging authorization code for tokens…");
177+ return exchangeCode(result.code, verifier);
178+ } finally {
179+ cb.server.close();
180+ }
181+}
182+
183+/**
184+ * Extract chatgpt_account_id from the OAuth JWT access token.
185+ * Returns null if the token is not a JWT or lacks the claim.
186+ */
187+export function extractAccountId(accessToken: string): string | null {
188+ try {
189+ const parts = accessToken.split(".");
190+ const jwt = parts[1];
191+ if (parts.length !== 3 || !jwt) return null;
192+ const payload = JSON.parse(atob(jwt)) as Record<string, unknown>;
193+ const auth = payload["https://api.openai.com/auth"] as
194+ | { chatgpt_account_id?: string }
195+ | undefined;
196+ return auth?.chatgpt_account_id ?? null;
197+ } catch {
198+ return null;
199+ }
200+}
201+
202+export const openaiOAuth: OAuthProviderConfig = {
203+ id: "openai",
204+ name: "OpenAI (ChatGPT Plus/Pro)",
205+ login: loginOpenAI,
206+ refreshToken: refreshOpenAIToken,
207+};