Skip to content

Commit f6f0d07

Browse files
committed
fix: fall back to Codex CLI OAuth after refresh failure
1 parent 06e79b2 commit f6f0d07

7 files changed

Lines changed: 253 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Docs: https://docs.openclaw.ai
3535
### Fixes
3636

3737
- Agents: retry empty final turns for generic `anthropic-messages` providers instead of limiting non-visible recovery to Kimi, so custom/proxied Anthropic-compatible routes can recover with a visible answer. Addresses #46080. Thanks @wmgx, @w1tv, and @iFwu.
38+
- Codex app-server: fall back to same-account Codex CLI OAuth tokens at runtime when the local OpenAI Codex refresh token is rejected, without overwriting the canonical OpenClaw auth profile. Fixes #82069. Thanks @aaajiao.
3839
- Control UI: rotate browser service-worker caches per build so updated Gateways are less likely to keep serving stale dashboard bundles that trigger protocol mismatch errors.
3940
- Discord: report unresolved configured bot-token SecretRefs during startup instead of treating the account as unconfigured. (#82009) Thanks @giodl73-repo.
4041
- CLI/config: preserve numeric-looking object keys such as Discord guild IDs during `config patch` recursive merges. (#81999) Thanks @giodl73-repo.

‎docs/concepts/oauth.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,10 @@ To reduce that, OpenClaw treats `auth-profiles.json` as a **token sink**:
4646
- we can keep multiple profiles and route them deterministically
4747
- external CLI reuse is provider-specific: Codex CLI can bootstrap an empty
4848
`openai-codex:default` profile, but once OpenClaw has a local OAuth profile,
49-
the local refresh token is canonical; other integrations can remain
50-
externally managed and re-read their CLI auth store
49+
the local refresh token is canonical. If that local refresh token is rejected,
50+
OpenClaw can use a usable same-account Codex CLI token as a runtime-only
51+
fallback; other integrations can remain externally managed and re-read their
52+
CLI auth store
5153
- status and startup paths that already know the configured provider set scope
5254
external CLI discovery to that set, so an unrelated CLI login store is not
5355
probed for a single-provider setup
@@ -146,7 +148,9 @@ At runtime:
146148
re-reads those CLI auth stores instead of spending copied refresh tokens.
147149
Codex CLI bootstrap is intentionally narrower: it seeds an empty
148150
`openai-codex:default` profile, then OpenClaw-owned refreshes keep the local
149-
profile canonical.
151+
profile canonical. If the local Codex refresh fails and Codex CLI has a
152+
usable token for the same account, OpenClaw may use that token for the current
153+
runtime request without writing it back to `auth-profiles.json`.
150154

151155
The refresh flow is automatic; you generally don't need to manage tokens manually.
152156

‎src/agents/auth-profiles/external-cli-sync.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,19 +154,36 @@ function hasInlineOAuthTokenMaterial(credential: OAuthCredential): boolean {
154154
export function readExternalCliBootstrapCredential(params: {
155155
profileId: string;
156156
credential: OAuthCredential;
157+
allowInlineOAuthTokenMaterial?: boolean;
158+
allowKeychainPrompt?: boolean;
157159
}): OAuthCredential | null {
158160
const provider = resolveExternalCliSyncProvider(params);
159161
if (!provider) {
160162
return null;
161163
}
162-
if (provider.bootstrapOnly && hasInlineOAuthTokenMaterial(params.credential)) {
164+
if (
165+
provider.bootstrapOnly &&
166+
!params.allowInlineOAuthTokenMaterial &&
167+
hasInlineOAuthTokenMaterial(params.credential)
168+
) {
163169
return null;
164170
}
165-
return provider.readCredentials();
171+
return provider.readCredentials({ allowKeychainPrompt: params.allowKeychainPrompt });
166172
}
167173

168174
export const readManagedExternalCliCredential = readExternalCliBootstrapCredential;
169175

176+
export function readExternalCliFallbackCredential(params: {
177+
profileId: string;
178+
credential: OAuthCredential;
179+
allowKeychainPrompt?: boolean;
180+
}): OAuthCredential | null {
181+
return readExternalCliBootstrapCredential({
182+
...params,
183+
allowInlineOAuthTokenMaterial: true,
184+
});
185+
}
186+
170187
function normalizeProviderScope(values: Iterable<string> | undefined): Set<string> | undefined {
171188
if (values === undefined) {
172189
return undefined;

‎src/agents/auth-profiles/oauth-manager.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
} from "./oauth-refresh-lock-errors.js";
1515
import {
1616
areOAuthCredentialsEquivalent,
17+
hasMatchingOAuthIdentity,
1718
hasUsableOAuthCredential,
1819
isSafeToAdoptBootstrapOAuthIdentity,
1920
isSafeToAdoptMainStoreOAuthIdentity,
@@ -45,6 +46,10 @@ export type OAuthManagerAdapter = {
4546
profileId: string;
4647
credential: OAuthCredential;
4748
}) => OAuthCredential | null;
49+
readFallbackCredential?: (params: {
50+
profileId: string;
51+
credential: OAuthCredential;
52+
}) => OAuthCredential | null;
4853
isRefreshTokenReusedError: (error: unknown) => boolean;
4954
};
5055

@@ -648,6 +653,34 @@ export function createOAuthManager(adapter: OAuthManagerAdapter) {
648653
// keep the original refresh error below
649654
}
650655
}
656+
const fallback = adapter.readFallbackCredential?.({
657+
profileId: params.profileId,
658+
credential: effectiveCredential,
659+
});
660+
if (
661+
fallback &&
662+
fallback.provider === params.credential.provider &&
663+
hasUsableOAuthCredential(fallback) &&
664+
hasMatchingOAuthIdentity(params.credential, fallback) &&
665+
canReuseOAuthCredentialAfterRefreshFailure({
666+
forceRefresh: params.forceRefresh,
667+
attempted: effectiveCredential,
668+
candidate: fallback,
669+
})
670+
) {
671+
log.info("using external OAuth credential after refresh failure", {
672+
profileId: params.profileId,
673+
provider: fallback.provider,
674+
expires: new Date(fallback.expires).toISOString(),
675+
});
676+
return {
677+
apiKey: await adapter.buildApiKey(fallback.provider, fallback, {
678+
cfg: params.cfg,
679+
agentDir: params.agentDir,
680+
}),
681+
credential: fallback,
682+
};
683+
}
651684
throw new OAuthManagerRefreshError({
652685
credential: params.credential,
653686
profileId: params.profileId,

‎src/agents/auth-profiles/oauth-shared.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ export function hasOAuthIdentity(
7878
);
7979
}
8080

81-
function hasMatchingOAuthIdentity(
81+
export function hasMatchingOAuthIdentity(
8282
existing: Pick<OAuthCredential, "accountId" | "email">,
8383
incoming: Pick<OAuthCredential, "accountId" | "email">,
8484
): boolean {

‎src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts‎

Lines changed: 180 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ const { getOAuthApiKeyMock } = vi.hoisted(() => ({
2121
}));
2222

2323
const { readCodexCliCredentialsCachedMock } = vi.hoisted(() => ({
24-
readCodexCliCredentialsCachedMock: vi.fn<() => OAuthCredential | null>(() => null),
24+
readCodexCliCredentialsCachedMock: vi.fn<(_options?: unknown) => OAuthCredential | null>(
25+
() => null,
26+
),
2527
}));
2628

2729
const {
@@ -462,6 +464,183 @@ describe("resolveApiKeyForProfile openai-codex refresh fallback", () => {
462464
expect(persisted.profiles[profileId]).not.toHaveProperty("refresh");
463465
});
464466

467+
it("uses same-account Codex CLI credentials after forced local refresh fails", async () => {
468+
const profileId = "openai-codex:default";
469+
saveAuthProfileStore(
470+
{
471+
version: 1,
472+
profiles: {
473+
[profileId]: {
474+
type: "oauth",
475+
provider: "openai-codex",
476+
access: "local-access-token",
477+
refresh: "local-refresh-token",
478+
expires: Date.now() + 86_400_000,
479+
accountId: "acct-shared",
480+
},
481+
},
482+
},
483+
agentDir,
484+
);
485+
readCodexCliCredentialsCachedMock.mockReturnValue({
486+
type: "oauth",
487+
provider: "openai-codex",
488+
access: "codex-cli-access-token",
489+
refresh: "codex-cli-refresh-token",
490+
expires: Date.now() + 86_400_000,
491+
accountId: "acct-shared",
492+
});
493+
refreshProviderOAuthCredentialWithPluginMock.mockImplementationOnce(async () => {
494+
throw new Error(
495+
'401 {"error":{"message":"Your refresh token is expired.","code":"refresh_token_expired"}}',
496+
);
497+
});
498+
499+
await expect(
500+
resolveApiKeyForProfile({
501+
store: ensureAuthProfileStore(agentDir),
502+
profileId,
503+
agentDir,
504+
forceRefresh: true,
505+
}),
506+
).resolves.toEqual({
507+
apiKey: "codex-cli-access-token",
508+
provider: "openai-codex",
509+
email: undefined,
510+
});
511+
512+
expect(readCodexCliCredentialsCachedMock).toHaveBeenCalledWith({
513+
ttlMs: expect.any(Number),
514+
allowKeychainPrompt: false,
515+
});
516+
const persisted = await readPersistedStore(agentDir);
517+
const persistedProfile = requireOAuthProfile(persisted, profileId);
518+
expect(persistedProfile.accountId).toBe("acct-shared");
519+
expect(persistedProfile).not.toHaveProperty("access");
520+
expect(persistedProfile).not.toHaveProperty("refresh");
521+
expect(JSON.stringify(persisted)).not.toContain("codex-cli-access-token");
522+
expect(JSON.stringify(persisted)).not.toContain("codex-cli-refresh-token");
523+
});
524+
525+
it("rejects mismatched Codex CLI fallback after forced local refresh fails", async () => {
526+
const profileId = "openai-codex:default";
527+
saveAuthProfileStore(
528+
{
529+
version: 1,
530+
profiles: {
531+
[profileId]: {
532+
type: "oauth",
533+
provider: "openai-codex",
534+
access: "local-access-token",
535+
refresh: "local-refresh-token",
536+
expires: Date.now() + 86_400_000,
537+
accountId: "acct-local",
538+
},
539+
},
540+
},
541+
agentDir,
542+
);
543+
readCodexCliCredentialsCachedMock.mockReturnValue({
544+
type: "oauth",
545+
provider: "openai-codex",
546+
access: "codex-cli-access-token",
547+
refresh: "codex-cli-refresh-token",
548+
expires: Date.now() + 86_400_000,
549+
accountId: "acct-other",
550+
});
551+
refreshProviderOAuthCredentialWithPluginMock.mockImplementationOnce(async () => {
552+
throw new Error(
553+
'401 {"error":{"message":"Your refresh token is expired.","code":"refresh_token_expired"}}',
554+
);
555+
});
556+
557+
await expect(
558+
resolveApiKeyForProfile({
559+
store: ensureAuthProfileStore(agentDir),
560+
profileId,
561+
agentDir,
562+
forceRefresh: true,
563+
}),
564+
).rejects.toThrow(/OAuth token refresh failed for openai-codex/);
565+
});
566+
567+
it("rejects identity-less Codex CLI fallback after forced local refresh fails", async () => {
568+
const profileId = "openai-codex:default";
569+
saveAuthProfileStore(
570+
{
571+
version: 1,
572+
profiles: {
573+
[profileId]: {
574+
type: "oauth",
575+
provider: "openai-codex",
576+
access: "local-access-token",
577+
refresh: "local-refresh-token",
578+
expires: Date.now() + 86_400_000,
579+
},
580+
},
581+
},
582+
agentDir,
583+
);
584+
readCodexCliCredentialsCachedMock.mockReturnValue({
585+
type: "oauth",
586+
provider: "openai-codex",
587+
access: "codex-cli-access-token",
588+
refresh: "codex-cli-refresh-token",
589+
expires: Date.now() + 86_400_000,
590+
accountId: "acct-cli",
591+
});
592+
refreshProviderOAuthCredentialWithPluginMock.mockImplementationOnce(async () => {
593+
throw new Error(
594+
'401 {"error":{"message":"Your refresh token is expired.","code":"refresh_token_expired"}}',
595+
);
596+
});
597+
598+
await expect(
599+
resolveApiKeyForProfile({
600+
store: ensureAuthProfileStore(agentDir),
601+
profileId,
602+
agentDir,
603+
forceRefresh: true,
604+
}),
605+
).rejects.toThrow(/OAuth token refresh failed for openai-codex/);
606+
});
607+
608+
it("rejects unchanged Codex CLI fallback during forced refresh", async () => {
609+
const profileId = "openai-codex:default";
610+
const credential: OAuthCredential = {
611+
type: "oauth",
612+
provider: "openai-codex",
613+
access: "shared-access-token",
614+
refresh: "shared-refresh-token",
615+
expires: Date.now() + 86_400_000,
616+
accountId: "acct-shared",
617+
};
618+
saveAuthProfileStore(
619+
{
620+
version: 1,
621+
profiles: {
622+
[profileId]: credential,
623+
},
624+
},
625+
agentDir,
626+
);
627+
readCodexCliCredentialsCachedMock.mockReturnValue({ ...credential });
628+
refreshProviderOAuthCredentialWithPluginMock.mockImplementationOnce(async () => {
629+
throw new Error(
630+
'401 {"error":{"message":"Your refresh token is expired.","code":"refresh_token_expired"}}',
631+
);
632+
});
633+
634+
await expect(
635+
resolveApiKeyForProfile({
636+
store: ensureAuthProfileStore(agentDir),
637+
profileId,
638+
agentDir,
639+
forceRefresh: true,
640+
}),
641+
).rejects.toThrow(/OAuth token refresh failed for openai-codex/);
642+
});
643+
465644
it("adopts fresher stored credentials after refresh_token_reused", async () => {
466645
const profileId = "openai-codex:default";
467646
saveAuthProfileStore(

‎src/agents/auth-profiles/oauth.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,10 @@ import { refreshChutesTokens } from "../chutes-oauth.js";
1919
import { log } from "./constants.js";
2020
import { resolveTokenExpiryState } from "./credential-state.js";
2121
import { formatAuthDoctorHint } from "./doctor.js";
22-
import { readManagedExternalCliCredential } from "./external-cli-sync.js";
22+
import {
23+
readExternalCliFallbackCredential,
24+
readManagedExternalCliCredential,
25+
} from "./external-cli-sync.js";
2326
import { createOAuthManager, OAuthManagerRefreshError } from "./oauth-manager.js";
2427
import { assertNoOAuthSecretRefPolicyViolations } from "./policy.js";
2528
import { suggestOAuthProfileIdForLegacyDefault } from "./repair.js";
@@ -184,6 +187,14 @@ const oauthManager = createOAuthManager({
184187
profileId,
185188
credential,
186189
}),
190+
readFallbackCredential: ({ profileId, credential }) =>
191+
credential.provider === "openai-codex"
192+
? readExternalCliFallbackCredential({
193+
profileId,
194+
credential,
195+
allowKeychainPrompt: false,
196+
})
197+
: null,
187198
isRefreshTokenReusedError,
188199
});
189200

0 commit comments

Comments
 (0)