dsh-delete-guard 0.0.0-stage → 2.2.3

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/lib/guard.js ADDED
@@ -0,0 +1,1048 @@
1
+ /**
2
+ * Destructive-command detection and rewrite planning.
3
+ *
4
+ * This module is pure: it takes a command string and returns a verdict plus the
5
+ * list of paths a rewrite should move to the Recycle Bin. No I/O, no ctx, so it
6
+ * is directly unit-testable.
7
+ *
8
+ * Design notes
9
+ * ------------
10
+ * The matcher is *command-position aware*: a delete verb only counts when it
11
+ * appears where a command can start (after a separator or at the string head).
12
+ * That keeps `Get-Content form.txt` and `$rm = 1` from being false positives,
13
+ * which is the failure mode of naive `/\brm\b/` guards.
14
+ *
15
+ * Unlike a block-only guard, a matched command is not simply denied: the parsed
16
+ * operands are handed back so the caller can perform a real recycle-bin move.
17
+ * Denial is the fallback for the cases where a safe rewrite cannot be proven
18
+ * (pipelines, command substitution, `-Recurse` over an unresolved glob, etc.).
19
+ */
20
+
21
+ /** PowerShell delete verbs whose operand list we can trust. */
22
+ const PS_DELETE_VERBS = ['remove-item', 'ri'];
23
+ /** PowerShell cmdlet aliases that mean the same thing. */
24
+ const PS_DELETE_ALIASES = ['del', 'erase', 'rd', 'rmdir', 'rm'];
25
+ /** POSIX delete verbs. */
26
+ const POSIX_DELETE_VERBS = ['rm', 'unlink', 'rmdir', 'shred', 'srm'];
27
+
28
+ /**
29
+ * Delete-cmdlet parameters that consume the following token as their value.
30
+ * Lower-cased, because the lookup is case-insensitive.
31
+ *
32
+ * Kept as an explicit list rather than a `-<word> <word>` heuristic: an operand
33
+ * legitimately follows no flag at all, and guessing would swallow real targets.
34
+ * `-Path` / `-LiteralPath` are handled separately because their value *is* the
35
+ * target.
36
+ */
37
+ const FLAGS_TAKING_VALUE = new Set([
38
+ '-erroraction',
39
+ '-ea',
40
+ '-errorvariable',
41
+ '-ev',
42
+ '-warningaction',
43
+ '-wa',
44
+ '-warningvariable',
45
+ '-wv',
46
+ '-informationaction',
47
+ '-infa',
48
+ '-informationvariable',
49
+ '-iv',
50
+ '-outbuffer',
51
+ '-ob',
52
+ '-outvariable',
53
+ '-ov',
54
+ '-pipelinevariable',
55
+ '-pv',
56
+ '-filter',
57
+ '-include',
58
+ '-exclude',
59
+ '-credential',
60
+ '-confirm',
61
+ '-whatif',
62
+ '-verbose',
63
+ '-debug',
64
+ ]);
65
+
66
+ /**
67
+ * Programs that mean "permanently erase" rather than "delete". They are never
68
+ * rewritten — they are denied outright.
69
+ *
70
+ * Matched in **program position** (the command word of a statement, optionally
71
+ * behind a path or a launcher), never as a substring of the whole line. Whole-
72
+ * line matching was the bug: `Get-Content C:\logs\sdelete.log`,
73
+ * `Select-String -Pattern "wipe" notes.md` and `grep -n "shred" *.md` all name an
74
+ * erase tool while erasing nothing, and all three were refused as if they were
75
+ * about to erase the disk.
76
+ */
77
+ const WIPE_PROGRAMS = new Set(['sdelete', 'sdelete64', 'shred', 'srm', 'wipe']);
78
+
79
+ /**
80
+ * Verbs whose following argument is itself the program that will run.
81
+ * `Start-Process -FilePath shred …` and `cmd /c shred …` name the wipe tool as
82
+ * an argument, so looking only at the command word would miss them.
83
+ */
84
+ const LAUNCHER_VERBS = new Set(['start-process', 'start', 'saps', 'cmd', 'invoke-item', 'ii']);
85
+
86
+ /**
87
+ * Erase by flag rather than by program name. Matched anywhere in the command:
88
+ * the flag shape *is* the evidence, and no read-only command is spelled
89
+ * `cipher /w` or `format D:`.
90
+ */
91
+ const WIPE_FLAG_SHAPES = [
92
+ /\bcipher\s+\/w\b/i,
93
+ /\bcipher\s+\/w:\S+/i,
94
+ /\bformat\s+[a-z]:/i,
95
+ ];
96
+
97
+ /**
98
+ * A wipe-program name anywhere inside the body handed to a child interpreter
99
+ * (`bash -c "shred -u x"`). Such a body is shell text, not an operand, so the
100
+ * argument that *calls* itself out of program position does not protect it.
101
+ */
102
+ const WIPE_NAME_IN_BODY = /\b(?:sdelete64|sdelete|shred|srm|wipe)\b/i;
103
+
104
+ /** Denial text shared by every permanent-erase rule. */
105
+ const WIPE_REASON =
106
+ 'Permanent-erase tools (shred/sdelete/srm/cipher /w/format) are disabled by the recycle-bin guard. ' +
107
+ 'Use the file_trash tool so the data stays recoverable.';
108
+
109
+ /**
110
+ * Command fragments that empty or bypass the Recycle Bin. Denied, because the
111
+ * whole point of this plugin is that deleted data stays recoverable.
112
+ */
113
+ const EMPTY_RECYCLE_RULES = [
114
+ // `Clear-RecycleBin` is an action only in command position. Matching it
115
+ // anywhere refused `Select-String -Pattern "Clear-RecycleBin" README.md`,
116
+ // i.e. reading this plugin's own documentation about the rule. Command
117
+ // position is resolved per statement by `commandWordsOf` below, which also
118
+ // reaches the invoke-operator and child-shell spellings.
119
+ // Reaching *into* the bin store is only meaningful behind a delete verb, so
120
+ // these stay verb-anchored and are judged per statement.
121
+ { re: /\bremove-item\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
122
+ { re: /\brd\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
123
+ { re: /\brmdir\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
124
+ { re: /\bdel\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
125
+ { re: /\brm\b[^\n;&|]*(?:\$recycle\.bin|recycler\b)/i, what: 'a delete inside the Recycle Bin' },
126
+ ];
127
+
128
+ /**
129
+ * The Recycle Bin's own emptying paths, which never name a delete verb.
130
+ *
131
+ * Four shapes reach the bin's contents: the cmdlet in command position
132
+ * (`Clear-RecycleBin -Force`), the invoke operator with the name as a string
133
+ * (`& "Clear-RecycleBin"`), a child shell running it
134
+ * (`pwsh -Command "Clear-RecycleBin"`, `-EncodedCommand <base64>`), and the
135
+ * Win32 call `SHEmptyRecycleBin`. A fifth drives the bin's *own* shell verbs
136
+ * over its items (`InvokeVerb('delete')` / `Verbs()` + `DoIt()`), which is what
137
+ * Explorer's "delete" does to a bin item: permanent, no recycle.
138
+ *
139
+ * All five were allowed by 1.0.6 and are holes worth closing: `pwsh -Command
140
+ * "Clear-RecycleBin -Force"` empties the bin silently, one shell call away.
141
+ */
142
+ const EMPTY_BIN_COMMAND = /^clear-recyclebin$/i;
143
+ const EMPTY_BIN_API = /\bSHEmptyRecycleBin\w*\b/i;
144
+ const BIN_NAMESPACE_REF = /Namespace\(\s*(?:10|0xa)\s*\)|shell:RecycleBinFolder|\$recycle\.bin/i;
145
+ const BIN_VERB_DRIVE = /\bInvokeVerb\s*\(|\.Verbs\s*\(\s*\)|\.DoIt\s*\(/i;
146
+
147
+ /**
148
+ * Constructs that can hide a delete from a text-level parser, or make the
149
+ * rewrite target set unknowable. A command containing any of these is denied
150
+ * rather than rewritten: silently moving the wrong path is worse than refusing.
151
+ *
152
+ * Entries may carry `dialects` to restrict them to one shell language. The
153
+ * distinction matters for `$( … )`: PowerShell treats it as command
154
+ * substitution (opaque), while in bash it is ordinary everyday syntax
155
+ * (`$(pwd)`, `$(date)`). Applying the PowerShell rule to bash would refuse
156
+ * almost every real command, so it is dialect-scoped.
157
+ */
158
+ const OPAQUE_CONSTRUCTS = [
159
+ { re: /\$\(/, what: 'command substitution $( … )', dialects: ['pwsh'] },
160
+ { re: /`[^`]*`/, what: 'backtick command substitution', dialects: ['pwsh', 'bash'] },
161
+ { re: /(?<![<>=!])<<</, what: 'here-string / here-doc', dialects: ['pwsh', 'bash'] },
162
+ { re: /\|\s*(?:Remove-Item|del|rm|ri)\b/i, what: 'piped delete', dialects: ['pwsh', 'bash'] },
163
+ // `… | xargs rm` runs a delete whose targets arrive from stdin, so the target
164
+ // set is unknowable. `xargs` hides the verb from the statement parser.
165
+ { re: /\bxargs\b[^\n;&|]*\b(?:rm|rmdir|unlink|del|erase|rd)\b/i, what: 'xargs-driven delete', dialects: ['pwsh', 'bash'] },
166
+ { re: /(?:Remove-Item|del|rm|ri)\b[^\n;&|]*-Recurse\b[^\n;&|]*\*/, what: 'recursive wildcard delete', dialects: ['pwsh', 'bash'] },
167
+ { re: /(?:Remove-Item|rm)\b[^\n;&|]*--?no-preserve-root/, what: 'no-preserve-root', dialects: ['pwsh', 'bash'] },
168
+ ];
169
+
170
+ /**
171
+ * Deletes that never appear as a shell delete verb, so the statement parser
172
+ * cannot see them at all. Each entry names what it does in `what`; a match is
173
+ * denied outright, because there is no operand list to hand to `file_trash`.
174
+ *
175
+ * Scope is deliberately narrow. These are *specific* erasing constructs, not
176
+ * the word "delete" anywhere in a line — the previous revision matched
177
+ * `shellDeleteVerb` over the whole command, which refused read-only audits for
178
+ * containing the Python statement `del L[a:b+1]` or the flag `Get-ChildItem -File`.
179
+ *
180
+ * `-delete` is listed for `find` only: in bash, `rm --delete` is not a thing,
181
+ * while `find … -delete` is the ordinary way to erase a tree without `rm`.
182
+ */
183
+ const ERASE_CONSTRUCTS = [
184
+ // .NET calls that unlink directly, bypassing the verb table. The pattern keys
185
+ // on the *call*, not on the type reference: `[System.IO.File]::ReadAllBytes`,
186
+ // `::Exists`, `::Copy` and `::Move` name the same type and erase nothing, so
187
+ // matching the literal `[System.IO.File]` refused ordinary read-only audits —
188
+ // e.g. reading a .bat file to check its byte count and line endings.
189
+ { re: /::\s*(?:Delete|DeleteFile|DeleteDirectory)\s*\(/i, what: 'a .NET File/Directory::Delete() call', dialects: ['pwsh'] },
190
+ // The instance-method spelling: `[System.IO.FileInfo]::new($p).Delete()` and
191
+ // the recursive overload `[System.IO.DirectoryInfo]::new($d).Delete($true)`.
192
+ // The no-argument form was a hole until 1.0.4 — only `.Delete($true)` matched,
193
+ // so `(Get-Item $p).Delete()` erased a file unguarded.
194
+ { re: /\.\s*Delete\s*\(\s*(?:\)|\$?(?:true|1)\s*[,)])/i, what: 'a .NET instance Delete() call', dialects: ['pwsh'] },
195
+ // Invoke-Expression / iex evaluates a string: the verb is inside the string,
196
+ // so no statement-level verb is ever seen.
197
+ { re: /\b(?:Invoke-Expression|iex)\b/i, what: 'Invoke-Expression / iex', dialects: ['pwsh'] },
198
+ // `cmd /c del …` hands the delete to a child interpreter.
199
+ { re: /\bcmd(?:\.exe)?\s+\/[ck]\b[^\n]*\b(?:del|erase|rd|rmdir)\b/i, what: 'a delete delegated to cmd.exe', dialects: ['pwsh', 'bash'] },
200
+ // `robocopy … /MIR` mirrors an empty source over the target, which empties it
201
+ // without ever naming a delete verb. /PURGE is the same trick with pruning.
202
+ { re: /\brobocopy\b[^\n]*\/(?:MIR|PURGE)\b/i, what: 'robocopy /MIR or /PURGE (empties the target)', dialects: ['pwsh', 'bash'] },
203
+ // `find … -delete` unlinks without `rm`.
204
+ { re: /\bfind\b[^\n]*(?:^|\s)-delete\b/i, what: 'find -delete', dialects: ['bash'] },
205
+ ];
206
+
207
+ /**
208
+ * Interpreter invocations whose *body* is opaque to this parser. The check is
209
+ * two-part on purpose: the interpreter must be invoked with an inline-body flag,
210
+ * and the body must contain an erasing construct. `python -c "print(1+1)"` and
211
+ * `bash -c "ls -la"` must keep working.
212
+ *
213
+ * The erasing API is matched by member name, not by module prefix:
214
+ * `require('fs').rmSync(...)` never contains the text `fs.rmSync`, so a
215
+ * module-qualified pattern missed it. Each name below is a delete in the
216
+ * language it belongs to — `remove`, `unlink`, `rmdir`, `rmtree` — and none of
217
+ * them is a common non-deleting call.
218
+ */
219
+ const INLINE_BODY_FLAGS = /(?:^|\s)(?:-c|-e|-Command|-EncodedCommand|--eval|--execute)\s/i;
220
+ const INTERPRETER = /\b(?:bash|sh|zsh|pwsh|powershell|node|python|python3|perl|ruby)\b/i;
221
+ const PROGRAMMATIC_ERASE =
222
+ /(?:\.\s*(?:rmSync|rmdirSync|unlinkSync|removeSync|rmdir|unlink|rmtree|remove_tree|remove_entry)\s*\(|\.\s*rm\s*\(|\b(?:shutil\s*\.\s*rmtree|os\s*\.\s*(?:remove|unlink|rmdir))\b)/i;
223
+
224
+ /**
225
+ * Script-file writes that *create* a file containing delete text. Writing a
226
+ * helper script and then running it by path is the documented escape hatch in
227
+ * this plugin's own README; the guard cannot read the body back, but it can
228
+ * refuse to let the write happen.
229
+ *
230
+ * Both spellings are covered because both are ordinary: a redirection
231
+ * (`> clean.ps1`) and a write cmdlet (`| Out-File clean.ps1`). Without the
232
+ * second, the redirect rule is a formality.
233
+ */
234
+ const SCRIPT_WRITE_REDIRECT = />>?\s*\S+\.(?:ps1|sh|bash|zsh|bat|cmd|py|js|mjs|ts)\b/i;
235
+ const SCRIPT_WRITE_CMDLET =
236
+ /\b(?:Out-File|Set-Content|Add-Content|Tee-Object)\b[^\n;&|]*\.(?:ps1|sh|bash|zsh|bat|cmd|py|js|mjs|ts)\b/i;
237
+
238
+ /**
239
+ * Shell-level delete verbs, used only by the script-file rule, where the body
240
+ * is not parsed at all.
241
+ */
242
+ const SHELL_DELETE_VERB = /\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink)\b/i;
243
+
244
+
245
+ /**
246
+ * Substitutions that may appear inside a delete operand. The value is only
247
+ * known when the shell expands it, so no path can be proven safe to recycle:
248
+ * the operand must be refused rather than treated as a literal path.
249
+ *
250
+ * This is dialect-independent. bash permits `$( … )` as ordinary syntax, but
251
+ * never as an unexpandable delete target.
252
+ */
253
+ const SUBSTITUTION_IN_TARGET = /\$\(|`|\$\{|\$[A-Za-z_]/;
254
+
255
+ /** Path shapes that must never be rewritten into a recycle-bin move. */
256
+ const FORBIDDEN_TARGETS = [
257
+ { re: /^[a-z]:[\\/]?$/i, what: 'a drive root' },
258
+ { re: /^[\\/]$/, what: 'the filesystem root' },
259
+ { re: /^(?:\$env:SystemRoot|%SystemRoot%|[a-z]:\\Windows)(?:[\\/]|$)/i, what: 'the Windows directory' },
260
+ { re: /^(?:\$env:ProgramFiles|%ProgramFiles%|[a-z]:\\Program Files)/i, what: 'Program Files' },
261
+ { re: /(?:^|[\\/])\.\.(?:[\\/]|$)/, what: 'a parent-directory traversal' },
262
+ { re: /^\$recycle\.bin$/i, what: 'the Recycle Bin itself' },
263
+ ];
264
+
265
+ /**
266
+ * Strip a single layer of PowerShell quote characters.
267
+ * @param token - raw operand token.
268
+ * @returns the token without surrounding quotes.
269
+ */
270
+ function unquote(token) {
271
+ const t = token.trim();
272
+ if (t.length >= 2) {
273
+ const first = t[0];
274
+ const last = t[t.length - 1];
275
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
276
+ return t.slice(1, -1);
277
+ }
278
+ }
279
+ return t;
280
+ }
281
+
282
+ /**
283
+ * Split a command string into statements on unquoted separators, so each
284
+ * statement can be classified independently.
285
+ *
286
+ * Braces are separators. PowerShell wraps a delete in a script block all the
287
+ * time — `if (Test-Path $p) { Remove-Item $p }`, `foreach ($f in $fs) { … }`,
288
+ * `& { … }`, `try { … }`, `… | ForEach-Object { … }` — and a splitter that only
289
+ * honours `;` and newlines leaves the verb inside the block where the
290
+ * first-token matcher never reaches it. That is not a theoretical gap: it is
291
+ * exactly how a real `Remove-Item` ran unguarded on 2026-10-18, while the same
292
+ * delete written across three lines was caught (the newline happened to be a
293
+ * separator).
294
+ *
295
+ * `${name}` is the one brace form that is a variable rather than a block, so it
296
+ * is consumed whole. Shredding it into `$` + `NAME}` would turn a delete
297
+ * target of `${TARGET_DIR}` into a literal `$`, which is worse than missing it:
298
+ * the redirect message would name a path that does not exist.
299
+ *
300
+ * @param command - full command text.
301
+ * @returns the statement strings, trimmed and non-empty.
302
+ */
303
+ function splitStatements(command) {
304
+ const out = [];
305
+ let buf = '';
306
+ let quote = null;
307
+ for (let i = 0; i < command.length; i += 1) {
308
+ const ch = command[i];
309
+ if (quote !== null) {
310
+ buf += ch;
311
+ if (ch === quote) quote = null;
312
+ continue;
313
+ }
314
+ if (ch === '"' || ch === "'") {
315
+ quote = ch;
316
+ buf += ch;
317
+ continue;
318
+ }
319
+ if (ch === '{' && buf.endsWith('$')) {
320
+ const close = command.indexOf('}', i + 1);
321
+ const end = close === -1 ? command.length : close + 1;
322
+ buf += command.slice(i, end);
323
+ i = end - 1;
324
+ continue;
325
+ }
326
+ const isSep =
327
+ ch === ';' ||
328
+ ch === '\n' ||
329
+ ch === '\r' ||
330
+ ch === '|' ||
331
+ ch === '&' ||
332
+ ch === '{' ||
333
+ ch === '}';
334
+ if (isSep) {
335
+ if (buf.trim().length > 0) out.push(buf.trim());
336
+ buf = '';
337
+ continue;
338
+ }
339
+ buf += ch;
340
+ }
341
+ if (buf.trim().length > 0) out.push(buf.trim());
342
+ return out;
343
+ }
344
+
345
+ /**
346
+ * Tokenize a single statement into argv-like words, honouring quotes.
347
+ * @param statement - one statement.
348
+ * @returns the token list.
349
+ */
350
+ function tokenize(statement) {
351
+ const out = [];
352
+ let buf = '';
353
+ let quote = null;
354
+ let started = false;
355
+ for (let i = 0; i < statement.length; i += 1) {
356
+ const ch = statement[i];
357
+ if (quote !== null) {
358
+ if (ch === quote) {
359
+ quote = null;
360
+ } else {
361
+ buf += ch;
362
+ }
363
+ started = true;
364
+ continue;
365
+ }
366
+ if (ch === '"' || ch === "'") {
367
+ quote = ch;
368
+ started = true;
369
+ continue;
370
+ }
371
+ if (ch === ' ' || ch === '\t') {
372
+ if (started) {
373
+ out.push(buf);
374
+ buf = '';
375
+ started = false;
376
+ }
377
+ continue;
378
+ }
379
+ buf += ch;
380
+ started = true;
381
+ }
382
+ if (started) out.push(buf);
383
+ return out;
384
+ }
385
+
386
+ /**
387
+ * Reduce a token to the name of the program it would execute: unquoted, with
388
+ * the directory dropped, lower-cased, and with a launcher extension removed.
389
+ *
390
+ * `"C:\tools\sdelete64.exe"` → `sdelete64`. This is what makes "is this token a
391
+ * wipe tool" answerable without also matching a *file named* `sdelete.log`.
392
+ *
393
+ * @param token - one argv token.
394
+ * @returns the program name, or `''` for an empty token.
395
+ */
396
+ function programName(token) {
397
+ const bare = unquote(token).trim();
398
+ if (bare.length === 0) return '';
399
+ const base = bare.split(/[\\/]/).pop() ?? '';
400
+ return base.toLowerCase().replace(/\.(?:exe|com|bat|cmd|ps1|sh)$/, '');
401
+ }
402
+
403
+ /**
404
+ * Find a wipe program that a single statement actually runs.
405
+ *
406
+ * Only two positions count: the command word, and the argument of a launcher
407
+ * (`Start-Process -FilePath shred`, `cmd /c shred`). Everything else in a
408
+ * statement is an operand, and an operand is allowed to be a file whose name
409
+ * contains the word.
410
+ *
411
+ * @param statement - one statement, already split from the command.
412
+ * @returns the wipe program name, or `undefined` when the statement runs none.
413
+ */
414
+ function wipeProgramIn(statement) {
415
+ const tokens = tokenize(statement).filter((t) => t.length > 0);
416
+ // Four tokens is enough for `cmd.exe /d /c shred …`; a wipe tool invoked
417
+ // further along a launcher's line is not reachable without `&`/`.`, which the
418
+ // statement splitter already treats as a boundary.
419
+ for (let i = 0; i < tokens.length && i < 4; i += 1) {
420
+ const name = programName(tokens[i]);
421
+ if (name.length === 0) continue;
422
+ if (WIPE_PROGRAMS.has(name)) return name;
423
+ if (i === 0 && !LAUNCHER_VERBS.has(name)) return undefined;
424
+ }
425
+ return undefined;
426
+ }
427
+
428
+ /**
429
+ * Find the command word of one statement: the token that names the thing being
430
+ * run, with the wrapper prefixes removed the same way `parseDeleteStatement`
431
+ * removes them (`&`, `.`, `(`, `@(`, `$x =`) and quotes stripped.
432
+ *
433
+ * `& "Clear-RecycleBin"` is the case that motivated this: the statement
434
+ * splitter treats `&` as a separator, so what is left is a bare quoted name, and
435
+ * a `^clear-recyclebin` regex over raw text never saw it.
436
+ *
437
+ * @param statement - one statement.
438
+ * @returns the command word, or `''`.
439
+ */
440
+ function commandWord(statement) {
441
+ const tokens = tokenize(statement).filter((t) => t.length > 0);
442
+ for (let i = 0; i < tokens.length; i += 1) {
443
+ const t = tokens[i];
444
+ if (/^(?:[(\[{@&.]+|\$\(|=)$/.test(t)) continue;
445
+ const glued = /^[(\[{@&]+(.+)$/.exec(t);
446
+ if (glued !== null) return unquote(glued[1]).trim();
447
+ if (/^\$[A-Za-z_][\w:]*$/.test(t) && tokens[i + 1] === '=') {
448
+ i += 1;
449
+ continue;
450
+ }
451
+ const assign = /^\$[A-Za-z_][\w:]*\s*=\s*(.+)$/.exec(t);
452
+ if (assign !== null) return assign[1].trim();
453
+ return unquote(t).trim();
454
+ }
455
+ return '';
456
+ }
457
+
458
+ /**
459
+ * The body text of a statement that hands a program to a child shell:
460
+ * `pwsh -Command "…"`, `bash -c "…"`, `node -e "…"`.
461
+ *
462
+ * @param statement - one statement.
463
+ * @returns the body text, or `undefined` when the statement runs no child.
464
+ */
465
+ function inlineBodyText(statement) {
466
+ const tokens = tokenize(statement).filter((t) => t.length > 0);
467
+ for (let i = 0; i < tokens.length - 1; i += 1) {
468
+ if (!/^-(?:c|e|command|eval|execute)$/i.test(tokens[i])) continue;
469
+ return tokens.slice(i + 1).join(' ');
470
+ }
471
+ return undefined;
472
+ }
473
+
474
+ /**
475
+ * Every command word a statement can run: its own, plus the ones inside a body
476
+ * handed to a child shell.
477
+ *
478
+ * @param statement - one statement.
479
+ * @returns the command words found.
480
+ */
481
+ function commandWordsOf(statement) {
482
+ const words = [commandWord(statement), ...launcherPayloadWords(statement)];
483
+ const body = inlineBodyText(statement);
484
+ if (body !== undefined) {
485
+ for (const inner of splitStatements(body)) words.push(commandWord(inner));
486
+ }
487
+ return words.filter((w) => w.length > 0);
488
+ }
489
+
490
+ /**
491
+ * Command words hidden in a launcher's arguments: `Start-Process pwsh
492
+ * -ArgumentList "-c","Clear-RecycleBin -Force"`, `cmd /c rd …`.
493
+ *
494
+ * The program is an operand there, so `commandWord` never sees it. Each argument
495
+ * token is split on commas (PowerShell array syntax) and re-read as a statement.
496
+ *
497
+ * @param statement - one statement.
498
+ * @returns the command words found in launcher arguments.
499
+ */
500
+ function launcherPayloadWords(statement) {
501
+ if (!LAUNCHER_VERBS.has(commandWord(statement).toLowerCase())) return [];
502
+ const out = [];
503
+ for (const token of tokenize(statement).slice(1)) {
504
+ for (const piece of token.split(/[,;]/)) {
505
+ const inner = piece.trim();
506
+ if (inner.length === 0) continue;
507
+ for (const nested of splitStatements(inner)) out.push(commandWord(nested));
508
+ }
509
+ }
510
+ return out;
511
+ }
512
+
513
+ /**
514
+ * Decode `-EncodedCommand` bodies (base64 of UTF-16LE) into statements.
515
+ *
516
+ * The flag exists to hand PowerShell a program without it appearing on the
517
+ * command line, so treating it as opaque would let it carry any delete past
518
+ * every text rule. Decoding costs nothing and makes the body visible to the same
519
+ * per-statement checks as everything else.
520
+ *
521
+ * @param command - the full command text.
522
+ * @returns the statements decoded from every encoded body.
523
+ */
524
+ function decodedInlineBodies(command) {
525
+ const out = [];
526
+ for (const m of command.matchAll(/-EncodedCommand\s+([A-Za-z0-9+/=]{8,})/gi)) {
527
+ try {
528
+ const text = Buffer.from(m[1], 'base64').toString('utf16le');
529
+ if (text.trim().length > 0) out.push(...splitStatements(text));
530
+ } catch {
531
+ // Not decodable as base64/UTF-16LE: nothing to add.
532
+ }
533
+ }
534
+ return out;
535
+ }
536
+
537
+ /**
538
+ * Map a path as written in Git Bash (MSYS) onto the Windows path it denotes.
539
+ *
540
+ * Git Bash resolves `/c/Users/x` to `C:\Users\x`, and `/cygdrive/c/...` the same
541
+ * way, but handing the raw string to `file_trash` makes Node's Windows resolver
542
+ * read it as `<cwd drive>:\c\Users\x` — a different location. Only the
543
+ * drive-mapped forms are translatable without guessing: `~` is expanded by the
544
+ * shell, and `/tmp`, `/usr`, `/proc` are MSYS mount points whose real targets are
545
+ * installation-specific.
546
+ *
547
+ * @param operand - one delete operand.
548
+ * @returns `{ path }` with the Windows form, or `{ refuse }` with the reason.
549
+ */
550
+ function translatePosixPath(operand) {
551
+ if (operand === '~' || operand.startsWith('~/') || operand.startsWith('~\\')) {
552
+ return {
553
+ refuse:
554
+ 'Refusing a delete whose target is `~`: the shell expands home to a path this plugin cannot see. ' +
555
+ 'Write the real location (a Windows path, or a path relative to the working directory) and hand that to file_trash.',
556
+ };
557
+ }
558
+ if (!operand.startsWith('/')) return { path: operand };
559
+ // `/` is the same root in both shells; leave it for the forbidden-target rule
560
+ // so the refusal says "filesystem root" rather than "unmappable mount point".
561
+ if (operand === '/') return { path: operand };
562
+ const mapped = /^\/cygdrive\/([A-Za-z])(\/.*)?$/.exec(operand)
563
+ ?? /^\/([A-Za-z])(\/.*)?$/.exec(operand);
564
+ if (mapped === null) {
565
+ return {
566
+ refuse:
567
+ `Refusing a delete that targets the POSIX path "${operand}": that is a Git Bash / MSYS mount point, not a ` +
568
+ 'Windows path, so the real location cannot be proven. Resolve it first, then pass the Windows path to file_trash.',
569
+ };
570
+ }
571
+ const rest = (mapped[2] ?? '/').replace(/\//g, '\\');
572
+ return { path: `${mapped[1].toUpperCase()}:${rest}` };
573
+ }
574
+
575
+ /**
576
+ * Find a wipe program named inside a body that is handed to a child
577
+ * interpreter (`bash -c "shred -u x"`). The body is shell text, so the name is
578
+ * not in program position here and `wipeProgramIn` cannot see it.
579
+ *
580
+ * @param statement - one statement, already split from the command.
581
+ * @returns the matched name, or `undefined`.
582
+ */
583
+ function wipeProgramInInlineBody(statement) {
584
+ if (!INLINE_BODY_FLAGS.test(statement)) return undefined;
585
+ const found = WIPE_NAME_IN_BODY.exec(statement);
586
+ return found === null ? undefined : found[0].toLowerCase();
587
+ }
588
+
589
+ /**
590
+ * Classify one statement as a delete we can rewrite.
591
+ * @param statement - one statement string.
592
+ * @returns the verb plus its operand tokens, or `undefined` when not a delete.
593
+ */
594
+ function parseDeleteStatement(statement) {
595
+ const tokens = tokenize(statement);
596
+ if (tokens.length === 0) return undefined;
597
+
598
+ const known = new Set([
599
+ ...PS_DELETE_VERBS,
600
+ ...PS_DELETE_ALIASES,
601
+ ...POSIX_DELETE_VERBS,
602
+ ]);
603
+
604
+ // A delete can be wrapped so that the verb is not the first token but is
605
+ // still the whole statement's action: `(Remove-Item $p)` groups it, and
606
+ // `$x = Remove-Item $p` binds its output. In both shapes the verb is a whole
607
+ // token and everything after it is its operand list, so step over the wrapper
608
+ // instead of dropping the statement.
609
+ //
610
+ // Only leading `(`, `$(`, `@(`, `&`, `.` and a `$name =` / `$env:name =`
611
+ // assignment are skipped. A general "find the verb anywhere" scan is not used
612
+ // here on purpose: it would re-introduce the whole-text matching that made
613
+ // `del L[a:b+1]` inside a Python body look like a shell delete.
614
+ for (let guard = 0; guard < tokens.length; guard += 1) {
615
+ const t = tokens[0];
616
+ // A wrapper that is its own token: `(`, `$(`, `@(`, `&`, `.`, `=`.
617
+ if (/^(?:[(\[{@&.]+|\$\(|=)$/.test(t)) {
618
+ tokens.shift();
619
+ continue;
620
+ }
621
+ // A wrapper glued to the verb: `(Remove-Item`, `@(Remove-Item`.
622
+ const glued = /^[(\[{@&]+(.+)$/.exec(t);
623
+ if (glued !== null) {
624
+ tokens[0] = glued[1];
625
+ continue;
626
+ }
627
+ // `$x =` as two tokens, or `$x=` glued to its value.
628
+ if (/^\$[A-Za-z_][\w:]*$/.test(t) && tokens[1] === '=') {
629
+ tokens.splice(0, 2);
630
+ continue;
631
+ }
632
+ const assign = /^\$[A-Za-z_][\w:]*\s*=\s*(.+)$/.exec(t);
633
+ if (assign !== null) {
634
+ tokens[0] = assign[1];
635
+ continue;
636
+ }
637
+ break;
638
+ }
639
+ if (tokens.length === 0) return undefined;
640
+
641
+ // `xargs <verb>` executes the verb with targets read from stdin. Step past
642
+ // the wrapper (and its own flags) so the delete is recognised at all — the
643
+ // target set stays unknowable, which is why OPAQUE_CONSTRUCTS denies it.
644
+ if (tokens[0].toLowerCase() === 'xargs') {
645
+ let i = 1;
646
+ while (i < tokens.length && tokens[i].startsWith('-')) {
647
+ // `-I{}` consumes the next token as its placeholder replacement.
648
+ if (/^-i$/i.test(tokens[i])) i += 1;
649
+ i += 1;
650
+ }
651
+ if (i < tokens.length && known.has(tokens[i].toLowerCase())) {
652
+ return {
653
+ verb: tokens[i].toLowerCase(),
654
+ operands: [],
655
+ recursive: false,
656
+ force: false,
657
+ preserveRoot: false,
658
+ statement,
659
+ viaXargs: true,
660
+ };
661
+ }
662
+ return undefined;
663
+ }
664
+
665
+ const verb = tokens[0].toLowerCase();
666
+ // Skip a leading `PowerShell -Command` style wrapper is out of scope: the
667
+ // guard denies those via OPAQUE_CONSTRUCTS or treats the wrapper as the verb.
668
+ if (!known.has(verb)) return undefined;
669
+
670
+ const operands = [];
671
+ let recursive = false;
672
+ let force = false;
673
+ let preserveRoot = false;
674
+ let splat = false;
675
+
676
+ for (let i = 1; i < tokens.length; i += 1) {
677
+ const tok = tokens[i];
678
+ if (tok.startsWith('-')) {
679
+ const flag = tok.toLowerCase();
680
+ if (flag === '-recurse' || flag === '-r') recursive = true;
681
+ if (flag === '-force' || flag === '-f') force = true;
682
+ if (flag === '--no-preserve-root') preserveRoot = true;
683
+ // A flag that takes a value is not a target: without this, `-ErrorAction
684
+ // SilentlyContinue` made "SilentlyContinue" a path to recycle, and the
685
+ // redirect message told the model to `file_trash` a value name. The two
686
+ // path flags are the exception — their value *is* the target.
687
+ const takesValue = FLAGS_TAKING_VALUE.has(flag);
688
+ const isPathFlag = flag === '-path' || flag === '-literalpath';
689
+ if ((takesValue || isPathFlag) && i + 1 < tokens.length) {
690
+ if (isPathFlag) operands.push(unquote(tokens[i + 1]));
691
+ i += 1;
692
+ }
693
+ continue;
694
+ }
695
+ // Combined short flags such as `-rf`.
696
+ if (/^-[a-z]{2,}$/i.test(tok)) {
697
+ const flags = tok.slice(1).toLowerCase();
698
+ if (flags.includes('r')) recursive = true;
699
+ if (flags.includes('f')) force = true;
700
+ continue;
701
+ }
702
+ // `Remove-Item @targets` splats an array whose contents only exist at run
703
+ // time. Treating "@targets" as a literal path would recycle a file that
704
+ // happens to be named that; the caller refuses instead (see below).
705
+ if (tok.startsWith('@')) splat = true;
706
+ operands.push(unquote(tok));
707
+ }
708
+
709
+ // PowerShell accepts a comma-separated operand list: `Remove-Item a, b`. The
710
+ // tokenizer keeps the separator glued to the preceding token, so split it off
711
+ // and treat each element as its own operand. A closing bracket glued to the
712
+ // last operand (`(Remove-Item C:\x)`) is stripped for the same reason: it is
713
+ // the wrapper's, not part of the path.
714
+ const expanded = [];
715
+ for (const operand of operands) {
716
+ for (const piece of operand.split(',')) {
717
+ const trimmed = piece.trim().replace(/^[)\]}]+/, '').replace(/[)\]}]+$/, '');
718
+ if (trimmed.length > 0) expanded.push(trimmed);
719
+ }
720
+ }
721
+
722
+ // A delete verb with no operands still has to be reported: its targets come
723
+ // from somewhere else (stdin, a splat, a pipeline). Returning `undefined` here
724
+ // would make the statement indistinguishable from a non-delete, which is how
725
+ // `xargs -I{} rm -f` slipped through after braces became separators.
726
+ return { verb, operands: expanded, recursive, force, preserveRoot, splat, statement };
727
+ }
728
+
729
+ /**
730
+ * Denial verdict for touching the Recycle Bin, naming the vector that was seen.
731
+ * @param what - the command, API or mechanism that would empty or modify the bin.
732
+ * @returns the verdict object.
733
+ */
734
+ function emptyRecycleVerdict(what) {
735
+ return {
736
+ action: 'deny',
737
+ kind: 'empty-recycle',
738
+ reason:
739
+ `Refusing ${what}, which empties or modifies the Recycle Bin: deleted items are kept recoverable on purpose. ` +
740
+ 'Purge them manually from Explorer if you really mean it.',
741
+ };
742
+ }
743
+
744
+ /**
745
+ * Decide what to do with a command that the model is about to run.
746
+ *
747
+ * @param command - the raw command text from the `pwsh`/`bash` tool arguments.
748
+ * @param options - guard policy switches.
749
+ * @param options.forbidEmptyRecycleBin - deny commands that empty the bin.
750
+ * @param options.forbidWipe - deny permanent-erase tools.
751
+ * @param options.blockScriptDeletes - deny inline script text containing deletes.
752
+ * @param options.dialect - which shell language the command is written in
753
+ * ('pwsh' or 'bash'). Defaults to 'pwsh'. Dialect-scoped rules such as the
754
+ * `$( … )` command-substitution check only apply to their own shell.
755
+ * @returns a verdict object.
756
+ */
757
+ export function classifyCommand(command, options = {}) {
758
+ const {
759
+ forbidEmptyRecycleBin = true,
760
+ forbidWipe = true,
761
+ blockScriptDeletes = true,
762
+ dialect = 'pwsh',
763
+ } = options;
764
+
765
+ if (typeof command !== 'string' || command.trim().length === 0) {
766
+ return { action: 'allow' };
767
+ }
768
+
769
+ // Both of the next two rule tables are judged per statement, not per command
770
+ // text: the evidence for "this command runs a wipe tool" is a word in program
771
+ // position, and "this command touches the bin" is a delete verb plus a bin
772
+ // path in the *same* statement. Whole-command matching made an unrelated
773
+ // string literal convict the rest of the line.
774
+ const statements = splitStatements(command);
775
+ // A body handed in through -EncodedCommand is judged like any other
776
+ // statement: the flag only hides it from a human reading the command line.
777
+ const bodyStatements = decodedInlineBodies(command);
778
+ const judged = [...statements, ...bodyStatements];
779
+
780
+ if (forbidEmptyRecycleBin) {
781
+ for (const statement of judged) {
782
+ for (const { re } of EMPTY_RECYCLE_RULES) {
783
+ if (re.test(statement)) {
784
+ return {
785
+ action: 'deny',
786
+ kind: 'empty-recycle',
787
+ reason:
788
+ 'Emptying or reaching into the Recycle Bin is disabled by the recycle-bin guard. ' +
789
+ 'Deleted items are kept recoverable on purpose; purge them manually from Explorer if you really mean it.',
790
+ };
791
+ }
792
+ }
793
+ // The cmdlet by command word: covers `Clear-RecycleBin`, `& "Clear-RecycleBin"`
794
+ // and `pwsh -Command "Clear-RecycleBin"` in one place.
795
+ if (commandWordsOf(statement).some((w) => EMPTY_BIN_COMMAND.test(w))) {
796
+ return emptyRecycleVerdict('Clear-RecycleBin');
797
+ }
798
+ }
799
+ if (EMPTY_BIN_API.test(command)) {
800
+ return emptyRecycleVerdict('the SHEmptyRecycleBin API');
801
+ }
802
+ // Shell verbs driven over bin items are how Explorer empties the bin one
803
+ // item at a time: `InvokeVerb('delete')` on a bin item is permanent, not a
804
+ // recycle. Reading the bin (Move-Item out of $R, listing $I records) stays
805
+ // allowed — only driving its verbs is refused.
806
+ if (BIN_NAMESPACE_REF.test(command) && BIN_VERB_DRIVE.test(command)) {
807
+ return emptyRecycleVerdict("the Recycle Bin's own shell verbs (InvokeVerb / Verbs / DoIt)");
808
+ }
809
+ }
810
+
811
+ if (forbidWipe) {
812
+ for (const statement of judged) {
813
+ const program = wipeProgramIn(statement) ?? wipeProgramInInlineBody(statement);
814
+ if (program !== undefined) {
815
+ return {
816
+ action: 'deny',
817
+ kind: 'wipe',
818
+ reason: `${WIPE_REASON} ("${program}" erases the data instead of moving it.)`,
819
+ };
820
+ }
821
+ }
822
+ for (const rule of WIPE_FLAG_SHAPES) {
823
+ if (rule.test(command)) {
824
+ return { action: 'deny', kind: 'wipe', reason: WIPE_REASON };
825
+ }
826
+ }
827
+ }
828
+
829
+ // Opaque constructs: refuse rather than risk moving the wrong path.
830
+ // Rules may be dialect-scoped; skip any that do not apply to this shell.
831
+ for (const { re, what, dialects } of OPAQUE_CONSTRUCTS) {
832
+ if (Array.isArray(dialects) && !dialects.includes(dialect)) continue;
833
+ if (re.test(command)) {
834
+ const hasDelete = judged.some((s) => parseDeleteStatement(s) !== undefined);
835
+ if (hasDelete) {
836
+ return {
837
+ action: 'deny',
838
+ kind: 'opaque',
839
+ reason:
840
+ `Refusing a delete that uses ${what}: the target set cannot be proven safe to rewrite. ` +
841
+ 'Call the file_trash tool with explicit literal paths instead.',
842
+ };
843
+ }
844
+ }
845
+ }
846
+
847
+ // Erasing constructs that carry no shell delete verb at all. Denied outright:
848
+ // there is no operand list to redirect to `file_trash`.
849
+ for (const { re, what, dialects } of ERASE_CONSTRUCTS) {
850
+ if (Array.isArray(dialects) && !dialects.includes(dialect)) continue;
851
+ if (re.test(command)) {
852
+ return {
853
+ action: 'deny',
854
+ kind: 'erase-api',
855
+ reason:
856
+ `Refusing ${what}: it unlinks files without a delete command, so nothing can be routed to the ` +
857
+ 'Recycle Bin. Use the file_trash tool with explicit literal paths instead.',
858
+ };
859
+ }
860
+ }
861
+
862
+ if (blockScriptDeletes) {
863
+ // A delete that runs inside a child process cannot be routed to the Recycle
864
+ // Bin: the shell only sees the interpreter, and the erase happens after the
865
+ // guard has finished.
866
+ //
867
+ // Every rule below is judged per *statement*, not per command text. The rule
868
+ // this replaces matched across the whole command, which meant a benign
869
+ // `python -c "…del d['a']…"` was refused as soon as any other statement in
870
+ // the same command mentioned `bash` — one statement's evidence convicted
871
+ // another statement's work. Splitting first keeps the evidence local.
872
+ // `judged` also carries statements decoded out of `-EncodedCommand`, so a
873
+ // delete cannot hide in a base64 body.
874
+ const statements = judged;
875
+
876
+ // 1. A shell's inline body that contains a shell delete verb.
877
+ // `pwsh -Command "Remove-Item C:\x"`, `bash -c "rm -rf /tmp/x"`.
878
+ // Scoped to shells: in Python or Ruby, `del` and `rm` are that
879
+ // language's own syntax, so they are judged by rule 2 instead.
880
+ for (const statement of statements) {
881
+ const shellInterp = /\b(?:bash|sh|zsh|pwsh|powershell)\b/i.test(statement);
882
+ const inlineBody = INLINE_BODY_FLAGS.test(statement);
883
+ if (shellInterp && inlineBody && SHELL_DELETE_VERB.test(statement)) {
884
+ return {
885
+ action: 'deny',
886
+ kind: 'script',
887
+ reason:
888
+ 'Deletes inside an inline shell command string are disabled by the recycle-bin guard: the erase ' +
889
+ 'happens inside the child process and would bypass the Recycle Bin. ' +
890
+ 'Run the delete as a direct file_trash tool call instead.',
891
+ };
892
+ }
893
+ }
894
+
895
+ // 2. A non-shell inline body that calls a real erasing API.
896
+ // `node -e "fs.rmSync(...)"`, `python -c "shutil.rmtree(...)"`.
897
+ //
898
+ // Judged across the whole command on purpose, unlike rules 1 and 3: an
899
+ // inline body is routinely multi-line (`python -c @' … '@`), so the
900
+ // interpreter sits on one line and the erase call several lines later.
901
+ // Per-statement matching would miss exactly those. The cross-statement
902
+ // risk that motivated splitting — a shell word in one statement
903
+ // convicting another — does not apply here: `shutil.rmtree` and
904
+ // `fs.rmSync` are not words any other statement would contain by accident.
905
+ const otherInterp = /\b(?:node|python|python3|perl|ruby)\b/i.test(command);
906
+ const inlineBody = INLINE_BODY_FLAGS.test(command);
907
+ if (otherInterp && inlineBody && PROGRAMMATIC_ERASE.test(command)) {
908
+ return {
909
+ action: 'deny',
910
+ kind: 'script',
911
+ reason:
912
+ 'Deletes inside an inline program string are disabled by the recycle-bin guard: the erase happens ' +
913
+ 'inside the child process and would bypass the Recycle Bin. ' +
914
+ 'Run the delete as a direct file_trash tool call instead.',
915
+ };
916
+ }
917
+
918
+ // 3. Writing a script file whose body contains a delete, then running it by
919
+ // path, is the escape hatch this plugin's own README documents. The guard
920
+ // cannot read the body back, but it can refuse to let the write happen.
921
+ //
922
+ // Judged across the whole command: a pipe is a statement separator here,
923
+ // so `"Remove-Item x" | Out-File clean.ps1` would otherwise be two
924
+ // statements — the delete text in one, the write target in the other, and
925
+ // neither one guilty on its own. The write target (`.ps1`, `.sh`, `.py`)
926
+ // is specific enough that no unrelated statement carries it by accident.
927
+ if (
928
+ (SCRIPT_WRITE_REDIRECT.test(command) || SCRIPT_WRITE_CMDLET.test(command)) &&
929
+ SHELL_DELETE_VERB.test(command)
930
+ ) {
931
+ return {
932
+ action: 'deny',
933
+ kind: 'script',
934
+ reason:
935
+ 'Refusing to write a script file containing a delete: a script run by path executes its deletes ' +
936
+ 'inside a child process, where they bypass the Recycle Bin. ' +
937
+ 'Run the delete as a direct file_trash tool call instead.',
938
+ };
939
+ }
940
+ }
941
+
942
+
943
+ // Rewritable deletes: collect every operand across every statement, including
944
+ // the ones decoded out of an -EncodedCommand body.
945
+
946
+ // A delete verb with no operand list is a piped/receiving delete: the targets
947
+ // arrive from the upstream command or from a splat, so they cannot be
948
+ // enumerated. The pipeline case is caught earlier by OPAQUE_CONSTRUCTS, but a
949
+ // bare `Remove-Item` reaching here still means "delete whatever you were
950
+ // handed", which is never safe to wave through.
951
+ for (const statement of judged) {
952
+ const parsed = parseDeleteStatement(statement);
953
+ if (parsed === undefined) continue;
954
+ if (parsed.operands.length > 0 || parsed.splat) continue;
955
+ return {
956
+ action: 'deny',
957
+ kind: 'opaque',
958
+ reason:
959
+ `Refusing a "${parsed.verb}" with no explicit operands: its targets come from another command, ` +
960
+ 'so they cannot be proven safe to route to the Recycle Bin. ' +
961
+ 'Call the file_trash tool with explicit literal paths instead.',
962
+ };
963
+ }
964
+
965
+ const targets = [];
966
+ const seen = new Set();
967
+ for (const statement of judged) {
968
+ const parsed = parseDeleteStatement(statement);
969
+ if (parsed === undefined) continue;
970
+ if (parsed.preserveRoot) {
971
+ return {
972
+ action: 'deny',
973
+ kind: 'forbidden-target',
974
+ reason: 'Refusing a delete that targets the filesystem root.',
975
+ };
976
+ }
977
+ // `Remove-Item @targets`: the array's contents exist only at run time, so no
978
+ // literal path can be proven. Refuse rather than recycle a file whose name
979
+ // happens to be "@targets".
980
+ if (parsed.splat) {
981
+ return {
982
+ action: 'deny',
983
+ kind: 'opaque',
984
+ reason:
985
+ 'Refusing a delete that splats an argument array (@name): its contents are only known at run time, ' +
986
+ 'so they cannot be proven safe to route to the Recycle Bin. ' +
987
+ 'Pass explicit literal paths to file_trash instead.',
988
+ };
989
+ }
990
+ for (const rawOperand of parsed.operands) {
991
+ // A Git Bash user writes `/c/tmp/x`; `file_trash` needs `C:\tmp\x`. The
992
+ // translation has to happen here, where the dialect is known: `pwsh` reads
993
+ // `/c/tmp/x` as a drive-relative Windows path, so the two shells mean
994
+ // different things by the same string.
995
+ let operand = rawOperand;
996
+ if (dialect === 'bash') {
997
+ const mapped = translatePosixPath(operand);
998
+ if (mapped.refuse !== undefined) {
999
+ return { action: 'deny', kind: 'opaque', reason: mapped.refuse };
1000
+ }
1001
+ operand = mapped.path;
1002
+ }
1003
+ // An operand that is itself a substitution has no provable value: the
1004
+ // shell expands it at run time. `rm -rf $(cat list.txt)` would otherwise
1005
+ // be tokenized into the literal strings `$(cat` and `list.txt)`, and
1006
+ // "recycling" those would move the wrong things. This check is
1007
+ // dialect-independent — bash allows `$( … )` as syntax, but never as an
1008
+ // unexpandable delete target.
1009
+ if (SUBSTITUTION_IN_TARGET.test(operand)) {
1010
+ return {
1011
+ action: 'deny',
1012
+ kind: 'opaque',
1013
+ reason:
1014
+ 'Refusing a delete whose target is a command substitution: the real path is only known at ' +
1015
+ 'run time, so it cannot be proven safe to route to the Recycle Bin. ' +
1016
+ 'Resolve the path first, then pass explicit literal paths to file_trash.',
1017
+ };
1018
+ }
1019
+ for (const { re, what } of FORBIDDEN_TARGETS) {
1020
+ if (re.test(operand)) {
1021
+ return {
1022
+ action: 'deny',
1023
+ kind: 'forbidden-target',
1024
+ reason: `Refusing a delete that targets ${what}.`,
1025
+ };
1026
+ }
1027
+ }
1028
+ if (operand === '*' || operand === '*.ps1' || operand === '**') {
1029
+ return {
1030
+ action: 'deny',
1031
+ kind: 'forbidden-target',
1032
+ reason: 'Refusing a bare glob delete: the expanded target set is unknown. Pass explicit paths to file_trash.',
1033
+ };
1034
+ }
1035
+ if (!seen.has(operand)) {
1036
+ seen.add(operand);
1037
+ targets.push(operand);
1038
+ }
1039
+ }
1040
+ }
1041
+
1042
+ if (targets.length > 0) {
1043
+ return { action: 'rewrite', kind: 'delete', targets };
1044
+ }
1045
+ return { action: 'allow' };
1046
+ }
1047
+
1048
+ export { splitStatements, tokenize, parseDeleteStatement, unquote };