Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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 @@ -292,6 +292,8 @@ El panel de control y el `ocx status` muestran **posible uso fuera del opencodex

Una lectura ilegible de 5h no puede ocultar un bloque semanal. El uso desconocido no fabrica un cero, y una lectura faltante no borra una tupla de bloqueo ya medida. Un tiempo de reinicio predicho solo no lo desbloquea. Mientras está bloqueado, la recuperación comprueba los metadatos de uso propio en un horario limitado de 5/10/20/40/60 minutos, por lo que se observa un restablecimiento canjeado fuera de opencodex antes del restablecimiento previsto; el primer cheque espera cinco minutos, los cheques permanecen al menos cinco minutos de diferencia y el siguiente cheque se introduce al último restablecimiento de bloqueo conocido. Un principal en pausa o requerido para la re-autenticación no recibe ninguna comprobación antes de su reset predicho. Un `Retry-After` más largo también retrasa la preparación de perfiles y tokens. Solo el uso nuevo y válido o la evidencia autorizada de ausencia de ventana pueden levantar el bloqueo. En el modo Pool, una cuota `--refresh` evita la frescura de la memoria caché, pero aún honra el ritmo de lectura fallida; una lectura diferida no hace ningún nuevo intento de diagnóstico. Otros límites de pausa, reautenticación y aguas arriba permanecen independientes.

Antes de rechazar una solicitud, si el uso que sostiene el bloqueo se midió por última vez hace más de 60 segundos, OpenCodex puede volver a leer el uso una vez. Si esa lectura nueva ya no bloquea según los umbrales configurados, por ejemplo después de que un restablecimiento canjeado fuera de OpenCodex despejara todas las ventanas bloqueantes, la solicitud se resuelve de nuevo; una lectura que sigue bloqueando, o una lectura fallida o aplazada, mantiene el rechazo. Las solicitudes rechazadas a la vez comparten esa lectura, la cuenta principal recibe como máximo una lectura así por minuto, y el ritmo de lecturas fallidas, una cuenta principal en pausa o pendiente de reautenticación y el mantenimiento del perfil nativo la omiten. Una solicitud que se autentica con el propio inicio de sesión principal usa su propia credencial para esa lectura y nunca la almacenada.

La protección trata una nueva respuesta de uso WHAM válida como un reemplazo para la lectura de 5 horas anterior cuando su ventana principal dura explícitamente **al menos 24 horas** e informa sobre el uso válido, o su ventana principal es explícitamente `null` y un secundario medido proporciona el uso semanal. En cualquier caso, las ventanas secundarias / terciarias deben ser explícitamente `null` o explícitamente durar al menos 24 horas e informar el uso válido. Esto sigue el límite corto / largo del analizador, por lo que una ventana de un día califica, así como ventanas semanales / mensuales. La ventana actual sigue utilizando el mismo umbral de ventana larga configurado (98% por defecto). Esto se basa en la única instantánea reportada; no se requieren observaciones repetidas. Cualquier campo de ventana omitido, una duración desconocida o encabezados de respuesta parcial no pueden borrar un bloque anterior. Las respuestas totalmente nulas con solo créditos y lecturas complementarias mensuales tampoco pueden establecer la recuperación. El proxy comprueba la credencial almacenada de nuevo antes de aplicar una respuesta retardada. Un archivo ilegible o portador reemplazado no puede actualizar la memoria caché de uso, liberar el bloqueo o poner en cuarentena la nueva credencial, incluso para la misma cuenta sin leer la segunda cuota. Su uso ordinario analizado aún se puede devolver al llamante solicitante, sin actualizaciones de estado compartido o evidencia de recuperación. La tarjeta de cuenta muestra el uso publicado en caché, manteniendo su cuota alineada con el estado de bloqueo; Direct cuota de proveedor omite una respuesta no publicada y su informe en caché anterior. Las identidades de cuentas en conflicto y las respuestas obsoletas 401/403 retienen la información almacenada en caché actual y no pueden borrar o establecer el estado de reautenticación de la cuenta actual.

