@hasna/hooks 0.12.6 → 0.12.7
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 +10 -4
- package/bin/hooks-mcp.js +3160 -1130
- package/bin/index.js +3503 -1475
- package/bin/native-safety-entry.js +25 -20
- package/bin/native-safety-worker.cjs +25 -20
- package/bin/serve.js +2 -2
- package/dist/index.js +3347 -1301
- package/dist/lib/claude-skills-coordination.d.ts +16 -2
- package/dist/lib/installer.d.ts +11 -0
- package/dist/lib/native-safety-registration.d.ts +8 -3
- package/hooks/hook-trash-guard/README.md +49 -15
- package/hooks/hook-trash-guard/src/hook.ts +741 -125
- package/hooks/hook-workspace-repos-guard/src/hook.ts +274 -79
- package/hooks/shell-words.ts +368 -0
- package/package.json +2 -2
|
@@ -42,6 +42,23 @@
|
|
|
42
42
|
* command that mixes an owned `rm` with a handed-over one is refused
|
|
43
43
|
* rather than partially rewritten.
|
|
44
44
|
*
|
|
45
|
+
* Reading a command (scanCommand):
|
|
46
|
+
* - Each segment's command is read twice: by the shared command-position
|
|
47
|
+
* walk (commandWordIndex) and by the strict wrapper model
|
|
48
|
+
* (unwrapCommand, hooks/shell-words.ts, with sudo, doas and flock
|
|
49
|
+
* added), which reads option clusters (`timeout -vk 5 30 rm`) and
|
|
50
|
+
* long-option abbreviations (`nice --adj 5 rm`) the way the real tools
|
|
51
|
+
* do. A delete found by either reading counts. When the command word or
|
|
52
|
+
* a wrapper argument cannot be read before it runs (an expansion such as
|
|
53
|
+
* `$X`, `{a,rm}`, a glob or `$'…'`, an unknown option, `env -C`), the
|
|
54
|
+
* reading fails closed: the segment is refused when any of its words
|
|
55
|
+
* could run a delete, or could become one.
|
|
56
|
+
* - Command substitutions run before the command, wherever bash runs
|
|
57
|
+
* them: unquoted, inside double quotes, in backticks (nested ones
|
|
58
|
+
* unescaped) and in a here-document body whose delimiter is unquoted. A
|
|
59
|
+
* delete inside one is refused. Text in single quotes, a quoted
|
|
60
|
+
* here-document body and a quoted argument stay data.
|
|
61
|
+
*
|
|
45
62
|
* Fail-closed on internal error: if evaluation throws, the hook denies a
|
|
46
63
|
* command that contains a delete-verb word and stays silent otherwise.
|
|
47
64
|
*/
|
|
@@ -59,6 +76,20 @@ import {
|
|
|
59
76
|
type CodewithHookInput,
|
|
60
77
|
type CodewithHookOutput,
|
|
61
78
|
} from "../../codewith-native-common";
|
|
79
|
+
import {
|
|
80
|
+
FLAG,
|
|
81
|
+
LOOKUP,
|
|
82
|
+
OPTIONAL,
|
|
83
|
+
REFUSE,
|
|
84
|
+
VALUE,
|
|
85
|
+
WRAPPER_SPECS,
|
|
86
|
+
expandBraces,
|
|
87
|
+
splitsOrMoves,
|
|
88
|
+
unwrapCommand,
|
|
89
|
+
type ShellWord,
|
|
90
|
+
type WrapperSpec,
|
|
91
|
+
} from "../../shell-words";
|
|
92
|
+
export { expandBraces } from "../../shell-words";
|
|
62
93
|
|
|
63
94
|
const RULE = "trash-guard";
|
|
64
95
|
|
|
@@ -131,12 +162,58 @@ const WRAPPER_POSITIONALS: Record<string, number> = {
|
|
|
131
162
|
timeout: 1,
|
|
132
163
|
};
|
|
133
164
|
|
|
165
|
+
/**
|
|
166
|
+
* sudo, doas and flock, for the strict reading only. The shared walk skips
|
|
167
|
+
* sudo and doas with the value-option list in WRAPPERS and does not know
|
|
168
|
+
* flock; modelling them here lets the strict model read the command and the
|
|
169
|
+
* wrappers after them (`sudo timeout -vk 5 30 rm`, `flock /tmp/l rm`).
|
|
170
|
+
* Options are sudo 1.9's, OpenBSD doas's and util-linux 2.41 flock's. A
|
|
171
|
+
* working directory or chroot (`-D`, `-R`), help, version, a host and
|
|
172
|
+
* timestamp removal are not modelled, so the reading fails closed; `-e`,
|
|
173
|
+
* `-l` and `-v` run no command. flock's first operand is its lock file, and
|
|
174
|
+
* `flock <file> -c|--command <string>` runs a shell string (readCommandAt).
|
|
175
|
+
*/
|
|
176
|
+
const RUNNER_SPECS: Record<string, WrapperSpec> = {
|
|
177
|
+
sudo: {
|
|
178
|
+
short: {
|
|
179
|
+
A: FLAG, B: FLAG, b: FLAG, E: FLAG, H: FLAG, i: FLAG, k: FLAG, N: FLAG, n: FLAG, P: FLAG, S: FLAG, s: FLAG,
|
|
180
|
+
C: VALUE, g: VALUE, p: VALUE, r: VALUE, T: VALUE, t: VALUE, U: VALUE, u: VALUE,
|
|
181
|
+
e: LOOKUP, l: LOOKUP, v: LOOKUP, D: REFUSE, R: REFUSE, h: REFUSE, K: REFUSE, V: REFUSE,
|
|
182
|
+
},
|
|
183
|
+
long: {
|
|
184
|
+
askpass: FLAG, bell: FLAG, background: FLAG, "close-from": VALUE, chdir: REFUSE, "preserve-env": OPTIONAL, edit: LOOKUP,
|
|
185
|
+
group: VALUE, "set-home": FLAG, help: REFUSE, host: REFUSE, login: FLAG, "remove-timestamp": REFUSE, "reset-timestamp": FLAG,
|
|
186
|
+
list: LOOKUP, "no-update": FLAG, "non-interactive": FLAG, "preserve-groups": FLAG, prompt: VALUE, chroot: REFUSE, role: VALUE,
|
|
187
|
+
stdin: FLAG, shell: FLAG, type: VALUE, "command-timeout": VALUE, "other-user": VALUE, user: VALUE, version: REFUSE, validate: LOOKUP,
|
|
188
|
+
},
|
|
189
|
+
assignments: true,
|
|
190
|
+
},
|
|
191
|
+
doas: { short: { n: FLAG, s: FLAG, u: VALUE, C: REFUSE, L: REFUSE }, long: {} },
|
|
192
|
+
flock: {
|
|
193
|
+
short: { s: FLAG, x: FLAG, e: FLAG, n: FLAG, u: FLAG, o: FLAG, F: FLAG, w: VALUE, E: VALUE, h: REFUSE, V: REFUSE },
|
|
194
|
+
long: {
|
|
195
|
+
shared: FLAG, exclusive: FLAG, unlock: FLAG, nonblock: FLAG, nonblocking: FLAG, nb: FLAG, timeout: VALUE, wait: VALUE,
|
|
196
|
+
"conflict-exit-code": VALUE, close: FLAG, "no-fork": FLAG, fcntl: FLAG, verbose: FLAG, help: REFUSE, version: REFUSE,
|
|
197
|
+
},
|
|
198
|
+
positionals: [/^[\s\S]+$/],
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
/** The wrappers the strict reading models. */
|
|
203
|
+
const STRICT_SPECS: Record<string, WrapperSpec> = { ...WRAPPER_SPECS, ...RUNNER_SPECS };
|
|
204
|
+
|
|
205
|
+
/** flock's shell-string form: `flock <file> -c|--command <string>`, matched exactly as flock does. */
|
|
206
|
+
const FLOCK_COMMAND = new Set(["-c", "--command"]);
|
|
207
|
+
|
|
134
208
|
/**
|
|
135
209
|
* Applet dispatchers. `busybox rm` is a different `rm` implementation whose
|
|
136
210
|
* flags are not GNU's, so its deletes are refused rather than rewritten.
|
|
137
211
|
*/
|
|
138
212
|
const APPLET_DISPATCHERS = new Set(["busybox", "toybox"]);
|
|
139
213
|
|
|
214
|
+
/** Delete verbs a runner (`xargs`, `find -exec`) may run. */
|
|
215
|
+
const DELETE_VERBS = new Set(["rm", "rmdir", "unlink", "shred"]);
|
|
216
|
+
|
|
140
217
|
/** Shell keywords that may precede the real command in a segment. */
|
|
141
218
|
const KEYWORDS = new Set(["!", "{", "}", "then", "do", "else", "elif", "if", "while", "until", "for", "case", "esac", "fi", "done", "select", "function"]);
|
|
142
219
|
|
|
@@ -173,6 +250,165 @@ function baseVerb(word: string): string {
|
|
|
173
250
|
return slash >= 0 ? word.slice(slash + 1) : word;
|
|
174
251
|
}
|
|
175
252
|
|
|
253
|
+
const ANSI_C_ESCAPES: Record<string, string> = {
|
|
254
|
+
a: "\x07", b: "\b", e: "\x1b", E: "\x1b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?",
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Decode the body of a bash `$'…'` string that starts at `from` (just past
|
|
259
|
+
* its opening quote): the text, and the index just past the closing quote.
|
|
260
|
+
*/
|
|
261
|
+
function readAnsiC(raw: string, from: number): { text: string; end: number } {
|
|
262
|
+
let text = "";
|
|
263
|
+
let i = from;
|
|
264
|
+
while (i < raw.length && raw[i] !== "'") {
|
|
265
|
+
if (raw[i] !== "\\" || i + 1 >= raw.length) {
|
|
266
|
+
text += raw[i++];
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
const c = raw[i + 1];
|
|
270
|
+
const rest = raw.slice(i + 1);
|
|
271
|
+
let m: RegExpMatchArray | null;
|
|
272
|
+
if (Object.hasOwn(ANSI_C_ESCAPES, c)) {
|
|
273
|
+
text += ANSI_C_ESCAPES[c];
|
|
274
|
+
i += 2;
|
|
275
|
+
} else if ((m = rest.match(/^[0-7]{1,3}/))) {
|
|
276
|
+
text += String.fromCharCode(parseInt(m[0], 8) & 0xff);
|
|
277
|
+
i += 1 + m[0].length;
|
|
278
|
+
} else if ((m = rest.match(/^x([0-9A-Fa-f]{1,2})/)) || (m = rest.match(/^u([0-9A-Fa-f]{1,4})/)) || (m = rest.match(/^U([0-9A-Fa-f]{1,8})/))) {
|
|
279
|
+
const point = parseInt(m[1], 16);
|
|
280
|
+
text += point <= 0x10ffff ? String.fromCodePoint(point) : "";
|
|
281
|
+
i += 1 + m[0].length;
|
|
282
|
+
} else if (c === "c" && i + 2 < raw.length) {
|
|
283
|
+
text += String.fromCharCode(raw.charCodeAt(i + 2) & 0x1f);
|
|
284
|
+
i += 3;
|
|
285
|
+
} else {
|
|
286
|
+
text += `\\${c}`;
|
|
287
|
+
i += 2;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return { text, end: Math.min(i + 1, raw.length) };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* The text a word stands for as a command name or wrapper argument: decodeWord,
|
|
295
|
+
* plus bash's `$'…'` (ANSI-C escapes) and `$"…"` (locale) quoting, so
|
|
296
|
+
* `$'rm'` and `$'\x72m'` are `rm`.
|
|
297
|
+
*/
|
|
298
|
+
export function decodeCommandWord(raw: string): string {
|
|
299
|
+
let out = "";
|
|
300
|
+
let i = 0;
|
|
301
|
+
while (i < raw.length) {
|
|
302
|
+
const ch = raw[i];
|
|
303
|
+
if (ch === "$" && raw[i + 1] === "'") {
|
|
304
|
+
const ansi = readAnsiC(raw, i + 2);
|
|
305
|
+
out += ansi.text;
|
|
306
|
+
i = ansi.end;
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (ch === "$" && raw[i + 1] === '"') {
|
|
310
|
+
i++;
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
if (ch === "\\") {
|
|
314
|
+
if (i + 1 < raw.length) out += raw[i + 1];
|
|
315
|
+
i += 2;
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (ch === "'") {
|
|
319
|
+
const end = raw.indexOf("'", i + 1);
|
|
320
|
+
if (end === -1) {
|
|
321
|
+
out += raw.slice(i + 1);
|
|
322
|
+
break;
|
|
323
|
+
}
|
|
324
|
+
out += raw.slice(i + 1, end);
|
|
325
|
+
i = end + 1;
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (ch === '"') {
|
|
329
|
+
i++;
|
|
330
|
+
while (i < raw.length && raw[i] !== '"') {
|
|
331
|
+
if (raw[i] === "\\" && i + 1 < raw.length) {
|
|
332
|
+
out += raw[i + 1];
|
|
333
|
+
i += 2;
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
out += raw[i];
|
|
337
|
+
i++;
|
|
338
|
+
}
|
|
339
|
+
i++;
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
out += ch;
|
|
343
|
+
i++;
|
|
344
|
+
}
|
|
345
|
+
return out;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Whether the shell can turn this word into other text, or into several words
|
|
350
|
+
* or none, so it cannot be read statically: any `$` (parameter, command and
|
|
351
|
+
* arithmetic expansion, and the `$'…'` and `$"…"` forms), a backtick, an
|
|
352
|
+
* unquoted glob (`*`, `?`, `[…]`), and a brace pattern or named tilde prefix
|
|
353
|
+
* (splitsOrMoves). A wrapper argument or command word like this is never
|
|
354
|
+
* skipped or trusted: the reading fails closed.
|
|
355
|
+
*/
|
|
356
|
+
export function expandsWord(raw: string): boolean {
|
|
357
|
+
if (splitsOrMoves(raw)) return true;
|
|
358
|
+
let quote: "'" | '"' | null = null;
|
|
359
|
+
for (let i = 0; i < raw.length; i++) {
|
|
360
|
+
const ch = raw[i];
|
|
361
|
+
if (quote === "'") {
|
|
362
|
+
if (ch === "'") quote = null;
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
if (ch === "\\") {
|
|
366
|
+
i++;
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
if (ch === "`" || ch === "$") return true;
|
|
370
|
+
if (ch === '"') {
|
|
371
|
+
quote = quote === null ? '"' : null;
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if (quote !== null) continue;
|
|
375
|
+
if (ch === "'") quote = "'";
|
|
376
|
+
else if (ch === "*" || ch === "?") return true;
|
|
377
|
+
else if (ch === "[" && unquotedAfter(raw, i + 1, "]")) return true;
|
|
378
|
+
}
|
|
379
|
+
return false;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Whether `target` occurs outside quotes in `raw` from `from` on. */
|
|
383
|
+
function unquotedAfter(raw: string, from: number, target: string): boolean {
|
|
384
|
+
let quote: "'" | '"' | null = null;
|
|
385
|
+
for (let i = from; i < raw.length; i++) {
|
|
386
|
+
const ch = raw[i];
|
|
387
|
+
if (quote !== "'" && ch === "\\") i++;
|
|
388
|
+
else if (quote === null && ch === target) return true;
|
|
389
|
+
else if (ch === "'" && quote !== '"') quote = quote === "'" ? null : "'";
|
|
390
|
+
else if (ch === '"' && quote !== "'") quote = quote === '"' ? null : '"';
|
|
391
|
+
}
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Whether a word the shell expands at run time could become the name of a
|
|
397
|
+
* delete: one of its brace expansions (expandBraces), or a name inside one
|
|
398
|
+
* (`$(which rm)`, `${RM:-rm}`, `$'\x72m'`), is a delete verb. Too many
|
|
399
|
+
* alternatives count.
|
|
400
|
+
*/
|
|
401
|
+
function mayNameDelete(raw: string): boolean {
|
|
402
|
+
if (!expandsWord(raw)) return false;
|
|
403
|
+
const words = expandBraces(raw);
|
|
404
|
+
return words === null || words.some((word) => decodeCommandWord(word).split(/[^A-Za-z0-9_]+/).some((token) => DELETE_VERBS.has(token)));
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** The name of the command a word runs: `/bin/rm`, `"rm"` and `$'rm'` are `rm`. */
|
|
408
|
+
function commandName(raw: string): string {
|
|
409
|
+
return baseVerb(decodeCommandWord(raw));
|
|
410
|
+
}
|
|
411
|
+
|
|
176
412
|
export interface Word {
|
|
177
413
|
/** Raw source text of the word, including its quotes and escapes. */
|
|
178
414
|
text: string;
|
|
@@ -186,6 +422,8 @@ interface Segment {
|
|
|
186
422
|
words: Word[];
|
|
187
423
|
/** Indices into `words` that are redirection targets, not operands. */
|
|
188
424
|
redirects: Set<number>;
|
|
425
|
+
/** Deep lexing only: bodies of the here-documents whose operator is in this segment. */
|
|
426
|
+
heredocs?: string[];
|
|
189
427
|
}
|
|
190
428
|
|
|
191
429
|
interface LexResult {
|
|
@@ -196,6 +434,151 @@ interface LexResult {
|
|
|
196
434
|
substitutions: string[];
|
|
197
435
|
}
|
|
198
436
|
|
|
437
|
+
export interface LexOptions {
|
|
438
|
+
/**
|
|
439
|
+
* The trash guard's reading. Without it the lexer keeps the reading
|
|
440
|
+
* workspace-repos-guard was written against: substitutions only where they
|
|
441
|
+
* are unquoted, and a here-document operator skips the rest of its line.
|
|
442
|
+
* With it, `substitutions` also holds every `$( )` and backtick inside
|
|
443
|
+
* double quotes and in a here-document body whose delimiter is unquoted,
|
|
444
|
+
* backtick bodies are unescaped (so a nested backtick is a substitution
|
|
445
|
+
* again), the rest of a here-document operator's line is lexed as the
|
|
446
|
+
* command it is, the bodies are skipped from the next unquoted newline,
|
|
447
|
+
* and each body is recorded on the segment holding its operator.
|
|
448
|
+
*/
|
|
449
|
+
deep?: boolean;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** The lexer options scanCommand reads with. */
|
|
453
|
+
const DEEP: LexOptions = { deep: true };
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* A backtick body as the shell runs it: inside backticks `\$`, `` \` `` and
|
|
457
|
+
* `\\` lose their backslash, and inside double quotes so does `\"`.
|
|
458
|
+
*/
|
|
459
|
+
function unescapeBacktick(body: string, inDouble: boolean): string {
|
|
460
|
+
return body.replace(/\\([$`\\"])/g, (match, ch: string) => (ch === '"' && !inDouble ? match : ch));
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* The bodies of the `$( )` and backtick substitutions inside the double-quoted
|
|
465
|
+
* string from `open` to `close` (its quotes), or null when one cannot be
|
|
466
|
+
* followed. Single quotes are literal there, so they hide nothing.
|
|
467
|
+
*/
|
|
468
|
+
function doubleQuotedSubstitutions(text: string, open: number, close: number): string[] | null {
|
|
469
|
+
const found: string[] = [];
|
|
470
|
+
let j = open + 1;
|
|
471
|
+
while (j < close - 1) {
|
|
472
|
+
const c = text[j];
|
|
473
|
+
if (c === "\\") {
|
|
474
|
+
j += 2;
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
if (c === "`") {
|
|
478
|
+
const e = scanBacktickAt(text, j);
|
|
479
|
+
if (e < 0) return null;
|
|
480
|
+
found.push(unescapeBacktick(text.slice(j + 1, e - 1), true));
|
|
481
|
+
j = e;
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
if (c === "$" && text[j + 1] === "(") {
|
|
485
|
+
const e = scanParenAt(text, j + 1);
|
|
486
|
+
if (e < 0) return null;
|
|
487
|
+
found.push(text.slice(j + 2, e - 1));
|
|
488
|
+
j = e;
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
j++;
|
|
492
|
+
}
|
|
493
|
+
return found;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* The bodies of the substitutions in a here-document body whose delimiter is
|
|
498
|
+
* unquoted: bash expands `$( )` and backticks there, and quotes are literal.
|
|
499
|
+
* Null when one cannot be followed.
|
|
500
|
+
*/
|
|
501
|
+
function heredocBodySubstitutions(body: string): string[] | null {
|
|
502
|
+
const found: string[] = [];
|
|
503
|
+
let j = 0;
|
|
504
|
+
while (j < body.length) {
|
|
505
|
+
const c = body[j];
|
|
506
|
+
if (c === "\\") {
|
|
507
|
+
j += 2;
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
if (c === "`") {
|
|
511
|
+
const e = scanBacktickAt(body, j);
|
|
512
|
+
if (e < 0) return null;
|
|
513
|
+
found.push(unescapeBacktick(body.slice(j + 1, e - 1), false));
|
|
514
|
+
j = e;
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (c === "$" && body[j + 1] === "(") {
|
|
518
|
+
const e = scanParenAt(body, j + 1);
|
|
519
|
+
if (e < 0) return null;
|
|
520
|
+
found.push(body.slice(j + 2, e - 1));
|
|
521
|
+
j = e;
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
j++;
|
|
525
|
+
}
|
|
526
|
+
return found;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** A here-document operator waiting for its body (deep lexing). */
|
|
530
|
+
interface PendingHeredoc {
|
|
531
|
+
delimiter: string;
|
|
532
|
+
quoted: boolean;
|
|
533
|
+
/** `<<-`: leading tabs are stripped from body lines and the terminator. */
|
|
534
|
+
stripTabs: boolean;
|
|
535
|
+
/** The heredoc list of the segment the operator is in. */
|
|
536
|
+
owner: string[];
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Read the bodies of `pending` here-documents, which start on the line after
|
|
541
|
+
* the newline at `newline`, in order, as bash reads them: each ends at the
|
|
542
|
+
* first line equal to its delimiter (after its leading tabs, for `<<-`), or
|
|
543
|
+
* at the end of the text when there is none (bash warns and runs it). A line
|
|
544
|
+
* with a trailing carriage return also ends it, which bash does not do: an
|
|
545
|
+
* earlier end only puts more text in front of the command reading, never
|
|
546
|
+
* less. Each body is recorded on its owner, and an unquoted body's
|
|
547
|
+
* substitutions are added to `substitutions`. Returns the index of the
|
|
548
|
+
* newline that ends the last terminator line, or the end of the text; -1
|
|
549
|
+
* when a substitution in a body cannot be followed.
|
|
550
|
+
*/
|
|
551
|
+
function readHeredocBodies(text: string, newline: number, pending: PendingHeredoc[], substitutions: string[]): number {
|
|
552
|
+
let lineStart = newline + 1;
|
|
553
|
+
for (const heredoc of pending) {
|
|
554
|
+
const bodyStart = Math.min(lineStart, text.length);
|
|
555
|
+
for (;;) {
|
|
556
|
+
if (lineStart > text.length) {
|
|
557
|
+
lineStart = text.length + 1;
|
|
558
|
+
break;
|
|
559
|
+
}
|
|
560
|
+
const lineEnd = text.indexOf("\n", lineStart);
|
|
561
|
+
const stop = lineEnd === -1 ? text.length : lineEnd;
|
|
562
|
+
let line = text.slice(lineStart, stop).replace(/\r$/, "");
|
|
563
|
+
if (heredoc.stripTabs) line = line.replace(/^\t+/, "");
|
|
564
|
+
if (line === heredoc.delimiter) break;
|
|
565
|
+
lineStart = stop + 1;
|
|
566
|
+
}
|
|
567
|
+
const body = text.slice(bodyStart, Math.min(lineStart, text.length));
|
|
568
|
+
heredoc.owner.push(body);
|
|
569
|
+
if (!heredoc.quoted) {
|
|
570
|
+
const found = heredocBodySubstitutions(body);
|
|
571
|
+
if (!found) return -1;
|
|
572
|
+
substitutions.push(...found);
|
|
573
|
+
}
|
|
574
|
+
if (lineStart <= text.length) {
|
|
575
|
+
const lineEnd = text.indexOf("\n", lineStart);
|
|
576
|
+
lineStart = (lineEnd === -1 ? text.length : lineEnd) + 1;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
return Math.min(lineStart - 1, text.length);
|
|
580
|
+
}
|
|
581
|
+
|
|
199
582
|
/** A reason this hook refuses a command. */
|
|
200
583
|
interface Refusal {
|
|
201
584
|
reason: string;
|
|
@@ -205,6 +588,12 @@ interface Refusal {
|
|
|
205
588
|
interface RmHit {
|
|
206
589
|
word: Word;
|
|
207
590
|
operands: Word[];
|
|
591
|
+
/**
|
|
592
|
+
* Handed off only because the cwd is under a protected root: every operand
|
|
593
|
+
* names a literal path outside the roots, which workspace-repos-guard does
|
|
594
|
+
* not own.
|
|
595
|
+
*/
|
|
596
|
+
cwdOnly?: boolean;
|
|
208
597
|
}
|
|
209
598
|
|
|
210
599
|
export interface ScanResult {
|
|
@@ -427,11 +816,14 @@ export function scanParenAt(text: string, from: number): number {
|
|
|
427
816
|
* a rewrite can replace exactly the verb token and leave every other byte —
|
|
428
817
|
* flags, quoting, globs, variables, substitutions — untouched.
|
|
429
818
|
*/
|
|
430
|
-
export function lexCommand(command: string): LexResult {
|
|
819
|
+
export function lexCommand(command: string, options: LexOptions = {}): LexResult {
|
|
820
|
+
const deep = options.deep === true;
|
|
431
821
|
const segments: Segment[] = [];
|
|
432
822
|
const substitutions: string[] = [];
|
|
433
823
|
let words: Word[] = [];
|
|
434
824
|
let redirects = new Set<number>();
|
|
825
|
+
let heredocs: string[] = [];
|
|
826
|
+
let pendingHeredocs: PendingHeredoc[] = [];
|
|
435
827
|
let wordStart = -1;
|
|
436
828
|
let pendingRedirect = false;
|
|
437
829
|
let trustworthy = true;
|
|
@@ -450,9 +842,10 @@ export function lexCommand(command: string): LexResult {
|
|
|
450
842
|
|
|
451
843
|
const closeSegment = (end: number): void => {
|
|
452
844
|
closeWord(end);
|
|
453
|
-
if (words.length > 0) segments.push({ words, redirects });
|
|
845
|
+
if (words.length > 0) segments.push(deep ? { words, redirects, heredocs } : { words, redirects });
|
|
454
846
|
words = [];
|
|
455
847
|
redirects = new Set<number>();
|
|
848
|
+
if (deep) heredocs = [];
|
|
456
849
|
pendingRedirect = false;
|
|
457
850
|
};
|
|
458
851
|
|
|
@@ -471,6 +864,16 @@ export function lexCommand(command: string): LexResult {
|
|
|
471
864
|
}
|
|
472
865
|
if (ch === "\n") {
|
|
473
866
|
closeSegment(i);
|
|
867
|
+
if (pendingHeredocs.length > 0) {
|
|
868
|
+
// Deep lexing: the bodies start on the line after the operator's line.
|
|
869
|
+
const end = readHeredocBodies(command, i, pendingHeredocs, substitutions);
|
|
870
|
+
pendingHeredocs = [];
|
|
871
|
+
if (end < 0) {
|
|
872
|
+
trustworthy = false;
|
|
873
|
+
i = n;
|
|
874
|
+
} else i = end;
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
474
877
|
i++;
|
|
475
878
|
continue;
|
|
476
879
|
}
|
|
@@ -489,6 +892,13 @@ export function lexCommand(command: string): LexResult {
|
|
|
489
892
|
i += command[i + 1] === "|" ? 2 : 1;
|
|
490
893
|
continue;
|
|
491
894
|
}
|
|
895
|
+
if (deep && ch === "(" && wordStart >= 0 && "?*+@!".includes(command[i - 1])) {
|
|
896
|
+
// An extended glob (`@(a|b)`, `!(x)`) under `shopt -s extglob`, or a
|
|
897
|
+
// subshell after a word: the reading is ambiguous, so it is not trusted.
|
|
898
|
+
trustworthy = false;
|
|
899
|
+
i = n;
|
|
900
|
+
continue;
|
|
901
|
+
}
|
|
492
902
|
if (ch === "(" || ch === ")") {
|
|
493
903
|
closeSegment(i);
|
|
494
904
|
i++;
|
|
@@ -503,6 +913,20 @@ export function lexCommand(command: string): LexResult {
|
|
|
503
913
|
i = n;
|
|
504
914
|
continue;
|
|
505
915
|
}
|
|
916
|
+
if (deep) {
|
|
917
|
+
// The same delimiter grammar, but the rest of the line is still the
|
|
918
|
+
// command (`cat <<EOF && rm x`); the body is read at the next newline.
|
|
919
|
+
const after = i + 2 + marker[0].length;
|
|
920
|
+
if (after < n && !/[\s;&|()<>]/.test(command[after])) {
|
|
921
|
+
trustworthy = false;
|
|
922
|
+
i = n;
|
|
923
|
+
continue;
|
|
924
|
+
}
|
|
925
|
+
closeWord(i);
|
|
926
|
+
pendingHeredocs.push({ delimiter: marker[2], quoted: marker[1] !== "", stripTabs: marker[0].startsWith("-"), owner: heredocs });
|
|
927
|
+
i = after;
|
|
928
|
+
continue;
|
|
929
|
+
}
|
|
506
930
|
const bodyStart = command.indexOf("\n", i + 2 + marker[0].length);
|
|
507
931
|
if (bodyStart === -1) {
|
|
508
932
|
trustworthy = false;
|
|
@@ -542,10 +966,14 @@ export function lexCommand(command: string): LexResult {
|
|
|
542
966
|
if (ch === '"') {
|
|
543
967
|
if (wordStart < 0) wordStart = i;
|
|
544
968
|
const e = scanDouble(i);
|
|
545
|
-
|
|
969
|
+
const quoted = e < 0 || !deep ? [] : doubleQuotedSubstitutions(command, i, e);
|
|
970
|
+
if (e < 0 || !quoted) {
|
|
546
971
|
trustworthy = false;
|
|
547
972
|
i = n;
|
|
548
|
-
} else
|
|
973
|
+
} else {
|
|
974
|
+
substitutions.push(...quoted);
|
|
975
|
+
i = e;
|
|
976
|
+
}
|
|
549
977
|
continue;
|
|
550
978
|
}
|
|
551
979
|
if (ch === "`") {
|
|
@@ -555,7 +983,8 @@ export function lexCommand(command: string): LexResult {
|
|
|
555
983
|
trustworthy = false;
|
|
556
984
|
i = n;
|
|
557
985
|
} else {
|
|
558
|
-
|
|
986
|
+
const body = command.slice(i + 1, e - 1);
|
|
987
|
+
substitutions.push(deep ? unescapeBacktick(body, false) : body);
|
|
559
988
|
i = e;
|
|
560
989
|
}
|
|
561
990
|
continue;
|
|
@@ -586,6 +1015,9 @@ export function lexCommand(command: string): LexResult {
|
|
|
586
1015
|
}
|
|
587
1016
|
|
|
588
1017
|
closeSegment(n);
|
|
1018
|
+
// A here-document operator with no line after it has an empty body (bash
|
|
1019
|
+
// warns and runs the command).
|
|
1020
|
+
if (pendingHeredocs.length > 0 && readHeredocBodies(command, n, pendingHeredocs, substitutions) < 0) trustworthy = false;
|
|
589
1021
|
return { segments, trustworthy, substitutions };
|
|
590
1022
|
}
|
|
591
1023
|
|
|
@@ -826,14 +1258,10 @@ export function protectedTargetReason(target: string, home: string): string | nu
|
|
|
826
1258
|
* command whose effective cwd sits under one (a relative operand there means
|
|
827
1259
|
* a path inside the guarded roots).
|
|
828
1260
|
*/
|
|
829
|
-
function isHandoff(
|
|
1261
|
+
function isHandoff(targets: Array<string | null>, cwd: string, home: string): boolean {
|
|
830
1262
|
const roots = handoffRoots(home);
|
|
831
1263
|
if (roots.some((root) => isUnder(cwd, root))) return true;
|
|
832
|
-
|
|
833
|
-
const target = resolveLiteralTarget(operand.text, cwd, home);
|
|
834
|
-
if (target && roots.some((root) => isUnder(target, root))) return true;
|
|
835
|
-
}
|
|
836
|
-
return false;
|
|
1264
|
+
return targets.some((target) => target !== null && roots.some((root) => isUnder(target, root)));
|
|
837
1265
|
}
|
|
838
1266
|
|
|
839
1267
|
/* ------------------------------------------------------------------ */
|
|
@@ -845,144 +1273,320 @@ interface ScanContext {
|
|
|
845
1273
|
home: string;
|
|
846
1274
|
/** Recursion depth for substitution bodies. */
|
|
847
1275
|
depth: number;
|
|
1276
|
+
/** Whether any here-document body in the command mentions a delete verb. */
|
|
1277
|
+
bodiesMention: boolean;
|
|
848
1278
|
}
|
|
849
1279
|
|
|
850
1280
|
/**
|
|
851
|
-
*
|
|
852
|
-
*
|
|
853
|
-
*
|
|
854
|
-
* Only command position counts, and only `rm`'s own grammar is rewritten.
|
|
1281
|
+
* What a segment says about deletes whatever word of it runs, computed once:
|
|
1282
|
+
* the fail-closed scan reads every word of a segment as the command, and these
|
|
1283
|
+
* checks look at the whole segment, so they must not be recomputed per word.
|
|
855
1284
|
*/
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
1285
|
+
interface SegmentFacts {
|
|
1286
|
+
/** find: a -delete primary. */
|
|
1287
|
+
findDelete: boolean;
|
|
1288
|
+
/** find: an -exec, -execdir, -ok or -okdir primary followed by a delete verb. */
|
|
1289
|
+
findExecDelete: boolean;
|
|
1290
|
+
/** xargs: any word names a delete verb. */
|
|
1291
|
+
namesDelete: boolean;
|
|
1292
|
+
/** Index of the last exact `-c`/`--command` word (flock's shell-string form), or -1. */
|
|
1293
|
+
lastFlockCommand: number;
|
|
1294
|
+
/** The segment text, its env split-string reading and its own here-document bodies mention a delete verb. */
|
|
1295
|
+
textMention: boolean;
|
|
1296
|
+
envMention: boolean;
|
|
1297
|
+
bodiesMention: boolean;
|
|
1298
|
+
}
|
|
859
1299
|
|
|
860
|
-
|
|
861
|
-
result.trustworthy = lexed.trustworthy;
|
|
1300
|
+
const SEGMENT_FACTS = new WeakMap<Segment, SegmentFacts>();
|
|
862
1301
|
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
1302
|
+
function segmentFacts(segment: Segment): SegmentFacts {
|
|
1303
|
+
const cached = SEGMENT_FACTS.get(segment);
|
|
1304
|
+
if (cached) return cached;
|
|
1305
|
+
const words = segment.words.map((word) => decodeCommandWord(word.text));
|
|
1306
|
+
const execIndex = words.findIndex((word) => word === "-exec" || word === "-execdir" || word === "-ok" || word === "-okdir");
|
|
1307
|
+
let lastFlockCommand = -1;
|
|
1308
|
+
segment.words.forEach((word, at) => {
|
|
1309
|
+
if (FLOCK_COMMAND.has(decodeWord(word.text))) lastFlockCommand = at;
|
|
1310
|
+
});
|
|
1311
|
+
const facts: SegmentFacts = {
|
|
1312
|
+
findDelete: words.includes("-delete"),
|
|
1313
|
+
findExecDelete: execIndex >= 0 && words.slice(execIndex).some((word) => DELETE_VERBS.has(baseVerb(word))),
|
|
1314
|
+
namesDelete: words.some((word) => DELETE_VERBS.has(baseVerb(word))),
|
|
1315
|
+
lastFlockCommand,
|
|
1316
|
+
textMention: mentionsDeleteVerb(segmentText(segment)),
|
|
1317
|
+
envMention: mentionsDeleteVerb(envSplitCommandText(segment.words.map((word) => decodeWord(word.text)))),
|
|
1318
|
+
bodiesMention: mentionsDeleteVerb((segment.heredocs ?? []).join("\n")),
|
|
1319
|
+
};
|
|
1320
|
+
SEGMENT_FACTS.set(segment, facts);
|
|
1321
|
+
return facts;
|
|
1322
|
+
}
|
|
866
1323
|
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
const index = commandWordIndex(segment);
|
|
870
|
-
if (index < 0) continue;
|
|
871
|
-
const verb = baseVerb(decodeWord(segment.words[index].text));
|
|
872
|
-
|
|
873
|
-
if (verb === "cd") {
|
|
874
|
-
const operand = segment.words[index + 1];
|
|
875
|
-
if (operand) {
|
|
876
|
-
const target = resolveLiteralTarget(operand.text, cwd, ctx.home);
|
|
877
|
-
if (target) cwd = target;
|
|
878
|
-
else cwd = ctx.cwd;
|
|
879
|
-
}
|
|
880
|
-
continue;
|
|
881
|
-
}
|
|
1324
|
+
/** Shells that run a script read from standard input. */
|
|
1325
|
+
const STDIN_SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh"]);
|
|
882
1326
|
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
1327
|
+
/**
|
|
1328
|
+
* Whether the shell whose word is at `index` reads its script from standard
|
|
1329
|
+
* input: `-s` is given, or no `-c` option and no script operand. Its stdin may
|
|
1330
|
+
* be any here-document in the command (`cat <<'EOF' | bash`).
|
|
1331
|
+
*/
|
|
1332
|
+
function shellReadsStdin(segment: Segment, index: number): boolean {
|
|
1333
|
+
if (!STDIN_SHELLS.has(commandName(segment.words[index].text))) return false;
|
|
1334
|
+
for (let at = index + 1; at < segment.words.length; at++) {
|
|
1335
|
+
if (segment.redirects.has(at)) continue;
|
|
1336
|
+
const word = decodeWord(segment.words[at].text);
|
|
1337
|
+
if (word === "--") return at + 1 >= segment.words.length;
|
|
1338
|
+
if (/^-[A-Za-z]*s/.test(word)) return true;
|
|
1339
|
+
if (/^-[A-Za-z]*c/.test(word)) return false;
|
|
1340
|
+
if (word === "-o" || word === "+o" || word === "-O" || word === "+O") {
|
|
1341
|
+
at++;
|
|
886
1342
|
continue;
|
|
887
1343
|
}
|
|
1344
|
+
if (!/^[-+]/.test(word) || word === "-") return word === "-";
|
|
1345
|
+
}
|
|
1346
|
+
return true;
|
|
1347
|
+
}
|
|
888
1348
|
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
const hit: RmHit = { word: segment.words[index], operands };
|
|
896
|
-
if (isHandoff(hit.operands, cwd, ctx.home)) {
|
|
897
|
-
result.handoffHits.push(hit);
|
|
898
|
-
continue;
|
|
899
|
-
}
|
|
900
|
-
result.rmHits.push(hit);
|
|
901
|
-
for (const operand of hit.operands) {
|
|
902
|
-
// An unresolvable operand (variable, glob, substitution) is not
|
|
903
|
-
// classified here: the rewrite still applies, and `trash guard`
|
|
904
|
-
// classifies the paths the shell actually expands to.
|
|
905
|
-
const target = resolveLiteralTarget(operand.text, cwd, ctx.home);
|
|
906
|
-
if (!target) continue;
|
|
907
|
-
const reason = protectedTargetReason(target, ctx.home);
|
|
908
|
-
if (reason) {
|
|
909
|
-
result.protectedHits.push({ reason });
|
|
910
|
-
break;
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
continue;
|
|
914
|
-
}
|
|
1349
|
+
/** What the command at one word of a segment does, as far as this hook is concerned. */
|
|
1350
|
+
type Reading =
|
|
1351
|
+
| { kind: "none" }
|
|
1352
|
+
| { kind: "cd"; cwd: string }
|
|
1353
|
+
| { kind: "rm"; hit: RmHit; handoff: boolean; protectedReason: string | null }
|
|
1354
|
+
| { kind: "refuse"; reason: string };
|
|
915
1355
|
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
1356
|
+
const deletes = (reading: Reading): boolean => reading.kind === "rm" || reading.kind === "refuse";
|
|
1357
|
+
|
|
1358
|
+
const UNREADABLE_WRAPPER_REASON =
|
|
1359
|
+
"This command's command word or wrapper arguments cannot be read before it runs (an expansion such as a variable, substitution, brace or glob pattern, an unknown or unsupported option, a working directory or a non-decimal duration), so this hook cannot tell which word runs, and one of its words could run a delete. Run the delete as a plain `rm -- <path>` command, which is redirected into trash.";
|
|
1360
|
+
|
|
1361
|
+
const BRACE_LIMIT_REASON =
|
|
1362
|
+
"This delete's brace pattern names more paths than this hook will check. Run the delete on explicit paths with `rm -- <path> …`, which is redirected into trash.";
|
|
1363
|
+
|
|
1364
|
+
const BRACE_ROOT_REASON =
|
|
1365
|
+
"This delete's brace pattern expands to a path under a protected repository checkout. Deletes there are refused; run them through the owning workflow, and write any other delete out as plain paths.";
|
|
1366
|
+
|
|
1367
|
+
const TWO_READINGS_REASON =
|
|
1368
|
+
"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.";
|
|
1369
|
+
|
|
1370
|
+
/**
|
|
1371
|
+
* Index of the command word in `segment` by the strict wrapper model
|
|
1372
|
+
* (unwrapCommand with STRICT_SPECS): -1 when the segment runs no command,
|
|
1373
|
+
* null when a wrapper's arguments cannot be read. Redirections are not words
|
|
1374
|
+
* of the command.
|
|
1375
|
+
*/
|
|
1376
|
+
export function strictCommandIndex(segment: Segment): number | null {
|
|
1377
|
+
const kept: number[] = [];
|
|
1378
|
+
segment.words.forEach((_, at) => {
|
|
1379
|
+
if (!segment.redirects.has(at)) kept.push(at);
|
|
1380
|
+
});
|
|
1381
|
+
const words: ShellWord[] = kept.map((at) => {
|
|
1382
|
+
const raw = segment.words[at].text;
|
|
1383
|
+
return { text: decodeCommandWord(raw), opaque: expandsWord(raw) };
|
|
1384
|
+
});
|
|
1385
|
+
const found = unwrapCommand(words, STRICT_SPECS);
|
|
1386
|
+
if (found === null) return null;
|
|
1387
|
+
return found.index < 0 ? -1 : kept[found.index];
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
/** What the command whose word is at `index` of `segment` does. */
|
|
1391
|
+
function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanContext): Reading {
|
|
1392
|
+
const verb = commandName(segment.words[index].text);
|
|
1393
|
+
|
|
1394
|
+
if (verb === "cd") {
|
|
1395
|
+
const operand = segment.words[index + 1];
|
|
1396
|
+
if (!operand) return { kind: "none" };
|
|
1397
|
+
return { kind: "cd", cwd: resolveLiteralTarget(operand.text, cwd, ctx.home) ?? ctx.cwd };
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
if (Object.hasOwn(REFUSED_VERBS, verb)) return { kind: "refuse", reason: REFUSED_VERBS[verb] };
|
|
1401
|
+
|
|
1402
|
+
if (verb === "rm") {
|
|
1403
|
+
const operands = rmOperands(segment, index);
|
|
1404
|
+
// `rm` with no operand deletes nothing (GNU `rm` exits "missing
|
|
1405
|
+
// operand"), so `rm --help` and a bare `rm -rf` are not interceptable
|
|
1406
|
+
// deletes and are left exactly as written.
|
|
1407
|
+
if (operands.length === 0) return { kind: "none" };
|
|
1408
|
+
const hit: RmHit = { word: segment.words[index], operands };
|
|
1409
|
+
const roots = handoffRoots(ctx.home);
|
|
1410
|
+
const underRoot = (target: string | null): boolean => target !== null && roots.some((root) => isUnder(target, root));
|
|
1411
|
+
// Each operand's literal path, or null when it cannot be resolved before
|
|
1412
|
+
// expansion (a variable, a glob, a substitution): those are not classified
|
|
1413
|
+
// here; the rewrite still applies, and `trash guard` classifies the paths
|
|
1414
|
+
// the shell actually expands to. A brace pattern is expanded here too,
|
|
1415
|
+
// because bash does it before rm runs: its paths are checked against the
|
|
1416
|
+
// protected class, and one under a protected root that the literal word
|
|
1417
|
+
// does not show is refused rather than left to a hook that reads words.
|
|
1418
|
+
const targets: Array<string | null> = [];
|
|
1419
|
+
const expanded: string[] = [];
|
|
1420
|
+
for (const operand of operands) {
|
|
1421
|
+
const literal = resolveLiteralTarget(operand.text, cwd, ctx.home);
|
|
1422
|
+
targets.push(literal);
|
|
1423
|
+
if (!operand.text.includes("{")) continue;
|
|
1424
|
+
const words = expandBraces(operand.text);
|
|
1425
|
+
if (words === null) return { kind: "refuse", reason: BRACE_LIMIT_REASON };
|
|
1426
|
+
for (const word of words) {
|
|
1427
|
+
const target = resolveLiteralTarget(word, cwd, ctx.home);
|
|
1428
|
+
if (target === null) continue;
|
|
1429
|
+
if (underRoot(target) && !underRoot(literal)) return { kind: "refuse", reason: BRACE_ROOT_REASON };
|
|
1430
|
+
expanded.push(target);
|
|
923
1431
|
}
|
|
924
|
-
continue;
|
|
925
1432
|
}
|
|
1433
|
+
if (isHandoff(targets, cwd, ctx.home)) {
|
|
1434
|
+
hit.cwdOnly = targets.every((target) => target !== null && !underRoot(target));
|
|
1435
|
+
return { kind: "rm", hit, handoff: true, protectedReason: null };
|
|
1436
|
+
}
|
|
1437
|
+
for (const target of [...targets, ...expanded]) {
|
|
1438
|
+
if (!target) continue;
|
|
1439
|
+
const reason = protectedTargetReason(target, ctx.home);
|
|
1440
|
+
if (reason) return { kind: "rm", hit, handoff: false, protectedReason: reason };
|
|
1441
|
+
}
|
|
1442
|
+
return { kind: "rm", hit, handoff: false, protectedReason: null };
|
|
1443
|
+
}
|
|
926
1444
|
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
? "`git rm` is refused: without `--cached` it deletes the working-tree file, and its semantics are not `rm`'s. Use `rm -- <path>` (intercepted and redirected into trash) to remove the file, or `git rm --cached -- <path>` to unstage it without deleting."
|
|
936
|
-
: "`git clean` deletes untracked files irrecoverably and is refused. Remove them explicitly with `rm -- <path>` (intercepted and redirected into trash), or preview with `git clean -n`.",
|
|
937
|
-
});
|
|
938
|
-
}
|
|
939
|
-
}
|
|
940
|
-
continue;
|
|
1445
|
+
if (APPLET_DISPATCHERS.has(verb)) {
|
|
1446
|
+
const appletIndex = segment.words.findIndex((word, at) => at > index && !decodeWord(word.text).startsWith("-"));
|
|
1447
|
+
const applet = appletIndex >= 0 ? commandName(segment.words[appletIndex].text) : "";
|
|
1448
|
+
if (applet === "rm" || Object.hasOwn(REFUSED_VERBS, applet)) {
|
|
1449
|
+
return {
|
|
1450
|
+
kind: "refuse",
|
|
1451
|
+
reason: `\`${verb} ${applet}\` runs the ${verb} applet, whose own \`rm\` is not GNU \`rm\` and cannot be rewritten in place. Run the delete as \`rm -- <path>\`, which is redirected into trash.`,
|
|
1452
|
+
};
|
|
941
1453
|
}
|
|
1454
|
+
return { kind: "none" };
|
|
1455
|
+
}
|
|
942
1456
|
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1457
|
+
if (verb === "git") {
|
|
1458
|
+
const sub = gitSubcommand(segment, index);
|
|
1459
|
+
if (sub === "rm" || sub === "clean") {
|
|
1460
|
+
const dryOrIndexOnly = sub === "rm" ? gitRmIsNonDeleting(segment, index) : gitHasDryRun(segment, index);
|
|
1461
|
+
if (!dryOrIndexOnly) {
|
|
1462
|
+
return {
|
|
1463
|
+
kind: "refuse",
|
|
948
1464
|
reason:
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
const execIndex = words.findIndex((word) => word === "-exec" || word === "-execdir" || word === "-ok");
|
|
954
|
-
if (execIndex >= 0 && words.slice(execIndex).some((word) => word === "rm" || word === "rmdir" || word === "unlink" || word === "shred")) {
|
|
955
|
-
result.refusals.push({
|
|
956
|
-
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>`.",
|
|
957
|
-
});
|
|
958
|
-
continue;
|
|
1465
|
+
sub === "rm"
|
|
1466
|
+
? "`git rm` is refused: without `--cached` it deletes the working-tree file, and its semantics are not `rm`'s. Use `rm -- <path>` (intercepted and redirected into trash) to remove the file, or `git rm --cached -- <path>` to unstage it without deleting."
|
|
1467
|
+
: "`git clean` deletes untracked files irrecoverably and is refused. Remove them explicitly with `rm -- <path>` (intercepted and redirected into trash), or preview with `git clean -n`.",
|
|
1468
|
+
};
|
|
959
1469
|
}
|
|
960
|
-
continue;
|
|
961
1470
|
}
|
|
1471
|
+
return { kind: "none" };
|
|
1472
|
+
}
|
|
962
1473
|
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
1474
|
+
const facts = segmentFacts(segment);
|
|
1475
|
+
if (verb === "find") {
|
|
1476
|
+
if (facts.findDelete) {
|
|
1477
|
+
return {
|
|
1478
|
+
kind: "refuse",
|
|
1479
|
+
reason:
|
|
1480
|
+
"`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.",
|
|
1481
|
+
};
|
|
1482
|
+
}
|
|
1483
|
+
if (facts.findExecDelete) {
|
|
1484
|
+
return {
|
|
1485
|
+
kind: "refuse",
|
|
1486
|
+
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>`.",
|
|
1487
|
+
};
|
|
968
1488
|
}
|
|
1489
|
+
return { kind: "none" };
|
|
1490
|
+
}
|
|
969
1491
|
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
1492
|
+
if (verb === "xargs" && facts.namesDelete) {
|
|
1493
|
+
return {
|
|
1494
|
+
kind: "refuse",
|
|
1495
|
+
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.",
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
// `flock <file> -c <string>` runs the string through a shell: as the shared
|
|
1500
|
+
// reading sees it (`flock`) and as the strict one does (`-c`, the word after
|
|
1501
|
+
// the lock file).
|
|
1502
|
+
const flockString = verb === "flock" ? facts.lastFlockCommand > index : FLOCK_COMMAND.has(verb);
|
|
1503
|
+
if (OPAQUE_COMMANDS.has(verb) || flockString) {
|
|
1504
|
+
// A shell reads a here-document on its own line as its script, and one
|
|
1505
|
+
// that reads standard input may be fed any here-document in the command.
|
|
1506
|
+
const bodiesMention = shellReadsStdin(segment, index) ? ctx.bodiesMention : facts.bodiesMention;
|
|
1507
|
+
if ((verb === "env" ? facts.envMention : facts.textMention) || bodiesMention) {
|
|
1508
|
+
return {
|
|
1509
|
+
kind: "refuse",
|
|
1510
|
+
reason: `\`${flockString ? "flock" : verb}\` runs a command string this hook cannot rewrite in place. Run the delete directly as \`rm -- <path>\` (intercepted and redirected into trash), or as a script that uses \`trash guard\` itself.`,
|
|
1511
|
+
};
|
|
976
1512
|
}
|
|
977
1513
|
}
|
|
1514
|
+
return { kind: "none" };
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
/**
|
|
1518
|
+
* Classify a command string: which `rm` verbs are ours to rewrite, which are
|
|
1519
|
+
* handed to the guarded-roots hook, and why anything else is refused.
|
|
1520
|
+
*
|
|
1521
|
+
* Only command position counts, and only `rm`'s own grammar is rewritten.
|
|
1522
|
+
* Each segment's command is read by the shared walk (commandWordIndex) and by
|
|
1523
|
+
* the strict wrapper model (strictCommandIndex). The shared reading is applied
|
|
1524
|
+
* as it always was; a delete that only the strict reading finds is applied
|
|
1525
|
+
* too, and two different deletes are refused. When the strict model cannot
|
|
1526
|
+
* read the wrapper arguments, a segment any of whose words could run a delete
|
|
1527
|
+
* is refused.
|
|
1528
|
+
*/
|
|
1529
|
+
export function scanCommand(command: string, options: { cwd: string; home: string; depth?: number }): ScanResult {
|
|
1530
|
+
const result: ScanResult = { rmHits: [], handoffHits: [], refusals: [], protectedHits: [], trustworthy: true };
|
|
1531
|
+
|
|
1532
|
+
const lexed = lexCommand(command, DEEP);
|
|
1533
|
+
result.trustworthy = lexed.trustworthy;
|
|
1534
|
+
const ctx: ScanContext = {
|
|
1535
|
+
cwd: options.cwd, home: options.home, depth: options.depth ?? 0,
|
|
1536
|
+
bodiesMention: mentionsDeleteVerb(lexed.segments.flatMap((segment) => segment.heredocs ?? []).join("\n")),
|
|
1537
|
+
};
|
|
1538
|
+
|
|
1539
|
+
if (!lexed.trustworthy) {
|
|
1540
|
+
return result;
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
// Refusals that only the strict or fail-closed reading finds come after every
|
|
1544
|
+
// other refusal, so a command the shared reading already refused keeps its
|
|
1545
|
+
// reason.
|
|
1546
|
+
const later: Refusal[] = [];
|
|
1547
|
+
const apply = (reading: Reading, refusals: Refusal[] = result.refusals): void => {
|
|
1548
|
+
if (reading.kind === "refuse") refusals.push({ reason: reading.reason });
|
|
1549
|
+
else if (reading.kind === "rm" && reading.handoff) result.handoffHits.push(reading.hit);
|
|
1550
|
+
else if (reading.kind === "rm") {
|
|
1551
|
+
result.rmHits.push(reading.hit);
|
|
1552
|
+
if (reading.protectedReason) result.protectedHits.push({ reason: reading.protectedReason });
|
|
1553
|
+
}
|
|
1554
|
+
};
|
|
1555
|
+
|
|
1556
|
+
let cwd = ctx.cwd;
|
|
1557
|
+
for (const segment of lexed.segments) {
|
|
1558
|
+
const index = commandWordIndex(segment);
|
|
1559
|
+
const strict = strictCommandIndex(segment);
|
|
1560
|
+
const shared: Reading = index < 0 ? { kind: "none" } : readCommandAt(segment, index, cwd, ctx);
|
|
1561
|
+
// The shared reading first, so its reasons keep their place.
|
|
1562
|
+
if (shared.kind !== "cd") apply(shared);
|
|
1563
|
+
const expands = (at: number | null): boolean => at !== null && at >= 0 && expandsWord(segment.words[at].text);
|
|
1564
|
+
if (strict === null || expands(index) || expands(strict)) {
|
|
1565
|
+
// Fail closed: the word that runs is unknown, so every word that could
|
|
1566
|
+
// run a delete counts, including one an expansion could turn into a
|
|
1567
|
+
// delete verb.
|
|
1568
|
+
if (segment.words.some((word, at) => !segment.redirects.has(at) && (deletes(readCommandAt(segment, at, cwd, ctx)) || mayNameDelete(word.text)))) {
|
|
1569
|
+
later.push({ reason: UNREADABLE_WRAPPER_REASON });
|
|
1570
|
+
}
|
|
1571
|
+
} else if (strict >= 0 && strict !== index) {
|
|
1572
|
+
const other = readCommandAt(segment, strict, cwd, ctx);
|
|
1573
|
+
if (deletes(other)) {
|
|
1574
|
+
if (deletes(shared)) later.push({ reason: TWO_READINGS_REASON });
|
|
1575
|
+
else apply(other, later);
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
if (shared.kind === "cd") cwd = shared.cwd;
|
|
1579
|
+
}
|
|
978
1580
|
|
|
979
1581
|
// A delete hidden inside a command substitution runs before the rewritten
|
|
980
1582
|
// verb and cannot be swapped in place — refuse rather than rewrite a
|
|
981
|
-
// command that still contains a live delete.
|
|
1583
|
+
// command that still contains a live delete. A body that cannot be read
|
|
1584
|
+
// to its end is refused when it mentions a delete.
|
|
982
1585
|
if (ctx.depth < 3) {
|
|
983
1586
|
for (const body of lexed.substitutions) {
|
|
984
1587
|
const inner = scanCommand(body, { cwd, home: ctx.home, depth: ctx.depth + 1 });
|
|
985
|
-
if (inner.rmHits.length > 0 || inner.refusals.length > 0 || inner.handoffHits.length > 0 || inner.protectedHits.length > 0
|
|
1588
|
+
if (inner.rmHits.length > 0 || inner.refusals.length > 0 || inner.handoffHits.length > 0 || inner.protectedHits.length > 0
|
|
1589
|
+
|| (!inner.trustworthy && mentionsDeleteVerb(body))) {
|
|
986
1590
|
result.refusals.push({
|
|
987
1591
|
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.",
|
|
988
1592
|
});
|
|
@@ -994,6 +1598,7 @@ export function scanCommand(command: string, options: { cwd: string; home: strin
|
|
|
994
1598
|
reason: "This command nests a delete inside command substitutions deeper than this hook will follow. Run the delete as a separate `rm -- <path>` command.",
|
|
995
1599
|
});
|
|
996
1600
|
}
|
|
1601
|
+
result.refusals.push(...later);
|
|
997
1602
|
|
|
998
1603
|
return result;
|
|
999
1604
|
}
|
|
@@ -1122,14 +1727,17 @@ export interface GuardDependencies {
|
|
|
1122
1727
|
* enough. Ordinary command/control-flow/quoting stays with the existing lexer. */
|
|
1123
1728
|
function changesExecutionEnvironment(command: string): boolean {
|
|
1124
1729
|
const stateCommands = new Set(["export", "set", "unset", "readonly", "declare", "typeset", "local", "alias", "unalias", "read", "readarray", "mapfile", "getopts", "trap", "enable", "function", "env", "sudo", "doas", "stdbuf"]);
|
|
1125
|
-
const parsed = lexCommand(command);
|
|
1730
|
+
const parsed = lexCommand(command, DEEP);
|
|
1126
1731
|
return parsed.segments.some((segment) => {
|
|
1127
|
-
|
|
1128
|
-
const
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1732
|
+
// Both readings of the command word (see scanCommand).
|
|
1733
|
+
const strict = strictCommandIndex(segment);
|
|
1734
|
+
return [commandWordIndex(segment), ...(strict === null ? [] : [strict])].some((index) => {
|
|
1735
|
+
const prefix = segment.words.slice(0, index < 0 ? segment.words.length : index);
|
|
1736
|
+
if (prefix.some((word) => ASSIGNMENT_RE.test(decodeWord(word.text)) || stateCommands.has(commandName(word.text)))) return true;
|
|
1737
|
+
if (index < 0) return false;
|
|
1738
|
+
const word = segment.words[index]!;
|
|
1739
|
+
return stateCommands.has(commandName(word.text)) || /^\s*\(\s*\)\s*\{/.test(command.slice(word.end));
|
|
1740
|
+
});
|
|
1133
1741
|
});
|
|
1134
1742
|
}
|
|
1135
1743
|
|
|
@@ -1228,6 +1836,14 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
|
|
|
1228
1836
|
}
|
|
1229
1837
|
|
|
1230
1838
|
if (scanned.rmHits.length === 0) {
|
|
1839
|
+
if (scanned.handoffHits.some((hit) => hit.cwdOnly)) {
|
|
1840
|
+
// Handed off only because the cwd is inside a checkout, but every path
|
|
1841
|
+
// is outside the roots: workspace-repos-guard does not own it, so
|
|
1842
|
+
// abstaining would let the raw delete run.
|
|
1843
|
+
return deny(
|
|
1844
|
+
"[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.",
|
|
1845
|
+
);
|
|
1846
|
+
}
|
|
1231
1847
|
if (scanned.handoffHits.length > 0) {
|
|
1232
1848
|
// Every delete here belongs to the guarded repo-checkout roots, which
|
|
1233
1849
|
// `workspace-repos-guard` owns. Abstain and let that hook decide.
|