import { createHash, randomBytes } from 'node:crypto'; import fs from 'node:fs/promises'; import path from 'node:path'; const DRIVE_PREFIX_REGEX = /^[a-zA-Z]:/; function hasControlChar(value: string): boolean { for (let i = 0; i < value.length; i += 1) { const code = value.charCodeAt(i); if (code < 0x20 || code === 0x7f) return true; } return false; } export function sha256Hex(content: Buffer | string): string { return createHash('sha256').update(content).digest('hex'); } export function assertSafeRelativePath(rawPath: string): string { if (!rawPath || rawPath.trim() !== rawPath) { throw new Error(`Invalid relative path: ${JSON.stringify(rawPath)}`); } if ( rawPath.includes('\\') || rawPath.startsWith('/') || rawPath.endsWith('/') || DRIVE_PREFIX_REGEX.test(rawPath) || hasControlChar(rawPath) ) { throw new Error(`Unsafe relative path: ${JSON.stringify(rawPath)}`); } const segments = rawPath.split('/'); for (const segment of segments) { if (!segment || segment === '.' || segment === '..') { throw new Error(`Unsafe path segment in ${JSON.stringify(rawPath)}`); } } return segments.join('/'); } export function assertNoPathCollisions(relPaths: readonly string[]): void { const seenLower = new Map(); const normalized = relPaths.map((entry) => assertSafeRelativePath(entry)); for (const entry of normalized) { const lower = entry.toLowerCase(); const existing = seenLower.get(lower); if (existing) { throw new Error( `Conflicting paths detected: ${JSON.stringify(existing)} and ${JSON.stringify(entry)}` ); } seenLower.set(lower, entry); } // Check every ancestor directory prefix against all file paths so non-adjacent // entries such as ['a', 'a-x', 'a/b'] or ['a', 'a.x', 'a/b'] always fail closed. const ancestorDirs = new Map(); for (const entry of normalized) { const parts = entry.split('/'); for (let i = 1; i < parts.length; i += 1) { const dirPrefix = parts.slice(0, i).join('/').toLowerCase(); if (!ancestorDirs.has(dirPrefix)) { ancestorDirs.set(dirPrefix, entry); } } } for (const entry of normalized) { const conflictingDescendant = ancestorDirs.get(entry.toLowerCase()); if (conflictingDescendant) { throw new Error( `File and directory path conflict: ${JSON.stringify(entry)} vs ${JSON.stringify(conflictingDescendant)}` ); } } } async function canonicalizeRoot(rootDir: string): Promise { const absRoot = path.resolve(rootDir); const missing: string[] = []; let cursor = absRoot; while (true) { try { const stats = await fs.lstat(cursor); if (stats.isSymbolicLink()) { throw new Error(`Refusing symlinked root path: ${cursor}`); } const real = await fs.realpath(cursor); return path.join(real, ...missing.reverse()); } catch (error) { if ( typeof error === 'object' && error !== null && 'code' in error && (error as { code?: string }).code === 'ENOENT' ) { const parent = path.dirname(cursor); if (parent === cursor) { return absRoot; } missing.push(path.basename(cursor)); cursor = parent; continue; } throw error; } } } /** * Resolves `targetDir` relative to canonical `baseCwd`, walking `lstat` on * every intermediate segment inside `baseCwd` so a symlinked parent directory * (e.g. `/.agents -> /outside` when `/outside/skills` exists) fails closed. */ export async function assertContainedRoot( baseCwd: string, targetDir: string ): Promise { const canonicalCwd = await fs.realpath(path.resolve(baseCwd)); const resolved = path.resolve(canonicalCwd, targetDir); const rel = path.relative(canonicalCwd, resolved); if (!rel || rel === '.') { return canonicalCwd; } if (rel.startsWith('..') || path.isAbsolute(rel)) { return canonicalizeRoot(resolved); } const posixRel = rel.split(path.sep).join('/'); return assertNoSymlinkChain(canonicalCwd, posixRel); } export async function assertNoSymlinkChain( rootDir: string, relPath: string ): Promise { const safeRel = assertSafeRelativePath(relPath); const canonicalRoot = await canonicalizeRoot(rootDir); const segments = safeRel.split('/'); let current = canonicalRoot; for (const segment of segments) { current = path.join(current, segment); const relativeToRoot = path.relative(canonicalRoot, current); if (relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) { throw new Error(`Path escapes target root: ${safeRel}`); } try { const stats = await fs.lstat(current); if (stats.isSymbolicLink()) { throw new Error(`Refusing symlink inside target tree: ${current}`); } } catch (error) { if ( typeof error === 'object' && error !== null && 'code' in error && (error as { code?: string }).code === 'ENOENT' ) { // Remaining segments do not exist yet; keep checking containment only. continue; } throw error; } } return current; } export async function writeFileAtomic( targetPath: string, content: Buffer | string, options?: Readonly<{ mode?: number }> ): Promise { const dir = path.dirname(targetPath); await fs.mkdir(dir, { recursive: true }); const tempPath = path.join( dir, `.${path.basename(targetPath)}.tmp-${process.pid}-${randomBytes(6).toString('hex')}` ); try { await fs.writeFile(tempPath, content); if (options?.mode !== undefined) { await fs.chmod(tempPath, options.mode); } await fs.rename(tempPath, targetPath); } catch (error) { await fs.rm(tempPath, { force: true }).catch(() => undefined); throw error; } }