Responses a las solicitudes enviadas con la credencial principal identificada actualizan su uso en caché desde sus cabeceras de cuota, ya sea que el proxy sustituya la credencial almacenada o el llamante envíe la misma credencial. Una respuesta se aplica solo si esa credencial sigue siendo la credencial principal observada cuando llega; una credencial propiedad del llamante para otra cuenta o espacio de trabajo nunca actualiza el uso de la cuenta principal.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,7 @@ stay at least five minutes apart, and the next check is pulled in to the latest
or reauthentication-required main receives no checks before its predicted reset. A longer `Retry-After` also delays profile and token preparation. Only fresh valid usage or authoritative window-absence evidence
can lift the block. In Pool mode, a quota `--refresh` bypasses cache freshness but still honors failed-read pacing;
a deferred read makes no new diagnostic attempt. Other pause, reauthentication, and upstream limits remain independent.
Before refusing a request, if the usage behind the block was last measured more than 60 seconds ago, OpenCodex may read usage once more. When that fresh reading no longer blocks under the configured thresholds, for example after a reset redeemed outside OpenCodex cleared every blocking window, the request is resolved again; a reading that still blocks, or a failed or deferred read, keeps the refusal. Concurrent refusals share that read, the main account gets at most one such read per minute, and failed-read pacing, a paused or reauthentication-required main, and native-main maintenance skip it. A request that authenticates as the main login itself uses its own credential for that read and never the stored one.

Protection treats one fresh valid WHAM usage response as a replacement for the old 5h reading when
its primary window explicitly lasts **at least 24 hours** and reports valid usage, or its primary window is
Expand Down
2 changes: 1 addition & 1 deletion scripts/test-layout/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -1190,7 +1190,7 @@
"main-account-hard-lock-auth.test.ts": "codex-integration", "main-account-hard-lock-fallback-routing.test.ts": "codex-integration", "main-account-hard-lock-usage-limit.test.ts": "codex-integration",
"main-account-hard-lock-default.test.ts": "codex-integration",
"main-account-hard-lock-policy.test.ts": "codex-integration",
"main-account-hard-lock-recovery.test.ts": "codex-integration", "main-account-credit-renewal.test.ts": "codex-integration",
"main-account-hard-lock-refusal-read.test.ts": "codex-integration", "main-account-hard-lock-recovery.test.ts": "codex-integration", "main-account-credit-renewal.test.ts": "codex-integration",
"main-account-policy-binding-wait.test.ts": "codex-integration",
"main-device-reauth-api.test.ts": "codex-integration",
"main-device-reauth-ui.test.ts": "gui",
Expand Down
4 changes: 3 additions & 1 deletion src/codex/auth-api/main-account-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,8 @@ export interface MainAccountInfoProbeOptions {
passive?: boolean;
/** Exact owned result obtained before entering WHAM's shared credential claim. Never serialized. */
preparedToken?: MainAccountToken | null;
/** Always use paced usage scheduling, so failure backoff and Retry-After are recorded in every mode. */
paced?: boolean;
}

