UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

556 lines (555 loc) • 35.9 kB
import { posix, win32 } from "node:path"; import { planShellReads } from "./shell-read-plan.js"; import { startedShellOfCall } from "../../core/call-shell.js"; import { literalTextOf, SUBSTITUTION_PLACEHOLDER } from "../../shell/lex.js"; import { createShellReadEstablisher, establishShellReadsLexically } from "./shell-read-establish.js"; import { isAbsoluteForFamily, isWinFormPath, normalizeAbsPathLexically } from "./safety.js"; import { isDeviceSpelling, localDriveSpellingOf, nativeSepOf } from "../../core/unc-spelling.js"; import { launchedCommands, launchedReadings, reentryText, runsStoredLine, scriptFileAt, spellLaunched, streamSuppliesOnlyData } from "./shell-reentry-text.js"; import { programPositionRefusalSentence, readProgramPosition } from "./bash-program-position.js"; import { bashClassifyDefaultAllow } from "./bash-readonly-classifier.js"; import { programArgs } from "./shell-read-write-targets.js"; import { declaresOption, implementationsOf, programRow, rowRefusesArgv, runsShellText, selectedOptions, writeReadings } from "./program-read-model.js"; import { inlineUntrusted } from "../../core/untrusted-text.js"; import { certainlyRunOn, deletesEverythingFrom, findActionsOf, findDirsDown, findHandedCommands, findStartsOf, findWordOf } from "./find-actions.js"; import { removalActionOf as actionOf, SHELL_REMOVAL_COMMANDS } from "./removal-actions.js"; import { unreadActingFinds } from "./find-unread-lead.js"; export { SHELL_REMOVAL_ACTIONS, SHELL_REMOVAL_COMMANDS } from "./removal-actions.js"; const REMOVAL_COMMAND_SET = new Set(SHELL_REMOVAL_COMMANDS); function removalSeatAt(seat, plan, segment, apart) { const started = seat.startedIn ?? []; const left = started.length > 0 && !apart && segment.bases !== "unmodelled" && segment.bases.length > 0 && segment.bases.every((b) => seat.departures?.has(b) === true) && !plan.shape.backgrounded; return { homes: seat.homes, workspace: [...seat.workspace, ...(left ? [] : started)] }; } function standsWithin(path, dir) { return KEY_READINGS.some((reading) => { const k = removalKey(path, STAR_RUN, reading); const d = removalKey(dir, STAR_RUN, reading); return k === d || k.startsWith(d.endsWith("/") ? d : `${d}/`); }); } async function departuresOf(plan, startedIn, start, env, signal) { const out = new Set(); if (start === undefined) return out; for (const base of new Set(plan.segments.flatMap((s) => (s.bases === "unmodelled" ? [] : s.bases)))) { if (standsWithin(base, startedIn) || standsWithin(base, start)) continue; const canonical = await answeredLocation(env, base, signal); if (canonical !== undefined && !standsWithin(canonical, start)) out.add(base); } return out; } const EVERY_ENTRY_SEGMENT = String.raw `(?:\*+(?:\?\**)?|\?\*+|\**\[[!^]\.\]\*+)`; const STAR_RUN = /(?:[\\/]+\*+)+[\\/]*$/; const ENTRY_SEGMENT = new RegExp(`^${EVERY_ENTRY_SEGMENT}$`); function bareRunOf(word, windows) { const units = word.pieces.flatMap((p) => { const glob = p.expansion?.pattern; if (glob !== undefined) { const negated = /^\[[!^]/.test(glob.written) && /^\.+$/.test(glob.folded.slice(2, -1)); return [{ folded: glob.folded, ...(glob.folded.length === 1 ? { entry: glob.folded } : negated ? { entry: "[!.]" } : {}) }]; } return p.literal === undefined ? [{}] : [...p.literal].map((c) => (c === "/" || (windows && c === "\\") ? { sep: true } : {})); }); const run = []; let end = units.length; while (end > 0 && units[end - 1].sep === true) end--; while (end > 0) { let start = end; while (start > 0 && units[start - 1].sep !== true) start--; const segment = units.slice(start, end); if (!segment.every((u) => u.entry !== undefined) || !ENTRY_SEGMENT.test(segment.map((u) => u.entry).join(""))) break; run.unshift(segment.map((u) => u.folded).join("")); end = start; while (end > 0 && units[end - 1].sep === true) end--; } return run; } const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const exactRun = (segments) => new RegExp(`${segments.map((s) => `[\\\\/]+${escapeRegExp(s)}`).join("")}[\\\\/]*$`); function everyEntryRunOf(read, word) { const windows = isWinFormPath(read.target ?? read.origin ?? read.candidate.spelled); const bare = read.candidate.expands === "glob" && word !== undefined ? bareRunOf(word, windows) : []; if (bare.every((s) => /^\*+$/.test(s))) return () => STAR_RUN; const exact = exactRun(bare); const listed = read.established === "expansion" ? read.target : undefined; return (view) => (view !== listed && exact.test(view) ? exact : STAR_RUN); } const trailingSeparatorOf = (read) => /\/+$/.exec(read.candidate.raw)?.[0] ?? ""; function removalKey(path, every = STAR_RUN, reading = "as_written") { const read = reading === "drive" ? (localDriveSpellingOf(path) ?? path) : path; let k = normalizeAbsPathLexically(read.normalize("NFC")).replace(/\\/g, "/").toLowerCase(); k = k.replace(every, ""); const drive = driveOf(path, k); let rest = k.slice(drive.length); if (rest === "") rest = "/"; if (rest.length > 1) rest = rest.replace(/\/+$/, ""); return drive + rest.replace(/^\/private\/(etc|var|tmp|home)(?=\/|$)/, "/$1"); } const KEY_READINGS = ["as_written", "drive"]; function driveOf(path, key) { return isWinFormPath(path) && key.length >= 2 && key[1] === ":" ? key.slice(0, 2) : ""; } const MOUNTED_DRIVE_KEY = /^\/(?:system\/)?volumes(?:\/[^/]+){0,2}$|^\/mnt\/(?:[^/]+|[a-z]\/[^/]+)$|^\/(?:run\/)?media(?:\/[^/]+){0,3}$/; function segmentsUp(path, levels) { const family = isWinFormPath(path) ? win32 : posix; let at = path; for (let i = 0; i < levels; i++) at = family.dirname(at); return at; } const runParts = (run) => run.match(/[\\/]+[^\\/]+/g) ?? []; const runAt = (dir, run) => `${dir.replace(isWinFormPath(dir) ? /[\\/]+$/ : /\/+$/, "")}${run.replace(/[\\/]+/g, nativeSepOf(dir))}`; function emptiedDirectoriesOf(read, views, everyFor) { const tail = trailingSeparatorOf(read); const levelOf = (every, parts) => (every === STAR_RUN ? STAR_RUN : exactRun(parts.map((p) => p.replace(/^[\\/]+/, "")))); const every = read.origin !== undefined ? everyFor(read.origin) : STAR_RUN; const pattern = read.established === "expansion" && read.origin !== undefined ? every.exec(read.origin) : null; if (pattern !== null) { const match = read.spellings.find((s) => s !== read.origin); const parts = runParts(pattern[0]); return match === undefined ? [] : parts.map((_, i) => ({ dir: segmentsUp(match, parts.length - i), run: `${parts.slice(i).join("")}${tail}`, every: levelOf(every, parts.slice(i)) })); } return views.flatMap((view) => { const viewEvery = everyFor(view); const m = viewEvery.exec(view); return m === null ? [] : [{ dir: segmentsUp(view, runParts(m[0]).length), run: `${runParts(m[0]).join("")}${tail}`, every: viewEvery }]; }); } export function dangerousRemovalOf(path, seat, rm, every = STAR_RUN) { if (!isAbsoluteForFamily("own", path)) return undefined; return removalKindIn("as_written", path, seat, rm, every) ?? removalKindIn("drive", path, seat, rm, every); } function removalKindIn(reading, path, seat, rm, every) { const k = removalKey(path, every, reading); const drive = driveOf(path, k); const rest = k.slice(drive.length); if (rest === "/" || /^\/\/[^/]+\/[^/]+$/.test(k)) return "filesystem_root"; if (seat.homes.some((h) => isAbsoluteForFamily("own", h) && removalKey(h, STAR_RUN, reading) === k)) return "home"; const prefix = k.endsWith("/") ? k : `${k}/`; if (seat.workspace.some((w) => isAbsoluteForFamily("own", w) && (removalKey(w, STAR_RUN, reading) === k || removalKey(w, STAR_RUN, reading).startsWith(prefix)))) return "workspace"; if (/^\/[^/]+$/.test(rest)) return "top_level"; if (rm !== undefined && (rm.recursive || every.test(path)) && drive === "" && !k.startsWith("//") && MOUNTED_DRIVE_KEY.test(rest)) return "mounted_drive"; return undefined; } function tildeNamesAHome(spelled, everyFor) { const m = /^~([^/]*)(\/.*)?$/.exec(spelled); if (m === null) return false; const home = `/~home${m[2] ?? ""}`; const key = removalKey(home, everyFor(home)); return key === "/~home" || !key.startsWith("/~home/"); } function removalKindOf(read, word, seat, rm, answered) { const everyFor = everyEntryRunOf(read, word); const unplaced = read.established === "unestablishable"; const floors = unplaced && read.candidate.bases === "unmodelled" ? read.spellings : []; const views = [read.target, read.origin, ...floors].filter((v) => v !== undefined); const assumed = new Set([...floors, ...(isDeviceSpelling(read.candidate.spelled) && read.target !== undefined ? [read.target] : [])]); const tail = trailingSeparatorOf(read); for (const view of views) { const every = everyFor(view); const kind = dangerousRemovalOf(view, seat, rm, every); if (kind !== undefined) return { kind, at: assumed.has(view) ? read.candidate.spelled : tail !== "" && every.test(view) ? `${view.replace(/[\\/]+$/, "")}${tail}` : view }; } for (const { dir, run, every } of emptiedDirectoriesOf(read, views, everyFor)) { const answer = isAbsoluteForFamily("own", dir) ? answered(dir) : undefined; for (const at of [...(answer !== undefined ? [runAt(answer, run)] : []), runAt(dir, run)]) { const kind = dangerousRemovalOf(at, seat, rm, every); if (kind !== undefined) return { kind, at }; } } return unplaced && tildeNamesAHome(read.candidate.spelled, everyFor) ? { kind: "home", at: read.candidate.spelled } : undefined; } export const KNOWN_SAFE_ROOTS = Object.freeze(["TMPDIR", "HOME"]); function belowKnownSafeRoot(word, safe, segment) { const [head, ...rest] = word.pieces; const e = head?.expansion; const name = e?.kind === "parameter" && (e.body === undefined || e.body === e.name) ? e.name : undefined; if (name === undefined || !safe.has(name) || segment.rebound === "all" || segment.rebound.has(name)) return false; if (rest.some((p) => p.literal === undefined)) return false; const below = rest.map((p) => p.literal).join(""); return /^\/[^*?[\]]+$/.test(below) && !below.split("/").includes(".."); } function optionsReceived(row, args) { const rewrittenAt = args.findIndex((w) => w.rewritten === true); const asWritten = (rewrittenAt < 0 ? args : args.slice(0, rewrittenAt)).map((w) => w.spelled); const present = args.filter((w) => w.vanishes !== true); const chosenAt = present.findIndex((w) => w.rewritten === true); const shellChooses = chosenAt >= 0 && writeReadings(row, present.slice(0, chosenAt + 1).map((w) => w.spelled)).some((r) => r.written.length === 0); return { refused: rowRefusesArgv(row, asWritten), shellChooses }; } const TRAVERSAL = (o) => o.selects === "traversal"; const FORCED = (o) => o.mode === "forced"; function selectsOptions(row, args, shellChooses, ...wanted) { return implementationsOf(row).some((view) => { const selected = selectedOptions(view, args, "one-implementation"); return wanted.every((has) => selected.some(has) || (shellChooses && declaresOption(view, has))); }); } export function removalFindingsOf(shell, established, seat, safeRoots = KNOWN_SAFE_ROOTS, answered = () => undefined) { const unread = unreadPlan(established.plan) ? [{ guard: "unverifiable_shell_text", program: shell, text: established.plan.unreadable, source: "unread" }] : []; return [...unread, ...segmentFindingsOf(established, seat, safeRoots, answered, false, false)]; } function segmentFindingsOf(established, seat, safeRoots, answered, enclosingRelocated, apart, entries = []) { const out = []; const safe = new Set(safeRoots); for (const segment of established.plan.segments) { const program = segment.verb?.basename; const position = readProgramPosition(segment.argv); const removal = removalProgramOf(segment); const args = removal === undefined ? [] : programArgs(segment); const spelled = args.map((w) => w.spelled); const received = removal === undefined ? undefined : optionsReceived(removal.row, args); if (removal !== undefined && received?.refused === false) { const { row, named } = removal; const removed = new Set(writeReadings(row, spelled).flatMap((r) => r.written.map((w) => w.at))); const options = new Set(args.filter((_, at) => !removed.has(at)).map((w) => w.raw)); const forced = selectsOptions(row, spelled, received.shellChooses, TRAVERSAL, FORCED); const rm = row.key === "rm" || !named ? { recursive: selectsOptions(row, spelled, received.shellChooses, TRAVERSAL) } : undefined; if (forced && segment.reentry === "argv") out.push({ guard: "unverifiable_delete", program: removal.program, operand: segment.text.trim(), source: "stream" }); const relocated = enclosingRelocated || position.baseMovedAt.length > 0; for (const read of established.reads.get(segment) ?? []) { if ((named && read.candidate.face !== "write") || read.candidate.provenance === "program_path" || options.has(read.candidate.raw)) continue; if (refusedByRemoval(read)) continue; const word = segment.argv.find((w) => w.raw === read.candidate.raw); const at = removalSeatAt(seat, established.plan, segment, apart); const judged = removalKindOf(read, word, at, rm, answered) ?? narrowedEntryKindOf(read, entries, at, rm); if (judged !== undefined) { const untracked = read.candidate.bases === "unmodelled" ? established.plan.segments.find((s) => s.bases === "unmodelled")?.text.trim() : undefined; out.push({ guard: "dangerous_delete", kind: judged.kind, program: removal.program, operand: read.candidate.raw, target: judged.at, ...(untracked !== undefined ? { untrackedFrom: untracked } : {}) }); continue; } if (!forced || read.established !== "unestablishable" || (read.candidate.expands !== "unresolvable" && !relocated)) continue; if (word !== undefined && belowKnownSafeRoot(word, safe, segment)) continue; out.push({ guard: "unverifiable_delete", program: removal.program, operand: read.candidate.raw, source: read.candidate.expands === "unresolvable" ? "rewritten" : "relocated" }); } } const walk = removalWalkOf(segment); if (walk !== undefined) out.push(...walkFindingsOf(established, segment, walk, seat, safe, apart, enclosingRelocated || position.baseMovedAt.length > 0, answered)); const script = runtimeScriptOf(segment, !apart && streamDataContext(established.plan, segment)); if (script !== undefined && program !== undefined) out.push({ guard: "unverifiable_shell_text", program, text: script, source: "produced" }); if (program !== undefined && programWordFromOwnText(segment)) out.push({ guard: "unverifiable_shell_text", program: program.includes(SUBSTITUTION_PLACEHOLDER) ? segment.text.trim() : program, text: segment.text.trim(), source: "produced" }); if (programUnread(segment)) { const refusal = position.refusal; const named = segment.launcherChain[0] ?? segment.text.trim(); out.push(refusal !== undefined ? { guard: "unverifiable_shell_text", program: named, refusal, source: "position" } : { guard: "unverifiable_shell_text", program: named, text: segment.text.trim(), source: "unread" }); } const handedRelocated = enclosingRelocated || position.baseMovedAt.length > 0; const narrowed = narrowedEntriesOf(established, segment, removalSeatAt(seat, established.plan, segment, apart)); for (const nested of segment.nested) { if (unreadPlan(nested)) out.push({ guard: "unverifiable_shell_text", program: program ?? segment.text.trim(), text: segment.text.trim(), source: "unread" }); const sub = established.nested.get(nested); const line = nested.segments.length === 1 ? nested.segments[0].text.trim() : undefined; if (sub !== undefined) out.push(...segmentFindingsOf(sub, seat, safeRoots, answered, handedRelocated, true, (line !== undefined ? narrowed.get(line) : undefined) ?? [])); } } return out; } function runtimeScriptOf(segment, dataContext = false) { const program = segment.verb; if (segment.reentry !== "shell" || program === undefined || !runsShellText(program.basename)) return undefined; const MARK = "\u0000"; const spell = (k, from = 0) => { const w = segment.argv[k]; const literal = literalTextOf(w.pieces); return literal !== undefined ? literal.slice(from) : `${MARK}${w.raw.slice(from)}`; }; const pos = readProgramPosition(segment.argv); if (pos.program !== undefined && pos.refusal === undefined) { const argv = segment.argv.slice(pos.program.index + 1); const file = scriptFileAt(program.basename, argv.map((w) => w.folded)); const source = file === undefined ? undefined : argv[file]; if (source !== undefined && source.pieces.length === 1 && source.pieces[0].expansion?.kind === "process") return source.raw; const dataOnly = dataContext && segment.rebound !== "all" && segment.rebound.size === 0 && streamSuppliesOnlyData(segment.argv); if ((pos.argvFromStdin && !dataOnly) || runsStoredLine(program.basename, argv.map((w) => w.folded))) return segment.text.trim(); } const named = pos.program !== undefined && pos.refusal === undefined ? [{ shell: program.basename, words: segment.argv.slice(pos.program.index + 1).map((_, k) => spell(pos.program.index + 1 + k)) }] : []; const launched = launchedCommands(segment.argv, pos).flatMap((c) => { const shell = launchedReadings(segment.argv, c).shell; return shell === undefined ? [] : [{ shell, words: spellLaunched(segment.argv, c.args, { word: spell }) }]; }); const texts = [...named, ...launched].flatMap(({ shell, words }) => [reentryText(shell, words), ...(segment.stdin ?? []).map((s) => reentryText(shell, words, s.literal ?? `${MARK}${s.from}`))]); const text = texts.find((t) => t?.includes(MARK) === true); return text === undefined ? undefined : text.split(MARK).join(""); } const unreadPlan = (plan) => plan.unreadable !== undefined && (plan.unreadTail !== undefined || plan.segments.length === 0); const programUnread = (s) => s.declines.includes("unreadable_program_position"); const unsettledProgramReads = (s) => s.verb === undefined ? [] : s.reads.filter((c) => c.provenance === "program_path" && c.expands === "unresolvable"); const programNameUnsettled = (s) => unsettledProgramReads(s).length > 0; const POSITIONAL_PARAMETER = /^(?:\d+|[@*])$/; const POSITIONAL_IN_TEXT = /\$\{?[\d@*]/; const reboundName = (s, name) => s.rebound !== "all" && s.rebound.has(name); const valueFromOwnText = (e, s) => { if (e.kind === "command") return e.body !== undefined && (POSITIONAL_IN_TEXT.test(e.body) || [...e.body.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)/g)].some((m) => reboundName(s, m[1]))); if (e.kind !== "parameter") return false; return (e.name !== undefined && (POSITIONAL_PARAMETER.test(e.name) || reboundName(s, e.name))) || (e.body !== undefined && POSITIONAL_IN_TEXT.test(e.body)); }; const programWordFromOwnText = (s) => unsettledProgramReads(s).some((c) => s.argv.find((w) => w.raw === c.raw)?.pieces.some((p) => p.expansion !== undefined && valueFromOwnText(p.expansion, s)) === true); const RM_REMOVAL_ROW = programRow("rm"); function removalProgramOf(s) { const basename = s.verb?.basename; const row = basename !== undefined ? programRow(basename) : undefined; if (row !== undefined && REMOVAL_COMMAND_SET.has(row.key)) return { program: basename, row, named: true }; return programNameUnsettled(s) && RM_REMOVAL_ROW !== undefined ? { program: s.verb.name, row: RM_REMOVAL_ROW, named: false } : undefined; } function removalWalkOf(s) { const row = s.verb === undefined ? undefined : programRow(s.verb.basename); const at = readProgramPosition(s.argv).program?.index; if (row === undefined || at === undefined || actionOf(row.key) !== "walk") return undefined; const words = s.argv.slice(at + 1).map(findWordOf); const actions = findActionsOf(row, words); const from = deletesEverythingFrom(actions, words); return from.length > 0 ? { actions, from } : undefined; } function walkFindingsOf(established, segment, walk, seat, safe, apart, relocated, answered) { const program = segment.verb.basename; const at = removalSeatAt(seat, established.plan, segment, apart); const out = []; if (walk.actions.startsFromFile) return [{ guard: "unverifiable_delete", program, operand: segment.text.trim(), source: "stream" }]; const named = walk.actions.starts.length > 0; if (!named && relocated) return [{ guard: "unverifiable_delete", program, operand: ".", source: "relocated" }]; if (!named) { const bases = segment.bases === "unmodelled" ? (seat.startedIn ?? []) : segment.bases; for (const base of bases) { const landed = isAbsoluteForFamily("own", base) ? answered(base) : undefined; const kind = dangerousRemovalOf(base, at, { recursive: true }) ?? (landed === undefined ? undefined : dangerousRemovalOf(`${landed.replace(/[\\/]+$/, "")}/*`, at, { recursive: true })); if (kind !== undefined) return [{ guard: "dangerous_delete", kind, program, operand: ".", target: base }]; } return out; } const starts = new Set(walk.from.map((w) => w.raw)); for (const read of established.reads.get(segment) ?? []) { if ((read.candidate.provenance !== "operand" && read.candidate.provenance !== "option_value") || !starts.has(read.candidate.raw)) continue; const word = segment.argv.find((w) => w.raw === read.candidate.raw); const judged = removalKindOf(read, word, at, { recursive: true }, answered); if (judged !== undefined) { const untracked = read.candidate.bases === "unmodelled" ? established.plan.segments.find((s) => s.bases === "unmodelled")?.text.trim() : undefined; out.push({ guard: "dangerous_delete", kind: judged.kind, program, operand: read.candidate.raw, target: judged.at, ...(untracked !== undefined ? { untrackedFrom: untracked } : {}) }); continue; } if (read.established !== "unestablishable" || (read.candidate.expands !== "unresolvable" && !relocated)) continue; if (word !== undefined && belowKnownSafeRoot(word, safe, segment)) continue; out.push({ guard: "unverifiable_delete", program, operand: read.candidate.raw, source: read.candidate.expands === "unresolvable" ? "rewritten" : "relocated" }); } return out; } function narrowedEntriesOf(established, segment, seat) { const out = new Map(); const row = segment.verb === undefined ? undefined : programRow(segment.verb.basename); const program = readProgramPosition(segment.argv).program?.index; if (row === undefined || program === undefined || actionOf(row.key) !== "walk") return out; const words = segment.argv.slice(program + 1).map(findWordOf); const commands = findHandedCommands(row, words).filter((c) => c.entry === "one"); if (commands.length === 0) return out; const actions = findActionsOf(row, words); const starts = findStartsOf(actions, words); const placed = (j) => actions.starts.length === 0 ? segment.bases === "unmodelled" ? [] : segment.bases : (established.reads.get(segment) ?? []).flatMap((r) => ((r.candidate.provenance === "operand" || r.candidate.provenance === "option_value") && r.candidate.raw === starts[j].raw && r.target !== undefined ? [r.target] : [])); const named = [...seat.homes, ...seat.workspace].filter((p) => isAbsoluteForFamily("own", p) && !isWinFormPath(p)).map((p) => normalizeAbsPathLexically(p)); for (const c of commands) { for (const target of new Set(placed(c.start))) { if (isWinFormPath(target)) continue; const top = normalizeAbsPathLexically(target).replace(/(.)\/+$/, "$1"); const below = (p) => p !== top && p.startsWith(top === "/" ? "/" : `${top}/`); const cells = new Set(); for (const location of named) { for (let p = location; below(p); p = posix.dirname(p)) { const { way, dir } = findDirsDown(starts[c.start], top, p.slice(top === "/" ? 1 : top.length + 1).split("/")); if (certainlyRunOn(actions, way, dir)[c.action] === true) cells.add(p); } } if (cells.size > 0) out.set(c.line, [...(out.get(c.line) ?? []), { at: top, cells: [...cells] }]); } } return out; } function narrowedEntryKindOf(read, entries, seat, rm) { const target = read.target; if (target === undefined) return undefined; for (const e of entries) { const head = `${e.at === "/" ? "" : e.at}/{}`; if (target !== head && !target.startsWith(`${head}/`)) continue; for (const cell of e.cells) { const at = `${cell}${target.slice(head.length)}`; const kind = dangerousRemovalOf(at, seat, rm); if (kind !== undefined) return { kind, at }; } } return undefined; } export function refusedByRemoval(read) { const name = read.established === "expansion" ? read.spellings.find((s) => s !== read.origin) : read.candidate.expands === "unresolvable" ? undefined : read.candidate.spelled; return name !== undefined && /(?:^|\/)\.\.?\/*$/.test(name); } export function planRunsRemoval(plan, nested = false) { return unreadPlan(plan) || plan.segments.some((s) => removalProgramOf(s) !== undefined || removalWalkOf(s) !== undefined || runtimeScriptOf(s, !nested && streamDataContext(plan, s)) !== undefined || programUnread(s) || s.nested.some((p) => planRunsRemoval(p, true))); } function streamDataContext(plan, segment) { return plan.unreadable === undefined && !plan.shape.grouped && !plan.shape.backgrounded && !plan.shape.strayRedirection && plan.segments.at(-1) === segment && segment.redirects.length === 0 && plan.segments.every((s, i) => s.connector === (i === 0 ? "start" : "|") && (s === segment || (s.verb?.listed === true && s.redirects.length === 0))); } const untrackedFromOf = (f) => f.untrackedFrom === undefined ? "" : ` — the working directory is not tracked from \`${inlineUntrusted(f.untrackedFrom, 120)}\` on (a directory change before it cannot be followed), so this target was judged where the command stood when tracking stopped`; const REMOVAL_GUARD_SENTENCE = { dangerous_delete: { card: (row, f) => `Dangerous removal: ${row}${untrackedFromOf(f)}. No permission mode, allow rule or classifier clears this — only a person confirming this call does.`, rows: { filesystem_root: (f) => `\`${f.program}\` would remove the filesystem root (${inlineUntrusted(f.target, 200)})`, home: (f) => `\`${f.program}\` would remove a home directory (${inlineUntrusted(f.target, 200)})`, workspace: (f) => `\`${f.program}\` would remove a workspace directory — the task root, the working directory or an additional working directory — or one of its ancestors (${inlineUntrusted(f.target, 200)})`, top_level: (f) => `\`${f.program}\` would remove a top-level system directory (${inlineUntrusted(f.target, 200)})`, mounted_drive: (f) => `\`${f.program}\` would remove a mounted drive, the folder that holds mounted drives, or a file or folder at the top level of a drive (${inlineUntrusted(f.target, 200)}) — if you meant something deeper inside, name it by its full path`, unread_starts: (f) => `\`${f.program}\` may remove a protected location: the engine does not read where this walk starts (${inlineUntrusted(f.operand, 80)} — BSD's \`-f\` or a cluster of leading options), and it deletes, runs a command or writes a file (${inlineUntrusted(f.target, 200)}) — writing each leading option as a word of its own and each starting point as a plain path (\`find -x ./build …\`) lets the engine check it`, }, }, unverifiable_delete: { card: (row) => `This delete could not be checked first: ${row}. Writing the exact path into the command (or setting the variable to a literal path in the same command, e.g. \`DIR=/exact/path; rm -rf "$DIR"\`) lets the engine check it.`, rows: { rewritten: (f) => `\`${f.program}\` deletes ${inlineUntrusted(f.operand, 200)} recursively and by force, and the shell fills that path in from a value this command does not set (a name with no value here or one set in a form the engine cannot read, a substitution, a parameter operator)`, stream: (f) => `\`${f.program}\` deletes recursively and by force the paths named by the input it is fed (${inlineUntrusted(f.operand, 200)})`, relocated: (f) => `\`${f.program}\` deletes ${inlineUntrusted(f.operand, 200)} recursively and by force, relative to a directory a launcher option moved it into, which this command does not say`, }, }, unverifiable_shell_text: { card: (row) => `This command could not be checked first: ${row}.`, rows: { produced: (f) => `\`${f.program}\` runs shell text that is only put together when the command runs (${inlineUntrusted(f.text, 200)}), so the engine cannot read it beforehand — writing that text into the command itself (a \`-c\` string, a here-document or a here-string) lets the engine read it. Where values are data, pass them as whole quoted operands after \`--\` in a literal script, e.g. \`sh -c 'cat -- "$1"' _ VALUE\`; program or expression positions still need review, and read checks still apply`, unread: (f) => `the engine cannot read all the shell text \`${f.program}\`'s command may evaluate (${inlineUntrusted(f.text, 200)})`, position: (f) => inlineUntrusted(programPositionRefusalSentence(f.refusal), 400), }, }, }; function removalGuardSentence(f) { switch (f.guard) { case "dangerous_delete": { const g = REMOVAL_GUARD_SENTENCE.dangerous_delete; return g.card(g.rows[f.kind](f), f); } case "unverifiable_delete": { const g = REMOVAL_GUARD_SENTENCE.unverifiable_delete; return g.card(g.rows[f.source](f), f); } case "unverifiable_shell_text": { const g = REMOVAL_GUARD_SENTENCE.unverifiable_shell_text; return g.card(f.source === "position" ? g.rows.position(f) : g.rows[f.source](f), f); } default: { const exhaustive = f; return exhaustive; } } } const REMOVAL_GUARD_ORDER = Object.keys(REMOVAL_GUARD_SENTENCE); function verdictOf(findings) { for (const guard of REMOVAL_GUARD_ORDER) { const f = findings.find((x) => x.guard === guard); if (f !== undefined) return { guard: f.guard, text: removalGuardSentence(f) }; } return undefined; } const REMOVAL_RESOLVE_TIMEOUT_MS = 10_000; export function removalReadingOf(command, req, seat, safeRoots = KNOWN_SAFE_ROOTS) { const homeDir = seat?.env?.homeDir; const cwd = req.cwd ?? req.root ?? ""; const roots = req.root !== undefined ? [req.root] : cwd !== "" ? [cwd] : []; const boundary = { roots, ...(cwd !== "" ? { cwd } : {}), ...(homeDir !== undefined ? { homeDir } : {}) }; const plan = planShellReads(startedShellOfCall(req), command, { readers: new Set(bashClassifyDefaultAllow()), cwd, roots, cdPath: seat?.env?.cdPath ?? "unknown", ...(homeDir !== undefined ? { homeDir } : {}) }); const unread = unreadActingFinds(plan).map((f) => ({ guard: "dangerous_delete", kind: "unread_starts", program: f.program, operand: f.word, target: f.text })); if (!planRunsRemoval(plan) && unread.length === 0) return undefined; return { async judge(signal) { const env = seat?.env; const answer = (p) => (env === undefined ? Promise.resolve(undefined) : answeredLocation(env, p, signal)); const withAnswers = async (spelled) => [...spelled, ...(await Promise.all(spelled.map(answer))).filter((a) => a !== undefined)]; const [homes, start] = await Promise.all([withAnswers(homeDir !== undefined ? [homeDir] : []), req.cwd !== undefined ? answer(req.cwd) : undefined]); const departures = env !== undefined && req.cwd !== undefined ? await departuresOf(plan, req.cwd, start, env, signal) : undefined; const startedIn = req.cwd !== undefined ? { startedIn: [req.cwd, ...(start !== undefined ? [start] : [])] } : {}; const workspace = [...(req.root !== undefined ? [req.root] : []), ...(seat?.additionalRoots?.() ?? [])]; const spelledSeat = { homes, workspace, ...startedIn, ...(departures !== undefined ? { departures } : {}) }; const lexicalPlan = establishShellReadsLexically(plan, boundary); const lexical = removalFindingsOf(startedShellOfCall(req), lexicalPlan, spelledSeat, safeRoots); if (lexical.some((f) => f.guard === "dangerous_delete") || env === undefined) return verdictOf([...lexical, ...unread]); const established = roots.length === 0 ? undefined : await resolvedOrUndefined(createShellReadEstablisher(env, roots, { rootsCanonical: true }).establish(plan, boundary, signal), signal); const plans = established === undefined ? [lexicalPlan] : [established, lexicalPlan]; const removalSeat = { ...spelledSeat, workspace: await withAnswers(workspace) }; const wanted = new Set(); for (const p of plans) removalFindingsOf(startedShellOfCall(req), p, removalSeat, safeRoots, (dir) => void wanted.add(dir)); const answers = new Map(await Promise.all([...wanted].map(async (dir) => [dir, await answer(dir)]))); return verdictOf([...plans.flatMap((p) => removalFindingsOf(startedShellOfCall(req), p, removalSeat, safeRoots, (dir) => answers.get(dir))), ...unread]); }, }; } async function answeredLocation(env, path, signal) { const r = await resolvedOrUndefined(env.canonicalPath(path, signal), signal); return r !== undefined && r.ok ? r.value : undefined; } async function resolvedOrUndefined(leg, signal) { let timer; try { return await Promise.race([ leg.catch(() => undefined), new Promise((resolve) => { timer = setTimeout(() => resolve(undefined), REMOVAL_RESOLVE_TIMEOUT_MS); signal?.addEventListener("abort", () => resolve(undefined), { once: true }); }), ]); } finally { if (timer !== undefined) clearTimeout(timer); } }