import fs from 'fs'; import path from 'path'; import { Readable } from 'stream'; import * as zlib from 'zlib'; import * as tarStream from 'tar-stream'; import { nodeProxyTransport } from './proxy-transport'; /** The Content-Type of a folder an instance sends as a tar. */ export const TAR_CONTENT_TYPE = 'application/x-tar'; /** * The header saying a pull's body is zstd-compressed. A pull asks for it with `compression=zstd`; * a server that predates it sends neither. It is not Content-Encoding, so fetch never decodes the * body on its own. */ export const COMPRESSION_HEADER = 'x-limrun-compression'; // Node has zstd from 22.15; an older Node pulls and pushes uncompressed. const zstdCompress = (zlib as any).createZstdCompress as | ((options?: object) => NodeJS.ReadWriteStream) | undefined; const zstdDecompress = (zlib as any).createZstdDecompress as (() => NodeJS.ReadWriteStream) | undefined; /** pullQuery is the query a pull adds to its URL: a folder as a tar, compressed when Node can read it. */ export function pullQuery(): string { return zstdDecompress ? 'archive=tar&compression=zstd' : 'archive=tar'; } /** * pushFile PUTs a local file to `url`, compressed with zstd as it is read when `compress` is set * and Node has zstd, and returns the `path` the instance answers with. */ export async function pushFile( url: string, token: string, localPath: string, compress: boolean, ): Promise { const size = (await fs.promises.stat(localPath)).size; const file = fs.createReadStream(localPath); const zstd = compress && zstdCompress ? zstdCompress({ params: { [(zlib as any).constants.ZSTD_c_compressionLevel]: 3 } }) : undefined; const headers: Record = { 'Content-Type': 'application/octet-stream', Authorization: `Bearer ${token}`, }; let body: Readable = file; if (zstd) { headers['Content-Encoding'] = 'zstd'; file.on('error', (err) => (zstd as any).destroy(err)); body = file.pipe(zstd) as unknown as Readable; } else { headers['Content-Length'] = String(size); } try { const response = await nodeProxyTransport.fetch(url, { method: 'PUT', headers, body: body as any, duplex: 'half', } as any); if (!response.ok) { const errorBody = await response.text(); throw new Error(`Upload of '${localPath}' failed: ${response.status} ${errorBody}`); } return ((await response.json()) as { path: string }).path; } finally { file.destroy(); } } /** What a pull wrote. */ export type PullResult = { /** The absolute local path of the file or folder written. */ path: string; /** True when the remote was a folder, unpacked into `path`. */ isDirectory: boolean; }; /** * pullTarget is where a pull of `remote` into `local` writes: `local`, or `remote`'s base name * inside it when `local` is an existing folder. Without `local`, the base name in the current * directory. */ export async function pullTarget(remote: string, local?: string): Promise { const name = path.posix.basename(remote.replace(/\/+$/, '')); const nameless = name === '' || name === '.' || name === '..' || name === '~'; if (local === undefined || local === '') { if (nameless) throw new Error(`"${remote}" has no name to save it under; pass the local path to write to`); return path.resolve(name); } const target = path.resolve(local); const stat = await fs.promises.stat(target).catch(() => null); if (!stat?.isDirectory()) return target; if (nameless) { throw new Error( `${target} is a folder and "${remote}" has no name to put inside it; pass the local path to write to`, ); } return path.join(target, name); } /** * pullToLocalPath GETs `url`, whose query ends with {@link pullQuery}, and writes the answer to `target`: a * tar is unpacked into the folder `target`, anything else is written to the file `target` through * a temporary file renamed into place. */ export async function pullToLocalPath( url: string, token: string, remote: string, target: string, ): Promise { const response = await nodeProxyTransport.fetch(url, { method: 'GET', headers: { Authorization: `Bearer ${token}` }, }); if (!response.ok) { const errorBody = await response.text(); throw new Error(`Pull of '${remote}' failed: ${response.status} ${errorBody}`); } if (!response.body) throw new Error(`Pull of '${remote}' failed: the response has no body`); let source: AsyncIterable = Readable.fromWeb(response.body as any); const compression = response.headers.get(COMPRESSION_HEADER); if (compression) { if (compression !== 'zstd' || !zstdDecompress) { throw new Error( `Pull of '${remote}' failed: the body is compressed with ${compression}, which this Node cannot read`, ); } const raw = source as Readable; const decompress = zstdDecompress(); raw.on('error', (err) => (decompress as any).destroy(err)); source = raw.pipe(decompress) as unknown as AsyncIterable; } const mediaType = (response.headers.get('content-type') ?? '').split(';')[0]!.trim().toLowerCase(); if (mediaType === TAR_CONTENT_TYPE) { await fs.promises.mkdir(target, { recursive: true }); await unpackTar(source, target); return { path: target, isDirectory: true }; } await writeFileAtomically(source, target); return { path: target, isDirectory: false }; } async function writeFileAtomically(source: AsyncIterable, target: string): Promise { const dir = path.dirname(target); await fs.promises.mkdir(dir, { recursive: true }); const temporary = path.join( dir, `.lim-pull-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`, ); const handle = await fs.promises.open(temporary, 'wx', 0o644); try { try { for await (const chunk of source) await handle.write(chunk); } finally { await handle.close(); } await fs.promises.rename(temporary, target); } catch (err) { await fs.promises.rm(temporary, { force: true }); throw err; } } /** * unpackTar extracts a tar into `dir`, an existing folder. Entries are relative to `dir`: an * absolute name or one with a `..` component fails the unpack. Symlinks keep their targets, as tar * keeps them, wherever they point: they are created after every file and folder, and nothing is * written through a symlink, so a target outside `dir` is never written to. Entries other than * files, folders and symlinks are skipped. */ export async function unpackTar(source: AsyncIterable, dir: string): Promise { const extract = tarStream.extract(); const input = Readable.from(source); input.on('error', (err) => extract.destroy(err)); input.pipe(extract); const links: { name: string; target: string }[] = []; const folders: { path: string; mode: number; mtime: Date | undefined }[] = []; try { for await (const entry of extract) { const header = entry.header; const name = entryName(header.name); const dst = name === '' ? dir : path.join(dir, ...name.split('/')); const mode = (header.mode ?? 0o644) & 0o7777; if (header.type === 'file' || header.type === 'contiguous-file') { if (name === '') throw new Error('the tar has a file entry for its own folder'); await makeDirs(dir, path.posix.dirname(name)); await writeEntry(dst, entry as unknown as AsyncIterable, mode, header.mtime); continue; } entry.resume(); if (name === '') continue; if (header.type === 'directory') { await makeDirs(dir, name); folders.push({ path: dst, mode, mtime: header.mtime }); } else if (header.type === 'symlink') { if (!header.linkname) throw new Error(`the tar has a symlink "${name}" without a target`); links.push({ name, target: header.linkname }); } } } finally { input.unpipe(extract); input.destroy(); } for (const link of links) { await makeDirs(dir, path.posix.dirname(link.name)); const dst = path.join(dir, ...link.name.split('/')); await removeEntry(dst); await fs.promises.symlink(link.target, dst); } // Folders get their modes and times last: writing into them changes their times, and a // read-only folder could not be written into. for (const folder of folders.reverse()) { await fs.promises.chmod(folder.path, folder.mode | 0o700); if (folder.mtime) await fs.promises.utimes(folder.path, folder.mtime, folder.mtime).catch(() => {}); } } /** entryName returns an entry's name as a clean relative slash path, '' for the folder itself. */ function entryName(raw: string): string { if (raw.startsWith('/') || path.isAbsolute(raw) || /^[A-Za-z]:/.test(raw)) { throw new Error(`the tar has an absolute entry "${raw}"`); } const parts = raw.split('/'); if (parts.includes('..') || raw.includes('\\')) throw new Error(`the tar has an entry outside its folder: "${raw}"`); return parts.filter((part) => part !== '' && part !== '.').join('/'); } /** makeDirs creates the folders of `rel` under `root` one at a time, refusing links and files. */ async function makeDirs(root: string, rel: string): Promise { if (rel === '' || rel === '.') return; let current = root; for (const part of rel.split('/')) { current = path.join(current, part); const stat = await fs.promises.lstat(current).catch((err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') return null; throw err; }); if (!stat) { await fs.promises.mkdir(current, 0o755); } else if (stat.isSymbolicLink()) { throw new Error(`refusing to write through the symlink ${current}`); } else if (!stat.isDirectory()) { throw new Error(`${current} is a file, not a folder`); } } } /** removeEntry removes a file or symlink so a new entry replaces it rather than writing through it. */ async function removeEntry(dst: string): Promise { const stat = await fs.promises.lstat(dst).catch((err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') return null; throw err; }); if (!stat) return; if (stat.isDirectory()) throw new Error(`${dst} is a folder, not a file`); await fs.promises.rm(dst); } async function writeEntry( dst: string, chunks: AsyncIterable, mode: number, mtime: Date | undefined, ): Promise { await removeEntry(dst); // 'wx' fails rather than follow a symlink that appeared at dst. const handle = await fs.promises.open(dst, 'wx', mode | 0o200); try { for await (const chunk of chunks) await handle.write(chunk); } finally { await handle.close(); } if ((mode & 0o200) === 0) await fs.promises.chmod(dst, mode); if (mtime) await fs.promises.utimes(dst, mtime, mtime).catch(() => {}); }