Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Api.test.ts

1,489 lines52.5 KB

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