Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(openai-codex): force-refresh the Codex OAuth token on a 401 response

Jack Rudenkoc10b21ee8150
diff --git a/packages/cli/src/auth/codex-oauth.ts b/packages/cli/src/auth/codex-oauth.ts
index 09ae4378..a732e3e8 100644
--- a/packages/cli/src/auth/codex-oauth.ts
+++ b/packages/cli/src/auth/codex-oauth.ts
@@ -213,16 +213,30 @@ export class CodexOAuth {
}
/**
- * Force refresh the access token
+ * Force refresh the access token.
+ *
+ * Single-flighted through the same `refreshPromise` lock as `getAccessToken`:
+ * a rotated refresh token is single-use, so two concurrent forced refreshes
+ * (two requests answered 401 at once) that each spent it would leave the
+ * second holding a token the server already invalidated. A refresh already
+ * in flight is joined, never duplicated.
*/
async refreshToken(): Promise<void> {
+ if (this.refreshPromise) {
+ log("[CodexOAuth] Joining in-progress refresh");
+ await this.refreshPromise;
+ return;
+ }
if (!this.credentials) {
throw new Error(
"No OpenAI Codex OAuth credentials found. Please run `claudish login codex` first."
);
}
- await this.doRefreshToken();
+ this.refreshPromise = this.doRefreshToken().finally(() => {
+ this.refreshPromise = null;
+ });
+ await this.refreshPromise;
}
/**
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.ts
index 0cd95cd0..1654fa96 100644
--- a/packages/cli/src/handlers/composed-handler.ts
+++ b/packages/cli/src/handlers/composed-handler.ts
@@ -1757,7 +1757,15 @@ export class ComposedHandler implements ModelHandler {
if (!response.ok) {
// 401: retry with forced auth refresh (OAuth token expiry)
- if (response.status === 401 && this.provider.forceRefreshAuth) {
+ // Only for a request with no binding (every transport but `openai-codex`,
+ // unchanged) or one bound to the OAuth arm: a forced OAuth refresh cannot
+ // fix an API key, so an `openai-codex` api-key request takes the ordinary
+ // error path below.
+ if (
+ response.status === 401 &&
+ this.provider.forceRefreshAuth &&
+ (binding === undefined || binding.auth?.arm === "oauth")
+ ) {
log(`[${this.provider.displayName}] Got 401, forcing auth refresh and retrying`);
// The forced refresh AND the retry fetch that follows it, as one
// re-issuable operation. Both are network calls and either can fail
@@ -2266,7 +2274,12 @@ export class ComposedHandler implements ModelHandler {
b ? { auth: b.auth, accountKey: accountKeyFromBinding(b) } : undefined;
let legBinding = toLegBinding(binding);
const refreshAuth = this.provider.refreshAuth?.bind(this.provider);
- const forceRefreshAuth = this.provider.forceRefreshAuth?.bind(this.provider);
+ // Same gate as the primary 401 branch; the arm cannot change mid-turn
+ // (the issuer refuses a leg on another arm), so it is decided once here.
+ const forceRefreshAuth =
+ binding === undefined || binding.auth?.arm === "oauth"
+ ? this.provider.forceRefreshAuth?.bind(this.provider)
+ : undefined;
const issueLeg = createLegIssuer<LegBinding>({
providerDisplayName: this.provider.displayName,
getBinding: () => legBinding,
diff --git a/packages/cli/src/providers/transport/openai-codex.ts b/packages/cli/src/providers/transport/openai-codex.ts
index c113b859..ea9fbe90 100644
--- a/packages/cli/src/providers/transport/openai-codex.ts
+++ b/packages/cli/src/providers/transport/openai-codex.ts
@@ -23,8 +23,10 @@
import { normalizeCodexModel } from "../../adapters/codex-api-format.js";
import { lookupModelForProvider } from "../../adapters/model-catalog.js";
+import { CodexOAuth } from "../../auth/codex-oauth.js";
import { credentials } from "../../auth/credentials/authority.js";
import { recordSignedArm } from "../../auth/credentials/billing-probe.js";
+import { CodexOAuthHalf } from "../../auth/credentials/codex-credential.js";
import type { RequestAuth } from "../../auth/credentials/types.js";
import { classifyConnectionError } from "../../handlers/shared/connection-error.js";
import { conversationKey } from "./conversation-key.js";
@@ -92,6 +94,30 @@ export class OpenAICodexTransport extends OpenAIProviderTransport {
return { auth: this.cachedAuth };
}
+ /**
+ * After a 401 on the subscription arm: rotate the Codex OAuth token and mint
+ * a fresh artifact from the OAuth half ONLY.
+ *
+ * The api-key half is never consulted, so a 401 retry can never change arm:
+ * an expired subscription token must not quietly re-sign the request with
+ * OPENAI_CODEX_API_KEY on the metered `api.openai.com`. ComposedHandler calls
+ * this only when the request's binding is the `"oauth"` arm.
+ *
+ * `refreshToken()` single-flights through CodexOAuth's refresh lock, so
+ * concurrent 401s on one login spend the (single-use) refresh token once.
+ * Every throw propagates unchanged: a connection failure reaches the
+ * `forceRefreshAuth` site in composed-handler, which classifies it (one of
+ * the five auth sites); swallowing it here would be a sixth site that hides
+ * an outage.
+ */
+ async forceRefreshAuth(): Promise<AuthBinding> {
+ await CodexOAuth.getInstance().refreshToken();
+ const auth = await new CodexOAuthHalf().getRequestAuth({ model: "" });
+ // Kept for callers that pass no binding; the request path uses the return.
+ this.cachedAuth = auth;
+ return { auth };
+ }
+
/**
* The artifact a call reads: the request's binding when one is passed (its
* `auth`, even when null), else `cachedAuth` for callers that pass none.