The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import { |
| 4 | authScopeResponse, |
| 5 | AuthAdministrativeClientScopes, |
| 6 | connectDeviceVerificationCode, |
| 7 | } from "@t3tools/contracts"; |
| 8 | import { expect, it } from "@effect/vitest"; |
| 9 | import * as DateTime from "effect/DateTime"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import * as Redacted from "effect/Redacted"; |
| 13 | import * as TestClock from "effect/testing/TestClock"; |
| 14 | |
| 15 | import * as ServerConfig from "../config.ts"; |
| 16 | import { makeDpopKey } from "./dpop.testkit.ts"; |
| 17 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 18 | import * as SqlitePersistence from "../persistence/Sqlite.ts"; |
| 19 | import * as EnvironmentAuth from "./EnvironmentAuth.ts"; |
| 20 | |
| 21 | import * as ServerSecretStore from "./ServerSecretStore.ts"; |
| 22 | import * as SessionStore from "./SessionStore.ts"; |
| 23 | import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; |
| 24 | |
| 25 | const TEST_SERVER_PORT = 13_773; |
| 26 | |
| 27 | const layerServerConfig = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) => |
| 28 | Layer.effect( |
| 29 | ServerConfig.ServerConfig, |
| 30 | Effect.gen(function* () { |
| 31 | const config = yield* ServerConfig.ServerConfig; |
| 32 | return { |
| 33 | ...config, |
| 34 | ...overrides, |
| 35 | port: TEST_SERVER_PORT, |
| 36 | } satisfies ServerConfig.ServerConfig["Service"]; |
| 37 | }), |
| 38 | ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" }))); |
| 39 | |
| 40 | const layerEnvironmentAuth = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) => |
| 41 | EnvironmentAuth.layer.pipe( |
| 42 | Layer.provide(ManagedPolicy.layerTest()), |
| 43 | Layer.provideMerge(SqlitePersistence.layerMemory), |
| 44 | Layer.provide(ServerSecretStore.layer), |
| 45 | Layer.provide(ServerEnvironment.layerIdentity), |
| 46 | Layer.provide(layerServerConfig(overrides)), |
| 47 | ); |
| 48 | |
| 49 | const makeCookieRequest = ( |
| 50 | cookieName: string, |
| 51 | sessionToken: string, |
| 52 | ): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] => |
| 53 | ({ |
| 54 | cookies: { |
| 55 | [cookieName]: sessionToken, |
| 56 | }, |
| 57 | headers: {}, |
| 58 | }) as unknown as Parameters< |
| 59 | EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"] |
| 60 | >[0]; |
| 61 | |
| 62 | const makeBearerRequest = ( |
| 63 | token: string, |
| 64 | ): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] => |
| 65 | ({ |
| 66 | cookies: {}, |
| 67 | headers: { |
| 68 | authorization: `Bearer ${token}`, |
| 69 | }, |
| 70 | }) as unknown as Parameters< |
| 71 | EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"] |
| 72 | >[0]; |
| 73 | |
| 74 | const requestMetadata = { |
| 75 | deviceType: "desktop" as const, |
| 76 | os: "macOS", |
| 77 | browser: "Chrome", |
| 78 | ipAddress: "192.168.1.23", |
| 79 | }; |
| 80 | |
| 81 | it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( |
| 82 | "EnvironmentAuth.layer", |
| 83 | (it) => { |
| 84 | it.effect("uses the reusable dev cookie without overriding a normal scoped cookie", () => |
| 85 | Effect.gen(function* () { |
| 86 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 87 | const sessions = yield* SessionStore.SessionStore; |
| 88 | const token = "reusable-dev-auth-token-that-is-long-enough"; |
| 89 | const devExchange = yield* serverAuth.createBrowserSession(token, requestMetadata); |
| 90 | const pairing = yield* serverAuth.issuePairingCredential({ |
| 91 | scopes: ["orchestration:read"], |
| 92 | }); |
| 93 | const scopedExchange = yield* serverAuth.createBrowserSession( |
| 94 | pairing.credential, |
| 95 | requestMetadata, |
| 96 | ); |
| 97 | const request = { |
| 98 | cookies: { |
| 99 | [sessions.cookieName]: scopedExchange.sessionToken, |
| 100 | [devExchange.cookieName ?? "missing"]: devExchange.sessionToken, |
| 101 | }, |
| 102 | headers: {}, |
| 103 | } as unknown as Parameters< |
| 104 | EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"] |
| 105 | >[0]; |
| 106 | |
| 107 | const authenticated = yield* serverAuth.authenticateHttpRequest(request); |
| 108 | expect(devExchange.cookieName).toMatch(/^t3_dev_session_/); |
| 109 | expect(devExchange.expireNormalCookie).toBe(true); |
| 110 | expect(devExchange.response).toMatchObject( |
| 111 | authScopeResponse(AuthAdministrativeClientScopes), |
| 112 | ); |
| 113 | expect(authenticated.scopes).toEqual(["orchestration:read"]); |
| 114 | }).pipe( |
| 115 | Effect.provide( |
| 116 | layerEnvironmentAuth({ |
| 117 | mode: "web", |
| 118 | devUrl: new URL("http://127.0.0.1:5173"), |
| 119 | devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"), |
| 120 | }), |
| 121 | ), |
| 122 | ), |
| 123 | ); |
| 124 | |
| 125 | it.effect("does not fall back to the dev cookie after a normal cookie is rejected", () => |
| 126 | Effect.gen(function* () { |
| 127 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 128 | const sessions = yield* SessionStore.SessionStore; |
| 129 | const token = "reusable-dev-auth-token-that-is-long-enough"; |
| 130 | const devExchange = yield* serverAuth.createBrowserSession(token, requestMetadata); |
| 131 | const pairing = yield* serverAuth.issuePairingCredential({ |
| 132 | scopes: ["orchestration:read"], |
| 133 | }); |
| 134 | const scopedExchange = yield* serverAuth.createBrowserSession( |
| 135 | pairing.credential, |
| 136 | requestMetadata, |
| 137 | ); |
| 138 | const scoped = yield* sessions.verify(scopedExchange.sessionToken); |
| 139 | yield* sessions.revoke(scoped.sessionId); |
| 140 | const request = { |
| 141 | cookies: { |
| 142 | [sessions.cookieName]: scopedExchange.sessionToken, |
| 143 | [devExchange.cookieName ?? "missing"]: devExchange.sessionToken, |
| 144 | }, |
| 145 | headers: {}, |
| 146 | } as unknown as Parameters< |
| 147 | EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"] |
| 148 | >[0]; |
| 149 | |
| 150 | const error = yield* Effect.flip(serverAuth.authenticateHttpRequest(request)); |
| 151 | expect(error._tag).toBe("ServerAuthInvalidCredentialError"); |
| 152 | }).pipe( |
| 153 | Effect.provide( |
| 154 | layerEnvironmentAuth({ |
| 155 | mode: "web", |
| 156 | devUrl: new URL("http://127.0.0.1:5173"), |
| 157 | devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"), |
| 158 | }), |
| 159 | ), |
| 160 | ), |
| 161 | ); |
| 162 | |
| 163 | it.effect("does not use the dev cookie when Authorization is invalid or empty", () => |
| 164 | Effect.gen(function* () { |
| 165 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 166 | const token = "reusable-dev-auth-token-that-is-long-enough"; |
| 167 | const devExchange = yield* serverAuth.createBrowserSession(token, requestMetadata); |
| 168 | for (const authorization of [ |
| 169 | "Bearer invalid", |
| 170 | "bearer invalid", |
| 171 | "bEaReR invalid", |
| 172 | "Basic invalid", |
| 173 | "", |
| 174 | ] as const) { |
| 175 | const request = { |
| 176 | cookies: { [devExchange.cookieName ?? "missing"]: devExchange.sessionToken }, |
| 177 | headers: { authorization }, |
| 178 | } as unknown as Parameters< |
| 179 | EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"] |
| 180 | >[0]; |
| 181 | const error = yield* Effect.flip(serverAuth.authenticateHttpRequest(request)); |
| 182 | expect(EnvironmentAuth.isServerAuthCredentialError(error)).toBe(true); |
| 183 | } |
| 184 | }).pipe( |
| 185 | Effect.provide( |
| 186 | layerEnvironmentAuth({ |
| 187 | mode: "web", |
| 188 | devUrl: new URL("http://127.0.0.1:5173"), |
| 189 | devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"), |
| 190 | }), |
| 191 | ), |
| 192 | ), |
| 193 | ); |
| 194 | |
| 195 | it.effect("exchanges the reusable dev token for a local scoped OAuth session", () => |
| 196 | Effect.gen(function* () { |
| 197 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 198 | const sessions = yield* SessionStore.SessionStore; |
| 199 | const token = "reusable-dev-auth-token-that-is-long-enough"; |
| 200 | const exchanged = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 201 | token, |
| 202 | ["orchestration:read"], |
| 203 | requestMetadata, |
| 204 | ); |
| 205 | |
| 206 | expect(exchanged.access_token).not.toBe(token); |
| 207 | expect(exchanged.scope).toBe("orchestration:read"); |
| 208 | const dpop = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 209 | token, |
| 210 | ["orchestration:read"], |
| 211 | requestMetadata, |
| 212 | { proofKeyThumbprint: "test-proof-key" }, |
| 213 | ); |
| 214 | expect(dpop.access_token).not.toBe(token); |
| 215 | expect(dpop.access_token).not.toBe(exchanged.access_token); |
| 216 | expect(dpop.token_type).toBe("DPoP"); |
| 217 | expect(dpop.scope).toBe("orchestration:read"); |
| 218 | |
| 219 | const secondBearer = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 220 | token, |
| 221 | ["orchestration:read"], |
| 222 | requestMetadata, |
| 223 | ); |
| 224 | const firstSession = yield* serverAuth.authenticateHttpRequest( |
| 225 | makeBearerRequest(exchanged.access_token), |
| 226 | ); |
| 227 | const secondSession = yield* serverAuth.authenticateHttpRequest( |
| 228 | makeBearerRequest(secondBearer.access_token), |
| 229 | ); |
| 230 | expect(firstSession.subject).toBe("reusable-dev-token-child"); |
| 231 | expect(secondSession.subject).toBe("reusable-dev-token-child"); |
| 232 | expect((yield* sessions.verify(token)).subject).toBe("reusable-dev-token"); |
| 233 | const before = yield* serverAuth.listClientSessions(firstSession.sessionId); |
| 234 | const denied = yield* serverAuth |
| 235 | .exchangeBootstrapCredentialForAccessToken(token, ["review:write"], requestMetadata) |
| 236 | .pipe(Effect.flip); |
| 237 | expect(denied._tag).toBe("ServerAuthScopeNotGrantedError"); |
| 238 | const empty = yield* serverAuth |
| 239 | .exchangeBootstrapCredentialForAccessToken(token, [], requestMetadata) |
| 240 | .pipe(Effect.flip); |
| 241 | expect(empty._tag).toBe("ServerAuthScopeNotGrantedError"); |
| 242 | expect(yield* serverAuth.listClientSessions(firstSession.sessionId)).toEqual(before); |
| 243 | }).pipe( |
| 244 | Effect.provide( |
| 245 | layerEnvironmentAuth({ |
| 246 | mode: "web", |
| 247 | devUrl: new URL("http://127.0.0.1:5173"), |
| 248 | devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"), |
| 249 | }), |
| 250 | ), |
| 251 | ), |
| 252 | ); |
| 253 | |
| 254 | it.effect("uses a one-time startup credential after local dev token revocation", () => |
| 255 | Effect.gen(function* () { |
| 256 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 257 | const sessions = yield* SessionStore.SessionStore; |
| 258 | const token = "reusable-dev-auth-token-that-is-long-enough"; |
| 259 | const initial = yield* serverAuth.issueStartupPairingCredential(); |
| 260 | const seeded = yield* sessions.verify(token); |
| 261 | |
| 262 | yield* sessions.revoke(seeded.sessionId); |
| 263 | const recovery = yield* serverAuth.issueStartupPairingCredential(); |
| 264 | |
| 265 | expect(initial.credential).toBe(token); |
| 266 | expect(recovery.credential).not.toBe(token); |
| 267 | expect((yield* Effect.flip(sessions.verify(token)))._tag).toBe("SessionTokenRevokedError"); |
| 268 | expect( |
| 269 | (yield* serverAuth.createBrowserSession(recovery.credential, requestMetadata)).response, |
| 270 | ).toMatchObject({ |
| 271 | authenticated: true, |
| 272 | ...authScopeResponse(AuthAdministrativeClientScopes), |
| 273 | }); |
| 274 | }).pipe( |
| 275 | Effect.provide( |
| 276 | layerEnvironmentAuth({ |
| 277 | mode: "web", |
| 278 | devUrl: new URL("http://127.0.0.1:5173"), |
| 279 | devAuthToken: Redacted.make("reusable-dev-auth-token-that-is-long-enough"), |
| 280 | }), |
| 281 | ), |
| 282 | ), |
| 283 | ); |
| 284 | |
| 285 | it.effect("prefers a bearer token over a stale legacy cookie", () => |
| 286 | Effect.gen(function* () { |
| 287 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 288 | const sessions = yield* SessionStore.SessionStore; |
| 289 | const bearer = yield* serverAuth.issueSession(); |
| 290 | const verified = yield* serverAuth.authenticateHttpRequest({ |
| 291 | cookies: { [sessions.legacyCookieName ?? "t3_session"]: "stale" }, |
| 292 | headers: { authorization: `Bearer ${bearer.token}` }, |
| 293 | } as never); |
| 294 | |
| 295 | expect(verified.sessionId).toBe(bearer.sessionId); |
| 296 | }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), |
| 297 | ); |
| 298 | |
| 299 | it.effect("prefers a bearer token over an empty primary cookie", () => |
| 300 | Effect.gen(function* () { |
| 301 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 302 | const sessions = yield* SessionStore.SessionStore; |
| 303 | const bearer = yield* serverAuth.issueSession(); |
| 304 | const verified = yield* serverAuth.authenticateHttpRequest({ |
| 305 | cookies: { [sessions.cookieName]: "" }, |
| 306 | headers: { authorization: `Bearer ${bearer.token}` }, |
| 307 | } as never); |
| 308 | |
| 309 | expect(verified.sessionId).toBe(bearer.sessionId); |
| 310 | }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), |
| 311 | ); |
| 312 | |
| 313 | it.effect( |
| 314 | "holds an untrusted T3 Connect device until it is approved, and revocation cuts it off", |
| 315 | () => |
| 316 | Effect.gen(function* () { |
| 317 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 318 | const deviceKey = "Kq3vZ8sYbTn0eW1pLr5uXc7dHf9gJm2aQs4tVw6yBzE"; |
| 319 | const admin = yield* serverAuth.issueSession({ label: "Owner" }); |
| 320 | const exchange = (credential: string) => |
| 321 | serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 322 | credential, |
| 323 | undefined, |
| 324 | requestMetadata, |
| 325 | { proofKeyThumbprint: deviceKey }, |
| 326 | ); |
| 327 | |
| 328 | // Relay mints can arrive together; they must share one request and one code. |
| 329 | const mint = serverAuth.issueConnectCredential({ |
| 330 | proofKeyThumbprint: deviceKey, |
| 331 | requireApproval: true, |
| 332 | }); |
| 333 | const [requested, concurrent] = yield* Effect.all([mint, mint], { |
| 334 | concurrency: "unbounded", |
| 335 | }); |
| 336 | expect(concurrent.credential).toBe(requested.credential); |
| 337 | expect((yield* exchange(requested.credential).pipe(Effect.flip))._tag).toBe( |
| 338 | "ServerAuthConnectApprovalPendingError", |
| 339 | ); |
| 340 | const [request] = (yield* serverAuth.listPairingLinks()).filter( |
| 341 | (link) => link.connectDeviceRequest !== undefined, |
| 342 | ); |
| 343 | expect(request?.connectDeviceRequest).toEqual({ |
| 344 | verificationCode: connectDeviceVerificationCode(deviceKey), |
| 345 | client: requestMetadata, |
| 346 | }); |
| 347 | // A retry through the relay keeps the one request the approver is looking at. |
| 348 | const retried = yield* serverAuth.issueConnectCredential({ |
| 349 | proofKeyThumbprint: deviceKey, |
| 350 | requireApproval: true, |
| 351 | }); |
| 352 | expect(retried.credential).toBe(requested.credential); |
| 353 | |
| 354 | expect(yield* serverAuth.approveConnectDevice(request!.id)).toBe(true); |
| 355 | // A stale prompt on another client must not report denying an approved device. |
| 356 | expect(yield* serverAuth.revokePairingLink(request!.id)).toBe(false); |
| 357 | expect( |
| 358 | (yield* serverAuth.listPairingLinks()).some((link) => link.connectDeviceRequest), |
| 359 | ).toBe(false); |
| 360 | yield* exchange(requested.credential); |
| 361 | expect( |
| 362 | (yield* serverAuth.listConnectDevices()).map((device) => device.proofKeyThumbprint), |
| 363 | ).toEqual([deviceKey]); |
| 364 | |
| 365 | const refreshed = yield* serverAuth.issueConnectCredential({ |
| 366 | proofKeyThumbprint: deviceKey, |
| 367 | requireApproval: true, |
| 368 | }); |
| 369 | yield* exchange(refreshed.credential); |
| 370 | |
| 371 | const deviceSessions = () => |
| 372 | serverAuth |
| 373 | .listClientSessions(admin.sessionId) |
| 374 | .pipe( |
| 375 | Effect.map((sessions) => |
| 376 | sessions.filter( |
| 377 | (session) => session.subject === EnvironmentAuth.CLOUD_CONNECT_SUBJECT, |
| 378 | ), |
| 379 | ), |
| 380 | ); |
| 381 | // A credential minted before revocation must not let the device back in afterwards. |
| 382 | const unspent = yield* serverAuth.issueConnectCredential({ |
| 383 | proofKeyThumbprint: deviceKey, |
| 384 | requireApproval: true, |
| 385 | }); |
| 386 | const [oldestDeviceSession, newestDeviceSession] = yield* deviceSessions(); |
| 387 | expect(newestDeviceSession).toBeDefined(); |
| 388 | // Authorized clients lists T3 Connect sessions under this name. |
| 389 | expect(newestDeviceSession?.client.label).toBe("T3 Connect"); |
| 390 | // Revoking any one of the device's sessions ends all of them and its trust. |
| 391 | expect( |
| 392 | yield* serverAuth.revokeClientSession(admin.sessionId, oldestDeviceSession!.sessionId), |
| 393 | ).toBe(true); |
| 394 | expect(yield* deviceSessions()).toEqual([]); |
| 395 | expect(yield* serverAuth.listConnectDevices()).toEqual([]); |
| 396 | expect((yield* exchange(unspent.credential).pipe(Effect.flip))._tag).toBe( |
| 397 | "ServerAuthInvalidCredentialError", |
| 398 | ); |
| 399 | expect(yield* serverAuth.listConnectDevices()).toEqual([]); |
| 400 | const afterRevoke = yield* serverAuth.issueConnectCredential({ |
| 401 | proofKeyThumbprint: deviceKey, |
| 402 | requireApproval: true, |
| 403 | }); |
| 404 | expect((yield* exchange(afterRevoke.credential).pipe(Effect.flip))._tag).toBe( |
| 405 | "ServerAuthConnectApprovalPendingError", |
| 406 | ); |
| 407 | // Deny sticks: retries get the dead request back instead of a fresh prompt. |
| 408 | const [denied] = (yield* serverAuth.listPairingLinks()).filter( |
| 409 | (link) => link.connectDeviceRequest !== undefined, |
| 410 | ); |
| 411 | expect(yield* serverAuth.revokePairingLink(denied!.id)).toBe(true); |
| 412 | const afterDeny = yield* serverAuth.issueConnectCredential({ |
| 413 | proofKeyThumbprint: deviceKey, |
| 414 | requireApproval: true, |
| 415 | }); |
| 416 | expect(afterDeny.credential).toBe(afterRevoke.credential); |
| 417 | expect((yield* exchange(afterDeny.credential).pipe(Effect.flip))._tag).toBe( |
| 418 | "ServerAuthInvalidCredentialError", |
| 419 | ); |
| 420 | expect( |
| 421 | (yield* serverAuth.listPairingLinks()).some((link) => link.connectDeviceRequest), |
| 422 | ).toBe(false); |
| 423 | }).pipe(Effect.provide(layerEnvironmentAuth())), |
| 424 | ); |
| 425 | |
| 426 | it.effect("renews a pairing-link DPoP session in place while its device keeps using it", () => |
| 427 | Effect.gen(function* () { |
| 428 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 429 | const sessions = yield* SessionStore.SessionStore; |
| 430 | const admin = yield* serverAuth.issueSession({ label: "Owner" }); |
| 431 | const key = makeDpopKey(); |
| 432 | const other = makeDpopKey(); |
| 433 | const pair = (proofKeyThumbprint?: string) => |
| 434 | serverAuth |
| 435 | .issuePairingCredential({ scopes: ["orchestration:read"] }) |
| 436 | .pipe( |
| 437 | Effect.flatMap((pairing) => |
| 438 | serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 439 | pairing.credential, |
| 440 | undefined, |
| 441 | requestMetadata, |
| 442 | proofKeyThumbprint ? { proofKeyThumbprint } : undefined, |
| 443 | ), |
| 444 | ), |
| 445 | ); |
| 446 | const sessionExpiry = (sessionId: string) => |
| 447 | serverAuth |
| 448 | .listClientSessions(admin.sessionId) |
| 449 | .pipe( |
| 450 | Effect.map( |
| 451 | (sessions) => |
| 452 | sessions.find((session) => session.sessionId === sessionId)?.expiresAt |
| 453 | .epochMilliseconds, |
| 454 | ), |
| 455 | ); |
| 456 | |
| 457 | const paired = yield* pair(key.thumbprint); |
| 458 | expect(paired.expires_in).toBe(60 * 60); |
| 459 | const { sessionId } = yield* sessions.verify(paired.access_token); |
| 460 | const pairedAt = (yield* DateTime.now).epochMilliseconds; |
| 461 | // Listed for the whole renewal window, so an idle device can still be revoked. |
| 462 | expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 30 * 24 * 60 * 60 * 1000); |
| 463 | |
| 464 | yield* TestClock.adjust("20 days"); |
| 465 | const replay = new EnvironmentAuth.ServerAuthInvalidCredentialError({ |
| 466 | dpopFailureReason: "replay", |
| 467 | }); |
| 468 | const rejected = yield* serverAuth |
| 469 | .renewAccessToken(paired.access_token, key.thumbprint, Effect.fail(replay)) |
| 470 | .pipe(Effect.flip); |
| 471 | expect(rejected).toBe(replay); |
| 472 | expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 30 * 24 * 60 * 60 * 1000); |
| 473 | |
| 474 | const renewed = yield* serverAuth.renewAccessToken( |
| 475 | paired.access_token, |
| 476 | key.thumbprint, |
| 477 | Effect.void, |
| 478 | ); |
| 479 | expect(renewed.scope).toBe("orchestration:read"); |
| 480 | const verified = yield* sessions.verify(renewed.access_token); |
| 481 | expect(verified.sessionId).toBe(sessionId); |
| 482 | expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 50 * 24 * 60 * 60 * 1000); |
| 483 | |
| 484 | const refused = (token: string, thumbprint: string) => |
| 485 | serverAuth |
| 486 | .renewAccessToken( |
| 487 | token, |
| 488 | thumbprint, |
| 489 | Effect.die("Invalid credentials cannot consume a proof."), |
| 490 | ) |
| 491 | .pipe( |
| 492 | Effect.flip, |
| 493 | Effect.map((error) => error._tag), |
| 494 | ); |
| 495 | expect(yield* refused(renewed.access_token, other.thumbprint)).toBe( |
| 496 | "ServerAuthInvalidCredentialError", |
| 497 | ); |
| 498 | // Bearer and T3 Connect sessions keep their fixed lifetimes, so unlinking still cuts off. |
| 499 | const bearer = yield* pair(); |
| 500 | expect(yield* refused(bearer.access_token, key.thumbprint)).toBe( |
| 501 | "ServerAuthInvalidCredentialError", |
| 502 | ); |
| 503 | const connect = yield* serverAuth.issueConnectCredential({ |
| 504 | proofKeyThumbprint: key.thumbprint, |
| 505 | requireApproval: false, |
| 506 | }); |
| 507 | const connected = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 508 | connect.credential, |
| 509 | undefined, |
| 510 | requestMetadata, |
| 511 | { proofKeyThumbprint: key.thumbprint }, |
| 512 | ); |
| 513 | expect(yield* refused(connected.access_token, key.thumbprint)).toBe( |
| 514 | "ServerAuthInvalidCredentialError", |
| 515 | ); |
| 516 | |
| 517 | // Inside the renewed window, so only the revocation can refuse it. |
| 518 | expect(yield* serverAuth.revokeClientSession(admin.sessionId, sessionId)).toBe(true); |
| 519 | expect(yield* refused(renewed.access_token, key.thumbprint)).toBe( |
| 520 | "ServerAuthInvalidCredentialError", |
| 521 | ); |
| 522 | |
| 523 | // Idle past the window, the device pairs again. |
| 524 | const idle = yield* pair(key.thumbprint); |
| 525 | yield* TestClock.adjust("31 days"); |
| 526 | expect(yield* refused(idle.access_token, key.thumbprint)).toBe( |
| 527 | "ServerAuthInvalidCredentialError", |
| 528 | ); |
| 529 | }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), |
| 530 | ); |
| 531 | |
| 532 | it.effect("renews a peer link's session while it is used, and no other MCP client's", () => |
| 533 | Effect.gen(function* () { |
| 534 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 535 | const day = 24 * 60 * 60 * 1000; |
| 536 | const issue = (peerLink: boolean) => |
| 537 | serverAuth.issueMcpClientSession({ |
| 538 | label: peerLink ? "T3 Code · A" : "ChatGPT", |
| 539 | access: "auto", |
| 540 | peerLink, |
| 541 | client: requestMetadata, |
| 542 | }); |
| 543 | const use = (session: { readonly token: string }) => |
| 544 | serverAuth.authenticateMcpClient(makeBearerRequest(session.token)).pipe( |
| 545 | Effect.map((client) => client.linkExpiresAt?.epochMilliseconds ?? null), |
| 546 | Effect.catchTags({ |
| 547 | ServerAuthInvalidCredentialError: () => Effect.succeed("refused" as const), |
| 548 | }), |
| 549 | ); |
| 550 | const listedExpiry = (session: { readonly sessionId: string }) => |
| 551 | serverAuth |
| 552 | .listSessions() |
| 553 | .pipe( |
| 554 | Effect.map( |
| 555 | (sessions) => |
| 556 | sessions.find((listed) => listed.sessionId === session.sessionId)?.expiresAt |
| 557 | .epochMilliseconds, |
| 558 | ), |
| 559 | ); |
| 560 | const issuedAt = (yield* DateTime.now).epochMilliseconds; |
| 561 | const used = yield* issue(true); |
| 562 | const idle = yield* issue(true); |
| 563 | const revoked = yield* issue(true); |
| 564 | const outside = yield* issue(false); |
| 565 | |
| 566 | // Within a day of its full lifetime, a call leaves the session row alone. |
| 567 | yield* TestClock.adjust("12 hours"); |
| 568 | expect(yield* use(used)).toBe(issuedAt + 30 * day); |
| 569 | expect(yield* listedExpiry(used)).toBe(issuedAt + 30 * day); |
| 570 | |
| 571 | yield* TestClock.adjust("468 hours"); |
| 572 | expect(yield* use(used)).toBe(issuedAt + 50 * day); |
| 573 | expect(yield* listedExpiry(used)).toBe(issuedAt + 50 * day); |
| 574 | expect(yield* use(outside)).toBeNull(); |
| 575 | expect(yield* listedExpiry(outside)).toBe(issuedAt + 30 * day); |
| 576 | expect(yield* serverAuth.revokeSession(revoked.sessionId)).toBe(true); |
| 577 | expect(yield* use(revoked)).toBe("refused"); |
| 578 | |
| 579 | // Day 40: past the token's own 30 days, so only the renewal keeps the used link. |
| 580 | yield* TestClock.adjust("20 days"); |
| 581 | expect(yield* use(used)).toBe(issuedAt + 70 * day); |
| 582 | expect(yield* use(idle)).toBe("refused"); |
| 583 | expect(yield* use(outside)).toBe("refused"); |
| 584 | expect(yield* use(revoked)).toBe("refused"); |
| 585 | expect(yield* listedExpiry(idle)).toBeUndefined(); |
| 586 | expect(yield* listedExpiry(revoked)).toBeUndefined(); |
| 587 | |
| 588 | // Renewed links still end 30 days after their last use. |
| 589 | yield* TestClock.adjust("30 days"); |
| 590 | expect(yield* use(used)).toBe("refused"); |
| 591 | }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), |
| 592 | ); |
| 593 | |
| 594 | it.effect("preserves pairing grants after rejecting scopes they do not grant", () => |
| 595 | Effect.gen(function* () { |
| 596 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 597 | const pairingCredential = yield* serverAuth.issuePairingCredential({ |
| 598 | scopes: ["orchestration:read", "orchestration:operate"], |
| 599 | }); |
| 600 | |
| 601 | const error = yield* serverAuth |
| 602 | .exchangeBootstrapCredentialForAccessToken( |
| 603 | pairingCredential.credential, |
| 604 | ["access:write"], |
| 605 | requestMetadata, |
| 606 | ) |
| 607 | .pipe(Effect.flip); |
| 608 | |
| 609 | expect(error._tag).toBe("ServerAuthScopeNotGrantedError"); |
| 610 | expect((yield* serverAuth.listPairingLinks()).map((link) => link.id)).toContain( |
| 611 | pairingCredential.id, |
| 612 | ); |
| 613 | expect(yield* serverAuth.listSessions()).toEqual([]); |
| 614 | |
| 615 | const token = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 616 | pairingCredential.credential, |
| 617 | ["orchestration:read"], |
| 618 | requestMetadata, |
| 619 | ); |
| 620 | const session = yield* serverAuth.authenticateHttpRequest( |
| 621 | makeBearerRequest(token.access_token), |
| 622 | ); |
| 623 | |
| 624 | expect(token.scope).toBe("orchestration:read"); |
| 625 | expect(session.scopes).toEqual(["orchestration:read"]); |
| 626 | expect((yield* serverAuth.listPairingLinks()).map((link) => link.id)).not.toContain( |
| 627 | pairingCredential.id, |
| 628 | ); |
| 629 | const reused = yield* serverAuth |
| 630 | .exchangeBootstrapCredentialForAccessToken( |
| 631 | pairingCredential.credential, |
| 632 | ["orchestration:read"], |
| 633 | requestMetadata, |
| 634 | ) |
| 635 | .pipe(Effect.flip); |
| 636 | expect(reused._tag).toBe("ServerAuthInvalidCredentialError"); |
| 637 | }).pipe(Effect.provide(layerEnvironmentAuth())), |
| 638 | ); |
| 639 | |
| 640 | it.effect.each([ |
| 641 | { label: "omits scope", requestedScopes: undefined }, |
| 642 | { |
| 643 | label: "requests unsupported permissions alongside a granted one", |
| 644 | requestedScopes: ["orchestration:read", "access:write"] as const, |
| 645 | }, |
| 646 | ])("inherits a constrained pairing grant when token exchange $label", ({ requestedScopes }) => |
| 647 | Effect.gen(function* () { |
| 648 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 649 | const pairingCredential = yield* serverAuth.issuePairingCredential({ |
| 650 | scopes: ["orchestration:read"], |
| 651 | }); |
| 652 | |
| 653 | const token = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 654 | pairingCredential.credential, |
| 655 | requestedScopes, |
| 656 | requestMetadata, |
| 657 | ); |
| 658 | |
| 659 | expect(token.scope).toBe("orchestration:read"); |
| 660 | }).pipe(Effect.provide(layerEnvironmentAuth())), |
| 661 | ); |
| 662 | |
| 663 | it.effect( |
| 664 | "preserves a rejected MCP pairing code for exactly one concurrent lower-access retry", |
| 665 | () => |
| 666 | Effect.gen(function* () { |
| 667 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 668 | const pairing = yield* serverAuth.issuePairingCredential({ |
| 669 | scopes: ["orchestration:read"], |
| 670 | }); |
| 671 | |
| 672 | const rejected = yield* Effect.flip( |
| 673 | serverAuth.consumeMcpApprovalCode(pairing.credential, "full-access"), |
| 674 | ); |
| 675 | expect(rejected).toMatchObject({ |
| 676 | _tag: "ServerAuthMcpApprovalCodeError", |
| 677 | reason: "insufficient_scope", |
| 678 | }); |
| 679 | |
| 680 | const retry = Effect.result( |
| 681 | serverAuth.consumeMcpApprovalCode(pairing.credential, "read-only"), |
| 682 | ); |
| 683 | const results = yield* Effect.all([retry, retry], { concurrency: "unbounded" }); |
| 684 | |
| 685 | expect(results.filter((result) => result._tag === "Success")).toHaveLength(1); |
| 686 | expect(results.filter((result) => result._tag === "Failure")).toMatchObject([ |
| 687 | { failure: { _tag: "ServerAuthMcpApprovalCodeError", reason: "unknown_or_used" } }, |
| 688 | ]); |
| 689 | }).pipe(Effect.provide(layerEnvironmentAuth())), |
| 690 | ); |
| 691 | |
| 692 | it.effect("spends peer-link pairing codes only for the chosen link access", () => |
| 693 | Effect.gen(function* () { |
| 694 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 695 | const pairing = yield* serverAuth.issuePairingCredential({ |
| 696 | access: "approval-required", |
| 697 | purpose: "peer-link", |
| 698 | }); |
| 699 | expect(pairing.purpose).toBe("peer-link"); |
| 700 | |
| 701 | const ordinarySession = yield* serverAuth |
| 702 | .exchangeBootstrapCredentialForAccessToken(pairing.credential, undefined, requestMetadata) |
| 703 | .pipe(Effect.flip); |
| 704 | expect(ordinarySession._tag).toBe("ServerAuthInvalidCredentialError"); |
| 705 | |
| 706 | for (const input of [ |
| 707 | { access: "approval-required", peerLink: false }, |
| 708 | { access: "auto", peerLink: true }, |
| 709 | ] as const) { |
| 710 | const rejected = yield* serverAuth |
| 711 | .consumeMcpApprovalCode(pairing.credential, input.access, input.peerLink) |
| 712 | .pipe(Effect.flip); |
| 713 | expect(rejected._tag).toBe("ServerAuthMcpApprovalCodeError"); |
| 714 | } |
| 715 | |
| 716 | expect( |
| 717 | yield* serverAuth.consumeMcpApprovalCode(pairing.credential, "approval-required", true), |
| 718 | ).toBe("approval-required"); |
| 719 | }).pipe(Effect.provide(layerEnvironmentAuth())), |
| 720 | ); |
| 721 | |
| 722 | it.effect("narrows seeded desktop grants to the requested scopes", () => |
| 723 | Effect.gen(function* () { |
| 724 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 725 | const token = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 726 | "desktop-bootstrap-token", |
| 727 | ["orchestration:read"], |
| 728 | requestMetadata, |
| 729 | ); |
| 730 | const session = yield* serverAuth.authenticateHttpRequest( |
| 731 | makeBearerRequest(token.access_token), |
| 732 | ); |
| 733 | |
| 734 | expect(token.scope).toBe("orchestration:read"); |
| 735 | expect(session.scopes).toEqual(["orchestration:read"]); |
| 736 | }).pipe( |
| 737 | Effect.provide(layerEnvironmentAuth({ desktopBootstrapToken: "desktop-bootstrap-token" })), |
| 738 | ), |
| 739 | ); |
| 740 | |
| 741 | it.effect("rotates desktop bearer sessions without accumulating authorized clients", () => |
| 742 | Effect.gen(function* () { |
| 743 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 744 | const sessions = yield* SessionStore.SessionStore; |
| 745 | const browser = yield* serverAuth.createBrowserSession( |
| 746 | "desktop-bootstrap-token", |
| 747 | requestMetadata, |
| 748 | ); |
| 749 | const browserSession = yield* serverAuth.authenticateHttpRequest( |
| 750 | makeCookieRequest(sessions.cookieName, browser.sessionToken), |
| 751 | ); |
| 752 | const staleSessions = yield* Effect.forEach([1, 2, 3], () => |
| 753 | sessions.issue({ subject: "desktop-bootstrap", method: "bearer-access-token" }), |
| 754 | ); |
| 755 | const pairing = yield* serverAuth.issuePairingCredential(); |
| 756 | const paired = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 757 | pairing.credential, |
| 758 | undefined, |
| 759 | { ...requestMetadata, label: "T3 Code Desktop" }, |
| 760 | ); |
| 761 | const first = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 762 | "desktop-bootstrap-token", |
| 763 | undefined, |
| 764 | requestMetadata, |
| 765 | ); |
| 766 | const firstSession = yield* serverAuth.authenticateHttpRequest( |
| 767 | makeBearerRequest(first.access_token), |
| 768 | ); |
| 769 | const second = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 770 | "desktop-bootstrap-token", |
| 771 | undefined, |
| 772 | requestMetadata, |
| 773 | ); |
| 774 | |
| 775 | const active = yield* serverAuth.listSessions(); |
| 776 | const firstError = yield* serverAuth |
| 777 | .authenticateHttpRequest(makeBearerRequest(first.access_token)) |
| 778 | .pipe(Effect.flip); |
| 779 | const secondSession = yield* serverAuth.authenticateHttpRequest( |
| 780 | makeBearerRequest(second.access_token), |
| 781 | ); |
| 782 | |
| 783 | expect(active).toHaveLength(3); |
| 784 | expect(active.map((entry) => entry.sessionId)).toContain(browserSession.sessionId); |
| 785 | expect(active.map((entry) => entry.sessionId)).toContain(secondSession.sessionId); |
| 786 | expect(active.map((entry) => entry.sessionId)).not.toContain(firstSession.sessionId); |
| 787 | expect(firstError._tag).toBe("ServerAuthInvalidCredentialError"); |
| 788 | for (const stale of staleSessions) { |
| 789 | const error = yield* sessions.verify(stale.token).pipe(Effect.flip); |
| 790 | expect(error._tag).toBe("SessionTokenRevokedError"); |
| 791 | } |
| 792 | const pairedSession = yield* serverAuth.authenticateHttpRequest( |
| 793 | makeBearerRequest(paired.access_token), |
| 794 | ); |
| 795 | expect(pairedSession.subject).toBe("one-time-token"); |
| 796 | expect(active.map((entry) => entry.sessionId)).toContain(pairedSession.sessionId); |
| 797 | }).pipe( |
| 798 | Effect.provide( |
| 799 | layerEnvironmentAuth({ |
| 800 | desktopBootstrapToken: "desktop-bootstrap-token", |
| 801 | }), |
| 802 | ), |
| 803 | ), |
| 804 | ); |
| 805 | |
| 806 | it.effect("issues startup pairing URLs that bootstrap administrative sessions", () => |
| 807 | Effect.gen(function* () { |
| 808 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 809 | const sessions = yield* SessionStore.SessionStore; |
| 810 | |
| 811 | const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773"); |
| 812 | const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token"); |
| 813 | const listedPairingLinks = yield* serverAuth.listPairingLinks(); |
| 814 | expect(token).toBeTruthy(); |
| 815 | expect( |
| 816 | listedPairingLinks.some( |
| 817 | (pairingLink) => pairingLink.subject === "administrative-bootstrap", |
| 818 | ), |
| 819 | ).toBe(false); |
| 820 | |
| 821 | const exchanged = yield* serverAuth.createBrowserSession(token ?? "", requestMetadata); |
| 822 | const verified = yield* serverAuth.authenticateHttpRequest( |
| 823 | makeCookieRequest(sessions.cookieName, exchanged.sessionToken), |
| 824 | ); |
| 825 | |
| 826 | expect(verified.scopes).toEqual(AuthAdministrativeClientScopes); |
| 827 | expect(verified.subject).toBe("administrative-bootstrap"); |
| 828 | }).pipe(Effect.provide(layerEnvironmentAuth())), |
| 829 | ); |
| 830 | |
| 831 | it.effect( |
| 832 | "lists pairing links and revokes other sessions while keeping the administrative session", |
| 833 | () => |
| 834 | Effect.gen(function* () { |
| 835 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 836 | const sessions = yield* SessionStore.SessionStore; |
| 837 | |
| 838 | const administrativeExchange = yield* serverAuth.createBrowserSession( |
| 839 | "desktop-bootstrap-token", |
| 840 | requestMetadata, |
| 841 | ); |
| 842 | const administrativeSession = yield* serverAuth.authenticateHttpRequest( |
| 843 | makeCookieRequest(sessions.cookieName, administrativeExchange.sessionToken), |
| 844 | ); |
| 845 | const pairingCredential = yield* serverAuth.issuePairingCredential({ |
| 846 | label: "Julius iPhone", |
| 847 | }); |
| 848 | const listedPairingLinks = yield* serverAuth.listPairingLinks(); |
| 849 | const clientExchange = yield* serverAuth.createBrowserSession( |
| 850 | pairingCredential.credential, |
| 851 | { |
| 852 | ...requestMetadata, |
| 853 | deviceType: "mobile", |
| 854 | os: "iOS", |
| 855 | browser: "Safari", |
| 856 | ipAddress: "192.168.1.88", |
| 857 | }, |
| 858 | ); |
| 859 | const clientSession = yield* serverAuth.authenticateHttpRequest( |
| 860 | makeCookieRequest(sessions.cookieName, clientExchange.sessionToken), |
| 861 | ); |
| 862 | const clientsBeforeRevoke = yield* serverAuth.listClientSessions( |
| 863 | administrativeSession.sessionId, |
| 864 | ); |
| 865 | const unspentCode = yield* serverAuth.issuePairingCredential({ label: "unspent" }); |
| 866 | const unspentApproval = yield* serverAuth.issuePairingCredential({ |
| 867 | access: "read-only", |
| 868 | }); |
| 869 | const revokedCount = yield* serverAuth.revokeOtherClientSessions( |
| 870 | administrativeSession.sessionId, |
| 871 | ); |
| 872 | const clientsAfterRevoke = yield* serverAuth.listClientSessions( |
| 873 | administrativeSession.sessionId, |
| 874 | ); |
| 875 | expect( |
| 876 | (yield* serverAuth |
| 877 | .createBrowserSession(unspentCode.credential, requestMetadata) |
| 878 | .pipe(Effect.exit))._tag, |
| 879 | ).toBe("Failure"); |
| 880 | expect( |
| 881 | (yield* serverAuth |
| 882 | .consumeMcpApprovalCode(unspentApproval.credential, "read-only") |
| 883 | .pipe(Effect.exit))._tag, |
| 884 | ).toBe("Failure"); |
| 885 | |
| 886 | expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id); |
| 887 | expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe( |
| 888 | "Julius iPhone", |
| 889 | ); |
| 890 | expect(clientsBeforeRevoke).toHaveLength(2); |
| 891 | expect( |
| 892 | clientsBeforeRevoke.find((entry) => entry.sessionId === administrativeSession.sessionId) |
| 893 | ?.current, |
| 894 | ).toBe(true); |
| 895 | expect( |
| 896 | clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId) |
| 897 | ?.current, |
| 898 | ).toBe(false); |
| 899 | expect( |
| 900 | clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client |
| 901 | .label, |
| 902 | ).toBe("Julius iPhone"); |
| 903 | expect( |
| 904 | clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client |
| 905 | .deviceType, |
| 906 | ).toBe("mobile"); |
| 907 | expect(revokedCount).toBe(1); |
| 908 | expect(clientsAfterRevoke).toHaveLength(1); |
| 909 | expect(clientsAfterRevoke[0]?.sessionId).toBe(administrativeSession.sessionId); |
| 910 | }).pipe( |
| 911 | Effect.provide( |
| 912 | layerEnvironmentAuth({ |
| 913 | desktopBootstrapToken: "desktop-bootstrap-token", |
| 914 | }), |
| 915 | ), |
| 916 | ), |
| 917 | ); |
| 918 | |
| 919 | it.effect("accepts cookie sessions on socket upgrades only from the app's own origins", () => |
| 920 | Effect.gen(function* () { |
| 921 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 922 | const sessions = yield* SessionStore.SessionStore; |
| 923 | const pairing = yield* serverAuth.issuePairingCredential(); |
| 924 | const exchanged = yield* serverAuth.createBrowserSession( |
| 925 | pairing.credential, |
| 926 | requestMetadata, |
| 927 | ); |
| 928 | const upgrade = (headers: Record<string, string>) => |
| 929 | serverAuth.authenticateWebSocketUpgrade( |
| 930 | { |
| 931 | url: "/ws", |
| 932 | cookies: { [sessions.cookieName]: exchanged.sessionToken }, |
| 933 | headers: { host: "192.168.1.50:3773", ...headers }, |
| 934 | } as never, |
| 935 | "rpc", |
| 936 | ); |
| 937 | |
| 938 | yield* upgrade({ origin: "http://192.168.1.50:3773" }); |
| 939 | yield* upgrade({ |
| 940 | origin: "https://box.tail1234.ts.net", |
| 941 | "x-forwarded-host": "box.tail1234.ts.net", |
| 942 | }); |
| 943 | yield* upgrade({ origin: "t3code://app" }); |
| 944 | yield* upgrade({ origin: "http://localhost:5733" }); |
| 945 | yield* upgrade({}); |
| 946 | |
| 947 | const otherPort = yield* Effect.flip(upgrade({ origin: "http://192.168.1.50:8080" })); |
| 948 | expect(otherPort._tag).toBe("ServerAuthInvalidCredentialError"); |
| 949 | const opaque = yield* Effect.flip(upgrade({ origin: "null" })); |
| 950 | expect(opaque._tag).toBe("ServerAuthInvalidCredentialError"); |
| 951 | }).pipe( |
| 952 | Effect.provide( |
| 953 | layerEnvironmentAuth({ |
| 954 | mode: "web", |
| 955 | host: "192.168.1.50", |
| 956 | devUrl: new URL("http://localhost:5733"), |
| 957 | }), |
| 958 | ), |
| 959 | ), |
| 960 | ); |
| 961 | |
| 962 | it.effect("accepts cookie sessions on HTTP requests only from the app's own origins", () => |
| 963 | Effect.gen(function* () { |
| 964 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 965 | const sessions = yield* SessionStore.SessionStore; |
| 966 | const pairing = yield* serverAuth.issuePairingCredential(); |
| 967 | const exchanged = yield* serverAuth.createBrowserSession( |
| 968 | pairing.credential, |
| 969 | requestMetadata, |
| 970 | ); |
| 971 | const post = (headers: Record<string, string>) => |
| 972 | serverAuth.authenticateHttpRequest({ |
| 973 | cookies: { [sessions.cookieName]: exchanged.sessionToken }, |
| 974 | headers: { host: "localhost:13773", ...headers }, |
| 975 | } as never); |
| 976 | |
| 977 | yield* post({ origin: "http://192.168.1.50:5733", "sec-fetch-site": "same-origin" }); |
| 978 | yield* post({ origin: "http://localhost:13773" }); |
| 979 | |
| 980 | const otherPort = yield* Effect.flip( |
| 981 | post({ origin: "http://localhost:3000", "sec-fetch-site": "same-site" }), |
| 982 | ); |
| 983 | expect(otherPort._tag).toBe("ServerAuthInvalidCredentialError"); |
| 984 | const state = yield* serverAuth.getSessionState({ |
| 985 | cookies: { [sessions.cookieName]: exchanged.sessionToken }, |
| 986 | headers: { host: "localhost:13773", origin: "http://localhost:3000" }, |
| 987 | } as never); |
| 988 | expect(state.authenticated).toBe(false); |
| 989 | }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web" }))), |
| 990 | ); |
| 991 | |
| 992 | it.effect.each(["Bearer", "bearer", "bEaReR"])( |
| 993 | "accepts %s for HTTP and socket upgrades regardless of page origin", |
| 994 | (scheme) => |
| 995 | Effect.gen(function* () { |
| 996 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 997 | const bearer = yield* serverAuth.issueSession(); |
| 998 | const request = { |
| 999 | url: "/ws", |
| 1000 | cookies: {}, |
| 1001 | headers: { |
| 1002 | host: "192.168.1.50:3773", |
| 1003 | origin: "http://192.168.1.50:8080", |
| 1004 | authorization: `${scheme} ${bearer.token}`, |
| 1005 | }, |
| 1006 | } as never; |
| 1007 | const verified = yield* serverAuth.authenticateWebSocketUpgrade(request, "rpc"); |
| 1008 | expect(verified.sessionId).toBe(bearer.sessionId); |
| 1009 | expect((yield* serverAuth.authenticateHttpRequest(request)).sessionId).toBe( |
| 1010 | bearer.sessionId, |
| 1011 | ); |
| 1012 | }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), |
| 1013 | ); |
| 1014 | |
| 1015 | it.effect("binds a DPoP session's RPC socket ticket to its proof key", () => |
| 1016 | Effect.gen(function* () { |
| 1017 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 1018 | const sessions = yield* SessionStore.SessionStore; |
| 1019 | const key = makeDpopKey(); |
| 1020 | const other = makeDpopKey(); |
| 1021 | const exchanged = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 1022 | "desktop-bootstrap-token", |
| 1023 | ["orchestration:read"], |
| 1024 | requestMetadata, |
| 1025 | { proofKeyThumbprint: key.thumbprint }, |
| 1026 | ); |
| 1027 | const session = yield* sessions.verify(exchanged.access_token); |
| 1028 | const host = "192.168.1.50:3773"; |
| 1029 | const socketUrl = `http://${host}/ws`; |
| 1030 | const iat = Math.floor((yield* DateTime.now).epochMilliseconds / 1_000); |
| 1031 | const upgrade = (ticket: string, use: "rpc" | "media", proof?: string) => |
| 1032 | serverAuth.authenticateWebSocketUpgrade( |
| 1033 | { |
| 1034 | method: "GET", |
| 1035 | url: `/ws?orchestrationProtocol=2&wsTicket=${ticket}${proof ? `&dpop=${proof}` : ""}`, |
| 1036 | cookies: {}, |
| 1037 | headers: { host }, |
| 1038 | } as never, |
| 1039 | use, |
| 1040 | ); |
| 1041 | |
| 1042 | const rpc = yield* serverAuth.issueWebSocketTicket(session, { use: "rpc" }); |
| 1043 | const bare = yield* Effect.flip(upgrade(Redacted.value(rpc.ticket), "rpc")); |
| 1044 | expect(bare._tag).toBe("ServerAuthInvalidCredentialError"); |
| 1045 | const signed = yield* upgrade( |
| 1046 | Redacted.value(rpc.ticket), |
| 1047 | "rpc", |
| 1048 | key.sign({ method: "GET", url: socketUrl, token: Redacted.value(rpc.ticket), iat }), |
| 1049 | ); |
| 1050 | expect(signed.sessionId).toBe(session.sessionId); |
| 1051 | |
| 1052 | const wrongKey = yield* Effect.flip( |
| 1053 | upgrade( |
| 1054 | Redacted.value(rpc.ticket), |
| 1055 | "rpc", |
| 1056 | other.sign({ method: "GET", url: socketUrl, token: Redacted.value(rpc.ticket), iat }), |
| 1057 | ), |
| 1058 | ); |
| 1059 | expect(wrongKey._tag).toBe("ServerAuthInvalidCredentialError"); |
| 1060 | const onMedia = yield* Effect.flip( |
| 1061 | upgrade( |
| 1062 | Redacted.value(rpc.ticket), |
| 1063 | "media", |
| 1064 | key.sign({ method: "GET", url: socketUrl, token: Redacted.value(rpc.ticket), iat }), |
| 1065 | ), |
| 1066 | ); |
| 1067 | expect(onMedia._tag).toBe("ServerAuthInvalidCredentialError"); |
| 1068 | |
| 1069 | const media = yield* serverAuth.issueWebSocketTicket(session, { use: "media" }); |
| 1070 | expect((yield* upgrade(Redacted.value(media.ticket), "media")).sessionId).toBe( |
| 1071 | session.sessionId, |
| 1072 | ); |
| 1073 | const mediaOnRpc = yield* Effect.flip(upgrade(Redacted.value(media.ticket), "rpc")); |
| 1074 | expect(mediaOnRpc._tag).toBe("ServerAuthInvalidCredentialError"); |
| 1075 | |
| 1076 | // Clients that predate ticket binding still connect with the unbound ticket they mint. |
| 1077 | const legacy = yield* serverAuth.issueWebSocketTicket(session); |
| 1078 | expect((yield* upgrade(Redacted.value(legacy.ticket), "rpc")).sessionId).toBe( |
| 1079 | session.sessionId, |
| 1080 | ); |
| 1081 | }).pipe( |
| 1082 | Effect.provide(layerEnvironmentAuth({ desktopBootstrapToken: "desktop-bootstrap-token" })), |
| 1083 | ), |
| 1084 | ); |
| 1085 | |
| 1086 | it.effect.each(["DPoP", "dpop", "dPoP"])( |
| 1087 | "accepts %s for a proof-bound HTTP request", |
| 1088 | (scheme) => |
| 1089 | Effect.gen(function* () { |
| 1090 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 1091 | const key = makeDpopKey(); |
| 1092 | const { access_token: token } = |
| 1093 | yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 1094 | "desktop-bootstrap-token", |
| 1095 | ["orchestration:read"], |
| 1096 | requestMetadata, |
| 1097 | { proofKeyThumbprint: key.thumbprint }, |
| 1098 | ); |
| 1099 | const iat = Math.floor((yield* DateTime.now).epochMilliseconds / 1_000); |
| 1100 | const request = { |
| 1101 | method: "GET", |
| 1102 | url: "/api/auth/session", |
| 1103 | cookies: {}, |
| 1104 | headers: { |
| 1105 | host: "192.168.1.50:3773", |
| 1106 | authorization: `${scheme} ${token}`, |
| 1107 | dpop: key.sign({ |
| 1108 | method: "GET", |
| 1109 | url: "http://192.168.1.50:3773/api/auth/session", |
| 1110 | token, |
| 1111 | iat, |
| 1112 | }), |
| 1113 | }, |
| 1114 | } as never; |
| 1115 | expect((yield* serverAuth.authenticateHttpRequest(request)).sessionId).toBeTypeOf( |
| 1116 | "string", |
| 1117 | ); |
| 1118 | }).pipe( |
| 1119 | Effect.provide( |
| 1120 | layerEnvironmentAuth({ desktopBootstrapToken: "desktop-bootstrap-token" }), |
| 1121 | ), |
| 1122 | ), |
| 1123 | ); |
| 1124 | |
| 1125 | it.effect("rejects a replayed proof on a bound RPC socket ticket", () => |
| 1126 | Effect.gen(function* () { |
| 1127 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 1128 | const sessions = yield* SessionStore.SessionStore; |
| 1129 | const key = makeDpopKey(); |
| 1130 | const exchanged = yield* serverAuth.exchangeBootstrapCredentialForAccessToken( |
| 1131 | "desktop-bootstrap-token", |
| 1132 | ["orchestration:read"], |
| 1133 | requestMetadata, |
| 1134 | { proofKeyThumbprint: key.thumbprint }, |
| 1135 | ); |
| 1136 | const session = yield* sessions.verify(exchanged.access_token); |
| 1137 | const rpc = yield* serverAuth.issueWebSocketTicket(session, { use: "rpc" }); |
| 1138 | const request = { |
| 1139 | method: "GET", |
| 1140 | url: `/ws?wsTicket=${Redacted.value(rpc.ticket)}&dpop=${key.sign({ |
| 1141 | method: "GET", |
| 1142 | url: "http://192.168.1.50:3773/ws", |
| 1143 | token: Redacted.value(rpc.ticket), |
| 1144 | iat: Math.floor((yield* DateTime.now).epochMilliseconds / 1_000), |
| 1145 | })}`, |
| 1146 | cookies: {}, |
| 1147 | headers: { host: "192.168.1.50:3773" }, |
| 1148 | } as never; |
| 1149 | |
| 1150 | yield* serverAuth.authenticateWebSocketUpgrade(request, "rpc"); |
| 1151 | const replayed = yield* Effect.flip( |
| 1152 | serverAuth.authenticateWebSocketUpgrade(request, "rpc"), |
| 1153 | ); |
| 1154 | expect(replayed._tag).toBe("ServerAuthInvalidCredentialError"); |
| 1155 | if (replayed._tag === "ServerAuthInvalidCredentialError") { |
| 1156 | expect(replayed.dpopFailureReason).toBe("replay"); |
| 1157 | } |
| 1158 | }).pipe( |
| 1159 | Effect.provide(layerEnvironmentAuth({ desktopBootstrapToken: "desktop-bootstrap-token" })), |
| 1160 | ), |
| 1161 | ); |
| 1162 | }, |
| 1163 | ); |