UNPKG

@anthropic-ai/sdk

Version:
277 lines • 12 kB
import { crypto, fs as nodefs, path } from "../../internal/node.mjs"; import { readEnv } from "../../internal/utils/env.mjs"; import { ToolError } from "../../lib/tools/ToolError.mjs"; const fs = nodefs.promises; /** Mode for directories the file tools create: owner-only under any umask, like the memory tool. */ export const DIR_CREATE_MODE = 0o700; /** * Mode for files the file tools create: owner-only, so other local users can't * read what an agent wrote. A file that already exists keeps its own mode. */ export const FILE_CREATE_MODE = 0o600; /** True when `p` is `root` itself or lexically contained within it, with names compared exactly. */ export function isWithin(root, p) { const from = path.resolve(root); const to = path.resolve(p); return to === from || to.startsWith(from.endsWith(path.sep) ? from : from + path.sep); } /** * {@link isWithin}, but on Windows also true for names that differ only by case, * for checks that refuse. */ export function isWithinAnyCase(root, p) { const rel = path.relative(root, p); return rel === '' || (!rel.startsWith('..' + path.sep) && rel !== '..' && !path.isAbsolute(rel)); } /** {@link isWithin} with letter case and Unicode form ignored on every platform, for checks that refuse. */ function isWithinFolded(root, p) { return isWithin(root.toLowerCase().normalize('NFC'), p.toLowerCase().normalize('NFC')); } /** * The first entry of `roots` whose canonical form contains the * already-canonical `target`, returned as configured; `undefined` when none * does. Each root goes through {@link canonicalize} at check time, exactly like * the workdir in {@link confineToRoot}, so granting access (`allowedRoots`) * and refusing writes (`readOnlyRoots`) can never resolve the same entry two * different ways. */ export async function containingRoot(roots, target, contains = isWithin) { for (const root of roots) { if (contains(await canonicalize(path.resolve(root)), target)) return root; } return undefined; } /** Matches Linux MAXSYMLINKS, the threshold at which `realpath` itself reports ELOOP. */ const MAX_SYMLINK_HOPS = 40; /** The `code` of a Node system error, or `undefined` for anything else. */ export function errnoCode(err) { const code = err?.code; return typeof code === 'string' ? code : undefined; } /** * Fully resolve `abs`: `realpath` the longest existing ancestor and re-append * the rest, but never re-append a component that is itself a symlink — read the * link and continue from its target instead. This handles paths being created * (write/edit) without letting a symlink leaf (e.g. a dangling one pointing * outside a confinement root) slip through unresolved. * * Returns a symlink-free path or throws an errno-carrying error (`ELOOP` for a * cycle or more than {@link MAX_SYMLINK_HOPS} links, the `lstat`/`realpath` * error for an unreadable component); it never returns `abs` unresolved. Only * symlink hops count against the cap, so any depth of not-yet-existing * directories still resolves. */ export async function canonicalize(abs) { const tail = []; let prefix = abs; let hops = 0; for (;;) { let real; try { real = await fs.realpath(prefix); } catch (realpathErr) { let isLink; try { isLink = (await fs.lstat(prefix)).isSymbolicLink(); } catch (lstatErr) { const code = errnoCode(lstatErr); if (code !== 'ENOENT' && code !== 'ENOTDIR') throw lstatErr; const parent = path.dirname(prefix); if (parent === prefix) throw lstatErr; tail.push(path.basename(prefix)); prefix = parent; continue; } if (!isLink) throw realpathErr; if (++hops > MAX_SYMLINK_HOPS) { throw Object.assign(new Error('too many levels of symbolic links'), { code: 'ELOOP' }); } const parent = await fs.realpath(path.dirname(prefix)); prefix = path.resolve(parent, await fs.readlink(prefix), ...tail.splice(0).reverse()); continue; } return tail.length ? path.join(real, ...tail.reverse()) : real; } } /** * Resolve `p` against `root` and confine it to `root` or one of `allowedRoots` * (absolute paths, resolved at check time exactly like `root`). * * Absolute and relative inputs go through the same canonicalise-then-contain * check — an absolute path that lands inside a permitted root is accepted, * only paths that resolve *outside* all of them are rejected. Every symlink in * `p` (including the leaf, even a dangling one) is resolved before the * confinement check, and the resolved path is what the caller then operates * on, so a symlink inside `root` that points outside it can neither pass the * check nor be followed afterwards. `..` is collapsed lexically before any * symlink is followed. A path that cannot be resolved (symlink loop, unreadable * component) is rejected with a `ToolError` naming `p`, never the host's * absolute path. * * Residual TOCTOU: a component could still be swapped for a symlink between this * call and the eventual `fs` operation. Closing that fully needs per-component * `O_NOFOLLOW`/`openat`, which Node does not expose ergonomically; this is why a * sandbox is still recommended for the toolset as a whole. */ export async function confineToRoot(root, p, opts) { const allowedRoots = opts?.allowedRoots ?? []; const realRoot = await canonicalize(path.resolve(root)); let real; try { real = await canonicalize(path.resolve(realRoot, p)); } catch (err) { throw new ToolError(fsErrorMessage(err, `path ${JSON.stringify(p)}`)); } if (isWithin(realRoot, real) || (await containingRoot(allowedRoots, real)) !== undefined) { return real; } const permitted = allowedRoots.length ? "the session's working directory and its other permitted directories" : "the session's working directory"; throw new ToolError(`path ${JSON.stringify(p)} is outside ${permitted}`); } /** * Atomically write `content` to `targetPath`: write a sibling temp file, fsync * it, then rename over the target. The rename is atomic on most filesystems, so * a crash mid-write never leaves the target half-written. * * A new file is created {@link FILE_CREATE_MODE}; an existing one keeps its * permission bits (the rename replaces the inode, so they are copied onto the * temp file first) — an edit must not strip `+x` or sharing the owner chose. */ export async function atomicWriteFile(targetPath, content) { const dir = path.dirname(targetPath); const tempPath = path.join(dir, `.tmp-${process.pid}-${crypto.randomUUID()}`); const existingMode = await fs.stat(targetPath).then((st) => st.mode & 0o777, () => undefined); let handle; try { handle = await fs.open(tempPath, 'wx', FILE_CREATE_MODE); if (existingMode !== undefined) await handle.chmod(existingMode); await handle.writeFile(content, 'utf-8'); await handle.sync(); await handle.close(); handle = undefined; await fs.rename(tempPath, targetPath); } catch (err) { if (handle) await handle.close().catch(() => { }); await fs.unlink(tempPath).catch(() => { }); throw err; } } /** * Map a thrown filesystem error to a consistent, language-independent message, * so the model sees the same wording regardless of the runtime (Node's raw * `ENOENT: no such file...` text would otherwise leak through). Codes we don't * special-case render as the bare code, never Node's message, which embeds the * host's absolute path. */ export function fsErrorMessage(err, file) { const code = errnoCode(err); switch (code) { case 'ENOENT': return `${file}: no such file or directory`; case 'EACCES': case 'EPERM': return `${file}: permission denied`; case 'ENOTDIR': return `${file}: not a directory`; case 'EISDIR': return `${file}: is a directory`; case 'ELOOP': return `${file}: too many levels of symbolic links`; case 'ENAMETOOLONG': return `${file}: file name too long`; case 'ENOSPC': return `${file}: no space left on device`; case 'EMFILE': case 'ENFILE': return `${file}: too many open files`; default: return `${file}: ${code !== undefined ? `i/o error (${code})` : 'i/o error'}`; } } /** * The first executable file called `name` in an entry of `searchPath`, or `null`. An entry that is * relative to the current directory or, on Windows, to the current drive (`\bin`) is skipped. * With `notInside`, so is a file that resolves to somewhere inside one of those directories, * and the result is the resolved path that was checked. * @internal */ export async function findExecutable(name, notInside = [], searchPath = readEnv('PATH') ?? '') { for (const dir of absolutePathEntries(searchPath)) { const candidate = path.join(dir, name); try { await fs.access(candidate, nodefs.constants.X_OK); if (!(await fs.stat(candidate)).isFile()) continue; if (notInside.length === 0) return candidate; const real = await fs.realpath(candidate); if ((await containingRoot(notInside, real, isWithinFolded)) === undefined) return real; } catch { // not here, or no telling where it is } } return null; } /** * The resolved `PATH` entries outside the `notInside` directories, or `null` when there are none. * Left out are an entry that would read as two, and one where a `helpers` name leads inside. * Throws when a `notInside` directory can't be resolved, so there is no telling what is outside. * @internal */ export async function searchPathOutside(notInside, helpers) { const resolve = (p) => fs.realpath(p).catch(() => undefined); const isInside = async (real) => (await containingRoot(notInside, real, isWithinFolded)) !== undefined; let outside = null; nextEntry: for (const dir of absolutePathEntries(readEnv('PATH') ?? '')) { const real = await resolve(dir); // An entry that isn't there supplies nothing, but one outside still means `PATH` reaches outside. if (await isInside(real ?? (await canonicalize(dir).catch(() => dir)))) continue; outside ?? (outside = []); if (real === undefined || real.includes(path.delimiter)) continue; for (const name of helpers) { const helper = await resolve(path.join(real, name)); if (helper !== undefined && (await isInside(helper))) continue nextEntry; } outside.push(real); } return outside && outside.join(path.delimiter); } function absolutePathEntries(searchPath) { return searchPath .split(path.delimiter) .filter((dir) => path.isAbsolute(dir) && path.resolve(dir) === path.join(dir, '.')); } /** * The environment for a program the toolset starts: that of this process without the `ANTHROPIC_*` * variables, in any letter case, as Windows reads them. They hold its credentials, the API key, the * auth token and the per-work session token among them. Everything else (PATH, HOME, locale, …) is * passed through unchanged. * @internal */ export function scrubbedShellEnv() { const env = {}; for (const [key, value] of Object.entries(process.env)) { if (key.toUpperCase().startsWith('ANTHROPIC_')) continue; env[key] = value; } return env; } //# sourceMappingURL=fs-util.mjs.map