dsh-delete-guard 0.0.0-stage → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md ADDED
@@ -0,0 +1,211 @@
1
+ # dsh-delete-guard
2
+
3
+ **English** | [简体中文](README.md) | [日本語](README.ja.md)
4
+
5
+ **An agent cannot delete what it cannot recover.**
6
+
7
+ A deletion has exactly two outcomes here: it lands in the Windows Recycle Bin
8
+ (restorable from Explorer), or it is refused and re-issued as a `file_trash`
9
+ call. There is no third one — and **writing the content away is the same thing as
10
+ deleting it.**
11
+
12
+ ```
13
+ agent: Remove-Item -Recurse -Force .\src
14
+ refused: The delete guard blocked this delete. Re-run this as: file_trash with paths = ["…\src"]
15
+ then: file_trash → moved to the Recycle Bin, "Restore" works
16
+ ```
17
+
18
+ ```
19
+ agent: $lines=Get-Content $f; $idx=(…Select-String…).LineNumber; Set-Content $f $lines[0..($idx-2)]
20
+ refused: …`$idx` is offset by arithmetic in a slice endpoint, it is never checked for $null…
21
+ Fix, then re-run: if (-not $idx) { throw "anchor not found" }
22
+ ```
23
+
24
+ ## The problem
25
+
26
+ In DSH a model's `pwsh` delete erases files outright: `ctx.fs` has no delete,
27
+ `ctx.shell` has only `execute()`, and nothing sits in between. One
28
+ `Remove-Item -Recurse -Force` takes a directory with it — no bin, no undo.
29
+
30
+ This plugin hooks `tools/pre-execute` (the seam the host actually routes every
31
+ tool call through), **refuses** those calls, and tells the model to use
32
+ `file_trash`. That tool moves items with `SHFileOperationW(FOF_ALLOWUNDO)` — the
33
+ same Win32 call Explorer uses — so the `$I`/`$R` metadata in `$Recycle.Bin` is
34
+ correct and Restore works.
35
+
36
+ Coverage goes past `Remove-Item`: pipelines, `xargs`, variable-built targets,
37
+ `if { }` blocks, inline `-Command` / `-EncodedCommand`, the persistent terminal,
38
+ Git Bash `/c/...` paths, and every spelling of emptying the bin.
39
+
40
+ There is a second class with **no delete verb at all**: read a file, compute a
41
+ slice, write it back over the same file. In PowerShell `$lines[0..($null-2)]` is not
42
+ an error — it is `$lines[0..-2]`, the first line plus the last two, so a 605-line
43
+ file can be saved as 24 lines silently. Such a command cannot go to the bin (a
44
+ network share has none) and cannot be caught by comparing sizes afterwards, so the
45
+ guard refuses it before the write: read-then-rewrite of one file, and an unchecked
46
+ slice endpoint that feeds a write.
47
+
48
+ ## Install
49
+
50
+ ```shell
51
+ # from npm
52
+ dsh plugin --profile web add dsh-delete-guard
53
+ # or straight from the repository
54
+ dsh plugin --profile web add github:deepestevan/dsh-delete-guard
55
+ # or from a local tarball (when you have changed the source)
56
+ pnpm pack --pack-destination ./temp/pack # bump `version` first
57
+ dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.0.tgz
58
+ # restart dsh web: lib/*.js is loaded at process start
59
+ ```
60
+
61
+ Update with `remove` then `add`: a lone `add` can answer `Already up to date` and change
62
+ nothing, and `lib/*.js` is only reloaded when the process restarts.
63
+
64
+ ## What it blocks
65
+
66
+ **Redirected into the Recycle Bin**
67
+
68
+ ```
69
+ Remove-Item C:\tmp\a.txt del / erase / rd / rmdir / rm / unlink
70
+ Remove-Item -Recurse -Force C:\tmp\dir
71
+ if (Test-Path $p) { Remove-Item $p -Force }
72
+ terminal_send: "Remove-Item C:\tmp\a.txt"
73
+ ```
74
+
75
+ **Refused outright**
76
+
77
+ | Category | Examples |
78
+ | --- | --- |
79
+ | Targets that cannot be proven | `Remove-Item $(…)`, `… \| Remove-Item`, `xargs rm`, `Remove-Item @targets`, `-Recurse C:\tmp\*` |
80
+ | Dangerous paths | `C:\`, `\`, `C:\Windows`, `Program Files`, `..\..\`, Git Bash `~` and `/tmp` |
81
+ | Erases with no delete verb | `[System.IO.File]::Delete(…)`, `Invoke-Expression "…"`, `cmd /c del`, `robocopy /MIR`, `find -delete` |
82
+ | Permanent-erase tools | `shred`, `sdelete`, `srm`, `cipher /w`, `format X:` (matched in program position only) |
83
+ | Emptying the bin | `Clear-RecycleBin` (bare, `&`, child shell, `-EncodedCommand`), `SHEmptyRecycleBin`, driving bin items' shell verbs, deleting `$Recycle.Bin` contents |
84
+ | Locations without a bin | UNC shares and exFAT/FAT32 volumes, where "recycling" is a permanent erase |
85
+ | Deletes inside scripts | shell / Python / Node inline bodies, and writing delete text into `.ps1`/`.sh`/`.py` |
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
+ | **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
+
89
+ **Allowed**: read-only work, commands that only mention a delete word
90
+ (`Select-String -Pattern "Remove-Item"`, `Get-Content shred.exe`), **restoring**
91
+ files out of the bin, `Add-Content` / `>>` / `-Append` (an append replaces
92
+ nothing), writes to `$null` / `/dev/null`, a full rewrite that first copies the file
93
+ to `.bak` or writes a temp file it verifies (the incident record's §6 spelling
94
+ passes untouched), and a wipe-program **name mentioned** inside a `node -e` / `python -c`
95
+ body — it is a program only when it reaches `exec` / `execSync` / `spawn` / `system` /
96
+ `subprocess.*` (a `bash -c` body is shell text and is judged whole).
97
+
98
+ ## Two tools
99
+
100
+ | Tool | Purpose |
101
+ | --- | --- |
102
+ | `file_trash { paths, reason? }` | The only permitted way to delete. Local items move into the Recycle Bin; share items are copied to a local volume, verified, recycled there, and only then removed (see "Network shares"). Reports per-path results |
103
+ | `trash_status { drive? }` | Item count and byte size of the bin on a volume, to confirm a deletion landed |
104
+
105
+ ## Configuration
106
+
107
+ Override in the profile's `cordis.patch.yml` (`config` is replaced as a whole
108
+ block — restate every key you want to keep):
109
+
110
+ | Key | Default | Meaning |
111
+ | --- | --- | --- |
112
+ | `enabled` | `true` | Master switch |
113
+ | `blockDestructiveCommands` | `true` | Intercept shell deletes and redirect to `file_trash` |
114
+ | `forbidEmptyRecycleBin` | `true` | Refuse emptying or modifying the bin |
115
+ | `forbidWipe` | `true` | Refuse `shred` / `sdelete` / `srm` / `cipher /w` / `format` |
116
+ | `blockScriptDeletes` | `true` | Refuse deletes in script files and inline strings |
117
+ | `blockTruncatingWrites` | `true` | Refuse read-then-rewrite of the same file, and an unchecked slice endpoint in a command that writes |
118
+ | `uncRecoverableMove` | `true` | Share deletes: copy to a local NTFS volume, verify, recycle the copy, then remove the original. `false` keeps the plain refusal |
119
+ | `stagingRoot` | `%LOCALAPPDATA%\dsh-delete-guard\staging` | Staging directory for share deletes (must be on a local volume with a bin) |
120
+
121
+ ## Restoring a deleted file
122
+
123
+ Restoring is not a plugin feature and needs none: the bin belongs to the OS.
124
+ Explorer's right-click "Restore" works. From a script, read the
125
+ `X:\$Recycle.Bin\<SID>\$I*` records (offset 24 = original path length in chars,
126
+ offset 28 = UTF-16LE path), match the one you want, and `Move-Item` its paired `$R`
127
+ file back. The `$R`/`$I` names are random, so those records are the only index;
128
+ skip any whose payload is missing. Do not depend on the localized verb name.
129
+
130
+ ## Network shares (no Recycle Bin)
131
+
132
+ A UNC path has no Recycle Bin: `SHFileOperationW` erases there and reports success,
133
+ which is why the bridge refuses those paths. `file_trash` now does what a person does
134
+ by hand, in one call, in a fixed order:
135
+
136
+ 1. copy the item to a local NTFS volume that does have a bin
137
+ (`%LOCALAPPDATA%\dsh-delete-guard\staging\<timestamp>-<name>`, override with `stagingRoot`);
138
+ 2. verify the copy against the original: same relative paths, same kinds, same sizes;
139
+ 3. recycle the staging folder — the copy is now restorable;
140
+ 4. only then remove the original.
141
+
142
+ **What that guarantees**: the *content* is recoverable from the local bin; the
143
+ *original path* is not, because the share has no bin to hold it — step 4 is an
144
+ ordinary permanent delete. The order is therefore the safety property: any failure
145
+ before step 4 leaves the original untouched, and step 4 runs only after the bridge
146
+ confirms the staged copy is in the bin.
147
+
148
+ A restore lands in the staging path, not back on the share (the bin's `$I` record
149
+ holds the staging location), so the tool prints that path in its result.
150
+
151
+ Refused, all before any copy: a share root (`\\host\share`) or a bare host; a tree
152
+ containing a **reparse point** (junction/symlink — a copy either duplicates the
153
+ target's contents or needs privileges to recreate the link); **not enough free
154
+ space** on the staging volume.
155
+
156
+ `uncRecoverableMove: false` restores the plain refusal and deletes nothing.
157
+
158
+ ## What it does not cover
159
+
160
+ | Not covered | Why |
161
+ | --- | --- |
162
+ | Deletes already inside a script file | The guard never sees the body; it refuses the write and the inline forms it can see |
163
+ | Arbitrary C# through `Add-Type` (e.g. `DeleteFileW`) | Out of reach for text matching; only the bin-specific API is named and blocked |
164
+ | A command name assembled into a variable, then `& $c` | Cannot be evaluated textually |
165
+ | Execution channels outside the tool list (custom-named shells, third-party plugins) | The list is explicit — see below |
166
+ | A delete split across two terminal sends | Each send is judged on its own text |
167
+ | Non-Windows platforms | The bridge is `SHFileOperationW` |
168
+ | Free-space exhaustion | A same-volume NTFS recycle is a rename and consumes no space, so there is nothing to pre-check |
169
+ | **Overwriting without reading** (`echo x > notes.md`, `Invoke-WebRequest -OutFile`, `git checkout -- f`) | A deliberate rewrite, not read-modify-write: the new content does not depend on the old, and `write`/`edit` do the same thing. Making every write verb a delete is the over-broad rule this plugin rejected |
170
+ | **Indirect writes inside a read-modify-write** (compilers, `npm run build`, `robocopy` over build output) | The write happens in a child process; the command text names no provable target |
171
+ | Post-write size fuse / rollback | Rolling back needs the old bytes, which must be copied *before* the write — the same target-enumeration problem. `tools/post-execute` can only turn a result into feedback, and a per-call tree snapshot is O(workspace) and would still miss a UNC target outside the workspace |
172
+ | Moving something off a share (`Move-Item`, `robocopy /MOV`) | That is a move, not a delete: the content reaches the destination, but the share copy is unlinked for good and no bin record exists. `file_trash` is the path that keeps one |
173
+
174
+ Covered shell tools: `pwsh`, `powershell`, `cmd`, `bash`, `sh`, `zsh`, `shell`,
175
+ `terminal_send`, `terminal_write`. Reasoning and measurements:
176
+ the decision is made on the statement's command word, the shape of the call, and program position — never on a word appearing somewhere in the line.
177
+
178
+ ## Tests
179
+
180
+ ```shell
181
+ node test/run-all.mjs
182
+ ```
183
+
184
+ 128 cases across seven layers: command classification (50), overwrite guard (22),
185
+ share staging (8), `file_trash` operand guard (15), host schema + hook wiring (14),
186
+ host schema acceptance (5), live end-to-end against the real Recycle Bin (14,
187
+ including a real `\\localhost\C$` path). `test/` is not shipped in the tarball, so it
188
+ must be green before packing; two layers load the host's own validators and report
189
+ **skipped** (not failed) where no DSH install exists. The overwrite-guard layer keeps
190
+ "the incident command must be refused" and "42 ordinary commands must still pass" in
191
+ one file on purpose: a rule that catches the incident and also refuses `npm run build`
192
+ is not a fix.
193
+
194
+ ## Documentation
195
+
196
+ | File | Contents |
197
+ | --- | --- |
198
+ | [CHANGELOG.md](CHANGELOG.md) | Version summaries |
199
+ | [SECURITY.md](SECURITY.md) | Threat model: a policy layer, not a sandbox |
200
+ | [docs/incidents/](docs/incidents/) | Incident records: the measurement behind each rule, with the verbatim command (not in the npm package — see `files`) |
201
+ | [LICENSE](LICENSE) | MIT |
202
+
203
+ Incident records stay in the repository because they *are* the evidence for the
204
+ rules: a rule whose origin ("which command, under what conditions, with what
205
+ result") is unavailable can only be maintained by guessing. Design rationale and
206
+ the release runbook remain the maintainer's notes and ship with neither the
207
+ repository nor the package.
208
+
209
+ ## License
210
+
211
+ MIT — see [LICENSE](LICENSE).
package/README.ja.md ADDED
@@ -0,0 +1,195 @@
1
+ # dsh-delete-guard
2
+
3
+ [English](README.en.md) | [简体中文](README.md) | **日本語**
4
+
5
+ **復元できないものは、エージェントに消させない。**
6
+
7
+ 削除の結果は 2 つだけです。Windows のごみ箱に入る(エクスプローラーから元に戻せる)
8
+ か、拒否されて `file_trash` 呼び出しに置き換わるか。それ以外はありません。
9
+ **内容を書き潰すことも、削除と同じことです。**
10
+
11
+ ```
12
+ agent: Remove-Item -Recurse -Force .\src
13
+ 拒否: The delete guard blocked this delete. Re-run this as: file_trash with paths = ["…\src"]
14
+ その後: file_trash → ごみ箱へ移動。「元に戻す」が使える
15
+ ```
16
+
17
+ ```
18
+ agent: $lines=Get-Content $f; $idx=(…Select-String…).LineNumber; Set-Content $f $lines[0..($idx-2)]
19
+ 拒否: …`$idx` is offset by arithmetic in a slice endpoint, it is never checked for $null…
20
+ Fix, then re-run: if (-not $idx) { throw "anchor not found" }
21
+ ```
22
+
23
+ ## 何を解決するか
24
+
25
+ DSH では、モデルが `pwsh` で削除を実行するとファイルはそのまま消えます。`ctx.fs` に
26
+ delete は無く、`ctx.shell` にあるのは `execute()` だけで、その間に何も挟まりません。
27
+ `Remove-Item -Recurse -Force` の一言でディレクトリごと消え、ごみ箱も取り消しもありません。
28
+
29
+ 本プラグインは `tools/pre-execute`(ホストがすべてのツール呼び出しを通す接点)にフックし、
30
+ そうした呼び出しを**拒否**して、`file_trash` を使うようモデルに伝えます。`file_trash` は
31
+ `SHFileOperationW(FOF_ALLOWUNDO)` で移動します——エクスプローラーと同じ Win32 API なので、
32
+ `$Recycle.Bin` の `$I`/`$R` メタデータが正しく作られ、「元に戻す」が機能します。
33
+
34
+ 対象は `Remove-Item` だけではありません。パイプ、`xargs`、変数で組み立てた対象、
35
+ `if { }` 内の削除、インラインの `-Command` / `-EncodedCommand`、永続ターミナル、
36
+ Git Bash の `/c/...` パス、ごみ箱を空にするあらゆる書き方に規則があります。
37
+
38
+ **削除動詞を伴わない破壊**にも規則があります。ファイルを読み、切り出し、同じファイルへ
39
+ 書き戻す形です。PowerShell では `$lines[0..($null-2)]` はエラーではなく `$lines[0..-2]`、
40
+ つまり「先頭行 + 末尾 2 行」になります——605 行が 24 行として静かに保存され得ます。
41
+ こうしたコマンドはごみ箱へ送れず(ネットワーク共有にごみ箱はありません)、事後の
42
+ サイズ比較でも見つからないため、ガードは書き込みの前に「同一ファイルの読み書き」と
43
+ 「未検査のスライス端点」として拒否します。
44
+
45
+ ## インストール
46
+
47
+ ```shell
48
+ # npm から導入
49
+ dsh plugin --profile web add dsh-delete-guard
50
+ # またはリポジトリから直接
51
+ dsh plugin --profile web add github:deepestevan/dsh-delete-guard
52
+ # またはローカルの tarball から(ソースを変更したとき)
53
+ pnpm pack --pack-destination ./temp/pack # 先に package.json の version を上げる
54
+ dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.0.tgz
55
+ # dsh web を再起動(lib/*.js はプロセス起動時に読み込まれる)
56
+ ```
57
+
58
+ 更新は `remove` → `add` の 2 段階です。`add` だけだと `Already up to date` を返して何も
59
+ 変わらないことがあり、`lib/*.js` はプロセス再起動でしか読み直されません。
60
+
61
+ ## 何を止めるか
62
+
63
+ **ごみ箱へ誘導される**
64
+
65
+ ```
66
+ Remove-Item C:\tmp\a.txt del / erase / rd / rmdir / rm / unlink
67
+ Remove-Item -Recurse -Force C:\tmp\dir
68
+ if (Test-Path $p) { Remove-Item $p -Force }
69
+ terminal_send: "Remove-Item C:\tmp\a.txt"
70
+ ```
71
+
72
+ **そのまま拒否する**
73
+
74
+ | 区分 | 例 |
75
+ | --- | --- |
76
+ | 対象を証明できない | `Remove-Item $(…)`、`… \| Remove-Item`、`xargs rm`、`Remove-Item @targets`、`-Recurse C:\tmp\*` |
77
+ | 危険なパス | `C:\`、`\`、`C:\Windows`、`Program Files`、`..\..\`、Git Bash の `~` と `/tmp` |
78
+ | 削除動詞を伴わない消去 | `[System.IO.File]::Delete(…)`、`Invoke-Expression "…"`、`cmd /c del`、`robocopy /MIR`、`find -delete` |
79
+ | 完全消去ツール | `shred`、`sdelete`、`srm`、`cipher /w`、`format X:`(プログラム位置のみで判定) |
80
+ | ごみ箱の空化 | `Clear-RecycleBin`(素の形・`&`・子シェル・`-EncodedCommand`)、`SHEmptyRecycleBin`、ごみ箱項目のシェル動詞、`$Recycle.Bin` 配下の直接削除 |
81
+ | ごみ箱が無い場所 | UNC 共有と exFAT/FAT32 ボリューム(そこで「ごみ箱へ」は完全消去と同じ) |
82
+ | スクリプト内の削除 | シェル / Python / Node のインライン本体、および削除語を含むテキストの `.ps1`/`.sh`/`.py` への書き込み |
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
+ | **未検査のスライス端点** | 同一コマンド内でファイルを書き、かつ `$idx ± n` を端点に使う(`$l[0..($idx-2)]`、`-First ($i-1)`)。`$idx` は `$null` 検査済みでない。PowerShell はエラーにせず、`0..($null-2)` は `0..-2`(先頭行 + 末尾 2 行)になる |
85
+
86
+ **許可される**:読み取り専用の作業、削除語に言及するだけのコマンド
87
+ (`Select-String -Pattern "Remove-Item"`、`Get-Content shred.exe`)、ごみ箱から
88
+ の**復元**、`Add-Content` / `>>` / `-Append`(追記は置き換えない)、`$null` / `/dev/null`
89
+ への書き込み、そして**`.bak` か検証付き一時ファイルを先に作る**全面書き換え
90
+ (事故記録 §6 の書き方はそのまま通ります)。また `node -e` / `python -c` の本体で消去ツール名に
91
+ **言及**しただけのテキストはプログラム名として扱いません——`exec` / `execSync` / `spawn` /
92
+ `system` / `subprocess.*` に渡されたときだけです(`bash -c` の本体はシェルテキストなので
93
+ 全体で判定します)。
94
+
95
+ ## 2 つのツール
96
+
97
+ | ツール | 役割 |
98
+ | --- | --- |
99
+ | `file_trash { paths, reason? }` | 唯一許可された削除手段。ローカルの項目はごみ箱へ移動し、共有の項目はローカルへ複製 → 検証 → 複製をごみ箱へ → その後に元を削除(「ネットワーク共有」参照)。パスごとに結果を報告 |
100
+ | `trash_status { drive? }` | そのボリュームのごみ箱の項目数とバイト数。削除が本当に入ったかの確認に使う |
101
+
102
+ ## 設定
103
+
104
+ プロファイルの `cordis.patch.yml` で上書きします(`config` はブロックごと置き換わるので、
105
+ 残したいキーはすべて書き直す):
106
+
107
+ | キー | 既定値 | 意味 |
108
+ | --- | --- | --- |
109
+ | `enabled` | `true` | 全体スイッチ |
110
+ | `blockDestructiveCommands` | `true` | シェル削除を横取りし `file_trash` へ誘導 |
111
+ | `forbidEmptyRecycleBin` | `true` | ごみ箱の空化・改変を拒否 |
112
+ | `forbidWipe` | `true` | `shred` / `sdelete` / `srm` / `cipher /w` / `format` を拒否 |
113
+ | `blockScriptDeletes` | `true` | スクリプトファイルとインライン文字列内の削除を拒否 |
114
+ | `blockTruncatingWrites` | `true` | 同一ファイルの読み書きと、書き込みを伴う未検査スライス端点を拒否 |
115
+ | `uncRecoverableMove` | `true` | 共有の削除:ローカル NTFS へ複製 → 検証 → 複製をごみ箱へ → その後に元を削除。`false` で拒否のみ |
116
+ | `stagingRoot` | `%LOCALAPPDATA%\dsh-delete-guard\staging` | 共有削除のステージング先(ごみ箱のあるローカルボリューム) |
117
+
118
+ ## 消したファイルを戻す
119
+
120
+ 復元はプラグインの機能ではなく、必要でもありません。ごみ箱は OS のものです。
121
+ エクスプローラーの右クリック「元に戻す」で戻せます。スクリプトからは
122
+ `X:\$Recycle.Bin\<SID>\$I*` のレコードを読み(オフセット 24 が元パスの文字数、
123
+ オフセット 28 から UTF-16LE のパス)、目的のものを探して対になる `$R` を
124
+ `Move-Item` で戻します。`$R`/`$I` の名前はランダムなので、そのレコードが唯一の索引です。
125
+ payload が無いレコードは飛ばし、ローカライズされた動詞名には依存しないこと。
126
+
127
+ ## ネットワーク共有(ごみ箱が無い)
128
+
129
+ UNC パスにごみ箱はありません。`SHFileOperationW` はそこで**消去して成功を返す**ため、ブリッジは
130
+ 先に拒否していました。`file_trash` は人が手でやることを 1 回の呼び出しで、決まった順序で行います:
131
+
132
+ 1. ごみ箱のあるローカル NTFS ボリュームへ複製(`%LOCALAPPDATA%\dsh-delete-guard\staging\<時刻>-<名前>`、`stagingRoot` で変更可)
133
+ 2. 元と突き合わせて検証:相対パス集合・種別・各ファイルのサイズ
134
+ 3. ステージングフォルダをごみ箱へ——この時点で複製は復元可能
135
+ 4. その後にだけ元を削除
136
+
137
+ **保証の範囲**:復元できるのは**内容**(ローカルのごみ箱)であり、**元のパス**ではありません。
138
+ 共有にごみ箱が無いため、4 は通常の完全削除です。だから順序そのものが安全条件で、4 より前の失敗は
139
+ 元に触れず、4 はブリッジが複製の収容を確認した後にだけ実行されます。
140
+
141
+ 復元先は共有ではなくステージングパスになります(ごみ箱の `$I` が記録するのはその場所)。ツールは
142
+ そのパスを結果に出力します。
143
+
144
+ 複製前に拒否するもの:共有ルート(`\\host\share`)やホスト名のみの形、**リパースポイント**
145
+ (ジャンクション/シンボリックリンク)を含むツリー、ステージング先の**空き容量不足**。
146
+
147
+ `uncRecoverableMove: false` で 2.3.0 の拒否のみに戻り、何も削除しません。
148
+
149
+ ## 何を守らないか
150
+
151
+ | 対象外 | 理由 |
152
+ | --- | --- |
153
+ | スクリプトファイル内に既にある削除 | 本体をガードは見ない。書き込みと、見えるインライン形を拒否するまで |
154
+ | `Add-Type` で書いた任意の C#(`DeleteFileW` など) | テキスト判定の外。ごみ箱専用 API だけは名前で塞ぐ |
155
+ | コマンド名を変数に組み立てて `& $c` | テキストでは評価できない |
156
+ | ツール名リスト外の実行経路(独自名のシェル、第三者プラグイン) | リストは明示的(下記) |
157
+ | ターミナル送信 2 回に分けて組み立てた削除 | 1 回の送信のテキストしか見ていない |
158
+ | Windows 以外 | ブリッジが `SHFileOperationW` |
159
+ | 空き容量の枯渇 | 同一 NTFS ボリューム内のごみ箱移動は rename で、新しい容量を使わない |
160
+ | **読まずに上書き**(`echo x > 既存.md`、`Invoke-WebRequest -OutFile`、`git checkout -- f`) | 意図的な書き換えであり読み書きではない。新しい内容は古い内容に依存せず、`write`/`edit` も同じことをする。すべての書き込み動詞を削除扱いにすると本プラグインが退けた過剰な規則になる |
161
+ | 読み書きの中の**間接的な書き込み**(コンパイラ、`npm run build`、`robocopy` の成果物) | 書き込みは子プロセス内で起き、コマンドテキストに証明できる対象が無い |
162
+ | 書き込み後のサイズ比較・ロールバック | 戻すには書き込み前のバイト列が必要で、結局は対象の列挙問題に戻る。`tools/post-execute` は結果をフィードバックに変えるだけで、切り詰めを巻き戻せない。毎回ツリーをスナップショットするのは O(ワークスペース) で、しかも UNC 上の対象は含まれない |
163
+ | 共有上のものを `Move-Item` / `robocopy /MOV` で移動 | それは「移動」であり「削除」ではない。内容は移動先に残るが、共有側は完全に unlink され、ごみ箱の記録も残らない。記録を残すのは `file_trash` |
164
+
165
+ 対象のシェルツール名:`pwsh`、`powershell`、`cmd`、`bash`、`sh`、`zsh`、`shell`、
166
+ `terminal_send`、`terminal_write`。判定は文の命令語・呼び出しの形・プログラム位置で行い、行内に語が現れたかどうかでは見ません。
167
+
168
+ ## テスト
169
+
170
+ ```shell
171
+ node test/run-all.mjs
172
+ ```
173
+
174
+ 7 層・128 ケース:コマンド分類(50)、上書きガード(22)、共有ステージング(8)、
175
+ `file_trash` オペランドガード(15)、ホストのスキーマとフック配線(14)、ホストのスキーマ受理(5)、
176
+ 実ごみ箱に対するエンドツーエンド(14、実 `\\localhost\C$` パスを含む)。`test/` は tarball に
177
+ 含まれないので、パック前に緑である必要があります。うち 2 層はホスト自身の検証器を読み込むため、
178
+ DSH のインストールが無い環境では失敗ではなく**スキップ**として報告されます。
179
+
180
+ ## ドキュメント
181
+
182
+ | ファイル | 内容 |
183
+ | --- | --- |
184
+ | [CHANGELOG.md](CHANGELOG.md) | バージョン摘要 |
185
+ | [SECURITY.md](SECURITY.md) | 脅威モデル:サンドボックスではなくポリシー層 |
186
+ | [docs/incidents/](docs/incidents/) | 事故記録:各規則の背景にある実測と逐語コマンド(npm パッケージには含まれません) |
187
+ | [LICENSE](LICENSE) | MIT |
188
+
189
+ 事故記録はリポジトリに残します。規則の根拠そのものだからです——「どのコマンドが、どんな条件で、
190
+ 何を壊したか」が分からない規則は、推測でしか保守できません。設計の根拠とリリース手順は
191
+ メンテナ側のノートに留め、リポジトリにもパッケージにも含めません。
192
+
193
+ ## ライセンス
194
+
195
+ MIT — [LICENSE](LICENSE)。
package/README.md CHANGED
@@ -1,3 +1,191 @@
1
- # Temporary Holding Version
1
+ # dsh-delete-guard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [English](README.en.md) | **简体中文** | [日本語](README.ja.md)
4
+
5
+ **让 agent 删不掉「恢复不了」的东西。**
6
+
7
+ 删除只有两条路:进 Windows 回收站(资源管理器里能还原),或者被拦下来换成一次
8
+ `file_trash` 调用。没有第三条:**把文件内容写没了,和把它删掉是同一件事。**
9
+
10
+ ```
11
+ agent: Remove-Item -Recurse -Force .\src
12
+ 被拒: The delete guard blocked this delete. Re-run this as: file_trash with paths = ["…\src"]
13
+ 随后: file_trash → 移入回收站,「还原」可用
14
+ ```
15
+
16
+ ```
17
+ agent: $lines=Get-Content $f; $idx=(…Select-String…).LineNumber; Set-Content $f $lines[0..($idx-2)]
18
+ 被拒: …`$idx` is offset by arithmetic in a slice endpoint, it is never checked for $null…
19
+ Fix, then re-run: if (-not $idx) { throw "anchor not found" }
20
+ ```
21
+
22
+ ## 解决什么问题
23
+
24
+ DSH 里模型执行 `pwsh` 的删除命令,文件是被直接抹掉的:`ctx.fs` 没有 delete,
25
+ `ctx.shell` 只有 `execute()`,没有任何中间层。一句 `Remove-Item -Recurse -Force`
26
+ 就能带走一整个目录,没有回收站,没有撤销。
27
+
28
+ 本插件挂在 `tools/pre-execute`(宿主真正路由每个工具调用的接缝),把这些调用**拒绝**,
29
+ 并告诉模型改用 `file_trash`;后者用 `SHFileOperationW(FOF_ALLOWUNDO)` 移动文件——和资源
30
+ 管理器删文件是同一套 Win32 API,所以 `$Recycle.Bin` 的 `$I`/`$R` 元数据正确,「还原」可用。
31
+
32
+ 挡住的不只是 `Remove-Item`:管道、`xargs`、变量拼接的目标、写在 `if { }` 里的删除、内联
33
+ `-Command` / `-EncodedCommand`、持久终端里敲的命令、Git Bash 的 `/c/...` 路径、以及清空
34
+ 回收站的各种写法,各有对应规则。
35
+
36
+ 还有一类**没有删除动词**的毁灭:把文件读进来、算一刀、再覆盖回同一个文件。
37
+ `$lines[0..($null-2)]` 在 PowerShell 里不是错误,而是 `$lines[0..-2]`,即「首行 + 末两行」
38
+ ——605 行可以这样被静默保存成 24 行。这类命令既不能进回收站(网络共享根本没有回收站),
39
+ 也不能靠事后比对发现,所以守卫在写入前就按「读改写同一文件」和「未断言的切片端点」拒绝。
40
+
41
+ ## 安装
42
+
43
+ ```shell
44
+ # 从 npm 安装
45
+ dsh plugin --profile web add dsh-delete-guard
46
+ # 或直接从仓库安装(npm 不可用时)
47
+ dsh plugin --profile web add github:deepestevan/dsh-delete-guard
48
+ # 或者从本地 tarball(改过源码时用这条)
49
+ pnpm pack --pack-destination ./temp/pack # 先升 package.json 的 version
50
+ dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.0.tgz
51
+ # 重启 dsh web:lib/*.js 只在进程启动时加载
52
+ ```
53
+
54
+ `file:` 必须指向 tarball,不能指向源码目录——目录形式 pnpm 会硬链接,源码一挪插件就悬空。
55
+
56
+ 更新走 `remove` + `add` 两步:单跑 `add` 可能返回 `Already up to date` 而什么都没换,而 `lib/*.js` 只有进程重启才会重新加载。
57
+
58
+ ## 挡住什么
59
+
60
+ **会进回收站(被重定向)**
61
+
62
+ ```
63
+ Remove-Item C:\tmp\a.txt del / erase / rd / rmdir / rm / unlink
64
+ Remove-Item -Recurse -Force C:\tmp\dir
65
+ if (Test-Path $p) { Remove-Item $p -Force }
66
+ terminal_send: "Remove-Item C:\tmp\a.txt"
67
+ ```
68
+
69
+ **直接拒绝**
70
+
71
+ | 类别 | 例子 |
72
+ | --- | --- |
73
+ | 目标不可枚举(没法证明搬对东西) | `Remove-Item $(…)`、`… \| Remove-Item`、`xargs rm`、`Remove-Item @targets`、`-Recurse C:\tmp\*` |
74
+ | 危险路径 | `C:\`、`\`、`C:\Windows`、`Program Files`、`..\..\`、Git Bash 的 `~` / `/tmp` |
75
+ | 无删除动词的擦除 | `[System.IO.File]::Delete(…)`、`Invoke-Expression "…"`、`cmd /c del`、`robocopy /MIR`、`find -delete` |
76
+ | 永久擦除工具 | `shred`、`sdelete`、`srm`、`cipher /w`、`format X:`(只按程序位置判定) |
77
+ | 清空回收站 | `Clear-RecycleBin`(含 `&`、子壳、`-EncodedCommand` 形态)、`SHEmptyRecycleBin`、对回收站条目驱动 shell 动词、直接删 `$Recycle.Bin` 内容 |
78
+ | 没有回收站的位置 | UNC 共享、exFAT/FAT32 卷(在那里"回收"等于永久擦除) |
79
+ | 脚本内删除 | 内联 shell / Python / Node 体里的删除动词与擦除调用;把含删除的文本写进 `.ps1`/`.sh`/`.py` |
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
+ | **未断言的切片端点** | 同一命令里既写文件、又用 `$idx ± n` 当区间端点(`$l[0..($idx-2)]`、`-First ($i-1)`),而 `$idx` 从没检查过 `$null`。`$null` 在 PowerShell 里不报错:`0..($null-2)` 就是 `0..-2` = 首行 + 末两行 |
82
+
83
+ **放行**:只读命令、只提到删除词的操作(`Select-String -Pattern "Remove-Item"`、
84
+ `Get-Content shred.exe`)、从回收站**还原**文件、`Add-Content` / `>>` / `-Append`
85
+ (追加不替换)、写 `$null` / `/dev/null`、以及**带 `.bak` 备份或临时文件校验**的整档重写
86
+ (事故记录 §6 的那套写法原样通过)。另外,`node -e` / `python -c` 体里**提到**擦除工具名的文本不算程序名——
87
+ 只有把它交给 `exec` / `execSync` / `spawn` / `system` / `subprocess.*` 才算(`bash -c` 体是 shell 文本,仍按整段判)。
88
+
89
+ ## 两个工具
90
+
91
+ | 工具 | 作用 |
92
+ | --- | --- |
93
+ | `file_trash { paths, reason? }` | 唯一允许的删除方式。本地条目移入回收站;共享条目先复制到本地卷、校验、回收副本,之后才删原件(见「网络共享」)。逐条报告成功与失败 |
94
+ | `trash_status { drive? }` | 报告该卷回收站的项目数与占用,用于确认删除确实落进了回收站 |
95
+
96
+ ## 配置
97
+
98
+ 在 profile 的 `cordis.patch.yml` 里覆盖(`config` 是整块替换,要保留的键必须重述):
99
+
100
+ | 键 | 默认 | 含义 |
101
+ | --- | --- | --- |
102
+ | `enabled` | `true` | 总开关 |
103
+ | `blockDestructiveCommands` | `true` | 拦截 shell 删除并重定向到 `file_trash` |
104
+ | `forbidEmptyRecycleBin` | `true` | 禁止清空或改动回收站 |
105
+ | `forbidWipe` | `true` | 禁止 `shred` / `sdelete` / `srm` / `cipher /w` / `format` |
106
+ | `blockScriptDeletes` | `true` | 禁止脚本文件与内联字符串里的删除 |
107
+ | `blockTruncatingWrites` | `true` | 禁止「读改写同一文件」与「未断言的切片端点 + 写文件」 |
108
+ | `uncRecoverableMove` | `true` | 共享删除:先复制到本地 NTFS 卷 + 校验 + 回收副本,再删原件;`false` 则纯拒绝 |
109
+ | `stagingRoot` | `%LOCALAPPDATA%\dsh-delete-guard\staging` | 共享删除的暂存目录(必须在有回收站的本地卷上) |
110
+
111
+ ## 恢复已删的文件
112
+
113
+ 恢复不是插件的功能,也不需要——回收站是操作系统的。脚本里这样还原(与界面语言无关):
114
+
115
+ 1. 读 `X:\$Recycle.Bin\<SID>\$I*` 记录:偏移 24 是原路径字符数,偏移 28 起是 UTF-16LE 原路径;
116
+ 2. 按原路径匹配到目标条目,取配对的 `$R` 文件;
117
+ 3. `Move-Item` 搬回原位。
118
+
119
+ `$R`/`$I` 的文件名是随机的(`$R3LCXYR.txt`),原文件名不在文件名里,只能靠解析 `$I`
120
+ 反查;动词还原后可能残留孤儿 `$I` 记录,跳过 payload 缺失的即可。资源管理器里右键
121
+ 「还原」与之一致,只是脚本化时别依赖本地化的动词名。
122
+
123
+ ## 网络共享(没有回收站)
124
+
125
+ UNC 路径下不存在回收站:`SHFileOperationW` 在那里是**擦除并返回成功**,所以桥接会先拒绝。
126
+ `file_trash` 于是做人在这种情况下的做法,一次调用完成,顺序固定:
127
+
128
+ 1. 把条目复制到有回收站的本地 NTFS 卷(`%LOCALAPPDATA%\dsh-delete-guard\staging\<时间戳>-<名字>`,可用 `stagingRoot` 改);
129
+ 2. 对照原件校验:相对路径集合、条目类型、每个文件的大小;
130
+ 3. 把暂存目录送进回收站——副本这时可还原;
131
+ 4. 最后才删除原件。
132
+
133
+ **保证的范围要说清**:可恢复的是**内容**(在本地回收站里),不是**原路径**——共享上没有回收站放它,
134
+ 第 4 步就是一次普通永久删除。所以顺序本身就是安全属性:第 4 步之前的任何失败都不碰原件,第 4 步只在
135
+ 桥接确认暂存副本已进回收站之后才跑。
136
+
137
+ 还原时落点是暂存路径而不是原共享路径(回收站的 `$I` 记的是暂存位置),所以工具会把该路径打出来。
138
+
139
+ 会被拒绝,且都在复制之前停住:共享根(`\\host\share`)与只有主机名的形态、树里含**重解析点**
140
+ (junction/符号链接:复制要么把目标内容一起复制进来、要么需要权限重建链接)、暂存卷**空间不足**。
141
+
142
+ `uncRecoverableMove: false` 退回 2.3.0 的纯拒绝,且什么都不删。
143
+
144
+ ## 不挡什么
145
+
146
+ | 不覆盖 | 原因 |
147
+ | --- | --- |
148
+ | 脚本文件里已有的删除(守卫从未见过内容) | 只能拒绝写入与看得见的内联形态,不能执行期改写 |
149
+ | `Add-Type` 里写任意 C#(如 `DeleteFileW`) | 文本判定够不到;只有针对回收站的 API 被点名拦掉 |
150
+ | 命令名先拼进变量再 `& $c` 调用 | 文本层面无法求值 |
151
+ | 表格外工具名的执行通道(自定义 shell 工具、第三方插件) | 覆盖名单是显式的,见下 |
152
+ | 终端里分两次发送才拼出的删除 | 每次 send 只看到这一次的文本 |
153
+ | 非 Windows 平台 | 桥接是 `SHFileOperationW` |
154
+ | 空余空间不足时的删除 | NTFS 同卷回收是 rename,不占新空间,没有可预检的东西 |
155
+ | **没读过就覆盖**(`echo x > 既有文件.md`、`Invoke-WebRequest -OutFile $f`、`git checkout -- f`) | 这是「有意重写」,不是读改写:新内容不依赖旧内容,`write`/`edit` 工具也做同一件事。按动词列举覆盖写入会连构建日志、生成配置一起拒绝,正是本插件否掉的做法 |
156
+ | 读改写里的**间接**写(编译器、`npm run build`、`robocopy` 覆盖产物) | 写入发生在子进程内部,命令文本里没有可判定的目标 |
157
+ | 写完之后再比对体积(截断熔断) | 需要覆盖前的旧内容才能回滚:`tools/post-execute` 只能把结果改成反馈,撤不回已截断的内容;每轮 shell 调用快照整棵树是 O(工作区),而且本次事故的目标在 UNC 共享上,任何工作区快照都不包含它 |
158
+ | 把共享上的东西 `Move-Item` / `robocopy /MOV` 到本地 | 那是"移动"不是"删除":内容到了目标位置,但共享上的原件被永久 unlink,没有回收站记录。要留记录就得走 `file_trash` |
159
+
160
+ 覆盖的 shell 工具名:`pwsh`、`powershell`、`cmd`、`bash`、`sh`、`zsh`、`shell`、
161
+ `terminal_send`、`terminal_write`。判定看的是语句的命令词、调用的形态和程序位置,不是「这一行里出现过这个词」。
162
+
163
+ ## 测试
164
+
165
+ ```shell
166
+ node test/run-all.mjs
167
+ ```
168
+
169
+ 128 项、七层:命令分类(50)、覆盖守卫(22)、暂存删除(8)、`file_trash` 操作数守卫(15)、宿主 schema 与钩子接线(14)、
170
+ 宿主 schema 受理(5)、对真实回收站的端到端(14,含真 `\\localhost\C$` 路径)。`test/` 不进 tarball,所以打包前必须
171
+ 全绿;其中两层会加载宿主自己的校验器,找不到 DSH 安装时报「跳过」而非失败。
172
+ 覆盖守卫那一层里,"事故命令必须被拒" 与 "42 条日常命令必须照常放行" 用的是同一份文件:
173
+ 只拦住事故、却把 `npm run build` 也拒掉的规则不算修好。
174
+
175
+ ## 文档
176
+
177
+ | 文件 | 内容 |
178
+ | --- | --- |
179
+ | [CHANGELOG.md](CHANGELOG.md) | 版本摘要 |
180
+ | [SECURITY.md](SECURITY.md) | 威胁模型:策略层,不是沙箱 |
181
+ | [docs/incidents/](docs/incidents/) | 事故记录:每条规则背后的实测与逐字命令(不进 npm 包,见 `files`) |
182
+ | [LICENSE](LICENSE) | MIT |
183
+
184
+ 事故记录留在仓库里,因为它就是规则的证据:一条规则若说不清"当初哪条命令、在什么条件下、
185
+ 造成了什么后果",接手的人就只能靠猜去维护它。设计取舍、逐轮实测与发布跑批仍属维护者侧的
186
+ 工程笔记,不随仓库与包发布。(2.2.0 曾把笔记整体移出仓库,起因是里面带私有主机名与 UNC
187
+ 路径;记录留在仓库时按同一条标准脱敏。)
188
+
189
+ ## 许可
190
+
191
+ MIT,见 [LICENSE](LICENSE)。