// Shared private runtime boundary and durable, create-only filesystem primitives. import { lstat, mkdir, readdir, readFile, open, link, unlink } from 'node:fs/promises'; import { dirname, join, parse, isAbsolute, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { caseFold } from 'unicode-case-folding'; import { safeRelative, assertSeparateRoots } from './paths.mjs'; export const codeRoot = fileURLToPath(new URL('../../../', import.meta.url)).replace(/\/$/, ''); export async function noSymlinks(path) { if (typeof path !== 'string' || !isAbsolute(path) || resolve(path) !== path || path === parse(path).root) throw new Error('normalized absolute path required'); let cursor = path; while (cursor !== dirname(cursor)) { try { if ((await lstat(cursor)).isSymbolicLink()) throw new Error('symlink path'); } catch (e) { if (e.code !== 'ENOENT') throw e; } cursor = dirname(cursor); } } export async function runtimeRoot(root, forbiddenRoots, additional = []) { if (!forbiddenRoots || Array.isArray(forbiddenRoots) || !['source', 'code', 'served'].every(k => Object.hasOwn(forbiddenRoots, k)) || Object.keys(forbiddenRoots).some(k => !['source', 'code', 'served', 'primary'].includes(k)) || !Array.isArray(forbiddenRoots.served)) throw new Error('explicit source, code and served exclusions required'); const excluded = [forbiddenRoots.source, forbiddenRoots.code, ...forbiddenRoots.served, codeRoot, ...additional, ...(Object.hasOwn(forbiddenRoots, 'primary') ? [forbiddenRoots.primary] : [])]; await noSymlinks(root); for (const path of new Set(excluded)) { await noSymlinks(path); await assertSeparateRoots([root, path]); } for (let cursor = root; cursor !== dirname(cursor); cursor = dirname(cursor)) { try { await lstat(join(cursor, '.git')); throw new Error('runtime root inside Git repository'); } catch (e) { if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') throw e; } try { await lstat(join(cursor, 'HEAD')); await lstat(join(cursor, 'objects')); await lstat(join(cursor, 'refs')); throw new Error('runtime root inside bare Git repository'); } catch (e) { if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') throw e; } } } export function checkedMap(files) { if (!(files instanceof Map) || !files.size || files.size > 10000) throw new Error('invalid files map'); const seen = new Set(); for (const [path, bytes] of files) { safeRelative(path); const folded = caseFold(path).normalize('NFC'); if (seen.has(folded) || !Buffer.isBuffer(bytes) || bytes.length > 128 * 1024 * 1024) throw new Error('invalid or colliding file'); seen.add(folded); } return files; } export async function readTree(root) { await noSymlinks(root); const files = new Map(); async function visit(relative) { const full = join(root, relative); const info = await lstat(full); if (info.isSymbolicLink()) throw new Error('symlink package member'); if (info.isDirectory()) { const entries = await readdir(full); if (relative && entries.length === 0) throw new Error('empty package directory'); for (const name of entries.sort()) await visit(relative ? `${relative}/${name}` : name); } else if (info.isFile() && info.size <= 128 * 1024 * 1024) { if (files.size >= 10000) throw new Error('too many package members'); files.set(safeRelative(relative), await readFile(full)); } else throw new Error('nonregular package member'); } await visit(''); return checkedMap(files); } export async function syncDirectory(path) { const handle = await open(path, 'r'); try { await handle.sync(); } finally { await handle.close(); } } // mkdir(recursive) identifies the first newly created component. Persist the // entire new directory chain, including its link in the existing parent, before // acknowledging creation. The existing parent is the trusted durable boundary. export async function durableDirectory(path) { await noSymlinks(path); const firstCreated = await mkdir(path, { recursive: true, mode: 0o700 }); const boundary = dirname(firstCreated ?? path); for (let cursor = path; ; cursor = dirname(cursor)) { await syncDirectory(cursor); if (cursor === boundary) break; } } export async function writeTree(root, files) { checkedMap(files); await mkdir(root, { mode: 0o700 }); const directories = new Set([root]); for (const [path, bytes] of files) { const full = join(root, path); await durableDirectory(dirname(full)); for (let dir = dirname(full); dir.startsWith(root); dir = dirname(dir)) { directories.add(dir); if (dir === root) break; } const handle = await open(full, 'wx', 0o600); try { await handle.writeFile(bytes); await handle.sync(); } finally { await handle.close(); } } for (const dir of [...directories].sort((a, b) => b.length - a.length)) await syncDirectory(dir); await syncDirectory(dirname(root)); } export async function putFile(path, bytes) { await noSymlinks(path); await durableDirectory(dirname(path)); const temp = `${path}.tmp-${crypto.randomUUID()}`; try { const handle = await open(temp, 'wx', 0o600); try { await handle.writeFile(bytes); await handle.sync(); } finally { await handle.close(); } try { await link(temp, path); } catch (e) { if (e.code !== 'EEXIST') throw e; await noSymlinks(path); if (!(await lstat(path)).isFile() || !(await readFile(path)).equals(bytes)) throw new Error('conflicting existing bytes'); } await syncDirectory(dirname(path)); } finally { await unlink(temp).catch(e => { if (e.code !== 'ENOENT') throw e; }); } } export function sameFiles(a, b) { return a.size === b.size && [...a].every(([path, bytes]) => b.get(path)?.equals(bytes)); }