// Shared, id-addressed, REFRESHING Codex token resolver (P2). // // Hoisted here from apps/worker/src/activities/codex-auth.ts so BOTH the worker // (turn-time bearer for the streamed run) AND the api (the /wham/usage quota-bar // reads) drive ONE resolver — no duplicated refresh/CAS/single-flight logic. The // worker re-exports buildCodexTokenResolver from @opengeni/db for back-compat, so // the agent-turn.ts call site is unchanged. // // Why @opengeni/db is the right home: the resolver only orchestrates accessors // this package already owns (loadCodexCredentialForRun / recordCodexTokenRefresh / // setCodexCredentialStatus / encryptEnvironmentValue) plus pure @opengeni/codex // refresh helpers and the @opengeni/config key — keeping the refresh-CAS + RLS // invariants co-located with the rows they protect. // // CROSS-PROCESS SAFETY: the process-module `inflight` map coalesces local callers, // while a Postgres advisory transaction lock serializes API/worker replicas. A // waiter re-reads after taking that lock and skips refresh when the version moved. // The existing (id,version) CAS remains the final stale-family write fence. import { environmentsEncryptionKeyBytes, type Settings } from "@opengeni/config"; import { accessTokenExpiry, CODEX_CLIENT_VERSION, CODEX_REFRESH_FALLBACK_MS, CODEX_REFRESH_WINDOW_MS, CodexReloginRequired, codexUsageConfirmsQuotaAvailable, type CodexTokenSnapshot, type CodexUsagePayload, type CodexFetch, type CodexRateLimitResetCreditsDetails, type ResetCreditFetchFailureReason, fetchCodexRateLimitResetCredits, fetchCodexUsage, normalizeCodexUsage, parseIdToken, refreshCodexToken, } from "@opengeni/codex"; import { encryptEnvironmentValue } from "./environment-crypto"; import type { CodexPlanEntitlementExclusion } from "./codex-plan-entitlement"; import type { Database } from "./database"; export type CodexCredentialTokens = { accessToken: string; refreshToken: string; idToken: string; }; export type CodexCredentialCooldownKind = "quota" | "rate_limit"; export type CodexCredentialForRun = { id: string; version: number; workspaceId: string; tokens: CodexCredentialTokens; chatgptAccountId: string | null; scopes: string | null; planType: string | null; /** Plan before the most recent recorded plan change (see migration 0524). */ planPreviousType?: string | null; planChangedAt?: Date | null; /** Models the recorded plan was proven not to include, expired or not. */ planEntitlementExclusion?: CodexPlanEntitlementExclusion | null; isFedramp: boolean; expiresAt: Date | null; lastRefreshAt: Date | null; status: string; lastError: string | null; exhaustedUntil: Date | null; exhaustedKind: CodexCredentialCooldownKind | null; exhaustedRevision: number; }; export type CodexAccountUsageSnapshot = { primaryUsedPercent?: number | null; primaryResetAt?: Date | null; secondaryUsedPercent?: number | null; secondaryResetAt?: Date | null; checkedAt?: Date; resetCreditAvailableCount?: number | null; resetCreditsCheckedAt?: Date | null; /** * Provider-reported current ChatGPT plan (`plan_type`). Persisted with * `planCheckedAt`; a changed plan retires any plan entitlement exclusion. */ planType?: string | null; planCheckedAt?: Date; /** * Clear only a quota cooldown with this exact revision. Set solely after a * live provider response proves allowance is open; a concurrent refusal * advances the revision and makes this observation stale. */ clearQuotaCooldownRevision?: number; }; type CodexCredentialRefreshInput = { id: string; version: number; workspaceId: string; credentialEncrypted: string; expiresAt: Date | null; lastRefreshAt: Date; /** `chatgpt_plan_type` from a rotated id_token; omitted when none was returned. */ planType?: string | null; }; type CodexCredentialStatusTarget = { id: string; version: number; }; // Single-flight per CREDENTIAL INSTANCE (row id + version), process-module scope. // Keying by the loaded credential's id+version — NOT by workspaceId alone (P1-b) — // is what makes a disconnect→reconnect safe: a post-reconnect getToken loads a // DIFFERENT row (new uuid id) and so gets a distinct key, instead of coalescing // onto the OLD in-flight refresh and writing stale rotated tokens over the freshly // connected credential. Concurrent calls for the SAME credential still coalesce, // so the one-time refresh token is never double-spent. export type CodexCredentialTokenSnapshot = CodexTokenSnapshot & { /** Exact credential-row version whose bearer is about to reach the provider. */ credentialVersion: number; /** Plan recorded for that version (from the id_token of the latest refresh). */ planType?: string | null; }; const inflight = new Map>(); const CODEX_TOKEN_REFRESH_TIMEOUT_MS = 6_000; export type CodexTokenDeadlineClock = { setTimeout: (callback: () => void, delayMs: number) => ReturnType; clearTimeout: (handle: ReturnType) => void; }; export type CodexTokenDeadlineOptions = { timeoutMs?: number | undefined; signal?: AbortSignal | undefined; clock?: CodexTokenDeadlineClock | undefined; }; const systemCodexTokenDeadlineClock: CodexTokenDeadlineClock = { setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs), clearTimeout: (handle) => globalThis.clearTimeout(handle), }; /** * Bound a refresh promise without abandoning its rejection handler when the * deadline or cancellation wins. The provider promise is observed exactly * once, while the observer itself always fulfills, so a late provider failure * cannot become an unhandled rejection or replace the authoritative outcome. */ export async function withCodexTokenDeadline( operation: Promise, options: CodexTokenDeadlineOptions = {}, ): Promise { const timeoutMs = options.timeoutMs ?? CODEX_TOKEN_REFRESH_TIMEOUT_MS; if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { throw new Error("Codex token refresh timeout must be positive"); } const clock = options.clock ?? systemCodexTokenDeadlineClock; const signal = options.signal; return await new Promise((resolve, reject) => { let settled = false; let timeout: ReturnType | undefined; const cleanup = (): void => { if (timeout !== undefined) { clock.clearTimeout(timeout); timeout = undefined; } signal?.removeEventListener("abort", onAbort); }; const settle = ( outcome: { kind: "resolve"; value: T } | { kind: "reject"; error: unknown }, ) => { if (settled) return; settled = true; cleanup(); if (outcome.kind === "resolve") { resolve(outcome.value); } else { reject(outcome.error); } }; const onAbort = (): void => { settle({ kind: "reject", error: signal?.reason ?? new Error("Codex token refresh cancelled"), }); }; if (signal?.aborted) { onAbort(); } else { signal?.addEventListener("abort", onAbort, { once: true }); timeout = clock.setTimeout( () => settle({ kind: "reject", error: new Error("Codex token refresh timed out") }), timeoutMs, ); } // Do not use Promise.race here. Its derived promise can obscure which // branch owns settlement, while this fulfillment-only observer makes the // losing provider branch explicitly consumed after timeout/cancellation. void Promise.resolve(operation).then( (value) => settle({ kind: "resolve", value }), (error) => settle({ kind: "reject", error }), ); }); } // Dependencies are injectable so the lifecycle logic (single-flight, staleness, // needs_relogin transition) is unit-testable without a database. Production uses // the root composition wrapper supplies the real db + codex functions. export type CodexAuthDeps = { loadCredential: ( db: Database, settings: Settings, workspaceId: string, credentialId: string, ) => Promise; recordRefresh: (db: Database, input: CodexCredentialRefreshInput) => Promise; setStatus: ( db: Database, workspaceId: string, status: "active" | "needs_relogin" | "error", lastError: string | null, target: CodexCredentialStatusTarget, ) => Promise; refresh: typeof refreshCodexToken; encrypt: typeof encryptEnvironmentValue; keyBytes: typeof environmentsEncryptionKeyBytes; withRefreshLock: ( db: Database, workspaceId: string, credentialId: string, fn: (lockedDb: Database) => Promise, ) => Promise; recordUsage?: ( db: Database, workspaceId: string, credentialId: string, snapshot: CodexAccountUsageSnapshot, ) => Promise; /** * A token refresh observed a different plan on a credential that carried a * plan exclusion, which that write retired. Called after the refresh lock is * released so capacity waiters blocked by the exclusion can re-evaluate. */ onPlanExclusionRetired?: ( db: Database, workspaceId: string, credentialId: string, ) => Promise; /** * Separates local refresh single-flight between resolvers that load the same * row under different authorities (for example Codex Apps versus inference), * so one caller never adopts another authority's outcome. The database refresh * lock still serializes them; the second re-reads the version and skips the * provider refresh. */ refreshKeyScope?: string; }; export function buildCodexTokenResolver( db: Database, settings: Settings, workspaceId: string, // The RESOLVED effective credential id (pin > workspace active), threaded from // the worker. A mid-turn switch loads a DIFFERENT row id, gets a distinct // single-flight key, and the (id, version) CAS in recordCodexTokenRefresh writes // 0 rows against the now-inactive row — so a refresh racing a switch can never // clobber the newly-active account. The single-flight map needs zero change. credentialId: string, deps: CodexAuthDeps, ): { getToken: () => Promise; refresh: () => Promise; } { const snapshot = (cred: CodexCredentialForRun): CodexCredentialTokenSnapshot => ({ accessToken: cred.tokens.accessToken, chatgptAccountId: cred.chatgptAccountId, isFedramp: cred.isFedramp, credentialVersion: cred.version, planType: cred.planType, }); // Credentials whose refresh just retired a plan exclusion; drained after the // refresh lock is released (see onPlanExclusionRetired). const planExclusionRetired = new Set(); const performRefresh = async ( refreshDb: Database, cred: CodexCredentialForRun, ): Promise => { try { // Bound even injected/custom refresh implementations that ignore abort // signals. The provider client has its own AbortController timeout; this // outer fence ensures the DB advisory transaction cannot be held forever. const next = await withCodexTokenDeadline(deps.refresh(cred.tokens.refreshToken)); const tokens = { access_token: next.accessToken ?? cred.tokens.accessToken, refresh_token: next.refreshToken ?? cred.tokens.refreshToken, id_token: next.idToken ?? cred.tokens.idToken, }; const key = deps.keyBytes(settings); if (!key) { throw new Error("OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY is not configured"); } // A rotated id_token carries the account's CURRENT ChatGPT plan. Persist // it with the tokens so a plan change is visible without a reconnect. const refreshedPlanType = next.idToken ? parseIdToken(next.idToken).planType : null; // Compare-and-set on the loaded (id, version): if a disconnect→reconnect // replaced the row mid-refresh, this writes 0 rows and we must NOT clobber // the new credential with our now-defunct rotated tokens. const persisted = await deps.recordRefresh(refreshDb, { id: cred.id, version: cred.version, workspaceId, credentialEncrypted: deps.encrypt(key, JSON.stringify(tokens)), expiresAt: accessTokenExpiry(tokens.access_token), lastRefreshAt: new Date(), ...(refreshedPlanType ? { planType: refreshedPlanType } : {}), }); if (!persisted) { // The row changed under us. Our rotated tokens belong to a stale family; // fall back to whatever is connected NOW (a reconnect leaves an active // row). If nothing active remains, a relogin is genuinely required. const current = await deps.loadCredential(refreshDb, settings, workspaceId, credentialId); if (current && current.status === "active") { return snapshot(current); } throw new CodexReloginRequired( "Codex credential changed during token refresh; reconnect required.", ); } if ( refreshedPlanType && cred.planEntitlementExclusion && (cred.planType ?? "").toLowerCase() !== refreshedPlanType.toLowerCase() ) { planExclusionRetired.add(cred.id); } return { accessToken: tokens.access_token, chatgptAccountId: cred.chatgptAccountId, isFedramp: cred.isFedramp, credentialVersion: cred.version + 1, planType: refreshedPlanType ?? cred.planType, }; } catch (error) { if (error instanceof CodexReloginRequired) { // Stamp needs_relogin ONLY if the row we refreshed is STILL current // (compare-and-set on the loaded id+version). A relogin triggered by the // OLD token family must never stamp needs_relogin onto a freshly // reconnected credential. await deps.setStatus(refreshDb, workspaceId, "needs_relogin", error.message, { id: cred.id, version: cred.version, }); } throw error; } }; // ALL refreshes — whether proactive or a 401 retry — coalesce locally and then // serialize globally before any rotating refresh token reaches the provider. const doRefresh = (cred: CodexCredentialForRun): Promise => { const key = `${deps.refreshKeyScope ?? "default"}:${cred.id}:${cred.version}`; const existing = inflight.get(key); if (existing) { return existing; } const promise = deps .withRefreshLock(db, workspaceId, credentialId, async (lockedDb) => { try { const current = await deps.loadCredential(lockedDb, settings, workspaceId, credentialId); if (!current || current.status !== "active") { throw new CodexReloginRequired( "Codex credential became unavailable while waiting to refresh.", ); } if (current.version !== cred.version) { return { ok: true as const, value: snapshot(current) }; } return { ok: true as const, value: await performRefresh(lockedDb, current) }; } catch (error) { // withCodexCredentialRefreshLock uses an advisory TRANSACTION lock. // performRefresh may persist `needs_relogin` before surfacing a // permanent OAuth failure; throwing from this callback would roll that // status write back with the outer transaction. Return the failure so // the transaction commits, then rethrow after the lock is released. return { ok: false as const, error }; } }) .then(async (outcome) => { if (planExclusionRetired.delete(cred.id)) { await deps.onPlanExclusionRetired?.(db, workspaceId, cred.id).catch(() => undefined); } if (!outcome.ok) throw outcome.error; return outcome.value; }) .finally(() => { if (inflight.get(key) === promise) { inflight.delete(key); } }); inflight.set(key, promise); return promise; }; const resolve = async (force: boolean): Promise => { const cred = await deps.loadCredential(db, settings, workspaceId, credentialId); if (!cred) { throw new CodexReloginRequired("No Codex subscription is connected for this workspace."); } const exp = cred.expiresAt ?? accessTokenExpiry(cred.tokens.accessToken); const stale = force || (exp ? exp.getTime() <= Date.now() + CODEX_REFRESH_WINDOW_MS : cred.lastRefreshAt ? cred.lastRefreshAt.getTime() < Date.now() - CODEX_REFRESH_FALLBACK_MS : true); return stale ? doRefresh(cred) : snapshot(cred); }; return { getToken: () => resolve(false), refresh: () => resolve(true) }; } function errorUsagePayload(reason?: "needs_relogin"): CodexUsagePayload { return { status: "error", planType: null, fiveHour: null, weekly: null, limitReached: false, fetchedAt: new Date().toISOString(), rateLimitResetCredits: null, ...(reason ? { reason } : {}), }; } /** * THE single per-account usage path both the api route and an (optional) worker * poll call, so the refresh discipline and the cache-write can never drift. * * 1. resolve a REFRESHING bearer for THIS account (proactive staleness refresh, * single-flight, (id,version) CAS-persist) — this is what stops an idle * account's expired JWT from 401-ing the usage read. * 2. fetch GET /wham/usage with that bearer. * 3. normalize (§3) into the P2/P3 contract. * 4. on any windows present, write the usage cache and conditionally reconcile * the exact older typed quota cooldown observed before provider I/O. * * A refresh that stamps needs_relogin returns { status:"error", reason } and never * hits the provider; a transient refresh error returns a plain error payload. */ export async function fetchCodexUsageForAccount( db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps, fetchImpl: CodexFetch = fetch, ): Promise { const resolver = buildCodexTokenResolver(db, settings, workspaceId, credentialId, deps); let token: CodexTokenSnapshot; try { token = await resolver.getToken(); } catch (error) { return errorUsagePayload(error instanceof CodexReloginRequired ? "needs_relogin" : undefined); } // Snapshot cooldown authority immediately before provider I/O. The usage // write may clear only this exact revision; any concurrent refusal advances // it and wins. A metadata-read failure must not sink the usage response. const observedCredential = await deps .loadCredential(db, settings, workspaceId, credentialId) .catch(() => null); let normalized: CodexUsagePayload; try { const usage = await fetchCodexUsage( { accessToken: token.accessToken, chatgptAccountId: token.chatgptAccountId, isFedramp: token.isFedramp, clientVersion: CODEX_CLIENT_VERSION, }, fetchImpl, ); normalized = normalizeCodexUsage(usage.status, usage.payload); } catch { // A network throw on the /wham/usage read must surface as an error PAYLOAD // ({status:"error"} at 200), never an unhandled 500 from the route. return errorUsagePayload(); } const parsedQuota = normalized.status !== "error" && (normalized.fiveHour != null || normalized.weekly != null); const observedPlanType = normalized.status !== "error" && typeof normalized.planType === "string" ? normalized.planType.trim() || null : null; if (parsedQuota || normalized.rateLimitResetCredits || observedPlanType) { const checkedAt = new Date(); // Quota windows and reset-summary freshness are independent. A malformed // usage body can still carry a syntactically valid count; that count may be // cached without erasing or falsely refreshing the last valid quota truth. // Cache-write is best-effort: a disconnect under us (false) or a transient // write error must NOT sink the freshly-read result we are about to return. await deps .recordUsage?.(db, workspaceId, credentialId, { ...(parsedQuota ? { primaryUsedPercent: normalized.fiveHour?.percent ?? null, primaryResetAt: normalized.fiveHour?.resetAt ? new Date(normalized.fiveHour.resetAt) : null, secondaryUsedPercent: normalized.weekly?.percent ?? null, secondaryResetAt: normalized.weekly?.resetAt ? new Date(normalized.weekly.resetAt) : null, checkedAt, } : {}), ...(observedCredential?.exhaustedUntil && observedCredential.exhaustedKind === "quota" && codexUsageConfirmsQuotaAvailable(normalized) ? { clearQuotaCooldownRevision: observedCredential.exhaustedRevision } : {}), ...(normalized.rateLimitResetCredits ? { resetCreditAvailableCount: normalized.rateLimitResetCredits.availableCount, resetCreditsCheckedAt: checkedAt, } : {}), ...(observedPlanType ? { planType: observedPlanType, planCheckedAt: checkedAt } : {}), }) .catch(() => undefined); } return normalized; } export type CodexCredentialPlanRecheck = { /** Plan recorded before this re-check (null when never observed). */ previousPlanType: string | null; /** Freshly observed plan, or null when neither provider source reported one. */ planType: string | null; source: "usage" | "token_refresh" | null; /** Credential version the observation belongs to (after any refresh). */ credentialVersion: number | null; /** * The credential's most recent recorded plan change after this observation * was persisted (including one this re-check itself observed). Ordinary * observers of an unchanged plan never overwrite it. */ planChangedFrom: string | null; planChangedAt: Date | null; /** Plan exclusion after this observation, including expired entries. */ exclusion: CodexPlanEntitlementExclusion | null; }; /** * Re-read one credential's CURRENT ChatGPT plan from the provider and persist * it. /wham/usage `plan_type` is tried first because it rotates no token; when * it reports no plan, one forced token refresh reads `chatgpt_plan_type` from * the new id_token (under the shared refresh lock and version CAS). Provider * failures produce `planType: null`, never an exception, so a caller can fall * back to its existing terminal behavior. The returned change record and * exclusion are read back after the observation is persisted. */ export async function recheckCodexCredentialPlan( db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps, fetchImpl: CodexFetch = fetch, ): Promise { const load = () => deps.loadCredential(db, settings, workspaceId, credentialId).catch(() => null); const before = await load(); const previousPlanType = before?.planType ?? null; const result = ( planType: string | null, source: CodexCredentialPlanRecheck["source"], after: CodexCredentialForRun | null, credentialVersion: number | null, ): CodexCredentialPlanRecheck => { const record = after ?? before; return { previousPlanType, planType, source, credentialVersion, planChangedFrom: record?.planPreviousType ?? null, planChangedAt: record?.planChangedAt ?? null, exclusion: record?.planEntitlementExclusion ?? null, }; }; const usage = await fetchCodexUsageForAccount( db, settings, workspaceId, credentialId, deps, fetchImpl, ).catch(() => null); const usagePlan = usage && usage.status !== "error" && typeof usage.planType === "string" ? usage.planType.trim() || null : null; if (usagePlan) { const after = await load(); return result(usagePlan, "usage", after, after?.version ?? before?.version ?? null); } try { const refreshed = await buildCodexTokenResolver( db, settings, workspaceId, credentialId, deps, ).refresh(); const planType = typeof refreshed.planType === "string" ? refreshed.planType.trim() || null : null; const after = await load(); return result(planType, planType ? "token_refresh" : null, after, refreshed.credentialVersion); } catch { return result(null, null, null, before?.version ?? null); } } export type CodexRateLimitResetCreditsAccountResult = | { ok: true; status: number; details: CodexRateLimitResetCreditsDetails } | { ok: false; status: number; reason: ResetCreditFetchFailureReason | "needs_relogin"; }; /** * Fresh detailed reset-credit inventory for one exact workspace credential. * The token is refreshed through the same resolver as usage and never escapes * this server-side function. Detailed rows are returned to the route only and * are never persisted as redemption authority. */ export async function fetchCodexRateLimitResetCreditsForAccount( db: Database, settings: Settings, workspaceId: string, credentialId: string, deps: CodexAuthDeps, fetchImpl: CodexFetch = fetch, ): Promise { const resolver = buildCodexTokenResolver(db, settings, workspaceId, credentialId, deps); let token: CodexTokenSnapshot; try { token = await resolver.getToken(); } catch (error) { return { ok: false, status: 0, reason: error instanceof CodexReloginRequired ? "needs_relogin" : "network_error", }; } return await fetchCodexRateLimitResetCredits( { accessToken: token.accessToken, chatgptAccountId: token.chatgptAccountId, isFedramp: token.isFedramp, clientVersion: CODEX_CLIENT_VERSION, }, fetchImpl, ); }