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 // Registration profiles outlive tokens, but belong only to this environment/instance.
232 // Accept the original single-registration record until it is next saved.
233 const readRegistrations = registrationStore.get.pipe(
234 Effect.mapError(() =>
235 failure("registration", "Could not read the ChatGPT sign-in registration. Try again."),
236 ),
237 Effect.flatMap((bytes) =>
238 Option.isNone(bytes)
239 ? Effect.succeed<typeof RegistrationProfiles.Type>({ profiles: [], lastClientId: null })
240 : decodeRegistration(new TextDecoder().decode(bytes.value)).pipe(
241 Effect.map((record) => {
242 const saved =
243 "profiles" in record
244 ? record
245 : { profiles: [record], lastClientId: record.clientId };
246 const last = saved.profiles.find(
247 (profile) => profile.clientId === saved.lastClientId,
248 );
249 const ordered = last
250 ? [last, ...saved.profiles.filter((profile) => profile.clientId !== last.clientId)]
251 : saved.profiles;
252 return {
253 ...saved,
254 profiles: ordered.map((profile) => ({
255 ...profile,
256 connectionLabel:
257 profile.connectionLabel ?? `Connection ${saved.profiles.indexOf(profile) + 1}`,
258 })),
259 };
260 }),
261 Effect.mapError(() =>
262 failure("registration", "The saved ChatGPT sign-in registration is invalid."),
263 ),
264 ),
265 ),
266 );
267 const accountCounts = Effect.gen(function* () {
268 const instanceIds = new Set<string>([options.instanceId]);
269 if (Option.isSome(settings)) {
270 const current = yield* settings.value.getSettings;
271 // Include the legacy default instance as well as explicitly configured ones.
272 instanceIds.add("codex");
273 for (const [id, instance] of Object.entries(current.providerInstances)) {
274 if (instance.driver === "codex") instanceIds.add(id);
275 }
276 }
277 const accounts = new Set<string>();
278 const connections = new Set<string>();
279 const savedConnections = new Set<string>();
280 let unidentifiedConnectedConnectionCount = 0;
281 for (const id of instanceIds) {
282 const registrations = yield* ProviderCredentialStore.make("codex-chatgpt-registration", id);
283 const registrationBytes = yield* registrations.get;
284 if (Option.isSome(registrationBytes)) {
285 const saved = yield* decodeRegistration(new TextDecoder().decode(registrationBytes.value));
286 for (const profile of "profiles" in saved ? saved.profiles : [saved]) {
287 savedConnections.add(profile.clientId);
288 }
289 }
290 const credentials = yield* ProviderCredentialStore.make("codex-chatgpt", id);
291 const credentialBytes = yield* credentials.get;
292 if (Option.isNone(credentialBytes)) continue;
293 const saved = yield* decodeSessions(new TextDecoder().decode(credentialBytes.value));
294 for (const session of "sessions" in saved ? saved.sessions : [saved]) {
295 if (!session.scopes.includes(REQUIRED_SCOPE) || connections.has(session.clientId)) continue;
296 connections.add(session.clientId);
297 // Subjects are client-scoped. Use verified email only for counting locally,
298 // never export it or merge the underlying profiles.
299 const email = session.email?.trim().toLowerCase();
300 if (email) accounts.add(email);
301 else unidentifiedConnectedConnectionCount++;
302 }
303 }
304 return {
305 accountCountScope: Option.isSome(settings) ? "environment" : "provider_instance",
306 connectedAccountCount: accounts.size,
307 connectedConnectionCount: connections.size,
308 savedConnectionCount: savedConnections.size,
309 unidentifiedConnectedConnectionCount,
310 };
311 }).pipe(
312 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
313 Effect.provideService(Crypto.Crypto, crypto),
314 );
315 const saveRegistration = Effect.fnUntraced(function* (profile: typeof Registration.Type) {
316 const saved = yield* readRegistrations;
317 profile = {
318 ...profile,
319 connectionLabel:
320 saved.profiles.find((entry) => entry.clientId === profile.clientId)?.connectionLabel ??
321 profile.connectionLabel ??
322 `Connection ${saved.profiles.length + 1}`,
323 };
324 yield* encodeRegistration({
325 profiles: [profile, ...saved.profiles.filter((entry) => entry.clientId !== profile.clientId)],
326 lastClientId: profile.clientId,
327 }).pipe(
328 Effect.flatMap((json) => registrationStore.set(new TextEncoder().encode(json))),
329 Effect.mapError(() =>
330 failure("registration", "Could not save the ChatGPT sign-in registration. Try again."),
331 ),
332 );
333 });
334 // The active pointer and all profile token sets change in one protected atomic write.
335 const save = Effect.fnUntraced(function* (record: CodexChatGptCredentials, activate = true) {
336 const saved = yield* readSessions;
337 yield* writeSessions({
338 activeClientId: activate ? record.clientId : saved.activeClientId,
339 sessions: [
340 ...saved.sessions.filter((session) => session.clientId !== record.clientId),
341 record,
342 ],
343 });
344 });
345 const clearTokens = Effect.gen(function* () {
346 const saved = yield* readSessions;
347 const sessions = saved.sessions.filter((session) => session.clientId !== saved.activeClientId);
348 if (sessions.length) yield* writeSessions({ activeClientId: null, sessions });
349 else
350 yield* store.remove.pipe(
351 Effect.mapError(() =>
352 failure("disconnect", "Could not clear the ChatGPT connection. Try again."),
353 ),
354 );
355 });
356 const remove = Effect.gen(function* () {
357 // Promote legacy identity into the retained profile before deleting credentials.
358 const credentials = yield* read;
359 if (Option.isSome(credentials)) {
360 const { clientId, subject, email } = credentials.value;
361 const saved = yield* readRegistrations;
362 const profile = saved.profiles.find((entry) => entry.clientId === clientId);
363 if (profile && (profile.subject === undefined || profile.email === undefined))
364 yield* saveRegistration({ ...profile, subject, email });
365 }
366 yield* clearTokens;
367 });
368 const exchange = Effect.fn("CodexChatGptAuth.exchange")(function* (body: URLSearchParams) {
369 const endpoints = yield* discover;
370 const response = yield* http
371 .execute(
372 HttpClientRequest.post(endpoints.token_endpoint).pipe(
373 HttpClientRequest.setHeader("accept", "application/json"),
374 HttpClientRequest.bodyText(body.toString(), "application/x-www-form-urlencoded"),
375 ),
376 )
377 .pipe(
378 Effect.flatMap((result) =>
379 result.json.pipe(
380 Effect.map((raw) => ({
381 ok: result.status >= 200 && result.status < 300,
382 status: result.status,
383 raw,
384 })),
385 ),
386 ),
387 Effect.mapError(() =>
388 failure("exchange", "ChatGPT sign-in is temporarily unavailable. Try again."),
389 ),
390 );
391 if (!response.ok) {
392 const error = yield* Effect.try({
393 try: () => decodeOAuthError(response.raw).error,
394 catch: () => failure("exchange", "ChatGPT did not accept this sign-in. Try again."),
395 });
396 if (
397 body.get("grant_type") === "refresh_token" &&
398 [
399 "invalid_grant",
400 "invalid_refresh_token",
401 "token_expired",
402 "refresh_token_expired",
403 "refresh_token_invalidated",
404 "refresh_token_reused",
405 ].includes(error)
406 ) {
407 yield* remove;
408 return yield* failure(
409 "refresh",
410 "Your ChatGPT connection expired or was disconnected. Sign in again.",
411 );
412 }
413 if (error === "invalid_client")
414 return yield* failure(
415 "client",
416 "OpenAI rejected this app's client registration. Check the ChatGPT connection configuration.",
417 );
418 if (body.get("grant_type") === "authorization_code" && error === "invalid_grant")
419 return yield* failure("code-expired", "This sign-in code expired. Start again.");
420 return yield* failure(
421 "exchange",
422 error === "access_denied"
423 ? "ChatGPT sign-in was declined. Sign in again when you are ready."
424 : "ChatGPT could not complete sign-in. Try again.",
425 );
426 }
427 return yield* Effect.try({
428 try: () => decodeTokens(response.raw),
429 catch: () =>
430 failure("exchange", "ChatGPT returned an invalid token response. Sign in again."),
431 });
432 });
433 const earliest = (value: (typeof TokenResponse.Type)["earliest_refresh_at"]) => {
434 if (value === undefined) return null;
435 const time = typeof value === "number" ? value * 1000 : Date.parse(value);
436 return Number.isFinite(time) ? time : null;
437 };
438 const authenticate = Effect.fn("CodexChatGptAuth.authenticate")(function* (
439 method: string,
440 context: ProviderAuthFlowContext,
441 ) {
442 const endpoints = yield* discover;
443 const existing = yield* read;
444 const previous = Option.getOrUndefined(existing);
445 const registrations = yield* readRegistrations;
446 const changingAccount = method === "chatgpt-change-account";
447 const selectedClientId = method.startsWith("chatgpt-profile:")
448 ? method.slice("chatgpt-profile:".length)
449 : (previous?.clientId ?? registrations.lastClientId);
450 const savedRegistration = changingAccount
451 ? undefined
452 : registrations.profiles.find((profile) => profile.clientId === selectedClientId);
453 // Older development registrations used localhost, which cannot be changed on reauth.
454 // Register a 127.0.0.1 connection instead, preserving the verified account.
455 const legacyCallback = savedRegistration?.redirectUri?.includes("//localhost:") === true;
456 const registeredClientId = legacyCallback ? undefined : savedRegistration?.clientId;
457 const selectedTokens = (yield* readSessions).sessions.find(
458 (session) => session.clientId === selectedClientId,
459 );
460 const state = NodeCrypto.randomBytes(32).toString("base64url");
461 const nonce = NodeCrypto.randomBytes(32).toString("base64url");
462 const verifier = NodeCrypto.randomBytes(64).toString("base64url");
463 const returnUrl =
464 codexAuthReturnUrl(context.returnUrl) ?? codexAuthReturnUrl(options.defaultReturnUrl);
465 const pageNonce = NodeCrypto.randomBytes(24).toString("base64url");
466 const callback = Promise.withResolvers<{ url: URL; response?: NodeHttp.ServerResponse }>();
467 const clientCallback = context.callbackMode === "client";
468 let used = false;
469 const server = clientCallback
470 ? undefined
471 : yield* Effect.acquireRelease(
472 Effect.tryPromise({
473 try: () =>
474 new Promise<NodeHttp.Server>((resolve, reject) => {
475 const server = NodeHttp.createServer((request, response) => {
476 const url = new URL(request.url ?? "/", "http://127.0.0.1");
477 if (request.method !== "GET" || url.pathname !== "/auth/callback") {
478 response.writeHead(404).end();
479 return;
480 }
481 if (used) {
482 response.writeHead(410).end("Sign-in is no longer active.");
483 return;
484 }
485 used = true;
486 callback.resolve({ url, response });
487 });
488 server.once("error", reject);
489 server.listen(0, "127.0.0.1", () => resolve(server));
490 }),
491 catch: () =>
492 failure("callback", "Could not start the local sign-in callback. Try again."),
493 }),
494 (server) =>
495 Effect.promise(
496 () =>
497 new Promise<void>((resolve) => {
498 server.closeAllConnections();
499 server.close(() => resolve());
500 }),
501 ),
502 );
503 const address = server?.address();
504 if (!clientCallback && (!address || typeof address === "string"))
505 return yield* failure("callback", "Could not start the local sign-in callback.");
506 // Only the port may vary between attempts; token exchange uses this exact URI.
507 const port =
508 address && typeof address !== "string" ? address.port : NodeCrypto.randomInt(49_152, 65_536);
509 const redirectUri = `http://127.0.0.1:${port}/auth/callback`;
510 const idTokenHint = selectedTokens?.idToken ?? options.reconnectProfile?.idTokenHint;
511 const url = new URL(endpoints.authorization_endpoint);
512 url.search = new URLSearchParams({
513 client_id: registeredClientId ?? "dynamic_agent_client",
514 ...(registeredClientId
515 ? {
516 ...(savedRegistration?.email ? { login_hint: savedRegistration.email } : {}),
517 ...(idTokenHint ? { id_token_hint: idTokenHint } : {}),
518 ...(savedRegistration?.sharingEnabled === false ||
519 (selectedTokens && !selectedTokens.scopes.includes(REQUIRED_SCOPE))
520 ? { prompt: "consent" }
521 : {}),
522 }
523 : { agent_name_hint: "T3 Code" }),
524 ext_agent_host_id: hostId,
525 response_type: "code",
526 redirect_uri: redirectUri,
527 scope: "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct",
528 resource,
529 state,
530 nonce,
531 code_challenge_method: "S256",
532 code_challenge: NodeCrypto.createHash("sha256").update(verifier).digest("base64url"),
533 }).toString();
534 yield* context.setInteraction(
535 {
536 type: "browser",
537 id: context.flowId,
538 url: url.toString(),
539 requiresConsent: false,
540 acceptsCallback: true,
541 },
542 undefined,
543 (callbackUrl) =>
544 Effect.try({
545 try: () => {
546 const returned = codexCallbackUrl(callbackUrl, redirectUri, state);
547 if (used) throw new Error("used");
548 used = true;
549 callback.resolve({ url: returned });
550 },
551 catch: () =>
552 failure("complete", "This redirect URL does not belong to the active ChatGPT sign-in."),
553 }),
554 );
555 const received = yield* Effect.tryPromise({
556 try: () => callback.promise,
557 catch: () => failure("callback", "ChatGPT sign-in could not be completed."),
558 });
559 const returned = received.url;
560 yield* Effect.gen(function* () {
561 if (returned.searchParams.get("state") !== state)
562 return yield* failure("callback", "ChatGPT sign-in could not be verified. Start again.");
563 if (returned.searchParams.has("error"))
564 return yield* failure(
565 "callback",
566 returned.searchParams.get("error") === "access_denied"
567 ? "ChatGPT sign-in was declined. Sign in again when you are ready."
568 : "ChatGPT sign-in could not be completed. Start again.",
569 );
570 const code = returned.searchParams.get("code");
571 const clientId = registeredClientId ?? returned.searchParams.get("client_id");
572 if (
573 !code ||
574 !clientId ||
575 !clientId.startsWith("oaiapp_") ||
576 (registeredClientId &&
577 returned.searchParams.has("client_id") &&
578 returned.searchParams.get("client_id") !== registeredClientId)
579 )
580 return yield* failure(
581 "callback",
582 "ChatGPT registration is incomplete. Start sign-in again.",
583 );
584 yield* context.verifying;
585 const tokens = yield* exchange(
586 new URLSearchParams({
587 grant_type: "authorization_code",
588 client_id: clientId,
589 code,
590 code_verifier: verifier,
591 redirect_uri: redirectUri,
592 resource,
593 }),
594 ).pipe(
595 Effect.catch((error) =>
596 Effect.gen(function* () {
597 if (error.operation === "code-expired") {
598 if (!registeredClientId)
599 yield* withSessionLock(saveRegistration({ clientId, redirectUri }));
600 return yield* failure(
601 "exchange",
602 "This sign-in code expired. Reconnect the saved ChatGPT profile to start a fresh sign-in.",
603 );
604 }
605 return yield* error;
606 }),
607 ),
608 );
609 if (!tokens.id_token)
610 return yield* failure(
611 "verify",
612 "ChatGPT did not return a verified identity. Sign in again.",
613 );
614 const identity = yield* Effect.tryPromise({
615 try: async () => {
616 const { payload } = await jwtVerify(tokens.id_token!, jwks!, {
617 issuer: endpoints.issuer,
618 audience: clientId,
619 algorithms: ["RS256", "ES256"],
620 clockTolerance: 5,
621 });
622 if (payload.nonce !== nonce || !payload.sub || !payload.exp) throw new Error("identity");
623 return {
624 subject: payload.sub,
625 email: typeof payload.email === "string" ? payload.email : null,
626 };
627 },
628 catch: () => failure("verify", "ChatGPT sign-in could not be verified. Start again."),
629 });
630 const expectedSubject =
631 savedRegistration?.subject ??
632 (previous?.clientId === registeredClientId ? previous?.subject : undefined);
633 // Subjects are checked within the same registration. Legacy callback migration
634 // registers a new client, whose subject cannot be compared with the old client.
635 if (registeredClientId && expectedSubject && identity.subject !== expectedSubject)
636 return yield* failure(
637 "verify",
638 "This sign-in returned a different ChatGPT account. Use the different-account sign-in option instead. Your saved connection is unchanged.",
639 );
640 const knownProfile = registrations.profiles.find((profile) => profile.clientId === clientId);
641 if (
642 knownProfile &&
643 ((knownProfile.redirectUri &&
644 (() => {
645 const original = new URL(knownProfile.redirectUri);
646 const current = new URL(redirectUri);
647 return (
648 original.protocol !== current.protocol ||
649 original.hostname !== current.hostname ||
650 original.pathname !== current.pathname
651 );
652 })()) ||
653 (knownProfile.subject && knownProfile.subject !== identity.subject))
654 )
655 return yield* failure(
656 "verify",
657 "ChatGPT returned a conflicting account registration. Start again.",
658 );
659 if (tokens.token_type.toLowerCase() !== "bearer")
660 return yield* failure(
661 "verify",
662 "ChatGPT returned an unsupported connection. Sign in again.",
663 );
664 const scopes = tokens.scope.split(/\s+/).filter(Boolean);
665 yield* withSessionLock(
666 Effect.gen(function* () {
667 yield* saveRegistration({
668 clientId,
669 redirectUri,
670 sharingEnabled: scopes.includes(REQUIRED_SCOPE),
671 ...identity,
672 });
673 yield* save(
674 {
675 clientId,
676 accessToken: tokens.access_token,
677 idToken: tokens.id_token!,
678 issuer: endpoints.issuer,
679 refreshToken: tokens.refresh_token ?? null,
680 expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000,
681 earliestRefreshAt: earliest(tokens.earliest_refresh_at),
682 scopes,
683 ...identity,
684 },
685 scopes.includes(REQUIRED_SCOPE) || Option.isNone(yield* read),
686 );
687 }),
688 );
689 if (!scopes.includes(REQUIRED_SCOPE))
690 return yield* failure(
691 "sharing",
692 previous && previous.clientId !== clientId
693 ? "Token sharing was not enabled for the new account. Your existing ChatGPT connection is unchanged."
694 : "Signed in with ChatGPT, but token sharing is disabled. Sign in again and enable token sharing, or use another provider.",
695 );
696 }).pipe(
697 Effect.onExit((result) =>
698 Effect.promise(
699 () =>
700 new Promise<void>((resolve) => {
701 const response = received.response;
702 if (!response || response.destroyed) {
703 resolve();
704 return;
705 }
706 response.once("close", resolve);
707 response
708 .writeHead(200, {
709 "content-type": "text/html; charset=utf-8",
710 "cache-control": "no-store",
711 "referrer-policy": "no-referrer",
712 "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${pageNonce}'; base-uri 'none'; frame-ancestors 'none'`,
713 "x-content-type-options": "nosniff",
714 })
715 .end(codexAuthCallbackPage(Exit.isSuccess(result), returnUrl, pageNonce), resolve);
716 }),
717 ),
718 ),
719 );
720 });
721 const access = lock.withPermit(
722 withSessionLock(
723 Effect.uninterruptible(
724 Effect.gen(function* () {
725 const saved = yield* read;
726 if (Option.isNone(saved))
727 return yield* failure("access", "Sign in with ChatGPT to use managed Codex.");
728 let record = saved.value;
729 if (!record.scopes.includes(REQUIRED_SCOPE))
730 return yield* failure(
731 "sharing",
732 "Token sharing is disabled. Sign in with ChatGPT and enable token sharing.",
733 );
734 const now = yield* Clock.currentTimeMillis;
735 if (record.expiresAt - now > 60_000) return record;
736 if (record.earliestRefreshAt !== null && record.earliestRefreshAt > now) {
737 if (record.expiresAt > now) return record;
738 return yield* failure(
739 "refresh",
740 "ChatGPT cannot renew this connection yet. Try again shortly.",
741 );
742 }
743 if (!record.refreshToken) {
744 yield* remove;
745 return yield* failure("refresh", "Your ChatGPT connection expired. Sign in again.");
746 }
747 const tokens = yield* exchange(
748 new URLSearchParams({
749 grant_type: "refresh_token",
750 client_id: record.clientId,
751 refresh_token: record.refreshToken,
752 resource,
753 }),
754 ).pipe(
755 Effect.interruptible,
756 Effect.timeout("20 seconds"),
757 Effect.mapError((error) =>
758 error._tag === "ProviderSetupError" && error.operation === "client"
759 ? error
760 : failure(
761 "refresh",
762 "Could not renew the ChatGPT connection. Retry, or sign in again.",
763 ),
764 ),
765 );
766 if (!tokens.refresh_token || tokens.token_type.toLowerCase() !== "bearer") {
767 return yield* failure("refresh", "ChatGPT returned an invalid renewal. Sign in again.");
768 }
769 record = {
770 ...record,
771 accessToken: tokens.access_token,
772 refreshToken: tokens.refresh_token,
773 expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000,
774 earliestRefreshAt: earliest(tokens.earliest_refresh_at),
775 scopes: tokens.scope.split(/\s+/).filter(Boolean),
776 };
777 yield* save(record);
778 if (!record.scopes.includes(REQUIRED_SCOPE))
779 return yield* failure(
780 "sharing",
781 "ChatGPT token sharing is no longer enabled. Sign in again.",
782 );
783 return record;
784 }),
785 ),
786 ),
787 );
788 const logout = Effect.gen(function* () {
789 const credentials = Option.getOrUndefined(yield* read);
790 let confirmed = !credentials?.refreshToken;
791 if (credentials?.refreshToken) {
792 for (let attempt = 0; attempt < 3; attempt++) {
793 const result = yield* Effect.gen(function* () {
794 const endpoints = yield* discover;
795 if (!endpoints.revocation_endpoint) return { confirmed: false, retry: false };
796 const response = yield* http.execute(
797 HttpClientRequest.post(endpoints.revocation_endpoint).pipe(
798 HttpClientRequest.bodyText(
799 new URLSearchParams({
800 token: credentials.refreshToken!,
801 token_type_hint: "refresh_token",
802 client_id: credentials.clientId,
803 }).toString(),
804 "application/x-www-form-urlencoded",
805 ),
806 ),
807 );
808 return { confirmed: response.status === 200, retry: response.status >= 500 };
809 }).pipe(
810 Effect.timeout("10 seconds"),
811 Effect.orElseSucceed(() => ({ confirmed: false, retry: true })),
812 );
813 confirmed = result.confirmed;
814 if (confirmed || !result.retry || attempt === 2) break;
815 yield* Effect.sleep(attempt === 0 ? "250 millis" : "1 second");
816 }
817 }
818 yield* remove;
819 return confirmed
820 ? undefined
821 : "Signed out locally. Remote revocation could not be confirmed. Disconnect the app in ChatGPT Settings.";
822 });
823 if (options.reconnectProfile) {
824 const { idTokenHint: _hint, ...registration } = options.reconnectProfile;
825 yield* saveRegistration(registration).pipe(Effect.orDie);
826 }
827 const controller = yield* ProviderAuthFlow.make({
828 instanceId: options.instanceId,
829 credentialBinding: store.binding,
830 refreshMethodsAfterAuth: true,
831 methods: Effect.gen(function* () {
832 const saved = yield* readRegistrations;
833 const active = Option.getOrUndefined(yield* read);
834 const current = saved.profiles.find(
835 (profile) => profile.clientId === (active?.clientId ?? saved.lastClientId),
836 );
837 const profiles = current
838 ? [current, ...saved.profiles.filter((profile) => profile.clientId !== current.clientId)]
839 : saved.profiles;
840 return [
841 {
842 id: "chatgpt",
843 name: "Sign in with ChatGPT",
844 description: current?.email ? `Reconnect ${current.email}.` : null,
845 ...(current?.email ? { accountEmail: current.email } : {}),
846 type: "agent" as const,
847 },
848 {
849 id: "chatgpt-change-account",
850 name: "Use a different ChatGPT account",
851 description: "Register a connection for another ChatGPT account.",
852 type: "agent" as const,
853 },
854 // The wire contract allows 32 methods; advertise the 30 most recent profiles.
855 ...profiles.slice(0, 30).map((profile) => ({
856 id: profileMethodId(profile.clientId),
857 name: `${profile.email ?? "ChatGPT account"} · ${profile.connectionLabel}`,
858 ...(profile.email ? { accountEmail: profile.email } : {}),
859 description: "Reuse this account's original sign-in registration.",
860 type: "agent" as const,
861 })),
862 ];
863 }),
864 authenticate: (method, context) =>
865 lock.withPermit(
866 track(
867 "auth",
868 {
869 flow: options.telemetryFlow ?? "direct",
870 intent:
871 options.telemetryFlow === "primary_handoff"
872 ? options.reconnectProfile
873 ? "saved_profile"
874 : "different_account"
875 : method === "chatgpt-change-account"
876 ? "different_account"
877 : method.startsWith("chatgpt-profile:")
878 ? "saved_profile"
879 : "default",
880 callbackMode: context.callbackMode ?? "server",
881 },
882 authenticate(method, context),
883 context.expiresAt,
884 ),
885 ),
886 logout: lock.withPermit(withSessionLock(logout)),
887 });
888 const reconnectProfile = Effect.fnUntraced(function* (methodId: string) {
889 if (methodId === "chatgpt-change-account") return null;
890 const registrations = yield* readRegistrations;
891 const active = Option.getOrUndefined(yield* read);
892 const clientId = methodId.startsWith("chatgpt-profile:")
893 ? methodId.slice("chatgpt-profile:".length)
894 : (active?.clientId ?? registrations.lastClientId);
895 const registration = registrations.profiles.find((profile) => profile.clientId === clientId);
896 if (!registration) {
897 if (methodId.startsWith("chatgpt-profile:"))
898 return yield* failure("export", "This saved connection is no longer available.");
899 return null;
900 }
901 const session = (yield* readSessions).sessions.find((session) => session.clientId === clientId);
902 return { ...registration, ...(session?.idToken ? { idTokenHint: session.idToken } : {}) };
903 });
904 const exportProfile = Effect.gen(function* () {
905 const credentials = Option.getOrUndefined(yield* read);
906 const registration =
907 credentials &&
908 (yield* readRegistrations).profiles.find(
909 (profile) => profile.clientId === credentials.clientId,
910 );
911 if (!credentials?.idToken || !credentials.issuer || !registration)
912 return yield* failure(
913 "export",
914 "Complete ChatGPT sign-in before transferring this connection.",
915 );
916 return {
917 registration,
918 credentials: { ...credentials, idToken: credentials.idToken, issuer: credentials.issuer },
919 } satisfies ChatGptTransferredProfile;
920 });
921 const importProfile = (
922 profile: ChatGptTransferredProfile,
923 stopSessions: Effect.Effect<void, ProviderSetupError>,
924 ) => {
925 const validate = Effect.gen(function* () {
926 const endpoints = yield* discover;
927 const credentials = profile.credentials;
928 if (
929 credentials.clientId !== profile.registration.clientId ||
930 credentials.issuer !== endpoints.issuer ||
931 !credentials.scopes.includes(REQUIRED_SCOPE) ||
932 credentials.expiresAt <= (yield* Clock.currentTimeMillis)
933 )
934 return yield* failure(
935 "import",
936 "The transferred ChatGPT connection is invalid or expired.",
937 );
938 const identity = yield* Effect.tryPromise({
939 try: () =>
940 jwtVerify(credentials.idToken, jwks!, {
941 issuer: endpoints.issuer,
942 audience: credentials.clientId,
943 algorithms: ["RS256", "ES256"],
944 clockTolerance: 5,
945 }),
946 catch: () => failure("import", "The transferred ChatGPT identity could not be verified."),
947 });
948 if (
949 identity.payload.sub !== credentials.subject ||
950 profile.registration.subject !== credentials.subject ||
951 (identity.payload.email ?? null) !== credentials.email ||
952 (profile.registration.email !== undefined &&
953 profile.registration.email !== credentials.email)
954 )
955 return yield* failure(
956 "import",
957 "The transferred ChatGPT identity does not match its profile.",
958 );
959 });
960 const saveImported = Effect.gen(function* () {
961 const { idTokenHint: _hint, ...registration } = profile.registration;
962 const existing = (yield* readRegistrations).profiles.find(
963 (saved) => saved.clientId === registration.clientId,
964 );
965 if (existing?.subject && existing.subject !== profile.credentials.subject)
966 return yield* failure(
967 "import",
968 "The transferred identity conflicts with the saved ChatGPT connection.",
969 );
970 yield* saveRegistration(registration);
971 yield* save(profile.credentials, true);
972 });
973 return lock.withPermit(
974 track(
975 "transfer",
976 { flow: "primary_handoff" },
977 validate.pipe(
978 Effect.andThen(controller.adoptCredentials!(withSessionLock(saveImported), stopSessions)),
979 ),
980 ),
981 );
982 };
983 return {
984 controller: { ...controller, reconnectProfile, importProfile },
985 read,
986 access,
987 exportProfile,
988 revoke: lock.withPermit(withSessionLock(remove)),
989 };
990});