Open History to see the last commit
1import { sha256 } from "@noble/hashes/sha2";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { describe, expect, it } from "@effect/vitest";
5import * as Clock from "effect/Clock";
6import * as ConfigProvider from "effect/ConfigProvider";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as Hex from "effect/encoding/Hex";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as PlatformError from "effect/PlatformError";
15import * as Sink from "effect/Sink";
16import * as Stream from "effect/Stream";
17import * as TestClock from "effect/testing/TestClock";
18import { HttpClient, HttpClientResponse } from "effect/http";
19import { ChildProcess, ChildProcessSpawner } from "effect/process";
20import * as HostProcess from "./HostProcess.ts";
21
22import * as RelayClient from "./relayClient.ts";
23
24// POSIX exec-bit checks do not apply on NTFS.
25const windowsHost = HostProcess.Platform.defaultValue() === "win32";
26
27const layerHostRuntime = (env: Record<string, string> = {}, platform: NodeJS.Platform = "linux") =>
28 Layer.mergeAll(
29 Layer.succeed(HostProcess.Platform, platform),
30 Layer.succeed(HostProcess.Architecture, "x64"),
31 Layer.succeed(HostProcess.Environment, env),
32 ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
33 );
34
35function makeHandle(exitCode = 0, output = "") {
36 const stdout = output ? Stream.make(new TextEncoder().encode(output)) : Stream.empty;
37 return ChildProcessSpawner.makeHandle({
38 pid: ChildProcessSpawner.ProcessId(100),
39 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
40 isRunning: Effect.succeed(false),
41 kill: () => Effect.void,
42 unref: Effect.succeed(Effect.void),
43 stdin: Sink.drain,
44 stdout,
45 stderr: Stream.empty,
46 all: stdout,
47 getInputFd: () => Sink.drain,
48 getOutputFd: () => Stream.empty,
49 });
50}
51
52const layerHttpClient = (bytes: Uint8Array) =>
53 Layer.succeed(
54 HttpClient.HttpClient,
55 HttpClient.make((request) =>
56 Effect.succeed(
57 HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)),
58 ),
59 ),
60 );
61
62const layerSpawner = (commands: Array<string>, versions: Record<string, string> = {}) =>
63 Layer.succeed(
64 ChildProcessSpawner.ChildProcessSpawner,
65 ChildProcessSpawner.make((command) =>
66 Effect.sync(() => {
67 if (!ChildProcess.isStandardCommand(command)) {
68 commands.push("piped-command");
69 return makeHandle();
70 }
71 commands.push(command.command);
72 if (command.args[0] === "version") {
73 const version = versions[command.command] ?? RelayClient.CLOUDFLARED_VERSION;
74 return makeHandle(0, `cloudflared version ${version} (built 2026-01-01-00:00 UTC)\n`);
75 }
76 return makeHandle();
77 }),
78 ),
79 );
80
81const writeExecutable = (filePath: string, contents = "cloudflared") =>
82 Effect.gen(function* () {
83 const fileSystem = yield* FileSystem.FileSystem;
84 yield* fileSystem.makeDirectory(filePath.slice(0, filePath.lastIndexOf("/")), {
85 recursive: true,
86 });
87 yield* fileSystem.writeFileString(filePath, contents);
88 yield* fileSystem.chmod(filePath, 0o755);
89 });
90
91type RelayClientTestServices =
92 | Layer.Success<
93 ReturnType<typeof layerHostRuntime> | typeof NodeServices.layer | typeof NodeCrypto.layer
94 >
95 | HttpClient.HttpClient
96 | ChildProcessSpawner.ChildProcessSpawner;
97
98const managedPathFor = (baseDir: string, version: string) =>
99 `${baseDir}/tools/cloudflared/${version}/linux-x64/cloudflared`;
100
101const renameError = (code: string, path: string) =>
102 PlatformError.systemError({
103 _tag: code === "EBUSY" ? "Busy" : code === "EACCES" ? "PermissionDenied" : "Unknown",
104 module: "FileSystem",
105 method: "rename",
106 pathOrDescriptor: path,
107 cause: Object.assign(new Error(code), { code }),
108 });
109
110type InstallRename = "staging" | "activation";
111
112const makeLockedRenames = (
113 fileSystem: FileSystem.FileSystem,
114 input: { readonly rename: InstallRename; readonly failures: number; readonly code: string },
115) =>
116 Effect.gen(function* () {
117 const firstAttempt = yield* Deferred.make<void>();
118 const renames = { attempts: 0 };
119 const locked = FileSystem.make({
120 ...fileSystem,
121 rename: (from, to) =>
122 Effect.suspend(() => {
123 if ((to.endsWith(".tmp") ? "staging" : "activation") !== input.rename) {
124 return fileSystem.rename(from, to);
125 }
126 renames.attempts += 1;
127 return renames.attempts <= input.failures
128 ? Deferred.succeed(firstAttempt, undefined).pipe(
129 Effect.andThen(Effect.fail(renameError(input.code, to))),
130 )
131 : fileSystem.rename(from, to);
132 }),
133 });
134 return { locked, renames, firstAttempt };
135 });
136
137const testBinary = new TextEncoder().encode("test-cloudflared-binary");
138const testReleaseAsset = {
139 url: "https://example.test/cloudflared",
140 sha256: Hex.encode(sha256(testBinary)),
141 archive: "binary",
142} as const;
143
144const layerInstallRuntime = (platform: NodeJS.Platform) =>
145 Layer.mergeAll(
146 NodeServices.layer,
147 NodeCrypto.layer,
148 layerHttpClient(testBinary),
149 layerSpawner([]),
150 layerHostRuntime({ PATH: "" }, platform),
151 );
152
153describe("RelayClient", () => {
154 it.effect("cancels a contended install without removing the other installer's lock", () =>
155 Effect.gen(function* () {
156 const fileSystem = yield* FileSystem.FileSystem;
157 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
158 const directory = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64`;
159 const lockPath = `${directory}/cloudflared.lock`;
160 yield* fileSystem.makeDirectory(directory, { recursive: true });
161 yield* fileSystem.writeFileString(lockPath, "other-installer");
162 const contended = yield* Deferred.make<void>();
163 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }).pipe(
164 Effect.provideService(FileSystem.FileSystem, {
165 ...fileSystem,
166 rename: (from, to) =>
167 fileSystem
168 .rename(from, to)
169 .pipe(
170 Effect.tapError(() =>
171 to === lockPath ? Deferred.succeed(contended, undefined) : Effect.void,
172 ),
173 ),
174 }),
175 );
176 const installing = yield* manager.install.pipe(Effect.forkChild);
177 yield* Deferred.await(contended);
178 yield* Fiber.interrupt(installing);
179 expect(yield* fileSystem.readFileString(lockPath)).toBe("other-installer");
180 }).pipe(
181 Effect.scoped,
182 Effect.provide(
183 Layer.mergeAll(
184 NodeServices.layer,
185 NodeCrypto.layer,
186 layerHttpClient(new Uint8Array()),
187 layerSpawner([]),
188 layerHostRuntime({ PATH: "" }),
189 ),
190 ),
191 ),
192 );
193
194 it.effect.each(["live owner", "recent legacy"] as const)("keeps a lock with a %s", (kind) =>
195 Effect.gen(function* () {
196 const fileSystem = yield* FileSystem.FileSystem;
197 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
198 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
199 const owner = `${process.pid}-still-running`;
200 yield* fileSystem.makeDirectory(lockPath.slice(0, lockPath.lastIndexOf("/")), {
201 recursive: true,
202 });
203 if (kind === "live owner") {
204 yield* fileSystem.makeDirectory(lockPath);
205 yield* fileSystem.writeFileString(`${lockPath}/${owner}`, "");
206 } else {
207 yield* fileSystem.writeFileString(lockPath, "");
208 }
209 const written = yield* fileSystem.stat(lockPath);
210 yield* TestClock.setTime(
211 Option.getOrThrow(written.mtime).getTime() + (kind === "live owner" ? 3_600_000 : 6_000),
212 );
213 const waiting = yield* Deferred.make<void>();
214 const clock = yield* Clock.Clock;
215 const manager = yield* RelayClient.makeCloudflaredRelayClient({
216 baseDir,
217 releaseAsset: testReleaseAsset,
218 });
219 const installing = yield* manager.install.pipe(
220 Effect.provideService(Clock.Clock, {
221 ...clock,
222 sleep: () => Deferred.succeed(waiting, undefined).pipe(Effect.andThen(Effect.never)),
223 }),
224 Effect.forkChild,
225 );
226 yield* Deferred.await(waiting);
227 yield* Fiber.interrupt(installing);
228 if (kind === "live owner") {
229 expect(yield* fileSystem.readDirectory(lockPath)).toEqual([owner]);
230 } else {
231 expect(yield* fileSystem.readFileString(lockPath)).toBe("");
232 }
233 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
234 );
235
236 it.effect.skipIf(windowsHost)("replaces an install lock left by an exited installer", () =>
237 Effect.gen(function* () {
238 const fileSystem = yield* FileSystem.FileSystem;
239 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
240 prefix: "t3-cloudflared-test-",
241 });
242 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
243 yield* fileSystem.makeDirectory(lockPath.slice(0, lockPath.lastIndexOf("/")), {
244 recursive: true,
245 });
246 yield* fileSystem.makeDirectory(lockPath);
247 yield* fileSystem.writeFileString(`${lockPath}/2147483647-exited-installer`, "");
248 const manager = yield* RelayClient.makeCloudflaredRelayClient({
249 baseDir,
250 releaseAsset: testReleaseAsset,
251 });
252
253 expect(yield* manager.install).toMatchObject({ status: "available" });
254 expect(yield* fileSystem.exists(lockPath)).toBe(false);
255 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
256 );
257
258 it.effect.skipIf(windowsHost)("replaces an empty install lock left by an exited installer", () =>
259 Effect.gen(function* () {
260 const fileSystem = yield* FileSystem.FileSystem;
261 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
262 prefix: "t3-cloudflared-test-",
263 });
264 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
265 yield* fileSystem.makeDirectory(lockPath.slice(0, lockPath.lastIndexOf("/")), {
266 recursive: true,
267 });
268 yield* fileSystem.writeFileString(lockPath, "");
269 const written = yield* fileSystem.stat(lockPath);
270 const mtime = Option.getOrThrow(written.mtime).getTime();
271 // File mtimes use wall time; advance the test clock past legacy expiry.
272 yield* TestClock.setTime(mtime + 60 * 60 * 1_000);
273 const manager = yield* RelayClient.makeCloudflaredRelayClient({
274 baseDir,
275 releaseAsset: testReleaseAsset,
276 });
277
278 expect(yield* manager.install).toMatchObject({ status: "available" });
279 expect(yield* fileSystem.exists(lockPath)).toBe(false);
280 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
281 );
282
283 it.effect("keeps a replacement lock when a stale contender resumes cleanup", () =>
284 Effect.gen(function* () {
285 const fileSystem = yield* FileSystem.FileSystem;
286 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
287 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
288 const abandoned = "2147483647-exited-installer";
289 const replacement = `${process.pid}-replacement`;
290 yield* fileSystem.makeDirectory(lockPath, { recursive: true });
291 yield* fileSystem.writeFileString(`${lockPath}/${abandoned}`, "");
292 const checked = yield* Deferred.make<void>();
293 let replaced = false;
294 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }).pipe(
295 Effect.provideService(FileSystem.FileSystem, {
296 ...fileSystem,
297 readDirectory: (path) =>
298 fileSystem.readDirectory(path).pipe(
299 Effect.tap((entries) =>
300 Effect.gen(function* () {
301 if (path !== lockPath) return;
302 if (replaced) {
303 expect(entries).toEqual([replacement]);
304 yield* Deferred.succeed(checked, undefined);
305 return;
306 }
307 replaced = true;
308 yield* fileSystem.rename(lockPath, `${lockPath}.old`);
309 yield* fileSystem.makeDirectory(lockPath);
310 yield* fileSystem.writeFileString(`${lockPath}/${replacement}`, "");
311 }),
312 ),
313 ),
314 }),
315 );
316 const installing = yield* manager.install.pipe(Effect.forkChild);
317 yield* Deferred.await(checked);
318 yield* Fiber.interrupt(installing);
319 expect(yield* fileSystem.readDirectory(lockPath)).toEqual([replacement]);
320 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
321 );
322
323 it.effect("releases the install lock when a download is cancelled", () =>
324 Effect.gen(function* () {
325 const fileSystem = yield* FileSystem.FileSystem;
326 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
327 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
328 const downloading = yield* Deferred.make<void>();
329 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
330 const installing = yield* manager
331 .installWithProgress((event) =>
332 event.type === "progress" && event.stage === "downloading"
333 ? Deferred.succeed(downloading, undefined).pipe(Effect.andThen(Effect.never))
334 : Effect.void,
335 )
336 .pipe(Effect.forkChild);
337 yield* Deferred.await(downloading);
338 expect(yield* fileSystem.exists(lockPath)).toBe(true);
339 yield* Fiber.interrupt(installing);
340 expect(yield* fileSystem.exists(lockPath)).toBe(false);
341 }).pipe(
342 Effect.scoped,
343 Effect.provide(
344 Layer.mergeAll(
345 NodeServices.layer,
346 NodeCrypto.layer,
347 layerHttpClient(new Uint8Array()),
348 layerSpawner([]),
349 layerHostRuntime({ PATH: "" }),
350 ),
351 ),
352 ),
353 );
354
355 it.effect.skipIf(windowsHost)("releases a lock acquired while installation is cancelled", () =>
356 Effect.gen(function* () {
357 const fileSystem = yield* FileSystem.FileSystem;
358 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
359 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
360 const acquired = yield* Deferred.make<void>();
361 const completeWrite = yield* Deferred.make<void>();
362 let pauseWrite = true;
363 const manager = yield* RelayClient.makeCloudflaredRelayClient({
364 baseDir,
365 releaseAsset: {
366 url: "https://example.test/cloudflared",
367 sha256: Hex.encode(sha256(new TextEncoder().encode("test-binary"))),
368 archive: "binary",
369 },
370 }).pipe(
371 Effect.provideService(FileSystem.FileSystem, {
372 ...fileSystem,
373 rename: (from, to) =>
374 fileSystem
375 .rename(from, to)
376 .pipe(
377 Effect.tap(() =>
378 to === lockPath && pauseWrite
379 ? Deferred.succeed(acquired, undefined).pipe(
380 Effect.andThen(Deferred.await(completeWrite)),
381 )
382 : Effect.void,
383 ),
384 ),
385 }),
386 );
387
388 const installing = yield* manager.install.pipe(Effect.forkChild);
389 yield* Deferred.await(acquired);
390 const cancelling = yield* Fiber.interrupt(installing).pipe(
391 Effect.forkChild({ startImmediately: true }),
392 );
393 yield* Deferred.succeed(completeWrite, undefined);
394 yield* Fiber.join(cancelling);
395 expect(yield* fileSystem.exists(lockPath)).toBe(false);
396
397 pauseWrite = false;
398 expect(yield* manager.install).toMatchObject({ status: "available" });
399 expect(yield* fileSystem.exists(lockPath)).toBe(false);
400 }).pipe(
401 Effect.scoped,
402 Effect.provide(
403 Layer.mergeAll(
404 NodeServices.layer,
405 NodeCrypto.layer,
406 layerHttpClient(new TextEncoder().encode("test-binary")),
407 layerSpawner([]),
408 layerHostRuntime({ PATH: "" }),
409 ),
410 ),
411 ),
412 );
413
414 it.effect.skipIf(windowsHost)(
415 "removes a staged client whose rename lands after cancellation",
416 () =>
417 Effect.gen(function* () {
418 const fileSystem = yield* FileSystem.FileSystem;
419 const scope = yield* Effect.scope;
420 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
421 prefix: "t3-cloudflared-test-",
422 });
423 const directory = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64`;
424 const renamePending = yield* Deferred.make<void>();
425 const allowRename = yield* Deferred.make<void>();
426 const renameFinished = yield* Deferred.make<void, PlatformError.PlatformError>();
427 const manager = yield* RelayClient.makeCloudflaredRelayClient({
428 baseDir,
429 releaseAsset: testReleaseAsset,
430 }).pipe(
431 Effect.provideService(FileSystem.FileSystem, {
432 ...fileSystem,
433 // Like Node's rename, the staging rename completes even if its caller is interrupted.
434 rename: (from, to) =>
435 to.endsWith(".tmp")
436 ? Effect.forkIn(
437 Deferred.complete(
438 renameFinished,
439 Deferred.await(allowRename).pipe(Effect.andThen(fileSystem.rename(from, to))),
440 ),
441 scope,
442 ).pipe(
443 Effect.andThen(Deferred.succeed(renamePending, undefined)),
444 Effect.andThen(Deferred.await(renameFinished)),
445 )
446 : fileSystem.rename(from, to),
447 // Land the rename before the install temp directory is removed.
448 remove: (path, options) =>
449 path.endsWith(".tmp")
450 ? fileSystem
451 .remove(path, options)
452 .pipe(
453 Effect.andThen(Deferred.succeed(allowRename, undefined)),
454 Effect.andThen(Deferred.await(renameFinished)),
455 )
456 : fileSystem.remove(path, options),
457 }),
458 );
459
460 const installing = yield* manager.install.pipe(Effect.forkChild);
461 yield* Deferred.await(renamePending);
462 yield* Effect.yieldNow;
463 const cancelling = yield* Fiber.interrupt(installing).pipe(
464 Effect.forkChild({ startImmediately: true }),
465 );
466 yield* Effect.yieldNow;
467 yield* Deferred.succeed(allowRename, undefined);
468 yield* Fiber.join(cancelling);
469 yield* Deferred.await(renameFinished);
470
471 expect(yield* fileSystem.readDirectory(directory)).toEqual([]);
472 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
473 );
474
475 it.effect.skipIf(windowsHost)(
476 "downloads, verifies, validates, and atomically installs the managed executable",
477 () =>
478 Effect.gen(function* () {
479 const fileSystem = yield* FileSystem.FileSystem;
480 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
481 prefix: "t3-cloudflared-test-",
482 });
483 const bytes = new TextEncoder().encode("test-cloudflared-binary");
484 const manager = yield* RelayClient.makeCloudflaredRelayClient({
485 baseDir,
486 releaseAsset: {
487 url: "https://example.test/cloudflared",
488 sha256: Hex.encode(sha256(bytes)),
489 archive: "binary",
490 },
491 });
492
493 const progress: Array<string> = [];
494 const installed = yield* manager.installWithProgress((event) =>
495 Effect.sync(() => {
496 if (event.type === "progress") {
497 progress.push(event.stage);
498 }
499 }),
500 );
501 const managedPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared`;
502 expect(installed).toEqual({
503 status: "available",
504 executablePath: managedPath,
505 source: "managed",
506 version: RelayClient.CLOUDFLARED_VERSION,
507 });
508 expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe(
509 "test-cloudflared-binary",
510 );
511 expect(progress).toEqual([
512 "checking",
513 "waiting_for_lock",
514 "downloading",
515 "verifying",
516 "installing",
517 "validating",
518 "activating",
519 ]);
520 expect(yield* manager.resolve).toEqual(installed);
521 }).pipe(
522 Effect.scoped,
523 Effect.provide(
524 Layer.mergeAll(
525 NodeServices.layer,
526 NodeCrypto.layer,
527 layerHttpClient(new TextEncoder().encode("test-cloudflared-binary")),
528 layerSpawner([]),
529 layerHostRuntime(),
530 ),
531 ),
532 ),
533 );
534
535 it.effect.skipIf(windowsHost)(
536 "installs when the downloaded binary's first launch is held by an antivirus scan",
537 () =>
538 Effect.gen(function* () {
539 const fileSystem = yield* FileSystem.FileSystem;
540 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
541 prefix: "t3-cloudflared-test-",
542 });
543 const scanning = yield* Deferred.make<void>();
544 const manager = yield* RelayClient.makeCloudflaredRelayClient({
545 baseDir,
546 releaseAsset: testReleaseAsset,
547 }).pipe(
548 Effect.provideService(
549 ChildProcessSpawner.ChildProcessSpawner,
550 ChildProcessSpawner.make(() =>
551 Deferred.succeed(scanning, undefined).pipe(
552 Effect.andThen(Effect.sleep("25 seconds")),
553 Effect.as(
554 makeHandle(
555 0,
556 `cloudflared version ${RelayClient.CLOUDFLARED_VERSION} (built 2026-01-01-00:00 UTC)\n`,
557 ),
558 ),
559 ),
560 ),
561 ),
562 );
563
564 const installing = yield* manager.install.pipe(Effect.forkChild);
565 yield* Deferred.await(scanning);
566 yield* TestClock.adjust("25 seconds");
567
568 expect(yield* Fiber.join(installing)).toMatchObject({
569 status: "available",
570 source: "managed",
571 version: RelayClient.CLOUDFLARED_VERSION,
572 });
573 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
574 );
575
576 it.effect("rejects downloads whose checksum does not match the pinned manifest", () =>
577 Effect.gen(function* () {
578 const fileSystem = yield* FileSystem.FileSystem;
579 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
580 prefix: "t3-cloudflared-test-",
581 });
582 const manager = yield* RelayClient.makeCloudflaredRelayClient({
583 baseDir,
584 releaseAsset: {
585 url: "https://example.test/cloudflared",
586 sha256: Hex.encode(sha256(new TextEncoder().encode("expected"))),
587 archive: "binary",
588 },
589 });
590
591 const error = yield* manager.install.pipe(Effect.flip);
592 expect(error).toBeInstanceOf(RelayClient.RelayClientInstallError);
593 expect(error.reason).toBe("invalid_checksum");
594 expect(
595 yield* fileSystem.exists(
596 `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`,
597 ),
598 ).toBe(false);
599 }).pipe(
600 Effect.scoped,
601 Effect.provide(
602 Layer.mergeAll(
603 NodeServices.layer,
604 NodeCrypto.layer,
605 layerHttpClient(new TextEncoder().encode("tampered")),
606 layerSpawner([]),
607 layerHostRuntime(),
608 ),
609 ),
610 ),
611 );
612
613 it.effect.skipIf(windowsHost)("serializes concurrent installs within one runtime", () => {
614 const commands: Array<string> = [];
615 const bytes = new TextEncoder().encode("test-cloudflared-binary");
616 return Effect.gen(function* () {
617 const fileSystem = yield* FileSystem.FileSystem;
618 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
619 prefix: "t3-cloudflared-test-",
620 });
621 const manager = yield* RelayClient.makeCloudflaredRelayClient({
622 baseDir,
623 releaseAsset: {
624 url: "https://example.test/cloudflared",
625 sha256: Hex.encode(sha256(bytes)),
626 archive: "binary",
627 },
628 });
629
630 const [first, second] = yield* Effect.all([manager.install, manager.install], {
631 concurrency: "unbounded",
632 });
633 expect(second).toEqual(first);
634 expect(commands).toHaveLength(2);
635 }).pipe(
636 Effect.scoped,
637 Effect.provide(
638 Layer.mergeAll(
639 NodeServices.layer,
640 NodeCrypto.layer,
641 layerHttpClient(bytes),
642 layerSpawner(commands),
643 layerHostRuntime(),
644 ),
645 ),
646 );
647 });
648
649 it.effect("observes hydrated PATH changes after the manager has been constructed", () => {
650 const platform = windowsHost ? "win32" : "linux";
651 const executableName = windowsHost ? "cloudflared.exe" : "cloudflared";
652 const configEnv = { PATH: "" };
653 const hostEnv = { PATH: "" };
654 return Effect.gen(function* () {
655 const fileSystem = yield* FileSystem.FileSystem;
656 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
657 prefix: "t3-cloudflared-test-",
658 });
659 const binDir = `${baseDir}/bin`;
660 const executablePath = `${binDir}/${executableName}`;
661 const resolvedExecutablePath = windowsHost
662 ? executablePath.replaceAll("/", "\\")
663 : executablePath;
664 const manager = yield* RelayClient.makeCloudflaredRelayClient({
665 baseDir,
666 });
667
668 const resolveWithStaleConfig = manager.resolve.pipe(
669 Effect.provideService(
670 ConfigProvider.ConfigProvider,
671 ConfigProvider.fromEnv({ env: configEnv }),
672 ),
673 Effect.provideService(HostProcess.Environment, hostEnv),
674 );
675
676 expect(yield* resolveWithStaleConfig).toEqual({
677 status: "missing",
678 version: RelayClient.CLOUDFLARED_VERSION,
679 });
680
681 yield* fileSystem.makeDirectory(binDir);
682 yield* fileSystem.writeFileString(executablePath, "cloudflared");
683 if (!windowsHost) yield* fileSystem.chmod(executablePath, 0o755);
684 hostEnv.PATH = binDir;
685
686 expect(yield* resolveWithStaleConfig).toEqual({
687 status: "available",
688 executablePath: resolvedExecutablePath,
689 source: "path",
690 version: RelayClient.CLOUDFLARED_VERSION,
691 });
692
693 const resolveWithOverride = manager.resolve.pipe(
694 Effect.provideService(
695 ConfigProvider.ConfigProvider,
696 ConfigProvider.fromEnv({
697 env: { PATH: "", T3CODE_CLOUDFLARED_PATH: executablePath },
698 }),
699 ),
700 Effect.provideService(HostProcess.Environment, { PATH: "" }),
701 );
702 expect(yield* resolveWithOverride).toEqual({
703 status: "available",
704 executablePath,
705 source: "override",
706 version: RelayClient.CLOUDFLARED_VERSION,
707 });
708 }).pipe(
709 Effect.scoped,
710 Effect.provide(
711 Layer.mergeAll(
712 NodeServices.layer,
713 NodeCrypto.layer,
714 layerHttpClient(new Uint8Array()),
715 layerSpawner([]),
716 layerHostRuntime(configEnv, platform),
717 ),
718 ),
719 );
720 });
721
722 describe("version selection", () => {
723 const run = <A, E>(
724 body: (baseDir: string) => Effect.Effect<A, E, RelayClientTestServices>,
725 options: { readonly versions?: Record<string, string> } = {},
726 ) =>
727 Effect.gen(function* () {
728 const fileSystem = yield* FileSystem.FileSystem;
729 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
730 prefix: "t3-cloudflared-test-",
731 });
732 return yield* body(baseDir);
733 }).pipe(
734 Effect.scoped,
735 Effect.provide(
736 Layer.mergeAll(
737 NodeServices.layer,
738 NodeCrypto.layer,
739 layerHttpClient(new Uint8Array()),
740 layerSpawner([], options.versions),
741 layerHostRuntime({ PATH: "" }),
742 ),
743 ),
744 );
745
746 it.effect.skipIf(windowsHost)("skips binaries older than the minimum version", () => {
747 const versions: Record<string, string> = {};
748 return run(
749 (baseDir) =>
750 Effect.gen(function* () {
751 const oldPath = `${baseDir}/old/cloudflared`;
752 const newPath = `${baseDir}/new/cloudflared`;
753 yield* writeExecutable(oldPath);
754 yield* writeExecutable(newPath);
755 const managed = managedPathFor(baseDir, "2026.10.0");
756 yield* writeExecutable(managed);
757 versions[managed] = "2026.10.0";
758 versions[oldPath] = "2026.10.2";
759 versions[newPath] = "2026.10.3";
760 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
761 const env = { PATH: `${baseDir}/old:${baseDir}/new` };
762 expect(
763 yield* manager.resolve.pipe(
764 Effect.provideService(
765 ConfigProvider.ConfigProvider,
766 ConfigProvider.fromEnv({ env }),
767 ),
768 Effect.provideService(HostProcess.Environment, env),
769 ),
770 ).toEqual({
771 status: "available",
772 executablePath: newPath,
773 source: "path",
774 version: RelayClient.CLOUDFLARED_MIN_VERSION,
775 });
776 }),
777 { versions },
778 );
779 });
780
781 it.effect.skipIf(windowsHost)(
782 "finds a PATH binary through an empty entry by its absolute path",
783 () =>
784 run((baseDir) =>
785 Effect.gen(function* () {
786 const cwd = `${baseDir}/work`;
787 const inCwd = `${cwd}/cloudflared`;
788 yield* writeExecutable(inCwd);
789 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
790 const resolveWith = (searchPath: string) => {
791 const env = { PATH: searchPath };
792 return manager.resolve.pipe(
793 Effect.provideService(
794 ConfigProvider.ConfigProvider,
795 ConfigProvider.fromEnv({ env }),
796 ),
797 Effect.provideService(HostProcess.Environment, env),
798 Effect.provideService(HostProcess.WorkingDirectory, cwd),
799 );
800 };
801 const found = {
802 status: "available",
803 executablePath: inCwd,
804 source: "path",
805 version: RelayClient.CLOUDFLARED_VERSION,
806 };
807
808 expect(yield* resolveWith(`:${baseDir}/missing`)).toEqual(found);
809 expect(yield* resolveWith(`${baseDir}/missing:`)).toEqual(found);
810 const missing = { status: "missing", version: RelayClient.CLOUDFLARED_VERSION };
811 // An empty PATH searches nothing, not even the working directory.
812 expect(yield* resolveWith("")).toEqual(missing);
813 // A whitespace entry is not an empty one.
814 expect(yield* resolveWith(` :${baseDir}/missing`)).toEqual(missing);
815 expect(yield* resolveWith(`${baseDir}/missing: `)).toEqual(missing);
816 }),
817 ),
818 );
819
820 it.effect.skipIf(windowsHost)(
821 "preserves trailing whitespace and quotes in POSIX PATH entries",
822 () =>
823 run((baseDir) =>
824 Effect.gen(function* () {
825 const trailingSpaceDir = `${baseDir}/path entry `;
826 const trailingSpaceBin = `${trailingSpaceDir}/cloudflared`;
827 const trailingQuoteDir = `${baseDir}/quoted"`;
828 const trailingQuoteBin = `${trailingQuoteDir}/cloudflared`;
829 yield* writeExecutable(trailingSpaceBin);
830 yield* writeExecutable(trailingQuoteBin);
831 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
832 const resolveWith = (searchPath: string) => {
833 const env = { PATH: searchPath };
834 return manager.resolve.pipe(
835 Effect.provideService(
836 ConfigProvider.ConfigProvider,
837 ConfigProvider.fromEnv({ env }),
838 ),
839 Effect.provideService(HostProcess.Environment, env),
840 );
841 };
842
843 expect(yield* resolveWith(trailingSpaceDir)).toEqual({
844 status: "available",
845 executablePath: trailingSpaceBin,
846 source: "path",
847 version: RelayClient.CLOUDFLARED_VERSION,
848 });
849 expect(yield* resolveWith(trailingQuoteDir)).toEqual({
850 status: "available",
851 executablePath: trailingQuoteBin,
852 source: "path",
853 version: RelayClient.CLOUDFLARED_VERSION,
854 });
855 }),
856 ),
857 );
858
859 it.effect.skipIf(windowsHost)("reports an outdated override as missing", () => {
860 const versions: Record<string, string> = {};
861 return run(
862 (baseDir) =>
863 Effect.gen(function* () {
864 const overridePath = `${baseDir}/override/cloudflared`;
865 yield* writeExecutable(overridePath);
866 versions[overridePath] = "2026.10.2";
867 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
868 const env = { PATH: "", T3CODE_CLOUDFLARED_PATH: overridePath };
869 const withEnv = Effect.provideService(
870 ConfigProvider.ConfigProvider,
871 ConfigProvider.fromEnv({ env }),
872 );
873 expect(yield* manager.resolve.pipe(withEnv)).toEqual({
874 status: "missing",
875 version: RelayClient.CLOUDFLARED_VERSION,
876 });
877 const error = yield* manager.install.pipe(withEnv, Effect.flip);
878 expect(error.reason).toBe("override_missing");
879 }),
880 { versions },
881 );
882 });
883
884 it.effect.skipIf(windowsHost)(
885 "prefers the pinned release, then the newest older managed release, then PATH",
886 () => {
887 const versions: Record<string, string> = {};
888 return run(
889 (baseDir) =>
890 Effect.gen(function* () {
891 const fileSystem = yield* FileSystem.FileSystem;
892 const pathBinary = `${baseDir}/bin/cloudflared`;
893 const older = managedPathFor(baseDir, "2025.9.0");
894 const newer = managedPathFor(baseDir, "2026.1.0");
895 const pinned = managedPathFor(baseDir, RelayClient.CLOUDFLARED_VERSION);
896 const newerServer = managedPathFor(baseDir, "2099.1.0");
897 const olderBackupFile = `${baseDir}/tools/cloudflared/backup-of-2025.8.0.txt`;
898 const newerBackupFile = `${baseDir}/tools/cloudflared/backup-of-2026.10.2.txt`;
899 const nonDirectoryVersion = `${baseDir}/tools/cloudflared/2026.10.3`;
900 versions[newerServer] = "2099.1.0";
901 yield* writeExecutable(newerServer);
902 versions[pathBinary] = "2026.10.3";
903 versions[older] = "2025.9.0";
904 versions[newer] = "2026.10.3";
905 yield* writeExecutable(pathBinary);
906 yield* writeExecutable(older);
907 yield* writeExecutable(newer);
908 yield* fileSystem.writeFileString(olderBackupFile, "keep-older");
909 yield* fileSystem.writeFileString(newerBackupFile, "keep-newer");
910 yield* fileSystem.writeFileString(nonDirectoryVersion, "not-a-release-dir");
911 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
912 const resolveWith = manager.resolve.pipe(
913 Effect.provideService(
914 ConfigProvider.ConfigProvider,
915 ConfigProvider.fromEnv({ env: { PATH: `${baseDir}/bin` } }),
916 ),
917 Effect.provideService(HostProcess.Environment, { PATH: `${baseDir}/bin` }),
918 );
919
920 expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.10.3" });
921
922 yield* writeExecutable(pinned);
923 expect(yield* resolveWith).toMatchObject({
924 executablePath: pinned,
925 source: "managed",
926 version: RelayClient.CLOUDFLARED_VERSION,
927 });
928
929 yield* manager.pruneManagedVersions;
930 expect(
931 (yield* fileSystem.readDirectory(`${baseDir}/tools/cloudflared`)).sort(),
932 ).toEqual([
933 "2026.1.0",
934 "2026.10.3",
935 RelayClient.CLOUDFLARED_VERSION,
936 "2099.1.0",
937 "backup-of-2025.8.0.txt",
938 "backup-of-2026.10.2.txt",
939 ]);
940
941 yield* fileSystem.remove(pinned);
942 expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.10.3" });
943 yield* fileSystem.remove(`${baseDir}/tools/cloudflared/2026.1.0`, {
944 recursive: true,
945 });
946 expect(yield* resolveWith).toMatchObject({ source: "path", version: "2026.10.3" });
947 }),
948 { versions },
949 );
950 },
951 );
952
953 it.effect.skipIf(windowsHost)(
954 "keeps a self-updated managed binary as a fallback but still installs the pin",
955 () => {
956 const versions: Record<string, string> = {};
957 return run(
958 (baseDir) =>
959 Effect.gen(function* () {
960 const pinned = managedPathFor(baseDir, RelayClient.CLOUDFLARED_VERSION);
961 versions[pinned] = "2026.10.3";
962 yield* writeExecutable(pinned);
963 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
964 const resolved = yield* manager.resolve;
965 expect(resolved).toEqual({
966 status: "available",
967 executablePath: pinned,
968 source: "managed",
969 version: "2026.10.3",
970 });
971 expect(
972 resolved.status === "available" && RelayClient.isPinnedManagedRelayClient(resolved),
973 ).toBe(false);
974 }),
975 { versions },
976 );
977 },
978 );
979 });
980
981 it("orders and parses cloudflared versions", () => {
982 expect(
983 RelayClient.parseCloudflaredVersionOutput(
984 "cloudflared version 2026.5.2 (built 2026-05-20-10:00 UTC)",
985 ),
986 ).toBe("2026.5.2");
987 expect(RelayClient.parseCloudflaredVersionOutput("Incorrect Usage")).toBeNull();
988 expect(RelayClient.compareCloudflaredVersions("2025.10.0", "2025.6.1")).toBeGreaterThan(0);
989 expect(RelayClient.compareCloudflaredVersions("2023.8.2", "2025.6.1")).toBeLessThan(0);
990 });
991
992 it.effect.each([
993 ["linux", "EBUSY"],
994 ["win32", "EXDEV"],
995 ] as const)("fails staging at once on %s for %s", ([platform, code]) =>
996 Effect.gen(function* () {
997 const fileSystem = yield* FileSystem.FileSystem;
998 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
999 prefix: "t3-cloudflared-test-",
1000 });
1001 const { locked, renames } = yield* makeLockedRenames(fileSystem, {
1002 rename: "staging",
1003 failures: Infinity,
1004 code,
1005 });
1006 const manager = yield* RelayClient.makeCloudflaredRelayClient({
1007 baseDir,
1008 releaseAsset: testReleaseAsset,
1009 }).pipe(Effect.provideService(FileSystem.FileSystem, locked));
1010
1011 const error = yield* manager.install.pipe(Effect.flip);
1012
1013 expect(error.message).toBe("Could not stage the relay client.");
1014 expect(renames.attempts).toBe(1);
1015 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime(platform))),
1016 );
1017});