The Open Framework for Building Agents
fix(eve): ChatGPT auth - store credentials with just-secrets (#3151)
Andrew Barba6cb22a4e040d
diff --git a/.changeset/quiet-secrets-shine.md b/.changeset/quiet-secrets-shine.mdnew file mode 100644index 000000000..550c93123--- /dev/null+++ b/.changeset/quiet-secrets-shine.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Store ChatGPT refresh credentials in the OS credential store using vendored just-secrets, with access tokens kept in memory. Existing users must sign in once through eve; a successful save removes the old plaintext session file. ChatGPT sign-in now remains inside the model setup panel while browser authentication is in progress.diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex 37a871582..303a0db07 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -192,16 +192,20 @@ Sign in directly from eve; the Codex CLI is not required: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.+eve stores your refresh token and account details in your operating system's credential store through [just-secrets](https://github.com/vercel-labs/just-secrets): the login Keychain on macOS, Credential Manager on Windows, or Secret Service on Linux. Access tokens stay in process memory; a new eve process refreshes the saved session when it first needs a token. The login is separate from Codex and is never written to your project.-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.+If you previously signed in through Codex or used eve's `~/.eve/auth/chatgpt.json` file, sign in once through eve after upgrading. eve removes the old plaintext file after successfully saving the new session. It does not fall back to file storage if the OS credential store is unavailable.++Linux, including WSL, requires `/usr/bin/secret-tool` (commonly provided by `libsecret-tools`), a session D-Bus, and an unlocked Secret Service keyring. On macOS, unlock your login keychain and allow credential access if prompted. On Windows, PowerShell and Credential Manager must be available in your user session. OS credential storage protects secrets at rest; it does not guarantee isolation from malicious processes running as your OS user.++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. Device sign-in still requires an available OS credential store; use an API-key model in headless environments without one.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`**: 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.+- **`chatgpt-sub unavailable`**: follow the reported OS credential-store recovery steps, or check your network connection if token refresh failed. Retry from `/model`. If eve reports an invalid stored session, sign in again to replace it.- **Model rejected by the backend**: model availability depends on the signed-in ChatGPT account. Pick another supported OpenAI model.- **Device sign-in unavailable**: enable device code authorization in ChatGPT security settings, or sign in from a local terminal with port 1455 available.diff --git a/packages/eve/package.json b/packages/eve/package.jsonindex 332cf7503..567e5b975 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -513,6 +513,7 @@"jose": "6.2.3","jsonc-parser": "3.3.1","just-bash": "3.1.0",+ "just-secrets": "0.0.2","marked": "catalog:","microsandbox": "0.5.5","next": "catalog:",diff --git a/packages/eve/scripts/vendor-compiled/index.mjs b/packages/eve/scripts/vendor-compiled/index.mjsindex 711a875b0..f36dd8a32 100644--- a/packages/eve/scripts/vendor-compiled/index.mjs+++ b/packages/eve/scripts/vendor-compiled/index.mjs@@ -48,6 +48,7 @@ import grayMatter from "./gray-matter.mjs";import jose from "./jose.mjs";import jsoncParser from "./jsonc-parser.mjs";import jsonSchema from "./json-schema.mjs";+import justSecrets from "./just-secrets.mjs";import marked from "./marked.mjs";import picocolors from "./picocolors.mjs";import semver from "./semver.mjs";@@ -75,6 +76,7 @@ export const MODULES = [jose,jsoncParser,jsonSchema,+ justSecrets,marked,mcp,modelContextProtocolServer,diff --git a/packages/eve/scripts/vendor-compiled/just-secrets.mjs b/packages/eve/scripts/vendor-compiled/just-secrets.mjsnew file mode 100644index 000000000..2774fa8e4--- /dev/null+++ b/packages/eve/scripts/vendor-compiled/just-secrets.mjs@@ -0,0 +1,13 @@+import { createDeclarationCopier } from "./_shared.mjs";++export default {+ packageName: "just-secrets",+ compiledPath: "just-secrets",+ // The Windows backend loads windows.ps1 relative to import.meta.url.+ bundling: "standalone",+ fingerprintFiles: ["src/windows.ps1"],+ copyDeclarations: createDeclarationCopier({+ declarationRoot: "src",+ discoverExtraFiles: () => ["windows.ps1"],+ }),+};diff --git a/packages/eve/src/cli/dev/tui/setup-commands.test.ts b/packages/eve/src/cli/dev/tui/setup-commands.test.tsindex b247fdcf3..617b40e9b 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.test.ts@@ -241,39 +241,23 @@ describe("runTuiSetupCommand", () => {});});- it("hands model-owned subprocesses both the terminal and suspended runtime", async () => {- const calls: string[] = [];+ it("keeps model setup attached to the TUI panel", async () => {const renderer = fakePanelRenderer();- renderer.withInheritedStdio = async (task) => {- calls.push("terminal:release");- const result = await task();- calls.push("terminal:restore");- return result;- };+ renderer.withInheritedStdio = vi.fn(async (task) => task());+ const exclusiveCalls = vi.fn();const withExclusiveTerminal = async <T>(task: () => Promise<T>): Promise<T> => {- calls.push("runtime:suspend");- const result = await task();- calls.push("runtime:resume");- return result;+ exclusiveCalls();+ return task();};- const flows = fakeFlows({- runModelFlow: vi.fn<TuiSetupFlows["runModelFlow"]>(async (input) => {- await input.withExclusiveTerminal?.(async () => {- calls.push("codex");- });- return { kind: "cancelled" };- }),- });+ const flows = fakeFlows();await run({ command: "model", flows, renderer, withExclusiveTerminal });- expect(calls).toEqual([- "terminal:release",- "runtime:suspend",- "codex",- "runtime:resume",- "terminal:restore",- ]);+ expect(flows.runModelFlow).toHaveBeenCalledWith(+ expect.not.objectContaining({ withExclusiveTerminal: expect.anything() }),+ );+ expect(renderer.withInheritedStdio).not.toHaveBeenCalled();+ expect(exclusiveCalls).not.toHaveBeenCalled();});it("forwards an automatic provider entry to the model flow", async () => {diff --git a/packages/eve/src/cli/dev/tui/setup-commands.ts b/packages/eve/src/cli/dev/tui/setup-commands.tsindex 385e1a4ea..bb208530d 100644--- a/packages/eve/src/cli/dev/tui/setup-commands.ts+++ b/packages/eve/src/cli/dev/tui/setup-commands.ts@@ -293,8 +293,6 @@ async function executeSetupCommand(if (input.onOnboardingScreen !== undefined) {modelInput.onScreen = (screen) => input.onOnboardingScreen?.({ screen });}- modelInput.withExclusiveTerminal = (task) =>- renderer.withInheritedStdio(() => input.withExclusiveTerminal?.(task) ?? task());const result = await flows.runModelFlow(modelInput);if (result.kind === "cancelled") {return {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.tsindex 2c45d3e4a..80ac59b60 100644--- 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.ts@@ -1,72 +1,294 @@-import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readFile, readdir, rm, stat, utimes, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterEach, describe, expect, it } from "vitest";+import { dirname, join } from "node:path";+import { setTimeout as delay } from "node:timers/promises";+import { afterEach, describe, expect, it, vi } from "vitest";-import { createChatGptCredentialStore } from "./credential-store.js";+import {+ ChatGptInvalidStoredSessionError,+ 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 path = join(root, "auth", "chatgpt.json");+ await mkdir(dirname(path), { mode: 0o700 });+ return path;+}++function memorySecrets(initial: string | null = null) {+ let value = initial;+ return {+ get: vi.fn(async (_input: { service: string; name: string }) => value),+ set: vi.fn(async (input: { service: string; name: string; value: string }) => {+ value = input.value;+ }),+ current: () => value,+ replace: (next: string | null) => {+ value = next;+ },+ };}+const credentials = {accessToken: "access",refreshToken: "refresh",expiresAt: 2_000_000_000_000,+ accountId: "account-1",+ accountLabel: "[email protected]",+};+const refreshCredentials = {+ refreshToken: credentials.refreshToken,+ accountId: credentials.accountId,+ accountLabel: credentials.accountLabel,};describe("ChatGPT credential storage", () => {- it("stores credentials atomically with private permissions", async () => {+ it("keeps long access tokens in memory and persists only the refresh session", async () => {const path = await credentialPath();- const store = createChatGptCredentialStore(path);+ const native = memorySecrets();+ const store = createChatGptCredentialStore(path, native);+ const session = { ...credentials, accessToken: `header.${"a".repeat(6000)}.signature` };+ await writeFile(path, JSON.stringify(session));+await expect(store.read()).resolves.toBeUndefined();+ expect(await readFile(path, "utf8")).toBe(JSON.stringify(session));+ await expect(store.update(async () => session)).resolves.toEqual(session);++ expect(native.set).toHaveBeenCalledWith({+ service: "eve",+ name: "chatgpt",+ value: expect.any(String),+ });+ expect(JSON.parse(native.current()!)).toEqual({+ sessionId: expect.any(String),+ ...refreshCredentials,+ });+ expect(native.current()).not.toContain(session.accessToken);+ expect(Buffer.byteLength(native.current()!)).toBeLessThanOrEqual(2560);+ expect(await readdir(dirname(path))).toEqual([]);+ await expect(store.read()).resolves.toEqual(session);+ await expect(createChatGptCredentialStore(path, native).read()).resolves.toEqual(+ refreshCredentials,+ );+ });++ it("preserves warm access across rotation but invalidates it after a replacement login", async () => {+ const path = await credentialPath();+ const native = memorySecrets();+ const first = createChatGptCredentialStore(path, native);+ const second = createChatGptCredentialStore(path, native);+ await first.update(async () => credentials);+ const initialId = JSON.parse(native.current()!).sessionId;++ const rotated = { ...credentials, refreshToken: "rotated", accessToken: "second-access" };+ await second.update(async () => rotated);+ expect(JSON.parse(native.current()!).sessionId).toBe(initialId);+ await expect(first.read()).resolves.toEqual({ ...credentials, refreshToken: "rotated" });++ const replacement = {+ ...credentials,+ accessToken: "replacement-access",+ refreshToken: "replacement-refresh",+ };+ const replace = vi.fn(async () => replacement);+ await second.update(replace, { replace: true });+ expect(replace).toHaveBeenCalledWith(undefined);+ expect(JSON.parse(native.current()!).sessionId).not.toBe(initialId);+ await expect(first.read()).resolves.toEqual({+ ...refreshCredentials,+ refreshToken: "replacement-refresh",+ });+ await expect(second.read()).resolves.toEqual(replacement);+ });++ it("clears warm credentials when the OS entry is deleted", async () => {+ const path = await credentialPath();+ const native = memorySecrets();+ const store = createChatGptCredentialStore(path, native);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);+ const previous = native.current();+ native.replace(null);+ await expect(store.read()).resolves.toBeUndefined();+ native.replace(previous);+ await expect(store.read()).resolves.toEqual(refreshCredentials);});- it("serializes rotation across independent stores and rereads inside the lock", async () => {+ it("serializes independent stores and rereads the latest refresh token inside the lock", async () => {const path = await credentialPath();- const first = createChatGptCredentialStore(path);- const second = createChatGptCredentialStore(path);+ const native = memorySecrets();+ const first = createChatGptCredentialStore(path, native);+ const second = createChatGptCredentialStore(path, native);await first.update(async () => credentials);+ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();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` };- }),- ),- );+ const firstUpdate = first.update(async (current) => {+ observed.push(current?.refreshToken ?? "missing");+ entered.resolve();+ await release.promise;+ return { ...credentials, refreshToken: "refresh-rotated" };+ });+ await entered.promise;+ const secondUpdate = second.update(async (current) => {+ observed.push(current?.refreshToken ?? "missing");+ return { ...credentials, refreshToken: `${current?.refreshToken}-again` };+ });+ release.resolve();+ await Promise.all([firstUpdate, secondUpdate]);expect(observed).toEqual(["refresh", "refresh-rotated"]);+ expect(JSON.parse(native.current()!).refreshToken).toBe("refresh-rotated-again");+ await expect(stat(`${path}.lock`)).rejects.toMatchObject({ code: "ENOENT" });});it("keeps the prior session and releases the lock if refresh fails", async () => {- const store = createChatGptCredentialStore(await credentialPath());+ const path = await credentialPath();+ const native = memorySecrets();+ const store = createChatGptCredentialStore(path, native);await store.update(async () => credentials);+ const saved = native.current();await expect(store.update(async () => {throw new Error("temporary failure");}),).rejects.toThrow("temporary failure");+ expect(native.current()).toBe(saved);+ expect(native.set).toHaveBeenCalledOnce();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 () => {+ it.each(["get", "set"] as const)(+ "sanitizes native %s failures and preserves plaintext until a successful secure save",+ async (operation) => {+ const path = await credentialPath();+ const native = memorySecrets();+ const store = createChatGptCredentialStore(path, native);+ await writeFile(path, "old-plaintext-token");+ native[operation].mockRejectedValueOnce(new Error("native-secret-output"));+ const failure = await store.update(async () => credentials).catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(Error);+ expect(String(failure)).toContain("OS secret store");+ expect(String(failure)).not.toContain("native-secret-output");+ expect(failure).not.toHaveProperty("cause");+ expect(native.current()).toBeNull();+ expect(await readFile(path, "utf8")).toBe("old-plaintext-token");+ await expect(stat(`${path}.lock`)).rejects.toMatchObject({ code: "ENOENT" });++ await expect(store.update(async () => credentials)).resolves.toEqual(credentials);+ await expect(readFile(path, "utf8")).rejects.toMatchObject({ code: "ENOENT" });+ },+ );++ it("recovers when a native write reports failure after committing the session", 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");+ const native = memorySecrets();+ const store = createChatGptCredentialStore(path, native);+ await writeFile(path, "old-plaintext-token");+ native.set.mockImplementationOnce(async ({ value }) => {+ native.replace(value);+ throw new Error("native-secret-output");+ });+ await expect(store.update(async () => credentials)).rejects.toThrow("OS secret store");+ expect(await readFile(path, "utf8")).toBe("old-plaintext-token");+ await expect(store.read()).resolves.toEqual(refreshCredentials);+ await expect(readFile(path, "utf8")).rejects.toMatchObject({ code: "ENOENT" });+ expect(native.set).toHaveBeenCalledOnce();+ });++ it.each([+ "sensitive-token",+ "null",+ JSON.stringify({ sessionId: "", refreshToken: "sensitive-token" }),+ JSON.stringify({ sessionId: "session", refreshToken: "" }),+ "x".repeat(2561),+ ])("replaces an invalid OS record after explicit sign-in (%#)", async (raw) => {+ const path = await credentialPath();+ const native = memorySecrets(raw);+ const store = createChatGptCredentialStore(path, native);+ await writeFile(path, "old-plaintext-token");+ const failure = await store.read().catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(ChatGptInvalidStoredSessionError);+ expect(String(failure)).not.toContain("sensitive-token");+ const refresh = vi.fn(async () => credentials);+ await expect(store.update(refresh)).rejects.toBeInstanceOf(ChatGptInvalidStoredSessionError);+ expect(refresh).not.toHaveBeenCalled();+ expect(native.set).not.toHaveBeenCalled();+ expect(await readFile(path, "utf8")).toBe("old-plaintext-token");++ await expect(store.update(refresh, { replace: true })).resolves.toEqual(credentials);+ expect(refresh).toHaveBeenCalledWith(undefined);+ await expect(store.read()).resolves.toEqual(credentials);+ await expect(readFile(path, "utf8")).rejects.toMatchObject({ code: "ENOENT" });+ });++ it("retries legacy cleanup after secure persistence succeeds but removal fails", async () => {+ const path = await credentialPath();+ const native = memorySecrets();+ const store = createChatGptCredentialStore(path, native);+ await mkdir(path);+ await expect(store.update(async () => credentials)).rejects.toThrow(+ "the old plaintext session could not be removed",+ );+ expect(JSON.parse(native.current()!).refreshToken).toBe(credentials.refreshToken);+ await expect(stat(`${path}.lock`)).rejects.toMatchObject({ code: "ENOENT" });++ await rm(path, { recursive: true });+ await writeFile(path, "old-plaintext-token");+ await expect(store.read()).resolves.toEqual(credentials);+ await expect(readFile(path, "utf8")).rejects.toMatchObject({ code: "ENOENT" });+ expect(native.set).toHaveBeenCalledOnce();+ });++ it("rejects oversized UTF-8 refresh records before any native write", async () => {+ const path = await credentialPath();+ const native = memorySecrets();+ const store = createChatGptCredentialStore(path, native);+ await writeFile(path, "old-plaintext-token");+ await expect(+ store.update(async () => ({ ...credentials, refreshToken: "é".repeat(1300) })),+ ).rejects.toThrow("2,560-byte limit");+ expect(native.set).not.toHaveBeenCalled();+ expect(await readFile(path, "utf8")).toBe("old-plaintext-token");+ await expect(stat(`${path}.lock`)).rejects.toMatchObject({ code: "ENOENT" });+ });++ it("does not steal a pending native write's lock after the former two-minute stale threshold", async () => {+ const path = await credentialPath();+ const native = memorySecrets();+ const first = createChatGptCredentialStore(path, native);+ const second = createChatGptCredentialStore(path, native);+ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const follower = Promise.withResolvers<string | undefined>();+ native.set.mockImplementationOnce(async ({ value }) => {+ entered.resolve();+ await release.promise;+ native.replace(value);+ });+ const firstUpdate = first.update(async () => credentials);+ await entered.promise;+ const old = new Date(Date.now() - 121_000);+ await utimes(`${path}.lock`, old, old);+ const secondUpdate = second.update(async (current) => {+ follower.resolve(current?.refreshToken);+ return { ...credentials, refreshToken: `${current?.refreshToken}-rotated` };+ });+ try {+ await expect(+ Promise.race([follower.promise.then(() => "stolen"), delay(250, "held")]),+ ).resolves.toBe("held");+ } finally {+ release.resolve();+ await Promise.all([firstUpdate, secondUpdate]);+ }+ await expect(follower.promise).resolves.toBe(credentials.refreshToken);+ expect(JSON.parse(native.current()!).refreshToken).toBe("refresh-rotated");});});diff --git a/packages/eve/src/public/models/openai/chatgpt/credential-store.ts b/packages/eve/src/public/models/openai/chatgpt/credential-store.tsindex 600211934..de984a904 100644--- a/packages/eve/src/public/models/openai/chatgpt/credential-store.ts+++ b/packages/eve/src/public/models/openai/chatgpt/credential-store.ts@@ -1,64 +1,105 @@import { randomUUID } from "node:crypto";-import { mkdir, open, rm, stat, writeFile } from "node:fs/promises";+import { mkdir, rm, stat } from "node:fs/promises";import { homedir } from "node:os";import { dirname, join } from "node:path";import { setTimeout as delay } from "node:timers/promises";+import { secrets } from "#compiled/just-secrets/index.js";import { isErrnoCode, isObject } from "#shared/guards.js";-import { renameWithTransientBusyRetry } from "#shared/rename-with-retry.js";-import type { ChatGptCredentials } from "./oauth.js";+import type { ChatGptCredentials, ChatGptRefreshCredentials } from "./oauth.js";++const SECRET_ID = { service: "eve", name: "chatgpt" };+const MAX_SECRET_BYTES = 2560;++export class ChatGptInvalidStoredSessionError extends Error {+ constructor() {+ super(+ "The ChatGPT session in the OS secret store is invalid. Sign in again from /model to replace it.",+ );+ }+}export interface ChatGptCredentialStore {- read(): Promise<ChatGptCredentials | undefined>;+ read(): Promise<ChatGptRefreshCredentials | ChatGptCredentials | undefined>;update(- callback: (current: ChatGptCredentials | undefined) => Promise<ChatGptCredentials>,+ callback: (+ current: ChatGptRefreshCredentials | ChatGptCredentials | undefined,+ ) => Promise<ChatGptCredentials>,+ options?: { replace?: boolean },): Promise<ChatGptCredentials>;}+interface SecretStore {+ get(input: { service: string; name: string }): Promise<string | null>;+ set(input: { service: string; name: string; value: string }): Promise<void>;+}+export function createChatGptCredentialStore(path = join(homedir(), ".eve", "auth", "chatgpt.json"),+ secretStore: SecretStore = secrets,): ChatGptCredentialStore {- async function read(): Promise<ChatGptCredentials | undefined> {- let value: unknown;+ let cached: { sessionId: string; credentials: ChatGptCredentials } | undefined;++ async function removeLegacyFile(): Promise<void> {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;+ await rm(path, { force: true });+ } catch {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.",+ "ChatGPT credentials are stored securely, but the old plaintext session could not be removed. Stop older eve processes, remove ~/.eve/auth/chatgpt.json, and retry.",);}+ }++ async function load() {+ let raw: string | null;+ try {+ raw = await secretStore.get(SECRET_ID);+ } catch {+ throw secretStoreError();+ }+ if (raw === null) {+ cached = undefined;+ return undefined;+ }+ let value: unknown;+ try {+ if (Buffer.byteLength(raw) > MAX_SECRET_BYTES) throw new Error();+ value = JSON.parse(raw);+ } catch {+ throw new ChatGptInvalidStoredSessionError();+ }if (!isObject(value) ||- typeof value.accessToken !== "string" ||- !value.accessToken ||+ typeof value.sessionId !== "string" ||+ !value.sessionId ||typeof value.refreshToken !== "string" ||- !value.refreshToken ||- typeof value.expiresAt !== "number" ||- !Number.isFinite(value.expiresAt)+ !value.refreshToken) {- throw new Error(- "The saved ChatGPT session is invalid. Remove ~/.eve/auth/chatgpt.json and sign in again from /model.",- );+ throw new ChatGptInvalidStoredSessionError();}- return {- accessToken: value.accessToken,+ const refresh: ChatGptRefreshCredentials = {refreshToken: value.refreshToken,- expiresAt: value.expiresAt,...(typeof value.accountId === "string" && { accountId: value.accountId }),...(typeof value.accountLabel === "string" && { accountLabel: value.accountLabel }),};+ // Rotation in another process does not invalidate this process's live access token.+ const credentials =+ cached?.sessionId === value.sessionId+ ? {+ ...refresh,+ accessToken: cached.credentials.accessToken,+ expiresAt: cached.credentials.expiresAt,+ }+ : refresh;+ await removeLegacyFile();+ return { sessionId: value.sessionId, credentials };}return {- read,- async update(callback) {+ async read() {+ return (await load())?.credentials;+ },+ async update(callback, options) {await mkdir(dirname(path), { recursive: true, mode: 0o700 });const lockPath = `${path}.lock`;const deadline = Date.now() + 35_000;@@ -68,12 +109,12 @@ export function createChatGptCredentialStore(break;} catch (error) {if (!isErrnoCode(error, "EEXIST")) throw error;- // Token requests time out after 30 seconds; a two-minute lock survived a crash.+ // Native reads/writes can each wait two minutes for OS prompts, plus OAuth refresh.const info = await stat(lockPath).catch((error: unknown) => {if (isErrnoCode(error, "ENOENT")) return undefined;throw error;});- if (info && Date.now() - info.mtimeMs > 120_000) {+ if (info && Date.now() - info.mtimeMs > 10 * 60_000) {await rm(lockPath, { recursive: true, force: true });continue;}@@ -82,16 +123,50 @@ export function createChatGptCredentialStore(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);+ const current = options?.replace ? undefined : await load();+ const next = await callback(current?.credentials);+ const sessionId = current?.sessionId ?? randomUUID();+ const value = JSON.stringify({+ sessionId,+ refreshToken: next.refreshToken,+ ...(next.accountId && { accountId: next.accountId }),+ ...(next.accountLabel && { accountLabel: next.accountLabel }),+ });+ if (Buffer.byteLength(value) > MAX_SECRET_BYTES) {+ throw new Error(+ "The ChatGPT refresh session exceeds the OS secret store's 2,560-byte limit. Use an API-key model instead.",+ );+ }+ try {+ await secretStore.set({ ...SECRET_ID, value });+ } catch {+ throw secretStoreError();+ }+ cached = { sessionId, credentials: next };+ await removeLegacyFile();return next;} finally {- await rm(temporaryPath, { force: true });await rm(lockPath, { recursive: true, force: true });}},};}++let defaultStore: ChatGptCredentialStore | undefined;++export function getDefaultChatGptCredentialStore(): ChatGptCredentialStore {+ return (defaultStore ??= createChatGptCredentialStore());+}++function secretStoreError(): Error {+ const recovery =+ process.platform === "linux"+ ? "Install libsecret-tools and start or unlock a Secret Service keyring with a session D-Bus. Headless sessions may need an API-key model."+ : process.platform === "win32"+ ? "Allow Windows PowerShell and Credential Manager access in your user session."+ : "Unlock your login keychain and allow credential access.";+ return new Error(+ `Could not access ChatGPT credentials in the OS secret store. ${recovery} Retry from /model.`,+ );+}diff --git a/packages/eve/src/public/models/openai/chatgpt/oauth.ts b/packages/eve/src/public/models/openai/chatgpt/oauth.tsindex 93aef38c5..df05f2533 100644--- a/packages/eve/src/public/models/openai/chatgpt/oauth.ts+++ b/packages/eve/src/public/models/openai/chatgpt/oauth.ts@@ -11,14 +11,17 @@ 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;+export interface ChatGptRefreshCredentials {readonly refreshToken: string;- readonly expiresAt: number;readonly accountId?: string;readonly accountLabel?: string;}+export interface ChatGptCredentials extends ChatGptRefreshCredentials {+ readonly accessToken: string;+ readonly expiresAt: number;+}+export class ChatGptSignInRequiredError extends Error {constructor() {super(`ChatGPT subscription login expired or was revoked. ${CHATGPT_LOGIN_HINT}`);@@ -30,7 +33,7 @@ export async function requestChatGptTokens(options: {fetch?: typeof fetch;signal?: AbortSignal;- previous?: ChatGptCredentials;+ previous?: ChatGptRefreshCredentials;now?: () => number;} = {},): Promise<ChatGptCredentials> {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 48a4a700d..0d28f2c9d 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,7 +1,7 @@import { describe, expect, it, vi } from "vitest";import type { ChatGptCredentialStore } from "./credential-store.js";-import type { ChatGptCredentials } from "./oauth.js";+import type { ChatGptCredentials, ChatGptRefreshCredentials } from "./oauth.js";import { createCodexTokenBroker } from "./token-broker.js";const credentials: ChatGptCredentials = {@@ -13,14 +13,15 @@ const credentials: ChatGptCredentials = {};function memoryStore(- initial: ChatGptCredentials | undefined = credentials,+ initial: ChatGptCredentials | ChatGptRefreshCredentials | undefined = credentials,): ChatGptCredentialStore {let value = initial;return {read: vi.fn(async () => value),- update: vi.fn(async (callback) => {- value = await callback(value);- return value;+ update: vi.fn<ChatGptCredentialStore["update"]>(async (callback) => {+ const next = await callback(value);+ value = next;+ return next;}),};}@@ -46,10 +47,42 @@ describe("ChatGPT token broker", () => {});await broker.getToken({ reason: "request" });expect(store.read).toHaveBeenCalledOnce();+ await expect(broker.refreshState()).resolves.toMatchObject({ kind: "ready" });expect(fetch).not.toHaveBeenCalled();expect(broker.state()).toEqual({ kind: "ready", accountLabel: "[email protected]" });});+ it("exchanges a saved refresh token on a cold start and caches the access token", async () => {+ const store = memoryStore({ refreshToken: "saved-refresh", accountId: "acct-1" });+ const fetch = vi.fn<typeof globalThis.fetch>(async () => refreshed());+ const broker = createCodexTokenBroker({ store, fetch });+ await expect(broker.getToken({ reason: "request" })).resolves.toMatchObject({+ token: "new-access",+ accountId: "acct-1",+ });+ expect(fetch.mock.calls[0]?.[1]?.body?.toString()).toContain("refresh_token=saved-refresh");+ await broker.getToken({ reason: "request" });+ await broker.refreshState();+ expect(fetch).toHaveBeenCalledOnce();+ });++ it("reads the latest saved refresh token after acquiring the update lock", async () => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () => refreshed());+ const broker = createCodexTokenBroker({+ fetch,+ store: {+ read: async () => ({ refreshToken: "previous-refresh" }),+ update: async (callback) => callback({ refreshToken: "rotated-by-other-process" }),+ },+ });+ await expect(broker.getToken({ reason: "request" })).resolves.toMatchObject({+ token: "new-access",+ });+ expect(fetch.mock.calls[0]?.[1]?.body?.toString()).toContain(+ "refresh_token=rotated-by-other-process",+ );+ });+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());diff --git a/packages/eve/src/public/models/openai/chatgpt/token-broker.ts b/packages/eve/src/public/models/openai/chatgpt/token-broker.tsindex b367291e3..da7556e66 100644--- a/packages/eve/src/public/models/openai/chatgpt/token-broker.ts+++ b/packages/eve/src/public/models/openai/chatgpt/token-broker.ts@@ -1,9 +1,13 @@-import { createChatGptCredentialStore, type ChatGptCredentialStore } from "./credential-store.js";+import {+ getDefaultChatGptCredentialStore,+ type ChatGptCredentialStore,+} from "./credential-store.js";import {CHATGPT_LOGIN_HINT,ChatGptSignInRequiredError,requestChatGptTokens,type ChatGptCredentials,+ type ChatGptRefreshCredentials,} from "./oauth.js";const TOKEN_REFRESH_WINDOW_MS = 5 * 60_000;@@ -38,7 +42,7 @@ export interface CodexTokenBrokerOptions {}export function createCodexTokenBroker(options: CodexTokenBrokerOptions = {}): CodexTokenBroker {- const store = options.store ?? createChatGptCredentialStore();+ const store = options.store ?? getDefaultChatGptCredentialStore();const now = options.now ?? Date.now;let currentState: ChatGptAuthState = { kind: "checking" };let cached: ChatGptToken | undefined;@@ -92,14 +96,15 @@ export function createCodexTokenBroker(options: CodexTokenBrokerOptions = {}): CcurrentState = { kind: "signed-out" };throw new Error(`ChatGPT subscription is not signed in. ${CHATGPT_LOGIN_HINT}`);}- const rejectedToken = credentials.accessToken;+ const rejectedToken = tokenFrom(credentials)?.token;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 (+ "accessToken" in current &&isFresh(tokenFrom(current), now()) &&- (!forceRefresh || current.accessToken !== rejectedToken)+ (!forceRefresh || tokenFrom(current)?.token !== rejectedToken))return current;return requestChatGptTokens(@@ -113,6 +118,7 @@ export function createCodexTokenBroker(options: CodexTokenBrokerOptions = {}): C});}const token = tokenFrom(credentials);+ if (!token) throw new Error(`ChatGPT access token is unavailable. ${CHATGPT_LOGIN_HINT}`);cached = token;currentState = readyState(token);return token;@@ -135,7 +141,10 @@ export function getDefaultCodexTokenBroker(): CodexTokenBroker {return defaultBroker;}-function tokenFrom(credentials: ChatGptCredentials): ChatGptToken {+function tokenFrom(+ credentials: ChatGptCredentials | ChatGptRefreshCredentials,+): ChatGptToken | undefined {+ if (!("accessToken" in credentials)) return undefined;return {token: credentials.accessToken,expiresAt: credentials.expiresAt,@@ -151,6 +160,9 @@ function readyState(token: ChatGptToken): ChatGptAuthState {};}-function isFresh(token: ChatGptToken, now: number): boolean {- return token.expiresAt === undefined || token.expiresAt - TOKEN_REFRESH_WINDOW_MS > now;+function isFresh(token: ChatGptToken | undefined, now: number): boolean {+ return (+ token !== undefined &&+ (token.expiresAt === undefined || token.expiresAt - TOKEN_REFRESH_WINDOW_MS > now)+ );}diff --git a/packages/eve/src/setup/flows/chatgpt-auth.test.ts b/packages/eve/src/setup/flows/chatgpt-auth.test.tsindex 535541d10..83a1cbbc5 100644--- a/packages/eve/src/setup/flows/chatgpt-auth.test.ts+++ b/packages/eve/src/setup/flows/chatgpt-auth.test.ts@@ -1,6 +1,9 @@import { afterEach, describe, expect, it, vi } from "vitest";-import type { ChatGptCredentialStore } from "#public/models/openai/chatgpt/credential-store.js";+import {+ ChatGptInvalidStoredSessionError,+ 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";@@ -46,6 +49,44 @@ function setup() {const device = { device_auth_id: "device-id", user_code: "ABCD-EFGH", interval: "1" };describe("ChatGPT device sign-in", () => {+ it("reports unavailable secure storage before opening OAuth", async () => {+ const options = setup();+ vi.spyOn(options.store, "read").mockRejectedValue(new Error("OS secret store is locked"));+ await expect(ensureChatGptAuth(options)).rejects.toThrow("OS secret store is locked");+ expect(options.open).not.toHaveBeenCalled();+ expect(options.fetch).not.toHaveBeenCalled();+ expect(options.store.update).not.toHaveBeenCalled();+ });++ it("checks secure storage even after the broker was previously signed out", async () => {+ const options = setup();+ await expect(options.broker.refreshState()).resolves.toEqual({ kind: "signed-out" });+ vi.spyOn(options.store, "read").mockRejectedValue(new Error("OS secret store is locked"));+ await expect(ensureChatGptAuth(options)).rejects.toThrow("OS secret store is locked");+ expect(options.open).not.toHaveBeenCalled();+ expect(options.fetch).not.toHaveBeenCalled();+ });++ it("allows a new sign-in to replace malformed secure credentials", async () => {+ vi.useFakeTimers();+ const options = setup();+ vi.spyOn(options.store, "read")+ .mockRejectedValueOnce(new ChatGptInvalidStoredSessionError())+ .mockRejectedValueOnce(new ChatGptInvalidStoredSessionError());+ 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 login = ensureChatGptAuth(options);+ await vi.advanceTimersByTimeAsync(2001);+ await login;+ expect(options.store.update).toHaveBeenCalledWith(expect.any(Function), { replace: true });+ });+it("completes a first sign-in after pending polls without any Codex credentials", async () => {vi.useFakeTimers();const options = setup();diff --git a/packages/eve/src/setup/flows/chatgpt-auth.ts b/packages/eve/src/setup/flows/chatgpt-auth.tsindex a8ebfb536..9d7929996 100644--- a/packages/eve/src/setup/flows/chatgpt-auth.ts+++ b/packages/eve/src/setup/flows/chatgpt-auth.ts@@ -3,7 +3,8 @@ import { createServer } from "node:http";import { setTimeout as delay } from "node:timers/promises";import {- createChatGptCredentialStore,+ ChatGptInvalidStoredSessionError,+ getDefaultChatGptCredentialStore,type ChatGptCredentialStore,} from "#public/models/openai/chatgpt/credential-store.js";import {@@ -37,9 +38,15 @@ interface ChatGptAuthOptions {/** 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();+ const store = options.store ?? getDefaultChatGptCredentialStore();options.signal?.throwIfAborted();const state = await broker.refreshState();if (state.kind === "ready") return;+ try {+ await store.read();+ } catch (error) {+ if (!(error instanceof ChatGptInvalidStoredSessionError)) throw error;+ }const controller = new AbortController();const cancel = (): void => controller.abort(new WizardCancelledError());process.once("SIGINT", cancel);@@ -56,10 +63,13 @@ export async function ensureChatGptAuth(options: ChatGptAuthOptions = {}): Promi? await deviceLogin({ ...options, signal, log, open }): await browserLogin({ ...options, signal, log, open });signal.throwIfAborted();- await (options.store ?? createChatGptCredentialStore()).update(async () => {- signal.throwIfAborted();- return tokens;- });+ await store.update(+ async () => {+ signal.throwIfAborted();+ return tokens;+ },+ { replace: true },+ );const refreshed = await broker.refreshState();if (refreshed.kind !== "ready")throw new Error("ChatGPT sign-in could not be verified. Retry from /model.");diff --git a/packages/eve/src/setup/flows/model.test.ts b/packages/eve/src/setup/flows/model.test.tsindex 1d6313f43..90f53c35e 100644--- a/packages/eve/src/setup/flows/model.test.ts+++ b/packages/eve/src/setup/flows/model.test.ts@@ -185,22 +185,21 @@ describe("runModelFlow", () => {expect(menuPaints[0]?.notices).toEqual([]);});- it("selects ChatGPT under Change provider through exclusive terminal auth", async () => {+ it("keeps ChatGPT authentication inside the model flow panel", async () => {const { prompter, menuPaints } = scriptedPrompter({ menu: ["provider"] });- const ensureChatGptAuth = vi.fn(async () => {});+ const stopSpinner = vi.fn();+ prompter.log.spinner = vi.fn((message) => ({+ stop: message.startsWith("Waiting for ChatGPT") ? stopSpinner : vi.fn(),+ }));+ const ensureChatGptAuth = vi.fn<ModelFlowDeps["ensureChatGptAuth"]>(async (options) => {+ options?.log?.("Sign in to ChatGPT in your browser.");+ });const deps = flowDeps({ensureChatGptAuth,runProviderFlow: vi.fn(async () => ({ kind: "chatgpt" }) as const),});- const exclusiveCalls: string[] = [];- const withExclusiveTerminal = async <T>(task: () => Promise<T>): Promise<T> => {- exclusiveCalls.push("called");- return task();- };- await expect(- runModelFlow({ appRoot: APP_ROOT, prompter, deps, withExclusiveTerminal }),- ).resolves.toEqual({+ await expect(runModelFlow({ appRoot: APP_ROOT, prompter, deps })).resolves.toEqual({kind: "done",accessChanged: true,modelMessage: `Model changed to ${pc.bold("chatgpt/gpt-5.6-sol")}. Live on your next prompt.`,@@ -213,7 +212,12 @@ describe("runModelFlow", () => {"done",]);expect(menuPaints).toHaveLength(1);- expect(exclusiveCalls).toEqual(["called"]);+ expect(prompter.log.spinner).toHaveBeenCalledWith(+ "Waiting for ChatGPT sign-in in your browser…",+ { kind: "external-action", emphasis: "browser" },+ );+ expect(prompter.log.info).toHaveBeenCalledWith("Sign in to ChatGPT in your browser.");+ expect(stopSpinner).toHaveBeenCalledOnce();expect(ensureChatGptAuth).toHaveBeenCalledOnce();expect(deps.applySettings).toHaveBeenCalledWith({appRoot: APP_ROOT,diff --git a/packages/eve/src/setup/flows/model.ts b/packages/eve/src/setup/flows/model.tsindex f2a9e5463..a402cb3d2 100644--- a/packages/eve/src/setup/flows/model.ts+++ b/packages/eve/src/setup/flows/model.ts@@ -291,8 +291,6 @@ export async function runModelFlow(input: {initialStep?: "provider";onScreen?: (screen: "model_provider" | "model_settings") => void;signal?: AbortSignal;- /** 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;deps?: Partial<ModelFlowDeps>;@@ -506,7 +504,7 @@ export async function runModelFlow(input: {shouldAuthenticateChatGpt = true;}if (commitDraft && shouldAuthenticateChatGpt) {- await authenticateChatGpt(deps, input.withExclusiveTerminal, signal);+ await authenticateChatGpt(deps, prompter, signal);}if (commitDraft && hasModelSettingsChanges(patch)) {@@ -551,13 +549,21 @@ function routingForModelSelection(selection: string): ModelRouting {async function authenticateChatGpt(deps: ModelFlowDeps,- withExclusiveTerminal: (<T>(task: () => Promise<T>) => Promise<T>) | undefined,+ prompter: Prompter,signal: AbortSignal | undefined,): Promise<void> {- const authenticate = (): Promise<void> => deps.ensureChatGptAuth({ signal });- await (withExclusiveTerminal === undefined- ? authenticate()- : withExclusiveTerminal(authenticate));+ const spinner = prompter.log.spinner?.("Waiting for ChatGPT sign-in in your browser…", {+ kind: "external-action",+ emphasis: "browser",+ });+ try {+ await deps.ensureChatGptAuth({+ signal,+ log: (message) => prompter.log.info(message),+ });+ } finally {+ spinner?.stop();+ }}function hasModelSettingsChanges(patch: AgentModelSettingsPatch): boolean {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 676ce4f25..25726c597 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1500,6 +1500,9 @@ importers:just-bash:specifier: 3.1.0version: 3.1.0([email protected])+ just-secrets:+ specifier: 0.0.2+ version: 0.0.2marked:specifier: 'catalog:'version: 17.0.6@@ -11868,6 +11871,10 @@ packages:resolution: {integrity: sha512-/t28X8EH3+j/zvELGkNhlFV2g6hc3oHBzy6zPBnNq2nqUN0DGS9PsD889JfQ7F6ll08gqFoutiS+VJHK30wZpg==}+ resolution: {integrity: sha512-8Zh2rbEtvRQN6OJnHNO39g5E7MR80GpSxfezrAhre3wzhgCnmdK1oismE1qMW3S+aaIQ3REIoramtIqHVTDavA==}+ engines: {node: '>=22'}+resolution: {integrity: sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==}@@ -27540,6 +27547,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+dependencies:buffer-equal-constant-time: 1.0.1diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex fcf33126d..96f45b2bd 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -66,6 +66,7 @@ minimumReleaseAgeExclude:- "@upstash/*"- "@vercel/*"- "@workflow/*"- nitro# Required by [email protected], published September 3.