Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexChatGptAuth.ts

1,013 lines41.8 KB

1// @effect-diagnostics nodeBuiltinImport:off - OAuth loopback listener and PKCE use Node APIs.
2import * as NodeCrypto from "node:crypto";
3import * as NodeHttp from "node:http";
4import { createRemoteJWKSet, jwtVerify } from "jose";
5import {
6 ProviderSetupError,
7 type ChatGptReconnectProfile,
8 type ChatGptTransferredProfile,
9 type ProviderInstanceId,
10} from "@t3tools/contracts";
11import { codexCallbackUrl } from "@t3tools/shared/codexAuthHandoff";
12import { hashTelemetryId } from "@t3tools/shared/telemetryId";
13import * as Clock from "effect/Clock";
14import * as Cause from "effect/Cause";
15import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
16import { openAiUserId } from "../telemetry/Identify.ts";
17import * as Crypto from "effect/Crypto";
18import * as Hex from "effect/encoding/Hex";
19import * as Exit from "effect/Exit";
20import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts";
21import * as Effect from "effect/Effect";
22import * as Option from "effect/Option";
23import * as Schema from "effect/Schema";
24import * as Semaphore from "effect/Semaphore";
25import * as ProviderAuthFlow from "@t3tools/provider-core/server/providerAuthFlow";
26import type { ProviderAuthFlowContext } from "@t3tools/provider-core/server/providerAuthFlow";
27import { HttpClient, HttpClientRequest } from "effect/http";
28import * as ProviderCredentialStore from "./ProviderCredentialStore.ts";
29import { withChatGptSessionLock } from "./CodexChatGptSessionLock.ts";
30import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
31import * as ServerSettings from "../serverSettings.ts";
32import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
33​
34const isSetupError = Schema.is(ProviderSetupError);
35const RESOURCE = "https://api.openai.com/v1";
36const REQUIRED_SCOPE = "chatgpt.tokens.use.direct";
37const DISCOVERY = "https://auth.openai.com/.well-known/openid-configuration";
38const TokenResponse = Schema.Struct({
39 access_token: Schema.NonEmptyString,
40 refresh_token: Schema.optionalKey(Schema.NonEmptyString),
41 id_token: Schema.optionalKey(Schema.String),
42 token_type: Schema.String,
43 expires_in: Schema.Int.check(Schema.isGreaterThan(0)),
44 scope: Schema.String,
45 earliest_refresh_at: Schema.optionalKey(Schema.Union([Schema.Finite, Schema.String])),
46});
47const Record = Schema.Struct({
48 clientId: Schema.String,
49 accessToken: Schema.String,
50 refreshToken: Schema.NullOr(Schema.String),
51 expiresAt: Schema.Finite,
52 earliestRefreshAt: Schema.NullOr(Schema.Finite),
53 scopes: Schema.Array(Schema.String),
54 subject: Schema.String,
55 email: Schema.NullOr(Schema.String),
56 idToken: Schema.optionalKey(Schema.String),
57 issuer: Schema.optionalKey(Schema.String),
58});
59export type CodexChatGptCredentials = typeof Record.Type;
60const Sessions = Schema.Struct({
61 activeClientId: Schema.NullOr(Schema.String),
62 sessions: Schema.Array(Record),
63});
64const sessionLocks = new WeakMap<
65 typeof ServerSecretStore.ServerSecretStore.Service,
66 Map<string, Semaphore.Semaphore>
67>();
68const Registration = Schema.Struct({
69 clientId: Schema.String.check(Schema.isPattern(/^oaiapp_/u)),
70 subject: Schema.optionalKey(Schema.String),
71 connectionLabel: Schema.optionalKey(Schema.String),
72 sharingEnabled: Schema.optionalKey(Schema.Boolean),
73 email: Schema.optionalKey(Schema.NullOr(Schema.String)),
74 redirectUri: Schema.optionalKey(
75 Schema.String.check(
76 Schema.isPattern(/^http:\/\/(?:127\.0\.0\.1|localhost):[1-9]\d{0,4}\/auth\/callback$/u),
77 ),
78 ),
79});
80const RegistrationProfiles = Schema.Struct({
81 profiles: Schema.Array(Registration),
82 lastClientId: Schema.NullOr(Schema.String),
83});
84const decodeRegistration = Schema.decodeUnknownEffect(
85 Schema.fromJsonString(Schema.Union([RegistrationProfiles, Registration])),
86);
87const encodeRegistration = Schema.encodeEffect(Schema.fromJsonString(RegistrationProfiles));
88const profileMethodId = (clientId: string) => `chatgpt-profile:${clientId}`;
89const Discovery = Schema.Struct({
90 issuer: Schema.String,
91 authorization_endpoint: Schema.String,
92 token_endpoint: Schema.String,
93 jwks_uri: Schema.String,
94 revocation_endpoint: Schema.optionalKey(Schema.String),
95});
96const OAuthError = Schema.Struct({ error: Schema.String });
97const decodeSessions = Schema.decodeUnknownEffect(
98 Schema.fromJsonString(Schema.Union([Sessions, Record])),
99);
100const encodeSessions = Schema.encodeEffect(Schema.fromJsonString(Sessions));
101const decodeTokens = Schema.decodeUnknownSync(TokenResponse);
102const decodeDiscoveryEffect = Schema.decodeUnknownEffect(Discovery);
103const decodeOAuthError = Schema.decodeUnknownSync(OAuthError);
104​
105export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* (options: {
106 readonly instanceId: ProviderInstanceId;
107 readonly discoveryUrl?: string;
108 readonly resource?: string;
109 readonly defaultReturnUrl?: string;
110 readonly reconnectProfile?: ChatGptReconnectProfile | null;
111 readonly telemetryFlow?: "direct" | "primary_handoff";
112 readonly expectedProfileKey?: string;
113}) {
114 const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
115 const settings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
116 const track = Effect.fn("CodexChatGptAuth.track")(function* <A, E extends ProviderSetupError, R>(
117 event: "auth" | "transfer",
118 properties: Readonly<Record<string, string>>,
119 task: Effect.Effect<A, E, R>,
120 expiresAt?: number,
121 ) {
122 if (Option.isNone(analytics)) return yield* task;
123 const record = (name: string, properties: Readonly<Record<string, unknown>>) =>
124 analytics.value.record(name, properties).pipe(Effect.ignoreCause);
125 const startedAt = yield* Clock.currentTimeMillis;
126 yield* record(`chatgpt.${event}.started`, properties);
127 return yield* task.pipe(
128 Effect.onExit((result) =>
129 Effect.gen(function* () {
130 const endedAt = yield* Clock.currentTimeMillis;
131 const error = Exit.isFailure(result)
132 ? Cause.findErrorOption(result.cause)
133 : Option.none();
134 const counts =
135 Exit.isSuccess(result) &&
136 (event === "transfer" || options.telemetryFlow !== "primary_handoff")
137 ? yield* accountCounts.pipe(Effect.catchCause(() => Effect.succeed({})))
138 : {};
139 yield* record(`chatgpt.${event}.completed`, {
140 ...counts,
141 ...properties,
142 outcome: Exit.isSuccess(result)
143 ? "succeeded"
144 : Cause.hasInterruptsOnly(result.cause)
145 ? expiresAt !== undefined && endedAt >= expiresAt
146 ? "expired"
147 : "cancelled"
148 : "failed",
149 durationMs: Math.max(0, endedAt - startedAt),
150 ...(Option.isSome(error) && isSetupError(error.value)
151 ? { failureStage: error.value.operation }
152 : {}),
153 });
154 }),
155 ),
156 );
157 });
158 const http = yield* HttpClient.HttpClient;
159 const store = yield* ProviderCredentialStore.make("codex-chatgpt", options.instanceId);
160 const registrationStore = yield* ProviderCredentialStore.make(
161 "codex-chatgpt-registration",
162 options.instanceId,
163 );
164 const secrets = yield* ServerSecretStore.ServerSecretStore;
165 const crypto = yield* Crypto.Crypto;
166 const environmentLocks = sessionLocks.get(secrets) ?? new Map<string, Semaphore.Semaphore>();
167 sessionLocks.set(secrets, environmentLocks);
168 const lock = environmentLocks.get(store.binding.key) ?? (yield* Semaphore.make(1));
169 environmentLocks.set(store.binding.key, lock);
170 const withSessionLock = <A, E, R>(task: Effect.Effect<A, E, R>) =>
171 withChatGptSessionLock(secrets.directory, store.binding.key, options.instanceId, task);
172 const environment = yield* ServerEnvironment.ServerEnvironmentIdentity;
173 const hostId = `urn:uuid:${yield* environment.getEnvironmentId}`;
174 const resource = options.resource ?? RESOURCE;
175 const failure = (operation: string, detail: string) =>
176 new ProviderSetupError({ instanceId: options.instanceId, operation, detail });
177 let metadata: typeof Discovery.Type | undefined;
178 let jwks: ReturnType<typeof createRemoteJWKSet> | undefined;
179 const discover = Effect.gen(function* () {
180 if (metadata) return metadata;
181 const result = yield* http.get(options.discoveryUrl ?? DISCOVERY).pipe(
182 Effect.flatMap((response) =>
183 Effect.gen(function* () {
184 if (response.status < 200 || response.status >= 300)
185 return yield* failure("discover", "Could not reach ChatGPT sign-in. Try again.");
186 return yield* response.json;
187 }),
188 ),
189 Effect.flatMap(decodeDiscoveryEffect),
190 Effect.mapError(() => failure("discover", "Could not reach ChatGPT sign-in. Try again.")),
191 );
192 if (
193 !options.discoveryUrl &&
194 (result.issuer !== "https://auth.openai.com" ||
195 [
196 result.authorization_endpoint,
197 result.token_endpoint,
198 result.jwks_uri,
199 ...(result.revocation_endpoint ? [result.revocation_endpoint] : []),
200 ].some((url) => new URL(url).origin !== result.issuer))
201 )
202 return yield* failure("discover", "ChatGPT sign-in configuration could not be verified.");
203 metadata = result;
204 jwks = createRemoteJWKSet(new URL(result.jwks_uri));
205 return result;
206 });
207 const readSessions = store.get.pipe(
208 Effect.mapError(() => failure("read", "Could not read the saved ChatGPT connection.")),
209 Effect.flatMap((bytes) =>
210 Option.isNone(bytes)
211 ? Effect.succeed<typeof Sessions.Type>({ activeClientId: null, sessions: [] })
212 : decodeSessions(new TextDecoder().decode(bytes.value)).pipe(
213 Effect.map((saved) =>
214 "sessions" in saved ? saved : { activeClientId: saved.clientId, sessions: [saved] },
215 ),
216 Effect.mapError(() =>
217 failure("read", "The saved ChatGPT connection is invalid. Sign in again."),
218 ),
219 ),
220 ),
221 );
222 const read = readSessions.pipe(
223 Effect.map((saved) =>
224 Option.fromUndefinedOr(
225 saved.sessions.find((session) => session.clientId === saved.activeClientId),
226 ),
227 ),
228 // The OpenAI account is the person, so it marks who owns this install.
229 Effect.tap((credentials) => {
230 const userId = Option.flatMap(credentials, (saved) =>
231 Option.flatMap(Option.fromUndefinedOr(saved.idToken), openAiUserId),
232 );
233 return Option.isSome(userId) && Option.isSome(analytics)
234 ? analytics.value.recordOwners(
235 [{ source: "openai", ownerId: hashTelemetryId(userId.value) }],
236 "server",
237 )
238 : Effect.void;
239 }),
240 );
241 const writeSessions = (saved: typeof Sessions.Type) =>
242 encodeSessions(saved).pipe(
243 Effect.flatMap((json) => store.set(new TextEncoder().encode(json))),
244 Effect.mapError(() => failure("save", "Could not save the ChatGPT connection.")),
245 );
246 const readRegistrations = registrationStore.get.pipe(
247 Effect.mapError(() =>
248 failure("registration", "Could not read the ChatGPT sign-in registration. Try again."),
249 ),
250 Effect.flatMap((bytes) =>
251 Option.isNone(bytes)
252 ? Effect.succeed<typeof RegistrationProfiles.Type>({ profiles: [], lastClientId: null })
253 : decodeRegistration(new TextDecoder().decode(bytes.value)).pipe(
254 Effect.map((record) => {
255 const saved =
256 "profiles" in record
257 ? record
258 : { profiles: [record], lastClientId: record.clientId };
259 const last = saved.profiles.find(
260 (profile) => profile.clientId === saved.lastClientId,
261 );
262 const ordered = last
263 ? [last, ...saved.profiles.filter((profile) => profile.clientId !== last.clientId)]
264 : saved.profiles;
265 return {
266 ...saved,
267 profiles: ordered.map((profile) => ({
268 ...profile,
269 connectionLabel:
270 profile.connectionLabel ?? `Connection ${saved.profiles.indexOf(profile) + 1}`,
271 })),
272 };
273 }),
274 Effect.mapError(() =>
275 failure("registration", "The saved ChatGPT sign-in registration is invalid."),
276 ),
277 ),
278 ),
279 );
280 const accountCounts = Effect.gen(function* () {
281 const instanceIds = new Set<string>([options.instanceId]);
282 if (Option.isSome(settings)) {
283 const current = yield* settings.value.getSettings;
284 instanceIds.add("codex");
285 for (const [id, instance] of Object.entries(current.providerInstances)) {
286 if (instance.driver === "codex") instanceIds.add(id);
287 }
288 }
289 const accounts = new Set<string>();
290 const connections = new Set<string>();
291 const savedConnections = new Set<string>();
292 let unidentifiedConnectedConnectionCount = 0;
293 for (const id of instanceIds) {
294 const registrations = yield* ProviderCredentialStore.make("codex-chatgpt-registration", id);
295 const registrationBytes = yield* registrations.get;
296 if (Option.isSome(registrationBytes)) {
297 const saved = yield* decodeRegistration(new TextDecoder().decode(registrationBytes.value));
298 for (const profile of "profiles" in saved ? saved.profiles : [saved]) {
299 savedConnections.add(profile.clientId);
300 }
301 }
302 const credentials = yield* ProviderCredentialStore.make("codex-chatgpt", id);
303 const credentialBytes = yield* credentials.get;
304 if (Option.isNone(credentialBytes)) continue;
305 const saved = yield* decodeSessions(new TextDecoder().decode(credentialBytes.value));
306 for (const session of "sessions" in saved ? saved.sessions : [saved]) {
307 if (!session.scopes.includes(REQUIRED_SCOPE) || connections.has(session.clientId)) continue;
308 connections.add(session.clientId);
309 // Client-scoped subjects need verified email for local counting only; never export email or merge profiles.
310 const email = session.email?.trim().toLowerCase();
311 if (email) accounts.add(email);
312 else unidentifiedConnectedConnectionCount++;
313 }
314 }
315 return {
316 accountCountScope: Option.isSome(settings) ? "environment" : "provider_instance",
317 connectedAccountCount: accounts.size,
318 connectedConnectionCount: connections.size,
319 savedConnectionCount: savedConnections.size,
320 unidentifiedConnectedConnectionCount,
321 };
322 }).pipe(
323 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
324 Effect.provideService(Crypto.Crypto, crypto),
325 );
326 const saveRegistration = Effect.fnUntraced(function* (profile: typeof Registration.Type) {
327 const saved = yield* readRegistrations;
328 profile = {
329 ...profile,
330 connectionLabel:
331 saved.profiles.find((entry) => entry.clientId === profile.clientId)?.connectionLabel ??
332 profile.connectionLabel ??
333 `Connection ${saved.profiles.length + 1}`,
334 };
335 yield* encodeRegistration({
336 profiles: [profile, ...saved.profiles.filter((entry) => entry.clientId !== profile.clientId)],
337 lastClientId: profile.clientId,
338 }).pipe(
339 Effect.flatMap((json) => registrationStore.set(new TextEncoder().encode(json))),
340 Effect.mapError(() =>
341 failure("registration", "Could not save the ChatGPT sign-in registration. Try again."),
342 ),
343 );
344 });
345 const save = Effect.fnUntraced(function* (record: CodexChatGptCredentials, activate = true) {
346 const saved = yield* readSessions;
347 yield* writeSessions({
348 activeClientId: activate ? record.clientId : saved.activeClientId,
349 sessions: [
350 ...saved.sessions.filter((session) => session.clientId !== record.clientId),
351 record,
352 ],
353 });
354 });
355 const clearTokens = Effect.gen(function* () {
356 const saved = yield* readSessions;
357 const sessions = saved.sessions.filter((session) => session.clientId !== saved.activeClientId);
358 if (sessions.length) yield* writeSessions({ activeClientId: null, sessions });
359 else
360 yield* store.remove.pipe(
361 Effect.mapError(() =>
362 failure("disconnect", "Could not clear the ChatGPT connection. Try again."),
363 ),
364 );
365 });
366 const remove = Effect.gen(function* () {
367 const credentials = yield* read;
368 if (Option.isSome(credentials)) {
369 const { clientId, subject, email } = credentials.value;
370 const saved = yield* readRegistrations;
371 const profile = saved.profiles.find((entry) => entry.clientId === clientId);
372 if (profile && (profile.subject === undefined || profile.email === undefined))
373 yield* saveRegistration({ ...profile, subject, email });
374 }
375 yield* clearTokens;
376 });
377 const exchange = Effect.fn("CodexChatGptAuth.exchange")(function* (body: URLSearchParams) {
378 const endpoints = yield* discover;
379 const response = yield* http
380 .execute(
381 HttpClientRequest.post(endpoints.token_endpoint).pipe(
382 HttpClientRequest.setHeader("accept", "application/json"),
383 HttpClientRequest.bodyText(body.toString(), "application/x-www-form-urlencoded"),
384 ),
385 )
386 .pipe(
387 Effect.flatMap((result) =>
388 result.json.pipe(
389 Effect.map((raw) => ({
390 ok: result.status >= 200 && result.status < 300,
391 status: result.status,
392 raw,
393 })),
394 ),
395 ),
396 Effect.mapError(() =>
397 failure("exchange", "ChatGPT sign-in is temporarily unavailable. Try again."),
398 ),
399 );
400 if (!response.ok) {
401 const error = yield* Effect.try({
402 try: () => decodeOAuthError(response.raw).error,
403 catch: () => failure("exchange", "ChatGPT did not accept this sign-in. Try again."),
404 });
405 if (
406 body.get("grant_type") === "refresh_token" &&
407 [
408 "invalid_grant",
409 "invalid_refresh_token",
410 "token_expired",
411 "refresh_token_expired",
412 "refresh_token_invalidated",
413 "refresh_token_reused",
414 ].includes(error)
415 ) {
416 yield* remove;
417 return yield* failure(
418 "refresh",
419 "Your ChatGPT connection expired or was disconnected. Sign in again.",
420 );
421 }
422 if (error === "invalid_client")
423 return yield* failure(
424 "client",
425 "OpenAI rejected this app's client registration. Check the ChatGPT connection configuration.",
426 );
427 if (body.get("grant_type") === "authorization_code" && error === "invalid_grant")
428 return yield* failure("code-expired", "This sign-in code expired. Start again.");
429 return yield* failure(
430 "exchange",
431 error === "access_denied"
432 ? "ChatGPT sign-in was declined. Sign in again when you are ready."
433 : "ChatGPT could not complete sign-in. Try again.",
434 );
435 }
436 return yield* Effect.try({
437 try: () => decodeTokens(response.raw),
438 catch: () =>
439 failure("exchange", "ChatGPT returned an invalid token response. Sign in again."),
440 });
441 });
442 const earliest = (value: (typeof TokenResponse.Type)["earliest_refresh_at"]) => {
443 if (value === undefined) return null;
444 const time = typeof value === "number" ? value * 1000 : Date.parse(value);
445 return Number.isFinite(time) ? time : null;
446 };
447 const authenticate = Effect.fn("CodexChatGptAuth.authenticate")(function* (
448 method: string,
449 context: ProviderAuthFlowContext,
450 ) {
451 const endpoints = yield* discover;
452 const existing = yield* read;
453 const previous = Option.getOrUndefined(existing);
454 const registrations = yield* readRegistrations;
455 const changingAccount = method === "chatgpt-change-account";
456 const selectedClientId = method.startsWith("chatgpt-profile:")
457 ? method.slice("chatgpt-profile:".length)
458 : (previous?.clientId ?? registrations.lastClientId);
459 const savedRegistration = changingAccount
460 ? undefined
461 : registrations.profiles.find((profile) => profile.clientId === selectedClientId);
462 // Legacy localhost registrations cannot change on reauth; register 127.0.0.1 while preserving the verified account.
463 const legacyCallback = savedRegistration?.redirectUri?.includes("//localhost:") === true;
464 const registeredClientId = legacyCallback ? undefined : savedRegistration?.clientId;
465 const selectedTokens = (yield* readSessions).sessions.find(
466 (session) => session.clientId === selectedClientId,
467 );
468 const state = NodeCrypto.randomBytes(32).toString("base64url");
469 const nonce = NodeCrypto.randomBytes(32).toString("base64url");
470 const verifier = NodeCrypto.randomBytes(64).toString("base64url");
471 const returnUrl =
472 codexAuthReturnUrl(context.returnUrl) ?? codexAuthReturnUrl(options.defaultReturnUrl);
473 const pageNonce = NodeCrypto.randomBytes(24).toString("base64url");
474 const callback = Promise.withResolvers<{ url: URL; response?: NodeHttp.ServerResponse }>();
475 const clientCallback = context.callbackMode === "client";
476 let used = false;
477 const server = clientCallback
478 ? undefined
479 : yield* Effect.acquireRelease(
480 Effect.tryPromise({
481 try: () =>
482 new Promise<NodeHttp.Server>((resolve, reject) => {
483 const server = NodeHttp.createServer((request, response) => {
484 const url = new URL(request.url ?? "/", "http://127.0.0.1");
485 if (request.method !== "GET" || url.pathname !== "/auth/callback") {
486 response.writeHead(404).end();
487 return;
488 }
489 if (used) {
490 response.writeHead(410).end("Sign-in is no longer active.");
491 return;
492 }
493 used = true;
494 callback.resolve({ url, response });
495 });
496 server.once("error", reject);
497 server.listen(0, "127.0.0.1", () => resolve(server));
498 }),
499 catch: () =>
500 failure("callback", "Could not start the local sign-in callback. Try again."),
501 }),
502 (server) =>
503 Effect.promise(
504 () =>
505 new Promise<void>((resolve) => {
506 server.closeAllConnections();
507 server.close(() => resolve());
508 }),
509 ),
510 );
511 const address = server?.address();
512 if (!clientCallback && (!address || typeof address === "string"))
513 return yield* failure("callback", "Could not start the local sign-in callback.");
514 // Only the port may vary between attempts; token exchange uses this exact URI.
515 const port =
516 address && typeof address !== "string" ? address.port : NodeCrypto.randomInt(49_152, 65_536);
517 const redirectUri = `http://127.0.0.1:${port}/auth/callback`;
518 const idTokenHint = selectedTokens?.idToken ?? options.reconnectProfile?.idTokenHint;
519 const url = new URL(endpoints.authorization_endpoint);
520 url.search = new URLSearchParams({
521 client_id: registeredClientId ?? "dynamic_agent_client",
522 ...(registeredClientId
523 ? {
524 ...(savedRegistration?.email ? { login_hint: savedRegistration.email } : {}),
525 ...(idTokenHint ? { id_token_hint: idTokenHint } : {}),
526 ...(savedRegistration?.sharingEnabled === false ||
527 (selectedTokens && !selectedTokens.scopes.includes(REQUIRED_SCOPE))
528 ? { prompt: "consent" }
529 : {}),
530 }
531 : { agent_name_hint: "T3 Code" }),
532 ext_agent_host_id: hostId,
533 response_type: "code",
534 redirect_uri: redirectUri,
535 scope: "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct",
536 resource,
537 state,
538 nonce,
539 code_challenge_method: "S256",
540 code_challenge: NodeCrypto.createHash("sha256").update(verifier).digest("base64url"),
541 }).toString();
542 yield* context.setInteraction(
543 {
544 type: "browser",
545 id: context.flowId,
546 url: url.toString(),
547 requiresConsent: false,
548 acceptsCallback: true,
549 },
550 undefined,
551 (callbackUrl) =>
552 Effect.try({
553 try: () => {
554 const returned = codexCallbackUrl(callbackUrl, redirectUri, state);
555 if (used) throw new Error("used");
556 used = true;
557 callback.resolve({ url: returned });
558 },
559 catch: () =>
560 failure("complete", "This redirect URL does not belong to the active ChatGPT sign-in."),
561 }),
562 );
563 const received = yield* Effect.tryPromise({
564 try: () => callback.promise,
565 catch: () => failure("callback", "ChatGPT sign-in could not be completed."),
566 });
567 const returned = received.url;
568 yield* Effect.gen(function* () {
569 if (returned.searchParams.get("state") !== state)
570 return yield* failure("callback", "ChatGPT sign-in could not be verified. Start again.");
571 if (returned.searchParams.has("error"))
572 return yield* failure(
573 "callback",
574 returned.searchParams.get("error") === "access_denied"
575 ? "ChatGPT sign-in was declined. Sign in again when you are ready."
576 : "ChatGPT sign-in could not be completed. Start again.",
577 );
578 const code = returned.searchParams.get("code");
579 const clientId = registeredClientId ?? returned.searchParams.get("client_id");
580 if (
581 !code ||
582 !clientId ||
583 !clientId.startsWith("oaiapp_") ||
584 (registeredClientId &&
585 returned.searchParams.has("client_id") &&
586 returned.searchParams.get("client_id") !== registeredClientId)
587 )
588 return yield* failure(
589 "callback",
590 "ChatGPT registration is incomplete. Start sign-in again.",
591 );
592 yield* context.verifying;
593 const tokens = yield* exchange(
594 new URLSearchParams({
595 grant_type: "authorization_code",
596 client_id: clientId,
597 code,
598 code_verifier: verifier,
599 redirect_uri: redirectUri,
600 resource,
601 }),
602 ).pipe(
603 Effect.catch((error) =>
604 Effect.gen(function* () {
605 if (error.operation === "code-expired") {
606 if (!registeredClientId)
607 yield* withSessionLock(saveRegistration({ clientId, redirectUri }));
608 return yield* failure(
609 "exchange",
610 "This sign-in code expired. Reconnect the saved ChatGPT profile to start a fresh sign-in.",
611 );
612 }
613 return yield* error;
614 }),
615 ),
616 );
617 if (!tokens.id_token)
618 return yield* failure(
619 "verify",
620 "ChatGPT did not return a verified identity. Sign in again.",
621 );
622 const identity = yield* Effect.tryPromise({
623 try: async () => {
624 const { payload } = await jwtVerify(tokens.id_token!, jwks!, {
625 issuer: endpoints.issuer,
626 audience: clientId,
627 algorithms: ["RS256", "ES256"],
628 clockTolerance: 5,
629 });
630 if (payload.nonce !== nonce || !payload.sub || !payload.exp) throw new Error("identity");
631 return {
632 subject: payload.sub,
633 email: typeof payload.email === "string" ? payload.email : null,
634 };
635 },
636 catch: () => failure("verify", "ChatGPT sign-in could not be verified. Start again."),
637 });
638 const expectedSubject =
639 savedRegistration?.subject ??
640 (previous?.clientId === registeredClientId ? previous?.subject : undefined);
641 // Compare subjects only within a registration; legacy callback migration creates a new client.
642 if (registeredClientId && expectedSubject && identity.subject !== expectedSubject)
643 return yield* failure(
644 "verify",
645 "This sign-in returned a different ChatGPT account. Use the different-account sign-in option instead. Your saved connection is unchanged.",
646 );
647 const knownProfile = registrations.profiles.find((profile) => profile.clientId === clientId);
648 if (
649 knownProfile &&
650 ((knownProfile.redirectUri &&
651 (() => {
652 const original = new URL(knownProfile.redirectUri);
653 const current = new URL(redirectUri);
654 return (
655 original.protocol !== current.protocol ||
656 original.hostname !== current.hostname ||
657 original.pathname !== current.pathname
658 );
659 })()) ||
660 (knownProfile.subject && knownProfile.subject !== identity.subject))
661 )
662 return yield* failure(
663 "verify",
664 "ChatGPT returned a conflicting account registration. Start again.",
665 );
666 if (tokens.token_type.toLowerCase() !== "bearer")
667 return yield* failure(
668 "verify",
669 "ChatGPT returned an unsupported connection. Sign in again.",
670 );
671 const scopes = tokens.scope.split(/\s+/).filter(Boolean);
672 yield* withSessionLock(
673 Effect.gen(function* () {
674 yield* saveRegistration({
675 clientId,
676 redirectUri,
677 sharingEnabled: scopes.includes(REQUIRED_SCOPE),
678 ...identity,
679 });
680 yield* save(
681 {
682 clientId,
683 accessToken: tokens.access_token,
684 idToken: tokens.id_token!,
685 issuer: endpoints.issuer,
686 refreshToken: tokens.refresh_token ?? null,
687 expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000,
688 earliestRefreshAt: earliest(tokens.earliest_refresh_at),
689 scopes,
690 ...identity,
691 },
692 scopes.includes(REQUIRED_SCOPE) || Option.isNone(yield* read),
693 );
694 }),
695 );
696 if (!scopes.includes(REQUIRED_SCOPE))
697 return yield* failure(
698 "sharing",
699 previous && previous.clientId !== clientId
700 ? "Token sharing was not enabled for the new account. Your existing ChatGPT connection is unchanged."
701 : "Signed in with ChatGPT, but token sharing is disabled. Sign in again and enable token sharing, or use another provider.",
702 );
703 }).pipe(
704 Effect.onExit((result) =>
705 Effect.promise(
706 () =>
707 new Promise<void>((resolve) => {
708 const response = received.response;
709 if (!response || response.destroyed) {
710 resolve();
711 return;
712 }
713 response.once("close", resolve);
714 response
715 .writeHead(200, {
716 "content-type": "text/html; charset=utf-8",
717 "cache-control": "no-store",
718 "referrer-policy": "no-referrer",
719 "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${pageNonce}'; base-uri 'none'; frame-ancestors 'none'`,
720 "x-content-type-options": "nosniff",
721 })
722 .end(codexAuthCallbackPage(Exit.isSuccess(result), returnUrl, pageNonce), resolve);
723 }),
724 ),
725 ),
726 );
727 });
728 // ID tokens survive renewal but change on sign-in. Bind active children to the
729 // launch profile without putting an identity token or subject in their argv.
730 const profileKey = (record: CodexChatGptCredentials) =>
731 crypto
732 .digest(
733 "SHA-256",
734 new TextEncoder().encode(
735 JSON.stringify([record.clientId, record.subject, record.idToken ?? null]),
736 ),
737 )
738 .pipe(Effect.map(Hex.encode), Effect.orDie);
739 const access = lock.withPermit(
740 withSessionLock(
741 Effect.uninterruptible(
742 Effect.gen(function* () {
743 const saved = yield* read;
744 if (Option.isNone(saved))
745 return yield* failure("access", "Sign in with ChatGPT to use managed Codex.");
746 let record = saved.value;
747 if (
748 options.expectedProfileKey !== undefined &&
749 (yield* profileKey(record)) !== options.expectedProfileKey
750 )
751 return yield* failure("access", "The ChatGPT connection changed. Start a new session.");
752 if (!record.scopes.includes(REQUIRED_SCOPE))
753 return yield* failure(
754 "sharing",
755 "Token sharing is disabled. Sign in with ChatGPT and enable token sharing.",
756 );
757 const now = yield* Clock.currentTimeMillis;
758 if (record.expiresAt - now > 60_000) return record;
759 if (record.earliestRefreshAt !== null && record.earliestRefreshAt > now) {
760 if (record.expiresAt > now) return record;
761 return yield* failure(
762 "refresh",
763 "ChatGPT cannot renew this connection yet. Try again shortly.",
764 );
765 }
766 if (!record.refreshToken) {
767 yield* remove;
768 return yield* failure("refresh", "Your ChatGPT connection expired. Sign in again.");
769 }
770 const tokens = yield* exchange(
771 new URLSearchParams({
772 grant_type: "refresh_token",
773 client_id: record.clientId,
774 refresh_token: record.refreshToken,
775 resource,
776 }),
777 ).pipe(
778 Effect.interruptible,
779 Effect.timeout("20 seconds"),
780 Effect.mapError((error) =>
781 error._tag === "ProviderSetupError" && error.operation === "client"
782 ? error
783 : failure(
784 "refresh",
785 "Could not renew the ChatGPT connection. Retry, or sign in again.",
786 ),
787 ),
788 );
789 if (!tokens.refresh_token || tokens.token_type.toLowerCase() !== "bearer") {
790 return yield* failure("refresh", "ChatGPT returned an invalid renewal. Sign in again.");
791 }
792 record = {
793 ...record,
794 accessToken: tokens.access_token,
795 refreshToken: tokens.refresh_token,
796 expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000,
797 earliestRefreshAt: earliest(tokens.earliest_refresh_at),
798 scopes: tokens.scope.split(/\s+/).filter(Boolean),
799 };
800 yield* save(record);
801 if (!record.scopes.includes(REQUIRED_SCOPE))
802 return yield* failure(
803 "sharing",
804 "ChatGPT token sharing is no longer enabled. Sign in again.",
805 );
806 return record;
807 }),
808 ),
809 ),
810 );
811 const logout = Effect.gen(function* () {
812 const credentials = Option.getOrUndefined(yield* read);
813 let confirmed = !credentials?.refreshToken;
814 if (credentials?.refreshToken) {
815 for (let attempt = 0; attempt < 3; attempt++) {
816 const result = yield* Effect.gen(function* () {
817 const endpoints = yield* discover;
818 if (!endpoints.revocation_endpoint) return { confirmed: false, retry: false };
819 const response = yield* http.execute(
820 HttpClientRequest.post(endpoints.revocation_endpoint).pipe(
821 HttpClientRequest.bodyText(
822 new URLSearchParams({
823 token: credentials.refreshToken!,
824 token_type_hint: "refresh_token",
825 client_id: credentials.clientId,
826 }).toString(),
827 "application/x-www-form-urlencoded",
828 ),
829 ),
830 );
831 return { confirmed: response.status === 200, retry: response.status >= 500 };
832 }).pipe(
833 Effect.timeout("10 seconds"),
834 Effect.orElseSucceed(() => ({ confirmed: false, retry: true })),
835 );
836 confirmed = result.confirmed;
837 if (confirmed || !result.retry || attempt === 2) break;
838 yield* Effect.sleep(attempt === 0 ? "250 millis" : "1 second");
839 }
840 }
841 yield* remove;
842 return confirmed
843 ? undefined
844 : "Signed out locally. Remote revocation could not be confirmed. Disconnect the app in ChatGPT Settings.";
845 });
846 if (options.reconnectProfile) {
847 const { idTokenHint: _hint, ...registration } = options.reconnectProfile;
848 yield* saveRegistration(registration).pipe(Effect.orDie);
849 }
850 const controller = yield* ProviderAuthFlow.make({
851 instanceId: options.instanceId,
852 credentialBinding: store.binding,
853 refreshMethodsAfterAuth: true,
854 methods: Effect.gen(function* () {
855 const saved = yield* readRegistrations;
856 const active = Option.getOrUndefined(yield* read);
857 const current = saved.profiles.find(
858 (profile) => profile.clientId === (active?.clientId ?? saved.lastClientId),
859 );
860 const profiles = current
861 ? [current, ...saved.profiles.filter((profile) => profile.clientId !== current.clientId)]
862 : saved.profiles;
863 return [
864 {
865 id: "chatgpt",
866 name: "Sign in with ChatGPT",
867 description: current?.email ? `Reconnect ${current.email}.` : null,
868 ...(current?.email ? { accountEmail: current.email } : {}),
869 type: "agent" as const,
870 },
871 {
872 id: "chatgpt-change-account",
873 name: "Use a different ChatGPT account",
874 description: "Register a connection for another ChatGPT account.",
875 type: "agent" as const,
876 },
877 ...profiles.slice(0, 30).map((profile) => ({
878 id: profileMethodId(profile.clientId),
879 name: `${profile.email ?? "ChatGPT account"} · ${profile.connectionLabel}`,
880 ...(profile.email ? { accountEmail: profile.email } : {}),
881 description: "Reuse this account's original sign-in registration.",
882 type: "agent" as const,
883 })),
884 ];
885 }),
886 authenticate: (method, context) =>
887 lock.withPermit(
888 track(
889 "auth",
890 {
891 flow: options.telemetryFlow ?? "direct",
892 intent:
893 options.telemetryFlow === "primary_handoff"
894 ? options.reconnectProfile
895 ? "saved_profile"
896 : "different_account"
897 : method === "chatgpt-change-account"
898 ? "different_account"
899 : method.startsWith("chatgpt-profile:")
900 ? "saved_profile"
901 : "default",
902 callbackMode: context.callbackMode ?? "server",
903 },
904 authenticate(method, context),
905 context.expiresAt,
906 ),
907 ),
908 logout: lock.withPermit(withSessionLock(logout)),
909 });
910 const reconnectProfile = Effect.fnUntraced(function* (methodId: string) {
911 if (methodId === "chatgpt-change-account") return null;
912 const registrations = yield* readRegistrations;
913 const active = Option.getOrUndefined(yield* read);
914 const clientId = methodId.startsWith("chatgpt-profile:")
915 ? methodId.slice("chatgpt-profile:".length)
916 : (active?.clientId ?? registrations.lastClientId);
917 const registration = registrations.profiles.find((profile) => profile.clientId === clientId);
918 if (!registration) {
919 if (methodId.startsWith("chatgpt-profile:"))
920 return yield* failure("export", "This saved connection is no longer available.");
921 return null;
922 }
923 const session = (yield* readSessions).sessions.find((session) => session.clientId === clientId);
924 return { ...registration, ...(session?.idToken ? { idTokenHint: session.idToken } : {}) };
925 });
926 const exportProfile = Effect.gen(function* () {
927 const credentials = Option.getOrUndefined(yield* read);
928 const registration =
929 credentials &&
930 (yield* readRegistrations).profiles.find(
931 (profile) => profile.clientId === credentials.clientId,
932 );
933 if (!credentials?.idToken || !credentials.issuer || !registration)
934 return yield* failure(
935 "export",
936 "Complete ChatGPT sign-in before transferring this connection.",
937 );
938 return {
939 registration,
940 credentials: { ...credentials, idToken: credentials.idToken, issuer: credentials.issuer },
941 } satisfies ChatGptTransferredProfile;
942 });
943 const importProfile = (
944 profile: ChatGptTransferredProfile,
945 stopSessions: Effect.Effect<void, ProviderSetupError>,
946 ) => {
947 const validate = Effect.gen(function* () {
948 const endpoints = yield* discover;
949 const credentials = profile.credentials;
950 if (
951 credentials.clientId !== profile.registration.clientId ||
952 credentials.issuer !== endpoints.issuer ||
953 !credentials.scopes.includes(REQUIRED_SCOPE) ||
954 credentials.expiresAt <= (yield* Clock.currentTimeMillis)
955 )
956 return yield* failure(
957 "import",
958 "The transferred ChatGPT connection is invalid or expired.",
959 );
960 const identity = yield* Effect.tryPromise({
961 try: () =>
962 jwtVerify(credentials.idToken, jwks!, {
963 issuer: endpoints.issuer,
964 audience: credentials.clientId,
965 algorithms: ["RS256", "ES256"],
966 clockTolerance: 5,
967 }),
968 catch: () => failure("import", "The transferred ChatGPT identity could not be verified."),
969 });
970 if (
971 identity.payload.sub !== credentials.subject ||
972 profile.registration.subject !== credentials.subject ||
973 (identity.payload.email ?? null) !== credentials.email ||
974 (profile.registration.email !== undefined &&
975 profile.registration.email !== credentials.email)
976 )
977 return yield* failure(
978 "import",
979 "The transferred ChatGPT identity does not match its profile.",
980 );
981 });
982 const saveImported = Effect.gen(function* () {
983 const { idTokenHint: _hint, ...registration } = profile.registration;
984 const existing = (yield* readRegistrations).profiles.find(
985 (saved) => saved.clientId === registration.clientId,
986 );
987 if (existing?.subject && existing.subject !== profile.credentials.subject)
988 return yield* failure(
989 "import",
990 "The transferred identity conflicts with the saved ChatGPT connection.",
991 );
992 yield* saveRegistration(registration);
993 yield* save(profile.credentials, true);
994 });
995 return lock.withPermit(
996 track(
997 "transfer",
998 { flow: "primary_handoff" },
999 validate.pipe(
1000 Effect.andThen(controller.adoptCredentials!(withSessionLock(saveImported), stopSessions)),
1001 ),
1002 ),
1003 );
1004 };
1005 return {
1006 controller: { ...controller, reconnectProfile, importProfile },
1007 read,
1008 access,
1009 profileKey,
1010 exportProfile,
1011 revoke: lock.withPermit(withSessionLock(remove)),
1012 };
1013});