The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | // @effect-diagnostics nodeBuiltinImport:off - OAuth loopback listener uses Node APIs. |
| 2 | import * as NodeHttp from "node:http"; |
| 3 | import { |
| 4 | ProviderSetupError, |
| 5 | type ChatGptReconnectProfile, |
| 6 | type ChatGptTransferredProfile, |
| 7 | type ProviderInstanceId, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import { codexCallbackUrl } from "@t3tools/shared/codexAuthHandoff"; |
| 10 | import { hashTelemetryId } from "@t3tools/shared/telemetryId"; |
| 11 | import * as Clock from "effect/Clock"; |
| 12 | import * as Cause from "effect/Cause"; |
| 13 | import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; |
| 14 | import { openAiUserId } from "../telemetry/Identify.ts"; |
| 15 | import * as Digest from "effect/crypto/Digest"; |
| 16 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 17 | import * as Signature from "effect/crypto/Signature"; |
| 18 | import * as JoseError from "effect/jose/JoseError"; |
| 19 | import * as Jwks from "effect/jose/Jwks"; |
| 20 | import * as Jwt from "effect/jose/Jwt"; |
| 21 | import * as Base64Url from "effect/encoding/Base64Url"; |
| 22 | import * as Hex from "effect/encoding/Hex"; |
| 23 | import * as Exit from "effect/Exit"; |
| 24 | import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts"; |
| 25 | import * as Effect from "effect/Effect"; |
| 26 | import * as Option from "effect/Option"; |
| 27 | import * as Schema from "effect/Schema"; |
| 28 | import * as Semaphore from "effect/Semaphore"; |
| 29 | import * as ProviderAuthFlow from "@t3tools/provider-core/server/providerAuthFlow"; |
| 30 | import type { ProviderAuthFlowContext } from "@t3tools/provider-core/server/providerAuthFlow"; |
| 31 | import { HttpClient, HttpClientRequest } from "effect/http"; |
| 32 | import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; |
| 33 | import { withChatGptSessionLock } from "./CodexChatGptSessionLock.ts"; |
| 34 | import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; |
| 35 | import * as ServerSettings from "../serverSettings.ts"; |
| 36 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 37 | |
| 38 | const isSetupError = Schema.is(ProviderSetupError); |
| 39 | const RESOURCE = "https://api.openai.com/v1"; |
| 40 | const REQUIRED_SCOPE = "chatgpt.tokens.use.direct"; |
| 41 | const DISCOVERY = "https://auth.openai.com/.well-known/openid-configuration"; |
| 42 | const 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 | }); |
| 51 | const 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 | }); |
| 63 | export type CodexChatGptCredentials = typeof Record.Type; |
| 64 | const Sessions = Schema.Struct({ |
| 65 | activeClientId: Schema.NullOr(Schema.String), |
| 66 | sessions: Schema.Array(Record), |
| 67 | }); |
| 68 | const sessionLocks = new WeakMap< |
| 69 | typeof ServerSecretStore.ServerSecretStore.Service, |
| 70 | Map<string, Semaphore.Semaphore> |
| 71 | >(); |
| 72 | const 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 | }); |
| 84 | const RegistrationProfiles = Schema.Struct({ |
| 85 | profiles: Schema.Array(Registration), |
| 86 | lastClientId: Schema.NullOr(Schema.String), |
| 87 | }); |
| 88 | const decodeRegistration = Schema.decodeUnknownEffect( |
| 89 | Schema.fromJsonString(Schema.Union([RegistrationProfiles, Registration])), |
| 90 | ); |
| 91 | const encodeRegistration = Schema.encodeEffect(Schema.fromJsonString(RegistrationProfiles)); |
| 92 | const profileMethodId = (clientId: string) => `chatgpt-profile:${clientId}`; |
| 93 | const 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 | }); |
| 100 | const OAuthError = Schema.Struct({ error: Schema.String }); |
| 101 | const JWKS_CACHE_TTL_MS = 10 * 60 * 1000; |
| 102 | const IdTokenClaims = Schema.Struct({ |
| 103 | sub: Schema.String, |
| 104 | nonce: Schema.optionalKey(Schema.Unknown), |
| 105 | email: Schema.optionalKey(Schema.Unknown), |
| 106 | }); |
| 107 | const decodeKeySet = Schema.decodeUnknownEffect(Jwks.KeySet); |
| 108 | const decodeSessions = Schema.decodeUnknownEffect( |
| 109 | Schema.fromJsonString(Schema.Union([Sessions, Record])), |
| 110 | ); |
| 111 | const encodeSessions = Schema.encodeEffect(Schema.fromJsonString(Sessions)); |
| 112 | const decodeTokens = Schema.decodeUnknownSync(TokenResponse); |
| 113 | const decodeDiscoveryEffect = Schema.decodeUnknownEffect(Discovery); |
| 114 | const decodeOAuthError = Schema.decodeUnknownSync(OAuthError); |
| 115 | |
| 116 | export 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 | let connectionNumber = saved.profiles.length + 1; |
| 391 | while ( |
| 392 | saved.profiles.some((entry) => entry.connectionLabel === `Connection ${connectionNumber}`) |
| 393 | ) |
| 394 | connectionNumber++; |
| 395 | profile = { |
| 396 | ...profile, |
| 397 | connectionLabel: |
| 398 | saved.profiles.find((entry) => entry.clientId === profile.clientId)?.connectionLabel ?? |
| 399 | profile.connectionLabel ?? |
| 400 | `Connection ${connectionNumber}`, |
| 401 | }; |
| 402 | yield* encodeRegistration({ |
| 403 | profiles: [profile, ...saved.profiles.filter((entry) => entry.clientId !== profile.clientId)], |
| 404 | lastClientId: profile.clientId, |
| 405 | }).pipe( |
| 406 | Effect.flatMap((json) => registrationStore.set(new TextEncoder().encode(json))), |
| 407 | Effect.mapError(() => |
| 408 | failure("registration", "Could not save the ChatGPT sign-in registration. Try again."), |
| 409 | ), |
| 410 | ); |
| 411 | }); |
| 412 | const save = Effect.fnUntraced(function* (record: CodexChatGptCredentials, activate = true) { |
| 413 | const saved = yield* readSessions; |
| 414 | yield* writeSessions({ |
| 415 | activeClientId: activate ? record.clientId : saved.activeClientId, |
| 416 | sessions: [ |
| 417 | ...saved.sessions.filter((session) => session.clientId !== record.clientId), |
| 418 | record, |
| 419 | ], |
| 420 | }); |
| 421 | }); |
| 422 | const clearTokens = Effect.gen(function* () { |
| 423 | const saved = yield* readSessions; |
| 424 | const sessions = saved.sessions.filter((session) => session.clientId !== saved.activeClientId); |
| 425 | if (sessions.length) yield* writeSessions({ activeClientId: null, sessions }); |
| 426 | else |
| 427 | yield* store.remove.pipe( |
| 428 | Effect.mapError(() => |
| 429 | failure("disconnect", "Could not clear the ChatGPT connection. Try again."), |
| 430 | ), |
| 431 | ); |
| 432 | }); |
| 433 | const remove = Effect.gen(function* () { |
| 434 | const credentials = yield* read; |
| 435 | if (Option.isSome(credentials)) { |
| 436 | const { clientId, subject, email } = credentials.value; |
| 437 | const saved = yield* readRegistrations; |
| 438 | const profile = saved.profiles.find((entry) => entry.clientId === clientId); |
| 439 | if (profile && (profile.subject === undefined || profile.email === undefined)) |
| 440 | yield* saveRegistration({ ...profile, subject, email }); |
| 441 | } |
| 442 | yield* clearTokens; |
| 443 | }); |
| 444 | const exchange = Effect.fn("CodexChatGptAuth.exchange")(function* (body: URLSearchParams) { |
| 445 | const endpoints = yield* discover; |
| 446 | const response = yield* http |
| 447 | .execute( |
| 448 | HttpClientRequest.post(endpoints.token_endpoint).pipe( |
| 449 | HttpClientRequest.setHeader("accept", "application/json"), |
| 450 | HttpClientRequest.bodyText(body.toString(), "application/x-www-form-urlencoded"), |
| 451 | ), |
| 452 | ) |
| 453 | .pipe( |
| 454 | Effect.flatMap((result) => |
| 455 | result.json.pipe( |
| 456 | Effect.map((raw) => ({ |
| 457 | ok: result.status >= 200 && result.status < 300, |
| 458 | status: result.status, |
| 459 | raw, |
| 460 | })), |
| 461 | ), |
| 462 | ), |
| 463 | Effect.mapError(() => |
| 464 | failure("exchange", "ChatGPT sign-in is temporarily unavailable. Try again."), |
| 465 | ), |
| 466 | ); |
| 467 | if (!response.ok) { |
| 468 | const error = yield* Effect.try({ |
| 469 | try: () => decodeOAuthError(response.raw).error, |
| 470 | catch: () => failure("exchange", "ChatGPT did not accept this sign-in. Try again."), |
| 471 | }); |
| 472 | if ( |
| 473 | body.get("grant_type") === "refresh_token" && |
| 474 | [ |
| 475 | "invalid_grant", |
| 476 | "invalid_refresh_token", |
| 477 | "token_expired", |
| 478 | "refresh_token_expired", |
| 479 | "refresh_token_invalidated", |
| 480 | "refresh_token_reused", |
| 481 | ].includes(error) |
| 482 | ) { |
| 483 | yield* remove; |
| 484 | return yield* failure( |
| 485 | "refresh", |
| 486 | "Your ChatGPT connection expired or was disconnected. Sign in again.", |
| 487 | ); |
| 488 | } |
| 489 | if (error === "invalid_client") |
| 490 | return yield* failure( |
| 491 | "client", |
| 492 | "OpenAI rejected this app's client registration. Check the ChatGPT connection configuration.", |
| 493 | ); |
| 494 | if (body.get("grant_type") === "authorization_code" && error === "invalid_grant") |
| 495 | return yield* failure("code-expired", "This sign-in code expired. Start again."); |
| 496 | return yield* failure( |
| 497 | "exchange", |
| 498 | error === "access_denied" |
| 499 | ? "ChatGPT sign-in was declined. Sign in again when you are ready." |
| 500 | : "ChatGPT could not complete sign-in. Try again.", |
| 501 | ); |
| 502 | } |
| 503 | return yield* Effect.try({ |
| 504 | try: () => decodeTokens(response.raw), |
| 505 | catch: () => |
| 506 | failure("exchange", "ChatGPT returned an invalid token response. Sign in again."), |
| 507 | }); |
| 508 | }); |
| 509 | const earliest = (value: (typeof TokenResponse.Type)["earliest_refresh_at"]) => { |
| 510 | if (value === undefined) return null; |
| 511 | const time = typeof value === "number" ? value * 1000 : Date.parse(value); |
| 512 | return Number.isFinite(time) ? time : null; |
| 513 | }; |
| 514 | const authenticate = Effect.fn("CodexChatGptAuth.authenticate")(function* ( |
| 515 | method: string, |
| 516 | context: ProviderAuthFlowContext, |
| 517 | ) { |
| 518 | const endpoints = yield* discover; |
| 519 | const existing = yield* read; |
| 520 | const previous = Option.getOrUndefined(existing); |
| 521 | const registrations = yield* readRegistrations; |
| 522 | const changingAccount = method === "chatgpt-change-account"; |
| 523 | const selectedClientId = method.startsWith("chatgpt-profile:") |
| 524 | ? method.slice("chatgpt-profile:".length) |
| 525 | : (previous?.clientId ?? registrations.lastClientId); |
| 526 | const savedRegistration = changingAccount |
| 527 | ? undefined |
| 528 | : registrations.profiles.find((profile) => profile.clientId === selectedClientId); |
| 529 | // Legacy localhost registrations cannot change on reauth; register 127.0.0.1 while preserving the verified account. |
| 530 | const legacyCallback = savedRegistration?.redirectUri?.includes("//localhost:") === true; |
| 531 | const registeredClientId = legacyCallback ? undefined : savedRegistration?.clientId; |
| 532 | const selectedTokens = (yield* readSessions).sessions.find( |
| 533 | (session) => session.clientId === selectedClientId, |
| 534 | ); |
| 535 | const randomToken = (size: number) => |
| 536 | random.randomBytes(size).pipe(Effect.map(Base64Url.encode)); |
| 537 | const state = yield* randomToken(32); |
| 538 | const nonce = yield* randomToken(32); |
| 539 | const verifier = yield* randomToken(64); |
| 540 | const returnUrl = |
| 541 | codexAuthReturnUrl(context.returnUrl) ?? codexAuthReturnUrl(options.defaultReturnUrl); |
| 542 | const pageNonce = yield* randomToken(24); |
| 543 | const callback = Promise.withResolvers<{ url: URL; response?: NodeHttp.ServerResponse }>(); |
| 544 | const clientCallback = context.callbackMode === "client"; |
| 545 | let used = false; |
| 546 | const server = clientCallback |
| 547 | ? undefined |
| 548 | : yield* Effect.acquireRelease( |
| 549 | Effect.tryPromise({ |
| 550 | try: () => |
| 551 | new Promise<NodeHttp.Server>((resolve, reject) => { |
| 552 | const callbackBase = "http://127.0.0.1/auth/callback"; |
| 553 | const server = NodeHttp.createServer((request, response) => { |
| 554 | const url = URL.parse(request.url ?? "/", callbackBase); |
| 555 | if (request.method !== "GET" || url?.pathname !== "/auth/callback") { |
| 556 | response.writeHead(404).end(); |
| 557 | return; |
| 558 | } |
| 559 | if (used) { |
| 560 | response.writeHead(410).end("Sign-in is no longer active."); |
| 561 | return; |
| 562 | } |
| 563 | // Reject a stray request without ending the sign-in, so the real redirect still lands. |
| 564 | let returned: URL; |
| 565 | try { |
| 566 | returned = codexCallbackUrl(url.toString(), callbackBase, state); |
| 567 | } catch { |
| 568 | response |
| 569 | .writeHead(400) |
| 570 | .end("This response does not belong to the active sign-in."); |
| 571 | return; |
| 572 | } |
| 573 | used = true; |
| 574 | callback.resolve({ url: returned, response }); |
| 575 | }); |
| 576 | server.once("error", reject); |
| 577 | server.listen(0, "127.0.0.1", () => resolve(server)); |
| 578 | }), |
| 579 | catch: () => |
| 580 | failure("callback", "Could not start the local sign-in callback. Try again."), |
| 581 | }), |
| 582 | (server) => |
| 583 | Effect.promise( |
| 584 | () => |
| 585 | new Promise<void>((resolve) => { |
| 586 | server.closeAllConnections(); |
| 587 | server.close(() => resolve()); |
| 588 | }), |
| 589 | ), |
| 590 | ); |
| 591 | const address = server?.address(); |
| 592 | if (!clientCallback && (!address || typeof address === "string")) |
| 593 | return yield* failure("callback", "Could not start the local sign-in callback."); |
| 594 | // Only the port may vary between attempts; token exchange uses this exact URI. |
| 595 | const port = |
| 596 | address && typeof address !== "string" |
| 597 | ? address.port |
| 598 | : yield* random.intBetween(49_152, 65_536, { halfOpen: true }); |
| 599 | const redirectUri = `http://127.0.0.1:${port}/auth/callback`; |
| 600 | const idTokenHint = selectedTokens?.idToken ?? options.reconnectProfile?.idTokenHint; |
| 601 | const codeChallenge = Base64Url.encode( |
| 602 | yield* digest.digest(Digest.sha256, new TextEncoder().encode(verifier)), |
| 603 | ); |
| 604 | const url = new URL(endpoints.authorization_endpoint); |
| 605 | url.search = new URLSearchParams({ |
| 606 | client_id: registeredClientId ?? "dynamic_agent_client", |
| 607 | ...(registeredClientId |
| 608 | ? { |
| 609 | ...(savedRegistration?.email ? { login_hint: savedRegistration.email } : {}), |
| 610 | ...(idTokenHint ? { id_token_hint: idTokenHint } : {}), |
| 611 | ...(savedRegistration?.sharingEnabled === false || |
| 612 | (selectedTokens && !selectedTokens.scopes.includes(REQUIRED_SCOPE)) |
| 613 | ? { prompt: "consent" } |
| 614 | : {}), |
| 615 | } |
| 616 | : { agent_name_hint: "T3 Code" }), |
| 617 | ext_agent_host_id: hostId, |
| 618 | response_type: "code", |
| 619 | redirect_uri: redirectUri, |
| 620 | scope: "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct", |
| 621 | resource, |
| 622 | state, |
| 623 | nonce, |
| 624 | code_challenge_method: "S256", |
| 625 | code_challenge: codeChallenge, |
| 626 | }).toString(); |
| 627 | yield* context.setInteraction( |
| 628 | { |
| 629 | type: "browser", |
| 630 | id: context.flowId, |
| 631 | url: url.toString(), |
| 632 | requiresConsent: false, |
| 633 | acceptsCallback: true, |
| 634 | }, |
| 635 | undefined, |
| 636 | (callbackUrl) => |
| 637 | Effect.try({ |
| 638 | try: () => { |
| 639 | const returned = codexCallbackUrl(callbackUrl, redirectUri, state); |
| 640 | if (used) throw new Error("used"); |
| 641 | used = true; |
| 642 | callback.resolve({ url: returned }); |
| 643 | }, |
| 644 | catch: () => |
| 645 | failure("complete", "This redirect URL does not belong to the active ChatGPT sign-in."), |
| 646 | }), |
| 647 | ); |
| 648 | const received = yield* Effect.tryPromise({ |
| 649 | try: () => callback.promise, |
| 650 | catch: () => failure("callback", "ChatGPT sign-in could not be completed."), |
| 651 | }); |
| 652 | const returned = received.url; |
| 653 | yield* Effect.gen(function* () { |
| 654 | if (returned.searchParams.get("state") !== state) |
| 655 | return yield* failure("callback", "ChatGPT sign-in could not be verified. Start again."); |
| 656 | if (returned.searchParams.has("error")) |
| 657 | return yield* failure( |
| 658 | "callback", |
| 659 | returned.searchParams.get("error") === "access_denied" |
| 660 | ? "ChatGPT sign-in was declined. Sign in again when you are ready." |
| 661 | : "ChatGPT sign-in could not be completed. Start again.", |
| 662 | ); |
| 663 | const code = returned.searchParams.get("code"); |
| 664 | const clientId = registeredClientId ?? returned.searchParams.get("client_id"); |
| 665 | if ( |
| 666 | !code || |
| 667 | !clientId || |
| 668 | !clientId.startsWith("oaiapp_") || |
| 669 | (registeredClientId && |
| 670 | returned.searchParams.has("client_id") && |
| 671 | returned.searchParams.get("client_id") !== registeredClientId) |
| 672 | ) |
| 673 | return yield* failure( |
| 674 | "callback", |
| 675 | "ChatGPT registration is incomplete. Start sign-in again.", |
| 676 | ); |
| 677 | yield* context.verifying; |
| 678 | const tokens = yield* exchange( |
| 679 | new URLSearchParams({ |
| 680 | grant_type: "authorization_code", |
| 681 | client_id: clientId, |
| 682 | code, |
| 683 | code_verifier: verifier, |
| 684 | redirect_uri: redirectUri, |
| 685 | resource, |
| 686 | }), |
| 687 | ).pipe( |
| 688 | Effect.catch((error) => |
| 689 | Effect.gen(function* () { |
| 690 | if (error.operation === "code-expired") { |
| 691 | if (!registeredClientId) |
| 692 | yield* withSessionLock(saveRegistration({ clientId, redirectUri })); |
| 693 | return yield* failure( |
| 694 | "exchange", |
| 695 | "This sign-in code expired. Reconnect the saved ChatGPT profile to start a fresh sign-in.", |
| 696 | ); |
| 697 | } |
| 698 | return yield* error; |
| 699 | }), |
| 700 | ), |
| 701 | ); |
| 702 | if (!tokens.id_token) |
| 703 | return yield* failure( |
| 704 | "verify", |
| 705 | "ChatGPT did not return a verified identity. Sign in again.", |
| 706 | ); |
| 707 | const identity = yield* verifyIdToken(tokens.id_token, clientId).pipe( |
| 708 | Effect.flatMap(({ claims }) => |
| 709 | claims.nonce === nonce |
| 710 | ? Effect.succeed({ |
| 711 | subject: claims.sub, |
| 712 | email: typeof claims.email === "string" ? claims.email : null, |
| 713 | }) |
| 714 | : Effect.fail(failure("verify", "identity")), |
| 715 | ), |
| 716 | Effect.mapError(() => |
| 717 | failure("verify", "ChatGPT sign-in could not be verified. Start again."), |
| 718 | ), |
| 719 | ); |
| 720 | const expectedSubject = |
| 721 | savedRegistration?.subject ?? |
| 722 | (previous?.clientId === registeredClientId ? previous?.subject : undefined); |
| 723 | // Compare subjects only within a registration; legacy callback migration creates a new client. |
| 724 | if (registeredClientId && expectedSubject && identity.subject !== expectedSubject) |
| 725 | return yield* failure( |
| 726 | "verify", |
| 727 | "This sign-in returned a different ChatGPT account. Use the different-account sign-in option instead. Your saved connection is unchanged.", |
| 728 | ); |
| 729 | const knownProfile = registrations.profiles.find((profile) => profile.clientId === clientId); |
| 730 | if ( |
| 731 | knownProfile && |
| 732 | ((knownProfile.redirectUri && |
| 733 | (() => { |
| 734 | const original = new URL(knownProfile.redirectUri); |
| 735 | const current = new URL(redirectUri); |
| 736 | return ( |
| 737 | original.protocol !== current.protocol || |
| 738 | original.hostname !== current.hostname || |
| 739 | original.pathname !== current.pathname |
| 740 | ); |
| 741 | })()) || |
| 742 | (knownProfile.subject && knownProfile.subject !== identity.subject)) |
| 743 | ) |
| 744 | return yield* failure( |
| 745 | "verify", |
| 746 | "ChatGPT returned a conflicting account registration. Start again.", |
| 747 | ); |
| 748 | if (tokens.token_type.toLowerCase() !== "bearer") |
| 749 | return yield* failure( |
| 750 | "verify", |
| 751 | "ChatGPT returned an unsupported connection. Sign in again.", |
| 752 | ); |
| 753 | const scopes = tokens.scope.split(/\s+/).filter(Boolean); |
| 754 | yield* withSessionLock( |
| 755 | Effect.gen(function* () { |
| 756 | yield* saveRegistration({ |
| 757 | clientId, |
| 758 | redirectUri, |
| 759 | sharingEnabled: scopes.includes(REQUIRED_SCOPE), |
| 760 | ...identity, |
| 761 | }); |
| 762 | yield* save( |
| 763 | { |
| 764 | clientId, |
| 765 | accessToken: tokens.access_token, |
| 766 | idToken: tokens.id_token!, |
| 767 | issuer: endpoints.issuer, |
| 768 | refreshToken: tokens.refresh_token ?? null, |
| 769 | expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000, |
| 770 | earliestRefreshAt: earliest(tokens.earliest_refresh_at), |
| 771 | scopes, |
| 772 | ...identity, |
| 773 | }, |
| 774 | scopes.includes(REQUIRED_SCOPE) || Option.isNone(yield* read), |
| 775 | ); |
| 776 | }), |
| 777 | ); |
| 778 | if (!scopes.includes(REQUIRED_SCOPE)) |
| 779 | return yield* failure( |
| 780 | "sharing", |
| 781 | previous && previous.clientId !== clientId |
| 782 | ? "Token sharing was not enabled for the new account. Your existing ChatGPT connection is unchanged." |
| 783 | : "Signed in with ChatGPT, but token sharing is disabled. Sign in again and enable token sharing, or use another provider.", |
| 784 | ); |
| 785 | }).pipe( |
| 786 | Effect.onExit((result) => |
| 787 | Effect.promise( |
| 788 | () => |
| 789 | new Promise<void>((resolve) => { |
| 790 | const response = received.response; |
| 791 | if (!response || response.destroyed) { |
| 792 | resolve(); |
| 793 | return; |
| 794 | } |
| 795 | response.once("close", resolve); |
| 796 | response |
| 797 | .writeHead(200, { |
| 798 | "content-type": "text/html; charset=utf-8", |
| 799 | "cache-control": "no-store", |
| 800 | "referrer-policy": "no-referrer", |
| 801 | "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${pageNonce}'; base-uri 'none'; frame-ancestors 'none'`, |
| 802 | "x-content-type-options": "nosniff", |
| 803 | }) |
| 804 | .end(codexAuthCallbackPage(Exit.isSuccess(result), returnUrl, pageNonce), resolve); |
| 805 | }), |
| 806 | ), |
| 807 | ), |
| 808 | ); |
| 809 | }); |
| 810 | // ID tokens survive renewal but change on sign-in. Bind active children to the |
| 811 | // launch profile without putting an identity token or subject in their argv. |
| 812 | const profileKey = (record: CodexChatGptCredentials) => |
| 813 | digest |
| 814 | .digest( |
| 815 | Digest.sha256, |
| 816 | new TextEncoder().encode( |
| 817 | JSON.stringify([record.clientId, record.subject, record.idToken ?? null]), |
| 818 | ), |
| 819 | ) |
| 820 | .pipe(Effect.map(Hex.encode), Effect.orDie); |
| 821 | const access = Effect.gen(function* () { |
| 822 | const saved = yield* read; |
| 823 | if (Option.isNone(saved)) |
| 824 | return yield* failure("access", "Sign in with ChatGPT to use managed Codex."); |
| 825 | let record = saved.value; |
| 826 | if ( |
| 827 | options.expectedProfileKey !== undefined && |
| 828 | (yield* profileKey(record)) !== options.expectedProfileKey |
| 829 | ) |
| 830 | return yield* failure("access", "The ChatGPT connection changed. Start a new session."); |
| 831 | if (!record.scopes.includes(REQUIRED_SCOPE)) |
| 832 | return yield* failure( |
| 833 | "sharing", |
| 834 | "Token sharing is disabled. Sign in with ChatGPT and enable token sharing.", |
| 835 | ); |
| 836 | const now = yield* Clock.currentTimeMillis; |
| 837 | if (record.expiresAt - now > 60_000) return record; |
| 838 | if (record.earliestRefreshAt !== null && record.earliestRefreshAt > now) { |
| 839 | if (record.expiresAt > now) return record; |
| 840 | return yield* failure( |
| 841 | "refresh", |
| 842 | "ChatGPT cannot renew this connection yet. Try again shortly.", |
| 843 | ); |
| 844 | } |
| 845 | if (!record.refreshToken) { |
| 846 | yield* remove; |
| 847 | return yield* failure("refresh", "Your ChatGPT connection expired. Sign in again."); |
| 848 | } |
| 849 | const tokens = yield* exchange( |
| 850 | new URLSearchParams({ |
| 851 | grant_type: "refresh_token", |
| 852 | client_id: record.clientId, |
| 853 | refresh_token: record.refreshToken, |
| 854 | resource, |
| 855 | }), |
| 856 | ).pipe( |
| 857 | Effect.interruptible, |
| 858 | Effect.timeout("20 seconds"), |
| 859 | Effect.mapError((error) => |
| 860 | error._tag === "ProviderSetupError" && error.operation === "client" |
| 861 | ? error |
| 862 | : failure("refresh", "Could not renew the ChatGPT connection. Retry, or sign in again."), |
| 863 | ), |
| 864 | ); |
| 865 | if (!tokens.refresh_token || tokens.token_type.toLowerCase() !== "bearer") { |
| 866 | return yield* failure("refresh", "ChatGPT returned an invalid renewal. Sign in again."); |
| 867 | } |
| 868 | record = { |
| 869 | ...record, |
| 870 | accessToken: tokens.access_token, |
| 871 | refreshToken: tokens.refresh_token, |
| 872 | expiresAt: (yield* Clock.currentTimeMillis) + tokens.expires_in * 1000, |
| 873 | earliestRefreshAt: earliest(tokens.earliest_refresh_at), |
| 874 | scopes: tokens.scope.split(/\s+/).filter(Boolean), |
| 875 | }; |
| 876 | yield* save(record); |
| 877 | if (!record.scopes.includes(REQUIRED_SCOPE)) |
| 878 | return yield* failure( |
| 879 | "sharing", |
| 880 | "ChatGPT token sharing is no longer enabled. Sign in again.", |
| 881 | ); |
| 882 | return record; |
| 883 | }).pipe(Effect.uninterruptible, withSessionLock, lock.withPermit); |
| 884 | const logout = Effect.gen(function* () { |
| 885 | const credentials = Option.getOrUndefined(yield* read); |
| 886 | let confirmed = !credentials?.refreshToken; |
| 887 | if (credentials?.refreshToken) { |
| 888 | for (let attempt = 0; attempt < 3; attempt++) { |
| 889 | const result = yield* Effect.gen(function* () { |
| 890 | const endpoints = yield* discover; |
| 891 | if (!endpoints.revocation_endpoint) return { confirmed: false, retry: false }; |
| 892 | const response = yield* http.execute( |
| 893 | HttpClientRequest.post(endpoints.revocation_endpoint).pipe( |
| 894 | HttpClientRequest.bodyText( |
| 895 | new URLSearchParams({ |
| 896 | token: credentials.refreshToken!, |
| 897 | token_type_hint: "refresh_token", |
| 898 | client_id: credentials.clientId, |
| 899 | }).toString(), |
| 900 | "application/x-www-form-urlencoded", |
| 901 | ), |
| 902 | ), |
| 903 | ); |
| 904 | return { confirmed: response.status === 200, retry: response.status >= 500 }; |
| 905 | }).pipe( |
| 906 | Effect.timeout("10 seconds"), |
| 907 | Effect.orElseSucceed(() => ({ confirmed: false, retry: true })), |
| 908 | ); |
| 909 | confirmed = result.confirmed; |
| 910 | if (confirmed || !result.retry || attempt === 2) break; |
| 911 | yield* Effect.sleep(attempt === 0 ? "250 millis" : "1 second"); |
| 912 | } |
| 913 | } |
| 914 | yield* remove; |
| 915 | return confirmed |
| 916 | ? undefined |
| 917 | : "Signed out locally. Remote revocation could not be confirmed. Disconnect the app in ChatGPT Settings."; |
| 918 | }); |
| 919 | if (options.reconnectProfile) { |
| 920 | const { idTokenHint: _hint, ...registration } = options.reconnectProfile; |
| 921 | yield* saveRegistration(registration).pipe(Effect.orDie); |
| 922 | } |
| 923 | const controller = yield* ProviderAuthFlow.make({ |
| 924 | instanceId: options.instanceId, |
| 925 | credentialBinding: store.binding, |
| 926 | refreshMethodsAfterAuth: true, |
| 927 | methods: Effect.gen(function* () { |
| 928 | const saved = yield* readRegistrations; |
| 929 | const active = Option.getOrUndefined(yield* read); |
| 930 | const sessions = (yield* readSessions).sessions; |
| 931 | const current = saved.profiles.find( |
| 932 | (profile) => profile.clientId === (active?.clientId ?? saved.lastClientId), |
| 933 | ); |
| 934 | const profiles = current |
| 935 | ? [current, ...saved.profiles.filter((profile) => profile.clientId !== current.clientId)] |
| 936 | : saved.profiles; |
| 937 | return [ |
| 938 | { |
| 939 | id: "chatgpt", |
| 940 | name: "Sign in with ChatGPT", |
| 941 | description: current?.email ? `Reconnect ${current.email}.` : null, |
| 942 | ...(current?.email ? { accountEmail: current.email } : {}), |
| 943 | type: "agent" as const, |
| 944 | }, |
| 945 | { |
| 946 | id: "chatgpt-change-account", |
| 947 | name: "Use a different ChatGPT account", |
| 948 | description: "Register a connection for another ChatGPT account.", |
| 949 | type: "agent" as const, |
| 950 | }, |
| 951 | ...profiles.slice(0, 30).map((profile) => ({ |
| 952 | id: profileMethodId(profile.clientId), |
| 953 | canRemove: |
| 954 | profile.subject === undefined && |
| 955 | !sessions.some((session) => session.clientId === profile.clientId), |
| 956 | name: `${profile.email ?? "ChatGPT account"} · ${profile.connectionLabel}`, |
| 957 | ...(profile.email ? { accountEmail: profile.email } : {}), |
| 958 | description: "Reuse this account's original sign-in registration.", |
| 959 | type: "agent" as const, |
| 960 | })), |
| 961 | ]; |
| 962 | }), |
| 963 | authenticate: (method, context) => |
| 964 | lock.withPermit( |
| 965 | track( |
| 966 | "auth", |
| 967 | { |
| 968 | flow: options.telemetryFlow ?? "direct", |
| 969 | intent: |
| 970 | options.telemetryFlow === "primary_handoff" |
| 971 | ? options.reconnectProfile |
| 972 | ? "saved_profile" |
| 973 | : "different_account" |
| 974 | : method === "chatgpt-change-account" |
| 975 | ? "different_account" |
| 976 | : method.startsWith("chatgpt-profile:") |
| 977 | ? "saved_profile" |
| 978 | : "default", |
| 979 | callbackMode: context.callbackMode ?? "server", |
| 980 | }, |
| 981 | authenticate(method, context), |
| 982 | context.expiresAt, |
| 983 | ), |
| 984 | ), |
| 985 | removeMethod: Effect.fn("CodexChatGptAuth.removeMethod")(function (methodId) { |
| 986 | return lock.withPermit( |
| 987 | withSessionLock( |
| 988 | Effect.gen(function* () { |
| 989 | const saved = yield* readRegistrations; |
| 990 | const profile = saved.profiles.find( |
| 991 | (entry) => profileMethodId(entry.clientId) === methodId, |
| 992 | ); |
| 993 | if ( |
| 994 | !profile || |
| 995 | profile.subject !== undefined || |
| 996 | (yield* readSessions).sessions.some( |
| 997 | (session) => session.clientId === profile.clientId, |
| 998 | ) |
| 999 | ) |
| 1000 | return yield* failure( |
| 1001 | "removeMethod", |
| 1002 | "Only incomplete ChatGPT connections can be removed.", |
| 1003 | ); |
| 1004 | const profiles = saved.profiles.filter((entry) => entry.clientId !== profile.clientId); |
| 1005 | yield* encodeRegistration({ |
| 1006 | profiles, |
| 1007 | lastClientId: |
| 1008 | saved.lastClientId === profile.clientId |
| 1009 | ? (profiles[0]?.clientId ?? null) |
| 1010 | : saved.lastClientId, |
| 1011 | }).pipe( |
| 1012 | Effect.flatMap((json) => registrationStore.set(new TextEncoder().encode(json))), |
| 1013 | Effect.mapError(() => |
| 1014 | failure( |
| 1015 | "removeMethod", |
| 1016 | "Could not remove the saved ChatGPT connection. Try again.", |
| 1017 | ), |
| 1018 | ), |
| 1019 | ); |
| 1020 | }), |
| 1021 | ), |
| 1022 | ); |
| 1023 | }), |
| 1024 | logout: lock.withPermit(withSessionLock(logout)), |
| 1025 | }); |
| 1026 | const reconnectProfile = Effect.fnUntraced(function* (methodId: string) { |
| 1027 | if (methodId === "chatgpt-change-account") return null; |
| 1028 | const registrations = yield* readRegistrations; |
| 1029 | const active = Option.getOrUndefined(yield* read); |
| 1030 | const clientId = methodId.startsWith("chatgpt-profile:") |
| 1031 | ? methodId.slice("chatgpt-profile:".length) |
| 1032 | : (active?.clientId ?? registrations.lastClientId); |
| 1033 | const registration = registrations.profiles.find((profile) => profile.clientId === clientId); |
| 1034 | if (!registration) { |
| 1035 | if (methodId.startsWith("chatgpt-profile:")) |
| 1036 | return yield* failure("export", "This saved connection is no longer available."); |
| 1037 | return null; |
| 1038 | } |
| 1039 | const session = (yield* readSessions).sessions.find((session) => session.clientId === clientId); |
| 1040 | return { ...registration, ...(session?.idToken ? { idTokenHint: session.idToken } : {}) }; |
| 1041 | }); |
| 1042 | const exportProfile = Effect.gen(function* () { |
| 1043 | const credentials = Option.getOrUndefined(yield* read); |
| 1044 | const registration = |
| 1045 | credentials && |
| 1046 | (yield* readRegistrations).profiles.find( |
| 1047 | (profile) => profile.clientId === credentials.clientId, |
| 1048 | ); |
| 1049 | if (!credentials?.idToken || !credentials.issuer || !registration) |
| 1050 | return yield* failure( |
| 1051 | "export", |
| 1052 | "Complete ChatGPT sign-in before transferring this connection.", |
| 1053 | ); |
| 1054 | return { |
| 1055 | registration, |
| 1056 | credentials: { ...credentials, idToken: credentials.idToken, issuer: credentials.issuer }, |
| 1057 | } satisfies ChatGptTransferredProfile; |
| 1058 | }); |
| 1059 | const importProfile = ( |
| 1060 | profile: ChatGptTransferredProfile, |
| 1061 | stopSessions: Effect.Effect<void, ProviderSetupError>, |
| 1062 | ) => { |
| 1063 | const validate = Effect.gen(function* () { |
| 1064 | const endpoints = yield* discover; |
| 1065 | const credentials = profile.credentials; |
| 1066 | if ( |
| 1067 | credentials.clientId !== profile.registration.clientId || |
| 1068 | credentials.issuer !== endpoints.issuer || |
| 1069 | !credentials.scopes.includes(REQUIRED_SCOPE) || |
| 1070 | credentials.expiresAt <= (yield* Clock.currentTimeMillis) |
| 1071 | ) |
| 1072 | return yield* failure( |
| 1073 | "import", |
| 1074 | "The transferred ChatGPT connection is invalid or expired.", |
| 1075 | ); |
| 1076 | const identity = yield* verifyIdToken(credentials.idToken, credentials.clientId).pipe( |
| 1077 | Effect.mapError(() => |
| 1078 | failure("import", "The transferred ChatGPT identity could not be verified."), |
| 1079 | ), |
| 1080 | ); |
| 1081 | if ( |
| 1082 | identity.claims.sub !== credentials.subject || |
| 1083 | profile.registration.subject !== credentials.subject || |
| 1084 | (identity.claims.email ?? null) !== credentials.email || |
| 1085 | (profile.registration.email !== undefined && |
| 1086 | profile.registration.email !== credentials.email) |
| 1087 | ) |
| 1088 | return yield* failure( |
| 1089 | "import", |
| 1090 | "The transferred ChatGPT identity does not match its profile.", |
| 1091 | ); |
| 1092 | }); |
| 1093 | const saveImported = Effect.gen(function* () { |
| 1094 | const { idTokenHint: _hint, ...registration } = profile.registration; |
| 1095 | const existing = (yield* readRegistrations).profiles.find( |
| 1096 | (saved) => saved.clientId === registration.clientId, |
| 1097 | ); |
| 1098 | if (existing?.subject && existing.subject !== profile.credentials.subject) |
| 1099 | return yield* failure( |
| 1100 | "import", |
| 1101 | "The transferred identity conflicts with the saved ChatGPT connection.", |
| 1102 | ); |
| 1103 | yield* saveRegistration(registration); |
| 1104 | yield* save(profile.credentials, true); |
| 1105 | }); |
| 1106 | return lock.withPermit( |
| 1107 | track( |
| 1108 | "transfer", |
| 1109 | { flow: "primary_handoff" }, |
| 1110 | validate.pipe( |
| 1111 | Effect.andThen(controller.adoptCredentials!(withSessionLock(saveImported), stopSessions)), |
| 1112 | ), |
| 1113 | ), |
| 1114 | ); |
| 1115 | }; |
| 1116 | return { |
| 1117 | controller: { ...controller, reconnectProfile, importProfile }, |
| 1118 | read, |
| 1119 | access, |
| 1120 | profileKey, |
| 1121 | exportProfile, |
| 1122 | revoke: lock.withPermit(withSessionLock(remove)), |
| 1123 | }; |
| 1124 | }); |