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