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