Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "codex-team",
"version": "0.0.5",
"version": "0.0.6",
"description": "Manage multiple Codex ChatGPT auth snapshots and quota usage from the command line.",
"license": "MIT",
"type": "module",
Expand Down
16 changes: 9 additions & 7 deletions src/account-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
QuotaWindowSnapshot,
SnapshotMeta,
createSnapshotMeta,
getSnapshotIdentity,
parseAuthSnapshot,
parseSnapshotMeta,
readAuthSnapshotFile,
Expand Down Expand Up @@ -268,7 +269,7 @@ export class AccountStore {

try {
const currentSnapshot = await readAuthSnapshotFile(this.paths.currentAuthPath);
if (currentSnapshot.tokens.account_id !== snapshot.tokens.account_id) {
if (getSnapshotIdentity(currentSnapshot) !== getSnapshotIdentity(snapshot)) {
return;
}

Expand Down Expand Up @@ -348,7 +349,7 @@ export class AccountStore {
throw new Error(`Account metadata name mismatch for "${name}".`);
}

if (meta.account_id !== snapshot.tokens.account_id) {
if (meta.account_id !== getSnapshotIdentity(snapshot)) {
throw new Error(`Account metadata account_id mismatch for "${name}".`);
}

Expand Down Expand Up @@ -413,14 +414,15 @@ export class AccountStore {
}

const snapshot = await readAuthSnapshotFile(this.paths.currentAuthPath);
const currentIdentity = getSnapshotIdentity(snapshot);
const matchedAccounts = accounts
.filter((account) => account.account_id === snapshot.tokens.account_id)
.filter((account) => account.account_id === currentIdentity)
.map((account) => account.name);

return {
exists: true,
auth_mode: snapshot.auth_mode,
account_id: snapshot.tokens.account_id,
account_id: currentIdentity,
matched_accounts: matchedAccounts,
managed: matchedAccounts.length > 0,
duplicate_match: matchedAccounts.length > 1,
Expand Down Expand Up @@ -538,7 +540,7 @@ export class AccountStore {
await atomicWriteFile(this.paths.currentAuthPath, `${rawAuth.trimEnd()}\n`);
const writtenSnapshot = await readAuthSnapshotFile(this.paths.currentAuthPath);

if (writtenSnapshot.tokens.account_id !== account.account_id) {
if (getSnapshotIdentity(writtenSnapshot) !== account.account_id) {
throw new Error(`Switch verification failed for account "${name}".`);
}

Expand Down Expand Up @@ -604,7 +606,7 @@ export class AccountStore {
}

meta.auth_mode = result.authSnapshot.auth_mode;
meta.account_id = result.authSnapshot.tokens.account_id;
meta.account_id = getSnapshotIdentity(result.authSnapshot);
meta.updated_at = now.toISOString();
meta.quota = result.quota;
await this.writeAccountMeta(name, meta);
Expand Down Expand Up @@ -780,7 +782,7 @@ export class AccountStore {
}
if (account.duplicateAccountId) {
warnings.push(
`Account "${account.name}" shares account_id ${account.account_id} with another saved account.`,
`Account "${account.name}" shares identity ${account.account_id} with another saved account.`,
);
}
}
Expand Down
79 changes: 69 additions & 10 deletions src/auth-snapshot.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";

export interface AuthSnapshotTokens {
account_id: string;
account_id?: string;
[key: string]: unknown;
}

export interface AuthSnapshot {
auth_mode: string;
OPENAI_API_KEY?: string | null;
tokens: AuthSnapshotTokens;
tokens?: AuthSnapshotTokens;
last_refresh?: string;
[key: string]: unknown;
}
Expand Down Expand Up @@ -87,6 +88,41 @@ function asOptionalNumber(value: unknown, fieldName: string): number | undefined
return value;
}

function normalizeAuthMode(authMode: string): string {
return authMode.trim().toLowerCase();
}

export function isApiKeyAuthMode(authMode: string): boolean {
return normalizeAuthMode(authMode) === "apikey";
}

export function isSupportedChatGPTAuthMode(authMode: string): boolean {
const normalized = normalizeAuthMode(authMode);
return normalized === "chatgpt" || normalized === "chatgpt_auth_tokens";
}

function fingerprintApiKey(apiKey: string): string {
return createHash("sha256").update(apiKey).digest("hex").slice(0, 16);
}

export function getSnapshotIdentity(snapshot: AuthSnapshot): string {
if (isApiKeyAuthMode(snapshot.auth_mode)) {
const apiKey = snapshot.OPENAI_API_KEY;
if (typeof apiKey !== "string" || apiKey.trim() === "") {
throw new Error('Field "OPENAI_API_KEY" must be a non-empty string for apikey auth.');
}

return `key_${fingerprintApiKey(apiKey)}`;
}

const accountId = snapshot.tokens?.account_id;
if (typeof accountId !== "string" || accountId.trim() === "") {
throw new Error('Field "tokens.account_id" must be a non-empty string.');
}

return accountId;
}

export function defaultQuotaSnapshot(): QuotaSnapshot {
return {
status: "stale",
Expand Down Expand Up @@ -168,20 +204,43 @@ export function parseAuthSnapshot(raw: string): AuthSnapshot {
}

const authMode = asNonEmptyString(parsed.auth_mode, "auth_mode");
const tokens = parsed.tokens;

if (!isRecord(parsed.tokens)) {
if (tokens !== undefined && tokens !== null && !isRecord(tokens)) {
throw new Error('Field "tokens" must be an object.');
}

const accountId = asNonEmptyString(parsed.tokens.account_id, "tokens.account_id");
const apiKeyMode = isApiKeyAuthMode(authMode);
const normalizedApiKey =
parsed.OPENAI_API_KEY === null || parsed.OPENAI_API_KEY === undefined
? parsed.OPENAI_API_KEY
: asNonEmptyString(parsed.OPENAI_API_KEY, "OPENAI_API_KEY");

if (apiKeyMode) {
if (typeof normalizedApiKey !== "string" || normalizedApiKey.trim() === "") {
throw new Error('Field "OPENAI_API_KEY" must be a non-empty string for apikey auth.');
}
} else {
if (!isRecord(tokens)) {
throw new Error('Field "tokens" must be an object.');
}

asNonEmptyString(tokens.account_id, "tokens.account_id");
}

return {
...parsed,
auth_mode: authMode,
tokens: {
...parsed.tokens,
account_id: accountId,
},
OPENAI_API_KEY: normalizedApiKey,
...(isRecord(tokens)
? {
tokens: {
...tokens,
...(typeof tokens.account_id === "string" && tokens.account_id.trim() !== ""
? { account_id: tokens.account_id }
: {}),
},
}
: {}),
};
}

Expand All @@ -201,7 +260,7 @@ export function createSnapshotMeta(
return {
name,
auth_mode: snapshot.auth_mode,
account_id: snapshot.tokens.account_id,
account_id: getSnapshotIdentity(snapshot),
created_at: existingCreatedAt ?? timestamp,
updated_at: timestamp,
last_switched_at: null,
Expand Down
4 changes: 2 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ function describeCurrentStatus(status: Awaited<ReturnType<AccountStore["getCurre
} else {
lines.push("Current auth: present");
lines.push(`Auth mode: ${status.auth_mode}`);
lines.push(`Account ID: ${maskAccountId(status.account_id ?? "")}`);
lines.push(`Identity: ${maskAccountId(status.account_id ?? "")}`);
if (status.matched_accounts.length === 0) {
lines.push("Managed account: no (unmanaged)");
} else if (status.matched_accounts.length === 1) {
Expand Down Expand Up @@ -369,7 +369,7 @@ function describeQuotaAccounts(
})),
[
{ key: "name", label: "NAME" },
{ key: "account_id", label: "ACCOUNT ID" },
{ key: "account_id", label: "IDENTITY" },
{ key: "plan_type", label: "PLAN TYPE" },
{ key: "available", label: "AVAILABLE" },
{ key: "five_hour", label: "5H USED" },
Expand Down
23 changes: 11 additions & 12 deletions src/quota-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
type QuotaSnapshot,
type QuotaWindowSnapshot,
decodeJwtPayload,
isSupportedChatGPTAuthMode,
} from "./auth-snapshot.js";

const DEFAULT_CHATGPT_BASE_URL = "https://chatgpt.com";
Expand Down Expand Up @@ -84,14 +85,11 @@ function extractStringClaim(
return typeof value === "string" && value.trim() !== "" ? value : undefined;
}

function isSupportedChatGPTMode(authMode: string): boolean {
const normalized = authMode.trim().toLowerCase();
return normalized === "chatgpt" || normalized === "chatgpt_auth_tokens";
}

function parsePlanType(snapshot: AuthSnapshot): string | undefined {
const tokens = snapshot.tokens ?? {};

for (const tokenName of ["id_token", "access_token"]) {
const token = snapshot.tokens[tokenName];
const token = tokens[tokenName];
if (typeof token !== "string" || token.trim() === "") {
continue;
}
Expand All @@ -113,10 +111,11 @@ function parsePlanType(snapshot: AuthSnapshot): string | undefined {

export function extractChatGPTAuth(snapshot: AuthSnapshot): ExtractedChatGPTAuth {
const authMode = snapshot.auth_mode ?? "";
const supported = isSupportedChatGPTMode(authMode);
const accessTokenValue = snapshot.tokens.access_token;
const refreshTokenValue = snapshot.tokens.refresh_token;
const directAccountId = snapshot.tokens.account_id;
const supported = isSupportedChatGPTAuthMode(authMode);
const tokens = snapshot.tokens ?? {};
const accessTokenValue = tokens.access_token;
const refreshTokenValue = tokens.refresh_token;
const directAccountId = tokens.account_id;

let accountId =
typeof directAccountId === "string" && directAccountId.trim() !== ""
Expand All @@ -127,7 +126,7 @@ export function extractChatGPTAuth(snapshot: AuthSnapshot): ExtractedChatGPTAuth
let clientId: string | undefined;

for (const tokenName of ["id_token", "access_token"]) {
const token = snapshot.tokens[tokenName];
const token = tokens[tokenName];
if (typeof token !== "string" || token.trim() === "") {
continue;
}
Expand Down Expand Up @@ -441,7 +440,7 @@ async function refreshChatGPTAuthTokens(
...snapshot,
last_refresh: (options.now ?? new Date()).toISOString(),
tokens: {
...snapshot.tokens,
...(snapshot.tokens ?? {}),
access_token: payload.access_token,
id_token: payload.id_token,
refresh_token: payload.refresh_token ?? extracted.refreshToken,
Expand Down
31 changes: 30 additions & 1 deletion tests/account-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
jsonResponse,
readCurrentAuth,
textResponse,
writeCurrentApiKeyAuth,
writeCurrentAuth,
} from "./test-helpers.js";

Expand Down Expand Up @@ -62,7 +63,7 @@ describe("AccountStore", () => {
expect(switchResult.backup_path).toBe(join(homeDir, ".codex-team", "backups", "last-active-auth.json"));

const current = await readCurrentAuth(homeDir);
expect(current.tokens.account_id).toBe("acct-alpha");
expect(current.tokens?.account_id).toBe("acct-alpha");

const backupRaw = await readFile(
join(homeDir, ".codex-team", "backups", "last-active-auth.json"),
Expand Down Expand Up @@ -130,6 +131,34 @@ describe("AccountStore", () => {
}
});

test("saves and switches apikey-managed accounts", async () => {
const homeDir = await createTempHome();

try {
const store = createAccountStore(homeDir);
await writeCurrentApiKeyAuth(homeDir, "sk-alpha");
const alpha = await store.saveCurrentAccount("alpha");

await writeCurrentApiKeyAuth(homeDir, "sk-beta");
await store.saveCurrentAccount("beta");

const current = await store.getCurrentStatus();
expect(current.exists).toBe(true);
expect(current.auth_mode).toBe("apikey");
expect(current.account_id).toMatch(/^key_[0-9a-f]{16}$/);
expect(current.matched_accounts).toEqual(["beta"]);

const switchResult = await store.switchAccount("alpha");
expect(switchResult.account.account_id).toBe(alpha.account_id);

const switched = await readCurrentAuth(homeDir);
expect(switched.auth_mode).toBe("apikey");
expect(switched.OPENAI_API_KEY).toBe("sk-alpha");
} finally {
await cleanupTempHome(homeDir);
}
});

test("refreshes quotas and keeps cached balance when a later refresh fails", async () => {
const homeDir = await createTempHome();
let attempts = 0;
Expand Down
17 changes: 15 additions & 2 deletions tests/auth-snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,19 @@ import { describe, expect, test } from "@rstest/core";

import {
createSnapshotMeta,
getSnapshotIdentity,
parseAuthSnapshot,
parseSnapshotMeta,
} from "../src/auth-snapshot.js";
import { createAuthPayload } from "./test-helpers.js";
import { createApiKeyPayload, createAuthPayload } from "./test-helpers.js";

describe("auth snapshot parsing", () => {
test("parses a valid auth snapshot", () => {
const payload = createAuthPayload("acct-primary");
const snapshot = parseAuthSnapshot(JSON.stringify(payload));

expect(snapshot.auth_mode).toBe("chatgpt");
expect(snapshot.tokens.account_id).toBe("acct-primary");
expect(snapshot.tokens?.account_id).toBe("acct-primary");
});

test("rejects a snapshot without auth_mode", () => {
Expand All @@ -23,6 +24,18 @@ describe("auth snapshot parsing", () => {
expect(() => parseAuthSnapshot(JSON.stringify(payload))).toThrow(/auth_mode/);
});

test("parses an apikey auth snapshot and derives a stable identity", () => {
const payload = createApiKeyPayload("sk-test-primary");
const snapshot = parseAuthSnapshot(JSON.stringify(payload));
const reparsed = parseAuthSnapshot(JSON.stringify(payload));

expect(snapshot.auth_mode).toBe("apikey");
expect(snapshot.OPENAI_API_KEY).toBe("sk-test-primary");
expect(snapshot.tokens).toBeUndefined();
expect(getSnapshotIdentity(snapshot)).toMatch(/^key_[0-9a-f]{16}$/);
expect(getSnapshotIdentity(snapshot)).toBe(getSnapshotIdentity(reparsed));
});

test("creates metadata with a preserved created_at on overwrite", () => {
const payload = createAuthPayload("acct-primary");
const created = createSnapshotMeta("main", payload, new Date("2026-03-18T00:00:00.000Z"));
Expand Down
Loading
Loading