@hasna/hooks 0.13.1 → 0.14.0
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/README.md +30 -15
- package/bin/hooks/stop-review.js +53 -17
- package/bin/hooks-mcp.js +4787 -1415
- package/bin/index.js +5250 -2337
- package/bin/native-safety-entry.js +15 -37
- package/bin/native-safety-worker.cjs +38 -36
- package/bin/serve.js +34 -11
- package/dist/index.js +4970 -1579
- package/dist/lib/claude-skills-coordination.d.ts +1 -1
- package/dist/lib/codex-safety-trust.d.ts +2 -2
- package/dist/lib/native-safety-registration.d.ts +2 -2
- package/dist/lib/native-safety.d.ts +1 -1
- package/dist/lib/registry.d.ts +3 -1
- package/dist/native-safety.d.ts +4 -2
- package/dist/native-safety.js +21 -2
- package/dist/sdk/index.js +9 -53
- package/hooks/hook-job-folder-guard/README.md +61 -0
- package/hooks/hook-job-folder-guard/package.json +12 -0
- package/hooks/hook-job-folder-guard/src/classify.ts +398 -0
- package/hooks/hook-job-folder-guard/src/hook.ts +96 -0
- package/hooks/hook-protected-delete-guard/README.md +114 -0
- package/hooks/hook-protected-delete-guard/package.json +12 -0
- package/hooks/hook-protected-delete-guard/src/hook.ts +539 -0
- package/hooks/hook-signed-link-guard/src/classify.ts +41 -2
- package/hooks/hook-stop-review/README.md +16 -0
- package/hooks/hook-stop-review/manifest.json +1 -1
- package/hooks/hook-stop-review/package.json +1 -1
- package/hooks/hook-stop-review/src/hook.ts +1 -1
- package/hooks/hook-stop-review/src/native.ts +44 -8
- package/hooks/hook-stop-review/src/policy.ts +20 -8
- package/hooks/hook-stop-review/src/runtime.ts +16 -13
- package/hooks/hook-stop-review/src/types.ts +12 -2
- package/hooks/hook-trash-guard/README.md +130 -13
- package/hooks/hook-trash-guard/src/hook.ts +518 -71
- package/hooks/local-executors.ts +130 -12
- package/hooks/native-safety-composite.ts +19 -8
- package/package.json +3 -3
- package/scripts/build-native-entry.ts +123 -0
- package/scripts/build-native-worker.ts +11 -4
- package/scripts/validate-package.ts +8 -2
- package/hooks/native-safety-entry.ts +0 -11
|
@@ -90,7 +90,7 @@ import {
|
|
|
90
90
|
type WrapperSpec,
|
|
91
91
|
} from "../../shell-words";
|
|
92
92
|
export { expandBraces } from "../../shell-words";
|
|
93
|
-
import { ansiPlain, launchedCommands, legacyQuotes, localExecutor, readWithLegacyQuotes, shellProgram } from "../../local-executors";
|
|
93
|
+
import { ansiPlain, ansiPlainEvery, launchedCommands, legacyQuotes, localExecutor, readWithLegacyQuotes, shellProgram } from "../../local-executors";
|
|
94
94
|
|
|
95
95
|
const RULE = "trash-guard";
|
|
96
96
|
|
|
@@ -109,6 +109,9 @@ const DEFAULT_DESCRIPTION = "Delete via trash guard (rm intercepted and made rec
|
|
|
109
109
|
* delete under them — belongs to `hook-workspace-repos-guard`; this hook only
|
|
110
110
|
* needs to know where the handoff boundary is so it does not shadow it.
|
|
111
111
|
*/
|
|
112
|
+
/** The refusal for a delete handed over to workspace-repos-guard, here and in the native-safety composite. */
|
|
113
|
+
export const HANDOFF_REFUSED = "[workspace-repos-guard] Deletion under a protected repository checkout is refused.";
|
|
114
|
+
|
|
112
115
|
const HANDOFF_ROOTS = [".hasna/repos/clones", "workspace/repos"] as const;
|
|
113
116
|
|
|
114
117
|
/**
|
|
@@ -130,6 +133,14 @@ const REFUSED_VERBS: Record<string, string> = {
|
|
|
130
133
|
"`shred` destroys content irrecoverably and is never allowed. Re-run it as `rm -- <path>` and it is redirected into trash.",
|
|
131
134
|
};
|
|
132
135
|
|
|
136
|
+
const FIND_DELETE_REASON =
|
|
137
|
+
"`find -delete` deletes files irrecoverably and is refused. List the paths first (`find … -print`), then remove them explicitly with `rm -- <path>` so the delete is redirected into trash.";
|
|
138
|
+
const FIND_EXEC_DELETE_REASON =
|
|
139
|
+
"`find -exec <delete>` is refused: the delete runs through find, not through `rm`, and cannot be redirected into trash. Remove the paths explicitly with `rm -- <path>`.";
|
|
140
|
+
|
|
141
|
+
/** The refusals of a delete this scan read exactly, each of which it also shows to ScanOptions.observe. */
|
|
142
|
+
export const OBSERVED_REFUSALS: ReadonlySet<string> = new Set([...Object.values(REFUSED_VERBS), FIND_DELETE_REASON, FIND_EXEC_DELETE_REASON]);
|
|
143
|
+
|
|
133
144
|
/**
|
|
134
145
|
* Commands whose own argument string is a shell command we cannot rewrite in
|
|
135
146
|
* place. When one of these is in command position and the command mentions a
|
|
@@ -221,8 +232,21 @@ const KEYWORDS = new Set(["!", "{", "}", "then", "do", "else", "elif", "if", "wh
|
|
|
221
232
|
/** git's value-taking global options, skipped before the subcommand. */
|
|
222
233
|
const GIT_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"]);
|
|
223
234
|
|
|
224
|
-
/**
|
|
225
|
-
|
|
235
|
+
/**
|
|
236
|
+
* Delete verbs an opaque command string might carry, in any case: a case-insensitive filesystem (the macOS default)
|
|
237
|
+
* finds /bin/rm for `RM` (HO-00225).
|
|
238
|
+
*/
|
|
239
|
+
const DELETE_VERB_WORD_RE = /(^|[^A-Za-z0-9_.-])(rm|rmdir|unlink|shred)(?![A-Za-z0-9_.-])/i;
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* The text a check reads: quoting stripped, and also with bash's `$'…'` and `$"…"` quoting decoded where that reads
|
|
243
|
+
* differently, so `r$'m'` and `$'\x72m'` are `rm` (HO-00226).
|
|
244
|
+
*/
|
|
245
|
+
function textReadings(text: string): string[] {
|
|
246
|
+
const plain = decodeWord(text);
|
|
247
|
+
const spelled = decodeCommandWord(text);
|
|
248
|
+
return spelled === plain ? [plain] : [plain, spelled];
|
|
249
|
+
}
|
|
226
250
|
|
|
227
251
|
/**
|
|
228
252
|
* Whether a command string mentions a delete verb as its own word, once
|
|
@@ -231,7 +255,32 @@ const DELETE_VERB_WORD_RE = /(^|[^A-Za-z0-9_.-])(rm|rmdir|unlink|shred)(?![A-Za-
|
|
|
231
255
|
* failure) — never to justify a rewrite, only a refusal.
|
|
232
256
|
*/
|
|
233
257
|
export function mentionsDeleteVerb(text: string): boolean {
|
|
234
|
-
return DELETE_VERB_WORD_RE.test(
|
|
258
|
+
return textReadings(text).some((reading) => DELETE_VERB_WORD_RE.test(reading));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** find's `-delete` primary as its own word (not `--delete`, not `-deleted`). */
|
|
262
|
+
const FIND_DELETE_WORD_RE = /(^|[^A-Za-z0-9_.-])-delete(?![A-Za-z0-9_.-])/;
|
|
263
|
+
const GIT_WORD_RE = /(^|[^A-Za-z0-9_.-])git(?![A-Za-z0-9_.-])/i;
|
|
264
|
+
const CLEAN_WORD_RE = /(^|[^A-Za-z0-9_.-])clean(?![A-Za-z0-9_.-])/;
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Whether a command string names a delete form this hook refuses outright but
|
|
268
|
+
* whose words hold none of the delete verbs above: find's `-delete` primary, or
|
|
269
|
+
* `clean` after `git` in the same command (HO-00219). Like mentionsDeleteVerb it
|
|
270
|
+
* reads the text once quoting is stripped, and is used only to refuse a command
|
|
271
|
+
* that cannot be read structurally, never to justify a rewrite. Each piece
|
|
272
|
+
* between `;`, `&`, `|` and newlines is tested on its own, so the cost stays
|
|
273
|
+
* linear in the command's length.
|
|
274
|
+
*/
|
|
275
|
+
export function mentionsRefusedDeleteForm(text: string): boolean {
|
|
276
|
+
return textReadings(text).some((decoded) => {
|
|
277
|
+
if (FIND_DELETE_WORD_RE.test(decoded)) return true;
|
|
278
|
+
for (const piece of decoded.split(/[\n;&|]/)) {
|
|
279
|
+
const git = GIT_WORD_RE.exec(piece);
|
|
280
|
+
if (git && CLEAN_WORD_RE.test(piece.slice(git.index + git[0].length))) return true;
|
|
281
|
+
}
|
|
282
|
+
return false;
|
|
283
|
+
});
|
|
235
284
|
}
|
|
236
285
|
|
|
237
286
|
/** env's split-string value may be attached to its option. This text is used
|
|
@@ -280,7 +329,8 @@ function readAnsiC(raw: string, from: number): { text: string; end: number } {
|
|
|
280
329
|
const point = parseInt(m[1], 16);
|
|
281
330
|
text += point <= 0x10ffff ? String.fromCodePoint(point) : "";
|
|
282
331
|
i += 1 + m[0].length;
|
|
283
|
-
} else if (c === "c" && i + 2 < raw.length) {
|
|
332
|
+
} else if (c === "c" && i + 2 < raw.length && raw[i + 2] !== "'") {
|
|
333
|
+
// `\c` takes the next character, but never the word's closing quote (HO-00222).
|
|
284
334
|
text += String.fromCharCode(raw.charCodeAt(i + 2) & 0x1f);
|
|
285
335
|
i += 3;
|
|
286
336
|
} else {
|
|
@@ -408,13 +458,14 @@ function unquotedAfter(raw: string, from: number, target: string): boolean {
|
|
|
408
458
|
/**
|
|
409
459
|
* Whether a word the shell expands at run time could become the name of a
|
|
410
460
|
* delete: one of its brace expansions (expandBraces), or a name inside one
|
|
411
|
-
* (`$(which rm)`, `${RM:-rm}`, `$'\x72m'`),
|
|
461
|
+
* (`$(which rm)`, `${RM:-rm}`, `$'\x72m'`), or a value the command assigns to a
|
|
462
|
+
* variable it uses (`C=rm; $C`, HO-00225), is a delete verb. Too many
|
|
412
463
|
* alternatives count.
|
|
413
464
|
*/
|
|
414
|
-
function mayNameDelete(raw: string): boolean {
|
|
465
|
+
function mayNameDelete(raw: string, ctx: ScanContext): boolean {
|
|
415
466
|
if (!expandsWord(raw)) return false;
|
|
416
467
|
const words = expandBraces(raw);
|
|
417
|
-
return words === null || words.some((word) =>
|
|
468
|
+
return words === null || words.some((word) => expansionNames(word, ctx).some((token) => DELETE_VERBS.has(token)));
|
|
418
469
|
}
|
|
419
470
|
|
|
420
471
|
/** The name of the command a word runs: `/bin/rm`, `"rm"` and `$'rm'` are `rm`. */
|
|
@@ -437,6 +488,11 @@ interface Segment {
|
|
|
437
488
|
redirects: Set<number>;
|
|
438
489
|
/** Deep lexing only: bodies of the here-documents whose operator is in this segment. */
|
|
439
490
|
heredocs?: string[];
|
|
491
|
+
/**
|
|
492
|
+
* Deep lexing only: the operators just before and just after the segment (`;`, a newline as `\n`, `&&`, `||`, `|`,
|
|
493
|
+
* `&`, `&>`, `(`, `)`, or `` at either end of the command).
|
|
494
|
+
*/
|
|
495
|
+
position?: { before: string; after: string };
|
|
440
496
|
}
|
|
441
497
|
|
|
442
498
|
interface LexResult {
|
|
@@ -460,6 +516,13 @@ export interface LexOptions {
|
|
|
460
516
|
* and each body is recorded on the segment holding its operator.
|
|
461
517
|
*/
|
|
462
518
|
deep?: boolean;
|
|
519
|
+
/**
|
|
520
|
+
* When given, `#` comments are read as bash reads them, and each comment's span `[start, end)` is pushed here
|
|
521
|
+
* (HO-00210). A `#` that starts a word outside quotes, `${ … }` and `(( … ))` starts a comment running to the end
|
|
522
|
+
* of its line, and the quotes, here-document operators and substitutions in it are not syntax. Without it, as
|
|
523
|
+
* before, a comment is read as words, so a quote in it can hide the lines after it.
|
|
524
|
+
*/
|
|
525
|
+
comments?: Array<[number, number]>;
|
|
463
526
|
}
|
|
464
527
|
|
|
465
528
|
/** The lexer options scanCommand reads with. */
|
|
@@ -633,6 +696,25 @@ function scanSingleAt(text: string, from: number): number {
|
|
|
633
696
|
return end === -1 ? -1 : end + 1;
|
|
634
697
|
}
|
|
635
698
|
|
|
699
|
+
/** Index just past the `}` that closes the `${` whose `{` is at `from`, or -1. Quotes, substitutions and nested `${` are followed. */
|
|
700
|
+
function scanBraceAt(text: string, from: number): number {
|
|
701
|
+
let depth = 1;
|
|
702
|
+
let j = from + 1;
|
|
703
|
+
while (j < text.length) {
|
|
704
|
+
const c = text[j];
|
|
705
|
+
const e = c === "\\" ? j + 2 : c === "'" ? scanSingleAt(text, j) : c === '"' ? scanDoubleAt(text, j)
|
|
706
|
+
: c === "`" ? scanBacktickAt(text, j) : c === "$" && text[j + 1] === "(" ? scanParenAt(text, j + 1) : 0;
|
|
707
|
+
if (e < 0) return -1;
|
|
708
|
+
if (e > 0) j = e;
|
|
709
|
+
else if (c === "$" && text[j + 1] === "{") {
|
|
710
|
+
depth++;
|
|
711
|
+
j += 2;
|
|
712
|
+
} else if (c === "}" && --depth === 0) return j + 1;
|
|
713
|
+
else j++;
|
|
714
|
+
}
|
|
715
|
+
return -1;
|
|
716
|
+
}
|
|
717
|
+
|
|
636
718
|
function scanBacktickAt(text: string, from: number): number {
|
|
637
719
|
let j = from + 1;
|
|
638
720
|
while (j < text.length) {
|
|
@@ -831,6 +913,7 @@ export function scanParenAt(text: string, from: number): number {
|
|
|
831
913
|
*/
|
|
832
914
|
export function lexCommand(command: string, options: LexOptions = {}): LexResult {
|
|
833
915
|
const deep = options.deep === true;
|
|
916
|
+
const comments = options.comments;
|
|
834
917
|
const segments: Segment[] = [];
|
|
835
918
|
const substitutions: string[] = [];
|
|
836
919
|
let words: Word[] = [];
|
|
@@ -843,6 +926,7 @@ export function lexCommand(command: string, options: LexOptions = {}): LexResult
|
|
|
843
926
|
let i = 0;
|
|
844
927
|
const n = command.length;
|
|
845
928
|
|
|
929
|
+
// A case statement is not parsed here: a pattern's `)` is read like any other `)`, as on main (HO-00185 review 7).
|
|
846
930
|
const closeWord = (end: number): void => {
|
|
847
931
|
if (wordStart >= 0) {
|
|
848
932
|
const index = words.length;
|
|
@@ -853,9 +937,13 @@ export function lexCommand(command: string, options: LexOptions = {}): LexResult
|
|
|
853
937
|
}
|
|
854
938
|
};
|
|
855
939
|
|
|
856
|
-
|
|
940
|
+
let before = "";
|
|
941
|
+
const closeSegment = (end: number, after: string): void => {
|
|
857
942
|
closeWord(end);
|
|
858
|
-
if (words.length > 0)
|
|
943
|
+
if (words.length > 0) {
|
|
944
|
+
segments.push(deep ? { words, redirects, heredocs, position: { before, after } } : { words, redirects });
|
|
945
|
+
}
|
|
946
|
+
before = after;
|
|
859
947
|
words = [];
|
|
860
948
|
redirects = new Set<number>();
|
|
861
949
|
if (deep) heredocs = [];
|
|
@@ -876,7 +964,7 @@ export function lexCommand(command: string, options: LexOptions = {}): LexResult
|
|
|
876
964
|
continue;
|
|
877
965
|
}
|
|
878
966
|
if (ch === "\n") {
|
|
879
|
-
closeSegment(i);
|
|
967
|
+
closeSegment(i, "\n");
|
|
880
968
|
if (pendingHeredocs.length > 0) {
|
|
881
969
|
// Deep lexing: the bodies start on the line after the operator's line.
|
|
882
970
|
const end = readHeredocBodies(command, i, pendingHeredocs, substitutions);
|
|
@@ -891,18 +979,41 @@ export function lexCommand(command: string, options: LexOptions = {}): LexResult
|
|
|
891
979
|
continue;
|
|
892
980
|
}
|
|
893
981
|
if (ch === ";") {
|
|
894
|
-
closeSegment(i);
|
|
982
|
+
closeSegment(i, ";");
|
|
895
983
|
i++;
|
|
896
984
|
continue;
|
|
897
985
|
}
|
|
898
986
|
if (ch === "&") {
|
|
899
|
-
closeSegment(i);
|
|
987
|
+
closeSegment(i, command[i + 1] === "&" ? "&&" : command[i + 1] === ">" ? "&>" : "&");
|
|
900
988
|
i += command[i + 1] === "&" ? 2 : 1;
|
|
901
989
|
continue;
|
|
902
990
|
}
|
|
903
991
|
if (ch === "|") {
|
|
904
|
-
|
|
905
|
-
i
|
|
992
|
+
// `|&` pipes stdout and stderr: the next command is a pipeline stage (HO-00185 review 4, B3).
|
|
993
|
+
closeSegment(i, command[i + 1] === "|" ? "||" : "|");
|
|
994
|
+
i += /[|&]/.test(command[i + 1]) ? 2 : 1;
|
|
995
|
+
continue;
|
|
996
|
+
}
|
|
997
|
+
if (comments && wordStart < 0 && (ch === "#" || (ch === "(" && command[i + 1] === "("))) {
|
|
998
|
+
// A comment runs to its newline, which ends the segment as usual. `(( … ))` is arithmetic, where `#` is not a
|
|
999
|
+
// comment (bash 5.2), so it is passed over whole.
|
|
1000
|
+
const newline = command.indexOf("\n", i);
|
|
1001
|
+
const e = ch === "(" ? scanParenAt(command, i) : newline < 0 ? n : newline;
|
|
1002
|
+
if (ch === "#") comments.push([i, e]);
|
|
1003
|
+
if (e < 0) {
|
|
1004
|
+
trustworthy = false;
|
|
1005
|
+
i = n;
|
|
1006
|
+
} else i = e;
|
|
1007
|
+
continue;
|
|
1008
|
+
}
|
|
1009
|
+
if (comments && ch === "$" && command[i + 1] === "{") {
|
|
1010
|
+
// `${ … }` is one word whatever spaces it holds, and a `#` in it is not a comment.
|
|
1011
|
+
if (wordStart < 0) wordStart = i;
|
|
1012
|
+
const e = scanBraceAt(command, i + 1);
|
|
1013
|
+
if (e < 0) {
|
|
1014
|
+
trustworthy = false;
|
|
1015
|
+
i = n;
|
|
1016
|
+
} else i = e;
|
|
906
1017
|
continue;
|
|
907
1018
|
}
|
|
908
1019
|
if (deep && ch === "(" && wordStart >= 0 && "?*+@!".includes(command[i - 1])) {
|
|
@@ -913,7 +1024,7 @@ export function lexCommand(command: string, options: LexOptions = {}): LexResult
|
|
|
913
1024
|
continue;
|
|
914
1025
|
}
|
|
915
1026
|
if (ch === "(" || ch === ")") {
|
|
916
|
-
closeSegment(i);
|
|
1027
|
+
closeSegment(i, ch);
|
|
917
1028
|
i++;
|
|
918
1029
|
continue;
|
|
919
1030
|
}
|
|
@@ -1027,7 +1138,7 @@ export function lexCommand(command: string, options: LexOptions = {}): LexResult
|
|
|
1027
1138
|
i++;
|
|
1028
1139
|
}
|
|
1029
1140
|
|
|
1030
|
-
closeSegment(n);
|
|
1141
|
+
closeSegment(n, "");
|
|
1031
1142
|
// A here-document operator with no line after it has an empty body (bash
|
|
1032
1143
|
// warns and runs the command).
|
|
1033
1144
|
if (pendingHeredocs.length > 0 && readHeredocBodies(command, n, pendingHeredocs, substitutions) < 0) trustworthy = false;
|
|
@@ -1346,8 +1457,69 @@ interface ScanContext {
|
|
|
1346
1457
|
home: string;
|
|
1347
1458
|
/** Recursion depth for substitution bodies. */
|
|
1348
1459
|
depth: number;
|
|
1460
|
+
/** Whether the command names CDPATH (an assignment or export), so a relative `cd` name may go anywhere (HO-00185). */
|
|
1461
|
+
setsCdpath: boolean;
|
|
1349
1462
|
/** Whether any here-document body in the command mentions a delete verb. */
|
|
1350
1463
|
bodiesMention: boolean;
|
|
1464
|
+
/** What the command itself assigns to each variable (`C=rm`, `export C=clean`), decoded (HO-00225). */
|
|
1465
|
+
assigned: Map<string, Assigned>;
|
|
1466
|
+
/** Set while reading a command find -exec or xargs runs: launchedRefusal reads the nested ones itself. */
|
|
1467
|
+
launched?: boolean;
|
|
1468
|
+
/** A caller's view of each delete this scan reads (ScanOptions.observe). */
|
|
1469
|
+
observe?: DeleteObserver;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
/**
|
|
1473
|
+
* A delete a scan read exactly, shown to a caller that judges deletes by its own class (protected-delete-guard): an
|
|
1474
|
+
* `rm`, `rmdir`, `unlink` or `shred` with its operand words as written and the directory it would run in, or a `find`
|
|
1475
|
+
* with a delete action. Every reading of a segment is shown (the shared one, the strict one, main's placement, the
|
|
1476
|
+
* fail-closed one), so a caller sees each delete the scan could attribute to a word. It never changes this hook's
|
|
1477
|
+
* verdict.
|
|
1478
|
+
*/
|
|
1479
|
+
export type ObservedDelete = { verb: "rm" | "rmdir" | "unlink" | "shred"; operands: string[]; cwd: string } | { verb: "find"; cwd: string };
|
|
1480
|
+
export type DeleteObserver = (seen: ObservedDelete) => void;
|
|
1481
|
+
|
|
1482
|
+
/** A variable's assigned values, and every name they hold. */
|
|
1483
|
+
interface Assigned {
|
|
1484
|
+
values: string[];
|
|
1485
|
+
names: Set<string>;
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
const NAME_SPLIT = /[^A-Za-z0-9_]+/;
|
|
1489
|
+
|
|
1490
|
+
/** Every `NAME=value` word in the command, wherever it stands, with its value decoded. Used only to refuse. */
|
|
1491
|
+
function assignments(segments: Segment[]): Map<string, Assigned> {
|
|
1492
|
+
const found = new Map<string, Assigned>();
|
|
1493
|
+
for (const word of segments.flatMap((segment) => segment.words)) {
|
|
1494
|
+
const name = ASSIGNMENT_RE.exec(word.text)?.[0].slice(0, -1);
|
|
1495
|
+
if (!name) continue;
|
|
1496
|
+
const value = decodeCommandWord(word.text.slice(name.length + 1));
|
|
1497
|
+
const entry = found.get(name) ?? { values: [], names: new Set<string>() };
|
|
1498
|
+
entry.values.push(value);
|
|
1499
|
+
for (const token of value.split(NAME_SPLIT)) entry.names.add(token);
|
|
1500
|
+
found.set(name, entry);
|
|
1501
|
+
}
|
|
1502
|
+
return found;
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
/**
|
|
1506
|
+
* The names an expanding word may stand for as far as the command shows (HO-00225): the names written inside it
|
|
1507
|
+
* (`${C:-clean}`, `$(echo clean)`), every name held by any value the command assigns to a variable it uses
|
|
1508
|
+
* (`C=rm; $C`), and the word with those values put in (`C=r; ${C}m`), at most 16 spellings of it. Used only to refuse.
|
|
1509
|
+
*/
|
|
1510
|
+
function expansionNames(raw: string, ctx: ScanContext): string[] {
|
|
1511
|
+
const names = decodeCommandWord(raw).split(NAME_SPLIT);
|
|
1512
|
+
let spellings: string[] = [];
|
|
1513
|
+
for (const name of new Set(Array.from(raw.matchAll(/\$\{?([A-Za-z_]\w*)/g), (use) => use[1]!))) {
|
|
1514
|
+
const entry = ctx.assigned.get(name);
|
|
1515
|
+
if (!entry) continue;
|
|
1516
|
+
for (const token of entry.names) names.push(token);
|
|
1517
|
+
const use = new RegExp(`\\$(?:\\{${name}\\}|${name}(?!\\w))`, "g");
|
|
1518
|
+
spellings = (spellings.length > 0 ? spellings : [raw])
|
|
1519
|
+
.flatMap((spelling) => entry.values.slice(0, 16).map((value) => spelling.replace(use, () => value))).slice(0, 16);
|
|
1520
|
+
}
|
|
1521
|
+
for (const spelling of spellings) for (const token of decodeCommandWord(spelling).split(NAME_SPLIT)) names.push(token);
|
|
1522
|
+
return names;
|
|
1351
1523
|
}
|
|
1352
1524
|
|
|
1353
1525
|
/**
|
|
@@ -1386,7 +1558,7 @@ function segmentFacts(segment: Segment): SegmentFacts {
|
|
|
1386
1558
|
findExecDelete: execIndex >= 0 && words.slice(execIndex).some((word) => DELETE_VERBS.has(baseVerb(word))),
|
|
1387
1559
|
namesDelete: words.some((word) => DELETE_VERBS.has(baseVerb(word))),
|
|
1388
1560
|
lastFlockCommand,
|
|
1389
|
-
textMention:
|
|
1561
|
+
textMention: shellStringMentionsDelete(segmentText(segment), words.join(" ")),
|
|
1390
1562
|
envMention: mentionsDeleteVerb(envSplitCommandText(segment.words.map((word) => decodeWord(word.text)))),
|
|
1391
1563
|
bodiesMention: mentionsDeleteVerb((segment.heredocs ?? []).join("\n")),
|
|
1392
1564
|
};
|
|
@@ -1422,7 +1594,8 @@ function shellReadsStdin(segment: Segment, index: number): boolean {
|
|
|
1422
1594
|
/** What the command at one word of a segment does, as far as this hook is concerned. */
|
|
1423
1595
|
type Reading =
|
|
1424
1596
|
| { kind: "none" }
|
|
1425
|
-
|
|
1597
|
+
// `kept`: a cd this reading cannot follow, which keeps the session's directory (readDirectoryChange).
|
|
1598
|
+
| { kind: "cd"; cwd: string; kept?: true }
|
|
1426
1599
|
| { kind: "rm"; hit: RmHit; handoff: boolean; protectedReason: string | null }
|
|
1427
1600
|
| { kind: "refuse"; reason: string };
|
|
1428
1601
|
|
|
@@ -1440,6 +1613,9 @@ const BRACE_ROOT_REASON =
|
|
|
1440
1613
|
const TWO_READINGS_REASON =
|
|
1441
1614
|
"This command's wrapper arguments can be read as running two different deletes, so no single rewrite is safe. Run the delete as a plain `rm -- <path>` command, which is redirected into trash.";
|
|
1442
1615
|
|
|
1616
|
+
const MAIN_HANDOFF_REASON =
|
|
1617
|
+
"This command deletes after a `cd` this hook cannot follow, and where that cd leads the delete is in a protected repository checkout (owned by workspace-repos-guard). Write the cd with its directory alone, or run the delete as its own `rm -- <path>` command.";
|
|
1618
|
+
|
|
1443
1619
|
/**
|
|
1444
1620
|
* Index of the command word in `segment` by the strict wrapper model
|
|
1445
1621
|
* (unwrapCommand with STRICT_SPECS): -1 when the segment runs no command,
|
|
@@ -1460,17 +1636,81 @@ export function strictCommandIndex(segment: Segment): number | null {
|
|
|
1460
1636
|
return found.index < 0 ? -1 : kept[found.index];
|
|
1461
1637
|
}
|
|
1462
1638
|
|
|
1639
|
+
/**
|
|
1640
|
+
* Where a `cd` leaves the shell, read with bash's grammar (HO-00185): options first (`-L`, `-P`, `-e`, alone or
|
|
1641
|
+
* combined, the ones bash accepts on Linux), then `--`, then the directory; `cd` with no operand goes home. Before
|
|
1642
|
+
* this, `cd -- DIR` (or `-P`, `-L`, `-e`) was read as a directory named after the option under the current one, and a
|
|
1643
|
+
* bare `cd` as staying put, so from inside a checkout a later delete was handed to workspace-repos-guard, which read
|
|
1644
|
+
* the cd correctly and allowed it: the raw delete ran where the two hooks are registered on their own. These are the
|
|
1645
|
+
* plain spellings workspace-repos-guard reads the same way, so the two place the shell alike: options written bare,
|
|
1646
|
+
* no redirection before the directory. Any other spelling of the operands keeps main's reading (the word after
|
|
1647
|
+
* `cd`). A quoted or escaped verb (`"cd"`, `\cd`, `c\d`) is the cd builtin to bash, so it is read with the same
|
|
1648
|
+
* grammar (review 5, B2; main took the word after it): workspace-repos-guard does not read it, but this hook now refuses a delete it would hand
|
|
1649
|
+
* off instead of abstaining, so following it into a checkout refuses there, and the local-executor refusals that need
|
|
1650
|
+
* the shell's place in a checkout fire again. A
|
|
1651
|
+
* destination this hook cannot follow (one it cannot read before it runs, `cd -`, a relative name while the command
|
|
1652
|
+
* sets CDPATH, an option bash rejects such as `-x` or `-@`, more than one operand) keeps the session's directory, as
|
|
1653
|
+
* before: such a cd may fail, and a delete after `;` then runs where the session is. `pushd` and `popd` are not read, as before: workspace-repos-
|
|
1654
|
+
* guard does not read them, and following one into a checkout here would hand off a delete it allows.
|
|
1655
|
+
* Each word is read once, up to the second operand, so many `cd` words stay linear.
|
|
1656
|
+
* The grammar applies only where bash runs the cd in the current shell and workspace-repos-guard reads it as plain
|
|
1657
|
+
* (review 3): the first word of its segment, or the first after `{`. A cd in a pipeline or the background runs in a
|
|
1658
|
+
* child shell and moves nothing; one after a keyword (`if`, `do`, `then`) or an assignment keeps main's reading; one
|
|
1659
|
+
* inside `( … )` moves the shell for the rest of the command, as on main (scanCommand).
|
|
1660
|
+
*/
|
|
1661
|
+
function readDirectoryChange(segment: Segment, index: number, cwd: string, ctx: ScanContext): Reading {
|
|
1662
|
+
const unknown: Reading = { kind: "cd", cwd: ctx.cwd, kept: true };
|
|
1663
|
+
// Main's reading: the word right after `cd` is the directory. Any spelling that is not plain keeps it (review 2):
|
|
1664
|
+
// workspace-repos-guard reads only plain spellings with bash's grammar, and where both hooks read a cd they should
|
|
1665
|
+
// place the shell alike.
|
|
1666
|
+
const mainReading = (): Reading => {
|
|
1667
|
+
const next = segment.words[index + 1];
|
|
1668
|
+
if (!next) return { kind: "none" };
|
|
1669
|
+
return { kind: "cd", cwd: resolveLiteralTarget(next.text, cwd, ctx.home) ?? ctx.cwd };
|
|
1670
|
+
};
|
|
1671
|
+
const position = segment.position;
|
|
1672
|
+
if (position && (position.before === "|" || position.after === "|" || position.after === "&")) return { kind: "none" };
|
|
1673
|
+
if (index !== 0 && !(index === 1 && segment.words[0]!.text === "{")) return mainReading();
|
|
1674
|
+
// Plain: the verb written `cd`, each option written as a bare `-L`/`-P`/`-e` cluster or `--`, and no redirection
|
|
1675
|
+
// before the directory. Anything else keeps main's reading.
|
|
1676
|
+
let operand: string | null = null;
|
|
1677
|
+
let options = true;
|
|
1678
|
+
for (let at = index + 1; at < segment.words.length; at++) {
|
|
1679
|
+
if (segment.redirects.has(at)) {
|
|
1680
|
+
if (operand === null) return mainReading();
|
|
1681
|
+
continue;
|
|
1682
|
+
}
|
|
1683
|
+
const raw = segment.words[at]!.text;
|
|
1684
|
+
const word = expandsWord(raw) ? raw : decodeWord(raw);
|
|
1685
|
+
if (options && (word === "--" || (word.startsWith("-") && word !== "-")) && raw !== word) return mainReading();
|
|
1686
|
+
if (options && word === "--") { options = false; continue; }
|
|
1687
|
+
if (options && word.startsWith("-") && word !== "-") {
|
|
1688
|
+
if (/^-[LPe]+$/.test(word)) continue;
|
|
1689
|
+
return unknown;
|
|
1690
|
+
}
|
|
1691
|
+
options = false;
|
|
1692
|
+
if (operand !== null) return unknown;
|
|
1693
|
+
operand = raw;
|
|
1694
|
+
}
|
|
1695
|
+
// `cd &> f` is a bare cd with a redirection, which the lexer splits off; workspace-repos-guard does not read it as a cd.
|
|
1696
|
+
if (operand === null) return position?.after === "&>" ? mainReading() : { kind: "cd", cwd: ctx.home };
|
|
1697
|
+
const word = decodeWord(operand);
|
|
1698
|
+
if (word === "-") return unknown;
|
|
1699
|
+
if (ctx.setsCdpath && !/^(?:\/|\.|~|\$HOME|\$\{HOME\})/.test(word)) return unknown;
|
|
1700
|
+
const target = resolveLiteralTarget(operand, cwd, ctx.home);
|
|
1701
|
+
return target === null ? unknown : { kind: "cd", cwd: target };
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1463
1704
|
/** What the command whose word is at `index` of `segment` does. */
|
|
1464
1705
|
function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanContext): Reading {
|
|
1465
1706
|
const verb = commandName(segment.words[index].text);
|
|
1466
1707
|
|
|
1467
|
-
if (verb === "cd")
|
|
1468
|
-
const operand = segment.words[index + 1];
|
|
1469
|
-
if (!operand) return { kind: "none" };
|
|
1470
|
-
return { kind: "cd", cwd: resolveLiteralTarget(operand.text, cwd, ctx.home) ?? ctx.cwd };
|
|
1471
|
-
}
|
|
1708
|
+
if (verb === "cd") return readDirectoryChange(segment, index, cwd, ctx);
|
|
1472
1709
|
|
|
1473
|
-
if (Object.hasOwn(REFUSED_VERBS, verb))
|
|
1710
|
+
if (Object.hasOwn(REFUSED_VERBS, verb)) {
|
|
1711
|
+
ctx.observe?.({ verb: verb as "rmdir" | "unlink" | "shred", operands: rmOperands(segment, index).map((word) => word.text), cwd });
|
|
1712
|
+
return { kind: "refuse", reason: REFUSED_VERBS[verb] };
|
|
1713
|
+
}
|
|
1474
1714
|
|
|
1475
1715
|
// Local executors (interpreters with an inline program, ssh/scp/sftp
|
|
1476
1716
|
// local-exec options, rsync -e, git sshCommand, sed e/s///e) run a command
|
|
@@ -1480,7 +1720,8 @@ function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanCo
|
|
|
1480
1720
|
// broadens refusals beyond a checkout. Checked before the verb-specific
|
|
1481
1721
|
// branches so git/find/xargs do not short-circuit it. rm is never an
|
|
1482
1722
|
// executor here, so the rewrite path below is unaffected.
|
|
1483
|
-
|
|
1723
|
+
// A command find -exec or xargs runs was already read for executors with its launcher (launchedRefusal).
|
|
1724
|
+
const execReading = ctx.launched ? null : readLocalExecutor(segment, index, cwd, ctx);
|
|
1484
1725
|
if (execReading) return execReading;
|
|
1485
1726
|
|
|
1486
1727
|
if (verb === "rm") {
|
|
@@ -1489,6 +1730,7 @@ function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanCo
|
|
|
1489
1730
|
// operand"), so `rm --help` and a bare `rm -rf` are not interceptable
|
|
1490
1731
|
// deletes and are left exactly as written.
|
|
1491
1732
|
if (operands.length === 0) return { kind: "none" };
|
|
1733
|
+
ctx.observe?.({ verb: "rm", operands: operands.map((word) => word.text), cwd });
|
|
1492
1734
|
const hit: RmHit = { word: segment.words[index], operands };
|
|
1493
1735
|
const roots = handoffRoots(ctx.home);
|
|
1494
1736
|
const underRoot = (target: string | null): boolean => target !== null && roots.some((root) => isUnder(target, root));
|
|
@@ -1539,10 +1781,16 @@ function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanCo
|
|
|
1539
1781
|
}
|
|
1540
1782
|
|
|
1541
1783
|
if (verb === "git") {
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1784
|
+
// The subcommand as written, with `$'…'` and `$"…"` decoded (`git $'clean'`), and past redirections
|
|
1785
|
+
// (`git &>/dev/null -C . rm`), and, for a word the shell expands, every name it may stand for (`${C:-clean}`,
|
|
1786
|
+
// `C=clean; git $C`): each one that may be rm or clean is read as it (HO-00225).
|
|
1787
|
+
for (const [decode, past] of [[decodeWord, false], [decodeCommandWord, false], [decodeCommandWord, true]] as const) {
|
|
1788
|
+
const at = gitSubcommandAt(segment, index, decode, past);
|
|
1789
|
+
if (at < 0) continue;
|
|
1790
|
+
const raw = segment.words[at].text;
|
|
1791
|
+
const names = expandsWord(raw) ? [decode(raw), ...expansionNames(raw, ctx)] : [decode(raw)];
|
|
1792
|
+
for (const sub of ["rm", "clean"].filter((name) => names.includes(name))) {
|
|
1793
|
+
if (sub === "rm" ? gitRmIsNonDeleting(segment, index) : gitHasDryRun(segment, index)) continue;
|
|
1546
1794
|
return {
|
|
1547
1795
|
kind: "refuse",
|
|
1548
1796
|
reason:
|
|
@@ -1557,20 +1805,10 @@ function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanCo
|
|
|
1557
1805
|
|
|
1558
1806
|
const facts = segmentFacts(segment);
|
|
1559
1807
|
if (verb === "find") {
|
|
1560
|
-
if (facts.findDelete) {
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
"`find -delete` deletes files irrecoverably and is refused. List the paths first (`find … -print`), then remove them explicitly with `rm -- <path>` so the delete is redirected into trash.",
|
|
1565
|
-
};
|
|
1566
|
-
}
|
|
1567
|
-
if (facts.findExecDelete) {
|
|
1568
|
-
return {
|
|
1569
|
-
kind: "refuse",
|
|
1570
|
-
reason: "`find -exec <delete>` is refused: the delete runs through find, not through `rm`, and cannot be redirected into trash. Remove the paths explicitly with `rm -- <path>`.",
|
|
1571
|
-
};
|
|
1572
|
-
}
|
|
1573
|
-
return { kind: "none" };
|
|
1808
|
+
if (facts.findDelete || facts.findExecDelete) ctx.observe?.({ verb: "find", cwd });
|
|
1809
|
+
if (facts.findDelete) return { kind: "refuse", reason: FIND_DELETE_REASON };
|
|
1810
|
+
if (facts.findExecDelete) return { kind: "refuse", reason: FIND_EXEC_DELETE_REASON };
|
|
1811
|
+
return launchedRefusal(segment, index, cwd, ctx) ?? { kind: "none" };
|
|
1574
1812
|
}
|
|
1575
1813
|
|
|
1576
1814
|
if (verb === "xargs" && facts.namesDelete) {
|
|
@@ -1579,6 +1817,7 @@ function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanCo
|
|
|
1579
1817
|
reason: "`xargs rm` takes its targets from stdin, so this hook cannot verify what would be deleted. Pipe the paths into an explicit `rm -- <path> …` instead, which is redirected into trash.",
|
|
1580
1818
|
};
|
|
1581
1819
|
}
|
|
1820
|
+
if (verb === "xargs") return launchedRefusal(segment, index, cwd, ctx) ?? { kind: "none" };
|
|
1582
1821
|
|
|
1583
1822
|
// `flock <file> -c <string>` runs the string through a shell: as the shared
|
|
1584
1823
|
// reading sees it (`flock`) and as the strict one does (`-c`, the word after
|
|
@@ -1664,6 +1903,41 @@ function readLocalExecutor(
|
|
|
1664
1903
|
const LAUNCHER_DEPTH_REASON =
|
|
1665
1904
|
"This command nests find/xargs launchers too deeply for this hook to read what they run under a protected repository checkout. Run the inner command directly.";
|
|
1666
1905
|
|
|
1906
|
+
/**
|
|
1907
|
+
* Each command find's -exec family or xargs runs, and each one that runs in turn, read once by both command-position
|
|
1908
|
+
* models: one this hook refuses when typed (`git clean`, `find -delete`) is refused here too, with its own reason
|
|
1909
|
+
* (HO-00225). findExecDelete and namesDelete know only the delete verbs, and readLocalExecutor reads launched commands
|
|
1910
|
+
* for local executors only. Past 64 launched commands, a command that names a refused form is refused.
|
|
1911
|
+
*/
|
|
1912
|
+
function launchedRefusal(segment: Segment, index: number, cwd: string, ctx: ScanContext): Reading | null {
|
|
1913
|
+
if (ctx.launched) return null;
|
|
1914
|
+
const decoded = segment.words.map((word) => decodeCommandWord(word.text));
|
|
1915
|
+
const skip = (at: number): boolean => segment.redirects.has(at);
|
|
1916
|
+
const inner: ScanContext = { ...ctx, launched: true };
|
|
1917
|
+
const launchers = [{ at: index, end: segment.words.length }];
|
|
1918
|
+
const seen = new Set<string>();
|
|
1919
|
+
for (let next = 0; next < launchers.length; next++) {
|
|
1920
|
+
const { at, end } = launchers[next]!;
|
|
1921
|
+
for (const range of launchedCommands(decoded.slice(0, end), at, skip)) {
|
|
1922
|
+
const key = `${range.start}:${range.end}`;
|
|
1923
|
+
if (seen.has(key)) continue;
|
|
1924
|
+
seen.add(key);
|
|
1925
|
+
if (seen.size > 64) return mentionsRefusedDeleteForm(segmentText(segment)) ? { kind: "refuse", reason: UNREADABLE_WRAPPER_REASON } : null;
|
|
1926
|
+
const sub: Segment = {
|
|
1927
|
+
words: segment.words.slice(range.start, range.end),
|
|
1928
|
+
redirects: new Set([...segment.redirects].filter((r) => r >= range.start && r < range.end).map((r) => r - range.start)),
|
|
1929
|
+
};
|
|
1930
|
+
for (const command of new Set([commandWordIndex(sub), strictCommandIndex(sub) ?? -1])) {
|
|
1931
|
+
if (command < 0) continue;
|
|
1932
|
+
const reading = readCommandAt(sub, command, cwd, inner);
|
|
1933
|
+
if (reading.kind === "refuse") return reading;
|
|
1934
|
+
launchers.push({ at: range.start + command, end: range.end });
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
return null;
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1667
1941
|
/**
|
|
1668
1942
|
* Whether a local executor's effective cwd, or one of its literal operands,
|
|
1669
1943
|
* sits under a protected repo-checkout root — the only place trash-guard adds a
|
|
@@ -1694,14 +1968,85 @@ function executorTargetsHandoff(segment: Segment, index: number, cwd: string, ho
|
|
|
1694
1968
|
* read the wrapper arguments, a segment any of whose words could run a delete
|
|
1695
1969
|
* is refused.
|
|
1696
1970
|
*/
|
|
1697
|
-
|
|
1971
|
+
interface ScanOptions {
|
|
1972
|
+
cwd: string;
|
|
1973
|
+
home: string;
|
|
1974
|
+
depth?: number;
|
|
1975
|
+
/** Called for each delete the scan reads exactly (ObservedDelete), in substitution bodies too. */
|
|
1976
|
+
observe?: DeleteObserver;
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
const CASE_WORD_RE = /(^|[^A-Za-z0-9_.-])(case|esac)(?![A-Za-z0-9_.-])/;
|
|
1980
|
+
|
|
1981
|
+
/**
|
|
1982
|
+
* The command with each `#` comment (LexOptions.comments) blanked to spaces. Every other character keeps its offset,
|
|
1983
|
+
* so a delete found in it is rewritten in place in the command itself.
|
|
1984
|
+
*/
|
|
1985
|
+
export function blankComments(command: string): string {
|
|
1986
|
+
if (!command.includes("#")) return command;
|
|
1987
|
+
const spans: Array<[number, number]> = [];
|
|
1988
|
+
lexCommand(command, { ...DEEP, comments: spans });
|
|
1989
|
+
let out = command;
|
|
1990
|
+
for (const [start, end] of spans) out = out.slice(0, start) + " ".repeat(end - start) + out.slice(end);
|
|
1991
|
+
return out;
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1994
|
+
/**
|
|
1995
|
+
* Both readings of a command with comments (HO-00210): the one this hook always had, where a quote or here-document
|
|
1996
|
+
* operator in a comment can hide the lines after it, and the one with its comments blanked. Each reading misses what
|
|
1997
|
+
* the other may catch, so every delete, handoff and refusal either finds is kept, and the command is trusted only when
|
|
1998
|
+
* both trust it. It never removes a refusal or a delete the first reading finds.
|
|
1999
|
+
*
|
|
2000
|
+
* A third reading spells each `\'` inside an ANSI-C `$'…'` word as `\x27` (ansiPlain), which bash decodes to the same
|
|
2001
|
+
* quote (HO-00213). The lexer ends `$'it\'s'` at the escaped quote, so the next lines could read as quoted and a delete
|
|
2002
|
+
* on them was trusted and missed. That spelling moves offsets, so what it finds is kept and the command is not trusted:
|
|
2003
|
+
* refused, never rewritten. The words are found in one pass from the left (ansiPlain) and, beside that, from every
|
|
2004
|
+
* `$'` (ansiPlainEvery), because a `$'` bash does not read as ANSI-C can start a word that hides the real one
|
|
2005
|
+
* (HO-00222).
|
|
2006
|
+
*/
|
|
2007
|
+
export function scanCommand(command: string, options: ScanOptions): ScanResult {
|
|
2008
|
+
const kept = scanReading(command, options);
|
|
2009
|
+
const blanked = blankComments(command);
|
|
2010
|
+
let result = blanked === command ? kept : unionReadings(kept, scanReading(blanked, options));
|
|
2011
|
+
for (const plain of ansiReadings(command)) {
|
|
2012
|
+
const spelled = scanCommand(plain, options);
|
|
2013
|
+
const found = spelled.rmHits.length + spelled.handoffHits.length + spelled.refusals.length + spelled.protectedHits.length > 0;
|
|
2014
|
+
if (found) result = { ...unionReadings(result, spelled), trustworthy: false };
|
|
2015
|
+
}
|
|
2016
|
+
return result;
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
/** The respelled readings of `command` (ansiPlain, then ansiPlainEvery) that differ from it and from each other. */
|
|
2020
|
+
function ansiReadings(command: string): string[] {
|
|
2021
|
+
const plain = ansiPlain(command);
|
|
2022
|
+
const every = ansiPlainEvery(command);
|
|
2023
|
+
return [plain, every].filter((reading, index, all) => reading !== command && all.indexOf(reading) === index);
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
function unionReadings(kept: ScanResult, other: ScanResult): ScanResult {
|
|
2027
|
+
// A delete both readings find is one hit (rewriteCommand refuses overlapping spans).
|
|
2028
|
+
const add = (into: RmHit[], from: RmHit[]): RmHit[] =>
|
|
2029
|
+
[...into, ...from.filter((hit) => !into.some((own) => own.word.start === hit.word.start && own.word.end === hit.word.end))];
|
|
2030
|
+
return {
|
|
2031
|
+
rmHits: add(kept.rmHits, other.rmHits),
|
|
2032
|
+
handoffHits: add(kept.handoffHits, other.handoffHits),
|
|
2033
|
+
refusals: [...kept.refusals, ...other.refusals.filter((refusal) => !kept.refusals.some((own) => own.reason === refusal.reason))],
|
|
2034
|
+
protectedHits: [...kept.protectedHits, ...other.protectedHits],
|
|
2035
|
+
trustworthy: kept.trustworthy && other.trustworthy,
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
function scanReading(command: string, options: ScanOptions): ScanResult {
|
|
1698
2040
|
const result: ScanResult = { rmHits: [], handoffHits: [], refusals: [], protectedHits: [], trustworthy: true };
|
|
1699
2041
|
|
|
1700
2042
|
const lexed = lexCommand(command, DEEP);
|
|
1701
2043
|
result.trustworthy = lexed.trustworthy;
|
|
1702
2044
|
const ctx: ScanContext = {
|
|
1703
2045
|
cwd: options.cwd, home: options.home, depth: options.depth ?? 0,
|
|
2046
|
+
setsCdpath: /\bCDPATH\b/.test(command),
|
|
1704
2047
|
bodiesMention: mentionsDeleteVerb(lexed.segments.flatMap((segment) => segment.heredocs ?? []).join("\n")),
|
|
2048
|
+
assigned: assignments(lexed.segments),
|
|
2049
|
+
observe: options.observe,
|
|
1705
2050
|
};
|
|
1706
2051
|
|
|
1707
2052
|
if (!lexed.trustworthy) {
|
|
@@ -1726,10 +2071,41 @@ export function scanCommand(command: string, options: { cwd: string; home: strin
|
|
|
1726
2071
|
};
|
|
1727
2072
|
|
|
1728
2073
|
let cwd = ctx.cwd;
|
|
2074
|
+
// Main's placement, kept beside this one for refusals only (HO-00185 reviews 7 to 9). The two disagree where bash
|
|
2075
|
+
// may not run a cd this reading follows (one after `||`, a case pattern `cd)`, one inside `${ … }`, a failing
|
|
2076
|
+
// `cd -P /missing`), and where this reading does not follow a cd bash runs (`cd DIR # comment` and `cd DIR $EMPTY`
|
|
2077
|
+
// read as more than one operand). Every reading that depends on the directory (the command word, the fail-closed
|
|
2078
|
+
// scan, the strict reading, the protected class and the substitution bodies) also runs at main's placement, and a
|
|
2079
|
+
// refusal found there is kept. It never adds a delete or a rewrite.
|
|
2080
|
+
let mainCwd = ctx.cwd;
|
|
2081
|
+
// Main's handoff (a delete under the checkout roots, or run from inside one) is kept too, once this reading has not
|
|
2082
|
+
// followed a cd that main followed somewhere else (HO-00185 review 11, B1): with Trash installed,
|
|
2083
|
+
// the native-safety composite reads only this reading's handoffs, so `cd ~/.hasna/repos # c` then `rm -rf clones`
|
|
2084
|
+
// was rewritten into Trash where main's composite refused it. It is not kept after a cd this reading follows and main
|
|
2085
|
+
// misreads (`cd -- /tmp` from a checkout), which is the change this reading makes. Once bound, it stays bound.
|
|
2086
|
+
let mainHandoffBinds = false;
|
|
1729
2087
|
for (const segment of lexed.segments) {
|
|
2088
|
+
// A cd moves the shell for the rest of the command, inside `( … )` too, as on main: the lexer's `)` is not always
|
|
2089
|
+
// bash's (a case pattern, `${x:-)}`), so ending a cd's directory there let a delete run raw (HO-00185 reviews 7
|
|
2090
|
+
// and 8). A delete after a subshell that left a checkout is refused rather than redirected.
|
|
1730
2091
|
const index = commandWordIndex(segment);
|
|
1731
2092
|
const strict = strictCommandIndex(segment);
|
|
1732
2093
|
const shared: Reading = index < 0 ? { kind: "none" } : readCommandAt(segment, index, cwd, ctx);
|
|
2094
|
+
const placementsDiffer = mainCwd !== cwd;
|
|
2095
|
+
// A refusal at main's placement: a local executor there, or a delete of the protected class there.
|
|
2096
|
+
const keepMainRefusal = (atMain: Reading): void => {
|
|
2097
|
+
if (atMain.kind === "refuse") later.push({ reason: atMain.reason });
|
|
2098
|
+
else if (atMain.kind === "rm" && atMain.protectedReason) result.protectedHits.push({ reason: atMain.protectedReason });
|
|
2099
|
+
else if (atMain.kind === "rm" && atMain.handoff && mainHandoffBinds) {
|
|
2100
|
+
// handoffHits make the composite refuse as main's did; the refusal gives trash-guard alone this reason.
|
|
2101
|
+
result.handoffHits.push(atMain.hit);
|
|
2102
|
+
later.push({ reason: MAIN_HANDOFF_REASON });
|
|
2103
|
+
}
|
|
2104
|
+
};
|
|
2105
|
+
if (index >= 0 && placementsDiffer) keepMainRefusal(readCommandAt(segment, index, mainCwd, ctx));
|
|
2106
|
+
if (index >= 0 && commandName(segment.words[index].text) === "cd" && segment.words[index + 1]) {
|
|
2107
|
+
mainCwd = resolveLiteralTarget(segment.words[index + 1].text, mainCwd, ctx.home) ?? ctx.cwd;
|
|
2108
|
+
}
|
|
1733
2109
|
// The shared reading first, so its reasons keep their place.
|
|
1734
2110
|
if (shared.kind !== "cd") apply(shared);
|
|
1735
2111
|
const expands = (at: number | null): boolean => at !== null && at >= 0 && expandsWord(segment.words[at].text);
|
|
@@ -1737,7 +2113,9 @@ export function scanCommand(command: string, options: { cwd: string; home: strin
|
|
|
1737
2113
|
// Fail closed: the word that runs is unknown, so every word that could
|
|
1738
2114
|
// run a delete counts, including one an expansion could turn into a
|
|
1739
2115
|
// delete verb.
|
|
1740
|
-
|
|
2116
|
+
const couldDelete = (at: number): boolean => deletes(readCommandAt(segment, at, cwd, ctx))
|
|
2117
|
+
|| (placementsDiffer && deletes(readCommandAt(segment, at, mainCwd, ctx)));
|
|
2118
|
+
if (segment.words.some((word, at) => !segment.redirects.has(at) && (couldDelete(at) || mayNameDelete(word.text, ctx)))) {
|
|
1741
2119
|
later.push({ reason: UNREADABLE_WRAPPER_REASON });
|
|
1742
2120
|
}
|
|
1743
2121
|
} else if (strict >= 0 && strict !== index) {
|
|
@@ -1746,8 +2124,23 @@ export function scanCommand(command: string, options: { cwd: string; home: strin
|
|
|
1746
2124
|
if (deletes(shared)) later.push({ reason: TWO_READINGS_REASON });
|
|
1747
2125
|
else apply(other, later);
|
|
1748
2126
|
}
|
|
2127
|
+
if (placementsDiffer) keepMainRefusal(readCommandAt(segment, strict, mainCwd, ctx));
|
|
2128
|
+
}
|
|
2129
|
+
// A case-insensitive filesystem (the macOS default) runs /bin/rm for `RM`, so the segment is read again in lower
|
|
2130
|
+
// case, and a delete or refusal found there at a command position this reading does not already read as one is
|
|
2131
|
+
// refused (HO-00225).
|
|
2132
|
+
const folded = foldedSegment(segment);
|
|
2133
|
+
const own = new Set([index, strict ?? -1]);
|
|
2134
|
+
if (folded && [commandWordIndex(folded), strictCommandIndex(folded) ?? -1].some((at) => at >= 0
|
|
2135
|
+
&& deletes(readCommandAt(folded, at, cwd, ctx)) && !(own.has(at) && deletes(readCommandAt(segment, at, cwd, ctx))))) {
|
|
2136
|
+
later.push({ reason: CAPITALS_REASON });
|
|
1749
2137
|
}
|
|
1750
2138
|
if (shared.kind === "cd") cwd = shared.cwd;
|
|
2139
|
+
// A cd this reading does not follow: one it cannot read (`kept`), or one it reads as moving nothing (a pipeline
|
|
2140
|
+
// stage or the background, which is also how this lexer reads `cd DIR ${x:+|}`).
|
|
2141
|
+
const notFollowed = (shared.kind === "cd" && shared.kept === true)
|
|
2142
|
+
|| (shared.kind === "none" && index >= 0 && commandName(segment.words[index].text) === "cd");
|
|
2143
|
+
if (notFollowed && mainCwd !== cwd) mainHandoffBinds = true;
|
|
1751
2144
|
}
|
|
1752
2145
|
|
|
1753
2146
|
// A delete hidden inside a command substitution runs before the rewritten
|
|
@@ -1755,10 +2148,14 @@ export function scanCommand(command: string, options: { cwd: string; home: strin
|
|
|
1755
2148
|
// command that still contains a live delete. A body that cannot be read
|
|
1756
2149
|
// to its end is refused when it mentions a delete.
|
|
1757
2150
|
if (ctx.depth < 3) {
|
|
2151
|
+
// Each body is read at this reading's directory and, where it differs, at main's placement (HO-00185 review 9, M1).
|
|
2152
|
+
const live = (body: string, at: string): boolean => {
|
|
2153
|
+
const inner = scanCommand(body, { cwd: at, home: ctx.home, depth: ctx.depth + 1, observe: ctx.observe });
|
|
2154
|
+
return inner.rmHits.length > 0 || inner.refusals.length > 0 || inner.handoffHits.length > 0 || inner.protectedHits.length > 0
|
|
2155
|
+
|| (!inner.trustworthy && mentionsDeleteVerb(body));
|
|
2156
|
+
};
|
|
1758
2157
|
for (const body of lexed.substitutions) {
|
|
1759
|
-
|
|
1760
|
-
if (inner.rmHits.length > 0 || inner.refusals.length > 0 || inner.handoffHits.length > 0 || inner.protectedHits.length > 0
|
|
1761
|
-
|| (!inner.trustworthy && mentionsDeleteVerb(body))) {
|
|
2158
|
+
if (live(body, cwd) || (mainCwd !== cwd && live(body, mainCwd))) {
|
|
1762
2159
|
result.refusals.push({
|
|
1763
2160
|
reason: "This command runs a delete inside a command substitution `$(…)`, which this hook cannot rewrite. Run the delete as a separate `rm -- <path>` command, which is redirected into trash.",
|
|
1764
2161
|
});
|
|
@@ -1771,6 +2168,10 @@ export function scanCommand(command: string, options: { cwd: string; home: strin
|
|
|
1771
2168
|
});
|
|
1772
2169
|
}
|
|
1773
2170
|
result.refusals.push(...later);
|
|
2171
|
+
// A case statement inside a substitution ends it at its first pattern's `)` (scanParenAt), so the rest of the
|
|
2172
|
+
// statement may not have been read as commands at all: such a command is never rewritten, and is refused when its
|
|
2173
|
+
// scan found a delete or it names a delete verb (scanVerdict; HO-00185 review 7 B2, HO-00208 B1).
|
|
2174
|
+
if (lexed.substitutions.some((body) => CASE_WORD_RE.test(body))) result.trustworthy = false;
|
|
1774
2175
|
|
|
1775
2176
|
return result;
|
|
1776
2177
|
}
|
|
@@ -1779,16 +2180,60 @@ function segmentText(segment: Segment): string {
|
|
|
1779
2180
|
return segment.words.map((word) => word.text).join(" ");
|
|
1780
2181
|
}
|
|
1781
2182
|
|
|
1782
|
-
|
|
1783
|
-
|
|
2183
|
+
const CAPITALS_REASON =
|
|
2184
|
+
"A command name in capitals, such as `RM`, runs the lower-case command on a case-insensitive filesystem (the macOS default), and in lower case this command deletes or is refused. Write it in lower case.";
|
|
2185
|
+
|
|
2186
|
+
/**
|
|
2187
|
+
* The segment with each word that could name a command and holds a capital letter spelled in lower case, or null if
|
|
2188
|
+
* none. Options (`-C`, `-F`) and words with other characters (a program, an expansion) keep their case: theirs matters.
|
|
2189
|
+
*/
|
|
2190
|
+
function foldedSegment(segment: Segment): Segment | null {
|
|
2191
|
+
let changed = false;
|
|
2192
|
+
const words = segment.words.map((word) => {
|
|
2193
|
+
const text = decodeCommandWord(word.text);
|
|
2194
|
+
if (!/[A-Z]/.test(text) || !/^[A-Za-z0-9_./+][A-Za-z0-9_./+-]*$/.test(text)) return word;
|
|
2195
|
+
changed = true;
|
|
2196
|
+
return { ...word, text: shellQuoteWord(text.toLowerCase()) };
|
|
2197
|
+
});
|
|
2198
|
+
return changed ? { ...segment, words } : null;
|
|
2199
|
+
}
|
|
2200
|
+
|
|
2201
|
+
/**
|
|
2202
|
+
* Whether a command string a shell will run (`bash -c`, `eval`, `su -c`, …) names
|
|
2203
|
+
* a delete: a delete verb, or a form refused outright (`find -delete`, `git
|
|
2204
|
+
* clean`). The text is read as written, with each word's ANSI-C `$'…'` quoting
|
|
2205
|
+
* decoded as bash decodes it (so `$'cd x\nrm -rf build'` holds a newline, not
|
|
2206
|
+
* `\nrm`), and that decoded text decoded once more, as the shell running the
|
|
2207
|
+
* string reads it (`bash -c "$'\x72m' -rf build"`). HO-00221. Used only to
|
|
2208
|
+
* refuse.
|
|
2209
|
+
*/
|
|
2210
|
+
function shellStringMentionsDelete(text: string, decodedWords: string): boolean {
|
|
2211
|
+
return [text, decodedWords, decodeCommandWord(decodedWords)].some((reading) => mentionsDeleteVerb(reading) || mentionsRefusedDeleteForm(reading));
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
/**
|
|
2215
|
+
* The index of git's subcommand word, skipping git's own value-taking global options read with `decode`, and the
|
|
2216
|
+
* targets of redirections when `pastRedirects` is set, or -1.
|
|
2217
|
+
*/
|
|
2218
|
+
function gitSubcommandAt(segment: Segment, verbIndex: number, decode: (raw: string) => string, pastRedirects = false): number {
|
|
1784
2219
|
let index = verbIndex + 1;
|
|
1785
2220
|
while (index < segment.words.length) {
|
|
1786
|
-
|
|
1787
|
-
|
|
2221
|
+
if (pastRedirects && segment.redirects.has(index)) {
|
|
2222
|
+
index++;
|
|
2223
|
+
continue;
|
|
2224
|
+
}
|
|
2225
|
+
const option = decode(segment.words[index].text);
|
|
2226
|
+
if (!option.startsWith("-")) return index;
|
|
1788
2227
|
index++;
|
|
1789
2228
|
if (GIT_VALUE_OPTIONS.has(option)) index++;
|
|
1790
2229
|
}
|
|
1791
|
-
return
|
|
2230
|
+
return -1;
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
/** The git subcommand, skipping git's own value-taking global options. */
|
|
2234
|
+
export function gitSubcommand(segment: Segment, verbIndex: number): string | null {
|
|
2235
|
+
const at = gitSubcommandAt(segment, verbIndex, decodeWord);
|
|
2236
|
+
return at < 0 ? null : decodeWord(segment.words[at].text);
|
|
1792
2237
|
}
|
|
1793
2238
|
|
|
1794
2239
|
/** `git rm` that does not remove a working-tree file: `--cached` or a dry run. */
|
|
@@ -1823,6 +2268,9 @@ export function rewriteCommand(command: string, hits: RmHit[], trashPath: string
|
|
|
1823
2268
|
execution.runtime, "--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", trashPath, "guard"].map(shellQuoteWord).join(" ")
|
|
1824
2269
|
: `${shellQuoteWord(trashPath)} guard`;
|
|
1825
2270
|
const ordered = [...hits].sort((a, b) => b.word.start - a.word.start);
|
|
2271
|
+
// Two verbs whose spans overlap cannot both be replaced in place: the command comes back unchanged, which
|
|
2272
|
+
// rewriteIsComplete refuses.
|
|
2273
|
+
if (ordered.some((hit, at) => at > 0 && hit.word.end > ordered[at - 1].word.start)) return command;
|
|
1826
2274
|
let out = command;
|
|
1827
2275
|
for (const hit of ordered) {
|
|
1828
2276
|
out = `${out.slice(0, hit.word.start)}${replacement}${out.slice(hit.word.end)}`;
|
|
@@ -1978,28 +2426,25 @@ function scanVerdict(scanned: ScanResult, command: string): CodewithHookOutput |
|
|
|
1978
2426
|
}
|
|
1979
2427
|
|
|
1980
2428
|
if (!scanned.trustworthy) {
|
|
1981
|
-
// The
|
|
1982
|
-
// can be trusted
|
|
1983
|
-
|
|
2429
|
+
// The scan could not follow this command to its end, so no rewrite of it
|
|
2430
|
+
// can be trusted: the lexer stopped, a `case` word sits inside a
|
|
2431
|
+
// substitution (scanReading), or the `$'…'` spelling found what the plain
|
|
2432
|
+
// reading missed (scanCommand). A delete the scan found, or a delete-verb
|
|
2433
|
+
// word, means it might be a delete: refuse. The text match alone misses a quoted verb the
|
|
2434
|
+
// scan still read (`r""m` after two here-documents; HO-00208 B1).
|
|
2435
|
+
return scanned.rmHits.length > 0 || scanned.handoffHits.length > 0 || mentionsDeleteVerb(command)
|
|
2436
|
+
|| mentionsRefusedDeleteForm(command)
|
|
1984
2437
|
? deny(
|
|
1985
|
-
"[trash-guard] This
|
|
2438
|
+
"[trash-guard] This hook could not follow this command to its end (an unclosed quote, substitution or here-document, or a construct it does not read, such as `case` inside a substitution), so a delete inside it cannot be redirected. Re-run the delete as a plain `rm -- <path>` command.",
|
|
1986
2439
|
)
|
|
1987
2440
|
: { continue: true };
|
|
1988
2441
|
}
|
|
1989
2442
|
|
|
1990
2443
|
if (scanned.rmHits.length === 0) {
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
return deny(
|
|
1996
|
-
"[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.",
|
|
1997
|
-
);
|
|
1998
|
-
}
|
|
1999
|
-
// No delete to redirect. Any handed off belongs to the guarded
|
|
2000
|
-
// repo-checkout roots, which `workspace-repos-guard` owns: abstain and
|
|
2001
|
-
// let that hook decide.
|
|
2002
|
-
return { continue: true };
|
|
2444
|
+
// A delete from inside, or of a path under, the guarded repo-checkout roots, which workspace-repos-guard owns: refused
|
|
2445
|
+
// here too, with the text the native-safety composite gives (HO-00185 review 4). Abstaining let a raw delete run
|
|
2446
|
+
// when the cwd was inside a checkout and every path outside it, or when the two hooks placed the shell differently.
|
|
2447
|
+
return scanned.handoffHits.length > 0 ? deny(HANDOFF_REFUSED) : { continue: true };
|
|
2003
2448
|
}
|
|
2004
2449
|
|
|
2005
2450
|
if (scanned.handoffHits.length > 0) {
|
|
@@ -2086,7 +2531,9 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
|
|
|
2086
2531
|
|
|
2087
2532
|
/** Verdict used when the hook itself fails: refuse anything that could delete. */
|
|
2088
2533
|
export function fallbackVerdict(command: string): CodewithHookOutput {
|
|
2089
|
-
|
|
2534
|
+
// find -delete and git clean too, not only the rm-type verbs (HO-00225 N6).
|
|
2535
|
+
const names = (): boolean => mentionsDeleteVerb(command) || mentionsRefusedDeleteForm(command);
|
|
2536
|
+
return names() || readWithLegacyQuotes(command, names) || /^\s*\*\*\* Delete File:/m.test(command)
|
|
2090
2537
|
? deny(
|
|
2091
2538
|
"[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.",
|
|
2092
2539
|
)
|