Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off -- FileSystem.remove cannot remove an empty directory nonrecursively.
2import * as NodeFSP from "node:fs/promises";
3import * as Cache from "effect/Cache";
4import * as Clock from "effect/Clock";
5import type {
6 RelayClientInstallProgressEvent,
7 RelayClientInstallProgressStage,
8} from "@t3tools/contracts";
9import * as Config from "effect/Config";
10import * as Context from "effect/Context";
11import * as Crypto from "effect/Crypto";
12import * as Data from "effect/Data";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Hex from "effect/encoding/Hex";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Path from "effect/Path";
21import type * as PlatformError from "effect/PlatformError";
22import * as Schedule from "effect/Schedule";
23import * as Semaphore from "effect/Semaphore";
24import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
25import { ChildProcess, ChildProcessSpawner } from "effect/process";
26import { isWindowsRenameLock } from "./atomicWrite.ts";
27import * as HostProcess from "./HostProcess.ts";
28
29export const CLOUDFLARED_VERSION = "2026.10.4";
30// Minimum for --output support; older connectors exit on that flag.
31export const CLOUDFLARED_MIN_VERSION = "2025.6.1";
32const CLOUDFLARED_PATH_ENV_NAME = "T3CODE_CLOUDFLARED_PATH";
33
34const CLOUDFLARED_DOWNLOAD_TIMEOUT = "10 minutes";
35
36export type RelayClientExecutableSource = "override" | "managed" | "path";
37
38export type RelayClientStatus =
39 | {
40 readonly status: "available";
41 readonly executablePath: string;
42 readonly source: RelayClientExecutableSource;
43 readonly version: string;
44 }
45 | {
46 readonly status: "missing";
47 readonly version: string;
48 }
49 | {
50 readonly status: "unsupported";
51 readonly platform: NodeJS.Platform;
52 readonly arch: string;
53 readonly version: string;
54 };
55
56export type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: "available" }>;
57
58export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{
59 readonly reason:
60 | "download_failed"
61 | "invalid_checksum"
62 | "install_locked"
63 | "override_missing"
64 | "unsupported_platform"
65 | "validation_failed"
66 | "write_failed";
67 readonly message: string;
68 readonly cause?: unknown;
69}> {}
70
71class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{
72 readonly command: string;
73 readonly exitCode: number;
74}> {}
75
76export interface CloudflaredReleaseAsset {
77 readonly url: string;
78 readonly sha256: string;
79 readonly archive: "binary" | "tgz";
80}
81
82const CLOUDFLARED_RELEASE_ASSETS: Readonly<
83 Partial<Record<`${NodeJS.Platform}-${string}`, CloudflaredReleaseAsset>>
84> = {
85 "darwin-arm64": {
86 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-darwin-arm64.tgz",
87 sha256: "68b6bc4080ac1330234db2a9002d07f98b000537a1bd531a687b660d4160fa7f",
88 archive: "tgz",
89 },
90 "darwin-x64": {
91 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-darwin-amd64.tgz",
92 sha256: "f11fbef4207d715892331917dafd437f032cf4b7137ed64dea3008338c1c613d",
93 archive: "tgz",
94 },
95 "linux-arm64": {
96 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-linux-arm64",
97 sha256: "2b7203b4fb0ba28a0c1e12f8855ce2c25f76d266a8d5edafac5540b6812acff6",
98 archive: "binary",
99 },
100 "linux-x64": {
101 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-linux-amd64",
102 sha256: "ae5e8add7884b0531d66bbca4570d1de491ff6da51e4ebe7eb160cdf241d9e42",
103 archive: "binary",
104 },
105 "win32-x64": {
106 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-windows-amd64.exe",
107 sha256: "411b16d40c8d872243efeb52c550053d00af0a8a97fbb32e730fb8aba429eaa8",
108 archive: "binary",
109 },
110 // Cloudflare publishes no Windows ARM64 build; Windows 11 on ARM runs x64 under emulation.
111 "win32-arm64": {
112 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-windows-amd64.exe",
113 sha256: "411b16d40c8d872243efeb52c550053d00af0a8a97fbb32e730fb8aba429eaa8",
114 archive: "binary",
115 },
116};
117
118const INSTALL_LOCK_RETRY_COUNT = 100;
119const INSTALL_LOCK_RETRY_DELAY = "100 millis";
120// Legacy locks have no owner; allow both ten-minute download stages and the install tail.
121const INSTALL_LOCK_LEGACY_STALE_MS = 30 * 60 * 1_000;
122const VERSION_PROBE_TIMEOUT = "10 seconds";
123
124const ACTIVATE_RETRY_COUNT = 40;
125const ACTIVATE_RETRY_DELAY = "250 millis";
126
127const trimmedString = (name: string) =>
128 Config.String(name).pipe(
129 Config.option,
130 Config.map(
131 Option.flatMap((value) => {
132 const trimmed = value.trim();
133 return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
134 }),
135 ),
136 );
137
138const CloudflaredConfig = Config.all({
139 executableOverride: trimmedString(CLOUDFLARED_PATH_ENV_NAME),
140});
141
142export interface CloudflaredRelayClientOptions {
143 readonly baseDir: string;
144 readonly releaseAsset?: CloudflaredReleaseAsset;
145}
146
147export interface RelayClientShape {
148 readonly resolve: Effect.Effect<RelayClientStatus>;
149 readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
150 readonly installWithProgress: (
151 report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
152 ) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
153 /** Removes managed releases older than the pin, except the newest one. Call once the pin has connected. */
154 readonly pruneManagedVersions: Effect.Effect<void>;
155}
156
157export function isPinnedManagedRelayClient(client: AvailableRelayClient): boolean {
158 return client.source === "managed" && client.version === CLOUDFLARED_VERSION;
159}
160
161export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(
162 "@t3tools/shared/relayClient",
163) {}
164
165function executableFileName(platform: NodeJS.Platform): string {
166 return platform === "win32" ? "cloudflared.exe" : "cloudflared";
167}
168
169function resolveReleaseAsset(
170 platform: NodeJS.Platform,
171 arch: string,
172): CloudflaredReleaseAsset | null {
173 return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;
174}
175
176const VERSION_PATTERN = /\b(\d{4})\.(\d{1,2})\.(\d+)\b/u;
177
178function parseVersion(value: string): readonly [number, number, number] | null {
179 const match = VERSION_PATTERN.exec(value);
180 return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
181}
182
183export function compareCloudflaredVersions(left: string, right: string): number {
184 const a = parseVersion(left) ?? [0, 0, 0];
185 const b = parseVersion(right) ?? [0, 0, 0];
186 return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
187}
188
189export function parseCloudflaredVersionOutput(output: string): string | null {
190 const version = parseVersion(output);
191 return version ? version.join(".") : null;
192}
193
194class VersionProbeKey extends Data.Class<{
195 readonly executablePath: string;
196 readonly size: number;
197 readonly mtimeMillis: number;
198}> {}
199
200function isLockContention(error: PlatformError.PlatformError): boolean {
201 const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
202 return (
203 error.reason._tag === "AlreadyExists" ||
204 error.reason._tag === "BadResource" ||
205 code === "ENOTEMPTY" ||
206 isWindowsRenameLock(error)
207 );
208}
209
210function parseLockOwnerPid(owner: string): number | null {
211 const separator = owner.indexOf("-");
212 if (separator <= 0) return null;
213 const pid = Number(owner.slice(0, separator));
214 return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
215}
216
217function processIsAlive(pid: number): boolean {
218 try {
219 process.kill(pid, 0);
220 return true;
221 } catch (error) {
222 return (error as { readonly code?: unknown }).code !== "ESRCH";
223 }
224}
225
226const wrapInstallFailure =
227 (
228 reason: RelayClientInstallError["reason"],
229 message: string,
230 ): (<E, R>(
231 effect: Effect.Effect<void, E, R>,
232 ) => Effect.Effect<void, RelayClientInstallError, R>) =>
233 (effect) =>
234 effect.pipe(
235 Effect.mapError(
236 (cause) =>
237 new RelayClientInstallError({
238 reason,
239 message,
240 cause,
241 }),
242 ),
243 );
244
245export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function* (
246 options: CloudflaredRelayClientOptions,
247): Effect.fn.Return<
248 RelayClientShape,
249 never,
250 | ChildProcessSpawner.ChildProcessSpawner
251 | Crypto.Crypto
252 | FileSystem.FileSystem
253 | HttpClient.HttpClient
254 | Path.Path
255> {
256 const crypto = yield* Crypto.Crypto;
257 const fileSystem = yield* FileSystem.FileSystem;
258 const httpClient = yield* HttpClient.HttpClient;
259 const path = yield* Path.Path;
260 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
261 const installSemaphore = yield* Semaphore.make(1);
262 const platform = yield* HostProcess.Platform;
263 const arch = yield* HostProcess.Architecture;
264 const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);
265 const loadCloudflaredConfig = Effect.suspend(() => CloudflaredConfig).pipe(Effect.orDie);
266 const managedRoot = path.join(options.baseDir, "tools", "cloudflared");
267 const managedPathFor = (version: string) =>
268 path.join(managedRoot, version, `${platform}-${arch}`, executableFileName(platform));
269 const managedPath = managedPathFor(CLOUDFLARED_VERSION);
270
271 const isExecutableFile = Effect.fn("cloudflared.isExecutableFile")(function* (
272 executablePath: string,
273 ) {
274 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
275 if (Option.isNone(info) || info.value.type !== "File") return false;
276 return platform === "win32" || (info.value.mode & 0o111) !== 0;
277 });
278
279 // Cache successful version probes per file revision; do not let transient failures hide valid binaries.
280 const versionCache = yield* Cache.makeWith(
281 (key: VersionProbeKey) =>
282 spawner
283 .string(
284 ChildProcess.make(key.executablePath, ["version"], { stdin: "ignore", stderr: "ignore" }),
285 )
286 .pipe(
287 Effect.map(parseCloudflaredVersionOutput),
288 Effect.timeoutOption(VERSION_PROBE_TIMEOUT),
289 Effect.map(Option.getOrNull),
290 Effect.orElseSucceed(() => null),
291 ),
292 {
293 capacity: 16,
294 timeToLive: (exit) =>
295 Exit.isSuccess(exit) && exit.value !== null ? Duration.infinity : Duration.zero,
296 },
297 );
298 const probeVersion = Effect.fn("cloudflared.probeVersion")(function* (executablePath: string) {
299 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
300 if (Option.isNone(info) || info.value.type !== "File") return null;
301 if (platform !== "win32" && (info.value.mode & 0o111) === 0) return null;
302 return yield* Cache.get(
303 versionCache,
304 new VersionProbeKey({
305 executablePath,
306 size: Number(info.value.size),
307 mtimeMillis: Option.getOrUndefined(info.value.mtime)?.getTime() ?? 0,
308 }),
309 );
310 });
311
312 const compatibleCandidate = Effect.fn("cloudflared.compatibleCandidate")(function* (
313 executablePath: string,
314 source: RelayClientExecutableSource,
315 expectedVersion?: string,
316 ) {
317 const version = yield* probeVersion(executablePath);
318 if (version === null || compareCloudflaredVersions(version, CLOUDFLARED_MIN_VERSION) < 0) {
319 return null;
320 }
321 if (expectedVersion !== undefined && version !== expectedVersion) {
322 yield* Effect.logWarning("Ignoring a managed relay client that reports another version", {
323 executablePath,
324 expectedVersion,
325 version,
326 });
327 return null;
328 }
329 return { status: "available", executablePath, source, version } satisfies AvailableRelayClient;
330 });
331
332 // Newer managed folders may belong to another server; never use or prune them.
333 const olderManagedVersions = Effect.gen(function* () {
334 const entries = yield* fileSystem
335 .readDirectory(managedRoot)
336 .pipe(Effect.orElseSucceed(() => []));
337 return entries
338 .filter(
339 (entry) =>
340 parseVersion(entry) !== null &&
341 compareCloudflaredVersions(entry, CLOUDFLARED_VERSION) < 0,
342 )
343 .sort((left, right) => compareCloudflaredVersions(right, left));
344 });
345
346 const resolvePathExecutable = Effect.gen(function* () {
347 // Read hydrated PATH directly; ConfigProvider may have cached it before fixPath.
348 const pathValue = (yield* HostProcess.Environment).PATH?.trim();
349 if (!pathValue) return null;
350 const delimiter = platform === "win32" ? ";" : ":";
351 for (const directory of pathValue.split(delimiter)) {
352 const trimmed = directory.trim().replace(/^"|"$/gu, "");
353 if (trimmed.length === 0) continue;
354 const candidate = path.join(trimmed, executableFileName(platform));
355 if (!(yield* isExecutableFile(candidate))) continue;
356 const available = yield* compatibleCandidate(candidate, "path");
357 if (available) return available;
358 yield* Effect.logWarning("Skipping an incompatible relay client on PATH", {
359 executablePath: candidate,
360 minimumVersion: CLOUDFLARED_MIN_VERSION,
361 });
362 }
363 return null;
364 });
365
366 const missingStatus: RelayClientStatus = { status: "missing", version: CLOUDFLARED_VERSION };
367 const unsupportedStatus: RelayClientStatus = {
368 status: "unsupported",
369 platform,
370 arch,
371 version: CLOUDFLARED_VERSION,
372 };
373 const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {
374 const config = yield* loadCloudflaredConfig;
375 if (Option.isSome(config.executableOverride)) {
376 const override = yield* compatibleCandidate(config.executableOverride.value, "override");
377 if (override) return override;
378 yield* Effect.logWarning(
379 `${CLOUDFLARED_PATH_ENV_NAME} must point to cloudflared ${CLOUDFLARED_MIN_VERSION} or newer`,
380 { executablePath: config.executableOverride.value },
381 );
382 return missingStatus;
383 }
384 const pinned = yield* compatibleCandidate(managedPath, "managed");
385 if (pinned) return pinned;
386 for (const version of yield* olderManagedVersions) {
387 const older = yield* compatibleCandidate(managedPathFor(version), "managed");
388 if (older) return older;
389 }
390 const pathExecutable = yield* resolvePathExecutable;
391 if (pathExecutable) return pathExecutable;
392 return releaseAsset ? missingStatus : unsupportedStatus;
393 }).pipe(Effect.withSpan("cloudflared.resolve"));
394
395 const pruneManagedVersions: RelayClientShape["pruneManagedVersions"] = Effect.gen(function* () {
396 // Retain the newest older release for rollback or older servers that cannot redownload it.
397 for (const version of (yield* olderManagedVersions).slice(1)) {
398 // Windows cannot delete another server's running connector; retry next prune.
399 yield* fileSystem.remove(path.join(managedRoot, version), { recursive: true }).pipe(
400 Effect.tap(() => Effect.logInfo("Removed an older managed relay client", { version })),
401 Effect.catch((cause) =>
402 Effect.logDebug("Could not remove an older managed relay client", { version, cause }),
403 ),
404 );
405 }
406 }).pipe(Effect.withSpan("cloudflared.pruneManagedVersions"));
407
408 const renameWhenUnlocked = (from: string, to: string) =>
409 fileSystem.rename(from, to).pipe(
410 Effect.retry({
411 times: ACTIVATE_RETRY_COUNT,
412 schedule: Schedule.spaced(ACTIVATE_RETRY_DELAY),
413 while: (error) => platform === "win32" && isWindowsRenameLock(error),
414 }),
415 );
416
417 const runCommand = Effect.fn("cloudflared.runCommand")(function* (
418 command: string,
419 args: ReadonlyArray<string>,
420 ) {
421 const child = yield* spawner.spawn(
422 ChildProcess.make(command, args, {
423 shell: false,
424 stdout: "ignore",
425 stderr: "ignore",
426 }),
427 );
428 const exitCode = Number(yield* child.exitCode);
429 if (exitCode !== 0) {
430 return yield* new CloudflaredCommandError({ command, exitCode });
431 }
432 });
433
434 const downloadAsset = Effect.fn("cloudflared.downloadAsset")(function* (
435 asset: CloudflaredReleaseAsset,
436 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
437 ) {
438 yield* report("downloading");
439 const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe(
440 Effect.timeout(CLOUDFLARED_DOWNLOAD_TIMEOUT),
441 Effect.flatMap(HttpClientResponse.filterStatusOk),
442 Effect.mapError(
443 (cause) =>
444 new RelayClientInstallError({
445 reason: "download_failed",
446 message: "Could not download the relay client.",
447 cause,
448 }),
449 ),
450 );
451 const bytes = new Uint8Array(
452 yield* response.arrayBuffer.pipe(
453 Effect.timeout(CLOUDFLARED_DOWNLOAD_TIMEOUT),
454 Effect.mapError(
455 (cause) =>
456 new RelayClientInstallError({
457 reason: "download_failed",
458 message: "Could not read the downloaded relay client binary.",
459 cause,
460 }),
461 ),
462 ),
463 );
464 yield* report("verifying");
465 const checksum = yield* crypto.digest("SHA-256", bytes).pipe(
466 Effect.mapError(
467 (cause) =>
468 new RelayClientInstallError({
469 reason: "validation_failed",
470 message: "Could not verify the downloaded relay client checksum.",
471 cause,
472 }),
473 ),
474 );
475 if (Hex.encode(checksum) !== asset.sha256) {
476 return yield* new RelayClientInstallError({
477 reason: "invalid_checksum",
478 message: "Downloaded relay client checksum did not match the pinned release.",
479 });
480 }
481 return bytes;
482 });
483
484 const removeEmptyLock = (lockPath: string) =>
485 Effect.tryPromise(() => NodeFSP.rmdir(lockPath)).pipe(Effect.ignore);
486
487 const releaseOwnedLock = Effect.fn("cloudflared.releaseOwnedLock")(function* (
488 lockPath: string,
489 owner: string,
490 ) {
491 yield* fileSystem.remove(path.join(lockPath, owner), { force: true }).pipe(Effect.ignore);
492 // A replacement contains a different owner entry, so rmdir cannot remove it.
493 yield* removeEmptyLock(lockPath);
494 });
495
496 const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
497 lockPath: string,
498 ) {
499 const owner = `${process.pid}-${yield* crypto.randomUUIDv4()}`;
500 const candidate = yield* Effect.acquireRelease(
501 fileSystem.makeTempDirectory({ directory: path.dirname(lockPath), prefix: ".lock-" }),
502 (directory) =>
503 fileSystem.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore),
504 );
505 yield* fileSystem.writeFileString(path.join(candidate, owner), "");
506 for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
507 const acquired = yield* Effect.acquireRelease(
508 // Publish a populated directory atomically, with no ownerless acquisition window.
509 fileSystem.rename(candidate, lockPath),
510 () => releaseOwnedLock(lockPath, owner),
511 ).pipe(
512 Effect.as(true),
513 Effect.catchIf(isLockContention, () => Effect.succeed(false)),
514 );
515 if (acquired) return;
516
517 const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
518 if (Option.isNone(lockInfo)) continue;
519 if (lockInfo.value.type === "Directory") {
520 const owners = yield* fileSystem
521 .readDirectory(lockPath)
522 .pipe(Effect.orElseSucceed(() => []));
523 let recovered = owners.length === 0;
524 for (const entry of owners) {
525 const pid = parseLockOwnerPid(entry);
526 if (pid !== null && !processIsAlive(pid)) {
527 yield* releaseOwnedLock(lockPath, entry);
528 recovered = true;
529 }
530 }
531 if (recovered) {
532 yield* removeEmptyLock(lockPath);
533 continue;
534 }
535 } else {
536 const now = yield* Clock.currentTimeMillis;
537 const mtime = lockInfo.value.mtime;
538 if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_LEGACY_STALE_MS) {
539 // Nonrecursive removal also refuses a populated directory that replaced this file.
540 yield* fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore);
541 continue;
542 }
543 }
544 yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
545 }
546 return yield* new RelayClientInstallError({
547 reason: "install_locked",
548 message: "Another relay client installation is still in progress.",
549 });
550 });
551
552 const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (
553 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
554 ) {
555 yield* report("checking");
556 const config = yield* loadCloudflaredConfig;
557 if (Option.isSome(config.executableOverride)) {
558 const override = yield* compatibleCandidate(config.executableOverride.value, "override");
559 if (override) return override;
560 return yield* new RelayClientInstallError({
561 reason: "override_missing",
562 message: `${CLOUDFLARED_PATH_ENV_NAME} must point to cloudflared ${CLOUDFLARED_MIN_VERSION} or newer.`,
563 });
564 }
565 const existing = yield* compatibleCandidate(managedPath, "managed", CLOUDFLARED_VERSION);
566 if (existing) return existing;
567 if (!releaseAsset) {
568 return yield* new RelayClientInstallError({
569 reason: "unsupported_platform",
570 message: `T3 Code does not provide a managed relay client binary for ${platform}-${arch}.`,
571 });
572 }
573
574 const managedDirectory = path.dirname(managedPath);
575 const lockPath = `${managedPath}.lock`;
576 yield* fileSystem
577 .makeDirectory(managedDirectory, { recursive: true })
578 .pipe(
579 wrapInstallFailure("write_failed", "Could not create the relay client tool directory."),
580 );
581 yield* report("waiting_for_lock");
582 yield* acquireInstallLock(lockPath).pipe(
583 Effect.catchTags({
584 PlatformError: (cause) =>
585 Effect.fail(
586 new RelayClientInstallError({
587 reason: "write_failed",
588 message: "Could not acquire the relay client installation lock.",
589 cause,
590 }),
591 ),
592 }),
593 );
594 return yield* Effect.gen(function* () {
595 const afterLock = yield* compatibleCandidate(managedPath, "managed", CLOUDFLARED_VERSION);
596 if (afterLock) return afterLock;
597
598 const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
599 directory: managedDirectory,
600 prefix: ".install-",
601 });
602 const archivePath = path.join(
603 tempDirectory,
604 releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),
605 );
606 const download = yield* downloadAsset(releaseAsset, report);
607 yield* report("installing");
608 yield* fileSystem
609 .writeFile(archivePath, download)
610 .pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));
611
612 const executablePath = path.join(tempDirectory, executableFileName(platform));
613 if (releaseAsset.archive === "tgz") {
614 yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
615 wrapInstallFailure("write_failed", "Could not extract the relay client."),
616 );
617 }
618 if (platform !== "win32") {
619 yield* fileSystem
620 .chmod(executablePath, 0o755)
621 .pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable."));
622 }
623 yield* report("validating");
624 // Verify the pin so mislabeled assets cannot cause repeated redownloads.
625 const installedVersion = yield* probeVersion(executablePath);
626 if (installedVersion !== CLOUDFLARED_VERSION) {
627 return yield* new RelayClientInstallError({
628 reason: "validation_failed",
629 message:
630 installedVersion === null
631 ? "The downloaded relay client binary did not run."
632 : `The downloaded relay client reports version ${installedVersion}, not ${CLOUDFLARED_VERSION}.`,
633 });
634 }
635
636 const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4()}.tmp`;
637 yield* report("activating");
638 yield* renameWhenUnlocked(executablePath, stagedPath).pipe(
639 wrapInstallFailure("write_failed", "Could not stage the relay client."),
640 );
641 yield* renameWhenUnlocked(stagedPath, managedPath).pipe(
642 wrapInstallFailure("write_failed", "Could not activate the relay client."),
643 Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),
644 );
645 return {
646 status: "available",
647 executablePath: managedPath,
648 source: "managed",
649 version: CLOUDFLARED_VERSION,
650 } satisfies AvailableRelayClient;
651 }).pipe(
652 Effect.scoped,
653 Effect.catchIf(
654 (cause) => !(cause instanceof RelayClientInstallError),
655 (cause) =>
656 Effect.fail(
657 new RelayClientInstallError({
658 reason: "write_failed",
659 message: "Could not install the relay client.",
660 cause,
661 }),
662 ),
663 ),
664 );
665 });
666 const installWithProgress: RelayClientShape["installWithProgress"] = (report) =>
667 installSemaphore.withPermit(
668 installUnlocked((stage) =>
669 report({
670 type: "progress",
671 stage,
672 }),
673 ).pipe(Effect.scoped),
674 );
675 const install = installWithProgress(() => Effect.void);
676
677 return RelayClient.of({ resolve, install, installWithProgress, pruneManagedVersions });
678});
679
680export const layerCloudflared = (options: CloudflaredRelayClientOptions) =>
681 Layer.effect(RelayClient, makeCloudflaredRelayClient(options));