The Open Framework for Building Agents
fix(eve): authentication - sign in to ChatGPT without Codex CLI (#3120)
Andrew Barba67f3b8d81719
diff --git a/.changeset/native-chatgpt-sign-in.md b/.changeset/native-chatgpt-sign-in.mdnew file mode 100644index 000000000..0133236fb--- /dev/null+++ b/.changeset/native-chatgpt-sign-in.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Sign in to a ChatGPT subscription directly from eve without installing the Codex CLI. eve now manages its own local login and token refresh, with browser sign-in, device codes over SSH, and actionable recovery messages; existing Codex users sign in once through `/model` after upgrading.diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex 749be9352..f24ecb5b1 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -170,7 +170,7 @@ Run source mutations inside `withSuspendedSource()`. It acquires a unique watche## ChatGPT subscription models-`chatgpt()` from `eve/models/openai` serves an OpenAI model through the local Codex login and bills the ChatGPT subscription. With no argument, it selects `gpt-5.6-sol`:+`chatgpt()` from `eve/models/openai` serves an OpenAI model through your local ChatGPT login and bills the ChatGPT subscription. With no argument, it selects `gpt-5.6-sol`:```ts title="agent/agent.ts"import { defineAgent } from "eve";@@ -185,20 +185,24 @@ Pass another bare OpenAI model slug to override the default. `experimental_chatg`chatgpt()` uses stateless requests (`store: false`). eve retains reasoning summaries and encrypted reasoning in session history and replays them after tool calls and on later turns. You do not need to configure `reasoning.encrypted_content` explicitly.-Authentication is delegated entirely to the Codex CLI:+Sign in directly from eve; the Codex CLI is not required:-1. Install or upgrade `codex` and run `codex login`.-2. `eve dev` asks `codex app-server` for a usable access token. Codex owns refresh and credential persistence; eve does not read or write Codex login files.-3. Normal token expiry is refreshed automatically. If the login is revoked, the status line shows `codex login`; completing login inside or outside eve repairs the running dev session without restarting it.+1. Run `eve dev`, open `/model`, and select **Provider** → **ChatGPT subscription**.+2. Complete sign-in in the browser. If the browser does not open, use the URL printed in the terminal.+3. Return to eve after the terminal confirms that your subscription is connected. Normal token expiry is refreshed automatically.++eve stores this session in `~/.eve/auth/chatgpt.json` with owner-only file permissions on Unix. It is separate from any Codex login and is never written to your project. Keep this file private. To remove the local eve login, stop your eve processes and delete the file. Existing Codex users must sign in once through eve after upgrading.++Over SSH, or if localhost port 1455 is occupied, eve shows a device code instead. Open the displayed link in a browser and enter the code. Device sign-in requires enabling device code authorization in **ChatGPT Settings → Security**, or having a workspace admin enable it in workspace permissions. Sign-in times out after five minutes; press **Ctrl+C** to cancel sooner.ChatGPT subscription credentials are local user credentials. `eve deploy` blocks agents whose active model is `chatgpt()` because those credentials are not uploaded to a deployment. Use an environment branch with a deployable model, or switch to an AI Gateway model before deploying.Troubleshooting:-- **`chatgpt-sub login`**: run `codex login`.-- **`chatgpt-sub unavailable`**: ensure `codex` is installed, current, and available on `PATH`; then restart the command.+- **`chatgpt-sub login`**: open `/model` and select **Provider** → **ChatGPT subscription** to sign in again. The running dev session picks up the new login.+- **`chatgpt-sub unavailable`**: check your network connection and retry from `/model`. If eve reports an invalid credential file, remove `~/.eve/auth/chatgpt.json` and sign in again.- **Model rejected by the backend**: model availability depends on the signed-in ChatGPT account. Pick another supported OpenAI model.-- **SSH/headless login**: run `codex login --device-auth` in another terminal, then return to the still-running `eve dev` session.+- **Device sign-in unavailable**: enable device code authorization in ChatGPT security settings, or sign in from a local terminal with port 1455 available.## What to read nextdiff --git a/packages/eve/src/cli/commands/deploy.ts b/packages/eve/src/cli/commands/deploy.tsindex f74af514d..a2e78a909 100644--- a/packages/eve/src/cli/commands/deploy.ts+++ b/packages/eve/src/cli/commands/deploy.ts@@ -83,7 +83,7 @@ export async function runDeployCommand(}if (result.kind === "local-model") {logger.error(- "ChatGPT subscription models use local Codex credentials and cannot be deployed. Switch to an AI Gateway or server-authenticated model before running `eve deploy`.",+ "ChatGPT subscription models use local ChatGPT credentials and cannot be deployed. Switch to an AI Gateway or server-authenticated model before running `eve deploy`.",);process.exitCode = 1;return;diff --git a/packages/eve/src/cli/dev/tui/status-line.test.ts b/packages/eve/src/cli/dev/tui/status-line.test.tsindex 8a5de4bc7..745fc78a6 100644--- a/packages/eve/src/cli/dev/tui/status-line.test.ts+++ b/packages/eve/src/cli/dev/tui/status-line.test.ts@@ -252,7 +252,7 @@ describe("buildStatusLine", () => {theme: plain,width: 120,});- expect(chatgptLogin).toBe("openai/gpt-5.6-sol ⚠ chatgpt-sub login · codex login");+ expect(chatgptLogin).toBe("openai/gpt-5.6-sol ⚠ chatgpt-sub login · /model");const notConnected = buildStatusLine({model: "m",diff --git a/packages/eve/src/cli/dev/tui/status-line.ts b/packages/eve/src/cli/dev/tui/status-line.tsindex 603fe4b08..159ef1e08 100644--- a/packages/eve/src/cli/dev/tui/status-line.ts+++ b/packages/eve/src/cli/dev/tui/status-line.ts@@ -118,7 +118,7 @@ function renderEndpoint(return { text: c.dim("chatgpt-sub checking…"), standalone: true };case "signed-out":case "reauth-required":- return { text: c.yellow(`${g.warning} chatgpt-sub login · codex login`), standalone: true };+ return { text: c.yellow(`${g.warning} chatgpt-sub login · /model`), standalone: true };case "unavailable":return { text: c.yellow(`${g.warning} chatgpt-sub unavailable`), standalone: true };}diff --git a/packages/eve/src/public/models/openai/chatgpt/codex-app-server.test.ts b/packages/eve/src/public/models/openai/chatgpt/codex-app-server.test.tsdeleted file mode 100644index 8d28383e7..000000000--- a/packages/eve/src/public/models/openai/chatgpt/codex-app-server.test.ts+++ /dev/null@@ -1,98 +0,0 @@-import { EventEmitter } from "node:events";-import { PassThrough } from "node:stream";--import { describe, expect, it, vi } from "vitest";--import { CodexAppServerClient, type CodexAppServerProcess } from "./codex-app-server.js";--describe("Codex app-server client", () => {- it("initializes once and requests an auth token without exposing it", async () => {- const child = new FakeChild();- const client = new CodexAppServerClient({- spawnProcess: vi.fn(() => child.asChildProcess()),- });-- const status = await client.getAuthStatus({ refreshToken: true });-- expect(status).toEqual({- authMethod: "chatgpt",- authToken: "secret-token",- requiresOpenaiAuth: true,- });- expect(child.requests.map((request) => request.method)).toEqual([- "initialize",- "initialized",- "getAuthStatus",- ]);- expect(child.requests[2]?.params).toEqual({ includeToken: true, refreshToken: true });- });-- it("reports a missing Codex binary with actionable guidance", async () => {- const child = new FakeChild({- failWith: Object.assign(new Error("spawn codex ENOENT"), { code: "ENOENT" }),- });- const client = new CodexAppServerClient({- spawnProcess: vi.fn(() => child.asChildProcess()),- });-- await expect(client.getAuthStatus({ refreshToken: false })).rejects.toThrow(- "requires the Codex CLI",- );- });-});--interface RpcRequest {- readonly id?: number;- readonly method: string;- readonly params?: unknown;-}--class FakeChild extends EventEmitter {- readonly stdin = new PassThrough();- readonly stdout = new PassThrough();- readonly stderr = new PassThrough();- readonly requests: RpcRequest[] = [];- readonly #failWith?: Error;- #input = "";-- constructor(options: { readonly failWith?: Error } = {}) {- super();- this.#failWith = options.failWith;- this.stdin.on("data", (chunk: Buffer) => this.#receive(chunk.toString()));- queueMicrotask(() => {- if (this.#failWith !== undefined) this.emit("error", this.#failWith);- });- }-- asChildProcess(): CodexAppServerProcess {- return this;- }-- kill(): boolean {- return true;- }-- unref(): void {}-- #receive(chunk: string): void {- this.#input += chunk;- while (true) {- const newline = this.#input.indexOf("\n");- if (newline < 0) return;- const line = this.#input.slice(0, newline);- this.#input = this.#input.slice(newline + 1);- const request = JSON.parse(line) as RpcRequest;- this.requests.push(request);- if (request.id === undefined) continue;- const result =- request.method === "initialize"- ? { codexHome: "/tmp/codex" }- : {- authMethod: "chatgpt",- authToken: "secret-token",- requiresOpenaiAuth: true,- };- this.stdout.write(`${JSON.stringify({ id: request.id, result })}\n`);- }- }-}diff --git a/packages/eve/src/public/models/openai/chatgpt/codex-app-server.ts b/packages/eve/src/public/models/openai/chatgpt/codex-app-server.tsdeleted file mode 100644index 1a7f2c8c6..000000000--- a/packages/eve/src/public/models/openai/chatgpt/codex-app-server.ts+++ /dev/null@@ -1,253 +0,0 @@-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";-import { createInterface, type Interface } from "node:readline";--import { isObject } from "#shared/guards.js";--interface RpcError {- readonly code?: number;- readonly message?: string;-}--interface RpcResponse {- readonly error?: RpcError;- readonly id?: number;- readonly result?: unknown;-}--export interface CodexAuthStatus {- readonly authMethod?: string;- readonly authToken?: string;- readonly requiresOpenaiAuth?: boolean;-}--export interface CodexAppServer {- getAuthStatus(input: { readonly refreshToken: boolean }): Promise<CodexAuthStatus>;- restart?(): void;-}--export interface CodexAppServerProcess {- readonly stderr: ChildProcessWithoutNullStreams["stderr"];- readonly stdin: ChildProcessWithoutNullStreams["stdin"];- readonly stdout: ChildProcessWithoutNullStreams["stdout"];- kill(): boolean;- once(event: "error", listener: (error: Error) => void): this;- once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;- unref(): void;-}--type SpawnCodexAppServer = (- command: string,- args: readonly string[],- options: {- readonly env?: NodeJS.ProcessEnv;- stdio: ["pipe", "pipe", "pipe"];- },-) => CodexAppServerProcess;--export interface CodexAppServerOptions {- readonly command?: string;- readonly env?: NodeJS.ProcessEnv;- readonly spawnProcess?: SpawnCodexAppServer;-}--/** Minimal authenticated subset of Codex's JSONL app-server protocol. */-export class CodexAppServerClient implements CodexAppServer {- readonly #command: string;- readonly #env: NodeJS.ProcessEnv | undefined;- readonly #spawnProcess: SpawnCodexAppServer;- #connection: Promise<CodexAppServerConnection> | undefined;-- constructor(options: CodexAppServerOptions = {}) {- this.#command = options.command ?? "codex";- this.#env = options.env;- this.#spawnProcess = options.spawnProcess ?? spawnCodexAppServer;- }-- async getAuthStatus(input: { readonly refreshToken: boolean }): Promise<CodexAuthStatus> {- const connection = await this.#connect();- try {- return await connection.getAuthStatus(input);- } catch (error) {- if (connection.exited) this.#connection = undefined;- throw error;- }- }-- restart(): void {- const connection = this.#connection;- this.#connection = undefined;- void connection?.then((value) => value.close()).catch(() => undefined);- }-- #connect(): Promise<CodexAppServerConnection> {- if (this.#connection === undefined) {- this.#connection = CodexAppServerConnection.start({- command: this.#command,- env: this.#env,- spawnProcess: this.#spawnProcess,- }).catch((error: unknown) => {- this.#connection = undefined;- throw error;- });- }- return this.#connection;- }-}--class CodexAppServerConnection {- readonly #child: CodexAppServerProcess;- readonly #lines: Interface;- readonly #pending = new Map<- number,- { readonly reject: (error: Error) => void; readonly resolve: (value: unknown) => void }- >();- #nextId = 1;- #exited = false;- #failure: Error | undefined;-- private constructor(child: CodexAppServerProcess) {- this.#child = child;- // The broker must not keep the agent runtime alive during normal shutdown.- child.unref();- unrefStream(child.stdin);- unrefStream(child.stdout);- unrefStream(child.stderr);- child.stderr.resume();- this.#lines = createInterface({ input: child.stdout });- this.#lines.on("line", (line) => this.#handleLine(line));- child.once("error", (error) => this.#fail(error));- child.once("exit", (code, signal) => {- const suffix = signal === null ? `code ${code ?? "unknown"}` : `signal ${signal}`;- this.#fail(new Error(`Codex app-server exited with ${suffix}.`));- });- }-- get exited(): boolean {- return this.#exited;- }-- close(): void {- this.#child.kill();- this.#fail(new Error("Codex app-server connection was restarted."));- }-- static async start(input: {- readonly command: string;- readonly env?: NodeJS.ProcessEnv;- readonly spawnProcess: SpawnCodexAppServer;- }): Promise<CodexAppServerConnection> {- let child: CodexAppServerProcess;- try {- child = input.spawnProcess(input.command, ["app-server", "--stdio"], {- env: input.env,- stdio: ["pipe", "pipe", "pipe"],- });- } catch (error) {- throw codexUnavailableError(error);- }-- const connection = new CodexAppServerConnection(child);- try {- await connection.#request("initialize", {- capabilities: null,- clientInfo: { name: "eve", title: "eve", version: "0.35.0" },- });- connection.#notify("initialized", {});- return connection;- } catch (error) {- child.kill();- throw error;- }- }-- async getAuthStatus(input: { readonly refreshToken: boolean }): Promise<CodexAuthStatus> {- const value = await this.#request("getAuthStatus", {- includeToken: true,- refreshToken: input.refreshToken,- });- if (!isObject(value)) {- throw new Error("Codex app-server returned an invalid authentication response.");- }- return {- ...(typeof value.authMethod === "string" && { authMethod: value.authMethod }),- ...(typeof value.authToken === "string" && { authToken: value.authToken }),- ...(typeof value.requiresOpenaiAuth === "boolean" && {- requiresOpenaiAuth: value.requiresOpenaiAuth,- }),- };- }-- #request(method: string, params: unknown): Promise<unknown> {- if (this.#exited) {- return Promise.reject(this.#failure ?? new Error("Codex app-server is not running."));- }- const id = this.#nextId++;- const response = new Promise<unknown>((resolve, reject) => {- this.#pending.set(id, { reject, resolve });- });- this.#write({ id, method, params });- return response;- }-- #notify(method: string, params: unknown): void {- this.#write({ method, params });- }-- #write(value: unknown): void {- this.#child.stdin.write(`${JSON.stringify(value)}\n`);- }-- #handleLine(line: string): void {- let value: RpcResponse;- try {- value = JSON.parse(line) as RpcResponse;- } catch {- return;- }- if (typeof value.id !== "number") return;- const pending = this.#pending.get(value.id);- if (pending === undefined) return;- this.#pending.delete(value.id);- if (value.error !== undefined) {- pending.reject(- new Error(value.error.message ?? `Codex app-server request failed (${value.error.code}).`),- );- return;- }- pending.resolve(value.result);- }-- #fail(error: Error): void {- if (this.#exited) return;- this.#exited = true;- this.#failure = codexUnavailableError(error);- this.#lines.close();- for (const pending of this.#pending.values()) pending.reject(this.#failure);- this.#pending.clear();- }-}--function spawnCodexAppServer(- command: string,- args: readonly string[],- options: {- readonly env?: NodeJS.ProcessEnv;- stdio: ["pipe", "pipe", "pipe"];- },-): CodexAppServerProcess {- return spawn(command, [...args], options);-}--function unrefStream(stream: NodeJS.ReadableStream | NodeJS.WritableStream): void {- if ("unref" in stream && typeof stream.unref === "function") stream.unref();-}--function codexUnavailableError(error: unknown): Error {- if (error instanceof Error && "code" in error && error.code === "ENOENT") {- return new Error(- "ChatGPT subscription authentication requires the Codex CLI. Install or upgrade `codex`, then run `codex login`.",- );- }- const message = error instanceof Error ? error.message : String(error);- return new Error(`Codex app-server is unavailable: ${message}`);-}diff --git a/packages/eve/src/public/models/openai/chatgpt/credential-store.scenario.test.ts b/packages/eve/src/public/models/openai/chatgpt/credential-store.scenario.test.tsnew file mode 100644index 000000000..2c45d3e4a--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/credential-store.scenario.test.ts@@ -0,0 +1,72 @@+import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { createChatGptCredentialStore } from "./credential-store.js";++const roots: string[] = [];+afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+});+async function credentialPath() {+ const root = await mkdtemp(join(tmpdir(), "eve-chatgpt-auth-"));+ roots.push(root);+ return join(root, "auth", "chatgpt.json");+}+const credentials = {+ accessToken: "access",+ refreshToken: "refresh",+ expiresAt: 2_000_000_000_000,+};++describe("ChatGPT credential storage", () => {+ it("stores credentials atomically with private permissions", async () => {+ const path = await credentialPath();+ const store = createChatGptCredentialStore(path);+ await expect(store.read()).resolves.toBeUndefined();+ await store.update(async () => credentials);+ expect(JSON.parse(await readFile(path, "utf8"))).toEqual(credentials);+ if (process.platform !== "win32") expect((await stat(path)).mode % 512).toBe(0o600);+ await expect(store.read()).resolves.toEqual(credentials);+ });++ it("serializes rotation across independent stores and rereads inside the lock", async () => {+ const path = await credentialPath();+ const first = createChatGptCredentialStore(path);+ const second = createChatGptCredentialStore(path);+ await first.update(async () => credentials);+ const observed: string[] = [];+ await Promise.all(+ [first, second].map((store) =>+ store.update(async (current) => {+ observed.push(current?.refreshToken ?? "missing");+ return { ...credentials, refreshToken: `${current?.refreshToken}-rotated` };+ }),+ ),+ );+ expect(observed).toEqual(["refresh", "refresh-rotated"]);+ });++ it("keeps the prior session and releases the lock if refresh fails", async () => {+ const store = createChatGptCredentialStore(await credentialPath());+ await store.update(async () => credentials);+ await expect(+ store.update(async () => {+ throw new Error("temporary failure");+ }),+ ).rejects.toThrow("temporary failure");+ await expect(store.read()).resolves.toEqual(credentials);+ await expect(store.update(async () => credentials)).resolves.toEqual(credentials);+ });++ it("reports malformed credential files without disclosing their contents", async () => {+ const path = await credentialPath();+ const store = createChatGptCredentialStore(path);+ await store.update(async () => credentials);+ await writeFile(path, "secret-token");+ const error = await store.read().catch((value: unknown) => value);+ expect(String(error)).toContain("~/.eve/auth/chatgpt.json");+ expect(String(error)).not.toContain("secret-token");+ });+});diff --git a/packages/eve/src/public/models/openai/chatgpt/credential-store.ts b/packages/eve/src/public/models/openai/chatgpt/credential-store.tsnew file mode 100644index 000000000..600211934--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/credential-store.ts@@ -0,0 +1,97 @@+import { randomUUID } from "node:crypto";+import { mkdir, open, rm, stat, writeFile } from "node:fs/promises";+import { homedir } from "node:os";+import { dirname, join } from "node:path";+import { setTimeout as delay } from "node:timers/promises";++import { isErrnoCode, isObject } from "#shared/guards.js";+import { renameWithTransientBusyRetry } from "#shared/rename-with-retry.js";+import type { ChatGptCredentials } from "./oauth.js";++export interface ChatGptCredentialStore {+ read(): Promise<ChatGptCredentials | undefined>;+ update(+ callback: (current: ChatGptCredentials | undefined) => Promise<ChatGptCredentials>,+ ): Promise<ChatGptCredentials>;+}++export function createChatGptCredentialStore(+ path = join(homedir(), ".eve", "auth", "chatgpt.json"),+): ChatGptCredentialStore {+ async function read(): Promise<ChatGptCredentials | undefined> {+ let value: unknown;+ try {+ const file = await open(path, "r");+ try {+ if ((await file.stat()).size > 64 * 1024) throw new Error("Credential file is too large.");+ value = JSON.parse(await file.readFile("utf8"));+ } finally {+ await file.close();+ }+ } catch (error) {+ if (isErrnoCode(error, "ENOENT")) return undefined;+ throw new Error(+ "Could not read the saved ChatGPT session. Check ~/.eve/auth/chatgpt.json permissions or remove it and sign in again from /model.",+ );+ }+ if (+ !isObject(value) ||+ typeof value.accessToken !== "string" ||+ !value.accessToken ||+ typeof value.refreshToken !== "string" ||+ !value.refreshToken ||+ typeof value.expiresAt !== "number" ||+ !Number.isFinite(value.expiresAt)+ ) {+ throw new Error(+ "The saved ChatGPT session is invalid. Remove ~/.eve/auth/chatgpt.json and sign in again from /model.",+ );+ }+ return {+ accessToken: value.accessToken,+ refreshToken: value.refreshToken,+ expiresAt: value.expiresAt,+ ...(typeof value.accountId === "string" && { accountId: value.accountId }),+ ...(typeof value.accountLabel === "string" && { accountLabel: value.accountLabel }),+ };+ }++ return {+ read,+ async update(callback) {+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });+ const lockPath = `${path}.lock`;+ const deadline = Date.now() + 35_000;+ for (;;) {+ try {+ await mkdir(lockPath, { mode: 0o700 });+ break;+ } catch (error) {+ if (!isErrnoCode(error, "EEXIST")) throw error;+ // Token requests time out after 30 seconds; a two-minute lock survived a crash.+ const info = await stat(lockPath).catch((error: unknown) => {+ if (isErrnoCode(error, "ENOENT")) return undefined;+ throw error;+ });+ if (info && Date.now() - info.mtimeMs > 120_000) {+ await rm(lockPath, { recursive: true, force: true });+ continue;+ }+ if (Date.now() >= deadline)+ throw new Error("Another eve process is updating the ChatGPT session. Retry shortly.");+ await delay(100);+ }+ }+ const temporaryPath = `${path}.${randomUUID()}.tmp`;+ try {+ const next = await callback(await read());+ await writeFile(temporaryPath, `${JSON.stringify(next)}\n`, { mode: 0o600, flag: "wx" });+ await renameWithTransientBusyRetry(temporaryPath, path);+ return next;+ } finally {+ await rm(temporaryPath, { force: true });+ await rm(lockPath, { recursive: true, force: true });+ }+ },+ };+}diff --git a/packages/eve/src/public/models/openai/chatgpt/model.ts b/packages/eve/src/public/models/openai/chatgpt/model.tsindex c76a4ab2e..ffc6a819f 100644--- a/packages/eve/src/public/models/openai/chatgpt/model.ts+++ b/packages/eve/src/public/models/openai/chatgpt/model.ts@@ -7,7 +7,7 @@ import { createCodexFetch, type CodexTransportOptions } from "./transport.js";const CODEX_LOCAL_AUTH_API_KEY = "codex-local-auth";-/** Configures the Codex model selected by the local Codex login. */+/** Configures the Codex model selected by the local ChatGPT login. */export interface CodexModelOptions {/** OpenAI model ID passed to the Codex Responses endpoint, for example `gpt-5.6-sol`. */readonly model: string;diff --git a/packages/eve/src/public/models/openai/chatgpt/oauth.test.ts b/packages/eve/src/public/models/openai/chatgpt/oauth.test.tsnew file mode 100644index 000000000..1c90edb95--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/oauth.test.ts@@ -0,0 +1,109 @@+import { describe, expect, it, vi } from "vitest";+import { CHATGPT_CLIENT_ID, requestChatGptTokens } from "./oauth.js";+import { createUnsignedJwt } from "./unsigned-jwt.js";++describe("ChatGPT OAuth token exchange", () => {+ it("exchanges a PKCE code and retains account identity from the ID token", async () => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () =>+ Response.json({+ access_token: "access",+ refresh_token: "refresh",+ expires_in: 3600,+ id_token: createUnsignedJwt({+ email: "[email protected]",+ "https://api.openai.com/auth": { chatgpt_account_id: "acct-1" },+ }),+ }),+ );+ await expect(+ requestChatGptTokens(+ {+ grant_type: "authorization_code",+ code: "code",+ code_verifier: "verifier",+ redirect_uri: "http://localhost:1455/auth/callback",+ },+ { fetch, now: () => 1000 },+ ),+ ).resolves.toEqual({+ accessToken: "access",+ refreshToken: "refresh",+ expiresAt: 3_601_000,+ accountId: "acct-1",+ accountLabel: "[email protected]",+ });+ expect(fetch.mock.calls[0]?.[0]).toBe("https://auth.openai.com/oauth/token");+ const request = fetch.mock.calls[0]?.[1];+ expect(request?.redirect).toBe("error");+ expect(request?.body).toEqual(+ new URLSearchParams({+ client_id: CHATGPT_CLIENT_ID,+ grant_type: "authorization_code",+ code: "code",+ code_verifier: "verifier",+ redirect_uri: "http://localhost:1455/auth/callback",+ }),+ );+ });++ it("keeps the refresh token when the provider does not rotate it", async () => {+ const previous = {+ accessToken: "old",+ refreshToken: "keep",+ expiresAt: 1,+ accountId: "acct-1",+ };+ await expect(+ requestChatGptTokens(+ { grant_type: "refresh_token", refresh_token: "keep" },+ { previous, fetch: async () => Response.json({ access_token: "new", expires_in: 3600 }) },+ ),+ ).resolves.toMatchObject({ refreshToken: "keep", accountId: "acct-1" });+ });++ it.each([{}, { access_token: "access" }, { access_token: "", refresh_token: "refresh" }])(+ "rejects incomplete credentials",+ async (body) => {+ await expect(+ requestChatGptTokens({}, { fetch: async () => Response.json(body) }),+ ).rejects.toThrow("usable session");+ },+ );++ it("does not expose response bodies or network errors", async () => {+ for (const fetch of [+ async () => new Response("secret", { status: 500 }),+ async () => {+ throw new Error("secret");+ },+ ]) {+ const error = await requestChatGptTokens({}, { fetch }).catch((value: unknown) => value);+ expect(String(error)).not.toContain("secret");+ }+ });++ it.each(["secret-token", "x".repeat(65 * 1024)])(+ "rejects malformed or oversized responses without disclosing them",+ async (body) => {+ await expect(+ requestChatGptTokens({}, { fetch: async () => new Response(body) }),+ ).rejects.toThrow("invalid response");+ },+ );++ it("preserves caller cancellation", async () => {+ const controller = new AbortController();+ controller.abort(new Error("cancelled"));+ await expect(+ requestChatGptTokens(+ {},+ {+ signal: controller.signal,+ fetch: async () => {+ throw new Error("aborted");+ },+ },+ ),+ ).rejects.toThrow("cancelled");+ });+});diff --git a/packages/eve/src/public/models/openai/chatgpt/oauth.ts b/packages/eve/src/public/models/openai/chatgpt/oauth.tsnew file mode 100644index 000000000..93aef38c5--- /dev/null+++ b/packages/eve/src/public/models/openai/chatgpt/oauth.ts@@ -0,0 +1,125 @@+import { isObject } from "#shared/guards.js";+import {+ extractCodexAccountIdFromToken,+ extractCodexAccountLabelFromToken,+ readCodexJwtExpirationMs,+} from "./auth.js";++export const CHATGPT_ISSUER = "https://auth.openai.com";+// OpenAI's public OAuth client, also used by fx and opencode; no client secret.+export const CHATGPT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";+export const CHATGPT_LOGIN_HINT =+ "Open `/model` in `eve dev` and select ChatGPT subscription to sign in.";++export interface ChatGptCredentials {+ readonly accessToken: string;+ readonly refreshToken: string;+ readonly expiresAt: number;+ readonly accountId?: string;+ readonly accountLabel?: string;+}++export class ChatGptSignInRequiredError extends Error {+ constructor() {+ super(`ChatGPT subscription login expired or was revoked. ${CHATGPT_LOGIN_HINT}`);+ }+}++export async function requestChatGptTokens(+ parameters: Record<string, string>,+ options: {+ fetch?: typeof fetch;+ signal?: AbortSignal;+ previous?: ChatGptCredentials;+ now?: () => number;+ } = {},+): Promise<ChatGptCredentials> {+ const signal = AbortSignal.any([+ AbortSignal.timeout(30_000),+ ...(options.signal ? [options.signal] : []),+ ]);+ let response: Response;+ try {+ response = await (options.fetch ?? fetch)(`${CHATGPT_ISSUER}/oauth/token`, {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ client_id: CHATGPT_CLIENT_ID, ...parameters }),+ signal,+ redirect: "error",+ });+ } catch {+ options.signal?.throwIfAborted();+ throw new Error("Could not reach ChatGPT authentication. Check your connection and retry.");+ }+ if (!response.ok) {+ if (options.previous && [400, 401, 403].includes(response.status)) {+ throw new ChatGptSignInRequiredError();+ }+ throw new Error(+ `ChatGPT authentication failed (HTTP ${response.status}). Retry sign-in from /model.`,+ );+ }+ const value = await readChatGptAuthResponse(response);+ const accessToken =+ isObject(value) && typeof value.access_token === "string" ? value.access_token : undefined;+ const refreshToken =+ isObject(value) && typeof value.refresh_token === "string"+ ? value.refresh_token+ : options.previous?.refreshToken;+ if (!accessToken || !refreshToken || !isObject(value)) {+ throw new Error(+ "ChatGPT authentication did not return a usable session. Retry sign-in from /model.",+ );+ }+ const idToken = typeof value.id_token === "string" ? value.id_token : undefined;+ const accountId =+ extractCodexAccountIdFromToken(idToken) ??+ extractCodexAccountIdFromToken(accessToken) ??+ options.previous?.accountId;+ const accountLabel =+ extractCodexAccountLabelFromToken(idToken) ??+ extractCodexAccountLabelFromToken(accessToken) ??+ options.previous?.accountLabel;+ const now = (options.now ?? Date.now)();+ const expiresAt =+ typeof value.expires_in === "number" &&+ Number.isFinite(value.expires_in) &&+ value.expires_in > 0+ ? now + value.expires_in * 1000+ : (readCodexJwtExpirationMs(accessToken) ?? now + 3600_000);+ if (!Number.isFinite(expiresAt) || expiresAt <= now) {+ throw new Error(+ "ChatGPT authentication returned an expired session. Retry sign-in from /model.",+ );+ }+ return {+ accessToken,+ refreshToken,+ expiresAt,+ ...(accountId && { accountId }),+ ...(accountLabel && { accountLabel }),+ };+}++export async function readChatGptAuthResponse(response: Response): Promise<unknown> {+ const reader = response.body?.getReader();+ if (!reader)+ throw new Error("ChatGPT authentication returned an empty response. Retry from /model.");+ try {+ const chunks: Uint8Array[] = [];+ let bytes = 0;+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ bytes += value.byteLength;+ if (bytes > 64 * 1024) throw new Error("Response too large.");+ chunks.push(value);+ }+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));+ } catch {+ await reader.cancel().catch(() => {});+ throw new Error("ChatGPT authentication returned an invalid response. Retry from /model.");+ } finally {+ reader.releaseLock();+ }+}diff --git a/packages/eve/src/public/models/openai/chatgpt/token-broker.test.ts b/packages/eve/src/public/models/openai/chatgpt/token-broker.test.tsindex 9878ecce4..48a4a700d 100644--- a/packages/eve/src/public/models/openai/chatgpt/token-broker.test.ts+++ b/packages/eve/src/public/models/openai/chatgpt/token-broker.test.ts@@ -1,146 +1,150 @@import { describe, expect, it, vi } from "vitest";-import type { CodexAppServer } from "./codex-app-server.js";+import type { ChatGptCredentialStore } from "./credential-store.js";+import type { ChatGptCredentials } from "./oauth.js";import { createCodexTokenBroker } from "./token-broker.js";-import { createUnsignedJwt } from "./unsigned-jwt.js";-describe("Codex token broker", () => {- it("caches a fresh ChatGPT token", async () => {- const token = createUnsignedJwt({- exp: 2_000_000_000,- chatgpt_account_id: "acct-1",- sub: "samlp|profile|[email protected]",- });- const getAuthStatus = vi.fn(async () => ({ authMethod: "chatgpt", authToken: token }));- const broker = createCodexTokenBroker({- appServer: { getAuthStatus },- now: () => 1_800_000_000_000,- });-- await expect(broker.getToken({ reason: "request" })).resolves.toMatchObject({+const credentials: ChatGptCredentials = {+ accessToken: "access-token",+ refreshToken: "refresh-token",+ expiresAt: 2_000_000_000_000,+ accountId: "acct-1",+ accountLabel: "[email protected]",+};++function memoryStore(+ initial: ChatGptCredentials | undefined = credentials,+): ChatGptCredentialStore {+ let value = initial;+ return {+ read: vi.fn(async () => value),+ update: vi.fn(async (callback) => {+ value = await callback(value);+ return value;+ }),+ };+}++function refreshed() {+ return Response.json({+ access_token: "new-access",+ refresh_token: "new-refresh",+ expires_in: 3600,+ });+}++describe("ChatGPT token broker", () => {+ it("caches an eve session without spawning Codex", async () => {+ const store = memoryStore();+ const fetch = vi.fn<typeof globalThis.fetch>();+ const broker = createCodexTokenBroker({ store, fetch, now: () => 1_800_000_000_000 });+ await expect(broker.getToken({ reason: "request" })).resolves.toEqual({+ token: credentials.accessToken,+ expiresAt: credentials.expiresAt,accountId: "acct-1",- accountLabel: "[email protected]",- token,+ accountLabel: "[email protected]",});await broker.getToken({ reason: "request" });-- expect(getAuthStatus).toHaveBeenCalledOnce();- expect(broker.state()).toMatchObject({- kind: "ready",- accountLabel: "[email protected]",- });- });-- it("asks Codex to refresh a token within five minutes of expiry", async () => {- const stale = createUnsignedJwt({ exp: 1_800_000_100 });- const fresh = createUnsignedJwt({ exp: 2_000_000_000 });- const getAuthStatus = vi- .fn<CodexAppServer["getAuthStatus"]>()- .mockResolvedValueOnce({ authMethod: "chatgpt", authToken: stale })- .mockResolvedValueOnce({ authMethod: "chatgpt", authToken: fresh });- const broker = createCodexTokenBroker({- appServer: { getAuthStatus },- now: () => 1_800_000_000_000,- });-- await expect(broker.getToken({ reason: "request" })).resolves.toMatchObject({ token: fresh });- expect(getAuthStatus).toHaveBeenNthCalledWith(1, { refreshToken: false });- expect(getAuthStatus).toHaveBeenNthCalledWith(2, { refreshToken: true });+ expect(store.read).toHaveBeenCalledOnce();+ expect(fetch).not.toHaveBeenCalled();+ expect(broker.state()).toEqual({ kind: "ready", accountLabel: "[email protected]" });});- it("coalesces concurrent forced refreshes", async () => {- const token = createUnsignedJwt({ exp: 2_000_000_000 });- let release: (() => void) | undefined;- const gate = new Promise<void>((resolve) => {- release = resolve;+ it("refreshes within five minutes of expiry and persists rotated credentials", async () => {+ const store = memoryStore({ ...credentials, expiresAt: 1_800_000_100_000 });+ const fetch = vi.fn<typeof globalThis.fetch>(async () => refreshed());+ const broker = createCodexTokenBroker({ store, fetch, now: () => 1_800_000_000_000 });+ await expect(broker.getToken({ reason: "request" })).resolves.toMatchObject({+ token: "new-access",});- const getAuthStatus = vi.fn(async () => {- await gate;- return { authMethod: "chatgpt", authToken: token };+ expect(fetch.mock.calls[0]?.[1]?.body?.toString()).toContain("refresh_token=refresh-token");+ await expect(store.read()).resolves.toMatchObject({+ accessToken: "new-access",+ refreshToken: "new-refresh",});- const broker = createCodexTokenBroker({ appServer: { getAuthStatus } });+ });+ it("coalesces concurrent rejected-token refreshes", async () => {+ const gate = Promise.withResolvers<Response>();+ const fetch = vi.fn<typeof globalThis.fetch>(() => gate.promise);+ const broker = createCodexTokenBroker({ store: memoryStore(), fetch });const first = broker.getToken({ reason: "rejected" });const second = broker.getToken({ reason: "rejected" });- await vi.waitFor(() => expect(getAuthStatus).toHaveBeenCalledOnce());- release?.();+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledOnce());+ gate.resolve(refreshed());await Promise.all([first, second]);-- expect(getAuthStatus).toHaveBeenCalledWith({ refreshToken: true });- });-- it("forces a refresh after an ordinary resolution is already in flight", async () => {- const rejected = createUnsignedJwt({ exp: 2_000_000_000, sub: "rejected" });- const refreshed = createUnsignedJwt({ exp: 2_000_000_000, sub: "refreshed" });- let release: (() => void) | undefined;- const gate = new Promise<void>((resolve) => {- release = resolve;- });- const getAuthStatus = vi- .fn<CodexAppServer["getAuthStatus"]>()- .mockImplementationOnce(async () => {- await gate;- return { authMethod: "chatgpt", authToken: rejected };- })- .mockResolvedValueOnce({ authMethod: "chatgpt", authToken: refreshed });- const broker = createCodexTokenBroker({ appServer: { getAuthStatus } });-- const request = broker.getToken({ reason: "request" });- await vi.waitFor(() => expect(getAuthStatus).toHaveBeenCalledOnce());- const retry = broker.getToken({ reason: "rejected" });- release?.();-- await expect(request).resolves.toMatchObject({ token: rejected });- await expect(retry).resolves.toMatchObject({ token: refreshed });- expect(getAuthStatus).toHaveBeenNthCalledWith(1, { refreshToken: false });- expect(getAuthStatus).toHaveBeenNthCalledWith(2, { refreshToken: true });+ expect(fetch).toHaveBeenCalledOnce();});- it("reports signed out when Codex has no ChatGPT token", async () => {+ it("reuses credentials another eve process refreshed while acquiring the lock", async () => {+ const fetch = vi.fn<typeof globalThis.fetch>();const broker = createCodexTokenBroker({- appServer: { getAuthStatus: async () => ({ requiresOpenaiAuth: true }) },+ fetch,+ store: {+ read: async () => credentials,+ update: async (callback) => callback({ ...credentials, accessToken: "other-process" }),+ },});+ await expect(broker.getToken({ reason: "rejected" })).resolves.toMatchObject({+ token: "other-process",+ });+ expect(fetch).not.toHaveBeenCalled();+ });- await expect(broker.getToken({ reason: "request" })).rejects.toThrow("codex login");- expect(broker.state()).toEqual({ kind: "signed-out" });+ it("forces a refresh after an ordinary resolution already in flight", async () => {+ const gate = Promise.withResolvers<ChatGptCredentials>();+ const store = memoryStore();+ vi.mocked(store.read).mockReturnValueOnce(gate.promise);+ const fetch = vi.fn<typeof globalThis.fetch>(async () => refreshed());+ const broker = createCodexTokenBroker({ store, fetch });+ const first = broker.getToken({ reason: "request" });+ const second = broker.getToken({ reason: "rejected" });+ gate.resolve(credentials);+ await expect(first).resolves.toMatchObject({ token: "access-token" });+ await expect(second).resolves.toMatchObject({ token: "new-access" });+ expect(fetch).toHaveBeenCalledOnce();});- it("reports reauthentication after a rejected token cannot refresh", async () => {- const broker = createCodexTokenBroker({- appServer: { getAuthStatus: async () => ({ authMethod: "chatgpt" }) },+ it("reports signed out and discovers a subsequent eve login", async () => {+ const store = memoryStore();+ vi.mocked(store.read).mockResolvedValueOnce(undefined);+ const broker = createCodexTokenBroker({ store });+ await expect(broker.getToken({ reason: "request" })).rejects.toThrow("/model");+ expect(broker.state()).toEqual({ kind: "signed-out" });+ await expect(broker.refreshState()).resolves.toEqual({+ kind: "ready",+ accountLabel: "[email protected]",});-- await expect(broker.getToken({ reason: "rejected" })).rejects.toThrow("codex login");- expect(broker.state()).toEqual({ kind: "reauth-required" });});- it("restarts Codex before probing a repaired signed-out session", async () => {- const token = createUnsignedJwt({ exp: 2_000_000_000 });- const restart = vi.fn();- const getAuthStatus = vi- .fn<CodexAppServer["getAuthStatus"]>()- .mockResolvedValueOnce({ requiresOpenaiAuth: true })- .mockResolvedValueOnce({ authMethod: "chatgpt", authToken: token });- const broker = createCodexTokenBroker({ appServer: { getAuthStatus, restart } });-- await broker.getToken({ reason: "request" }).catch(() => undefined);- await expect(broker.refreshState()).resolves.toMatchObject({ kind: "ready" });-- expect(restart).toHaveBeenCalledOnce();+ it("preserves the sign-in hint when credentials disappear before a rejected request retries", async () => {+ const store = memoryStore();+ vi.mocked(store.read).mockResolvedValue(undefined);+ const broker = createCodexTokenBroker({ store });+ await expect(broker.getToken({ reason: "rejected" })).rejects.toThrow("/model");+ expect(broker.state()).toEqual({ kind: "reauth-required" });});- it("reports an unavailable app-server without including token material", async () => {- const secret = "secret-bearer-token";+ it("reports revoked credentials without exposing the provider response", async () => {const broker = createCodexTokenBroker({- appServer: {- getAuthStatus: async () => {- throw new Error("Codex app-server exited");- },- },+ store: memoryStore(),+ fetch: async () => new Response("secret-bearer-token", { status: 401 }),});+ await expect(broker.getToken({ reason: "rejected" })).rejects.toThrow("/model");+ expect(broker.state()).toEqual({ kind: "reauth-required" });+ });- const error = await broker.getToken({ reason: "request" }).catch((value: unknown) => value);- expect(String(error)).not.toContain(secret);+ it("keeps credentials after a temporary provider failure and recovers", async () => {+ const fetch = vi+ .fn<typeof globalThis.fetch>()+ .mockResolvedValueOnce(new Response("secret", { status: 503 }))+ .mockResolvedValueOnce(refreshed());+ const store = memoryStore({ ...credentials, expiresAt: 1 });+ const broker = createCodexTokenBroker({ store, fetch });+ await expect(broker.getToken({ reason: "request" })).rejects.toThrow("HTTP 503");expect(broker.state()).toMatchObject({ kind: "unavailable" });+ expect(JSON.stringify(broker.state())).not.toContain("secret");+ await expect(store.read()).resolves.toMatchObject({ refreshToken: "refresh-token" });+ await expect(broker.refreshState()).resolves.toMatchObject({ kind: "ready" });});});diff --git a/packages/eve/src/public/models/openai/chatgpt/token-broker.ts b/packages/eve/src/public/models/openai/chatgpt/token-broker.tsindex 268b93fb7..b367291e3 100644--- a/packages/eve/src/public/models/openai/chatgpt/token-broker.ts+++ b/packages/eve/src/public/models/openai/chatgpt/token-broker.ts@@ -1,13 +1,10 @@+import { createChatGptCredentialStore, type ChatGptCredentialStore } from "./credential-store.js";import {- extractCodexAccountIdFromToken,- extractCodexAccountLabelFromToken,- readCodexJwtExpirationMs,-} from "./auth.js";-import {- CodexAppServerClient,- type CodexAppServer,- type CodexAppServerOptions,-} from "./codex-app-server.js";+ CHATGPT_LOGIN_HINT,+ ChatGptSignInRequiredError,+ requestChatGptTokens,+ type ChatGptCredentials,+} from "./oauth.js";const TOKEN_REFRESH_WINDOW_MS = 5 * 60_000;@@ -34,13 +31,14 @@ export interface CodexTokenBroker {state(): ChatGptAuthState;}-export interface CodexTokenBrokerOptions extends CodexAppServerOptions {- readonly appServer?: CodexAppServer;+export interface CodexTokenBrokerOptions {+ readonly store?: ChatGptCredentialStore;+ readonly fetch?: typeof fetch;readonly now?: () => number;}export function createCodexTokenBroker(options: CodexTokenBrokerOptions = {}): CodexTokenBroker {- const appServer = options.appServer ?? new CodexAppServerClient(options);+ const store = options.store ?? createChatGptCredentialStore();const now = options.now ?? Date.now;let currentState: ChatGptAuthState = { kind: "checking" };let cached: ChatGptToken | undefined;@@ -51,9 +49,6 @@ export function createCodexTokenBroker(options: CodexTokenBrokerOptions = {}): Creturn getToken(input.reason);},async refreshState() {- if (currentState.kind === "signed-out" || currentState.kind === "reauth-required") {- appServer.restart?.();- }cached = undefined;try {await getToken("request");@@ -90,44 +85,47 @@ export function createCodexTokenBroker(options: CodexTokenBrokerOptions = {}): Casync function resolveToken(forceRefresh: boolean): Promise<ChatGptToken> {try {- const status = await appServer.getAuthStatus({ refreshToken: forceRefresh });- if (status.authMethod !== "chatgpt" || status.authToken === undefined) {+ let credentials = await store.read();+ if (!credentials) {cached = undefined;- currentState = forceRefresh ? { kind: "reauth-required" } : { kind: "signed-out" };- throw new Error(- "ChatGPT subscription authentication is unavailable. Run `codex login`, then retry.",- );+ if (forceRefresh) throw new ChatGptSignInRequiredError();+ currentState = { kind: "signed-out" };+ throw new Error(`ChatGPT subscription is not signed in. ${CHATGPT_LOGIN_HINT}`);}- const token = tokenFrom(status.authToken);- if (!forceRefresh && !isFresh(token, now())) {- const refreshed = await appServer.getAuthStatus({ refreshToken: true });- if (refreshed.authMethod !== "chatgpt" || refreshed.authToken === undefined) {- cached = undefined;- currentState = { kind: "reauth-required" };- throw new Error(- "ChatGPT subscription authentication could not be refreshed. Run `codex login`, then retry.",+ const rejectedToken = credentials.accessToken;+ if (forceRefresh || !isFresh(tokenFrom(credentials), now())) {+ credentials = await store.update(async (current) => {+ if (!current) throw new ChatGptSignInRequiredError();+ // A different eve process may already have rotated this refresh token.+ if (+ isFresh(tokenFrom(current), now()) &&+ (!forceRefresh || current.accessToken !== rejectedToken)+ )+ return current;+ return requestChatGptTokens(+ { grant_type: "refresh_token", refresh_token: current.refreshToken },+ {+ fetch: options.fetch,+ previous: current,+ now,+ },);- }- return accept(refreshed.authToken);+ });}+ const token = tokenFrom(credentials);cached = token;currentState = readyState(token);return token;} catch (error) {- if (currentState.kind === "checking" || currentState.kind === "ready") {+ cached = undefined;+ if (error instanceof ChatGptSignInRequiredError) currentState = { kind: "reauth-required" };+ else if (currentState.kind !== "signed-out") {const reason = error instanceof Error ? error.message : String(error);currentState = { kind: "unavailable", reason };}throw error;}}-- function accept(rawToken: string): ChatGptToken {- const token = tokenFrom(rawToken);- cached = token;- currentState = readyState(token);- return token;- }}let defaultBroker: CodexTokenBroker | undefined;@@ -137,15 +135,12 @@ export function getDefaultCodexTokenBroker(): CodexTokenBroker {return defaultBroker;}-function tokenFrom(token: string): ChatGptToken {- const accountId = extractCodexAccountIdFromToken(token);- const accountLabel = extractCodexAccountLabelFromToken(token);- const expiresAt = readCodexJwtExpirationMs(token);+function tokenFrom(credentials: ChatGptCredentials): ChatGptToken {return {- token,- ...(accountId !== undefined && { accountId }),- ...(accountLabel !== undefined && { accountLabel }),- ...(expiresAt !== undefined && { expiresAt }),+ token: credentials.accessToken,+ expiresAt: credentials.expiresAt,+ ...(credentials.accountId && { accountId: credentials.accountId }),+ ...(credentials.accountLabel && { accountLabel: credentials.accountLabel }),};}diff --git a/packages/eve/src/public/models/openai/chatgpt/transport.ts b/packages/eve/src/public/models/openai/chatgpt/transport.tsindex a5db99663..fbb26b0ca 100644--- a/packages/eve/src/public/models/openai/chatgpt/transport.ts+++ b/packages/eve/src/public/models/openai/chatgpt/transport.ts@@ -14,8 +14,7 @@ export interface CodexTransportOptions {/*** Routes OpenAI Responses requests through the Codex backend. Authentication is- * resolved by the Codex CLI; eve never reads, refreshes, or persists OAuth- * credentials itself.+ * resolved and refreshed from eve's local ChatGPT session.*/export function createCodexFetch(options: CodexTransportOptions = {}): Fetch {const httpFetch = options.fetch ?? fetch;diff --git a/packages/eve/src/public/models/openai/index.ts b/packages/eve/src/public/models/openai/index.tsindex 09ac4ac8a..43a56439b 100644--- a/packages/eve/src/public/models/openai/index.ts+++ b/packages/eve/src/public/models/openai/index.ts@@ -4,16 +4,15 @@ import { createCodexSubscriptionModel } from "./chatgpt/model.js";/*** Creates a language model billed to the local ChatGPT subscription instead- * of an API key, served through the Codex backend the `codex login` flow- * authorizes.+ * of an API key. Sign in through `/model` in `eve dev`.** Defaults to `gpt-5.6-sol`. Pass a bare OpenAI model slug or an* `openai/`-prefixed id to override it; the Codex backend serves OpenAI models* only, so any other provider-qualified id is rejected. Model availability is* enforced by the Codex backend per account at call time, not at compile time.*- * Credentials are read from the Codex CLI login on the machine the agent- * runs on, so this model works in local dev and fails in a deployment.+ * eve stores and refreshes credentials locally without requiring the Codex+ * CLI. This model works in local dev and fails in a deployment.* Branch on environment for production:** ```tsdiff --git a/packages/eve/src/setup/flows/chatgpt-auth.scenario.test.ts b/packages/eve/src/setup/flows/chatgpt-auth.scenario.test.tsnew file mode 100644index 000000000..1cd4b271d--- /dev/null+++ b/packages/eve/src/setup/flows/chatgpt-auth.scenario.test.ts@@ -0,0 +1,137 @@+import { createHash } from "node:crypto";+import { createServer } from "node:http";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createCodexTokenBroker } from "#public/models/openai/chatgpt/token-broker.js";+import type { ChatGptCredentialStore } from "#public/models/openai/chatgpt/credential-store.js";+import type { ChatGptCredentials } from "#public/models/openai/chatgpt/oauth.js";+import { ensureChatGptAuth } from "./chatgpt-auth.js";++const controllers: AbortController[] = [];+afterEach(() => {+ for (const controller of controllers.splice(0)) controller.abort();+});++function setup() {+ let credentials: ChatGptCredentials | undefined;+ const store: ChatGptCredentialStore = {+ read: async () => credentials,+ update: vi.fn<ChatGptCredentialStore["update"]>(async (callback) => {+ credentials = await callback(credentials);+ return credentials;+ }),+ };+ const controller = new AbortController();+ controllers.push(controller);+ const fetch = vi.fn<typeof globalThis.fetch>(async () =>+ Response.json({ access_token: "access", refresh_token: "refresh", expires_in: 3600 }),+ );+ return {+ store,+ controller,+ fetch,+ broker: createCodexTokenBroker({ store, fetch }),+ log: vi.fn(),+ headless: false,+ };+}++describe("native ChatGPT browser login", () => {+ it("signs in from an empty eve session with PKCE and ignores unrelated callbacks", async () => {+ const options = setup();+ let state: string | null = null;+ let challenge: string | null = null;+ let browser: Promise<void> | undefined;+ const login = ensureChatGptAuth({+ ...options,+ signal: options.controller.signal,+ open: (url) => {+ browser = (async () => {+ const auth = new URL(url);+ state = auth.searchParams.get("state");+ challenge = auth.searchParams.get("code_challenge");+ expect(auth.searchParams.get("code_challenge_method")).toBe("S256");+ expect(state?.length).toBeGreaterThanOrEqual(32);+ const wrong = await globalThis.fetch(+ "http://127.0.0.1:1455/auth/callback?state=wrong&error=denied",+ );+ expect(wrong.status).toBe(400);+ const valid = await globalThis.fetch(+ `http://127.0.0.1:1455/auth/callback?state=${state}&code=authorization-code`,+ );+ expect(valid.status).toBe(200);+ })();+ },+ });+ await login;+ await browser;+ const body = options.fetch.mock.calls[0]?.[1]?.body;+ expect(body).toBeInstanceOf(URLSearchParams);+ const parameters = body as URLSearchParams;+ expect(parameters.get("code")).toBe("authorization-code");+ expect(+ createHash("sha256")+ .update(parameters.get("code_verifier") ?? "")+ .digest("base64url"),+ ).toBe(challenge);+ await expect(options.store.read()).resolves.toMatchObject({+ accessToken: "access",+ refreshToken: "refresh",+ });+ expect(options.log).toHaveBeenLastCalledWith("ChatGPT subscription connected.");+ expect(options.log.mock.calls.flat().join("\n")).not.toContain("refresh");+ });++ it("cancels the listener without storing credentials, allowing the next login", async () => {+ const options = setup();+ await expect(+ ensureChatGptAuth({+ ...options,+ signal: options.controller.signal,+ open: () => options.controller.abort(new Error("cancelled")),+ }),+ ).rejects.toThrow("cancelled");+ expect(options.store.update).not.toHaveBeenCalled();+ const server = createServer();+ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(1455, "127.0.0.1", resolve);+ });+ await new Promise<void>((resolve) => server.close(() => resolve()));+ });++ it("rejects a declined sign-in without leaking the provider error", async () => {+ const options = setup();+ let browser: Promise<Response> | undefined;+ await expect(+ ensureChatGptAuth({+ ...options,+ open: (url) => {+ const state = new URL(url).searchParams.get("state");+ browser = globalThis.fetch(+ `http://127.0.0.1:1455/auth/callback?state=${state}&error=denied&error_description=secret`,+ );+ },+ }),+ ).rejects.toThrow("declined");+ await browser;+ expect(options.store.update).not.toHaveBeenCalled();+ expect(options.log.mock.calls.flat().join("\n")).not.toContain("secret");+ });+ it("preserves the cancellation reason while a real device timer is pending", async () => {+ const options = setup();+ options.fetch.mockResolvedValueOnce(+ Response.json({ device_auth_id: "device", user_code: "ABCD-EFGH", interval: "30" }),+ );+ const login = ensureChatGptAuth({+ ...options,+ headless: true,+ signal: options.controller.signal,+ open: () => {+ setTimeout(() => options.controller.abort(new Error("device sign-in cancelled")), 10);+ },+ });+ await expect(login).rejects.toThrow("device sign-in cancelled");+ expect(options.store.update).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/setup/flows/chatgpt-auth.test.ts b/packages/eve/src/setup/flows/chatgpt-auth.test.tsnew file mode 100644index 000000000..535541d10--- /dev/null+++ b/packages/eve/src/setup/flows/chatgpt-auth.test.ts@@ -0,0 +1,154 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import type { ChatGptCredentialStore } from "#public/models/openai/chatgpt/credential-store.js";+import type { ChatGptCredentials } from "#public/models/openai/chatgpt/oauth.js";+import { createCodexTokenBroker } from "#public/models/openai/chatgpt/token-broker.js";+import { ensureChatGptAuth } from "./chatgpt-auth.js";++vi.mock("node:timers/promises", () => ({+ setTimeout: (ms: number, _value: unknown, options: { signal: AbortSignal }) =>+ new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ options.signal.removeEventListener("abort", abort);+ resolve();+ }, ms);+ const abort = (): void => {+ clearTimeout(timer);+ reject(new DOMException("The operation was aborted", "AbortError"));+ };+ options.signal.addEventListener("abort", abort, { once: true });+ if (options.signal.aborted) abort();+ }),+}));++afterEach(() => vi.useRealTimers());++function setup() {+ let credentials: ChatGptCredentials | undefined;+ const store: ChatGptCredentialStore = {+ read: async () => credentials,+ update: vi.fn<ChatGptCredentialStore["update"]>(async (callback) => {+ credentials = await callback(credentials);+ return credentials;+ }),+ };+ const fetch = vi.fn<typeof globalThis.fetch>();+ return {+ store,+ fetch,+ broker: createCodexTokenBroker({ store, fetch }),+ open: vi.fn(),+ log: vi.fn(),+ headless: true,+ };+}++const device = { device_auth_id: "device-id", user_code: "ABCD-EFGH", interval: "1" };++describe("ChatGPT device sign-in", () => {+ it("completes a first sign-in after pending polls without any Codex credentials", async () => {+ vi.useFakeTimers();+ const options = setup();+ options.fetch+ .mockResolvedValueOnce(Response.json(device))+ .mockResolvedValueOnce(new Response(null, { status: 403 }))+ .mockResolvedValueOnce(new Response(null, { status: 404 }))+ .mockResolvedValueOnce(+ Response.json({ authorization_code: "code", code_verifier: "verifier" }),+ )+ .mockResolvedValueOnce(+ Response.json({ access_token: "access", refresh_token: "refresh", expires_in: 3600 }),+ );+ const login = ensureChatGptAuth(options);+ await vi.advanceTimersByTimeAsync(6001);+ await login;+ expect(options.open).toHaveBeenCalledWith("https://auth.openai.com/codex/device");+ expect(options.log.mock.calls[0]?.[0]).toContain("ABCD-EFGH");+ expect(options.fetch.mock.calls[1]?.[1]?.body).toBe(+ JSON.stringify({ device_auth_id: "device-id", user_code: "ABCD-EFGH" }),+ );+ const parameters = options.fetch.mock.calls[4]?.[1]?.body as URLSearchParams;+ expect(parameters.get("redirect_uri")).toBe("https://auth.openai.com/deviceauth/callback");+ expect(parameters.get("code_verifier")).toBe("verifier");+ await expect(options.store.read()).resolves.toMatchObject({+ accessToken: "access",+ refreshToken: "refresh",+ });+ });++ it("explains disabled device authorization without exposing provider content", async () => {+ const options = setup();+ options.fetch.mockResolvedValueOnce(new Response("secret", { status: 403 }));+ await expect(ensureChatGptAuth(options)).rejects.toThrow("Settings > Security");+ expect(options.store.update).not.toHaveBeenCalled();+ });++ it("bounds pending device sign-in to five minutes", async () => {+ vi.useFakeTimers();+ const options = setup();+ options.fetch+ .mockResolvedValueOnce(Response.json(device))+ .mockResolvedValue(new Response(null, { status: 404 }));+ const result = ensureChatGptAuth(options).catch((error: unknown) => error);+ await vi.advanceTimersByTimeAsync(300_000);+ expect(String(await result)).toContain("timed out");+ expect(options.store.update).not.toHaveBeenCalled();+ });++ it("cancels polling without storing a partial session", async () => {+ vi.useFakeTimers();+ const options = setup();+ options.fetch.mockResolvedValueOnce(Response.json(device));+ const controller = new AbortController();+ const result = ensureChatGptAuth({ ...options, signal: controller.signal }).catch(+ (error: unknown) => error,+ );+ await vi.advanceTimersByTimeAsync(1);+ controller.abort(new Error("cancelled"));+ expect(String(await result)).toContain("cancelled");+ expect(options.store.update).not.toHaveBeenCalled();+ });++ it("does not save a login cancelled while waiting for the credential lock", async () => {+ vi.useFakeTimers();+ const options = setup();+ options.fetch+ .mockResolvedValueOnce(Response.json(device))+ .mockResolvedValueOnce(+ Response.json({ authorization_code: "code", code_verifier: "verifier" }),+ )+ .mockResolvedValueOnce(+ Response.json({ access_token: "access", refresh_token: "refresh", expires_in: 3600 }),+ );+ const lock = Promise.withResolvers<void>();+ const save = vi.fn();+ vi.mocked(options.store.update).mockImplementationOnce(async (callback) => {+ await lock.promise;+ const credentials = await callback(undefined);+ save(credentials);+ return credentials;+ });+ const controller = new AbortController();+ const result = ensureChatGptAuth({ ...options, signal: controller.signal }).catch(+ (error: unknown) => error,+ );+ await vi.advanceTimersByTimeAsync(2001);+ expect(options.store.update).toHaveBeenCalledOnce();+ controller.abort(new Error("cancelled while waiting"));+ lock.resolve();+ expect(String(await result)).toContain("cancelled while waiting");+ expect(save).not.toHaveBeenCalled();+ });++ it("reuses an existing eve login without opening a browser", async () => {+ const options = setup();+ await options.store.update(async () => ({+ accessToken: "access",+ refreshToken: "refresh",+ expiresAt: Date.now() + 3600_000,+ }));+ await ensureChatGptAuth(options);+ expect(options.open).not.toHaveBeenCalled();+ expect(options.fetch).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/setup/flows/chatgpt-auth.ts b/packages/eve/src/setup/flows/chatgpt-auth.tsindex a7780420d..a8ebfb536 100644--- a/packages/eve/src/setup/flows/chatgpt-auth.ts+++ b/packages/eve/src/setup/flows/chatgpt-auth.ts@@ -1,23 +1,247 @@-import { spawn } from "node:child_process";+import { createHash, randomBytes } from "node:crypto";+import { createServer } from "node:http";+import { setTimeout as delay } from "node:timers/promises";-import { getDefaultCodexTokenBroker } from "#public/models/openai/chatgpt/token-broker.js";+import {+ createChatGptCredentialStore,+ type ChatGptCredentialStore,+} from "#public/models/openai/chatgpt/credential-store.js";+import {+ CHATGPT_CLIENT_ID,+ CHATGPT_ISSUER,+ requestChatGptTokens,+ readChatGptAuthResponse,+ type ChatGptCredentials,+} from "#public/models/openai/chatgpt/oauth.js";+import {+ getDefaultCodexTokenBroker,+ type CodexTokenBroker,+} from "#public/models/openai/chatgpt/token-broker.js";+import { isErrnoCode, isObject } from "#shared/guards.js";+import { openUrl } from "#setup/primitives/open-url.js";+import { WizardCancelledError } from "#setup/step.js";-/** Ensures Codex owns a usable ChatGPT login before setup authors `chatgpt()`. */-export async function ensureChatGptAuth(): Promise<void> {- const state = await getDefaultCodexTokenBroker().refreshState();- if (state.kind === "ready") return;+const LOGIN_TIMEOUT_MS = 5 * 60_000;+const REDIRECT_URI = "http://localhost:1455/auth/callback";++interface ChatGptAuthOptions {+ readonly signal?: AbortSignal;+ readonly broker?: CodexTokenBroker;+ readonly store?: ChatGptCredentialStore;+ readonly fetch?: typeof fetch;+ readonly open?: (url: string) => void;+ readonly log?: (message: string) => void;+ readonly headless?: boolean;+}- const child = spawn("codex", ["login"], { stdio: "inherit" });- await new Promise<void>((resolve, reject) => {- child.once("error", reject);- child.once("exit", (code, signal) => {- if (code === 0) resolve();- else reject(new Error(`codex login failed (${signal ?? code ?? "unknown"}).`));+/** Signs in directly with OpenAI; credentials belong to eve, independently of Codex. */+export async function ensureChatGptAuth(options: ChatGptAuthOptions = {}): Promise<void> {+ const broker = options.broker ?? getDefaultCodexTokenBroker();+ options.signal?.throwIfAborted();+ const state = await broker.refreshState();+ if (state.kind === "ready") return;+ const controller = new AbortController();+ const cancel = (): void => controller.abort(new WizardCancelledError());+ process.once("SIGINT", cancel);+ const timeout = setTimeout(+ () => controller.abort(new Error("ChatGPT sign-in timed out. Retry from /model.")),+ LOGIN_TIMEOUT_MS,+ );+ const signal = AbortSignal.any([controller.signal, ...(options.signal ? [options.signal] : [])]);+ const log = options.log ?? ((message: string) => process.stdout.write(`${message}\n`));+ const open = options.open ?? openUrl;+ try {+ const headless = options.headless ?? Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY);+ const tokens = headless+ ? await deviceLogin({ ...options, signal, log, open })+ : await browserLogin({ ...options, signal, log, open });+ signal.throwIfAborted();+ await (options.store ?? createChatGptCredentialStore()).update(async () => {+ signal.throwIfAborted();+ return tokens;});- });+ const refreshed = await broker.refreshState();+ if (refreshed.kind !== "ready")+ throw new Error("ChatGPT sign-in could not be verified. Retry from /model.");+ log("ChatGPT subscription connected.");+ } catch (error) {+ signal.throwIfAborted();+ throw error;+ } finally {+ clearTimeout(timeout);+ process.removeListener("SIGINT", cancel);+ }+}- const refreshed = await getDefaultCodexTokenBroker().refreshState();- if (refreshed.kind !== "ready") {- throw new Error("Codex login completed without a usable ChatGPT session.");+type LoginOptions = ChatGptAuthOptions & {+ signal: AbortSignal;+ log: (message: string) => void;+ open: (url: string) => void;+};++async function browserLogin(options: LoginOptions): Promise<ChatGptCredentials> {+ const verifier = randomBytes(32).toString("base64url");+ const state = randomBytes(32).toString("base64url");+ const authorization = new URL(`${CHATGPT_ISSUER}/oauth/authorize`);+ authorization.search = new URLSearchParams({+ response_type: "code",+ client_id: CHATGPT_CLIENT_ID,+ redirect_uri: REDIRECT_URI,+ scope: "openid profile email offline_access",+ code_challenge: createHash("sha256").update(verifier).digest("base64url"),+ code_challenge_method: "S256",+ id_token_add_organizations: "true",+ codex_cli_simplified_flow: "true",+ state,+ originator: "eve",+ }).toString();+ const callback = Promise.withResolvers<string>();+ // Attach rejection handling before the listener starts, including immediate cancellation.+ void callback.promise.catch(() => {});+ const server = createServer(+ { requestTimeout: 10_000, headersTimeout: 10_000, maxHeaderSize: 8192 },+ (request, response) => {+ const url = URL.parse(request.url ?? "", REDIRECT_URI);+ response.setHeader("content-type", "text/plain; charset=utf-8");+ response.setHeader("cache-control", "no-store");+ if (request.method !== "GET" || url?.pathname !== "/auth/callback") {+ response.writeHead(404).end("Not found.");+ return;+ }+ if (url.searchParams.get("state") !== state) {+ response+ .writeHead(400)+ .end("This sign-in belongs to another attempt. Return to eve and use its sign-in link.");+ return;+ }+ if (url.searchParams.has("error")) {+ response.writeHead(400).end("ChatGPT sign-in was declined. Return to eve to retry.");+ callback.reject(new Error("ChatGPT sign-in was declined. Retry from /model."));+ return;+ }+ const code = url.searchParams.get("code");+ if (!code) {+ response.writeHead(400).end("Missing authorization code.");+ return;+ }+ response.end(+ "Authorization received. Return to eve to finish connecting your ChatGPT subscription.",+ );+ callback.resolve(code);+ },+ );+ server.maxConnections = 10;+ const abort = (): void => callback.reject(options.signal.reason);+ options.signal.addEventListener("abort", abort, { once: true });+ try {+ options.signal.throwIfAborted();+ try {+ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(1455, "127.0.0.1", resolve);+ });+ } catch (error) {+ if (!isErrnoCode(error, "EADDRINUSE"))+ throw new Error(+ "Could not start ChatGPT sign-in on localhost:1455. Free the port and retry from /model.",+ );+ options.log("Local sign-in port is in use. Continuing with a device code.");+ return await deviceLogin(options);+ }+ options.signal.throwIfAborted();+ options.log(+ `Sign in to ChatGPT in your browser:\n${authorization.href}\nWaiting for sign-in. Press Ctrl+C to cancel.`,+ );+ options.open(authorization.href);+ const code = await callback.promise;+ return await requestChatGptTokens(+ {+ grant_type: "authorization_code",+ code,+ code_verifier: verifier,+ redirect_uri: REDIRECT_URI,+ },+ options,+ );+ } finally {+ options.signal.removeEventListener("abort", abort);+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+}++async function deviceLogin(options: LoginOptions): Promise<ChatGptCredentials> {+ const device = await deviceRequest("usercode", { client_id: CHATGPT_CLIENT_ID }, options);+ if (!device.ok)+ throw new Error(+ `ChatGPT device sign-in is unavailable (HTTP ${device.status}). Enable device code authorization in ChatGPT Settings > Security, then retry from /model.`,+ );+ const value = await readChatGptAuthResponse(device);+ if (+ !isObject(value) ||+ typeof value.device_auth_id !== "string" ||+ !value.device_auth_id ||+ typeof value.user_code !== "string" ||+ !/^[A-Z0-9-]{4,32}$/iu.test(value.user_code)+ ) {+ throw new Error("ChatGPT returned an invalid device code. Retry from /model.");+ }+ const interval = Math.min(30, Math.max(1, Number(value.interval) || 5)) * 1000;+ const url = `${CHATGPT_ISSUER}/codex/device`;+ options.log(+ `Open ${url} and enter code: ${value.user_code}\nIf prompted, enable device code authorization in ChatGPT Settings > Security.\nWaiting for sign-in. Press Ctrl+C to cancel.`,+ );+ options.open(url);+ for (;;) {+ await delay(interval + 1000, undefined, { signal: options.signal });+ const response = await deviceRequest(+ "token",+ { device_auth_id: value.device_auth_id, user_code: value.user_code },+ options,+ );+ if (response.status === 403 || response.status === 404) continue;+ if (!response.ok)+ throw new Error(+ `ChatGPT device sign-in failed (HTTP ${response.status}). Retry from /model.`,+ );+ const result = await readChatGptAuthResponse(response);+ if (+ !isObject(result) ||+ typeof result.authorization_code !== "string" ||+ !result.authorization_code ||+ typeof result.code_verifier !== "string" ||+ !result.code_verifier+ )+ throw new Error("ChatGPT returned an invalid device authorization. Retry from /model.");+ return requestChatGptTokens(+ {+ grant_type: "authorization_code",+ code: result.authorization_code,+ code_verifier: result.code_verifier,+ redirect_uri: `${CHATGPT_ISSUER}/deviceauth/callback`,+ },+ options,+ );+ }+}++async function deviceRequest(+ path: "usercode" | "token",+ body: Record<string, string>,+ options: LoginOptions,+): Promise<Response> {+ try {+ return await (options.fetch ?? fetch)(`${CHATGPT_ISSUER}/api/accounts/deviceauth/${path}`, {+ method: "POST",+ headers: { "content-type": "application/json", "user-agent": "eve" },+ body: JSON.stringify(body),+ redirect: "error",+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(30_000)]),+ });+ } catch {+ options.signal.throwIfAborted();+ throw new Error(+ "Could not reach ChatGPT device sign-in. Check your connection and retry from /model.",+ );}}diff --git a/packages/eve/src/setup/flows/model.ts b/packages/eve/src/setup/flows/model.tsindex 689690ce2..12c930c9d 100644--- a/packages/eve/src/setup/flows/model.ts+++ b/packages/eve/src/setup/flows/model.ts@@ -123,7 +123,7 @@ export interface ModelFlowDeps {readProviderSelection: typeof readProviderSelection;/** The provider sub-flow behind the menu's provider row. */runProviderFlow: typeof runProviderFlow;- /** Ensures Codex owns a usable login before selecting ChatGPT. */+ /** Ensures eve has a usable ChatGPT login before selecting the subscription. */ensureChatGptAuth: typeof ensureChatGptAuth;writeProviderSelection: typeof writeProviderSelection;}@@ -290,7 +290,7 @@ export async function runModelFlow(input: {/** Opens provider setup before the root menu when runtime evidence requires it. */initialStep?: "provider";signal?: AbortSignal;- /** Gives Codex uncontested inherited stdio while it performs login. */+ /** Gives ChatGPT sign-in exclusive terminal ownership. */withExclusiveTerminal?: <T>(task: () => Promise<T>) => Promise<T>;/** Live ChatGPT identity shown in this configuration flow only. */chatGptAccountLabel?: string;@@ -503,7 +503,7 @@ export async function runModelFlow(input: {shouldAuthenticateChatGpt = true;}if (commitDraft && shouldAuthenticateChatGpt) {- await authenticateChatGpt(deps, input.withExclusiveTerminal);+ await authenticateChatGpt(deps, input.withExclusiveTerminal, signal);}if (commitDraft && hasModelSettingsChanges(patch)) {@@ -549,8 +549,9 @@ function routingForModelSelection(selection: string): ModelRouting {async function authenticateChatGpt(deps: ModelFlowDeps,withExclusiveTerminal: (<T>(task: () => Promise<T>) => Promise<T>) | undefined,+ signal: AbortSignal | undefined,): Promise<void> {- const authenticate = (): Promise<void> => deps.ensureChatGptAuth();+ const authenticate = (): Promise<void> => deps.ensureChatGptAuth({ signal });await (withExclusiveTerminal === undefined? authenticate(): withExclusiveTerminal(authenticate));diff --git a/packages/eve/src/setup/flows/provider.ts b/packages/eve/src/setup/flows/provider.tsindex 72c676c5b..09c31b333 100644--- a/packages/eve/src/setup/flows/provider.ts+++ b/packages/eve/src/setup/flows/provider.ts@@ -127,7 +127,7 @@ function providerOptions(hint:selectionExplicit && selectedProvider === "chatgpt"? "Current"- : "Authenticate through the Codex CLI",+ : "Sign in with your ChatGPT account",checked: (selectionExplicit && selectedProvider === "chatgpt") || undefined,},{