@leeruu/agentguard 0.1.1 → 0.1.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.
package/README.md CHANGED
@@ -247,8 +247,14 @@ limits: # W2 解析并校验,W4 才执行
247
247
  ## 开发
248
248
 
249
249
  ```bash
250
+ git clone https://github.com/MmUu001/agentguard.git
251
+ cd agentguard
250
252
  npm install # 运行时依赖只有 yaml;devDeps 是 typescript / @types/node
251
253
  npm run build # tsc -> dist/
254
+ ```
255
+
256
+ > 在本仓库目录内调试请用 `node dist/main.js`,不要用 `npx @leeruu/agentguard`——
257
+ > 在包自己的目录里 npx 会解析到当前项目本身,bin 未链接时直接失败。
252
258
 
253
259
  npm run check:w1 # W1 验收:差分比对 + 6 类边界
254
260
  npm run check:w2 # W2 验收:判定语义 + 20 种非法策略 + 性能
package/dist/cli.js CHANGED
@@ -609,6 +609,124 @@ function demoCommand(argv) {
609
609
  }
610
610
  return runDemo({ ...(policyPath === undefined ? {} : { policyPath }) });
611
611
  }
612
+ /* ================================================================== *
613
+ * explain
614
+ * ================================================================== */
615
+ function explainUsage() {
616
+ return [
617
+ `${NAME} explain [options]`,
618
+ '',
619
+ '判定一次工具调用会得到什么结果(不执行,只判定)。',
620
+ `不传 --policy 时读 ${defaultPolicyPath()}`,
621
+ '',
622
+ 'Options:',
623
+ ' --tool <name> 工具名(必填),如 bash / read_file',
624
+ ' --command <cmd> 以 bash 类工具的命令串做匹配',
625
+ ' --path <p> 以文件路径做匹配',
626
+ ' --policy <file> 指定策略文件',
627
+ ].join('\n');
628
+ }
629
+ function collectExplainArgs(argv) {
630
+ const policies = [];
631
+ const opts = {};
632
+ const rest = [];
633
+ for (let i = 0; i < argv.length; i++) {
634
+ const arg = argv[i];
635
+ if (arg === '--policy') {
636
+ const value = argv[i + 1];
637
+ if (value === undefined)
638
+ throw new FlagError('--policy 后面必须跟文件路径');
639
+ policies.push(value);
640
+ i += 1;
641
+ continue;
642
+ }
643
+ if (arg.startsWith('--policy=')) {
644
+ policies.push(arg.slice('--policy='.length));
645
+ continue;
646
+ }
647
+ if (arg === '--tool' || arg === '--command' || arg === '--path') {
648
+ const value = argv[i + 1];
649
+ if (value === undefined)
650
+ throw new FlagError(`${arg} 后面必须跟一个值`);
651
+ opts[arg.slice(2)] = value;
652
+ i += 1;
653
+ continue;
654
+ }
655
+ if (arg === '--help' || arg === '-h') {
656
+ rest.push('--help');
657
+ continue;
658
+ }
659
+ rest.push(arg);
660
+ }
661
+ return { policies, ...opts, rest };
662
+ }
663
+ function explainCommand(argv) {
664
+ let parsed;
665
+ try {
666
+ parsed = collectExplainArgs(argv);
667
+ }
668
+ catch (err) {
669
+ process.stderr.write(`${NAME}: ${err.message}\n\n${explainUsage()}\n`);
670
+ return 2;
671
+ }
672
+ if (parsed.rest.includes('--help') || parsed.rest.includes('-h')) {
673
+ process.stdout.write(explainUsage() + '\n');
674
+ return 0;
675
+ }
676
+ if (parsed.rest.length > 0) {
677
+ process.stderr.write(`${NAME}: 不认识的参数 "${parsed.rest[0]}"\n\n${explainUsage()}\n`);
678
+ return 2;
679
+ }
680
+ if (parsed.policies[0] === 'help' && parsed.policies.length === 1) {
681
+ process.stdout.write(explainUsage() + '\n');
682
+ return 0;
683
+ }
684
+ const policyPaths = parsed.policies.length > 0
685
+ ? parsed.policies
686
+ : existsSync(defaultPolicyPath())
687
+ ? [defaultPolicyPath()]
688
+ : null;
689
+ if (policyPaths === null) {
690
+ process.stderr.write(`${NAME}: 没有找到策略文件。先跑 \`${NAME} init\`\n`);
691
+ return 2;
692
+ }
693
+ const tool = parsed.tool;
694
+ if (tool === undefined) {
695
+ process.stderr.write(`${NAME}: --tool 必填(要判定的工具名)\n\n${explainUsage()}\n`);
696
+ return 2;
697
+ }
698
+ if (parsed.command === undefined && parsed.path === undefined) {
699
+ process.stderr.write(`${NAME}: 至少给一个 --command 或 --path(要判定的内容)\n\n${explainUsage()}\n`);
700
+ return 2;
701
+ }
702
+ let policy;
703
+ try {
704
+ policy = loadPolicy(policyPaths);
705
+ }
706
+ catch (err) {
707
+ process.stderr.write(`${NAME}: 策略加载失败\n ${err.message}\n`);
708
+ return 2;
709
+ }
710
+ const args = {};
711
+ if (parsed.command !== undefined)
712
+ args.command = parsed.command;
713
+ if (parsed.path !== undefined)
714
+ args.path = parsed.path;
715
+ const result = decide(policy, tool, args);
716
+ const verdict = result.decision === 'ask' ? 'ask*' : result.decision;
717
+ const lines = [];
718
+ lines.push('');
719
+ lines.push(` 判定 ${verdict}${result.decision === 'ask' ? '(当前无审批通道,按拒绝处理)' : ''}`);
720
+ lines.push(` 规则 ${result.ruleId ?? '(未命中规则 → fail-closed)'}`);
721
+ if (result.reason !== null)
722
+ lines.push(` 原因 ${result.reason}`);
723
+ lines.push(` 策略 ${policy.sources.join(' + ')}`);
724
+ if (result.dryRun)
725
+ lines.push(' 模式 dry_run(真实运行时会放行,只记录)');
726
+ lines.push('');
727
+ process.stdout.write(lines.join('\n'));
728
+ return 0;
729
+ }
612
730
  /* ================================================================== */