export const EMPTY_MAIN_ACCOUNT_INFO: MainAccountInfo = { email: null, plan: null, quota: null };
Expand Down Expand Up @@ -215,7 +217,7 @@ export async function fetchMainAccountInfoAttempt(
}
}
const probeOptions = preparedToken === undefined ? options : { ...options, preparedToken };
const paced = sharedMainQuotaPacingEnabled(config ?? loadConfig());
const paced = options.paced === true || sharedMainQuotaPacingEnabled(config ?? loadConfig());
const operation = async () => ({
...await fetchMainAccountInfoWhileOwned(forceRefresh, retriesRemaining, nativeMainLease, explicitRefresh, postReset, paced, probeOptions),
identityGeneration: captureMainAccountIdentityGeneration(),
Expand Down
172 changes: 172 additions & 0 deletions src/codex/auth-api/main-hard-lock-refusal-read.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import type { OcxConfig } from "../../types";
import { MAIN_CODEX_ACCOUNT_ID } from "../account-id";
import { reconcileMainCodexAccountRuntimeState } from "../account-lifecycle";
import { isCodexAccountPaused } from "../account-pause";
import { isAccountNeedsReauth } from "../account-runtime-state";
import { getMainAccountHardLockStatus } from "../main-account-hard-lock";
import { getValidMainAccountToken, mainAccountTokenIsCurrent, mainAccountTokenQuotaWriter } from "../main-account";
import {
captureMainAccountIdentityGeneration, captureMainQuotaDispatch, getMainQuotaCredentialGeneration, getObservedMainQuotaIdentityKey,
isMainAccountIdentityGenerationLive, isMainQuotaDispatchLive, matchesMainQuotaCredential, observeMainQuotaCredential,
} from "../main-account-cache";
import { tryAcquireNativeMainProfileClaim } from "../native-main-admission";
import { isNativeMainTrafficBlocked } from "../native-profile-startup";
import {
getMainPolicyUsageObservedAt, isValidWhamHistoryObservation, parseMainPolicyUsageQuota, parseUsageQuota, setAccountQuotaFromParsed,
type WhamUsageResponse,
} from "../quota";
import { fetchCodexUsage, nextCodexUsageQueryAt } from "../quota-query-backoff";
import { WHAM_REQUEST_TIMEOUT_MS } from "../quota-recovery-timing";
import { captureConfigGeneration } from "../../lib/state-store-sweeper";
import type { AdmissionLease } from "../../lib/admission";
import { fetchMainAccountInfoAttempt } from "./main-account-probe";
import { isQuotaDispatchCurrent, nextQuotaDispatchSequence, publishQuotaDispatch } from "./pool-quota-probe";

/** A hard-lock reading younger than this is current enough to refuse on (#8113). */
export const MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS = 60_000;
/** At most one refusal-triggered WHAM read per main identity in this window. */
export const MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS = 60_000;

// Last refusal read per main identity, kept for the whole interval so an A→B→A switch cannot reset it.
const lastReadAt = new Map<string, number>();
let inFlight: Promise<void> | undefined;

/**
* The caller's own credential when the refused request authenticates as the main login itself
* (caller-owned Direct, or a request-scoped main bearer in Pool). Such a request may not read the
* physical main credential, so its fresh read uses this bearer, which the lock already proved is
* the observed main credential.
*/
export interface MainHardLockRefusalCaller {
bearer: string;
accountId: string;
}

/** Test-only: forget the per-identity pacing and any settled read. */
export function resetMainHardLockRefusalReadForTests(): void {
lastReadAt.clear();
inFlight = undefined;
}

/**
* Before a main hard-lock refusal, read WHAM once when the reading behind the lock is stale (#8113).
*
* A reset redeemed outside OpenCodex leaves the cached reading above the threshold until a later
* observation replaces it, and the paced background recovery may not run for minutes. When the
* cached reading is older than {@link MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS}, this reads usage once:
* with the proxy-owned main credential and the native-main claim through the recovery probe, or,
* for a caller-owned main request, with the caller's own bearer, published only while that bearer
* still matches the observed main credential. Concurrent refusals share
* one read, and each main identity gets at most one read per
* {@link MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS}. Server-advised usage backoff, a paused main,
* reauthentication quarantine and native-main maintenance all skip the read. The read is passive:
* it never sets or clears the reauthentication quarantine.
*
* Returns `true` when the lock no longer blocks, so the caller may resolve the request again;
* `false` keeps the refusal. A failed read keeps the existing policy observation.
*/
export async function refreshMainHardLockBeforeRefusal(
config: OcxConfig,
policy: Parameters<typeof getMainAccountHardLockStatus>[0] = config,
signal?: AbortSignal,
/** The caller-owned main credential; `null` when the request is caller-owned but unusable for a read. */
caller?: MainHardLockRefusalCaller | null,
now: () => number = Date.now,
): Promise<boolean> {
const blocked = () => getMainAccountHardLockStatus(policy, now()).state === "blocked";
if (!blocked()) return true;
if (caller === null) return false;
// The usage measurement's age, not the snapshot's write time: credits-only merges rewrite the latter.
const observedAt = getMainPolicyUsageObservedAt();
if (observedAt !== undefined && now() - observedAt < MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS) return false;
if (isNativeMainTrafficBlocked() || isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)
|| isCodexAccountPaused(config, MAIN_CODEX_ACCOUNT_ID)) return false;
if (!inFlight) {
const identity = getObservedMainQuotaIdentityKey() ?? "";
for (const [key, at] of lastReadAt) {
if (now() - at >= MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS) lastReadAt.delete(key);
}
if (lastReadAt.has(identity)) return false;
const queryAfter = nextCodexUsageQueryAt(`main:${captureConfigGeneration()}:${getMainQuotaCredentialGeneration()}`);
if (queryAfter !== undefined && queryAfter > now()) return false;
let read: Promise<void>;
if (caller) {
// Without a live proof for the caller's credential there is nothing to read; keep the minute.
const dispatch = captureMainQuotaDispatch(caller.bearer, caller.accountId, captureConfigGeneration());
if (!dispatch) return false;
lastReadAt.set(identity, now());
read = readCallerMainUsage(caller, dispatch);
} else {
const lease = tryAcquireNativeMainProfileClaim();
if (!lease) return false;
lastReadAt.set(identity, now());
read = readMainUsage(config, lease).finally(() => lease.release());
}
read = read
.catch(() => { /* the refusal stands on the existing observation */ })
.finally(() => { if (inFlight === read) inFlight = undefined; });
inFlight = read;
}
await abortable(inFlight, signal);
return !blocked();
}

async function readMainUsage(config: OcxConfig, lease: AdmissionLease): Promise<void> {
reconcileMainCodexAccountRuntimeState();
const identityGeneration = captureMainAccountIdentityGeneration();
// Refresh can need an exclusive credential claim, so obtain the token before WHAM's shared claim.
const prepared = await getValidMainAccountToken({ preserveReauth: true });
if (!prepared) return;
if (mainAccountTokenQuotaWriter(prepared)) {
if (!mainAccountTokenIsCurrent(prepared)) return;
} else observeMainQuotaCredential(prepared.accessToken, prepared.chatgptAccountId);
if (!isMainAccountIdentityGenerationLive(identityGeneration) || isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)) return;
// Paced in every account mode: a failed or Retry-After answer must defer the next read.
await fetchMainAccountInfoAttempt(true, 1, lease, false, false, false, config,
{ passive: true, preparedToken: prepared, paced: true });
}

