@ia-ccun/code-agent-cli 0.0.58-beta.1 → 0.0.58-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,16 +24,29 @@
24
24
  import fs from "node:fs";
25
25
  import { homedir } from "node:os";
26
26
  import path from "node:path";
27
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
27
+ import type {
28
+ ExtensionAPI,
29
+ ExtensionContext,
30
+ } from "@earendil-works/pi-coding-agent";
28
31
  import { isToolCallEventType } from "@earendil-works/pi-coding-agent";
29
32
 
30
33
  const STATUS_KEY = "safety-guard";
31
34
  const PROMPT_WIDGET_KEY = "safety-guard-prompt";
35
+ const MATCH_START = ">>>";
36
+ const MATCH_END = "<<<";
37
+ const LINE_MARK = "!!!";
32
38
 
33
39
  type RiskLevel = "prompt" | "strong-confirm" | "block-noninteractive";
34
- type RuleCategory = "git" | "filesystem" | "docker" | "package" | "system" | "database" | "secrets";
35
-
36
- type CommandRule = {
40
+ type RuleCategory =
41
+ | "git"
42
+ | "filesystem"
43
+ | "docker"
44
+ | "package"
45
+ | "system"
46
+ | "database"
47
+ | "secrets";
48
+
49
+ export type CommandRule = {
37
50
  pattern: RegExp;
38
51
  label: string;
39
52
  category: RuleCategory;
@@ -41,7 +54,10 @@ type CommandRule = {
41
54
  };
42
55
 
43
56
  type AllowScope = "session" | "permanent";
44
- type AllowDecision = { block: true; reason: string } | { allow: true; scope?: AllowScope } | undefined;
57
+ type AllowDecision =
58
+ | { block: true; reason: string }
59
+ | { allow: true; scope?: AllowScope }
60
+ | undefined;
45
61
  type AllowEntry = {
46
62
  key: string;
47
63
  kind: "bash" | "write" | "edit";
@@ -53,91 +69,376 @@ type AllowEntry = {
53
69
  };
54
70
  type AllowStore = { version: 1; entries: AllowEntry[] };
55
71
 
56
- const ALLOW_STORE_PATH = path.join(homedir(), ".aicode-cli", "agent", "safety-guard-allow.json");
72
+ const ALLOW_STORE_PATH = path.join(
73
+ homedir(),
74
+ ".aicode-cli",
75
+ "agent",
76
+ "safety-guard-allow.json",
77
+ );
57
78
 
58
79
  const GIT_RULES: CommandRule[] = [
59
- { pattern: /\bgit\s+reset\s+--hard\b/i, label: "git reset --hard", category: "git", level: "block-noninteractive" },
60
- { pattern: /\bgit\s+reset\s+(?:--soft|--mixed|--merge|--keep)\b/i, label: "git reset history rewrite", category: "git", level: "strong-confirm" },
61
- { pattern: /\bgit\s+reset\s+(?:HEAD[~^]|[a-f0-9]{7,40}\b)/i, label: "git reset to revision", category: "git", level: "strong-confirm" },
62
- { pattern: /\bgit\s+clean\b[^\n;&|]*\s-[^\s;&|]*f/i, label: "git clean -f", category: "git", level: "block-noninteractive" },
63
- { pattern: /\bgit\s+checkout\s+--\s+/i, label: "git checkout -- <path>", category: "git", level: "prompt" },
64
- { pattern: /\bgit\s+switch\b/i, label: "git switch", category: "git", level: "prompt" },
65
- { pattern: /\bgit\s+restore\b/i, label: "git restore", category: "git", level: "prompt" },
66
- { pattern: /\bgit\s+branch\s+-(?:d|D)\b/i, label: "git branch delete", category: "git", level: "prompt" },
67
- { pattern: /\bgit\s+tag\s+-d\b/i, label: "git tag delete", category: "git", level: "prompt" },
68
- { pattern: /\bgit\s+push\b[^\n;&|]*--force(?:-with-lease)?\b/i, label: "git push --force", category: "git", level: "strong-confirm" },
69
- { pattern: /\bgit\s+push\b[^\n;&|]*(?:--delete|:refs\/heads\/)/i, label: "git push delete branch", category: "git", level: "strong-confirm" },
70
- { pattern: /\bgit\s+rebase\b/i, label: "git rebase", category: "git", level: "strong-confirm" },
71
- { pattern: /\bgit\s+filter-(?:branch|repo)\b/i, label: "git history filtering", category: "git", level: "strong-confirm" },
72
- { pattern: /\bgit\s+commit\b[^\n;&|]*--amend\b/i, label: "git commit --amend", category: "git", level: "prompt" },
73
- { pattern: /\bgit\s+commit\b[^\n;&|]*--(?:fixup|squash)\b/i, label: "git commit fixup/squash", category: "git", level: "prompt" },
74
- { pattern: /\bgit\s+replace\b/i, label: "git replace", category: "git", level: "strong-confirm" },
75
- { pattern: /\bgit\s+notes\s+(?:remove|prune)\b/i, label: "git notes remove/prune", category: "git", level: "prompt" },
76
- { pattern: /\bgit\s+update-ref\b/i, label: "git update-ref", category: "git", level: "strong-confirm" },
77
- { pattern: /\bgit\s+reflog\s+expire\b/i, label: "git reflog expire", category: "git", level: "strong-confirm" },
78
- { pattern: /\bgit\s+gc\b[^\n;&|]*--prune(?:=|\s+)?(?:now|all)?\b/i, label: "git gc --prune", category: "git", level: "strong-confirm" },
79
- { pattern: /\bgit\s+prune\b/i, label: "git prune", category: "git", level: "strong-confirm" },
80
+ {
81
+ pattern: /\bgit\s+reset\s+--hard\b/i,
82
+ label: "git reset --hard",
83
+ category: "git",
84
+ level: "block-noninteractive",
85
+ },
86
+ {
87
+ pattern: /\bgit\s+reset\s+(?:--soft|--mixed|--merge|--keep)\b/i,
88
+ label: "git reset history rewrite",
89
+ category: "git",
90
+ level: "strong-confirm",
91
+ },
92
+ {
93
+ pattern: /\bgit\s+reset\s+(?:HEAD[~^]|[a-f0-9]{7,40}\b)/i,
94
+ label: "git reset to revision",
95
+ category: "git",
96
+ level: "strong-confirm",
97
+ },
98
+ {
99
+ pattern: /\bgit\s+clean\b[^\n;&|]*\s-[^\s;&|]*f/i,
100
+ label: "git clean -f",
101
+ category: "git",
102
+ level: "block-noninteractive",
103
+ },
104
+
105
+ {
106
+ pattern: /\bgit\s+push\b[^\n;&|]*--force(?:-with-lease)?\b/i,
107
+ label: "git push --force",
108
+ category: "git",
109
+ level: "strong-confirm",
110
+ },
111
+ {
112
+ pattern: /\bgit\s+push\b[^\n;&|]*(?:--delete|:refs\/heads\/)/i,
113
+ label: "git push delete branch",
114
+ category: "git",
115
+ level: "strong-confirm",
116
+ },
117
+ {
118
+ pattern: /\bgit\s+rebase\b/i,
119
+ label: "git rebase",
120
+ category: "git",
121
+ level: "strong-confirm",
122
+ },
123
+ {
124
+ pattern: /\bgit\s+filter-(?:branch|repo)\b/i,
125
+ label: "git history filtering",
126
+ category: "git",
127
+ level: "strong-confirm",
128
+ },
129
+
130
+ {
131
+ pattern: /\bgit\s+commit\b[^\n;&|]*--(?:fixup|squash)\b/i,
132
+ label: "git commit fixup/squash",
133
+ category: "git",
134
+ level: "prompt",
135
+ },
136
+ {
137
+ pattern: /\bgit\s+replace\b/i,
138
+ label: "git replace",
139
+ category: "git",
140
+ level: "strong-confirm",
141
+ },
142
+ {
143
+ pattern: /\bgit\s+notes\s+(?:remove|prune)\b/i,
144
+ label: "git notes remove/prune",
145
+ category: "git",
146
+ level: "prompt",
147
+ },
148
+ {
149
+ pattern: /\bgit\s+update-ref\b/i,
150
+ label: "git update-ref",
151
+ category: "git",
152
+ level: "strong-confirm",
153
+ },
154
+ {
155
+ pattern: /\bgit\s+reflog\s+expire\b/i,
156
+ label: "git reflog expire",
157
+ category: "git",
158
+ level: "strong-confirm",
159
+ },
160
+ {
161
+ pattern: /\bgit\s+gc\b[^\n;&|]*--prune(?:=|\s+)?(?:now|all)?\b/i,
162
+ label: "git gc --prune",
163
+ category: "git",
164
+ level: "strong-confirm",
165
+ },
166
+ {
167
+ pattern: /\bgit\s+prune\b/i,
168
+ label: "git prune",
169
+ category: "git",
170
+ level: "strong-confirm",
171
+ },
80
172
  ];
81
173
 
82
174
  const FILESYSTEM_RULES: CommandRule[] = [
83
- { pattern: /(^|[^\w-])rm\s+[^\n;&|]*-[^\s;&|]*r[^\s;&|]*f?\b/i, label: "recursive rm", category: "filesystem", level: "prompt" },
84
- { pattern: /(^|[^\w-])rm\s+[^\n;&|]*-[^\s;&|]*f[^\s;&|]*r\b/i, label: "recursive force rm", category: "filesystem", level: "prompt" },
85
- { pattern: /(^|[^\w-])rm\s+[^\n;&|]*(?:-[^\s;&|]*(?:r|f)[^\s;&|]*(?:r|f)[^\s;&|]*\s+)?(?:\/|~|\$HOME|\.)(?:\s|$|[;&|])/i, label: "rm targeting root/home/current directory", category: "filesystem", level: "block-noninteractive" },
86
- { pattern: /(^|[^\w-])rm\s+[^\n;&|]*\*/i, label: "rm with glob", category: "filesystem", level: "prompt" },
87
- { pattern: /\bfind\b[^\n;&|]*\s-delete\b/i, label: "find -delete", category: "filesystem", level: "prompt" },
88
- { pattern: /\bfind\b[^\n;&|]*\s-exec\s+rm\b/i, label: "find -exec rm", category: "filesystem", level: "prompt" },
89
- { pattern: /\bxargs\b[^\n;&|]*\brm\b/i, label: "xargs rm", category: "filesystem", level: "prompt" },
90
- { pattern: /\btruncate\s+-s\s+0\b/i, label: "truncate file to zero", category: "filesystem", level: "prompt" },
91
- { pattern: /\bshred\b/i, label: "shred", category: "filesystem", level: "strong-confirm" },
92
- { pattern: /\bdd\b[^\n;&|]*\bof=\/dev\//i, label: "dd to block device", category: "filesystem", level: "block-noninteractive" },
175
+ {
176
+ pattern: /(^|[^\w-])rm\s+[^\n;&|]*-[^\s;&|]*r[^\s;&|]*f?\b/i,
177
+ label: "recursive rm",
178
+ category: "filesystem",
179
+ level: "prompt",
180
+ },
181
+ {
182
+ pattern: /(^|[^\w-])rm\s+[^\n;&|]*-[^\s;&|]*f[^\s;&|]*r\b/i,
183
+ label: "recursive force rm",
184
+ category: "filesystem",
185
+ level: "prompt",
186
+ },
187
+ {
188
+ pattern:
189
+ /(^|[^\w-])rm\s+[^\n;&|]*(?:-[^\s;&|]*(?:r|f)[^\s;&|]*(?:r|f)[^\s;&|]*\s+)?(?:\/|~|\$HOME|\.)(?:\s|$|[;&|])/i,
190
+ label: "rm targeting root/home/current directory",
191
+ category: "filesystem",
192
+ level: "block-noninteractive",
193
+ },
194
+ {
195
+ pattern: /(^|[^\w-])rm\s+[^\n;&|]*\*/i,
196
+ label: "rm with glob",
197
+ category: "filesystem",
198
+ level: "prompt",
199
+ },
200
+ {
201
+ pattern: /\bfind\b[^\n;&|]*\s-delete\b/i,
202
+ label: "find -delete",
203
+ category: "filesystem",
204
+ level: "prompt",
205
+ },
206
+ {
207
+ pattern: /\bfind\b[^\n;&|]*\s-exec\s+rm\b/i,
208
+ label: "find -exec rm",
209
+ category: "filesystem",
210
+ level: "prompt",
211
+ },
212
+ {
213
+ pattern: /\bxargs\b[^\n;&|]*\brm\b/i,
214
+ label: "xargs rm",
215
+ category: "filesystem",
216
+ level: "prompt",
217
+ },
218
+ {
219
+ pattern: /\btruncate\s+-s\s+0\b/i,
220
+ label: "truncate file to zero",
221
+ category: "filesystem",
222
+ level: "prompt",
223
+ },
224
+ {
225
+ pattern: /\bshred\b/i,
226
+ label: "shred",
227
+ category: "filesystem",
228
+ level: "strong-confirm",
229
+ },
230
+ {
231
+ pattern: /\bdd\b[^\n;&|]*\bof=\/dev\//i,
232
+ label: "dd to block device",
233
+ category: "filesystem",
234
+ level: "block-noninteractive",
235
+ },
93
236
  { pattern: /\bdd\b/i, label: "dd", category: "filesystem", level: "prompt" },
94
- { pattern: /\bmkfs(?:\.|\b)/i, label: "mkfs", category: "filesystem", level: "block-noninteractive" },
95
- { pattern: /\b(?:wipefs|parted|fdisk|sfdisk|sgdisk)\b/i, label: "disk partition/filesystem tool", category: "filesystem", level: "block-noninteractive" },
237
+ {
238
+ pattern: /\bmkfs(?:\.|\b)/i,
239
+ label: "mkfs",
240
+ category: "filesystem",
241
+ level: "block-noninteractive",
242
+ },
243
+ {
244
+ pattern: /\b(?:wipefs|parted|fdisk|sfdisk|sgdisk)\b/i,
245
+ label: "disk partition/filesystem tool",
246
+ category: "filesystem",
247
+ level: "block-noninteractive",
248
+ },
96
249
  ];
97
250
 
98
251
  const DOCKER_RULES: CommandRule[] = [
99
- { pattern: /\bdocker\s+(?:rm|rmi)\b/i, label: "docker remove", category: "docker", level: "prompt" },
100
- { pattern: /\bdocker\s+volume\s+(?:rm|prune)\b/i, label: "docker volume removal/prune", category: "docker", level: "block-noninteractive" },
101
- { pattern: /\bdocker\s+system\s+prune\b/i, label: "docker system prune", category: "docker", level: "strong-confirm" },
102
- { pattern: /\bdocker\s+compose\s+down\b[^\n;&|]*(?:-v|--volumes)\b/i, label: "docker compose down --volumes", category: "docker", level: "block-noninteractive" },
103
- { pattern: /\bdocker-compose\s+down\b[^\n;&|]*(?:-v|--volumes)\b/i, label: "docker-compose down --volumes", category: "docker", level: "block-noninteractive" },
104
- { pattern: /\bpodman\s+(?:rm|rmi)\b/i, label: "podman remove", category: "docker", level: "prompt" },
105
- { pattern: /\bpodman\s+system\s+prune\b/i, label: "podman system prune", category: "docker", level: "strong-confirm" },
252
+ {
253
+ pattern: /\bdocker\s+(?:rm|rmi)\b/i,
254
+ label: "docker remove",
255
+ category: "docker",
256
+ level: "prompt",
257
+ },
258
+ {
259
+ pattern: /\bdocker\s+volume\s+(?:rm|prune)\b/i,
260
+ label: "docker volume removal/prune",
261
+ category: "docker",
262
+ level: "block-noninteractive",
263
+ },
264
+ {
265
+ pattern: /\bdocker\s+system\s+prune\b/i,
266
+ label: "docker system prune",
267
+ category: "docker",
268
+ level: "strong-confirm",
269
+ },
270
+ {
271
+ pattern: /\bdocker\s+compose\s+down\b[^\n;&|]*(?:-v|--volumes)\b/i,
272
+ label: "docker compose down --volumes",
273
+ category: "docker",
274
+ level: "block-noninteractive",
275
+ },
276
+ {
277
+ pattern: /\bdocker-compose\s+down\b[^\n;&|]*(?:-v|--volumes)\b/i,
278
+ label: "docker-compose down --volumes",
279
+ category: "docker",
280
+ level: "block-noninteractive",
281
+ },
282
+ {
283
+ pattern: /\bpodman\s+(?:rm|rmi)\b/i,
284
+ label: "podman remove",
285
+ category: "docker",
286
+ level: "prompt",
287
+ },
288
+ {
289
+ pattern: /\bpodman\s+system\s+prune\b/i,
290
+ label: "podman system prune",
291
+ category: "docker",
292
+ level: "strong-confirm",
293
+ },
106
294
  ];
107
295
 
108
296
  const PACKAGE_MANAGER_RULES: CommandRule[] = [
109
- { pattern: /\b(?:npm|pnpm|yarn|bun)\s+(?:uninstall|remove|rm|prune|autoclean)\b/i, label: "JS package removal", category: "package", level: "prompt" },
110
- { pattern: /\b(?:pip|uv|cargo)\s+(?:uninstall|remove)\b/i, label: "package removal", category: "package", level: "prompt" },
111
- { pattern: /\b(?:pacman|paru|yay)\s+-R/i, label: "Arch package removal", category: "package", level: "strong-confirm" },
112
- { pattern: /\bapt(?:-get)?\s+(?:remove|purge|autoremove)\b/i, label: "APT package removal", category: "package", level: "strong-confirm" },
113
- { pattern: /\bdnf\s+remove\b/i, label: "DNF package removal", category: "package", level: "strong-confirm" },
297
+ {
298
+ pattern:
299
+ /\b(?:npm|pnpm|yarn|bun)\s+(?:uninstall|remove|rm|prune|autoclean)\b/i,
300
+ label: "JS package removal",
301
+ category: "package",
302
+ level: "prompt",
303
+ },
304
+ {
305
+ pattern: /\b(?:pip|uv|cargo)\s+(?:uninstall|remove)\b/i,
306
+ label: "package removal",
307
+ category: "package",
308
+ level: "prompt",
309
+ },
310
+ {
311
+ pattern: /\b(?:pacman|paru|yay)\s+-R/i,
312
+ label: "Arch package removal",
313
+ category: "package",
314
+ level: "strong-confirm",
315
+ },
316
+ {
317
+ pattern: /\bapt(?:-get)?\s+(?:remove|purge|autoremove)\b/i,
318
+ label: "APT package removal",
319
+ category: "package",
320
+ level: "strong-confirm",
321
+ },
322
+ {
323
+ pattern: /\bdnf\s+remove\b/i,
324
+ label: "DNF package removal",
325
+ category: "package",
326
+ level: "strong-confirm",
327
+ },
114
328
  ];
115
329
 
116
330
  const SYSTEM_RULES: CommandRule[] = [
117
331
  { pattern: /\bsudo\b/i, label: "sudo", category: "system", level: "prompt" },
118
- { pattern: /\b(?:shutdown|reboot|poweroff)\b/i, label: "shutdown/reboot", category: "system", level: "block-noninteractive" },
119
- { pattern: /\bsystemctl\s+(?:stop|disable|mask|restart)\b/i, label: "systemctl service change", category: "system", level: "prompt" },
120
- { pattern: /\b(?:killall|pkill)\b/i, label: "process kill", category: "system", level: "prompt" },
121
- { pattern: /\bkill\s+-9\b/i, label: "kill -9", category: "system", level: "prompt" },
122
- { pattern: /\b(?:umount|mount|swapon|swapoff)\b/i, label: "mount/swap change", category: "system", level: "prompt" },
123
- { pattern: /\b(?:chmod|chown)\b[^\n;&|]*\s-R\b/i, label: "recursive chmod/chown", category: "system", level: "prompt" },
124
- { pattern: /\bchmod\b[^\n;&|]*\s777\b/i, label: "chmod 777", category: "system", level: "prompt" },
125
- { pattern: /\bsetfacl\b/i, label: "ACL change", category: "system", level: "prompt" },
126
- { pattern: /:\(\)\s*\{/i, label: "fork bomb", category: "system", level: "block-noninteractive" },
332
+ {
333
+ pattern: /\b(?:shutdown|reboot|poweroff)\b/i,
334
+ label: "shutdown/reboot",
335
+ category: "system",
336
+ level: "block-noninteractive",
337
+ },
338
+ {
339
+ pattern: /\bsystemctl\s+(?:stop|disable|mask|restart)\b/i,
340
+ label: "systemctl service change",
341
+ category: "system",
342
+ level: "prompt",
343
+ },
344
+ {
345
+ pattern: /\b(?:killall|pkill)\b/i,
346
+ label: "process kill",
347
+ category: "system",
348
+ level: "prompt",
349
+ },
350
+ {
351
+ pattern: /\bkill\s+-9\b/i,
352
+ label: "kill -9",
353
+ category: "system",
354
+ level: "prompt",
355
+ },
356
+ {
357
+ pattern: /\b(?:umount|mount|swapon|swapoff)\b/i,
358
+ label: "mount/swap change",
359
+ category: "system",
360
+ level: "prompt",
361
+ },
362
+ {
363
+ pattern: /\b(?:chmod|chown)\b[^\n;&|]*\s-R\b/i,
364
+ label: "recursive chmod/chown",
365
+ category: "system",
366
+ level: "prompt",
367
+ },
368
+ {
369
+ pattern: /\bchmod\b[^\n;&|]*\s777\b/i,
370
+ label: "chmod 777",
371
+ category: "system",
372
+ level: "prompt",
373
+ },
374
+ {
375
+ pattern: /\bsetfacl\b/i,
376
+ label: "ACL change",
377
+ category: "system",
378
+ level: "prompt",
379
+ },
380
+ {
381
+ pattern: /:\(\)\s*\{/i,
382
+ label: "fork bomb",
383
+ category: "system",
384
+ level: "block-noninteractive",
385
+ },
127
386
  ];
128
387
 
129
388
  const DATABASE_RULES: CommandRule[] = [
130
- { pattern: /\bDROP\s+(?:DATABASE|SCHEMA)\b/i, label: "SQL drop database/schema", category: "database", level: "block-noninteractive" },
131
- { pattern: /\bDROP\s+TABLE\b/i, label: "SQL drop table", category: "database", level: "strong-confirm" },
132
- { pattern: /\bDROP\s+INDEX\b/i, label: "SQL drop index", category: "database", level: "strong-confirm" },
133
- { pattern: /\bTRUNCATE\s+(?:TABLE\s+)?[\w.`\"\[\]-]+/i, label: "SQL truncate table", category: "database", level: "strong-confirm" },
134
- { pattern: /\bDELETE\s+FROM\b(?:(?!\bWHERE\b|;)[\s\S])*(?:;|$)/i, label: "SQL delete without WHERE", category: "database", level: "strong-confirm" },
135
- { pattern: /\bUPDATE\s+[\w.`\"\[\]-]+\s+SET\b(?:(?!\bWHERE\b|;)[\s\S])*(?:;|$)/i, label: "SQL update without WHERE", category: "database", level: "strong-confirm" },
136
- { pattern: /\bALTER\s+TABLE\b[\s\S]*\bDROP\s+(?:COLUMN|CONSTRAINT)\b/i, label: "SQL alter table drop", category: "database", level: "strong-confirm" },
389
+ {
390
+ pattern: /\bDROP\s+(?:DATABASE|SCHEMA)\b/i,
391
+ label: "SQL drop database/schema",
392
+ category: "database",
393
+ level: "block-noninteractive",
394
+ },
395
+ {
396
+ pattern: /\bDROP\s+TABLE\b/i,
397
+ label: "SQL drop table",
398
+ category: "database",
399
+ level: "strong-confirm",
400
+ },
401
+ {
402
+ pattern: /\bDROP\s+INDEX\b/i,
403
+ label: "SQL drop index",
404
+ category: "database",
405
+ level: "strong-confirm",
406
+ },
407
+ {
408
+ pattern: /\bTRUNCATE\s+(?:TABLE\s+)?[\w.`\"\[\]-]+/i,
409
+ label: "SQL truncate table",
410
+ category: "database",
411
+ level: "strong-confirm",
412
+ },
413
+ {
414
+ pattern: /\bDELETE\s+FROM\b(?:(?!\bWHERE\b|;)[\s\S])*(?:;|$)/i,
415
+ label: "SQL delete without WHERE",
416
+ category: "database",
417
+ level: "strong-confirm",
418
+ },
419
+ {
420
+ pattern:
421
+ /\bUPDATE\s+[\w.`\"\[\]-]+\s+SET\b(?:(?!\bWHERE\b|;)[\s\S])*(?:;|$)/i,
422
+ label: "SQL update without WHERE",
423
+ category: "database",
424
+ level: "strong-confirm",
425
+ },
426
+ {
427
+ pattern: /\bALTER\s+TABLE\b[\s\S]*\bDROP\s+(?:COLUMN|CONSTRAINT)\b/i,
428
+ label: "SQL alter table drop",
429
+ category: "database",
430
+ level: "strong-confirm",
431
+ },
137
432
  ];
138
433
 
139
434
  const SECRET_EXPOSURE_RULES: CommandRule[] = [
140
- { pattern: /\b(?:cat|grep|rg|awk|sed|cp)\b[^\n;&|]*(?:\.env(?:\.[^\s;&|]+)?|id_rsa|id_ed25519|\.git-credentials|auth\.json|\.npmrc|\.pypirc|\.netrc|credentials|hosts\.yml|\.pem|\.key|\.p12|\.kdbx)/i, label: "possible secret file access", category: "secrets", level: "prompt" },
435
+ {
436
+ pattern:
437
+ /\b(?:cat|grep|rg|awk|sed|cp)\b[^\n;&|]*(?:\.env(?:\.[^\s;&|]+)?|id_rsa|id_ed25519|\.git-credentials|auth\.json|\.npmrc|\.pypirc|\.netrc|credentials|hosts\.yml|\.pem|\.key|\.p12|\.kdbx)/i,
438
+ label: "possible secret file access",
439
+ category: "secrets",
440
+ level: "prompt",
441
+ },
141
442
  ];
142
443
 
143
444
  const DANGEROUS_BASH_RULES: CommandRule[] = [
@@ -153,7 +454,11 @@ function normalizeCwd(cwd: string): string {
153
454
  return path.resolve(cwd || process.cwd());
154
455
  }
155
456
 
156
- function allowKey(kind: AllowEntry["kind"], value: string, cwd: string): string {
457
+ function allowKey(
458
+ kind: AllowEntry["kind"],
459
+ value: string,
460
+ cwd: string,
461
+ ): string {
157
462
  return `${kind}:${normalizeCwd(cwd)}:${value}`;
158
463
  }
159
464
 
@@ -161,18 +466,22 @@ function readAllowStore(): AllowStore {
161
466
  try {
162
467
  const raw = fs.readFileSync(ALLOW_STORE_PATH, "utf8");
163
468
  const parsed = JSON.parse(raw) as Partial<AllowStore>;
164
- if (parsed.version !== 1 || !Array.isArray(parsed.entries)) return { version: 1, entries: [] };
469
+ if (parsed.version !== 1 || !Array.isArray(parsed.entries))
470
+ return { version: 1, entries: [] };
165
471
  return {
166
472
  version: 1,
167
- entries: parsed.entries.filter((entry): entry is AllowEntry => (
168
- !!entry
169
- && typeof entry.key === "string"
170
- && (entry.kind === "bash" || entry.kind === "write" || entry.kind === "edit")
171
- && typeof entry.value === "string"
172
- && typeof entry.cwd === "string"
173
- && typeof entry.label === "string"
174
- && typeof entry.createdAt === "string"
175
- )),
473
+ entries: parsed.entries.filter(
474
+ (entry): entry is AllowEntry =>
475
+ !!entry &&
476
+ typeof entry.key === "string" &&
477
+ (entry.kind === "bash" ||
478
+ entry.kind === "write" ||
479
+ entry.kind === "edit") &&
480
+ typeof entry.value === "string" &&
481
+ typeof entry.cwd === "string" &&
482
+ typeof entry.label === "string" &&
483
+ typeof entry.createdAt === "string",
484
+ ),
176
485
  };
177
486
  } catch {
178
487
  return { version: 1, entries: [] };
@@ -181,13 +490,19 @@ function readAllowStore(): AllowStore {
181
490
 
182
491
  function writeAllowStore(store: AllowStore): void {
183
492
  fs.mkdirSync(path.dirname(ALLOW_STORE_PATH), { recursive: true });
184
- fs.writeFileSync(ALLOW_STORE_PATH, `${JSON.stringify(store, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
493
+ fs.writeFileSync(ALLOW_STORE_PATH, `${JSON.stringify(store, null, 2)}\n`, {
494
+ encoding: "utf8",
495
+ mode: 0o600,
496
+ });
185
497
  }
186
498
 
187
499
  function addPermanentAllow(entry: Omit<AllowEntry, "createdAt">): void {
188
500
  const store = readAllowStore();
189
501
  const next: AllowEntry = { ...entry, createdAt: new Date().toISOString() };
190
- store.entries = [...store.entries.filter((existing) => existing.key !== entry.key), next];
502
+ store.entries = [
503
+ ...store.entries.filter((existing) => existing.key !== entry.key),
504
+ next,
505
+ ];
191
506
  writeAllowStore(store);
192
507
  }
193
508
 
@@ -244,32 +559,43 @@ async function confirmOrBlock(
244
559
  };
245
560
 
246
561
  const promptTitle = [
247
- ctx.ui.theme.fg("warning", `⚠ ${title}`),
562
+ ctx.ui.theme.fg("warning", `${title}`),
248
563
  "",
249
564
  message,
250
565
  ].join("\n");
251
566
 
252
- void ctx.ui.select(promptTitle, [
253
- "Block",
254
- "Allow once",
255
- "Allow for this session",
256
- "Always allow in this cwd",
257
- ]).then((choice) => {
258
- switch (choice) {
259
- case "Allow once":
260
- finish({ allow: true });
261
- break;
262
- case "Allow for this session":
263
- finish({ allow: true, scope: "session" });
264
- break;
265
- case "Always allow in this cwd":
266
- finish({ allow: true, scope: "permanent" });
267
- break;
268
- default:
269
- finish({ block: true, reason: "Blocked by aicode-safety-guard extension" });
270
- break;
271
- }
272
- }).catch(() => finish({ block: true, reason: "Blocked by aicode-safety-guard extension" }));
567
+ void ctx.ui
568
+ .select(promptTitle, [
569
+ "Block",
570
+ "Allow once",
571
+ "Allow for this session",
572
+ "Always allow in this cwd",
573
+ ])
574
+ .then((choice) => {
575
+ switch (choice) {
576
+ case "Allow once":
577
+ finish({ allow: true });
578
+ break;
579
+ case "Allow for this session":
580
+ finish({ allow: true, scope: "session" });
581
+ break;
582
+ case "Always allow in this cwd":
583
+ finish({ allow: true, scope: "permanent" });
584
+ break;
585
+ default:
586
+ finish({
587
+ block: true,
588
+ reason: "Blocked by aicode-safety-guard extension",
589
+ });
590
+ break;
591
+ }
592
+ })
593
+ .catch(() =>
594
+ finish({
595
+ block: true,
596
+ reason: "Blocked by aicode-safety-guard extension",
597
+ }),
598
+ );
273
599
  });
274
600
  }
275
601
 
@@ -285,7 +611,9 @@ function stripHeredocBodies(command: string): string {
285
611
  }
286
612
 
287
613
  kept.push(line);
288
- const match = line.match(/<<-?\s*(?:['"]?)([A-Za-z_][A-Za-z0-9_]*)(?:['"]?)/);
614
+ const match = line.match(
615
+ /<<-?\s*(?:['"]?)([A-Za-z_][A-Za-z0-9_]*)(?:['"]?)/,
616
+ );
289
617
  if (match) terminator = match[1];
290
618
  }
291
619
 
@@ -297,11 +625,7 @@ function previewCommand(command: string, maxChars = 800): string {
297
625
  return `${command.slice(0, maxChars)}\n… [truncated ${command.length - maxChars} chars for prompt display]`;
298
626
  }
299
627
 
300
- function highlightMatchedPattern(
301
- rule: CommandRule,
302
- line: string,
303
- highlight: (value: string) => string,
304
- ): string {
628
+ export function markMatchedPattern(rule: CommandRule, line: string): string {
305
629
  rule.pattern.lastIndex = 0;
306
630
  const match = rule.pattern.exec(line);
307
631
  rule.pattern.lastIndex = 0;
@@ -309,13 +633,12 @@ function highlightMatchedPattern(
309
633
 
310
634
  const start = match.index;
311
635
  const end = start + match[0].length;
312
- return `${line.slice(0, start)}${highlight(`>>> ${match[0]} <<<`)}${line.slice(end)}`;
636
+ return `${line.slice(0, start)}${MATCH_START} ${match[0]} ${MATCH_END}${line.slice(end)}`;
313
637
  }
314
638
 
315
- function matchingCommandExcerpt(
639
+ export function matchingCommandExcerpt(
316
640
  rule: CommandRule,
317
641
  commandForMatching: string,
318
- highlight: (value: string) => string = (value) => value,
319
642
  ): string {
320
643
  const lines = commandForMatching.split(/\r?\n/);
321
644
  const matchedIndexes = lines
@@ -347,37 +670,43 @@ function matchingCommandExcerpt(
347
670
  .sort((a, b) => a - b)
348
671
  .map((lineIndex) => {
349
672
  const isMatchedLine = matchedSet.has(lineIndex);
350
- const marker = isMatchedLine ? highlight("!!!") : " ";
673
+ const marker = isMatchedLine ? LINE_MARK : " ";
351
674
  const lineNumber = String(lineIndex + 1).padStart(lineNumberWidth, " ");
352
- const line = isMatchedLine ? highlightMatchedPattern(rule, lines[lineIndex], highlight) : lines[lineIndex];
675
+ const line = isMatchedLine
676
+ ? markMatchedPattern(rule, lines[lineIndex])
677
+ : lines[lineIndex];
353
678
  return `${marker} ${lineNumber} | ${line}`;
354
679
  });
355
680
 
356
- if (matchedIndexes.length > 3) excerptLines.push(`… ${matchedIndexes.length - 3} more matching lines omitted`);
681
+ if (matchedIndexes.length > 3)
682
+ excerptLines.push(
683
+ `… ${matchedIndexes.length - 3} more matching lines omitted`,
684
+ );
357
685
  return previewCommand(excerptLines.join("\n"), 1000);
358
686
  }
359
687
 
360
- function formatRuleMessage(
688
+ export function formatRuleMessage(
361
689
  rule: CommandRule,
362
690
  commandForMatching: string,
363
- highlight: (value: string) => string = (value) => value,
364
691
  ): { title: string; message: string; nonInteractiveReason: string } {
365
- const title = rule.level === "strong-confirm"
366
- ? "⚠ aicode提示:高危 bash 命令"
367
- : "⚠ aicode提示:危险 bash 命令";
368
- const impact = rule.level === "strong-confirm"
369
- ? "此操作难以撤销。执行前请确认目标、分支和作用域。"
370
- : "执行前请确认目标和作用域。";
371
- const excerpt = matchingCommandExcerpt(rule, commandForMatching, highlight);
692
+ const title =
693
+ rule.level === "strong-confirm"
694
+ ? "aicode提示:高危 bash 命令"
695
+ : "aicode提示:危险 bash 命令";
696
+ const impact =
697
+ rule.level === "strong-confirm"
698
+ ? "此操作难以撤销。执行前请确认目标、分支和作用域。"
699
+ : "执行前请确认目标和作用域。";
700
+ const excerpt = matchingCommandExcerpt(rule, commandForMatching);
372
701
 
373
702
  return {
374
703
  title,
375
704
  message: [
376
- `原因:${highlight(rule.label)}(${rule.category})`,
705
+ `原因:${rule.label}(${rule.category})`,
377
706
  impact,
378
707
  "",
379
708
  "危险行和上下文",
380
- `标记为 ${highlight("!!!")} 的行触发了安全规则;匹配的模式包裹为 ${highlight(">>> pattern >>>")}。`,
709
+ `标记为 ${LINE_MARK} 的行触发了安全规则;匹配的模式包裹为 ${MATCH_START} ... ${MATCH_END}。`,
381
710
  "────────────────────────────────────────",
382
711
  excerpt,
383
712
  "────────────────────────────────────────",
@@ -402,35 +731,55 @@ export default function safetyGuard(pi: ExtensionAPI) {
402
731
  const sessionAllow = new Map<string, AllowEntry>();
403
732
  let permanentAllow = readAllowStore();
404
733
 
405
- const isAllowed = (key: string): boolean => sessionAllow.has(key) || permanentAllow.entries.some((entry) => entry.key === key);
734
+ const isAllowed = (key: string): boolean =>
735
+ sessionAllow.has(key) ||
736
+ permanentAllow.entries.some((entry) => entry.key === key);
406
737
 
407
- const rememberAllow = (entry: Omit<AllowEntry, "createdAt">, scope: AllowScope, ctx: ExtensionContext): void => {
738
+ const rememberAllow = (
739
+ entry: Omit<AllowEntry, "createdAt">,
740
+ scope: AllowScope,
741
+ ctx: ExtensionContext,
742
+ ): void => {
408
743
  const next: AllowEntry = { ...entry, createdAt: new Date().toISOString() };
409
744
  if (scope === "session") {
410
745
  sessionAllow.set(entry.key, next);
411
- if (ctx.hasUI) ctx.ui.notify(`Allowed for this session: ${formatAllowEntry(next)}`, "info");
746
+ if (ctx.hasUI)
747
+ ctx.ui.notify(
748
+ `Allowed for this session: ${formatAllowEntry(next)}`,
749
+ "info",
750
+ );
412
751
  return;
413
752
  }
414
753
 
415
754
  addPermanentAllow(entry);
416
755
  permanentAllow = readAllowStore();
417
- if (ctx.hasUI) ctx.ui.notify(`Permanently allowed: ${formatAllowEntry(next)}`, "info");
756
+ if (ctx.hasUI)
757
+ ctx.ui.notify(`Permanently allowed: ${formatAllowEntry(next)}`, "info");
418
758
  };
419
759
 
420
760
  pi.registerCommand("safety-guard", {
421
- description: "Safety guard control: on | off | status | allow-list | allow-clear-session | allow-clear-permanent",
761
+ description:
762
+ "Safety guard control: on | off | status | allow-list | allow-clear-session | allow-clear-permanent",
422
763
  handler: async (args, ctx) => {
423
764
  const cmd = args?.trim().toLowerCase();
424
765
  if (!cmd || cmd === "status") {
425
766
  permanentAllow = readAllowStore();
426
- if (ctx.hasUI) ctx.ui.notify(`Safety guard: ${enabled ? "ON" : "OFF"}. Allows: ${sessionAllow.size} session, ${permanentAllow.entries.length} permanent.\n\nTo add more safety rules, contact xujianjiang.`, "info");
767
+ if (ctx.hasUI)
768
+ ctx.ui.notify(
769
+ `Safety guard: ${enabled ? "ON" : "OFF"}. Allows: ${sessionAllow.size} session, ${permanentAllow.entries.length} permanent.\n\nTo add more safety rules, contact xujianjiang.`,
770
+ "info",
771
+ );
427
772
  updateStatus(ctx, enabled);
428
773
  return;
429
774
  }
430
775
  if (cmd === "on") {
431
776
  enabled = true;
432
777
  updateStatus(ctx, enabled);
433
- if (ctx.hasUI) ctx.ui.notify("Safety guard enabled\n\nTo add more safety rules, contact xujianjiang", "info");
778
+ if (ctx.hasUI)
779
+ ctx.ui.notify(
780
+ "Safety guard enabled\n\nTo add more safety rules, contact xujianjiang",
781
+ "info",
782
+ );
434
783
  return;
435
784
  }
436
785
  if (cmd === "off") {
@@ -443,26 +792,36 @@ export default function safetyGuard(pi: ExtensionAPI) {
443
792
  permanentAllow = readAllowStore();
444
793
  const lines = [
445
794
  "Session allows:",
446
- ...(sessionAllow.size ? [...sessionAllow.values()].map(formatAllowEntry) : ["(none)"]),
795
+ ...(sessionAllow.size
796
+ ? [...sessionAllow.values()].map(formatAllowEntry)
797
+ : ["(none)"]),
447
798
  "",
448
799
  `Permanent allows (${ALLOW_STORE_PATH}):`,
449
- ...(permanentAllow.entries.length ? permanentAllow.entries.map(formatAllowEntry) : ["(none)"]),
800
+ ...(permanentAllow.entries.length
801
+ ? permanentAllow.entries.map(formatAllowEntry)
802
+ : ["(none)"]),
450
803
  ];
451
804
  if (ctx.hasUI) ctx.ui.notify(lines.join("\n"), "info");
452
805
  return;
453
806
  }
454
807
  if (cmd === "allow-clear-session") {
455
808
  sessionAllow.clear();
456
- if (ctx.hasUI) ctx.ui.notify("Cleared safety guard session allow-list", "info");
809
+ if (ctx.hasUI)
810
+ ctx.ui.notify("Cleared safety guard session allow-list", "info");
457
811
  return;
458
812
  }
459
813
  if (cmd === "allow-clear-permanent") {
460
814
  writeAllowStore({ version: 1, entries: [] });
461
815
  permanentAllow = readAllowStore();
462
- if (ctx.hasUI) ctx.ui.notify("Cleared safety guard permanent allow-list", "info");
816
+ if (ctx.hasUI)
817
+ ctx.ui.notify("Cleared safety guard permanent allow-list", "info");
463
818
  return;
464
819
  }
465
- if (ctx.hasUI) ctx.ui.notify("Usage: /safety-guard on|off|status|allow-list|allow-clear-session|allow-clear-permanent", "warning");
820
+ if (ctx.hasUI)
821
+ ctx.ui.notify(
822
+ "Usage: /safety-guard on|off|status|allow-list|allow-clear-session|allow-clear-permanent",
823
+ "warning",
824
+ );
466
825
  return;
467
826
  },
468
827
  });
@@ -476,10 +835,15 @@ export default function safetyGuard(pi: ExtensionAPI) {
476
835
  if (isToolCallEventType("bash", event)) {
477
836
  const command = event.input.command ?? "";
478
837
  const commandForMatching = stripHeredocBodies(command);
479
- const shellMatch = DANGEROUS_BASH_RULES.find((entry) => entry.pattern.test(commandForMatching));
480
- const databaseMatch = DATABASE_RULES.find((entry) => entry.pattern.test(command));
838
+ const shellMatch = DANGEROUS_BASH_RULES.find((entry) =>
839
+ entry.pattern.test(commandForMatching),
840
+ );
841
+ const databaseMatch = DATABASE_RULES.find((entry) =>
842
+ entry.pattern.test(command),
843
+ );
481
844
  const match = shellMatch ?? databaseMatch;
482
- const matchedCommandText = databaseMatch && !shellMatch ? command : commandForMatching;
845
+ const matchedCommandText =
846
+ databaseMatch && !shellMatch ? command : commandForMatching;
483
847
  if (!match) return;
484
848
 
485
849
  const entry = {
@@ -492,8 +856,13 @@ export default function safetyGuard(pi: ExtensionAPI) {
492
856
  };
493
857
  if (isAllowed(entry.key)) return;
494
858
 
495
- const prompt = formatRuleMessage(match, matchedCommandText, (value) => ctx.ui.theme.fg("warning", value));
496
- const decision = await confirmOrBlock(ctx, prompt.title, prompt.message, prompt.nonInteractiveReason);
859
+ const prompt = formatRuleMessage(match, matchedCommandText);
860
+ const decision = await confirmOrBlock(
861
+ ctx,
862
+ prompt.title,
863
+ prompt.message,
864
+ prompt.nonInteractiveReason,
865
+ );
497
866
  const scope = allowedScope(decision);
498
867
  if (scope) rememberAllow(entry, scope, ctx);
499
868
  if (decision && "block" in decision) return decision;
@@ -552,4 +921,4 @@ export default function safetyGuard(pi: ExtensionAPI) {
552
921
  // 其他工具不拦截
553
922
  return;
554
923
  });
555
- }
924
+ }