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