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