Open History to see the last commit
1import { sha256 } from "@noble/hashes/sha2";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { describe, expect, it } from "@effect/vitest";
4import * as ConfigProvider from "effect/ConfigProvider";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Hex from "effect/encoding/Hex";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as PlatformError from "effect/PlatformError";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15import { HttpClient, HttpClientResponse } from "effect/http";
16import { ChildProcess, ChildProcessSpawner } from "effect/process";
17import * as HostProcess from "./HostProcess.ts";
18
19import * as RelayClient from "./relayClient.ts";
20
21// The suite runs the linux code path against the real filesystem, checking
22// POSIX exec bits that NTFS never reports; the win32 branch skips that check.
23const windowsHost = HostProcess.Platform.defaultValue() === "win32";
24
25const layerHostRuntime = (env: Record<string, string> = {}, platform: NodeJS.Platform = "linux") =>
26 Layer.mergeAll(
27 Layer.succeed(HostProcess.Platform, platform),
28 Layer.succeed(HostProcess.Architecture, "x64"),
29 Layer.succeed(HostProcess.Environment, env),
30 ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
31 );
32
33function makeHandle(exitCode = 0, output = "") {
34 const stdout = output ? Stream.make(new TextEncoder().encode(output)) : Stream.empty;
35 return ChildProcessSpawner.makeHandle({
36 pid: ChildProcessSpawner.ProcessId(100),
37 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
38 isRunning: Effect.succeed(false),
39 kill: () => Effect.void,
40 unref: Effect.succeed(Effect.void),
41 stdin: Sink.drain,
42 stdout,
43 stderr: Stream.empty,
44 all: stdout,
45 getInputFd: () => Sink.drain,
46 getOutputFd: () => Stream.empty,
47 });
48}
49
50const layerHttpClient = (bytes: Uint8Array) =>
51 Layer.succeed(
52 HttpClient.HttpClient,
53 HttpClient.make((request) =>
54 Effect.succeed(
55 HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)),
56 ),
57 ),
58 );
59
60// Records each request and never responds, simulating a wedged endpoint.
61const layerStalledHttpClient = (requests: Array<unknown>) =>
62 Layer.succeed(
63 HttpClient.HttpClient,
64 HttpClient.make((request) => {
65 requests.push(request);
66 return Effect.never;
67 }),
68 );
69
70// Answers `cloudflared version` with the version recorded for that path, which
71// defaults to the pinned release; tests change it to simulate other binaries.
72const layerSpawner = (commands: Array<string>, versions: Record<string, string> = {}) =>
73 Layer.succeed(
74 ChildProcessSpawner.ChildProcessSpawner,
75 ChildProcessSpawner.make((command) =>
76 Effect.sync(() => {
77 if (!ChildProcess.isStandardCommand(command)) {
78 commands.push("piped-command");
79 return makeHandle();
80 }
81 commands.push(command.command);
82 if (command.args[0] === "version") {
83 const version = versions[command.command] ?? RelayClient.CLOUDFLARED_VERSION;
84 return makeHandle(0, `cloudflared version ${version} (built 2026-01-01-00:00 UTC)\n`);
85 }
86 return makeHandle();
87 }),
88 ),
89 );
90
91const writeExecutable = (filePath: string, contents = "cloudflared") =>
92 Effect.gen(function* () {
93 const fileSystem = yield* FileSystem.FileSystem;
94 yield* fileSystem.makeDirectory(filePath.slice(0, filePath.lastIndexOf("/")), {
95 recursive: true,
96 });
97 yield* fileSystem.writeFileString(filePath, contents);
98 yield* fileSystem.chmod(filePath, 0o755);
99 });
100
101type RelayClientTestServices =
102 | Layer.Success<ReturnType<typeof layerHostRuntime> | typeof NodeServices.layer>
103 | HttpClient.HttpClient
104 | ChildProcessSpawner.ChildProcessSpawner;
105
106const managedPathFor = (baseDir: string, version: string) =>
107 `${baseDir}/tools/cloudflared/${version}/linux-x64/cloudflared`;
108
109const renameError = (code: string, path: string) =>
110 PlatformError.systemError({
111 _tag: code === "EBUSY" ? "Busy" : code === "EACCES" ? "PermissionDenied" : "Unknown",
112 module: "FileSystem",
113 method: "rename",
114 pathOrDescriptor: path,
115 cause: Object.assign(new Error(code), { code }),
116 });
117
118type InstallRename = "staging" | "activation";
119
120/**
121 * Fails the first `failures` staging or activation renames with `code`, as Windows does while
122 * another process holds the file. Staging moves the binary to a `.tmp` name beside its final path.
123 */
124const makeLockedRenames = (
125 fileSystem: FileSystem.FileSystem,
126 input: { readonly rename: InstallRename; readonly failures: number; readonly code: string },
127) =>
128 Effect.gen(function* () {
129 const firstAttempt = yield* Deferred.make<void>();
130 const renames = { attempts: 0 };
131 const locked = FileSystem.make({
132 ...fileSystem,
133 rename: (from, to) =>
134 Effect.suspend(() => {
135 if ((to.endsWith(".tmp") ? "staging" : "activation") !== input.rename) {
136 return fileSystem.rename(from, to);
137 }
138 renames.attempts += 1;
139 return renames.attempts <= input.failures
140 ? Deferred.succeed(firstAttempt, undefined).pipe(
141 Effect.andThen(Effect.fail(renameError(input.code, to))),
142 )
143 : fileSystem.rename(from, to);
144 }),
145 });
146 return { locked, renames, firstAttempt };
147 });
148
149const testBinary = new TextEncoder().encode("test-cloudflared-binary");
150const testReleaseAsset = {
151 url: "https://example.test/cloudflared",
152 sha256: Hex.encode(sha256(testBinary)),
153 archive: "binary",
154} as const;
155
156const layerInstallRuntime = (platform: NodeJS.Platform) =>
157 Layer.mergeAll(
158 NodeServices.layer,
159 layerHttpClient(testBinary),
160 layerSpawner([]),
161 layerHostRuntime({ PATH: "" }, platform),
162 );
163
164const managedDirectory = (baseDir: string, platform: NodeJS.Platform) =>
165 `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/${platform}-x64`;
166
167describe("RelayClient", () => {
168 it.effect("cancels a contended install without removing the other installer's lock", () =>
169 Effect.gen(function* () {
170 const fileSystem = yield* FileSystem.FileSystem;
171 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
172 const directory = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64`;
173 const lockPath = `${directory}/cloudflared.lock`;
174 yield* fileSystem.makeDirectory(directory, { recursive: true });
175 yield* fileSystem.writeFileString(lockPath, "other-installer");
176 const contended = yield* Deferred.make<void>();
177 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }).pipe(
178 Effect.provideService(FileSystem.FileSystem, {
179 ...fileSystem,
180 writeFileString: (path, contents, options) =>
181 fileSystem
182 .writeFileString(path, contents, options)
183 .pipe(
184 Effect.tapError(() =>
185 path === lockPath ? Deferred.succeed(contended, undefined) : Effect.void,
186 ),
187 ),
188 }),
189 );
190 const installing = yield* manager.install.pipe(Effect.forkChild);
191 yield* Deferred.await(contended);
192 yield* Fiber.interrupt(installing);
193 expect(yield* fileSystem.readFileString(lockPath)).toBe("other-installer");
194 }).pipe(
195 Effect.scoped,
196 Effect.provide(
197 Layer.mergeAll(
198 NodeServices.layer,
199 layerHttpClient(new Uint8Array()),
200 layerSpawner([]),
201 layerHostRuntime({ PATH: "" }),
202 ),
203 ),
204 ),
205 );
206
207 it.effect("releases the install lock when a download is cancelled", () =>
208 Effect.gen(function* () {
209 const fileSystem = yield* FileSystem.FileSystem;
210 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
211 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
212 const downloading = yield* Deferred.make<void>();
213 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
214 const installing = yield* manager
215 .installWithProgress((event) =>
216 event.type === "progress" && event.stage === "downloading"
217 ? Deferred.succeed(downloading, undefined).pipe(Effect.andThen(Effect.never))
218 : Effect.void,
219 )
220 .pipe(Effect.forkChild);
221 yield* Deferred.await(downloading);
222 expect(yield* fileSystem.exists(lockPath)).toBe(true);
223 yield* Fiber.interrupt(installing);
224 expect(yield* fileSystem.exists(lockPath)).toBe(false);
225 }).pipe(
226 Effect.scoped,
227 Effect.provide(
228 Layer.mergeAll(
229 NodeServices.layer,
230 layerHttpClient(new Uint8Array()),
231 layerSpawner([]),
232 layerHostRuntime({ PATH: "" }),
233 ),
234 ),
235 ),
236 );
237
238 it.effect.skipIf(windowsHost)("releases a lock acquired while installation is cancelled", () =>
239 Effect.gen(function* () {
240 const fileSystem = yield* FileSystem.FileSystem;
241 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
242 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
243 const acquired = yield* Deferred.make<void>();
244 const completeWrite = yield* Deferred.make<void>();
245 let pauseWrite = true;
246 const manager = yield* RelayClient.makeCloudflaredRelayClient({
247 baseDir,
248 releaseAsset: {
249 url: "https://example.test/cloudflared",
250 sha256: Hex.encode(sha256(new TextEncoder().encode("test-binary"))),
251 archive: "binary",
252 },
253 }).pipe(
254 Effect.provideService(FileSystem.FileSystem, {
255 ...fileSystem,
256 writeFileString: (path, contents, options) =>
257 fileSystem
258 .writeFileString(path, contents, options)
259 .pipe(
260 Effect.tap(() =>
261 path === lockPath && pauseWrite
262 ? Deferred.succeed(acquired, undefined).pipe(
263 Effect.andThen(Deferred.await(completeWrite)),
264 )
265 : Effect.void,
266 ),
267 ),
268 }),
269 );
270
271 const installing = yield* manager.install.pipe(Effect.forkChild);
272 yield* Deferred.await(acquired);
273 const cancelling = yield* Fiber.interrupt(installing).pipe(
274 Effect.forkChild({ startImmediately: true }),
275 );
276 yield* Deferred.succeed(completeWrite, undefined);
277 yield* Fiber.join(cancelling);
278 expect(yield* fileSystem.exists(lockPath)).toBe(false);
279
280 pauseWrite = false;
281 expect(yield* manager.install).toMatchObject({ status: "available" });
282 expect(yield* fileSystem.exists(lockPath)).toBe(false);
283 }).pipe(
284 Effect.scoped,
285 Effect.provide(
286 Layer.mergeAll(
287 NodeServices.layer,
288 layerHttpClient(new TextEncoder().encode("test-binary")),
289 layerSpawner([]),
290 layerHostRuntime({ PATH: "" }),
291 ),
292 ),
293 ),
294 );
295 it.effect.skipIf(windowsHost)(
296 "resolves explicit overrides before managed and PATH executables",
297 () =>
298 Effect.gen(function* () {
299 const fileSystem = yield* FileSystem.FileSystem;
300 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
301 prefix: "t3-cloudflared-test-",
302 });
303 const overridePath = `${baseDir}/override-cloudflared`;
304 yield* fileSystem.writeFileString(overridePath, "override");
305 yield* fileSystem.chmod(overridePath, 0o755);
306 const manager = yield* RelayClient.makeCloudflaredRelayClient({
307 baseDir,
308 });
309
310 expect(
311 yield* manager.resolve.pipe(
312 Effect.provideService(
313 ConfigProvider.ConfigProvider,
314 ConfigProvider.fromEnv({
315 env: { PATH: "", T3CODE_CLOUDFLARED_PATH: overridePath },
316 }),
317 ),
318 ),
319 ).toEqual({
320 status: "available",
321 executablePath: overridePath,
322 source: "override",
323 version: RelayClient.CLOUDFLARED_VERSION,
324 });
325 }).pipe(
326 Effect.scoped,
327 Effect.provide(
328 Layer.mergeAll(
329 NodeServices.layer,
330 layerHttpClient(new Uint8Array()),
331 layerSpawner([]),
332 layerHostRuntime(),
333 ),
334 ),
335 ),
336 );
337
338 it.effect.skipIf(windowsHost)(
339 "downloads, verifies, validates, and atomically installs the managed executable",
340 () =>
341 Effect.gen(function* () {
342 const fileSystem = yield* FileSystem.FileSystem;
343 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
344 prefix: "t3-cloudflared-test-",
345 });
346 const bytes = new TextEncoder().encode("test-cloudflared-binary");
347 const manager = yield* RelayClient.makeCloudflaredRelayClient({
348 baseDir,
349 releaseAsset: {
350 url: "https://example.test/cloudflared",
351 sha256: Hex.encode(sha256(bytes)),
352 archive: "binary",
353 },
354 });
355
356 const progress: Array<string> = [];
357 const installed = yield* manager.installWithProgress((event) =>
358 Effect.sync(() => {
359 if (event.type === "progress") {
360 progress.push(event.stage);
361 }
362 }),
363 );
364 const managedPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared`;
365 expect(installed).toEqual({
366 status: "available",
367 executablePath: managedPath,
368 source: "managed",
369 version: RelayClient.CLOUDFLARED_VERSION,
370 });
371 expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe(
372 "test-cloudflared-binary",
373 );
374 expect(progress).toEqual([
375 "checking",
376 "waiting_for_lock",
377 "downloading",
378 "verifying",
379 "installing",
380 "validating",
381 "activating",
382 ]);
383 expect(yield* manager.resolve).toEqual(installed);
384 }).pipe(
385 Effect.scoped,
386 Effect.provide(
387 Layer.mergeAll(
388 NodeServices.layer,
389 layerHttpClient(new TextEncoder().encode("test-cloudflared-binary")),
390 layerSpawner([]),
391 layerHostRuntime(),
392 ),
393 ),
394 ),
395 );
396
397 it.effect("rejects downloads whose checksum does not match the pinned manifest", () =>
398 Effect.gen(function* () {
399 const fileSystem = yield* FileSystem.FileSystem;
400 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
401 prefix: "t3-cloudflared-test-",
402 });
403 const manager = yield* RelayClient.makeCloudflaredRelayClient({
404 baseDir,
405 releaseAsset: {
406 url: "https://example.test/cloudflared",
407 sha256: Hex.encode(sha256(new TextEncoder().encode("expected"))),
408 archive: "binary",
409 },
410 });
411
412 const error = yield* manager.install.pipe(Effect.flip);
413 expect(error).toBeInstanceOf(RelayClient.RelayClientInstallError);
414 expect(error.reason).toBe("invalid_checksum");
415 expect(
416 yield* fileSystem.exists(
417 `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`,
418 ),
419 ).toBe(false);
420 }).pipe(
421 Effect.scoped,
422 Effect.provide(
423 Layer.mergeAll(
424 NodeServices.layer,
425 layerHttpClient(new TextEncoder().encode("tampered")),
426 layerSpawner([]),
427 layerHostRuntime(),
428 ),
429 ),
430 ),
431 );
432
433 it.effect.skipIf(windowsHost)("serializes concurrent installs within one runtime", () => {
434 const commands: Array<string> = [];
435 const bytes = new TextEncoder().encode("test-cloudflared-binary");
436 return Effect.gen(function* () {
437 const fileSystem = yield* FileSystem.FileSystem;
438 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
439 prefix: "t3-cloudflared-test-",
440 });
441 const manager = yield* RelayClient.makeCloudflaredRelayClient({
442 baseDir,
443 releaseAsset: {
444 url: "https://example.test/cloudflared",
445 sha256: Hex.encode(sha256(bytes)),
446 archive: "binary",
447 },
448 });
449
450 const [first, second] = yield* Effect.all([manager.install, manager.install], {
451 concurrency: "unbounded",
452 });
453 expect(second).toEqual(first);
454 // The first install validates the download once; the second, after waiting
455 // its turn, probes the activated binary and reuses it instead of downloading.
456 expect(commands).toHaveLength(2);
457 }).pipe(
458 Effect.scoped,
459 Effect.provide(
460 Layer.mergeAll(
461 NodeServices.layer,
462 layerHttpClient(bytes),
463 layerSpawner(commands),
464 layerHostRuntime(),
465 ),
466 ),
467 );
468 });
469
470 it.effect("observes hydrated PATH changes after the manager has been constructed", () => {
471 const platform = windowsHost ? "win32" : "linux";
472 const executableName = windowsHost ? "cloudflared.exe" : "cloudflared";
473 const configEnv = { PATH: "" };
474 const hostEnv = { PATH: "" };
475 return Effect.gen(function* () {
476 const fileSystem = yield* FileSystem.FileSystem;
477 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
478 prefix: "t3-cloudflared-test-",
479 });
480 const binDir = `${baseDir}/bin`;
481 const executablePath = `${binDir}/${executableName}`;
482 const resolvedExecutablePath = windowsHost
483 ? executablePath.replaceAll("/", "\\")
484 : executablePath;
485 const manager = yield* RelayClient.makeCloudflaredRelayClient({
486 baseDir,
487 });
488
489 const resolveWithStaleConfig = manager.resolve.pipe(
490 Effect.provideService(
491 ConfigProvider.ConfigProvider,
492 ConfigProvider.fromEnv({ env: configEnv }),
493 ),
494 Effect.provideService(HostProcess.Environment, hostEnv),
495 );
496
497 expect(yield* resolveWithStaleConfig).toEqual({
498 status: "missing",
499 version: RelayClient.CLOUDFLARED_VERSION,
500 });
501
502 yield* fileSystem.makeDirectory(binDir);
503 yield* fileSystem.writeFileString(executablePath, "cloudflared");
504 if (!windowsHost) yield* fileSystem.chmod(executablePath, 0o755);
505 hostEnv.PATH = binDir;
506
507 expect(yield* resolveWithStaleConfig).toEqual({
508 status: "available",
509 executablePath: resolvedExecutablePath,
510 source: "path",
511 version: RelayClient.CLOUDFLARED_VERSION,
512 });
513
514 const resolveWithOverride = manager.resolve.pipe(
515 Effect.provideService(
516 ConfigProvider.ConfigProvider,
517 ConfigProvider.fromEnv({
518 env: { PATH: "", T3CODE_CLOUDFLARED_PATH: executablePath },
519 }),
520 ),
521 Effect.provideService(HostProcess.Environment, { PATH: "" }),
522 );
523 expect(yield* resolveWithOverride).toEqual({
524 status: "available",
525 executablePath,
526 source: "override",
527 version: RelayClient.CLOUDFLARED_VERSION,
528 });
529 }).pipe(
530 Effect.scoped,
531 Effect.provide(
532 Layer.mergeAll(
533 NodeServices.layer,
534 layerHttpClient(new Uint8Array()),
535 layerSpawner([]),
536 layerHostRuntime(configEnv, platform),
537 ),
538 ),
539 );
540 });
541
542 describe("version selection", () => {
543 const run = <A, E>(
544 body: (baseDir: string) => Effect.Effect<A, E, RelayClientTestServices>,
545 options: { readonly versions?: Record<string, string> } = {},
546 ) =>
547 Effect.gen(function* () {
548 const fileSystem = yield* FileSystem.FileSystem;
549 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
550 prefix: "t3-cloudflared-test-",
551 });
552 return yield* body(baseDir);
553 }).pipe(
554 Effect.scoped,
555 Effect.provide(
556 Layer.mergeAll(
557 NodeServices.layer,
558 layerHttpClient(new Uint8Array()),
559 layerSpawner([], options.versions),
560 layerHostRuntime({ PATH: "" }),
561 ),
562 ),
563 );
564
565 it.effect.skipIf(windowsHost)("skips a PATH binary older than the minimum version", () => {
566 const versions: Record<string, string> = {};
567 return run(
568 (baseDir) =>
569 Effect.gen(function* () {
570 const oldPath = `${baseDir}/old/cloudflared`;
571 const newPath = `${baseDir}/new/cloudflared`;
572 yield* writeExecutable(oldPath);
573 yield* writeExecutable(newPath);
574 versions[oldPath] = "2023.8.2";
575 versions[newPath] = RelayClient.CLOUDFLARED_MIN_VERSION;
576 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
577 const env = { PATH: `${baseDir}/old:${baseDir}/new` };
578 expect(
579 yield* manager.resolve.pipe(
580 Effect.provideService(
581 ConfigProvider.ConfigProvider,
582 ConfigProvider.fromEnv({ env }),
583 ),
584 Effect.provideService(HostProcess.Environment, env),
585 ),
586 ).toEqual({
587 status: "available",
588 executablePath: newPath,
589 source: "path",
590 version: RelayClient.CLOUDFLARED_MIN_VERSION,
591 });
592 }),
593 { versions },
594 );
595 });
596
597 it.effect.skipIf(windowsHost)("reports an outdated override as missing", () => {
598 const versions: Record<string, string> = {};
599 return run(
600 (baseDir) =>
601 Effect.gen(function* () {
602 const overridePath = `${baseDir}/override/cloudflared`;
603 yield* writeExecutable(overridePath);
604 versions[overridePath] = "2025.6.0";
605 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
606 const env = { PATH: "", T3CODE_CLOUDFLARED_PATH: overridePath };
607 const withEnv = Effect.provideService(
608 ConfigProvider.ConfigProvider,
609 ConfigProvider.fromEnv({ env }),
610 );
611 expect(yield* manager.resolve.pipe(withEnv)).toEqual({
612 status: "missing",
613 version: RelayClient.CLOUDFLARED_VERSION,
614 });
615 const error = yield* manager.install.pipe(withEnv, Effect.flip);
616 expect(error.reason).toBe("override_missing");
617 }),
618 { versions },
619 );
620 });
621
622 it.effect.skipIf(windowsHost)(
623 "prefers the pinned release, then the newest older managed release, then PATH",
624 () => {
625 const versions: Record<string, string> = {};
626 return run(
627 (baseDir) =>
628 Effect.gen(function* () {
629 const fileSystem = yield* FileSystem.FileSystem;
630 const pathBinary = `${baseDir}/bin/cloudflared`;
631 const older = managedPathFor(baseDir, "2025.9.0");
632 const newer = managedPathFor(baseDir, "2026.1.0");
633 const pinned = managedPathFor(baseDir, RelayClient.CLOUDFLARED_VERSION);
634 // A newer server sharing this base dir owns this folder.
635 const newerServer = managedPathFor(baseDir, "2099.1.0");
636 versions[newerServer] = "2099.1.0";
637 yield* writeExecutable(newerServer);
638 versions[pathBinary] = "2026.9.3";
639 versions[older] = "2025.9.0";
640 versions[newer] = "2026.1.0";
641 yield* writeExecutable(pathBinary);
642 yield* writeExecutable(older);
643 yield* writeExecutable(newer);
644 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
645 const resolveWith = manager.resolve.pipe(
646 Effect.provideService(
647 ConfigProvider.ConfigProvider,
648 ConfigProvider.fromEnv({ env: { PATH: `${baseDir}/bin` } }),
649 ),
650 Effect.provideService(HostProcess.Environment, { PATH: `${baseDir}/bin` }),
651 );
652
653 expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.1.0" });
654
655 yield* writeExecutable(pinned);
656 expect(yield* resolveWith).toMatchObject({
657 executablePath: pinned,
658 source: "managed",
659 version: RelayClient.CLOUDFLARED_VERSION,
660 });
661
662 yield* manager.pruneManagedVersions;
663 expect(
664 (yield* fileSystem.readDirectory(`${baseDir}/tools/cloudflared`)).sort(),
665 ).toEqual(["2026.1.0", RelayClient.CLOUDFLARED_VERSION, "2099.1.0"]);
666
667 // The kept older release still outranks PATH; PATH is the last resort.
668 yield* fileSystem.remove(pinned);
669 expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.1.0" });
670 yield* fileSystem.remove(`${baseDir}/tools/cloudflared/2026.1.0`, {
671 recursive: true,
672 });
673 expect(yield* resolveWith).toMatchObject({ source: "path", version: "2026.9.3" });
674 }),
675 { versions },
676 );
677 },
678 );
679
680 it.effect.skipIf(windowsHost)(
681 "keeps a self-updated managed binary as a fallback but still installs the pin",
682 () => {
683 const versions: Record<string, string> = {};
684 return run(
685 (baseDir) =>
686 Effect.gen(function* () {
687 const pinned = managedPathFor(baseDir, RelayClient.CLOUDFLARED_VERSION);
688 versions[pinned] = "2026.9.3";
689 yield* writeExecutable(pinned);
690 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
691 const resolved = yield* manager.resolve;
692 expect(resolved).toEqual({
693 status: "available",
694 executablePath: pinned,
695 source: "managed",
696 version: "2026.9.3",
697 });
698 expect(
699 resolved.status === "available" && RelayClient.isPinnedManagedRelayClient(resolved),
700 ).toBe(false);
701 }),
702 { versions },
703 );
704 },
705 );
706 });
707
708 it("orders and parses cloudflared versions", () => {
709 expect(
710 RelayClient.parseCloudflaredVersionOutput(
711 "cloudflared version 2026.5.2 (built 2026-05-20-10:00 UTC)",
712 ),
713 ).toBe("2026.5.2");
714 expect(RelayClient.parseCloudflaredVersionOutput("Incorrect Usage")).toBeNull();
715 expect(RelayClient.compareCloudflaredVersions("2025.10.0", "2025.6.1")).toBeGreaterThan(0);
716 expect(RelayClient.compareCloudflaredVersions("2023.8.2", "2025.6.1")).toBeLessThan(0);
717 });
718
719 it.effect.each([
720 ["staging", "EBUSY"],
721 ["activation", "EACCES"],
722 ] as const)("retries %s on Windows while another process holds the binary", ([rename, code]) =>
723 Effect.gen(function* () {
724 const fileSystem = yield* FileSystem.FileSystem;
725 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
726 prefix: "t3-cloudflared-test-",
727 });
728 const { locked, renames, firstAttempt } = yield* makeLockedRenames(fileSystem, {
729 rename,
730 failures: 2,
731 code,
732 });
733 const manager = yield* RelayClient.makeCloudflaredRelayClient({
734 baseDir,
735 releaseAsset: testReleaseAsset,
736 }).pipe(Effect.provideService(FileSystem.FileSystem, locked));
737
738 const installing = yield* manager.install.pipe(Effect.forkChild);
739 yield* Deferred.await(firstAttempt);
740 yield* TestClock.adjust("1 second");
741 const installed = yield* Fiber.join(installing);
742
743 expect(renames.attempts).toBe(3);
744 expect(new TextDecoder().decode(yield* fileSystem.readFile(installed.executablePath))).toBe(
745 "test-cloudflared-binary",
746 );
747 expect(yield* fileSystem.readDirectory(managedDirectory(baseDir, "win32"))).toEqual([
748 "cloudflared.exe",
749 ]);
750 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("win32"))),
751 );
752
753 it.effect.each([
754 ["staging", "EPERM", "Could not stage the relay client."],
755 ["activation", "EBUSY", "Could not activate the relay client."],
756 ] as const)("gives up on a Windows %s lock that does not clear", ([rename, code, message]) =>
757 Effect.gen(function* () {
758 const fileSystem = yield* FileSystem.FileSystem;
759 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
760 prefix: "t3-cloudflared-test-",
761 });
762 const { locked, renames, firstAttempt } = yield* makeLockedRenames(fileSystem, {
763 rename,
764 failures: Infinity,
765 code,
766 });
767 const manager = yield* RelayClient.makeCloudflaredRelayClient({
768 baseDir,
769 releaseAsset: testReleaseAsset,
770 }).pipe(Effect.provideService(FileSystem.FileSystem, locked));
771
772 const installing = yield* manager.install.pipe(Effect.flip, Effect.forkChild);
773 yield* Deferred.await(firstAttempt);
774 yield* TestClock.adjust("1 minute");
775 const error = yield* Fiber.join(installing);
776
777 expect(error.message).toBe(message);
778 expect(renames.attempts).toBe(41);
779 // Nothing is installed, and the staged copy, download folder, and install lock are gone.
780 expect(yield* fileSystem.readDirectory(managedDirectory(baseDir, "win32"))).toEqual([]);
781 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("win32"))),
782 );
783
784 it.effect.each([
785 ["linux", "EBUSY"],
786 ["win32", "EXDEV"],
787 ] as const)("fails staging at once on %s for %s", ([platform, code]) =>
788 Effect.gen(function* () {
789 const fileSystem = yield* FileSystem.FileSystem;
790 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
791 prefix: "t3-cloudflared-test-",
792 });
793 const { locked, renames } = yield* makeLockedRenames(fileSystem, {
794 rename: "staging",
795 failures: Infinity,
796 code,
797 });
798 const manager = yield* RelayClient.makeCloudflaredRelayClient({
799 baseDir,
800 releaseAsset: testReleaseAsset,
801 }).pipe(Effect.provideService(FileSystem.FileSystem, locked));
802
803 const error = yield* manager.install.pipe(Effect.flip);
804
805 expect(error.message).toBe("Could not stage the relay client.");
806 expect(renames.attempts).toBe(1);
807 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime(platform))),
808 );
809
810 it.effect("fails a stalled download after the download timeout", () => {
811 const requests: Array<unknown> = [];
812 return Effect.gen(function* () {
813 const fileSystem = yield* FileSystem.FileSystem;
814 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
815 prefix: "t3-cloudflared-test-",
816 });
817 const manager = yield* RelayClient.makeCloudflaredRelayClient({
818 baseDir,
819 releaseAsset: {
820 url: "https://example.test/cloudflared",
821 sha256: "00".repeat(32),
822 archive: "binary",
823 },
824 });
825
826 const child = yield* Effect.forkChild(manager.install);
827 // Spin until the wedged download is in flight, so the clock
828 // adjustment below cannot run before the timeout is armed.
829 while (requests.length === 0) {
830 yield* Effect.yieldNow;
831 }
832 // The download timeout is 10 minutes; advance past it.
833 yield* TestClock.adjust("11 minutes");
834 const error = yield* Fiber.join(child).pipe(Effect.flip);
835 expect(error).toBeInstanceOf(RelayClient.RelayClientInstallError);
836 expect(error.reason).toBe("download_failed");
837 }).pipe(
838 Effect.scoped,
839 Effect.provide(
840 Layer.mergeAll(
841 NodeServices.layer,
842 layerStalledHttpClient(requests),
843 layerSpawner([]),
844 layerHostRuntime({ PATH: "" }),
845 ),
846 ),
847 );
848 });
849});