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

http.test.ts

1,265 lines48.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as PlatformError from "effect/PlatformError";
12import * as Schema from "effect/Schema";
13import * as TestClock from "effect/testing/TestClock";
14import * as Tracer from "effect/Tracer";
15import * as Stream from "effect/Stream";
16import {
17 HttpClient,
18 HttpClientResponse,
19 HttpServerRequest,
20 type HttpClientRequest,
21} from "effect/http";
22​
23import { DESKTOP_UPDATE_RESTART_MARKER_FILE, EnvironmentId } from "@t3tools/contracts";
24import { RelayClientTracer } from "@t3tools/shared/relayTracing";
25import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
26import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
27import * as ServerConfigModule from "../config.ts";
28import { writeServiceState } from "../serviceLauncher.ts";
29import {
30 SERVICE_LAUNCHER_PROTOCOL,
31 SERVICE_STATE_FILE,
32 SERVICE_STOP_MARKER_FILE,
33 type ServiceUpdateRecord,
34} from "./serviceProtocol.ts";
35import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
36import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
37import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
38import * as CliTokenManager from "./CliTokenManager.ts";
39import {
40 RelayManagedEndpointRecoveryRegistrationRequest,
41 type RelayLinkProofRequest,
42} from "@t3tools/contracts/relay";
43import {
44 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
45 CLOUD_ENDPOINT_RUNTIME_CONFIG,
46 CLOUD_LINKED_USER_ID,
47 decodeConfirmedOrigin,
48 decodeRuntimeConfig,
49 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
50 RELAY_URL_SECRET,
51} from "./config.ts";
52import {
53 consumeCloudReplayGuards,
54 isSupportedLinkProviderKind,
55 linkProofScopes,
56 pendingServiceUpdateExists,
57 parseManagedEndpointLocalOrigin,
58 reconcileDesiredCloudLink,
59 reconcileDesiredCloudLinkIfStillDesired,
60 recoverManagedCloudTunnel,
61 registerManagedCloudTunnelRecovery,
62 releaseManagedTunnelOnShutdown,
63 startManagedCloudTunnelIfOriginConfirmed,
64} from "./http.ts";
65import {
66 managedTunnelStartupAction,
67 retryManagedTunnelRegistration,
68} from "./managedTunnelStartup.ts";
69import { shouldRetryCloudLink } from "./relayResponse.ts";
70import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
71import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";
72​
73const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
74 new ServerSecretStore.SecretStorePersistError({
75 resource: "cloud replay guard",
76 cause: PlatformError.systemError({
77 _tag: tag,
78 module: "FileSystem",
79 method: "open",
80 pathOrDescriptor: "cloud-replay-guard.bin",
81 }),
82 });
83​
84const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");
85// Linking wakes the awareness relay; these tests do not run it.
86const idleAwarenessRelay = AgentAwarenessRelay.AgentAwarenessRelay.of({
87 publishThread: () => Effect.void,
88 drain: Effect.void,
89 requestCatchUp: () => Effect.void,
90 start: () => Effect.void,
91});
92const decodeManagedTunnelRecoveryRegistration = Schema.decodeUnknownEffect(
93 Schema.fromJsonString(RelayManagedEndpointRecoveryRegistrationRequest),
94);
95​
96function makeSecretStore(
97 create: ServerSecretStore.ServerSecretStore["Service"]["create"],
98): ServerSecretStore.ServerSecretStore["Service"] {
99 return {
100 get: unusedSecretStoreOperation,
101 set: unusedSecretStoreOperation,
102 create,
103 getOrCreateRandom: unusedSecretStoreOperation,
104 remove: unusedSecretStoreOperation,
105 };
107​
108it("preserves messages surfaced by cloud 500 responses", () => {
109 const cause = new Error("cloud operation failed");
110​
111 expect([
112 new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({ cause }).message,
113 new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({ cause }).message,
114 new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({}).message,
115 new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({ cause }).message,
116 new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({}).message,
117 new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}).message,
118 new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({ cause }).message,
119 new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({ cause }).message,
120 ]).toEqual([
121 "Could not verify the linked cloud account.",
122 "Could not read the linked cloud account.",
123 "Cloud linked user is not installed for this environment.",
124 "Failed to sign cloud link JWT.",
125 "Cloud mint public key is not installed for this environment.",
126 "Cloud relay issuer is not installed for this environment.",
127 "Failed to sign cloud health JWT.",
128 "Failed to sign cloud mint JWT.",
129 ]);
130});
131​
132describe("consumeCloudReplayGuards", () => {
133 it.effect("reports already-created guards as replay conflicts", () =>
134 Effect.gen(function* () {
135 const consumed = yield* consumeCloudReplayGuards({
136 secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))),
137 names: ["cloud-jti", "cloud-nonce"],
138 value: new Uint8Array(),
139 });
140​
141 expect(consumed).toBe(false);
142 }),
143 );
144​
145 it.effect("preserves replay-store availability failures", () =>
146 Effect.gen(function* () {
147 const failure = storeFailure("PermissionDenied");
148 const error = yield* Effect.flip(
149 consumeCloudReplayGuards({
150 secrets: makeSecretStore(() => Effect.fail(failure)),
151 names: ["cloud-jti", "cloud-nonce"],
152 value: new Uint8Array(),
153 }),
154 );
155​
156 expect(error).toBe(failure);
157 }),
158 );
159});
160​
161describe("relay request tracing", () => {
162 it.effect("does not accept an unauthenticated request trace parent", () =>
163 Effect.gen(function* () {
164 const spans: Array<Tracer.Span> = [];
165 const productTracer = Tracer.make({
166 span: (options) => {
167 const span = new Tracer.NativeSpan(options);
168 spans.push(span);
169 return span;
170 },
171 });
172 const request = HttpServerRequest.fromWeb(
173 new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
174 headers: {
175 traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
176 },
177 }),
178 );
179​
180 yield* traceRelayRequest(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(
181 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
182 Effect.provideService(RelayClientTracer, Option.some(productTracer)),
183 );
184​
185 expect(spans).toHaveLength(1);
186 const span = spans[0]!;
187 expect(span.traceId).not.toBe("0123456789abcdef0123456789abcdef");
188 expect(Option.isNone(span.parent)).toBe(true);
189 }),
190 );
191​
192 it.effect("continues an authenticated relay trace with the product tracer", () =>
193 Effect.gen(function* () {
194 const spans: Array<Tracer.Span> = [];
195 const productTracer = Tracer.make({
196 span: (options) => {
197 const span = new Tracer.NativeSpan(options);
198 spans.push(span);
199 return span;
200 },
201 });
202 const request = HttpServerRequest.fromWeb(
203 new Request("https://environment.example.test/api/t3-cloud/mint-credential", {
204 headers: {
205 traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
206 },
207 }),
208 );
209​
210 yield* traceAuthenticatedRelayRequest(
211 Effect.void.pipe(Effect.withSpan("relay.mint.handler")),
212 ).pipe(
213 Effect.provideService(HttpServerRequest.HttpServerRequest, request),
214 Effect.provideService(RelayClientTracer, Option.some(productTracer)),
215 );
216​
217 expect(spans).toHaveLength(1);
218 const span = spans[0]!;
219 expect(span.traceId).toBe("0123456789abcdef0123456789abcdef");
220 expect(Option.getOrUndefined(span.parent)?.spanId).toBe("0123456789abcdef");
221 }),
222 );
223});
224​
225describe("reconcileDesiredCloudLink", () => {
226 it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
227 Effect.gen(function* () {
228 const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
229​
230 expect(error).toMatchObject({
231 _tag: "EnvironmentHttpUnauthorizedError",
232 message: "Run `t3 connect link` to authorize this environment.",
233 });
234 }).pipe(
235 Effect.provideService(
236 ServerSecretStore.ServerSecretStore,
237 makeSecretStore(unusedSecretStoreOperation),
238 ),
239 Effect.provideService(
240 ServerEnvironment.ServerEnvironment,
241 ServerEnvironment.ServerEnvironment.of({
242 getEnvironmentId: unusedSecretStoreOperation(),
243 getDescriptor: unusedSecretStoreOperation(),
244 }),
245 ),
246 Effect.provideService(
247 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
248 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
249 applyConfig: unusedSecretStoreOperation,
250 recoveryRequests: Stream.empty,
251 requestRecovery: () => Effect.void,
252 tunnelConnected: Stream.empty,
253 withLinkStateLock: (effect) => effect,
254 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),
255 ),
256 Effect.provideService(
257 EnvironmentAuth.EnvironmentAuth,
258 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
259 ),
260 Effect.provideService(
261 CliTokenManager.CloudCliTokenManager,
262 CliTokenManager.CloudCliTokenManager.of({
263 get: unusedSecretStoreOperation(),
264 getExisting: Effect.succeedNone,
265 hasCredential: unusedSecretStoreOperation(),
266 store: () => unusedSecretStoreOperation(),
267 clear: unusedSecretStoreOperation(),
268 }),
269 ),
270 Effect.provideService(
271 HttpClient.HttpClient,
272 HttpClient.make(() => unusedSecretStoreOperation()),
273 ),
274 Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay),
275 Effect.provide(NodeServices.layer),
276 ),
277 );
278});
279​
280describe("parseManagedEndpointLocalOrigin", () => {
281 it.each([
282 {
283 input: "http://127.0.0.1:80",
284 httpBaseUrl: "http://127.0.0.1",
285 wsBaseUrl: "ws://127.0.0.1",
286 port: 80,
287 },
288 {
289 input: "https://127.0.0.1:443",
290 httpBaseUrl: "https://127.0.0.1",
291 wsBaseUrl: "wss://127.0.0.1",
292 port: 443,
293 },
294 ])("accepts an explicit default port in $input", ({ input, httpBaseUrl, wsBaseUrl, port }) => {
295 expect(parseManagedEndpointLocalOrigin(input)).toEqual({
296 httpBaseUrl,
297 wsBaseUrl,
298 origin: { localHttpHost: "127.0.0.1", localHttpPort: port },
299 });
300 });
301​
302 it.each([
303 "ftp://127.0.0.1:3773",
304 "http://user:password@127.0.0.1:3773",
305 "http://127.0.0.1:3773/api",
306 "http://127.0.0.1:3773?mode=test",
307 "http://127.0.0.1:3773#fragment",
308 ])("rejects non-origin URL %s", (input) => {
309 expect(() => parseManagedEndpointLocalOrigin(input)).toThrow("Invalid local origin");
310 });
311});
312​
313describe("releaseManagedTunnelOnShutdown", () => {
314 const cliToken: CliTokenManager.PersistedToken = {
315 accessToken: "cli-access-token",
316 refreshToken: "cli-refresh-token",
317 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
318 };
319​
320 function makeMemorySecretStore(initial: Iterable<readonly [string, string]> = []) {
321 const values = new Map<string, Uint8Array>(
322 Array.from(initial, ([name, value]) => [name, new TextEncoder().encode(value)] as const),
323 );
324 const store: ServerSecretStore.ServerSecretStore["Service"] = {
325 get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))),
326 set: (name, value) =>
327 Effect.sync(() => {
328 values.set(name, value);
329 }),
330 create: (name, value) =>
331 Effect.sync(() => {
332 values.set(name, value);
333 }),
334 getOrCreateRandom: unusedSecretStoreOperation,
335 remove: (name) =>
336 Effect.sync(() => {
337 values.delete(name);
338 }),
339 };
340 return { store, values };
341 }
342​
343 interface ReleaseHarness {
344 readonly store: ServerSecretStore.ServerSecretStore["Service"];
345 readonly applyConfigCalls: Array<unknown>;
346 readonly requests: Array<HttpClientRequest.HttpClientRequest>;
347 readonly onRequest?: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<void>;
348 readonly respond?: () => Response;
349 readonly respondEffect?: Effect.Effect<Response>;
350 }
351​
352 // Writes the launcher's durable state file into this test's baseDir with
353 // the launcher's own writer; the release reads it to detect an in-flight
354 // update handoff.
355 const writeLauncherState = (update: ServiceUpdateRecord) =>
356 Effect.gen(function* () {
357 const path = yield* Path.Path;
358 const config = yield* ServerConfigModule.ServerConfig;
359 const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);
360 yield* Effect.promise(() =>
361 writeServiceState(statePath, {
362 protocol: SERVICE_LAUNCHER_PROTOCOL,
363 activeVersion: "0.0.30",
364 update,
365 }),
366 );
367 });
368​
369 // Writes the marker the desktop app leaves just before it stops its backend
370 // to install an update, and returns when it was written.
371 const writeDesktopUpdateRestartMarker = Effect.gen(function* () {
372 const fs = yield* FileSystem.FileSystem;
373 const path = yield* Path.Path;
374 const config = yield* ServerConfigModule.ServerConfig;
375 const runtimeDir = path.join(config.baseDir, "runtime");
376 const markerPath = path.join(runtimeDir, DESKTOP_UPDATE_RESTART_MARKER_FILE);
377 yield* fs.makeDirectory(runtimeDir, { recursive: true });
378 yield* fs.writeFileString(markerPath, "");
379 const { mtime } = yield* fs.stat(markerPath);
380 return Option.getOrThrow(mtime).getTime();
381 });
382​
383 const provideReleaseHarness =
384 (harness: ReleaseHarness) =>
385 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
386 effect.pipe(
387 Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store),
388 Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay),
389 Effect.provideService(
390 ServerEnvironment.ServerEnvironment,
391 ServerEnvironment.ServerEnvironment.of({
392 getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),
393 getDescriptor: Effect.die("unused"),
394 }),
395 ),
396 Effect.provideService(
397 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
398 ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
399 applyConfig: (config) =>
400 Effect.sync(() => {
401 harness.applyConfigCalls.push(config);
402 return config === null
403 ? ({
404 status: "disabled",
405 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus)
406 : ({
407 status: "running",
408 providerKind: "cloudflare_tunnel",
409 pid: 123,
410 } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus);
411 }),
412 recoveryRequests: Stream.empty,
413 requestRecovery: () => Effect.void,
414 tunnelConnected: Stream.empty,
415 withLinkStateLock: (effect) => effect,
416 }),
417 ),
418 Effect.provideService(
419 EnvironmentAuth.EnvironmentAuth,
420 EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
421 ),
422 Effect.provideService(
423 CliTokenManager.CloudCliTokenManager,
424 CliTokenManager.CloudCliTokenManager.of({
425 get: unusedSecretStoreOperation(),
426 getExisting: Effect.succeedSome(cliToken),
427 hasCredential: unusedSecretStoreOperation(),
428 store: () => unusedSecretStoreOperation(),
429 clear: unusedSecretStoreOperation(),
430 }),
431 ),
432 Effect.provideService(
433 HttpClient.HttpClient,
434 HttpClient.make((request) =>
435 Effect.sync(() => {
436 harness.requests.push(request);
437 }).pipe(
438 Effect.andThen(harness.onRequest?.(request) ?? Effect.void),
439 Effect.andThen(
440 harness.respondEffect ??
441 Effect.sync(() => (harness.respond ?? (() => Response.json({ ok: true })))()),
442 ),
443 Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
444 ),
445 ),
446 ),
447 // The release consults the launcher state file under the configured
448 // baseDir, so every harness run gets a scoped temp baseDir.
449 Effect.provide(
450 ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
451 Layer.provideMerge(NodeServices.layer),
452 ),
453 ),
454 Effect.scoped,
455 );
456​
457 // The persisted state of a CLI-managed link whose tunnel is releasable.
458 const managedLinkSecrets = [
459 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
460 [CLOUD_ENDPOINT_CONFIRMED_ORIGIN, "confirmed-origin"],
461 [RELAY_URL_SECRET, "https://relay.example.test"],
462 [CLOUD_CLI_DESIRED_LINK_SECRET, "managed"],
463 ] as const;
464​
465 it.effect("does not recreate a link that was unlinked while startup registration retried", () => {
466 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
467 const applyConfigCalls: Array<unknown> = [];
468 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
469​
470 return Effect.gen(function* () {
471 // Registration started while this marker existed. Unlink removes it
472 // before startup receives the relay's final not_linked response.
473 values.delete(CLOUD_CLI_DESIRED_LINK_SECRET);
474​
475 expect(yield* reconcileDesiredCloudLinkIfStillDesired("http://127.0.0.1:3773")).toBeNull();
476 expect(requests).toEqual([]);
477 expect(applyConfigCalls).toEqual([]);
478 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
479 });
480​
481 it.effect("stops the connector, releases the relay tunnel, and drops the dead token", () => {
482 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
483 const applyConfigCalls: Array<unknown> = [];
484 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
485​
486 return Effect.gen(function* () {
487 const released = yield* releaseManagedTunnelOnShutdown();
488​
489 expect(released).toBe(true);
490 expect(applyConfigCalls).toEqual([null]);
491 expect(requests).toHaveLength(1);
492 const request = requests[0]!;
493 expect(request.method).toBe("DELETE");
494 expect(request.url).toBe(
495 "https://relay.example.test/v1/client/environment-links/env_123/tunnel",
496 );
497 expect(request.headers.authorization).toBe("Bearer cli-access-token");
498 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
499 expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false);
500 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
501 });
502​
503 it.effect("does nothing for links without a stored managed tunnel runtime config", () => {
504 const { store } = makeMemorySecretStore();
505 const applyConfigCalls: Array<unknown> = [];
506 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
507​
508 return Effect.gen(function* () {
509 const released = yield* releaseManagedTunnelOnShutdown();
510​
511 expect(released).toBe(false);
512 expect(applyConfigCalls).toEqual([]);
513 expect(requests).toEqual([]);
514 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
515 });
516​
517 it.effect("leaves the tunnel of a web/mobile-installed link untouched", () => {
518 // A managed runtime config without a CLI-desired link: the environment was
519 // linked by a web/mobile client, and nothing re-provisions the tunnel on
520 // the next boot, so shutdown must not release it.
521 const { store, values } = makeMemorySecretStore([
522 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
523 [RELAY_URL_SECRET, "https://relay.example.test"],
524 ]);
525 const applyConfigCalls: Array<unknown> = [];
526 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
527​
528 return Effect.gen(function* () {
529 const released = yield* releaseManagedTunnelOnShutdown();
530​
531 expect(released).toBe(false);
532 expect(applyConfigCalls).toEqual([]);
533 expect(requests).toEqual([]);
534 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
535 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
536 });
537​
538 it.effect("leaves the tunnel of a publish-only desired link untouched", () => {
539 const { store, values } = makeMemorySecretStore([
540 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
541 [RELAY_URL_SECRET, "https://relay.example.test"],
542 [CLOUD_CLI_DESIRED_LINK_SECRET, "publish_only"],
543 ]);
544 const applyConfigCalls: Array<unknown> = [];
545 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
546​
547 return Effect.gen(function* () {
548 const released = yield* releaseManagedTunnelOnShutdown();
549​
550 expect(released).toBe(false);
551 expect(applyConfigCalls).toEqual([]);
552 expect(requests).toEqual([]);
553 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
554 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
555 });
556​
557 it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
558 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
559 const applyConfigCalls: Array<unknown> = [];
560 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
561​
562 return Effect.gen(function* () {
563 yield* writeLauncherState({
564 id: "update-1",
565 fromVersion: "0.0.30",
566 targetVersion: "0.0.31",
567 dbPath: "/tmp/state.sqlite",
568 status: "pending",
569 });
570​
571 const released = yield* releaseManagedTunnelOnShutdown();
572​
573 // The launcher restarts a server immediately, so the tunnel is not
574 // orphaned; keeping it avoids the hostname route re-propagation that
575 // dominates update downtime. The stored config must survive so the
576 // next boot respawns the connector against the same tunnel.
577 expect(released).toBe(false);
578 expect(applyConfigCalls).toEqual([]);
579 expect(requests).toEqual([]);
580 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
581 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
582 });
583​
584 it.effect("keeps the tunnel once when the desktop app restarts it for an update", () => {
585 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
586 const applyConfigCalls: Array<unknown> = [];
587 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
588​
589 return Effect.gen(function* () {
590 yield* TestClock.setTime(yield* writeDesktopUpdateRestartMarker);
591​
592 expect(yield* releaseManagedTunnelOnShutdown()).toBe(false);
593 expect(requests).toEqual([]);
594 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
595​
596 // The shutdown consumed the marker, so a later quit releases the tunnel.
597 expect(yield* releaseManagedTunnelOnShutdown()).toBe(true);
598 expect(requests).toHaveLength(1);
599 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
600 });
601​
602 it.effect("releases the tunnel when the desktop update marker is stale", () => {
603 const { store } = makeMemorySecretStore(managedLinkSecrets);
604 const applyConfigCalls: Array<unknown> = [];
605 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
606​
607 return Effect.gen(function* () {
608 const writtenAt = yield* writeDesktopUpdateRestartMarker;
609 yield* TestClock.setTime(writtenAt + Duration.toMillis(Duration.minutes(2)));
610​
611 expect(yield* releaseManagedTunnelOnShutdown()).toBe(true);
612 expect(requests).toHaveLength(1);
613 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
614 });
615​
616 it.effect("still releases a pending update when the launcher is stopping", () => {
617 // `t3 service uninstall` or `systemctl stop` during the pending window:
618 // the launcher writes its stop marker before signalling the child, so no
619 // replacement server is coming and the tunnel must not be kept.
620 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
621 const applyConfigCalls: Array<unknown> = [];
622 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
623​
624 return Effect.gen(function* () {
625 yield* writeLauncherState({
626 id: "update-1",
627 fromVersion: "0.0.30",
628 targetVersion: "0.0.31",
629 dbPath: "/tmp/state.sqlite",
630 status: "pending",
631 });
632 const fs = yield* FileSystem.FileSystem;
633 const path = yield* Path.Path;
634 const config = yield* ServerConfigModule.ServerConfig;
635 yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
636​
637 expect(yield* pendingServiceUpdateExists).toBe(true);
638 const released = yield* releaseManagedTunnelOnShutdown();
639​
640 expect(released).toBe(true);
641 expect(requests).toHaveLength(1);
642 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
643 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
644 });
645​
646 it.effect("still releases when the recorded update already settled", () => {
647 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
648 const applyConfigCalls: Array<unknown> = [];
649 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
650​
651 return Effect.gen(function* () {
652 yield* writeLauncherState({
653 id: "update-1",
654 fromVersion: "0.0.30",
655 targetVersion: "0.0.31",
656 status: "committed",
657 });
658​
659 const released = yield* releaseManagedTunnelOnShutdown();
660​
661 expect(released).toBe(true);
662 expect(requests).toHaveLength(1);
663 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
664 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
665 });
666​
667 it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
668 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
669 const applyConfigCalls: Array<unknown> = [];
670 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
671 const freshConfig = new TextEncoder().encode("fresh-runtime-config");
672​
673 return Effect.gen(function* () {
674 const released = yield* releaseManagedTunnelOnShutdown();
675​
676 expect(released).toBe(true);
677 // The finalizer only drops the config it released; the one written by
678 // the restarted process while the DELETE was in flight stays.
679 expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
680 }).pipe(
681 provideReleaseHarness({
682 store,
683 applyConfigCalls,
684 requests,
685 respond: () => {
686 // A restarted process reconciled and stored a fresh connector config
687 // while this shutdown's release request was in flight.
688 values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig);
689 return Response.json({ ok: true });
690 },
691 }),
692 );
693 });
694​
695 it.effect("keeps the stored connector token when the relay skipped the release", () => {
696 // ok:false means a concurrent provision owns the recorded tunnel, so the
697 // stored runtime config (possibly freshly written by that provision) must
698 // survive.
699 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
700 const applyConfigCalls: Array<unknown> = [];
701 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
702​
703 return Effect.gen(function* () {
704 const released = yield* releaseManagedTunnelOnShutdown();
705​
706 expect(released).toBe(false);
707 expect(requests).toHaveLength(1);
708 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
709 }).pipe(
710 provideReleaseHarness({
711 store,
712 applyConfigCalls,
713 requests,
714 respond: () => Response.json({ ok: false }),
715 }),
716 );
717 });
718​
719 it.effect("keeps the stored connector token when the relay release request fails", () => {
720 const { store, values } = makeMemorySecretStore(managedLinkSecrets);
721 const applyConfigCalls: Array<unknown> = [];
722 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
723​
724 return Effect.gen(function* () {
725 const result = yield* Effect.result(releaseManagedTunnelOnShutdown());
726​
727 expect(result._tag).toBe("Failure");
728 expect(requests).toHaveLength(1);
729 // The tunnel still exists, so the stored token stays valid across the
730 // restart and the next boot can bring the connector back immediately.
731 expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
732 }).pipe(
733 provideReleaseHarness({
734 store,
735 applyConfigCalls,
736 requests,
737 respond: () => Response.json({ ok: false }, { status: 503 }),
738 }),
739 );
740 });
741​
742 it.effect("registers an existing tunnel and starts the confirmed connector", () => {
743 const { store } = makeMemorySecretStore([
744 [
745 CLOUD_ENDPOINT_RUNTIME_CONFIG,
746 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
747 ],
748 [RELAY_URL_SECRET, "https://relay.example.test"],
749 [CLOUD_LINKED_USER_ID, "user-123"],
750 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
751 ]);
752 const applyConfigCalls: Array<unknown> = [];
753 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
754​
755 return Effect.gen(function* () {
756 expect(yield* registerManagedCloudTunnelRecovery("http://127.0.0.1:3773")).toMatchObject({
757 status: "ready",
758 });
759 expect(requests).toHaveLength(1);
760 expect(requests[0]?.method).toBe("POST");
761 expect(requests[0]?.url).toBe(
762 "https://relay.example.test/v1/environments/env_123/tunnel/recovery",
763 );
764 expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
765 const body = requests[0]?.body;
766 expect(body?._tag).toBe("Uint8Array");
767 if (body?._tag === "Uint8Array") {
768 expect(
769 yield* decodeManagedTunnelRecoveryRegistration(new TextDecoder().decode(body.body)),
770 ).toMatchObject({
771 cloudUserId: "user-123",
772 tunnelId: "existing-tunnel",
773 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
774 });
775 }
776 expect(applyConfigCalls).toHaveLength(1);
777 }).pipe(
778 provideReleaseHarness({
779 store,
780 applyConfigCalls,
781 requests,
782 respond: () => Response.json({ status: "ready" }),
783 }),
784 );
785 });
786​
787 it.effect("reconciles a changed port after a relay outage outlasts the startup fallback", () => {
788 const config = {
789 providerKind: "cloudflare_tunnel" as const,
790 connectorToken: "existing-token",
791 tunnelId: "existing-tunnel",
792 };
793 const { store } = makeMemorySecretStore([
794 [CLOUD_ENDPOINT_RUNTIME_CONFIG, JSON.stringify(config)],
795 [
796 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
797 JSON.stringify({
798 config,
799 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
800 }),
801 ],
802 [RELAY_URL_SECRET, "https://relay.example.test"],
803 [CLOUD_LINKED_USER_ID, "user-123"],
804 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
805 ]);
806 const applyConfigCalls: Array<unknown> = [];
807 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
808 let relayAvailable = false;
809 const localOrigin = "http://127.0.0.1:4884";
810​
811 return Effect.gen(function* () {
812 const fallbackStarted = yield* Deferred.make<void>();
813 const firstFailure = yield* Deferred.make<void>();
814 expect(yield* startManagedCloudTunnelIfOriginConfirmed(localOrigin)).toBe(false);
815 const registration = yield* Effect.forkChild(
816 retryManagedTunnelRegistration(
817 registerManagedCloudTunnelRecovery(localOrigin).pipe(
818 Effect.tapError(() => Deferred.succeed(firstFailure, undefined)),
819 ),
820 shouldRetryCloudLink,
821 startManagedCloudTunnelIfOriginConfirmed(localOrigin, {
822 requireConfirmedOrigin: false,
823 }).pipe(
824 Effect.orDie,
825 Effect.tap((started) => {
826 expect(started).toBe(true);
827 return Deferred.succeed(fallbackStarted, undefined);
828 }),
829 Effect.asVoid,
830 ),
831 ),
832 { startImmediately: true },
833 );
834 yield* Deferred.await(firstFailure);
835 yield* TestClock.adjust("15 minutes");
836 yield* Effect.raceFirst(
837 Deferred.await(fallbackStarted),
838 Fiber.join(registration).pipe(
839 Effect.andThen(Effect.die("Registration ended before starting the fallback")),
840 ),
841 );
842 expect(applyConfigCalls).toEqual([config]);
843 const attemptsBeforeRecovery = requests.length;
844​
845 relayAvailable = true;
846 yield* TestClock.adjust("1 minute");
847 expect(yield* Fiber.join(registration)).toMatchObject({ status: "ready" });
848 expect(requests.length).toBeGreaterThan(attemptsBeforeRecovery);
849 const marker = yield* store.get(CLOUD_ENDPOINT_CONFIRMED_ORIGIN);
850 expect(Option.isSome(marker)).toBe(true);
851 if (Option.isSome(marker)) {
852 expect(
853 Option.getOrThrow(decodeConfirmedOrigin(new TextDecoder().decode(marker.value))),
854 ).toEqual({
855 config,
856 origin: { localHttpHost: "127.0.0.1", localHttpPort: 4884 },
857 });
858 }
859 }).pipe(
860 provideReleaseHarness({
861 store,
862 applyConfigCalls,
863 requests,
864 respond: () =>
865 relayAvailable
866 ? Response.json({ status: "ready" })
867 : Response.json({ message: "relay unavailable" }, { status: 503 }),
868 }),
869 );
870 });
871​
872 it.effect(
873 "starts a connector with a marker for the current origin without contacting relay",
874 () => {
875 const configJson =
876 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}';
877 const config = {
878 providerKind: "cloudflare_tunnel" as const,
879 connectorToken: "existing-token",
880 tunnelId: "existing-tunnel",
881 };
882 const { store } = makeMemorySecretStore([
883 [CLOUD_ENDPOINT_RUNTIME_CONFIG, configJson],
884 [
885 CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
886 `{"config":${configJson},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}`,
887 ],
888 ]);
889 const applyConfigCalls: Array<unknown> = [];
890 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
891​
892 return Effect.gen(function* () {
893 expect(yield* startManagedCloudTunnelIfOriginConfirmed("http://127.0.0.1:3773")).toBe(true);
894 expect(applyConfigCalls).toEqual([config]);
895 expect(requests).toEqual([]);
896 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
897 },
898 );
899​
900 it.effect.each([
901 { name: "missing", marker: undefined, origin: "http://127.0.0.1:3773" },
902 {
903 name: "stale",
904 marker:
905 '{"config":{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"},"origin":{"localHttpHost":"127.0.0.1","localHttpPort":3773}}',
906 origin: "http://127.0.0.1:4884",
907 },
908 ])("does not start a connector with a $name origin marker", ({ marker, origin }) => {
909 const entries: Array<readonly [string, string]> = [
910 [
911 CLOUD_ENDPOINT_RUNTIME_CONFIG,
912 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}',
913 ],
914 ];
915 if (marker !== undefined) entries.push([CLOUD_ENDPOINT_CONFIRMED_ORIGIN, marker]);
916 const { store } = makeMemorySecretStore(entries);
917 const applyConfigCalls: Array<unknown> = [];
918 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
919​
920 return Effect.gen(function* () {
921 expect(yield* startManagedCloudTunnelIfOriginConfirmed(origin)).toBe(false);
922 expect(applyConfigCalls).toEqual([]);
923 expect(requests).toEqual([]);
924 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
925 });
926​
927 it.effect(
928 "starts the stored connector without a marker when confirmation is not required",
929 () => {
930 const config = {
931 providerKind: "cloudflare_tunnel" as const,
932 connectorToken: "existing-token",
933 tunnelId: "existing-tunnel",
934 };
935 const { store } = makeMemorySecretStore([
936 [CLOUD_ENDPOINT_RUNTIME_CONFIG, JSON.stringify(config)],
937 ]);
938 const applyConfigCalls: Array<unknown> = [];
939 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
940​
941 return Effect.gen(function* () {
942 expect(
943 yield* startManagedCloudTunnelIfOriginConfirmed("http://127.0.0.1:3773", {
944 requireConfirmedOrigin: false,
945 }),
946 ).toBe(true);
947 expect(applyConfigCalls).toEqual([config]);
948 expect(requests).toEqual([]);
949 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
950 },
951 );
952​
953 it.effect.each(["replaced", "removed"] as const)(
954 "does not activate a tunnel when its runtime config is %s during registration",
955 (mutation) => {
956 const originalConfig =
957 '{"providerKind":"cloudflare_tunnel","connectorToken":"existing-token","tunnelId":"existing-tunnel"}';
958 const { store, values } = makeMemorySecretStore([
959 [CLOUD_ENDPOINT_RUNTIME_CONFIG, originalConfig],
960 [RELAY_URL_SECRET, "https://relay.example.test"],
961 [CLOUD_LINKED_USER_ID, "user-123"],
962 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
963 ]);
964 const applyConfigCalls: Array<unknown> = [];
965 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
966​
967 return Effect.gen(function* () {
968 expect(yield* registerManagedCloudTunnelRecovery("http://127.0.0.1:3773")).toEqual({
969 status: "superseded",
970 });
971 expect(applyConfigCalls).toEqual([]);
972 expect(values.has(CLOUD_ENDPOINT_CONFIRMED_ORIGIN)).toBe(false);
973 }).pipe(
974 provideReleaseHarness({
975 store,
976 applyConfigCalls,
977 requests,
978 respond: () => {
979 if (mutation === "replaced") {
980 values.set(
981 CLOUD_ENDPOINT_RUNTIME_CONFIG,
982 new TextEncoder().encode(
983 '{"providerKind":"cloudflare_tunnel","connectorToken":"fresh-token","tunnelId":"fresh-tunnel"}',
984 ),
985 );
986 } else {
987 values.delete(CLOUD_ENDPOINT_RUNTIME_CONFIG);
988 }
989 return Response.json({ status: "ready" });
990 },
991 }),
992 );
993 },
994 );
995​
996 it.effect("requests startup recovery for a legacy config without a recorded tunnel ID", () => {
997 const { store } = makeMemorySecretStore([
998 [
999 CLOUD_ENDPOINT_RUNTIME_CONFIG,
1000 '{"providerKind":"cloudflare_tunnel","connectorToken":"token"}',
1001 ],
1002 [RELAY_URL_SECRET, "https://relay.example.test"],
1003 [CLOUD_LINKED_USER_ID, "user-123"],
1004 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1005 ]);
1006 const applyConfigCalls: Array<unknown> = [];
1007 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1008​
1009 return Effect.gen(function* () {
1010 const registration = yield* registerManagedCloudTunnelRecovery("http://127.0.0.1:3773");
1011 expect(registration).toEqual({
1012 status: "recovery_required",
1013 config: { providerKind: "cloudflare_tunnel", connectorToken: "token" },
1014 });
1015 expect(
1016 managedTunnelStartupAction({
1017 wantsCliLink: false,
1018 registration,
1019 }),
1020 ).toEqual({
1021 action: "request_recovery",
1022 config: { providerKind: "cloudflare_tunnel", connectorToken: "token" },
1023 });
1024 expect(requests).toEqual([]);
1025 expect(applyConfigCalls).toEqual([]);
1026 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
1027 });
1028​
1029 it.effect("recovers a web-linked tunnel with its environment credential", () => {
1030 const oldConfig =
1031 '{"providerKind":"cloudflare_tunnel","connectorToken":"old-token","tunnelId":"old-tunnel"}';
1032 const nextConfig = {
1033 providerKind: "cloudflare_tunnel",
1034 connectorToken: "new-token",
1035 tunnelId: "new-tunnel",
1036 } as const;
1037 const { store, values } = makeMemorySecretStore([
1038 [CLOUD_ENDPOINT_RUNTIME_CONFIG, oldConfig],
1039 [RELAY_URL_SECRET, "https://relay.example.test"],
1040 [CLOUD_LINKED_USER_ID, "user-123"],
1041 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1042 ]);
1043 const applyConfigCalls: Array<unknown> = [];
1044 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1045​
1046 return Effect.gen(function* () {
1047 expect(yield* recoverManagedCloudTunnel("http://127.0.0.1:3773")).toBe(true);
1048 expect(requests).toHaveLength(1);
1049 expect(requests[0]?.method).toBe("POST");
1050 expect(requests[0]?.url).toBe("https://relay.example.test/v1/environments/env_123/tunnel");
1051 expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
1052 expect(applyConfigCalls).toEqual([nextConfig]);
1053 expect(
1054 Option.getOrNull(
1055 decodeRuntimeConfig(new TextDecoder().decode(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG))),
1056 ),
1057 ).toEqual(nextConfig);
1058 }).pipe(
1059 provideReleaseHarness({
1060 store,
1061 applyConfigCalls,
1062 requests,
1063 respond: () =>
1064 Response.json({
1065 endpoint: {
1066 httpBaseUrl: "https://environment.example.test/",
1067 wsBaseUrl: "wss://environment.example.test/ws",
1068 providerKind: "cloudflare_tunnel",
1069 },
1070 endpointRuntime: nextConfig,
1071 }),
1072 }),
1073 );
1074 });
1075​
1076 it.effect("allows managed tunnel provisioning to take longer than ten seconds", () =>
1077 Effect.gen(function* () {
1078 const oldConfig =
1079 '{"providerKind":"cloudflare_tunnel","connectorToken":"old-token","tunnelId":"old-tunnel"}';
1080 const nextConfig = {
1081 providerKind: "cloudflare_tunnel" as const,
1082 connectorToken: "new-token",
1083 tunnelId: "new-tunnel",
1084 };
1085 const { store } = makeMemorySecretStore([
1086 [CLOUD_ENDPOINT_RUNTIME_CONFIG, oldConfig],
1087 [RELAY_URL_SECRET, "https://relay.example.test"],
1088 [CLOUD_LINKED_USER_ID, "user-123"],
1089 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1090 ]);
1091 const applyConfigCalls: Array<unknown> = [];
1092 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1093 const requestStarted = yield* Deferred.make<void>();
1094 const response = yield* Deferred.make<Response>();
1095 const recovery = yield* recoverManagedCloudTunnel("http://127.0.0.1:3773").pipe(
1096 provideReleaseHarness({
1097 store,
1098 applyConfigCalls,
1099 requests,
1100 onRequest: () => Deferred.succeed(requestStarted, undefined),
1101 respondEffect: Deferred.await(response),
1102 }),
1103 Effect.forkChild({ startImmediately: true }),
1104 );
1105​
1106 yield* Deferred.await(requestStarted);
1107 expect(requests).toHaveLength(1);
1108 yield* TestClock.adjust("11 seconds");
1109 yield* Effect.yieldNow;
1110 yield* Deferred.succeed(
1111 response,
1112 Response.json({
1113 endpoint: {
1114 httpBaseUrl: "https://environment.example.test/",
1115 wsBaseUrl: "wss://environment.example.test/ws",
1116 providerKind: "cloudflare_tunnel",
1117 },
1118 endpointRuntime: nextConfig,
1119 }),
1120 );
1121​
1122 expect(yield* Fiber.join(recovery)).toBe(true);
1123 expect(requests).toHaveLength(1);
1124 expect(applyConfigCalls).toEqual([nextConfig]);
1125 }),
1126 );
1127​
1128 it.effect("does not recover an environment without a managed tunnel credential", () => {
1129 const { store } = makeMemorySecretStore([
1130 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1131 [RELAY_URL_SECRET, "https://relay.example.test"],
1132 ]);
1133 const applyConfigCalls: Array<unknown> = [];
1134 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1135​
1136 return Effect.gen(function* () {
1137 expect(yield* recoverManagedCloudTunnel("http://127.0.0.1:3773")).toBe(false);
1138 expect(applyConfigCalls).toEqual([]);
1139 expect(requests).toEqual([]);
1140 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
1141 });
1142​
1143 it.effect("ignores recovery requests for a tunnel that has already been replaced", () => {
1144 const { store } = makeMemorySecretStore([
1146 CLOUD_ENDPOINT_RUNTIME_CONFIG,
1147 '{"providerKind":"cloudflare_tunnel","connectorToken":"current-token","tunnelId":"current-tunnel"}',
1148 ],
1149 [RELAY_URL_SECRET, "https://relay.example.test"],
1150 [CLOUD_LINKED_USER_ID, "user-123"],
1151 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1152 ]);
1153 const applyConfigCalls: Array<unknown> = [];
1154 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1155​
1156 return Effect.gen(function* () {
1157 expect(
1158 yield* recoverManagedCloudTunnel("http://127.0.0.1:3773", {
1159 providerKind: "cloudflare_tunnel",
1160 connectorToken: "old-token",
1161 tunnelId: "old-tunnel",
1162 }),
1163 ).toBe(false);
1164 expect(requests).toEqual([]);
1165 expect(applyConfigCalls).toEqual([]);
1166 }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
1167 });
1168​
1169 it.effect.each([
1170 { status: 401, errorTag: "EnvironmentHttpUnauthorizedError" },
1171 { status: 403, errorTag: "EnvironmentHttpForbiddenError" },
1172 { status: 409, errorTag: "EnvironmentHttpBadRequestError" },
1173 ])("preserves a permanent $status relay recovery failure", ({ status, errorTag }) => {
1174 const { store } = makeMemorySecretStore([
1175 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1176 [RELAY_URL_SECRET, "https://relay.example.test"],
1177 [CLOUD_LINKED_USER_ID, "user-123"],
1178 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1179 ]);
1180 const applyConfigCalls: Array<unknown> = [];
1181 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1182​
1183 return Effect.gen(function* () {
1184 const error = yield* Effect.flip(recoverManagedCloudTunnel("http://127.0.0.1:3773"));
1185​
1186 expect(error._tag).toBe(errorTag);
1187 expect(requests).toHaveLength(1);
1188 expect(applyConfigCalls).toEqual([]);
1189 }).pipe(
1190 provideReleaseHarness({
1191 store,
1192 applyConfigCalls,
1193 requests,
1194 respond: () => Response.json({}, { status }),
1195 }),
1196 );
1197 });
1198​
1199 it.effect("keeps a tunnel configuration replaced during recovery", () => {
1200 const { store, values } = makeMemorySecretStore([
1201 [CLOUD_ENDPOINT_RUNTIME_CONFIG, "old-config"],
1202 [RELAY_URL_SECRET, "https://relay.example.test"],
1203 [CLOUD_LINKED_USER_ID, "user-123"],
1204 [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
1205 ]);
1206 const applyConfigCalls: Array<unknown> = [];
1207 const requests: Array<HttpClientRequest.HttpClientRequest> = [];
1208 const freshConfig = new TextEncoder().encode("fresh-config");
1209​
1210 return Effect.gen(function* () {
1211 expect(yield* recoverManagedCloudTunnel("http://127.0.0.1:3773")).toBe(false);
1212 expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);
1213 expect(applyConfigCalls).toEqual([]);
1214 }).pipe(
1215 provideReleaseHarness({
1216 store,
1217 applyConfigCalls,
1218 requests,
1219 respond: () => {
1220 values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig);
1221 return Response.json({
1222 endpoint: {
1223 httpBaseUrl: "https://environment.example.test/",
1224 wsBaseUrl: "wss://environment.example.test/ws",
1225 providerKind: "cloudflare_tunnel",
1226 },
1227 endpointRuntime: {
1228 providerKind: "cloudflare_tunnel",
1229 connectorToken: "replacement-token",
1230 },
1231 });
1232 },
1233 }),
1234 );
1235 });
1236});
1237​
1238describe("link proof provider kinds", () => {
1239 const proofRequest = (
1240 providerKind: RelayLinkProofRequest["endpoint"]["providerKind"],
1241 ): RelayLinkProofRequest => ({
1242 challenge: "challenge",
1243 relayIssuer: "https://relay.example.test",
1244 endpoint: {
1245 httpBaseUrl: "http://127.0.0.1:7331",
1246 wsBaseUrl: "ws://127.0.0.1:7331",
1247 providerKind,
1248 },
1249 origin: { localHttpHost: "127.0.0.1", localHttpPort: 7331 },
1250 });
1251​
1252 it("accepts managed and manual endpoints but not t3_relay", () => {
1253 expect(isSupportedLinkProviderKind(proofRequest("cloudflare_tunnel"))).toBe(true);
1254 expect(isSupportedLinkProviderKind(proofRequest("manual"))).toBe(true);
1255 expect(isSupportedLinkProviderKind(proofRequest("t3_relay"))).toBe(false);
1256 });
1257​
1258 it("only claims the managed-tunnel scope for tunnel links", () => {
1259 expect(linkProofScopes(proofRequest("cloudflare_tunnel"))).toEqual([
1260 "agent_activity_notifications",
1261 "managed_tunnels",
1262 ]);
1263 expect(linkProofScopes(proofRequest("manual"))).toEqual(["agent_activity_notifications"]);
1264 });
1265});