@leeruu/agentguard 0.0.0-stage → 0.1.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/dist/proxy.js ADDED
@@ -0,0 +1,440 @@
1
+ /**
2
+ * agentguard · stdio 双向代理
3
+ *
4
+ * 设计约束(来自技术方案第 3 章「五个必坑」):
5
+ * 1. 任何诊断输出只写 stderr —— stdout 是协议流,写一个字节的日志就会污染它。
6
+ * 2. 不经过 readline —— 大 JSON(超长文件内容)会被行缓冲截断。这里用自建分割器,
7
+ * 只在遇到 0x0A 时切分,行长度无上限。
8
+ * 3. stdio 必须是 'pipe' —— 子进程直接继承 fd 等于把代理短路掉。
9
+ * 4. 转发原始字节,不 JSON.parse → JSON.stringify 往返(浮点精度 / 字段顺序 / \u 转义
10
+ * 都会变)。解析只发生在需要判定的地方(W3 接入策略时),转发永远走原始 Buffer。
11
+ * 5. Windows 下 npx / 各种 CLI 是 .cmd 垫片,直接 spawn 会 ENOENT。见 resolveCommand()。
12
+ *
13
+ * 第四个消息方向(server → client 的请求,如 sampling/createMessage)不走任何特殊分支:
14
+ * 只要方向是 upstream 往外,就原样转发,代理绝不消费 —— 否则某些 server 功能会静默挂住。
15
+ */
16
+ import { spawn } from 'node:child_process';
17
+ import { statSync } from 'node:fs';
18
+ import { delimiter, extname, join } from 'node:path';
19
+ import { buildErrorLine, ErrorCode } from './errors.js';
20
+ import { logger } from './logger.js';
21
+ import { decide } from './policy/decide.js';
22
+ import { LimitTracker } from './limits.js';
23
+ const LF = 0x0a;
24
+ /* ------------------------------------------------------------------ *
25
+ * 行分割:只在 0x0A 处切,行内字节原样保留(含行尾换行符)
26
+ * ------------------------------------------------------------------ */
27
+ class LineSplitter {
28
+ rest = [];
29
+ push(chunk) {
30
+ const lines = [];
31
+ let start = 0;
32
+ for (;;) {
33
+ const nl = chunk.indexOf(LF, start);
34
+ if (nl === -1)
35
+ break;
36
+ if (this.rest.length === 0) {
37
+ // 常见路径:整行都在这一块里,零拷贝
38
+ lines.push(chunk.subarray(start, nl + 1));
39
+ }
40
+ else {
41
+ this.rest.push(chunk.subarray(start, nl + 1));
42
+ lines.push(Buffer.concat(this.rest));
43
+ this.rest = [];
44
+ }
45
+ start = nl + 1;
46
+ }
47
+ if (start < chunk.length)
48
+ this.rest.push(chunk.subarray(start));
49
+ return lines;
50
+ }
51
+ /** 流结束时吐出最后一段没有换行结尾的内容(MCP 允许最后一行不带 \n) */
52
+ flush() {
53
+ if (this.rest.length === 0)
54
+ return undefined;
55
+ const tail = this.rest.length === 1 ? this.rest[0] : Buffer.concat(this.rest);
56
+ this.rest = [];
57
+ return tail;
58
+ }
59
+ }
60
+ /* ------------------------------------------------------------------ *
61
+ * 管道泵:带背压,不无界缓冲
62
+ * ------------------------------------------------------------------ */
63
+ function pump(src, dst, sink, endDstOnSourceEnd, dstLabel) {
64
+ const splitter = new LineSplitter();
65
+ let paused = false;
66
+ let dstBroken = false;
67
+ dst.on('drain', () => {
68
+ if (!paused)
69
+ return;
70
+ paused = false;
71
+ src.resume();
72
+ });
73
+ // 高危防御:upstream 先退出而 client 还在写(或客户端断开时我们还在回写),
74
+ // dst.write 会触发 EPIPE。Writable 没有监听 'error' 事件时会直接抛出,
75
+ // 整个代理进程带着堆栈崩掉。这里转成日志 + 该方向停止转发。
76
+ dst.on('error', (err) => {
77
+ dstBroken = true;
78
+ process.stderr.write(`agentguard: ${dstLabel} 写入失败,该方向停止转发:${err.message}\n`);
79
+ });
80
+ src.on('data', (chunk) => {
81
+ const buf = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;
82
+ let full = false;
83
+ for (const line of splitter.push(buf)) {
84
+ if (sink(line) === false)
85
+ continue;
86
+ if (dstBroken)
87
+ continue;
88
+ if (dst.write(line) === false)
89
+ full = true;
90
+ }
91
+ // 先写完本块内的所有行,再暂停;否则剩余行会滞留在内存里等下一次 data
92
+ if (full) {
93
+ paused = true;
94
+ src.pause();
95
+ }
96
+ });
97
+ src.on('end', () => {
98
+ const tail = splitter.flush();
99
+ if (!dstBroken && tail !== undefined && sink(tail) !== false)
100
+ dst.write(tail);
101
+ if (endDstOnSourceEnd)
102
+ dst.end();
103
+ });
104
+ src.on('error', (err) => {
105
+ process.stderr.write(`agentguard: upstream stream error: ${err.message}\n`);
106
+ });
107
+ }
108
+ /**
109
+ * 在 Windows 上按 PATH + PATHEXT 顺序解析可执行文件。
110
+ *
111
+ * 为什么不用 spawn(cmd, args, { shell: true }):Node 在 shell 模式下把
112
+ * [file, ...args].join(' ') 直接拼进 /c,参数里的空格不会被成对引号保护,
113
+ * `.../server-filesystem "D:\\my projects"` 会被劈成两个参数。这里自己拼命令行
114
+ * 并对每个 token 单独加引号,然后用 windowsVerbatimArguments 原样交给 cmd.exe。
115
+ */
116
+ export function resolveCommand(command, env = process.env) {
117
+ const isWindows = process.platform === 'win32';
118
+ const isShim = /\.(cmd|bat)$/i.test(command);
119
+ if (!isWindows)
120
+ return { file: command, via: 'direct' };
121
+ if (command === '')
122
+ throw new Error('empty upstream command');
123
+ const exts = (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
124
+ .split(';')
125
+ .map((ext) => ext.trim())
126
+ .filter((ext) => ext !== '');
127
+ const names = extname(command) === '' ? exts.map((ext) => command + ext) : [command];
128
+ const hasSeparator = /[\\/]/.test(command);
129
+ const candidates = [];
130
+ if (hasSeparator) {
131
+ candidates.push(...names);
132
+ }
133
+ else {
134
+ const pathVar = env.PATH ?? env.Path ?? '';
135
+ for (const dir of pathVar.split(delimiter)) {
136
+ if (dir === '')
137
+ continue;
138
+ for (const name of names)
139
+ candidates.push(join(dir, name));
140
+ }
141
+ }
142
+ for (const candidate of candidates) {
143
+ try {
144
+ if (statSync(candidate).isFile()) {
145
+ return { file: candidate, via: /\.(cmd|bat)$/i.test(candidate) ? 'cmd' : 'direct' };
146
+ }
147
+ }
148
+ catch {
149
+ // 不存在或无权限,继续找下一个候选
150
+ }
151
+ }
152
+ // 没找到:交给 spawn 报 ENOENT(或 cmd.exe 自己去解析),错误信息会带上原始命令名
153
+ return { file: command, via: isShim ? 'cmd' : 'direct' };
154
+ }
155
+ function quoteForCmd(token) {
156
+ if (token === '')
157
+ return '""';
158
+ if (!/[\s"&|<>^()]/.test(token))
159
+ return token;
160
+ return `"${token.replace(/"/g, '""')}"`;
161
+ }
162
+ function spawnUpstream(resolved, args, spec) {
163
+ const options = {
164
+ // 坑 #3:三条流全部显式 pipe,子进程绝不能继承我们的 fd
165
+ stdio: ['pipe', 'pipe', 'inherit'],
166
+ cwd: spec.cwd,
167
+ env: spec.env ?? process.env,
168
+ windowsHide: true,
169
+ };
170
+ if (resolved.via === 'cmd' && process.platform === 'win32') {
171
+ const line = [resolved.file, ...args].map(quoteForCmd).join(' ');
172
+ return spawn(process.env.ComSpec ?? 'cmd.exe', ['/d', '/s', '/c', `"${line}"`], {
173
+ ...options,
174
+ windowsVerbatimArguments: true,
175
+ });
176
+ }
177
+ return spawn(resolved.file, [...args], options);
178
+ }
179
+ /* ------------------------------------------------------------------ *
180
+ * 判定闸门(W3)
181
+ *
182
+ * 只拦 client → upstream 方向的 tools/call:
183
+ * allow → 原样转发
184
+ * deny → 用原 id 回 -32001,upstream 根本收不到这条消息(命令没有执行机会)
185
+ * ask → 同理回 -32001,并在消息里说明「无审批通道,按拒绝处理」
186
+ *
187
+ * 为什么 ask 不弹交互确认:代理的 stdin 就是协议流,从里面读 y/n 会把 MCP 消息吃掉;
188
+ * 真要做交互,必须另开控制终端(CONIN$ / /dev/tty),否则一读就死锁。
189
+ * 在拿到可靠的审批通道之前,ask 的行为就是「明确拒绝」,绝不静默放行。
190
+ * ------------------------------------------------------------------ */
191
+ const TOOLS_CALL = Buffer.from('"tools/call"', 'utf8');
192
+ const CLIENT_INFO = Buffer.from('"clientInfo"', 'utf8');
193
+ const ID_PEEK = /"id"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+|null)/;
194
+ function isRecord(value) {
195
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
196
+ }
197
+ function toRequestId(value) {
198
+ if (typeof value === 'string' || typeof value === 'number')
199
+ return value;
200
+ if (value === null)
201
+ return null;
202
+ return undefined;
203
+ }
204
+ /**
205
+ * 解析一行 JSON。容忍 UTF-8 BOM:某些客户端/编辑器会把 BOM 带进行首,
206
+ * 标准 JSON.parse 会直接抛错,表现为「某个 agent 配上来就所有调用都失败」。
207
+ */
208
+ function parseJsonLine(line) {
209
+ const text = line.toString('utf8');
210
+ return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
211
+ }
212
+ /** 只读响应头 512 字节取 id,避免为每个响应解析整行(响应体可能几 MB) */
213
+ function peekId(line) {
214
+ const text = (line.length > 512 ? line.subarray(0, 512) : line).toString('utf8');
215
+ const match = ID_PEEK.exec(text);
216
+ if (match === null)
217
+ return undefined;
218
+ const token = match[1];
219
+ if (token === 'null')
220
+ return null;
221
+ if (token.startsWith('"')) {
222
+ try {
223
+ return JSON.parse(token);
224
+ }
225
+ catch {
226
+ return undefined;
227
+ }
228
+ }
229
+ return Number(token);
230
+ }
231
+ function createGate(policy, out, options) {
232
+ // 已放行、尚未收到响应的请求 id;upstream 崩溃时它们必须收到错误,否则 client 会一直等
233
+ const pending = new Set();
234
+ // clientInfo.name 只在 initialize 里出现一次,抓到后整场复用
235
+ let agent = null;
236
+ const record = (tool, args, decision, detail) => {
237
+ if (options.audit === undefined)
238
+ return;
239
+ try {
240
+ options.audit.write({
241
+ ts: new Date().toISOString(),
242
+ reqId: detail.reqId,
243
+ tool,
244
+ args,
245
+ decision,
246
+ ...(detail.raw === undefined || detail.raw === decision ? {} : { raw: detail.raw }),
247
+ ruleId: detail.ruleId,
248
+ reason: detail.reason,
249
+ ms: Number(detail.ms.toFixed(3)),
250
+ session: options.session,
251
+ agent,
252
+ ...(detail.dryRun === true ? { dryRun: true } : {}),
253
+ });
254
+ }
255
+ catch (err) {
256
+ logger.error('审计记录写入异常', { error: err.message });
257
+ }
258
+ };
259
+ return {
260
+ onClientLine(line) {
261
+ if (agent === null && line.indexOf(CLIENT_INFO) !== -1) {
262
+ try {
263
+ const message = parseJsonLine(line);
264
+ const name = message.params?.clientInfo?.name;
265
+ if (typeof name === 'string' && name !== '')
266
+ agent = name;
267
+ }
268
+ catch {
269
+ // 解析不了就当没抓到,不影响转发
270
+ }
271
+ }
272
+ // 快速路径:不含 "tools/call" 的行不解析、不判定,直接转发
273
+ if (line.indexOf(TOOLS_CALL) === -1)
274
+ return true;
275
+ let message;
276
+ try {
277
+ message = parseJsonLine(line);
278
+ }
279
+ catch {
280
+ logger.warn('无法解析的 tools/call 行,原样转发交给 upstream 报错');
281
+ return true;
282
+ }
283
+ if (!isRecord(message) || message.method !== 'tools/call')
284
+ return true;
285
+ const params = isRecord(message.params) ? message.params : {};
286
+ const tool = typeof params.name === 'string' ? params.name : '';
287
+ const args = params.arguments ?? {};
288
+ const id = toRequestId(message.id);
289
+ const reqId = typeof id === 'string' || typeof id === 'number' ? id : null;
290
+ let result;
291
+ try {
292
+ result = decide(policy, tool, args);
293
+ }
294
+ catch (err) {
295
+ // 判定过程本身异常也必须 fail closed,绝不能因为「引擎出错」就放行
296
+ logger.error('策略判定异常,按拒绝处理', { error: err.message });
297
+ record(tool, args, 'deny', {
298
+ ruleId: null,
299
+ reason: `判定异常:${err.message}`,
300
+ ms: 0,
301
+ reqId,
302
+ });
303
+ if (id !== undefined) {
304
+ out.write(buildErrorLine(id, ErrorCode.POLICY_UNAVAILABLE, 'Policy engine failure (fail-closed)'));
305
+ }
306
+ return false;
307
+ }
308
+ if (result.dryRun && result.raw !== 'allow') {
309
+ logger.info('dry_run:本应拦截,已放行', {
310
+ tool,
311
+ raw: result.raw,
312
+ rule: result.ruleId ?? '-',
313
+ });
314
+ }
315
+ if (result.decision === 'allow') {
316
+ // 限流只在「策略本来会放行」的调用上生效;被拒的调用回 -32001 更有信息量
317
+ const limit = options.limits?.check(tool);
318
+ if (limit !== undefined && !limit.ok) {
319
+ const reason = `限流:${tool} 在 ${limit.rule.window} 内超过 ${limit.maxCalls} 次`;
320
+ record(tool, args, 'deny', { ruleId: null, reason, ms: result.elapsedMs, reqId });
321
+ if (id !== undefined) {
322
+ out.write(buildErrorLine(id, ErrorCode.RATE_LIMITED, `Rate limited: ${reason}`, {
323
+ maxCalls: limit.maxCalls,
324
+ window: limit.rule.window,
325
+ count: limit.count,
326
+ }));
327
+ }
328
+ logger.warn('触发限流', { tool, window: limit.rule.window, max: limit.maxCalls });
329
+ return false;
330
+ }
331
+ record(tool, args, 'allow', {
332
+ raw: result.raw,
333
+ ruleId: result.ruleId,
334
+ reason: result.reason,
335
+ ms: result.elapsedMs,
336
+ reqId,
337
+ dryRun: result.dryRun,
338
+ });
339
+ if (typeof id === 'string' || typeof id === 'number')
340
+ pending.add(id);
341
+ return true;
342
+ }
343
+ const ruleLabel = result.ruleId ?? '(fail-closed)';
344
+ record(tool, args, result.decision === 'ask' ? 'ask' : 'deny', {
345
+ raw: result.raw,
346
+ ruleId: result.ruleId,
347
+ reason: result.reason,
348
+ ms: result.elapsedMs,
349
+ reqId,
350
+ dryRun: result.dryRun,
351
+ });
352
+ if (id === undefined) {
353
+ // 通知没有 id,按协议不能回 error;丢掉即等于「不执行」
354
+ logger.warn('拒绝了一个无 id 的 tools/call 通知', { tool, rule: ruleLabel });
355
+ return false;
356
+ }
357
+ const text = result.decision === 'ask'
358
+ ? `Blocked by policy ${ruleLabel}: 需要人工确认,当前无审批通道,按拒绝处理${result.reason === null ? '' : `(${result.reason})`}`
359
+ : `Blocked by policy ${ruleLabel}: ${result.reason ?? ''}`;
360
+ out.write(buildErrorLine(id, ErrorCode.POLICY_DENIED, text, {
361
+ ruleId: result.ruleId,
362
+ reason: result.reason,
363
+ decision: result.raw,
364
+ dryRun: result.dryRun,
365
+ }));
366
+ logger.info('拦截调用', { tool, rule: ruleLabel, id });
367
+ return false;
368
+ },
369
+ onUpstreamLine(line) {
370
+ if (pending.size === 0)
371
+ return;
372
+ const id = peekId(line);
373
+ if (typeof id === 'string' || typeof id === 'number')
374
+ pending.delete(id);
375
+ },
376
+ onUpstreamClose() {
377
+ for (const id of pending) {
378
+ out.write(buildErrorLine(id, ErrorCode.INTERNAL_ERROR, 'upstream exited before responding'));
379
+ }
380
+ pending.clear();
381
+ },
382
+ };
383
+ }
384
+ /* ------------------------------------------------------------------ *
385
+ * 代理主体
386
+ * ------------------------------------------------------------------ */
387
+ export function startProxy(spec) {
388
+ const [command, ...args] = spec.command;
389
+ if (command === undefined)
390
+ throw new Error('no upstream command given');
391
+ const resolved = resolveCommand(command, spec.env ?? process.env);
392
+ const child = spawnUpstream(resolved, args, spec);
393
+ const gate = spec.policy === undefined
394
+ ? null
395
+ : createGate(spec.policy, process.stdout, {
396
+ audit: spec.audit,
397
+ limits: spec.policy.limits.length === 0 ? undefined : new LimitTracker(spec.policy.limits),
398
+ session: spec.session ?? 'unknown',
399
+ });
400
+ // 必须在 done 的 close 监听之前注册:先把「未完成请求的错误」写出去,再让进程收尾
401
+ if (gate !== null)
402
+ child.once('close', () => gate.onUpstreamClose());
403
+ // 优先等 'close':'exit' 触发时 stdout 管道可能还没读空,upstream「回完最后一条响应
404
+ // 立刻退出」时那条有丢失风险(本机 40 轮压测未复现,属防御性写法)。
405
+ // 但若 upstream 有孙进程占住管道,'close' 可能迟迟不来 —— 所以 exit 后 500ms 强制收尾。
406
+ const done = new Promise((resolve, reject) => {
407
+ let settled = false;
408
+ const finish = (code, signal) => {
409
+ if (settled)
410
+ return;
411
+ settled = true;
412
+ resolve(code ?? (signal === null ? 0 : 1));
413
+ };
414
+ child.once('error', reject);
415
+ child.once('exit', (code, signal) => {
416
+ setTimeout(() => finish(code, signal), 500).unref();
417
+ });
418
+ child.once('close', (code, signal) => finish(code, signal));
419
+ });
420
+ // 主链路只关心退出,这里吞掉避免 unattended rejection
421
+ done.catch(() => { });
422
+ // client → upstream:先过判定闸门(无策略时纯转发);W4 的策略钩子与审计都挂在这里
423
+ if (child.stdin) {
424
+ pump(process.stdin, child.stdin, (line) => (gate === null ? true : gate.onClientLine(line)), true, 'client → upstream');
425
+ }
426
+ // upstream → client:原样转发,包括 server 主动发起的请求
427
+ if (child.stdout) {
428
+ pump(child.stdout, process.stdout, (line) => {
429
+ gate?.onUpstreamLine(line);
430
+ return true;
431
+ }, false, 'upstream → client');
432
+ }
433
+ const kill = () => {
434
+ if (child.exitCode === null && child.signalCode === null)
435
+ child.kill();
436
+ };
437
+ // 退出时顺手带走子进程。信号处理交给 main(它要先把审计刷盘再退)
438
+ process.once('exit', kill);
439
+ return { child, done };
440
+ }
package/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
2
  "name": "@leeruu/agentguard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Local permission gateway for MCP agents: YAML policy, deterministic decisions, full audit trail.",
5
+ "license": "Apache-2.0",
6
+ "author": "leeruu",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/MmUu001/agentguard.git"
10
+ },
11
+ "homepage": "https://github.com/MmUu001/agentguard#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/MmUu001/agentguard/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "type": "module",
19
+ "engines": {
20
+ "node": ">=20"
21
+ },
22
+ "bin": {
23
+ "agentguard": "dist/main.js"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "packs",
28
+ "NOTICE"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.json",
32
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
33
+ "prepublishOnly": "npm run clean && npm run build",
34
+ "check:w1": "node tests/w1-check.mjs",
35
+ "check:w2": "node tests/w2-check.mjs",
36
+ "check:w3": "node tests/w3-check.mjs",
37
+ "check:w4": "node tests/w4-check.mjs",
38
+ "check:w5": "node tests/w5-check.mjs",
39
+ "check:attacks": "node tests/attacks-check.mjs",
40
+ "check:stress": "node tests/stress-check.mjs",
41
+ "check:lint": "node tests/lint-check.mjs",
42
+ "check:coldstart": "node tests/coldstart-check.mjs",
43
+ "check:real": "node tests/real-fs-check.mjs",
44
+ "check:pkg": "node tests/install-check.mjs",
45
+ "check:all": "node tests/w1-check.mjs && node tests/w2-check.mjs && node tests/w3-check.mjs && node tests/w4-check.mjs && node tests/w5-check.mjs && node tests/attacks-check.mjs && node tests/stress-check.mjs && node tests/lint-check.mjs && node tests/coldstart-check.mjs && node tests/real-fs-check.mjs && node tests/export-check.mjs && node tests/epipe-check.mjs && node tests/demo-check.mjs && node tests/install-check.mjs",
46
+ "check:demo": "node tests/demo-check.mjs",
47
+ "check:epipe": "node tests/epipe-check.mjs",
48
+ "check:export": "node tests/export-check.mjs"
49
+ },
50
+ "keywords": [
51
+ "mcp",
52
+ "mcp-server",
53
+ "agent",
54
+ "ai-agent",
55
+ "security",
56
+ "permission",
57
+ "policy",
58
+ "guardrail",
59
+ "firewall",
60
+ "claude-code",
61
+ "cursor",
62
+ "llm"
63
+ ],
64
+ "devDependencies": {
65
+ "@types/node": "^22.20.5",
66
+ "typescript": "^5.9.3"
67
+ },
68
+ "dependencies": {
69
+ "yaml": "^2.9.1"
70
+ }
71
+ }
@@ -0,0 +1,104 @@
1
+ version: 1
2
+
3
+ # core · 灾难性误操作(默认必装)
4
+ #
5
+ # 取舍:只拦「几乎不可能正确」的命令。判错 = 误伤一次正常开发;
6
+ # 判漏 = 整个项目或整台机器没了。所以这几个正则写宽一点是故意的。
7
+ #
8
+ # 工具名列表覆盖 Claude Code / Cursor / Cline / 各家 shell server 的常见命名,
9
+ # 不是精确匹配清单 —— 你的工具名不在里面,加一行即可。
10
+
11
+ rules:
12
+ # ── rm 递归强制删除 ────────────────────────────────────────────────
13
+ # 覆盖:rm -rf /、rm -fr /var、rm -r -f /、rm -rf ~、rm -rf /*、rm -rf $HOME
14
+ # 不覆盖:rm -rf ./build(正常开发,必须放过)
15
+ - id: core-rm-rf-root
16
+ match:
17
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
18
+ args.command:
19
+ regex: '(?:^|[\s;&|])rm\s+(?:-[a-zA-Z]+\s+)*-(?:[a-zA-Z]*r[a-zA-Z]*f|[a-zA-Z]*f[a-zA-Z]*r)[a-zA-Z]*\s+(?:/|/\*|~|~/\*|\$HOME/?)(?:[\s;&|]|$)'
20
+ decision: deny
21
+ reason: 递归强制删除根目录或家目录
22
+
23
+ # rm -r -f / —— 短参数拆开写,上面那条正则吃不到
24
+ - id: core-rm-rf-split-flags
25
+ match:
26
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
27
+ args.command:
28
+ regex: '(?:^|[\s;&|])rm\s+(?:-[a-zA-Z]+\s+)*(?:-[rR]\s+-[a-zA-Z]*f[a-zA-Z]*|-[fF]\s+-[a-zA-Z]*r[a-zA-Z]*)\s+(?:/|/\*|~|~/\*|\$HOME/?|/(?:etc|usr|bin|sbin|lib|lib64|boot|var|opt|sys|proc|dev|Windows|System|Library)(?:/|[\s;&|]|$))'
29
+ decision: deny
30
+ reason: 递归强制删除根目录或家目录(参数拆写变体)
31
+
32
+ # 系统目录:rm -rf /var、rm -rf /etc/nginx 之类。/tmp 与用户项目目录不在此列
33
+ - id: core-rm-rf-system
34
+ match:
35
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
36
+ args.command:
37
+ regex: '(?:^|[\s;&|])rm\s+(?:-[a-zA-Z]+\s+)*-(?:[a-zA-Z]*r[a-zA-Z]*f|[a-zA-Z]*f[a-zA-Z]*r)[a-zA-Z]*\s+/(?:etc|usr|bin|sbin|lib|lib64|boot|var|opt|sys|proc|dev|Windows|System|Library|Applications|private)(?:/|[\s;&|]|$)'
38
+ decision: deny
39
+ reason: 递归删除系统目录
40
+
41
+ # ── git 强制推送 ──────────────────────────────────────────────────
42
+ # --force-with-lease 是安全版本,必须放过
43
+ - id: core-force-push
44
+ match:
45
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
46
+ args.command:
47
+ regex: 'git\s+push\s+(?:[^\n]*\s)?(?:-f\b|--force(?!-))'
48
+ decision: ask
49
+ reason: 强制推送会覆盖远端历史
50
+
51
+ # ── 破坏性 SQL ────────────────────────────────────────────────────
52
+ - id: core-sql-destructive-command
53
+ match:
54
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
55
+ args.command:
56
+ regex: '\b(?:drop\s+(?:table|database|schema)|truncate\s+table)\b'
57
+ decision: deny
58
+ reason: 破坏性 SQL
59
+
60
+ - id: core-sql-destructive-query
61
+ match:
62
+ tool: [postgres_query, mysql_query, sqlite_query, execute_sql, run_sql, db_query]
63
+ args.query:
64
+ regex: '\b(?:drop\s+(?:table|database|schema)|truncate\s+table)\b'
65
+ decision: deny
66
+ reason: 破坏性 SQL
67
+
68
+ # ── 下载即执行 ────────────────────────────────────────────────────
69
+ - id: core-pipe-to-shell
70
+ match:
71
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
72
+ args.command:
73
+ regex: '(?:curl|wget)\s[^\n|]*\|\s*(?:sudo\s+)?(?:ba|z|k|da)?sh\b'
74
+ decision: deny
75
+ reason: 把远程脚本直接管道给 shell 执行
76
+
77
+ # ── 写系统目录 / 私钥 ─────────────────────────────────────────────
78
+ - id: core-write-system-path
79
+ match:
80
+ tool: [write_file, write_text_file, edit_file, create_directory, move_file, apply_patch]
81
+ args.path:
82
+ glob:
83
+ - '/etc/**'
84
+ - '/usr/**'
85
+ - '/bin/**'
86
+ - '/sbin/**'
87
+ - '/boot/**'
88
+ - '/lib/**'
89
+ - '/System/**'
90
+ - '/Library/**'
91
+ - 'C:/Windows/**'
92
+ - '**/.ssh/**'
93
+ - '**/.aws/**'
94
+ decision: deny
95
+ reason: 写入系统目录或凭据目录
96
+
97
+ # ── 磁盘级破坏 ────────────────────────────────────────────────────
98
+ - id: core-disk-destroy
99
+ match:
100
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
101
+ args.command:
102
+ regex: '\b(?:mkfs(?:\.\w+)?|shred\s[^\n]*/dev/|dd\s[^\n]*of=/dev/)'
103
+ decision: deny
104
+ reason: 格式化或覆写磁盘设备
package/packs/git.yaml ADDED
@@ -0,0 +1,43 @@
1
+ version: 1
2
+
3
+ # git · 版本库破坏(开发者可选)
4
+ #
5
+ # 这里的动作大多不可从 args 判断「是否会丢东西」,所以一律用 ask(当前实现 = 明确拒绝),
6
+ # 让用户自己看一眼再决定,而不是靠猜测。
7
+ #
8
+ # 明确不覆盖:`git rebase` 已推送分支 —— 从命令行参数无法知道「这个分支推送过没有」,
9
+ # 硬写会变成对本地日常 rebase 的持续误伤。这类判断需要读 git 状态,超出「纯 args 匹配」的能力。
10
+
11
+ rules:
12
+ - id: git-reset-hard
13
+ match:
14
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
15
+ args.command:
16
+ regex: 'git\s+reset\s+(?:[^\n]*\s)?--hard\b'
17
+ decision: ask
18
+ reason: reset --hard 会丢弃未提交的改动
19
+
20
+ # git clean -fdx / -xfd / -fdxq 都算
21
+ - id: git-clean-fdx
22
+ match:
23
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
24
+ args.command:
25
+ regex: 'git\s+clean\s+[^\n]*(?:-[a-zA-Z]*f[a-zA-Z]*[dx]|-[a-zA-Z]*[dx][a-zA-Z]*f)'
26
+ decision: ask
27
+ reason: git clean 会删除未跟踪文件(含被 .gitignore 忽略的)
28
+
29
+ - id: git-push-delete
30
+ match:
31
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
32
+ args.command:
33
+ regex: '(?:git\s+push\s+(?:[^\n]*\s)?(?:--delete|-d)\b|git\s+push\s+\S+\s+:)'
34
+ decision: ask
35
+ reason: 删除远端分支
36
+
37
+ - id: git-checkout-discard
38
+ match:
39
+ tool: [bash, shell, run_command, execute_command, terminal, powershell]
40
+ args.command:
41
+ regex: 'git\s+(?:checkout|restore)\s+(?:--\s+)?(?:\.|\*)(?:\s|$)'
42
+ decision: ask
43
+ reason: 丢弃工作区未提交的改动