|
| 1 | +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; |
| 2 | +import { tmpdir } from "node:os"; |
| 3 | +import { join } from "node:path"; |
| 4 | +import { spawn } from "node:child_process"; |
| 5 | + |
| 6 | +export type FlyGuestErrorKind = "timeout" | "output_limit" | "disconnect" | "transport" | "file_limit"; |
| 7 | + |
| 8 | +/** Sanitized transport errors never include CLI output, command arguments, or credentials. */ |
| 9 | +export class FlyGuestError extends Error { |
| 10 | + constructor(readonly kind: FlyGuestErrorKind) { |
| 11 | + super(`Fly guest transport ${kind.replace("_", " ")}`); |
| 12 | + this.name = "FlyGuestError"; |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +export type FlyGuestCommandResult = { ok: boolean; exitCode: number; stdout: string; stderr: string }; |
| 17 | +export type FlyGuestTransportOptions = { |
| 18 | + app: string; |
| 19 | + machine: string; |
| 20 | + token: string; |
| 21 | + cliPath?: string; |
| 22 | + timeoutMs?: number; |
| 23 | + outputLimitBytes?: number; |
| 24 | + fileLimitBytes?: number; |
| 25 | + /** Subprocess injection is used by deterministic local protocol fixtures. */ |
| 26 | + spawnProcess?: typeof spawn; |
| 27 | +}; |
| 28 | + |
| 29 | +function pathSegment(value: string, name: string): string { |
| 30 | + if (!value || value === "." || value === ".." || /[\0/\r\n]/.test(value)) throw new TypeError(`${name} must be a path segment`); |
| 31 | + return value; |
| 32 | +} |
| 33 | + |
| 34 | +function guestPath(value: string): string { |
| 35 | + if (!value.startsWith("/") || value.includes("\0") || value.includes("\r") || value.includes("\n") || value.split("/").some(part => part === "." || part === "..")) { |
| 36 | + throw new TypeError("Guest file path must be absolute and normalized"); |
| 37 | + } |
| 38 | + return value; |
| 39 | +} |
| 40 | + |
| 41 | +export function createFlyGuestTransport(options: FlyGuestTransportOptions) { |
| 42 | + pathSegment(options.app, "app"); |
| 43 | + pathSegment(options.machine, "machine"); |
| 44 | + if (!options.token) throw new TypeError("Fly token is required"); |
| 45 | + const timeoutMs = options.timeoutMs ?? 30_000; |
| 46 | + const outputLimitBytes = options.outputLimitBytes ?? 1024 * 1024; |
| 47 | + const fileLimitBytes = options.fileLimitBytes ?? 16 * 1024 * 1024; |
| 48 | + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 10 * 60_000) throw new TypeError("timeoutMs must be between 1ms and 10 minutes"); |
| 49 | + if (!Number.isSafeInteger(outputLimitBytes) || outputLimitBytes < 1 || outputLimitBytes > 16 * 1024 * 1024 || !Number.isSafeInteger(fileLimitBytes) || fileLimitBytes < 1 || fileLimitBytes > 64 * 1024 * 1024) throw new TypeError("transport limits exceed the supported bounds"); |
| 50 | + const spawnProcess = options.spawnProcess ?? spawn; |
| 51 | + const base = ["--app", options.app, "--machine", options.machine]; |
| 52 | + |
| 53 | + async function invoke(args: string[], limit = outputLimitBytes, input?: string | Uint8Array): Promise<FlyGuestCommandResult> { |
| 54 | + return new Promise((resolve, reject) => { |
| 55 | + let stdout = Buffer.alloc(0), stderr = Buffer.alloc(0), settled = false, exceeded = false; |
| 56 | + const child = spawnProcess(options.cliPath ?? "fly", args, { env: { ...process.env, FLY_API_TOKEN: options.token }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, detached: process.platform !== "win32" }); |
| 57 | + const killTree = () => { |
| 58 | + try { |
| 59 | + if (child.pid && process.platform !== "win32") process.kill(-child.pid, "SIGKILL"); |
| 60 | + else child.kill("SIGKILL"); |
| 61 | + } catch { child.kill("SIGKILL"); } |
| 62 | + }; |
| 63 | + const finishError = (error: FlyGuestError) => { |
| 64 | + if (settled) return; |
| 65 | + settled = true; |
| 66 | + clearTimeout(deadline); |
| 67 | + killTree(); |
| 68 | + reject(error); |
| 69 | + }; |
| 70 | + const collect = (current: Buffer, chunk: Buffer): Buffer => { |
| 71 | + const remaining = limit - stdout.byteLength - stderr.byteLength; |
| 72 | + if (chunk.byteLength > remaining) { |
| 73 | + exceeded = true; |
| 74 | + return Buffer.concat([current, chunk.subarray(0, Math.max(0, remaining))]); |
| 75 | + } |
| 76 | + return Buffer.concat([current, chunk]); |
| 77 | + }; |
| 78 | + child.stdout.on("data", (chunk: Buffer) => { stdout = collect(stdout, chunk); if (exceeded) finishError(new FlyGuestError("output_limit")); }); |
| 79 | + child.stderr.on("data", (chunk: Buffer) => { stderr = collect(stderr, chunk); if (exceeded) finishError(new FlyGuestError("output_limit")); }); |
| 80 | + child.on("error", () => finishError(new FlyGuestError("transport"))); |
| 81 | + const deadline = setTimeout(() => finishError(new FlyGuestError("timeout")), timeoutMs); |
| 82 | + child.stdin.end(input); |
| 83 | + child.on("close", (code: number | null) => { |
| 84 | + if (settled) return; |
| 85 | + settled = true; |
| 86 | + clearTimeout(deadline); |
| 87 | + if (code === null) return reject(new FlyGuestError("disconnect")); |
| 88 | + resolve({ ok: code === 0, exitCode: code, stdout: stdout.toString("utf8"), stderr: stderr.toString("utf8") }); |
| 89 | + }); |
| 90 | + }); |
| 91 | + } |
| 92 | + |
| 93 | + return { |
| 94 | + /** Arguments are passed as an argv vector after `--`; no shell parses guest input. */ |
| 95 | + run(command: readonly string[], input?: string | Uint8Array): Promise<FlyGuestCommandResult> { |
| 96 | + if (!command.length || command.some(arg => typeof arg !== "string" || arg.includes("\0"))) throw new TypeError("Guest command must contain valid arguments"); |
| 97 | + return invoke(["machine", "exec", options.machine, "--app", options.app, "--no-container", "--timeout", String(Math.max(1, Math.ceil(timeoutMs / 1000))), "--", ...command], outputLimitBytes, input); |
| 98 | + }, |
| 99 | + async upload(remotePath: string, bytes: Uint8Array): Promise<void> { |
| 100 | + remotePath = guestPath(remotePath); |
| 101 | + if (bytes.byteLength > fileLimitBytes) throw new FlyGuestError("file_limit"); |
| 102 | + const directory = await mkdtemp(join(tmpdir(), "factorize-fly-upload-")); |
| 103 | + const localPath = join(directory, "payload"); |
| 104 | + try { |
| 105 | + await writeFile(localPath, bytes, { mode: 0o600 }); |
| 106 | + const result = await invoke(["sftp", "put", localPath, remotePath, ...base, "--no-container", "--user", "root"], 64 * 1024); |
| 107 | + if (!result.ok) throw new FlyGuestError("transport"); |
| 108 | + } finally { await rm(directory, { recursive: true, force: true }); } |
| 109 | + }, |
| 110 | + async download(remotePath: string): Promise<Uint8Array> { |
| 111 | + remotePath = guestPath(remotePath); |
| 112 | + const directory = await mkdtemp(join(tmpdir(), "factorize-fly-download-")); |
| 113 | + const localPath = join(directory, "payload"); |
| 114 | + try { |
| 115 | + const result = await invoke(["sftp", "get", remotePath, localPath, ...base, "--no-container", "--user", "root"], 64 * 1024); |
| 116 | + if (!result.ok) throw new FlyGuestError("transport"); |
| 117 | + const size = (await stat(localPath)).size; |
| 118 | + if (size > fileLimitBytes) throw new FlyGuestError("file_limit"); |
| 119 | + return new Uint8Array(await readFile(localPath)); |
| 120 | + } catch (error) { |
| 121 | + if (error instanceof FlyGuestError) throw error; |
| 122 | + throw new FlyGuestError("transport"); |
| 123 | + } finally { await rm(directory, { recursive: true, force: true }); } |
| 124 | + }, |
| 125 | + }; |
| 126 | +} |
0 commit comments