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

CodexChatGptAuth.ts

1,016 lines41.9 KB

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