src/fsguard.js
// Workspace confinement. Every path in a recipe is relative to the workspace folder
// (AGENTROVE_WORKFLOW_ROOT, or the folder the CLI / MCP server was started in) and is checked here:
// - no absolute paths, drive letters, UNC paths, "..", ":" (NTFS streams), control characters or
// characters Windows refuses; no names starting with "." (protects .git, .env, .ssh and similar);
// no reserved device names (CON, NUL, COM1...); no trailing dots or spaces;
// - reads resolve links (realpath) and must stay inside the workspace;
// - writes, moves and copies never go through a link: every existing folder on the way and the
// target itself are checked with lstat;
// - listings skip links and hidden entries and never follow linked folders.
// This module only reads; src/apply.js performs the writes.
import { realpathSync, statSync, lstatSync, readdirSync, readFileSync, existsSync } from "node:fs";
import { homedir } from "node:os";
import { resolve, join, sep, parse as parsePath, relative, dirname } from "node:path";
import { ToolError } from "./errors.js";
import { compileGlob } from "./glob.js";
export const IS_WIN = process.platform === "win32";
const CASE_INSENSITIVE = IS_WIN || process.platform === "darwin";
/** Comparison key for paths: case-insensitive where the file system usually is. */
export const pathKey = (p) => (CASE_INSENSITIVE ? p.toLowerCase() : p);
export const within = (root, p) => pathKey(p) === pathKey(root) || pathKey(p).startsWith(pathKey(root.endsWith(sep) ? root : root + sep));
const RESERVED = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(?:\..*)?$/i;
const BAD = /[<>:"|?*\u0000-\u001f\u007f]/;
const BAD_GLOB = /[<>:"|\u0000-\u001f\u007f]/;
// ---------------------------------------------------------------------------------------------
// Workspace choice (security review 2026-11-26, finding C6). A folder set explicitly through the
// environment variable is used as given, except for drive/file-system roots, the home folder itself,
// the folder that holds the home folders, and system folders. Without the variable, the start folder
// is used only when it looks like a project the user chose (see PROJECT_MARKERS).
// ---------------------------------------------------------------------------------------------
export const PROJECT_MARKERS = [
".agentrove-workspace", ".git", ".hg", ".svn", ".claude", ".mcp.json", ".vscode", "CLAUDE.md", "AGENTS.md",
"package.json", "pyproject.toml", "setup.py", "requirements.txt", "go.mod", "Cargo.toml", "pom.xml", "build.gradle",
"build.gradle.kts", "composer.json", "Gemfile", "deno.json", "CMakeLists.txt", "Makefile",
];
function systemFolders() {
const env = process.env;
if (IS_WIN) {
const sys = env.SystemRoot || env.windir || "C:\\Windows";
const drive = parsePath(sys).root || "C:\\";
return {
trees: [sys, env.ProgramFiles || join(drive, "Program Files"), env["ProgramFiles(x86)"] || join(drive, "Program Files (x86)"), env.ProgramW6432, env.ProgramData || join(drive, "ProgramData"), join(drive, "$Recycle.Bin"), join(drive, "System Volume Information"), join(drive, "Recovery"), join(drive, "PerfLogs")].filter(Boolean),
exact: [join(drive, "Users"), join(drive, "Users", "Public")],
};
}
return {
trees: ["/bin", "/boot", "/dev", "/etc", "/lib", "/lib32", "/lib64", "/libx32", "/proc", "/run", "/sbin", "/sys", "/usr", "/snap", "/System", "/Library", "/Applications", "/private/etc", "/private/var/db"],
exact: ["/home", "/Users", "/var", "/private", "/private/var", "/opt", "/mnt", "/media", "/srv", "/tmp", "/private/tmp", "/Volumes", "/root"],
};
}
const realOrSelf = (p) => {
try {
return realpathSync(p);
} catch {
return resolve(p);
}
};
/** Why a folder may not be a workspace (null if it may). */
export function forbiddenWorkspace(real) {
if (parsePath(real).root === real || pathKey(parsePath(real).root) === pathKey(real + sep)) return "a drive or file-system root";
let home = "";
try {
home = realOrSelf(homedir());
} catch {
/* no home folder */
}
if (home && pathKey(real) === pathKey(home)) return "your home folder itself (choose a project folder inside it)";
if (home && pathKey(real) === pathKey(dirname(home))) return "the folder that holds the users' home folders";
const { trees, exact } = systemFolders();
for (const t of trees.map(realOrSelf)) if (within(t, real)) return `a system folder (${t})`;
for (const e of exact.map(realOrSelf)) if (pathKey(real) === pathKey(e)) return `a shared system location (${e})`;
return null;
}
/**
* Resolves and checks the workspace folder. explicit: the folder came from the environment variable
* (envName); otherwise it is the start folder and must contain a project marker.
*/
export function workspaceRoot(dir, { explicit = true, envName = "the workspace variable" } = {}) {
let real;
try {
real = realpathSync(resolve(dir));
} catch {
throw new ToolError("invalid_workspace", `The workspace folder ${dir} does not exist.`);
}
if (!statSync(real).isDirectory()) throw new ToolError("invalid_workspace", `The workspace folder ${dir} is not a folder.`);
const why = forbiddenWorkspace(real);
if (why) throw new ToolError("invalid_workspace", `Refusing to use ${real} as the workspace: it is ${why}. Set ${envName} to a project folder, or start the CLI or MCP server in one.`);
if (!explicit && !PROJECT_MARKERS.some((m) => existsSync(join(real, m)))) {
throw new ToolError("workspace_not_chosen", `${real} does not look like a project folder (no ${PROJECT_MARKERS.slice(0, 6).join(", ")}, package.json, pyproject.toml or similar). Set ${envName} to the folder you want to use, or add an empty .agentrove-workspace file to it.`);
}
return real;
}
// ---------------------------------------------------------------------------------------------
// Protected names (security review 2026-11-26, finding C5): files and folders that AI coding tools,
// package managers or build tools read as instructions, configuration or code. Write targets with
// such a name (in any folder, any case) are refused, so a confirmed write cannot plant them.
// Not exhaustive; reviewing the planned paths stays the main check.
// ---------------------------------------------------------------------------------------------
export const PROTECTED_FILES = new Set([
// AI assistant instructions, skills and MCP configuration
"claude.md", "claude.local.md", "agents.md", "agent.md", "gemini.md", "qwen.md", "copilot-instructions.md", "conventions.md", "skill.md",
"llms.txt", "llms-full.txt", ".cursorrules", ".windsurfrules", ".clinerules", ".roorules", ".goosehints",
"mcp.json", ".mcp.json", "mcp_settings.json", "cline_mcp_settings.json", "claude_desktop_config.json", "settings.json", "settings.local.json", "opencode.json", "agent.json",
// package managers, build and test tools (read or executed automatically)
"package.json", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml", "pnpm-workspace.yaml", ".npmrc", ".yarnrc", ".yarnrc.yml",
"tsconfig.json", "jsconfig.json", "deno.json", "deno.jsonc", "bunfig.toml", "composer.json", "devcontainer.json", "launch.json", "tasks.json",
"vercel.json", "netlify.toml", "turbo.json", "nx.json", "lerna.json", "renovate.json", "biome.json", ".babelrc", "babel.config.json", "jest.config.json", "firebase.json",
"pyproject.toml", "setup.py", "setup.cfg", "conftest.py", "sitecustomize.py", "usercustomize.py", "pytest.ini", "tox.ini", "requirements.txt", "pipfile",
"makefile", "gnumakefile", "dockerfile", "docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml", "cmakelists.txt", "build.gradle", "build.gradle.kts",
"settings.gradle", "settings.gradle.kts", "pom.xml", "cargo.toml", "build.rs", "go.mod", "gemfile", "rakefile", "jenkinsfile", "azure-pipelines.yml", "bitbucket-pipelines.yml",
".envrc", ".env", ".gitattributes", ".gitignore", ".gitmodules", ".editorconfig", "desktop.ini", "autorun.inf",
]);
export const PROTECTED_DIRS = new Set([".git", ".hg", ".svn", ".claude", ".cursor", ".windsurf", ".codex", ".gemini", ".continue", ".clinerules", ".roo", ".github", ".gitlab", ".vscode", ".idea", ".devcontainer", ".husky", ".config", "node_modules"]);
// Copilot instruction/prompt/chat-mode files, VS Code workspaces (can define tasks), and tool configs
// such as vite.config.ts, jest.config.js or eslint.config.mjs (loaded and run by those tools).
const PROTECTED_PATTERNS = [/\.instructions\.md$/i, /\.prompt\.md$/i, /\.chatmode\.md$/i, /\.code-workspace$/i, /^[\w-]+\.config\.(?:[cm]?[jt]s|json)$/i];
/** Throws protected_name if a write target is (or is inside) a protected name. */
export function checkWritableName(rel, field) {
const segs = rel.split("/");
for (const d of segs.slice(0, -1)) if (PROTECTED_DIRS.has(d.toLowerCase())) throw new ToolError("protected_name", `${field}: ${rel} is inside ${d}/, which tools read as configuration. Files are never written there.`);
const base = segs[segs.length - 1];
if (PROTECTED_FILES.has(base.toLowerCase()) || PROTECTED_DIRS.has(base.toLowerCase()) || PROTECTED_PATTERNS.some((p) => p.test(base))) {
throw new ToolError("protected_name", `${field}: ${base} is a name that AI assistants, package managers or build tools read as instructions, configuration or code. It is never written, so a write cannot plant one; choose another name.`);
}
}
/**
* Normalises a recipe path ("./data\\x.csv" -> "data/x.csv") or throws.
* opts.allowRoot: "." is allowed (folders). opts.glob: * ? { } , allowed.
*/
export function normalizeRel(p, field, opts = {}) {
if (typeof p !== "string" || !p.trim()) throw new ToolError("invalid_path", `${field}: the path is empty.`);
if (p.length > 400) throw new ToolError("invalid_path", `${field}: the path is longer than 400 characters.`);
let s = p.replace(/\\/g, "/");
if (s.startsWith("/") || /^[A-Za-z]:/.test(s)) throw new ToolError("path_outside_workspace", `${field}: ${p} is an absolute path. Use a path relative to the workspace folder.`);
while (s.startsWith("./")) s = s.slice(2);
if (s.endsWith("/")) s = s.replace(/\/+$/, "");
if (s === "." || s === "") {
if (opts.allowRoot) return ".";
throw new ToolError("invalid_path", `${field}: ${p} is the workspace folder itself, not a file.`);
}
const segs = s.split("/");
if (segs.length > 24) throw new ToolError("invalid_path", `${field}: ${p} is nested more than 24 folders deep.`);
for (const seg of segs) {
if (seg === "..") throw new ToolError("path_outside_workspace", `${field}: ${p} contains "..". Paths must stay inside the workspace folder.`);
if (seg === "" || seg === ".") throw new ToolError("invalid_path", `${field}: ${p} has an empty or "." segment.`);
if (/~\d+(?:\.|$)/.test(seg)) throw new ToolError("invalid_path", `${field}: ${p} contains ${seg}, which looks like a Windows 8.3 short name (they can stand for hidden names such as .env). Use the full name.`);
if (seg.startsWith(".")) throw new ToolError("hidden_path", `${field}: ${p} names a hidden file or folder (starting with "."). Hidden entries such as .git, .env or .ssh are never read or written.`);
if ((opts.glob ? BAD_GLOB : BAD).test(seg)) throw new ToolError("invalid_path", `${field}: ${p} contains a character that is not allowed in paths (< > : " | ${opts.glob ? "" : "? * "}or control characters).`);
if (/[ .]$/.test(seg) || /^ /.test(seg)) throw new ToolError("invalid_path", `${field}: ${p} has a name that starts with a space or ends with a dot or space.`);
if (RESERVED.test(seg)) throw new ToolError("invalid_path", `${field}: ${p} uses a reserved Windows device name (${seg}).`);
if (seg.length > 200) throw new ToolError("invalid_path", `${field}: a name in ${p} is longer than 200 characters.`);
}
return segs.join("/");
}
export const absOf = (root, rel) => (rel === "." ? root : join(root, ...rel.split("/")));
const relOf = (root, abs) => relative(root, abs).split(sep).join("/") || ".";
function lstatOrNull(p) {
try {
return lstatSync(p);
} catch (e) {
if (e.code === "ENOENT" || e.code === "ENOTDIR") return null;
throw new ToolError("io_error", `Cannot inspect ${p}: ${e.code ?? e.message}.`);
}
}
/** Resolves an existing path for reading: links are followed but must end inside the workspace, at a non-hidden entry. */
export function resolveForRead(root, rel, field, kind = "file") {
const abs = absOf(root, rel);
let real;
try {
real = realpathSync(abs);
} catch {
throw new ToolError("not_found", `${field}: ${rel} was not found in the workspace.`);
}
if (!within(root, real)) throw new ToolError("path_outside_workspace", `${field}: ${rel} resolves (through a link) to a location outside the workspace.`);
const realRel = relOf(root, real);
if (realRel !== "." && realRel.split("/").some((s) => s.startsWith("."))) throw new ToolError("hidden_path", `${field}: ${rel} resolves to a hidden file or folder.`);
const st = statSync(real);
if (kind === "file" && !st.isFile()) throw new ToolError("invalid_path", `${field}: ${rel} is not a regular file.`);
if (kind === "dir" && !st.isDirectory()) throw new ToolError("invalid_path", `${field}: ${rel} is not a folder.`);
return { abs: real, size: st.size, mtimeMs: st.mtimeMs };
}
/** Reads a text file inside the workspace (size-limited, UTF-8, BOM removed, binary refused). */
export function readText(ctx, rel, field) {
const r = resolveForRead(ctx.root, rel, field, "file");
if (r.size > ctx.limits.max_file_bytes) throw new ToolError("limit_exceeded", `${field}: ${rel} is ${r.size} bytes; the limit is ${ctx.limits.max_file_bytes} bytes per file.`);
ctx.addRead(r.size, field);
const buf = readFileSync(r.abs);
if (buf.length > ctx.limits.max_file_bytes) throw new ToolError("limit_exceeded", `${field}: ${rel} grew past the size limit while it was read.`);
if (buf.subarray(0, 8000).includes(0)) throw new ToolError("invalid_input", `${field}: ${rel} looks like a binary file, not text.`);
ctx.sources.set(pathKey(rel), { path: rel, size: buf.length, mtime_ms: Math.trunc(r.mtimeMs) });
let text = buf.toString("utf8");
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
return text;
}
/**
* Lists files under the workspace that match a glob (relative to the workspace root). Skips hidden
* entries and links (counted), never follows linked folders. Returns sorted file records.
*/
export function findFiles(ctx, pattern, field, { includeDirs = false } = {}) {
const g = compileGlob(pattern, field);
const baseAbs = resolveForRead(ctx.root, g.base, field, "dir").abs;
const out = [];
let skippedLinks = 0;
let skippedHidden = 0;
const maxDepth = Math.min(g.maxDepth, 12);
const walk = (dirAbs, depth) => {
ctx.tick();
let entries;
try {
entries = readdirSync(dirAbs, { withFileTypes: true });
} catch (e) {
throw new ToolError("io_error", `${field}: cannot list ${relOf(ctx.root, dirAbs)} (${e.code ?? e.message}).`);
}
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
for (const e of entries) {
if (e.name.startsWith(".")) {
skippedHidden++;
continue;
}
const abs = join(dirAbs, e.name);
if (e.isSymbolicLink()) {
skippedLinks++;
continue;
}
const rel = relOf(ctx.root, abs);
if (e.isDirectory()) {
if (includeDirs && g.match(rel)) out.push({ rel, abs, dir: true });
if (depth + 1 < maxDepth) walk(abs, depth + 1);
} else if (e.isFile() && g.match(rel)) out.push({ rel, abs, dir: false });
if (out.length > ctx.limits.max_files) throw new ToolError("limit_exceeded", `${field}: more than ${ctx.limits.max_files} matching files. Narrow the pattern or raise limits.max_files (hard limit 10000).`);
}
};
walk(baseAbs, 0);
if (skippedLinks) ctx.warn(`${field}: skipped ${skippedLinks} link(s) (symbolic links and junctions are never followed or listed).`);
void skippedHidden;
return out.map((f) => {
const st = statSync(f.abs);
const name = f.rel.split("/").pop();
const dot = name.lastIndexOf(".");
const folder = f.rel.includes("/") ? f.rel.slice(0, f.rel.lastIndexOf("/")) : ".";
return {
path: f.rel,
name,
stem: dot > 0 ? name.slice(0, dot) : name,
ext: dot > 0 ? name.slice(dot + 1).toLowerCase() : "",
folder,
kind: f.dir ? "folder" : "file",
size: f.dir ? 0 : st.size,
modified: new Date(Math.trunc(st.mtimeMs)).toISOString(),
_mtime_ms: Math.trunc(st.mtimeMs),
};
});
}
/**
* Inspects a target path for writing (nothing is created). Every existing folder on the way must be a
* real folder (not a link); the target must be absent or a regular file that is not a link.
* Returns { rel, abs, exists, size, mtimeMs, nlink, missingFolders: [rel...] }.
*/
export function inspectTarget(root, rel, field) {
const segs = rel.split("/");
const missing = folderChain(root, segs.slice(0, -1), field);
if (!missing.length) {
// Belt and braces: the deepest existing folder must resolve inside the workspace.
const parentReal = realpathSync(segs.length > 1 ? join(root, ...segs.slice(0, -1)) : root);
if (!within(root, parentReal)) throw new ToolError("path_outside_workspace", `${field}: the folder for ${rel} resolves outside the workspace.`);
}
const abs = join(root, ...segs);
const st = missing.length ? null : lstatOrNull(abs);
if (st?.isSymbolicLink()) throw new ToolError("unsafe_path", `${field}: ${rel} is a link (symbolic link or junction). workflow-automation never writes through or replaces links.`);
if (st && !st.isFile()) throw new ToolError("invalid_path", `${field}: ${rel} exists and is not a regular file.`);
return { rel, abs, exists: !!st, size: st?.size ?? 0, mtimeMs: st ? Math.trunc(st.mtimeMs) : 0, nlink: st?.nlink ?? 0, missingFolders: missing };
}
/** Checks folders root/segs[0]/segs[1]/...: each existing one must be a real folder (not a link). Returns the missing ones. */
export function folderChain(root, segs, field) {
let cur = root;
const missing = [];
for (let i = 0; i < segs.length; i++) {
cur = join(cur, segs[i]);
const folderRel = segs.slice(0, i + 1).join("/");
if (missing.length) {
missing.push(folderRel);
continue;
}
const st = lstatOrNull(cur);
if (!st) missing.push(folderRel);
else if (st.isSymbolicLink()) throw new ToolError("unsafe_path", `${field}: the folder ${folderRel} is a link (symbolic link or junction). workflow-automation never writes through links.`);
else if (!st.isDirectory()) throw new ToolError("invalid_path", `${field}: ${folderRel} exists and is not a folder.`);
}
return missing;
}
/** Source of a move or copy: an existing regular file (not a link) inside the workspace. */
export function inspectSource(root, rel, field) {
const segs = rel.split("/");
let cur = root;
for (let i = 0; i < segs.length - 1; i++) {
cur = join(cur, segs[i]);
const st = lstatOrNull(cur);
if (!st) throw new ToolError("not_found", `${field}: ${rel} was not found in the workspace.`);
if (st.isSymbolicLink()) throw new ToolError("unsafe_path", `${field}: the folder ${segs.slice(0, i + 1).join("/")} is a link; files behind links are never moved or copied.`);
}
const abs = join(root, ...segs);
const st = lstatOrNull(abs);
if (!st) throw new ToolError("not_found", `${field}: ${rel} was not found in the workspace.`);
if (st.isSymbolicLink()) throw new ToolError("unsafe_path", `${field}: ${rel} is a link; links are never moved or copied.`);
if (!st.isFile()) throw new ToolError("invalid_path", `${field}: ${rel} is not a regular file (only files are moved or copied).`);
return { rel, abs, size: st.size, mtimeMs: Math.trunc(st.mtimeMs) };
}
export function readBytes(abs) {
return readFileSync(abs);
}