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

CodexChatGptAuth.ts

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