/** Usage read with the caller's own main bearer: no physical credential read, no reauth state. */
async function readCallerMainUsage(
caller: MainHardLockRefusalCaller, dispatch: NonNullable<ReturnType<typeof captureMainQuotaDispatch>>,
): Promise<void> {
// The dispatch proof also fences credential commits (refresh, reauthentication) that advance the
// mutation epoch before the observed credential itself changes.
const writerGeneration = dispatch.configGeneration;
// Ordered like the main probe: a response publishes only if no later dispatch already published.
const sequence = nextQuotaDispatchSequence();
const key = `main:${writerGeneration}:${dispatch.credentialGeneration}`;
const admission = await fetchCodexUsage(key, {
headers: { Authorization: `Bearer ${caller.bearer}`, "ChatGPT-Account-Id": caller.accountId },
signal: AbortSignal.timeout(WHAM_REQUEST_TIMEOUT_MS),
}, undefined, { pacingKey: key });
// A joined read belongs to another owner, which publishes its own evidence.
if (!admission || admission.kind === "joined") return;
let usable = false;
try {
if (!admission.response.ok) return;
const data = await admission.response.json() as WhamUsageResponse;
if (data === null || typeof data !== "object" || Array.isArray(data)) return;
// The main login may have changed while the read was in flight; never publish across it.
if (!isMainQuotaDispatchLive(dispatch) || !matchesMainQuotaCredential(caller.bearer, caller.accountId)
|| writerGeneration !== captureConfigGeneration() || !isQuotaDispatchCurrent(sequence)) return;
const quota = parseUsageQuota(data);
if (!quota) return;
setAccountQuotaFromParsed(MAIN_CODEX_ACCOUNT_ID, quota, writerGeneration, dispatch.writer, parseMainPolicyUsageQuota(data),
undefined, false, false, isValidWhamHistoryObservation(data) ? quota : null);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
publishQuotaDispatch(sequence);
usable = true;
} finally {
admission.settle(usable);
}
}

