@@ -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+};