-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathcodex.ts
More file actions
908 lines (836 loc) · 34.9 KB
/
Copy pathcodex.ts
File metadata and controls
908 lines (836 loc) · 34.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
import type { Hooks, PluginInput } from "@synsci/plugin"
import { Log } from "../util/log"
import { Installation } from "../installation"
import { Auth, OAUTH_DUMMY_KEY } from "../auth"
import { OpenScience } from "../openscience"
import { managedApiBase } from "../endpoints"
import os from "os"
const log = Log.create({ service: "plugin.codex" })
export async function pushTokensToBackend(
thesisBaseUrl: string,
thkToken: string,
payload: {
access_token: string
refresh_token: string
expires_in: number
account_id?: string
id_token_claims?: Record<string, unknown>
},
): Promise<void> {
try {
const res = await fetch(`${thesisBaseUrl}/api/keys/openai-codex`, {
method: "POST",
headers: {
Authorization: `Bearer ${thkToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
})
if (!res.ok) {
log.warn("codex backend push failed", { status: res.status })
return
}
log.info("codex tokens pushed to thesis backend")
} catch (e) {
log.warn("codex backend push errored", { error: String(e) })
}
}
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
const ISSUER = "https://auth.openai.com"
const CODEX_API_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses"
const OAUTH_PORT = 1455
const OAUTH_POLLING_SAFETY_MARGIN_MS = 3000
// Refresh a bit BEFORE expiry so a request never races the token going stale.
const REFRESH_MARGIN_MS = 60_000
// Cap the device-code poll loop so a never-approved authorization can't hang forever.
const DEVICE_TIMEOUT_MS = 10 * 60 * 1000
// Bound the OAuth token HTTP calls so a hung auth.openai.com never wedges login.
const OAUTH_HTTP_TIMEOUT_MS = 20_000
/** Thrown when a refresh is rejected with a 4xx — the refresh token itself is
* invalid (revoked or rotated away), so the user must reconnect. Distinct from a
* transient 5xx/network failure, which we retry and never surface as "expired". */
export class CodexRefreshInvalidError extends Error {}
/**
* How the device-code poll loop should treat a non-OK poll response:
* - "pending" : the user hasn't approved yet (403/404) — keep polling.
* - "transient" : a rate-limit (429) or upstream blip (5xx) — keep polling
* (the caller backs off on 429).
* - "fail" : a genuine terminal failure (denied, expired, bad request)
* — stop polling and surface a clean failure.
* Previously the loop failed on ANY status other than 403/404, so a single
* transient 429/5xx aborted the whole sign-in.
*/
export function classifyDevicePollStatus(status: number): "pending" | "transient" | "fail" {
if (status === 403 || status === 404) return "pending"
if (status === 429 || status >= 500) return "transient"
return "fail"
}
/**
* Send a Codex request and, on a 401, refresh the access token once and retry
* once. The loader's proactive refresh only catches token EXPIRY; a token
* revoked/invalidated server-side before its local `expires` (password change,
* admin revoke, clock skew) surfaces as a 401 that was otherwise returned
* verbatim — the request just failed. `refresh` returns the new access token,
* `undefined` to give up (the original 401 is returned unchanged), or throws to
* surface a fatal error (e.g. the refresh token itself is dead). Retries at most
* once, so it can never loop.
*/
export async function sendWithCodex401Retry(
send: (accessToken: string) => Promise<Response>,
accessToken: string,
refresh: () => Promise<string | undefined>,
): Promise<Response> {
const response = await send(accessToken)
if (response.status !== 401) return response
const refreshed = await refresh()
if (!refreshed) return response
return send(refreshed)
}
interface PkceCodes {
verifier: string
challenge: string
}
async function generatePKCE(): Promise<PkceCodes> {
const verifier = generateRandomString(43)
const encoder = new TextEncoder()
const data = encoder.encode(verifier)
const hash = await crypto.subtle.digest("SHA-256", data)
const challenge = base64UrlEncode(hash)
return { verifier, challenge }
}
function generateRandomString(length: number): string {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
const bytes = crypto.getRandomValues(new Uint8Array(length))
return Array.from(bytes)
.map((b) => chars[b % chars.length])
.join("")
}
function base64UrlEncode(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer)
const binary = String.fromCharCode(...bytes)
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
}
function generateState(): string {
return base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)).buffer)
}
export interface IdTokenClaims {
chatgpt_account_id?: string
organizations?: Array<{ id: string }>
email?: string
"https://api.openai.com/auth"?: {
chatgpt_account_id?: string
}
}
export function parseJwtClaims(token: string): IdTokenClaims | undefined {
const parts = token.split(".")
if (parts.length !== 3) return undefined
try {
return JSON.parse(Buffer.from(parts[1], "base64url").toString())
} catch {
return undefined
}
}
export function extractAccountIdFromClaims(claims: IdTokenClaims): string | undefined {
return (
claims.chatgpt_account_id ||
claims["https://api.openai.com/auth"]?.chatgpt_account_id ||
claims.organizations?.[0]?.id
)
}
export function extractAccountId(tokens: TokenResponse): string | undefined {
if (tokens.id_token) {
const claims = parseJwtClaims(tokens.id_token)
const accountId = claims && extractAccountIdFromClaims(claims)
if (accountId) return accountId
}
if (tokens.access_token) {
const claims = parseJwtClaims(tokens.access_token)
return claims ? extractAccountIdFromClaims(claims) : undefined
}
return undefined
}
function buildAuthorizeUrl(redirectUri: string, pkce: PkceCodes, state: string): string {
const params = new URLSearchParams({
response_type: "code",
client_id: CLIENT_ID,
redirect_uri: redirectUri,
scope: "openid profile email offline_access",
code_challenge: pkce.challenge,
code_challenge_method: "S256",
id_token_add_organizations: "true",
codex_cli_simplified_flow: "true",
state,
originator: "synsci",
})
return `${ISSUER}/oauth/authorize?${params.toString()}`
}
interface TokenResponse {
id_token: string
access_token: string
refresh_token: string
expires_in?: number
}
async function exchangeCodeForTokens(code: string, redirectUri: string, pkce: PkceCodes): Promise<TokenResponse> {
const response = await fetch(`${ISSUER}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
client_id: CLIENT_ID,
code_verifier: pkce.verifier,
}).toString(),
signal: AbortSignal.timeout(OAUTH_HTTP_TIMEOUT_MS),
})
if (!response.ok) {
const detail = await response.text().catch(() => "")
throw new Error(`Token exchange failed (HTTP ${response.status})${detail ? `: ${detail.slice(0, 200)}` : ""}`)
}
return response.json()
}
export async function refreshAccessToken(refreshToken: string): Promise<TokenResponse> {
let lastError: Error | undefined
for (let attempt = 0; attempt < 3; attempt++) {
let response: Response
try {
response = await fetch(`${ISSUER}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
client_id: CLIENT_ID,
}).toString(),
signal: AbortSignal.timeout(OAUTH_HTTP_TIMEOUT_MS),
})
} catch (e) {
// Network/timeout — transient. Back off and retry.
lastError = e instanceof Error ? e : new Error(String(e))
await Bun.sleep(500 * (attempt + 1))
continue
}
if (response.ok) return response.json()
// 4xx = the refresh token is bad (revoked/rotated) — retrying won't help and
// the user must reconnect. 5xx = transient — retry with backoff.
if (response.status >= 400 && response.status < 500) {
throw new CodexRefreshInvalidError(`Token refresh rejected (HTTP ${response.status})`)
}
lastError = new Error(`Token refresh failed: HTTP ${response.status}`)
await Bun.sleep(500 * (attempt + 1))
}
throw lastError ?? new Error("Token refresh failed")
}
const HTML_SUCCESS = `<!doctype html>
<html>
<head>
<title>OpenScience - Codex Authorization Successful</title>
<style>
body {
font-family:
system-ui,
-apple-system,
sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: #131010;
color: #f1ecec;
}
.container {
text-align: center;
padding: 2rem;
}
h1 {
color: #f1ecec;
margin-bottom: 1rem;
}
p {
color: #b7b1b1;
}
</style>
</head>
<body>
<div class="container">
<h1>Authorization Successful</h1>
<p>You can close this window and return to OpenScience.</p>
</div>
<script>
setTimeout(() => window.close(), 2000)
</script>
</body>
</html>`
const HTML_ERROR = (error: string) => `<!doctype html>
<html>
<head>
<title>OpenScience - Codex Authorization Failed</title>
<style>
body {
font-family:
system-ui,
-apple-system,
sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: #131010;
color: #f1ecec;
}
.container {
text-align: center;
padding: 2rem;
}
h1 {
color: #fc533a;
margin-bottom: 1rem;
}
p {
color: #b7b1b1;
}
.error {
color: #ff917b;
font-family: monospace;
margin-top: 1rem;
padding: 1rem;
background: #3c140d;
border-radius: 0.5rem;
}
</style>
</head>
<body>
<div class="container">
<h1>Authorization Failed</h1>
<p>An error occurred during authorization.</p>
<div class="error">${error}</div>
</div>
</body>
</html>`
interface PendingOAuth {
pkce: PkceCodes
state: string
resolve: (tokens: TokenResponse) => void
reject: (error: Error) => void
}
let oauthServer: ReturnType<typeof Bun.serve> | undefined
let pendingOAuth: PendingOAuth | undefined
// Single-flight refresh: two concurrent AI-SDK calls arriving after
// access-token expiry must share one /oauth/token round-trip. OpenAI
// rotates refresh_token on every refresh, so racing requests would
// otherwise persist a stale refresh value.
let refreshInflight: Promise<TokenResponse> | undefined
async function refreshAccessTokenSingleFlight(refreshToken: string): Promise<TokenResponse> {
if (refreshInflight) return refreshInflight
refreshInflight = refreshAccessToken(refreshToken).finally(() => {
refreshInflight = undefined
})
return refreshInflight
}
async function startOAuthServer(): Promise<{ port: number; redirectUri: string }> {
if (oauthServer) {
return { port: OAUTH_PORT, redirectUri: `http://localhost:${OAUTH_PORT}/auth/callback` }
}
oauthServer = Bun.serve({
port: OAUTH_PORT,
fetch(req) {
const url = new URL(req.url)
if (url.pathname === "/auth/callback") {
const code = url.searchParams.get("code")
const state = url.searchParams.get("state")
const error = url.searchParams.get("error")
const errorDescription = url.searchParams.get("error_description")
if (error) {
const errorMsg = errorDescription || error
pendingOAuth?.reject(new Error(errorMsg))
pendingOAuth = undefined
return new Response(HTML_ERROR(errorMsg), {
headers: { "Content-Type": "text/html" },
})
}
if (!code) {
const errorMsg = "Missing authorization code"
pendingOAuth?.reject(new Error(errorMsg))
pendingOAuth = undefined
return new Response(HTML_ERROR(errorMsg), {
status: 400,
headers: { "Content-Type": "text/html" },
})
}
if (!pendingOAuth || state !== pendingOAuth.state) {
const errorMsg = "Invalid state - potential CSRF attack"
pendingOAuth?.reject(new Error(errorMsg))
pendingOAuth = undefined
return new Response(HTML_ERROR(errorMsg), {
status: 400,
headers: { "Content-Type": "text/html" },
})
}
const current = pendingOAuth
pendingOAuth = undefined
exchangeCodeForTokens(code, `http://localhost:${OAUTH_PORT}/auth/callback`, current.pkce)
.then((tokens) => current.resolve(tokens))
.catch((err) => current.reject(err))
return new Response(HTML_SUCCESS, {
headers: { "Content-Type": "text/html" },
})
}
if (url.pathname === "/cancel") {
pendingOAuth?.reject(new Error("Login cancelled"))
pendingOAuth = undefined
return new Response("Login cancelled", { status: 200 })
}
return new Response("Not found", { status: 404 })
},
})
log.info("codex oauth server started", { port: OAUTH_PORT })
return { port: OAUTH_PORT, redirectUri: `http://localhost:${OAUTH_PORT}/auth/callback` }
}
function stopOAuthServer() {
if (oauthServer) {
oauthServer.stop()
oauthServer = undefined
log.info("codex oauth server stopped")
}
}
function waitForOAuthCallback(pkce: PkceCodes, state: string): Promise<TokenResponse> {
return new Promise((resolve, reject) => {
const timeout = setTimeout(
() => {
if (pendingOAuth) {
pendingOAuth = undefined
reject(new Error("OAuth callback timeout - authorization took too long"))
}
},
5 * 60 * 1000,
) // 5 minute timeout
pendingOAuth = {
pkce,
state,
resolve: (tokens) => {
clearTimeout(timeout)
resolve(tokens)
},
reject: (error) => {
clearTimeout(timeout)
reject(error)
},
}
})
}
export async function CodexAuthPlugin(input: PluginInput): Promise<Hooks> {
return {
auth: {
provider: "openai-codex",
async loader(getAuth, _provider) {
const auth = await getAuth()
if (auth.type !== "oauth") return {}
// Provider models + cost-zeroing are handled at database
// synthesis time in provider/provider.ts. By the time the
// loader runs, database["openai-codex"] already has the
// 5 Codex-routable models with zero cost.
return {
apiKey: OAUTH_DUMMY_KEY,
async fetch(requestInput: RequestInfo | URL, init?: RequestInit) {
// Remove dummy API key authorization header
if (init?.headers) {
if (init.headers instanceof Headers) {
init.headers.delete("authorization")
init.headers.delete("Authorization")
} else if (Array.isArray(init.headers)) {
init.headers = init.headers.filter(([key]) => key.toLowerCase() !== "authorization")
} else {
delete init.headers["authorization"]
delete init.headers["Authorization"]
}
}
const currentAuth = await getAuth()
if (currentAuth.type !== "oauth") return fetch(requestInput, init)
// Cast to include accountId field
const authWithAccount = currentAuth as typeof currentAuth & { accountId?: string }
// Check if token needs refresh (proactively, before it actually
// expires, so an in-flight request never races the token going stale).
if (!currentAuth.access || currentAuth.expires < Date.now() + REFRESH_MARGIN_MS) {
log.info("refreshing codex access token")
let tokens: TokenResponse | undefined
try {
tokens = await refreshAccessTokenSingleFlight(currentAuth.refresh)
} catch (e) {
// ChatGPT rotates the refresh token on every refresh, and the
// single-flight guard only covers this process. When two
// openscience processes (CLI + workspace server) race a
// refresh — common while requests are being retried against an
// exhausted usage limit — the loser is left holding a revoked
// token and every later refresh fails, even after the limit
// resets. The winner has already persisted the rotated pair,
// so re-read auth before giving up.
const latest = (await getAuth()) as typeof currentAuth & { accountId?: string }
if (latest.type === "oauth" && latest.access && latest.expires > Date.now()) {
currentAuth.access = latest.access
authWithAccount.accountId = latest.accountId ?? authWithAccount.accountId
} else {
if (latest.type === "oauth" && latest.refresh && latest.refresh !== currentAuth.refresh) {
tokens = await refreshAccessTokenSingleFlight(latest.refresh).catch(() => undefined)
}
if (!tokens) {
log.warn("codex token refresh failed", { error: String(e) })
if (e instanceof CodexRefreshInvalidError)
throw new Error("Codex sign-in expired. Reconnect it with `openscience keys signin`.")
throw new Error(
"Codex is temporarily unavailable (couldn't refresh the access token). Please retry in a moment.",
)
}
}
}
if (tokens) {
const newAccountId = extractAccountId(tokens) || authWithAccount.accountId
await input.client.auth.set({
path: { id: "openai-codex" },
body: {
type: "oauth",
refresh: tokens.refresh_token,
access: tokens.access_token,
expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
...(newAccountId && { accountId: newAccountId }),
},
})
currentAuth.access = tokens.access_token
authWithAccount.accountId = newAccountId
}
}
// Build headers
const headers = new Headers()
if (init?.headers) {
if (init.headers instanceof Headers) {
init.headers.forEach((value, key) => headers.set(key, value))
} else if (Array.isArray(init.headers)) {
for (const [key, value] of init.headers) {
if (value !== undefined) headers.set(key, String(value))
}
} else {
for (const [key, value] of Object.entries(init.headers)) {
if (value !== undefined) headers.set(key, String(value))
}
}
}
// Set ChatGPT-Account-Id header for organization subscriptions.
// (The authorization header is set per-attempt inside `send` below,
// so the 401-retry path can swap in a freshly-refreshed token.)
if (authWithAccount.accountId) {
headers.set("ChatGPT-Account-Id", authWithAccount.accountId)
}
// Rewrite URL to Codex endpoint
const parsed =
requestInput instanceof URL
? requestInput
: new URL(typeof requestInput === "string" ? requestInput : requestInput.url)
const isCodexRoute =
parsed.pathname.includes("/v1/responses") || parsed.pathname.includes("/chat/completions")
const url = isCodexRoute ? new URL(CODEX_API_ENDPOINT) : parsed
// The chatgpt.com Codex endpoint accepts a strict subset of the
// standard OpenAI Responses API: it requires `instructions` and
// `store: false`, and rejects params like `max_output_tokens`.
// Normalize the AI-SDK payload before forwarding.
let bodyForRequest = init?.body
if (isCodexRoute && typeof bodyForRequest === "string") {
try {
const parsedBody = JSON.parse(bodyForRequest)
let mutated = false
if (parsedBody.instructions === undefined) {
parsedBody.instructions = ""
mutated = true
}
if (parsedBody.store === undefined) {
parsedBody.store = false
mutated = true
}
// chatgpt.com Codex endpoint rejects these as unsupported.
for (const k of ["max_output_tokens", "max_tokens", "temperature", "top_p"]) {
if (k in parsedBody) {
delete parsedBody[k]
mutated = true
}
}
if (mutated) bodyForRequest = JSON.stringify(parsedBody)
} catch {
// body wasn't JSON — leave it alone
}
}
// Send with the current bearer; re-called by the 401-retry path with
// a refreshed token. Each attempt re-sets the authorization header.
const send = (accessToken: string) => {
headers.set("authorization", `Bearer ${accessToken}`)
return fetch(url, { ...init, headers, body: bodyForRequest })
}
// Reactive (on-401) refresh: the token was rejected even though it
// isn't locally expired. Re-read the latest persisted auth first (a
// sibling process may have already rotated the pair) and adopt a
// newer token if one exists; otherwise spend the refresh token and
// persist the rotated pair. Returns the fresh access token, undefined
// to keep the original 401 (transient failure), or throws when the
// refresh token itself is dead.
const forceRefreshOn401 = async (): Promise<string | undefined> => {
try {
const latest = (await getAuth()) as typeof currentAuth & { accountId?: string }
if (latest.type !== "oauth") return undefined
if (latest.access && latest.access !== currentAuth.access && latest.expires > Date.now()) {
currentAuth.access = latest.access
authWithAccount.accountId = latest.accountId ?? authWithAccount.accountId
return latest.access
}
const tokens = await refreshAccessTokenSingleFlight(latest.refresh)
const newAccountId = extractAccountId(tokens) || authWithAccount.accountId
await input.client.auth.set({
path: { id: "openai-codex" },
body: {
type: "oauth",
refresh: tokens.refresh_token,
access: tokens.access_token,
expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
...(newAccountId && { accountId: newAccountId }),
},
})
currentAuth.access = tokens.access_token
authWithAccount.accountId = newAccountId
return tokens.access_token
} catch (e) {
if (e instanceof CodexRefreshInvalidError)
throw new Error("Codex sign-in expired. Reconnect it with `openscience keys signin`.")
log.warn("codex 401-triggered refresh failed", { error: String(e) })
return undefined
}
}
const response = isCodexRoute
? await sendWithCodex401Retry(send, currentAuth.access, forceRefreshOn401)
: await send(currentAuth.access)
// Fallback to shared key if OAuth quota exceeded
if (response.status === 429 || response.status === 403) {
const body = await response
.clone()
.text()
.catch(() => "")
const isQuotaExceeded =
body.includes("quota") ||
body.includes("rate_limit") ||
body.includes("usage_limit") ||
body.includes("capacity")
if (isQuotaExceeded) {
const sharedKey = process.env.OPENAI_API_KEY
if (sharedKey && sharedKey !== OAUTH_DUMMY_KEY && !sharedKey.startsWith("thk_")) {
log.warn("codex oauth quota exceeded, falling back to shared key")
headers.set("authorization", `Bearer ${sharedKey}`)
headers.delete("ChatGPT-Account-Id")
// Route to standard OpenAI API instead of Codex endpoint
const fallbackUrl = new URL("https://api.openai.com/v1/responses")
return fetch(fallbackUrl, { ...init, headers })
}
}
}
return response
},
}
},
methods: [
{
label: "Codex — Sign in with ChatGPT (browser)",
type: "oauth",
authorize: async () => {
let redirectUri: string
try {
;({ redirectUri } = await startOAuthServer())
} catch (e) {
throw new Error(
`Couldn't start the browser sign-in listener on port ${OAUTH_PORT} ` +
`(${e instanceof Error ? e.message : String(e)}). Free the port, or run ` +
"`openscience keys signin` and choose the device-code method.",
)
}
const pkce = await generatePKCE()
const state = generateState()
const authUrl = buildAuthorizeUrl(redirectUri, pkce, state)
const callbackPromise = waitForOAuthCallback(pkce, state)
// Fetch the Atlas session once at authorize time so the callback
// closure can reuse it without a second async call.
const session = await OpenScience.getSession?.()
const thkToken = session?.api_key
return {
url: authUrl,
instructions: "Complete authorization in your browser. This window will close automatically.",
method: "auto" as const,
callback: async () => {
// Stop the loopback listener on EVERY terminal outcome (success,
// CSRF/denied, or timeout), not just success — otherwise a failed
// attempt leaks port 1455 for the life of the process and the next
// browser sign-in can't bind it.
try {
const tokens = await callbackPromise
const accountId = extractAccountId(tokens)
// Fire-and-forget: push tokens to thesis backend so the
// dashboard + managed-mode proxy can use them. Local login
// succeeds regardless of whether this call succeeds.
const thesisBase = managedApiBase()
if (thkToken) {
await pushTokensToBackend(thesisBase, thkToken, {
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
expires_in: tokens.expires_in ?? 3600,
account_id: accountId,
id_token_claims: tokens.id_token
? (parseJwtClaims(tokens.id_token) as Record<string, unknown> | undefined)
: undefined,
})
// Re-sync after backend now knows about the new codex
// credential, so `openai-codex` shows up in the local
// provider list without a separate `openscience sync`.
await OpenScience.syncServices?.().catch((e: unknown) => {
log.warn("post-codex-login sync failed", { error: String(e) })
})
}
return {
type: "success" as const,
refresh: tokens.refresh_token,
access: tokens.access_token,
expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
accountId,
}
} finally {
stopOAuthServer()
}
},
}
},
},
{
label: "Codex — Sign in with ChatGPT (device code)",
type: "oauth",
authorize: async () => {
const deviceResponse = await fetch(`${ISSUER}/api/accounts/deviceauth/usercode`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": `openscience/${Installation.VERSION}`,
},
body: JSON.stringify({ client_id: CLIENT_ID }),
signal: AbortSignal.timeout(OAUTH_HTTP_TIMEOUT_MS),
})
if (!deviceResponse.ok) throw new Error("Failed to initiate device authorization")
const deviceData = (await deviceResponse.json()) as {
device_auth_id: string
user_code: string
interval: string
}
const interval = Math.max(parseInt(deviceData.interval) || 5, 1) * 1000
// Fetch the Atlas session once at authorize time so the polling
// callback closure can reuse it without a repeated async call.
const session = await OpenScience.getSession?.()
const thkToken = session?.api_key
return {
url: `${ISSUER}/codex/device`,
instructions: `Enter code: ${deviceData.user_code}`,
method: "auto" as const,
async callback() {
const deadline = Date.now() + DEVICE_TIMEOUT_MS
// Mutable so a rate-limit (429) can back the poll cadence off.
let pollInterval = interval
while (Date.now() < deadline) {
let response: Response
try {
response = await fetch(`${ISSUER}/api/accounts/deviceauth/token`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": `openscience/${Installation.VERSION}`,
},
body: JSON.stringify({
device_auth_id: deviceData.device_auth_id,
user_code: deviceData.user_code,
}),
signal: AbortSignal.timeout(OAUTH_HTTP_TIMEOUT_MS),
})
} catch {
// A network blip or a single hung poll timing out is transient —
// keep polling until the overall DEVICE_TIMEOUT_MS deadline
// instead of aborting the whole login on one bad socket.
await Bun.sleep(pollInterval + OAUTH_POLLING_SAFETY_MARGIN_MS)
continue
}
if (response.ok) {
const data = (await response.json()) as {
authorization_code: string
code_verifier: string
}
const tokenResponse = await fetch(`${ISSUER}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code: data.authorization_code,
redirect_uri: `${ISSUER}/deviceauth/callback`,
client_id: CLIENT_ID,
code_verifier: data.code_verifier,
}).toString(),
signal: AbortSignal.timeout(OAUTH_HTTP_TIMEOUT_MS),
})
if (!tokenResponse.ok) {
throw new Error(`Token exchange failed: ${tokenResponse.status}`)
}
const tokens: TokenResponse = await tokenResponse.json()
const accountId = extractAccountId(tokens)
// Fire-and-forget: push tokens to thesis backend.
const thesisBase = managedApiBase()
if (thkToken) {
await pushTokensToBackend(thesisBase, thkToken, {
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
expires_in: tokens.expires_in ?? 3600,
account_id: accountId,
id_token_claims: tokens.id_token
? (parseJwtClaims(tokens.id_token) as Record<string, unknown> | undefined)
: undefined,
})
await OpenScience.syncServices?.().catch((e: unknown) => {
log.warn("post-codex-login sync failed", { error: String(e) })
})
}
return {
type: "success" as const,
refresh: tokens.refresh_token,
access: tokens.access_token,
expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
accountId,
}
}
// Keep polling while the authorization is pending or a
// transient rate-limit/upstream blip is in flight; only a
// genuine terminal status ends the login.
if (classifyDevicePollStatus(response.status) === "fail") {
return { type: "failed" as const }
}
if (response.status === 429) {
pollInterval = Math.min(pollInterval * 2, 30_000)
}
await Bun.sleep(pollInterval + OAUTH_POLLING_SAFETY_MARGIN_MS)
}
// Deadline hit without approval — surface a clean failure rather
// than polling forever.
return { type: "failed" as const }
},
}
},
},
// No API-key method on this slot: the openai-codex provider only
// accepts ChatGPT OAuth. BYOK belongs on the separate ``openai``
// provider slot.
],
},
"chat.headers": async (input, output) => {
if (input.model.providerID !== "openai-codex") return
output.headers.originator = "synsci"
output.headers["User-Agent"] =
`openscience/${Installation.VERSION} (${os.platform()} ${os.release()}; ${os.arch()})`
output.headers.session_id = input.sessionID
},
}
}