dsh-delete-guard 2.2.3 → 2.4.1

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/move-guard.js CHANGED
@@ -48,6 +48,11 @@ function forbiddenReason(p) {
48
48
  if (/^[a-z]:[\\/]windows(?:[\\/]|$)/i.test(p)) return 'the Windows directory';
49
49
  if (/^[a-z]:[\\/]program files(?: \(x86\))?(?:[\\/]|$)/i.test(p)) return 'Program Files';
50
50
  if (isRecycleBinStorage(p)) return 'the Recycle Bin storage directory itself';
51
+ // A share root (`\\host\share`) is the network equivalent of a drive root: it is
52
+ // not an item, and staging it would copy (and then delete) everything on the
53
+ // share. `\\host` alone is not even a location.
54
+ const unc = /^[\\/]{2}([^\\/]+)(?:[\\/]([^\\/]+))?[\\/]?$/.exec(p);
55
+ if (unc !== null) return unc[2] === undefined ? 'a network host, not a path' : 'a network share root';
51
56
  return undefined;
52
57
  }
53
58
 
@@ -74,6 +79,18 @@ export function validateTrashTarget(raw, cwd) {
74
79
  return { ok: false, error: `unresolvable path: ${error.message}` };
75
80
  }
76
81
 
82
+ // `\\host` (a host with no share) is not a path: `resolve` reads it as a
83
+ // drive-relative path and yields `<cwd drive>:\host` — a *local* file that has
84
+ // nothing to do with the share the caller meant. Refuse the shape instead of
85
+ // recycling something else (measured: `resolve('\\\\host')` → `F:\host`).
86
+ if (/^[\\/]{2}[^\\/]/.test(text) && !/^[\\/]{2}/.test(absolute)) {
87
+ return {
88
+ ok: false,
89
+ error: `refusing "${text}": that names a network host but no share, so it is not a path. `
90
+ + 'Use the full `\\\\host\\share\\...` form.',
91
+ };
92
+ }
93
+
77
94
  const reason = forbiddenReason(absolute);
