delete-guard-agent 0.5.0 → 0.6.0
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.md +6 -3
- package/SKILL.md +7 -0
- package/hooks/pretooluse.py +18 -9
- package/package.json +1 -1
- package/scripts/delete_guard/core.py +65 -40
- package/scripts/delete_guard/paths.py +180 -8
- package/scripts/delete_guard/rules/common.py +18 -0
- package/src/extension.ts +13 -2
package/README.md
CHANGED
|
@@ -134,7 +134,10 @@ python scripts/guard.py command "rm -rf /mnt/d/data" --json
|
|
|
134
134
|
| H11 | 目标是系统关键前缀(/usr /etc /bin /home…) | Linux | block |
|
|
135
135
|
| H12 | 目标是挂载点(删除作用于整个卷) | Linux/macOS | block |
|
|
136
136
|
| H13 | 目标是 macOS 家目录特殊目录(Documents/Library…) | macOS | block |
|
|
137
|
-
| H14 | 云/容器/ORM 工具破坏性动词(terraform destroy、prisma migrate reset、docker
|
|
137
|
+
| H14 | 云/容器/ORM 工具破坏性动词(terraform destroy、prisma migrate reset、docker 卷/容器删除、kubectl delete namespace、SQL DROP) | 全平台 | warn/block |
|
|
138
|
+
| H15 | 覆盖型销毁(通配 mv/cp 落入已存在目录、`>` 重定向清空非空文件) | 全平台 | warn |
|
|
139
|
+
| H16 | 目标是家目录根(`/home`、`/root`、`/home/<u>`、`/Users/<u>`、`C:\Users\<u>`) | 全平台 | block |
|
|
140
|
+
| H17 | 目标是凭据/密钥目录或文件(`.ssh` `.aws` `.gnupg` `.kube` `.docker` `.config/gh`、`id_rsa`、`.netrc`…) | 全平台 | block |
|
|
138
141
|
|
|
139
142
|
## 代码结构(0.2 起拆包;0.3 起 find/git 意图在 core.py 内原生解析)
|
|
140
143
|
|
|
@@ -167,7 +170,7 @@ python -m unittest discover tests -v
|
|
|
167
170
|
以下项已由 CI 的 `ubuntu-latest` / `windows-latest` / `macos-latest` runner
|
|
168
171
|
或真机 E2E 覆盖:
|
|
169
172
|
|
|
170
|
-
- [x] 单元测试(
|
|
173
|
+
- [x] 单元测试(140 个,含 H3/H4/H11-H15/find/git 断言、中文社区与第四轮事故回归、预筛一致性比对、过度拦截反例)在
|
|
171
174
|
ubuntu + windows + macos 三个 runner 上跑
|
|
172
175
|
- [x] macOS 真机回归(H3 APFS 大小写、H13 家目录特殊目录)——由
|
|
173
176
|
`macos-latest` runner 真机执行,不再是仅静态判定
|
|
@@ -193,7 +196,7 @@ python -m unittest discover tests -v
|
|
|
193
196
|
规则集未经实战,你的真实使用是最有价值的数据源。遇到以下情况请开
|
|
194
197
|
[误报/漏报 issue](https://github.com/xinghe-labs/blast-radius-guard/issues/new?template=false-positive.yml):
|
|
195
198
|
|
|
196
|
-
- **误报**:安全的命令被 block
|
|
199
|
+
- **误报**:安全的命令被 block(比如正常的清理脚本被拦,或 `rg "terraform destroy"` 被当成要执行)
|
|
197
200
|
- **漏报**:危险的命令被 allow/warn
|
|
198
201
|
|
|
199
202
|
模板会引导你贴出命令原文、OS 和 `--json` 判定输出——这是调规则需要的全部信息。
|
package/SKILL.md
CHANGED
|
@@ -48,6 +48,13 @@ description: Use before running ANY destructive file operation (rm -rf, rd /s /q
|
|
|
48
48
|
删的是挂载进来的整个卷(rsync --delete 清空备份盘是运维最经典的整卷事故)。
|
|
49
49
|
8. **非判定宿主的平台语义不算数。** 在 WSL 里看不到 NTFS reparse 属性、
|
|
50
50
|
在 Linux 上验证不了 APFS 大小写语义。判定结果为"无法验证"时,去目标平台复跑。
|
|
51
|
+
9. **家目录和凭据目录不在"可清理"范围内,永远(判定器 H16/H17)。** `/home`、`/root`、
|
|
52
|
+
`/home/<user>`、`/Users/<user>`、`C:\Users\<user>` 是"这个人在机器上的
|
|
53
|
+
全部身份";`.ssh`、`.aws`、`.gnupg`、`.kube`、`.docker`、`.config/gh`、
|
|
54
|
+
`.netrc`、`id_rsa` 删除不可逆,私钥还必须按已泄露处理。事故:
|
|
55
|
+
claude-code#83058(~200GB 家目录)、STUPID-2026-0128(SSH/AWS/GH 凭据全毁)、
|
|
56
|
+
deepseek-harness#13675(%USERPROFILE% 下 86k 文件)。清理"缓存/临时文件"时,
|
|
57
|
+
路径必须显式落在具体项目目录内,且不得向上用 `..` 或家目录变量兜底。
|
|
51
58
|
|
|
52
59
|
## 操作流程
|
|
53
60
|
|
package/hooks/pretooluse.py
CHANGED
|
@@ -30,6 +30,7 @@ from __future__ import annotations
|
|
|
30
30
|
|
|
31
31
|
import json
|
|
32
32
|
import os
|
|
33
|
+
import re
|
|
33
34
|
import subprocess
|
|
34
35
|
import sys
|
|
35
36
|
from pathlib import Path
|
|
@@ -37,6 +38,21 @@ from pathlib import Path
|
|
|
37
38
|
GUARD_TIMEOUT = 5
|
|
38
39
|
RELEVANT_TOOLS = {"Bash", "PowerShell"}
|
|
39
40
|
|
|
41
|
+
# 快速预筛(与 src/extension.ts 的同名模式保持逐字一致,测试会比对两边):
|
|
42
|
+
# 不含删除/移动/破坏性工具动词的命令直接放行,省掉一次 Python 子进程。
|
|
43
|
+
# 0.5.1 修:旧版只认 shell 删除动词,H14(云/容器/ORM/SQL)与 H15(> 重定向)
|
|
44
|
+
# 的 block 判定永远到不了 hook —— 硬拦截层对这两类规则形同虚设。
|
|
45
|
+
QUICK_PREDICATE_SRC = (
|
|
46
|
+
r"(?:\b(?:rm|rmdir|del|erase|rd|unlink|shred|trash|remove-item|ri|move-item|"
|
|
47
|
+
r"mv|move|sudo|doas|su)\b)"
|
|
48
|
+
r"|(?:\bgit\s+(?:clean|worktree|rm)\b)"
|
|
49
|
+
r"|(?:\bfind\b[^|;]*?-delete\b)"
|
|
50
|
+
r"|(?:\b(?:docker|terraform|pulumi|kubectl|prisma|alembic|drizzle|railway|"
|
|
51
|
+
r"gcloud|supabase|neon|kiro|psql|mysql|mariadb|sqlite3|sqlcmd|aws)\b)"
|
|
52
|
+
r"|>>?"
|
|
53
|
+
)
|
|
54
|
+
QUICK_PREDICATE = re.compile(QUICK_PREDICATE_SRC, re.IGNORECASE)
|
|
55
|
+
|
|
40
56
|
_PY_CACHE: list[str] | None = None
|
|
41
57
|
|
|
42
58
|
|
|
@@ -69,13 +85,6 @@ def resolve_python() -> list[str] | None:
|
|
|
69
85
|
return None
|
|
70
86
|
# 注:find -delete 形态不在判定范围(见 SKILL.md「范围外形态」),
|
|
71
87
|
# 预筛不含它,避免永不匹配的死条目。
|
|
72
|
-
QUICK_PREDICATE = (
|
|
73
|
-
"rm ", "rm -", "rmdir", "del ", "erase", "rd ", "unlink", "shred",
|
|
74
|
-
"remove-item", "move-item", " move ", "mv ", "sudo rm", "trash ",
|
|
75
|
-
"rmrf",
|
|
76
|
-
)
|
|
77
|
-
|
|
78
|
-
|
|
79
88
|
def guard_path() -> Path | None:
|
|
80
89
|
here = Path(__file__).resolve().parent.parent
|
|
81
90
|
p = here / "scripts" / "guard.py"
|
|
@@ -103,8 +112,8 @@ def main() -> int:
|
|
|
103
112
|
)
|
|
104
113
|
return 2
|
|
105
114
|
|
|
106
|
-
low = command
|
|
107
|
-
if not
|
|
115
|
+
low = command
|
|
116
|
+
if not QUICK_PREDICATE.search(low):
|
|
108
117
|
return 0
|
|
109
118
|
|
|
110
119
|
gp = guard_path()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "delete-guard-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Blast-radius judge for destructive commands on Windows, Linux and macOS: blocks filesystem-root and volume-root deletes, quote-chain degradation, NTFS/APFS case collisions, junction and symlink traversal, sudo-escalated deletes, system-prefix wipes and mount-point deletions before the agent executes them.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "xinghe-labs",
|
|
@@ -13,29 +13,33 @@ import re
|
|
|
13
13
|
from dataclasses import dataclass, field
|
|
14
14
|
|
|
15
15
|
from .paths import (
|
|
16
|
+
_CMD_FLAG_RE,
|
|
17
|
+
_REPARSE_ATTR,
|
|
18
|
+
_SHELL_VAR_RE,
|
|
16
19
|
DELETE_VERBS_POSIX,
|
|
17
20
|
DELETE_VERBS_PS,
|
|
18
21
|
DELETE_VERBS_WIN,
|
|
22
|
+
FORCE_LONG,
|
|
23
|
+
FORCE_SHORT,
|
|
19
24
|
MOVE_VERBS,
|
|
20
25
|
PRIVILEGE_ESCALATORS,
|
|
21
26
|
RECURSIVE_LONG,
|
|
22
27
|
RECURSIVE_SHORT,
|
|
23
|
-
FORCE_LONG,
|
|
24
|
-
FORCE_SHORT,
|
|
25
28
|
SHELL_LAUNCHERS,
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
+
analysis_path,
|
|
30
|
+
cloud_tool_match,
|
|
31
|
+
glob_base_dir,
|
|
29
32
|
has_cjk,
|
|
33
|
+
home_destruction,
|
|
30
34
|
human_bytes,
|
|
31
35
|
is_ancestor_of_cwd,
|
|
32
36
|
is_drive_root,
|
|
33
|
-
|
|
34
|
-
glob_base_dir,
|
|
35
|
-
overwrite_risk,
|
|
37
|
+
is_windows_style_path,
|
|
36
38
|
is_wsl_windows_mount,
|
|
37
39
|
macos_home_special,
|
|
40
|
+
overwrite_risk,
|
|
38
41
|
posix_system_prefix,
|
|
42
|
+
same_path,
|
|
39
43
|
)
|
|
40
44
|
from .platform import host_name, is_wsl, unknowns_for_host
|
|
41
45
|
from .rules import RULES, VERDICT_ORDER
|
|
@@ -272,9 +276,7 @@ def is_flag_token(v: str, cmd_verb: bool = False) -> bool:
|
|
|
272
276
|
# POSIX 删除动词下的 /d /x 是真实路径(目录名恰好单字母合法存在)
|
|
273
277
|
if _CMD_FLAG_RE.match(v):
|
|
274
278
|
return cmd_verb
|
|
275
|
-
|
|
276
|
-
return True
|
|
277
|
-
return False
|
|
279
|
+
return bool(_CMD_LONG_FLAG_RE.match(v) and cmd_verb)
|
|
278
280
|
|
|
279
281
|
|
|
280
282
|
@dataclass
|
|
@@ -393,9 +395,7 @@ def extract_intent(parsed: ParsedCommand) -> Intent:
|
|
|
393
395
|
force = True
|
|
394
396
|
if tok in {"/purge", "--prune-empty-dirs"}:
|
|
395
397
|
force = True
|
|
396
|
-
if tok in {f.lower() for f in RECURSIVE_LONG}:
|
|
397
|
-
recursive = True
|
|
398
|
-
elif tok in RECURSIVE_LONG:
|
|
398
|
+
if tok in {f.lower() for f in RECURSIVE_LONG} or tok in RECURSIVE_LONG:
|
|
399
399
|
recursive = True
|
|
400
400
|
elif tok.startswith("-") and not tok.startswith("--"):
|
|
401
401
|
body = tok.lstrip("-")
|
|
@@ -465,34 +465,39 @@ def case_collision(path: str, windows_layout: bool | None = None) -> str | None:
|
|
|
465
465
|
NTFS/APFS 大小写不敏感 —— 这正是 D:\\CampusconnECT 删掉
|
|
466
466
|
D:\\CampusConnect 的原因(claude-code#60442)。
|
|
467
467
|
|
|
468
|
-
windows_layout 为 None
|
|
468
|
+
windows_layout 为 None 时按目标形态推断(盘符路径走 Windows 布局,
|
|
469
|
+
绝对 POSIX 路径走 macOS 布局)。刻意**不**用 os.name 推断:那样
|
|
470
|
+
macOS 分支在 Linux 上永远不可测,测试无法覆盖 APFS 路径(0.5.1 修)。
|
|
471
|
+
仅用于测试显式指定布局。
|
|
469
472
|
"""
|
|
470
473
|
if not path or not case_insensitive_host():
|
|
471
474
|
return None
|
|
472
475
|
if windows_layout is None:
|
|
473
|
-
windows_layout =
|
|
476
|
+
windows_layout = is_windows_style_path(path)
|
|
474
477
|
# 逐级比对大小写:Windows 走盘符/反斜杠布局,macOS 走 POSIX 布局
|
|
478
|
+
# 回归(0.5.1):POSIX 分支曾用 os.path.join("", seg) 丢掉根目录,
|
|
479
|
+
# 路径退化成相对,逐级核对在第二段就 listdir 失败 → macOS 上 H3 永不触发
|
|
475
480
|
if windows_layout:
|
|
476
481
|
drive, tail = ntpath.splitdrive(path)
|
|
477
482
|
segments = [s for s in tail.replace("/", "\\").split("\\") if s]
|
|
478
|
-
cur = drive + "\\" if drive else ""
|
|
479
|
-
|
|
483
|
+
cur = drive + "\\" if drive else "."
|
|
484
|
+
joiner = ntpath.join
|
|
480
485
|
else:
|
|
481
486
|
segments = [s for s in path.replace("\\", "/").split("/") if s]
|
|
482
|
-
cur = ""
|
|
483
|
-
|
|
487
|
+
cur = "/"
|
|
488
|
+
joiner = os.path.join
|
|
484
489
|
for seg in segments:
|
|
485
490
|
try:
|
|
486
|
-
entries = os.listdir(cur
|
|
491
|
+
entries = os.listdir(cur)
|
|
487
492
|
except OSError:
|
|
488
493
|
return None
|
|
489
494
|
match = next((e for e in entries if e == seg), None)
|
|
490
495
|
if match is None:
|
|
491
496
|
ci = next((e for e in entries if e.lower() == seg.lower()), None)
|
|
492
497
|
if ci is not None:
|
|
493
|
-
return
|
|
498
|
+
return joiner(cur, ci)
|
|
494
499
|
return None
|
|
495
|
-
cur =
|
|
500
|
+
cur = joiner(cur, match)
|
|
496
501
|
return None
|
|
497
502
|
|
|
498
503
|
|
|
@@ -556,9 +561,7 @@ def _is_reparse(entry: os.DirEntry, st: os.stat_result) -> bool:
|
|
|
556
561
|
if entry.is_symlink():
|
|
557
562
|
return True
|
|
558
563
|
attrs = getattr(st, "st_file_attributes", 0)
|
|
559
|
-
|
|
560
|
-
return True
|
|
561
|
-
return False
|
|
564
|
+
return bool(attrs & _REPARSE_ATTR)
|
|
562
565
|
|
|
563
566
|
|
|
564
567
|
def is_mount_point(path: str) -> bool:
|
|
@@ -576,7 +579,7 @@ def is_mount_point(path: str) -> bool:
|
|
|
576
579
|
fields = line.split()
|
|
577
580
|
if len(fields) >= 2:
|
|
578
581
|
mp = fields[1].replace("\\040", " ").replace("\\011", "\t")
|
|
579
|
-
if mp
|
|
582
|
+
if mp in (real, path):
|
|
580
583
|
return True
|
|
581
584
|
except OSError:
|
|
582
585
|
return False
|
|
@@ -588,6 +591,11 @@ def is_mount_point(path: str) -> bool:
|
|
|
588
591
|
# ---------------------------------------------------------------------------
|
|
589
592
|
|
|
590
593
|
|
|
594
|
+
def _home_code(kind: str) -> str:
|
|
595
|
+
"""home_destruction 的类别 → 规则码。"""
|
|
596
|
+
return "H17_CREDENTIAL_TARGET" if kind == "cred" else "H16_HOME_ROOT"
|
|
597
|
+
|
|
598
|
+
|
|
591
599
|
def judge_command(
|
|
592
600
|
command: str,
|
|
593
601
|
cwd: str | None = None,
|
|
@@ -657,7 +665,7 @@ def judge_command(
|
|
|
657
665
|
f"目标带引号且含空格/CJK,经 {' -> '.join(layers)} 跳转时"
|
|
658
666
|
"参数会在层间被重新解释",
|
|
659
667
|
)
|
|
660
|
-
lower_layers = [
|
|
668
|
+
lower_layers = [layer.lower() for layer in layers]
|
|
661
669
|
inner_wsl = (
|
|
662
670
|
wsl_context
|
|
663
671
|
if wsl_context is not None
|
|
@@ -666,7 +674,7 @@ def judge_command(
|
|
|
666
674
|
inner_priv = (
|
|
667
675
|
privileged_context
|
|
668
676
|
if privileged_context is not None
|
|
669
|
-
else any(
|
|
677
|
+
else any(layer in PRIVILEGE_ESCALATORS for layer in lower_layers)
|
|
670
678
|
)
|
|
671
679
|
return _merge_inner(
|
|
672
680
|
hazards,
|
|
@@ -709,7 +717,7 @@ def judge_command(
|
|
|
709
717
|
# 原生 Linux 上 /mnt 下可能是任意普通挂载,交由 H12 按真实挂载表判定。
|
|
710
718
|
if wsl_context is None:
|
|
711
719
|
wsl_context = is_wsl() or "wsl" in [
|
|
712
|
-
|
|
720
|
+
layer.lower() for layer in parsed.shell_layers
|
|
713
721
|
]
|
|
714
722
|
|
|
715
723
|
# H15 覆盖型销毁(命令级判定;需要目标存在性核对,仅在真实 FS 上有效)
|
|
@@ -756,12 +764,15 @@ def judge_command(
|
|
|
756
764
|
radii: list[BlastRadius] = []
|
|
757
765
|
for target in intent.targets:
|
|
758
766
|
radii.append(walk_blast_radius(target))
|
|
767
|
+
# 判定用的归一形态:展开 ~ / $HOME、合并 .. 与 .(不跟链接)
|
|
768
|
+
ap = analysis_path(target)
|
|
759
769
|
|
|
760
|
-
if is_drive_root(
|
|
770
|
+
if is_drive_root(ap):
|
|
761
771
|
add("H2_DRIVE_ROOT", f"目标 {target!r} 是卷根")
|
|
762
772
|
|
|
763
773
|
real = case_collision(target)
|
|
764
|
-
|
|
774
|
+
# 不能用 normcase 比较:Windows 上它把大小写抹平,等于把 H3 关掉
|
|
775
|
+
if real and not same_path(real, target):
|
|
765
776
|
add("H3_CASE_COLLISION", f"{target!r} 实际指向已存在的 {real!r}")
|
|
766
777
|
|
|
767
778
|
br = radii[-1]
|
|
@@ -822,19 +833,28 @@ def judge_command(
|
|
|
822
833
|
)
|
|
823
834
|
|
|
824
835
|
# H11 系统关键前缀(含变量退化形态,如空变量后剩余的 /*)
|
|
825
|
-
sys_prefix = posix_system_prefix(
|
|
836
|
+
sys_prefix = posix_system_prefix(ap)
|
|
826
837
|
if sys_prefix and intent.recursive:
|
|
827
838
|
add("H11_SYSTEM_PREFIX", f"{target!r} 命中系统前缀 {sys_prefix}")
|
|
828
839
|
|
|
829
840
|
# H12 挂载点
|
|
830
|
-
if intent.recursive and is_mount_point(
|
|
841
|
+
if intent.recursive and is_mount_point(ap):
|
|
831
842
|
add("H12_MOUNT_POINT", f"{target!r} 是挂载点,删除作用于整个卷")
|
|
832
843
|
|
|
833
|
-
# H13 macOS
|
|
834
|
-
special = macos_home_special(
|
|
844
|
+
# H13 macOS 家目录特殊目录(~/Downloads 这类形态归一后也要命中)
|
|
845
|
+
special = macos_home_special(ap)
|
|
835
846
|
if special:
|
|
836
847
|
add("H13_MACOS_HOME_SPECIAL", f"{target!r} 命中 macOS 家目录特殊目录 {special}")
|
|
837
848
|
|
|
849
|
+
# H16/H17 家目录根 & 凭据目录/文件:删除即不可逆、无回收余地。
|
|
850
|
+
# 家目录根只在递归删除时成灾(非递归只会 rmdir 失败),凭据目录/文件
|
|
851
|
+
# 即使单文件删除也已不可逆,故不受 recursive 约束。
|
|
852
|
+
hit = home_destruction(ap)
|
|
853
|
+
if hit:
|
|
854
|
+
kind, desc = hit
|
|
855
|
+
if kind == "cred" or intent.recursive:
|
|
856
|
+
add(_home_code(kind), f"{target!r} 命中{desc}")
|
|
857
|
+
|
|
838
858
|
unknowns.extend(unknowns_for_host())
|
|
839
859
|
if any(br.truncated for br in radii):
|
|
840
860
|
unknowns.append("爆炸半径统计已达上限,实际文件数更多")
|
|
@@ -859,7 +879,7 @@ def judge_path(path: str, cwd: str | None = None) -> dict:
|
|
|
859
879
|
if is_drive_root(path):
|
|
860
880
|
add("H2_DRIVE_ROOT", f"{path!r} 是卷根")
|
|
861
881
|
real = case_collision(path)
|
|
862
|
-
if real and
|
|
882
|
+
if real and not same_path(real, path):
|
|
863
883
|
add("H3_CASE_COLLISION", f"{path!r} 实际指向已存在的 {real!r}")
|
|
864
884
|
if has_cjk(path):
|
|
865
885
|
add("H5_CJK_SILENT_FAIL", f"路径含 CJK:{path!r}")
|
|
@@ -872,14 +892,19 @@ def judge_path(path: str, cwd: str | None = None) -> dict:
|
|
|
872
892
|
if br.reparse_points:
|
|
873
893
|
add("H4_REPARSE_TRAVERSAL", f"{path!r} 子树内有 {br.reparse_points} 个链接")
|
|
874
894
|
|
|
875
|
-
|
|
895
|
+
ap = analysis_path(path)
|
|
896
|
+
sys_prefix = posix_system_prefix(ap)
|
|
876
897
|
if sys_prefix:
|
|
877
898
|
add("H11_SYSTEM_PREFIX", f"{path!r} 命中系统前缀 {sys_prefix}")
|
|
878
|
-
if is_mount_point(
|
|
899
|
+
if is_mount_point(ap):
|
|
879
900
|
add("H12_MOUNT_POINT", f"{path!r} 是挂载点")
|
|
880
|
-
special = macos_home_special(
|
|
901
|
+
special = macos_home_special(ap)
|
|
881
902
|
if special:
|
|
882
903
|
add("H13_MACOS_HOME_SPECIAL", f"{path!r} 命中 macOS 家目录特殊目录 {special}")
|
|
904
|
+
hit = home_destruction(ap)
|
|
905
|
+
if hit:
|
|
906
|
+
kind, desc = hit
|
|
907
|
+
add(_home_code(kind), f"{path!r} 命中{desc}")
|
|
883
908
|
|
|
884
909
|
unknowns.extend(unknowns_for_host())
|
|
885
910
|
|
|
@@ -201,6 +201,96 @@ def has_cjk(s: str) -> bool:
|
|
|
201
201
|
return False
|
|
202
202
|
|
|
203
203
|
|
|
204
|
+
# H16 家目录 / 凭据目录:递归删除这里 = 毁掉一个人在机器上的全部身份
|
|
205
|
+
# (SSH/AWS/GitHub 凭据、未备份的工作成果)。依据见 INCIDENTS.md 候选 21-23:
|
|
206
|
+
# 家目录整体 ~200GB(claude-code#83058)、700GB 主目录、
|
|
207
|
+
# %USERPROFILE% 下 86k 文件(deepseek-harness#13675)、~/.ssh 全毁。
|
|
208
|
+
POSIX_HOME_ROOTS = {"home", "root"}
|
|
209
|
+
|
|
210
|
+
# 凭据/密钥目录:按段序列匹配,不限前缀(~/.ssh、/home/u/.ssh、C:\Users\u\.ssh 同判)
|
|
211
|
+
CREDENTIAL_DIRS = {
|
|
212
|
+
(".ssh",), (".aws",), (".gnupg",), (".pki",), (".kube",), (".docker",),
|
|
213
|
+
(".config", "gh"), (".config", "gcloud"),
|
|
214
|
+
}
|
|
215
|
+
# 单个凭据文件(删掉一个私钥同样是不可逆的凭据丢失)
|
|
216
|
+
CREDENTIAL_FILES = {
|
|
217
|
+
".netrc", ".git-credentials", ".npmrc", ".pypirc",
|
|
218
|
+
"id_rsa", "id_ed25519", "id_ecdsa",
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def home_destruction(path: str) -> tuple[str, str] | None:
|
|
223
|
+
"""H16/H17:目标是家目录根本身、或家目录下的凭据目录/文件。
|
|
224
|
+
|
|
225
|
+
返回 ("home" | "cred", 描述文本),否则 None。
|
|
226
|
+
入参应是归一后的形态(analysis_path 已展开 ~ / $HOME / %USERPROFILE%)。
|
|
227
|
+
"""
|
|
228
|
+
p = path.strip().strip("'\"")
|
|
229
|
+
if not p:
|
|
230
|
+
return None
|
|
231
|
+
norm = p.replace("\\", "/")
|
|
232
|
+
# 盘符路径(C:/Users/...)与 POSIX 路径共用 split,但跳过驱动器段
|
|
233
|
+
segs = [s for s in norm.split("/") if s and not (len(s) == 2 and s[1] == ":")]
|
|
234
|
+
if not segs:
|
|
235
|
+
return None
|
|
236
|
+
low = [s.lower() for s in segs]
|
|
237
|
+
|
|
238
|
+
# 1) POSIX 家目录根:/home、/root、/home/<user>
|
|
239
|
+
if len(low) == 1 and low[0] in POSIX_HOME_ROOTS:
|
|
240
|
+
return "home", f"家目录根 `/{low[0]}`(所有用户数据与凭据)"
|
|
241
|
+
# 2) 家目录根:/home/<user>、/Users/<user>、C:\\Users\\<user>(恰好两段)
|
|
242
|
+
if len(low) == 2 and low[0] in ("home", "users"):
|
|
243
|
+
return "home", f"家目录根 `/{segs[0]}/{segs[1]}`(全部个人数据与凭据)"
|
|
244
|
+
|
|
245
|
+
# 3) 凭据目录:任一段序列命中 CREDENTIAL_DIRS
|
|
246
|
+
for cred in CREDENTIAL_DIRS:
|
|
247
|
+
n = len(cred)
|
|
248
|
+
for i in range(len(low) - n + 1):
|
|
249
|
+
if tuple(low[i:i + n]) == cred:
|
|
250
|
+
shown = segs[i] if n == 1 else "/".join(segs[i:i + n])
|
|
251
|
+
return "cred", f"凭据/密钥目录 `{shown}`"
|
|
252
|
+
# 4) 凭据文件
|
|
253
|
+
if low[-1] in CREDENTIAL_FILES:
|
|
254
|
+
return "cred", f"凭据文件 `{segs[-1]}`"
|
|
255
|
+
return None
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def same_path(a: str, b: str) -> bool:
|
|
259
|
+
"""大小写敏感的字面比较(H3 用)。
|
|
260
|
+
|
|
261
|
+
os.path.normcase 在 Windows 上会 lowercase 整条路径 —— 用它比较
|
|
262
|
+
"目标 vs 磁盘真实路径" 等于把 H3 在唯一真正需要它的平台上关掉:
|
|
263
|
+
D:\\CampusconnECT 与 D:\\CampusConnect 会被判成同一个路径。
|
|
264
|
+
normpath 只做分隔符/.. 归一,保留大小写。
|
|
265
|
+
"""
|
|
266
|
+
try:
|
|
267
|
+
return os.path.normpath(os.path.expanduser(a)) == os.path.normpath(
|
|
268
|
+
os.path.expanduser(b)
|
|
269
|
+
)
|
|
270
|
+
except (TypeError, ValueError, OSError):
|
|
271
|
+
return False
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def analysis_path(target: str) -> str:
|
|
275
|
+
"""把目标归一成"判定用的绝对形态":展开 ~ 与 $HOME、合并 .. / .、
|
|
276
|
+
统一分隔符,但**不做存在性检查也不做 realpath**(realpath 会跟掉
|
|
277
|
+
junction,H4 需要看到链接本身)。
|
|
278
|
+
|
|
279
|
+
目的:让 `~/Downloads`、`/Users/me/../me/Documents`、`D:\\a\\..\\`
|
|
280
|
+
这类形态在 H2/H11/H13 面前与它们的绝对形态等价。
|
|
281
|
+
"""
|
|
282
|
+
p = target.strip().strip("'\"")
|
|
283
|
+
if not p:
|
|
284
|
+
return p
|
|
285
|
+
try:
|
|
286
|
+
p = os.path.expanduser(os.path.expandvars(p))
|
|
287
|
+
except (TypeError, ValueError):
|
|
288
|
+
return p
|
|
289
|
+
if is_windows_style_path(p) and not p.startswith("/"):
|
|
290
|
+
return ntpath.normpath(p)
|
|
291
|
+
return os.path.normpath(p) if p.startswith("/") else p
|
|
292
|
+
|
|
293
|
+
|
|
204
294
|
def is_ancestor_of_cwd(target: str, cwd: str) -> bool:
|
|
205
295
|
try:
|
|
206
296
|
t = os.path.abspath(os.path.expanduser(target))
|
|
@@ -238,11 +328,18 @@ def overwrite_risk(command: str) -> str | None:
|
|
|
238
328
|
返回形态描述,不命中 None。
|
|
239
329
|
"""
|
|
240
330
|
import os as _os
|
|
241
|
-
|
|
331
|
+
# 保留大小写:目标路径要做真实存在性核对,lowercase 后
|
|
332
|
+
# 在大小写敏感的 FS(ext4/APFS 敏感卷)上会永远查不到
|
|
333
|
+
# (0.5.1 修:`> Src.Main.PY` 曾被判成 allow)
|
|
334
|
+
norm = _norm_cmd_preserve_case(command)
|
|
242
335
|
|
|
243
336
|
# 形态 1/3:mv / cp 批量覆盖(通配符源 + 已存在目标目录)
|
|
244
337
|
# 允许 -r/-rf/-a 等旗标夹在动词与源之间
|
|
245
|
-
m = re.search(
|
|
338
|
+
m = re.search(
|
|
339
|
+
r"\b(mv|cp)\s+(?:-[a-zA-Z]+\s+)?(\S*\*[\S\s]*?)\s+(\S+)$",
|
|
340
|
+
norm,
|
|
341
|
+
re.IGNORECASE,
|
|
342
|
+
)
|
|
246
343
|
if m and "*?" not in m.group(3):
|
|
247
344
|
dest = m.group(3).strip("'\"")
|
|
248
345
|
if _os.path.isdir(dest):
|
|
@@ -252,7 +349,10 @@ def overwrite_risk(command: str) -> str | None:
|
|
|
252
349
|
)
|
|
253
350
|
|
|
254
351
|
# 形态 2:> 重定向到已存在非空文件(>> 追加不拦:负向前瞻排除 >>)
|
|
255
|
-
m = re.search(
|
|
352
|
+
m = re.search(
|
|
353
|
+
r"(?:^|&&|;)\s*[^&;]*?(?<!>)>(?!>)\s*(\S+)\s*(?:2>|&|$)",
|
|
354
|
+
norm,
|
|
355
|
+
)
|
|
256
356
|
if m:
|
|
257
357
|
target = m.group(1).strip("'\"")
|
|
258
358
|
if _os.path.isfile(target):
|
|
@@ -268,6 +368,51 @@ def _norm_cmd(text: str) -> str:
|
|
|
268
368
|
return " ".join(text.lower().split())
|
|
269
369
|
|
|
270
370
|
|
|
371
|
+
def _norm_cmd_preserve_case(text: str) -> str:
|
|
372
|
+
"""只归一空白,不动大小写(路径要拿去核磁盘)。"""
|
|
373
|
+
return " ".join(text.split())
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# 只读勘察类命令:它们出现在命令行时,命中词很可能只是被搜索/打印的
|
|
377
|
+
# 文本,而不是要执行的动词(`rg "docker volume rm" docs/`、
|
|
378
|
+
# `git log --grep="terraform destroy"`、`echo "不要跑 terraform destroy"`)。
|
|
379
|
+
_READONLY_HEADS = {
|
|
380
|
+
"grep", "rg", "ag", "ack", "egrep", "fgrep", "ack-grep",
|
|
381
|
+
"echo", "printf", "cat", "head", "tail", "less", "more", "bat",
|
|
382
|
+
"man", "which", "whereis", "type", "history", "ls", "dir", "stat",
|
|
383
|
+
"file", "diff", "wc",
|
|
384
|
+
}
|
|
385
|
+
# git 只读子命令(其余 git 子命令仍按原样匹配)
|
|
386
|
+
_READONLY_GIT_SUBS = {
|
|
387
|
+
"log", "show", "grep", "diff", "blame", "status", "branch",
|
|
388
|
+
"remote", "tag", "rev-parse", "ls-files", "describe", "shortlog",
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _readonly_head(norm: str) -> bool:
|
|
393
|
+
"""命令首段(跳过 cd … &&)是否为只读勘察类命令。"""
|
|
394
|
+
body = norm.strip()
|
|
395
|
+
for _ in range(4):
|
|
396
|
+
stripped = re.sub(r"^cd\s+[^&;|]+\s*(?:&&|;|\|\|)\s*", "", body)
|
|
397
|
+
if stripped == body:
|
|
398
|
+
break
|
|
399
|
+
body = stripped
|
|
400
|
+
tokens = body.split()
|
|
401
|
+
if not tokens:
|
|
402
|
+
return False
|
|
403
|
+
head = tokens[0].lstrip("(").lower()
|
|
404
|
+
if head == "git":
|
|
405
|
+
sub = tokens[1].lower() if len(tokens) > 1 else ""
|
|
406
|
+
return sub in _READONLY_GIT_SUBS
|
|
407
|
+
return head in _READONLY_HEADS
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _inside_quotes(norm: str, pos: int) -> bool:
|
|
411
|
+
"""pos 处是否处于引号内(单引号或双引号奇数个即在内)。"""
|
|
412
|
+
before = norm[:pos]
|
|
413
|
+
return (before.count('"') % 2 == 1) or (before.count("'") % 2 == 1)
|
|
414
|
+
|
|
415
|
+
|
|
271
416
|
def cloud_tool_match(command: str) -> tuple[str, str] | None:
|
|
272
417
|
"""H14:命令是否命中云/容器/ORM 工具的破坏性形态。
|
|
273
418
|
|
|
@@ -275,10 +420,31 @@ def cloud_tool_match(command: str) -> tuple[str, str] | None:
|
|
|
275
420
|
先做直接前缀/包含匹配;SQL 破坏语句经引号内提取二次检测。
|
|
276
421
|
"""
|
|
277
422
|
norm = _norm_cmd(command)
|
|
423
|
+
# 只读勘察命令(grep/rg/echo/git log …)里的命中词只是被搜索的文本,
|
|
424
|
+
# 不是要执行的动词 —— 否则 `rg "docker volume rm" docs/` 会被 warn,
|
|
425
|
+
# `echo "不要跑 terraform destroy"` 会直接 block(0.5.1 修)
|
|
426
|
+
if _readonly_head(norm):
|
|
427
|
+
return None
|
|
428
|
+
if "--help" in norm or " -h " in norm:
|
|
429
|
+
return None
|
|
278
430
|
# SQL 破坏语句优先于工具表匹配(TRUNCATE/DROP 的破坏语义精确,block 级)
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
431
|
+
# docker 容器级删除:容器文件系统与日志随之销毁(STUPID-2026-0133 /
|
|
432
|
+
# claude-code#101241:用户只授权 restart,agent 跑了 docker rm,毁掉
|
|
433
|
+
# 唯一一份待诊断的崩溃日志)。不作用于卷,所以只 warn。
|
|
434
|
+
# 用 \b(?!i) 排除 docker rmi(删镜像,可重建,不是数据销毁)。
|
|
435
|
+
if re.search(r"\bdocker(\s+container)?\s+rm\b(?!i)", norm):
|
|
436
|
+
return "docker rm", "STUPID-2026-0133 (claude-code#101241)"
|
|
437
|
+
if re.search(r"\bdocker\s+container\s+prune\b", norm):
|
|
438
|
+
return "docker container prune", "STUPID-2026-0133 (claude-code#101241)"
|
|
439
|
+
|
|
440
|
+
sql_stmt = re.search(r"\b(drop\s+(table|database|schema)\b|truncate\b)", norm)
|
|
441
|
+
sql_client = re.search(
|
|
442
|
+
r"\b(psql|mysql|mariadb|sqlite3|sqlcmd|neon|supabase)\b"
|
|
443
|
+
r"|\b(npx|yarn|pnpm)\s+\w+\s+db\b",
|
|
444
|
+
norm,
|
|
445
|
+
)
|
|
446
|
+
if sql_stmt and sql_client:
|
|
447
|
+
return "sql drop/truncate", "prisma blog 2026-07, claude-code Neon truncate 2026-07"
|
|
282
448
|
tables = [
|
|
283
449
|
(DOCKER_DESTRUCTIVE, "claude-code#14944/#41357, deedglass compose-down-v"),
|
|
284
450
|
(K8S_DESTRUCTIVE, "deedglass kubectl-delete, agenticcontrolplane 2026-04"),
|
|
@@ -289,8 +455,14 @@ def cloud_tool_match(command: str) -> tuple[str, str] | None:
|
|
|
289
455
|
for shape in table:
|
|
290
456
|
# 包含式匹配:python -m alembic downgrade base、cd x && terraform
|
|
291
457
|
# destroy 等前缀形态也要命中(形状本身是多词短语,误配风险低)
|
|
292
|
-
|
|
293
|
-
|
|
458
|
+
idx = norm.find(shape)
|
|
459
|
+
if idx < 0:
|
|
460
|
+
continue
|
|
461
|
+
# 引号内的命中交给上层:psql -c "DROP …" 是真执行,
|
|
462
|
+
# 而 echo "terraform destroy" 已被 _readonly_head 拦在上面
|
|
463
|
+
if _inside_quotes(norm, idx):
|
|
464
|
+
continue
|
|
465
|
+
return shape, evidence
|
|
294
466
|
return None
|
|
295
467
|
|
|
296
468
|
|
|
@@ -57,4 +57,22 @@ RULES_COMMON: dict[str, tuple[str, str, str]] = {
|
|
|
57
57
|
"目标解析错误时没有任何回收余地",
|
|
58
58
|
"macrumors#1176135 (sudo rm -R / .Spotlight-v100), steam-for-linux 2015",
|
|
59
59
|
),
|
|
60
|
+
# H16/H17:家目录根与凭据目录 —— 删除它们等于抹掉一个人在机器上的
|
|
61
|
+
# 全部身份(私钥、云凭据、未备份的成果)。事故链见 INCIDENTS.md 候选 21-23:
|
|
62
|
+
# ~200GB 家目录(claude-code#83058)、700GB 主目录、%USERPROFILE% 下
|
|
63
|
+
# 86k 文件(deepseek-harness#13675)、~/.ssh 全毁(私钥须按泄露处理)。
|
|
64
|
+
"H16_HOME_ROOT": (
|
|
65
|
+
"block",
|
|
66
|
+
"目标是家目录根本身(/home、/root、/home/<user>、/Users/<user>、"
|
|
67
|
+
"C:\\Users\\<user>),删除会毁掉整台机器上的个人数据与全部凭据",
|
|
68
|
+
"claude-code#83058 (~200GB home), STUPID-2026-0128, "
|
|
69
|
+
"deepseek-harness#13675 (86k files under %USERPROFILE%)",
|
|
70
|
+
),
|
|
71
|
+
"H17_CREDENTIAL_TARGET": (
|
|
72
|
+
"block",
|
|
73
|
+
"目标是凭据/密钥目录或文件(.ssh/.aws/.gnupg/.kube/.docker、"
|
|
74
|
+
"id_rsa 等),删除不可逆且私钥必须按已泄露处理",
|
|
75
|
+
"STUPID-2026-0128 (SSH/AWS/GH credentials destroyed), "
|
|
76
|
+
"deepseek-harness#13675 (~/.ssh wiped)",
|
|
77
|
+
),
|
|
60
78
|
}
|
package/src/extension.ts
CHANGED
|
@@ -22,6 +22,17 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
22
22
|
|
|
23
23
|
const GUARD_TIMEOUT_MS = 5_000;
|
|
24
24
|
|
|
25
|
+
/**
|
|
26
|
+
* 快速预筛(与 hooks/pretooluse.py 的 QUICK_PREDICATE_SRC 逐字一致,
|
|
27
|
+
* tests/test_guard.py 会比对两边):不含破坏性动词的命令直接放行。
|
|
28
|
+
*
|
|
29
|
+
* 0.5.1 修:旧版只认 shell 删除动词,H14(云/容器/ORM/SQL)与
|
|
30
|
+
* H15(> 重定向)的 block 判定永远到不了扩展 —— 硬拦截层对这两类规则
|
|
31
|
+
* 形同虚设,而它们恰好是唯一 block 级的云/数据层保护。
|
|
32
|
+
*/
|
|
33
|
+
const QUICK_PREDICATE =
|
|
34
|
+
/(?:\b(?:rm|rmdir|del|erase|rd|unlink|shred|trash|remove-item|ri|move-item|mv|move|sudo|doas|su)\b)|(?:\bgit\s+(?:clean|worktree|rm)\b)|(?:\bfind\b[^|;]*?-delete\b)|(?:\b(?:docker|terraform|pulumi|kubectl|prisma|alembic|drizzle|railway|gcloud|supabase|neon|kiro|psql|mysql|mariadb|sqlite3|sqlcmd|aws)\b)|>>?/i;
|
|
35
|
+
|
|
25
36
|
function guardScript(): string | null {
|
|
26
37
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
27
38
|
const p = join(here, "..", "scripts", "guard.py");
|
|
@@ -99,8 +110,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
99
110
|
const command = typeof input?.command === "string" ? input.command : undefined;
|
|
100
111
|
if (!command || !command.trim()) return undefined;
|
|
101
112
|
|
|
102
|
-
//
|
|
103
|
-
if (
|
|
113
|
+
// 快速预筛:不含破坏性动词时不启动子进程(省掉 python 探测和 ~50ms)
|
|
114
|
+
if (!QUICK_PREDICATE.test(command)) {
|
|
104
115
|
return undefined;
|
|
105
116
|
}
|
|
106
117
|
|