openai-codex-oauth.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. loginOpenAICodex,
  4. loginOpenAICodexDeviceCode,
  5. openaiCodexOAuthProvider,
  6. refreshOpenAICodexToken,
  7. } from "../src/utils/oauth/openai-codex.ts";
  8. function jsonResponse(body: unknown, status: number = 200): Response {
  9. return new Response(JSON.stringify(body), {
  10. status,
  11. headers: { "Content-Type": "application/json" },
  12. });
  13. }
  14. function getUrl(input: unknown): string {
  15. if (typeof input === "string") return input;
  16. if (input instanceof URL) return input.toString();
  17. if (input instanceof Request) return input.url;
  18. throw new Error(`Unsupported fetch input: ${String(input)}`);
  19. }
  20. function createAccessToken(accountId: string): string {
  21. const header = Buffer.from(JSON.stringify({ alg: "none" })).toString("base64");
  22. const payload = Buffer.from(
  23. JSON.stringify({
  24. "https://api.openai.com/auth": {
  25. chatgpt_account_id: accountId,
  26. },
  27. }),
  28. ).toString("base64");
  29. return `${header}.${payload}.signature`;
  30. }
  31. function deviceAuthPendingResponse(): Response {
  32. return jsonResponse(
  33. {
  34. error: {
  35. message: "Device authorization is pending. Please try again.",
  36. type: "invalid_request_error",
  37. param: null,
  38. code: "deviceauth_authorization_pending",
  39. },
  40. },
  41. 403,
  42. );
  43. }
  44. describe("OpenAI Codex OAuth", () => {
  45. afterEach(() => {
  46. vi.restoreAllMocks();
  47. vi.unstubAllGlobals();
  48. vi.useRealTimers();
  49. });
  50. it("uses the injected fetch for browser authorization code exchange", async () => {
  51. const accessToken = createAccessToken("account-browser");
  52. let authorizationUrl = "";
  53. const injectedFetch = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
  54. expect(getUrl(input)).toBe("https://auth.openai.com/oauth/token");
  55. expect(init?.method).toBe("POST");
  56. expect(init?.headers).toMatchObject({ "Content-Type": "application/x-www-form-urlencoded" });
  57. const params = new URLSearchParams(String(init?.body));
  58. expect(params.get("grant_type")).toBe("authorization_code");
  59. expect(params.get("code")).toBe("oauth-code");
  60. return jsonResponse({
  61. access_token: accessToken,
  62. refresh_token: "refresh-token",
  63. expires_in: 3600,
  64. });
  65. });
  66. const globalFetch = vi.fn(async () => {
  67. throw new Error("global fetch should not be used");
  68. });
  69. vi.stubGlobal("fetch", globalFetch);
  70. await expect(
  71. loginOpenAICodex({
  72. onAuth: ({ url }) => {
  73. authorizationUrl = url;
  74. },
  75. onPrompt: async () => {
  76. throw new Error("Prompt should not be used");
  77. },
  78. onManualCodeInput: async () => {
  79. const state = new URL(authorizationUrl).searchParams.get("state");
  80. if (!state) throw new Error("Authorization state was not provided");
  81. return `http://localhost:1455/auth/callback?code=oauth-code&state=${state}`;
  82. },
  83. onSelect: async () => "browser",
  84. fetch: injectedFetch as typeof fetch,
  85. }),
  86. ).resolves.toMatchObject({
  87. access: accessToken,
  88. refresh: "refresh-token",
  89. accountId: "account-browser",
  90. });
  91. expect(injectedFetch).toHaveBeenCalledTimes(1);
  92. expect(globalFetch).not.toHaveBeenCalled();
  93. });
  94. it("logs in with the OpenAI Codex device code flow", async () => {
  95. vi.useFakeTimers();
  96. const startTime = new Date("2026-05-20T00:00:00Z");
  97. vi.setSystemTime(startTime);
  98. const accessToken = createAccessToken("account-123");
  99. const deviceInfos: Array<{
  100. userCode: string;
  101. verificationUri: string;
  102. instructions?: string;
  103. intervalSeconds?: number;
  104. expiresInSeconds?: number;
  105. }> = [];
  106. const pollTimes: number[] = [];
  107. const pollResponses = [
  108. deviceAuthPendingResponse(),
  109. jsonResponse({
  110. authorization_code: "oauth-code",
  111. code_challenge: "device-code-challenge",
  112. code_verifier: "device-code-verifier",
  113. }),
  114. ];
  115. const fetchMock = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
  116. const url = getUrl(input);
  117. if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
  118. expect(init?.method).toBe("POST");
  119. expect(init?.headers).toMatchObject({ "Content-Type": "application/json" });
  120. expect(JSON.parse(String(init?.body))).toEqual({ client_id: "app_EMoamEEZ73f0CkXaXp7hrann" });
  121. return jsonResponse({
  122. device_auth_id: "device-auth-id",
  123. user_code: "ABCD-1234",
  124. interval: "5",
  125. });
  126. }
  127. if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
  128. pollTimes.push(Date.now());
  129. expect(init?.method).toBe("POST");
  130. expect(init?.headers).toMatchObject({ "Content-Type": "application/json" });
  131. expect(JSON.parse(String(init?.body))).toEqual({
  132. device_auth_id: "device-auth-id",
  133. user_code: "ABCD-1234",
  134. });
  135. const response = pollResponses.shift();
  136. if (!response) {
  137. throw new Error("Unexpected extra device auth poll");
  138. }
  139. return response;
  140. }
  141. if (url === "https://auth.openai.com/oauth/token") {
  142. expect(init?.method).toBe("POST");
  143. expect(init?.headers).toMatchObject({ "Content-Type": "application/x-www-form-urlencoded" });
  144. const params = new URLSearchParams(String(init?.body));
  145. expect(params.get("grant_type")).toBe("authorization_code");
  146. expect(params.get("client_id")).toBe("app_EMoamEEZ73f0CkXaXp7hrann");
  147. expect(params.get("code")).toBe("oauth-code");
  148. expect(params.get("redirect_uri")).toBe("https://auth.openai.com/deviceauth/callback");
  149. expect(params.get("code_verifier")).toBe("device-code-verifier");
  150. return jsonResponse({
  151. access_token: accessToken,
  152. refresh_token: "refresh-token",
  153. expires_in: 3600,
  154. });
  155. }
  156. throw new Error(`Unexpected fetch URL: ${url}`);
  157. });
  158. vi.stubGlobal("fetch", fetchMock);
  159. const credentialsPromise = loginOpenAICodexDeviceCode({
  160. onDeviceCode: (info) => deviceInfos.push(info),
  161. });
  162. for (let i = 0; i < 5 && pollTimes.length === 0; i++) {
  163. await vi.advanceTimersByTimeAsync(0);
  164. }
  165. expect(deviceInfos).toEqual([
  166. {
  167. userCode: "ABCD-1234",
  168. verificationUri: "https://auth.openai.com/codex/device",
  169. intervalSeconds: 5,
  170. expiresInSeconds: 900,
  171. },
  172. ]);
  173. expect(pollTimes).toEqual([startTime.getTime()]);
  174. await vi.advanceTimersByTimeAsync(4999);
  175. expect(pollTimes).toEqual([startTime.getTime()]);
  176. await vi.advanceTimersByTimeAsync(1);
  177. await expect(credentialsPromise).resolves.toMatchObject({
  178. access: accessToken,
  179. refresh: "refresh-token",
  180. expires: startTime.getTime() + 5000 + 3600 * 1000,
  181. accountId: "account-123",
  182. });
  183. expect(pollTimes).toEqual([startTime.getTime(), startTime.getTime() + 5000]);
  184. });
  185. it("offers browser login first and uses the selected OpenAI Codex device code flow", async () => {
  186. const accessToken = createAccessToken("account-456");
  187. const selectPrompts: Array<{
  188. message: string;
  189. options: Array<{ id: string; label: string }>;
  190. }> = [];
  191. const deviceInfos: Array<{
  192. userCode: string;
  193. verificationUri: string;
  194. intervalSeconds?: number;
  195. expiresInSeconds?: number;
  196. }> = [];
  197. vi.stubGlobal(
  198. "fetch",
  199. vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
  200. const url = getUrl(input);
  201. if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
  202. expect(JSON.parse(String(init?.body))).toEqual({ client_id: "app_EMoamEEZ73f0CkXaXp7hrann" });
  203. return jsonResponse({
  204. device_auth_id: "device-auth-id",
  205. user_code: "WXYZ-7890",
  206. interval: "5",
  207. });
  208. }
  209. if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
  210. return jsonResponse({
  211. authorization_code: "oauth-code",
  212. code_challenge: "device-code-challenge",
  213. code_verifier: "device-code-verifier",
  214. });
  215. }
  216. if (url === "https://auth.openai.com/oauth/token") {
  217. return jsonResponse({
  218. access_token: accessToken,
  219. refresh_token: "refresh-token",
  220. expires_in: 3600,
  221. });
  222. }
  223. throw new Error(`Unexpected fetch URL: ${url}`);
  224. }),
  225. );
  226. await expect(
  227. openaiCodexOAuthProvider.login({
  228. onAuth: () => {
  229. throw new Error("Browser login should not start");
  230. },
  231. onDeviceCode: (info) => deviceInfos.push(info),
  232. onPrompt: async () => {
  233. throw new Error("Prompt should not be used");
  234. },
  235. onSelect: async (prompt) => {
  236. selectPrompts.push(prompt);
  237. return "device_code";
  238. },
  239. }),
  240. ).resolves.toMatchObject({
  241. access: accessToken,
  242. refresh: "refresh-token",
  243. accountId: "account-456",
  244. });
  245. expect(selectPrompts).toEqual([
  246. {
  247. message: "Select OpenAI Codex login method:",
  248. options: [
  249. { id: "browser", label: "Browser login (default)" },
  250. { id: "device_code", label: "Device code login (headless)" },
  251. ],
  252. },
  253. ]);
  254. expect(deviceInfos).toEqual([
  255. {
  256. userCode: "WXYZ-7890",
  257. verificationUri: "https://auth.openai.com/codex/device",
  258. intervalSeconds: 5,
  259. expiresInSeconds: 900,
  260. },
  261. ]);
  262. });
  263. it("refreshes tokens through the injected fetch implementation", async () => {
  264. const accessToken = createAccessToken("account-refresh");
  265. const injectedFetch = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
  266. expect(getUrl(input)).toBe("https://auth.openai.com/oauth/token");
  267. expect(init?.method).toBe("POST");
  268. expect(init?.headers).toMatchObject({ "Content-Type": "application/x-www-form-urlencoded" });
  269. const params = new URLSearchParams(String(init?.body));
  270. expect(params.get("grant_type")).toBe("refresh_token");
  271. expect(params.get("refresh_token")).toBe("refresh-token");
  272. return jsonResponse({
  273. access_token: accessToken,
  274. refresh_token: "next-refresh-token",
  275. expires_in: 3600,
  276. });
  277. });
  278. const globalFetch = vi.fn(async () => {
  279. throw new Error("global fetch should not be used");
  280. });
  281. vi.stubGlobal("fetch", globalFetch);
  282. await expect(refreshOpenAICodexToken("refresh-token", injectedFetch as typeof fetch)).resolves.toMatchObject({
  283. access: accessToken,
  284. refresh: "next-refresh-token",
  285. accountId: "account-refresh",
  286. });
  287. expect(injectedFetch).toHaveBeenCalledTimes(1);
  288. expect(globalFetch).not.toHaveBeenCalled();
  289. });
  290. it("cancels when OpenAI Codex login method selection is cancelled", async () => {
  291. await expect(
  292. openaiCodexOAuthProvider.login({
  293. onAuth: () => {},
  294. onDeviceCode: () => {},
  295. onPrompt: async () => "",
  296. onSelect: async () => undefined,
  297. }),
  298. ).rejects.toThrow("Login cancelled");
  299. });
  300. it("cancels the OpenAI Codex device code flow while waiting", async () => {
  301. vi.useFakeTimers();
  302. const controller = new AbortController();
  303. const pollTimes: number[] = [];
  304. vi.stubGlobal(
  305. "fetch",
  306. vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
  307. const url = getUrl(input);
  308. if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
  309. expect(JSON.parse(String(init?.body))).toEqual({ client_id: "app_EMoamEEZ73f0CkXaXp7hrann" });
  310. return jsonResponse({
  311. device_auth_id: "device-auth-id",
  312. user_code: "ABCD-1234",
  313. interval: "5",
  314. });
  315. }
  316. if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
  317. pollTimes.push(Date.now());
  318. return deviceAuthPendingResponse();
  319. }
  320. throw new Error(`Unexpected fetch URL: ${url}`);
  321. }),
  322. );
  323. const credentialsPromise = loginOpenAICodexDeviceCode({
  324. onDeviceCode: () => {},
  325. signal: controller.signal,
  326. });
  327. const rejectionPromise = credentialsPromise.then(
  328. () => new Error("Expected login to fail"),
  329. (error: unknown) => error,
  330. );
  331. for (let i = 0; i < 5 && pollTimes.length === 0; i++) {
  332. await vi.advanceTimersByTimeAsync(0);
  333. }
  334. expect(pollTimes).toHaveLength(1);
  335. controller.abort();
  336. const rejection = await rejectionPromise;
  337. expect(rejection).toBeInstanceOf(Error);
  338. expect((rejection as Error).message).toBe("Login cancelled");
  339. });
  340. it("times out the OpenAI Codex device code flow after 15 minutes", async () => {
  341. vi.useFakeTimers();
  342. const pollTimes: number[] = [];
  343. vi.stubGlobal(
  344. "fetch",
  345. vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
  346. const url = getUrl(input);
  347. if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
  348. expect(JSON.parse(String(init?.body))).toEqual({ client_id: "app_EMoamEEZ73f0CkXaXp7hrann" });
  349. return jsonResponse({
  350. device_auth_id: "device-auth-id",
  351. user_code: "ABCD-1234",
  352. interval: "60",
  353. });
  354. }
  355. if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
  356. pollTimes.push(Date.now());
  357. return deviceAuthPendingResponse();
  358. }
  359. throw new Error(`Unexpected fetch URL: ${url}`);
  360. }),
  361. );
  362. const credentialsPromise = loginOpenAICodexDeviceCode({
  363. onDeviceCode: () => {},
  364. });
  365. const rejectionPromise = credentialsPromise.then(
  366. () => new Error("Expected login to fail"),
  367. (error: unknown) => error,
  368. );
  369. for (let i = 0; i < 5 && pollTimes.length === 0; i++) {
  370. await vi.advanceTimersByTimeAsync(0);
  371. }
  372. expect(pollTimes).toHaveLength(1);
  373. await vi.advanceTimersByTimeAsync(15 * 60 * 1000);
  374. const rejection = await rejectionPromise;
  375. expect(rejection).toBeInstanceOf(Error);
  376. expect((rejection as Error).message).toBe("Device flow timed out");
  377. });
  378. it("treats OpenAI Codex device auth 403 and 404 responses as pending", async () => {
  379. vi.useFakeTimers();
  380. const accessToken = createAccessToken("account-403-404");
  381. const pollTimes: number[] = [];
  382. const pollResponses = [
  383. jsonResponse({ error: "access_denied", error_description: "denied" }, 403),
  384. new Response("not ready", { status: 404, headers: { "Content-Type": "text/plain" } }),
  385. jsonResponse({
  386. authorization_code: "oauth-code",
  387. code_challenge: "device-code-challenge",
  388. code_verifier: "device-code-verifier",
  389. }),
  390. ];
  391. vi.stubGlobal(
  392. "fetch",
  393. vi.fn(async (input: unknown): Promise<Response> => {
  394. const url = getUrl(input);
  395. if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
  396. return jsonResponse({
  397. device_auth_id: "device-auth-id",
  398. user_code: "ABCD-1234",
  399. interval: "1",
  400. });
  401. }
  402. if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
  403. pollTimes.push(Date.now());
  404. const response = pollResponses.shift();
  405. if (!response) {
  406. throw new Error("Unexpected extra device auth poll");
  407. }
  408. return response;
  409. }
  410. if (url === "https://auth.openai.com/oauth/token") {
  411. return jsonResponse({
  412. access_token: accessToken,
  413. refresh_token: "refresh-token",
  414. expires_in: 3600,
  415. });
  416. }
  417. throw new Error(`Unexpected fetch URL: ${url}`);
  418. }),
  419. );
  420. const credentialsPromise = loginOpenAICodexDeviceCode({
  421. onDeviceCode: () => {},
  422. });
  423. for (let i = 0; i < 5 && pollTimes.length === 0; i++) {
  424. await vi.advanceTimersByTimeAsync(0);
  425. }
  426. await vi.advanceTimersByTimeAsync(1000);
  427. await vi.advanceTimersByTimeAsync(1000);
  428. await expect(credentialsPromise).resolves.toMatchObject({
  429. access: accessToken,
  430. refresh: "refresh-token",
  431. accountId: "account-403-404",
  432. });
  433. expect(pollTimes).toHaveLength(3);
  434. });
  435. it("includes the response body in OpenAI Codex device auth poll failures", async () => {
  436. vi.stubGlobal(
  437. "fetch",
  438. vi.fn(async (input: unknown): Promise<Response> => {
  439. const url = getUrl(input);
  440. if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
  441. return jsonResponse({
  442. device_auth_id: "device-auth-id",
  443. user_code: "ABCD-1234",
  444. interval: "5",
  445. });
  446. }
  447. if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
  448. return jsonResponse({ error: "server_error", error_description: "try again later" }, 500);
  449. }
  450. throw new Error(`Unexpected fetch URL: ${url}`);
  451. }),
  452. );
  453. await expect(
  454. loginOpenAICodexDeviceCode({
  455. onDeviceCode: () => {},
  456. }),
  457. ).rejects.toThrow(
  458. 'OpenAI Codex device auth failed with status 500: {"error":"server_error","error_description":"try again later"}',
  459. );
  460. });
  461. it("does not write token refresh failures to stderr", async () => {
  462. const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
  463. vi.stubGlobal(
  464. "fetch",
  465. vi.fn(async (): Promise<Response> => {
  466. return new Response(
  467. JSON.stringify({
  468. error: {
  469. message: "Could not validate your token. Please try signing in again.",
  470. type: "invalid_request_error",
  471. },
  472. }),
  473. { status: 401, statusText: "Unauthorized", headers: { "Content-Type": "application/json" } },
  474. );
  475. }),
  476. );
  477. await expect(refreshOpenAICodexToken("invalid-refresh-token")).rejects.toThrow(
  478. /OpenAI Codex token refresh failed \(401\).*Could not validate your token/,
  479. );
  480. expect(consoleError).not.toHaveBeenCalled();
  481. });
  482. });