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

CodexChatGptAuth.ts

1,065 lines43.7 KB

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