Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,11 @@ changes Orca files, or changes the active pool account.

### `ocx account list [provider] [--json] [--all] [--quota [--refresh]]`

Stored ChatGPT pool accounts remain listable on hosts without a native Codex home, including in the
dashboard and on account refresh. Listing does not create a Codex home or sign out the native main
account. Disabling the Codex client integration does not disable an existing native login's quota
observation; invalid explicit `CODEX_HOME` paths still report a configuration error.

Without a provider, lists the Codex pool, OAuth accounts, and configured API-key pools. Empty
providers are skipped unless `--all` is present. With a provider, lists only that credential family.
Human output uses `PROVIDER TYPE ID PLAN/LABEL PRIORITY STATUS`; a manually chosen Codex row is marked
Expand Down
1 change: 1 addition & 0 deletions scripts/test-layout/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"server-combo-plan-model-refusal.test.ts": "server",
"codex-main-token-invalidated.test.ts": "codex-integration",
"codex-main-grant-refusal.test.ts": "codex-integration",
"codex-auth-headless-accounts.test.ts": "codex-integration",
"responses-alternate-main-cancellation.test.ts": "responses",
"codex-shim-path-readiness.test.ts": "codex-integration",
"codex-shim-fnm.test.ts": "codex-integration",
Expand Down
4 changes: 2 additions & 2 deletions src/codex/auth-api/account-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import type { OAuthAccountHealth, OAuthHealthLabel } from "../../oauth/health";
import { isSelectableCodexPoolAccount } from "../account-id";
import type { AdmissionLease } from "../../lib/admission";
import { tryAcquireNativeMainProfileClaim } from "../native-main-admission";
import { withNativeMainCredentialClaim, isNativeMainClaimUnavailable } from "./http";
import { withNativeMainCredentialClaim, isNativeMainClaimUnavailable, isNativeMainObservationUnavailable } from "./http";
import { fetchMainAccountInfoAttempt, EMPTY_MAIN_ACCOUNT_INFO, mainResetCreditsForCurrentIdentity } from "./main-account-probe";
import { fetchPoolAccountQuota, PoolQuotaProbeBusyError, POOL_QUOTA_REFRESH_CONCURRENCY } from "./pool-quota-probe";
import type { PoolQuotaResult } from "./pool-quota-probe";
Expand Down Expand Up @@ -442,7 +442,7 @@ export async function listCodexAuthAccountsSnapshot(
try {
return await withNativeMainCredentialClaim(async () => projectSnapshot(isMainAccountRefreshGrantRejected()));
} catch (error) {
if (isNativeMainClaimUnavailable(error)) return projectSnapshot();
if (isNativeMainObservationUnavailable(error)) return projectSnapshot();
throw error;
} finally {
projectionLease.release();
Expand Down
6 changes: 6 additions & 0 deletions src/codex/auth-api/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ export function isNativeMainClaimUnavailable(error: unknown): error is NativePro
&& (error.code === "NATIVE_MAIN_CLAIM_BUSY" || error.code === "NATIVE_MAIN_CLAIM_UNAVAILABLE");
}

/** Missing native homes leave reads unobserved; credential operations still require their claim. */
export function isNativeMainObservationUnavailable(error: unknown): error is NativeProfileError {
return error instanceof NativeProfileError
&& (error.code === "CODEX_HOME_UNAVAILABLE" || isNativeMainClaimUnavailable(error));
Comment thread
alexalok marked this conversation as resolved.
Resolved
Comment thread
alexalok marked this conversation as resolved.
Resolved
}

export function withNativeMainCredentialClaim<T>(operation: () => Promise<T>): Promise<T> {
return withNativeMainSharedClaim(resolveNativeProfileContext(), operation);
}
Expand Down
4 changes: 2 additions & 2 deletions src/codex/auth-api/main-account-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import type { AdmissionLease } from "../../lib/admission";
import { nonEmptyPlan } from "./runtime-config";
import { tryAcquireNativeMainProfileClaim } from "../native-main-admission";
import { WHAM_REQUEST_TIMEOUT_MS } from "../quota-recovery-timing";
import { withNativeMainCredentialClaim, isNativeMainClaimUnavailable } from "./http";
import { withNativeMainCredentialClaim, isNativeMainObservationUnavailable } from "./http";
import { readMainAuthErrorCode, currentQuotaDispatchSequence, nextQuotaDispatchSequence, isQuotaDispatchCurrent, publishQuotaDispatch } from "./pool-quota-probe";

/**
Expand Down Expand Up @@ -198,7 +198,7 @@ export async function fetchMainAccountInfoAttempt(
try {
return await withNativeMainCredentialClaim(operation);
} catch (error) {
if (isNativeMainClaimUnavailable(error)) {
if (isNativeMainObservationUnavailable(error)) {
return {
info: EMPTY_MAIN_ACCOUNT_INFO,
credentialChecked: false,
Expand Down
6 changes: 3 additions & 3 deletions structure/providers/openai-accounts.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,9 +250,9 @@ restored from the Accounts picker or Codex Auth through gated recovery: missing
from the canonical preset, disabled canonical rows are re-enabled without replacing saved mode or
model settings, and noncanonical `openai` rows never receive that recovery path.

`GET /api/codex-auth/accounts?refresh=1` treats missing main credentials, HTTP 401, and allowlisted
terminal 403 codes as `needsReauth`; generic permission failures remain non-terminal, and a
successful main usage refresh clears the runtime mark.
Account listing and explicit refresh return stored pool accounts without creating a missing native `CODEX_HOME`; an unchecked main observation leaves credential/reauth state unchanged.
When the native home is accessible, `GET /api/codex-auth/accounts?refresh=1` treats missing main credentials, HTTP 401 responses with a known terminal code, unrecognized HTTP 401 responses when the access token is not verifiably live, and allowlisted terminal 403 responses as `needsReauth`; successful refresh clears the runtime mark.
Generic permission failures remain non-terminal; invalid explicit home paths and unsafe storage still fail closed, and credential operations retain their strict claim requirements.

`src/codex/chatgpt-refresh-failure.ts` classifies token-endpoint failures for both stored-pool
and native-main refresh. Exact structured terminal codes apply only to authentication-error
Expand Down
199 changes: 199 additions & 0 deletions tests/codex-integration/codex-auth-headless-accounts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { getCodexAccountCredential, saveCodexAccountCredential } from "../../src/codex/account-store";
import { resetMainCodexAccountIdentityTrackingForTests } from "../../src/codex/account-lifecycle";
import { clearAccountNeedsReauth, isAccountNeedsReauth, markAccountNeedsReauth } from "../../src/codex/account-runtime-state";
import type { CodexAuthAccountDto } from "../../src/codex/auth-api/account-list";
import { withNativeMainCredentialClaim } from "../../src/codex/auth-api/http";
import { handleCodexAuthAPI } from "../../src/codex/auth-api/routes";
import {
captureMainAccountIdentityGeneration, clearMainAccountInfoCache,
getMainAccountCredentialPresence, getMainAccountInfoCache,
} from "../../src/codex/main-account-cache";
import { MAIN_CODEX_ACCOUNT_ID } from "../../src/codex/main-account";
import { clearAccountQuota } from "../../src/codex/quota";
import { resetQuotaQueryBackoffForTests } from "../../src/codex/quota-query-backoff";
import { resetLifecycleDrainStateForTests } from "../../src/server/lifecycle";
import type { OcxConfig } from "../../src/types";
import { removeTreeWithRetry } from "../helpers/remove-tree";

let root: string;
let nativeHome: string;
let previousOcxHome: string | undefined;
let previousCodexHome: string | undefined;
let originalFetch: typeof fetch;
const poolId = "headless-pool";

function config(codexIntegration = false): OcxConfig {
return {
port: 10100, defaultProvider: "openai", providers: {},
clientIntegrations: { codex: codexIntegration },
codexAccounts: [{ id: poolId, email: "pool@example.test", plan: "plus", isMain: false }],
};
}

function savePool() {
saveCodexAccountCredential(poolId, {
accessToken: "fixture-pool-access", refreshToken: "fixture-pool-refresh",
chatgptAccountId: "fixture-pool-identity", expiresAt: Date.now() + 3_600_000,
});
return getCodexAccountCredential(poolId);
}

function usageResponse(): Response {
return Response.json({
plan_type: "plus",
rate_limit: { primary_window: { used_percent: 17, limit_window_seconds: 18_000 } },
});
}

async function listAccounts(cfg: OcxConfig, method = "GET", suffix = "") {
const url = new URL(`http://localhost/api/codex-auth/accounts${suffix}`);
const response = await handleCodexAuthAPI(new Request(url, { method }), url, cfg);
expect(response?.status).toBe(200);
return (await response!.json() as { accounts: CodexAuthAccountDto[] }).accounts;
}

function resetRuntimeState() {
clearMainAccountInfoCache();
clearAccountQuota();
clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
clearAccountNeedsReauth(poolId);
resetMainCodexAccountIdentityTrackingForTests();
resetQuotaQueryBackoffForTests();
resetLifecycleDrainStateForTests();
}

beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "ocx-headless-accounts-"));
nativeHome = join(root, "missing-codex-home");
previousOcxHome = process.env.OPENCODEX_HOME;
previousCodexHome = process.env.CODEX_HOME;
process.env.OPENCODEX_HOME = join(root, "ocx");
process.env.CODEX_HOME = nativeHome;
mkdirSync(process.env.OPENCODEX_HOME);
originalFetch = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = new URL(input instanceof Request ? input.url : String(input));
if (url.origin !== "https://chatgpt.com" || !url.pathname.endsWith("/wham/usage")) {
throw new Error("unexpected fixture network request");
}
return usageResponse();
}) as typeof fetch;
resetRuntimeState();
});

afterEach(() => {
globalThis.fetch = originalFetch;
resetRuntimeState();
if (previousOcxHome === undefined) delete process.env.OPENCODEX_HOME;
else process.env.OPENCODEX_HOME = previousOcxHome;
if (previousCodexHome === undefined) delete process.env.CODEX_HOME;
else process.env.CODEX_HOME = previousCodexHome;
removeTreeWithRetry(root);
});

describe("account listing without a native Codex home", () => {
for (const integration of [false, true]) {
for (const [method, suffix] of [["GET", ""], ["GET", "?refresh=1"], ["POST", "/refresh"]]) {
test(`${method} accounts${suffix}, integration=${integration}: stored pool remains available`, async () => {
const credential = savePool();
const accounts = await listAccounts(config(integration), method, suffix);
expect(accounts).toHaveLength(2);
expect(accounts.find(account => account.id === poolId)).toMatchObject({
hasCredential: true, needsReauth: false, plan: "plus", quota: { shortPercent: 17 },
});
expect(accounts.find(account => account.id === MAIN_CODEX_ACCOUNT_ID)).toMatchObject({
hasCredential: false, needsReauth: false, quota: null,
});
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(false);
expect(getCodexAccountCredential(poolId)).toEqual(credential);
expect(existsSync(nativeHome)).toBe(false);
});
}
}

test("an explicit non-directory CODEX_HOME still refuses account listing", async () => {
writeFileSync(nativeHome, "fixture-not-a-directory");
const credential = savePool();
await expect(listAccounts(config())).rejects.toThrow("not a directory");
expect(getCodexAccountCredential(poolId)).toEqual(credential);
expect(readFileSync(nativeHome, "utf8")).toBe("fixture-not-a-directory");
});

test("a home removed during pool refresh does not fail final account projection", async () => {
mkdirSync(nativeHome);
savePool();
globalThis.fetch = (async () => {
removeTreeWithRetry(nativeHome);
return usageResponse();
}) as typeof fetch;
const accounts = await listAccounts(config());
expect(accounts.find(account => account.id === poolId)).toMatchObject({
hasCredential: true, needsReauth: false, quota: { shortPercent: 17 },
});
expect(existsSync(nativeHome)).toBe(false);
});

test("disabled client integration still observes an existing native login", async () => {
mkdirSync(nativeHome);
const auth = JSON.stringify({ tokens: {
access_token: "fixture-main-access", account_id: "fixture-main-identity",
} });
writeFileSync(join(nativeHome, "auth.json"), auth);
savePool();
const accounts = await listAccounts(config());
expect(accounts.find(account => account.id === MAIN_CODEX_ACCOUNT_ID)).toMatchObject({
hasCredential: true, needsReauth: false, plan: "plus", quota: { shortPercent: 17 },
});
expect(readFileSync(join(nativeHome, "auth.json"), "utf8")).toBe(auth);
});

test("a missing home preserves previously observed identity and reauth state", async () => {
mkdirSync(nativeHome);
writeFileSync(join(nativeHome, "auth.json"), JSON.stringify({ tokens: {
access_token: "fixture-main-access", account_id: "fixture-main-identity",
} }));
savePool();
await listAccounts(config());
markAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
const generation = captureMainAccountIdentityGeneration();
const info = getMainAccountInfoCache();
expect(info?.quota?.shortPercent).toBe(17);
expect(getMainAccountCredentialPresence()).toBe(true);
removeTreeWithRetry(nativeHome);

const accounts = await listAccounts(config(), "GET", "?refresh=1");
expect(accounts.find(account => account.id === MAIN_CODEX_ACCOUNT_ID)).toMatchObject({
hasCredential: true, needsReauth: true, quota: null,
});
expect(accounts.find(account => account.id === poolId)).toMatchObject({
hasCredential: true, needsReauth: false, quota: { shortPercent: 17 },
});
expect(captureMainAccountIdentityGeneration()).toBe(generation);
expect(getMainAccountInfoCache()).toEqual(info);
expect(getMainAccountCredentialPresence()).toBe(true);
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(true);
expect(existsSync(nativeHome)).toBe(false);
});

test("an unsafe OpenCodex storage root still refuses account listing", async () => {
mkdirSync(nativeHome);
const unsafeRoot = join(root, "not-a-config-directory");
writeFileSync(unsafeRoot, "fixture-unsafe-root");
process.env.OPENCODEX_HOME = unsafeRoot;
await expect(listAccounts(config())).rejects.toMatchObject({ code: "PROFILE_STORAGE_UNSAFE" });
expect(readFileSync(unsafeRoot, "utf8")).toBe("fixture-unsafe-root");
});

test("credential operations still refuse a missing native home before executing", async () => {
const mutationPath = join(root, "must-not-be-written");
await expect((async () => withNativeMainCredentialClaim(async () => {
writeFileSync(mutationPath, "unexpected mutation");
}))()).rejects.toMatchObject({ code: "CODEX_HOME_UNAVAILABLE" });
expect(existsSync(mutationPath)).toBe(false);
expect(existsSync(nativeHome)).toBe(false);
});
});
1 change: 1 addition & 0 deletions tests/fixtures/test-layout-expected.json
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@
"server-combo-plan-model-refusal.test.ts": "server",
"codex-main-token-invalidated.test.ts": "codex-integration",
"codex-main-grant-refusal.test.ts": "codex-integration",
"codex-auth-headless-accounts.test.ts": "codex-integration",
"responses-alternate-main-cancellation.test.ts": "responses",
"codex-shim-path-readiness.test.ts": "codex-integration",
"codex-shim-fnm.test.ts": "codex-integration",
Expand Down
Loading