dsh-delete-guard 2.4.1 → 2.4.2
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 +111 -0
- package/README.en.md +7 -5
- package/README.ja.md +4 -2
- package/README.md +5 -3
- 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/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,117 @@ each profile actually ran.
|
|
|
7
7
|
The long-form reasoning behind every entry — what was measured, what was
|
|
8
8
|
rejected, what the trade-off costs — lives in the maintainer's engineering notes (`INCIDENTS.md`, not shipped since 2.2.0).
|
|
9
9
|
|
|
10
|
+
## [2.4.2] — 2026-11-25
|
|
11
|
+
|
|
12
|
+
**Renumbering false positives from real measurements.** The rules from 2.3.0 / 2.4.0 were
|
|
13
|
+
built from one incident each. This release is built from **62,131 shell commands that
|
|
14
|
+
actually ran on this machine** (5,746 session logs), re-classified with today's matcher:
|
|
15
|
+
1,580 would now be refused, and **432 of those were false positives (0.70% of all
|
|
16
|
+
commands)**. Three independent audits — two per-command, one code-level — plus my own
|
|
17
|
+
mechanical re-checks. Evidence: `docs/incidents/2026-11-24-rule-false-positive-sweep.md`,
|
|
18
|
+
plan: `docs/incidents/2026-11-24-fix-plan-2-4-2.md`.
|
|
19
|
+
|
|
20
|
+
### `in-place-rewrite`: two conditions instead of a new rule
|
|
21
|
+
|
|
22
|
+
The rule stays "reads the same file it writes". What was missing was **order** and
|
|
23
|
+
**recoverability** — not a different predicate.
|
|
24
|
+
|
|
25
|
+
- **Order.** A read that happens only *after* the last write is a verification read-back;
|
|
26
|
+
its value cannot feed a write that already ran. Releases 330 historical commands.
|
|
27
|
+
- `.NET` writes participate: giving them no statement index made the last-write lookup
|
|
28
|
+
return `-1`, which emptied the read set and would have let **223** `.NET`
|
|
29
|
+
read→write commands through — including the shape §9.4 of the incident record
|
|
30
|
+
claims is covered.
|
|
31
|
+
- Suppressed inside any repetition construct (`for`, `foreach`, `while`, `do`, `until`,
|
|
32
|
+
`switch`, `%`/`ForEach-Object`, `.ForEach(`), because there textual order is not
|
|
33
|
+
execution order. The first gate listed only three keywords and missed `%`, the
|
|
34
|
+
commonest spelling.
|
|
35
|
+
- **Recoverability.** A copy step now has to be an actual statement writing a *different*
|
|
36
|
+
path derived from the target, **before** the overwrite. The previous check was a
|
|
37
|
+
whole-text `BACKUP_MARKER.test(command)`, so all three of these were exempted while
|
|
38
|
+
truly rewriting a file from its only copy: a `.bak` in a trailing comment, a `.bak` in
|
|
39
|
+
the target's own name, and a `.bak` in an unrelated string.
|
|
40
|
+
- `sed -i.bak` still counts — the editor makes the copy itself, in the same statement.
|
|
41
|
+
- A temp file holding the **new** content is **not** a backup: verifying the output does
|
|
42
|
+
not make the input recoverable. Refused (this was 4 historical commands).
|
|
43
|
+
|
|
44
|
+
### A bounded substitution with the codec pinned is the `edit` tool
|
|
45
|
+
|
|
46
|
+
`$t = $t.Replace('a','b')` written back is a targeted change, not a rebuild. It is now
|
|
47
|
+
allowed when **both** sides state an encoding, which is the condition that actually
|
|
48
|
+
matters: `Get-Content -Raw` on a GBK document decodes it wrong, and `WriteAllText` then
|
|
49
|
+
writes the mojibake back — measured, with an ASCII needle the occurrence check passes and
|
|
50
|
+
every CJK character becomes `U+FFFD`. Encoding continuity is what prevents it; a
|
|
51
|
+
replacement-count check does not.
|
|
52
|
+
|
|
53
|
+
Not allowed: a document-wide regex (`-replace '(?s)^.*$'` reduces a file to one
|
|
54
|
+
character), a substitution applied to a slice, and a substitution with no codec stated.
|
|
55
|
+
Releases 183 commands (44% of the cluster).
|
|
56
|
+
|
|
57
|
+
### Four holes the sweep found (not false positives — the opposite)
|
|
58
|
+
|
|
59
|
+
| Command | Was | Now |
|
|
60
|
+
| --- | --- | --- |
|
|
61
|
+
| `Remove-Item x.txt -WhatIf` | `rewrite/delete` → told the model to re-run it as `file_trash` | rendered as a dry run: "this previewed, nothing was deleted" |
|
|
62
|
+
| `$i.InvokeVerb('delete')` alone | **allowed** (the rule needed a bin reference in the same command) | refused |
|
|
63
|
+
| `$i.Verbs() \| % { $_.DoIt() }` | **allowed** | refused |
|
|
64
|
+
| `const {execSync}=require('child_process'); execSync('…')` | **allowed** (every spawn branch required a leading dot) | refused |
|
|
65
|
+
|
|
66
|
+
The first is a safety inversion, not friction: the user asked to preview and the guard
|
|
67
|
+
advised destroying the file. The fix renders dry runs differently rather than dropping
|
|
68
|
+
them from classification — dropping statements let the word `-WhatIf` in a comment or a
|
|
69
|
+
string exempt a real write (measured, three cases).
|
|
70
|
+
|
|
71
|
+
Also: `-WhatIf`/`-Confirm`/`-Verbose`/`-Debug` are switches, not value-taking flags.
|
|
72
|
+
Listing them as value-taking made `Remove-Item -Verbose C:\x\a.txt` report "no explicit
|
|
73
|
+
operands", so the model was told its delete had no target instead of being handed the
|
|
74
|
+
paths.
|
|
75
|
+
|
|
76
|
+
### Smaller corrections
|
|
77
|
+
|
|
78
|
+
- `.Verbs()` is enumeration, not driving: the sanctioned restore path and read-only bin
|
|
79
|
+
listings are allowed again.
|
|
80
|
+
- `DoIt()` is never exempted by a restore word — a comment saying `# restore` laundered it.
|
|
81
|
+
- `Remove-Item variable:x` / `env:X` / `function:x` / `alias:X` are allowed: they delete
|
|
82
|
+
no file, and the old behaviour handed the model `file_trash "variable:x"`, an
|
|
83
|
+
instruction that cannot work. `HKCU:`/`Cert:`/`WSMan:` are refused **without** a
|
|
84
|
+
file_trash hint — the bin cannot hold a registry key.
|
|
85
|
+
- `Invoke-Expression` is judged by its body, not by the word.
|
|
86
|
+
- A shell invoked through a variable (`$shellPath='…bash.exe'; & $shellPath -c "…"`) is
|
|
87
|
+
refused when the body deletes. Previously the `$sh='bash'` spelling was caught only
|
|
88
|
+
because the variable *name* contains `sh`.
|
|
89
|
+
- `Select-String <pattern> <file>`: `-Path`'s value was eaten by `skip: 1`, so
|
|
90
|
+
`Select-String -Path a.md -Pattern x | Set-Content a.md` was allowed.
|
|
91
|
+
- A read folded into the write statement (`Set-Content $f (Get-Content $f | Select-Object -First 10)`)
|
|
92
|
+
is now a read. Four variants were allowed; this is the incident in one line.
|
|
93
|
+
|
|
94
|
+
### Costs, stated
|
|
95
|
+
|
|
96
|
+
- **Latency: +11% best-case, +16% median** on 6,000 real commands (41 interleaved rounds,
|
|
97
|
+
25 blocks, both versions in one process; the two-version comparison is in
|
|
98
|
+
`temp/bench-decisive.mjs`). The classifier was ~165 µs/command and is now ~192 µs.
|
|
99
|
+
For scale: one `stat()` is ~5 µs, one PowerShell spawn (what `file_trash` does) is
|
|
100
|
+
~70 ms — the guard is 0.3% of a trash call. A cheap precondition in the hook
|
|
101
|
+
(two regexes, verified to skip **no** command the classifier would block, on all 6,000)
|
|
102
|
+
keeps the new checks off the 88% of commands that neither read nor write.
|
|
103
|
+
- **Not reached:** the plan's target was "误伤 < 130". The measured result is **432 → 241**.
|
|
104
|
+
The remainder is dominated by 156 commands whose *read* side states no encoding — refused
|
|
105
|
+
on purpose, since that is the mojibake hazard — plus 24 with no encoding on either side
|
|
106
|
+
and the `UNSURE` group whose writes come from an external script.
|
|
107
|
+
- **`real` count drops 1,148 → 852, which looks like over-relaxation and is not.** Verified
|
|
108
|
+
mechanically: across the 5,917 commands now allowed, **zero** are "same file, read before
|
|
109
|
+
write". The drop is the sweep's own classifier mislabeling write-then-read-back
|
|
110
|
+
(`python x.py | Out-File out.txt; Get-Content out.txt`) as a whole-file rewrite. The
|
|
111
|
+
acceptance criteria were changed to a shape gate for this reason.
|
|
112
|
+
|
|
113
|
+
### Tests
|
|
114
|
+
|
|
115
|
+
116 → **148**, eight layers. New layer ③ `test/holes.test.mjs` (12 cases) pins each hole
|
|
116
|
+
and each correction with the direction it must move; layer ② grew from 22 to 30 cases
|
|
117
|
+
covering order, `.NET` ordering, folded reads, repetition, real-vs-fake backup steps,
|
|
118
|
+
pinned encoding, and the four "no discard token" rebuilds that keep the rule from
|
|
119
|
+
degenerating into a token list.
|
|
120
|
+
|
|
10
121
|
## [2.4.1] — 2026-11-24
|
|
11
122
|
|
|
12
123
|
The publish workflow's first run, and what it found. No production code changed.
|
package/README.en.md
CHANGED
|
@@ -54,7 +54,7 @@ dsh plugin --profile web add dsh-delete-guard
|
|
|
54
54
|
dsh plugin --profile web add github:deepestevan/dsh-delete-guard
|
|
55
55
|
# or from a local tarball (when you have changed the source)
|
|
56
56
|
pnpm pack --pack-destination ./temp/pack # bump `version` first
|
|
57
|
-
dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.
|
|
57
|
+
dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.2.tgz
|
|
58
58
|
# restart dsh web: lib/*.js is loaded at process start
|
|
59
59
|
```
|
|
60
60
|
|
|
@@ -84,6 +84,8 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
|
|
|
84
84
|
| Locations without a bin | UNC shares and exFAT/FAT32 volumes, where "recycling" is a permanent erase |
|
|
85
85
|
| Deletes inside scripts | shell / Python / Node inline bodies, and writing delete text into `.ps1`/`.sh`/`.py` |
|
|
86
86
|
| **Reading a file and rewriting it in one command** | `(Get-Content $f) \| Set-Content $f`, `$c = Get-Content $f; Set-Content $f $c`, `sed -i f`, `cat f > f`, `::ReadAllText` → `::WriteAllText` — the new content comes from the only copy, so a wrong slice or filter leaves nothing to restore. The `.bak` / verified-temp spelling is allowed |
|
|
87
|
+
| **A read folded into the write statement** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)` — reads, truncates and writes back on one line, which is the incident with fewer keystrokes |
|
|
88
|
+
| **A shell invoked through a variable** | `$shellPath='…bash.exe'; & $shellPath -c "rm -rf …"` — the program is not a literal, so the body cannot be judged |
|
|
87
89
|
| **An unchecked slice endpoint** | a command that both writes a file and slices with `$idx ± n` (`$l[0..($idx-2)]`, `-First ($i-1)`) where `$idx` was never checked for `$null`. PowerShell does not error: `0..($null-2)` *is* `0..-2` — the first line plus the last two |
|
|
88
90
|
|
|
89
91
|
**Allowed**: read-only work, commands that only mention a delete word
|
|
@@ -181,10 +183,10 @@ the decision is made on the statement's command word, the shape of the call, and
|
|
|
181
183
|
node test/run-all.mjs
|
|
182
184
|
```
|
|
183
185
|
|
|
184
|
-
|
|
185
|
-
share staging (8), `file_trash` operand guard (15), host schema +
|
|
186
|
-
host schema acceptance (5), live end-to-end against the real
|
|
187
|
-
including a real `\\localhost\C$` path). `test/` is not shipped in the tarball, so it
|
|
186
|
+
148 cases across eight layers: command classification (50), overwrite guard (30),
|
|
187
|
+
rule holes (12), share staging (8), `file_trash` operand guard (15), host schema +
|
|
188
|
+
hook wiring (14), host schema acceptance (5), live end-to-end against the real
|
|
189
|
+
Recycle Bin (14, including a real `\\localhost\C$` path). `test/` is not shipped in the tarball, so it
|
|
188
190
|
must be green before packing; two layers load the host's own validators and report
|
|
189
191
|
**skipped** (not failed) where no DSH install exists. The overwrite-guard layer keeps
|
|
190
192
|
"the incident command must be refused" and "42 ordinary commands must still pass" in
|
package/README.ja.md
CHANGED
|
@@ -51,7 +51,7 @@ dsh plugin --profile web add dsh-delete-guard
|
|
|
51
51
|
dsh plugin --profile web add github:deepestevan/dsh-delete-guard
|
|
52
52
|
# またはローカルの tarball から(ソースを変更したとき)
|
|
53
53
|
pnpm pack --pack-destination ./temp/pack # 先に package.json の version を上げる
|
|
54
|
-
dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.
|
|
54
|
+
dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.2.tgz
|
|
55
55
|
# dsh web を再起動(lib/*.js はプロセス起動時に読み込まれる)
|
|
56
56
|
```
|
|
57
57
|
|
|
@@ -81,6 +81,8 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
|
|
|
81
81
|
| ごみ箱が無い場所 | UNC 共有と exFAT/FAT32 ボリューム(そこで「ごみ箱へ」は完全消去と同じ) |
|
|
82
82
|
| スクリプト内の削除 | シェル / Python / Node のインライン本体、および削除語を含むテキストの `.ps1`/`.sh`/`.py` への書き込み |
|
|
83
83
|
| **同一ファイルの読み書き** | `(Get-Content $f) \| Set-Content $f`、`$c = Get-Content $f; Set-Content $f $c`、`sed -i f`、`cat f > f`、`::ReadAllText` → `::WriteAllText`——新しい内容は唯一のコピーから作られるため、切り出しやフィルタを誤ると復元元が残りません。`.bak` か検証付き一時ファイルを残す書き方は許可 |
|
|
84
|
+
| **書き込み文に折り込まれた読み取り** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)`——1 行で読み・切り詰め・書き戻し。事故の最短表記 |
|
|
85
|
+
| **変数経由のシェル呼び出し** | `$shellPath='…bash.exe'; & $shellPath -c "rm -rf …"`——プログラム名がリテラルでなく、本体を判定できない |
|
|
84
86
|
| **未検査のスライス端点** | 同一コマンド内でファイルを書き、かつ `$idx ± n` を端点に使う(`$l[0..($idx-2)]`、`-First ($i-1)`)。`$idx` は `$null` 検査済みでない。PowerShell はエラーにせず、`0..($null-2)` は `0..-2`(先頭行 + 末尾 2 行)になる |
|
|
85
87
|
|
|
86
88
|
**許可される**:読み取り専用の作業、削除語に言及するだけのコマンド
|
|
@@ -171,7 +173,7 @@ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消
|
|
|
171
173
|
node test/run-all.mjs
|
|
172
174
|
```
|
|
173
175
|
|
|
174
|
-
|
|
176
|
+
8 層・148 ケース:コマンド分類(50)、上書きガード(30)、規則の穴(12)、共有ステージング(8)、
|
|
175
177
|
`file_trash` オペランドガード(15)、ホストのスキーマとフック配線(14)、ホストのスキーマ受理(5)、
|
|
176
178
|
実ごみ箱に対するエンドツーエンド(14、実 `\\localhost\C$` パスを含む)。`test/` は tarball に
|
|
177
179
|
含まれないので、パック前に緑である必要があります。うち 2 層はホスト自身の検証器を読み込むため、
|
package/README.md
CHANGED
|
@@ -47,7 +47,7 @@ dsh plugin --profile web add dsh-delete-guard
|
|
|
47
47
|
dsh plugin --profile web add github:deepestevan/dsh-delete-guard
|
|
48
48
|
# 或者从本地 tarball(改过源码时用这条)
|
|
49
49
|
pnpm pack --pack-destination ./temp/pack # 先升 package.json 的 version
|
|
50
|
-
dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.
|
|
50
|
+
dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.2.tgz
|
|
51
51
|
# 重启 dsh web:lib/*.js 只在进程启动时加载
|
|
52
52
|
```
|
|
53
53
|
|
|
@@ -79,6 +79,8 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
|
|
|
79
79
|
| 脚本内删除 | 内联 shell / Python / Node 体里的删除动词与擦除调用;把含删除的文本写进 `.ps1`/`.sh`/`.py` |
|
|
80
80
|
| **读改写同一个文件** | `(Get-Content $f) \| Set-Content $f`、`$c = Get-Content $f; Set-Content $f $c`、`sed -i $f`、`cat $f > $f`、`::ReadAllText` → `::WriteAllText`——新内容来自唯一的副本,写坏就没得还原。带 `.bak` 备份或临时文件校验步骤的写法放行 |
|
|
81
81
|
| **未断言的切片端点** | 同一命令里既写文件、又用 `$idx ± n` 当区间端点(`$l[0..($idx-2)]`、`-First ($i-1)`),而 `$idx` 从没检查过 `$null`。`$null` 在 PowerShell 里不报错:`0..($null-2)` 就是 `0..-2` = 首行 + 末两行 |
|
|
82
|
+
| **读动词折进写语句里** | `Set-Content $f (Get-Content $f \| Select-Object -First 10)`:一行里既读又截断再写回,是事故最紧凑的拼法 |
|
|
83
|
+
| **经变量调用的 shell** | `$shellPath='…bash.exe'; & $shellPath -c "rm -rf …"`:程序名不是字面量,正文无法判定 |
|
|
82
84
|
|
|
83
85
|
**放行**:只读命令、只提到删除词的操作(`Select-String -Pattern "Remove-Item"`、
|
|
84
86
|
`Get-Content shred.exe`)、从回收站**还原**文件、`Add-Content` / `>>` / `-Append`
|
|
@@ -166,8 +168,8 @@ UNC 路径下不存在回收站:`SHFileOperationW` 在那里是**擦除并返
|
|
|
166
168
|
node test/run-all.mjs
|
|
167
169
|
```
|
|
168
170
|
|
|
169
|
-
|
|
170
|
-
宿主 schema 受理(5)、对真实回收站的端到端(14,含真 `\\localhost\C$` 路径)。`test/` 不进 tarball,所以打包前必须
|
|
171
|
+
148 项、八层:命令分类(50)、覆盖守卫(30)、规则漏洞(12)、暂存删除(8)、`file_trash` 操作数守卫(15)、
|
|
172
|
+
宿主 schema 与钩子接线(14)、宿主 schema 受理(5)、对真实回收站的端到端(14,含真 `\\localhost\C$` 路径)。`test/` 不进 tarball,所以打包前必须
|
|
171
173
|
全绿;其中两层会加载宿主自己的校验器,找不到 DSH 安装时报「跳过」而非失败。
|
|
172
174
|
覆盖守卫那一层里,"事故命令必须被拒" 与 "42 条日常命令必须照常放行" 用的是同一份文件:
|
|
173
175
|
只拦住事故、却把 `npm run build` 也拒掉的规则不算修好。
|
package/SECURITY.md
CHANGED
|
@@ -76,6 +76,93 @@ a security read:
|
|
|
76
76
|
honest: O(size) in time and the same in free space on the staging volume, so a
|
|
77
77
|
very large tree can exceed the tool call's timeout.
|
|
78
78
|
|
|
79
|
+
## Why there is no permanent-delete tool
|
|
80
|
+
|
|
81
|
+
Issue #2 asks for one: a tool that really erases when the user asked for it,
|
|
82
|
+
gated by a `user_request` / `user_quote` field. It is refused, and the reason is
|
|
83
|
+
not that permanent deletion is never legitimate — a user can always do it in
|
|
84
|
+
Explorer, or run a script themselves. The reason is that **the gate would be
|
|
85
|
+
authored by the thing it is meant to guard.**
|
|
86
|
+
|
|
87
|
+
Three layers, and only the first has a machine judge:
|
|
88
|
+
|
|
89
|
+
| Layer | Question | Judge |
|
|
90
|
+
| --- | --- | --- |
|
|
91
|
+
| 1 | did these characters come from the user? | the plugin, mechanically — `source.kind === 'user'` plus an `rpcId` on the `user/message` event |
|
|
92
|
+
| 2 | does that sentence mean "this file may be destroyed"? | nobody, automatically |
|
|
93
|
+
| 3 | should it run *now*? | a human — `{ kind: 'ask' }` where approvals are real; on a box with `approval policy: never` that resolves to allow, so the only remaining human gate is a command the person runs |
|
|
94
|
+
|
|
95
|
+
A verbatim quote can be checked. Intent cannot, because **the same characters
|
|
96
|
+
carry both readings**: "永久删除 a.md", "不要永久删除 a.md", "别永久删除 a.md",
|
|
97
|
+
"能永久删除 a.md 吗", "你上次说的『永久删除 a.md』是指哪一步" all contain the
|
|
98
|
+
affirmative token, and the last three are not instructions at all. A lexical
|
|
99
|
+
filter over negations is an enumeration treadmill, and it fails in the direction
|
|
100
|
+
of *allowing* — the token is present — which for a destructive action is the worst
|
|
101
|
+
direction to fail in. Adding a semantic model to classify the sentence only moves
|
|
102
|
+
the trust question up one level. (Even the provenance check needs care: `user/message`
|
|
103
|
+
also carries `agent-instructions` from `AGENTS.md`, `runtime-context` and spliced
|
|
104
|
+
agent input, so a filter that does not key on `source.kind` would let the agent
|
|
105
|
+
author its own permission slip.)
|
|
106
|
+
|
|
107
|
+
**Measured, on why the surrounding design cannot compensate.** 126 real guard
|
|
108
|
+
denials across 58 sessions (300 newest session logs on this machine, 2026-11-24),
|
|
109
|
+
classified by what the model did before the next user turn:
|
|
110
|
+
|
|
111
|
+
| follow-up | share |
|
|
112
|
+
| --- | --- |
|
|
113
|
+
| changed approach (typically by following the recipe the deny message names: copy to `.bak`, use `edit`) | 78% |
|
|
114
|
+
| `file_trash` within 5 tool calls | 14% |
|
|
115
|
+
| re-attempted a shape the guard would block | 4% |
|
|
116
|
+
| diagnosed first (`read`, `grep`, `Test-Path`) | 3% |
|
|
117
|
+
| wrote a delete into a script and ran that path | 0.8% |
|
|
118
|
+
| **stopped without another tool call** | **0%** |
|
|
119
|
+
|
|
120
|
+
A block does not end a turn; it re-routes. And the re-route follows the
|
|
121
|
+
alternative the deny message names — which is why every refusal here names one.
|
|
122
|
+
There is no acceptable alternative for "make it unrecoverable", so a
|
|
123
|
+
`permanent_delete` tool would be the shortest path to a goal the model had already
|
|
124
|
+
been told to pursue, with a fabricated-or-misapplied quote as its receipt.
|
|
125
|
+
|
|
126
|
+
**What would be honest**, if this is ever revisited: the gate is a real approval or
|
|
127
|
+
a command the human runs (`scripts/purge-bin-entry.ps1`, keyed off the `$I` record),
|
|
128
|
+
and `user_quote` is an audit field — never the key. Anything else is an audited
|
|
129
|
+
permanent delete with a receipt the agent wrote itself.
|
|
130
|
+
|
|
131
|
+
Note the asymmetry: "no permanent delete" is a policy, not an invariant — `Add-Type`
|
|
132
|
+
C# still reaches `DeleteFileW`, as the README's 「不挡什么」 table says. The choice
|
|
133
|
+
above keeps the *easy* path safe, which is what a policy layer can actually do.
|
|
134
|
+
|
|
135
|
+
## How the rules were calibrated (2026-11-25)
|
|
136
|
+
|
|
137
|
+
The rules from 2.3.0 / 2.4.0 each came from one incident. 2.4.2 came from a
|
|
138
|
+
measurement: **62,131 shell commands that actually ran on this machine** (5,746 session
|
|
139
|
+
logs), re-classified with the matcher as it stood. 1,580 would be refused; **432 of those
|
|
140
|
+
were false positives (0.70% of every command ever run here)**. Records:
|
|
141
|
+
`docs/incidents/2026-11-24-rule-false-positive-sweep.md` (evidence) and
|
|
142
|
+
`docs/incidents/2026-11-24-fix-plan-2-4-2.md` (plan, including the direction that was
|
|
143
|
+
rejected and why).
|
|
144
|
+
|
|
145
|
+
Two things from that exercise are worth keeping in view when changing a rule:
|
|
146
|
+
|
|
147
|
+
**1. A shape list is the same mistake as a verb list.** The first proposal was to refuse
|
|
148
|
+
only commands containing a discard token (`[a..b]`, `-First`, `Select-Object`). Measurements
|
|
149
|
+
saw four rebuilds that contain none of them and destroy a whole file anyway
|
|
150
|
+
(`| Where-Object { -not … }`, `for { … continue }`, `-replace '(?s)^.*$'`). The rule keeps
|
|
151
|
+
"reads the same file it writes" as its shape and adds **order** and **recoverability** —
|
|
152
|
+
it does not trade one word list for another.
|
|
153
|
+
|
|
154
|
+
**2. A count is not a shape.** After the change the sweep's `real` count fell 1,148 → 852,
|
|
155
|
+
which reads like 296 dangerous commands were let through. A mechanical check said otherwise:
|
|
156
|
+
across the 5,917 commands now allowed, **none** are "same file, read before write". The drop
|
|
157
|
+
was the sweep's own classifier mislabeling write-then-read-back as a whole-file rewrite. The
|
|
158
|
+
acceptance criteria were rewritten as a shape gate because of this.
|
|
159
|
+
|
|
160
|
+
**3. A dry run must not become an instruction.** `Remove-Item x -WhatIf` classified as
|
|
161
|
+
`rewrite`, and the rewrite branch tells the model to re-run the call as `file_trash` — so a
|
|
162
|
+
user asking to preview was advised to destroy the file. Dry runs are now rendered as
|
|
163
|
+
previews. The tempting fix (drop `-WhatIf` statements from classification) was measured and
|
|
164
|
+
rejected: the word in a comment or a string then exempts a real write.
|
|
165
|
+
|
|
79
166
|
## Reporting
|
|
80
167
|
|
|
81
168
|
Once this repository is public, use a GitHub Security Advisory (or a private
|
package/lib/guard.js
CHANGED
|
@@ -64,12 +64,20 @@ const FLAGS_TAKING_VALUE = new Set([
|
|
|
64
64
|
'-include',
|
|
65
65
|
'-exclude',
|
|
66
66
|
'-credential',
|
|
67
|
-
'-confirm',
|
|
68
|
-
'-whatif',
|
|
69
|
-
'-verbose',
|
|
70
|
-
'-debug',
|
|
71
67
|
]);
|
|
72
68
|
|
|
69
|
+
/**
|
|
70
|
+
* Common parameters that are **switches**: they take no value.
|
|
71
|
+
*
|
|
72
|
+
* These were listed above until 2026-11-25, which made them swallow the operand that
|
|
73
|
+
* followed. Measured: `Remove-Item -Verbose C:\x\a.txt` and
|
|
74
|
+
* `Remove-Item -Confirm C:\x\a.txt` both classified as "no explicit operands", so the
|
|
75
|
+
* model was told its delete had no target instead of being handed the paths to
|
|
76
|
+
* `file_trash`. `-WhatIf` had the same defect and, worse, turned a preview into a
|
|
77
|
+
* rewrite instruction (see `isDryRun` in index.js).
|
|
78
|
+
*/
|
|
79
|
+
const SWITCH_PARAMETERS = new Set(['-confirm', '-whatif', '-verbose', '-debug']);
|
|
80
|
+
|
|
73
81
|
/**
|
|
74
82
|
* Programs that mean "permanently erase" rather than "delete". They are never
|
|
75
83
|
* rewritten — they are denied outright.
|
|
@@ -119,14 +127,71 @@ const WIPE_NAME_IN_BODY = /\b(?:sdelete64|sdelete|shred|srm|wipe)\b/i;
|
|
|
119
127
|
* the body and could not tell documentation from a command.
|
|
120
128
|
*/
|
|
121
129
|
const SPAWN_CALL =
|
|
122
|
-
/(?:\.\s*(?:exec|execFile|execSync|spawn|spawnSync|popen)\s*\(|\bsubprocess\s*\.\s*(?:run|call|Popen|check_output|check_call)\s*\(|\bos\s*\.\s*(?:system|popen|execl?\w*|spawn\w*)\s*\(|\bsystem\s*\(|%\s*x\s*[({])/i;
|
|
130
|
+
/(?:\.\s*(?:exec|execFile|execSync|spawn|spawnSync|popen)\s*\(|\b(?:exec|execFile|execSync|spawn|spawnSync)\s*\(|\bsubprocess\s*\.\s*(?:run|call|Popen|check_output|check_call)\s*\(|\bos\s*\.\s*(?:system|popen|execl?\w*|spawn\w*)\s*\(|\bsystem\s*\(|%\s*x\s*[({])/i;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* A destructuring import of a process-spawning API:
|
|
134
|
+
* `const { execSync } = require('child_process')`. Measured 2026-11-25: this shape
|
|
135
|
+
* then calls a bare `execSync(...)`, which {@link SPAWN_CALL} did not catch (every
|
|
136
|
+
* branch required a leading dot), so `execSync('shred -u x')` was allowed.
|
|
137
|
+
*
|
|
138
|
+
* Recognised as the assignment itself rather than by loosening SPAWN_CALL: dropping
|
|
139
|
+
* the dot requirement would also match `db.exec(...)` and `/re/.exec(...)` in any
|
|
140
|
+
* context.
|
|
141
|
+
*/
|
|
142
|
+
const SPAWN_DESTRUCTURED = /(?:const|let|var)\s*\{[^}]*\b(?:exec|execFile|execSync|spawn|spawnSync|popen)\b[^}]*\}\s*=\s*require\s*\(\s*['"]child_process['"]\s*\)/i;
|
|
123
143
|
|
|
124
144
|
/**
|
|
125
145
|
* Child interpreters whose inline body is a shell program. For these, any name in
|
|
126
146
|
* the body counts as a program name; for every other interpreter the name must
|
|
127
147
|
* also reach a process-spawning call.
|
|
148
|
+
*
|
|
149
|
+
* Matched in **program position**, never as a bare word: `node -e "…{dialect:'pwsh'}…"`
|
|
150
|
+
* contains the literal `pwsh` and was audited as if it were a shell script, which
|
|
151
|
+
* made the same word in the same body read as a program name.
|
|
152
|
+
*/
|
|
153
|
+
const SHELL_INTERPRETERS = /^(?:bash|sh|zsh|pwsh|powershell)(?:\.exe)?$/i;
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* A shell invoked through a variable, decided from the statement's tokens rather
|
|
157
|
+
* than by regex over the whole line.
|
|
158
|
+
*
|
|
159
|
+
* `splitStatements` already treats `&` as a separator, so `… ; & $sh -c "…"` arrives
|
|
160
|
+
* as the statement `$sh -c "…"` — the `&` is gone by the time a per-statement check
|
|
161
|
+
* runs. Looking at the statement's own tokens is what makes the shape visible.
|
|
162
|
+
*
|
|
163
|
+
* Measured 2026-11-25: `$shellPath='…\bash.exe'; & $shellPath -c "…"` was allowed,
|
|
164
|
+
* while `$sh='bash'; & $sh -c "…"` was denied only because the variable name
|
|
165
|
+
* contains `sh` — a denial by coincidence of naming, not by rule.
|
|
166
|
+
*
|
|
167
|
+
* @param statement - one statement, already split.
|
|
168
|
+
* @returns whether the statement runs a variable as a shell with an inline body.
|
|
128
169
|
*/
|
|
129
|
-
|
|
170
|
+
function invokesShellVariable(statement) {
|
|
171
|
+
// Cheap pre-check before tokenizing: the statement has to *start* with a variable
|
|
172
|
+
// and carry an inline-body flag. `tokenize` per statement was measurable on the
|
|
173
|
+
// tool-call path (2026-11-25), and almost no statement looks like this.
|
|
174
|
+
const head = statement.trimStart();
|
|
175
|
+
if (head.charCodeAt(0) !== 36 /* $ */) return false;
|
|
176
|
+
if (!/-(?:c|command)\b/i.test(statement)) return false;
|
|
177
|
+
|
|
178
|
+
const tokens = tokenize(statement).filter((t) => t.length > 0);
|
|
179
|
+
const program = tokens[0];
|
|
180
|
+
if (program === undefined) return false;
|
|
181
|
+
// The program position must be a variable.
|
|
182
|
+
if (!/^\$[A-Za-z_][\w:]*$/.test(program)) return false;
|
|
183
|
+
// …and it must be handed an inline-body flag.
|
|
184
|
+
const flagAt = tokens.findIndex((t, i) => i > 0 && /^-(?:c|command)$/i.test(t));
|
|
185
|
+
if (flagAt === -1) return false;
|
|
186
|
+
// Only when the body is worth judging: a delete verb or an erase tool. Otherwise
|
|
187
|
+
// this is `$bash -c "ls -la"`, and refusing it would be a false positive — the
|
|
188
|
+
// direct spelling `bash -c "ls -la"` is allowed on purpose.
|
|
189
|
+
const body = tokens.slice(flagAt + 1).join(' ');
|
|
190
|
+
return SHELL_DELETE_VERB.test(body) || WIPE_NAME_IN_BODY.test(body);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Any shell name, for the places that genuinely need "does this statement mention one". */
|
|
194
|
+
const SHELL_NAME_ANYWHERE = /\b(?:bash|sh|zsh|pwsh|powershell)\b/i;
|
|
130
195
|
|
|
131
196
|
/** Denial text shared by every permanent-erase rule. */
|
|
132
197
|
const WIPE_REASON =
|
|
@@ -169,7 +234,34 @@ const EMPTY_RECYCLE_RULES = [
|
|
|
169
234
|
const EMPTY_BIN_COMMAND = /^clear-recyclebin$/i;
|
|
170
235
|
const EMPTY_BIN_API = /\bSHEmptyRecycleBin\w*\b/i;
|
|
171
236
|
const BIN_NAMESPACE_REF = /Namespace\(\s*(?:10|0xa)\s*\)|shell:RecycleBinFolder|\$recycle\.bin/i;
|
|
172
|
-
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Driving the bin's own verbs — the part that actually destroys.
|
|
240
|
+
*
|
|
241
|
+
* `.Verbs()` was listed here until 2026-11-25, which made **enumerating** a verb
|
|
242
|
+
* list look like **executing** one. Measured: the sanctioned recovery path
|
|
243
|
+
* (`$item.Verbs() | Where-Object { $_.Name -like '*还原*' }`) was refused, and so was
|
|
244
|
+
* a read-only listing of what verbs a bin item offers — while the README promises
|
|
245
|
+
* restoring is allowed.
|
|
246
|
+
*
|
|
247
|
+
* `DoIt()` stays in the driving set and is never exempted: it runs whichever verb is
|
|
248
|
+
* currently selected, and which one that is cannot be read off the command. Measured
|
|
249
|
+
* 2026-11-25: a "restore word anywhere in the line" exemption was fooled by a bare
|
|
250
|
+
* comment — `… | % { $_.DoIt() } # restore is a different verb` became allowed.
|
|
251
|
+
*/
|
|
252
|
+
const BIN_VERB_ENUM = /\.Verbs\s*\(\s*\)/i;
|
|
253
|
+
const BIN_VERB_DRIVE = /\bInvokeVerb\s*\(|\.DoIt\s*\(/i;
|
|
254
|
+
/** `InvokeVerb('…')` whose argument names a restore rather than a destroy. */
|
|
255
|
+
const BIN_VERB_RESTORE_ARG = /InvokeVerb\s*\(\s*['"][^'"]*(?:estore|还原|复原)[^'"]*['"]/i;
|
|
256
|
+
/** `InvokeVerb('…')` whose argument names a destroy. */
|
|
257
|
+
const BIN_VERB_DELETE_ARG = /InvokeVerb\s*\(\s*['"][^'"]*(?:delete|remove|删除|清除)[^'"]*['"]/i;
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Cheap pre-check: could this statement reach the bin's verbs at all? Neither
|
|
261
|
+
* `.DoIt(`/`InvokeVerb(` nor a bin reference appears in ordinary commands, so this
|
|
262
|
+
* one test keeps four regexes and two `Namespace(10)` probes off the common path.
|
|
263
|
+
*/
|
|
264
|
+
const BIN_TOUCH = /\bInvokeVerb\s*\(|\.DoIt\s*\(|Namespace\s*\(\s*(?:10|0xa)\s*\)|shell:RecycleBinFolder|\$recycle\.bin/i;
|
|
173
265
|
|
|
174
266
|
/**
|
|
175
267
|
* Constructs that can hide a delete from a text-level parser, or make the
|
|
@@ -219,9 +311,13 @@ const ERASE_CONSTRUCTS = [
|
|
|
219
311
|
// The no-argument form was a hole until 1.0.4 — only `.Delete($true)` matched,
|
|
220
312
|
// so `(Get-Item $p).Delete()` erased a file unguarded.
|
|
221
313
|
{ re: /\.\s*Delete\s*\(\s*(?:\)|\$?(?:true|1)\s*[,)])/i, what: 'a .NET instance Delete() call', dialects: ['pwsh'] },
|
|
222
|
-
// Invoke-Expression / iex evaluates a string: the verb is inside the string,
|
|
223
|
-
//
|
|
224
|
-
|
|
314
|
+
// Invoke-Expression / iex evaluates a string: the verb is inside the string, so
|
|
315
|
+
// no statement-level verb is ever seen. Judged by the **body**, not the word —
|
|
316
|
+
// matching the bare name refused `Invoke-Expression "Write-Output 'hello'"`
|
|
317
|
+
// (measured 2026-11-25). When the body is a literal, its text is right there;
|
|
318
|
+
// when it is a variable or a file, it cannot be read and the command is refused
|
|
319
|
+
// by the `iex` handling in classifyCommand below.
|
|
320
|
+
{ re: /\b(?:Invoke-Expression|iex)\b[^\n]*\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink)\b/i, what: 'an Invoke-Expression body containing a delete', dialects: ['pwsh'] },
|
|
225
321
|
// `cmd /c del …` hands the delete to a child interpreter.
|
|
226
322
|
{ re: /\bcmd(?:\.exe)?\s+\/[ck]\b[^\n]*\b(?:del|erase|rd|rmdir)\b/i, what: 'a delete delegated to cmd.exe', dialects: ['pwsh', 'bash'] },
|
|
227
323
|
// `robocopy … /MIR` mirrors an empty source over the target, which empties it
|
|
@@ -279,9 +375,25 @@ const SHELL_DELETE_VERB = /\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink)\b/i
|
|
|
279
375
|
*/
|
|
280
376
|
const SUBSTITUTION_IN_TARGET = /\$\(|`|\$\{|\$[A-Za-z_]/;
|
|
281
377
|
|
|
378
|
+
/**
|
|
379
|
+
* PowerShell providers that hold **no files**, so a delete through them destroys
|
|
380
|
+
* something the Recycle Bin could never have held. Allowed: refusing these gave the
|
|
381
|
+
* model an instruction that cannot work (`file_trash "variable:x"`).
|
|
382
|
+
*
|
|
383
|
+
* `Remove-Variable` / `clear-variable` were already allowed, so refusing
|
|
384
|
+
* `Remove-Item variable:x` was inconsistent as well as useless.
|
|
385
|
+
*/
|
|
386
|
+
const NON_FILE_PROVIDERS = new Set(['variable', 'env', 'function', 'alias', 'psdrive']);
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Providers that hold durable state outside the file system. Denied, but with a
|
|
390
|
+
* reason that does **not** name `file_trash` — routing a registry key or a
|
|
391
|
+
* certificate to the Recycle Bin is not a thing that can happen.
|
|
392
|
+
*/
|
|
393
|
+
const OTHER_PROVIDERS = new Set(['hkcu', 'hklm', 'cert', 'wsman', 'registry']);
|
|
394
|
+
|
|
282
395
|
/** Path shapes that must never be rewritten into a recycle-bin move. */
|
|
283
|
-
const FORBIDDEN_TARGETS = [
|
|
284
|
-
{ re: /^[a-z]:[\\/]?$/i, what: 'a drive root' },
|
|
396
|
+
const FORBIDDEN_TARGETS = [ { re: /^[a-z]:[\\/]?$/i, what: 'a drive root' },
|
|
285
397
|
{ re: /^[\\/]$/, what: 'the filesystem root' },
|
|
286
398
|
{ re: /^(?:\$env:SystemRoot|%SystemRoot%|[a-z]:\\Windows)(?:[\\/]|$)/i, what: 'the Windows directory' },
|
|
287
399
|
{ re: /^(?:\$env:ProgramFiles|%ProgramFiles%|[a-z]:\\Program Files)/i, what: 'Program Files' },
|
|
@@ -464,8 +576,12 @@ function translatePosixPath(operand) {
|
|
|
464
576
|
*/
|
|
465
577
|
function wipeProgramInInlineBody(statement) {
|
|
466
578
|
if (!INLINE_BODY_FLAGS.test(statement)) return undefined;
|
|
467
|
-
|
|
468
|
-
|
|
579
|
+
const isShell = SHELL_INTERPRETERS.test(commandWord(statement).replace(/\.exe$/i, ''));
|
|
580
|
+
if (!isShell) {
|
|
581
|
+
// A destructured child_process import makes the call site a bare `execSync(...)`,
|
|
582
|
+
// which SPAWN_CALL's dot-prefixed branches do not reach.
|
|
583
|
+
const spawned = SPAWN_CALL.exec(statement)
|
|
584
|
+
?? (SPAWN_DESTRUCTURED.test(statement) ? SPAWN_DESTRUCTURED.exec(statement) : null);
|
|
469
585
|
if (spawned === null) return undefined;
|
|
470
586
|
const tail = statement.slice(spawned.index);
|
|
471
587
|
const named = WIPE_NAME_IN_BODY.exec(tail);
|
|
@@ -573,6 +689,11 @@ function parseDeleteStatement(statement) {
|
|
|
573
689
|
// SilentlyContinue` made "SilentlyContinue" a path to recycle, and the
|
|
574
690
|
// redirect message told the model to `file_trash` a value name. The two
|
|
575
691
|
// path flags are the exception — their value *is* the target.
|
|
692
|
+
const bare = flag.replace(/:.+$/, '');
|
|
693
|
+
// Switches take no value, so whatever follows is a real operand.
|
|
694
|
+
// `-WhatIf:$false` / `-Confirm:$false` glue their boolean on; strip it and
|
|
695
|
+
// keep going, otherwise `$false` becomes a "path to recycle".
|
|
696
|
+
if (SWITCH_PARAMETERS.has(bare)) continue;
|
|
576
697
|
const takesValue = FLAGS_TAKING_VALUE.has(flag);
|
|
577
698
|
const isPathFlag = flag === '-path' || flag === '-literalpath';
|
|
578
699
|
if ((takesValue || isPathFlag) && i + 1 < tokens.length) {
|
|
@@ -693,10 +814,36 @@ export function classifyCommand(command, options = {}) {
|
|
|
693
814
|
}
|
|
694
815
|
// Shell verbs driven over bin items are how Explorer empties the bin one
|
|
695
816
|
// item at a time: `InvokeVerb('delete')` on a bin item is permanent, not a
|
|
696
|
-
// recycle. Reading the bin (Move-Item out of $R, listing $I records
|
|
697
|
-
// allowed — only driving
|
|
698
|
-
|
|
699
|
-
|
|
817
|
+
// recycle. Reading the bin (Move-Item out of $R, listing $I records, listing
|
|
818
|
+
// which verbs an item offers) stays allowed — only *driving* is refused.
|
|
819
|
+
//
|
|
820
|
+
// Judged per statement, so a bin reference in one statement and a `DoIt()` in
|
|
821
|
+
// another cannot convict each other; and so that `$i.InvokeVerb('delete')` on
|
|
822
|
+
// its own — no `Namespace(10)` text anywhere — is still caught, which it was
|
|
823
|
+
// not until 2026-11-25.
|
|
824
|
+
for (const statement of statements) {
|
|
825
|
+
// Skip the loop early when the statement cannot involve the bin at all:
|
|
826
|
+
// `DoIt(`/`InvokeVerb(` and a bin reference are the only triggers, and neither
|
|
827
|
+
// appears in ordinary commands. The four regexes below run per statement, so a
|
|
828
|
+
// single cheap guard keeps this off the common path (measured 2026-11-25).
|
|
829
|
+
if (!BIN_TOUCH.test(statement)) continue;
|
|
830
|
+
const referencesBin = BIN_NAMESPACE_REF.test(statement);
|
|
831
|
+
const drivesDoIt = /\.DoIt\s*\(/i.test(statement);
|
|
832
|
+
const drivesVerb = /\bInvokeVerb\s*\(/i.test(statement);
|
|
833
|
+
const restores = BIN_VERB_RESTORE_ARG.test(statement);
|
|
834
|
+
const deletes = BIN_VERB_DELETE_ARG.test(statement);
|
|
835
|
+
|
|
836
|
+
// `DoIt()` runs whatever verb is selected; the selection is not in the text,
|
|
837
|
+
// so it is never treated as a restore — a comment saying "restore" is not a
|
|
838
|
+
// verb argument.
|
|
839
|
+
if (drivesDoIt && (referencesBin || !restores)) {
|
|
840
|
+
return emptyRecycleVerdict("the Recycle Bin's own shell verbs (DoIt)");
|
|
841
|
+
}
|
|
842
|
+
if (drivesVerb && !restores) {
|
|
843
|
+
if (referencesBin || deletes) {
|
|
844
|
+
return emptyRecycleVerdict("the Recycle Bin's own shell verbs (InvokeVerb)");
|
|
845
|
+
}
|
|
846
|
+
}
|
|
700
847
|
}
|
|
701
848
|
}
|
|
702
849
|
|
|
@@ -765,12 +912,29 @@ export function classifyCommand(command, options = {}) {
|
|
|
765
912
|
// delete cannot hide in a base64 body.
|
|
766
913
|
const statements = judged;
|
|
767
914
|
|
|
915
|
+
// 0. A shell invoked through a variable. Which program runs is not in the text,
|
|
916
|
+
// so an inline body cannot be judged — refuse rather than assume it is
|
|
917
|
+
// harmless. Only when the statement has an inline body: `& $cmd` alone runs
|
|
918
|
+
// whatever the variable holds, and that is caught elsewhere if it deletes.
|
|
919
|
+
for (const statement of statements) {
|
|
920
|
+
if (invokesShellVariable(statement)) {
|
|
921
|
+
return {
|
|
922
|
+
action: 'deny',
|
|
923
|
+
kind: 'opaque',
|
|
924
|
+
reason:
|
|
925
|
+
'Refusing a shell invoked through a variable (`$name -c "…"`): which program runs is only known at ' +
|
|
926
|
+
'run time, so a delete inside the command string cannot be routed to the Recycle Bin. ' +
|
|
927
|
+
'Call the interpreter directly, or run the delete as a file_trash tool call.',
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
|
|
768
932
|
// 1. A shell's inline body that contains a shell delete verb.
|
|
769
933
|
// `pwsh -Command "Remove-Item C:\x"`, `bash -c "rm -rf /tmp/x"`.
|
|
770
934
|
// Scoped to shells: in Python or Ruby, `del` and `rm` are that
|
|
771
935
|
// language's own syntax, so they are judged by rule 2 instead.
|
|
772
936
|
for (const statement of statements) {
|
|
773
|
-
const shellInterp =
|
|
937
|
+
const shellInterp = SHELL_NAME_ANYWHERE.test(statement);
|
|
774
938
|
const inlineBody = INLINE_BODY_FLAGS.test(statement);
|
|
775
939
|
if (shellInterp && inlineBody && SHELL_DELETE_VERB.test(statement)) {
|
|
776
940
|
return {
|
|
@@ -904,6 +1068,27 @@ export function classifyCommand(command, options = {}) {
|
|
|
904
1068
|
}
|
|
905
1069
|
operand = mapped.path;
|
|
906
1070
|
}
|
|
1071
|
+
|
|
1072
|
+
// PowerShell providers are not file systems. `Remove-Item variable:x` deletes
|
|
1073
|
+
// a variable; `env:X` an environment entry; `function:x` a function. Telling
|
|
1074
|
+
// the model to `file_trash "variable:x"` is an instruction that cannot work —
|
|
1075
|
+
// the tool resolves it to a path that does not exist. Measured 2026-11-25.
|
|
1076
|
+
const provider = /^([A-Za-z]+):/.exec(operand);
|
|
1077
|
+
if (provider !== null && !/^[A-Za-z]$/.test(provider[1])) {
|
|
1078
|
+
const name = provider[1].toLowerCase();
|
|
1079
|
+
if (NON_FILE_PROVIDERS.has(name)) continue; // deletes nothing a bin could hold
|
|
1080
|
+
if (OTHER_PROVIDERS.has(name)) {
|
|
1081
|
+
return {
|
|
1082
|
+
action: 'deny',
|
|
1083
|
+
kind: 'forbidden-target',
|
|
1084
|
+
reason:
|
|
1085
|
+
`Refusing a delete that targets the ${provider[1]}: provider ("${operand}"). The Recycle Bin only ` +
|
|
1086
|
+
'holds files, so this cannot be routed there — and erasing it is not recoverable. ' +
|
|
1087
|
+
'Delete it deliberately with the provider\'s own tooling if that is really what you mean.',
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
|
|
907
1092
|
// An operand that is itself a substitution has no provable value: the
|
|
908
1093
|
// shell expands it at run time. `rm -rf $(cat list.txt)` would otherwise
|
|
909
1094
|
// be tokenized into the literal strings `$(cat` and `list.txt)`, and
|
package/lib/index.js
CHANGED
|
@@ -74,6 +74,31 @@ const SHELL_TOOLS = new Map([
|
|
|
74
74
|
['terminal_write', { field: 'text', dialect: 'pwsh' }],
|
|
75
75
|
]);
|
|
76
76
|
|
|
77
|
+
/**
|
|
78
|
+
* A cheap "could this command possibly touch files, the bin, or an interpreter?"
|
|
79
|
+
* test, used to skip the full classifier.
|
|
80
|
+
*
|
|
81
|
+
* Must be **over-inclusive**: every rule in `guard.js` needs at least one of these
|
|
82
|
+
* signals to fire, so anything this misses is a command that no rule could have
|
|
83
|
+
* matched anyway. The cost of a false positive is a few hundred microseconds; the
|
|
84
|
+
* cost of a false negative would be an unguarded command.
|
|
85
|
+
*/
|
|
86
|
+
const MAY_TOUCH_FILES = new RegExp([
|
|
87
|
+
// delete verbs
|
|
88
|
+
'\\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink|clear-content)\\b',
|
|
89
|
+
// write verbs and redirects
|
|
90
|
+
'\\b(?:Set-Content|Out-File|Add-Content|Export-Csv|Tee-Object|Copy-Item|Move-Item|New-Item|::Write\\w+|::Create\\w*)\\b',
|
|
91
|
+
'>{1}(?!>)',
|
|
92
|
+
// readers (they matter to the in-place rule)
|
|
93
|
+
'\\b(?:Get-Content|ReadAllText|ReadAllLines|Import-Csv|Select-String|OpenText)\\b',
|
|
94
|
+
// interpreters, inline bodies, opaque constructs
|
|
95
|
+
'\\b(?:bash|sh|zsh|pwsh|powershell|node|python|python3|perl|ruby|cmd(?:\\.exe)?)\\b',
|
|
96
|
+
'\\$-{0,1}\\(|`|<<|\\bxargs\\b|\\bfind\\b',
|
|
97
|
+
// trash / wipe / bin surfaces
|
|
98
|
+
'\\b(?:sdelete|sdelete64|shred|srm|wipe|cipher|format|robocopy|Invoke-Expression|iex|Add-Type)\\b',
|
|
99
|
+
'recycle|namespace\\(\\s*(?:10|0xa)\\s*\\)|invokeverb|\\bdoit\\b|\\.verbs\\s*\\(|shemptyrecyclebin',
|
|
100
|
+
].join('|'), 'i');
|
|
101
|
+
|
|
77
102
|
/**
|
|
78
103
|
* Reject an empty path list before any I/O.
|
|
79
104
|
* @param paths - candidate paths.
|
|
@@ -87,6 +112,32 @@ function cleanPaths(paths) {
|
|
|
87
112
|
.filter((p) => p.length > 0);
|
|
88
113
|
}
|
|
89
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Whether a shell command is a dry run (`-WhatIf`).
|
|
117
|
+
*
|
|
118
|
+
* Token-level on purpose. A textual test is fooled by the word appearing in a
|
|
119
|
+
* comment or inside a string value — measured 2026-11-25: with a textual test,
|
|
120
|
+
* `Set-Content $f $t # always -WhatIf first` and
|
|
121
|
+
* `Set-Content -Value "run -WhatIf then finish"` were both treated as dry runs even
|
|
122
|
+
* though they really write.
|
|
123
|
+
*
|
|
124
|
+
* `-WhatIf:$false` / `-WhatIf:$true` are **not** dry runs: the first really executes,
|
|
125
|
+
* and neither is the bare preview the switch is for.
|
|
126
|
+
*
|
|
127
|
+
* @param command - the raw command text.
|
|
128
|
+
* @returns whether the command would only preview.
|
|
129
|
+
*/
|
|
130
|
+
function isDryRun(command) {
|
|
131
|
+
if (typeof command !== 'string' || !/-whatif/i.test(command)) return false;
|
|
132
|
+
for (const line of command.split(/\r?\n/)) {
|
|
133
|
+
// Strip a trailing PowerShell comment so `… -WhatIf` in prose does not count.
|
|
134
|
+
const code = line.replace(/(?:^|\s)#.*$/, '');
|
|
135
|
+
// A `-WhatIf` token that is not followed by a `:` (i.e. not `:$false`).
|
|
136
|
+
if (/(?:^|\s)-whatif(?![:\w-])/i.test(code)) return true;
|
|
137
|
+
}
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
|
|
90
141
|
/**
|
|
91
142
|
* Resolve the workspace root the sandbox policy reports, falling back to the
|
|
92
143
|
* process working directory. The fallback matters: without a sandbox service
|
|
@@ -143,6 +194,20 @@ export function apply(ctx, config = {}) {
|
|
|
143
194
|
const command = args[spec.field];
|
|
144
195
|
if (typeof command !== 'string') return next();
|
|
145
196
|
|
|
197
|
+
// Cheap precondition: a command that cannot possibly delete or destroy content
|
|
198
|
+
// is not worth the full classifier.
|
|
199
|
+
//
|
|
200
|
+
// The classifier is ~250 µs on a long command (dozens of regexes over the whole
|
|
201
|
+
// text), which is real money on the tool-call path — the host pays it before
|
|
202
|
+
// every shell call. Two regexes cost ~1.8 µs and skip 88% of commands: measured
|
|
203
|
+
// on 6,000 real commands, only 11.6% mention both a reader and a writer.
|
|
204
|
+
//
|
|
205
|
+
// Deliberately over-inclusive: any mention of a delete verb, a write verb, a
|
|
206
|
+
// redirect, an interpreter, or a bin API lets the command through to the full
|
|
207
|
+
// check. A false positive here only costs time; a false negative would skip the
|
|
208
|
+
// guard, so the net is wide.
|
|
209
|
+
if (!MAY_TOUCH_FILES.test(command)) return next();
|
|
210
|
+
|
|
146
211
|
const verdict = classifyCommand(command, {
|
|
147
212
|
...guardOptions,
|
|
148
213
|
// The tool name identifies the shell language, which decides
|
|
@@ -162,6 +227,31 @@ export function apply(ctx, config = {}) {
|
|
|
162
227
|
|
|
163
228
|
// action === 'rewrite': steer the model to the recoverable path.
|
|
164
229
|
const list = verdict.targets.map((t) => `"${t}"`).join(', ');
|
|
230
|
+
|
|
231
|
+
// A dry run must not be turned into an instruction to really delete.
|
|
232
|
+
//
|
|
233
|
+
// Measured 2026-11-25: `Remove-Item -LiteralPath x.txt -WhatIf` classified as
|
|
234
|
+
// `rewrite/delete`, and this branch told the model to re-run it as `file_trash`
|
|
235
|
+
// — i.e. the user asked to preview and the guard advised destroying the file.
|
|
236
|
+
// That is a safety inversion, not a false positive. The reverse also happened:
|
|
237
|
+
// `Remove-Item -WhatIf x.txt` was refused as "no explicit operands" because
|
|
238
|
+
// `-WhatIf` was listed as a flag that consumes its value.
|
|
239
|
+
//
|
|
240
|
+
// The fix renders dry runs differently rather than omitting the statement from
|
|
241
|
+
// classification: dropping statements would let a real write be exempted by the
|
|
242
|
+
// word `-WhatIf` appearing in a comment or a string value.
|
|
243
|
+
if (isDryRun(command)) {
|
|
244
|
+
return {
|
|
245
|
+
kind: 'deny',
|
|
246
|
+
reason:
|
|
247
|
+
`This command is a dry run (\`-WhatIf\`), so nothing was executed and nothing needs to be deleted. ` +
|
|
248
|
+
`The guard does not rewrite dry runs into real deletions.\n\n` +
|
|
249
|
+
`If you actually meant to delete ${list}, call ${TRASH_TOOL} with those paths. If you only wanted to ` +
|
|
250
|
+
`preview, the command you just ran was correct — but remove \`-WhatIf\` would really delete, so don't.`,
|
|
251
|
+
info: { name: 'DeleteGuardError', code: 'DELETE_GUARD_DRY_RUN' },
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
165
255
|
return {
|
|
166
256
|
kind: 'deny',
|
|
167
257
|
reason:
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-delete-guard",
|
|
3
|
-
"version": "2.4.
|
|
3
|
+
"version": "2.4.2",
|
|
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",
|