function abortable(promise: Promise<void>, signal?: AbortSignal): Promise<void> {
if (!signal) return promise;
signal.throwIfAborted();
return new Promise<void>((resolve, reject) => {
const onAbort = () => reject(signal.reason);
signal.addEventListener("abort", onAbort, { once: true });
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
});
}
37 changes: 37 additions & 0 deletions src/codex/auth-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,43 @@ export async function resolveCodexAuthContext(
config: OcxConfig,
mode: CodexAccountMode,
options: ResolveCodexAuthContextOptions = {},
): Promise<CodexAuthContext> {
try {
return await resolveCodexAuthContextWithHint(headers, config, mode, options);
} catch (error) {
// #8113: a refusal resting on a reading older than 60 s first gets one fresh WHAM read, so a
// reset redeemed outside OpenCodex lifts the lock now instead of at the next paced recovery.
if (!(error instanceof CodexMainAccountHardLockError)) throw error;
const { refreshMainHardLockBeforeRefusal } = await import("./auth-api/main-hard-lock-refusal-read");
if (!await refreshMainHardLockBeforeRefusal(config, options.codexAuthPolicy ?? config, options.signal,
callerOwnedMainRefusal(headers, mode, options))) throw error;
return await resolveCodexAuthContextWithHint(headers, config, mode, options);
}
}

/**
* A refusal for a request that authenticates as the main login itself. That request may never
* read the physical main credential, so its fresh read uses the caller's own bearer (#8113).
* Any other refusal is about the proxy-owned main credential.
*/
function callerOwnedMainRefusal(
headers: Headers, mode: CodexAccountMode, options: ResolveCodexAuthContextOptions,
): { bearer: string; accountId: string } | null | undefined {
if (options.substituteMainCredentialForDirect === true || !hasCallerCodexBearer(headers)) return undefined;
if (mode !== "direct" && options.requestScopedMainCredential !== true) return undefined;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// An explicit stored-account selection resolves the proxy-owned credential, whatever bearer arrived.
if (options.accountId !== undefined && options.requestScopedMainCredential !== true) return undefined;
const bearer = authorizationCredential(headers);
const accountId = headers.get("chatgpt-account-id") ?? (bearer ? extractAccountId(undefined, bearer) : undefined);
// Caller-owned without a usable credential: no read at all, never the physical one.
return bearer && accountId ? { bearer, accountId } : null;
}

async function resolveCodexAuthContextWithHint(
headers: Headers,
config: OcxConfig,
mode: CodexAccountMode,
options: ResolveCodexAuthContextOptions,
): Promise<CodexAuthContext> {
// Filled by the inner resolver with the request's own fenced model evidence, so the hint obeys it.
const eligibility: RecoveryHintEligibility = {};
Expand Down
Loading
Loading