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 * as HttpServer from "effect/http/HttpServer"; |
| 2 | import { |
| 3 | RelayClientAuth, |
| 4 | RelayClientPrincipal, |
| 5 | type RelayClientDeviceRecord, |
| 6 | } from "@t3tools/contracts/relay"; |
| 7 | import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts"; |
| 8 | import * as RelayTokens from "../auth/RelayTokens.ts"; |
| 9 | import * as Devices from "../agentActivity/Devices.ts"; |
| 10 | // @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync. |
| 11 | import * as NodeCrypto from "node:crypto"; |
| 12 | import { createClerkClient, verifyToken } from "@clerk/backend"; |
| 13 | import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform"; |
| 14 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 15 | import { describe, expect, it } from "@effect/vitest"; |
| 16 | import { vi } from "vite-plus/test"; |
| 17 | import * as Context from "effect/Context"; |
| 18 | import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto"; |
| 19 | import * as DateTime from "effect/DateTime"; |
| 20 | import * as Deferred from "effect/Deferred"; |
| 21 | import * as Effect from "effect/Effect"; |
| 22 | import * as Layer from "effect/Layer"; |
| 23 | import * as Option from "effect/Option"; |
| 24 | import * as Predicate from "effect/Predicate"; |
| 25 | import * as Redacted from "effect/Redacted"; |
| 26 | import * as Schema from "effect/Schema"; |
| 27 | import * as Tracer from "effect/Tracer"; |
| 28 | import * as Etag from "effect/http/Etag"; |
| 29 | import * as HttpEffect from "effect/http/HttpEffect"; |
| 30 | import * as HttpRouter from "effect/http/HttpRouter"; |
| 31 | import * as HttpServerRequest from "effect/http/HttpServerRequest"; |
| 32 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 33 | import * as HttpApi from "effect/http-api/HttpApi"; |
| 34 | import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 35 | import { EnvironmentId } from "@t3tools/contracts"; |
| 36 | import { |
| 37 | RelayEnvironmentAuth, |
| 38 | RelayEnvironmentPrincipal, |
| 39 | RelayApi, |
| 40 | RelayEnvironmentLinkUnavailableError, |
| 41 | RelayEnvironmentLinkRequest, |
| 42 | } from "@t3tools/contracts/relay"; |
| 43 | import { relayProtectedErrorMessage } from "@t3tools/client-runtime/relay"; |
| 44 | import { RELAY_MANAGED_TUNNEL_RECOVERY_TYP, signRelayJwt } from "@t3tools/shared/relayJwt"; |
| 45 | |
| 46 | import { |
| 47 | RELAY_HTTP_ROUTER_CONFIG, |
| 48 | recoverEnvironmentTunnelRecord, |
| 49 | registerEnvironmentTunnelRecovery, |
| 50 | relayDpopFailureReason, |
| 51 | traceRelayHttpRequestWith, |
| 52 | unlinkEnvironmentRecord, |
| 53 | verifyRelayClientBearerToken, |
| 54 | verifyEnvironmentTunnelRecoveryProof, |
| 55 | withoutCapturedParentSpan, |
| 56 | } from "./Api.ts"; |
| 57 | import * as RelayHttpApi from "./Api.ts"; |
| 58 | import * as RelayConfiguration from "../Config.ts"; |
| 59 | import * as RelayDb from "../db.ts"; |
| 60 | import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts"; |
| 61 | import * as HeldHooks from "../hooks/HeldHooks.ts"; |
| 62 | import * as HookInbox from "../hooks/HookInbox.ts"; |
| 63 | import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts"; |
| 64 | import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts"; |
| 65 | import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts"; |
| 66 | import * as ManagedTunnelLimits from "../environments/ManagedTunnelLimits.ts"; |
| 67 | import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts"; |
| 68 | import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts"; |
| 69 | import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts"; |
| 70 | |
| 71 | vi.mock("@clerk/backend", () => ({ |
| 72 | createClerkClient: vi.fn(), |
| 73 | verifyToken: vi.fn(), |
| 74 | })); |
| 75 | |
| 76 | const relaySettings: RelayConfiguration.RelayConfiguration["Service"] = { |
| 77 | relayIssuer: "https://relay.example.test", |
| 78 | apns: { |
| 79 | teamId: "apns-team", |
| 80 | keyId: "apns-key", |
| 81 | privateKey: Redacted.make("apns-private-key"), |
| 82 | bundleId: "com.example.t3", |
| 83 | environment: "sandbox", |
| 84 | }, |
| 85 | clerkSecretKey: Redacted.make("clerk-secret-key"), |
| 86 | clerkPublishableKey: "pk_test_test", |
| 87 | clerkJwtAudience: "t3-code-relay", |
| 88 | apnsDeliveryJobSigningSecret: Redacted.make("apns-delivery-secret"), |
| 89 | cloudMintPrivateKey: Redacted.make("cloud-mint-private-key"), |
| 90 | cloudMintPublicKey: "cloud-mint-public-key", |
| 91 | managedEndpointBaseDomain: undefined, |
| 92 | managedEndpointNamespace: undefined, |
| 93 | }; |
| 94 | |
| 95 | const encodeLinkRequest = Schema.encodeEffect(Schema.fromJsonString(RelayEnvironmentLinkRequest)); |
| 96 | const decodeLinkUnavailableError = Schema.decodeUnknownEffect(RelayEnvironmentLinkUnavailableError); |
| 97 | |
| 98 | describe("managed endpoint provisioning errors", () => { |
| 99 | it.effect("returns the failed stage without exposing provider secrets through HTTP", () => { |
| 100 | let traceId = ""; |
| 101 | const handlers = RelayHttpApi.layerClientApi.pipe( |
| 102 | HttpRouter.provideRequest( |
| 103 | Layer.mergeAll( |
| 104 | Layer.mock(EnvironmentCredentials.EnvironmentCredentials, {}), |
| 105 | Layer.mock(EnvironmentLinks.EnvironmentLinks, {}), |
| 106 | Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), |
| 107 | Layer.mock(RelayDb.RelayTransactions, {}), |
| 108 | Layer.mock(HookInbox.HookInbox, {}), |
| 109 | ), |
| 110 | ), |
| 111 | Layer.provide( |
| 112 | Layer.mergeAll( |
| 113 | Layer.succeed(RelayConfiguration.RelayConfiguration, relaySettings), |
| 114 | NodeCryptoLayer.layer, |
| 115 | Layer.mock(RelayTokens.RelayTokens, { resolveDpopAccessTokenScopes: () => null }), |
| 116 | Layer.mock(EnvironmentLinker.EnvironmentLinker, { |
| 117 | link: () => |
| 118 | Effect.gen(function* () { |
| 119 | traceId = (yield* Effect.currentSpan.pipe(Effect.orDie)).traceId; |
| 120 | return yield* new ManagedEndpointProvider.ManagedEndpointProvisioningFailed({ |
| 121 | userId: "user-1", |
| 122 | environmentId: "environment-1", |
| 123 | stage: "ensure-tunnel", |
| 124 | tunnelId: "private-tunnel-id", |
| 125 | cause: new Error("private-provider-token"), |
| 126 | }); |
| 127 | }), |
| 128 | }), |
| 129 | Layer.mock(EnvironmentLinks.EnvironmentLinks, {}), |
| 130 | Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), |
| 131 | Layer.mock(Devices.Devices, {}), |
| 132 | Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }), |
| 133 | Layer.mock(ManagedTunnelLimits.ManagedTunnelLimits, {}), |
| 134 | ), |
| 135 | ), |
| 136 | Layer.provideMerge( |
| 137 | Layer.succeed(RelayClientAuth, { |
| 138 | clientBearer: (effect) => |
| 139 | Effect.provideService(effect, RelayClientPrincipal, { |
| 140 | userId: "user-1", |
| 141 | token: "test-token", |
| 142 | }), |
| 143 | }), |
| 144 | ), |
| 145 | ); |
| 146 | return Effect.gen(function* () { |
| 147 | const app = yield* Effect.acquireRelease( |
| 148 | Effect.sync(() => |
| 149 | HttpRouter.toWebHandler( |
| 150 | HttpApiBuilder.layer(HttpApi.make("RelayApi").add(RelayApi.groups.client)).pipe( |
| 151 | Layer.provide(handlers), |
| 152 | Layer.provide(HttpServer.layerServices), |
| 153 | ), |
| 154 | { disableLogger: true }, |
| 155 | ), |
| 156 | ), |
| 157 | (app) => Effect.promise(() => app.dispose()), |
| 158 | ); |
| 159 | const payload = yield* encodeLinkRequest({ |
| 160 | proof: "test-proof", |
| 161 | notificationsEnabled: false, |
| 162 | liveActivitiesEnabled: false, |
| 163 | managedTunnelsEnabled: true, |
| 164 | }); |
| 165 | const response = yield* Effect.promise(() => |
| 166 | app.handler( |
| 167 | new Request("https://relay.example.test/v1/client/environment-links", { |
| 168 | method: "POST", |
| 169 | headers: { |
| 170 | authorization: "Bearer test-token", |
| 171 | "content-type": "application/json", |
| 172 | }, |
| 173 | body: payload, |
| 174 | }), |
| 175 | ), |
| 176 | ); |
| 177 | expect(response.status).toBe(503); |
| 178 | const body = yield* Effect.promise(() => response.json()); |
| 179 | expect(body).toEqual({ |
| 180 | _tag: "RelayEnvironmentLinkUnavailableError", |
| 181 | code: "environment_link_unavailable", |
| 182 | reason: "managed_endpoint_provisioning_failed", |
| 183 | provisioningStage: "ensure-tunnel", |
| 184 | traceId, |
| 185 | }); |
| 186 | const error = yield* decodeLinkUnavailableError(body); |
| 187 | expect(relayProtectedErrorMessage(error)).toBe( |
| 188 | "Relay cannot provision the managed endpoint (managed_endpoint_provisioning_failed). Failed stage: ensure-tunnel.", |
| 189 | ); |
| 190 | }).pipe(Effect.scoped); |
| 191 | }); |
| 192 | }); |
| 193 | |
| 194 | describe("device listing compatibility", () => { |
| 195 | it.effect("keeps v1 iOS-only while v2 returns every platform for the same account", () => { |
| 196 | const iphone: RelayClientDeviceRecord = { |
| 197 | deviceId: "iphone", |
| 198 | label: "iPhone", |
| 199 | platform: "ios", |
| 200 | iosMajorVersion: 18, |
| 201 | appVersion: "1.0.0", |
| 202 | notifications: { |
| 203 | enabled: true, |
| 204 | notifyOnApproval: true, |
| 205 | notifyOnInput: true, |
| 206 | notifyOnCompletion: true, |
| 207 | notifyOnFailure: true, |
| 208 | }, |
| 209 | liveActivities: { enabled: true }, |
| 210 | updatedAt: "2026-09-09T00:00:00.000Z", |
| 211 | }; |
| 212 | const android: RelayClientDeviceRecord = { |
| 213 | ...iphone, |
| 214 | deviceId: "android", |
| 215 | label: "Android", |
| 216 | platform: "android", |
| 217 | iosMajorVersion: null, |
| 218 | androidApiLevel: 36, |
| 219 | }; |
| 220 | const layerHandlers = RelayHttpApi.layerClientApi.pipe( |
| 221 | HttpRouter.provideRequest( |
| 222 | Layer.mergeAll( |
| 223 | Layer.mock(EnvironmentCredentials.EnvironmentCredentials, {}), |
| 224 | Layer.mock(EnvironmentLinks.EnvironmentLinks, {}), |
| 225 | Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), |
| 226 | Layer.mock(RelayDb.RelayTransactions, {}), |
| 227 | Layer.mock(HookInbox.HookInbox, {}), |
| 228 | ), |
| 229 | ), |
| 230 | Layer.provide( |
| 231 | Layer.mergeAll( |
| 232 | Layer.succeed(RelayConfiguration.RelayConfiguration, relaySettings), |
| 233 | NodeCryptoLayer.layer, |
| 234 | Layer.mock(RelayTokens.RelayTokens, { resolveDpopAccessTokenScopes: () => null }), |
| 235 | Layer.mock(EnvironmentLinker.EnvironmentLinker, {}), |
| 236 | Layer.mock(EnvironmentLinks.EnvironmentLinks, {}), |
| 237 | Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), |
| 238 | Layer.mock(Devices.Devices, { |
| 239 | listForUser: ({ userId }) => { |
| 240 | expect(userId).toBe("user-1"); |
| 241 | return Effect.succeed([iphone, android]); |
| 242 | }, |
| 243 | }), |
| 244 | Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }), |
| 245 | Layer.mock(ManagedTunnelLimits.ManagedTunnelLimits, {}), |
| 246 | ), |
| 247 | ), |
| 248 | Layer.provideMerge( |
| 249 | Layer.succeed(RelayClientAuth, { |
| 250 | clientBearer: (effect) => |
| 251 | Effect.provideService(effect, RelayClientPrincipal, { |
| 252 | userId: "user-1", |
| 253 | token: "test-token", |
| 254 | }), |
| 255 | }), |
| 256 | ), |
| 257 | ); |
| 258 | return Effect.gen(function* () { |
| 259 | const app = yield* Effect.acquireRelease( |
| 260 | Effect.sync(() => |
| 261 | HttpRouter.toWebHandler( |
| 262 | HttpApiBuilder.layer(HttpApi.make("RelayApi").add(RelayApi.groups.client)).pipe( |
| 263 | Layer.provide(layerHandlers), |
| 264 | Layer.provide(HttpServer.layerServices), |
| 265 | ), |
| 266 | { disableLogger: true }, |
| 267 | ), |
| 268 | ), |
| 269 | (app) => Effect.promise(() => app.dispose()), |
| 270 | ); |
| 271 | for (const [version, devices] of [ |
| 272 | ["v1", [iphone]], |
| 273 | ["v2", [iphone, android]], |
| 274 | ] as const) { |
| 275 | const response = yield* Effect.promise(() => |
| 276 | app.handler( |
| 277 | new Request(`https://relay.example.test/${version}/client/devices`, { |
| 278 | headers: { authorization: "Bearer test-token" }, |
| 279 | }), |
| 280 | ), |
| 281 | ); |
| 282 | expect(response.status).toBe(200); |
| 283 | expect(response.headers.get("cache-control")).toBe("no-store"); |
| 284 | expect(yield* Effect.promise(() => response.json())).toEqual({ devices }); |
| 285 | } |
| 286 | }).pipe(Effect.scoped); |
| 287 | }); |
| 288 | }); |
| 289 | |
| 290 | describe("Cloudflare rate-limit retry hint", () => { |
| 291 | const provisioningFailed = (cause?: unknown) => |
| 292 | new ManagedEndpointProvider.ManagedEndpointProvisioningFailed({ |
| 293 | userId: "user-1", |
| 294 | environmentId: "env-1", |
| 295 | stage: "ensure-tunnel", |
| 296 | ...(cause === undefined |
| 297 | ? {} |
| 298 | : { |
| 299 | cause: new ManagedEndpointProvider.ManagedEndpointTunnelClientError({ |
| 300 | operation: "list", |
| 301 | cause, |
| 302 | }), |
| 303 | }), |
| 304 | }); |
| 305 | |
| 306 | const linkResponse = (failure: ManagedEndpointProvider.ManagedEndpointProvisioningFailed) => { |
| 307 | const layerHandlers = RelayHttpApi.layerClientApi.pipe( |
| 308 | HttpRouter.provideRequest( |
| 309 | Layer.mergeAll( |
| 310 | Layer.mock(EnvironmentCredentials.EnvironmentCredentials, {}), |
| 311 | Layer.mock(EnvironmentLinks.EnvironmentLinks, {}), |
| 312 | Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), |
| 313 | Layer.mock(RelayDb.RelayTransactions, {}), |
| 314 | Layer.mock(HookInbox.HookInbox, {}), |
| 315 | ), |
| 316 | ), |
| 317 | Layer.provide( |
| 318 | Layer.mergeAll( |
| 319 | Layer.succeed(RelayConfiguration.RelayConfiguration, relaySettings), |
| 320 | NodeCryptoLayer.layer, |
| 321 | Layer.mock(RelayTokens.RelayTokens, { resolveDpopAccessTokenScopes: () => null }), |
| 322 | Layer.mock(EnvironmentLinker.EnvironmentLinker, { link: () => Effect.fail(failure) }), |
| 323 | Layer.mock(EnvironmentLinks.EnvironmentLinks, {}), |
| 324 | Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), |
| 325 | Layer.mock(Devices.Devices, {}), |
| 326 | Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }), |
| 327 | Layer.mock(ManagedTunnelLimits.ManagedTunnelLimits, {}), |
| 328 | ), |
| 329 | ), |
| 330 | Layer.provideMerge( |
| 331 | Layer.succeed(RelayClientAuth, { |
| 332 | clientBearer: (effect) => |
| 333 | Effect.provideService(effect, RelayClientPrincipal, { |
| 334 | userId: "user-1", |
| 335 | token: "test-token", |
| 336 | }), |
| 337 | }), |
| 338 | ), |
| 339 | ); |
| 340 | return Effect.acquireRelease( |
| 341 | Effect.sync(() => |
| 342 | HttpRouter.toWebHandler( |
| 343 | HttpApiBuilder.layer(HttpApi.make("RelayApi").add(RelayApi.groups.client)).pipe( |
| 344 | Layer.provide(layerHandlers), |
| 345 | Layer.provide(HttpServer.layerServices), |
| 346 | ), |
| 347 | { disableLogger: true }, |
| 348 | ), |
| 349 | ), |
| 350 | (app) => Effect.promise(() => app.dispose()), |
| 351 | ).pipe( |
| 352 | Effect.flatMap((app) => |
| 353 | Effect.promise(() => |
| 354 | app.handler( |
| 355 | new Request("https://relay.example.test/v1/client/environment-links", { |
| 356 | method: "POST", |
| 357 | headers: { authorization: "Bearer test-token", "content-type": "application/json" }, |
| 358 | body: JSON.stringify({ |
| 359 | proof: "signed-proof", |
| 360 | notificationsEnabled: true, |
| 361 | liveActivitiesEnabled: true, |
| 362 | managedTunnelsEnabled: true, |
| 363 | }), |
| 364 | }), |
| 365 | ), |
| 366 | ), |
| 367 | ), |
| 368 | ); |
| 369 | }; |
| 370 | |
| 371 | it.effect("tells a link refused during a Cloudflare pause when to retry", () => |
| 372 | Effect.gen(function* () { |
| 373 | const paused = yield* linkResponse( |
| 374 | provisioningFailed( |
| 375 | new ManagedEndpointProvider.CloudflareApiPaused({ retryAfterMillis: 24_100 }), |
| 376 | ), |
| 377 | ); |
| 378 | expect(paused.status).toBe(503); |
| 379 | expect(paused.headers.get("retry-after")).toBe("25"); |
| 380 | |
| 381 | const other = yield* linkResponse(provisioningFailed()); |
| 382 | expect(other.status).toBe(503); |
| 383 | expect(other.headers.get("retry-after")).toBeNull(); |
| 384 | }).pipe(Effect.scoped), |
| 385 | ); |
| 386 | }); |
| 387 | |
| 388 | describe("relay client authentication", () => { |
| 389 | it.effect("preserves the existing Clerk session JWT path", () => |
| 390 | Effect.gen(function* () { |
| 391 | vi.mocked(verifyToken).mockResolvedValue({ |
| 392 | sub: "user_session", |
| 393 | aud: relaySettings.clerkJwtAudience, |
| 394 | } as never); |
| 395 | |
| 396 | expect(yield* verifyRelayClientBearerToken(relaySettings, "session-token")).toEqual({ |
| 397 | sub: "user_session", |
| 398 | mode: "clerk_session_bearer", |
| 399 | }); |
| 400 | expect(verifyToken).toHaveBeenCalledWith("session-token", { |
| 401 | secretKey: "clerk-secret-key", |
| 402 | audience: relaySettings.clerkJwtAudience, |
| 403 | }); |
| 404 | expect(createClerkClient).not.toHaveBeenCalled(); |
| 405 | }).pipe( |
| 406 | Effect.ensuring( |
| 407 | Effect.sync(() => { |
| 408 | vi.mocked(verifyToken).mockReset(); |
| 409 | vi.mocked(createClerkClient).mockReset(); |
| 410 | }), |
| 411 | ), |
| 412 | ), |
| 413 | ); |
| 414 | |
| 415 | it.effect("falls back to Clerk OAuth token verification for the headless CLI", () => |
| 416 | Effect.gen(function* () { |
| 417 | vi.mocked(verifyToken).mockRejectedValue(new Error("not a session JWT")); |
| 418 | vi.mocked(createClerkClient).mockReturnValue({ |
| 419 | authenticateRequest: vi.fn().mockResolvedValue({ |
| 420 | isAuthenticated: true, |
| 421 | toAuth: () => ({ userId: "user_oauth" }), |
| 422 | }), |
| 423 | } as never); |
| 424 | |
| 425 | expect(yield* verifyRelayClientBearerToken(relaySettings, "oauth-token")).toEqual({ |
| 426 | sub: "user_oauth", |
| 427 | mode: "clerk_oauth_bearer", |
| 428 | }); |
| 429 | expect(createClerkClient).toHaveBeenCalledWith({ |
| 430 | secretKey: "clerk-secret-key", |
| 431 | publishableKey: "pk_test_test", |
| 432 | }); |
| 433 | }).pipe( |
| 434 | Effect.ensuring( |
| 435 | Effect.sync(() => { |
| 436 | vi.mocked(verifyToken).mockReset(); |
| 437 | vi.mocked(createClerkClient).mockReset(); |
| 438 | }), |
| 439 | ), |
| 440 | ), |
| 441 | ); |
| 442 | }); |
| 443 | |
| 444 | describe("relay DPoP failure mapping", () => { |
| 445 | it("maps verifier failures to safe client-facing categories", () => { |
| 446 | const mappings = [ |
| 447 | ["time_window", "time_window"], |
| 448 | ["key_mismatch", "key_mismatch"], |
| 449 | ["method_mismatch", "request_mismatch"], |
| 450 | ["url_mismatch", "request_mismatch"], |
| 451 | ["access_token_hash_mismatch", "token_mismatch"], |
| 452 | ["replayed", "replay"], |
| 453 | ["missing_proof", "invalid_proof"], |
| 454 | ["malformed_proof", "invalid_proof"], |
| 455 | ["invalid_signature", "invalid_proof"], |
| 456 | ["invalid_proof", "invalid_proof"], |
| 457 | ] as const; |
| 458 | |
| 459 | for (const [code, expected] of mappings) { |
| 460 | expect(relayDpopFailureReason(code)).toBe(expected); |
| 461 | } |
| 462 | }); |
| 463 | }); |
| 464 | |
| 465 | describe("relay environment authentication", () => { |
| 466 | it.effect("preserves credential lookup persistence failures as internal errors", () => { |
| 467 | const failure = new EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError({ |
| 468 | stage: "lookup-credential", |
| 469 | cause: "database unavailable", |
| 470 | }); |
| 471 | const credentials: EnvironmentCredentials.EnvironmentCredentials["Service"] = { |
| 472 | create: () => Effect.die("unused create"), |
| 473 | authenticate: () => Effect.fail(failure), |
| 474 | revokeForEnvironmentPublicKey: () => Effect.die("unused revoke"), |
| 475 | }; |
| 476 | |
| 477 | return Effect.gen(function* () { |
| 478 | const auth = yield* RelayEnvironmentAuth; |
| 479 | const error = yield* Effect.flip( |
| 480 | auth.environmentBearer(Effect.succeed(HttpServerResponse.empty()), { |
| 481 | credential: Redacted.make("environment-credential"), |
| 482 | endpoint: {} as never, |
| 483 | group: {} as never, |
| 484 | }), |
| 485 | ); |
| 486 | |
| 487 | expect(Predicate.isTagged(error, "RelayInternalError")).toBe(true); |
| 488 | if (Predicate.isTagged(error, "RelayInternalError")) { |
| 489 | expect(error.reason).toBe("persistence_failed"); |
| 490 | } |
| 491 | }).pipe( |
| 492 | Effect.provideService( |
| 493 | HttpServerRequest.HttpServerRequest, |
| 494 | HttpServerRequest.fromWeb(new Request("https://relay.test/v1/server/link")), |
| 495 | ), |
| 496 | Effect.provideService(HttpServerRequest.ParsedSearchParams, {}), |
| 497 | Effect.provideService(HttpRouter.RouteContext, { |
| 498 | params: {}, |
| 499 | route: {} as never, |
| 500 | }), |
| 501 | Effect.provide( |
| 502 | RelayHttpApi.layerEnvironmentAuth.pipe( |
| 503 | Layer.provide(Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, credentials)), |
| 504 | ), |
| 505 | ), |
| 506 | Effect.scoped, |
| 507 | ); |
| 508 | }); |
| 509 | }); |
| 510 | |
| 511 | function layerRelayUnlinkTest(input?: { |
| 512 | readonly withTransaction?: RelayDb.RelayTransactions["Service"]["withTransaction"]; |
| 513 | readonly getForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["getForUser"]; |
| 514 | readonly revokeForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["revokeForUser"]; |
| 515 | readonly revokeCredential?: EnvironmentCredentials.EnvironmentCredentials["Service"]["revokeForEnvironmentPublicKey"]; |
| 516 | readonly prepareDeprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["prepareDeprovision"]; |
| 517 | readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"]; |
| 518 | readonly provision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["provision"]; |
| 519 | readonly reconcileOrigin?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["reconcileOrigin"]; |
| 520 | readonly release?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["release"]; |
| 521 | readonly clearInbox?: HookInbox.HookInbox["Service"]["clear"]; |
| 522 | }) { |
| 523 | return Layer.mergeAll( |
| 524 | Layer.mock(HookInbox.HookInbox, { |
| 525 | clear: input?.clearInbox ?? (() => Effect.void), |
| 526 | }), |
| 527 | Layer.succeed( |
| 528 | RelayDb.RelayTransactions, |
| 529 | RelayDb.RelayTransactions.of({ |
| 530 | withTransaction: input?.withTransaction ?? ((effect) => effect), |
| 531 | }), |
| 532 | ), |
| 533 | Layer.succeed( |
| 534 | EnvironmentLinks.EnvironmentLinks, |
| 535 | EnvironmentLinks.EnvironmentLinks.of({ |
| 536 | upsert: () => Effect.die("unused upsert"), |
| 537 | listDeliveryUsersForEnvironment: () => Effect.die("unused listDeliveryUsersForEnvironment"), |
| 538 | listForUser: () => Effect.die("unused listForUser"), |
| 539 | getForUser: input?.getForUser ?? (() => Effect.succeed(null)), |
| 540 | findActiveManagedForEnvironment: () => Effect.die("unused findActiveManagedForEnvironment"), |
| 541 | updateLiveActivityPreference: () => |
| 542 | Effect.die("unexpected Live Activity preference update"), |
| 543 | setHoldWebhooksWhileOffline: () => Effect.die("unused setHoldWebhooksWhileOffline"), |
| 544 | revokeForUser: input?.revokeForUser ?? (() => Effect.succeed(false)), |
| 545 | }), |
| 546 | ), |
| 547 | Layer.succeed( |
| 548 | EnvironmentCredentials.EnvironmentCredentials, |
| 549 | EnvironmentCredentials.EnvironmentCredentials.of({ |
| 550 | create: () => Effect.die("unused create"), |
| 551 | authenticate: () => Effect.die("unused authenticate"), |
| 552 | revokeForEnvironmentPublicKey: input?.revokeCredential ?? (() => Effect.succeed(false)), |
| 553 | }), |
| 554 | ), |
| 555 | Layer.succeed( |
| 556 | ManagedEndpointProvider.ManagedEndpointProvider, |
| 557 | ManagedEndpointProvider.ManagedEndpointProvider.of({ |
| 558 | provision: input?.provision ?? (() => Effect.die("unused provision")), |
| 559 | reconcileOrigin: input?.reconcileOrigin ?? (() => Effect.succeed("ready")), |
| 560 | prepareDeprovision: input?.prepareDeprovision ?? (() => Effect.succeed(null)), |
| 561 | deprovision: input?.deprovision ?? (() => Effect.succeed(true)), |
| 562 | release: input?.release ?? (() => Effect.die("unused release")), |
| 563 | }), |
| 564 | ), |
| 565 | ); |
| 566 | } |
| 567 | |
| 568 | const linkedEnvironmentRecord = { |
| 569 | environmentId: EnvironmentId.make("environment-1"), |
| 570 | label: "Environment 1", |
| 571 | endpoint: { |
| 572 | httpBaseUrl: "https://environment-1.example.test/", |
| 573 | wsBaseUrl: "wss://environment-1.example.test/ws", |
| 574 | providerKind: "cloudflare_tunnel", |
| 575 | }, |
| 576 | environmentPublicKey: "public-key", |
| 577 | linkedAt: "2026-07-28T00:00:00.000Z", |
| 578 | } as const; |
| 579 | |
| 580 | describe("relay managed tunnel recovery", () => { |
| 581 | it.effect("binds recovery requests to the host, cloud user, and T3 service origin", () => |
| 582 | Effect.gen(function* () { |
| 583 | const keyPair = NodeCrypto.generateKeyPairSync("ed25519", { |
| 584 | privateKeyEncoding: { format: "pem", type: "pkcs8" }, |
| 585 | publicKeyEncoding: { format: "pem", type: "spki" }, |
| 586 | }); |
| 587 | const now = yield* DateTime.now; |
| 588 | const issuedAt = Math.floor(now.epochMilliseconds / 1_000); |
| 589 | const proof = yield* signRelayJwt({ |
| 590 | privateKey: keyPair.privateKey, |
| 591 | typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP, |
| 592 | payload: { |
| 593 | iss: "t3-env:environment-1", |
| 594 | aud: "https://relay.example.test", |
| 595 | sub: "environment-1", |
| 596 | jti: "recovery-proof", |
| 597 | iat: issuedAt, |
| 598 | exp: issuedAt + 60, |
| 599 | action: "recover", |
| 600 | environmentId: "environment-1", |
| 601 | cloudUserId: "user-1", |
| 602 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 603 | }, |
| 604 | }); |
| 605 | const request = { |
| 606 | action: "recover" as const, |
| 607 | proof, |
| 608 | userId: "user-1", |
| 609 | environmentId: "environment-1", |
| 610 | environmentPublicKey: keyPair.publicKey, |
| 611 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 612 | }; |
| 613 | |
| 614 | yield* verifyEnvironmentTunnelRecoveryProof(request); |
| 615 | |
| 616 | const wrongOwner = yield* Effect.flip( |
| 617 | verifyEnvironmentTunnelRecoveryProof({ ...request, userId: "user-2" }), |
| 618 | ); |
| 619 | expect(wrongOwner).toMatchObject({ _tag: "Unauthorized" }); |
| 620 | |
| 621 | const wrongOrigin = yield* Effect.flip( |
| 622 | verifyEnvironmentTunnelRecoveryProof({ |
| 623 | ...request, |
| 624 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 5432 }, |
| 625 | }), |
| 626 | ); |
| 627 | expect(wrongOrigin).toMatchObject({ _tag: "Unauthorized" }); |
| 628 | |
| 629 | const wrongAction = yield* Effect.flip( |
| 630 | verifyEnvironmentTunnelRecoveryProof({ |
| 631 | action: "register", |
| 632 | proof, |
| 633 | userId: "user-1", |
| 634 | environmentId: "environment-1", |
| 635 | environmentPublicKey: keyPair.publicKey, |
| 636 | tunnelId: "existing-tunnel", |
| 637 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 638 | }), |
| 639 | ); |
| 640 | expect(wrongAction).toMatchObject({ _tag: "Unauthorized" }); |
| 641 | }).pipe( |
| 642 | Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings), |
| 643 | Effect.provide(NodeCryptoLayer.layerSignature), |
| 644 | ), |
| 645 | ); |
| 646 | |
| 647 | it.effect("rejects a signed registration proof for a different origin", () => |
| 648 | Effect.gen(function* () { |
| 649 | const keyPair = NodeCrypto.generateKeyPairSync("ed25519", { |
| 650 | privateKeyEncoding: { format: "pem", type: "pkcs8" }, |
| 651 | publicKeyEncoding: { format: "pem", type: "spki" }, |
| 652 | }); |
| 653 | const now = yield* DateTime.now; |
| 654 | const issuedAt = Math.floor(now.epochMilliseconds / 1_000); |
| 655 | const proof = yield* signRelayJwt({ |
| 656 | privateKey: keyPair.privateKey, |
| 657 | typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP, |
| 658 | payload: { |
| 659 | iss: "t3-env:environment-1", |
| 660 | aud: "https://relay.example.test", |
| 661 | sub: "environment-1", |
| 662 | jti: "registration-origin-proof", |
| 663 | iat: issuedAt, |
| 664 | exp: issuedAt + 60, |
| 665 | action: "register", |
| 666 | environmentId: "environment-1", |
| 667 | cloudUserId: "user-1", |
| 668 | tunnelId: "existing-tunnel", |
| 669 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 670 | }, |
| 671 | }); |
| 672 | |
| 673 | const error = yield* Effect.flip( |
| 674 | verifyEnvironmentTunnelRecoveryProof({ |
| 675 | action: "register", |
| 676 | proof, |
| 677 | userId: "user-1", |
| 678 | environmentId: "environment-1", |
| 679 | environmentPublicKey: keyPair.publicKey, |
| 680 | tunnelId: "existing-tunnel", |
| 681 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 5432 }, |
| 682 | }), |
| 683 | ); |
| 684 | |
| 685 | expect(error).toMatchObject({ _tag: "Unauthorized" }); |
| 686 | }).pipe( |
| 687 | Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings), |
| 688 | Effect.provide(NodeCryptoLayer.layerSignature), |
| 689 | ), |
| 690 | ); |
| 691 | |
| 692 | it.effect("registers recovery for an existing tunnel without provisioning it", () => { |
| 693 | let recoveryEnabledFor: { |
| 694 | readonly userId: string; |
| 695 | readonly environmentId: string; |
| 696 | readonly tunnelId: string; |
| 697 | readonly environmentPublicKey: string; |
| 698 | readonly origin: { readonly localHttpHost: string; readonly localHttpPort: number }; |
| 699 | } | null = null; |
| 700 | |
| 701 | return Effect.gen(function* () { |
| 702 | expect( |
| 703 | yield* registerEnvironmentTunnelRecovery({ |
| 704 | userId: "user-1", |
| 705 | environmentId: "environment-1", |
| 706 | environmentPublicKey: "public-key", |
| 707 | tunnelId: "existing-tunnel", |
| 708 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 709 | }), |
| 710 | ).toEqual({ status: "ready" }); |
| 711 | expect(recoveryEnabledFor).toEqual({ |
| 712 | userId: "user-1", |
| 713 | environmentId: "environment-1", |
| 714 | tunnelId: "existing-tunnel", |
| 715 | environmentPublicKey: "public-key", |
| 716 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 717 | }); |
| 718 | }).pipe( |
| 719 | Effect.provide( |
| 720 | Layer.merge( |
| 721 | layerRelayUnlinkTest({ |
| 722 | getForUser: () => Effect.succeed(linkedEnvironmentRecord), |
| 723 | provision: () => Effect.die("registration must not provision a tunnel"), |
| 724 | }), |
| 725 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations)({ |
| 726 | enableRecovery: (input) => |
| 727 | Effect.sync(() => { |
| 728 | recoveryEnabledFor = input; |
| 729 | return true; |
| 730 | }), |
| 731 | }), |
| 732 | ), |
| 733 | ), |
| 734 | ); |
| 735 | }); |
| 736 | |
| 737 | it.effect("requests recovery without enabling a stale tunnel", () => { |
| 738 | let recoveryEnabled = false; |
| 739 | |
| 740 | return Effect.gen(function* () { |
| 741 | expect( |
| 742 | yield* registerEnvironmentTunnelRecovery({ |
| 743 | userId: "user-1", |
| 744 | environmentId: "environment-1", |
| 745 | environmentPublicKey: "public-key", |
| 746 | tunnelId: "deleted-tunnel", |
| 747 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 748 | }), |
| 749 | ).toEqual({ status: "recovery_required" }); |
| 750 | expect(recoveryEnabled).toBe(false); |
| 751 | }).pipe( |
| 752 | Effect.provide( |
| 753 | Layer.merge( |
| 754 | layerRelayUnlinkTest({ |
| 755 | getForUser: () => Effect.succeed(linkedEnvironmentRecord), |
| 756 | reconcileOrigin: () => Effect.succeed("recovery_required"), |
| 757 | }), |
| 758 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations)({ |
| 759 | enableRecovery: () => |
| 760 | Effect.sync(() => { |
| 761 | recoveryEnabled = true; |
| 762 | return true; |
| 763 | }), |
| 764 | }), |
| 765 | ), |
| 766 | ), |
| 767 | ); |
| 768 | }); |
| 769 | |
| 770 | it.effect("rejects recovery registration for a different environment key", () => { |
| 771 | let recoveryEnabled = false; |
| 772 | |
| 773 | return Effect.gen(function* () { |
| 774 | const error = yield* Effect.flip( |
| 775 | registerEnvironmentTunnelRecovery({ |
| 776 | userId: "user-1", |
| 777 | environmentId: "environment-1", |
| 778 | environmentPublicKey: "different-public-key", |
| 779 | tunnelId: "existing-tunnel", |
| 780 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 781 | }), |
| 782 | ); |
| 783 | |
| 784 | expect(error).toMatchObject({ _tag: "Unauthorized" }); |
| 785 | expect(recoveryEnabled).toBe(false); |
| 786 | }).pipe( |
| 787 | Effect.provide( |
| 788 | Layer.merge( |
| 789 | layerRelayUnlinkTest({ |
| 790 | getForUser: () => Effect.succeed(linkedEnvironmentRecord), |
| 791 | }), |
| 792 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations)({ |
| 793 | enableRecovery: () => |
| 794 | Effect.sync(() => { |
| 795 | recoveryEnabled = true; |
| 796 | return true; |
| 797 | }), |
| 798 | }), |
| 799 | ), |
| 800 | ), |
| 801 | ); |
| 802 | }); |
| 803 | |
| 804 | it.effect("rejects recovery registration when the recorded tunnel changed", () => |
| 805 | Effect.gen(function* () { |
| 806 | const error = yield* Effect.flip( |
| 807 | registerEnvironmentTunnelRecovery({ |
| 808 | userId: "user-1", |
| 809 | environmentId: "environment-1", |
| 810 | environmentPublicKey: "public-key", |
| 811 | tunnelId: "stale-tunnel", |
| 812 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 813 | }), |
| 814 | ); |
| 815 | |
| 816 | expect(error).toMatchObject({ _tag: "Unauthorized" }); |
| 817 | }).pipe( |
| 818 | Effect.provide( |
| 819 | Layer.merge( |
| 820 | layerRelayUnlinkTest({ |
| 821 | getForUser: () => Effect.succeed(linkedEnvironmentRecord), |
| 822 | }), |
| 823 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations)({ |
| 824 | enableRecovery: () => Effect.succeed(false), |
| 825 | }), |
| 826 | ), |
| 827 | ), |
| 828 | ), |
| 829 | ); |
| 830 | |
| 831 | it.effect("recovers a linked environment and marks its tunnel as recoverable", () => { |
| 832 | let recoveryEnabledFor: { |
| 833 | readonly userId: string; |
| 834 | readonly environmentId: string; |
| 835 | readonly tunnelId: string; |
| 836 | readonly environmentPublicKey: string; |
| 837 | } | null = null; |
| 838 | const runtime = { |
| 839 | providerKind: "cloudflare_tunnel" as const, |
| 840 | connectorToken: "replacement-token", |
| 841 | tunnelId: "replacement-tunnel", |
| 842 | }; |
| 843 | |
| 844 | return Effect.gen(function* () { |
| 845 | expect( |
| 846 | yield* recoverEnvironmentTunnelRecord({ |
| 847 | userId: "user-1", |
| 848 | environmentId: "environment-1", |
| 849 | environmentPublicKey: "public-key", |
| 850 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 851 | }), |
| 852 | ).toEqual({ |
| 853 | endpoint: linkedEnvironmentRecord.endpoint, |
| 854 | endpointRuntime: runtime, |
| 855 | }); |
| 856 | expect(recoveryEnabledFor).toEqual({ |
| 857 | userId: "user-1", |
| 858 | environmentId: "environment-1", |
| 859 | tunnelId: "replacement-tunnel", |
| 860 | environmentPublicKey: "public-key", |
| 861 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 862 | }); |
| 863 | }).pipe( |
| 864 | Effect.provide( |
| 865 | Layer.merge( |
| 866 | layerRelayUnlinkTest({ |
| 867 | getForUser: () => Effect.succeed(linkedEnvironmentRecord), |
| 868 | provision: () => |
| 869 | Effect.succeed({ |
| 870 | endpoint: linkedEnvironmentRecord.endpoint, |
| 871 | runtime, |
| 872 | }), |
| 873 | }), |
| 874 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations)({ |
| 875 | enableRecovery: (input) => |
| 876 | Effect.sync(() => { |
| 877 | recoveryEnabledFor = input; |
| 878 | return true; |
| 879 | }), |
| 880 | }), |
| 881 | ), |
| 882 | ), |
| 883 | ); |
| 884 | }); |
| 885 | |
| 886 | it.effect("rejects a credential from a different environment owner", () => { |
| 887 | let provisioned = false; |
| 888 | |
| 889 | return Effect.gen(function* () { |
| 890 | const error = yield* Effect.flip( |
| 891 | recoverEnvironmentTunnelRecord({ |
| 892 | userId: "user-1", |
| 893 | environmentId: "environment-1", |
| 894 | environmentPublicKey: "different-public-key", |
| 895 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 896 | }), |
| 897 | ); |
| 898 | expect(error).toMatchObject({ _tag: "Unauthorized" }); |
| 899 | expect(provisioned).toBe(false); |
| 900 | }).pipe( |
| 901 | Effect.provide( |
| 902 | Layer.merge( |
| 903 | layerRelayUnlinkTest({ |
| 904 | getForUser: () => Effect.succeed(linkedEnvironmentRecord), |
| 905 | provision: () => |
| 906 | Effect.sync(() => { |
| 907 | provisioned = true; |
| 908 | return { |
| 909 | endpoint: linkedEnvironmentRecord.endpoint, |
| 910 | runtime: { providerKind: "cloudflare_tunnel", connectorToken: "token" }, |
| 911 | }; |
| 912 | }), |
| 913 | }), |
| 914 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations)({ |
| 915 | enableRecovery: () => Effect.die("unused"), |
| 916 | }), |
| 917 | ), |
| 918 | ), |
| 919 | ); |
| 920 | }); |
| 921 | |
| 922 | it.effect("does not recover a publish-only environment", () => |
| 923 | Effect.gen(function* () { |
| 924 | const error = yield* Effect.flip( |
| 925 | recoverEnvironmentTunnelRecord({ |
| 926 | userId: "user-1", |
| 927 | environmentId: "environment-1", |
| 928 | environmentPublicKey: "public-key", |
| 929 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 930 | }), |
| 931 | ); |
| 932 | expect(error).toMatchObject({ _tag: "Unauthorized" }); |
| 933 | }).pipe( |
| 934 | Effect.provide( |
| 935 | Layer.merge( |
| 936 | layerRelayUnlinkTest({ |
| 937 | getForUser: () => |
| 938 | Effect.succeed({ |
| 939 | ...linkedEnvironmentRecord, |
| 940 | endpoint: { |
| 941 | ...linkedEnvironmentRecord.endpoint, |
| 942 | providerKind: "manual" as const, |
| 943 | }, |
| 944 | }), |
| 945 | }), |
| 946 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations)({ |
| 947 | enableRecovery: () => Effect.die("unused"), |
| 948 | }), |
| 949 | ), |
| 950 | ), |
| 951 | ), |
| 952 | ); |
| 953 | |
| 954 | it.effect("rejects a recovered tunnel that changes the linked endpoint", () => { |
| 955 | let recoveryEnabled = false; |
| 956 | const cleaned: Array<string> = []; |
| 957 | |
| 958 | return Effect.gen(function* () { |
| 959 | const error = yield* Effect.flip( |
| 960 | recoverEnvironmentTunnelRecord({ |
| 961 | userId: "user-1", |
| 962 | environmentId: "environment-1", |
| 963 | environmentPublicKey: "public-key", |
| 964 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 965 | }), |
| 966 | ); |
| 967 | expect(error).toMatchObject({ _tag: "Unauthorized" }); |
| 968 | expect(recoveryEnabled).toBe(false); |
| 969 | expect(cleaned).toEqual(["replacement-tunnel"]); |
| 970 | }).pipe( |
| 971 | Effect.provide( |
| 972 | Layer.merge( |
| 973 | layerRelayUnlinkTest({ |
| 974 | getForUser: () => Effect.succeed(linkedEnvironmentRecord), |
| 975 | provision: () => |
| 976 | Effect.succeed({ |
| 977 | endpoint: { |
| 978 | httpBaseUrl: "https://different.example.test/", |
| 979 | wsBaseUrl: "wss://different.example.test/ws", |
| 980 | providerKind: "cloudflare_tunnel", |
| 981 | }, |
| 982 | runtime: { |
| 983 | providerKind: "cloudflare_tunnel", |
| 984 | connectorToken: "token", |
| 985 | tunnelId: "replacement-tunnel", |
| 986 | }, |
| 987 | }), |
| 988 | prepareDeprovision: () => Effect.die("must keep the active allocation"), |
| 989 | deprovision: () => Effect.die("must keep the active link DNS"), |
| 990 | release: ({ expectedTunnelId }) => |
| 991 | Effect.sync(() => { |
| 992 | if (expectedTunnelId) { |
| 993 | cleaned.push(expectedTunnelId); |
| 994 | } |
| 995 | return true; |
| 996 | }), |
| 997 | }), |
| 998 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations)({ |
| 999 | enableRecovery: () => |
| 1000 | Effect.sync(() => { |
| 1001 | recoveryEnabled = true; |
| 1002 | return true; |
| 1003 | }), |
| 1004 | }), |
| 1005 | ), |
| 1006 | ), |
| 1007 | ); |
| 1008 | }); |
| 1009 | |
| 1010 | it.effect.each([ |
| 1011 | { state: "removed", currentLink: null }, |
| 1012 | { |
| 1013 | state: "publish-only", |
| 1014 | currentLink: { |
| 1015 | ...linkedEnvironmentRecord, |
| 1016 | endpoint: { |
| 1017 | ...linkedEnvironmentRecord.endpoint, |
| 1018 | providerKind: "manual" as const, |
| 1019 | }, |
| 1020 | }, |
| 1021 | }, |
| 1022 | ])("removes a recovered tunnel when its link becomes $state", ({ currentLink }) => { |
| 1023 | let lookups = 0; |
| 1024 | const cleaned: Array<string> = []; |
| 1025 | const target = { |
| 1026 | userId: "user-1", |
| 1027 | environmentId: "environment-1", |
| 1028 | hostname: "environment-1.example.test", |
| 1029 | tunnelId: "replacement-tunnel", |
| 1030 | tunnelName: "environment-1-tunnel", |
| 1031 | dnsRecordId: "dns-1", |
| 1032 | readyAt: "2026-07-28T00:00:00.000Z", |
| 1033 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 1034 | updatedAt: "replacement-generation", |
| 1035 | generation: 3, |
| 1036 | tunnelReleasedAt: null, |
| 1037 | } satisfies ManagedEndpointProvider.ManagedEndpointDeprovisionTarget; |
| 1038 | |
| 1039 | return Effect.gen(function* () { |
| 1040 | const error = yield* Effect.flip( |
| 1041 | recoverEnvironmentTunnelRecord({ |
| 1042 | userId: "user-1", |
| 1043 | environmentId: "environment-1", |
| 1044 | environmentPublicKey: "public-key", |
| 1045 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 1046 | }), |
| 1047 | ); |
| 1048 | expect(error).toMatchObject({ _tag: "Unauthorized" }); |
| 1049 | expect(cleaned).toEqual(["replacement-tunnel"]); |
| 1050 | }).pipe( |
| 1051 | Effect.provide( |
| 1052 | Layer.merge( |
| 1053 | layerRelayUnlinkTest({ |
| 1054 | getForUser: () => |
| 1055 | Effect.sync(() => (++lookups === 1 ? linkedEnvironmentRecord : currentLink)), |
| 1056 | provision: () => |
| 1057 | Effect.succeed({ |
| 1058 | endpoint: linkedEnvironmentRecord.endpoint, |
| 1059 | runtime: { |
| 1060 | providerKind: "cloudflare_tunnel", |
| 1061 | connectorToken: "replacement-token", |
| 1062 | tunnelId: "replacement-tunnel", |
| 1063 | }, |
| 1064 | }), |
| 1065 | prepareDeprovision: () => Effect.succeed(target), |
| 1066 | deprovision: ({ target: captured }) => |
| 1067 | Effect.sync(() => { |
| 1068 | if (captured?.tunnelId) { |
| 1069 | cleaned.push(captured.tunnelId); |
| 1070 | } |
| 1071 | return true; |
| 1072 | }), |
| 1073 | }), |
| 1074 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations)({ |
| 1075 | enableRecovery: () => Effect.succeed(false), |
| 1076 | }), |
| 1077 | ), |
| 1078 | ), |
| 1079 | ); |
| 1080 | }); |
| 1081 | }); |
| 1082 | |
| 1083 | describe("relay environment unlink", () => { |
| 1084 | it.effect( |
| 1085 | "drops the unlinked endpoint's held webhooks, even if clearing or teardown fails", |
| 1086 | () => { |
| 1087 | const cleared: Array<string> = []; |
| 1088 | const endpointKey = "0123456789abcdef"; |
| 1089 | const unlink = (clearFails: boolean, teardownFails = false) => |
| 1090 | unlinkEnvironmentRecord({ |
| 1091 | userId: "user-1", |
| 1092 | environmentId: "environment-1", |
| 1093 | managedEndpointNamespace: "dev", |
| 1094 | }).pipe( |
| 1095 | Effect.provide( |
| 1096 | layerRelayUnlinkTest({ |
| 1097 | getForUser: () => Effect.succeed(linkedEnvironmentRecord), |
| 1098 | revokeForUser: () => Effect.succeed(true), |
| 1099 | prepareDeprovision: () => |
| 1100 | Effect.succeed({ |
| 1101 | userId: "user-1", |
| 1102 | environmentId: "environment-1", |
| 1103 | hostname: "dev-0123456789abcdef.example.test", |
| 1104 | tunnelId: "tunnel-1", |
| 1105 | tunnelName: `t3coderelay-managedendpoint-dev-${endpointKey}`, |
| 1106 | dnsRecordId: "dns-1", |
| 1107 | readyAt: "2026-07-28T00:00:00.000Z", |
| 1108 | tunnelReleasedAt: null, |
| 1109 | origin: null, |
| 1110 | updatedAt: "2026-07-28T00:00:00.000Z", |
| 1111 | generation: 1, |
| 1112 | }), |
| 1113 | clearInbox: (input) => |
| 1114 | clearFails |
| 1115 | ? Effect.fail( |
| 1116 | new HookInbox.HookInboxError({ |
| 1117 | operation: "clear", |
| 1118 | endpointKey: input.endpointKey, |
| 1119 | cause: new Error("unavailable"), |
| 1120 | }), |
| 1121 | ) |
| 1122 | : Effect.sync(() => void cleared.push(input.endpointKey)), |
| 1123 | ...(teardownFails |
| 1124 | ? { |
| 1125 | deprovision: (input) => |
| 1126 | Effect.fail( |
| 1127 | new ManagedEndpointProvider.ManagedEndpointDeprovisioningFailed({ |
| 1128 | userId: input.userId, |
| 1129 | environmentId: input.environmentId, |
| 1130 | stage: "delete-tunnel", |
| 1131 | cause: new Error("unavailable"), |
| 1132 | }), |
| 1133 | ), |
| 1134 | } |
| 1135 | : {}), |
| 1136 | }), |
| 1137 | ), |
| 1138 | ); |
| 1139 | return Effect.gen(function* () { |
| 1140 | expect(yield* unlink(false)).toBe(true); |
| 1141 | expect(cleared).toEqual([endpointKey]); |
| 1142 | expect(yield* unlink(true)).toBe(true); |
| 1143 | // A later link under another key shares the inbox, so it is emptied before teardown can fail. |
| 1144 | yield* unlink(false, true).pipe(Effect.flip); |
| 1145 | expect(cleared).toEqual([endpointKey, endpointKey]); |
| 1146 | }); |
| 1147 | }, |
| 1148 | ); |
| 1149 | |
| 1150 | it.effect("commits database revocation before deprovisioning the managed endpoint", () => { |
| 1151 | const calls: Array<string> = []; |
| 1152 | const deprovisionTarget = { |
| 1153 | userId: "user-1", |
| 1154 | environmentId: "environment-1", |
| 1155 | hostname: "environment-1.example.test", |
| 1156 | tunnelId: "tunnel-1", |
| 1157 | tunnelName: "environment-1-tunnel", |
| 1158 | dnsRecordId: "dns-1", |
| 1159 | readyAt: "2026-07-28T00:00:00.000Z", |
| 1160 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 1161 | updatedAt: "generation-before-unlink", |
| 1162 | generation: 1, |
| 1163 | tunnelReleasedAt: null, |
| 1164 | } satisfies ManagedEndpointProvider.ManagedEndpointDeprovisionTarget; |
| 1165 | |
| 1166 | return Effect.gen(function* () { |
| 1167 | expect( |
| 1168 | yield* unlinkEnvironmentRecord({ |
| 1169 | userId: "user-1", |
| 1170 | environmentId: "environment-1", |
| 1171 | }), |
| 1172 | ).toBe(true); |
| 1173 | expect(calls).toEqual([ |
| 1174 | "prepare", |
| 1175 | "lookup", |
| 1176 | "transaction", |
| 1177 | "link", |
| 1178 | "credential", |
| 1179 | "deprovision", |
| 1180 | ]); |
| 1181 | }).pipe( |
| 1182 | Effect.provide( |
| 1183 | layerRelayUnlinkTest({ |
| 1184 | withTransaction: (effect) => { |
| 1185 | calls.push("transaction"); |
| 1186 | return effect; |
| 1187 | }, |
| 1188 | getForUser: () => |
| 1189 | Effect.sync(() => { |
| 1190 | calls.push("lookup"); |
| 1191 | return linkedEnvironmentRecord; |
| 1192 | }), |
| 1193 | revokeForUser: () => |
| 1194 | Effect.sync(() => { |
| 1195 | calls.push("link"); |
| 1196 | return true; |
| 1197 | }), |
| 1198 | revokeCredential: () => |
| 1199 | Effect.sync(() => { |
| 1200 | calls.push("credential"); |
| 1201 | return true; |
| 1202 | }), |
| 1203 | prepareDeprovision: () => |
| 1204 | Effect.sync(() => { |
| 1205 | calls.push("prepare"); |
| 1206 | return deprovisionTarget; |
| 1207 | }), |
| 1208 | deprovision: (request) => |
| 1209 | Effect.sync(() => { |
| 1210 | expect(request.target).toBe(deprovisionTarget); |
| 1211 | calls.push("deprovision"); |
| 1212 | return true; |
| 1213 | }), |
| 1214 | }), |
| 1215 | ), |
| 1216 | ); |
| 1217 | }); |
| 1218 | |
| 1219 | it.effect("does not deprovision when database revocation fails", () => { |
| 1220 | const calls: Array<string> = []; |
| 1221 | const failure = new EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError({ |
| 1222 | environmentId: "environment-1", |
| 1223 | cause: "database unavailable", |
| 1224 | }); |
| 1225 | |
| 1226 | return Effect.gen(function* () { |
| 1227 | expect( |
| 1228 | yield* Effect.flip( |
| 1229 | unlinkEnvironmentRecord({ |
| 1230 | userId: "user-1", |
| 1231 | environmentId: "environment-1", |
| 1232 | }), |
| 1233 | ), |
| 1234 | ).toBe(failure); |
| 1235 | expect(calls).toEqual(["prepare", "transaction", "link", "credential"]); |
| 1236 | }).pipe( |
| 1237 | Effect.provide( |
| 1238 | layerRelayUnlinkTest({ |
| 1239 | withTransaction: (effect) => { |
| 1240 | calls.push("transaction"); |
| 1241 | return effect; |
| 1242 | }, |
| 1243 | getForUser: () => Effect.succeed(linkedEnvironmentRecord), |
| 1244 | revokeForUser: () => |
| 1245 | Effect.sync(() => { |
| 1246 | calls.push("link"); |
| 1247 | return true; |
| 1248 | }), |
| 1249 | revokeCredential: () => |
| 1250 | Effect.sync(() => { |
| 1251 | calls.push("credential"); |
| 1252 | }).pipe(Effect.andThen(Effect.fail(failure))), |
| 1253 | prepareDeprovision: () => |
| 1254 | Effect.sync(() => { |
| 1255 | calls.push("prepare"); |
| 1256 | return null; |
| 1257 | }), |
| 1258 | deprovision: () => |
| 1259 | Effect.sync(() => { |
| 1260 | calls.push("deprovision"); |
| 1261 | return true; |
| 1262 | }), |
| 1263 | }), |
| 1264 | ), |
| 1265 | ); |
| 1266 | }); |
| 1267 | |
| 1268 | it.effect("retries deprovisioning after the link is already revoked", () => { |
| 1269 | const calls: Array<string> = []; |
| 1270 | return Effect.gen(function* () { |
| 1271 | expect( |
| 1272 | yield* unlinkEnvironmentRecord({ |
| 1273 | userId: "user-1", |
| 1274 | environmentId: "environment-1", |
| 1275 | }), |
| 1276 | ).toBe(false); |
| 1277 | expect(calls).toEqual(["prepare", "deprovision"]); |
| 1278 | }).pipe( |
| 1279 | Effect.provide( |
| 1280 | layerRelayUnlinkTest({ |
| 1281 | prepareDeprovision: () => |
| 1282 | Effect.sync(() => { |
| 1283 | calls.push("prepare"); |
| 1284 | return null; |
| 1285 | }), |
| 1286 | deprovision: () => |
| 1287 | Effect.sync(() => { |
| 1288 | calls.push("deprovision"); |
| 1289 | return true; |
| 1290 | }), |
| 1291 | }), |
| 1292 | ), |
| 1293 | ); |
| 1294 | }); |
| 1295 | |
| 1296 | it.effect("retries unlink cleanup when a concurrent tunnel release wins the first claim", () => { |
| 1297 | let lookups = 0; |
| 1298 | const targets: Array<ManagedEndpointProvider.ManagedEndpointDeprovisionTarget | undefined> = []; |
| 1299 | const target = { |
| 1300 | userId: "user-1", |
| 1301 | environmentId: "environment-1", |
| 1302 | hostname: "environment-1.example.test", |
| 1303 | tunnelId: "tunnel-1", |
| 1304 | tunnelName: "environment-1-tunnel", |
| 1305 | dnsRecordId: "dns-1", |
| 1306 | readyAt: "2026-07-28T00:00:00.000Z", |
| 1307 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 1308 | updatedAt: "original-generation", |
| 1309 | generation: 1, |
| 1310 | tunnelReleasedAt: null, |
| 1311 | } satisfies ManagedEndpointProvider.ManagedEndpointDeprovisionTarget; |
| 1312 | |
| 1313 | return Effect.gen(function* () { |
| 1314 | expect( |
| 1315 | yield* unlinkEnvironmentRecord({ |
| 1316 | userId: "user-1", |
| 1317 | environmentId: "environment-1", |
| 1318 | }), |
| 1319 | ).toBe(true); |
| 1320 | expect(targets).toEqual([target, target]); |
| 1321 | }).pipe( |
| 1322 | Effect.provide( |
| 1323 | layerRelayUnlinkTest({ |
| 1324 | getForUser: () => Effect.sync(() => (++lookups === 1 ? linkedEnvironmentRecord : null)), |
| 1325 | revokeForUser: () => Effect.succeed(true), |
| 1326 | prepareDeprovision: () => Effect.succeed(target), |
| 1327 | deprovision: ({ target: captured }) => |
| 1328 | Effect.sync(() => { |
| 1329 | targets.push(captured ?? undefined); |
| 1330 | return targets.length > 1; |
| 1331 | }), |
| 1332 | }), |
| 1333 | ), |
| 1334 | ); |
| 1335 | }); |
| 1336 | }); |
| 1337 | |
| 1338 | describe("relay request tracing", () => { |
| 1339 | it.effect( |
| 1340 | "does not parent endpoint spans to an ambient parent captured while building handlers", |
| 1341 | () => |
| 1342 | Effect.gen(function* () { |
| 1343 | const spans: Array<Tracer.NativeSpan> = []; |
| 1344 | const tracer = Tracer.make({ |
| 1345 | span: (options) => { |
| 1346 | const span = new Tracer.NativeSpan(options); |
| 1347 | spans.push(span); |
| 1348 | return span; |
| 1349 | }, |
| 1350 | }); |
| 1351 | const ambientParent = Tracer.externalSpan({ |
| 1352 | traceId: "00000000000000000000000000000001", |
| 1353 | spanId: "0000000000000001", |
| 1354 | sampled: true, |
| 1355 | }); |
| 1356 | const endpoint = yield* withoutCapturedParentSpan( |
| 1357 | Effect.context<never>().pipe( |
| 1358 | Effect.map((capturedContext: Context.Context<never>) => |
| 1359 | Effect.succeed(HttpServerResponse.empty({ status: 204 })).pipe( |
| 1360 | Effect.withSpan("relay.test.endpoint"), |
| 1361 | Effect.provideContext(capturedContext), |
| 1362 | ), |
| 1363 | ), |
| 1364 | ), |
| 1365 | ).pipe(Effect.provideService(Tracer.ParentSpan, ambientParent)); |
| 1366 | const request = HttpServerRequest.fromWeb( |
| 1367 | new Request("https://relay.test/v1/mobile/devices?client=mobile", { |
| 1368 | method: "POST", |
| 1369 | headers: { |
| 1370 | authorization: "Bearer secret", |
| 1371 | dpop: "signed-proof", |
| 1372 | }, |
| 1373 | }), |
| 1374 | ); |
| 1375 | |
| 1376 | yield* traceRelayHttpRequestWith(endpoint, Layer.succeed(Tracer.Tracer, tracer)).pipe( |
| 1377 | Effect.provideService(HttpServerRequest.HttpServerRequest, request), |
| 1378 | ); |
| 1379 | |
| 1380 | expect(spans.map((span) => span.name)).toEqual(["POST", "relay.test.endpoint"]); |
| 1381 | expect(spans[0]?.kind).toBe("server"); |
| 1382 | expect(spans[0]?.attributes.get("url.path")).toBe("/v1/mobile/devices"); |
| 1383 | expect(spans[0]?.attributes.get("http.response.status_code")).toBe(204); |
| 1384 | expect(spans[0]?.attributes.get("http.request.header.authorization")).toBeUndefined(); |
| 1385 | expect(spans[0]?.attributes.get("http.request.header.dpop")).toBeUndefined(); |
| 1386 | expect(Option.isNone(spans[0]!.parent)).toBe(true); |
| 1387 | expect(Option.getOrUndefined(spans[1]!.parent)?.spanId).toBe(spans[0]?.spanId); |
| 1388 | }), |
| 1389 | ); |
| 1390 | }); |
| 1391 | |
| 1392 | describe("relay routing fallback", () => { |
| 1393 | it.effect("publishes activity for escaped delegated thread IDs longer than 100 characters", () => |
| 1394 | Effect.gen(function* () { |
| 1395 | const environmentId = "environment-1"; |
| 1396 | const environmentPublicKey = "environment-public-key"; |
| 1397 | const published: Array< |
| 1398 | Parameters<AgentActivityPublisher.AgentActivityPublisher["Service"]["publish"]>[0] |
| 1399 | > = []; |
| 1400 | const verified: Array< |
| 1401 | Parameters< |
| 1402 | EnvironmentPublishSignatures.EnvironmentPublishSignatures["Service"]["verify"] |
| 1403 | >[0] |
| 1404 | > = []; |
| 1405 | const layerPublisher = Layer.succeed(AgentActivityPublisher.AgentActivityPublisher, { |
| 1406 | publish: (input) => |
| 1407 | Effect.sync(() => { |
| 1408 | published.push(input); |
| 1409 | return { ok: true as const, deliveries: [] }; |
| 1410 | }), |
| 1411 | replayForLiveActivityRegistration: () => Effect.succeed(null), |
| 1412 | endIdleLiveActivities: Effect.void, |
| 1413 | }); |
| 1414 | const layerSignatures = Layer.succeed( |
| 1415 | EnvironmentPublishSignatures.EnvironmentPublishSignatures, |
| 1416 | { |
| 1417 | verify: (input) => |
| 1418 | Effect.sync(() => { |
| 1419 | verified.push(input); |
| 1420 | }), |
| 1421 | }, |
| 1422 | ); |
| 1423 | const layerAuth = Layer.succeed(RelayEnvironmentAuth, { |
| 1424 | environmentBearer: (effect) => |
| 1425 | effect.pipe( |
| 1426 | Effect.provideService(RelayEnvironmentPrincipal, { |
| 1427 | environmentId, |
| 1428 | environmentPublicKey, |
| 1429 | }), |
| 1430 | ), |
| 1431 | }); |
| 1432 | const layerRoutes = HttpApiBuilder.layer( |
| 1433 | HttpApi.make("RelayApi").add(RelayApi.groups.server), |
| 1434 | ).pipe( |
| 1435 | Layer.provide( |
| 1436 | RelayHttpApi.layerServerApi.pipe( |
| 1437 | HttpRouter.provideRequest( |
| 1438 | Layer.mergeAll( |
| 1439 | Layer.succeed(RelayConfiguration.RelayConfiguration, relaySettings), |
| 1440 | Layer.mock(EnvironmentLinks.EnvironmentLinks, {}), |
| 1441 | Layer.mock(ManagedEndpointAllocations.ManagedEndpointAllocations, {}), |
| 1442 | Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}), |
| 1443 | ), |
| 1444 | ), |
| 1445 | Layer.provide([layerPublisher, layerSignatures, Layer.mock(HeldHooks.HeldHooks, {})]), |
| 1446 | ), |
| 1447 | ), |
| 1448 | Layer.provide(layerAuth), |
| 1449 | Layer.provide([NodeServices.layer, NodeHttpPlatform.layer, Etag.layerWeak]), |
| 1450 | ); |
| 1451 | const httpEffect = yield* HttpRouter.toHttpEffect( |
| 1452 | Layer.mergeAll(layerRoutes, RelayHttpApi.layerNotFoundRoute, RelayHttpApi.layerCors), |
| 1453 | ).pipe(Effect.provideService(HttpRouter.RouterConfig, RELAY_HTTP_ROUTER_CONFIG)); |
| 1454 | const threadIds = [ |
| 1455 | "b7c8c522-d244-43dc-875f-7224fce79912", |
| 1456 | "t".repeat(512), |
| 1457 | "thread:delegated-task:command%3Amcp%3Ab7c8c522-d244-43dc-875f-7224fce79912%3Adelegate-task%3Agreet-subagent-20260813", |
| 1458 | ]; |
| 1459 | for (const threadId of threadIds) { |
| 1460 | const request = HttpServerRequest.fromWeb( |
| 1461 | new Request( |
| 1462 | `https://relay.test/v1/environments/${environmentId}/threads/${encodeURIComponent(threadId)}/agent-activity`, |
| 1463 | { |
| 1464 | method: "POST", |
| 1465 | headers: { |
| 1466 | authorization: "Bearer environment-credential", |
| 1467 | "content-type": "application/json", |
| 1468 | }, |
| 1469 | body: '{"state":null,"proof":"signed-proof"}', |
| 1470 | }, |
| 1471 | ), |
| 1472 | ); |
| 1473 | const response = yield* httpEffect.pipe( |
| 1474 | Effect.provideService(HttpServerRequest.HttpServerRequest, request), |
| 1475 | ); |
| 1476 | expect(response.status).toBe(200); |
| 1477 | } |
| 1478 | expect(published).toEqual( |
| 1479 | threadIds.map((threadId) => ({ |
| 1480 | environmentId, |
| 1481 | environmentPublicKey, |
| 1482 | threadId, |
| 1483 | state: null, |
| 1484 | })), |
| 1485 | ); |
| 1486 | expect(verified.map((input) => input.threadId)).toEqual(threadIds); |
| 1487 | }).pipe(Effect.scoped, Effect.provide(NodeCryptoLayer.layerSignature)), |
| 1488 | ); |
| 1489 | }); |
| 1490 | |
| 1491 | describe("relay CORS", () => { |
| 1492 | const origin = "https://app.t3.codes"; |
| 1493 | |
| 1494 | class HandlerFailed extends Schema.TaggedError<HandlerFailed>()("HandlerFailed", {}) {} |
| 1495 | |
| 1496 | it.effect("adds CORS headers to handler failures and defects", () => |
| 1497 | Effect.gen(function* () { |
| 1498 | const httpEffect = yield* HttpRouter.toHttpEffect( |
| 1499 | Layer.mergeAll( |
| 1500 | HttpRouter.add("GET", "/v1/fail", Effect.fail(new HandlerFailed())), |
| 1501 | HttpRouter.add("GET", "/v1/die", Effect.die(new Error("handler defect"))), |
| 1502 | RelayHttpApi.layerNotFoundRoute, |
| 1503 | RelayHttpApi.layerCors, |
| 1504 | ), |
| 1505 | ); |
| 1506 | for (const path of ["/v1/fail", "/v1/die"]) { |
| 1507 | const response = yield* sendRelayRequest( |
| 1508 | httpEffect, |
| 1509 | new Request(`https://relay.test${path}`, { headers: { origin } }), |
| 1510 | ); |
| 1511 | |
| 1512 | expect(response.status).toBe(500); |
| 1513 | expect(response.headers["access-control-allow-origin"]).toBe("*"); |
| 1514 | expect(response.headers["access-control-expose-headers"]).toBe( |
| 1515 | "traceparent,www-authenticate", |
| 1516 | ); |
| 1517 | } |
| 1518 | }).pipe(Effect.scoped), |
| 1519 | ); |
| 1520 | }); |
| 1521 | |
| 1522 | // Use the Workers request path so pre-response handlers apply. |
| 1523 | const sendRelayRequest = Effect.fnUntraced(function* <E, R>( |
| 1524 | httpEffect: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>, |
| 1525 | request: Request, |
| 1526 | ) { |
| 1527 | const sent = yield* Deferred.make<HttpServerResponse.HttpServerResponse>(); |
| 1528 | yield* HttpEffect.toHandled(httpEffect, (_request, response) => |
| 1529 | Deferred.succeed(sent, response), |
| 1530 | ).pipe( |
| 1531 | Effect.provideService(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)), |
| 1532 | Effect.exit, |
| 1533 | ); |
| 1534 | return yield* Deferred.await(sent); |
| 1535 | }); |