dsh-delete-guard 2.2.3 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +202 -0
- package/README.en.md +77 -12
- package/README.ja.md +63 -11
- package/README.md +57 -7
- package/SECURITY.md +40 -3
- package/cordis.patch.yml +2 -0
- package/lib/guard.js +57 -153
- package/lib/index.js +97 -6
- package/lib/move-guard.js +17 -0
- package/lib/rewrite-guard.js +642 -0
- package/lib/shell-text.js +205 -0
- package/lib/staging.js +292 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
**让 agent 删不掉「恢复不了」的东西。**
|
|
6
6
|
|
|
7
7
|
删除只有两条路:进 Windows 回收站(资源管理器里能还原),或者被拦下来换成一次
|
|
8
|
-
`file_trash`
|
|
8
|
+
`file_trash` 调用。没有第三条:**把文件内容写没了,和把它删掉是同一件事。**
|
|
9
9
|
|
|
10
10
|
```
|
|
11
11
|
agent: Remove-Item -Recurse -Force .\src
|
|
@@ -13,6 +13,12 @@ agent: Remove-Item -Recurse -Force .\src
|
|
|
13
13
|
随后: file_trash → 移入回收站,「还原」可用
|
|
14
14
|
```
|
|
15
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
|
+
|
|
16
22
|
## 解决什么问题
|
|
17
23
|
|
|
18
24
|
DSH 里模型执行 `pwsh` 的删除命令,文件是被直接抹掉的:`ctx.fs` 没有 delete,
|
|
@@ -27,6 +33,11 @@ DSH 里模型执行 `pwsh` 的删除命令,文件是被直接抹掉的:`ctx.
|
|
|
27
33
|
`-Command` / `-EncodedCommand`、持久终端里敲的命令、Git Bash 的 `/c/...` 路径、以及清空
|
|
28
34
|
回收站的各种写法,各有对应规则。
|
|
29
35
|
|
|
36
|
+
还有一类**没有删除动词**的毁灭:把文件读进来、算一刀、再覆盖回同一个文件。
|
|
37
|
+
`$lines[0..($null-2)]` 在 PowerShell 里不是错误,而是 `$lines[0..-2]`,即「首行 + 末两行」
|
|
38
|
+
——605 行可以这样被静默保存成 24 行。这类命令既不能进回收站(网络共享根本没有回收站),
|
|
39
|
+
也不能靠事后比对发现,所以守卫在写入前就按「读改写同一文件」和「未断言的切片端点」拒绝。
|
|
40
|
+
|
|
30
41
|
## 安装
|
|
31
42
|
|
|
32
43
|
```shell
|
|
@@ -36,7 +47,7 @@ dsh plugin --profile web add dsh-delete-guard
|
|
|
36
47
|
dsh plugin --profile web add github:deepestevan/dsh-delete-guard
|
|
37
48
|
# 或者从本地 tarball(改过源码时用这条)
|
|
38
49
|
pnpm pack --pack-destination ./temp/pack # 先升 package.json 的 version
|
|
39
|
-
dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.
|
|
50
|
+
dsh plugin --profile web add file:./temp/pack/dsh-delete-guard-2.4.0.tgz
|
|
40
51
|
# 重启 dsh web:lib/*.js 只在进程启动时加载
|
|
41
52
|
```
|
|
42
53
|
|
|
@@ -66,15 +77,20 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
|
|
|
66
77
|
| 清空回收站 | `Clear-RecycleBin`(含 `&`、子壳、`-EncodedCommand` 形态)、`SHEmptyRecycleBin`、对回收站条目驱动 shell 动词、直接删 `$Recycle.Bin` 内容 |
|
|
67
78
|
| 没有回收站的位置 | UNC 共享、exFAT/FAT32 卷(在那里"回收"等于永久擦除) |
|
|
68
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` = 首行 + 末两行 |
|
|
69
82
|
|
|
70
83
|
**放行**:只读命令、只提到删除词的操作(`Select-String -Pattern "Remove-Item"`、
|
|
71
|
-
`Get-Content shred.exe
|
|
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 文本,仍按整段判)。
|
|
72
88
|
|
|
73
89
|
## 两个工具
|
|
74
90
|
|
|
75
91
|
| 工具 | 作用 |
|
|
76
92
|
| --- | --- |
|
|
77
|
-
| `file_trash { paths, reason? }` |
|
|
93
|
+
| `file_trash { paths, reason? }` | 唯一允许的删除方式。本地条目移入回收站;共享条目先复制到本地卷、校验、回收副本,之后才删原件(见「网络共享」)。逐条报告成功与失败 |
|
|
78
94
|
| `trash_status { drive? }` | 报告该卷回收站的项目数与占用,用于确认删除确实落进了回收站 |
|
|
79
95
|
|
|
80
96
|
## 配置
|
|
@@ -88,6 +104,9 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
|
|
|
88
104
|
| `forbidEmptyRecycleBin` | `true` | 禁止清空或改动回收站 |
|
|
89
105
|
| `forbidWipe` | `true` | 禁止 `shred` / `sdelete` / `srm` / `cipher /w` / `format` |
|
|
90
106
|
| `blockScriptDeletes` | `true` | 禁止脚本文件与内联字符串里的删除 |
|
|
107
|
+
| `blockTruncatingWrites` | `true` | 禁止「读改写同一文件」与「未断言的切片端点 + 写文件」 |
|
|
108
|
+
| `uncRecoverableMove` | `true` | 共享删除:先复制到本地 NTFS 卷 + 校验 + 回收副本,再删原件;`false` 则纯拒绝 |
|
|
109
|
+
| `stagingRoot` | `%LOCALAPPDATA%\dsh-delete-guard\staging` | 共享删除的暂存目录(必须在有回收站的本地卷上) |
|
|
91
110
|
|
|
92
111
|
## 恢复已删的文件
|
|
93
112
|
|
|
@@ -101,6 +120,27 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
|
|
|
101
120
|
反查;动词还原后可能残留孤儿 `$I` 记录,跳过 payload 缺失的即可。资源管理器里右键
|
|
102
121
|
「还原」与之一致,只是脚本化时别依赖本地化的动词名。
|
|
103
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
|
+
|
|
104
144
|
## 不挡什么
|
|
105
145
|
|
|
106
146
|
| 不覆盖 | 原因 |
|
|
@@ -112,6 +152,10 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
|
|
|
112
152
|
| 终端里分两次发送才拼出的删除 | 每次 send 只看到这一次的文本 |
|
|
113
153
|
| 非 Windows 平台 | 桥接是 `SHFileOperationW` |
|
|
114
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` |
|
|
115
159
|
|
|
116
160
|
覆盖的 shell 工具名:`pwsh`、`powershell`、`cmd`、`bash`、`sh`、`zsh`、`shell`、
|
|
117
161
|
`terminal_send`、`terminal_write`。判定看的是语句的命令词、调用的形态和程序位置,不是「这一行里出现过这个词」。
|
|
@@ -122,9 +166,11 @@ terminal_send: "Remove-Item C:\tmp\a.txt"
|
|
|
122
166
|
node test/run-all.mjs
|
|
123
167
|
```
|
|
124
168
|
|
|
125
|
-
|
|
126
|
-
宿主 schema 受理(5)、对真实回收站的端到端(
|
|
169
|
+
128 项、七层:命令分类(50)、覆盖守卫(22)、暂存删除(8)、`file_trash` 操作数守卫(15)、宿主 schema 与钩子接线(14)、
|
|
170
|
+
宿主 schema 受理(5)、对真实回收站的端到端(14,含真 `\\localhost\C$` 路径)。`test/` 不进 tarball,所以打包前必须
|
|
127
171
|
全绿;其中两层会加载宿主自己的校验器,找不到 DSH 安装时报「跳过」而非失败。
|
|
172
|
+
覆盖守卫那一层里,"事故命令必须被拒" 与 "42 条日常命令必须照常放行" 用的是同一份文件:
|
|
173
|
+
只拦住事故、却把 `npm run build` 也拒掉的规则不算修好。
|
|
128
174
|
|
|
129
175
|
## 文档
|
|
130
176
|
|
|
@@ -132,9 +178,13 @@ node test/run-all.mjs
|
|
|
132
178
|
| --- | --- |
|
|
133
179
|
| [CHANGELOG.md](CHANGELOG.md) | 版本摘要 |
|
|
134
180
|
| [SECURITY.md](SECURITY.md) | 威胁模型:策略层,不是沙箱 |
|
|
181
|
+
| [docs/incidents/](docs/incidents/) | 事故记录:每条规则背后的实测与逐字命令(不进 npm 包,见 `files`) |
|
|
135
182
|
| [LICENSE](LICENSE) | MIT |
|
|
136
183
|
|
|
137
|
-
|
|
184
|
+
事故记录留在仓库里,因为它就是规则的证据:一条规则若说不清"当初哪条命令、在什么条件下、
|
|
185
|
+
造成了什么后果",接手的人就只能靠猜去维护它。设计取舍、逐轮实测与发布跑批仍属维护者侧的
|
|
186
|
+
工程笔记,不随仓库与包发布。(2.2.0 曾把笔记整体移出仓库,起因是里面带私有主机名与 UNC
|
|
187
|
+
路径;记录留在仓库时按同一条标准脱敏。)
|
|
138
188
|
|
|
139
189
|
## 许可
|
|
140
190
|
|
package/SECURITY.md
CHANGED
|
@@ -15,12 +15,31 @@ command line.
|
|
|
15
15
|
- An agent deleting files the user still needs — the ordinary failure mode. Every
|
|
16
16
|
recognised delete is refused and redirected to `file_trash`
|
|
17
17
|
(`SHFileOperationW(FOF_ALLOWUNDO)`), so the item is recoverable from Explorer.
|
|
18
|
-
-
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
- Volumes whose file system has no bin at all (exFAT/FAT32): refused before the
|
|
19
|
+
shell is called, because `SHFileOperationW` erases there and still reports
|
|
20
|
+
success.
|
|
21
|
+
- **Deletion on a share, which has no bin.** `file_trash` copies the item to a
|
|
22
|
+
local NTFS volume, verifies the copy (entry set, kinds, sizes), recycles the
|
|
23
|
+
staging folder, and only then removes the original. The guarantee is about
|
|
24
|
+
**content**, not about the original path: after a successful delete the bytes are
|
|
25
|
+
in the local bin and the item at the share path is gone, because there is no bin
|
|
26
|
+
on that volume to hold it. The step order is the safety property — any failure
|
|
27
|
+
before the last step leaves the original untouched, and the last step runs only
|
|
28
|
+
after the bridge confirms the staged copy is in the bin. A share root, a tree
|
|
29
|
+
containing a reparse point, and a staging volume without room are all refused
|
|
30
|
+
before any copy.
|
|
21
31
|
- Irreversible side doors: permanent-erase programs, erases performed through
|
|
22
32
|
.NET APIs, `Invoke-Expression`, deletes delegated to `cmd.exe`, and every
|
|
23
33
|
spelling of emptying the Recycle Bin.
|
|
34
|
+
- **Content destroyed without a delete verb**: a command that reads a file and
|
|
35
|
+
overwrites that same file (`Get-Content f … | Set-Content f`, `sed -i f`,
|
|
36
|
+
`cat f > f`), and a command that slices with an unchecked `$null`-able endpoint
|
|
37
|
+
and then writes the result. Both are refused, and the refusal names the
|
|
38
|
+
copy-then-verify recipe that makes the write undoable. This is the one class
|
|
39
|
+
where routing to the bin cannot help: on a UNC share there is no bin
|
|
40
|
+
(`scripts/recycle-bin.ps1` refuses it), so prevention is the whole remedy.
|
|
41
|
+
Record:
|
|
42
|
+
[docs/incidents/2026-11-14-full-file-rewrite-truncation.md](docs/incidents/2026-11-14-full-file-rewrite-truncation.md).
|
|
24
43
|
|
|
25
44
|
## Out of scope (by design, and verified as limits)
|
|
26
45
|
|
|
@@ -38,6 +57,24 @@ a security read:
|
|
|
38
57
|
`zsh`, `shell`, `terminal_send`, `terminal_write`) are not inspected at all.
|
|
39
58
|
- Deletes inside a script file whose body the guard never sees: it refuses the
|
|
40
59
|
write and the inline forms it can see, not the executed body.
|
|
60
|
+
- Overwrites that do not read the file first (`echo x > notes.md`,
|
|
61
|
+
`Invoke-WebRequest -OutFile`, `git checkout --`). Those are deliberate rewrites,
|
|
62
|
+
not read-modify-write: the new content does not depend on the old, and refusing
|
|
63
|
+
them would mean refusing `write`/`edit` too. README 「不挡什么」 lists them.
|
|
64
|
+
- Post-hoc rollback. There is no "compare the size afterwards and restore": the
|
|
65
|
+
old bytes are needed *before* the write, `tools/post-execute` can only turn a
|
|
66
|
+
result into feedback, and a per-call tree snapshot is O(workspace) and would
|
|
67
|
+
still miss a target outside the workspace.
|
|
68
|
+
- A rule that asks. `{ kind: 'ask' }` resolves to allow in the same tick wherever
|
|
69
|
+
approvals are auto-granted — the default for unattended deployments — so this
|
|
70
|
+
plugin denies rather than asks. A rule that only looks present is worse than no
|
|
71
|
+
rule.
|
|
72
|
+
- Staging a share delete is a *copy*, not an image: ACLs, alternate data streams,
|
|
73
|
+
sparse ranges and ownership are not reproduced (timestamps are), and the
|
|
74
|
+
verification compares entry sets, kinds and sizes rather than hashes. Content
|
|
75
|
+
recovery is the goal; a byte-for-byte clone is not what you get. The cost is also
|
|
76
|
+
honest: O(size) in time and the same in free space on the staging volume, so a
|
|
77
|
+
very large tree can exceed the tool call's timeout.
|
|
41
78
|
|
|
42
79
|
## Reporting
|
|
43
80
|
|
package/cordis.patch.yml
CHANGED
package/lib/guard.js
CHANGED
|
@@ -16,8 +16,15 @@
|
|
|
16
16
|
* operands are handed back so the caller can perform a real recycle-bin move.
|
|
17
17
|
* Denial is the fallback for the cases where a safe rewrite cannot be proven
|
|
18
18
|
* (pipelines, command substitution, `-Recurse` over an unresolved glob, etc.).
|
|
19
|
+
*
|
|
20
|
+
* This module judges *deletes*. Content that is destroyed without any delete
|
|
21
|
+
* verb — an in-place rewrite of the only copy — is `rewrite-guard.js`; the two
|
|
22
|
+
* are wired together at the bottom of `classifyCommand`.
|
|
19
23
|
*/
|
|
20
24
|
|
|
25
|
+
import { commandWord, splitStatements, tokenize, unquote } from './shell-text.js';
|
|
26
|
+
import { analyzeOverwriteRisk } from './rewrite-guard.js';
|
|
27
|
+
|
|
21
28
|
/** PowerShell delete verbs whose operand list we can trust. */
|
|
22
29
|
const PS_DELETE_VERBS = ['remove-item', 'ri'];
|
|
23
30
|
/** PowerShell cmdlet aliases that mean the same thing. */
|
|
@@ -95,12 +102,32 @@ const WIPE_FLAG_SHAPES = [
|
|
|
95
102
|
];
|
|
96
103
|
|
|
97
104
|
/**
|
|
98
|
-
* A wipe-program name anywhere inside the body handed to a child
|
|
105
|
+
* A wipe-program name anywhere inside the body handed to a child *shell*
|
|
99
106
|
* (`bash -c "shred -u x"`). Such a body is shell text, not an operand, so the
|
|
100
107
|
* argument that *calls* itself out of program position does not protect it.
|
|
101
108
|
*/
|
|
102
109
|
const WIPE_NAME_IN_BODY = /\b(?:sdelete64|sdelete|shred|srm|wipe)\b/i;
|
|
103
110
|
|
|
111
|
+
/**
|
|
112
|
+
* A call that hands a string to a process, for interpreters whose body is *not*
|
|
113
|
+
* shell text. `node -e "…shred…"` only erases anything if the name reaches an
|
|
114
|
+
* `exec`/`spawn`/`system` call; without one it is a word in a string.
|
|
115
|
+
*
|
|
116
|
+
* Measured 2026-11-15, on the published 2.2.3: maintaining this very repository
|
|
117
|
+
* was refused, because the README text being written quoted `shred` inside a
|
|
118
|
+
* `node -e` body — prose, no process involved. The rule read the name anywhere in
|
|
119
|
+
* the body and could not tell documentation from a command.
|
|
120
|
+
*/
|
|
121
|
+
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;
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Child interpreters whose inline body is a shell program. For these, any name in
|
|
126
|
+
* the body counts as a program name; for every other interpreter the name must
|
|
127
|
+
* also reach a process-spawning call.
|
|
128
|
+
*/
|
|
129
|
+
const SHELL_INTERPRETERS = /\b(?:bash|sh|zsh|pwsh|powershell)\b/i;
|
|
130
|
+
|
|
104
131
|
/** Denial text shared by every permanent-erase rule. */
|
|
105
132
|
const WIPE_REASON =
|
|
106
133
|
'Permanent-erase tools (shred/sdelete/srm/cipher /w/format) are disabled by the recycle-bin guard. ' +
|
|
@@ -262,127 +289,6 @@ const FORBIDDEN_TARGETS = [
|
|
|
262
289
|
{ re: /^\$recycle\.bin$/i, what: 'the Recycle Bin itself' },
|
|
263
290
|
];
|
|
264
291
|
|
|
265
|
-
/**
|
|
266
|
-
* Strip a single layer of PowerShell quote characters.
|
|
267
|
-
* @param token - raw operand token.
|
|
268
|
-
* @returns the token without surrounding quotes.
|
|
269
|
-
*/
|
|
270
|
-
function unquote(token) {
|
|
271
|
-
const t = token.trim();
|
|
272
|
-
if (t.length >= 2) {
|
|
273
|
-
const first = t[0];
|
|
274
|
-
const last = t[t.length - 1];
|
|
275
|
-
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
|
|
276
|
-
return t.slice(1, -1);
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
return t;
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* Split a command string into statements on unquoted separators, so each
|
|
284
|
-
* statement can be classified independently.
|
|
285
|
-
*
|
|
286
|
-
* Braces are separators. PowerShell wraps a delete in a script block all the
|
|
287
|
-
* time — `if (Test-Path $p) { Remove-Item $p }`, `foreach ($f in $fs) { … }`,
|
|
288
|
-
* `& { … }`, `try { … }`, `… | ForEach-Object { … }` — and a splitter that only
|
|
289
|
-
* honours `;` and newlines leaves the verb inside the block where the
|
|
290
|
-
* first-token matcher never reaches it. That is not a theoretical gap: it is
|
|
291
|
-
* exactly how a real `Remove-Item` ran unguarded on 2026-10-18, while the same
|
|
292
|
-
* delete written across three lines was caught (the newline happened to be a
|
|
293
|
-
* separator).
|
|
294
|
-
*
|
|
295
|
-
* `${name}` is the one brace form that is a variable rather than a block, so it
|
|
296
|
-
* is consumed whole. Shredding it into `$` + `NAME}` would turn a delete
|
|
297
|
-
* target of `${TARGET_DIR}` into a literal `$`, which is worse than missing it:
|
|
298
|
-
* the redirect message would name a path that does not exist.
|
|
299
|
-
*
|
|
300
|
-
* @param command - full command text.
|
|
301
|
-
* @returns the statement strings, trimmed and non-empty.
|
|
302
|
-
*/
|
|
303
|
-
function splitStatements(command) {
|
|
304
|
-
const out = [];
|
|
305
|
-
let buf = '';
|
|
306
|
-
let quote = null;
|
|
307
|
-
for (let i = 0; i < command.length; i += 1) {
|
|
308
|
-
const ch = command[i];
|
|
309
|
-
if (quote !== null) {
|
|
310
|
-
buf += ch;
|
|
311
|
-
if (ch === quote) quote = null;
|
|
312
|
-
continue;
|
|
313
|
-
}
|
|
314
|
-
if (ch === '"' || ch === "'") {
|
|
315
|
-
quote = ch;
|
|
316
|
-
buf += ch;
|
|
317
|
-
continue;
|
|
318
|
-
}
|
|
319
|
-
if (ch === '{' && buf.endsWith('$')) {
|
|
320
|
-
const close = command.indexOf('}', i + 1);
|
|
321
|
-
const end = close === -1 ? command.length : close + 1;
|
|
322
|
-
buf += command.slice(i, end);
|
|
323
|
-
i = end - 1;
|
|
324
|
-
continue;
|
|
325
|
-
}
|
|
326
|
-
const isSep =
|
|
327
|
-
ch === ';' ||
|
|
328
|
-
ch === '\n' ||
|
|
329
|
-
ch === '\r' ||
|
|
330
|
-
ch === '|' ||
|
|
331
|
-
ch === '&' ||
|
|
332
|
-
ch === '{' ||
|
|
333
|
-
ch === '}';
|
|
334
|
-
if (isSep) {
|
|
335
|
-
if (buf.trim().length > 0) out.push(buf.trim());
|
|
336
|
-
buf = '';
|
|
337
|
-
continue;
|
|
338
|
-
}
|
|
339
|
-
buf += ch;
|
|
340
|
-
}
|
|
341
|
-
if (buf.trim().length > 0) out.push(buf.trim());
|
|
342
|
-
return out;
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
/**
|
|
346
|
-
* Tokenize a single statement into argv-like words, honouring quotes.
|
|
347
|
-
* @param statement - one statement.
|
|
348
|
-
* @returns the token list.
|
|
349
|
-
*/
|
|
350
|
-
function tokenize(statement) {
|
|
351
|
-
const out = [];
|
|
352
|
-
let buf = '';
|
|
353
|
-
let quote = null;
|
|
354
|
-
let started = false;
|
|
355
|
-
for (let i = 0; i < statement.length; i += 1) {
|
|
356
|
-
const ch = statement[i];
|
|
357
|
-
if (quote !== null) {
|
|
358
|
-
if (ch === quote) {
|
|
359
|
-
quote = null;
|
|
360
|
-
} else {
|
|
361
|
-
buf += ch;
|
|
362
|
-
}
|
|
363
|
-
started = true;
|
|
364
|
-
continue;
|
|
365
|
-
}
|
|
366
|
-
if (ch === '"' || ch === "'") {
|
|
367
|
-
quote = ch;
|
|
368
|
-
started = true;
|
|
369
|
-
continue;
|
|
370
|
-
}
|
|
371
|
-
if (ch === ' ' || ch === '\t') {
|
|
372
|
-
if (started) {
|
|
373
|
-
out.push(buf);
|
|
374
|
-
buf = '';
|
|
375
|
-
started = false;
|
|
376
|
-
}
|
|
377
|
-
continue;
|
|
378
|
-
}
|
|
379
|
-
buf += ch;
|
|
380
|
-
started = true;
|
|
381
|
-
}
|
|
382
|
-
if (started) out.push(buf);
|
|
383
|
-
return out;
|
|
384
|
-
}
|
|
385
|
-
|
|
386
292
|
/**
|
|
387
293
|
* Reduce a token to the name of the program it would execute: unquoted, with
|
|
388
294
|
* the directory dropped, lower-cased, and with a launcher extension removed.
|
|
@@ -425,36 +331,6 @@ function wipeProgramIn(statement) {
|
|
|
425
331
|
return undefined;
|
|
426
332
|
}
|
|
427
333
|
|
|
428
|
-
/**
|
|
429
|
-
* Find the command word of one statement: the token that names the thing being
|
|
430
|
-
* run, with the wrapper prefixes removed the same way `parseDeleteStatement`
|
|
431
|
-
* removes them (`&`, `.`, `(`, `@(`, `$x =`) and quotes stripped.
|
|
432
|
-
*
|
|
433
|
-
* `& "Clear-RecycleBin"` is the case that motivated this: the statement
|
|
434
|
-
* splitter treats `&` as a separator, so what is left is a bare quoted name, and
|
|
435
|
-
* a `^clear-recyclebin` regex over raw text never saw it.
|
|
436
|
-
*
|
|
437
|
-
* @param statement - one statement.
|
|
438
|
-
* @returns the command word, or `''`.
|
|
439
|
-
*/
|
|
440
|
-
function commandWord(statement) {
|
|
441
|
-
const tokens = tokenize(statement).filter((t) => t.length > 0);
|
|
442
|
-
for (let i = 0; i < tokens.length; i += 1) {
|
|
443
|
-
const t = tokens[i];
|
|
444
|
-
if (/^(?:[(\[{@&.]+|\$\(|=)$/.test(t)) continue;
|
|
445
|
-
const glued = /^[(\[{@&]+(.+)$/.exec(t);
|
|
446
|
-
if (glued !== null) return unquote(glued[1]).trim();
|
|
447
|
-
if (/^\$[A-Za-z_][\w:]*$/.test(t) && tokens[i + 1] === '=') {
|
|
448
|
-
i += 1;
|
|
449
|
-
continue;
|
|
450
|
-
}
|
|
451
|
-
const assign = /^\$[A-Za-z_][\w:]*\s*=\s*(.+)$/.exec(t);
|
|
452
|
-
if (assign !== null) return assign[1].trim();
|
|
453
|
-
return unquote(t).trim();
|
|
454
|
-
}
|
|
455
|
-
return '';
|
|
456
|
-
}
|
|
457
|
-
|
|
458
334
|
/**
|
|
459
335
|
* The body text of a statement that hands a program to a child shell:
|
|
460
336
|
* `pwsh -Command "…"`, `bash -c "…"`, `node -e "…"`.
|
|
@@ -577,11 +453,24 @@ function translatePosixPath(operand) {
|
|
|
577
453
|
* interpreter (`bash -c "shred -u x"`). The body is shell text, so the name is
|
|
578
454
|
* not in program position here and `wipeProgramIn` cannot see it.
|
|
579
455
|
*
|
|
456
|
+
* Scoped by the interpreter's language. A shell body *is* shell text, so the name
|
|
457
|
+
* anywhere in it may run. A `node -e` / `python -c` body is not: `console.log(
|
|
458
|
+
* 'shred')` erases nothing, and matching the word there refused a documentation
|
|
459
|
+
* edit that quoted the name (measured 2026-11-15). For those interpreters the name
|
|
460
|
+
* counts only where it is handed to a process-spawning call.
|
|
461
|
+
*
|
|
580
462
|
* @param statement - one statement, already split from the command.
|
|
581
463
|
* @returns the matched name, or `undefined`.
|
|
582
464
|
*/
|
|
583
465
|
function wipeProgramInInlineBody(statement) {
|
|
584
466
|
if (!INLINE_BODY_FLAGS.test(statement)) return undefined;
|
|
467
|
+
if (!SHELL_INTERPRETERS.test(statement)) {
|
|
468
|
+
const spawned = SPAWN_CALL.exec(statement);
|
|
469
|
+
if (spawned === null) return undefined;
|
|
470
|
+
const tail = statement.slice(spawned.index);
|
|
471
|
+
const named = WIPE_NAME_IN_BODY.exec(tail);
|
|
472
|
+
return named === null ? undefined : named[0].toLowerCase();
|
|
473
|
+
}
|
|
585
474
|
const found = WIPE_NAME_IN_BODY.exec(statement);
|
|
586
475
|
return found === null ? undefined : found[0].toLowerCase();
|
|
587
476
|
}
|
|
@@ -749,6 +638,8 @@ function emptyRecycleVerdict(what) {
|
|
|
749
638
|
* @param options.forbidEmptyRecycleBin - deny commands that empty the bin.
|
|
750
639
|
* @param options.forbidWipe - deny permanent-erase tools.
|
|
751
640
|
* @param options.blockScriptDeletes - deny inline script text containing deletes.
|
|
641
|
+
* @param options.blockTruncatingWrites - deny in-place rewrites that can destroy
|
|
642
|
+
* the only copy of a file's content (see `rewrite-guard.js`).
|
|
752
643
|
* @param options.dialect - which shell language the command is written in
|
|
753
644
|
* ('pwsh' or 'bash'). Defaults to 'pwsh'. Dialect-scoped rules such as the
|
|
754
645
|
* `$( … )` command-substitution check only apply to their own shell.
|
|
@@ -759,6 +650,7 @@ export function classifyCommand(command, options = {}) {
|
|
|
759
650
|
forbidEmptyRecycleBin = true,
|
|
760
651
|
forbidWipe = true,
|
|
761
652
|
blockScriptDeletes = true,
|
|
653
|
+
blockTruncatingWrites = true,
|
|
762
654
|
dialect = 'pwsh',
|
|
763
655
|
} = options;
|
|
764
656
|
|
|
@@ -878,7 +770,7 @@ export function classifyCommand(command, options = {}) {
|
|
|
878
770
|
// Scoped to shells: in Python or Ruby, `del` and `rm` are that
|
|
879
771
|
// language's own syntax, so they are judged by rule 2 instead.
|
|
880
772
|
for (const statement of statements) {
|
|
881
|
-
const shellInterp =
|
|
773
|
+
const shellInterp = SHELL_INTERPRETERS.test(statement);
|
|
882
774
|
const inlineBody = INLINE_BODY_FLAGS.test(statement);
|
|
883
775
|
if (shellInterp && inlineBody && SHELL_DELETE_VERB.test(statement)) {
|
|
884
776
|
return {
|
|
@@ -940,6 +832,18 @@ export function classifyCommand(command, options = {}) {
|
|
|
940
832
|
}
|
|
941
833
|
|
|
942
834
|
|
|
835
|
+
// Content destroyed without a delete verb: an in-place rewrite of the only
|
|
836
|
+
// copy. Judged before the rewrite collection on purpose — `file_trash` is the
|
|
837
|
+
// remedy for a *delete*, and moving the file away is precisely what a
|
|
838
|
+
// read-modify-write is not allowed to have happened (and on a UNC share there
|
|
839
|
+
// is no bin to move it into at all). Deny, and hand back the safe recipe.
|
|
840
|
+
if (blockTruncatingWrites) {
|
|
841
|
+
const risk = analyzeOverwriteRisk(command, { statements: judged, dialect });
|
|
842
|
+
if (risk !== undefined) {
|
|
843
|
+
return { action: 'deny', kind: risk.kind, reason: risk.reason };
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
943
847
|
// Rewritable deletes: collect every operand across every statement, including
|
|
944
848
|
// the ones decoded out of an -EncodedCommand body.
|
|
945
849
|
|
package/lib/index.js
CHANGED
|
@@ -35,6 +35,7 @@ import { stat } from 'node:fs/promises';
|
|
|
35
35
|
import { classifyCommand } from './guard.js';
|
|
36
36
|
import { recyclePaths, recycleBinUsage } from './recycle.js';
|
|
37
37
|
import { validateTrashTarget, workspaceRootReason } from './move-guard.js';
|
|
38
|
+
import { defaultStagingRoot, isNetworkPath, stageForRecycle } from './staging.js';
|
|
38
39
|
|
|
39
40
|
export const name = 'delete-guard';
|
|
40
41
|
export const inject = ['tools', 'systemPrompt'];
|
|
@@ -117,10 +118,16 @@ export function apply(ctx, config = {}) {
|
|
|
117
118
|
forbidEmptyRecycleBin = true,
|
|
118
119
|
forbidWipe = true,
|
|
119
120
|
blockScriptDeletes = true,
|
|
121
|
+
blockTruncatingWrites = true,
|
|
122
|
+
uncRecoverableMove = true,
|
|
123
|
+
stagingRoot,
|
|
120
124
|
} = config;
|
|
121
125
|
|
|
122
|
-
const guardOptions = { forbidEmptyRecycleBin, forbidWipe, blockScriptDeletes };
|
|
126
|
+
const guardOptions = { forbidEmptyRecycleBin, forbidWipe, blockScriptDeletes, blockTruncatingWrites };
|
|
123
127
|
const workspaceRoot = resolveWorkspaceRoot(ctx);
|
|
128
|
+
const stageRoot = typeof stagingRoot === 'string' && stagingRoot.trim().length > 0
|
|
129
|
+
? stagingRoot.trim()
|
|
130
|
+
: defaultStagingRoot();
|
|
124
131
|
|
|
125
132
|
// --- 1. Intercept destructive shell commands ------------------------------
|
|
126
133
|
|
|
@@ -203,9 +210,30 @@ export function apply(ctx, config = {}) {
|
|
|
203
210
|
schema: {
|
|
204
211
|
type: 'object',
|
|
205
212
|
additionalProperties: false,
|
|
206
|
-
required: ['recycled', 'failures'],
|
|
213
|
+
required: ['recycled', 'staged', 'failures'],
|
|
207
214
|
properties: {
|
|
208
215
|
recycled: { type: 'array', items: { type: 'string' } },
|
|
216
|
+
// Items deleted from a volume with no Recycle Bin (a UNC share): the
|
|
217
|
+
// content was copied to a local NTFS volume, verified, recycled there,
|
|
218
|
+
// and only then removed from its original location. Reported apart from
|
|
219
|
+
// `recycled` because the original path is *not* in the bin — its
|
|
220
|
+
// content is.
|
|
221
|
+
staged: {
|
|
222
|
+
type: 'array',
|
|
223
|
+
items: {
|
|
224
|
+
type: 'object',
|
|
225
|
+
additionalProperties: false,
|
|
226
|
+
required: ['path', 'staged', 'recycled', 'sourceRemoved'],
|
|
227
|
+
properties: {
|
|
228
|
+
path: { type: 'string' },
|
|
229
|
+
staged: { type: 'string' },
|
|
230
|
+
recycled: { type: 'boolean' },
|
|
231
|
+
sourceRemoved: { type: 'boolean' },
|
|
232
|
+
verification: { type: 'string' },
|
|
233
|
+
remaining: { type: 'array', items: { type: 'string' } },
|
|
234
|
+
},
|
|
235
|
+
},
|
|
236
|
+
},
|
|
209
237
|
failures: {
|
|
210
238
|
type: 'array',
|
|
211
239
|
items: {
|
|
@@ -226,13 +254,26 @@ export function apply(ctx, config = {}) {
|
|
|
226
254
|
lines.push(`Moved to the Recycle Bin (${value.recycled.length}):`);
|
|
227
255
|
for (const p of value.recycled) lines.push(` ${p}`);
|
|
228
256
|
}
|
|
257
|
+
if (value.staged.length > 0) {
|
|
258
|
+
lines.push(`Deleted from a location with no Recycle Bin (${value.staged.length}):`);
|
|
259
|
+
for (const s of value.staged) {
|
|
260
|
+
lines.push(` ${s.path}`);
|
|
261
|
+
lines.push(` content copied to ${s.staged} and recycled from there (verified: ${s.verification ?? 'n/a'})`);
|
|
262
|
+
lines.push(
|
|
263
|
+
s.sourceRemoved
|
|
264
|
+
? ` the original at that share was removed after the copy was verified — the share has no Recycle Bin, `
|
|
265
|
+
+ 'so restoring means finding this entry in the local Recycle Bin, whose original location is the staging path'
|
|
266
|
+
: ` ⚠ the original is still there: removing it failed${s.remaining?.length ? ` (${s.remaining.join(', ')})` : ''}`,
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
229
270
|
if (value.failures.length > 0) {
|
|
230
271
|
lines.push(`Failed (${value.failures.length}):`);
|
|
231
272
|
for (const f of value.failures) lines.push(` ${f.path}: ${f.error}`);
|
|
232
273
|
}
|
|
233
274
|
if (lines.length === 0) lines.push('Nothing was deleted: no usable paths were provided.');
|
|
234
275
|
lines.push('');
|
|
235
|
-
lines.push('
|
|
276
|
+
lines.push('Items reported above are recoverable from the local Recycle Bin; they were not permanently erased.');
|
|
236
277
|
return [{ type: 'text', text: lines.join('\n') }];
|
|
237
278
|
},
|
|
238
279
|
},
|
|
@@ -241,6 +282,7 @@ export function apply(ctx, config = {}) {
|
|
|
241
282
|
if (paths.length === 0) {
|
|
242
283
|
return {
|
|
243
284
|
recycled: [],
|
|
285
|
+
staged: [],
|
|
244
286
|
failures: [{ path: '(none)', error: 'no usable paths were supplied' }],
|
|
245
287
|
};
|
|
246
288
|
}
|
|
@@ -276,13 +318,52 @@ export function apply(ctx, config = {}) {
|
|
|
276
318
|
}
|
|
277
319
|
}
|
|
278
320
|
|
|
279
|
-
|
|
280
|
-
|
|
321
|
+
// A network location has no Recycle Bin, so the bridge would refuse it. When
|
|
322
|
+
// staging is enabled the item is copied to a local NTFS volume, verified,
|
|
323
|
+
// recycled from there, and only then removed from the share: the content is
|
|
324
|
+
// recoverable, the path is not. See staging.js for the step order and for
|
|
325
|
+
// what "verified" does and does not cover.
|
|
326
|
+
const staged = [];
|
|
327
|
+
const direct = [];
|
|
328
|
+
for (const path of absolute) {
|
|
329
|
+
if (!isNetworkPath(path)) {
|
|
330
|
+
direct.push(path);
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
if (!uncRecoverableMove) {
|
|
334
|
+
failures.push({
|
|
335
|
+
path,
|
|
336
|
+
error: 'a network location has no Recycle Bin, so recycling here would erase the item permanently. '
|
|
337
|
+
+ 'Copy it to a local NTFS path first, or delete it from Explorer where Windows can warn the user.',
|
|
338
|
+
});
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
const outcome = await stageForRecycle(path, {
|
|
342
|
+
stagingRoot: stageRoot,
|
|
343
|
+
recycle: (list) => recyclePaths(list, { signal: exec.signal }),
|
|
344
|
+
});
|
|
345
|
+
if (outcome.ok) {
|
|
346
|
+
staged.push({
|
|
347
|
+
path,
|
|
348
|
+
staged: outcome.staged,
|
|
349
|
+
recycled: true,
|
|
350
|
+
sourceRemoved: outcome.sourceRemoved,
|
|
351
|
+
verification: outcome.verification,
|
|
352
|
+
...(outcome.remaining === undefined ? {} : { remaining: outcome.remaining }),
|
|
353
|
+
});
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
failures.push({ path, error: outcome.error });
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (direct.length === 0) {
|
|
360
|
+
return { recycled: [], staged, failures };
|
|
281
361
|
}
|
|
282
362
|
|
|
283
|
-
const result = await recyclePaths(
|
|
363
|
+
const result = await recyclePaths(direct, { signal: exec.signal });
|
|
284
364
|
return {
|
|
285
365
|
recycled: result.recycled,
|
|
366
|
+
staged,
|
|
286
367
|
failures: [...failures, ...result.failures],
|
|
287
368
|
};
|
|
288
369
|
},
|
|
@@ -351,6 +432,10 @@ export function apply(ctx, config = {}) {
|
|
|
351
432
|
' commands typed into a persistent terminal (`terminal_send`), which is judged the same way.',
|
|
352
433
|
'- In a Git Bash session, pass paths to `file_trash` as Windows paths (`C:\\tmp\\x`), not POSIX ones.',
|
|
353
434
|
' `/c/tmp/x` is translated to `C:\\tmp\\x` for you; `~` and other mount points (`/tmp`, `/usr`) are refused.',
|
|
435
|
+
'- A network share (`\\\\host\\share\\…`) has no Recycle Bin. `file_trash` handles it by copying the item to',
|
|
436
|
+
' a local NTFS volume, verifying the copy, recycling that, and only then removing the original — so the',
|
|
437
|
+
' content is recoverable from the local bin, while the share path itself is not. Do not `Move-Item` or',
|
|
438
|
+
' `robocopy /MOV` something off a share to "delete" it: that erases the source with no bin record at all.',
|
|
354
439
|
'- Do NOT empty or modify the Recycle Bin (`Clear-RecycleBin` in any form — bare, `&`, inside a',
|
|
355
440
|
' child shell, or encoded; `SHEmptyRecycleBin`; driving the bin items\' own shell verbs; walking',
|
|
356
441
|
' `$Recycle.Bin`). All of those are blocked.',
|
|
@@ -359,6 +444,12 @@ export function apply(ctx, config = {}) {
|
|
|
359
444
|
'- Do NOT use permanent-erase tools (`shred`, `sdelete`, `srm`, `cipher /w`). That is blocked.',
|
|
360
445
|
'- Do NOT put deletions inside shell scripts or inline `-Command` / `-e` strings; they cannot be',
|
|
361
446
|
' routed to the Recycle Bin and will be refused.',
|
|
447
|
+
'- Do NOT read a file and overwrite that same file in one shell command (`Get-Content f … |',
|
|
448
|
+
' Set-Content f`, `sed -i f`, `cat f > f`). A wrong slice or filter then replaces the only copy.',
|
|
449
|
+
' Copy it to `<name>.bak-<timestamp>` first, or use the `write` / `edit` tools. A network share has',
|
|
450
|
+
' no Recycle Bin, so nothing there can be recovered after the fact.',
|
|
451
|
+
'- Before slicing with an index (`$lines[0..($idx-1)]`), assert it: `if (-not $idx) { throw "anchor',
|
|
452
|
+
' not found" }`. A null endpoint silently becomes `0..-2`, i.e. the first line plus the last two.',
|
|
362
453
|
`- To overwrite a file, prefer the \`write\` / \`edit\` tools. Use \`${TRASH_TOOL}\` only when a path must go away.`,
|
|
363
454
|
`- \`${STATUS_TOOL}\` reports current bin occupancy if you need to confirm a deletion landed.`,
|
|
364
455
|
].join('\n'),
|