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