Skip to content

Commit 4ef5350

Browse files
authored
Merge pull request #1373 from luvs01/agent/fix-codex-plan-normalization
fix(codex): tolerate malformed account plan values
2 parents a522384 + 095a9a5 commit 4ef5350

13 files changed

Lines changed: 160 additions & 32 deletions

‎src/codex/auth-api.ts‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ import {
5858
parseAccountPriority,
5959
} from "./pool-rotation";
6060
import { checkAccountIdCollision, getMainChatgptAccountId, readCodexTokens, readCodexTokensResult } from "./auth-collision";
61+
import { codexPlanValue, isThirtyDayOnlyCodexPlan } from "./plan";
6162
export { checkAccountIdCollision, getMainChatgptAccountId } from "./auth-collision";
6263
export { clearAccountNeedsReauth, isAccountNeedsReauth, markAccountNeedsReauth } from "./account-runtime-state";
6364
import { clearAccountNeedsReauth, isAccountNeedsReauth, markAccountNeedsReauth } from "./account-runtime-state";
@@ -208,16 +209,11 @@ function codexAccountPersistenceConflict(
208209
: undefined;
209210
}
210211

211-
function isThirtyDayOnlyPlan(plan: string | null | undefined): boolean {
212-
const normalized = plan?.trim().toLowerCase();
213-
return normalized === "go" || normalized === "free";
214-
}
215-
216212
function quotaForPlan<T extends Omit<StoredAccountQuota, "updatedAt"> | StoredAccountQuota | null>(
217213
quota: T,
218-
plan: string | null | undefined,
214+
plan: unknown,
219215
): T {
220-
if (!quota || !isThirtyDayOnlyPlan(plan)) return quota;
216+
if (!quota || !isThirtyDayOnlyCodexPlan(plan)) return quota;
221217
return {
222218
...(quota.monthlyPercent !== undefined ? { monthlyPercent: quota.monthlyPercent } : {}),
223219
...(quota.monthlyResetAt !== undefined ? { monthlyResetAt: quota.monthlyResetAt } : {}),
@@ -233,14 +229,15 @@ function poolAccountDto(
233229
paused: boolean,
234230
priority: number,
235231
): CodexAuthAccountDto {
236-
const quota = quotaForPlan(quotaResult.quota, account.plan);
232+
const plan = codexPlanValue(account.plan);
233+
const quota = quotaForPlan(quotaResult.quota, plan);
237234
const needsReauth = !hasCredential || quotaResult.needsReauth || isAccountNeedsReauth(account.id);
238235
const health = projectCodexAccountHealth({ accountId: account.id, needsReauth });
239236
return {
240237
id: account.id,
241238
email: maskEmail(account.email) ?? account.email,
242239
...(account.alias !== undefined ? { alias: account.alias } : {}),
243-
...(account.plan !== undefined ? { plan: account.plan } : {}),
240+
...(plan !== undefined ? { plan } : {}),
244241
...(account.logLabel !== undefined ? { logLabel: account.logLabel } : {}),
245242
isMain: false,
246243
paused,
@@ -398,7 +395,7 @@ const POOL_CACHE_TTL = 5 * 60_000;
398395
const POOL_QUOTA_REFRESH_CONCURRENCY = 4;
399396

400397
function nonEmptyPlan(value: unknown): string | null {
401-
return typeof value === "string" && value.trim() !== "" ? value : null;
398+
return codexPlanValue(value) ?? null;
402399
}
403400

404401
function isRuntimeConfig(config: OcxConfig): boolean {
@@ -1334,7 +1331,7 @@ export async function handleCodexAuthAPI(
13341331
if (url.pathname === "/api/codex-auth/accounts" && req.method === "POST") {
13351332
if (!isUnverifiedCodexImportEnabled()) return manualImportDisabledResponse();
13361333

1337-
let body: { id: string; email: string; plan?: string; accessToken: string; refreshToken: string; chatgptAccountId: string };
1334+
let body: { id: string; email: string; plan?: unknown; accessToken: string; refreshToken: string; chatgptAccountId: string };
13381335
try { body = (await req.json()) as typeof body; } catch { return jsonResponse({ error: "Invalid JSON" }, 400); }
13391336
if (!body.id || !body.email || !body.accessToken || !body.refreshToken || !body.chatgptAccountId) {
13401337
return jsonResponse({ error: "Missing required fields" }, 400);
@@ -1349,8 +1346,9 @@ export async function handleCodexAuthAPI(
13491346
const preflightConflict = codexAccountPersistenceConflict(runtimeConfig, body.id, "create");
13501347
if (preflightConflict) return jsonResponse({ error: preflightConflict }, 400);
13511348
// 1.1: Duplicate check is scoped by personal vs workspace plan bucket.
1349+
const plan = codexPlanValue(body.plan);
13521350
const derivedAccountId = extractAccountId(undefined, body.accessToken) ?? body.chatgptAccountId;
1353-
const collision = checkAccountIdCollision(derivedAccountId, body.email, body.plan);
1351+
const collision = checkAccountIdCollision(derivedAccountId, body.email, plan);
13541352
if (collision.collision) {
13551353
return jsonResponse({ error: collision.reason }, 400);
13561354
}
@@ -1363,7 +1361,12 @@ export async function handleCodexAuthAPI(
13631361
const commitConflict = codexAccountPersistenceConflict(latestConfig, body.id, "create");
13641362
if (commitConflict) return jsonResponse({ error: commitConflict }, 400);
13651363
const addedAccount = withCodexAccountLogLabel(
1366-
{ id: body.id, email: body.email, plan: body.plan, isMain: false },
1364+
{
1365+
id: body.id,
1366+
email: body.email,
1367+
...(plan !== undefined ? { plan } : {}),
1368+
isMain: false,
1369+
},
13671370
latestConfig.codexAccounts ?? [],
13681371
);
13691372
const persistence = persistNewCodexAccount(

‎src/codex/auth-collision.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { loadConfig } from "../config";
55
import { resolveCodexHomeDir } from "./home";
66
import { extractAccountId } from "../oauth/chatgpt";
77
import { isSelectableCodexPoolAccount } from "./account-id";
8+
import { codexPlanKey } from "./plan";
89

910
export interface CodexTokens {
1011
access_token: string;
@@ -78,8 +79,9 @@ function normalizedEmail(email: string | undefined | null): string | null {
7879
return trimmed || null;
7980
}
8081

81-
function isWorkspacePlan(plan: string | undefined | null): boolean {
82-
return !!plan && /team|business|enterprise|workspace|edu/i.test(plan);
82+
function isWorkspacePlan(plan: unknown): boolean {
83+
const key = codexPlanKey(plan);
84+
return !!key && /team|business|enterprise|workspace|edu/.test(key);
8385
}
8486

8587
// Main login and managed pool accounts are separate duplicate buckets.
@@ -88,7 +90,7 @@ function isWorkspacePlan(plan: string | undefined | null): boolean {
8890
export function checkAccountIdCollision(
8991
chatgptAccountId: string,
9092
email?: string | null,
91-
plan?: string | null,
93+
plan?: unknown,
9294
excludeAccountId?: string | null,
9395
): { collision: true; reason: string } | { collision: false } {
9496
const candidateEmail = normalizedEmail(email);

‎src/codex/plan.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/** Preserve user/provider plan labels only when they are usable strings. */
2+
export function codexPlanValue(value: unknown): string | undefined {
3+
if (typeof value !== "string") return undefined;
4+
return value.trim() ? value : undefined;
5+
}
6+
7+
/** Case-insensitive key used by quota, capacity, and collision policy. */
8+
export function codexPlanKey(value: unknown): string | undefined {
9+
return codexPlanValue(value)?.trim().toLowerCase();
10+
}
11+
12+
export function isThirtyDayOnlyCodexPlan(value: unknown): boolean {
13+
const key = codexPlanKey(value);
14+
return key === "go" || key === "free";
15+
}

‎src/codex/quota.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs";
22
import { join } from "node:path";
33
import { atomicWriteFile, getConfigDir } from "../config";
44
import { captureConfigGeneration, type GenerationContext } from "../lib/state-store-sweeper";
5+
import { isThirtyDayOnlyCodexPlan } from "./plan";
56

67
export type StoredAccountQuota = {
78
weeklyPercent?: number;
@@ -36,7 +37,7 @@ let persistTimer: ReturnType<typeof setTimeout> | null = null;
3637

3738
export type WhamUsageResponse = {
3839
email?: string | null;
39-
plan_type?: string | null;
40+
plan_type?: unknown;
4041
rate_limit?: {
4142
// Live WHAM payloads send explicit nulls for absent windows (issue #315 repro).
4243
primary_window?: WhamUsageWindow | null;
@@ -72,7 +73,7 @@ export const CODEX_EXHAUSTED_USAGE_PERCENT = 100;
7273

7374
export function isCodexQuotaExhausted(
7475
quota: Pick<StoredAccountQuota, "weeklyPercent" | "monthlyPercent"> | null,
75-
plan?: string | null,
76+
plan?: unknown,
7677
): boolean {
7778
if (!quota) return false;
7879
const values = codexQuotaWindowForPlan(plan) === "monthly"
@@ -98,14 +99,13 @@ export function isCodexQuotaExhausted(
9899
* everything else (including an absent plan) reports weekly. Recovery reads the
99100
* window the parser actually wrote rather than second-guessing it.
100101
*/
101-
export function codexQuotaWindowForPlan(plan?: string | null): "monthly" | "weekly" {
102-
const normalized = plan?.trim().toLowerCase();
103-
return normalized === "go" || normalized === "free" ? "monthly" : "weekly";
102+
export function codexQuotaWindowForPlan(plan?: unknown): "monthly" | "weekly" {
103+
return isThirtyDayOnlyCodexPlan(plan) ? "monthly" : "weekly";
104104
}
105105

106106
export function isCompleteCodexQuotaRecoverySnapshot(
107107
quota: Pick<StoredAccountQuota, "weeklyPercent" | "monthlyPercent" | "monthlyIsPrimaryWindow"> | null,
108-
plan?: string | null,
108+
plan?: unknown,
109109
): boolean {
110110
if (!quota || isCodexQuotaExhausted(quota, plan)) return false;
111111
// Recovery still fails closed on MISSING EVIDENCE — a credits-only or windowless payload

‎src/codex/routing.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
selectPriorityTier,
1919
} from "./pool-rotation";
2020
import { CODEX_UNKNOWN_USAGE_SCORE, getAccountQuota } from "./quota";
21+
import { isThirtyDayOnlyCodexPlan } from "./plan";
2122
import { MAIN_CODEX_ACCOUNT_ID, getMainAccountPlan } from "./main-account";
2223
import { isSelectableCodexPoolAccount } from "./account-id";
2324
import type { OcxConfig } from "../types";
@@ -314,10 +315,9 @@ function deleteScopedHealth(accountId: string, scope: CodexQuotaScope): void {
314315
export function computeCodexUsageScore(quota: {
315316
weeklyPercent?: number;
316317
monthlyPercent?: number;
317-
} | null, plan?: string | null): number {
318+
} | null, plan?: unknown): number {
318319
if (!quota) return CODEX_UNKNOWN_USAGE_SCORE;
319-
const normalizedPlan = plan?.trim().toLowerCase();
320-
if (normalizedPlan === "go" || normalizedPlan === "free") {
320+
if (isThirtyDayOnlyCodexPlan(plan)) {
321321
return typeof quota.monthlyPercent === "number" && Number.isFinite(quota.monthlyPercent)
322322
? quota.monthlyPercent
323323
: CODEX_UNKNOWN_USAGE_SCORE;

‎src/providers/codex-capacity.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { codexPlanKey, codexPlanValue } from "../codex/plan";
2+
13
export const CODEX_CONFIGURED_CAPACITY_WEIGHTS = {
24
plus: 1,
35
business: 1,
@@ -22,7 +24,7 @@ export type CodexCapacityQuota = {
2224
export interface CodexCapacityAccount {
2325
isMain: boolean;
2426
active?: boolean;
25-
plan?: string | null;
27+
plan?: unknown;
2628
paused: boolean;
2729
needsReauth?: boolean;
2830
quota: CodexCapacityQuota | null;
@@ -82,8 +84,8 @@ type MutableWindow = {
8284
oldestUpdatedAt: number;
8385
};
8486

85-
function configuredWeight(plan: string | null | undefined): number | undefined {
86-
const normalized = plan?.trim().toLowerCase();
87+
function configuredWeight(plan: unknown): number | undefined {
88+
const normalized = codexPlanKey(plan);
8789
return normalized && Object.hasOwn(CODEX_CONFIGURED_CAPACITY_WEIGHTS, normalized)
8890
? CODEX_CONFIGURED_CAPACITY_WEIGHTS[normalized as keyof typeof CODEX_CONFIGURED_CAPACITY_WEIGHTS]
8991
: undefined;
@@ -168,9 +170,10 @@ export function aggregateCodexPoolCapacity(
168170
const current = accounts.find(account => account.active)
169171
?? accounts.find(account => account.isMain)
170172
?? accounts[0];
173+
const currentPlan = codexPlanValue(current?.plan);
171174
const currentAccount = current ? {
172175
isMain: current.isMain,
173-
...(current.plan !== undefined ? { plan: current.plan } : {}),
176+
...(currentPlan !== undefined ? { plan: currentPlan } : {}),
174177
quota: currentQuotaForDisplay(current, now),
175178
} : undefined;
176179
const windows = new Map<string, MutableWindow>();

‎src/providers/quota.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
} from "../codex/auth-api";
77
import { isMainAccountIdentityGenerationLive } from "../codex/main-account-cache";
88
import { MAIN_CODEX_ACCOUNT_ID } from "../codex/main-account";
9+
import { codexPlanKey } from "../codex/plan";
910
import { resolveEnvValue } from "../config";
1011
import { getValidAccessToken, getValidAccessTokenForAccount } from "../oauth";
1112
import { getAccountCredential, getAccountSet, getCredential } from "../oauth/store";
@@ -168,7 +169,7 @@ function cacheKeyWithAggregationState(
168169
const rows = snapshot.accounts.map(account => ({
169170
isMain: account.isMain,
170171
active: account.id === activeId,
171-
plan: account.plan?.trim().toLowerCase() ?? null,
172+
plan: codexPlanKey(account.plan) ?? null,
172173
paused: account.paused,
173174
needsReauth: account.needsReauth === true,
174175
quota: quotaSignatureValue(account.quota as CodexCapacityQuota | null),

‎tests/codex-auth-api.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -858,6 +858,32 @@ describe("codex-auth API", () => {
858858
expect(data.accounts.find(a => a.id === "pool-mask")?.email).toBe("p***[email protected]");
859859
});
860860

861+
test("GET /api/codex-auth/accounts omits a malformed persisted plan", async () => {
862+
const config = makeConfig({
863+
codexAccounts: [
864+
{ id: "pool-invalid-plan", email: "[email protected]", plan: { tier: "go" }, isMain: false },
865+
] as unknown as OcxConfig["codexAccounts"],
866+
});
867+
saveCodexAccountCredential("pool-invalid-plan", {
868+
accessToken: "access-invalid-plan",
869+
refreshToken: "refresh-invalid-plan",
870+
expiresAt: Date.now() + 5 * 60_000,
871+
chatgptAccountId: "acct-invalid-plan",
872+
});
873+
updateAccountQuota("pool-invalid-plan", 91, 111, 33, 333);
874+
875+
const req = new Request("http://localhost/api/codex-auth/accounts", { method: "GET" });
876+
const resp = await handleCodexAuthAPI(req, new URL(req.url), config);
877+
const data = await resp!.json() as {
878+
accounts: Array<{ id: string; plan?: unknown; quota?: Record<string, unknown> }>;
879+
};
880+
const account = data.accounts.find(row => row.id === "pool-invalid-plan");
881+
882+
expect(resp?.status).toBe(200);
883+
expect(account).not.toHaveProperty("plan");
884+
expect(account?.quota).toMatchObject({ weeklyPercent: 91, monthlyPercent: 33 });
885+
});
886+
861887
test("GET /api/codex-auth/accounts exposes only 30d quota for go and free plans", async () => {
862888
const config = makeConfig({
863889
codexAccounts: [
@@ -2259,12 +2285,13 @@ describe("codex-auth API", () => {
22592285
const req = new Request("http://localhost/api/codex-auth/accounts", {
22602286
method: "POST",
22612287
headers: { "Content-Type": "application/json" },
2262-
body: JSON.stringify(manualImportBody({ id: "manual-enabled" })),
2288+
body: JSON.stringify(manualImportBody({ id: "manual-enabled", plan: { tier: "go" } })),
22632289
});
22642290
const resp = await handleCodexAuthAPI(req, new URL(req.url), config);
22652291

22662292
expect(resp!.status).toBe(200);
22672293
expect(config.codexAccounts?.map(a => a.id)).toEqual(["manual-enabled"]);
2294+
expect(config.codexAccounts?.[0]).not.toHaveProperty("plan");
22682295
expect(config.codexAccounts?.[0]?.logLabel).toMatch(CODEX_ACCOUNT_LOG_LABEL_RE);
22692296
expect(getCodexAccountCredential("manual-enabled")).toMatchObject({
22702297
accessToken: "access-manual-test",

‎tests/codex-auth-collision.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,21 @@ function seedAccount(id: string, email: string, chatgptAccountId: string, plan?:
4646
}
4747

4848
describe("codex auth account collision", () => {
49+
test("treats a non-string plan as an unknown personal plan", () => {
50+
saveConfig({
51+
port: 10100,
52+
providers: {},
53+
defaultProvider: "openai",
54+
codexAccounts: [],
55+
} as OcxConfig);
56+
57+
expect(checkAccountIdCollision(
58+
"malformed-plan-account",
59+
60+
{ toString: 1 },
61+
)).toEqual({ collision: false });
62+
});
63+
4964
test("allows different team members that share a ChatGPT account id", async () => {
5065
seedAccount("team-member-a", "[email protected]", "shared-team-account");
5166

‎tests/codex-cooldown-recovery.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,9 @@ describe("Codex cooldown recovery worker", () => {
364364
}
365365
expect(codexQuotaWindowForPlan(undefined)).toBe("weekly");
366366
expect(codexQuotaWindowForPlan("")).toBe("weekly");
367+
for (const malformed of [{ tier: "go" }, 1, true]) {
368+
expect(codexQuotaWindowForPlan(malformed)).toBe("weekly");
369+
}
367370
// "free_workspace" is not "free": only the exact names take the monthly window.
368371
expect(codexQuotaWindowForPlan("free_workspace")).toBe("weekly");
369372

0 commit comments

Comments
 (0)