@hasna/hooks 0.12.17 → 0.12.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/native-safety-entry.js +37 -27
- package/bin/native-safety-worker.cjs +37 -27
- package/hooks/codewith-native-common.ts +47 -8
- package/hooks/hook-trash-guard/src/hook.ts +98 -94
- package/hooks/hook-workspace-repos-guard/src/hook.ts +98 -16
- package/hooks/local-executors.ts +268 -96
- package/hooks/native-safety-composite.ts +5 -1
- package/package.json +1 -1
|
@@ -301,6 +301,26 @@ function splitShellSegmentsUncached(command: string): ShellSegment[] {
|
|
|
301
301
|
}));
|
|
302
302
|
}
|
|
303
303
|
|
|
304
|
+
/**
|
|
305
|
+
* Set while a reader reads a command a second time with the earlier
|
|
306
|
+
* double-quote backslash reading (shellWordsPass), so that whatever it
|
|
307
|
+
* blocked stays blocked.
|
|
308
|
+
*/
|
|
309
|
+
let legacyQuotes = false;
|
|
310
|
+
|
|
311
|
+
function withLegacyQuotes<T>(read: () => T): T {
|
|
312
|
+
const was = legacyQuotes;
|
|
313
|
+
legacyQuotes = true;
|
|
314
|
+
try {
|
|
315
|
+
return read();
|
|
316
|
+
} finally {
|
|
317
|
+
legacyQuotes = was;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** A command holding a backslash and a double quote, which the two readings may read differently. */
|
|
322
|
+
const mayReadTwoWays = (command: string): boolean => command.includes("\\") && command.includes('"');
|
|
323
|
+
|
|
304
324
|
function shellWordsPass(segment: string, atomicSubstitutions: boolean): { words: string[]; unterminated: boolean } {
|
|
305
325
|
const words: string[] = [];
|
|
306
326
|
let current = "";
|
|
@@ -348,6 +368,16 @@ function shellWordsPass(segment: string, atomicSubstitutions: boolean): { words:
|
|
|
348
368
|
continue;
|
|
349
369
|
}
|
|
350
370
|
if (ch === "\\" && quote !== "'") {
|
|
371
|
+
const next = segment[i + 1] ?? "";
|
|
372
|
+
// Inside double quotes bash removes a backslash only before $ ` " \ and a
|
|
373
|
+
// newline (a line continuation, which removes both); before any other
|
|
374
|
+
// character the backslash is part of the word. The earlier reading
|
|
375
|
+
// (legacyQuotes) removed it before every character.
|
|
376
|
+
if (quote === '"' && !legacyQuotes && !/[$`"\\]/.test(next)) {
|
|
377
|
+
if (next === "\n") i += 1;
|
|
378
|
+
else current += ch;
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
351
381
|
escaped = true;
|
|
352
382
|
continue;
|
|
353
383
|
}
|
|
@@ -501,12 +531,17 @@ function gitInfoFromTokens(tokens: string[], baseCwd: string): GitCommandInfo |
|
|
|
501
531
|
}
|
|
502
532
|
|
|
503
533
|
export function gitCommandInfo(command: string, baseCwd: string = process.cwd()): GitCommandInfo | null {
|
|
504
|
-
|
|
505
|
-
const
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
534
|
+
const read = (): GitCommandInfo | null => {
|
|
535
|
+
for (const segment of splitShellSegments(command)) {
|
|
536
|
+
const tokens = shellWords(segment);
|
|
537
|
+
const info = gitInfoFromTokens(tokens, baseCwd);
|
|
538
|
+
if (info) return info;
|
|
539
|
+
}
|
|
540
|
+
return null;
|
|
541
|
+
};
|
|
542
|
+
// A commit or push the earlier reading finds is reported as it reported it
|
|
543
|
+
// (its target folder included); one only bash's reading finds is added.
|
|
544
|
+
return (mayReadTwoWays(command) ? withLegacyQuotes(read) : null) ?? read();
|
|
510
545
|
}
|
|
511
546
|
|
|
512
547
|
export function isGitCommitOrPush(command: string): boolean {
|
|
@@ -2569,14 +2604,18 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
|
|
|
2569
2604
|
return reason ? { block: true, operation: "oversized command", reason } : { block: false };
|
|
2570
2605
|
}
|
|
2571
2606
|
|
|
2572
|
-
if (shellCommandLayers(command).truncated) {
|
|
2607
|
+
if (shellCommandLayers(command).truncated || (mayReadTwoWays(command) && withLegacyQuotes(() => shellCommandLayers(command).truncated))) {
|
|
2573
2608
|
const reason = truncatedAnalysisBlockReason(command);
|
|
2574
2609
|
if (reason) {
|
|
2575
2610
|
return { block: true, operation: "unanalysable nested command", reason };
|
|
2576
2611
|
}
|
|
2577
2612
|
}
|
|
2578
2613
|
|
|
2579
|
-
|
|
2614
|
+
const targets = destructiveShellTargets(command, cwd, analysis);
|
|
2615
|
+
// Read with the earlier double-quote backslash reading first (legacyQuotes),
|
|
2616
|
+
// so that what it blocked stays blocked with the same reason.
|
|
2617
|
+
if (mayReadTwoWays(command)) targets.unshift(...withLegacyQuotes(() => destructiveShellTargets(command, cwd, analysis)));
|
|
2618
|
+
for (const target of targets) {
|
|
2580
2619
|
const targetCwd = target.baseCwd ?? cwd;
|
|
2581
2620
|
const targetPath = resolveFrom(targetCwd, target.path);
|
|
2582
2621
|
const rulesFor = (path: string) => {
|
|
@@ -90,7 +90,7 @@ import {
|
|
|
90
90
|
type WrapperSpec,
|
|
91
91
|
} from "../../shell-words";
|
|
92
92
|
export { expandBraces } from "../../shell-words";
|
|
93
|
-
import { launchedCommands, localExecutor, shellProgram } from "../../local-executors";
|
|
93
|
+
import { ansiPlain, launchedCommands, legacyQuotes, localExecutor, readWithLegacyQuotes, shellProgram } from "../../local-executors";
|
|
94
94
|
|
|
95
95
|
const RULE = "trash-guard";
|
|
96
96
|
|
|
@@ -135,7 +135,7 @@ const REFUSED_VERBS: Record<string, string> = {
|
|
|
135
135
|
* place. When one of these is in command position and the command mentions a
|
|
136
136
|
* delete verb, the command is refused rather than guessed at.
|
|
137
137
|
*/
|
|
138
|
-
const OPAQUE_COMMANDS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "eval", "source", ".", "su", "runuser", "env"]);
|
|
138
|
+
const OPAQUE_COMMANDS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "eval", "source", ".", "su", "runuser", "env"]);
|
|
139
139
|
|
|
140
140
|
/** Wrapper commands whose real command follows them (with their value-taking options). */
|
|
141
141
|
const WRAPPERS: Record<string, string[]> = {
|
|
@@ -297,17 +297,28 @@ function readAnsiC(raw: string, from: number): { text: string; end: number } {
|
|
|
297
297
|
* `$'rm'` and `$'\x72m'` are `rm`.
|
|
298
298
|
*/
|
|
299
299
|
export function decodeCommandWord(raw: string): string {
|
|
300
|
+
return decodeQuoted(raw, true);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Quote removal as bash does it. Outside quotes a backslash quotes the next
|
|
305
|
+
* character. Inside double quotes it is removed only before `$`, a backtick,
|
|
306
|
+
* `"`, `\` or a newline (a line continuation: both go) and kept before any
|
|
307
|
+
* other character, so `"\%a%e cmd"` is the sed script `\%a%e cmd`. The
|
|
308
|
+
* earlier reading (legacyQuotes) dropped it before every character.
|
|
309
|
+
*/
|
|
310
|
+
function decodeQuoted(raw: string, ansi: boolean): string {
|
|
300
311
|
let out = "";
|
|
301
312
|
let i = 0;
|
|
302
313
|
while (i < raw.length) {
|
|
303
314
|
const ch = raw[i];
|
|
304
|
-
if (ch === "$" && raw[i + 1] === "'") {
|
|
305
|
-
const
|
|
306
|
-
out +=
|
|
307
|
-
i =
|
|
315
|
+
if (ansi && ch === "$" && raw[i + 1] === "'") {
|
|
316
|
+
const decoded = readAnsiC(raw, i + 2);
|
|
317
|
+
out += decoded.text;
|
|
318
|
+
i = decoded.end;
|
|
308
319
|
continue;
|
|
309
320
|
}
|
|
310
|
-
if (ch === "$" && raw[i + 1] === '"') {
|
|
321
|
+
if (ansi && ch === "$" && raw[i + 1] === '"') {
|
|
311
322
|
i++;
|
|
312
323
|
continue;
|
|
313
324
|
}
|
|
@@ -330,7 +341,8 @@ export function decodeCommandWord(raw: string): string {
|
|
|
330
341
|
i++;
|
|
331
342
|
while (i < raw.length && raw[i] !== '"') {
|
|
332
343
|
if (raw[i] === "\\" && i + 1 < raw.length) {
|
|
333
|
-
|
|
344
|
+
const next = raw[i + 1];
|
|
345
|
+
out += legacyQuotes.on || /[$`"\\]/.test(next) ? next : next === "\n" ? "" : `\\${next}`;
|
|
334
346
|
i += 2;
|
|
335
347
|
continue;
|
|
336
348
|
}
|
|
@@ -1037,45 +1049,9 @@ function findHeredocEnd(rest: string, delimiter: string): number {
|
|
|
1037
1049
|
return -1;
|
|
1038
1050
|
}
|
|
1039
1051
|
|
|
1040
|
-
/** Strip one word's quoting and escapes, the way the shell would for a name. */
|
|
1052
|
+
/** Strip one word's quoting and escapes, the way the shell would for a name (decodeQuoted). */
|
|
1041
1053
|
export function decodeWord(text: string): string {
|
|
1042
|
-
|
|
1043
|
-
let i = 0;
|
|
1044
|
-
while (i < text.length) {
|
|
1045
|
-
const ch = text[i];
|
|
1046
|
-
if (ch === "\\") {
|
|
1047
|
-
if (i + 1 < text.length) out += text[i + 1];
|
|
1048
|
-
i += 2;
|
|
1049
|
-
continue;
|
|
1050
|
-
}
|
|
1051
|
-
if (ch === "'") {
|
|
1052
|
-
const end = text.indexOf("'", i + 1);
|
|
1053
|
-
if (end === -1) {
|
|
1054
|
-
out += text.slice(i + 1);
|
|
1055
|
-
break;
|
|
1056
|
-
}
|
|
1057
|
-
out += text.slice(i + 1, end);
|
|
1058
|
-
i = end + 1;
|
|
1059
|
-
continue;
|
|
1060
|
-
}
|
|
1061
|
-
if (ch === '"') {
|
|
1062
|
-
i++;
|
|
1063
|
-
while (i < text.length && text[i] !== '"') {
|
|
1064
|
-
if (text[i] === "\\" && i + 1 < text.length) {
|
|
1065
|
-
out += text[i + 1];
|
|
1066
|
-
i += 2;
|
|
1067
|
-
continue;
|
|
1068
|
-
}
|
|
1069
|
-
out += text[i];
|
|
1070
|
-
i++;
|
|
1071
|
-
}
|
|
1072
|
-
i++;
|
|
1073
|
-
continue;
|
|
1074
|
-
}
|
|
1075
|
-
out += ch;
|
|
1076
|
-
i++;
|
|
1077
|
-
}
|
|
1078
|
-
return out;
|
|
1054
|
+
return decodeQuoted(text, false);
|
|
1079
1055
|
}
|
|
1080
1056
|
|
|
1081
1057
|
/* ------------------------------------------------------------------ */
|
|
@@ -1095,7 +1071,7 @@ export function commandWordIndex(segment: Segment): number {
|
|
|
1095
1071
|
while (index < segment.words.length && guard++ < 32) {
|
|
1096
1072
|
if (segment.redirects.has(index)) { index++; continue; }
|
|
1097
1073
|
const raw = segment.words[index].text;
|
|
1098
|
-
const decoded =
|
|
1074
|
+
const decoded = decodeCommandWord(raw);
|
|
1099
1075
|
if (ASSIGNMENT_RE.test(decoded) && !decoded.startsWith("-")) {
|
|
1100
1076
|
index++;
|
|
1101
1077
|
continue;
|
|
@@ -1108,7 +1084,7 @@ export function commandWordIndex(segment: Segment): number {
|
|
|
1108
1084
|
// command -v/-V looks up every following name without executing one.
|
|
1109
1085
|
if (wrapper === "command") {
|
|
1110
1086
|
for (const word of segment.words.filter((_, at) => at > index && !segment.redirects.has(at))) {
|
|
1111
|
-
const option =
|
|
1087
|
+
const option = decodeCommandWord(word.text);
|
|
1112
1088
|
if (option === "--" || !option.startsWith("-")) break;
|
|
1113
1089
|
if (/^-[pvV]*[vV][pvV]*$/.test(option)) return -1;
|
|
1114
1090
|
}
|
|
@@ -1119,7 +1095,7 @@ export function commandWordIndex(segment: Segment): number {
|
|
|
1119
1095
|
index++;
|
|
1120
1096
|
while (index < segment.words.length) {
|
|
1121
1097
|
if (segment.redirects.has(index)) { index++; continue; }
|
|
1122
|
-
const option =
|
|
1098
|
+
const option = decodeCommandWord(segment.words[index].text);
|
|
1123
1099
|
if (!option.startsWith("-") || option === "-") break;
|
|
1124
1100
|
if (option === "--") {
|
|
1125
1101
|
index++;
|
|
@@ -1136,7 +1112,7 @@ export function commandWordIndex(segment: Segment): number {
|
|
|
1136
1112
|
}
|
|
1137
1113
|
let positionals = WRAPPER_POSITIONALS[wrapper] ?? 0;
|
|
1138
1114
|
while (positionals > 0 && index < segment.words.length) {
|
|
1139
|
-
const positional =
|
|
1115
|
+
const positional = decodeCommandWord(segment.words[index].text);
|
|
1140
1116
|
if (positional.startsWith("-") && positional !== "-") break;
|
|
1141
1117
|
index++;
|
|
1142
1118
|
positionals--;
|
|
@@ -1550,7 +1526,7 @@ function readLocalExecutor(
|
|
|
1550
1526
|
// own: read it as a command in its own right, by both command-position
|
|
1551
1527
|
// models, with the launcher's operands (find's start paths) and cwd deciding
|
|
1552
1528
|
// whether it runs under a checkout.
|
|
1553
|
-
for (const launched of launchedCommands(segment.words.map((word) =>
|
|
1529
|
+
for (const launched of launchedCommands(segment.words.map((word) => decodeCommandWord(word.text)), index, (at) => segment.redirects.has(at))) {
|
|
1554
1530
|
if (depth >= 8) return executorTargetsHandoff(scope.segment, scope.index, cwd, ctx.home) ? { kind: "refuse", reason: LAUNCHER_DEPTH_REASON } : null;
|
|
1555
1531
|
const sub: Segment = {
|
|
1556
1532
|
words: segment.words.slice(launched.start, launched.end),
|
|
@@ -1564,20 +1540,20 @@ function readLocalExecutor(
|
|
|
1564
1540
|
}
|
|
1565
1541
|
}
|
|
1566
1542
|
// `sh|bash|… -c PROGRAM` / `eval WORD…` whose program is not a plain literal
|
|
1567
|
-
// (an expansion, a substitution, several eval words) cannot be read at all;
|
|
1543
|
+
// (an expansion, a substitution, ANSI-C `$'…'` quoting, several eval words) cannot be read at all;
|
|
1568
1544
|
// under a checkout it is refused. A literal program keeps the shell-string
|
|
1569
1545
|
// reading below (OPAQUE_COMMANDS), as before.
|
|
1570
1546
|
const kept = segment.words.map((word, at) => ({ word, at })).filter(({ at }) => !segment.redirects.has(at));
|
|
1571
1547
|
const keptIndex = kept.findIndex(({ at }) => at === index);
|
|
1572
|
-
const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex);
|
|
1548
|
+
const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex, decodeCommandWord);
|
|
1573
1549
|
if (shell && !shell.literal && (executorTargetsHandoff(segment, index, cwd, ctx.home) || executorTargetsHandoff(scope.segment, scope.index, cwd, ctx.home))) {
|
|
1574
1550
|
return {
|
|
1575
1551
|
kind: "refuse",
|
|
1576
|
-
reason: `\`${verb}\` runs a shell program that is not a plain literal (an expansion, a substitution or several words), so this hook cannot read what it would delete under a protected repository checkout. Write the program out literally, or run it from outside the checkout.`,
|
|
1552
|
+
reason: `\`${verb}\` runs a shell program that is not a plain literal (an expansion, a substitution, ANSI-C \`$'…'\` quoting or several words), so this hook cannot read what it would delete under a protected repository checkout. Write the program out literally, or run it from outside the checkout.`,
|
|
1577
1553
|
};
|
|
1578
1554
|
}
|
|
1579
1555
|
const exec = localExecutor(
|
|
1580
|
-
segment.words.map((word) =>
|
|
1556
|
+
segment.words.map((word) => decodeCommandWord(word.text)),
|
|
1581
1557
|
index,
|
|
1582
1558
|
(at) => at >= 0 && at < segment.words.length && (segment.redirects.has(at) || expandsWord(segment.words[at].text)),
|
|
1583
1559
|
);
|
|
@@ -1633,7 +1609,11 @@ export function scanCommand(command: string, options: { cwd: string; home: strin
|
|
|
1633
1609
|
};
|
|
1634
1610
|
|
|
1635
1611
|
if (!lexed.trustworthy) {
|
|
1636
|
-
|
|
1612
|
+
// A command the lexer stops trusting at a `\'` inside `$'…'` is scanned
|
|
1613
|
+
// in the spelling it follows, which the shell runs the same; it stays
|
|
1614
|
+
// untrusted, so it is never rewritten.
|
|
1615
|
+
const plain = ansiPlain(command);
|
|
1616
|
+
return plain === command ? result : { ...scanCommand(plain, options), trustworthy: false };
|
|
1637
1617
|
}
|
|
1638
1618
|
|
|
1639
1619
|
// Refusals that only the strict or fail-closed reading finds come after every
|
|
@@ -1883,34 +1863,14 @@ function resolveTrash(deps: GuardDependencies): { path: string | null; error: st
|
|
|
1883
1863
|
const ABSENT_REASON =
|
|
1884
1864
|
"[trash-guard] No verified @hasna/trash guard was found on PATH. This deletion is refused. Install the current @hasna/trash package with Bun and run its setup; the operating-system trash utility is not a compatible guard.";
|
|
1885
1865
|
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
if (["apply_patch", "ApplyPatch", "functions.apply_patch"].includes(input.tool_name ?? "")) {
|
|
1889
|
-
const patch = input.tool_input?.command;
|
|
1890
|
-
if (typeof patch !== "string") return deny("[trash-guard] Unreadable patch input; deletion safety cannot be checked.");
|
|
1891
|
-
if (/^\s*\*\*\* Delete File:/m.test(patch)) {
|
|
1892
|
-
return deny("[trash-guard] Delete File would bypass recoverable deletion. First use `trash put -- <path>` or the trash_put MCP tool, then submit any remaining edits without the deletion block.");
|
|
1893
|
-
}
|
|
1894
|
-
return { continue: true };
|
|
1895
|
-
}
|
|
1896
|
-
if (input.tool_name !== "Bash") return { continue: true };
|
|
1897
|
-
|
|
1898
|
-
// A command we cannot READ is a payload we cannot verify, and the harness
|
|
1899
|
-
// falls back to the ORIGINAL tool input whenever `updatedInput` is missing or
|
|
1900
|
-
// empty -- so "cannot tell" must never resolve to "run it". Refuse instead.
|
|
1901
|
-
// A command that is PRESENT and empty runs nothing, so that stays allowed.
|
|
1902
|
-
const rawCommand = (input as { tool_input?: { command?: unknown } }).tool_input?.command;
|
|
1903
|
-
if (typeof rawCommand !== "string") {
|
|
1904
|
-
return deny(
|
|
1905
|
-
"[trash-guard] The Bash tool call carried no readable `command`, so this hook cannot verify what would run. Refusing a call it cannot verify. Re-run the delete explicitly as `rm -- <path>` so it can be redirected into trash.",
|
|
1906
|
-
);
|
|
1907
|
-
}
|
|
1908
|
-
|
|
1909
|
-
const command = getCommand(input);
|
|
1910
|
-
if (!command.trim()) return { continue: true };
|
|
1911
|
-
|
|
1912
|
-
const scanned = scanCommand(command, { cwd: deps.cwd, home: deps.home });
|
|
1866
|
+
const REWRITE_UNVERIFIED_REASON =
|
|
1867
|
+
"[trash-guard] The rewrite of this command did not verify (the delete could not be redirected cleanly), so the command is refused rather than run unredirected. Re-run the delete as a plain `rm -- <path>` command.";
|
|
1913
1868
|
|
|
1869
|
+
/**
|
|
1870
|
+
* The verdict a scan decides on its own (a refusal, or no delete to
|
|
1871
|
+
* redirect), or null when its `rm` hits are to be rewritten.
|
|
1872
|
+
*/
|
|
1873
|
+
function scanVerdict(scanned: ScanResult, command: string): CodewithHookOutput | null {
|
|
1914
1874
|
if (scanned.refusals.length > 0) {
|
|
1915
1875
|
return deny(`[trash-guard] ${scanned.refusals[0].reason}`);
|
|
1916
1876
|
}
|
|
@@ -1940,11 +1900,9 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
|
|
|
1940
1900
|
"[trash-guard] This delete runs from inside a protected repository checkout but names only paths outside it. Run it from outside the checkout (`cd /tmp && rm -- <path>`), where it is redirected into trash.",
|
|
1941
1901
|
);
|
|
1942
1902
|
}
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
return { continue: true };
|
|
1947
|
-
}
|
|
1903
|
+
// No delete to redirect. Any handed off belongs to the guarded
|
|
1904
|
+
// repo-checkout roots, which `workspace-repos-guard` owns: abstain and
|
|
1905
|
+
// let that hook decide.
|
|
1948
1906
|
return { continue: true };
|
|
1949
1907
|
}
|
|
1950
1908
|
|
|
@@ -1953,6 +1911,54 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
|
|
|
1953
1911
|
"[trash-guard] This command mixes a delete under the protected repo-checkout roots (owned by workspace-repos-guard) with a delete outside them, and a partial rewrite would leave one of them unredirected. Re-run them as separate commands, so each delete is handled by the hook that owns it.",
|
|
1954
1912
|
);
|
|
1955
1913
|
}
|
|
1914
|
+
return null;
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
export function evaluate(input: CodewithHookInput, deps: GuardDependencies): CodewithHookOutput {
|
|
1918
|
+
if (input.hook_event_name !== "PreToolUse") return { continue: true };
|
|
1919
|
+
if (["apply_patch", "ApplyPatch", "functions.apply_patch"].includes(input.tool_name ?? "")) {
|
|
1920
|
+
const patch = input.tool_input?.command;
|
|
1921
|
+
if (typeof patch !== "string") return deny("[trash-guard] Unreadable patch input; deletion safety cannot be checked.");
|
|
1922
|
+
if (/^\s*\*\*\* Delete File:/m.test(patch)) {
|
|
1923
|
+
return deny("[trash-guard] Delete File would bypass recoverable deletion. First use `trash put -- <path>` or the trash_put MCP tool, then submit any remaining edits without the deletion block.");
|
|
1924
|
+
}
|
|
1925
|
+
return { continue: true };
|
|
1926
|
+
}
|
|
1927
|
+
if (input.tool_name !== "Bash") return { continue: true };
|
|
1928
|
+
|
|
1929
|
+
// A command we cannot READ is a payload we cannot verify, and the harness
|
|
1930
|
+
// falls back to the ORIGINAL tool input whenever `updatedInput` is missing or
|
|
1931
|
+
// empty -- so "cannot tell" must never resolve to "run it". Refuse instead.
|
|
1932
|
+
// A command that is PRESENT and empty runs nothing, so that stays allowed.
|
|
1933
|
+
const rawCommand = (input as { tool_input?: { command?: unknown } }).tool_input?.command;
|
|
1934
|
+
if (typeof rawCommand !== "string") {
|
|
1935
|
+
return deny(
|
|
1936
|
+
"[trash-guard] The Bash tool call carried no readable `command`, so this hook cannot verify what would run. Refusing a call it cannot verify. Re-run the delete explicitly as `rm -- <path>` so it can be redirected into trash.",
|
|
1937
|
+
);
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
const command = getCommand(input);
|
|
1941
|
+
if (!command.trim()) return { continue: true };
|
|
1942
|
+
|
|
1943
|
+
const scan = () => scanCommand(command, { cwd: deps.cwd, home: deps.home });
|
|
1944
|
+
const hits = (result: ScanResult) => result.rmHits.map((hit) => hit.word.start).join();
|
|
1945
|
+
// A check fails if it fails with either double-quote backslash reading.
|
|
1946
|
+
const fails = (check: () => boolean) => check() || !!readWithLegacyQuotes(command, check);
|
|
1947
|
+
const scanned = scan();
|
|
1948
|
+
const verdict = scanVerdict(scanned, command);
|
|
1949
|
+
// Read with the earlier double-quote backslash reading too (legacyQuotes):
|
|
1950
|
+
// what it refused stays refused, with the same reason, and a delete only it
|
|
1951
|
+
// would have redirected is refused, not run unredirected.
|
|
1952
|
+
const legacy = readWithLegacyQuotes(command, () => {
|
|
1953
|
+
const result = scan();
|
|
1954
|
+
return { result, verdict: scanVerdict(result, command) };
|
|
1955
|
+
});
|
|
1956
|
+
if (legacy) {
|
|
1957
|
+
const { result: earlierScan, verdict: earlier } = legacy;
|
|
1958
|
+
if (earlier && !("continue" in earlier)) return earlier;
|
|
1959
|
+
if (!earlier && (!verdict || "continue" in verdict) && hits(earlierScan) !== hits(scanned)) return deny(REWRITE_UNVERIFIED_REASON);
|
|
1960
|
+
}
|
|
1961
|
+
if (verdict) return verdict;
|
|
1956
1962
|
|
|
1957
1963
|
const trash = resolveTrash(deps);
|
|
1958
1964
|
if (trash.error !== null) {
|
|
@@ -1965,20 +1971,18 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
|
|
|
1965
1971
|
}
|
|
1966
1972
|
const trashPath = trash.path;
|
|
1967
1973
|
|
|
1968
|
-
if (deps.execution && changesExecutionEnvironment(command)) {
|
|
1974
|
+
if (deps.execution && fails(() => changesExecutionEnvironment(command))) {
|
|
1969
1975
|
return deny("[trash-guard] A deletion combined with shell environment changes cannot use the verified native execution context. Run the deletion as a separate plain rm command.");
|
|
1970
1976
|
}
|
|
1971
1977
|
const rewritten = rewriteCommand(command, scanned.rmHits, trashPath, deps.execution);
|
|
1972
1978
|
const updatedInput = buildUpdatedInput(input.tool_input, rewritten);
|
|
1973
1979
|
if (deps.execution) updatedInput.hasna_execution = "hasna.hooks.execution.v1";
|
|
1974
1980
|
|
|
1975
|
-
if (!updatedInputIsComplete(updatedInput, command, scanned.rmHits, deps.cwd, deps.home)) {
|
|
1981
|
+
if (fails(() => !updatedInputIsComplete(updatedInput, command, scanned.rmHits, deps.cwd, deps.home))) {
|
|
1976
1982
|
// Never allow a partial rewrite: the harness falls back to the ORIGINAL
|
|
1977
1983
|
// tool input when `updatedInput` is missing or empty, which runs the raw
|
|
1978
1984
|
// `rm`. Refuse instead.
|
|
1979
|
-
return deny(
|
|
1980
|
-
"[trash-guard] The rewrite of this command did not verify (the delete could not be redirected cleanly), so the command is refused rather than run unredirected. Re-run the delete as a plain `rm -- <path>` command.",
|
|
1981
|
-
);
|
|
1985
|
+
return deny(REWRITE_UNVERIFIED_REASON);
|
|
1982
1986
|
}
|
|
1983
1987
|
|
|
1984
1988
|
return allowRewrite(updatedInput);
|
|
@@ -1986,7 +1990,7 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
|
|
|
1986
1990
|
|
|
1987
1991
|
/** Verdict used when the hook itself fails: refuse anything that could delete. */
|
|
1988
1992
|
export function fallbackVerdict(command: string): CodewithHookOutput {
|
|
1989
|
-
return mentionsDeleteVerb(command) || /^\s*\*\*\* Delete File:/m.test(command)
|
|
1993
|
+
return mentionsDeleteVerb(command) || readWithLegacyQuotes(command, () => mentionsDeleteVerb(command)) || /^\s*\*\*\* Delete File:/m.test(command)
|
|
1990
1994
|
? deny(
|
|
1991
1995
|
"[trash-guard] The hook failed while classifying this command, so it cannot be proven free of an unredirected delete. Re-run the delete as a plain `rm -- <path>` command.",
|
|
1992
1996
|
)
|
|
@@ -65,6 +65,7 @@ import { homedir } from "node:os";
|
|
|
65
65
|
import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
|
|
66
66
|
import {
|
|
67
67
|
commandWordIndex,
|
|
68
|
+
decodeCommandWord,
|
|
68
69
|
decodeWord,
|
|
69
70
|
envSplitCommandText,
|
|
70
71
|
gitSubcommand,
|
|
@@ -82,7 +83,7 @@ import {
|
|
|
82
83
|
type CodewithHookOutput,
|
|
83
84
|
} from "../../codewith-native-common";
|
|
84
85
|
import { ASSIGNMENT, baseName, expandBraces, splitsOrMoves, unwrapCommand, type ShellWord } from "../../shell-words";
|
|
85
|
-
import { embeddedProgramIsReadOnly, launchedCommands, localExecutor, shellProgram, type ExecutorFinding } from "../../local-executors";
|
|
86
|
+
import { ansiPlain, embeddedProgramIsReadOnly, launchedCommands, legacyQuotes, localExecutor, readWithLegacyQuotes, shellProgram, type ExecutorFinding } from "../../local-executors";
|
|
86
87
|
|
|
87
88
|
export { expandBraces, unwrapCommand };
|
|
88
89
|
|
|
@@ -343,8 +344,9 @@ function shellWords(command: string): ShellWord[] {
|
|
|
343
344
|
}
|
|
344
345
|
if (ch === "\\" && i + 1 < command.length) {
|
|
345
346
|
const next = command[i + 1];
|
|
346
|
-
// Inside double quotes a backslash escapes only $ ` " \ and newline
|
|
347
|
-
|
|
347
|
+
// Inside double quotes a backslash escapes only $ ` " \ and newline,
|
|
348
|
+
// and a line continuation removes the backslash and the newline.
|
|
349
|
+
text += quote === '"' && !/[$\x60"\\\n]/.test(next) ? ch + next : quote === '"' && next === "\n" && !legacyQuotes.on ? "" : next;
|
|
348
350
|
raw += ch + next;
|
|
349
351
|
inWord = true;
|
|
350
352
|
i++;
|
|
@@ -491,7 +493,7 @@ function partOperation(part: ReturnType<typeof lexCommand>["segments"][number]):
|
|
|
491
493
|
const kept = part.words.map((word, at) => ({ word, at })).filter(({ at }) => !part.redirects.has(at));
|
|
492
494
|
const index = commandWordIndex(part);
|
|
493
495
|
const shared = index < 0 ? "read" : commandOperation(part, index);
|
|
494
|
-
const strict = unwrapCommand(kept.map(({ word }) => (
|
|
496
|
+
const strict = unwrapCommand(kept.map(({ word }) => strictWord(word.text)));
|
|
495
497
|
if (strict === null) return strongest(shared, opaqueOperation(kept.map(({ word }) => decodeWord(word.text)).join(" ")));
|
|
496
498
|
if (strict.index < 0 || kept[strict.index].at === index) return shared;
|
|
497
499
|
return strongest(shared, commandOperation(part, kept[strict.index].at));
|
|
@@ -515,13 +517,14 @@ function runsDestructiveLocalProgram(part: ReturnType<typeof lexCommand>["segmen
|
|
|
515
517
|
// except that a destructive local executor inside it counts here too.
|
|
516
518
|
const kept = part.words.map((word, at) => ({ word, at })).filter(({ at }) => !part.redirects.has(at));
|
|
517
519
|
const keptIndex = kept.findIndex(({ at }) => at === index);
|
|
518
|
-
const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex);
|
|
520
|
+
const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex, decodeCommandWord);
|
|
519
521
|
if (shell) {
|
|
520
522
|
if (!shell.literal) return true;
|
|
521
523
|
const inner = lexCommand(shell.program!);
|
|
522
524
|
if (inner.trustworthy && inner.segments.some((segment) => segmentRunsDestructive(segment, depth + 1))) return true;
|
|
523
525
|
}
|
|
524
|
-
|
|
526
|
+
// Words as the shell passes them, ANSI-C `$'…'` decoded (`$'sed'` is sed).
|
|
527
|
+
const decoded = part.words.map((word) => decodeCommandWord(word.text));
|
|
525
528
|
// A launcher (find -exec/-execdir/-ok/-okdir, xargs) runs a command of its
|
|
526
529
|
// own; that command is read like one in command position, wrappers included.
|
|
527
530
|
for (const launched of launchedCommands(decoded, index, (at) => part.redirects.has(at))) {
|
|
@@ -543,11 +546,62 @@ function subSegment(part: ReturnType<typeof lexCommand>["segments"][number], sta
|
|
|
543
546
|
|
|
544
547
|
/** Whether a lexed simple command, read by both command-position models, runs a destructive local program. */
|
|
545
548
|
function segmentRunsDestructive(segment: ReturnType<typeof lexCommand>["segments"][number], depth = 0): boolean {
|
|
549
|
+
return commandIndices(segment).some((index) => runsDestructiveLocalProgram(segment, index, depth));
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* A word for the strict wrapper model: decoded as the shell passes it, and
|
|
554
|
+
* opaque when it expands at runtime. A word of plain characters and ANSI-C
|
|
555
|
+
* `$'…'` parts (`$'sudo'`, `ba$'sh'`) is decoded exactly, not opaque.
|
|
556
|
+
*/
|
|
557
|
+
function strictWord(raw: string): ShellWord {
|
|
558
|
+
return { text: decodeCommandWord(raw), opaque: /[$\x60]/.test(raw) && !/^(?:[^$\x60"'\\]|\$'(?:[^'\\]|\\.)*')+$/.test(raw) };
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** The command word of a lexed simple command under both command-position models (the shared walk and the strict wrapper model). */
|
|
562
|
+
function commandIndices(segment: ReturnType<typeof lexCommand>["segments"][number]): number[] {
|
|
563
|
+
const indices = new Set<number>();
|
|
546
564
|
const shared = commandWordIndex(segment);
|
|
547
|
-
if (shared >= 0
|
|
565
|
+
if (shared >= 0) indices.add(shared);
|
|
548
566
|
const kept = segment.words.map((word, at) => ({ word, at })).filter(({ at }) => !segment.redirects.has(at));
|
|
549
|
-
const strict = unwrapCommand(kept.map(({ word }) => (
|
|
550
|
-
|
|
567
|
+
const strict = unwrapCommand(kept.map(({ word }) => strictWord(word.text)));
|
|
568
|
+
if (strict !== null && strict.index >= 0) indices.add(kept[strict.index].at);
|
|
569
|
+
return [...indices];
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* The files lexed simple commands write through their own program: sed's
|
|
574
|
+
* `w`, `W` and `s///w` targets (localExecutor `writes`), with the command in
|
|
575
|
+
* command position, behind a wrapper, run by find or xargs, or inside a
|
|
576
|
+
* command substitution. segmentTargets judges each exactly as it judges a `>`
|
|
577
|
+
* redirect target. A sed script this cannot read is refused elsewhere: it is
|
|
578
|
+
* an unresolved local executor (runsDestructiveLocalProgram).
|
|
579
|
+
*/
|
|
580
|
+
function programWriteTargets(lexed: { segments: ReturnType<typeof lexCommand>["segments"]; substitutions?: string[] }, depth = 0): string[] {
|
|
581
|
+
if (depth > 8) return [];
|
|
582
|
+
const files: string[] = [];
|
|
583
|
+
for (const segment of lexed.segments) {
|
|
584
|
+
const decoded = segment.words.map((word) => decodeCommandWord(word.text));
|
|
585
|
+
const opaqueAt = (at: number) => at >= 0 && at < segment.words.length && (segment.redirects.has(at) || expandsAtRuntime(segment.words[at].text));
|
|
586
|
+
const kept = segment.words.filter((_, at) => !segment.redirects.has(at));
|
|
587
|
+
for (const index of commandIndices(segment)) {
|
|
588
|
+
// A sed target is a file name as written: `$HOME/t` and `~/t` are not expanded.
|
|
589
|
+
files.push(...(localExecutor(decoded, index, opaqueAt)?.writes ?? []).map((file) => (file[0] === "/" ? file : `./${file}`)));
|
|
590
|
+
// A literal `sh -c`/`eval` program writes where its own sed writes, as a
|
|
591
|
+
// `>` inside the program does.
|
|
592
|
+
const shell = shellProgram(kept.map((word) => word.text), kept.indexOf(segment.words[index]), decodeCommandWord);
|
|
593
|
+
const inner = shell?.literal ? lexCommand(shell.program!) : null;
|
|
594
|
+
if (inner?.trustworthy) files.push(...programWriteTargets(inner, depth + 1));
|
|
595
|
+
for (const launched of launchedCommands(decoded, index, (at) => segment.redirects.has(at))) {
|
|
596
|
+
files.push(...programWriteTargets({ segments: [subSegment(segment, launched.start, launched.end)] }, depth + 1));
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
for (const body of lexed.substitutions ?? []) {
|
|
601
|
+
const inner = lexCommand(body);
|
|
602
|
+
if (inner.trustworthy) files.push(...programWriteTargets(inner, depth + 1));
|
|
603
|
+
}
|
|
604
|
+
return files;
|
|
551
605
|
}
|
|
552
606
|
|
|
553
607
|
/**
|
|
@@ -562,6 +616,10 @@ function segmentRunsDestructive(segment: ReturnType<typeof lexCommand>["segments
|
|
|
562
616
|
function hidesDestructiveExecutor(text: string, depth = 0): boolean {
|
|
563
617
|
if (depth > 4) return false;
|
|
564
618
|
const lexed = lexCommand(text);
|
|
619
|
+
// A command the lexer stops trusting at a `\'` inside `$'…'` is read in
|
|
620
|
+
// the spelling it follows, which the shell runs the same.
|
|
621
|
+
const plain = lexed.trustworthy ? text : ansiPlain(text);
|
|
622
|
+
if (plain !== text) return hidesDestructiveExecutor(plain, depth + 1);
|
|
565
623
|
if (lexed.trustworthy && lexed.segments.some((segment) => segmentRunsDestructive(segment))) return true;
|
|
566
624
|
const bodies = commandSubstitutions(text);
|
|
567
625
|
return (bodies ?? lexed.substitutions).some((body) => hidesDestructiveExecutor(body, depth + 1));
|
|
@@ -574,7 +632,7 @@ function commandOperation(part: ReturnType<typeof lexCommand>["segments"][number
|
|
|
574
632
|
// its own command word would otherwise read as.
|
|
575
633
|
if (runsDestructiveLocalProgram(part, index)) return "delete";
|
|
576
634
|
const kept = part.words.filter((_, at) => at >= index && !part.redirects.has(at));
|
|
577
|
-
const words = kept.map((word) =>
|
|
635
|
+
const words = kept.map((word) => decodeCommandWord(word.text));
|
|
578
636
|
const tool = words[0].split("/").pop();
|
|
579
637
|
if (["rm", "rmdir", "shred"].includes(tool ?? "")) return asksForHelp(words, 1, false) ? "read" : "delete";
|
|
580
638
|
// POSIX/BSD unlink takes no options, so `unlink --help` removes a file
|
|
@@ -608,7 +666,7 @@ function commandOperation(part: ReturnType<typeof lexCommand>["segments"][number
|
|
|
608
666
|
// opaque reading below.
|
|
609
667
|
if (tool === "find" && !kept.some((word) => expandsAtRuntime(word.text)) && !words.some((word) => FIND_ACTIONS.has(word))) return "read";
|
|
610
668
|
if (tool === "env" && mentionsDeleteVerb(envSplitCommandText(words))) return "delete";
|
|
611
|
-
if (["sh", "bash", "zsh", "dash", "ksh", "ash", "eval", "source", ".", "su", "runuser", "env", "xargs", "find", "busybox", "toybox"].includes(tool ?? "")) {
|
|
669
|
+
if (["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "eval", "source", ".", "su", "runuser", "env", "xargs", "find", "busybox", "toybox"].includes(tool ?? "")) {
|
|
612
670
|
return opaqueOperation(words.join(" "));
|
|
613
671
|
}
|
|
614
672
|
if (["mkdir", "mkfile", "touch", "mv", "cp", "ln", "tee", "install", "dd", "rsync", "scp", "truncate"].includes(tool ?? "")) return "write";
|
|
@@ -1193,9 +1251,14 @@ const DETACHED_CWD = "/";
|
|
|
1193
1251
|
*/
|
|
1194
1252
|
export function bashTargets(command: string, home: string, cwd: string): PathTarget[] {
|
|
1195
1253
|
if (!command) return [];
|
|
1254
|
+
// A command the lexer stops trusting at a `\'` inside `$'…'` is also read in
|
|
1255
|
+
// the spelling it follows, which the shell runs the same.
|
|
1256
|
+
const plain = lexCommand(command).trustworthy ? command : ansiPlain(command);
|
|
1196
1257
|
const data = dataHeredocs(command);
|
|
1197
|
-
|
|
1198
|
-
|
|
1258
|
+
return [
|
|
1259
|
+
...(plain === command ? [] : bashTargets(plain, home, cwd)),
|
|
1260
|
+
...(data ? [...segmentTargets(data.outer, home, cwd), ...data.bodies.flatMap((body) => bashTargets(body, home, DETACHED_CWD))] : segmentTargets(command, home, cwd)),
|
|
1261
|
+
];
|
|
1199
1262
|
}
|
|
1200
1263
|
|
|
1201
1264
|
/** Where segmentTargets splits a command into parts; the capture keeps each separator as a part. */
|
|
@@ -1256,7 +1319,7 @@ function onlyReads(segment: LexedSegment, text: string, skip: LexedWord[] = []):
|
|
|
1256
1319
|
if (segmentOperation(text) !== "read") return false;
|
|
1257
1320
|
const index = commandWordIndex(segment);
|
|
1258
1321
|
const kept = segment.words.filter((_, at) => !segment.redirects.has(at));
|
|
1259
|
-
const strict = unwrapCommand(kept.map((word) => (
|
|
1322
|
+
const strict = unwrapCommand(kept.map((word) => strictWord(word.text)));
|
|
1260
1323
|
if (strict === null) return false;
|
|
1261
1324
|
const runsAt = [index < 0 ? Infinity : index, strict.index < 0 ? Infinity : segment.words.indexOf(kept[strict.index])];
|
|
1262
1325
|
if (segment.words.some((word, at) => at < Math.max(...runsAt) && !segment.redirects.has(at) && ASSIGNMENT.test(decodeWord(word.text)))) return false;
|
|
@@ -1417,8 +1480,24 @@ function segmentTargets(command: string, home: string, cwd: string): PathTarget[
|
|
|
1417
1480
|
// trailing operand counts only when that stage's own command writes or
|
|
1418
1481
|
// deletes, so the last word of a later read-only stage (`| head -60`) is
|
|
1419
1482
|
// never taken as the write target of an earlier stage.
|
|
1420
|
-
|
|
1421
|
-
|
|
1483
|
+
// Files a command's own program writes (sed `w` targets) are write
|
|
1484
|
+
// targets, like redirect operands. A part that holds a piece of a quoted
|
|
1485
|
+
// word the split cut takes them from the owning commands of the whole
|
|
1486
|
+
// lexed command, whose script is not cut.
|
|
1487
|
+
const partFrom = execCuts === null ? 0 : execCuts.offsets[index];
|
|
1488
|
+
const inPart = (word: LexedWord) => word.start < partFrom + rawSegment.length && word.end > partFrom;
|
|
1489
|
+
// Otherwise they come from the part itself, read whole before any group
|
|
1490
|
+
// unwrapping (which strips a trailing `)` from `x=$(sed …)`) and as
|
|
1491
|
+
// unwrapped; every target counts once per part, on its first stage.
|
|
1492
|
+
const partWrites = execCuts !== null && execCuts.words.some(inPart)
|
|
1493
|
+
? programWriteTargets({ segments: execCuts.lexed.segments.filter((owner) => owner.words.some(inPart)) })
|
|
1494
|
+
: [rawSegment.trim(), segment].flatMap((text) => {
|
|
1495
|
+
let lexedPart = lexCommand(text);
|
|
1496
|
+
if (!lexedPart.trustworthy) lexedPart = lexCommand(ansiPlain(text));
|
|
1497
|
+
return lexedPart.trustworthy ? programWriteTargets(lexedPart) : [];
|
|
1498
|
+
});
|
|
1499
|
+
const stages = pipelineStages(segment).map((stage, stageIndex) => {
|
|
1500
|
+
const operands: string[] = stageIndex === 0 ? [...new Set(partWrites)] : [];
|
|
1422
1501
|
// A redirect whose target cannot be read statically (empty, or built
|
|
1423
1502
|
// from `$...`/`$( )`/backticks) may write anywhere, including a
|
|
1424
1503
|
// protected path the stage names: the stage then counts as a write.
|
|
@@ -1572,6 +1651,9 @@ export function evaluate(input: CodewithHookInput, options: { home?: string } =
|
|
|
1572
1651
|
if (!command) return { output: { continue: true }, warnings };
|
|
1573
1652
|
const cwd = typeof input.cwd === "string" && input.cwd ? input.cwd : process.cwd();
|
|
1574
1653
|
const targets = bashTargets(command, home, cwd);
|
|
1654
|
+
// Read with the earlier double-quote backslash reading first (legacyQuotes),
|
|
1655
|
+
// so that what it blocked stays blocked, with the same reason.
|
|
1656
|
+
targets.unshift(...(readWithLegacyQuotes(command, () => bashTargets(command, home, cwd)) ?? []));
|
|
1575
1657
|
for (const target of targets) {
|
|
1576
1658
|
for (const root of roots) {
|
|
1577
1659
|
const verdict = classifyPath(target.path, root, orgs, target.op);
|