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 globalFetchInEffect:off - Local mock OAuth server validates the browser callback boundary. |
| 2 | import * as NodeNet from "node:net"; |
| 3 | import * as Context from "effect/Context"; |
| 4 | import * as Scope from "effect/Scope"; |
| 5 | import * as ServerConfig from "../config.ts"; |
| 6 | import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; |
| 7 | import * as NodeHttp from "node:http"; |
| 8 | import * as NodeCrypto from "node:crypto"; |
| 9 | import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto"; |
| 10 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 11 | import { assert, it } from "@effect/vitest"; |
| 12 | import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as Layer from "effect/Layer"; |
| 15 | import * as Option from "effect/Option"; |
| 16 | import * as Stream from "effect/Stream"; |
| 17 | import * as TestClock from "effect/testing/TestClock"; |
| 18 | import * as Fiber from "effect/Fiber"; |
| 19 | import * as Deferred from "effect/Deferred"; |
| 20 | import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts"; |
| 21 | import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; |
| 22 | import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; |
| 23 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 24 | import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; |
| 25 | import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; |
| 26 | import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts"; |
| 27 | |
| 28 | const assertSameCallback = (actual: string | null, expected: string | null) => { |
| 29 | const left = new URL(actual!); |
| 30 | const right = new URL(expected!); |
| 31 | assert.strictEqual(left.protocol, right.protocol); |
| 32 | assert.strictEqual(left.hostname, right.hostname); |
| 33 | assert.strictEqual(left.pathname, right.pathname); |
| 34 | }; |
| 35 | const environmentIds = new WeakMap<Map<string, Uint8Array>, EnvironmentId>(); |
| 36 | const instanceId = ProviderInstanceId.make("managed-codex-test"); |
| 37 | const makeHarnessFor = Effect.fnUntraced(function* ( |
| 38 | instanceId: ProviderInstanceId, |
| 39 | bytes: Map<string, Uint8Array> = new Map(), |
| 40 | failAnalytics = false, |
| 41 | ) { |
| 42 | const environmentId = environmentIds.get(bytes) ?? EnvironmentId.make(NodeCrypto.randomUUID()); |
| 43 | environmentIds.set(bytes, environmentId); |
| 44 | const environment = ServerEnvironment.ServerEnvironmentIdentity.of({ |
| 45 | getEnvironmentId: Effect.succeed(environmentId), |
| 46 | }); |
| 47 | const signingKeyFor = (kid: string) => { |
| 48 | const pair = NodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 }); |
| 49 | return { |
| 50 | kid, |
| 51 | privateKey: pair.privateKey, |
| 52 | publicJwk: { ...pair.publicKey.export({ format: "jwk" }), kid, alg: "RS256", use: "sig" }, |
| 53 | }; |
| 54 | }; |
| 55 | let signingKey = signingKeyFor("test"); |
| 56 | let jwksRequests = 0; |
| 57 | const untrustedKeys = NodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 }); |
| 58 | const signIdToken = (claims: Record<string, unknown>, privateKey: NodeCrypto.KeyObject) => { |
| 59 | const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url"); |
| 60 | const signingInput = `${encode({ alg: "RS256", kid: signingKey.kid })}.${encode(claims)}`; |
| 61 | const signature = NodeCrypto.sign("sha256", Buffer.from(signingInput), privateKey); |
| 62 | return `${signingInput}.${signature.toString("base64url")}`; |
| 63 | }; |
| 64 | const secrets = ServerSecretStore.ServerSecretStore.of({ |
| 65 | get: (name) => Effect.sync(() => Option.fromUndefinedOr(bytes.get(name))), |
| 66 | set: (name, value) => |
| 67 | Effect.sync(() => { |
| 68 | bytes.set(name, value); |
| 69 | }), |
| 70 | remove: (name) => |
| 71 | Effect.sync(() => { |
| 72 | bytes.delete(name); |
| 73 | }), |
| 74 | create: () => Effect.die("unused"), |
| 75 | getOrCreateRandom: () => Effect.die("Host identity must come from the environment."), |
| 76 | }); |
| 77 | let authorize: URL | undefined; |
| 78 | let refreshes = 0; |
| 79 | let revoked = false; |
| 80 | let refreshError: string | undefined; |
| 81 | let revocationStatus = 200; |
| 82 | let codeError: string | undefined; |
| 83 | const revocations: URLSearchParams[] = []; |
| 84 | let transient = false; |
| 85 | let invalidNonce = false; |
| 86 | let identityFailure: "issuer" | "audience" | "signature" | undefined; |
| 87 | let mismatchedState = false; |
| 88 | let callbackClientId: string | undefined; |
| 89 | let subject = "user-test"; |
| 90 | let email = "hidden@example.test"; |
| 91 | let grantScope = "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct"; |
| 92 | let origin = ""; |
| 93 | const exchanges: URLSearchParams[] = []; |
| 94 | const authorizationRequests: URL[] = []; |
| 95 | const callbackResponses: { body: string; headers: Headers }[] = []; |
| 96 | let returnUrl = "http://localhost:7001/welcome"; |
| 97 | const server = yield* Effect.acquireRelease( |
| 98 | Effect.promise( |
| 99 | () => |
| 100 | new Promise<NodeHttp.Server>((resolve) => { |
| 101 | const server = NodeHttp.createServer(async (request, response) => { |
| 102 | response.setHeader("content-type", "application/json"); |
| 103 | if (request.url === "/discovery") { |
| 104 | response.end( |
| 105 | JSON.stringify({ |
| 106 | issuer: origin, |
| 107 | authorization_endpoint: `${origin}/authorize`, |
| 108 | token_endpoint: `${origin}/token`, |
| 109 | jwks_uri: `${origin}/jwks`, |
| 110 | revocation_endpoint: `${origin}/revoke`, |
| 111 | }), |
| 112 | ); |
| 113 | return; |
| 114 | } |
| 115 | if (request.url === "/jwks") { |
| 116 | jwksRequests += 1; |
| 117 | response.end(JSON.stringify({ keys: [signingKey.publicJwk] })); |
| 118 | return; |
| 119 | } |
| 120 | if (request.url === "/revoke") { |
| 121 | let text = ""; |
| 122 | for await (const chunk of request) text += chunk.toString(); |
| 123 | revocations.push(new URLSearchParams(text)); |
| 124 | response.statusCode = revocationStatus; |
| 125 | response.end(); |
| 126 | return; |
| 127 | } |
| 128 | if (request.url === "/token") { |
| 129 | let text = ""; |
| 130 | for await (const chunk of request) text += chunk.toString(); |
| 131 | assert.strictEqual( |
| 132 | request.headers["content-type"], |
| 133 | "application/x-www-form-urlencoded", |
| 134 | ); |
| 135 | assert.isUndefined(request.headers.authorization); |
| 136 | const body = new URLSearchParams(text); |
| 137 | assert.isFalse(body.has("client_secret")); |
| 138 | assert.strictEqual(body.get("resource"), `${origin}/v1`); |
| 139 | exchanges.push(body); |
| 140 | if (body.get("grant_type") === "refresh_token") { |
| 141 | refreshes++; |
| 142 | if (transient) { |
| 143 | response.statusCode = 503; |
| 144 | response.end(JSON.stringify({ error: "temporarily_unavailable" })); |
| 145 | return; |
| 146 | } |
| 147 | if (revoked || refreshError) { |
| 148 | response.statusCode = 400; |
| 149 | response.end(JSON.stringify({ error: refreshError ?? "invalid_grant" })); |
| 150 | return; |
| 151 | } |
| 152 | response.end( |
| 153 | JSON.stringify({ |
| 154 | access_token: `access-${refreshes}`, |
| 155 | refresh_token: `refresh-${refreshes}`, |
| 156 | token_type: "Bearer", |
| 157 | expires_in: 3600, |
| 158 | scope: grantScope, |
| 159 | }), |
| 160 | ); |
| 161 | return; |
| 162 | } |
| 163 | if (codeError) { |
| 164 | response.statusCode = 400; |
| 165 | response.end(JSON.stringify({ error: codeError })); |
| 166 | return; |
| 167 | } |
| 168 | if (!authorize) { |
| 169 | response.statusCode = 400; |
| 170 | response.end("{}"); |
| 171 | return; |
| 172 | } |
| 173 | assertSameCallback( |
| 174 | body.get("redirect_uri"), |
| 175 | authorize.searchParams.get("redirect_uri"), |
| 176 | ); |
| 177 | assert.strictEqual( |
| 178 | NodeCrypto.createHash("sha256") |
| 179 | .update(body.get("code_verifier")!) |
| 180 | .digest("base64url"), |
| 181 | authorize.searchParams.get("code_challenge"), |
| 182 | ); |
| 183 | const token = signIdToken( |
| 184 | { |
| 185 | nonce: invalidNonce ? "incorrect" : authorize.searchParams.get("nonce"), |
| 186 | email, |
| 187 | iss: identityFailure === "issuer" ? "https://untrusted-issuer.test" : origin, |
| 188 | aud: |
| 189 | identityFailure === "audience" |
| 190 | ? "oaiapp_untrusted_audience" |
| 191 | : body.get("client_id")!, |
| 192 | sub: subject, |
| 193 | exp: 4_102_444_800, |
| 194 | }, |
| 195 | identityFailure === "signature" ? untrustedKeys.privateKey : signingKey.privateKey, |
| 196 | ); |
| 197 | response.end( |
| 198 | JSON.stringify({ |
| 199 | access_token: "initial-access", |
| 200 | refresh_token: "initial-refresh", |
| 201 | id_token: token, |
| 202 | token_type: "Bearer", |
| 203 | expires_in: 3600, |
| 204 | scope: grantScope, |
| 205 | }), |
| 206 | ); |
| 207 | return; |
| 208 | } |
| 209 | response.statusCode = 404; |
| 210 | response.end("{}"); |
| 211 | }); |
| 212 | server.listen(0, "127.0.0.1", () => resolve(server)); |
| 213 | }), |
| 214 | ), |
| 215 | (server) => |
| 216 | Effect.promise( |
| 217 | () => |
| 218 | new Promise<void>((resolve) => { |
| 219 | server.closeAllConnections(); |
| 220 | server.close(() => resolve()); |
| 221 | }), |
| 222 | ), |
| 223 | ); |
| 224 | const address = server.address(); |
| 225 | if (!address || typeof address === "string") throw new Error("mock address"); |
| 226 | origin = `http://127.0.0.1:${address.port}`; |
| 227 | const analyticsEvents: { |
| 228 | event: string; |
| 229 | properties: Readonly<Record<string, unknown>> | undefined; |
| 230 | }[] = []; |
| 231 | const analytics = AnalyticsService.AnalyticsService.of({ |
| 232 | record: (event, properties) => |
| 233 | failAnalytics |
| 234 | ? Effect.die("analytics unavailable") |
| 235 | : Effect.sync(() => { |
| 236 | analyticsEvents.push({ event, properties }); |
| 237 | }), |
| 238 | flush: Effect.void, |
| 239 | recordOwners: () => Effect.void, |
| 240 | }); |
| 241 | const auth = yield* makeCodexChatGptAuth({ |
| 242 | instanceId, |
| 243 | discoveryUrl: `${origin}/discovery`, |
| 244 | resource: `${origin}/v1`, |
| 245 | }).pipe( |
| 246 | Effect.provideService(AnalyticsService.AnalyticsService, analytics), |
| 247 | Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), |
| 248 | Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment), |
| 249 | ); |
| 250 | const phase = (phase: string) => |
| 251 | auth.controller.subscribe("owner").pipe( |
| 252 | Stream.filter((state) => state.phase === phase), |
| 253 | Stream.runHead, |
| 254 | Effect.map(Option.getOrThrow), |
| 255 | ); |
| 256 | const prepareCallback = (waiting: { authorizationUrl: string | null }) => { |
| 257 | authorize = new URL(waiting.authorizationUrl!); |
| 258 | authorizationRequests.push(authorize); |
| 259 | const callback = new URL(authorize.searchParams.get("redirect_uri")!); |
| 260 | callback.search = new URLSearchParams({ |
| 261 | code: "authorization-code", |
| 262 | state: mismatchedState ? "unmatched-state" : authorize.searchParams.get("state")!, |
| 263 | ...(callbackClientId |
| 264 | ? { client_id: callbackClientId } |
| 265 | : authorize.searchParams.get("client_id") === "dynamic_agent_client" |
| 266 | ? { client_id: "oaiapp_test" } |
| 267 | : {}), |
| 268 | }).toString(); |
| 269 | return callback; |
| 270 | }; |
| 271 | const startRemote = (methodId?: string) => |
| 272 | Effect.gen(function* () { |
| 273 | yield* auth.controller.start("owner", Effect.void, methodId, returnUrl, "client"); |
| 274 | const waiting = yield* phase("waiting"); |
| 275 | return { waiting, callbackUrl: prepareCallback(waiting).toString() }; |
| 276 | }); |
| 277 | const signInWithMethod = (methodId?: string) => |
| 278 | Effect.gen(function* () { |
| 279 | yield* auth.controller.start("owner", Effect.void, methodId, returnUrl); |
| 280 | const waiting = yield* phase("waiting"); |
| 281 | assert.strictEqual(waiting.interaction?.type, "browser"); |
| 282 | const callback = prepareCallback(waiting); |
| 283 | yield* Effect.promise(async () => { |
| 284 | const response = await fetch(callback); |
| 285 | callbackResponses.push({ body: await response.text(), headers: response.headers }); |
| 286 | }); |
| 287 | }); |
| 288 | const seedExpired = Effect.gen(function* () { |
| 289 | const stored = yield* auth.read; |
| 290 | const record = Option.getOrThrow(stored); |
| 291 | const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId).pipe( |
| 292 | Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), |
| 293 | ); |
| 294 | yield* store.set(new TextEncoder().encode(JSON.stringify({ ...record, expiresAt: 0 }))); |
| 295 | }); |
| 296 | return { |
| 297 | auth, |
| 298 | jwksRequests: () => jwksRequests, |
| 299 | rotateSigningKey: () => { |
| 300 | signingKey = signingKeyFor("rotated"); |
| 301 | }, |
| 302 | analyticsEvents, |
| 303 | secrets, |
| 304 | environmentId, |
| 305 | bytes, |
| 306 | handoff: (profile: Parameters<typeof subscribeChatGptHandoff>[0]["profile"]) => |
| 307 | subscribeChatGptHandoff( |
| 308 | { |
| 309 | instanceId, |
| 310 | environmentId, |
| 311 | attemptId: "test-handoff", |
| 312 | returnUrl, |
| 313 | profile, |
| 314 | }, |
| 315 | "owner", |
| 316 | { discoveryUrl: `${origin}/discovery`, resource: `${origin}/v1` }, |
| 317 | ).pipe(Stream.provideService(AnalyticsService.AnalyticsService, analytics)), |
| 318 | finishCallback: (state: { authorizationUrl: string | null }) => |
| 319 | Effect.promise(() => fetch(prepareCallback(state))), |
| 320 | destination: Effect.gen(function* () { |
| 321 | const destinationBytes = new Map<string, Uint8Array>(); |
| 322 | const destinationStore = ServerSecretStore.ServerSecretStore.of({ |
| 323 | ...secrets, |
| 324 | get: (name) => Effect.sync(() => Option.fromUndefinedOr(destinationBytes.get(name))), |
| 325 | set: (name, value) => |
| 326 | Effect.sync(() => { |
| 327 | destinationBytes.set(name, value); |
| 328 | }), |
| 329 | remove: (name) => |
| 330 | Effect.sync(() => { |
| 331 | destinationBytes.delete(name); |
| 332 | }), |
| 333 | }); |
| 334 | const destination = yield* makeCodexChatGptAuth({ |
| 335 | instanceId, |
| 336 | discoveryUrl: `${origin}/discovery`, |
| 337 | resource: `${origin}/v1`, |
| 338 | }).pipe( |
| 339 | Effect.provideService(AnalyticsService.AnalyticsService, analytics), |
| 340 | Effect.provideService(ServerSecretStore.ServerSecretStore, destinationStore), |
| 341 | Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment), |
| 342 | ); |
| 343 | return { auth: destination, bytes: destinationBytes }; |
| 344 | }), |
| 345 | bindProfile: (expectedProfileKey: string) => |
| 346 | makeCodexChatGptAuth({ |
| 347 | instanceId, |
| 348 | expectedProfileKey, |
| 349 | discoveryUrl: `${origin}/discovery`, |
| 350 | resource: `${origin}/v1`, |
| 351 | }).pipe( |
| 352 | Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), |
| 353 | Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment), |
| 354 | ), |
| 355 | recreateAuth: makeCodexChatGptAuth({ |
| 356 | instanceId, |
| 357 | discoveryUrl: `${origin}/discovery`, |
| 358 | resource: `${origin}/v1`, |
| 359 | }).pipe( |
| 360 | Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), |
| 361 | Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment), |
| 362 | ), |
| 363 | startRemote, |
| 364 | signIn: signInWithMethod(), |
| 365 | changeAccount: signInWithMethod("chatgpt-change-account"), |
| 366 | reconnectProfile: (clientId: string) => signInWithMethod(`chatgpt-profile:${clientId}`), |
| 367 | phase, |
| 368 | seedExpired, |
| 369 | exchanges, |
| 370 | authorizationRequests, |
| 371 | callbackResponses, |
| 372 | setReturnUrl: (value: string) => { |
| 373 | returnUrl = value; |
| 374 | }, |
| 375 | origin, |
| 376 | storedRecords: () => |
| 377 | Array.from(bytes.entries()).flatMap(([, value]) => { |
| 378 | const record = JSON.parse(new TextDecoder().decode(value)); |
| 379 | return record.sessions ?? [record]; |
| 380 | }), |
| 381 | revocations, |
| 382 | setRefreshError: (value: string) => { |
| 383 | refreshError = value; |
| 384 | }, |
| 385 | setRevocationStatus: (value: number) => { |
| 386 | revocationStatus = value; |
| 387 | }, |
| 388 | setCodeError: (value: string | undefined) => { |
| 389 | codeError = value; |
| 390 | }, |
| 391 | refreshes: () => refreshes, |
| 392 | setRevoked: () => { |
| 393 | revoked = true; |
| 394 | }, |
| 395 | setTransient: (value: boolean) => { |
| 396 | transient = value; |
| 397 | }, |
| 398 | setInvalidNonce: () => { |
| 399 | invalidNonce = true; |
| 400 | }, |
| 401 | setIdentityFailure: (value: "issuer" | "audience" | "signature") => { |
| 402 | identityFailure = value; |
| 403 | }, |
| 404 | mismatchCallbackState: (value = true) => { |
| 405 | mismatchedState = value; |
| 406 | }, |
| 407 | setCallbackClientId: (value: string) => { |
| 408 | callbackClientId = value; |
| 409 | }, |
| 410 | setIdentity: (newSubject: string, newEmail: string) => { |
| 411 | subject = newSubject; |
| 412 | email = newEmail; |
| 413 | }, |
| 414 | declineSharing: () => { |
| 415 | grantScope = "openid profile email"; |
| 416 | }, |
| 417 | }; |
| 418 | }); |
| 419 | const makeHarness = makeHarnessFor(instanceId); |
| 420 | const provision = <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 421 | effect.pipe( |
| 422 | Effect.scoped, |
| 423 | Effect.provide( |
| 424 | Layer.mergeAll(FetchHttpClient.layer, NodeServices.layer, NodePlatformCrypto.layer), |
| 425 | ), |
| 426 | ); |
| 427 | it.effect( |
| 428 | "changing account registers a new user-owned client and then reuses that registration", |
| 429 | () => |
| 430 | provision( |
| 431 | Effect.gen(function* () { |
| 432 | const h = yield* makeHarness; |
| 433 | yield* h.signIn; |
| 434 | yield* h.phase("succeeded"); |
| 435 | h.setCallbackClientId("oaiapp_other_account"); |
| 436 | h.setIdentity("other-user", "other@example.test"); |
| 437 | yield* h.changeAccount; |
| 438 | yield* h.phase("succeeded"); |
| 439 | assert.strictEqual( |
| 440 | h.authorizationRequests[1]!.searchParams.get("client_id"), |
| 441 | "dynamic_agent_client", |
| 442 | ); |
| 443 | assert.strictEqual(h.exchanges[1]!.get("client_id"), "oaiapp_other_account"); |
| 444 | const saved = Option.getOrThrow(yield* h.auth.read); |
| 445 | assert.strictEqual(saved.clientId, "oaiapp_other_account"); |
| 446 | assert.strictEqual(saved.subject, "other-user"); |
| 447 | assert.strictEqual(saved.email, "other@example.test"); |
| 448 | const redirectUri = h.authorizationRequests[1]!.searchParams.get("redirect_uri"); |
| 449 | yield* h.signIn; |
| 450 | yield* h.phase("succeeded"); |
| 451 | assert.strictEqual( |
| 452 | h.authorizationRequests[2]!.searchParams.get("client_id"), |
| 453 | "oaiapp_other_account", |
| 454 | ); |
| 455 | assertSameCallback( |
| 456 | h.authorizationRequests[2]!.searchParams.get("redirect_uri"), |
| 457 | redirectUri, |
| 458 | ); |
| 459 | }), |
| 460 | ), |
| 461 | ); |
| 462 | it.effect.each(["identity", "sharing"] as const)( |
| 463 | "failed account change preserves the original credentials and registration: %s", |
| 464 | (failure) => |
| 465 | provision( |
| 466 | Effect.gen(function* () { |
| 467 | const h = yield* makeHarness; |
| 468 | yield* h.signIn; |
| 469 | yield* h.phase("succeeded"); |
| 470 | const before = h.storedRecords(); |
| 471 | h.setCallbackClientId("oaiapp_other_account"); |
| 472 | if (failure === "identity") h.setInvalidNonce(); |
| 473 | else h.declineSharing(); |
| 474 | yield* h.changeAccount; |
| 475 | yield* h.phase("failed"); |
| 476 | assert.strictEqual( |
| 477 | h.authorizationRequests[1]!.searchParams.get("client_id"), |
| 478 | "dynamic_agent_client", |
| 479 | ); |
| 480 | if (failure === "sharing") { |
| 481 | assert.deepEqual( |
| 482 | Option.getOrThrow(yield* h.auth.read), |
| 483 | before.find((record) => record.accessToken), |
| 484 | ); |
| 485 | assert.lengthOf(h.storedRecords().find((record) => record.profiles).profiles, 2); |
| 486 | } else assert.deepEqual(h.storedRecords(), before); |
| 487 | }), |
| 488 | ), |
| 489 | ); |
| 490 | it.effect("reauthorizes on an available port when the original callback port is occupied", () => |
| 491 | provision( |
| 492 | Effect.gen(function* () { |
| 493 | const h = yield* makeHarness; |
| 494 | yield* h.signIn; |
| 495 | yield* h.phase("succeeded"); |
| 496 | const port = Number( |
| 497 | new URL(h.authorizationRequests[0]!.searchParams.get("redirect_uri")!).port, |
| 498 | ); |
| 499 | yield* Effect.acquireRelease( |
| 500 | Effect.promise( |
| 501 | () => |
| 502 | new Promise<NodeHttp.Server>((resolve, reject) => { |
| 503 | const server = NodeHttp.createServer(); |
| 504 | server.once("error", reject); |
| 505 | server.listen(port, "127.0.0.1", () => resolve(server)); |
| 506 | }), |
| 507 | ), |
| 508 | (server) => |
| 509 | Effect.promise(() => new Promise<void>((resolve) => server.close(() => resolve()))), |
| 510 | ); |
| 511 | yield* h.signIn; |
| 512 | yield* h.phase("succeeded"); |
| 513 | assert.notStrictEqual( |
| 514 | Number(new URL(h.authorizationRequests[1]!.searchParams.get("redirect_uri")!).port), |
| 515 | port, |
| 516 | ); |
| 517 | assert.strictEqual(h.authorizationRequests[1]!.searchParams.get("client_id"), "oaiapp_test"); |
| 518 | assert.strictEqual(h.exchanges.length, 2); |
| 519 | }), |
| 520 | ), |
| 521 | ); |
| 522 | it.effect("reauthorizes a registration without persisting its original port", () => |
| 523 | provision( |
| 524 | Effect.gen(function* () { |
| 525 | const bytes = new Map<string, Uint8Array>(); |
| 526 | const h = yield* makeHarnessFor(instanceId, bytes); |
| 527 | yield* h.signIn; |
| 528 | yield* h.phase("succeeded"); |
| 529 | yield* h.auth.revoke; |
| 530 | for (const [key, value] of bytes) { |
| 531 | const record = JSON.parse(new TextDecoder().decode(value)); |
| 532 | if (record.profiles) |
| 533 | bytes.set(key, new TextEncoder().encode(JSON.stringify({ clientId: "oaiapp_test" }))); |
| 534 | } |
| 535 | yield* h.signIn; |
| 536 | yield* h.phase("succeeded"); |
| 537 | assert.strictEqual(h.authorizationRequests[1]!.searchParams.get("client_id"), "oaiapp_test"); |
| 538 | assert.strictEqual(new URL(h.exchanges[1]!.get("redirect_uri")!).hostname, "127.0.0.1"); |
| 539 | }), |
| 540 | ), |
| 541 | ); |
| 542 | |
| 543 | it.effect( |
| 544 | "separate Codex accounts register independently and disconnect only their own tokens", |
| 545 | () => |
| 546 | provision( |
| 547 | Effect.gen(function* () { |
| 548 | const bytes = new Map<string, Uint8Array>(); |
| 549 | const personal = yield* makeHarnessFor(ProviderInstanceId.make("codex_personal"), bytes); |
| 550 | const work = yield* makeHarnessFor(ProviderInstanceId.make("codex_work"), bytes); |
| 551 | yield* personal.signIn; |
| 552 | yield* personal.phase("succeeded"); |
| 553 | const personalCredentials = Option.getOrThrow(yield* personal.auth.read); |
| 554 | assert.isTrue(Option.isNone(yield* work.auth.read)); |
| 555 | yield* work.signIn; |
| 556 | yield* work.phase("succeeded"); |
| 557 | assert.strictEqual( |
| 558 | work.authorizationRequests[0]!.searchParams.get("client_id"), |
| 559 | "dynamic_agent_client", |
| 560 | ); |
| 561 | assert.notStrictEqual( |
| 562 | personal.auth.controller.credentialBinding?.key, |
| 563 | work.auth.controller.credentialBinding?.key, |
| 564 | ); |
| 565 | yield* work.auth.controller.logout(Effect.void); |
| 566 | assert.isTrue(Option.isNone(yield* work.auth.read)); |
| 567 | assert.deepEqual(Option.getOrThrow(yield* personal.auth.read), personalCredentials); |
| 568 | }), |
| 569 | ), |
| 570 | ); |
| 571 | it.effect( |
| 572 | "emits the guide's first-time authorization request and fresh reauthorization values", |
| 573 | () => |
| 574 | provision( |
| 575 | Effect.gen(function* () { |
| 576 | const h = yield* makeHarness; |
| 577 | yield* h.signIn; |
| 578 | yield* h.phase("succeeded"); |
| 579 | assert.include( |
| 580 | h.callbackResponses[0]!.body, |
| 581 | 'content="1;url=http://localhost:7001/welcome"', |
| 582 | ); |
| 583 | const first = h.authorizationRequests[0]!; |
| 584 | assert.strictEqual( |
| 585 | first.searchParams.get("ext_agent_host_id"), |
| 586 | `urn:uuid:${h.environmentId}`, |
| 587 | ); |
| 588 | assert.strictEqual(first.origin, h.origin); |
| 589 | assert.strictEqual(first.pathname, "/authorize"); |
| 590 | assert.deepEqual(Array.from(first.searchParams.keys()).sort(), [ |
| 591 | "agent_name_hint", |
| 592 | "client_id", |
| 593 | "code_challenge", |
| 594 | "code_challenge_method", |
| 595 | "ext_agent_host_id", |
| 596 | "nonce", |
| 597 | "redirect_uri", |
| 598 | "resource", |
| 599 | "response_type", |
| 600 | "scope", |
| 601 | "state", |
| 602 | ]); |
| 603 | assert.strictEqual(first.searchParams.get("client_id"), "dynamic_agent_client"); |
| 604 | assert.strictEqual(first.searchParams.get("agent_name_hint"), "T3 Code"); |
| 605 | assert.strictEqual(first.searchParams.get("response_type"), "code"); |
| 606 | assert.strictEqual( |
| 607 | first.searchParams.get("scope"), |
| 608 | "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct", |
| 609 | ); |
| 610 | assert.strictEqual(first.searchParams.get("resource"), `${h.origin}/v1`); |
| 611 | assert.strictEqual(first.searchParams.get("code_challenge_method"), "S256"); |
| 612 | const callback = new URL(first.searchParams.get("redirect_uri")!); |
| 613 | assert.strictEqual(callback.protocol, "http:"); |
| 614 | assert.strictEqual(callback.hostname, "127.0.0.1"); |
| 615 | assert.strictEqual(callback.pathname, "/auth/callback"); |
| 616 | assert.isAbove(Number(callback.port), 0); |
| 617 | for (const key of ["state", "nonce", "code_challenge"]) { |
| 618 | assert.match(first.searchParams.get(key)!, /^[A-Za-z0-9_-]{43}$/u); |
| 619 | } |
| 620 | assert.notStrictEqual(first.searchParams.get("state"), first.searchParams.get("nonce")); |
| 621 | const originalIdToken = Option.getOrThrow(yield* h.auth.read).idToken; |
| 622 | yield* h.signIn; |
| 623 | yield* h.phase("succeeded"); |
| 624 | const second = h.authorizationRequests[1]!; |
| 625 | assert.strictEqual(second.searchParams.get("client_id"), "oaiapp_test"); |
| 626 | assert.isFalse(second.searchParams.has("agent_name_hint")); |
| 627 | assert.strictEqual(second.searchParams.get("login_hint"), "hidden@example.test"); |
| 628 | assert.strictEqual(second.searchParams.get("id_token_hint"), originalIdToken); |
| 629 | assert.strictEqual( |
| 630 | second.searchParams.get("ext_agent_host_id"), |
| 631 | first.searchParams.get("ext_agent_host_id"), |
| 632 | ); |
| 633 | assertSameCallback( |
| 634 | second.searchParams.get("redirect_uri"), |
| 635 | first.searchParams.get("redirect_uri"), |
| 636 | ); |
| 637 | assert.deepEqual( |
| 638 | Array.from(second.searchParams.keys()).sort(), |
| 639 | [ |
| 640 | ...Array.from(first.searchParams.keys()).filter((key) => key !== "agent_name_hint"), |
| 641 | "login_hint", |
| 642 | "id_token_hint", |
| 643 | ].sort(), |
| 644 | ); |
| 645 | for (const key of ["state", "nonce", "code_challenge"]) { |
| 646 | assert.notStrictEqual(first.searchParams.get(key), second.searchParams.get(key)); |
| 647 | } |
| 648 | yield* h.auth.controller.logout(Effect.void); |
| 649 | yield* h.signIn; |
| 650 | yield* h.phase("succeeded"); |
| 651 | const reconnect = h.authorizationRequests[2]!; |
| 652 | assert.strictEqual(reconnect.searchParams.get("client_id"), "oaiapp_test"); |
| 653 | assertSameCallback( |
| 654 | reconnect.searchParams.get("redirect_uri"), |
| 655 | first.searchParams.get("redirect_uri"), |
| 656 | ); |
| 657 | assert.isFalse(reconnect.searchParams.has("agent_name_hint")); |
| 658 | assert.isFalse(reconnect.searchParams.has("id_token_hint")); |
| 659 | assert.strictEqual(reconnect.searchParams.get("login_hint"), "hidden@example.test"); |
| 660 | assert.strictEqual( |
| 661 | reconnect.searchParams.get("ext_agent_host_id"), |
| 662 | first.searchParams.get("ext_agent_host_id"), |
| 663 | ); |
| 664 | assert.strictEqual( |
| 665 | h.exchanges[2]!.get("redirect_uri"), |
| 666 | reconnect.searchParams.get("redirect_uri"), |
| 667 | ); |
| 668 | assert.strictEqual(h.jwksRequests(), 1); |
| 669 | h.rotateSigningKey(); |
| 670 | yield* h.auth.controller.logout(Effect.void); |
| 671 | yield* h.signIn; |
| 672 | yield* h.phase("succeeded"); |
| 673 | assert.strictEqual(h.jwksRequests(), 2); |
| 674 | yield* TestClock.adjust("10 minutes"); |
| 675 | yield* h.auth.controller.logout(Effect.void); |
| 676 | yield* h.signIn; |
| 677 | yield* h.phase("succeeded"); |
| 678 | assert.strictEqual(h.jwksRequests(), 3); |
| 679 | }), |
| 680 | ), |
| 681 | ); |
| 682 | it.effect( |
| 683 | "returns to the initiating client only after sign-in has verified and saved credentials", |
| 684 | () => |
| 685 | provision( |
| 686 | Effect.gen(function* () { |
| 687 | const h = yield* makeHarness; |
| 688 | h.setReturnUrl( |
| 689 | "http://localhost:7001/settings/providers?instanceId=codex_work&code=secret-code", |
| 690 | ); |
| 691 | yield* h.signIn; |
| 692 | assert.isTrue(Option.isSome(yield* h.auth.read)); |
| 693 | const response = h.callbackResponses[0]!; |
| 694 | assert.include(response.headers.get("content-type")!, "text/html"); |
| 695 | assert.strictEqual(response.headers.get("cache-control"), "no-store"); |
| 696 | assert.strictEqual(response.headers.get("referrer-policy"), "no-referrer"); |
| 697 | assert.include(response.headers.get("content-security-policy")!, "default-src 'none'"); |
| 698 | assert.include(response.body, "You're signed in".replace("'", "'")); |
| 699 | assert.include( |
| 700 | response.body, |
| 701 | 'content="1;url=http://localhost:7001/settings/providers?instanceId=codex_work"', |
| 702 | ); |
| 703 | assert.notInclude(response.body, "secret-code"); |
| 704 | assert.include(response.body, 'history.replaceState(null,"","/auth/callback")'); |
| 705 | assert.notInclude(response.body, "authorization-code"); |
| 706 | assert.notInclude(response.body, "initial-access"); |
| 707 | assert.notInclude(response.body, "hidden@example.test"); |
| 708 | }), |
| 709 | ), |
| 710 | ); |
| 711 | it.effect( |
| 712 | "does not redirect to an arbitrary return URL or claim success after verification fails", |
| 713 | () => |
| 714 | provision( |
| 715 | Effect.gen(function* () { |
| 716 | const h = yield* makeHarness; |
| 717 | h.setReturnUrl("https://attacker.example/welcome"); |
| 718 | h.setInvalidNonce(); |
| 719 | yield* h.signIn; |
| 720 | yield* h.phase("failed"); |
| 721 | const response = h.callbackResponses[0]!; |
| 722 | assert.include(response.body, "Sign-in couldn't finish"); |
| 723 | assert.notInclude(response.body, 'http-equiv="refresh"'); |
| 724 | assert.notInclude(response.body, "attacker.example"); |
| 725 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 726 | }), |
| 727 | ), |
| 728 | ); |
| 729 | it.effect( |
| 730 | "verifies registration, PKCE, identity and persists rotating refresh before concurrent access", |
| 731 | () => |
| 732 | provision( |
| 733 | Effect.gen(function* () { |
| 734 | const h = yield* makeHarness; |
| 735 | yield* h.signIn; |
| 736 | yield* h.phase("succeeded"); |
| 737 | assert.strictEqual(Option.getOrThrow(yield* h.auth.read).subject, "user-test"); |
| 738 | assert.strictEqual(h.exchanges[0]?.get("client_id"), "oaiapp_test"); |
| 739 | yield* h.seedExpired; |
| 740 | const records = yield* Effect.all([h.auth.access, h.auth.access], { |
| 741 | concurrency: "unbounded", |
| 742 | }); |
| 743 | assert.strictEqual(h.refreshes(), 1); |
| 744 | assert.strictEqual(records[0].accessToken, "access-1"); |
| 745 | assert.strictEqual(records[1].refreshToken, "refresh-1"); |
| 746 | assert.isNull(h.exchanges[1]?.get("scope")); |
| 747 | yield* h.auth.controller.logout(Effect.void); |
| 748 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 749 | }), |
| 750 | ), |
| 751 | ); |
| 752 | it.effect("rejects invalid ID token nonce without saving credentials", () => |
| 753 | provision( |
| 754 | Effect.gen(function* () { |
| 755 | const h = yield* makeHarness; |
| 756 | h.setInvalidNonce(); |
| 757 | yield* h.signIn; |
| 758 | assert.include((yield* h.phase("failed")).message!, "could not be verified"); |
| 759 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 760 | }), |
| 761 | ), |
| 762 | ); |
| 763 | it.effect("retains identity after declined sharing but never admits inference", () => |
| 764 | provision( |
| 765 | Effect.gen(function* () { |
| 766 | const h = yield* makeHarness; |
| 767 | h.declineSharing(); |
| 768 | yield* h.signIn; |
| 769 | yield* h.phase("failed"); |
| 770 | assert.isTrue(Option.isSome(yield* h.auth.read)); |
| 771 | const result = yield* h.auth.access.pipe(Effect.result); |
| 772 | assert.strictEqual(result._tag, "Failure"); |
| 773 | assert.strictEqual(h.refreshes(), 0); |
| 774 | }), |
| 775 | ), |
| 776 | ); |
| 777 | it.effect("clears revoked refresh credentials and does not replay them", () => |
| 778 | provision( |
| 779 | Effect.gen(function* () { |
| 780 | const h = yield* makeHarness; |
| 781 | yield* h.signIn; |
| 782 | yield* h.phase("succeeded"); |
| 783 | yield* h.seedExpired; |
| 784 | h.setRevoked(); |
| 785 | yield* h.auth.access.pipe(Effect.result); |
| 786 | yield* h.auth.access.pipe(Effect.result); |
| 787 | assert.strictEqual(h.refreshes(), 1); |
| 788 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 789 | }), |
| 790 | ), |
| 791 | ); |
| 792 | |
| 793 | it.effect( |
| 794 | "preserves credentials through temporary renewal failure and retries the latest refresh", |
| 795 | () => |
| 796 | provision( |
| 797 | Effect.gen(function* () { |
| 798 | const h = yield* makeHarness; |
| 799 | yield* h.signIn; |
| 800 | yield* h.phase("succeeded"); |
| 801 | yield* h.seedExpired; |
| 802 | h.setTransient(true); |
| 803 | yield* h.auth.access.pipe(Effect.result); |
| 804 | assert.strictEqual(Option.getOrThrow(yield* h.auth.read).refreshToken, "initial-refresh"); |
| 805 | h.setTransient(false); |
| 806 | const renewed = yield* h.auth.access; |
| 807 | assert.strictEqual(renewed.refreshToken, "refresh-2"); |
| 808 | assert.strictEqual(h.exchanges.at(-1)?.get("refresh_token"), "initial-refresh"); |
| 809 | }), |
| 810 | ), |
| 811 | ); |
| 812 | |
| 813 | it.effect( |
| 814 | "disconnect retains the remembered account profile while a different account registers afresh", |
| 815 | () => |
| 816 | provision( |
| 817 | Effect.gen(function* () { |
| 818 | const h = yield* makeHarness; |
| 819 | yield* h.signIn; |
| 820 | yield* h.phase("succeeded"); |
| 821 | assert.strictEqual( |
| 822 | h.authorizationRequests[0]?.searchParams.get("client_id"), |
| 823 | "dynamic_agent_client", |
| 824 | ); |
| 825 | yield* h.auth.controller.logout(Effect.void); |
| 826 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 827 | assert.deepEqual(h.storedRecords(), [ |
| 828 | { |
| 829 | profiles: [ |
| 830 | { |
| 831 | clientId: "oaiapp_test", |
| 832 | connectionLabel: "Connection 1", |
| 833 | sharingEnabled: true, |
| 834 | redirectUri: h.authorizationRequests[0]!.searchParams.get("redirect_uri"), |
| 835 | subject: "user-test", |
| 836 | email: "hidden@example.test", |
| 837 | }, |
| 838 | ], |
| 839 | lastClientId: "oaiapp_test", |
| 840 | }, |
| 841 | ]); |
| 842 | const disconnected = yield* h.auth.controller |
| 843 | .subscribe("owner") |
| 844 | .pipe(Stream.runHead, Effect.map(Option.getOrThrow)); |
| 845 | assert.include( |
| 846 | disconnected.methods!.find((method) => method.id === "chatgpt")!.description!, |
| 847 | "hidden@example.test", |
| 848 | ); |
| 849 | assert.strictEqual( |
| 850 | disconnected.methods!.find((method) => method.id === "chatgpt")!.accountEmail, |
| 851 | "hidden@example.test", |
| 852 | ); |
| 853 | assert.strictEqual( |
| 854 | disconnected.methods!.find((method) => method.id === "chatgpt-profile:oaiapp_test")! |
| 855 | .accountEmail, |
| 856 | "hidden@example.test", |
| 857 | ); |
| 858 | assert.strictEqual((yield* h.auth.access.pipe(Effect.result))._tag, "Failure"); |
| 859 | assert.strictEqual(h.refreshes(), 0); |
| 860 | h.setCallbackClientId("oaiapp_different_workspace"); |
| 861 | h.setIdentity("different-user", "different@example.test"); |
| 862 | yield* h.changeAccount; |
| 863 | yield* h.phase("succeeded"); |
| 864 | assert.strictEqual( |
| 865 | h.authorizationRequests[1]?.searchParams.get("client_id"), |
| 866 | "dynamic_agent_client", |
| 867 | ); |
| 868 | assert.strictEqual(h.exchanges[1]?.get("client_id"), "oaiapp_different_workspace"); |
| 869 | assert.strictEqual(Option.getOrThrow(yield* h.auth.read).subject, "different-user"); |
| 870 | }), |
| 871 | ), |
| 872 | ); |
| 873 | |
| 874 | it.effect("rejects mismatched callback state and keeps waiting for the real redirect", () => |
| 875 | provision( |
| 876 | Effect.gen(function* () { |
| 877 | const h = yield* makeHarness; |
| 878 | h.mismatchCallbackState(); |
| 879 | yield* h.signIn; |
| 880 | assert.include(h.callbackResponses[0]!.body, "does not belong to the active sign-in"); |
| 881 | assert.strictEqual(h.exchanges.length, 0); |
| 882 | assert.deepEqual(h.storedRecords(), []); |
| 883 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 884 | h.mismatchCallbackState(false); |
| 885 | const waiting = yield* h.phase("waiting"); |
| 886 | const redirectUri = new URL(waiting.authorizationUrl!).searchParams.get("redirect_uri")!; |
| 887 | const unparsable = yield* Effect.promise(() => fetch(`${new URL(redirectUri).origin}//`)); |
| 888 | assert.strictEqual(unparsable.status, 404); |
| 889 | yield* h.finishCallback(waiting); |
| 890 | yield* h.phase("succeeded"); |
| 891 | assert.strictEqual(h.exchanges.length, 1); |
| 892 | }), |
| 893 | ), |
| 894 | ); |
| 895 | it.effect.each(["issuer", "audience", "signature"] as const)( |
| 896 | "rejects ID token %s verification before saving tokens or registration", |
| 897 | (invalidClaim) => |
| 898 | provision( |
| 899 | Effect.gen(function* () { |
| 900 | const h = yield* makeHarness; |
| 901 | h.setIdentityFailure(invalidClaim); |
| 902 | yield* h.signIn; |
| 903 | assert.include((yield* h.phase("failed")).message!, "could not be verified"); |
| 904 | assert.strictEqual(h.exchanges.length, 1); |
| 905 | assert.deepEqual(h.storedRecords(), []); |
| 906 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 907 | }), |
| 908 | ), |
| 909 | ); |
| 910 | it.effect.each([ |
| 911 | { revoked: false, label: "without changing the current account" }, |
| 912 | { revoked: true, label: "after token removal" }, |
| 913 | ])("rejects conflicting callback client ID on reauthorization $label", ({ revoked }) => |
| 914 | provision( |
| 915 | Effect.gen(function* () { |
| 916 | const h = yield* makeHarness; |
| 917 | yield* h.signIn; |
| 918 | yield* h.phase("succeeded"); |
| 919 | if (revoked) yield* h.auth.revoke; |
| 920 | const before = h.storedRecords(); |
| 921 | h.setCallbackClientId("oaiapp_untrusted_callback"); |
| 922 | yield* h.signIn; |
| 923 | assert.include((yield* h.phase("failed")).message!, "registration is incomplete"); |
| 924 | assert.strictEqual(h.authorizationRequests[1]?.searchParams.get("client_id"), "oaiapp_test"); |
| 925 | assert.strictEqual(h.exchanges.length, 1); |
| 926 | assert.deepEqual(h.storedRecords(), before); |
| 927 | assert.strictEqual(Option.isNone(yield* h.auth.read), revoked); |
| 928 | }), |
| 929 | ), |
| 930 | ); |
| 931 | |
| 932 | it.effect( |
| 933 | "completes remote sign-in on the owning environment and reuses its exact callback for reauthorization", |
| 934 | () => |
| 935 | Effect.gen(function* () { |
| 936 | const harness = yield* makeHarnessFor(instanceId); |
| 937 | const first = yield* harness.startRemote(); |
| 938 | assert.isTrue( |
| 939 | first.waiting.interaction?.type === "browser" && first.waiting.interaction.acceptsCallback, |
| 940 | ); |
| 941 | yield* harness.auth.controller.complete("owner", { |
| 942 | flowId: first.waiting.flowId!, |
| 943 | callbackUrl: first.callbackUrl, |
| 944 | }); |
| 945 | yield* harness.phase("succeeded"); |
| 946 | assert.strictEqual(Option.getOrThrow(yield* harness.auth.read).email, "hidden@example.test"); |
| 947 | const second = yield* harness.startRemote(); |
| 948 | assertSameCallback(second.callbackUrl, first.callbackUrl); |
| 949 | assert.strictEqual( |
| 950 | new URL(second.waiting.authorizationUrl!).searchParams.get("client_id"), |
| 951 | "oaiapp_test", |
| 952 | ); |
| 953 | yield* harness.auth.controller.complete("owner", { |
| 954 | flowId: second.waiting.flowId!, |
| 955 | callbackUrl: second.callbackUrl, |
| 956 | }); |
| 957 | yield* harness.phase("succeeded"); |
| 958 | assert.strictEqual(harness.exchanges.length, 2); |
| 959 | }).pipe( |
| 960 | Effect.scoped, |
| 961 | Effect.provide( |
| 962 | Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer, FetchHttpClient.layer), |
| 963 | ), |
| 964 | ), |
| 965 | ); |
| 966 | |
| 967 | it.effect( |
| 968 | "rejects foreign clients and malformed remote callbacks without consuming the owner's sign-in", |
| 969 | () => |
| 970 | Effect.gen(function* () { |
| 971 | const harness = yield* makeHarnessFor(instanceId); |
| 972 | const { waiting, callbackUrl } = yield* harness.startRemote(); |
| 973 | assert.isTrue(Option.isNone(yield* harness.auth.read)); |
| 974 | yield* Effect.flip( |
| 975 | harness.auth.controller.complete("other-client", { flowId: waiting.flowId!, callbackUrl }), |
| 976 | ); |
| 977 | const wrongPort = new URL(callbackUrl); |
| 978 | wrongPort.port = wrongPort.port === "65535" ? "65534" : "65535"; |
| 979 | for (const invalid of [ |
| 980 | wrongPort.toString(), |
| 981 | callbackUrl.replace("/auth/callback", "/other"), |
| 982 | callbackUrl + "&state=foreign", |
| 983 | callbackUrl + "&code=duplicate", |
| 984 | callbackUrl + "&error=access_denied", |
| 985 | callbackUrl.replace("127.0.0.1", "attacker.example"), |
| 986 | ]) { |
| 987 | yield* Effect.flip( |
| 988 | harness.auth.controller.complete("owner", { |
| 989 | flowId: waiting.flowId!, |
| 990 | callbackUrl: invalid, |
| 991 | }), |
| 992 | ); |
| 993 | } |
| 994 | assert.strictEqual(harness.exchanges.length, 0); |
| 995 | assert.isTrue(Option.isNone(yield* harness.auth.read)); |
| 996 | yield* harness.auth.controller.complete("owner", { flowId: waiting.flowId!, callbackUrl }); |
| 997 | yield* harness.phase("succeeded"); |
| 998 | }).pipe( |
| 999 | Effect.scoped, |
| 1000 | Effect.provide( |
| 1001 | Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer, FetchHttpClient.layer), |
| 1002 | ), |
| 1003 | ), |
| 1004 | ); |
| 1005 | |
| 1006 | it.effect("keeps simultaneous remote accounts and environments independent", () => |
| 1007 | Effect.gen(function* () { |
| 1008 | const first = yield* makeHarnessFor(instanceId); |
| 1009 | const second = yield* makeHarnessFor(instanceId); |
| 1010 | second.setIdentity("other-user", "other@example.test"); |
| 1011 | second.setCallbackClientId("oaiapp_other"); |
| 1012 | const a = yield* first.startRemote(); |
| 1013 | const b = yield* second.startRemote(); |
| 1014 | assert.notStrictEqual( |
| 1015 | new URL(a.waiting.authorizationUrl!).searchParams.get("ext_agent_host_id"), |
| 1016 | new URL(b.waiting.authorizationUrl!).searchParams.get("ext_agent_host_id"), |
| 1017 | ); |
| 1018 | yield* Effect.flip( |
| 1019 | first.auth.controller.complete("owner", { |
| 1020 | flowId: a.waiting.flowId!, |
| 1021 | callbackUrl: b.callbackUrl, |
| 1022 | }), |
| 1023 | ); |
| 1024 | yield* first.auth.controller.complete("owner", { |
| 1025 | flowId: a.waiting.flowId!, |
| 1026 | callbackUrl: a.callbackUrl, |
| 1027 | }); |
| 1028 | yield* second.auth.controller.complete("owner", { |
| 1029 | flowId: b.waiting.flowId!, |
| 1030 | callbackUrl: b.callbackUrl, |
| 1031 | }); |
| 1032 | yield* first.phase("succeeded"); |
| 1033 | yield* second.phase("succeeded"); |
| 1034 | assert.strictEqual(Option.getOrThrow(yield* first.auth.read).subject, "user-test"); |
| 1035 | assert.strictEqual(Option.getOrThrow(yield* second.auth.read).subject, "other-user"); |
| 1036 | }).pipe( |
| 1037 | Effect.scoped, |
| 1038 | Effect.provide( |
| 1039 | Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer, FetchHttpClient.layer), |
| 1040 | ), |
| 1041 | ), |
| 1042 | ); |
| 1043 | |
| 1044 | it.effect( |
| 1045 | "reconnects after Disconnect and restart with the same client and host on an available port", |
| 1046 | () => |
| 1047 | provision( |
| 1048 | Effect.gen(function* () { |
| 1049 | const bytes = new Map<string, Uint8Array>(); |
| 1050 | const first = yield* makeHarnessFor(instanceId, bytes); |
| 1051 | yield* first.signIn; |
| 1052 | yield* first.phase("succeeded"); |
| 1053 | const redirectUri = first.authorizationRequests[0]!.searchParams.get("redirect_uri"); |
| 1054 | yield* first.auth.controller.logout(Effect.void); |
| 1055 | const restarted = yield* makeHarnessFor(instanceId, bytes); |
| 1056 | yield* restarted.signIn; |
| 1057 | yield* restarted.phase("succeeded"); |
| 1058 | assert.strictEqual( |
| 1059 | restarted.authorizationRequests[0]!.searchParams.get("client_id"), |
| 1060 | "oaiapp_test", |
| 1061 | ); |
| 1062 | assertSameCallback( |
| 1063 | restarted.authorizationRequests[0]!.searchParams.get("redirect_uri"), |
| 1064 | redirectUri, |
| 1065 | ); |
| 1066 | assert.strictEqual( |
| 1067 | restarted.exchanges[0]!.get("redirect_uri"), |
| 1068 | restarted.authorizationRequests[0]!.searchParams.get("redirect_uri"), |
| 1069 | ); |
| 1070 | assert.strictEqual(Option.getOrThrow(yield* restarted.auth.read).subject, "user-test"); |
| 1071 | }), |
| 1072 | ), |
| 1073 | ); |
| 1074 | |
| 1075 | it.effect.each([ |
| 1076 | { disconnected: false, label: "while connected" }, |
| 1077 | { disconnected: true, label: "after Disconnect" }, |
| 1078 | ])("rejects a different verified identity during saved-profile reauth $label", ({ disconnected }) => |
| 1079 | provision( |
| 1080 | Effect.gen(function* () { |
| 1081 | const h = yield* makeHarness; |
| 1082 | yield* h.signIn; |
| 1083 | yield* h.phase("succeeded"); |
| 1084 | if (disconnected) yield* h.auth.controller.logout(Effect.void); |
| 1085 | const before = h.storedRecords(); |
| 1086 | h.setIdentity("another-user", "another@example.test"); |
| 1087 | yield* h.signIn; |
| 1088 | assert.include((yield* h.phase("failed")).message!, "different ChatGPT account"); |
| 1089 | assert.deepEqual(h.storedRecords(), before); |
| 1090 | assert.strictEqual(Option.isNone(yield* h.auth.read), disconnected); |
| 1091 | }), |
| 1092 | ), |
| 1093 | ); |
| 1094 | |
| 1095 | it.effect( |
| 1096 | "retains both profiles and reuses the original account's client and callback when returning from another account", |
| 1097 | () => |
| 1098 | provision( |
| 1099 | Effect.gen(function* () { |
| 1100 | const bytes = new Map<string, Uint8Array>(); |
| 1101 | const first = yield* makeHarnessFor(instanceId, bytes); |
| 1102 | yield* first.signIn; |
| 1103 | yield* first.phase("succeeded"); |
| 1104 | const redirectUri = first.authorizationRequests[0]!.searchParams.get("redirect_uri"); |
| 1105 | first.setIdentity("other-user", "other@example.test"); |
| 1106 | first.setCallbackClientId("oaiapp_other_account"); |
| 1107 | yield* first.changeAccount; |
| 1108 | const changed = yield* first.phase("succeeded"); |
| 1109 | assert.isTrue( |
| 1110 | changed.methods!.some((method) => method.id === "chatgpt-profile:oaiapp_test"), |
| 1111 | ); |
| 1112 | assert.isTrue( |
| 1113 | changed.methods!.some((method) => method.id === "chatgpt-profile:oaiapp_other_account"), |
| 1114 | ); |
| 1115 | yield* first.auth.controller.logout(Effect.void); |
| 1116 | const restarted = yield* makeHarnessFor(instanceId, bytes); |
| 1117 | yield* restarted.reconnectProfile("oaiapp_test"); |
| 1118 | yield* restarted.phase("succeeded"); |
| 1119 | assert.strictEqual( |
| 1120 | restarted.authorizationRequests[0]!.searchParams.get("client_id"), |
| 1121 | "oaiapp_test", |
| 1122 | ); |
| 1123 | assertSameCallback( |
| 1124 | restarted.authorizationRequests[0]!.searchParams.get("redirect_uri"), |
| 1125 | redirectUri, |
| 1126 | ); |
| 1127 | assert.strictEqual(Option.getOrThrow(yield* restarted.auth.read).subject, "user-test"); |
| 1128 | }), |
| 1129 | ), |
| 1130 | ); |
| 1131 | |
| 1132 | it.effect("preserves legacy profiles with the same email and subject", () => |
| 1133 | provision( |
| 1134 | Effect.gen(function* () { |
| 1135 | const bytes = new Map<string, Uint8Array>(); |
| 1136 | const h = yield* makeHarnessFor(instanceId, bytes); |
| 1137 | yield* h.signIn; |
| 1138 | yield* h.phase("succeeded"); |
| 1139 | const redirectUri = h.authorizationRequests[0]!.searchParams.get("redirect_uri"); |
| 1140 | for (const [key, value] of bytes) { |
| 1141 | const record = JSON.parse(new TextDecoder().decode(value)); |
| 1142 | if (record.profiles) |
| 1143 | bytes.set( |
| 1144 | key, |
| 1145 | new TextEncoder().encode( |
| 1146 | JSON.stringify({ |
| 1147 | ...record, |
| 1148 | profiles: [ |
| 1149 | { ...record.profiles[0], clientId: "oaiapp_old_duplicate" }, |
| 1150 | ...record.profiles, |
| 1151 | ], |
| 1152 | }), |
| 1153 | ), |
| 1154 | ); |
| 1155 | } |
| 1156 | const restarted = yield* makeHarnessFor(instanceId, bytes); |
| 1157 | const state = yield* restarted.auth.controller.subscribe("owner").pipe( |
| 1158 | Stream.filter((state) => state.methods != null), |
| 1159 | Stream.runHead, |
| 1160 | Effect.map(Option.getOrThrow), |
| 1161 | ); |
| 1162 | assert.deepEqual( |
| 1163 | state |
| 1164 | .methods!.filter((method) => method.id.startsWith("chatgpt-profile:")) |
| 1165 | .map((method) => method.id), |
| 1166 | ["chatgpt-profile:oaiapp_test", "chatgpt-profile:oaiapp_old_duplicate"], |
| 1167 | ); |
| 1168 | yield* restarted.signIn; |
| 1169 | yield* restarted.phase("succeeded"); |
| 1170 | assert.strictEqual( |
| 1171 | restarted.authorizationRequests[0]!.searchParams.get("client_id"), |
| 1172 | "oaiapp_test", |
| 1173 | ); |
| 1174 | assertSameCallback( |
| 1175 | restarted.authorizationRequests[0]!.searchParams.get("redirect_uri"), |
| 1176 | redirectUri, |
| 1177 | ); |
| 1178 | assert.lengthOf(restarted.storedRecords().find((record) => record.profiles).profiles, 2); |
| 1179 | }), |
| 1180 | ), |
| 1181 | ); |
| 1182 | |
| 1183 | it.effect("keeps distinct verified identities even when their email matches", () => |
| 1184 | provision( |
| 1185 | Effect.gen(function* () { |
| 1186 | const h = yield* makeHarness; |
| 1187 | yield* h.signIn; |
| 1188 | yield* h.phase("succeeded"); |
| 1189 | h.setIdentity("other-user", "hidden@example.test"); |
| 1190 | h.setCallbackClientId("oaiapp_other_account"); |
| 1191 | yield* h.changeAccount; |
| 1192 | const changed = yield* h.phase("succeeded"); |
| 1193 | assert.lengthOf( |
| 1194 | changed.methods!.filter((method) => method.id.startsWith("chatgpt-profile:")), |
| 1195 | 2, |
| 1196 | ); |
| 1197 | }), |
| 1198 | ), |
| 1199 | ); |
| 1200 | |
| 1201 | it.effect( |
| 1202 | "migrates a legacy registration and retains its verified identity when credentials are cleared", |
| 1203 | () => |
| 1204 | provision( |
| 1205 | Effect.gen(function* () { |
| 1206 | const bytes = new Map<string, Uint8Array>(); |
| 1207 | const first = yield* makeHarnessFor(instanceId, bytes); |
| 1208 | yield* first.signIn; |
| 1209 | yield* first.phase("succeeded"); |
| 1210 | const redirectUri = first.authorizationRequests[0]!.searchParams.get("redirect_uri"); |
| 1211 | for (const [key, value] of bytes) { |
| 1212 | const saved = JSON.parse(new TextDecoder().decode(value)); |
| 1213 | if (saved.profiles) |
| 1214 | bytes.set( |
| 1215 | key, |
| 1216 | new TextEncoder().encode(JSON.stringify({ clientId: "oaiapp_test", redirectUri })), |
| 1217 | ); |
| 1218 | } |
| 1219 | yield* first.auth.revoke; |
| 1220 | assert.deepEqual(first.storedRecords(), [ |
| 1221 | { |
| 1222 | profiles: [ |
| 1223 | { |
| 1224 | clientId: "oaiapp_test", |
| 1225 | connectionLabel: "Connection 1", |
| 1226 | redirectUri, |
| 1227 | subject: "user-test", |
| 1228 | email: "hidden@example.test", |
| 1229 | }, |
| 1230 | ], |
| 1231 | lastClientId: "oaiapp_test", |
| 1232 | }, |
| 1233 | ]); |
| 1234 | const restarted = yield* makeHarnessFor(instanceId, bytes); |
| 1235 | restarted.setIdentity("another-user", "another@example.test"); |
| 1236 | yield* restarted.signIn; |
| 1237 | assert.include((yield* restarted.phase("failed")).message!, "different ChatGPT account"); |
| 1238 | assert.isTrue(Option.isNone(yield* restarted.auth.read)); |
| 1239 | assert.strictEqual( |
| 1240 | restarted.authorizationRequests[0]!.searchParams.get("ext_agent_host_id"), |
| 1241 | first.authorizationRequests[0]!.searchParams.get("ext_agent_host_id"), |
| 1242 | ); |
| 1243 | }), |
| 1244 | ), |
| 1245 | ); |
| 1246 | |
| 1247 | it.effect("declined sharing on an older profile does not replace the active account", () => |
| 1248 | provision( |
| 1249 | Effect.gen(function* () { |
| 1250 | const h = yield* makeHarness; |
| 1251 | yield* h.signIn; |
| 1252 | yield* h.phase("succeeded"); |
| 1253 | h.setIdentity("other-user", "other@example.test"); |
| 1254 | h.setCallbackClientId("oaiapp_other_account"); |
| 1255 | yield* h.changeAccount; |
| 1256 | yield* h.phase("succeeded"); |
| 1257 | const before = h.storedRecords(); |
| 1258 | h.setIdentity("user-test", "hidden@example.test"); |
| 1259 | h.setCallbackClientId("oaiapp_test"); |
| 1260 | h.declineSharing(); |
| 1261 | yield* h.reconnectProfile("oaiapp_test"); |
| 1262 | assert.include( |
| 1263 | (yield* h.phase("failed")).message!, |
| 1264 | "existing ChatGPT connection is unchanged", |
| 1265 | ); |
| 1266 | assert.deepEqual( |
| 1267 | Option.getOrThrow(yield* h.auth.read), |
| 1268 | before.find((record) => record.clientId === "oaiapp_other_account"), |
| 1269 | ); |
| 1270 | }), |
| 1271 | ), |
| 1272 | ); |
| 1273 | |
| 1274 | it.effect.each([ |
| 1275 | "invalid_grant", |
| 1276 | "invalid_refresh_token", |
| 1277 | "token_expired", |
| 1278 | "refresh_token_expired", |
| 1279 | "refresh_token_invalidated", |
| 1280 | "refresh_token_reused", |
| 1281 | "invalid_client", |
| 1282 | "invalid_token", |
| 1283 | ])("refresh recovery follows the machine-readable code: %s", (code) => |
| 1284 | provision( |
| 1285 | Effect.gen(function* () { |
| 1286 | const h = yield* makeHarness; |
| 1287 | yield* h.signIn; |
| 1288 | yield* h.phase("succeeded"); |
| 1289 | yield* h.seedExpired; |
| 1290 | h.setRefreshError(code); |
| 1291 | yield* Effect.flip(h.auth.access); |
| 1292 | assert.strictEqual( |
| 1293 | Option.isNone(yield* h.auth.read), |
| 1294 | !["invalid_client", "invalid_token"].includes(code), |
| 1295 | ); |
| 1296 | assert.isTrue( |
| 1297 | h |
| 1298 | .storedRecords() |
| 1299 | .some((record) => |
| 1300 | record.profiles?.some( |
| 1301 | (profile: { clientId: string }) => profile.clientId === "oaiapp_test", |
| 1302 | ), |
| 1303 | ), |
| 1304 | ); |
| 1305 | }), |
| 1306 | ), |
| 1307 | ); |
| 1308 | |
| 1309 | it.effect( |
| 1310 | "logout revokes the latest refresh token with the selected client and clears its ID hint", |
| 1311 | () => |
| 1312 | provision( |
| 1313 | Effect.gen(function* () { |
| 1314 | const h = yield* makeHarness; |
| 1315 | yield* h.signIn; |
| 1316 | yield* h.phase("succeeded"); |
| 1317 | const host = h.authorizationRequests[0]!.searchParams.get("ext_agent_host_id"); |
| 1318 | assert.match(host!, /^urn:uuid:[0-9a-f-]{36}$/u); |
| 1319 | yield* h.seedExpired; |
| 1320 | yield* h.auth.access; |
| 1321 | const state = yield* h.auth.controller.logout(Effect.void); |
| 1322 | assert.strictEqual(state.message, "Signed out."); |
| 1323 | assert.deepEqual(Array.from(h.revocations[0]!), [ |
| 1324 | ["token", "refresh-1"], |
| 1325 | ["token_type_hint", "refresh_token"], |
| 1326 | ["client_id", "oaiapp_test"], |
| 1327 | ]); |
| 1328 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 1329 | yield* h.signIn; |
| 1330 | yield* h.phase("succeeded"); |
| 1331 | assert.isFalse(h.authorizationRequests[1]!.searchParams.has("id_token_hint")); |
| 1332 | assert.strictEqual(h.authorizationRequests[1]!.searchParams.get("ext_agent_host_id"), host); |
| 1333 | }), |
| 1334 | ), |
| 1335 | ); |
| 1336 | |
| 1337 | it.effect( |
| 1338 | "reauth hints come from the selected profile, including after another profile logs out", |
| 1339 | () => |
| 1340 | provision( |
| 1341 | Effect.gen(function* () { |
| 1342 | const h = yield* makeHarness; |
| 1343 | yield* h.signIn; |
| 1344 | yield* h.phase("succeeded"); |
| 1345 | const personal = Option.getOrThrow(yield* h.auth.read); |
| 1346 | h.setCallbackClientId("oaiapp_work"); |
| 1347 | h.setIdentity("work-user", "work@example.test"); |
| 1348 | yield* h.changeAccount; |
| 1349 | yield* h.phase("succeeded"); |
| 1350 | assert.isFalse(h.authorizationRequests[1]!.searchParams.has("id_token_hint")); |
| 1351 | assert.isFalse(h.authorizationRequests[1]!.searchParams.has("login_hint")); |
| 1352 | yield* h.auth.controller.logout(Effect.void); |
| 1353 | h.setCallbackClientId("oaiapp_test"); |
| 1354 | h.setIdentity("user-test", "hidden@example.test"); |
| 1355 | yield* h.reconnectProfile("oaiapp_test"); |
| 1356 | yield* h.phase("succeeded"); |
| 1357 | assert.strictEqual( |
| 1358 | h.authorizationRequests[2]!.searchParams.get("id_token_hint"), |
| 1359 | personal.idToken, |
| 1360 | ); |
| 1361 | assert.strictEqual( |
| 1362 | h.authorizationRequests[2]!.searchParams.get("login_hint"), |
| 1363 | personal.email, |
| 1364 | ); |
| 1365 | }), |
| 1366 | ), |
| 1367 | ); |
| 1368 | |
| 1369 | it.effect("an expired initial code retains the issued ID for a fresh authorization", () => |
| 1370 | provision( |
| 1371 | Effect.gen(function* () { |
| 1372 | const h = yield* makeHarness; |
| 1373 | h.setCodeError("invalid_grant"); |
| 1374 | yield* h.signIn; |
| 1375 | const failed = yield* h.phase("failed"); |
| 1376 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 1377 | assert.isTrue(failed.methods!.some((method) => method.id === "chatgpt-profile:oaiapp_test")); |
| 1378 | h.setCodeError(undefined); |
| 1379 | yield* h.reconnectProfile("oaiapp_test"); |
| 1380 | yield* h.phase("succeeded"); |
| 1381 | assert.strictEqual(h.authorizationRequests[1]!.searchParams.get("client_id"), "oaiapp_test"); |
| 1382 | assert.notStrictEqual( |
| 1383 | h.authorizationRequests[0]!.searchParams.get("state"), |
| 1384 | h.authorizationRequests[1]!.searchParams.get("state"), |
| 1385 | ); |
| 1386 | }), |
| 1387 | ), |
| 1388 | ); |
| 1389 | |
| 1390 | it.effect.each([false, true])( |
| 1391 | "removes only the selected incomplete connection across restart (authenticated: %s)", |
| 1392 | (authenticated) => |
| 1393 | provision( |
| 1394 | Effect.gen(function* () { |
| 1395 | const h = yield* makeHarness; |
| 1396 | if (authenticated) { |
| 1397 | yield* h.signIn; |
| 1398 | yield* h.phase("succeeded"); |
| 1399 | } |
| 1400 | const credentials = yield* h.auth.read; |
| 1401 | h.setCallbackClientId("oaiapp_failed"); |
| 1402 | h.setCodeError("invalid_grant"); |
| 1403 | yield* h.changeAccount; |
| 1404 | const failed = yield* h.phase("failed"); |
| 1405 | const methodId = "chatgpt-profile:oaiapp_failed"; |
| 1406 | assert.isTrue(failed.methods!.find((method) => method.id === methodId)?.canRemove); |
| 1407 | h.setCallbackClientId("oaiapp_other_failed"); |
| 1408 | yield* h.changeAccount; |
| 1409 | yield* h.phase("failed"); |
| 1410 | const { waiting } = yield* h.startRemote(methodId); |
| 1411 | const busy = yield* Effect.flip(h.auth.controller.removeMethod!(methodId)); |
| 1412 | assert.include(busy.detail, "Finish or cancel"); |
| 1413 | yield* h.auth.controller.cancel("owner", waiting.flowId!); |
| 1414 | const removed = yield* h.auth.controller.removeMethod!(methodId); |
| 1415 | assert.isFalse(removed.methods!.some((method) => method.id === methodId)); |
| 1416 | assert.isTrue( |
| 1417 | removed.methods!.some((method) => method.id === "chatgpt-profile:oaiapp_other_failed"), |
| 1418 | ); |
| 1419 | assert.deepEqual(yield* h.auth.read, credentials); |
| 1420 | h.setCallbackClientId("oaiapp_new_failed"); |
| 1421 | yield* h.changeAccount; |
| 1422 | const next = yield* h.phase("failed"); |
| 1423 | const profiles = next.methods!.filter((method) => method.id.startsWith("chatgpt-profile:")); |
| 1424 | assert.strictEqual(new Set(profiles.map((method) => method.name)).size, profiles.length); |
| 1425 | yield* h.auth.controller.removeMethod!("chatgpt-profile:oaiapp_new_failed"); |
| 1426 | const last = yield* h.auth.controller.removeMethod!("chatgpt-profile:oaiapp_other_failed"); |
| 1427 | assert.strictEqual( |
| 1428 | last.methods!.filter((method) => method.id.startsWith("chatgpt-profile:")).length, |
| 1429 | authenticated ? 1 : 0, |
| 1430 | ); |
| 1431 | const restarted = yield* h.recreateAuth; |
| 1432 | yield* restarted.controller.refreshMethods!; |
| 1433 | const state = yield* restarted.controller.subscribe("owner").pipe(Stream.runHead); |
| 1434 | assert.deepEqual(Option.getOrThrow(state).methods, last.methods); |
| 1435 | if (authenticated) { |
| 1436 | assert.isFalse( |
| 1437 | last.methods!.find((method) => method.id === "chatgpt-profile:oaiapp_test")?.canRemove, |
| 1438 | ); |
| 1439 | yield* Effect.flip(h.auth.controller.removeMethod!("chatgpt-profile:oaiapp_test")); |
| 1440 | yield* h.auth.controller.logout(Effect.void); |
| 1441 | } |
| 1442 | h.setCodeError(undefined); |
| 1443 | h.setCallbackClientId("oaiapp_test"); |
| 1444 | yield* h.signIn; |
| 1445 | yield* h.phase("succeeded"); |
| 1446 | assert.strictEqual( |
| 1447 | h.authorizationRequests.at(-1)!.searchParams.get("client_id"), |
| 1448 | authenticated ? "oaiapp_test" : "dynamic_agent_client", |
| 1449 | ); |
| 1450 | }), |
| 1451 | ), |
| 1452 | ); |
| 1453 | |
| 1454 | it.effect("identity-only sign-in requests consent on an explicit retry, then rechecks scopes", () => |
| 1455 | provision( |
| 1456 | Effect.gen(function* () { |
| 1457 | const h = yield* makeHarness; |
| 1458 | h.declineSharing(); |
| 1459 | yield* h.signIn; |
| 1460 | yield* h.phase("failed"); |
| 1461 | yield* h.reconnectProfile("oaiapp_test"); |
| 1462 | yield* h.phase("failed"); |
| 1463 | assert.strictEqual(h.authorizationRequests[1]!.searchParams.get("prompt"), "consent"); |
| 1464 | assert.isFalse(h.authorizationRequests[1]!.searchParams.has("force_reconsent")); |
| 1465 | assert.include( |
| 1466 | h.authorizationRequests[1]!.searchParams.get("scope")!, |
| 1467 | "chatgpt.tokens.use.direct", |
| 1468 | ); |
| 1469 | yield* Effect.flip(h.auth.access); |
| 1470 | }), |
| 1471 | ), |
| 1472 | ); |
| 1473 | |
| 1474 | it.effect( |
| 1475 | "controller replacement shares refresh serialization for the same environment session", |
| 1476 | () => |
| 1477 | provision( |
| 1478 | Effect.gen(function* () { |
| 1479 | const h = yield* makeHarness; |
| 1480 | yield* h.signIn; |
| 1481 | yield* h.phase("succeeded"); |
| 1482 | const replacement = yield* h.recreateAuth; |
| 1483 | yield* h.seedExpired; |
| 1484 | const records = yield* Effect.all([h.auth.access, replacement.access], { |
| 1485 | concurrency: "unbounded", |
| 1486 | }); |
| 1487 | assert.strictEqual(h.refreshes(), 1); |
| 1488 | assert.strictEqual(records[0].refreshToken, "refresh-1"); |
| 1489 | assert.deepEqual(records[0], records[1]); |
| 1490 | }), |
| 1491 | ), |
| 1492 | ); |
| 1493 | |
| 1494 | it.effect( |
| 1495 | "old localhost registrations retain their profile while a new client gets its own identity", |
| 1496 | () => |
| 1497 | provision( |
| 1498 | Effect.gen(function* () { |
| 1499 | const bytes = new Map<string, Uint8Array>(); |
| 1500 | const h = yield* makeHarnessFor(instanceId, bytes); |
| 1501 | yield* h.signIn; |
| 1502 | yield* h.phase("succeeded"); |
| 1503 | for (const [key, value] of bytes) { |
| 1504 | const record = JSON.parse(new TextDecoder().decode(value)); |
| 1505 | if (record.profiles) |
| 1506 | bytes.set( |
| 1507 | key, |
| 1508 | new TextEncoder().encode( |
| 1509 | JSON.stringify({ |
| 1510 | ...record, |
| 1511 | profiles: record.profiles.map((profile: { redirectUri: string }) => ({ |
| 1512 | ...profile, |
| 1513 | redirectUri: profile.redirectUri.replace("127.0.0.1", "localhost"), |
| 1514 | })), |
| 1515 | }), |
| 1516 | ), |
| 1517 | ); |
| 1518 | } |
| 1519 | h.setCallbackClientId("oaiapp_migrated"); |
| 1520 | h.setIdentity("new-client-subject", "hidden@example.test"); |
| 1521 | yield* h.signIn; |
| 1522 | yield* h.phase("succeeded"); |
| 1523 | assert.strictEqual( |
| 1524 | h.authorizationRequests[1]!.searchParams.get("client_id"), |
| 1525 | "dynamic_agent_client", |
| 1526 | ); |
| 1527 | assert.strictEqual( |
| 1528 | new URL(h.authorizationRequests[1]!.searchParams.get("redirect_uri")!).hostname, |
| 1529 | "127.0.0.1", |
| 1530 | ); |
| 1531 | assert.strictEqual(Option.getOrThrow(yield* h.auth.read).subject, "new-client-subject"); |
| 1532 | const profiles = (yield* h.phase("succeeded")).methods!; |
| 1533 | assert.isTrue(profiles.some((profile) => profile.id === "chatgpt-profile:oaiapp_test")); |
| 1534 | assert.isTrue(profiles.some((profile) => profile.id === "chatgpt-profile:oaiapp_migrated")); |
| 1535 | yield* h.signIn; |
| 1536 | yield* h.phase("succeeded"); |
| 1537 | assert.strictEqual( |
| 1538 | h.authorizationRequests[2]!.searchParams.get("client_id"), |
| 1539 | "oaiapp_migrated", |
| 1540 | ); |
| 1541 | assert.strictEqual( |
| 1542 | h.authorizationRequests[2]!.searchParams.get("login_hint"), |
| 1543 | "hidden@example.test", |
| 1544 | ); |
| 1545 | assert.isTrue(h.authorizationRequests[2]!.searchParams.has("id_token_hint")); |
| 1546 | }), |
| 1547 | ), |
| 1548 | ); |
| 1549 | |
| 1550 | it.effect("primary completes OAuth and destination imports and owns the refresh session", () => |
| 1551 | provision( |
| 1552 | Effect.gen(function* () { |
| 1553 | const h = yield* makeHarness; |
| 1554 | const destination = yield* h.destination; |
| 1555 | const before = h.bytes.size; |
| 1556 | const waiting = yield* Deferred.make<{ authorizationUrl: string | null }>(); |
| 1557 | const transferred = yield* h.handoff(null).pipe( |
| 1558 | Stream.tap((state) => |
| 1559 | state.phase === "auth" && state.state.phase === "waiting" |
| 1560 | ? Deferred.succeed(waiting, state.state) |
| 1561 | : Effect.void, |
| 1562 | ), |
| 1563 | Stream.filter((state) => state.phase === "finished"), |
| 1564 | Stream.runHead, |
| 1565 | Effect.map(Option.getOrThrow), |
| 1566 | Effect.forkChild, |
| 1567 | ); |
| 1568 | yield* h.finishCallback(yield* Deferred.await(waiting)); |
| 1569 | const result = yield* Fiber.join(transferred); |
| 1570 | assert.strictEqual(result.phase, "finished"); |
| 1571 | if (result.phase !== "finished") return; |
| 1572 | assert.strictEqual(h.bytes.size, before); |
| 1573 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 1574 | let stopped = false; |
| 1575 | const imported = yield* destination.auth.controller.importProfile!( |
| 1576 | result.profile, |
| 1577 | Effect.sync(() => { |
| 1578 | stopped = true; |
| 1579 | }), |
| 1580 | ); |
| 1581 | assert.isTrue(stopped); |
| 1582 | assert.strictEqual(imported.phase, "succeeded"); |
| 1583 | assert.deepStrictEqual( |
| 1584 | h.analyticsEvents.map(({ event }) => event), |
| 1585 | [ |
| 1586 | "chatgpt.auth.started", |
| 1587 | "chatgpt.auth.completed", |
| 1588 | "chatgpt.transfer.started", |
| 1589 | "chatgpt.transfer.completed", |
| 1590 | ], |
| 1591 | ); |
| 1592 | assert.isTrue( |
| 1593 | h.analyticsEvents.every(({ properties }) => properties?.flow === "primary_handoff"), |
| 1594 | ); |
| 1595 | assert.strictEqual(h.analyticsEvents[1]?.properties?.outcome, "succeeded"); |
| 1596 | assert.strictEqual(h.analyticsEvents[3]?.properties?.outcome, "succeeded"); |
| 1597 | assert.notProperty(h.analyticsEvents[1]?.properties ?? {}, "connectedAccountCount"); |
| 1598 | assert.strictEqual(h.analyticsEvents[1]?.properties?.intent, "different_account"); |
| 1599 | assert.strictEqual(h.analyticsEvents[3]?.properties?.connectedAccountCount, 1); |
| 1600 | assert.strictEqual(h.analyticsEvents[3]?.properties?.savedConnectionCount, 1); |
| 1601 | const saved = Option.getOrThrow(yield* destination.auth.read); |
| 1602 | assert.strictEqual(saved.clientId, result.profile.registration.clientId); |
| 1603 | assert.strictEqual(saved.refreshToken, "initial-refresh"); |
| 1604 | const reconnect = yield* destination.auth.controller.reconnectProfile!("chatgpt"); |
| 1605 | assert.strictEqual(reconnect?.idTokenHint, result.profile.credentials.idToken); |
| 1606 | assert.isFalse("refreshToken" in reconnect!); |
| 1607 | const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId).pipe( |
| 1608 | Effect.provideService( |
| 1609 | ServerSecretStore.ServerSecretStore, |
| 1610 | ServerSecretStore.ServerSecretStore.of({ |
| 1611 | get: (name) => Effect.sync(() => Option.fromUndefinedOr(destination.bytes.get(name))), |
| 1612 | set: (name, value) => |
| 1613 | Effect.sync(() => { |
| 1614 | destination.bytes.set(name, value); |
| 1615 | }), |
| 1616 | remove: () => Effect.void, |
| 1617 | create: () => Effect.die("unused"), |
| 1618 | getOrCreateRandom: () => Effect.die("unused"), |
| 1619 | }), |
| 1620 | ), |
| 1621 | ); |
| 1622 | yield* store.set(new TextEncoder().encode(JSON.stringify({ ...saved, expiresAt: 0 }))); |
| 1623 | yield* destination.auth.access; |
| 1624 | assert.strictEqual( |
| 1625 | h.exchanges.filter((entry) => entry.get("grant_type") === "authorization_code").length, |
| 1626 | 1, |
| 1627 | ); |
| 1628 | assert.strictEqual( |
| 1629 | h.exchanges.filter((entry) => entry.get("grant_type") === "refresh_token").length, |
| 1630 | 1, |
| 1631 | ); |
| 1632 | }), |
| 1633 | ), |
| 1634 | ); |
| 1635 | |
| 1636 | it.effect("transferred profiles reject mismatched identities without overwriting credentials", () => |
| 1637 | provision( |
| 1638 | Effect.gen(function* () { |
| 1639 | const h = yield* makeHarness; |
| 1640 | yield* h.signIn; |
| 1641 | yield* h.phase("succeeded"); |
| 1642 | const profile = yield* h.auth.exportProfile; |
| 1643 | const destination = yield* h.destination; |
| 1644 | yield* destination.auth.controller.importProfile!(profile, Effect.void); |
| 1645 | const original = Option.getOrThrow(yield* destination.auth.read); |
| 1646 | for (const credentials of [ |
| 1647 | { ...profile.credentials, subject: "wrong-user" }, |
| 1648 | { ...profile.credentials, clientId: "oaiapp_wrong" }, |
| 1649 | { ...profile.credentials, idToken: "not-a-jwt" }, |
| 1650 | { ...profile.credentials, scopes: ["openid"] }, |
| 1651 | { ...profile.credentials, expiresAt: 0 }, |
| 1652 | ]) { |
| 1653 | const result = yield* destination.auth.controller.importProfile!( |
| 1654 | { ...profile, credentials }, |
| 1655 | Effect.void, |
| 1656 | ).pipe(Effect.result); |
| 1657 | assert.strictEqual(result._tag, "Failure"); |
| 1658 | assert.deepEqual(Option.getOrThrow(yield* destination.auth.read), original); |
| 1659 | } |
| 1660 | }), |
| 1661 | ), |
| 1662 | ); |
| 1663 | |
| 1664 | it.effect("primary handoff reuses the selected registration and ID token hint", () => |
| 1665 | provision( |
| 1666 | Effect.gen(function* () { |
| 1667 | const h = yield* makeHarness; |
| 1668 | yield* h.signIn; |
| 1669 | yield* h.phase("succeeded"); |
| 1670 | const profile = yield* h.auth.controller.reconnectProfile!("chatgpt"); |
| 1671 | const waiting = yield* Deferred.make<{ authorizationUrl: string | null }>(); |
| 1672 | const resultFiber = yield* h.handoff(profile).pipe( |
| 1673 | Stream.tap((state) => |
| 1674 | state.phase === "auth" && state.state.phase === "waiting" |
| 1675 | ? Deferred.succeed(waiting, state.state) |
| 1676 | : Effect.void, |
| 1677 | ), |
| 1678 | Stream.runCollect, |
| 1679 | Effect.forkChild, |
| 1680 | ); |
| 1681 | const state = yield* Deferred.await(waiting); |
| 1682 | const url = new URL(state.authorizationUrl!); |
| 1683 | assert.strictEqual(url.searchParams.get("client_id"), profile!.clientId); |
| 1684 | assert.strictEqual(url.searchParams.get("id_token_hint"), profile!.idTokenHint); |
| 1685 | assert.strictEqual(url.searchParams.get("login_hint"), profile!.email); |
| 1686 | assert.strictEqual(url.searchParams.get("ext_agent_host_id"), `urn:uuid:${h.environmentId}`); |
| 1687 | yield* h.finishCallback(state); |
| 1688 | const results = yield* Fiber.join(resultFiber); |
| 1689 | assert.strictEqual(results.at(-1)?.phase, "finished"); |
| 1690 | }), |
| 1691 | ), |
| 1692 | ); |
| 1693 | |
| 1694 | it.effect( |
| 1695 | "cancelling primary handoff closes its callback listener without saving credentials", |
| 1696 | () => |
| 1697 | provision( |
| 1698 | Effect.gen(function* () { |
| 1699 | const h = yield* makeHarness; |
| 1700 | const waiting = yield* Deferred.make<{ authorizationUrl: string | null }>(); |
| 1701 | const flow = yield* h.handoff(null).pipe( |
| 1702 | Stream.tap((state) => |
| 1703 | state.phase === "auth" && state.state.phase === "waiting" |
| 1704 | ? Deferred.succeed(waiting, state.state) |
| 1705 | : Effect.void, |
| 1706 | ), |
| 1707 | Stream.runDrain, |
| 1708 | Effect.forkChild, |
| 1709 | ); |
| 1710 | const state = yield* Deferred.await(waiting); |
| 1711 | yield* Fiber.interrupt(flow); |
| 1712 | const callback = new URL( |
| 1713 | new URL(state.authorizationUrl!).searchParams.get("redirect_uri")!, |
| 1714 | ); |
| 1715 | const rejected = yield* Effect.promise(() => |
| 1716 | fetch(callback).then( |
| 1717 | () => false, |
| 1718 | () => true, |
| 1719 | ), |
| 1720 | ); |
| 1721 | assert.isTrue(rejected); |
| 1722 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 1723 | }), |
| 1724 | ), |
| 1725 | ); |
| 1726 | |
| 1727 | it.effect("telemetry failures do not fail a verified ChatGPT sign-in", () => |
| 1728 | provision( |
| 1729 | Effect.gen(function* () { |
| 1730 | const h = yield* makeHarnessFor(instanceId, new Map(), true); |
| 1731 | yield* h.signIn; |
| 1732 | const state = yield* h.phase("succeeded"); |
| 1733 | assert.strictEqual(state.phase, "succeeded"); |
| 1734 | assert.isTrue(Option.isSome(yield* h.auth.read)); |
| 1735 | }), |
| 1736 | ), |
| 1737 | ); |
| 1738 | it.effect("a running session renews its bound profile but refuses a replacement sign-in", () => |
| 1739 | provision( |
| 1740 | Effect.gen(function* () { |
| 1741 | const h = yield* makeHarness; |
| 1742 | yield* h.signIn; |
| 1743 | yield* h.phase("succeeded"); |
| 1744 | const profileKey = yield* h.auth.profileKey(Option.getOrThrow(yield* h.auth.read)); |
| 1745 | const first = yield* h.bindProfile(profileKey); |
| 1746 | const second = yield* h.bindProfile(profileKey); |
| 1747 | yield* h.seedExpired; |
| 1748 | const renewed = yield* Effect.all([first.access, second.access], { |
| 1749 | concurrency: "unbounded", |
| 1750 | }); |
| 1751 | assert.equal(h.refreshes(), 1); |
| 1752 | assert.equal(renewed[0].accessToken, "access-1"); |
| 1753 | assert.deepEqual(renewed[0], renewed[1]); |
| 1754 | assert.equal(yield* h.auth.profileKey(renewed[0]), profileKey); |
| 1755 | |
| 1756 | // Reconnecting the same account replaces its sign-in identity, too. |
| 1757 | yield* h.reconnectProfile("oaiapp_test"); |
| 1758 | yield* h.phase("succeeded"); |
| 1759 | const replacement = Option.getOrThrow(yield* h.auth.read); |
| 1760 | assert.equal(replacement.clientId, renewed[0].clientId); |
| 1761 | assert.equal(replacement.subject, renewed[0].subject); |
| 1762 | yield* h.seedExpired; |
| 1763 | assert.equal((yield* first.access.pipe(Effect.flip)).operation, "access"); |
| 1764 | assert.equal(h.refreshes(), 1); |
| 1765 | yield* h.auth.revoke; |
| 1766 | assert.equal((yield* second.access.pipe(Effect.flip)).operation, "access"); |
| 1767 | assert.isTrue(Option.isNone(yield* h.auth.read)); |
| 1768 | }), |
| 1769 | ), |
| 1770 | ); |
| 1771 | |
| 1772 | const makeRenewalBroker = Effect.gen(function* () { |
| 1773 | const oauthEntered = yield* Deferred.make<void>(); |
| 1774 | const oauthRelease = yield* Deferred.make<void>(); |
| 1775 | let pauseOAuth = false; |
| 1776 | const refreshTokens: string[] = []; |
| 1777 | const credentials = { |
| 1778 | clientId: "oaiapp_broker", |
| 1779 | subject: "broker-user", |
| 1780 | idToken: "broker-sign-in", |
| 1781 | email: null, |
| 1782 | accessToken: "expired-access", |
| 1783 | refreshToken: "single-use-refresh", |
| 1784 | expiresAt: 0, |
| 1785 | earliestRefreshAt: null, |
| 1786 | scopes: ["chatgpt.tokens.use.direct"], |
| 1787 | }; |
| 1788 | const environmentId = EnvironmentId.make("00000000-0000-4000-8000-000000000001"); |
| 1789 | const http = HttpClient.make((request) => |
| 1790 | Effect.gen(function* () { |
| 1791 | if (request.url.endsWith("openid-configuration")) { |
| 1792 | return HttpClientResponse.fromWeb( |
| 1793 | request, |
| 1794 | Response.json({ |
| 1795 | issuer: "https://auth.openai.com", |
| 1796 | authorization_endpoint: "https://auth.openai.com/authorize", |
| 1797 | token_endpoint: "https://auth.openai.com/token", |
| 1798 | jwks_uri: "https://auth.openai.com/jwks", |
| 1799 | }), |
| 1800 | ); |
| 1801 | } |
| 1802 | assert.equal(request.url, "https://auth.openai.com/token"); |
| 1803 | assert.equal(request.body._tag, "Uint8Array"); |
| 1804 | if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing refresh body"); |
| 1805 | const body = new URLSearchParams(new TextDecoder().decode(request.body.body)); |
| 1806 | refreshTokens.push(body.get("refresh_token")!); |
| 1807 | yield* Deferred.succeed(oauthEntered, undefined); |
| 1808 | if (pauseOAuth) yield* Deferred.await(oauthRelease); |
| 1809 | return HttpClientResponse.fromWeb( |
| 1810 | request, |
| 1811 | Response.json({ |
| 1812 | access_token: "renewed-access", |
| 1813 | refresh_token: "rotated-refresh", |
| 1814 | expires_in: 3600, |
| 1815 | token_type: "Bearer", |
| 1816 | scope: "chatgpt.tokens.use.direct", |
| 1817 | }), |
| 1818 | ); |
| 1819 | }), |
| 1820 | ); |
| 1821 | return yield* Effect.gen(function* () { |
| 1822 | const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); |
| 1823 | yield* store.set(new TextEncoder().encode(JSON.stringify(credentials))); |
| 1824 | const auth = yield* makeCodexChatGptAuth({ instanceId }); |
| 1825 | const profileKey = yield* auth.profileKey(credentials); |
| 1826 | const scope = yield* Scope.make(); |
| 1827 | yield* Effect.addFinalizer((exit) => Scope.close(scope, exit)); |
| 1828 | const context = yield* Layer.buildWithScope(CodexManagedTokenBroker.layer, scope); |
| 1829 | const broker = Context.get(context, CodexManagedTokenBroker.CodexManagedTokenBroker); |
| 1830 | const endpoint = yield* broker.endpoint; |
| 1831 | yield* Effect.addFinalizer(() => Deferred.succeed(oauthRelease, undefined)); |
| 1832 | return { |
| 1833 | auth, |
| 1834 | store, |
| 1835 | broker, |
| 1836 | endpoint, |
| 1837 | refreshTokens, |
| 1838 | request: { version: 1, instanceId, environmentId, profileKey }, |
| 1839 | oauthEntered, |
| 1840 | oauthRelease, |
| 1841 | pause: () => { |
| 1842 | pauseOAuth = true; |
| 1843 | }, |
| 1844 | }; |
| 1845 | }).pipe( |
| 1846 | Effect.provide(ServerSecretStore.layer), |
| 1847 | Effect.provideService(HttpClient.HttpClient, http), |
| 1848 | Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { |
| 1849 | getEnvironmentId: Effect.succeed(environmentId), |
| 1850 | }), |
| 1851 | ); |
| 1852 | }); |
| 1853 | |
| 1854 | const brokerClient = (endpoint: string, request: unknown) => |
| 1855 | Effect.acquireRelease( |
| 1856 | Effect.callback<{ socket: NodeNet.Socket; response: Promise<string> }, Error>((resume) => { |
| 1857 | const socket = NodeNet.createConnection(endpoint); |
| 1858 | let text = ""; |
| 1859 | socket.setEncoding("utf8"); |
| 1860 | socket.on("data", (chunk) => { |
| 1861 | text += chunk; |
| 1862 | }); |
| 1863 | const response = new Promise<string>((resolve) => socket.once("close", () => resolve(text))); |
| 1864 | socket.on("error", () => {}); |
| 1865 | socket.once("error", (error) => resume(Effect.fail(error))); |
| 1866 | socket.once("connect", () => { |
| 1867 | socket.write(JSON.stringify(request) + "\n"); |
| 1868 | resume(Effect.succeed({ socket, response })); |
| 1869 | }); |
| 1870 | return Effect.sync(() => { |
| 1871 | if (socket.connecting) socket.destroy(); |
| 1872 | }); |
| 1873 | }), |
| 1874 | ({ socket }) => Effect.sync(() => socket.destroy()), |
| 1875 | ); |
| 1876 | const provideBroker = <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 1877 | effect.pipe( |
| 1878 | Effect.scoped, |
| 1879 | Effect.provide( |
| 1880 | ServerConfig.layerTest(process.cwd(), { prefix: "t3-renewal-test-" }).pipe( |
| 1881 | Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer)), |
| 1882 | ), |
| 1883 | ), |
| 1884 | ); |
| 1885 | |
| 1886 | // regression: #16132 a renewal must outlive the Codex helper that asked for it, because the |
| 1887 | // refresh token it spends is single-use. |
| 1888 | it.effect("server-owned renewal persists rotated credentials after the helper disconnects", () => |
| 1889 | provideBroker( |
| 1890 | Effect.gen(function* () { |
| 1891 | const h = yield* makeRenewalBroker; |
| 1892 | h.pause(); |
| 1893 | const client = yield* brokerClient(h.endpoint, h.request); |
| 1894 | yield* Deferred.await(h.oauthEntered); |
| 1895 | client.socket.destroy(); |
| 1896 | yield* Effect.promise(() => client.response); |
| 1897 | assert.equal(Option.getOrThrow(yield* h.auth.read).refreshToken, "single-use-refresh"); |
| 1898 | yield* Deferred.succeed(h.oauthRelease, undefined); |
| 1899 | yield* h.broker.awaitIdle; |
| 1900 | const persisted = Option.getOrThrow(yield* h.auth.read); |
| 1901 | assert.equal(persisted.refreshToken, "rotated-refresh"); |
| 1902 | assert.equal((yield* h.auth.access).accessToken, "renewed-access"); |
| 1903 | assert.deepEqual(h.refreshTokens, ["single-use-refresh"]); |
| 1904 | }), |
| 1905 | ), |
| 1906 | ); |
| 1907 | |
| 1908 | it.live("the private broker refuses another environment, instance, or sign-in profile", () => |
| 1909 | provideBroker( |
| 1910 | Effect.gen(function* () { |
| 1911 | const h = yield* makeRenewalBroker; |
| 1912 | yield* Effect.forEach( |
| 1913 | [ |
| 1914 | { |
| 1915 | ...h.request, |
| 1916 | environmentId: EnvironmentId.make("00000000-0000-4000-8000-000000000002"), |
| 1917 | }, |
| 1918 | { ...h.request, instanceId: ProviderInstanceId.make("another-instance") }, |
| 1919 | { ...h.request, profileKey: "0".repeat(64) }, |
| 1920 | ], |
| 1921 | (request) => |
| 1922 | Effect.scoped( |
| 1923 | Effect.gen(function* () { |
| 1924 | const client = yield* brokerClient(h.endpoint, request); |
| 1925 | assert.equal(yield* Effect.promise(() => client.response), ""); |
| 1926 | }), |
| 1927 | ), |
| 1928 | ); |
| 1929 | yield* h.broker.awaitIdle; |
| 1930 | assert.deepEqual(h.refreshTokens, []); |
| 1931 | const client = yield* brokerClient(h.endpoint, h.request); |
| 1932 | assert.deepEqual(JSON.parse(yield* Effect.promise(() => client.response)), { |
| 1933 | token: "renewed-access", |
| 1934 | }); |
| 1935 | yield* h.broker.awaitIdle; |
| 1936 | assert.deepEqual(h.refreshTokens, ["single-use-refresh"]); |
| 1937 | }), |
| 1938 | ), |
| 1939 | ); |