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

CodexChatGptAuth.ts

997 lines41.1 KB

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