Open History to see the last commit
1import * as Clock from "effect/Clock";
2import type {
3 RelayClientInstallProgressEvent,
4 RelayClientInstallProgressStage,
5} from "@v12/contracts";
6import * as Config from "effect/Config";
7import * as Context from "effect/Context";
8import * as Crypto from "effect/Crypto";
9import * as Data from "effect/Data";
10import * as Effect from "effect/Effect";
11import * as Encoding from "effect/Encoding";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as PlatformError from "effect/PlatformError";
17import * as Semaphore from "effect/Semaphore";
18import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
19import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
20import { HostProcessArchitecture, HostProcessPlatform } from "./hostProcess.ts";
21
22export const CLOUDFLARED_VERSION = "2026.5.2";
23export const CLOUDFLARED_PATH_ENV_NAME = "V12_CLOUDFLARED_PATH";
24
25export type RelayClientExecutableSource = "override" | "managed" | "path";
26
27export type RelayClientStatus =
28 | {
29 readonly status: "available";
30 readonly executablePath: string;
31 readonly source: RelayClientExecutableSource;
32 readonly version: string;
33 }
34 | {
35 readonly status: "missing";
36 readonly version: string;
37 }
38 | {
39 readonly status: "unsupported";
40 readonly platform: NodeJS.Platform;
41 readonly arch: string;
42 readonly version: string;
43 };
44
45export type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: "available" }>;
46
47export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{
48 readonly reason:
49 | "download_failed"
50 | "invalid_checksum"
51 | "install_locked"
52 | "override_missing"
53 | "unsupported_platform"
54 | "validation_failed"
55 | "write_failed";
56 readonly message: string;
57 readonly cause?: unknown;
58}> {}
59
60class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{
61 readonly command: string;
62 readonly exitCode: number;
63}> {}
64
65export interface CloudflaredReleaseAsset {
66 readonly url: string;
67 readonly sha256: string;
68 readonly archive: "binary" | "tgz";
69}
70
71const CLOUDFLARED_RELEASE_ASSETS: Readonly<
72 Partial<Record<`${NodeJS.Platform}-${string}`, CloudflaredReleaseAsset>>
73> = {
74 "darwin-arm64": {
75 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-arm64.tgz",
76 sha256: "ba94054c9fd4297645093d59d51442e5e546d07bb0516120e694a13d5b216d38",
77 archive: "tgz",
78 },
79 "darwin-x64": {
80 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-amd64.tgz",
81 sha256: "7240f709506bc2c1eb9da4d89cf2555499c60280ecb854b7d80e8f17d4b7903d",
82 archive: "tgz",
83 },
84 "linux-arm64": {
85 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-arm64",
86 sha256: "5a4e8ce2701105271412059f44b6a0bf1ae4542b4d98ff3180c0c019443a5815",
87 archive: "binary",
88 },
89 "linux-x64": {
90 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-amd64",
91 sha256: "5286698547f03df745adb2355f04c12dde52ef425491e81f433642d695521886",
92 archive: "binary",
93 },
94 "win32-x64": {
95 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-windows-amd64.exe",
96 sha256: "20b9638f685333d623798e733effbad2487093f15ba592f6c7752360ff3b7ab7",
97 archive: "binary",
98 },
99};
100
101const INSTALL_LOCK_RETRY_COUNT = 100;
102const INSTALL_LOCK_RETRY_DELAY = "100 millis";
103const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;
104
105const trimmedString = (name: string) =>
106 Config.string(name).pipe(
107 Config.option,
108 Config.map(
109 Option.flatMap((value) => {
110 const trimmed = value.trim();
111 return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
112 }),
113 ),
114 );
115
116const CloudflaredConfig = Config.all({
117 executableOverride: trimmedString(CLOUDFLARED_PATH_ENV_NAME),
118 path: trimmedString("PATH"),
119});
120
121export interface CloudflaredRelayClientOptions {
122 readonly baseDir: string;
123 readonly releaseAsset?: CloudflaredReleaseAsset;
124}
125
126export interface RelayClientShape {
127 readonly resolve: Effect.Effect<RelayClientStatus>;
128 readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
129 readonly installWithProgress: (
130 report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
131 ) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
132}
133
134export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(
135 "@v12/shared/relayClient",
136) {}
137
138function executableFileName(platform: NodeJS.Platform): string {
139 return platform === "win32" ? "cloudflared.exe" : "cloudflared";
140}
141
142function resolveReleaseAsset(
143 platform: NodeJS.Platform,
144 arch: string,
145): CloudflaredReleaseAsset | null {
146 return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;
147}
148
149function isAlreadyExists(error: PlatformError.PlatformError): boolean {
150 return error.reason._tag === "AlreadyExists";
151}
152
153const wrapInstallFailure =
154 (
155 reason: RelayClientInstallError["reason"],
156 message: string,
157 ): (<E, R>(
158 effect: Effect.Effect<void, E, R>,
159 ) => Effect.Effect<void, RelayClientInstallError, R>) =>
160 (effect) =>
161 effect.pipe(
162 Effect.mapError(
163 (cause) =>
164 new RelayClientInstallError({
165 reason,
166 message,
167 cause,
168 }),
169 ),
170 );
171
172export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function* (
173 options: CloudflaredRelayClientOptions,
174): Effect.fn.Return<
175 RelayClientShape,
176 never,
177 | ChildProcessSpawner.ChildProcessSpawner
178 | Crypto.Crypto
179 | FileSystem.FileSystem
180 | HttpClient.HttpClient
181 | Path.Path
182> {
183 const crypto = yield* Crypto.Crypto;
184 const fileSystem = yield* FileSystem.FileSystem;
185 const httpClient = yield* HttpClient.HttpClient;
186 const path = yield* Path.Path;
187 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
188 const installSemaphore = yield* Semaphore.make(1);
189 const platform = yield* HostProcessPlatform;
190 const arch = yield* HostProcessArchitecture;
191 const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);
192 const loadCloudflaredConfig = Effect.suspend(() => CloudflaredConfig).pipe(Effect.orDie);
193 const managedPath = path.join(
194 options.baseDir,
195 "tools",
196 "cloudflared",
197 CLOUDFLARED_VERSION,
198 `${platform}-${arch}`,
199 executableFileName(platform),
200 );
201
202 const isExecutableFile = Effect.fn("cloudflared.isExecutableFile")(function* (
203 executablePath: string,
204 ) {
205 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
206 if (Option.isNone(info) || info.value.type !== "File") return false;
207 return platform === "win32" || (info.value.mode & 0o111) !== 0;
208 });
209
210 const resolvePathExecutable = Effect.gen(function* () {
211 const config = yield* loadCloudflaredConfig;
212 const pathValue = Option.getOrUndefined(config.path);
213 if (!pathValue) return null;
214 const delimiter = platform === "win32" ? ";" : ":";
215 for (const directory of pathValue.split(delimiter)) {
216 const trimmed = directory.trim().replace(/^"|"$/gu, "");
217 if (trimmed.length === 0) continue;
218 const candidate = path.join(trimmed, executableFileName(platform));
219 if (yield* isExecutableFile(candidate)) return candidate;
220 }
221 return null;
222 });
223
224 const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {
225 const config = yield* loadCloudflaredConfig;
226 if (Option.isSome(config.executableOverride)) {
227 return (yield* isExecutableFile(config.executableOverride.value))
228 ? {
229 status: "available",
230 executablePath: config.executableOverride.value,
231 source: "override",
232 version: CLOUDFLARED_VERSION,
233 }
234 : { status: "missing", version: CLOUDFLARED_VERSION };
235 }
236 if (yield* isExecutableFile(managedPath)) {
237 return {
238 status: "available",
239 executablePath: managedPath,
240 source: "managed",
241 version: CLOUDFLARED_VERSION,
242 };
243 }
244 const pathExecutable = yield* resolvePathExecutable;
245 if (pathExecutable) {
246 return {
247 status: "available",
248 executablePath: pathExecutable,
249 source: "path",
250 version: CLOUDFLARED_VERSION,
251 };
252 }
253 return releaseAsset
254 ? { status: "missing", version: CLOUDFLARED_VERSION }
255 : {
256 status: "unsupported",
257 platform,
258 arch,
259 version: CLOUDFLARED_VERSION,
260 };
261 });
262
263 const runCommand = Effect.fn("cloudflared.runCommand")(function* (
264 command: string,
265 args: ReadonlyArray<string>,
266 ) {
267 const child = yield* spawner.spawn(
268 ChildProcess.make(command, args, {
269 shell: false,
270 stdout: "ignore",
271 stderr: "ignore",
272 }),
273 );
274 const exitCode = Number(yield* child.exitCode);
275 if (exitCode !== 0) {
276 return yield* new CloudflaredCommandError({ command, exitCode });
277 }
278 });
279
280 const downloadAsset = Effect.fn("cloudflared.downloadAsset")(function* (
281 asset: CloudflaredReleaseAsset,
282 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
283 ) {
284 yield* report("downloading");
285 const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe(
286 Effect.flatMap(HttpClientResponse.filterStatusOk),
287 Effect.mapError(
288 (cause) =>
289 new RelayClientInstallError({
290 reason: "download_failed",
291 message: "Could not download the relay client.",
292 cause,
293 }),
294 ),
295 );
296 const bytes = new Uint8Array(
297 yield* response.arrayBuffer.pipe(
298 Effect.mapError(
299 (cause) =>
300 new RelayClientInstallError({
301 reason: "download_failed",
302 message: "Could not read the downloaded relay client binary.",
303 cause,
304 }),
305 ),
306 ),
307 );
308 yield* report("verifying");
309 const checksum = yield* crypto.digest("SHA-256", bytes).pipe(
310 Effect.mapError(
311 (cause) =>
312 new RelayClientInstallError({
313 reason: "validation_failed",
314 message: "Could not verify the downloaded relay client checksum.",
315 cause,
316 }),
317 ),
318 );
319 if (Encoding.encodeHex(checksum) !== asset.sha256) {
320 return yield* new RelayClientInstallError({
321 reason: "invalid_checksum",
322 message: "Downloaded relay client checksum did not match the pinned release.",
323 });
324 }
325 return bytes;
326 });
327
328 const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
329 lockPath: string,
330 ) {
331 for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
332 const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
333 Effect.as(true),
334 Effect.catch((error) =>
335 isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
336 ),
337 );
338 if (acquired) return;
339
340 const now = yield* Clock.currentTimeMillis;
341 const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
342 const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
343 if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {
344 yield* fileSystem.remove(lockPath, { force: true });
345 continue;
346 }
347 yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
348 }
349 return yield* new RelayClientInstallError({
350 reason: "install_locked",
351 message: "Another relay client installation is still in progress.",
352 });
353 });
354
355 const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (
356 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
357 ) {
358 yield* report("checking");
359 const existing = yield* resolve;
360 if (existing.status === "available") return existing;
361 const config = yield* loadCloudflaredConfig;
362 if (Option.isSome(config.executableOverride)) {
363 return yield* new RelayClientInstallError({
364 reason: "override_missing",
365 message: `${CLOUDFLARED_PATH_ENV_NAME} does not point to an executable file.`,
366 });
367 }
368 if (!releaseAsset) {
369 return yield* new RelayClientInstallError({
370 reason: "unsupported_platform",
371 message: `V12 does not provide a managed relay client binary for ${platform}-${arch}.`,
372 });
373 }
374
375 const managedDirectory = path.dirname(managedPath);
376 const lockPath = `${managedPath}.lock`;
377 yield* fileSystem
378 .makeDirectory(managedDirectory, { recursive: true })
379 .pipe(
380 wrapInstallFailure("write_failed", "Could not create the relay client tool directory."),
381 );
382 yield* report("waiting_for_lock");
383 yield* acquireInstallLock(lockPath).pipe(
384 Effect.catchTag("PlatformError", (cause) =>
385 Effect.fail(
386 new RelayClientInstallError({
387 reason: "write_failed",
388 message: "Could not acquire the relay client installation lock.",
389 cause,
390 }),
391 ),
392 ),
393 );
394 return yield* Effect.gen(function* () {
395 const afterLock = yield* resolve;
396 if (afterLock.status === "available") return afterLock;
397
398 const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
399 directory: managedDirectory,
400 prefix: ".install-",
401 });
402 const archivePath = path.join(
403 tempDirectory,
404 releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),
405 );
406 const download = yield* downloadAsset(releaseAsset, report);
407 yield* report("installing");
408 yield* fileSystem
409 .writeFile(archivePath, download)
410 .pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));
411
412 const executablePath = path.join(tempDirectory, executableFileName(platform));
413 if (releaseAsset.archive === "tgz") {
414 yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
415 wrapInstallFailure("write_failed", "Could not extract the relay client."),
416 );
417 }
418 if (platform !== "win32") {
419 yield* fileSystem
420 .chmod(executablePath, 0o755)
421 .pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable."));
422 }
423 yield* report("validating");
424 yield* runCommand(executablePath, ["--version"]).pipe(
425 wrapInstallFailure("validation_failed", "The downloaded relay client binary did not run."),
426 );
427
428 const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4}.tmp`;
429 yield* report("activating");
430 yield* fileSystem
431 .rename(executablePath, stagedPath)
432 .pipe(wrapInstallFailure("write_failed", "Could not stage the relay client."));
433 yield* fileSystem
434 .rename(stagedPath, managedPath)
435 .pipe(
436 wrapInstallFailure("write_failed", "Could not activate the relay client."),
437 Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),
438 );
439 return {
440 status: "available",
441 executablePath: managedPath,
442 source: "managed",
443 version: CLOUDFLARED_VERSION,
444 } satisfies AvailableRelayClient;
445 }).pipe(
446 Effect.scoped,
447 Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)),
448 Effect.catch((cause) =>
449 cause instanceof RelayClientInstallError
450 ? Effect.fail(cause)
451 : Effect.fail(
452 new RelayClientInstallError({
453 reason: "write_failed",
454 message: "Could not install the relay client.",
455 cause,
456 }),
457 ),
458 ),
459 );
460 });
461 const installWithProgress: RelayClientShape["installWithProgress"] = (report) =>
462 installSemaphore.withPermit(
463 installUnlocked((stage) =>
464 report({
465 type: "progress",
466 stage,
467 }),
468 ),
469 );
470 const install = installWithProgress(() => Effect.void);
471
472 return RelayClient.of({ resolve, install, installWithProgress });
473});
474
475export const layerCloudflared = (options: CloudflaredRelayClientOptions) =>
476 Layer.effect(RelayClient, makeCloudflaredRelayClient(options));