delete-guard-agent 0.5.0 → 0.5.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.md +3 -2
- package/hooks/pretooluse.py +18 -9
- package/package.json +1 -1
- package/scripts/delete_guard/core.py +46 -40
- package/scripts/delete_guard/paths.py +117 -8
- package/src/extension.ts +13 -2
package/README.md
CHANGED
|
@@ -135,6 +135,7 @@ python scripts/guard.py command "rm -rf /mnt/d/data" --json
|
|
|
135
135
|
| H12 | 目标是挂载点(删除作用于整个卷) | Linux/macOS | block |
|
|
136
136
|
| H13 | 目标是 macOS 家目录特殊目录(Documents/Library…) | macOS | block |
|
|
137
137
|
| H14 | 云/容器/ORM 工具破坏性动词(terraform destroy、prisma migrate reset、docker 卷删除、kubectl delete namespace、SQL DROP) | 全平台 | warn/block |
|
|
138
|
+
| H15 | 覆盖型销毁(通配 mv/cp 落入已存在目录、`>` 重定向清空非空文件) | 全平台 | warn |
|
|
138
139
|
|
|
139
140
|
## 代码结构(0.2 起拆包;0.3 起 find/git 意图在 core.py 内原生解析)
|
|
140
141
|
|
|
@@ -167,7 +168,7 @@ python -m unittest discover tests -v
|
|
|
167
168
|
以下项已由 CI 的 `ubuntu-latest` / `windows-latest` / `macos-latest` runner
|
|
168
169
|
或真机 E2E 覆盖:
|
|
169
170
|
|
|
170
|
-
- [x] 单元测试(
|
|
171
|
+
- [x] 单元测试(131 个,含 H3/H4/H11-H15/find/git 断言、中文社区与第四轮事故回归、预筛一致性比对、过度拦截反例)在
|
|
171
172
|
ubuntu + windows + macos 三个 runner 上跑
|
|
172
173
|
- [x] macOS 真机回归(H3 APFS 大小写、H13 家目录特殊目录)——由
|
|
173
174
|
`macos-latest` runner 真机执行,不再是仅静态判定
|
|
@@ -193,7 +194,7 @@ python -m unittest discover tests -v
|
|
|
193
194
|
规则集未经实战,你的真实使用是最有价值的数据源。遇到以下情况请开
|
|
194
195
|
[误报/漏报 issue](https://github.com/xinghe-labs/blast-radius-guard/issues/new?template=false-positive.yml):
|
|
195
196
|
|
|
196
|
-
- **误报**:安全的命令被 block
|
|
197
|
+
- **误报**:安全的命令被 block(比如正常的清理脚本被拦,或 `rg "terraform destroy"` 被当成要执行)
|
|
197
198
|
- **漏报**:危险的命令被 allow/warn
|
|
198
199
|
|
|
199
200
|
模板会引导你贴出命令原文、OS 和 `--json` 判定输出——这是调规则需要的全部信息。
|
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.5.
|
|
3
|
+
"version": "0.5.1",
|
|
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,32 @@ 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,
|
|
30
33
|
human_bytes,
|
|
31
34
|
is_ancestor_of_cwd,
|
|
32
35
|
is_drive_root,
|
|
33
|
-
|
|
34
|
-
glob_base_dir,
|
|
35
|
-
overwrite_risk,
|
|
36
|
+
is_windows_style_path,
|
|
36
37
|
is_wsl_windows_mount,
|
|
37
38
|
macos_home_special,
|
|
39
|
+
overwrite_risk,
|
|
38
40
|
posix_system_prefix,
|
|
41
|
+
same_path,
|
|
39
42
|
)
|
|
40
43
|
from .platform import host_name, is_wsl, unknowns_for_host
|
|
41
44
|
from .rules import RULES, VERDICT_ORDER
|
|
@@ -272,9 +275,7 @@ def is_flag_token(v: str, cmd_verb: bool = False) -> bool:
|
|
|
272
275
|
# POSIX 删除动词下的 /d /x 是真实路径(目录名恰好单字母合法存在)
|
|
273
276
|
if _CMD_FLAG_RE.match(v):
|
|
274
277
|
return cmd_verb
|
|
275
|
-
|
|
276
|
-
return True
|
|
277
|
-
return False
|
|
278
|
+
return bool(_CMD_LONG_FLAG_RE.match(v) and cmd_verb)
|
|
278
279
|
|
|
279
280
|
|
|
280
281
|
@dataclass
|
|
@@ -393,9 +394,7 @@ def extract_intent(parsed: ParsedCommand) -> Intent:
|
|
|
393
394
|
force = True
|
|
394
395
|
if tok in {"/purge", "--prune-empty-dirs"}:
|
|
395
396
|
force = True
|
|
396
|
-
if tok in {f.lower() for f in RECURSIVE_LONG}:
|
|
397
|
-
recursive = True
|
|
398
|
-
elif tok in RECURSIVE_LONG:
|
|
397
|
+
if tok in {f.lower() for f in RECURSIVE_LONG} or tok in RECURSIVE_LONG:
|
|
399
398
|
recursive = True
|
|
400
399
|
elif tok.startswith("-") and not tok.startswith("--"):
|
|
401
400
|
body = tok.lstrip("-")
|
|
@@ -465,34 +464,39 @@ def case_collision(path: str, windows_layout: bool | None = None) -> str | None:
|
|
|
465
464
|
NTFS/APFS 大小写不敏感 —— 这正是 D:\\CampusconnECT 删掉
|
|
466
465
|
D:\\CampusConnect 的原因(claude-code#60442)。
|
|
467
466
|
|
|
468
|
-
windows_layout 为 None
|
|
467
|
+
windows_layout 为 None 时按目标形态推断(盘符路径走 Windows 布局,
|
|
468
|
+
绝对 POSIX 路径走 macOS 布局)。刻意**不**用 os.name 推断:那样
|
|
469
|
+
macOS 分支在 Linux 上永远不可测,测试无法覆盖 APFS 路径(0.5.1 修)。
|
|
470
|
+
仅用于测试显式指定布局。
|
|
469
471
|
"""
|
|
470
472
|
if not path or not case_insensitive_host():
|
|
471
473
|
return None
|
|
472
474
|
if windows_layout is None:
|
|
473
|
-
windows_layout =
|
|
475
|
+
windows_layout = is_windows_style_path(path)
|
|
474
476
|
# 逐级比对大小写:Windows 走盘符/反斜杠布局,macOS 走 POSIX 布局
|
|
477
|
+
# 回归(0.5.1):POSIX 分支曾用 os.path.join("", seg) 丢掉根目录,
|
|
478
|
+
# 路径退化成相对,逐级核对在第二段就 listdir 失败 → macOS 上 H3 永不触发
|
|
475
479
|
if windows_layout:
|
|
476
480
|
drive, tail = ntpath.splitdrive(path)
|
|
477
481
|
segments = [s for s in tail.replace("/", "\\").split("\\") if s]
|
|
478
|
-
cur = drive + "\\" if drive else ""
|
|
479
|
-
|
|
482
|
+
cur = drive + "\\" if drive else "."
|
|
483
|
+
joiner = ntpath.join
|
|
480
484
|
else:
|
|
481
485
|
segments = [s for s in path.replace("\\", "/").split("/") if s]
|
|
482
|
-
cur = ""
|
|
483
|
-
|
|
486
|
+
cur = "/"
|
|
487
|
+
joiner = os.path.join
|
|
484
488
|
for seg in segments:
|
|
485
489
|
try:
|
|
486
|
-
entries = os.listdir(cur
|
|
490
|
+
entries = os.listdir(cur)
|
|
487
491
|
except OSError:
|
|
488
492
|
return None
|
|
489
493
|
match = next((e for e in entries if e == seg), None)
|
|
490
494
|
if match is None:
|
|
491
495
|
ci = next((e for e in entries if e.lower() == seg.lower()), None)
|
|
492
496
|
if ci is not None:
|
|
493
|
-
return
|
|
497
|
+
return joiner(cur, ci)
|
|
494
498
|
return None
|
|
495
|
-
cur =
|
|
499
|
+
cur = joiner(cur, match)
|
|
496
500
|
return None
|
|
497
501
|
|
|
498
502
|
|
|
@@ -556,9 +560,7 @@ def _is_reparse(entry: os.DirEntry, st: os.stat_result) -> bool:
|
|
|
556
560
|
if entry.is_symlink():
|
|
557
561
|
return True
|
|
558
562
|
attrs = getattr(st, "st_file_attributes", 0)
|
|
559
|
-
|
|
560
|
-
return True
|
|
561
|
-
return False
|
|
563
|
+
return bool(attrs & _REPARSE_ATTR)
|
|
562
564
|
|
|
563
565
|
|
|
564
566
|
def is_mount_point(path: str) -> bool:
|
|
@@ -576,7 +578,7 @@ def is_mount_point(path: str) -> bool:
|
|
|
576
578
|
fields = line.split()
|
|
577
579
|
if len(fields) >= 2:
|
|
578
580
|
mp = fields[1].replace("\\040", " ").replace("\\011", "\t")
|
|
579
|
-
if mp
|
|
581
|
+
if mp in (real, path):
|
|
580
582
|
return True
|
|
581
583
|
except OSError:
|
|
582
584
|
return False
|
|
@@ -657,7 +659,7 @@ def judge_command(
|
|
|
657
659
|
f"目标带引号且含空格/CJK,经 {' -> '.join(layers)} 跳转时"
|
|
658
660
|
"参数会在层间被重新解释",
|
|
659
661
|
)
|
|
660
|
-
lower_layers = [
|
|
662
|
+
lower_layers = [layer.lower() for layer in layers]
|
|
661
663
|
inner_wsl = (
|
|
662
664
|
wsl_context
|
|
663
665
|
if wsl_context is not None
|
|
@@ -666,7 +668,7 @@ def judge_command(
|
|
|
666
668
|
inner_priv = (
|
|
667
669
|
privileged_context
|
|
668
670
|
if privileged_context is not None
|
|
669
|
-
else any(
|
|
671
|
+
else any(layer in PRIVILEGE_ESCALATORS for layer in lower_layers)
|
|
670
672
|
)
|
|
671
673
|
return _merge_inner(
|
|
672
674
|
hazards,
|
|
@@ -709,7 +711,7 @@ def judge_command(
|
|
|
709
711
|
# 原生 Linux 上 /mnt 下可能是任意普通挂载,交由 H12 按真实挂载表判定。
|
|
710
712
|
if wsl_context is None:
|
|
711
713
|
wsl_context = is_wsl() or "wsl" in [
|
|
712
|
-
|
|
714
|
+
layer.lower() for layer in parsed.shell_layers
|
|
713
715
|
]
|
|
714
716
|
|
|
715
717
|
# H15 覆盖型销毁(命令级判定;需要目标存在性核对,仅在真实 FS 上有效)
|
|
@@ -756,12 +758,15 @@ def judge_command(
|
|
|
756
758
|
radii: list[BlastRadius] = []
|
|
757
759
|
for target in intent.targets:
|
|
758
760
|
radii.append(walk_blast_radius(target))
|
|
761
|
+
# 判定用的归一形态:展开 ~ / $HOME、合并 .. 与 .(不跟链接)
|
|
762
|
+
ap = analysis_path(target)
|
|
759
763
|
|
|
760
|
-
if is_drive_root(
|
|
764
|
+
if is_drive_root(ap):
|
|
761
765
|
add("H2_DRIVE_ROOT", f"目标 {target!r} 是卷根")
|
|
762
766
|
|
|
763
767
|
real = case_collision(target)
|
|
764
|
-
|
|
768
|
+
# 不能用 normcase 比较:Windows 上它把大小写抹平,等于把 H3 关掉
|
|
769
|
+
if real and not same_path(real, target):
|
|
765
770
|
add("H3_CASE_COLLISION", f"{target!r} 实际指向已存在的 {real!r}")
|
|
766
771
|
|
|
767
772
|
br = radii[-1]
|
|
@@ -822,16 +827,16 @@ def judge_command(
|
|
|
822
827
|
)
|
|
823
828
|
|
|
824
829
|
# H11 系统关键前缀(含变量退化形态,如空变量后剩余的 /*)
|
|
825
|
-
sys_prefix = posix_system_prefix(
|
|
830
|
+
sys_prefix = posix_system_prefix(ap)
|
|
826
831
|
if sys_prefix and intent.recursive:
|
|
827
832
|
add("H11_SYSTEM_PREFIX", f"{target!r} 命中系统前缀 {sys_prefix}")
|
|
828
833
|
|
|
829
834
|
# H12 挂载点
|
|
830
|
-
if intent.recursive and is_mount_point(
|
|
835
|
+
if intent.recursive and is_mount_point(ap):
|
|
831
836
|
add("H12_MOUNT_POINT", f"{target!r} 是挂载点,删除作用于整个卷")
|
|
832
837
|
|
|
833
|
-
# H13 macOS
|
|
834
|
-
special = macos_home_special(
|
|
838
|
+
# H13 macOS 家目录特殊目录(~/Downloads 这类形态归一后也要命中)
|
|
839
|
+
special = macos_home_special(ap)
|
|
835
840
|
if special:
|
|
836
841
|
add("H13_MACOS_HOME_SPECIAL", f"{target!r} 命中 macOS 家目录特殊目录 {special}")
|
|
837
842
|
|
|
@@ -859,7 +864,7 @@ def judge_path(path: str, cwd: str | None = None) -> dict:
|
|
|
859
864
|
if is_drive_root(path):
|
|
860
865
|
add("H2_DRIVE_ROOT", f"{path!r} 是卷根")
|
|
861
866
|
real = case_collision(path)
|
|
862
|
-
if real and
|
|
867
|
+
if real and not same_path(real, path):
|
|
863
868
|
add("H3_CASE_COLLISION", f"{path!r} 实际指向已存在的 {real!r}")
|
|
864
869
|
if has_cjk(path):
|
|
865
870
|
add("H5_CJK_SILENT_FAIL", f"路径含 CJK:{path!r}")
|
|
@@ -872,12 +877,13 @@ def judge_path(path: str, cwd: str | None = None) -> dict:
|
|
|
872
877
|
if br.reparse_points:
|
|
873
878
|
add("H4_REPARSE_TRAVERSAL", f"{path!r} 子树内有 {br.reparse_points} 个链接")
|
|
874
879
|
|
|
875
|
-
|
|
880
|
+
ap = analysis_path(path)
|
|
881
|
+
sys_prefix = posix_system_prefix(ap)
|
|
876
882
|
if sys_prefix:
|
|
877
883
|
add("H11_SYSTEM_PREFIX", f"{path!r} 命中系统前缀 {sys_prefix}")
|
|
878
|
-
if is_mount_point(
|
|
884
|
+
if is_mount_point(ap):
|
|
879
885
|
add("H12_MOUNT_POINT", f"{path!r} 是挂载点")
|
|
880
|
-
special = macos_home_special(
|
|
886
|
+
special = macos_home_special(ap)
|
|
881
887
|
if special:
|
|
882
888
|
add("H13_MACOS_HOME_SPECIAL", f"{path!r} 命中 macOS 家目录特殊目录 {special}")
|
|
883
889
|
|
|
@@ -201,6 +201,42 @@ def has_cjk(s: str) -> bool:
|
|
|
201
201
|
return False
|
|
202
202
|
|
|
203
203
|
|
|
204
|
+
def same_path(a: str, b: str) -> bool:
|
|
205
|
+
"""大小写敏感的字面比较(H3 用)。
|
|
206
|
+
|
|
207
|
+
os.path.normcase 在 Windows 上会 lowercase 整条路径 —— 用它比较
|
|
208
|
+
"目标 vs 磁盘真实路径" 等于把 H3 在唯一真正需要它的平台上关掉:
|
|
209
|
+
D:\\CampusconnECT 与 D:\\CampusConnect 会被判成同一个路径。
|
|
210
|
+
normpath 只做分隔符/.. 归一,保留大小写。
|
|
211
|
+
"""
|
|
212
|
+
try:
|
|
213
|
+
return os.path.normpath(os.path.expanduser(a)) == os.path.normpath(
|
|
214
|
+
os.path.expanduser(b)
|
|
215
|
+
)
|
|
216
|
+
except (TypeError, ValueError, OSError):
|
|
217
|
+
return False
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def analysis_path(target: str) -> str:
|
|
221
|
+
"""把目标归一成"判定用的绝对形态":展开 ~ 与 $HOME、合并 .. / .、
|
|
222
|
+
统一分隔符,但**不做存在性检查也不做 realpath**(realpath 会跟掉
|
|
223
|
+
junction,H4 需要看到链接本身)。
|
|
224
|
+
|
|
225
|
+
目的:让 `~/Downloads`、`/Users/me/../me/Documents`、`D:\\a\\..\\`
|
|
226
|
+
这类形态在 H2/H11/H13 面前与它们的绝对形态等价。
|
|
227
|
+
"""
|
|
228
|
+
p = target.strip().strip("'\"")
|
|
229
|
+
if not p:
|
|
230
|
+
return p
|
|
231
|
+
try:
|
|
232
|
+
p = os.path.expanduser(os.path.expandvars(p))
|
|
233
|
+
except (TypeError, ValueError):
|
|
234
|
+
return p
|
|
235
|
+
if is_windows_style_path(p) and not p.startswith("/"):
|
|
236
|
+
return ntpath.normpath(p)
|
|
237
|
+
return os.path.normpath(p) if p.startswith("/") else p
|
|
238
|
+
|
|
239
|
+
|
|
204
240
|
def is_ancestor_of_cwd(target: str, cwd: str) -> bool:
|
|
205
241
|
try:
|
|
206
242
|
t = os.path.abspath(os.path.expanduser(target))
|
|
@@ -238,11 +274,18 @@ def overwrite_risk(command: str) -> str | None:
|
|
|
238
274
|
返回形态描述,不命中 None。
|
|
239
275
|
"""
|
|
240
276
|
import os as _os
|
|
241
|
-
|
|
277
|
+
# 保留大小写:目标路径要做真实存在性核对,lowercase 后
|
|
278
|
+
# 在大小写敏感的 FS(ext4/APFS 敏感卷)上会永远查不到
|
|
279
|
+
# (0.5.1 修:`> Src.Main.PY` 曾被判成 allow)
|
|
280
|
+
norm = _norm_cmd_preserve_case(command)
|
|
242
281
|
|
|
243
282
|
# 形态 1/3:mv / cp 批量覆盖(通配符源 + 已存在目标目录)
|
|
244
283
|
# 允许 -r/-rf/-a 等旗标夹在动词与源之间
|
|
245
|
-
m = re.search(
|
|
284
|
+
m = re.search(
|
|
285
|
+
r"\b(mv|cp)\s+(?:-[a-zA-Z]+\s+)?(\S*\*[\S\s]*?)\s+(\S+)$",
|
|
286
|
+
norm,
|
|
287
|
+
re.IGNORECASE,
|
|
288
|
+
)
|
|
246
289
|
if m and "*?" not in m.group(3):
|
|
247
290
|
dest = m.group(3).strip("'\"")
|
|
248
291
|
if _os.path.isdir(dest):
|
|
@@ -252,7 +295,10 @@ def overwrite_risk(command: str) -> str | None:
|
|
|
252
295
|
)
|
|
253
296
|
|
|
254
297
|
# 形态 2:> 重定向到已存在非空文件(>> 追加不拦:负向前瞻排除 >>)
|
|
255
|
-
m = re.search(
|
|
298
|
+
m = re.search(
|
|
299
|
+
r"(?:^|&&|;)\s*[^&;]*?(?<!>)>(?!>)\s*(\S+)\s*(?:2>|&|$)",
|
|
300
|
+
norm,
|
|
301
|
+
)
|
|
256
302
|
if m:
|
|
257
303
|
target = m.group(1).strip("'\"")
|
|
258
304
|
if _os.path.isfile(target):
|
|
@@ -268,6 +314,51 @@ def _norm_cmd(text: str) -> str:
|
|
|
268
314
|
return " ".join(text.lower().split())
|
|
269
315
|
|
|
270
316
|
|
|
317
|
+
def _norm_cmd_preserve_case(text: str) -> str:
|
|
318
|
+
"""只归一空白,不动大小写(路径要拿去核磁盘)。"""
|
|
319
|
+
return " ".join(text.split())
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
# 只读勘察类命令:它们出现在命令行时,命中词很可能只是被搜索/打印的
|
|
323
|
+
# 文本,而不是要执行的动词(`rg "docker volume rm" docs/`、
|
|
324
|
+
# `git log --grep="terraform destroy"`、`echo "不要跑 terraform destroy"`)。
|
|
325
|
+
_READONLY_HEADS = {
|
|
326
|
+
"grep", "rg", "ag", "ack", "egrep", "fgrep", "ack-grep",
|
|
327
|
+
"echo", "printf", "cat", "head", "tail", "less", "more", "bat",
|
|
328
|
+
"man", "which", "whereis", "type", "history", "ls", "dir", "stat",
|
|
329
|
+
"file", "diff", "wc",
|
|
330
|
+
}
|
|
331
|
+
# git 只读子命令(其余 git 子命令仍按原样匹配)
|
|
332
|
+
_READONLY_GIT_SUBS = {
|
|
333
|
+
"log", "show", "grep", "diff", "blame", "status", "branch",
|
|
334
|
+
"remote", "tag", "rev-parse", "ls-files", "describe", "shortlog",
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _readonly_head(norm: str) -> bool:
|
|
339
|
+
"""命令首段(跳过 cd … &&)是否为只读勘察类命令。"""
|
|
340
|
+
body = norm.strip()
|
|
341
|
+
for _ in range(4):
|
|
342
|
+
stripped = re.sub(r"^cd\s+[^&;|]+\s*(?:&&|;|\|\|)\s*", "", body)
|
|
343
|
+
if stripped == body:
|
|
344
|
+
break
|
|
345
|
+
body = stripped
|
|
346
|
+
tokens = body.split()
|
|
347
|
+
if not tokens:
|
|
348
|
+
return False
|
|
349
|
+
head = tokens[0].lstrip("(").lower()
|
|
350
|
+
if head == "git":
|
|
351
|
+
sub = tokens[1].lower() if len(tokens) > 1 else ""
|
|
352
|
+
return sub in _READONLY_GIT_SUBS
|
|
353
|
+
return head in _READONLY_HEADS
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _inside_quotes(norm: str, pos: int) -> bool:
|
|
357
|
+
"""pos 处是否处于引号内(单引号或双引号奇数个即在内)。"""
|
|
358
|
+
before = norm[:pos]
|
|
359
|
+
return (before.count('"') % 2 == 1) or (before.count("'") % 2 == 1)
|
|
360
|
+
|
|
361
|
+
|
|
271
362
|
def cloud_tool_match(command: str) -> tuple[str, str] | None:
|
|
272
363
|
"""H14:命令是否命中云/容器/ORM 工具的破坏性形态。
|
|
273
364
|
|
|
@@ -275,10 +366,22 @@ def cloud_tool_match(command: str) -> tuple[str, str] | None:
|
|
|
275
366
|
先做直接前缀/包含匹配;SQL 破坏语句经引号内提取二次检测。
|
|
276
367
|
"""
|
|
277
368
|
norm = _norm_cmd(command)
|
|
369
|
+
# 只读勘察命令(grep/rg/echo/git log …)里的命中词只是被搜索的文本,
|
|
370
|
+
# 不是要执行的动词 —— 否则 `rg "docker volume rm" docs/` 会被 warn,
|
|
371
|
+
# `echo "不要跑 terraform destroy"` 会直接 block(0.5.1 修)
|
|
372
|
+
if _readonly_head(norm):
|
|
373
|
+
return None
|
|
374
|
+
if "--help" in norm or " -h " in norm:
|
|
375
|
+
return None
|
|
278
376
|
# SQL 破坏语句优先于工具表匹配(TRUNCATE/DROP 的破坏语义精确,block 级)
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
377
|
+
sql_stmt = re.search(r"\b(drop\s+(table|database|schema)\b|truncate\b)", norm)
|
|
378
|
+
sql_client = re.search(
|
|
379
|
+
r"\b(psql|mysql|mariadb|sqlite3|sqlcmd|neon|supabase)\b"
|
|
380
|
+
r"|\b(npx|yarn|pnpm)\s+\w+\s+db\b",
|
|
381
|
+
norm,
|
|
382
|
+
)
|
|
383
|
+
if sql_stmt and sql_client:
|
|
384
|
+
return "sql drop/truncate", "prisma blog 2026-07, claude-code Neon truncate 2026-07"
|
|
282
385
|
tables = [
|
|
283
386
|
(DOCKER_DESTRUCTIVE, "claude-code#14944/#41357, deedglass compose-down-v"),
|
|
284
387
|
(K8S_DESTRUCTIVE, "deedglass kubectl-delete, agenticcontrolplane 2026-04"),
|
|
@@ -289,8 +392,14 @@ def cloud_tool_match(command: str) -> tuple[str, str] | None:
|
|
|
289
392
|
for shape in table:
|
|
290
393
|
# 包含式匹配:python -m alembic downgrade base、cd x && terraform
|
|
291
394
|
# destroy 等前缀形态也要命中(形状本身是多词短语,误配风险低)
|
|
292
|
-
|
|
293
|
-
|
|
395
|
+
idx = norm.find(shape)
|
|
396
|
+
if idx < 0:
|
|
397
|
+
continue
|
|
398
|
+
# 引号内的命中交给上层:psql -c "DROP …" 是真执行,
|
|
399
|
+
# 而 echo "terraform destroy" 已被 _readonly_head 拦在上面
|
|
400
|
+
if _inside_quotes(norm, idx):
|
|
401
|
+
continue
|
|
402
|
+
return shape, evidence
|
|
294
403
|
return None
|
|
295
404
|
|
|
296
405
|
|
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
|
|