Skip to content
This repository was archived by the owner on May 23, 2026. It is now read-only.

Commit c64ac90

Browse files
fix(opencode): dedupe concurrent Codex OAuth refreshes (anomalyco#28236)
Co-authored-by: Aiden Cline <[email protected]>
1 parent 7a55444 commit c64ac90

2 files changed

Lines changed: 153 additions & 19 deletions

File tree

‎packages/opencode/src/plugin/codex.ts‎

Lines changed: 47 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,11 @@ interface TokenResponse {
118118
expires_in?: number
119119
}
120120

121+
interface CodexAuthPluginOptions {
122+
issuer?: string
123+
codexApiEndpoint?: string
124+
}
125+
121126
async function exchangeCodeForTokens(code: string, redirectUri: string, pkce: PkceCodes): Promise<TokenResponse> {
122127
const response = await fetch(`${ISSUER}/oauth/token`, {
123128
method: "POST",
@@ -136,8 +141,8 @@ async function exchangeCodeForTokens(code: string, redirectUri: string, pkce: Pk
136141
return response.json()
137142
}
138143

139-
async function refreshAccessToken(refreshToken: string): Promise<TokenResponse> {
140-
const response = await fetch(`${ISSUER}/oauth/token`, {
144+
async function refreshAccessToken(refreshToken: string, issuer = ISSUER): Promise<TokenResponse> {
145+
const response = await fetch(`${issuer}/oauth/token`, {
141146
method: "POST",
142147
headers: { "Content-Type": "application/x-www-form-urlencoded" },
143148
body: new URLSearchParams({
@@ -364,7 +369,10 @@ function waitForOAuthCallback(pkce: PkceCodes, state: string): Promise<TokenResp
364369
})
365370
}
366371

367-
export async function CodexAuthPlugin(input: PluginInput): Promise<Hooks> {
372+
export async function CodexAuthPlugin(input: PluginInput, options: CodexAuthPluginOptions = {}): Promise<Hooks> {
373+
const issuer = options.issuer ?? ISSUER
374+
const codexApiEndpoint = options.codexApiEndpoint ?? CODEX_API_ENDPOINT
375+
368376
return {
369377
provider: {
370378
id: "openai",
@@ -405,6 +413,13 @@ export async function CodexAuthPlugin(input: PluginInput): Promise<Hooks> {
405413
const auth = await getAuth()
406414
if (auth.type !== "oauth") return {}
407415

416+
let refreshPromise:
417+
| Promise<{
418+
access: string
419+
accountId: string | undefined
420+
}>
421+
| undefined
422+
408423
return {
409424
apiKey: OAUTH_DUMMY_KEY,
410425
async fetch(requestInput: RequestInfo | URL, init?: RequestInit) {
@@ -429,21 +444,34 @@ export async function CodexAuthPlugin(input: PluginInput): Promise<Hooks> {
429444

430445
// Check if token needs refresh
431446
if (!currentAuth.access || currentAuth.expires < Date.now()) {
432-
log.info("refreshing codex access token")
433-
const tokens = await refreshAccessToken(currentAuth.refresh)
434-
const newAccountId = extractAccountId(tokens) || authWithAccount.accountId
435-
await input.client.auth.set({
436-
path: { id: "openai" },
437-
body: {
438-
type: "oauth",
439-
refresh: tokens.refresh_token,
440-
access: tokens.access_token,
441-
expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
442-
...(newAccountId && { accountId: newAccountId }),
443-
},
444-
})
445-
currentAuth.access = tokens.access_token
446-
authWithAccount.accountId = newAccountId
447+
if (!refreshPromise) {
448+
log.info("refreshing codex access token")
449+
refreshPromise = refreshAccessToken(currentAuth.refresh, issuer)
450+
.then(async (tokens) => {
451+
const accountId = extractAccountId(tokens) || authWithAccount.accountId
452+
await input.client.auth.set({
453+
path: { id: "openai" },
454+
body: {
455+
type: "oauth",
456+
refresh: tokens.refresh_token,
457+
access: tokens.access_token,
458+
expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
459+
...(accountId && { accountId }),
460+
},
461+
})
462+
return {
463+
access: tokens.access_token,
464+
accountId,
465+
}
466+
})
467+
.finally(() => {
468+
refreshPromise = undefined
469+
})
470+
}
471+
472+
const refreshed = await refreshPromise
473+
currentAuth.access = refreshed.access
474+
authWithAccount.accountId = refreshed.accountId
447475
}
448476

449477
// Build headers
@@ -477,7 +505,7 @@ export async function CodexAuthPlugin(input: PluginInput): Promise<Hooks> {
477505
: new URL(typeof requestInput === "string" ? requestInput : requestInput.url)
478506
const url =
479507
parsed.pathname.includes("/v1/responses") || parsed.pathname.includes("/chat/completions")
480-
? new URL(CODEX_API_ENDPOINT)
508+
? new URL(codexApiEndpoint)
481509
: parsed
482510

483511
return fetch(url, {

‎packages/opencode/test/plugin/codex.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, test } from "bun:test"
22
import {
3+
CodexAuthPlugin,
34
parseJwtClaims,
45
extractAccountIdFromClaims,
56
extractAccountId,
@@ -120,4 +121,109 @@ describe("plugin.codex", () => {
120121
).toBe("acc-123")
121122
})
122123
})
124+
125+
test("deduplicates concurrent Codex token refreshes", async () => {
126+
let auth = {
127+
type: "oauth" as const,
128+
refresh: "refresh-old",
129+
access: "",
130+
expires: 0,
131+
}
132+
const authUpdates: Array<{
133+
body: { refresh: string; access: string; expires: number; accountId?: string }
134+
}> = []
135+
let resolveRefresh: (() => void) | undefined
136+
const refreshReady = new Promise<void>((resolve) => {
137+
resolveRefresh = resolve
138+
})
139+
let refreshRequests = 0
140+
const apiRequests: { authorization: string | null; accountId: string | null }[] = []
141+
142+
using server = Bun.serve({
143+
port: 0,
144+
async fetch(request) {
145+
const url = new URL(request.url)
146+
if (url.pathname === "/oauth/token") {
147+
expect(await request.text()).toContain("refresh_token=refresh-old")
148+
refreshRequests += 1
149+
await refreshReady
150+
return Response.json({
151+
id_token: createTestJwt({ chatgpt_account_id: "acc-123" }),
152+
access_token: "access-new",
153+
refresh_token: "refresh-new",
154+
expires_in: 3600,
155+
})
156+
}
157+
158+
if (url.pathname === "/backend-api/codex/responses") {
159+
apiRequests.push({
160+
authorization: request.headers.get("authorization"),
161+
accountId: request.headers.get("ChatGPT-Account-Id"),
162+
})
163+
return new Response("{}", { status: 200 })
164+
}
165+
166+
return new Response("unexpected request", { status: 500 })
167+
},
168+
})
169+
170+
const hooks = await CodexAuthPlugin(
171+
{
172+
client: {
173+
auth: {
174+
async set(input: { body: { refresh: string; access: string; expires: number; accountId?: string } }) {
175+
authUpdates.push(input)
176+
auth = {
177+
type: "oauth",
178+
refresh: input.body.refresh,
179+
access: input.body.access,
180+
expires: input.body.expires,
181+
...(input.body.accountId && { accountId: input.body.accountId }),
182+
}
183+
},
184+
},
185+
} as never,
186+
project: {} as never,
187+
directory: "",
188+
worktree: "",
189+
experimental_workspace: {
190+
register() {},
191+
},
192+
serverUrl: new URL("https://example.com"),
193+
$: {} as never,
194+
},
195+
{
196+
issuer: server.url.origin,
197+
codexApiEndpoint: new URL("/backend-api/codex/responses", server.url).toString(),
198+
},
199+
)
200+
const loaded = await hooks.auth!.loader!(async () => auth as never, {} as never)
201+
202+
const first = loaded.fetch!("https://api.openai.com/v1/responses")
203+
const second = loaded.fetch!("https://api.openai.com/v1/responses")
204+
205+
await waitFor(() => refreshRequests === 1)
206+
expect(apiRequests).toHaveLength(0)
207+
208+
resolveRefresh!()
209+
await Promise.all([first, second])
210+
211+
expect(refreshRequests).toBe(1)
212+
expect(authUpdates).toHaveLength(1)
213+
expect(authUpdates[0]?.body.refresh).toBe("refresh-new")
214+
expect(authUpdates[0]?.body.access).toBe("access-new")
215+
expect(authUpdates[0]?.body.accountId).toBe("acc-123")
216+
expect(apiRequests).toEqual([
217+
{ authorization: "Bearer access-new", accountId: "acc-123" },
218+
{ authorization: "Bearer access-new", accountId: "acc-123" },
219+
])
220+
})
123221
})
222+
223+
async function waitFor(predicate: () => boolean) {
224+
const started = Date.now()
225+
while (!predicate()) {
226+
if (Date.now() - started > 1_000) throw new Error("timed out waiting for condition")
227+
await new Promise((resolve) => setTimeout(resolve, 1))
228+
}
229+
}

0 commit comments

Comments
 (0)