613
731
  export async function runCli(argv) {
614
732
  const [sub, ...rest] = argv;
@@ -620,5 +738,7 @@ export async function runCli(argv) {
620
738
  return checkCommand(rest);
621
739
  if (sub === 'demo')
622
740
  return demoCommand(rest);
741
+ if (sub === 'explain')
742
+ return explainCommand(rest);
623
743
  return 2;
624
744
  }
package/dist/main.js CHANGED
@@ -13,7 +13,7 @@
13
13
  * 退出码:0 正常 / 1 upstream 启动失败 / 2 用法或策略配置错误。
14
14
  */
15
15
  import { existsSync, readFileSync } from 'node:fs';
16
- import { randomBytes } from 'node:crypto';
16
+ import { createHash, randomBytes } from 'node:crypto';
17
17
  import { homedir } from 'node:os';
18
18
  import { join } from 'node:path';
19
19
  import { AuditWriter, pruneAudit } from './audit/writer.js';
@@ -166,6 +166,21 @@ function resolvePolicy(explicit) {
166
166
  });
167
167
  return parsePolicy('version: 1\nrules: []\n', '<built-in deny-all>');
168
168
  }
169
+ /** 策略内容哈希(sha256 前 12 位),进审计记录用于回答「当时用的是哪版策略」 */
170
+ function computePolicyHash(policy) {
171
+ if (policy.sources.length === 0)
172
+ return undefined;
173
+ const hash = createHash('sha256');
174
+ for (const src of policy.sources) {
175
+ try {
176
+ hash.update(readFileSync(src, 'utf8'));
177
+ }
178
+ catch {
179
+ hash.update(src);
180
+ }
181
+ }
182
+ return hash.digest('hex').slice(0, 12);
183
+ }
169
184
  async function main() {
170
185
  const argv = process.argv.slice(2);
171
186
  // 客户端断开后写 stdout 会 EPIPE;不挂监听器会让进程带着堆栈崩掉
@@ -177,7 +192,8 @@ async function main() {
177
192
  if (argv[0] === 'audit' ||
178
193
  argv[0] === 'init' ||
179
194
  argv[0] === 'check' ||
180
- argv[0] === 'demo') {
195
+ argv[0] === 'demo' ||
196
+ argv[0] === 'explain') {
181
197
  const code = await runCli(argv);
182
198
  await flushStdout();
183
199
  process.exit(code);
@@ -214,6 +230,7 @@ async function main() {
214
230
  const policy = resolvePolicy(options.policies);
215
231
  const audit = openAudit();
216
232
  const session = randomBytes(2).toString('hex');
233
+ const policyHash = computePolicyHash(policy);
217
234
  let handle;
218
235
  try {
219
236
  handle = startProxy({
@@ -221,6 +238,7 @@ async function main() {
221
238
  policy,
222
239
  ...(audit === null ? {} : { audit }),
223
240
  session,
241
+ ...(policyHash === undefined ? {} : { policyHash }),
224
242
  });
225
243
  }
226
244
  catch (err) {
@@ -0,0 +1,44 @@
1
+ /**
2
+ * 跨客户端工具名别名表。
3
+ *
4
+ * 同一个操作在不同 Agent 客户端里叫法不同(Claude Code 叫 Bash,Cline 叫
5
+ * execute_command,Cursor 叫 run_terminal_cmd)。规则里写任何一个名字,
6
+ * 编译期自动展开为整组等价名 —— 消除「换一个客户端就漏配」这类问题。
7
+ *
8
+ * 只收录确认存在的真实工具名;拿不准的不写宁可漏。
9
+ * 匹配时 tool 字段同时做大小写不敏感比较,所以这里不用堆大小写变体。
10
+ */
11
+ export const TOOL_ALIASES = {
12
+ bash: [
13
+ 'Bash', 'bash', 'Shell', 'shell',
14
+ 'run_command', 'execute_command', 'run_terminal_cmd',
15
+ 'terminal', 'powershell',
16
+ ],
17
+ read_file: [
18
+ 'Read', 'read_file', 'read_text_file', 'read_multiple_files',
19
+ 'view_file', 'open_file',
20
+ ],
21
+ search: [
22
+ 'Glob', 'Grep', 'LS', 'list_files', 'list_directory', 'directory_tree',
23
+ 'search_files', 'get_file_info', 'codebase_search',
24
+ ],
25
+ write: [
26
+ 'Write', 'write_file', 'write_text_file',
27
+ 'edit_file', 'Edit', 'MultiEdit', 'replace_in_file', 'write_to_file',
28
+ 'create_directory', 'move_file', 'apply_patch',
29
+ ],
30
+ };
31
+ /** 把一组工具名展开为「自身 + 所在等价组的全部名字」 */
32
+ export function expandToolNames(names) {
33
+ const out = new Set();
34
+ for (const name of names) {
35
+ out.add(name);
36
+ for (const group of Object.values(TOOL_ALIASES)) {
37
+ if (group.some((g) => g.toLowerCase() === name.toLowerCase())) {
38
+ for (const g of group)
39
+ out.add(g);
40
+ }
41
+ }
42
+ }
43
+ return [...out];
44
+ }
@@ -30,14 +30,7 @@ export function baselineRules() {
30
30
  {
31
31
  id: 'base-allow-argless',
32
32
  match: {
33
- tool: [
34
- 'list_allowed_directories',
35
- 'grep',
36
- 'glob',
37
- 'search',
38
- 'codebase_search',
39
- 'list_tools',
40
- ],
33
+ tool: ['list_allowed_directories', 'codebase_search', 'list_tools'],
41
34
  },
42
35
  decision: 'allow',
43
36
  reason: '基线:放行无路径参数的只读工具',
@@ -14,11 +14,12 @@
14
14
  * - 所有 regex / glob 在加载期预编译,写错就是启动失败,而不是第一次调用才炸。
15
15
  */
16
16
  import { logger } from '../logger.js';
17
+ import { expandToolNames } from './aliases.js';
17
18
  import { compileGlob, matchGlob } from './glob.js';
18
19
  import { PolicyError, } from './types.js';
19
20
  const DECISIONS = ['allow', 'deny', 'ask'];
20
21
  const OPERATORS = ['glob', 'regex', 'equals', 'in', 'prefix'];
21
- const RULE_KEYS = new Set(['id', 'match', 'decision', 'reason']);
22
+ const RULE_KEYS = new Set(['id', 'match', 'decision', 'reason', 'except']);
22
23
  const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
23
24
  function isRecord(value) {
24
25
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -298,6 +299,20 @@ function compileMatcher(field, raw, origin, ruleId) {
298
299
  op = Array.isArray(raw) ? 'in' : 'equals';
299
300
  rawValue = raw;
300
301
  }
302
+ // 工具名别名归一:规则里写 bash,自动覆盖各客户端的等价工具名。
303
+ // 只对 equals / in 做(glob / regex 的 pattern 语义不由别名控制)。
304
+ if (path[0] === 'tool' && (op === 'equals' || op === 'in')) {
305
+ const names = Array.isArray(rawValue) ? rawValue : [rawValue];
306
+ const stringNames = [];
307
+ for (const n of names) {
308
+ if (typeof n !== 'string' || n === '') {
309
+ throw new PolicyError(`字段 "${field}" 的工具名必须是非空字符串`, origin, ruleId);
310
+ }
311
+ stringNames.push(n);
312
+ }
313
+ rawValue = expandToolNames(stringNames);
314
+ op = 'in';
315
+ }
301
316
  if (op === 'in' && !Array.isArray(rawValue)) {
302
317
  throw new PolicyError(`字段 "${field}" 的 in 取值得是数组`, origin, ruleId);
303
318
  }
@@ -363,13 +378,19 @@ function compileMatcher(field, raw, origin, ruleId) {
363
378
  /* ------------------------------------------------------------------ */
364
379
  function patternHits(matcher, value) {
365
380
  const text = toText(value);
381
+ // tool 字段做大小写不敏感比较:各客户端工具名大小写不统一(Bash / bash)
382
+ const ci = matcher.path[0] === 'tool';
383
+ const same = (a, b) => ci ? a.toLowerCase() === b.toLowerCase() : a === b;
366
384
  switch (matcher.op) {
367
385
  case 'equals':
368
- return matcher.patterns.some((pattern) => toText(pattern) === text);
386
+ return matcher.patterns.some((pattern) => same(toText(pattern), text));
369
387
  case 'prefix':
370
- return matcher.patterns.some((pattern) => text.startsWith(toText(pattern)));
388
+ return matcher.patterns.some((pattern) => {
389
+ const p = ci ? toText(pattern).toLowerCase() : toText(pattern);
390
+ return ci ? text.toLowerCase().startsWith(p) : text.startsWith(p);
391
+ });
371
392
  case 'in':
372
- return matcher.patterns.some((pattern) => toText(pattern) === text);
393
+ return matcher.patterns.some((pattern) => same(toText(pattern), text));
373
394
  case 'regex':
374
395
  return matcher.regexes.some((re) => re.test(text));
375
396
  case 'glob':
@@ -417,13 +438,34 @@ export function compileRule(raw, origin, index) {
417
438
  throw new PolicyError(`规则 "${id}" 的 match 为空 —— 空 match 会命中一切调用,若确实要全放行请用 defaults.on_no_match: allow`, origin, id);
418
439
  }
419
440
  const matchers = fields.map((field) => compileMatcher(field, match[field], origin, id));
441
+ // except:规则级白名单。主条件命中但 except 也命中 → 本规则不触发。
442
+ // 语义:整个 except 块按 match 同样的 AND/OR 规则判定,全部字段命中才算"被豁免"。
443
+ let exceptTest;
444
+ if (raw.except !== undefined) {
445
+ const exceptBlock = raw.except;
446
+ if (!isRecord(exceptBlock)) {
447
+ throw new PolicyError(`规则 "${id}" 的 except 必须是对象`, origin, id);
448
+ }
449
+ const exceptFields = Object.keys(exceptBlock);
450
+ if (exceptFields.length === 0) {
451
+ throw new PolicyError(`规则 "${id}" 的 except 为空(写了等于没写)`, origin, id);
452
+ }
453
+ const exceptMatchers = exceptFields.map((field) => compileMatcher(field, exceptBlock[field], origin, id));
454
+ exceptTest = (tool, args) => exceptMatchers.every((matcher) => fieldHits(matcher, tool, args));
455
+ }
420
456
  return {
421
457
  id,
422
458
  decision: decision,
423
459
  reason,
424
460
  matchers,
425
461
  origin,
426
- test: (tool, args) => matchers.every((matcher) => fieldHits(matcher, tool, args)),
462
+ test: (tool, args) => {
463
+ if (!matchers.every((matcher) => fieldHits(matcher, tool, args)))
464
+ return false;
465
+ if (exceptTest !== undefined && exceptTest(tool, args))
466
+ return false;
467
+ return true;
468
+ },
427
469
  };
428
470
  }
429
471
  export function compileRules(rawRules, origin) {
package/dist/proxy.js CHANGED
@@ -249,6 +249,7 @@ function createGate(policy, out, options) {
249
249
  ms: Number(detail.ms.toFixed(3)),
250
250
  session: options.session,
251
251
  agent,
252
+ ...(options.policyHash === undefined ? {} : { policyHash: options.policyHash }),
252
253
  ...(detail.dryRun === true ? { dryRun: true } : {}),
253
254
  });
254
255
  }
@@ -396,6 +397,7 @@ export function startProxy(spec) {
396
397
  audit: spec.audit,
397
398
  limits: spec.policy.limits.length === 0 ? undefined : new LimitTracker(spec.policy.limits),
398
399
  session: spec.session ?? 'unknown',
400
+ policyHash: spec.policyHash,
399
401
  });
400
402
  // 必须在 done 的 close 监听之前注册:先把「未完成请求的错误」写出去,再让进程收尾
401
403
  if (gate !== null)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leeruu/agentguard",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Local permission gateway for MCP agents: YAML policy, deterministic decisions, full audit trail.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "leeruu",
@@ -42,10 +42,11 @@
42
42
  "check:coldstart": "node tests/coldstart-check.mjs",
43
43
  "check:real": "node tests/real-fs-check.mjs",
44
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",
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/012-check.mjs && node tests/install-check.mjs",
46
46
  "check:demo": "node tests/demo-check.mjs",
47
47
  "check:epipe": "node tests/epipe-check.mjs",
48
- "check:export": "node tests/export-check.mjs"
48
+ "check:export": "node tests/export-check.mjs",
49
+ "check:012": "node tests/012-check.mjs"
49
50
  },
50
51
  "keywords": [
51
52
  "mcp",
@@ -11,6 +11,42 @@ version: 1
11
11
  # 代理只判定请求,不看响应 —— 要做需要在响应方向加规则引擎,留到后续。
12
12
 
13
13
  rules:
14
+ # ── 0. bash 读凭据(P0 补丁)────────────────────────────────────
15
+ # 上面的专用工具规则拦不住 bash:基线放行了整个 bash 工具,
16
+ # 而 `cat .env` / `printenv` 这类调用之前是放行的(实测)。
17
+ # 动词白名单 + 文件名负向断言(排除 .env.example / .sample / .template),
18
+ # 17 条用例实测 16 正确;唯一误伤(引号内字面提及)由 except 机制在 0.2.0 兜底。
19
+ # 明确拦不住的变形:$() 命令替换、变量拼接、python -c、任意编码变换 —— 概率性防线。
20
+ - id: secrets-shell-read
21
+ match:
22
+ tool: [bash, shell, run_command, execute_command, run_terminal_cmd, terminal, powershell]
23
+ args.command:
24
+ regex: '(?:^|[\s;&|(])(?:cat|less|more|head|tail|bat|strings|xxd|base64|cp|rsync|scp|tar|openssl|grep|awk|sed)\b[^\n]{0,200}?\.env(?!\.example|\.sample|\.template)\b'
25
+ except:
26
+ args.command:
27
+ regex: 'grep\s+-r\s+["''][^"'']*\.env'
28
+ decision: deny
29
+ reason: 通过 shell 读取凭据文件
30
+
31
+ - id: secrets-shell-key-file
32
+ match:
33
+ tool: [bash, shell, run_command, execute_command, run_terminal_cmd, terminal, powershell]
34
+ args.command:
35
+ regex: '(?:^|[\s;&|(])(?:cat|less|head|tail|base64|cp|rsync|scp|tar|openssl|ssh-add)\b[^\n]{0,200}?(?:id_rsa|id_ed25519|\.aws/credentials|\.npmrc|\.netrc|\.git-credentials)'
36
+ except:
37
+ args.command:
38
+ regex: 'grep\s+-r\s+["''][^"'']*(?:id_rsa|\.npmrc)'
39
+ decision: deny
40
+ reason: 通过 shell 读取私钥或云凭据
41
+
42
+ - id: secrets-shell-env-dump
43
+ match:
44
+ tool: [bash, shell, run_command, execute_command, run_terminal_cmd, terminal, powershell]
45
+ args.command:
46
+ regex: '(?:^|[\s;&|])(?:printenv|env)(?:\s*\||\s*$)'
47
+ decision: deny
48
+ reason: 导出全部环境变量(可能含密钥)
49
+
14
50
  # ── 1. 读凭据文件 ─────────────────────────────────────────────────
15
51
  # .env 家族用 regex 而不是 glob:要排除 .env.example / .env.sample / .env.template
16
52
  # 这些模板文件本来就要读。deny 压过 allow,写成 glob 就再也没有办法放行它们了。