feat(ai): add Codex device code login

This commit is contained in:
Vegard Stikbakke
2026-05-20 10:48:36 +02:00
Unverified
parent bf5ac0011e
commit 1ffeb828d3
9 changed files with 636 additions and 39 deletions
+1
View File
@@ -10,6 +10,7 @@
### Added
- Added first-class OAuth device-code callback metadata, shared polling support, and GitHub Copilot OAuth integration.
- Added OpenAI Codex subscription device-code login as a selectable headless alternative while keeping browser login as the default.
### Fixed
+16 -13
View File
@@ -8,16 +8,17 @@ const DEFAULT_POLL_INTERVAL_SECONDS = 5;
// RFC 8628 section 3.5: `slow_down` means the polling interval must increase by 5 seconds.
const SLOW_DOWN_INTERVAL_INCREMENT_MS = 5000;
export type OAuthDeviceCodePollResult =
type OAuthDeviceCodeIncompletePollResult =
| { status: "pending" }
| { status: "slow_down" }
| { status: "complete"; accessToken: string }
| { status: "failed"; message: string };
export type OAuthDeviceCodePollOptions = {
export type OAuthDeviceCodePollResult<T> = OAuthDeviceCodeIncompletePollResult | { status: "complete"; value: T };
export type OAuthDeviceCodePollOptions<T> = {
intervalSeconds?: number;
expiresInSeconds?: number;
poll: () => Promise<OAuthDeviceCodePollResult>;
poll: () => Promise<OAuthDeviceCodePollResult<T>>;
signal?: AbortSignal;
};
@@ -41,7 +42,7 @@ function abortableSleep(ms: number, signal: AbortSignal | undefined, cancelMessa
});
}
export async function pollOAuthDeviceCodeFlow(options: OAuthDeviceCodePollOptions): Promise<string> {
export async function pollOAuthDeviceCodeFlow<T>(options: OAuthDeviceCodePollOptions<T>): Promise<T> {
const deadline =
typeof options.expiresInSeconds === "number"
? Date.now() + options.expiresInSeconds * 1000
@@ -57,23 +58,25 @@ export async function pollOAuthDeviceCodeFlow(options: OAuthDeviceCodePollOption
throw new Error(CANCEL_MESSAGE);
}
const remainingMs = deadline - Date.now();
await abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);
const result = await options.poll();
if (result.status === "complete") {
return result.accessToken;
return result.value;
}
if (result.status === "pending") {
continue;
if (result.status === "failed") {
throw new Error(result.message);
}
if (result.status === "slow_down") {
slowDownResponses += 1;
// RFC 8628 section 3.5: apply this increase to this and all subsequent requests.
intervalMs = Math.max(MINIMUM_INTERVAL_MS, intervalMs + SLOW_DOWN_INTERVAL_INCREMENT_MS);
continue;
}
throw new Error(result.message);
// If the code expires before the next interval, wait only until expiry.
const sleepMs = Math.min(intervalMs, deadline - Date.now());
if (sleepMs <= 0) {
break;
}
await abortableSleep(sleepMs, options.signal, CANCEL_MESSAGE);
}
throw new Error(slowDownResponses > 0 ? SLOW_DOWN_TIMEOUT_MESSAGE : TIMEOUT_MESSAGE);
@@ -141,9 +141,13 @@ async function startDeviceFlow(domain: string): Promise<DeviceCodeResponse> {
};
}
async function pollForGitHubAccessToken(domain: string, device: DeviceCodeResponse, signal?: AbortSignal) {
async function pollForGitHubAccessToken(
domain: string,
device: DeviceCodeResponse,
signal?: AbortSignal,
): Promise<string> {
const urls = getUrls(domain);
return pollOAuthDeviceCodeFlow({
return pollOAuthDeviceCodeFlow<string>({
intervalSeconds: device.interval,
expiresInSeconds: device.expires_in,
signal,
@@ -163,7 +167,7 @@ async function pollForGitHubAccessToken(domain: string, device: DeviceCodeRespon
});
if (raw && typeof raw === "object" && typeof (raw as DeviceTokenSuccessResponse).access_token === "string") {
return { status: "complete", accessToken: (raw as DeviceTokenSuccessResponse).access_token };
return { status: "complete", value: (raw as DeviceTokenSuccessResponse).access_token };
}
if (raw && typeof raw === "object" && typeof (raw as DeviceTokenErrorResponse).error === "string") {
+8 -1
View File
@@ -19,7 +19,14 @@ export {
refreshGitHubCopilotToken,
} from "./github-copilot.ts";
// OpenAI Codex (ChatGPT OAuth)
export { loginOpenAICodex, openaiCodexOAuthProvider, refreshOpenAICodexToken } from "./openai-codex.ts";
export {
loginOpenAICodex,
loginOpenAICodexDeviceCode,
OPENAI_CODEX_BROWSER_LOGIN_METHOD,
OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD,
openaiCodexOAuthProvider,
refreshOpenAICodexToken,
} from "./openai-codex.ts";
export * from "./types.ts";
+247 -14
View File
@@ -17,15 +17,30 @@ if (typeof process !== "undefined" && (process.versions?.node || process.version
});
}
import { pollOAuthDeviceCodeFlow } from "./device-code.ts";
import { oauthErrorHtml, oauthSuccessHtml } from "./oauth-page.ts";
import { generatePKCE } from "./pkce.ts";
import type { OAuthCredentials, OAuthLoginCallbacks, OAuthPrompt, OAuthProviderInterface } from "./types.ts";
import type {
OAuthCredentials,
OAuthDeviceCodeInfo,
OAuthLoginCallbacks,
OAuthPrompt,
OAuthProviderInterface,
} from "./types.ts";
const CALLBACK_HOST = process.env.PI_OAUTH_CALLBACK_HOST || "127.0.0.1";
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
const AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";
const TOKEN_URL = "https://auth.openai.com/oauth/token";
const AUTH_BASE_URL = "https://auth.openai.com";
const AUTHORIZE_URL = `${AUTH_BASE_URL}/oauth/authorize`;
const TOKEN_URL = `${AUTH_BASE_URL}/oauth/token`;
const REDIRECT_URI = "http://localhost:1455/auth/callback";
const DEVICE_USER_CODE_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`;
const DEVICE_TOKEN_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/token`;
const DEVICE_VERIFICATION_URI = `${AUTH_BASE_URL}/codex/device`;
const DEVICE_REDIRECT_URI = `${AUTH_BASE_URL}/deviceauth/callback`;
const DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;
export const OPENAI_CODEX_BROWSER_LOGIN_METHOD = "browser";
export const OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD = "device_code";
const SCOPE = "openid profile email offline_access";
const JWT_CLAIM_PATH = "https://api.openai.com/auth";
@@ -33,6 +48,18 @@ type TokenSuccess = { type: "success"; access: string; refresh: string; expires:
type TokenFailure = { type: "failed"; message: string; status?: number };
type TokenResult = TokenSuccess | TokenFailure;
type DeviceAuthInfo = {
deviceAuthId: string;
userCode: string;
intervalSeconds: number;
};
type DeviceTokenSuccess = {
authorizationCode: string;
codeChallenge: string;
codeVerifier: string;
};
type JwtPayload = {
[JWT_CLAIM_PATH]?: {
chatgpt_account_id?: string;
@@ -93,18 +120,28 @@ async function exchangeAuthorizationCode(
code: string,
verifier: string,
redirectUri: string = REDIRECT_URI,
signal?: AbortSignal,
): Promise<TokenResult> {
const response = await fetch(TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: CLIENT_ID,
code,
code_verifier: verifier,
redirect_uri: redirectUri,
}),
});
let response: Response;
try {
response = await fetch(TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: CLIENT_ID,
code,
code_verifier: verifier,
redirect_uri: redirectUri,
}),
signal,
});
} catch (error) {
if (signal?.aborted) {
throw new Error("Login cancelled");
}
throw error;
}
if (!response.ok) {
const text = await response.text().catch(() => "");
@@ -184,6 +221,132 @@ async function refreshAccessToken(refreshToken: string): Promise<TokenResult> {
}
}
function parseDeviceIntervalSeconds(value: unknown): number | null {
const intervalSeconds = typeof value === "string" ? Number(value.trim()) : value;
if (typeof intervalSeconds !== "number" || !Number.isFinite(intervalSeconds) || intervalSeconds <= 0) {
return null;
}
return intervalSeconds;
}
function parseObjectJson(text: string, context: string): Record<string, unknown> {
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
throw new Error(`${context}: ${text}`);
}
if (!parsed || typeof parsed !== "object") {
throw new Error(`${context}: ${text}`);
}
return parsed as Record<string, unknown>;
}
function parseDeviceAuthInfo(text: string): DeviceAuthInfo {
const json = parseObjectJson(text, "Invalid OpenAI Codex device code response");
const deviceAuthId = json.device_auth_id;
const userCode = json.user_code;
const intervalSeconds = parseDeviceIntervalSeconds(json.interval);
if (typeof deviceAuthId !== "string" || typeof userCode !== "string" || intervalSeconds === null) {
throw new Error(`Invalid OpenAI Codex device code response: ${text}`);
}
return {
deviceAuthId,
userCode,
intervalSeconds,
};
}
function parseDeviceTokenSuccess(text: string): DeviceTokenSuccess {
const json = parseObjectJson(text, "Invalid OpenAI Codex device auth token response");
const authorizationCode = json.authorization_code;
const codeChallenge = json.code_challenge;
const codeVerifier = json.code_verifier;
if (typeof authorizationCode !== "string" || typeof codeChallenge !== "string" || typeof codeVerifier !== "string") {
throw new Error(`Invalid OpenAI Codex device auth token response: ${text}`);
}
return { authorizationCode, codeChallenge, codeVerifier };
}
async function readResponseDetails(response: Response): Promise<string> {
const responseBody = await response.text().catch(() => "");
return responseBody ? `: ${responseBody}` : "";
}
async function startOpenAICodexDeviceAuth(signal?: AbortSignal): Promise<DeviceAuthInfo> {
let response: Response;
try {
response = await fetch(DEVICE_USER_CODE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ client_id: CLIENT_ID }),
signal,
});
} catch (error) {
if (signal?.aborted) {
throw new Error("Login cancelled");
}
throw error;
}
if (!response.ok) {
if (response.status === 404) {
throw new Error(
"OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.",
);
}
throw new Error(
`OpenAI Codex device code request failed with status ${response.status}${await readResponseDetails(response)}`,
);
}
return parseDeviceAuthInfo(await response.text());
}
async function pollOpenAICodexDeviceAuth(device: DeviceAuthInfo, signal?: AbortSignal): Promise<DeviceTokenSuccess> {
return pollOAuthDeviceCodeFlow<DeviceTokenSuccess>({
intervalSeconds: device.intervalSeconds,
expiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,
signal,
poll: async () => {
let response: Response;
try {
response = await fetch(DEVICE_TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
device_auth_id: device.deviceAuthId,
user_code: device.userCode,
}),
signal,
});
} catch (error) {
if (signal?.aborted) {
throw new Error("Login cancelled");
}
throw error;
}
if (response.ok) {
return { status: "complete", value: parseDeviceTokenSuccess(await response.text()) };
}
if (response.status === 403 || response.status === 404) {
return { status: "pending" };
}
return {
status: "failed",
message: `OpenAI Codex device auth failed with status ${response.status}${await readResponseDetails(response)}`,
};
},
});
}
async function createAuthorizationFlow(
originator: string = "pi",
): Promise<{ verifier: string; state: string; url: string }> {
@@ -294,6 +457,46 @@ function getAccountId(accessToken: string): string | null {
return typeof accountId === "string" && accountId.length > 0 ? accountId : null;
}
/**
* Login with OpenAI Codex OAuth using the Codex device-code flow.
*/
export async function loginOpenAICodexDeviceCode(options: {
onDeviceCode: (info: OAuthDeviceCodeInfo) => void;
onProgress?: (message: string) => void;
signal?: AbortSignal;
}): Promise<OAuthCredentials> {
const device = await startOpenAICodexDeviceAuth(options.signal);
options.onDeviceCode({
userCode: device.userCode,
verificationUri: DEVICE_VERIFICATION_URI,
intervalSeconds: device.intervalSeconds,
expiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,
openBrowser: false,
});
const code = await pollOpenAICodexDeviceAuth(device, options.signal);
const tokenResult = await exchangeAuthorizationCode(
code.authorizationCode,
code.codeVerifier,
DEVICE_REDIRECT_URI,
options.signal,
);
if (tokenResult.type !== "success") {
throw new Error(tokenResult.message);
}
const accountId = getAccountId(tokenResult.access);
if (!accountId) {
throw new Error("Failed to extract accountId from token");
}
return {
access: tokenResult.access,
refresh: tokenResult.refresh,
expires: tokenResult.expires,
accountId,
};
}
/**
* Login with OpenAI Codex OAuth
*
@@ -440,6 +643,36 @@ export const openaiCodexOAuthProvider: OAuthProviderInterface = {
usesCallbackServer: true,
async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
let loginMethod = OPENAI_CODEX_BROWSER_LOGIN_METHOD;
if (callbacks.onSelect) {
const selected = await callbacks.onSelect({
message: "Select OpenAI Codex login method:",
options: [
{ id: OPENAI_CODEX_BROWSER_LOGIN_METHOD, label: "Browser login (default)" },
{ id: OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD, label: "Device code login (headless)" },
],
});
if (!selected) {
throw new Error("Login cancelled");
}
loginMethod = selected;
}
if (loginMethod === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) {
if (!callbacks.onDeviceCode) {
throw new Error("OpenAI Codex device code login requires a device code callback");
}
return loginOpenAICodexDeviceCode({
onDeviceCode: callbacks.onDeviceCode,
onProgress: callbacks.onProgress,
signal: callbacks.signal,
});
}
if (loginMethod !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) {
throw new Error(`Unknown OpenAI Codex login method: ${loginMethod}`);
}
return loginOpenAICodex({
onAuth: callbacks.onAuth,
onPrompt: callbacks.onPrompt,
+2
View File
@@ -28,6 +28,8 @@ export type OAuthDeviceCodeInfo = {
verificationUri: string;
intervalSeconds?: number;
expiresInSeconds?: number;
/** Whether the UI should automatically open the verification URI. Defaults to true. */
openBrowser?: boolean;
};
export type OAuthSelectOption = {
+7 -7
View File
@@ -6,7 +6,7 @@ describe("OAuth device-code polling", () => {
vi.useRealTimers();
});
it("waits before the first poll and returns the completed value", async () => {
it("polls immediately and returns the completed value", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-03-09T00:00:00Z"));
@@ -15,7 +15,7 @@ describe("OAuth device-code polling", () => {
pollTimes.push(Date.now());
return pollTimes.length === 1
? { status: "pending" as const }
: { status: "complete" as const, accessToken: "token" };
: { status: "complete" as const, value: "token" };
});
const resultPromise = pollOAuthDeviceCodeFlow({
@@ -24,17 +24,17 @@ describe("OAuth device-code polling", () => {
poll,
});
await vi.advanceTimersByTimeAsync(0);
expect(pollTimes).toEqual([new Date("2026-03-09T00:00:00Z").getTime()]);
await vi.advanceTimersByTimeAsync(1999);
expect(pollTimes).toEqual([]);
expect(pollTimes).toEqual([new Date("2026-03-09T00:00:00Z").getTime()]);
await vi.advanceTimersByTimeAsync(1);
expect(pollTimes).toEqual([new Date("2026-03-09T00:00:02Z").getTime()]);
await vi.advanceTimersByTimeAsync(2000);
await expect(resultPromise).resolves.toBe("token");
expect(pollTimes).toEqual([
new Date("2026-03-09T00:00:00Z").getTime(),
new Date("2026-03-09T00:00:02Z").getTime(),
new Date("2026-03-09T00:00:04Z").getTime(),
]);
});
+344 -1
View File
@@ -1,10 +1,353 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { refreshOpenAICodexToken } from "../src/utils/oauth/openai-codex.js";
import {
loginOpenAICodexDeviceCode,
openaiCodexOAuthProvider,
refreshOpenAICodexToken,
} from "../src/utils/oauth/openai-codex.js";
function jsonResponse(body: unknown, status: number = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}
function getUrl(input: unknown): string {
if (typeof input === "string") return input;
if (input instanceof URL) return input.toString();
if (input instanceof Request) return input.url;
throw new Error(`Unsupported fetch input: ${String(input)}`);
}
function createAccessToken(accountId: string): string {
const header = Buffer.from(JSON.stringify({ alg: "none" })).toString("base64");
const payload = Buffer.from(
JSON.stringify({
"https://api.openai.com/auth": {
chatgpt_account_id: accountId,
},
}),
).toString("base64");
return `${header}.${payload}.signature`;
}
describe("OpenAI Codex OAuth", () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.useRealTimers();
});
it("logs in with the OpenAI Codex device code flow", async () => {
vi.useFakeTimers();
const startTime = new Date("2026-05-20T00:00:00Z");
vi.setSystemTime(startTime);
const accessToken = createAccessToken("account-123");
const deviceInfos: Array<{
userCode: string;
verificationUri: string;
instructions?: string;
intervalSeconds?: number;
expiresInSeconds?: number;
openBrowser?: boolean;
}> = [];
const progressMessages: string[] = [];
const pollTimes: number[] = [];
const pollResponses = [
jsonResponse({ error: "authorization_pending" }, 403),
jsonResponse({
authorization_code: "oauth-code",
code_challenge: "device-code-challenge",
code_verifier: "device-code-verifier",
}),
];
const fetchMock = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
const url = getUrl(input);
if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
expect(init?.method).toBe("POST");
expect(init?.headers).toMatchObject({ "Content-Type": "application/json" });
expect(JSON.parse(String(init?.body))).toEqual({ client_id: "app_EMoamEEZ73f0CkXaXp7hrann" });
return jsonResponse({
device_auth_id: "device-auth-id",
user_code: "ABCD-1234",
interval: "5",
});
}
if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
pollTimes.push(Date.now());
expect(init?.method).toBe("POST");
expect(init?.headers).toMatchObject({ "Content-Type": "application/json" });
expect(JSON.parse(String(init?.body))).toEqual({
device_auth_id: "device-auth-id",
user_code: "ABCD-1234",
});
const response = pollResponses.shift();
if (!response) {
throw new Error("Unexpected extra device auth poll");
}
return response;
}
if (url === "https://auth.openai.com/oauth/token") {
expect(init?.method).toBe("POST");
expect(init?.headers).toMatchObject({ "Content-Type": "application/x-www-form-urlencoded" });
const params = new URLSearchParams(String(init?.body));
expect(params.get("grant_type")).toBe("authorization_code");
expect(params.get("client_id")).toBe("app_EMoamEEZ73f0CkXaXp7hrann");
expect(params.get("code")).toBe("oauth-code");
expect(params.get("redirect_uri")).toBe("https://auth.openai.com/deviceauth/callback");
expect(params.get("code_verifier")).toBe("device-code-verifier");
return jsonResponse({
access_token: accessToken,
refresh_token: "refresh-token",
expires_in: 3600,
});
}
throw new Error(`Unexpected fetch URL: ${url}`);
});
vi.stubGlobal("fetch", fetchMock);
const credentialsPromise = loginOpenAICodexDeviceCode({
onDeviceCode: (info) => deviceInfos.push(info),
onProgress: (message) => progressMessages.push(message),
});
for (let i = 0; i < 5 && pollTimes.length === 0; i++) {
await vi.advanceTimersByTimeAsync(0);
}
expect(deviceInfos).toEqual([
{
userCode: "ABCD-1234",
verificationUri: "https://auth.openai.com/codex/device",
intervalSeconds: 5,
expiresInSeconds: 900,
openBrowser: false,
},
]);
expect(progressMessages).toEqual([]);
expect(pollTimes).toEqual([startTime.getTime()]);
await vi.advanceTimersByTimeAsync(4999);
expect(pollTimes).toEqual([startTime.getTime()]);
await vi.advanceTimersByTimeAsync(1);
await expect(credentialsPromise).resolves.toMatchObject({
access: accessToken,
refresh: "refresh-token",
expires: startTime.getTime() + 5000 + 3600 * 1000,
accountId: "account-123",
});
expect(pollTimes).toEqual([startTime.getTime(), startTime.getTime() + 5000]);
});
it("offers browser login first and uses the selected OpenAI Codex device code flow", async () => {
const accessToken = createAccessToken("account-456");
const selectPrompts: Array<{
message: string;
options: Array<{ id: string; label: string }>;
}> = [];
const deviceInfos: Array<{ userCode: string; verificationUri: string; openBrowser?: boolean }> = [];
vi.stubGlobal(
"fetch",
vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
const url = getUrl(input);
if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
expect(JSON.parse(String(init?.body))).toEqual({ client_id: "app_EMoamEEZ73f0CkXaXp7hrann" });
return jsonResponse({
device_auth_id: "device-auth-id",
user_code: "WXYZ-7890",
interval: "5",
});
}
if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
return jsonResponse({
authorization_code: "oauth-code",
code_challenge: "device-code-challenge",
code_verifier: "device-code-verifier",
});
}
if (url === "https://auth.openai.com/oauth/token") {
return jsonResponse({
access_token: accessToken,
refresh_token: "refresh-token",
expires_in: 3600,
});
}
throw new Error(`Unexpected fetch URL: ${url}`);
}),
);
await expect(
openaiCodexOAuthProvider.login({
onAuth: () => {
throw new Error("Browser login should not start");
},
onDeviceCode: (info) => deviceInfos.push(info),
onPrompt: async () => {
throw new Error("Prompt should not be used");
},
onSelect: async (prompt) => {
selectPrompts.push(prompt);
return "device_code";
},
}),
).resolves.toMatchObject({
access: accessToken,
refresh: "refresh-token",
accountId: "account-456",
});
expect(selectPrompts).toEqual([
{
message: "Select OpenAI Codex login method:",
options: [
{ id: "browser", label: "Browser login (default)" },
{ id: "device_code", label: "Device code login (headless)" },
],
},
]);
expect(deviceInfos).toEqual([
{
userCode: "WXYZ-7890",
verificationUri: "https://auth.openai.com/codex/device",
intervalSeconds: 5,
expiresInSeconds: 900,
openBrowser: false,
},
]);
});
it("cancels when OpenAI Codex login method selection is cancelled", async () => {
await expect(
openaiCodexOAuthProvider.login({
onAuth: () => {},
onPrompt: async () => "",
onSelect: async () => undefined,
}),
).rejects.toThrow("Login cancelled");
});
it("cancels the OpenAI Codex device code flow while waiting", async () => {
vi.useFakeTimers();
const controller = new AbortController();
const pollTimes: number[] = [];
vi.stubGlobal(
"fetch",
vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
const url = getUrl(input);
if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
expect(JSON.parse(String(init?.body))).toEqual({ client_id: "app_EMoamEEZ73f0CkXaXp7hrann" });
return jsonResponse({
device_auth_id: "device-auth-id",
user_code: "ABCD-1234",
interval: "5",
});
}
if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
pollTimes.push(Date.now());
return jsonResponse({ error: "authorization_pending" }, 403);
}
throw new Error(`Unexpected fetch URL: ${url}`);
}),
);
const credentialsPromise = loginOpenAICodexDeviceCode({
onDeviceCode: () => {},
signal: controller.signal,
});
const rejectionPromise = credentialsPromise.then(
() => new Error("Expected login to fail"),
(error: unknown) => error,
);
for (let i = 0; i < 5 && pollTimes.length === 0; i++) {
await vi.advanceTimersByTimeAsync(0);
}
expect(pollTimes).toHaveLength(1);
controller.abort();
const rejection = await rejectionPromise;
expect(rejection).toBeInstanceOf(Error);
expect((rejection as Error).message).toBe("Login cancelled");
});
it("times out the OpenAI Codex device code flow after 15 minutes", async () => {
vi.useFakeTimers();
const pollTimes: number[] = [];
vi.stubGlobal(
"fetch",
vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
const url = getUrl(input);
if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
expect(JSON.parse(String(init?.body))).toEqual({ client_id: "app_EMoamEEZ73f0CkXaXp7hrann" });
return jsonResponse({
device_auth_id: "device-auth-id",
user_code: "ABCD-1234",
interval: "60",
});
}
if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
pollTimes.push(Date.now());
return jsonResponse({ error: "authorization_pending" }, 403);
}
throw new Error(`Unexpected fetch URL: ${url}`);
}),
);
const credentialsPromise = loginOpenAICodexDeviceCode({
onDeviceCode: () => {},
});
const rejectionPromise = credentialsPromise.then(
() => new Error("Expected login to fail"),
(error: unknown) => error,
);
for (let i = 0; i < 5 && pollTimes.length === 0; i++) {
await vi.advanceTimersByTimeAsync(0);
}
expect(pollTimes).toHaveLength(1);
await vi.advanceTimersByTimeAsync(15 * 60 * 1000);
const rejection = await rejectionPromise;
expect(rejection).toBeInstanceOf(Error);
expect((rejection as Error).message).toBe("Device flow timed out");
});
it("includes the response body in OpenAI Codex device auth poll failures", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (input: unknown): Promise<Response> => {
const url = getUrl(input);
if (url === "https://auth.openai.com/api/accounts/deviceauth/usercode") {
return jsonResponse({
device_auth_id: "device-auth-id",
user_code: "ABCD-1234",
interval: "5",
});
}
if (url === "https://auth.openai.com/api/accounts/deviceauth/token") {
return jsonResponse({ error: "server_error", error_description: "try again later" }, 500);
}
throw new Error(`Unexpected fetch URL: ${url}`);
}),
);
await expect(
loginOpenAICodexDeviceCode({
onDeviceCode: () => {},
}),
).rejects.toThrow(
'OpenAI Codex device auth failed with status 500: {"error":"server_error","error_description":"try again later"}',
);
});
it("does not write token refresh failures to stderr", async () => {
+4
View File
@@ -7,6 +7,10 @@
- Changed source syntax to avoid TypeScript constructs that require JavaScript emit, keeping core sources compatible with Node.js strip-only TypeScript checks.
- Removed web UI workspace references from the CLI package and dropped the package-level development watch script.
### Added
- Added a Codex subscription login method selector with device-code auth for headless environments.
### Fixed
- Fixed the system prompt to tell models to resolve pi docs and examples under the absolute package paths before reading topic-specific relative references ([#4752](https://github.com/earendil-works/pi/issues/4752)).