dsh-delete-guard 2.4.1 → 2.4.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/CHANGELOG.md +174 -0
- package/README.en.md +27 -31
- package/README.ja.md +16 -16
- package/README.md +35 -39
- package/SECURITY.md +87 -0
- package/lib/guard.js +204 -19
- package/lib/index.js +90 -0
- package/lib/rewrite-guard.js +313 -30
- package/lib/staging.js +9 -1
- package/package.json +1 -1
- package/scripts/recycle-bin.ps1 +185 -6
- package/scripts/verify-readme-structure.mjs +90 -0
package/lib/rewrite-guard.js
CHANGED
|
@@ -153,7 +153,12 @@ const READ_COMMANDS = new Map([
|
|
|
153
153
|
['type', { skip: 0 }],
|
|
154
154
|
['import-csv', { skip: 0 }],
|
|
155
155
|
['import-clixml', { skip: 0 }],
|
|
156
|
-
|
|
156
|
+
// `Select-String <pattern> <file>`: the pattern is the first positional. But the
|
|
157
|
+
// commonest spelling names the file with `-Path`, and `argumentsOf` already lifted
|
|
158
|
+
// that value into the positional list — so `skip: 1` ate the path and
|
|
159
|
+
// `Select-String -Path a.md -Pattern x | Set-Content a.md` was allowed
|
|
160
|
+
// (measured 2026-11-25). Matching the path flag explicitly avoids that.
|
|
161
|
+
['select-string', { skip: 0, pathFlag: true }],
|
|
157
162
|
['cat', { skip: 0 }],
|
|
158
163
|
['head', { skip: 0 }],
|
|
159
164
|
['tail', { skip: 0 }],
|
|
@@ -180,10 +185,33 @@ const DOTNET_WRITE = /::\s*(?:WriteAllText|WriteAllLines|WriteAllBytes|CreateTex
|
|
|
180
185
|
* either way the old content survives somewhere before the write. This is the
|
|
181
186
|
* escape hatch, and it is deliberately textual — the guard cannot run the
|
|
182
187
|
* command to find out.
|
|
188
|
+
*
|
|
189
|
+
* Note: these are only consulted **per statement and before the overwrite** (see
|
|
190
|
+
* `hasCopyStepFor`). A bare textual hit anywhere in the command is not evidence —
|
|
191
|
+
* a trailing comment or a bystander string used to be enough to exempt a real
|
|
192
|
+
* in-place rewrite.
|
|
183
193
|
*/
|
|
184
194
|
const BACKUP_MARKER = /\.(?:bak|backup|orig|old)\b|(?:^|[\\/\s'"`-])bak[-_.\d]/i;
|
|
185
195
|
const TEMP_MARKER = /\$env:(?:TEMP|TMP)\b|%TEMP%|%TMP%|New-TemporaryFile|\/tmp\/|[\\/]Temp[\\/]/i;
|
|
186
196
|
|
|
197
|
+
/**
|
|
198
|
+
* A statement that writes somewhere: a write verb, a copy verb, or a redirect.
|
|
199
|
+
* Used together with {@link BACKUP_MARKER} / {@link TEMP_MARKER} to decide whether
|
|
200
|
+
* a statement is the copy step itself rather than merely mentioning a backup name.
|
|
201
|
+
*/
|
|
202
|
+
const COPY_DESTINATION =
|
|
203
|
+
/\b(?:Set-Content|Out-File|Add-Content|Tee-Object|Copy-Item|Move-Item|cp|mv|move|New-Item)\b|>{1}(?!>)/i;
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Read verbs, matched **anywhere inside a statement**, not just as its first word.
|
|
207
|
+
*
|
|
208
|
+
* `Set-Content $f (Get-Content $f | Select-Object -First 10)` reads and truncates
|
|
209
|
+
* `$f` in one line — the most compact spelling of the 2026-11-14 incident. Until
|
|
210
|
+
* 2026-11-25 `readTargets` only looked at the statement's head, so every such form
|
|
211
|
+
* was allowed (four measured variants, all `allow`).
|
|
212
|
+
*/
|
|
213
|
+
const NESTED_READ = /\b(?:Get-Content|ReadAllText|ReadAllLines|ReadAllBytes|Import-Csv|Import-Clixml|Select-String|Get-Item|OpenText|OpenRead)\s*\(?\s*([^\s)|,;]+)/gi;
|
|
214
|
+
|
|
187
215
|
/**
|
|
188
216
|
* Slice endpoints whose value can be `$null` and which are then offset by
|
|
189
217
|
* arithmetic: `$idx - 2`. The `±` is what makes the failure silent rather than
|
|
@@ -446,37 +474,260 @@ function argumentsOf(tokens) {
|
|
|
446
474
|
|
|
447
475
|
/**
|
|
448
476
|
* The file expressions one statement reads.
|
|
477
|
+
*
|
|
478
|
+
* Two sources, and the second is the one that closes a hole:
|
|
479
|
+
*
|
|
480
|
+
* - the statement's **head** verb, when it is a reader (`Get-Content $f`);
|
|
481
|
+
* - a reader **nested inside** a write statement
|
|
482
|
+
* (`Set-Content $f (Get-Content $f | Select-Object -First 10)`).
|
|
483
|
+
*
|
|
484
|
+
* Until 2026-11-25 only the first was checked, so a read folded into the write
|
|
485
|
+
* was invisible and the whole in-place rewrite was allowed. That spelling is the
|
|
486
|
+
* most compact form of the incident this rule exists for, so it is not a corner
|
|
487
|
+
* case — it is the hazard with fewer keystrokes.
|
|
488
|
+
*
|
|
449
489
|
* @param statement - one statement.
|
|
450
490
|
* @returns the operands being read.
|
|
451
491
|
*/
|
|
452
492
|
function readTargets(statement) {
|
|
493
|
+
const out = [];
|
|
453
494
|
const tokens = statementTokens(statement);
|
|
454
|
-
|
|
455
|
-
|
|
495
|
+
const verb = tokens.length > 0
|
|
496
|
+
? commandWord(statement).toLowerCase().replace(/\.(?:exe|cmd|bat)$/, '')
|
|
497
|
+
: '';
|
|
456
498
|
const spec = READ_COMMANDS.get(verb);
|
|
457
|
-
if (spec === undefined) return [];
|
|
458
499
|
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
500
|
+
if (spec !== undefined) {
|
|
501
|
+
const positionals = argumentsOf(tokens);
|
|
502
|
+
// `Select-String` names its file with `-Path`, which `argumentsOf` already lifted
|
|
503
|
+
// into the positionals — so a plain `skip: N` would drop it. The pattern then
|
|
504
|
+
// reads as a file name and the real target is never compared.
|
|
505
|
+
if (spec.pathFlag === true) {
|
|
506
|
+
out.push(...positionals);
|
|
507
|
+
} else if (spec.last === true) {
|
|
508
|
+
if (positionals.length > 0) out.push(positionals[positionals.length - 1]);
|
|
509
|
+
} else {
|
|
510
|
+
out.push(...positionals.slice(spec.skip ?? 0));
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// Nested readers. Only when the statement is not already a reader itself —
|
|
515
|
+
// otherwise the head scan above already covered the file, and re-running this
|
|
516
|
+
// would duplicate operands (harmless, but it makes the maps noisier than needed).
|
|
517
|
+
if (spec === undefined) {
|
|
518
|
+
for (const match of statement.matchAll(NESTED_READ)) {
|
|
519
|
+
const operand = cleanOperand(match[1]);
|
|
520
|
+
if (operand.length > 0 && !/^[-)]/.test(operand)) out.push(operand);
|
|
521
|
+
}
|
|
462
522
|
}
|
|
463
|
-
|
|
523
|
+
|
|
524
|
+
return out;
|
|
464
525
|
}
|
|
465
526
|
|
|
466
527
|
/**
|
|
467
528
|
* Whether the command makes its own copy of what it is about to overwrite.
|
|
468
529
|
*
|
|
469
|
-
*
|
|
470
|
-
*
|
|
471
|
-
*
|
|
472
|
-
*
|
|
530
|
+
* **Statement-level, not textual.** The previous version short-circuited on
|
|
531
|
+
* `BACKUP_MARKER.test(command)`, so any of these was exempted while truly
|
|
532
|
+
* rewriting a file from its only copy (measured 2026-11-25, all three allowed):
|
|
533
|
+
*
|
|
534
|
+
* Set-Content $f $t # no .bak needed here ← marker in a comment
|
|
535
|
+
* $f='a.md.bak'; Set-Content $f $t ← marker in the TARGET name
|
|
536
|
+
* $note='.bak is for wimps'; Set-Content a.md $f ← marker in a bystander string
|
|
537
|
+
*
|
|
538
|
+
* A copy step has to be an actual write to a *different* path that derives from
|
|
539
|
+
* the item itself, and it has to happen before the overwrite. Three conditions,
|
|
540
|
+
* all decidable from the statement list:
|
|
541
|
+
*
|
|
542
|
+
* 1. a statement writes `<target>.bak*` / `<target>.tmp*` / `.new` / `.orig` …
|
|
543
|
+
* 2. that statement comes **before** the target's last write
|
|
544
|
+
* 3. the copy path is not the target path itself
|
|
545
|
+
*
|
|
546
|
+
* @param statements - the statements of the command.
|
|
547
|
+
* @param literals - variable name → literal path, from this command's assignments.
|
|
548
|
+
* @param targetKeys - the comparison keys of the file being overwritten.
|
|
549
|
+
* @param targetIndex - the statement index of the last write to that file.
|
|
550
|
+
* @returns whether a real copy step precedes the overwrite.
|
|
551
|
+
*/
|
|
552
|
+
function hasCopyStepFor(statements, literals, targetKeys, targetIndex) {
|
|
553
|
+
// Build the target matchers once per call rather than once per statement: this
|
|
554
|
+
// runs on every command that reads and rewrites a file, and constructing regexes
|
|
555
|
+
// in a loop was measurable (2026-11-25: ~17 µs of added cost on 6,000 commands).
|
|
556
|
+
const targetMatchers = [];
|
|
557
|
+
for (const key of targetKeys) {
|
|
558
|
+
if (!key.startsWith('lit:')) continue;
|
|
559
|
+
const t = key.slice(4);
|
|
560
|
+
const esc = t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
561
|
+
targetMatchers.push({
|
|
562
|
+
bare: new RegExp(`(?:^|[\\\\/\\s"'\`])${esc}(?![.\\w-])`, 'i'),
|
|
563
|
+
suffixed: new RegExp(`${esc}[._-](?:bak|backup|orig|old|tmp|new)`, 'i'),
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
for (let i = 0; i <= targetIndex && i < statements.length; i += 1) {
|
|
568
|
+
const statement = statements[i];
|
|
569
|
+
|
|
570
|
+
// `sed -i.bak` / `perl -pi.bak`: the editor makes the backup itself, in the
|
|
571
|
+
// same statement as the write. The suffix is the copy, so it counts — and this
|
|
572
|
+
// is the one case where the copy is not a separate, earlier statement.
|
|
573
|
+
if (/\b(?:sed|perl)\b[^\n;&|]*\s-[a-z]*i[._-](?:bak|backup|orig|old)\b/i.test(statement)) return true;
|
|
574
|
+
|
|
575
|
+
// Every other copy step has to come strictly BEFORE the overwrite: a backup
|
|
576
|
+
// taken afterwards preserves the already-destroyed content.
|
|
577
|
+
if (i >= targetIndex) continue;
|
|
578
|
+
|
|
579
|
+
const tokenText = statementTokens(statement).join(' ');
|
|
580
|
+
|
|
581
|
+
// A copy/temp destination in this statement, on the text level, is necessary
|
|
582
|
+
// but not sufficient: it also has to be a distinct path derived from the target.
|
|
583
|
+
if (!COPY_DESTINATION.test(tokenText)) continue;
|
|
584
|
+
|
|
585
|
+
// Condition 3: the copy must not be the target itself.
|
|
586
|
+
const samePath = targetMatchers.some((m) => m.bare.test(tokenText) && !m.suffixed.test(tokenText));
|
|
587
|
+
if (samePath) continue;
|
|
588
|
+
|
|
589
|
+
// Any distinct backup/temp destination that this statement writes counts.
|
|
590
|
+
if (BACKUP_MARKER.test(tokenText) || TEMP_MARKER.test(tokenText)) return true;
|
|
591
|
+
}
|
|
592
|
+
return false;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Whether the command repeats statements in a way that makes textual order
|
|
597
|
+
* unreliable: a read after a write may feed the *next* iteration's write.
|
|
598
|
+
*
|
|
599
|
+
* The previous gate only listed `for`/`foreach`/`while`, which misses the
|
|
600
|
+
* commonest PowerShell spellings — `%` (ForEach-Object), `do`/`until`, `switch`,
|
|
601
|
+
* and `.ForEach(`. Measured: `$fs | % { Set-Content $_ $c; $c = Get-Content $_ }`
|
|
602
|
+
* was not gated.
|
|
603
|
+
*
|
|
604
|
+
* The keyword must be in **command or pipeline position**, not merely present:
|
|
605
|
+
* `python -c "for i,l in enumerate(...)"` is a Python loop in a string, and
|
|
606
|
+
* treating it as a shell loop kept a legitimate command refused.
|
|
473
607
|
*
|
|
474
608
|
* @param command - the full command text.
|
|
475
|
-
* @
|
|
609
|
+
* @param statements - the statements of the command.
|
|
610
|
+
* @returns whether any repetition construct is present in executable position.
|
|
476
611
|
*/
|
|
477
|
-
function
|
|
478
|
-
|
|
479
|
-
|
|
612
|
+
function hasRepetition(command, statements) {
|
|
613
|
+
for (const statement of statements) {
|
|
614
|
+
const word = commandWord(statement).toLowerCase();
|
|
615
|
+
if (/^(?:for|foreach|while|do|until|switch|%|foreach-object)$/.test(word)) return true;
|
|
616
|
+
// `1..3 | % { … }` and `$x | ForEach-Object { … }`: the loop verb sits after a pipe.
|
|
617
|
+
if (/(?:^|\|)\s*(?:%|foreach-object)\b/i.test(statement)) return true;
|
|
618
|
+
if (/\.\s*foreach\s*\(/i.test(statement)) return true;
|
|
619
|
+
}
|
|
620
|
+
// `for(`/`foreach(` glued to a paren never tokenizes as a bare word.
|
|
621
|
+
if (/(?:^|[;|&\n])\s*(?:for|foreach|while|switch)\s*\(/i.test(command)) return true;
|
|
622
|
+
return false;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* Whether this command pins the text encoding on **both** sides of the rewrite.
|
|
627
|
+
*
|
|
628
|
+
* A byte-level hazard that the shape rules cannot see: `Get-Content -Raw` on a GBK
|
|
629
|
+
* or UTF-16 document decodes it with the wrong code page, and `WriteAllText` then
|
|
630
|
+
* writes the mojibake back as UTF-8. Nothing in the command is "wrong" — a plain
|
|
631
|
+
* `.Replace` of an ASCII needle passes every count check — and the CJK content is
|
|
632
|
+
* destroyed. Measured 2026-11-25: with an ASCII needle the occurrence check passes
|
|
633
|
+
* and every CJK character becomes U+FFFD.
|
|
634
|
+
*
|
|
635
|
+
* A single, bounded substitution with both encodings stated is equivalent to the
|
|
636
|
+
* `edit` tool: it changes the matched substring, leaves the rest byte-identical,
|
|
637
|
+
* and cannot re-encode the file because the codec is pinned. Anything less than
|
|
638
|
+
* that (no `-Encoding`, or only one side) stays refused.
|
|
639
|
+
*
|
|
640
|
+
* @param command - the full command text.
|
|
641
|
+
* @returns whether both sides name an encoding.
|
|
642
|
+
*/
|
|
643
|
+
function hasPinnedEncoding(command) {
|
|
644
|
+
// A read that states its codec: `Get-Content -Encoding utf8`, or a .NET read that
|
|
645
|
+
// passes an encoding object as its second argument
|
|
646
|
+
// (`::ReadAllText($path, $enc)` / `::ReadAllText('x', [Text.Encoding]::UTF8)`).
|
|
647
|
+
const readPins = /Get-Content\b[^\n;&|]*\s-Encoding\s+\w+/i.test(command)
|
|
648
|
+
|| /::\s*(?:ReadAllText|ReadAllLines)\s*\(\s*[^,()]+,\s*[^)]+\)/i.test(command);
|
|
649
|
+
// A write that states its codec: `Set-Content -Encoding utf8`, `Out-File -Encoding`,
|
|
650
|
+
// or `WriteAllText(path, text, <encoding>)` — the third argument is the codec.
|
|
651
|
+
const writePins = /(?:Set-Content|Out-File|Add-Content)\b[^\n;&|]*\s-Encoding\s+\w+/i.test(command)
|
|
652
|
+
|| /::\s*WriteAllText\s*\(\s*[^,()]+,\s*[^,()]+,\s*[^)]+\)/i.test(command);
|
|
653
|
+
return readPins && writePins;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Whether the command's only content change is a bounded, literal substitution.
|
|
657
|
+
*
|
|
658
|
+
* `$t = $t.Replace('old','new')` and `$t = $t -replace 'a','b'` change one
|
|
659
|
+
* substring; they do not rebuild the document. The distinction matters because
|
|
660
|
+
* the shape rules otherwise treat "read then write the same file" as one hazard,
|
|
661
|
+
* and a targeted replacement is nowhere near as destructive as a slice.
|
|
662
|
+
*
|
|
663
|
+
* Deliberately **not** enough on its own: a `-replace` whose pattern is a
|
|
664
|
+
* document-wide regex (`(?s)^.*$`, `\s+`) rewrites everything. That is why this
|
|
665
|
+
* predicate is only consulted together with {@link hasPinnedEncoding}.
|
|
666
|
+
*
|
|
667
|
+
* @param command - the full command text.
|
|
668
|
+
* @returns whether a bounded substitution is present.
|
|
669
|
+
*/
|
|
670
|
+
function hasBoundedSubstitution(command) {
|
|
671
|
+
// A literal-to-literal Replace / -replace, both sides quoted.
|
|
672
|
+
const literalSub = /\.\s*Replace\s*\(\s*'(?:[^'\\]|\\.){0,300}'\s*,\s*'(?:[^'\\]|\\.){0,300}'\s*\)/i.test(command)
|
|
673
|
+
|| /\.\s*Replace\s*\(\s*"(?:[^"\\]|\\.){0,300}"\s*,\s*"(?:[^"\\]|\\.){0,300}"\s*\)/i.test(command)
|
|
674
|
+
|| /\$\w+\s*-replace\s*'(?:[^'\\]|\\.){0,300}'\s*,\s*'(?:[^'\\]|\\.){0,300}'/i.test(command);
|
|
675
|
+
|
|
676
|
+
// A bare `-replace 'a','b'` in a pipeline: `(Get-Content $f -Raw) -replace 'a','b' | Set-Content $f`.
|
|
677
|
+
// `splitStatements` breaks on `|`, so the operator lands in its own statement and
|
|
678
|
+
// the leading `$\w+ =` / `(` anchor above never matches it.
|
|
679
|
+
const pipedSub = /(?:^|[;|]\s*|\)\s*)\(?-replace\s*'(?:[^'\\]|\\.){0,300}'\s*,\s*'(?:[^'\\]|\\.){0,300}'/i.test(command)
|
|
680
|
+
|| /(?:^|[;|]\s*)\(?-replace\s*"(?:[^"\\]|\\.){0,300}"\s*,\s*"(?:[^"\\]|\\.){0,300}"/i.test(command);
|
|
681
|
+
|
|
682
|
+
// The same substitution with the needle/replacement held in variables or a mix of
|
|
683
|
+
// variable and literal: `$t = $t.Replace($old, $new)`, `$c.Replace($old, "text")`.
|
|
684
|
+
// Common in real work (the pair is built earlier), and equivalent to the literal
|
|
685
|
+
// form as long as it stays a substitution — the wholesale-rewrite checks below
|
|
686
|
+
// still apply.
|
|
687
|
+
const varSub = /\.\s*Replace\s*\(\s*(?:\$[A-Za-z_][\w:]*|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\s*,\s*(?:\$[A-Za-z_][\w:]*|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\s*\)/i.test(command);
|
|
688
|
+
|
|
689
|
+
// A table of literal pairs applied in a loop:
|
|
690
|
+
// $pairs = @( @('old1','new1'), @('old2','new2'), … ); foreach ($p in $pairs) { $t = $t.Replace($p[0], $p[1]) }
|
|
691
|
+
// Same bounded substitution, just driven by data. Common for bulk renames in docs.
|
|
692
|
+
const tableSub = /\$\w+\s*=\s*@\s*\(\s*@\s*\(\s*'[^']*'\s*,\s*'[^']*'\s*\)/i.test(command)
|
|
693
|
+
|| /\.\s*Replace\s*\(\s*\$[A-Za-z_][\w:]*\s*\[\s*0\s*\]\s*,\s*\$[A-Za-z_][\w:]*\s*\[\s*1\s*\]\s*\)/i.test(command);
|
|
694
|
+
|
|
695
|
+
if (!literalSub && !pipedSub && !varSub && !tableSub) return false;
|
|
696
|
+
|
|
697
|
+
// The pattern must not match the whole document. These are the shapes that turn a
|
|
698
|
+
// substitution into a wholesale rewrite; with a pinned codec the bytes survive, but
|
|
699
|
+
// the content does not.
|
|
700
|
+
//
|
|
701
|
+
// Measured 2026-11-25: `$t -replace '(?s)^.*$','x'` with `-Encoding utf8` on both
|
|
702
|
+
// sides passed the old check and reduced a whole file to one character.
|
|
703
|
+
const wholeDocument = /\(\?s\)\s*\^?\.[*+]\$?|\^\.[*+]\$|\\s\*\\S\*|\^\.\*\$/i.test(command);
|
|
704
|
+
if (wholeDocument) return false;
|
|
705
|
+
|
|
706
|
+
// …and no wholesale discarding/rebuilding alongside it.
|
|
707
|
+
const destructive = /\[[^\]\n]*\.\.[^\]\n]*\]/.test(command)
|
|
708
|
+
|| /\|\s*Select-Object\s+-?(?:First|Skip|Last)\b/i.test(command)
|
|
709
|
+
|| /-TotalCount\b/i.test(command);
|
|
710
|
+
return !destructive;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Whether a statement writes `<something>.tmp/.bak` — i.e. makes a *copy* that can
|
|
715
|
+
* still hold the original bytes.
|
|
716
|
+
*
|
|
717
|
+
* Deliberately narrow. A temp file holding the **new** content is not a backup: if
|
|
718
|
+
* the transformation was semantically wrong, the original is gone just the same.
|
|
719
|
+
* `read → transform → write temp → verify temp → copy temp over original` verifies
|
|
720
|
+
* the output, not that the input is recoverable, so it does not qualify. This
|
|
721
|
+
* guard's own deny message asks for a backup of the original first, and that is
|
|
722
|
+
* the only step that makes a rewrite undoable.
|
|
723
|
+
*
|
|
724
|
+
* @param statement - one statement.
|
|
725
|
+
* @returns whether the statement writes a temp/backup destination.
|
|
726
|
+
*/
|
|
727
|
+
function writesTempOrBackup(statement) {
|
|
728
|
+
const text = statementTokens(statement).join(' ');
|
|
729
|
+
if (!/\.(?:tmp|bak|backup|orig|old)\b|[-_.]tmp\b/i.test(text)) return false;
|
|
730
|
+
return COPY_DESTINATION.test(text);
|
|
480
731
|
}
|
|
481
732
|
|
|
482
733
|
/**
|
|
@@ -488,21 +739,28 @@ function hasCopyStep(command) {
|
|
|
488
739
|
* @returns the refusal, or `undefined`.
|
|
489
740
|
*/
|
|
490
741
|
function inPlaceRewrite(command, statements, dialect) {
|
|
491
|
-
if (hasCopyStep(command)) return undefined;
|
|
492
|
-
|
|
493
742
|
const literals = collectLiterals(statements);
|
|
743
|
+
|
|
744
|
+
// Per-file bookkeeping. A single global "last write" index was wrong: in
|
|
745
|
+
// `Set-Content a …; Get-Content b`, it would treat b's read as a read-back of a.
|
|
746
|
+
/** @type {Map<string, { expr: string, lastWrite: number }>} */
|
|
494
747
|
const written = new Map();
|
|
748
|
+
/** @type {Map<string, { expr: string, firstRead: number }>} */
|
|
495
749
|
const read = new Map();
|
|
496
750
|
|
|
497
|
-
for (
|
|
751
|
+
for (let index = 0; index < statements.length; index += 1) {
|
|
752
|
+
const statement = statements[index];
|
|
753
|
+
|
|
498
754
|
for (const expr of writtenTargets(statement)) {
|
|
499
755
|
for (const key of exprKeys(expr, literals)) {
|
|
500
|
-
|
|
756
|
+
const prior = written.get(key);
|
|
757
|
+
written.set(key, { expr, lastWrite: index, });
|
|
758
|
+
if (prior !== undefined && prior.expr !== expr) written.set(key, { expr: prior.expr, lastWrite: index });
|
|
501
759
|
}
|
|
502
760
|
}
|
|
503
761
|
for (const expr of readTargets(statement)) {
|
|
504
762
|
for (const key of exprKeys(expr, literals)) {
|
|
505
|
-
if (!read.has(key)) read.set(key, expr);
|
|
763
|
+
if (!read.has(key)) read.set(key, { expr, firstRead: index });
|
|
506
764
|
}
|
|
507
765
|
}
|
|
508
766
|
}
|
|
@@ -510,21 +768,46 @@ function inPlaceRewrite(command, statements, dialect) {
|
|
|
510
768
|
// .NET content calls are not shell verbs, so `statementTokens` never sees them;
|
|
511
769
|
// they name the file as their first argument and are the other way to rewrite a
|
|
512
770
|
// file from its own bytes ([IO.File]::ReadAllText → ::WriteAllText).
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
771
|
+
//
|
|
772
|
+
// These must participate in the ORDER bookkeeping. Measured 2026-11-25: giving
|
|
773
|
+
// them no statement index made the last-write lookup return -1, which emptied
|
|
774
|
+
// the read set and let 223 historical `.NET` read→write commands through.
|
|
775
|
+
for (let index = 0; index < statements.length; index += 1) {
|
|
776
|
+
const statement = statements[index];
|
|
777
|
+
for (const match of statement.matchAll(DOTNET_WRITE)) {
|
|
778
|
+
for (const key of exprKeys(match[1], literals)) {
|
|
779
|
+
const prior = written.get(key);
|
|
780
|
+
written.set(key, { expr: prior?.expr ?? match[1], lastWrite: index });
|
|
781
|
+
}
|
|
516
782
|
}
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
783
|
+
for (const match of statement.matchAll(DOTNET_READ)) {
|
|
784
|
+
for (const key of exprKeys(match[1], literals)) {
|
|
785
|
+
if (!read.has(key)) read.set(key, { expr: match[1], firstRead: index });
|
|
786
|
+
}
|
|
521
787
|
}
|
|
522
788
|
}
|
|
523
789
|
|
|
524
|
-
|
|
790
|
+
const repeating = hasRepetition(command, statements);
|
|
791
|
+
|
|
792
|
+
for (const [key, { expr: writtenExpr, lastWrite }] of written) {
|
|
525
793
|
// The null device is plumbing, not a file.
|
|
526
794
|
if (/^(?:lit:)?(?:\$null|nul|\/dev\/null)$/i.test(key)) continue;
|
|
527
|
-
|
|
795
|
+
const readSide = read.get(key);
|
|
796
|
+
if (readSide === undefined) continue;
|
|
797
|
+
|
|
798
|
+
// Order: a read that happens only *after* the last write is a verification
|
|
799
|
+
// read-back, not the source of the new content. It cannot feed a write that
|
|
800
|
+
// already ran. Skipped entirely when the command repeats statements, because
|
|
801
|
+
// there textual order is not execution order.
|
|
802
|
+
if (!repeating && readSide.firstRead > lastWrite) continue;
|
|
803
|
+
|
|
804
|
+
// A real copy of the target, made before the overwrite, makes the write undoable.
|
|
805
|
+
if (hasCopyStepFor(statements, literals, new Set([key]), lastWrite)) continue;
|
|
806
|
+
|
|
807
|
+
// A bounded substitution with the codec pinned on both sides is what the `edit`
|
|
808
|
+
// tool does: it cannot re-encode the file and cannot drop content outside the
|
|
809
|
+
// matched substring. Anything weaker stays refused — see hasPinnedEncoding.
|
|
810
|
+
if (hasBoundedSubstitution(command) && hasPinnedEncoding(command)) continue;
|
|
528
811
|
|
|
529
812
|
const shown = unquote(String(writtenExpr));
|
|
530
813
|
const backup = dialect === 'bash'
|
package/lib/staging.js
CHANGED
|
@@ -59,7 +59,15 @@ import { basename, join } from 'node:path';
|
|
|
59
59
|
* @returns whether it is a UNC path.
|
|
60
60
|
*/
|
|
61
61
|
export function isNetworkPath(p) {
|
|
62
|
-
|
|
62
|
+
const text = String(p ?? '');
|
|
63
|
+
// `\\?\C:\…` starts with two backslashes but names a local volume. Treating it as a
|
|
64
|
+
// share sent local paths down the staging branch — they were copied, verified and
|
|
65
|
+
// recycled from a staging directory instead of in place (measured 2026-11-25).
|
|
66
|
+
if (/^[\\/]{2}\?[\\/](?!UNC[\\/])/i.test(text)) return false;
|
|
67
|
+
// `\\?\UNC\host\share\…` *is* a network path; it is spelled out instead of using the
|
|
68
|
+
// `\\host\share` form. Strip the prefix so the share rules see what they expect.
|
|
69
|
+
if (/^[\\/]{2}\?[\\/]UNC[\\/]/i.test(text)) return true;
|
|
70
|
+
return /^[\\/]{2}[^\\/]/.test(text);
|
|
63
71
|
}
|
|
64
72
|
|
|
65
73
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-delete-guard",
|
|
3
|
-
"version": "2.4.
|
|
3
|
+
"version": "2.4.3",
|
|
4
4
|
"description": "Force every DSH file deletion through the OS Recycle Bin. Intercepts shell tool calls at tools/pre-execute (pwsh, bash, cmd, the persistent terminal), rewrites destructive delete commands into a recoverable recycle-bin move (Win32 SHFileOperation / SHQueryRecycleBin), and blocks permanent-erase escapes — including content destroyed without a delete verb (in-place rewrites of the only copy, unchecked null slice endpoints). Deletions on UNC shares — which have no Recycle Bin — are staged to a local NTFS volume, verified, and recycled from there before the original is removed.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|