The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,774 lines 62.9 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3
4 import { describe, expect, it } from "@effect/vitest";
5 import * as Alchemy from "alchemy";
6 import * as Cloudflare from "@alchemy.run/cloudflare";
7 import * as ZeroTrust from "@distilled.cloud/cloudflare/zero-trust";
8 import * as Deferred from "effect/Deferred";
9 import * as Effect from "effect/Effect";
10 import * as Fiber from "effect/Fiber";
11 import * as Layer from "effect/Layer";
12 import * as Redacted from "effect/Redacted";
13
14 import * as RelayConfiguration from "../Config.ts";
15 import * as CloudflareApiPause from "./CloudflareApiPause.ts";
16 import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
17 import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
18 import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";
19
20 const config = RelayConfiguration.RelayConfiguration.of({
21 relayIssuer: "https://relay.example.test",
22 apns: {
23 environment: "sandbox",
24 teamId: "team-id",
25 keyId: "key-id",
26 privateKey: Redacted.make("private-key"),
27 bundleId: "com.t3tools.t3code.dev",
28 },
29 apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),
30 clerkSecretKey: Redacted.make("clerk-secret"),
31 clerkPublishableKey: "pk_test_test",
32 clerkJwtAudience: "t3-code-relay",
33 cloudMintPrivateKey: Redacted.make("cloud-private-key"),
34 cloudMintPublicKey: "cloud-public-key",
35 managedEndpointBaseDomain: "t3code.test",
36 managedEndpointNamespace: "dev_julius",
37 });
38
39 interface TunnelCall {
40 readonly operation:
41 | "get"
42 | "list"
43 | "create"
44 | "putConfiguration"
45 | "getConfiguration"
46 | "getToken"
47 | "delete";
48 readonly input: unknown;
49 }
50
51 interface TunnelConfiguration {
52 readonly ingress: ReadonlyArray<{
53 readonly hostname?: string;
54 readonly path?: string;
55 readonly service: string;
56 }>;
57 }
58
59 interface DnsCall {
60 readonly operation: "listRecords" | "createRecord" | "updateRecord" | "deleteRecord";
61 readonly input: unknown;
62 }
63
64 interface AllocationCall {
65 readonly operation:
66 | "get"
67 | "reserve"
68 | "recordTunnel"
69 | "recordDns"
70 | "markReady"
71 | "claimRelease"
72 | "claimDeprovision"
73 | "removeClaimed";
74 readonly input: unknown;
75 }
76
77 function allocationKey(input: { readonly userId: string; readonly environmentId: string }) {
78 return `${input.userId}:${input.environmentId}`;
79 }
80
81 function makeTunnelClient(calls: TunnelCall[] = []) {
82 return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
83 get: (tunnelId) =>
84 Effect.sync(() => {
85 calls.push({ operation: "get", input: tunnelId });
86 return {
87 id: tunnelId,
88 name: "managed-tunnel",
89 status: "down",
90 connsInactiveAt: "2026-06-01T00:00:00.000Z",
91 };
92 }),
93 list: (request) =>
94 Effect.sync(() => {
95 calls.push({ operation: "list", input: request });
96 return { result: [] };
97 }),
98 create: (request) =>
99 Effect.sync(() => {
100 calls.push({ operation: "create", input: request });
101 return { id: "tunnel-id", name: request.name };
102 }),
103 putConfiguration: (tunnelId, tunnelConfig) =>
104 Effect.sync(() => {
105 calls.push({ operation: "putConfiguration", input: { tunnelId, tunnelConfig } });
106 }),
107 getConfiguration: (tunnelId) =>
108 Effect.sync(() => {
109 calls.push({ operation: "getConfiguration", input: tunnelId });
110 return { ingress: [] };
111 }),
112 getToken: (tunnelId) =>
113 Effect.sync(() => {
114 calls.push({ operation: "getToken", input: tunnelId });
115 return "connector-token";
116 }),
117 delete: (tunnelId) =>
118 Effect.sync(() => {
119 calls.push({ operation: "delete", input: tunnelId });
120 }),
121 });
122 }
123
124 function makePersistentTunnelClient(
125 calls: TunnelCall[] = [],
126 configuration: { current: TunnelConfiguration | null } = { current: null },
127 ) {
128 let tunnel: { readonly id: string; readonly name: string } | null = null;
129 return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
130 get: (tunnelId) =>
131 Effect.suspend(() => {
132 calls.push({ operation: "get", input: tunnelId });
133 return tunnel === null
134 ? Effect.fail(
135 new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
136 operation: "get",
137 tunnelId,
138 cause: { _tag: "NotFound" },
139 }),
140 )
141 : Effect.succeed({
142 ...tunnel,
143 status: "down",
144 connsInactiveAt: "2026-06-01T00:00:00.000Z",
145 });
146 }),
147 list: (request) =>
148 Effect.sync(() => {
149 calls.push({ operation: "list", input: request });
150 return { result: tunnel === null ? [] : [tunnel] };
151 }),
152 create: (request) =>
153 Effect.sync(() => {
154 calls.push({ operation: "create", input: request });
155 tunnel = { id: "tunnel-id", name: request.name };
156 return tunnel;
157 }),
158 putConfiguration: (tunnelId, tunnelConfig) =>
159 Effect.sync(() => {
160 calls.push({ operation: "putConfiguration", input: { tunnelId, tunnelConfig } });
161 configuration.current = tunnelConfig;
162 }),
163 getConfiguration: (tunnelId: string) =>
164 Effect.sync(() => {
165 calls.push({ operation: "getConfiguration", input: tunnelId });
166 return configuration.current ?? { ingress: [] };
167 }),
168 getToken: (tunnelId) =>
169 Effect.sync(() => {
170 calls.push({ operation: "getToken", input: tunnelId });
171 return "connector-token";
172 }),
173 delete: (tunnelId) =>
174 Effect.sync(() => {
175 calls.push({ operation: "delete", input: tunnelId });
176 tunnel = null;
177 }),
178 });
179 }
180
181 function makeDnsClient(
182 calls: DnsCall[] = [],
183 records: ReadonlyArray<{ readonly id: string }> = [],
184 ) {
185 let currentRecords = [...records];
186 return ManagedEndpointProvider.ManagedEndpointDnsClient.of({
187 listRecords: (hostname) =>
188 Effect.sync(() => {
189 calls.push({ operation: "listRecords", input: hostname });
190 return currentRecords;
191 }),
192 createRecord: (request) =>
193 Effect.sync(() => {
194 calls.push({ operation: "createRecord", input: request });
195 const record = { id: "created-record-id" };
196 currentRecords = [record];
197 return record;
198 }),
199 updateRecord: (dnsRecordId, request) =>
200 Effect.gen(function* () {
201 calls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
202 if (!currentRecords.some((record) => record.id === dnsRecordId)) {
203 return yield* new ManagedEndpointProvider.ManagedEndpointDnsClientError({
204 operation: "update-record",
205 hostname: request.name,
206 dnsRecordId,
207 cause: { _tag: "NotFound", dnsRecordId },
208 });
209 }
210 }),
211 deleteRecord: (dnsRecordId) =>
212 Effect.sync(() => {
213 calls.push({ operation: "deleteRecord", input: dnsRecordId });
214 currentRecords = currentRecords.filter((record) => record.id !== dnsRecordId);
215 }),
216 });
217 }
218
219 function makeAllocations(calls: AllocationCall[] = []) {
220 const allocations = new Map<string, ManagedEndpointAllocations.ManagedEndpointAllocation>();
221 const recoveryEnabled = new Set<string>();
222 let generation = 0;
223 const mutate = (
224 key: string,
225 change: (
226 allocation: ManagedEndpointAllocations.ManagedEndpointAllocation,
227 ) => ManagedEndpointAllocations.ManagedEndpointAllocation,
228 ) => {
229 const allocation = allocations.get(key);
230 if (allocation !== undefined) {
231 allocations.set(key, {
232 ...change(allocation),
233 generation: allocation.generation + 1,
234 updatedAt: `generation-${++generation}`,
235 });
236 }
237 };
238 return ManagedEndpointAllocations.ManagedEndpointAllocations.of({
239 getByTunnelName: () => Effect.die("unused getByTunnelName"),
240 get: (input) =>
241 Effect.sync(() => {
242 calls.push({ operation: "get", input });
243 return allocations.get(allocationKey(input)) ?? null;
244 }),
245 reserve: (input) =>
246 Effect.sync(() => {
247 calls.push({ operation: "reserve", input });
248 const allocation = allocations.get(allocationKey(input)) ?? {
249 ...input,
250 tunnelId: null,
251 dnsRecordId: null,
252 readyAt: null,
253 origin: null,
254 updatedAt: `generation-${++generation}`,
255 generation: 0,
256 tunnelReleasedAt: null,
257 };
258 allocations.set(allocationKey(input), allocation);
259 return allocation;
260 }),
261 recordTunnel: (input) =>
262 Effect.sync(() => {
263 calls.push({ operation: "recordTunnel", input });
264 const current = allocations.get(allocationKey(input));
265 if (current?.generation !== input.generation) {
266 return null;
267 }
268 mutate(allocationKey(input), (allocation) => ({
269 ...allocation,
270 tunnelId: input.tunnelId,
271 tunnelReleasedAt: null,
272 readyAt: allocation.tunnelId === input.tunnelId ? allocation.readyAt : null,
273 }));
274 return allocations.get(allocationKey(input))?.generation ?? null;
275 }),
276 recordDns: (input) =>
277 Effect.sync(() => {
278 calls.push({ operation: "recordDns", input });
279 const current = allocations.get(allocationKey(input));
280 if (current?.generation !== input.generation || current.tunnelId !== input.tunnelId) {
281 return null;
282 }
283 mutate(allocationKey(input), (allocation) => ({
284 ...allocation,
285 dnsRecordId: input.dnsRecordId,
286 }));
287 return allocations.get(allocationKey(input))?.generation ?? null;
288 }),
289 markReady: (input) =>
290 Effect.sync(() => {
291 calls.push({ operation: "markReady", input });
292 const current = allocations.get(allocationKey(input));
293 if (current?.generation !== input.generation || current.tunnelId !== input.tunnelId) {
294 return false;
295 }
296 mutate(allocationKey(input), (allocation) => ({
297 ...allocation,
298 readyAt: "2026-06-02T00:00:00.000Z",
299 origin: input.origin,
300 }));
301 return true;
302 }),
303 enableRecovery: (input) =>
304 Effect.sync(() => {
305 const allocation = allocations.get(allocationKey(input));
306 if (allocation?.tunnelId !== input.tunnelId) {
307 return false;
308 }
309 recoveryEnabled.add(allocationKey(input));
310 return true;
311 }),
312 listByTunnelNames: (tunnelNames) =>
313 Effect.sync(() =>
314 [...allocations.values()]
315 .filter((allocation) => tunnelNames.includes(allocation.tunnelName))
316 .map((allocation) => ({
317 ...allocation,
318 recoveryEnabled: recoveryEnabled.has(allocationKey(allocation)),
319 })),
320 ),
321 claimRelease: (input) =>
322 Effect.sync(() => {
323 calls.push({ operation: "claimRelease", input });
324 const allocation = allocations.get(allocationKey(input));
325 if (
326 allocation === undefined ||
327 allocation.tunnelId !== input.tunnelId ||
328 allocation.generation !== input.generation
329 ) {
330 return null;
331 }
332 mutate(allocationKey(input), (current) => ({
333 ...current,
334 ...(input.markReleased === true ? { tunnelReleasedAt: "2026-06-02T00:00:00.000Z" } : {}),
335 }));
336 return allocations.get(allocationKey(input))?.generation ?? null;
337 }),
338 withClaimedTunnel: (input, effect) =>
339 Effect.suspend(() => {
340 const current = allocations.get(allocationKey(input));
341 return current?.tunnelId === input.tunnelId && current.generation === input.generation
342 ? effect.pipe(
343 Effect.asSome,
344 Effect.onError(() =>
345 Effect.sync(() => {
346 allocations.set(allocationKey(input), current);
347 }),
348 ),
349 )
350 : Effect.succeedNone;
351 }),
352 claimDeprovision: (input) =>
353 Effect.sync(() => {
354 calls.push({ operation: "claimDeprovision", input });
355 const allocation = allocations.get(allocationKey(input));
356 if (allocation === undefined || allocation.generation !== input.generation) {
357 return null;
358 }
359 mutate(allocationKey(input), (current) => current);
360 return allocations.get(allocationKey(input))?.generation ?? null;
361 }),
362 removeClaimed: (input) =>
363 Effect.sync(() => {
364 calls.push({ operation: "removeClaimed", input });
365 const allocation = allocations.get(allocationKey(input));
366 if (allocation === undefined || allocation.generation !== input.generation) {
367 return false;
368 }
369 allocations.delete(allocationKey(input));
370 return true;
371 }),
372 });
373 }
374
375 function makeTunnelLimits(
376 calls: Array<{ readonly userId: string; readonly environmentId: string }> = [],
377 result: ManagedTunnelLimits.ManagedTunnelLimitExceeded | null = null,
378 ) {
379 return ManagedTunnelLimits.ManagedTunnelLimits.of({
380 withCapacity: (input, reserve) =>
381 Effect.gen(function* () {
382 calls.push(input);
383 if (result !== null) {
384 return yield* result;
385 }
386 return yield* reserve;
387 }),
388 getOverride: () => Effect.die("unused"),
389 });
390 }
391
392 function layerProvider(
393 tunnelClient = makeTunnelClient(),
394 dnsClient = makeDnsClient(),
395 allocations = makeAllocations(),
396 tunnelLimits = makeTunnelLimits(),
397 ) {
398 return ManagedEndpointProvider.layer.pipe(
399 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
400 Layer.provide(RelayConfiguration.layer(config)),
401 Layer.provide(ManagedEndpointProvider.layerTunnelClient(tunnelClient)),
402 Layer.provide(ManagedEndpointProvider.layerDnsClient(dnsClient)),
403 Layer.provide(
404 Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, allocations),
405 ),
406 Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, tunnelLimits)),
407 );
408 }
409
410 const MANAGED_ENDPOINT_HASHES: Record<string, string> = {
411 "user_ABC:env_ABC": "d101ac68108a423e",
412 "user_ABC:env_shared": "d7e6356aaf8863aa",
413 "user_DEF:env_shared": "a2fc84ac1b8c1c35",
414 };
415
416 function expectedManagedEndpointHash(environmentId: string, userId: string): string {
417 const hash = MANAGED_ENDPOINT_HASHES[`${userId}:${environmentId}`];
418 if (hash === undefined) throw new Error(`No pinned hash for ${userId}:${environmentId}`);
419 return hash;
420 }
421
422 function expectedManagedHostname(environmentId: string, userId = "user_ABC"): string {
423 return `dev-julius-${expectedManagedEndpointHash(environmentId, userId)}.t3code.test`;
424 }
425
426 function expectedManagedTunnelName(environmentId: string, userId = "user_ABC"): string {
427 return `t3coderelay-managedendpoint-dev-julius-${expectedManagedEndpointHash(environmentId, userId)}`;
428 }
429
430 describe("ManagedEndpointProvider", () => {
431 it.effect("provisions a Cloudflare tunnel endpoint and connector token", () => {
432 const tunnelCalls: TunnelCall[] = [];
433 const dnsCalls: DnsCall[] = [];
434 const allocationCalls: AllocationCall[] = [];
435
436 return Effect.gen(function* () {
437 const hostname = expectedManagedHostname("env_ABC");
438 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
439 const result = yield* provider.provision({
440 userId: "user_ABC",
441 environmentId: "env_ABC",
442 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
443 });
444
445 expect(result).toEqual({
446 endpoint: {
447 httpBaseUrl: `https://${hostname}/`,
448 wsBaseUrl: `wss://${hostname}/ws`,
449 providerKind: "cloudflare_tunnel",
450 },
451 runtime: {
452 providerKind: "cloudflare_tunnel",
453 connectorToken: "connector-token",
454 tunnelId: "tunnel-id",
455 tunnelName: expectedManagedTunnelName("env_ABC"),
456 },
457 });
458 expect(dnsCalls).toEqual([
459 { operation: "listRecords", input: hostname },
460 {
461 operation: "createRecord",
462 input: {
463 type: "CNAME",
464 name: hostname,
465 content: "tunnel-id.cfargotunnel.com",
466 ttl: 1,
467 proxied: true,
468 },
469 },
470 ]);
471 expect(tunnelCalls.map((call) => call.operation)).toEqual([
472 "list",
473 "create",
474 "putConfiguration",
475 "getToken",
476 ]);
477 expect(tunnelCalls[2]?.input).toMatchObject({
478 tunnelConfig: {
479 ingress: [
480 {
481 hostname,
482 service: "http://127.0.0.1:3773",
483 },
484 { service: "http_status:404" },
485 ],
486 },
487 });
488 expect(tunnelCalls[0]?.input).toEqual({
489 name: expectedManagedTunnelName("env_ABC"),
490 isDeleted: false,
491 });
492 expect(allocationCalls.map((call) => call.operation)).toEqual([
493 "reserve",
494 "recordTunnel",
495 "recordDns",
496 "markReady",
497 ]);
498 }).pipe(
499 Effect.provide(
500 layerProvider(
501 makeTunnelClient(tunnelCalls),
502 makeDnsClient(dnsCalls),
503 makeAllocations(allocationCalls),
504 ),
505 ),
506 );
507 });
508
509 it.effect("refuses to provision past the managed tunnel limit without side effects", () => {
510 const tunnelCalls: TunnelCall[] = [];
511 const dnsCalls: DnsCall[] = [];
512 const allocationCalls: AllocationCall[] = [];
513 const exceeded = new ManagedTunnelLimits.ManagedTunnelLimitExceeded({
514 userId: "user_ABC",
515 environmentId: "env_ABC",
516 maxTunnels: 10,
517 activeTunnels: 10,
518 });
519
520 return Effect.gen(function* () {
521 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
522 const error = yield* Effect.flip(
523 provider.provision({
524 userId: "user_ABC",
525 environmentId: "env_ABC",
526 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
527 }),
528 );
529
530 expect(error).toBe(exceeded);
531 expect(tunnelCalls).toEqual([]);
532 expect(dnsCalls).toEqual([]);
533 expect(allocationCalls).toEqual([]);
534 }).pipe(
535 Effect.provide(
536 layerProvider(
537 makeTunnelClient(tunnelCalls),
538 makeDnsClient(dnsCalls),
539 makeAllocations(allocationCalls),
540 makeTunnelLimits([], exceeded),
541 ),
542 ),
543 );
544 });
545
546 it.effect("uses stage-scoped stable names without leaking unusual environment ids", () => {
547 const tunnelCalls: TunnelCall[] = [];
548
549 return Effect.gen(function* () {
550 const environmentId = "ENV With Spaces/../Symbols!" + "x".repeat(80);
551 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
552 yield* provider.provision({
553 userId: "user_ABC",
554 environmentId,
555 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
556 });
557
558 const requestedName = (
559 tunnelCalls.find((call) => call.operation === "list")?.input as
560 | { readonly name?: string }
561 | undefined
562 )?.name;
563 expect(requestedName).toMatch(/^t3coderelay-managedendpoint-dev-julius-[a-f0-9]{16}$/);
564 const configBody = (
565 tunnelCalls.find((call) => call.operation === "putConfiguration")?.input as
566 | { readonly tunnelConfig?: unknown }
567 | undefined
568 )?.tunnelConfig;
569 expect(configBody).toMatchObject({
570 ingress: [
571 {
572 hostname: expect.stringMatching(/^dev-julius-[a-f0-9]{16}\.t3code\.test$/),
573 },
574 { service: "http_status:404" },
575 ],
576 });
577 const hostname = (
578 configBody as
579 | {
580 readonly ingress?: readonly [{ readonly hostname?: unknown }, unknown];
581 }
582 | undefined
583 )?.ingress?.[0]?.hostname;
584 expect(typeof hostname === "string" ? hostname.split(".")[0]?.length : 0).toBeLessThanOrEqual(
585 63,
586 );
587 expect(tunnelCalls.find((call) => call.operation === "create")?.input).toMatchObject({
588 name: requestedName,
589 configSrc: "cloudflare",
590 });
591 }).pipe(Effect.provide(layerProvider(makeTunnelClient(tunnelCalls))));
592 });
593
594 it.effect("formats IPv6 loopback origins as valid Cloudflare ingress service URLs", () => {
595 const tunnelCalls: TunnelCall[] = [];
596
597 return Effect.gen(function* () {
598 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
599 yield* provider.provision({
600 userId: "user_ABC",
601 environmentId: "env-ipv6",
602 origin: { localHttpHost: "::1", localHttpPort: 3773 },
603 });
604
605 expect(
606 tunnelCalls.find((call) => call.operation === "putConfiguration")?.input,
607 ).toMatchObject({
608 tunnelConfig: {
609 ingress: [
610 {
611 service: "http://[::1]:3773",
612 },
613 { service: "http_status:404" },
614 ],
615 },
616 });
617 }).pipe(Effect.provide(layerProvider(makeTunnelClient(tunnelCalls))));
618 });
619
620 it.effect("rejects non-loopback managed endpoint origins before calling Cloudflare", () => {
621 const dnsCalls: DnsCall[] = [];
622
623 return Effect.gen(function* () {
624 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
625 const result = yield* Effect.result(
626 provider.provision({
627 userId: "user_ABC",
628 environmentId: "env_ABC",
629 origin: { localHttpHost: "192.168.1.10", localHttpPort: 3773 },
630 }),
631 );
632
633 expect(dnsCalls).toHaveLength(0);
634 expect(result._tag).toBe("Failure");
635 if (result._tag === "Failure") {
636 expect(result.failure).toMatchObject({
637 _tag: "ManagedEndpointOriginNotAllowed",
638 userId: "user_ABC",
639 environmentId: "env_ABC",
640 host: "192.168.1.10",
641 port: 3773,
642 });
643 }
644 }).pipe(Effect.provide(layerProvider(makeTunnelClient(), makeDnsClient(dnsCalls))));
645 });
646
647 it.effect("reuses checkpointed resources when provisioning is retried", () => {
648 const tunnelCalls: TunnelCall[] = [];
649 const dnsCalls: DnsCall[] = [];
650 const allocationCalls: AllocationCall[] = [];
651 const layer = layerProvider(
652 makePersistentTunnelClient(tunnelCalls),
653 makeDnsClient(dnsCalls),
654 makeAllocations(allocationCalls),
655 );
656
657 return Effect.gen(function* () {
658 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
659 const request = {
660 userId: "user_ABC",
661 environmentId: "env_ABC",
662 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
663 } as const;
664 yield* provider.provision(request);
665 yield* provider.provision(request);
666
667 expect(tunnelCalls.map((call) => call.operation)).toEqual([
668 "list",
669 "create",
670 "putConfiguration",
671 "getToken",
672 "list",
673 "putConfiguration",
674 "getToken",
675 ]);
676 expect(dnsCalls.map((call) => call.operation)).toEqual([
677 "listRecords",
678 "createRecord",
679 "updateRecord",
680 ]);
681 expect(allocationCalls.map((call) => call.operation)).toEqual([
682 "reserve",
683 "recordTunnel",
684 "recordDns",
685 "markReady",
686 "reserve",
687 "recordTunnel",
688 "recordDns",
689 "markReady",
690 ]);
691 }).pipe(Effect.provide(layer));
692 });
693
694 it.effect("recovers a ready tunnel for the same origin with only reads", () => {
695 const tunnelCalls: TunnelCall[] = [];
696 const dnsCalls: DnsCall[] = [];
697 const allocationCalls: AllocationCall[] = [];
698 const layer = layerProvider(
699 makePersistentTunnelClient(tunnelCalls),
700 makeDnsClient(dnsCalls),
701 makeAllocations(allocationCalls),
702 );
703
704 return Effect.gen(function* () {
705 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
706 const request = {
707 userId: "user_ABC",
708 environmentId: "env_ABC",
709 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
710 } as const;
711 const provisioned = yield* provider.provision(request);
712 tunnelCalls.length = 0;
713 dnsCalls.length = 0;
714 allocationCalls.length = 0;
715
716 const recovered = yield* provider.provision({ ...request, reuseReadyTunnel: true });
717
718 expect(recovered).toEqual(provisioned);
719 expect(tunnelCalls.map((call) => call.operation)).toEqual(["get", "getToken"]);
720 expect(dnsCalls).toEqual([]);
721 expect(allocationCalls.map((call) => call.operation)).toEqual(["reserve"]);
722 }).pipe(Effect.provide(layer));
723 });
724
725 it.effect("fully provisions a recovery when the ready tunnel cannot be reused", () => {
726 const tunnelCalls: TunnelCall[] = [];
727 const tunnelClient = makePersistentTunnelClient(tunnelCalls);
728 const layer = layerProvider(tunnelClient);
729
730 return Effect.gen(function* () {
731 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
732 const request = {
733 userId: "user_ABC",
734 environmentId: "env_ABC",
735 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
736 reuseReadyTunnel: true,
737 } as const;
738 yield* provider.provision(request);
739
740 tunnelCalls.length = 0;
741 yield* provider.provision({
742 ...request,
743 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 },
744 });
745 expect(tunnelCalls.map((call) => call.operation)).toEqual([
746 "list",
747 "putConfiguration",
748 "getToken",
749 ]);
750
751 yield* tunnelClient.delete("tunnel-id");
752 tunnelCalls.length = 0;
753 yield* provider.provision({
754 ...request,
755 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3774 },
756 });
757 expect(tunnelCalls.map((call) => call.operation)).toEqual([
758 "get",
759 "list",
760 "create",
761 "putConfiguration",
762 "getToken",
763 ]);
764 }).pipe(Effect.provide(layer));
765 });
766
767 it.effect("keeps a pause recorded while a shared pause read was in flight", () => {
768 let listCalls = 0;
769 const tunnelClient = {
770 list: () =>
771 Effect.suspend(() => {
772 listCalls += 1;
773 return Effect.fail({ _tag: "TooManyRequests", message: "Rate limited" });
774 }),
775 } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient;
776
777 return Effect.gen(function* () {
778 const readStarted = yield* Deferred.make<void>();
779 const releaseRead = yield* Deferred.make<void>();
780 const layer = ManagedEndpointProvider.layerCloudflareBindings(
781 tunnelClient,
782 {} as Cloudflare.DNS.ReadWriteDnsClient,
783 {} as Alchemy.BaseRuntimeContext,
784 ).pipe(
785 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
786 Layer.provide(RelayConfiguration.layer(config)),
787 Layer.provide(
788 Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()),
789 ),
790 Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())),
791 Layer.provide(
792 Layer.succeed(
793 CloudflareApiPause.CloudflareApiPause,
794 CloudflareApiPause.CloudflareApiPause.of({
795 pausedUntilMillis: Deferred.succeed(readStarted, undefined).pipe(
796 Effect.andThen(Deferred.await(releaseRead)),
797 Effect.as(0),
798 ),
799 pauseUntil: () => Effect.void,
800 }),
801 ),
802 ),
803 );
804
805 yield* Effect.gen(function* () {
806 const tunnels = yield* ManagedEndpointProvider.ManagedEndpointTunnelClient;
807 const list = tunnels.list({ isDeleted: false }).pipe(Effect.flip);
808 // The first call starts the shared read; the second hits a 429 meanwhile.
809 const reading = yield* Effect.forkChild(list);
810 yield* Deferred.await(readStarted);
811 yield* list;
812 yield* Deferred.succeed(releaseRead, undefined);
813 yield* Fiber.join(reading);
814 yield* list;
815 expect(listCalls).toBe(1);
816 }).pipe(Effect.provide(layer));
817 });
818 });
819
820 it.effect("reads a tunnel without remote configuration as having no ingress", () => {
821 const tunnelClient = {
822 getConfiguration: () =>
823 Effect.fail(
824 new ZeroTrust.TunnelConfigurationNotFound({
825 code: 1055,
826 message: "Tunnel configuration not found",
827 }),
828 ),
829 } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient;
830 const layer = ManagedEndpointProvider.layerCloudflareBindings(
831 tunnelClient,
832 {} as Cloudflare.DNS.ReadWriteDnsClient,
833 {} as Alchemy.BaseRuntimeContext,
834 ).pipe(
835 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
836 Layer.provide(RelayConfiguration.layer(config)),
837 Layer.provide(
838 Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()),
839 ),
840 Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())),
841 Layer.provide(
842 Layer.succeed(
843 CloudflareApiPause.CloudflareApiPause,
844 CloudflareApiPause.CloudflareApiPause.of({
845 pausedUntilMillis: Effect.succeed(0),
846 pauseUntil: () => Effect.void,
847 }),
848 ),
849 ),
850 );
851
852 return Effect.gen(function* () {
853 const tunnels = yield* ManagedEndpointProvider.ManagedEndpointTunnelClient;
854 expect(yield* tunnels.getConfiguration("tunnel-id")).toEqual({ ingress: [] });
855 }).pipe(Effect.provide(layer));
856 });
857
858 it.effect("does not hide non-not-found checkpoint update failures", () => {
859 const dnsCalls: DnsCall[] = [];
860 const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
861 operation: "update-record",
862 dnsRecordId: "created-record-id",
863 cause: new Error("Cloudflare DNS unavailable"),
864 });
865 let records: ReadonlyArray<{ readonly id: string }> = [];
866 const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
867 listRecords: (hostname) =>
868 Effect.sync(() => {
869 dnsCalls.push({ operation: "listRecords", input: hostname });
870 return records;
871 }),
872 createRecord: (request) =>
873 Effect.sync(() => {
874 dnsCalls.push({ operation: "createRecord", input: request });
875 const record = { id: "created-record-id" };
876 records = [record];
877 return record;
878 }),
879 updateRecord: (dnsRecordId, request) =>
880 Effect.sync(() => {
881 dnsCalls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
882 }).pipe(Effect.andThen(Effect.fail(failure))),
883 deleteRecord: () => Effect.void,
884 });
885 const allocations = makeAllocations();
886 const layer = layerProvider(makePersistentTunnelClient(), dnsClient, allocations);
887
888 return Effect.gen(function* () {
889 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
890 const request = {
891 userId: "user_ABC",
892 environmentId: "env_ABC",
893 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
894 } as const;
895 yield* provider.provision(request);
896 const error = yield* Effect.flip(provider.provision(request));
897
898 expect(error).toMatchObject({
899 _tag: "ManagedEndpointProvisioningFailed",
900 stage: "ensure-dns-record",
901 userId: "user_ABC",
902 environmentId: "env_ABC",
903 });
904 expect(dnsCalls.map((call) => call.operation)).toEqual([
905 "listRecords",
906 "createRecord",
907 "updateRecord",
908 ]);
909 expect(yield* allocations.get(request)).toMatchObject({
910 tunnelId: "tunnel-id",
911 readyAt: "2026-06-02T00:00:00.000Z",
912 });
913 }).pipe(Effect.provide(layer));
914 });
915
916 it.effect(
917 "deprovisions checkpointed DNS and tunnel resources before removing the allocation",
918 () => {
919 const tunnelCalls: TunnelCall[] = [];
920 const dnsCalls: DnsCall[] = [];
921 const allocationCalls: AllocationCall[] = [];
922 const layer = layerProvider(
923 makePersistentTunnelClient(tunnelCalls),
924 makeDnsClient(dnsCalls),
925 makeAllocations(allocationCalls),
926 );
927
928 return Effect.gen(function* () {
929 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
930 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
931 yield* provider.provision({
932 ...key,
933 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
934 });
935 yield* provider.deprovision(key);
936
937 expect(dnsCalls.map((call) => call.operation)).toEqual([
938 "listRecords",
939 "createRecord",
940 "deleteRecord",
941 ]);
942 expect(tunnelCalls.map((call) => call.operation)).toEqual([
943 "list",
944 "create",
945 "putConfiguration",
946 "getToken",
947 "delete",
948 ]);
949 expect(allocationCalls.map((call) => call.operation)).toEqual([
950 "reserve",
951 "recordTunnel",
952 "recordDns",
953 "markReady",
954 "get",
955 "claimDeprovision",
956 "removeClaimed",
957 ]);
958 }).pipe(Effect.provide(layer));
959 },
960 );
961
962 it.effect("does not deprovision an allocation superseded by a concurrent relink", () => {
963 const tunnelCalls: TunnelCall[] = [];
964 const dnsCalls: DnsCall[] = [];
965 const allocationCalls: AllocationCall[] = [];
966 const layer = layerProvider(
967 makePersistentTunnelClient(tunnelCalls),
968 makeDnsClient(dnsCalls),
969 makeAllocations(allocationCalls),
970 );
971
972 return Effect.gen(function* () {
973 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
974 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
975 const request = {
976 ...key,
977 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
978 } as const;
979 yield* provider.provision(request);
980 const unlinkTarget = yield* provider.prepareDeprovision(key);
981 expect(unlinkTarget).not.toBeNull();
982 if (unlinkTarget === null) {
983 return;
984 }
985
986 yield* provider.provision(request);
987 const tunnelCallCount = tunnelCalls.length;
988 const dnsCallCount = dnsCalls.length;
989 const allocationCallCount = allocationCalls.length;
990
991 yield* provider.deprovision({ ...key, target: unlinkTarget });
992
993 expect(tunnelCalls).toHaveLength(tunnelCallCount);
994 expect(dnsCalls).toHaveLength(dnsCallCount);
995 expect(allocationCalls.slice(allocationCallCount).map((call) => call.operation)).toEqual([
996 "claimDeprovision",
997 ]);
998 }).pipe(Effect.provide(layer));
999 });
1000
1001 it.effect("releases the tunnel while keeping the allocation, DNS record, and hostname", () => {
1002 const tunnelCalls: TunnelCall[] = [];
1003 const dnsCalls: DnsCall[] = [];
1004 const allocationCalls: AllocationCall[] = [];
1005 const layer = layerProvider(
1006 makePersistentTunnelClient(tunnelCalls),
1007 makeDnsClient(dnsCalls),
1008 makeAllocations(allocationCalls),
1009 );
1010
1011 return Effect.gen(function* () {
1012 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1013 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1014 const origin = { localHttpHost: "127.0.0.1", localHttpPort: 3773 } as const;
1015 const first = yield* provider.provision({ ...key, origin });
1016 const released = yield* provider.release(key);
1017 const second = yield* provider.provision({ ...key, origin });
1018
1019 expect(released).toBe(true);
1020 expect(second.endpoint).toEqual(first.endpoint);
1021 expect(tunnelCalls.map((call) => call.operation)).toEqual([
1022 "list",
1023 "create",
1024 "putConfiguration",
1025 "getToken",
1026 "delete",
1027 "list",
1028 "create",
1029 "putConfiguration",
1030 "getToken",
1031 ]);
1032 expect(dnsCalls.map((call) => call.operation)).toEqual([
1033 "listRecords",
1034 "createRecord",
1035 "updateRecord",
1036 ]);
1037 const claims = allocationCalls.filter((call) => call.operation === "claimRelease");
1038 expect(claims.map((call) => (call.input as { markReleased?: boolean }).markReleased)).toEqual(
1039 [undefined, undefined],
1040 );
1041 }).pipe(Effect.provide(layer));
1042 });
1043
1044 it.effect("marks the release on the claim that deletes the tunnel when asked", () => {
1045 const allocations = makeAllocations();
1046 const layer = layerProvider(makePersistentTunnelClient(), makeDnsClient(), allocations);
1047
1048 return Effect.gen(function* () {
1049 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1050 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1051 yield* provider.provision({
1052 ...key,
1053 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1054 });
1055 expect(yield* provider.release({ ...key, markReleased: true })).toBe(true);
1056 expect((yield* allocations.get(key))?.tunnelReleasedAt).toBe("2026-06-02T00:00:00.000Z");
1057 }).pipe(Effect.provide(layer));
1058 });
1059
1060 it.effect("keeps the tunnel alive when a concurrent provision outdates the release claim", () => {
1061 const tunnelCalls: TunnelCall[] = [];
1062 const allocations = makeAllocations();
1063 const outdated = ManagedEndpointAllocations.ManagedEndpointAllocations.of({
1064 ...allocations,
1065 claimRelease: () => Effect.succeed(null),
1066 });
1067 const layer = layerProvider(makePersistentTunnelClient(tunnelCalls), makeDnsClient(), outdated);
1068
1069 return Effect.gen(function* () {
1070 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1071 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1072 yield* provider.provision({
1073 ...key,
1074 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1075 });
1076 const released = yield* provider.release(key);
1077
1078 expect(released).toBe(false);
1079 expect(tunnelCalls.map((call) => call.operation)).toEqual([
1080 "list",
1081 "create",
1082 "putConfiguration",
1083 "getToken",
1084 ]);
1085 }).pipe(Effect.provide(layer));
1086 });
1087
1088 it.effect("does not release a tunnel when the requested tunnel id is outdated", () => {
1089 const tunnelCalls: TunnelCall[] = [];
1090 const layer = layerProvider(
1091 makePersistentTunnelClient(tunnelCalls),
1092 makeDnsClient(),
1093 makeAllocations(),
1094 );
1095
1096 return Effect.gen(function* () {
1097 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1098 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1099 yield* provider.provision({
1100 ...key,
1101 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1102 });
1103
1104 expect(yield* provider.release({ ...key, expectedTunnelId: "old-tunnel-id" })).toBe(false);
1105 expect(tunnelCalls.map((call) => call.operation)).not.toContain("delete");
1106 }).pipe(Effect.provide(layer));
1107 });
1108
1109 it.effect("keeps a tunnel when a provision replaces an ordinary release generation", () => {
1110 const tunnelCalls: TunnelCall[] = [];
1111 const allocations = makeAllocations();
1112 let replaceAfterClaim = false;
1113 const replaced = ManagedEndpointAllocations.ManagedEndpointAllocations.of({
1114 ...allocations,
1115 claimRelease: (input) =>
1116 allocations.claimRelease(input).pipe(
1117 Effect.tap((claimedGeneration) => {
1118 if (claimedGeneration === null || replaceAfterClaim) return Effect.void;
1119 replaceAfterClaim = true;
1120 return allocations
1121 .recordTunnel({
1122 userId: input.userId,
1123 environmentId: input.environmentId,
1124 tunnelId: "replacement-tunnel",
1125 generation: claimedGeneration,
1126 })
1127 .pipe(Effect.asVoid);
1128 }),
1129 ),
1130 });
1131 const layer = layerProvider(makePersistentTunnelClient(tunnelCalls), makeDnsClient(), replaced);
1132
1133 return Effect.gen(function* () {
1134 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1135 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1136 yield* provider.provision({
1137 ...key,
1138 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1139 });
1140
1141 expect(yield* provider.release(key)).toBe(false);
1142 expect(tunnelCalls.map((call) => call.operation)).not.toContain("delete");
1143 }).pipe(Effect.provide(layer));
1144 });
1145
1146 it.effect("asks for recovery when the recorded tunnel was deleted", () => {
1147 const tunnelCalls: TunnelCall[] = [];
1148 const layer = layerProvider(makePersistentTunnelClient(tunnelCalls));
1149
1150 return Effect.gen(function* () {
1151 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1152 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1153 const origin = { localHttpHost: "127.0.0.1", localHttpPort: 3773 } as const;
1154 const provisioned = yield* provider.provision({ ...key, origin });
1155 expect(yield* provider.release(key)).toBe(true);
1156
1157 expect(
1158 yield* provider.reconcileOrigin({
1159 ...key,
1160 tunnelId: provisioned.runtime.tunnelId!,
1161 origin,
1162 endpoint: provisioned.endpoint,
1163 }),
1164 ).toBe("recovery_required");
1165 }).pipe(Effect.provide(layer));
1166 });
1167
1168 it.effect("updates Cloudflare ingress once when the registered port changes", () => {
1169 const tunnelCalls: TunnelCall[] = [];
1170 const layer = layerProvider(makePersistentTunnelClient(tunnelCalls));
1171
1172 return Effect.gen(function* () {
1173 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1174 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1175 const provisioned = yield* provider.provision({
1176 ...key,
1177 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1178 });
1179 tunnelCalls.length = 0;
1180
1181 expect(
1182 yield* provider.reconcileOrigin({
1183 ...key,
1184 tunnelId: provisioned.runtime.tunnelId!,
1185 origin: { localHttpHost: "127.0.0.1", localHttpPort: 4884 },
1186 endpoint: provisioned.endpoint,
1187 }),
1188 ).toBe("ready");
1189 expect(tunnelCalls).toEqual([
1190 { operation: "get", input: "tunnel-id" },
1191 {
1192 operation: "putConfiguration",
1193 input: {
1194 tunnelId: "tunnel-id",
1195 tunnelConfig: {
1196 ingress: [
1197 {
1198 hostname: expectedManagedHostname("env_ABC"),
1199 service: "http://127.0.0.1:4884",
1200 },
1201 { service: "http_status:404" },
1202 ],
1203 },
1204 },
1205 },
1206 ]);
1207 }).pipe(Effect.provide(layer));
1208 });
1209
1210 it.effect("restores Cloudflare ingress that drifted from the recorded origin", () => {
1211 const tunnelCalls: TunnelCall[] = [];
1212 const configuration: { current: TunnelConfiguration | null } = { current: null };
1213 const layer = layerProvider(makePersistentTunnelClient(tunnelCalls, configuration));
1214
1215 return Effect.gen(function* () {
1216 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1217 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1218 const origin = { localHttpHost: "127.0.0.1", localHttpPort: 3773 } as const;
1219 const provisioned = yield* provider.provision({ ...key, origin });
1220 const reconcile = provider.reconcileOrigin({
1221 ...key,
1222 tunnelId: provisioned.runtime.tunnelId!,
1223 origin,
1224 endpoint: provisioned.endpoint,
1225 });
1226 tunnelCalls.length = 0;
1227
1228 expect(yield* reconcile).toBe("ready");
1229 expect(tunnelCalls.map((call) => call.operation)).toEqual(["get", "getConfiguration"]);
1230
1231 configuration.current = {
1232 ingress: [
1233 { hostname: expectedManagedHostname("env_ABC"), service: "http://127.0.0.1:4711" },
1234 { service: "http_status:404" },
1235 ],
1236 };
1237 expect(yield* reconcile).toBe("ready");
1238 expect(configuration.current).toEqual({
1239 ingress: [
1240 { hostname: expectedManagedHostname("env_ABC"), service: "http://127.0.0.1:3773" },
1241 { service: "http_status:404" },
1242 ],
1243 });
1244
1245 configuration.current = {
1246 ingress: [
1247 { hostname: "*.t3code.test", service: "http://127.0.0.1:4711" },
1248 { hostname: expectedManagedHostname("env_ABC"), service: "http://127.0.0.1:3773" },
1249 { service: "http_status:404" },
1250 ],
1251 };
1252 expect(yield* reconcile).toBe("ready");
1253 expect(configuration.current.ingress[0]).toEqual({
1254 hostname: expectedManagedHostname("env_ABC"),
1255 service: "http://127.0.0.1:3773",
1256 });
1257
1258 configuration.current = {
1259 ingress: [
1260 {
1261 hostname: expectedManagedHostname("env_ABC"),
1262 path: "/api",
1263 service: "http://127.0.0.1:3773",
1264 },
1265 { service: "http_status:404" },
1266 ],
1267 };
1268 expect(yield* reconcile).toBe("ready");
1269 expect(configuration.current.ingress[0]).toEqual({
1270 hostname: expectedManagedHostname("env_ABC"),
1271 service: "http://127.0.0.1:3773",
1272 });
1273 }).pipe(Effect.provide(layer));
1274 });
1275
1276 it.effect("rejects an active endpoint that does not match the allocation hostname", () => {
1277 const layer = layerProvider(makePersistentTunnelClient());
1278
1279 return Effect.gen(function* () {
1280 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1281 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1282 const provisioned = yield* provider.provision({
1283 ...key,
1284 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1285 });
1286
1287 const error = yield* Effect.flip(
1288 provider.reconcileOrigin({
1289 ...key,
1290 tunnelId: provisioned.runtime.tunnelId!,
1291 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1292 endpoint: {
1293 ...provisioned.endpoint,
1294 httpBaseUrl: "https://different-host.t3code.test/",
1295 },
1296 }),
1297 );
1298 expect(error).toMatchObject({
1299 _tag: "ManagedEndpointProvisioningFailed",
1300 stage: "verify-endpoint",
1301 });
1302 }).pipe(Effect.provide(layer));
1303 });
1304
1305 it.effect(
1306 "keeps a newly created tunnel available for retry after losing its allocation claim",
1307 () => {
1308 const tunnelCalls: TunnelCall[] = [];
1309 const allocations = makeAllocations();
1310 let changeGeneration = true;
1311 const changed = ManagedEndpointAllocations.ManagedEndpointAllocations.of({
1312 ...allocations,
1313 recordTunnel: (input) =>
1314 Effect.gen(function* () {
1315 if (changeGeneration) {
1316 changeGeneration = false;
1317 yield* allocations.claimDeprovision(input);
1318 }
1319 return yield* allocations.recordTunnel(input);
1320 }),
1321 });
1322 const layer = layerProvider(
1323 makePersistentTunnelClient(tunnelCalls),
1324 makeDnsClient(),
1325 changed,
1326 );
1327
1328 return Effect.gen(function* () {
1329 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1330 const input = {
1331 userId: "user_ABC",
1332 environmentId: "env_ABC",
1333 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1334 };
1335 const error = yield* Effect.flip(provider.provision(input));
1336
1337 expect(error).toMatchObject({
1338 _tag: "ManagedEndpointProvisioningFailed",
1339 stage: "record-tunnel",
1340 reason: "claim-lost",
1341 });
1342 expect(tunnelCalls.map((call) => call.operation)).toEqual(["list", "create"]);
1343 expect((yield* provider.provision(input)).runtime.tunnelId).toBe("tunnel-id");
1344 expect(tunnelCalls.filter((call) => call.operation === "create")).toHaveLength(1);
1345 expect(tunnelCalls.filter((call) => call.operation === "delete")).toEqual([]);
1346 }).pipe(Effect.provide(layer));
1347 },
1348 );
1349
1350 it.effect("does not change tunnel ingress after another provision takes ownership", () => {
1351 const tunnelCalls: TunnelCall[] = [];
1352 const allocations = makeAllocations();
1353 const changed = ManagedEndpointAllocations.ManagedEndpointAllocations.of({
1354 ...allocations,
1355 withClaimedTunnel: () => Effect.succeedNone,
1356 });
1357 const layer = layerProvider(makePersistentTunnelClient(tunnelCalls), makeDnsClient(), changed);
1358
1359 return Effect.gen(function* () {
1360 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1361 const error = yield* Effect.flip(
1362 provider.provision({
1363 userId: "user_ABC",
1364 environmentId: "env_ABC",
1365 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1366 }),
1367 );
1368
1369 expect(error).toMatchObject({
1370 _tag: "ManagedEndpointProvisioningFailed",
1371 stage: "configure-tunnel",
1372 reason: "claim-lost",
1373 });
1374 expect(tunnelCalls.map((call) => call.operation)).not.toContain("putConfiguration");
1375 }).pipe(Effect.provide(layer));
1376 });
1377
1378 it.effect("does not change DNS after another provision takes ownership", () => {
1379 const dnsCalls: DnsCall[] = [];
1380 const allocations = makeAllocations();
1381 let lockCount = 0;
1382 const changed = ManagedEndpointAllocations.ManagedEndpointAllocations.of({
1383 ...allocations,
1384 withClaimedTunnel: (input, effect) =>
1385 ++lockCount === 1 ? allocations.withClaimedTunnel(input, effect) : Effect.succeedNone,
1386 });
1387 const layer = layerProvider(makePersistentTunnelClient(), makeDnsClient(dnsCalls), changed);
1388
1389 return Effect.gen(function* () {
1390 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1391 const error = yield* Effect.flip(
1392 provider.provision({
1393 userId: "user_ABC",
1394 environmentId: "env_ABC",
1395 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1396 }),
1397 );
1398
1399 expect(error).toMatchObject({
1400 _tag: "ManagedEndpointProvisioningFailed",
1401 stage: "record-dns",
1402 });
1403 expect(dnsCalls).toEqual([]);
1404 }).pipe(Effect.provide(layer));
1405 });
1406
1407 it.effect("keeps a tunnel that reconnects before scheduled deletion", () => {
1408 const tunnelCalls: TunnelCall[] = [];
1409 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
1410 ...makePersistentTunnelClient(tunnelCalls),
1411 get: (tunnelId) =>
1412 Effect.succeed({
1413 id: tunnelId,
1414 name: expectedManagedTunnelName("env_ABC"),
1415 status: "healthy",
1416 connsInactiveAt: null,
1417 }),
1418 });
1419 const layer = layerProvider(tunnelClient, makeDnsClient(), makeAllocations());
1420
1421 return Effect.gen(function* () {
1422 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1423 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1424 yield* provider.provision({
1425 ...key,
1426 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1427 });
1428
1429 expect(
1430 yield* provider.release({
1431 ...key,
1432 expectedTunnelId: "tunnel-id",
1433 expectedStatus: "down",
1434 expectedInactiveBefore: "2026-06-01T00:05:00.000Z",
1435 }),
1436 ).toBe(false);
1437 expect(tunnelCalls.map((call) => call.operation)).not.toContain("delete");
1438 }).pipe(Effect.provide(layer));
1439 });
1440
1441 it.effect.each([
1442 { name: "the tunnel is gone", tunnelRemoved: true, released: true },
1443 { name: "the tunnel still exists", tunnelRemoved: false, released: false },
1444 ] as const)(
1445 "resolves a delete whose response was lost by checking whether $name",
1446 ({ tunnelRemoved, released }) => {
1447 const persistent = makePersistentTunnelClient();
1448 const lostResponse = new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
1449 operation: "delete",
1450 tunnelId: "tunnel-id",
1451 cause: { _tag: "TimeoutError" },
1452 });
1453 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
1454 ...persistent,
1455 delete: (tunnelId) =>
1456 (tunnelRemoved ? persistent.delete(tunnelId) : Effect.void).pipe(
1457 Effect.andThen(Effect.fail(lostResponse)),
1458 ),
1459 });
1460 const allocationCalls: AllocationCall[] = [];
1461 const allocations = makeAllocations(allocationCalls);
1462 const layer = layerProvider(tunnelClient, makeDnsClient(), allocations);
1463
1464 return Effect.gen(function* () {
1465 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1466 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1467 yield* provider.provision({
1468 ...key,
1469 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1470 });
1471 const result = yield* Effect.result(provider.release({ ...key, markReleased: true }));
1472 expect((yield* allocations.get(key))?.tunnelReleasedAt).toBe(
1473 released ? "2026-06-02T00:00:00.000Z" : null,
1474 );
1475
1476 if (released) {
1477 expect(result).toMatchObject({ _tag: "Success", success: true });
1478 } else {
1479 expect(result).toMatchObject({
1480 _tag: "Failure",
1481 failure: { stage: "delete-tunnel", cause: lostResponse },
1482 });
1483 }
1484 }).pipe(Effect.provide(layer));
1485 },
1486 );
1487
1488 it.effect("reports a tunnel with an attached connector as not released", () => {
1489 const persistent = makePersistentTunnelClient();
1490 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
1491 ...persistent,
1492 delete: (tunnelId) =>
1493 Effect.fail(
1494 new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
1495 operation: "delete",
1496 tunnelId,
1497 cause: {
1498 _tag: "BadRequest",
1499 code: 1022,
1500 message:
1501 "This tunnel has active connections. Please stop all cloudflared replicas, or wait a few minutes for connections to close, then try again.",
1502 },
1503 }),
1504 ),
1505 });
1506 const allocations = makeAllocations();
1507 const layer = layerProvider(tunnelClient, makeDnsClient(), allocations);
1508
1509 return Effect.gen(function* () {
1510 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1511 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1512 yield* provider.provision({
1513 ...key,
1514 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1515 });
1516 expect(yield* provider.release({ ...key, markReleased: true })).toBe(false);
1517 expect((yield* allocations.get(key))?.tunnelReleasedAt).toBeNull();
1518 expect((yield* persistent.get("tunnel-id")).id).toBe("tunnel-id");
1519 }).pipe(Effect.provide(layer));
1520 });
1521
1522 it.effect("keeps the allocation when tunnel cleanup fails so unlink can retry", () => {
1523 const allocationCalls: AllocationCall[] = [];
1524 const tunnelCalls: TunnelCall[] = [];
1525 let deleteAttempts = 0;
1526 const failure = new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
1527 operation: "delete",
1528 tunnelId: "tunnel-id",
1529 cause: "Cloudflare tunnel deletion failed",
1530 });
1531 const tunnels = makePersistentTunnelClient(tunnelCalls);
1532 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
1533 ...tunnels,
1534 delete: (tunnelId) =>
1535 Effect.gen(function* () {
1536 tunnelCalls.push({ operation: "delete", input: tunnelId });
1537 deleteAttempts++;
1538 if (deleteAttempts === 1) {
1539 return yield* failure;
1540 }
1541 }),
1542 });
1543 const layer = layerProvider(tunnelClient, makeDnsClient(), makeAllocations(allocationCalls));
1544
1545 return Effect.gen(function* () {
1546 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1547 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1548 yield* provider.provision({
1549 ...key,
1550 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1551 });
1552 const first = yield* Effect.result(provider.deprovision(key));
1553 expect(first._tag).toBe("Failure");
1554 if (first._tag === "Failure") {
1555 expect(first.failure).toMatchObject({
1556 _tag: "ManagedEndpointDeprovisioningFailed",
1557 stage: "delete-tunnel",
1558 userId: key.userId,
1559 environmentId: key.environmentId,
1560 tunnelId: "tunnel-id",
1561 });
1562 expect(first.failure.cause).toBe(failure);
1563 }
1564 yield* provider.deprovision(key);
1565
1566 expect(allocationCalls.map((call) => call.operation)).toEqual([
1567 "reserve",
1568 "recordTunnel",
1569 "recordDns",
1570 "markReady",
1571 "get",
1572 "claimDeprovision",
1573 "get",
1574 "claimDeprovision",
1575 "removeClaimed",
1576 ]);
1577 }).pipe(Effect.provide(layer));
1578 });
1579
1580 it.effect("marks the tunnel released when removing the allocation fails after deletion", () => {
1581 const allocationCalls: AllocationCall[] = [];
1582 const allocations = makeAllocations(allocationCalls);
1583 const layer = layerProvider(makePersistentTunnelClient(), makeDnsClient(), {
1584 ...allocations,
1585 removeClaimed: (input) =>
1586 Effect.suspend(() => {
1587 allocationCalls.push({ operation: "removeClaimed", input });
1588 return Effect.fail(
1589 new ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError({
1590 operation: "remove-claimed",
1591 stage: "database-request",
1592 userId: input.userId,
1593 environmentId: input.environmentId,
1594 }),
1595 );
1596 }),
1597 });
1598
1599 return Effect.gen(function* () {
1600 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1601 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1602 yield* provider.provision({
1603 ...key,
1604 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1605 });
1606 const result = yield* Effect.result(provider.deprovision(key));
1607
1608 expect(result._tag).toBe("Failure");
1609 if (result._tag === "Failure") {
1610 expect(result.failure).toMatchObject({ stage: "remove-allocation" });
1611 }
1612 // The tunnel is gone; without the mark the tunnel limit would keep counting it.
1613 const claim = allocationCalls.find((call) => call.operation === "claimDeprovision");
1614 if (claim === undefined) return expect.unreachable("deprovision never claimed the row");
1615 expect(allocationCalls.at(-1)).toMatchObject({
1616 operation: "claimRelease",
1617 input: {
1618 tunnelId: "tunnel-id",
1619 generation: (claim.input as { generation: number }).generation + 1,
1620 markReleased: true,
1621 },
1622 });
1623 }).pipe(Effect.provide(layer));
1624 });
1625
1626 it.effect.each(["NotFound", "RecordNotFound"])(
1627 "treats deleted remote resources as deprovisioned (%s)",
1628 (dnsErrorTag) => {
1629 const allocationCalls: AllocationCall[] = [];
1630 const notFound = { _tag: "NotFound" } as const;
1631 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
1632 ...makeTunnelClient(),
1633 delete: () =>
1634 Effect.fail(
1635 new ManagedEndpointProvider.ManagedEndpointTunnelClientError({
1636 operation: "delete",
1637 tunnelId: "tunnel-id",
1638 cause: notFound,
1639 }),
1640 ),
1641 });
1642 const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
1643 ...makeDnsClient(),
1644 deleteRecord: () =>
1645 Effect.fail(
1646 new ManagedEndpointProvider.ManagedEndpointDnsClientError({
1647 operation: "delete-record",
1648 dnsRecordId: "created-record-id",
1649 cause: { _tag: dnsErrorTag },
1650 }),
1651 ),
1652 });
1653 const layer = layerProvider(tunnelClient, dnsClient, makeAllocations(allocationCalls));
1654
1655 return Effect.gen(function* () {
1656 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1657 const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;
1658 yield* provider.provision({
1659 ...key,
1660 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1661 });
1662 yield* provider.deprovision(key);
1663
1664 expect(allocationCalls.map((call) => call.operation)).toContain("removeClaimed");
1665 }).pipe(Effect.provide(layer));
1666 },
1667 );
1668
1669 it.effect("scopes managed endpoint resources by user", () => {
1670 const tunnelCalls: TunnelCall[] = [];
1671
1672 return Effect.gen(function* () {
1673 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1674 yield* provider.provision({
1675 userId: "user_ABC",
1676 environmentId: "env_shared",
1677 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1678 });
1679 yield* provider.provision({
1680 userId: "user_DEF",
1681 environmentId: "env_shared",
1682 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1683 });
1684
1685 expect(
1686 tunnelCalls.filter((call) => call.operation === "list").map((call) => call.input),
1687 ).toEqual([
1688 { name: expectedManagedTunnelName("env_shared", "user_ABC"), isDeleted: false },
1689 { name: expectedManagedTunnelName("env_shared", "user_DEF"), isDeleted: false },
1690 ]);
1691 }).pipe(Effect.provide(layerProvider(makeTunnelClient(tunnelCalls))));
1692 });
1693
1694 it.effect("recovers when DNS creation reports failure after the record became visible", () => {
1695 const dnsCalls: DnsCall[] = [];
1696 const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({
1697 operation: "create-record",
1698 hostname: expectedManagedHostname("env_ABC"),
1699 cause: "ambiguous Cloudflare DNS response",
1700 });
1701 let records: ReadonlyArray<{ readonly id: string }> = [];
1702 const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({
1703 listRecords: (hostname) =>
1704 Effect.sync(() => {
1705 dnsCalls.push({ operation: "listRecords", input: hostname });
1706 return records;
1707 }),
1708 createRecord: (request) =>
1709 Effect.gen(function* () {
1710 dnsCalls.push({ operation: "createRecord", input: request });
1711 records = [{ id: "created-record-id" }];
1712 return yield* failure;
1713 }),
1714 updateRecord: (dnsRecordId, request) =>
1715 Effect.sync(() => {
1716 dnsCalls.push({ operation: "updateRecord", input: { dnsRecordId, request } });
1717 }),
1718 deleteRecord: (dnsRecordId) =>
1719 Effect.sync(() => {
1720 dnsCalls.push({ operation: "deleteRecord", input: dnsRecordId });
1721 }),
1722 });
1723
1724 return Effect.gen(function* () {
1725 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1726 yield* provider.provision({
1727 userId: "user_ABC",
1728 environmentId: "env_ABC",
1729 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1730 });
1731
1732 expect(dnsCalls.map((call) => call.operation)).toEqual([
1733 "listRecords",
1734 "createRecord",
1735 "listRecords",
1736 "updateRecord",
1737 ]);
1738 }).pipe(Effect.provide(layerProvider(makeTunnelClient(), dnsClient)));
1739 });
1740
1741 it.effect("reports mismatched tunnel responses without manufacturing a cause", () => {
1742 const dnsCalls: DnsCall[] = [];
1743 const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({
1744 ...makeTunnelClient(),
1745 create: () => Effect.succeed({ id: "returned-tunnel-id", name: "unexpected-tunnel" }),
1746 });
1747
1748 return Effect.gen(function* () {
1749 const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
1750 const error = yield* Effect.flip(
1751 provider.provision({
1752 userId: "user_ABC",
1753 environmentId: "env_ABC",
1754 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
1755 }),
1756 );
1757
1758 expect(error).toMatchObject({
1759 _tag: "ManagedEndpointProvisioningFailed",
1760 stage: "validate-tunnel-response",
1761 userId: "user_ABC",
1762 environmentId: "env_ABC",
1763 hostname: expectedManagedHostname("env_ABC"),
1764 tunnelName: expectedManagedTunnelName("env_ABC"),
1765 returnedTunnelId: "returned-tunnel-id",
1766 returnedTunnelName: "unexpected-tunnel",
1767 });
1768 if (error._tag === "ManagedEndpointProvisioningFailed") {
1769 expect(error.cause).toBeUndefined();
1770 }
1771 expect(dnsCalls).toHaveLength(0);
1772 }).pipe(Effect.provide(layerProvider(tunnelClient, makeDnsClient(dnsCalls))));
1773 });
1774 });