78
95
  if (reason !== undefined) {
79
96
  return { ok: false, error: `refusing to recycle ${reason}: "${absolute}"` };
@@ -0,0 +1,642 @@
1
+ /**
2
+ * The overwrite guard: content destroyed without a delete verb.
3
+ *
4
+ * `guard.js` polices commands that *name* a delete. The 2026-11-14 incident named
5
+ * none: `Get-Content $f` … `Set-Content -LiteralPath $f` replaced a 605-line
6
+ * ledger with 24 lines, and every rule in `guard.js` was correctly silent —
7
+ * there was no delete verb, no erase API, no script file. What was destroyed was
8
+ * not a file but the file's *content*, in place, with no other copy anywhere.
9
+ *
10
+ * Two things follow from that, and they decide the shape of this module.
11
+ *
12
+ * 1. "Route it to the Recycle Bin" — the remedy every other rule ends with — is
13
+ * not available here. The target lived on a UNC share, and
14
+ * `scripts/recycle-bin.ps1` refuses those on purpose: `SHFileOperationW`
15
+ * erases there and reports success. So a rule of the form "recycle the old
16
+ * copy before the write" (proposed as R1 in the incident record) would have
17
+ * been a no-op exactly on the case that motivated it, and would still fail
18
+ * wherever the bin has no store. Prevention has to happen before the write,
19
+ * and recovery has to come from a copy the *command itself* makes.
20
+ *
21
+ * 2. The signal cannot be a verb list. Enumerating write verbs
22
+ * (`Set-Content`/`Out-File`/`Copy-Item -Force`/`>`/…) re-creates, one
23
+ * vocabulary later, the blind spot that made this incident invisible:
24
+ * `Export-Csv`, `[IO.File]::WriteAllText`, `sed -i`, `tee`, `dd of=`, `cp`,
25
+ * `truncate`, a compiler writing over its own output … any list is incomplete,
26
+ * and a guard that reads as complete but is not is worse than one that states
27
+ * its scope. So this module does not ask "is this a write verb?" and neither
28
+ * does it ask "did the file get smaller?" (see below). It asks two narrower
29
+ * questions whose answers are provable from the text.
30
+ *
31
+ * Rule 1 — in-place rewrite. The same file is read *and* written by one command:
32
+ * `Get-Content f | Set-Content f`, `sed -i f`, `cat f > f`. The new content is
33
+ * derived from the only copy, so a wrong slice, a wrong filter or a failing
34
+ * redirect leaves nothing to restore from. Refused unless the command itself
35
+ * makes a copy (`.bak`, a temp file it then verifies) — which is also the exact
36
+ * workflow the incident's own §6 recommends, so the safe spelling is allowed
37
+ * untouched.
38
+ *
39
+ * Rule 2 — unchecked slice endpoint. A range/slice whose endpoint is `<var> ± n`
40
+ * and whose variable is never checked for `$null`, in a command that also writes
41
+ * a file. In PowerShell `$lines[0..($null-2)]` is `$lines[0..-2]`, which is
42
+ * `$lines[0,-1,-2]`: first line plus the last two (measured on pwsh 7: a
43
+ * 10-element array yields `L1,L10,L9`). No error, no warning — a 605-line ledger
44
+ * becomes 3 kept lines, and the write then saves that.
45
+ *
46
+ * Both rules require the *write* half on purpose. A read-only command that slices
47
+ * wrongly prints wrong text — that is how the incident was noticed, and it loses
48
+ * nothing. Refusing it would cost the model a round trip and protect nothing, so
49
+ * a buggy slice with no write in the same command stays allowed.
50
+ *
51
+ * What this module deliberately does not do
52
+ * ----------------------------------------
53
+ * - No post-hoc size comparison. "Refuse the write if the file shrank" needs the
54
+ * old content to restore, and a `tools/post-execute` hook cannot roll anything
55
+ * back: `PostToolDecision.block` only turns the result into feedback, after the
56
+ * truncation already happened. Taking the copy up front needs the target set,
57
+ * which is the enumeration problem again; snapshotting a whole tree per shell
58
+ * call is O(workspace) — and would still miss the incident's file, which was on
59
+ * a UNC share outside every workspace root.
60
+ * - No I/O. Pure function of the command text, like `guard.js`, so it is unit
61
+ * testable and cannot fail halfway through a decision.
62
+ * - No `ask` decision. In an auto-approving deployment (this machine: approval
63
+ * policy `never`) `ask` resolves to allow in the same tick, which would make
64
+ * the rule look present and do nothing. Deny-with-a-recipe is the shape that
65
+ * stays honest whether or not a human is watching.
66
+ */
67
+
68
+ import { commandWord, statementTokens, unquote } from './shell-text.js';
69
+
70
+ /**
71
+ * Verbs that replace a file's content. Targets are read the same way
72
+ * `parseDeleteStatement` reads delete operands: `-Path` / `-LiteralPath` /
73
+ * `-FilePath` name the target, otherwise it is the first positional argument.
74
+ *
75
+ * `copy`/`move` are here because they destroy an existing destination; `tee`,
76
+ * `dd`, `truncate` cover the bash side. `dd` names its target as `of=`.
77
+ */
78
+ const WRITE_COMMANDS = new Set([
79
+ 'set-content',
80
+ 'clear-content',
81
+ 'out-file',
82
+ 'tee-object',
83
+ 'export-csv',
84
+ 'export-clixml',
85
+ 'set-item',
86
+ 'new-item',
87
+ 'copy-item',
88
+ 'move-item',
89
+ 'rename-item',
90
+ 'tee',
91
+ 'truncate',
92
+ 'cp',
93
+ 'copy',
94
+ 'mv',
95
+ 'move',
96
+ 'dd',
97
+ ]);
98
+
99
+ /**
100
+ * Flags whose *value* is the file being written.
101
+ * `-Destination`/`-NewName` are how `Copy-Item`/`Move-Item`/`Rename-Item` name
102
+ * the path that gets destroyed.
103
+ */
104
+ const WRITE_PATH_FLAGS = new Set([
105
+ '-path',
106
+ '-literalpath',
107
+ '-filepath',
108
+ '-pspath',
109
+ '-destination',
110
+ '-newname',
111
+ ]);
112
+
113
+ /**
114
+ * Flags that consume the next token as a value without it being a target.
115
+ * Without this, `Set-Content -Encoding UTF8 $f` would read `UTF8` as the file.
116
+ */
117
+ const WRITE_VALUE_FLAGS = new Set([
118
+ '-value',
119
+ '-encoding',
120
+ '-delimiter',
121
+ '-width',
122
+ '-inputobject',
123
+ '-stream',
124
+ '-filter',
125
+ '-include',
126
+ '-exclude',
127
+ '-credential',
128
+ '-erroraction',
129
+ '-ea',
130
+ '-errorvariable',
131
+ '-ev',
132
+ '-warningaction',
133
+ '-wa',
134
+ '-informationaction',
135
+ '-infa',
136
+ '-outbuffer',
137
+ '-ob',
138
+ '-outvariable',
139
+ '-ov',
140
+ '-pipelinevariable',
141
+ '-pv',
142
+ ]);
143
+
144
+ /**
145
+ * Verbs that read a file's content. `skip` counts leading positionals that are
146
+ * not paths (`grep <pattern> <file>`, `Select-String <pattern> <file>`,
147
+ * `awk <program> <file>`); `last` marks the tools whose *last* positional is the
148
+ * file (`sed 's/a/b/' <file>`).
149
+ */
150
+ const READ_COMMANDS = new Map([
151
+ ['get-content', { skip: 0 }],
152
+ ['gc', { skip: 0 }],
153
+ ['type', { skip: 0 }],
154
+ ['import-csv', { skip: 0 }],
155
+ ['import-clixml', { skip: 0 }],
156
+ ['select-string', { skip: 1 }],
157
+ ['cat', { skip: 0 }],
158
+ ['head', { skip: 0 }],
159
+ ['tail', { skip: 0 }],
160
+ ['more', { skip: 0 }],
161
+ ['less', { skip: 0 }],
162
+ ['grep', { skip: 1 }],
163
+ ['awk', { skip: 1 }],
164
+ ['sort', { skip: 0 }],
165
+ ['uniq', { skip: 0 }],
166
+ ['sed', { last: true }],
167
+ ['perl', { last: true }],
168
+ ]);
169
+
170
+ /**
171
+ * .NET content calls, read and write, matched by member name.
172
+ * `[IO.File]::WriteAllText(path, text)` destroys the old content;
173
+ * `::ReadAllText(path)` reads it. Argument 0 is the path in both.
174
+ */
175
+ const DOTNET_READ = /::\s*(?:ReadAllText|ReadAllLines|ReadAllBytes|OpenRead|OpenText)\s*\(\s*([^,)]+)/gi;
176
+ const DOTNET_WRITE = /::\s*(?:WriteAllText|WriteAllLines|WriteAllBytes|CreateText|Create|AppendAllText|AppendAllLines)\s*\(\s*([^,)]+)/gi;
177
+
178
+ /**
179
+ * A copy of the target made by the command itself, or a temp-then-replace step:
180
+ * either way the old content survives somewhere before the write. This is the
181
+ * escape hatch, and it is deliberately textual — the guard cannot run the
182
+ * command to find out.
183
+ */
184
+ const BACKUP_MARKER = /\.(?:bak|backup|orig|old)\b|(?:^|[\\/\s'"`-])bak[-_.\d]/i;
185
+ const TEMP_MARKER = /\$env:(?:TEMP|TMP)\b|%TEMP%|%TMP%|New-TemporaryFile|\/tmp\/|[\\/]Temp[\\/]/i;
186
+
187
+ /**
188
+ * Slice endpoints whose value can be `$null` and which are then offset by
189
+ * arithmetic: `$idx - 2`. The `±` is what makes the failure silent rather than
190
+ * loud — `$null` itself indexes the last element, it does not throw.
191
+ */
192
+ const OFFSET_ENDPOINT = /\$\{?([A-Za-z_][\w:]*)\}?\s*[-+]\s*\d/;
193
+
194
+ /** The same hazard in the parameter forms that take a count. */
195
+ const COUNT_ARG =
196
+ /(?:-first|-skip|-last|\.substring\s*\(|\.remove\s*\()\s*\(?\s*\$\{?([A-Za-z_][\w:]*)\}?\s*[-+]/gi;
197
+
198
+ /** `.Count` / `Measure-Object` are 0 for an empty result, never `$null`. */
199
+ const SAFE_PROVENANCE = /\.count\b|\bmeasure-object\b|^\s*-?\d+\s*$/i;
200
+
201
+ /**
202
+ * Normalize a path for comparison: separators, case, trailing separator.
203
+ * Windows paths are case-insensitive, so `C:\Tmp\A.md` and `c:/tmp/a.md` are the
204
+ * same file and must compare equal, or the rule misses the plainest spelling.
205
+ * @param p - the path text.
206
+ * @returns the comparison key.
207
+ */
208
+ function pathKey(p) {
209
+ return p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
210
+ }
211
+
212
+ /**
213
+ * Remove the grouping punctuation a statement's own wrapper leaves on an operand:
214
+ * `(Get-Content $f)` tokenizes to `['(Get-Content', '$f)']`, and `$f)` is the same
215
+ * file as `$f`. Without this the read side is unkeyed and a piped in-place rewrite
216
+ * — the commonest spelling of the hazard — goes unseen.
217
+ *
218
+ * @param expr - the operand as written.
219
+ * @returns the operand without leading/trailing brackets.
220
+ */
221
+ function cleanOperand(expr) {
222
+ let t = String(expr ?? '').trim();
223
+ for (let i = 0; i < 2; i += 1) {
224
+ t = t.replace(/^[({\[]+/, '').replace(/[)}\]]+$/, '');
225
+ }
226
+ return t;
227
+ }
228
+
229
+ /**
230
+ * The comparison keys for one operand expression.
231
+ *
232
+ * A variable contributes two keys — its own name, and (when the command itself
233
+ * assigns it a literal) the path it holds — so `Get-Content $f` matches both
234
+ * `Set-Content $f` and `Set-Content 'C:\x\a.md'`. An interpolated string
235
+ * (`"$f.bak"`) contributes none: its value is not knowable here, and a wrong
236
+ * match would name a file the command never touches.
237
+ *
238
+ * @param expr - the operand as written.
239
+ * @param literals - variable name → literal path, from this command's assignments.
240
+ * @returns the keys, possibly empty.
241
+ */
242
+ function exprKeys(expr, literals) {
243
+ const t = cleanOperand(unquote(String(expr ?? '').trim()));
244
+ if (t.length === 0) return [];
245
+ const variable = /^\$\{?([A-Za-z_][\w:]*)\}?$/.exec(t);
246
+ if (variable !== null) {
247
+ const name = variable[1].toLowerCase();
248
+ const keys = [`var:${name}`];
249
+ const literal = literals.get(name);
250
+ if (literal !== undefined) keys.push(`lit:${pathKey(literal)}`);
251
+ return keys;
252
+ }
253
+ if (t.includes('$') || t.includes('%')) return [];
254
+ return [`lit:${pathKey(t)}`];
255
+ }
256
+
257
+ /**
258
+ * Record `$v = <literal>` assignments, which is how a command usually names the
259
+ * file it is about to destroy (`$f = '…\台账.md'`; `Set-Content -LiteralPath $f`).
260
+ *
261
+ * Only single-literal right-hand sides are recorded. Anything else stays
262
+ * unresolved — the operand key then remains `var:<name>`, which still matches the
263
+ * read side when both sides use the same variable, and that is the common case.
264
+ *
265
+ * @param statements - the statements of one command.
266
+ * @returns variable name → literal text.
267
+ */
268
+ function collectLiterals(statements) {
269
+ const literals = new Map();
270
+ for (const statement of statements) {
271
+ const assign = /^\s*\$\{?([A-Za-z_][\w:]*)\}?\s*=\s*(.+?)\s*$/.exec(statement);
272
+ if (assign === null) continue;
273
+ const name = assign[1].toLowerCase();
274
+ const value = unquote(assign[2]);
275
+ if (value.length === 0 || value.includes('$')) continue;
276
+ if (/[;(){}|]/.test(value)) continue;
277
+ literals.set(name, value);
278
+ }
279
+ return literals;
280
+ }
281
+
282
+ /**
283
+ * Record how a variable's value was produced, for the `$null` question.
284
+ *
285
+ * `$idx = (… | Select-Object -First 1).LineNumber` is `$null` when the pattern
286
+ * matches nothing; `$n = $lines.Count` is `0`. Only the second is safe to offset.
287
+ * Anything not visible in the command counts as unproven — the guard refuses what
288
+ * it cannot check, and this rule additionally requires a file write in the same
289
+ * command, so "unproven" is affordable here.
290
+ *
291
+ * @param statements - the statements of one command.
292
+ * @returns variable name → whether its provenance proves a non-null value.
293
+ */
294
+ function collectProvenance(statements) {
295
+ const safe = new Map();
296
+ for (const statement of statements) {
297
+ const assign = /^\s*\$\{?([A-Za-z_][\w:]*)\}?\s*=\s*(.+?)\s*$/.exec(statement);
298
+ if (assign === null) continue;
299
+ const name = assign[1].toLowerCase();
300
+ const provenSafe = SAFE_PROVENANCE.test(assign[2]);
301
+ // Any unsafe assignment outweighs a safe one: the loop may take either path.
302
+ safe.set(name, provenSafe && (safe.get(name) ?? true));
303
+ }
304
+ return safe;
305
+ }
306
+
307
+ /**
308
+ * Split a token that carries a `>` redirect into the part before it and the target
309
+ * after it: `f.txt>f.txt` → `{ before: 'f.txt', after: 'f.txt' }`, `2>$null` →
310
+ * `{ before: '', after: '$null' }`, `>out.md` → `{ before: '', after: 'out.md' }`.
311
+ *
312
+ * `>>` (append) never matches — the character class cannot span two `>`s — which
313
+ * is the desired outcome: an append destroys nothing.
314
+ *
315
+ * @param tok - one token.
316
+ * @returns the split, or `undefined` when the token carries no redirect.
317
+ */
318
+ function splitRedirect(tok) {
319
+ const match = /^([^\s>]*)>([^\s>]*)$/.exec(tok);
320
+ if (match === null) return undefined;
321
+ const before = /^(?:\d+|\*)$/.test(match[1]) ? '' : match[1];
322
+ return { before, after: match[2] };
323
+ }
324
+
325
+ /**
326
+ * The file expressions one statement writes.
327
+ *
328
+ * `Add-Content` never appears here: it is the one write that does not replace
329
+ * anything. `Set-Content -Append` and `>>` are treated the same way. Writing to
330
+ * the null device (`$null`, `NUL`, `/dev/null`) is still collected here and
331
+ * discarded by the caller, because that decision belongs with the comparison, not
332
+ * with the parsing.
333
+ *
334
+ * @param statement - one statement.
335
+ * @returns the operands being written.
336
+ */
337
+ function writtenTargets(statement) {
338
+ const tokens = statementTokens(statement);
339
+ if (tokens.length === 0) return [];
340
+ const targets = [];
341
+
342
+ // Redirection: `> f`, `>f`, `f>f`, `2> f`. `>>` appends, so it is not a rewrite;
343
+ // `splitRedirect` cannot span two `>`s, which is what makes that automatic.
344
+ for (let i = 0; i < tokens.length; i += 1) {
345
+ const tok = tokens[i];
346
+ if (tok === '>') {
347
+ if (tokens[i + 1] !== undefined) targets.push(tokens[i + 1]);
348
+ continue;
349
+ }
350
+ const redirect = splitRedirect(tok);
351
+ if (redirect !== undefined && redirect.after.length > 0) targets.push(redirect.after);
352
+ }
353
+
354
+ const verb = commandWord(statement).toLowerCase().replace(/\.(?:exe|cmd|bat)$/, '');
355
+ if (verb === 'dd') {
356
+ for (const tok of tokens) {
357
+ const of = /^of=(.+)$/i.exec(tok);
358
+ if (of !== null) targets.push(of[1]);
359
+ }
360
+ return targets;
361
+ }
362
+
363
+ // In-place editors: `sed -i`, `sed -i.bak`, `perl -pi`, `perl -i`. The file is
364
+ // read and rewritten in one step by definition, which is rule 1's exact shape.
365
+ if (verb === 'sed' || verb === 'perl') {
366
+ if (tokens.some((t) => /^-[a-z]*i/.test(t))) {
367
+ const positionals = argumentsOf(tokens);
368
+ if (positionals.length > 0) targets.push(positionals[positionals.length - 1]);
369
+ }
370
+ return targets;
371
+ }
372
+
373
+ if (!WRITE_COMMANDS.has(verb)) return targets;
374
+
375
+ // `Set-Content -Append` / `Export-Csv -Append` add to the file instead of
376
+ // truncating it, so the statement is not a rewrite.
377
+ if (tokens.some((t) => /^-append$/i.test(t))) return targets;
378
+
379
+ // For copy/move/rename the *source* is read, not written: only the destination
380
+ // is replaced. Treating `-LiteralPath` as a write target here made
381
+ // `Get-Content $f …; Copy-Item -LiteralPath $f -Destination $g` look like an
382
+ // in-place rewrite of `$f`.
383
+ const isCopy = verb === 'copy-item' || verb === 'move-item' || verb === 'rename-item'
384
+ || verb === 'copy' || verb === 'cp' || verb === 'mv' || verb === 'move';
385
+ if (isCopy) {
386
+ for (let i = 1; i < tokens.length; i += 1) {
387
+ const flag = tokens[i].toLowerCase();
388
+ if ((flag === '-destination' || flag === '-newname') && tokens[i + 1] !== undefined) {
389
+ targets.push(tokens[i + 1]);
390
+ i += 1;
391
+ }
392
+ }
393
+ const positionals = argumentsOf(tokens);
394
+ if (positionals.length > 0) targets.push(positionals[positionals.length - 1]);
395
+ return targets;
396
+ }
397
+
398
+ const positionals = argumentsOf(tokens);
399
+ if (positionals.length > 0) targets.push(positionals[0]);
400
+ return targets;
401
+ }
402
+
403
+ /**
404
+ * The positional arguments of one statement's command, with flag values consumed
405
+ * and redirection tokens dropped.
406
+ *
407
+ * Both halves matter for a false positive: `sed 's/a/b/' a.txt > b.txt` has `b.txt`
408
+ * as a *destination*, not an argument, and counting it as a positional made the
409
+ * `sed` reader claim it was writing the file it reads (`{ last: true }`).
410
+ *
411
+ * @param tokens - the statement's tokens, command word first.
412
+ * @returns the positional arguments.
413
+ */
414
+ function argumentsOf(tokens) {
415
+ const positionals = [];
416
+ for (let i = 1; i < tokens.length; i += 1) {
417
+ const tok = tokens[i];
418
+ if (tok === '>') {
419
+ i += 1;
420
+ continue;
421
+ }
422
+ const redirect = splitRedirect(tok);
423
+ if (redirect !== undefined) {
424
+ // `cat f.txt>f.txt` reads and truncates the same file in one token, which is
425
+ // the plainest form of the hazard: the operand before the `>` is an argument.
426
+ if (redirect.before.length > 0) positionals.push(redirect.before);
427
+ continue;
428
+ }
429
+ if (tok.startsWith('-')) {
430
+ const flag = tok.toLowerCase();
431
+ if (WRITE_PATH_FLAGS.has(flag) && tokens[i + 1] !== undefined) {
432
+ positionals.push(tokens[i + 1]);
433
+ i += 1;
434
+ continue;
435
+ }
436
+ if (WRITE_VALUE_FLAGS.has(flag) && tokens[i + 1] !== undefined) {
437
+ i += 1;
438
+ continue;
439
+ }
440
+ continue;
441
+ }
442
+ positionals.push(tok);
443
+ }
444
+ return positionals;
445
+ }
446
+
447
+ /**
448
+ * The file expressions one statement reads.
449
+ * @param statement - one statement.
450
+ * @returns the operands being read.
451
+ */
452
+ function readTargets(statement) {
453
+ const tokens = statementTokens(statement);
454
+ if (tokens.length === 0) return [];
455
+ const verb = commandWord(statement).toLowerCase().replace(/\.(?:exe|cmd|bat)$/, '');
456
+ const spec = READ_COMMANDS.get(verb);
457
+ if (spec === undefined) return [];
458
+
459
+ const positionals = argumentsOf(tokens);
460
+ if (spec.last === true) {
461
+ return positionals.length > 0 ? [positionals[positionals.length - 1]] : [];
462
+ }
463
+ return positionals.slice(spec.skip ?? 0);
464
+ }
465
+
466
+ /**
467
+ * Whether the command makes its own copy of what it is about to overwrite.
468
+ *
469
+ * Two spellings count, and both are what the incident's §6 safe pattern looks
470
+ * like: a `.bak`-style destination, or a temp file that is then copied/moved over
471
+ * the original. A bare mention of `$env:TEMP` is not enough — a command that
472
+ * reads one temp file and writes another would otherwise be exempted.
473
+ *
474
+ * @param command - the full command text.
475
+ * @returns whether a backup or verified-temp step is present.
476
+ */
477
+ function hasCopyStep(command) {
478
+ if (BACKUP_MARKER.test(command)) return true;
479
+ return TEMP_MARKER.test(command) && /\b(?:Copy-Item|Move-Item|cp|mv|move)\b/i.test(command);
480
+ }
481
+
482
+ /**
483
+ * Rule 1: is this command reading and rewriting the same file?
484
+ *
485
+ * @param command - the full command text.
486
+ * @param statements - the statements of the command.
487
+ * @param dialect - `pwsh` or `bash`, for the recipe in the message.
488
+ * @returns the refusal, or `undefined`.
489
+ */
490
+ function inPlaceRewrite(command, statements, dialect) {
491
+ if (hasCopyStep(command)) return undefined;
492
+
493
+ const literals = collectLiterals(statements);
494
+ const written = new Map();
495
+ const read = new Map();
496
+
497
+ for (const statement of statements) {
498
+ for (const expr of writtenTargets(statement)) {
499
+ for (const key of exprKeys(expr, literals)) {
500
+ if (!written.has(key)) written.set(key, expr);
501
+ }
502
+ }
503
+ for (const expr of readTargets(statement)) {
504
+ for (const key of exprKeys(expr, literals)) {
505
+ if (!read.has(key)) read.set(key, expr);
506
+ }
507
+ }
508
+ }
509
+
510
+ // .NET content calls are not shell verbs, so `statementTokens` never sees them;
511
+ // they name the file as their first argument and are the other way to rewrite a
512
+ // file from its own bytes ([IO.File]::ReadAllText → ::WriteAllText).
513
+ for (const match of command.matchAll(DOTNET_WRITE)) {
514
+ for (const key of exprKeys(match[1], literals)) {
515
+ if (!written.has(key)) written.set(key, match[1]);
516
+ }
517
+ }
518
+ for (const match of command.matchAll(DOTNET_READ)) {
519
+ for (const key of exprKeys(match[1], literals)) {
520
+ if (!read.has(key)) read.set(key, match[1]);
521
+ }
522
+ }
523
+
524
+ for (const [key, writtenExpr] of written) {
525
+ // The null device is plumbing, not a file.
526
+ if (/^(?:lit:)?(?:\$null|nul|\/dev\/null)$/i.test(key)) continue;
527
+ if (!read.has(key)) continue;
528
+
529
+ const shown = unquote(String(writtenExpr));
530
+ const backup = dialect === 'bash'
531
+ ? `cp "${shown}" "${shown}.bak-$(date +%Y%m%d-%H%M%S)"`
532
+ : `Copy-Item -LiteralPath "${shown}" -Destination "${shown}.bak-$(Get-Date -f yyyyMMdd-HHmmss)"`;
533
+ return {
534
+ kind: 'in-place-rewrite',
535
+ reason:
536
+ `The recycle-bin guard blocked this command: it reads "${shown}" and then overwrites that same file, ` +
537
+ 'so the new content is derived from the only copy. If the read, the slice or the pipeline is wrong, ' +
538
+ 'the original is gone — there is nothing to restore from, and a network share has no Recycle Bin.\n\n' +
539
+ `Do this instead (the copy step is what makes the write undoable):\n` +
540
+ ` 1. ${backup}\n` +
541
+ ' 2. write the new text to a temp file\n' +
542
+ ' 3. check it (line count or first/last line), then copy it over the original\n\n' +
543
+ 'For a find-and-replace on a document, the `edit` tool is safer than rewriting the whole file from a shell. ' +
544
+ 'For a rewrite that already copies the file to `<name>.bak-<timestamp>` first, re-run unchanged — that step is accepted.',
545
+ };
546
+ }
547
+ return undefined;
548
+ }
549
+
550
+ /**
551
+ * Rule 2: does an unchecked, offset slice endpoint feed a file write in the same
552
+ * command?
553
+ *
554
+ * @param command - the full command text.
555
+ * @param statements - the statements of the command.
556
+ * @returns the refusal, or `undefined`.
557
+ */
558
+ function uncheckedSlice(command, statements) {
559
+ // The write half is what turns a wrong slice into lost data. Without it the
560
+ // command prints the wrong lines and the file survives, so it stays allowed.
561
+ const writes = statements.some((s) => writtenTargets(s).length > 0);
562
+ if (!writes) return undefined;
563
+
564
+ const variables = new Set();
565
+ for (const match of command.matchAll(/\[([^[\]\n]{0,160}?\.\.[^[\]\n]{0,160}?)\]/g)) {
566
+ const endpoint = OFFSET_ENDPOINT.exec(match[1]);
567
+ if (endpoint === null) continue;
568
+ // `$lines[0..($lines.Count-1)]` cannot be null: Count is 0 for an empty array.
569
+ if (/\.count\b/i.test(match[1])) continue;
570
+ variables.add(endpoint[1].toLowerCase());
571
+ }
572
+ for (const match of command.matchAll(COUNT_ARG)) {
573
+ variables.add(match[1].toLowerCase());
574
+ }
575
+ if (variables.size === 0) return undefined;
576
+
577
+ // An assertion anywhere in the command clears the variable: the incident's own
578
+ // fix is one line, so the rule accepts it wherever it appears.
579
+ const provenance = collectProvenance(statements);
580
+ let offender;
581
+ for (const name of variables) {
582
+ if (provenance.get(name) === true) continue;
583
+ if (isAsserted(command, name)) continue;
584
+ offender = name;
585
+ break;
586
+ }
587
+ if (offender === undefined) return undefined;
588
+
589
+ return {
590
+ kind: 'slice-risk',
591
+ reason:
592
+ `The recycle-bin guard blocked this command: \`$${offender}\` is offset by arithmetic in a slice endpoint, ` +
593
+ 'it is never checked for $null, and the same command writes a file. In PowerShell a null offset is not an ' +
594
+ 'error — `$lines[0..($null-2)]` is `$lines[0..-2]`, i.e. `$lines[0,-1,-2]`, the first line and the last two — ' +
595
+ 'so a 605-line file can be saved over as 24 lines with no warning anywhere.\n\n' +
596
+ `Fix, then re-run: if (-not $${offender}) { throw "anchor not found" }\n` +
597
+ `Or compute the endpoint from a proven value (e.g. \`$lines.Count\`) instead of an unchecked match index. ` +
598
+ 'For the write itself, copy the original to `<name>.bak-<timestamp>` first, write a temp file, verify it, then replace.',
599
+ };
600
+ }
601
+
602
+ /**
603
+ * Whether the command proves a variable is not `$null` before using it.
604
+ * @param command - the full command text.
605
+ * @param name - the lower-cased variable name.
606
+ * @returns whether an assertion on that variable is present.
607
+ */
608
+ function isAsserted(command, name) {
609
+ const v = `\\$${name}\\b`;
610
+ const patterns = [
611
+ `${v}\\s*-\\s*(?:eq|ne|lt|le|gt|ge)\\s*\\$null`,
612
+ `\\$null\\s*-\\s*(?:eq|ne|lt|le)\\s*${v}`,
613
+ `${v}\\s*-(?:eq|le)\\s*(?:0|''|"")`,
614
+ `${v}\\s*\\?\\?`,
615
+ `if\\s*\\(\\s*!\\s*${v}`,
616
+ `if\\s*\\(\\s*-\\s*not\\s*\\(?\\s*${v}`,
617
+ `if\\s*\\(\\s*${v}\\s*\\)`,
618
+ ];
619
+ return patterns.some((p) => new RegExp(p, 'i').test(command));
620
+ }
621
+
622
+ /**
623
+ * Classify a command for content-destroying writes.
624
+ *
625
+ * @param command - the full command text.
626
+ * @param options - `statements` (already split, including decoded bodies) and
627
+ * `dialect` (`pwsh` or `bash`).
628
+ * @returns `{ kind, reason }` when the command must be refused, else `undefined`.
629
+ */
630
+ export function analyzeOverwriteRisk(command, options = {}) {
631
+ const { statements = [], dialect = 'pwsh' } = options;
632
+ if (typeof command !== 'string' || command.trim().length === 0) return undefined;
633
+ if (statements.length === 0) return undefined;
634
+
635
+ // The slice rule is judged first: its message names the actual mistake and the
636
+ // one-line fix, which is far more useful than the general "you are rewriting in
637
+ // place" note when both apply (the incident had both).
638
+ const slice = uncheckedSlice(command, statements);
639
+ if (slice !== undefined) return slice;
640
+
641
+ return inPlaceRewrite(command, statements, dialect);
642
+ }