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

CodexChatGptAuth.ts

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