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 | import { EnvironmentId } from "@t3tools/contracts"; |
| 2 | import { |
| 3 | RelayEnvironmentConnectScope, |
| 4 | RelayEnvironmentStatusScope, |
| 5 | } from "@t3tools/contracts/relay"; |
| 6 | import { describe, expect, it } from "@effect/vitest"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Fiber from "effect/Fiber"; |
| 9 | import * as Layer from "effect/Layer"; |
| 10 | |
| 11 | import { RELAY_GATEWAY_TIMEOUT_MESSAGE, relayRequestFailureDetail } from "./errorPresentation.ts"; |
| 12 | import * as ManagedRelay from "./managedRelay.ts"; |
| 13 | import * as RpcHttp from "../rpc/http.ts"; |
| 14 | |
| 15 | function layerManagedRelayTest( |
| 16 | fetchFn: typeof globalThis.fetch, |
| 17 | relayUrl = "https://relay.example.test", |
| 18 | accessTokenStore?: ManagedRelay.ManagedRelayAccessTokenStore, |
| 19 | ) { |
| 20 | const layerHttpClient = RpcHttp.layerRemoteHttpClient(fetchFn); |
| 21 | const layerSigner = Layer.succeed( |
| 22 | ManagedRelay.ManagedRelayDpopSigner, |
| 23 | ManagedRelay.ManagedRelayDpopSigner.of({ |
| 24 | thumbprint: Effect.succeed("client-thumbprint"), |
| 25 | createProof: (input: ManagedRelay.ManagedRelayDpopProofInput) => |
| 26 | Effect.succeed(`proof:${input.url}`), |
| 27 | }), |
| 28 | ); |
| 29 | return ManagedRelay.layer({ |
| 30 | relayUrl, |
| 31 | clientId: "t3-mobile", |
| 32 | ...(accessTokenStore ? { accessTokenStore } : {}), |
| 33 | }).pipe(Layer.provide(layerSigner), Layer.provide(layerHttpClient)); |
| 34 | } |
| 35 | |
| 36 | function clerkToken(subject: string, nonce: string): string { |
| 37 | const encode = (value: unknown) => |
| 38 | btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); |
| 39 | return `${encode({ alg: "RS256" })}.${encode({ sub: subject, nonce })}.c2lnbmF0dXJl`; |
| 40 | } |
| 41 | |
| 42 | describe("ManagedRelayClient", () => { |
| 43 | it.effect("rejects unsafe relay URLs before sending credentials", () => { |
| 44 | let requestCount = 0; |
| 45 | const fetchFn = (() => { |
| 46 | requestCount += 1; |
| 47 | return Promise.resolve(Response.json({})); |
| 48 | }) satisfies typeof globalThis.fetch; |
| 49 | |
| 50 | return Effect.gen(function* () { |
| 51 | const relayClient = yield* ManagedRelay.ManagedRelayClient; |
| 52 | const error = yield* relayClient |
| 53 | .listEnvironments({ clerkToken: "clerk-token" }) |
| 54 | .pipe(Effect.flip); |
| 55 | |
| 56 | expect(error).toMatchObject({ |
| 57 | _tag: "ManagedRelayUrlInvalidError", |
| 58 | relayUrl: "http://relay.example.test", |
| 59 | message: "Relay URL must be a secure absolute HTTPS origin.", |
| 60 | }); |
| 61 | expect(requestCount).toBe(0); |
| 62 | }).pipe(Effect.provide(layerManagedRelayTest(fetchFn, "http://relay.example.test"))); |
| 63 | }); |
| 64 | |
| 65 | it.effect("uses a cached token while another scope waits for an exchange", () => { |
| 66 | const exchangeStarted = Promise.withResolvers<void>(); |
| 67 | const releaseExchange = Promise.withResolvers<void>(); |
| 68 | let tokenExchangeCount = 0; |
| 69 | const statusTokens: Array<string | null> = []; |
| 70 | let persistedTokens: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry> = [ |
| 71 | { |
| 72 | accountId: "user-1", |
| 73 | clientId: "t3-mobile", |
| 74 | relayUrl: "https://relay.example.test", |
| 75 | thumbprint: "client-thumbprint", |
| 76 | scopes: [RelayEnvironmentStatusScope], |
| 77 | accessToken: "cached-status-token", |
| 78 | expiresAtMillis: Number.MAX_SAFE_INTEGER, |
| 79 | }, |
| 80 | ]; |
| 81 | const accessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = { |
| 82 | load: Effect.sync(() => persistedTokens), |
| 83 | save: (entries) => |
| 84 | Effect.sync(() => { |
| 85 | persistedTokens = entries; |
| 86 | }), |
| 87 | clear: Effect.sync(() => { |
| 88 | persistedTokens = []; |
| 89 | }), |
| 90 | }; |
| 91 | const fetchFn = ((input, init) => { |
| 92 | if (String(input).endsWith("/v1/client/dpop-token")) { |
| 93 | tokenExchangeCount += 1; |
| 94 | exchangeStarted.resolve(); |
| 95 | return releaseExchange.promise.then(() => |
| 96 | Response.json({ |
| 97 | access_token: "expanded-scope-token", |
| 98 | issued_token_type: "urn:ietf:params:oauth:token-type:access_token", |
| 99 | token_type: "DPoP", |
| 100 | expires_in: 1_800, |
| 101 | scope: `${RelayEnvironmentStatusScope} ${RelayEnvironmentConnectScope}`, |
| 102 | }), |
| 103 | ); |
| 104 | } |
| 105 | statusTokens.push(new Headers(init?.headers).get("authorization")); |
| 106 | return Promise.resolve( |
| 107 | Response.json({ |
| 108 | environmentId: "env-1", |
| 109 | endpoint: { |
| 110 | httpBaseUrl: "https://desktop.example.test/", |
| 111 | wsBaseUrl: "wss://desktop.example.test/ws", |
| 112 | providerKind: "cloudflare_tunnel", |
| 113 | }, |
| 114 | status: "online", |
| 115 | checkedAt: "2026-09-04T00:00:00.000Z", |
| 116 | }), |
| 117 | ); |
| 118 | }) satisfies typeof globalThis.fetch; |
| 119 | |
| 120 | return Effect.gen(function* () { |
| 121 | const relayClient = yield* ManagedRelay.ManagedRelayClient; |
| 122 | const statusInput = { |
| 123 | clerkToken: clerkToken("user-1", "session-1"), |
| 124 | scopes: [RelayEnvironmentStatusScope], |
| 125 | environmentId: EnvironmentId.make("env-1"), |
| 126 | } as const; |
| 127 | const expandedScopeInput = { |
| 128 | ...statusInput, |
| 129 | scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope], |
| 130 | } as const; |
| 131 | const firstMiss = yield* relayClient |
| 132 | .getEnvironmentStatus(expandedScopeInput) |
| 133 | .pipe(Effect.forkChild); |
| 134 | yield* Effect.promise(() => exchangeStarted.promise); |
| 135 | const secondMiss = yield* relayClient |
| 136 | .getEnvironmentStatus(expandedScopeInput) |
| 137 | .pipe(Effect.forkChild); |
| 138 | |
| 139 | const status = yield* relayClient.getEnvironmentStatus(statusInput); |
| 140 | expect(status.status).toBe("online"); |
| 141 | expect(statusTokens).toEqual(["DPoP cached-status-token"]); |
| 142 | |
| 143 | releaseExchange.resolve(); |
| 144 | yield* Fiber.join(firstMiss); |
| 145 | yield* Fiber.join(secondMiss); |
| 146 | expect(tokenExchangeCount).toBe(1); |
| 147 | expect(persistedTokens.map((token) => token.accessToken)).toEqual([ |
| 148 | "cached-status-token", |
| 149 | "expanded-scope-token", |
| 150 | ]); |
| 151 | yield* relayClient.resetTokenCache; |
| 152 | expect(persistedTokens).toEqual([]); |
| 153 | yield* relayClient.getEnvironmentStatus(expandedScopeInput); |
| 154 | expect(tokenExchangeCount).toBe(2); |
| 155 | }).pipe( |
| 156 | Effect.ensuring(Effect.sync(() => releaseExchange.resolve())), |
| 157 | Effect.provide(layerManagedRelayTest(fetchFn, undefined, accessTokenStore)), |
| 158 | ); |
| 159 | }); |
| 160 | |
| 161 | it.effect("reuses a persisted token across runtimes and Clerk session token rotation", () => { |
| 162 | let tokenExchangeCount = 0; |
| 163 | let persistedTokens: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry> = []; |
| 164 | const accessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = { |
| 165 | load: Effect.sync(() => persistedTokens), |
| 166 | save: (entries) => |
| 167 | Effect.sync(() => { |
| 168 | persistedTokens = entries; |
| 169 | }), |
| 170 | clear: Effect.sync(() => { |
| 171 | persistedTokens = []; |
| 172 | }), |
| 173 | }; |
| 174 | const fetchFn = ((input) => { |
| 175 | const url = String(input); |
| 176 | if (url.endsWith("/v1/client/dpop-token")) { |
| 177 | tokenExchangeCount += 1; |
| 178 | return Promise.resolve( |
| 179 | Response.json({ |
| 180 | access_token: "persisted-relay-token", |
| 181 | issued_token_type: "urn:ietf:params:oauth:token-type:access_token", |
| 182 | token_type: "DPoP", |
| 183 | expires_in: 1_800, |
| 184 | scope: RelayEnvironmentStatusScope, |
| 185 | }), |
| 186 | ); |
| 187 | } |
| 188 | return Promise.resolve( |
| 189 | Response.json({ |
| 190 | environmentId: "env-1", |
| 191 | endpoint: { |
| 192 | httpBaseUrl: "https://desktop.example.test/", |
| 193 | wsBaseUrl: "wss://desktop.example.test/ws", |
| 194 | providerKind: "cloudflare_tunnel", |
| 195 | }, |
| 196 | status: "online", |
| 197 | checkedAt: "2026-06-05T20:00:00.000Z", |
| 198 | descriptor: { |
| 199 | environmentId: "env-1", |
| 200 | label: "Desktop", |
| 201 | platform: { os: "darwin", arch: "arm64" }, |
| 202 | serverVersion: "0.0.0-test", |
| 203 | capabilities: { repositoryIdentity: true }, |
| 204 | }, |
| 205 | }), |
| 206 | ); |
| 207 | }) satisfies typeof globalThis.fetch; |
| 208 | const statusInput = (token: string) => |
| 209 | ({ |
| 210 | clerkToken: token, |
| 211 | scopes: [RelayEnvironmentStatusScope], |
| 212 | environmentId: EnvironmentId.make("env-1"), |
| 213 | }) as const; |
| 214 | |
| 215 | return Effect.gen(function* () { |
| 216 | yield* Effect.gen(function* () { |
| 217 | const relayClient = yield* ManagedRelay.ManagedRelayClient; |
| 218 | yield* relayClient.getEnvironmentStatus(statusInput(clerkToken("user-1", "session-1"))); |
| 219 | }).pipe(Effect.provide(layerManagedRelayTest(fetchFn, undefined, accessTokenStore))); |
| 220 | |
| 221 | expect(tokenExchangeCount).toBe(1); |
| 222 | expect(persistedTokens).toHaveLength(1); |
| 223 | |
| 224 | yield* Effect.gen(function* () { |
| 225 | const relayClient = yield* ManagedRelay.ManagedRelayClient; |
| 226 | yield* relayClient.getEnvironmentStatus(statusInput(clerkToken("user-1", "session-2"))); |
| 227 | }).pipe(Effect.provide(layerManagedRelayTest(fetchFn, undefined, accessTokenStore))); |
| 228 | |
| 229 | expect(tokenExchangeCount).toBe(1); |
| 230 | }); |
| 231 | }); |
| 232 | |
| 233 | it.effect("refreshes a persisted DPoP token once when the relay rejects it", () => { |
| 234 | let tokenExchangeCount = 0; |
| 235 | const statusTokens: Array<string | null> = []; |
| 236 | let persistedTokens: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry> = [ |
| 237 | { |
| 238 | accountId: "user-1", |
| 239 | clientId: "t3-mobile", |
| 240 | relayUrl: "https://relay.example.test", |
| 241 | thumbprint: "client-thumbprint", |
| 242 | scopes: [RelayEnvironmentStatusScope], |
| 243 | accessToken: "stale-relay-token", |
| 244 | expiresAtMillis: Number.MAX_SAFE_INTEGER, |
| 245 | }, |
| 246 | ]; |
| 247 | const accessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = { |
| 248 | load: Effect.sync(() => persistedTokens), |
| 249 | save: (entries) => |
| 250 | Effect.sync(() => { |
| 251 | persistedTokens = entries; |
| 252 | }), |
| 253 | clear: Effect.sync(() => { |
| 254 | persistedTokens = []; |
| 255 | }), |
| 256 | }; |
| 257 | const fetchFn = ((input, init) => { |
| 258 | const url = String(input); |
| 259 | if (url.endsWith("/v1/client/dpop-token")) { |
| 260 | tokenExchangeCount += 1; |
| 261 | return Promise.resolve( |
| 262 | Response.json({ |
| 263 | access_token: "fresh-relay-token", |
| 264 | issued_token_type: "urn:ietf:params:oauth:token-type:access_token", |
| 265 | token_type: "DPoP", |
| 266 | expires_in: 1_800, |
| 267 | scope: RelayEnvironmentStatusScope, |
| 268 | }), |
| 269 | ); |
| 270 | } |
| 271 | |
| 272 | const authorization = new Headers(init?.headers).get("authorization"); |
| 273 | statusTokens.push(authorization); |
| 274 | if (authorization === "DPoP stale-relay-token") { |
| 275 | return Promise.resolve( |
| 276 | Response.json( |
| 277 | { |
| 278 | _tag: "RelayAuthInvalidError", |
| 279 | code: "auth_invalid", |
| 280 | reason: "invalid_bearer", |
| 281 | traceId: "trace-stale-token", |
| 282 | }, |
| 283 | { status: 401 }, |
| 284 | ), |
| 285 | ); |
| 286 | } |
| 287 | return Promise.resolve( |
| 288 | Response.json({ |
| 289 | environmentId: "env-1", |
| 290 | endpoint: { |
| 291 | httpBaseUrl: "https://desktop.example.test/", |
| 292 | wsBaseUrl: "wss://desktop.example.test/ws", |
| 293 | providerKind: "cloudflare_tunnel", |
| 294 | }, |
| 295 | status: "online", |
| 296 | checkedAt: "2026-06-05T20:00:00.000Z", |
| 297 | descriptor: { |
| 298 | environmentId: "env-1", |
| 299 | label: "Desktop", |
| 300 | platform: { os: "darwin", arch: "arm64" }, |
| 301 | serverVersion: "0.0.0-test", |
| 302 | capabilities: { repositoryIdentity: true }, |
| 303 | }, |
| 304 | }), |
| 305 | ); |
| 306 | }) satisfies typeof globalThis.fetch; |
| 307 | |
| 308 | return Effect.gen(function* () { |
| 309 | const relayClient = yield* ManagedRelay.ManagedRelayClient; |
| 310 | const result = yield* relayClient.getEnvironmentStatus({ |
| 311 | clerkToken: clerkToken("user-1", "session-1"), |
| 312 | scopes: [RelayEnvironmentStatusScope], |
| 313 | environmentId: EnvironmentId.make("env-1"), |
| 314 | }); |
| 315 | |
| 316 | expect(result.status).toBe("online"); |
| 317 | expect(statusTokens).toEqual(["DPoP stale-relay-token", "DPoP fresh-relay-token"]); |
| 318 | expect(tokenExchangeCount).toBe(1); |
| 319 | expect(persistedTokens).toMatchObject([ |
| 320 | { |
| 321 | accessToken: "fresh-relay-token", |
| 322 | }, |
| 323 | ]); |
| 324 | }).pipe(Effect.provide(layerManagedRelayTest(fetchFn, undefined, accessTokenStore))); |
| 325 | }); |
| 326 | |
| 327 | it.effect("does not persist tokens when the Clerk subject cannot be decoded", () => { |
| 328 | let persistedTokens: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry> = []; |
| 329 | const accessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = { |
| 330 | load: Effect.succeed([]), |
| 331 | save: (entries) => |
| 332 | Effect.sync(() => { |
| 333 | persistedTokens = entries; |
| 334 | }), |
| 335 | clear: Effect.void, |
| 336 | }; |
| 337 | const fetchFn = ((input) => { |
| 338 | const url = String(input); |
| 339 | if (url.endsWith("/v1/client/dpop-token")) { |
| 340 | return Promise.resolve( |
| 341 | Response.json({ |
| 342 | access_token: "relay-token", |
| 343 | issued_token_type: "urn:ietf:params:oauth:token-type:access_token", |
| 344 | token_type: "DPoP", |
| 345 | expires_in: 1_800, |
| 346 | scope: RelayEnvironmentStatusScope, |
| 347 | }), |
| 348 | ); |
| 349 | } |
| 350 | return Promise.resolve( |
| 351 | Response.json({ |
| 352 | environmentId: "env-1", |
| 353 | endpoint: { |
| 354 | httpBaseUrl: "https://desktop.example.test/", |
| 355 | wsBaseUrl: "wss://desktop.example.test/ws", |
| 356 | providerKind: "cloudflare_tunnel", |
| 357 | }, |
| 358 | status: "online", |
| 359 | checkedAt: "2026-06-05T20:00:00.000Z", |
| 360 | descriptor: { |
| 361 | environmentId: "env-1", |
| 362 | label: "Desktop", |
| 363 | platform: { os: "darwin", arch: "arm64" }, |
| 364 | serverVersion: "0.0.0-test", |
| 365 | capabilities: { repositoryIdentity: true }, |
| 366 | }, |
| 367 | }), |
| 368 | ); |
| 369 | }) satisfies typeof globalThis.fetch; |
| 370 | |
| 371 | return Effect.gen(function* () { |
| 372 | const relayClient = yield* ManagedRelay.ManagedRelayClient; |
| 373 | yield* relayClient.getEnvironmentStatus({ |
| 374 | clerkToken: "not-a-jwt", |
| 375 | scopes: [RelayEnvironmentStatusScope], |
| 376 | environmentId: EnvironmentId.make("env-1"), |
| 377 | }); |
| 378 | |
| 379 | expect(persistedTokens).toEqual([]); |
| 380 | }).pipe(Effect.provide(layerManagedRelayTest(fetchFn, undefined, accessTokenStore))); |
| 381 | }); |
| 382 | |
| 383 | it.effect("explains a relay deadline 504 on link and keeps its trace ID", () => { |
| 384 | const fetchFn = (() => |
| 385 | Promise.resolve( |
| 386 | Response.json( |
| 387 | { error: "relay_request_deadline_exceeded" }, |
| 388 | { |
| 389 | status: 504, |
| 390 | headers: { |
| 391 | traceparent: "00-4684d7d140f34f0393d42744d240e207-0baf648c44f4bce6-01", |
| 392 | }, |
| 393 | }, |
| 394 | ), |
| 395 | )) satisfies typeof globalThis.fetch; |
| 396 | |
| 397 | return Effect.gen(function* () { |
| 398 | const relayClient = yield* ManagedRelay.ManagedRelayClient; |
| 399 | const error = yield* relayClient |
| 400 | .linkEnvironment({ |
| 401 | clerkToken: "clerk-token", |
| 402 | payload: { |
| 403 | proof: "link-proof", |
| 404 | notificationsEnabled: true, |
| 405 | liveActivitiesEnabled: true, |
| 406 | managedTunnelsEnabled: true, |
| 407 | }, |
| 408 | }) |
| 409 | .pipe(Effect.flip); |
| 410 | |
| 411 | expect(error).toMatchObject({ |
| 412 | _tag: "ManagedRelayRequestFailedError", |
| 413 | status: 504, |
| 414 | traceId: "4684d7d140f34f0393d42744d240e207", |
| 415 | }); |
| 416 | expect( |
| 417 | error._tag === "ManagedRelayRequestFailedError" ? relayRequestFailureDetail(error) : null, |
| 418 | ).toBe(RELAY_GATEWAY_TIMEOUT_MESSAGE); |
| 419 | }).pipe(Effect.provide(layerManagedRelayTest(fetchFn))); |
| 420 | }); |
| 421 | |
| 422 | it.effect("accepts generic DPoP errors from relays without the optional reason", () => { |
| 423 | const fetchFn = (() => |
| 424 | Promise.resolve( |
| 425 | Response.json( |
| 426 | { |
| 427 | _tag: "RelayAuthInvalidError", |
| 428 | code: "auth_invalid", |
| 429 | reason: "invalid_dpop", |
| 430 | traceId: "trace-old-relay", |
| 431 | }, |
| 432 | { status: 401 }, |
| 433 | ), |
| 434 | )) satisfies typeof globalThis.fetch; |
| 435 | |
| 436 | return Effect.gen(function* () { |
| 437 | const relayClient = yield* ManagedRelay.ManagedRelayClient; |
| 438 | const error = yield* relayClient |
| 439 | .listEnvironments({ clerkToken: "clerk-token" }) |
| 440 | .pipe(Effect.flip); |
| 441 | |
| 442 | expect(error).toMatchObject({ |
| 443 | _tag: "ManagedRelayRequestFailedError", |
| 444 | traceId: "trace-old-relay", |
| 445 | relayError: { |
| 446 | _tag: "RelayAuthInvalidError", |
| 447 | reason: "invalid_dpop", |
| 448 | }, |
| 449 | }); |
| 450 | if ( |
| 451 | error._tag === "ManagedRelayRequestFailedError" && |
| 452 | error.relayError?._tag === "RelayAuthInvalidError" |
| 453 | ) { |
| 454 | expect(error.relayError.dpopFailureReason).toBeUndefined(); |
| 455 | } |
| 456 | }).pipe(Effect.provide(layerManagedRelayTest(fetchFn))); |
| 457 | }); |
| 458 | }); |