@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/LICENSE +202 -0
- package/NOTICE +22 -0
- package/README.md +298 -2
- package/dist/audit/query.js +151 -0
- package/dist/audit/writer.js +174 -0
- package/dist/cli.js +624 -0
- package/dist/demo.js +246 -0
- package/dist/errors.js +28 -0
- package/dist/format.js +29 -0
- package/dist/limits.js +42 -0
- package/dist/logger.js +46 -0
- package/dist/main.js +239 -0
- package/dist/packs.js +51 -0
- package/dist/policy/bootstrap.js +127 -0
- package/dist/policy/decide.js +41 -0
- package/dist/policy/glob.js +80 -0
- package/dist/policy/load.js +203 -0
- package/dist/policy/match.js +431 -0
- package/dist/policy/types.js +15 -0
- package/dist/proxy.js +440 -0
- package/package.json +69 -4
- package/packs/core.yaml +104 -0
- package/packs/git.yaml +43 -0
- package/packs/net.yaml +48 -0
- package/packs/secrets.yaml +120 -0
package/dist/demo.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `agentguard demo` —— 不接任何 agent 也能看完整效果。
|
|
3
|
+
*
|
|
4
|
+
* 起一个内置的假 MCP server,经真实的代理链路发起 7 次工具调用,
|
|
5
|
+
* 把「放行 / 拦截 / 命中哪条规则 / 上游有没有真的执行」打成一张表。
|
|
6
|
+
*
|
|
7
|
+
* 为什么需要它:
|
|
8
|
+
* - 用户可能没有(或不能用)某个客户端,装客户端不该是理解产品的前提
|
|
9
|
+
* - 文章与演示里可以贴真实输出,而不是截图
|
|
10
|
+
* - 有人质疑「真能拦吗」时,一条命令自证
|
|
11
|
+
*
|
|
12
|
+
* 审计默认关闭:演示产生的假调用不该污染用户真实的审计记录。
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from 'node:child_process';
|
|
15
|
+
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { homedir, tmpdir } from 'node:os';
|
|
17
|
+
import { join } from 'node:path';
|
|
18
|
+
import { displayWidth, pad } from './format.js';
|
|
19
|
+
import { buildDefaultPolicyText } from './policy/bootstrap.js';
|
|
20
|
+
import { decide } from './policy/decide.js';
|
|
21
|
+
import { loadPolicy } from './policy/load.js';
|
|
22
|
+
/** 内联的假 MCP server:只回固定内容,用来证明「被拦的调用根本没到它这里」 */
|
|
23
|
+
const DEMO_SERVER = `
|
|
24
|
+
let buf = '';
|
|
25
|
+
const send = (o) => process.stdout.write(JSON.stringify(o) + '\\n');
|
|
26
|
+
|
|
27
|
+
process.stdin.on('data', (chunk) => {
|
|
28
|
+
buf += chunk.toString('utf8');
|
|
29
|
+
for (;;) {
|
|
30
|
+
const nl = buf.indexOf('\\n');
|
|
31
|
+
if (nl === -1) break;
|
|
32
|
+
const line = buf.slice(0, nl).trim();
|
|
33
|
+
buf = buf.slice(nl + 1);
|
|
34
|
+
if (line !== '') handle(line);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
function handle(line) {
|
|
39
|
+
let msg;
|
|
40
|
+
try {
|
|
41
|
+
msg = JSON.parse(line);
|
|
42
|
+
} catch {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if (msg.method === undefined) return;
|
|
46
|
+
|
|
47
|
+
if (msg.method === 'initialize') {
|
|
48
|
+
send({
|
|
49
|
+
jsonrpc: '2.0',
|
|
50
|
+
id: msg.id,
|
|
51
|
+
result: {
|
|
52
|
+
protocolVersion: (msg.params && msg.params.protocolVersion) || '2025-06-18',
|
|
53
|
+
capabilities: { tools: {} },
|
|
54
|
+
serverInfo: { name: 'agentguard-demo-server', version: '1' },
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (msg.method === 'tools/list') {
|
|
61
|
+
send({
|
|
62
|
+
jsonrpc: '2.0',
|
|
63
|
+
id: msg.id,
|
|
64
|
+
result: {
|
|
65
|
+
tools: [
|
|
66
|
+
{ name: 'read_file', inputSchema: { type: 'object' } },
|
|
67
|
+
{ name: 'write_file', inputSchema: { type: 'object' } },
|
|
68
|
+
{ name: 'bash', inputSchema: { type: 'object' } },
|
|
69
|
+
],
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (msg.method === 'tools/call') {
|
|
76
|
+
send({
|
|
77
|
+
jsonrpc: '2.0',
|
|
78
|
+
id: msg.id,
|
|
79
|
+
result: { content: [{ type: 'text', text: 'executed: ' + (msg.params && msg.params.name) }] },
|
|
80
|
+
});
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (msg.id !== undefined) {
|
|
85
|
+
send({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'method not found' } });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
`;
|
|
89
|
+
const SCENARIOS = [
|
|
90
|
+
{ label: '读 ./src/index.ts', tool: 'read_file', args: { path: './src/index.ts' } },
|
|
91
|
+
{ label: '读 ./.env', tool: 'read_file', args: { path: './.env' } },
|
|
92
|
+
{ label: '写 /etc/hosts', tool: 'write_file', args: { path: '/etc/hosts', content: 'x' } },
|
|
93
|
+
{ label: 'rm -rf /', tool: 'bash', args: { command: 'rm -rf /' } },
|
|
94
|
+
{ label: 'rm -rf ./build', tool: 'bash', args: { command: 'rm -rf ./build' } },
|
|
95
|
+
{ label: 'git push --force', tool: 'bash', args: { command: 'git push --force origin main' } },
|
|
96
|
+
{ label: '未定义的工具', tool: 'mystery_tool', args: { foo: 1 } },
|
|
97
|
+
];
|
|
98
|
+
function resolvePolicy(explicit, workDir) {
|
|
99
|
+
if (explicit !== undefined)
|
|
100
|
+
return { file: explicit, label: explicit };
|
|
101
|
+
const fallback = join(homedir(), '.agentguard', 'policy.yaml');
|
|
102
|
+
if (existsSync(fallback))
|
|
103
|
+
return { file: fallback, label: fallback };
|
|
104
|
+
const file = join(workDir, 'policy.yaml');
|
|
105
|
+
writeFileSync(file, buildDefaultPolicyText(['core', 'secrets']), 'utf8');
|
|
106
|
+
return { file, label: '内置默认策略(等同于 init 的 core + secrets + dev 基线)' };
|
|
107
|
+
}
|
|
108
|
+
export async function runDemo(options = {}) {
|
|
109
|
+
const workDir = mkdtempSync(join(tmpdir(), 'agentguard-demo-'));
|
|
110
|
+
let child = null;
|
|
111
|
+
try {
|
|
112
|
+
const serverFile = join(workDir, 'demo-server.mjs');
|
|
113
|
+
writeFileSync(serverFile, DEMO_SERVER, 'utf8');
|
|
114
|
+
const policy = resolvePolicy(options.policyPath, workDir);
|
|
115
|
+
let compiled;
|
|
116
|
+
try {
|
|
117
|
+
compiled = loadPolicy(policy.file);
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
process.stderr.write(`agentguard: 策略加载失败\n ${err.message}\n`);
|
|
121
|
+
return 2;
|
|
122
|
+
}
|
|
123
|
+
const entry = process.argv[1] ?? 'dist/main.js';
|
|
124
|
+
child = spawn(process.execPath, [entry, '--policy', policy.file, '--', process.execPath, serverFile], {
|
|
125
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
126
|
+
env: { ...process.env, AGENTGUARD_AUDIT: 'off', AGENTGUARD_LOG: 'silent' },
|
|
127
|
+
});
|
|
128
|
+
const run = child;
|
|
129
|
+
// 代理退出后 demo 继续写 stdin 会 EPIPE;忽略即可,退出流程自己会收尾
|
|
130
|
+
run.stdin?.on('error', () => { });
|
|
131
|
+
const pending = new Map();
|
|
132
|
+
let nextId = 0;
|
|
133
|
+
let buffer = '';
|
|
134
|
+
let stderr = '';
|
|
135
|
+
run.stderr?.on('data', (chunk) => {
|
|
136
|
+
stderr += chunk.toString('utf8');
|
|
137
|
+
});
|
|
138
|
+
run.stdout?.on('data', (chunk) => {
|
|
139
|
+
buffer += chunk.toString('utf8');
|
|
140
|
+
for (;;) {
|
|
141
|
+
const nl = buffer.indexOf('\n');
|
|
142
|
+
if (nl === -1)
|
|
143
|
+
break;
|
|
144
|
+
const line = buffer.slice(0, nl);
|
|
145
|
+
buffer = buffer.slice(nl + 1);
|
|
146
|
+
if (line.trim() === '')
|
|
147
|
+
continue;
|
|
148
|
+
try {
|
|
149
|
+
const msg = JSON.parse(line);
|
|
150
|
+
const resolve = msg.id === undefined ? undefined : pending.get(msg.id);
|
|
151
|
+
if (resolve !== undefined) {
|
|
152
|
+
pending.delete(msg.id);
|
|
153
|
+
resolve(msg);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
// 忽略非 JSON 行(demo 自己不会产生,防御一下)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
const request = (method, params) => new Promise((resolve, reject) => {
|
|
162
|
+
const id = ++nextId;
|
|
163
|
+
const timer = setTimeout(() => {
|
|
164
|
+
pending.delete(id);
|
|
165
|
+
reject(new Error(`${method} 超时(20s)`));
|
|
166
|
+
}, 20_000);
|
|
167
|
+
pending.set(id, (msg) => {
|
|
168
|
+
clearTimeout(timer);
|
|
169
|
+
resolve(msg);
|
|
170
|
+
});
|
|
171
|
+
run.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
|
|
172
|
+
});
|
|
173
|
+
await request('initialize', {
|
|
174
|
+
protocolVersion: '2025-06-18',
|
|
175
|
+
capabilities: {},
|
|
176
|
+
clientInfo: { name: 'agentguard-demo', version: '1' },
|
|
177
|
+
});
|
|
178
|
+
run.stdin?.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized', params: {} }) + '\n');
|
|
179
|
+
const rows = [];
|
|
180
|
+
let mismatch = 0;
|
|
181
|
+
for (const scenario of SCENARIOS) {
|
|
182
|
+
const reply = await request('tools/call', {
|
|
183
|
+
name: scenario.tool,
|
|
184
|
+
arguments: scenario.args,
|
|
185
|
+
});
|
|
186
|
+
const error = reply.error;
|
|
187
|
+
const decision = error === undefined
|
|
188
|
+
? 'allow'
|
|
189
|
+
: error.data?.decision === 'ask'
|
|
190
|
+
? 'ask'
|
|
191
|
+
: error.code === -32001
|
|
192
|
+
? 'deny'
|
|
193
|
+
: `error ${error.code}`;
|
|
194
|
+
// 代理不回报「放行时命中了哪条规则」(那要去读审计),这里用同一份策略在本地算一次;
|
|
195
|
+
// 同时校验它与代理实际行为一致 —— 不一致说明有 bug,值得当场暴露。
|
|
196
|
+
const local = decide(compiled, scenario.tool, scenario.args);
|
|
197
|
+
if (local.decision !== decision)
|
|
198
|
+
mismatch += 1;
|
|
199
|
+
rows.push({
|
|
200
|
+
label: scenario.label,
|
|
201
|
+
decision,
|
|
202
|
+
ruleId: local.ruleId,
|
|
203
|
+
executed: error === undefined,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
run.stdin?.end();
|
|
207
|
+
const label = (row) => row.ruleId ?? (row.decision === 'deny' ? '(fail-closed)' : '-');
|
|
208
|
+
const wLabel = Math.max(...rows.map((row) => displayWidth(row.label)), 4);
|
|
209
|
+
const wRule = Math.max(...rows.map((row) => displayWidth(label(row))), 6);
|
|
210
|
+
const lines = [];
|
|
211
|
+
lines.push('');
|
|
212
|
+
lines.push('agentguard demo —— 内置假 MCP server,走真实代理链路跑一遍');
|
|
213
|
+
lines.push(`策略 ${policy.label}`);
|
|
214
|
+
lines.push('');
|
|
215
|
+
lines.push(` ${pad('判定', 5)} ${pad('调用', wLabel)} ${pad('命中规则', wRule)} 上游`);
|
|
216
|
+
lines.push(` ${'─'.repeat(5 + 2 + wLabel + 2 + wRule + 6)}`);
|
|
217
|
+
for (const row of rows) {
|
|
218
|
+
const verdict = row.decision === 'ask' ? 'ask*' : row.decision;
|
|
219
|
+
lines.push(` ${pad(verdict, 5)} ${pad(row.label, wLabel)} ${pad(label(row), wRule)} ${row.executed ? '已执行' : '未执行'}`);
|
|
220
|
+
}
|
|
221
|
+
const allow = rows.filter((row) => row.decision === 'allow').length;
|
|
222
|
+
const deny = rows.filter((row) => row.decision === 'deny').length;
|
|
223
|
+
const ask = rows.filter((row) => row.decision === 'ask').length;
|
|
224
|
+
lines.push('');
|
|
225
|
+
lines.push(` 合计:allow ${allow} / deny ${deny} / ask* ${ask}`);
|
|
226
|
+
if (mismatch > 0) {
|
|
227
|
+
lines.push(` ⚠ 有 ${mismatch} 条代理结果与本地判定不一致(这是 bug,请反馈)`);
|
|
228
|
+
}
|
|
229
|
+
lines.push(' ask* 没有审批通道时按拒绝处理(fail-closed),不是放行');
|
|
230
|
+
lines.push(' 审计已关闭(演示不写 ~/.agentguard/audit)');
|
|
231
|
+
lines.push('');
|
|
232
|
+
process.stdout.write(lines.join('\n'));
|
|
233
|
+
if (stderr.trim() !== '') {
|
|
234
|
+
process.stderr.write(stderr);
|
|
235
|
+
}
|
|
236
|
+
return 0;
|
|
237
|
+
}
|
|
238
|
+
catch (err) {
|
|
239
|
+
process.stderr.write(`agentguard: demo 失败:${err.message}\n`);
|
|
240
|
+
return 1;
|
|
241
|
+
}
|
|
242
|
+
finally {
|
|
243
|
+
child?.kill();
|
|
244
|
+
rmSync(workDir, { recursive: true, force: true });
|
|
245
|
+
}
|
|
246
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON-RPC 错误码与错误响应构造。
|
|
3
|
+
*
|
|
4
|
+
* 自定义码落在 -32000 ~ -32099(JSON-RPC 2.0 留给实现自定义的区间):
|
|
5
|
+
* -32001 POLICY_DENIED 策略拒绝(含 ask 因无审批通道而按拒绝处理)
|
|
6
|
+
* -32002 POLICY_UNAVAILABLE 策略不可用 / 判定过程本身失败 → fail-closed
|
|
7
|
+
* -32003 UPSTREAM_EXITED upstream 已退出,未完成的请求不能让它一直等
|
|
8
|
+
* -32004 RATE_LIMITED 触发限流
|
|
9
|
+
*
|
|
10
|
+
* -32603(内部错误)是协议标准码,upstream 意外崩溃时用它回给 client。
|
|
11
|
+
*/
|
|
12
|
+
export const ErrorCode = {
|
|
13
|
+
POLICY_DENIED: -32001,
|
|
14
|
+
POLICY_UNAVAILABLE: -32002,
|
|
15
|
+
UPSTREAM_EXITED: -32003,
|
|
16
|
+
RATE_LIMITED: -32004,
|
|
17
|
+
INTERNAL_ERROR: -32603,
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* 构造一行错误响应(已带换行符)。
|
|
21
|
+
*
|
|
22
|
+
* id 必须原样回显:client 靠 id 匹配它发出去的那次调用。
|
|
23
|
+
* 通知(id === undefined)不构造响应 —— 通知没有 id,回 error 反而违反协议。
|
|
24
|
+
*/
|
|
25
|
+
export function buildErrorLine(id, code, message, data) {
|
|
26
|
+
const error = data === undefined ? { code, message } : { code, message, data };
|
|
27
|
+
return Buffer.from(JSON.stringify({ jsonrpc: '2.0', id, error }) + '\n', 'utf8');
|
|
28
|
+
}
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 终端文本对齐。中文/全角字符在等宽字体里占两列,按 `String.length` 补空格会错位。
|
|
3
|
+
* cli 与 demo 共用同一套,保证两处输出宽度一致。
|
|
4
|
+
*/
|
|
5
|
+
function charWidth(code) {
|
|
6
|
+
if (code >= 0x1100 &&
|
|
7
|
+
(code <= 0x115f ||
|
|
8
|
+
code === 0x2329 ||
|
|
9
|
+
code === 0x232a ||
|
|
10
|
+
(code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) ||
|
|
11
|
+
(code >= 0xac00 && code <= 0xd7a3) ||
|
|
12
|
+
(code >= 0xf900 && code <= 0xfaff) ||
|
|
13
|
+
(code >= 0xfe30 && code <= 0xfe6f) ||
|
|
14
|
+
(code >= 0xff00 && code <= 0xff60) ||
|
|
15
|
+
(code >= 0xffe0 && code <= 0xffe6))) {
|
|
16
|
+
return 2;
|
|
17
|
+
}
|
|
18
|
+
return 1;
|
|
19
|
+
}
|
|
20
|
+
export function displayWidth(text) {
|
|
21
|
+
let width = 0;
|
|
22
|
+
for (const char of text)
|
|
23
|
+
width += charWidth(char.codePointAt(0) ?? 0);
|
|
24
|
+
return width;
|
|
25
|
+
}
|
|
26
|
+
export function pad(text, width) {
|
|
27
|
+
const current = displayWidth(text);
|
|
28
|
+
return current >= width ? text : text + ' '.repeat(width - current);
|
|
29
|
+
}
|
package/dist/limits.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 限流执行。
|
|
3
|
+
*
|
|
4
|
+
* 语义与方案一致:`limits: [{ tool: bash, max_calls: 200, window: 1h }]`
|
|
5
|
+
* —— 每个窗口内该工具的调用次数上限,超出回 -32004。
|
|
6
|
+
*
|
|
7
|
+
* 两个刻意的实现选择:
|
|
8
|
+
* 1. **按规则 + 工具各自计数**:一条 limit 写了多个工具时,是「每个工具各自限额」,
|
|
9
|
+
* 而不是共享一个桶。前者更符合「防止某个工具跑飞」的直觉。
|
|
10
|
+
* 2. **固定窗口**而非滑动窗口:实现简单、行为可预测、内存 O(规则数)。
|
|
11
|
+
* 代价是窗口边界可能放过最多 2 倍瞬时流量 —— 对「防止整夜烧钱」这个诉求足够。
|
|
12
|
+
*/
|
|
13
|
+
export class LimitTracker {
|
|
14
|
+
#rules;
|
|
15
|
+
#now;
|
|
16
|
+
#buckets = new Map();
|
|
17
|
+
constructor(rules, now = Date.now) {
|
|
18
|
+
this.#rules = rules;
|
|
19
|
+
this.#now = now;
|
|
20
|
+
}
|
|
21
|
+
/** 记一次调用并判定;无论放行与否都要调用,这样「被拒后继续重试」也会被计数 */
|
|
22
|
+
check(tool) {
|
|
23
|
+
const now = this.#now();
|
|
24
|
+
let blocked = null;
|
|
25
|
+
for (let index = 0; index < this.#rules.length; index++) {
|
|
26
|
+
const rule = this.#rules[index];
|
|
27
|
+
if (!rule.tools.includes(tool))
|
|
28
|
+
continue;
|
|
29
|
+
const key = `${index}:${tool}`;
|
|
30
|
+
let bucket = this.#buckets.get(key);
|
|
31
|
+
if (bucket === undefined || now - bucket.start >= rule.windowMs) {
|
|
32
|
+
bucket = { count: 0, start: now };
|
|
33
|
+
this.#buckets.set(key, bucket);
|
|
34
|
+
}
|
|
35
|
+
bucket.count += 1;
|
|
36
|
+
if (bucket.count > rule.maxCalls && blocked === null) {
|
|
37
|
+
blocked = { ok: false, rule, count: bucket.count, maxCalls: rule.maxCalls };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return blocked ?? { ok: true, rule: null, count: 0, maxCalls: 0 };
|
|
41
|
+
}
|
|
42
|
+
}
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 日志:**只能写 stderr**。
|
|
3
|
+
*
|
|
4
|
+
* 这是方案第 3 章第 1 号坑 —— 往 stdout 写一个字节的日志,client 的 JSON 解析就崩,
|
|
5
|
+
* 表现为「配置完之后 server 直接连不上」,而且极难定位。所以这里不提供任何
|
|
6
|
+
* 写 stdout 的入口,也不依赖 console(console.log 就是 stdout)。
|
|
7
|
+
*
|
|
8
|
+
* 级别用环境变量控制,默认 warn:agent 的 stderr 会被客户端当「服务器日志」展示,
|
|
9
|
+
* 默认别刷屏。排查问题时 `AGENTGUARD_LOG=debug`。
|
|
10
|
+
*/
|
|
11
|
+
const LEVELS = {
|
|
12
|
+
debug: 10,
|
|
13
|
+
info: 20,
|
|
14
|
+
warn: 30,
|
|
15
|
+
error: 40,
|
|
16
|
+
silent: 100,
|
|
17
|
+
};
|
|
18
|
+
function currentThreshold() {
|
|
19
|
+
const raw = (process.env.AGENTGUARD_LOG ?? 'warn').trim().toLowerCase();
|
|
20
|
+
return LEVELS[raw] ?? LEVELS.warn;
|
|
21
|
+
}
|
|
22
|
+
function formatValue(value) {
|
|
23
|
+
if (typeof value === 'string') {
|
|
24
|
+
return /^[\w./:-]+$/.test(value) ? value : JSON.stringify(value);
|
|
25
|
+
}
|
|
26
|
+
if (value === undefined)
|
|
27
|
+
return 'undefined';
|
|
28
|
+
return JSON.stringify(value);
|
|
29
|
+
}
|
|
30
|
+
export function log(level, message, fields) {
|
|
31
|
+
if (LEVELS[level] < currentThreshold())
|
|
32
|
+
return;
|
|
33
|
+
let line = `agentguard[${level}] ${message}`;
|
|
34
|
+
if (fields !== undefined) {
|
|
35
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
36
|
+
line += ` ${key}=${formatValue(value)}`;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
process.stderr.write(line + '\n');
|
|
40
|
+
}
|
|
41
|
+
export const logger = {
|
|
42
|
+
debug: (message, fields) => log('debug', message, fields),
|
|
43
|
+
info: (message, fields) => log('info', message, fields),
|
|
44
|
+
warn: (message, fields) => log('warn', message, fields),
|
|
45
|
+
error: (message, fields) => log('error', message, fields),
|
|
46
|
+
};
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* agentguard · CLI 入口
|
|
4
|
+
*
|
|
5
|
+
* 用法:
|
|
6
|
+
* agentguard [--policy <file>]... -- <真实 mcp server 命令> [参数...]
|
|
7
|
+
*
|
|
8
|
+
* 策略来源(按优先级):
|
|
9
|
+
* 1. `--policy` 指定的文件(可重复,按顺序合并)
|
|
10
|
+
* 2. `~/.agentguard/policy.yaml`
|
|
11
|
+
* 3. 都没有 → 内置 deny-all 空策略 + stderr 告警。**绝不因为「没配置」就裸奔。**
|
|
12
|
+
*
|
|
13
|
+
* 退出码:0 正常 / 1 upstream 启动失败 / 2 用法或策略配置错误。
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
16
|
+
import { randomBytes } from 'node:crypto';
|
|
17
|
+
import { homedir } from 'node:os';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
import { AuditWriter, pruneAudit } from './audit/writer.js';
|
|
20
|
+
import { auditDir, auditKeepDays, PUBLISHED_SPEC, runCli } from './cli.js';
|
|
21
|
+
import { logger } from './logger.js';
|
|
22
|
+
import { loadPolicy, parsePolicy } from './policy/load.js';
|
|
23
|
+
import { PolicyError } from './policy/types.js';
|
|
24
|
+
import { startProxy } from './proxy.js';
|
|
25
|
+
const NAME = 'agentguard';
|
|
26
|
+
const DEFAULT_POLICY = join(homedir(), '.agentguard', 'policy.yaml');
|
|
27
|
+
class UsageError extends Error {
|
|
28
|
+
}
|
|
29
|
+
function readVersion() {
|
|
30
|
+
try {
|
|
31
|
+
const raw = readFileSync(new URL('../package.json', import.meta.url), 'utf8');
|
|
32
|
+
const pkg = JSON.parse(raw);
|
|
33
|
+
return typeof pkg.version === 'string' ? pkg.version : '0.0.0';
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return '0.0.0';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function printUsage(to = process.stdout) {
|
|
40
|
+
to.write([
|
|
41
|
+
`${NAME} ${readVersion()}`,
|
|
42
|
+
'',
|
|
43
|
+
'Usage:',
|
|
44
|
+
` ${NAME} [--policy <file>]... -- <command> [args...]`,
|
|
45
|
+
` ${NAME} init | check | demo`,
|
|
46
|
+
` ${NAME} audit <list|stats|export> [options]`,
|
|
47
|
+
` ${NAME} --version`,
|
|
48
|
+
'',
|
|
49
|
+
'Options:',
|
|
50
|
+
' --policy <file> 策略文件,可重复;按给出顺序合并(先给出的规则先声明)',
|
|
51
|
+
` 不传时读 ${DEFAULT_POLICY}`,
|
|
52
|
+
'',
|
|
53
|
+
'Example:',
|
|
54
|
+
` npx -y ${PUBLISHED_SPEC} -- npx -y @modelcontextprotocol/server-filesystem /projects`,
|
|
55
|
+
` npx -y ${PUBLISHED_SPEC} --policy ~/.agentguard/policy.yaml -- npx -y @modelcontextprotocol/server-filesystem /projects`,
|
|
56
|
+
` ${NAME} demo # 不接 agent,直接看拦截效果`,
|
|
57
|
+
` ${NAME} audit stats --since 7d`,
|
|
58
|
+
'',
|
|
59
|
+
'stdout carries the MCP JSON-RPC stream; all diagnostics go to stderr.',
|
|
60
|
+
'',
|
|
61
|
+
].join('\n'));
|
|
62
|
+
}
|
|
63
|
+
function parseArgs(argv) {
|
|
64
|
+
const policies = [];
|
|
65
|
+
for (let i = 0; i < argv.length; i++) {
|
|
66
|
+
const arg = argv[i];
|
|
67
|
+
if (arg === '--')
|
|
68
|
+
return { action: 'run', policies, command: argv.slice(i + 1) };
|
|
69
|
+
if (arg === '--version' || arg === '-v')
|
|
70
|
+
return { action: 'version', policies, command: [] };
|
|
71
|
+
if (arg === '--help' || arg === '-h')
|
|
72
|
+
return { action: 'help', policies, command: [] };
|
|
73
|
+
if (arg === '--policy') {
|
|
74
|
+
const value = argv[i + 1];
|
|
75
|
+
if (value === undefined || value === '') {
|
|
76
|
+
throw new UsageError('--policy 后面必须跟文件路径');
|
|
77
|
+
}
|
|
78
|
+
policies.push(value);
|
|
79
|
+
i += 1;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (arg.startsWith('--policy=')) {
|
|
83
|
+
const value = arg.slice('--policy='.length);
|
|
84
|
+
if (value === '')
|
|
85
|
+
throw new UsageError('--policy= 后面必须跟文件路径');
|
|
86
|
+
policies.push(value);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (arg.startsWith('-'))
|
|
90
|
+
throw new UsageError(`未知选项 ${arg}`);
|
|
91
|
+
// 没写 `--` 也允许(`agentguard npx -y ...`),但命令本身不能以 `-` 开头
|
|
92
|
+
return { action: 'run', policies, command: argv.slice(i) };
|
|
93
|
+
}
|
|
94
|
+
return { action: 'run', policies, command: [] };
|
|
95
|
+
}
|
|
96
|
+
function fail(message, code) {
|
|
97
|
+
process.stderr.write(`${NAME}: ${message}\n`);
|
|
98
|
+
process.exit(code);
|
|
99
|
+
}
|
|
100
|
+
/** 退出前把 stdout 队列排空;限时兜底,避免管道已断时永远等不到回调 */
|
|
101
|
+
function flushStdout(timeoutMs = 1000) {
|
|
102
|
+
return new Promise((resolve) => {
|
|
103
|
+
let settled = false;
|
|
104
|
+
const finish = () => {
|
|
105
|
+
if (settled)
|
|
106
|
+
return;
|
|
107
|
+
settled = true;
|
|
108
|
+
resolve();
|
|
109
|
+
};
|
|
110
|
+
try {
|
|
111
|
+
process.stdout.write('', finish);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
finish();
|
|
115
|
+
}
|
|
116
|
+
setTimeout(finish, timeoutMs);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
function loadOrExit(paths) {
|
|
120
|
+
try {
|
|
121
|
+
const policy = loadPolicy(paths);
|
|
122
|
+
logger.info('策略已加载', {
|
|
123
|
+
sources: policy.sources.join(','),
|
|
124
|
+
rules: policy.rules.length,
|
|
125
|
+
on_no_match: policy.defaults.onNoMatch,
|
|
126
|
+
dry_run: policy.defaults.dryRun,
|
|
127
|
+
limits: policy.limits.length,
|
|
128
|
+
});
|
|
129
|
+
return policy;
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
const message = err instanceof PolicyError ? err.message : err.message;
|
|
133
|
+
// 策略写错就不启动 —— 带着错误策略运行等于给用户假的安心
|
|
134
|
+
process.stderr.write(`${NAME}: 策略加载失败,拒绝启动\n ${message}\n`);
|
|
135
|
+
process.exit(2);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** 审计开关与目录。`AGENTGUARD_AUDIT=off` 可关闭;目录不可写时告警但不停摆。 */
|
|
139
|
+
function openAudit() {
|
|
140
|
+
if ((process.env.AGENTGUARD_AUDIT ?? '').trim().toLowerCase() === 'off') {
|
|
141
|
+
logger.info('审计已关闭(AGENTGUARD_AUDIT=off)');
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
const dir = auditDir();
|
|
145
|
+
try {
|
|
146
|
+
const removed = pruneAudit(dir, auditKeepDays());
|
|
147
|
+
if (removed.length > 0)
|
|
148
|
+
logger.info('清理过期审计文件', { removed: removed.length });
|
|
149
|
+
const writer = new AuditWriter(dir);
|
|
150
|
+
logger.info('审计已启用', { dir, keep_days: auditKeepDays() });
|
|
151
|
+
return writer;
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
logger.error('审计目录不可用,本次运行不写审计', { dir, error: err.message });
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function resolvePolicy(explicit) {
|
|
159
|
+
if (explicit.length > 0)
|
|
160
|
+
return loadOrExit(explicit);
|
|
161
|
+
if (existsSync(DEFAULT_POLICY))
|
|
162
|
+
return loadOrExit([DEFAULT_POLICY]);
|
|
163
|
+
logger.warn('未找到策略文件,以 deny-all 启动(所有 tools/call 都会被拒绝)', {
|
|
164
|
+
expected: DEFAULT_POLICY,
|
|
165
|
+
hint: '用 --policy <file> 指定,或先跑 agentguard init 生成一份',
|
|
166
|
+
});
|
|
167
|
+
return parsePolicy('version: 1\nrules: []\n', '<built-in deny-all>');
|
|
168
|
+
}
|
|
169
|
+
async function main() {
|
|
170
|
+
const argv = process.argv.slice(2);
|
|
171
|
+
// 客户端断开后写 stdout 会 EPIPE;不挂监听器会让进程带着堆栈崩掉
|
|
172
|
+
process.stdout.on('error', (err) => {
|
|
173
|
+
process.stderr.write(`agentguard: stdout 写入失败(客户端可能已断开):${err.message}\n`);
|
|
174
|
+
});
|
|
175
|
+
// 子命令优先于「把第一个词当 upstream 命令」的兜底行为。
|
|
176
|
+
// 退出前显式 flush:engines 声明的是 Node >=20,不同大版本对 exit 时 stdout 的处理不完全一致。
|
|
177
|
+
if (argv[0] === 'audit' ||
|
|
178
|
+
argv[0] === 'init' ||
|
|
179
|
+
argv[0] === 'check' ||
|
|
180
|
+
argv[0] === 'demo') {
|
|
181
|
+
const code = await runCli(argv);
|
|
182
|
+
await flushStdout();
|
|
183
|
+
process.exit(code);
|
|
184
|
+
}
|
|
185
|
+
let options;
|
|
186
|
+
try {
|
|
187
|
+
options = parseArgs(argv);
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
if (err instanceof UsageError) {
|
|
191
|
+
process.stderr.write(`${NAME}: ${err.message}\n\n`);
|
|
192
|
+
printUsage(process.stderr);
|
|
193
|
+
process.exit(2);
|
|
194
|
+
}
|
|
195
|
+
throw err;
|
|
196
|
+
}
|
|
197
|
+
if (options.action === 'version') {
|
|
198
|
+
process.stdout.write(`${readVersion()}\n`);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (options.action === 'help') {
|
|
202
|
+
printUsage();
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (options.command.length === 0) {
|
|
206
|
+
process.stderr.write(`${NAME}: no upstream command after "--"\n\n`);
|
|
207
|
+
printUsage(process.stderr);
|
|
208
|
+
process.exit(2);
|
|
209
|
+
}
|
|
210
|
+
const head = options.command[0];
|
|
211
|
+
if (head.startsWith('-')) {
|
|
212
|
+
fail(`refusing to treat "${head}" as an upstream command`, 2);
|
|
213
|
+
}
|
|
214
|
+
const policy = resolvePolicy(options.policies);
|
|
215
|
+
const audit = openAudit();
|
|
216
|
+
const session = randomBytes(2).toString('hex');
|
|
217
|
+
let handle;
|
|
218
|
+
try {
|
|
219
|
+
handle = startProxy({
|
|
220
|
+
command: options.command,
|
|
221
|
+
policy,
|
|
222
|
+
...(audit === null ? {} : { audit }),
|
|
223
|
+
session,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
fail(`cannot start upstream: ${err.message}`, 1);
|
|
228
|
+
}
|
|
229
|
+
const shutdown = async (code) => {
|
|
230
|
+
// 先刷审计再退出:被强杀的进程丢最后几条日志,比不写日志更误导人
|
|
231
|
+
await audit?.close();
|
|
232
|
+
await flushStdout();
|
|
233
|
+
process.exit(code);
|
|
234
|
+
};
|
|
235
|
+
process.once('SIGINT', () => void shutdown(130));
|
|
236
|
+
process.once('SIGTERM', () => void shutdown(143));
|
|
237
|
+
handle.done.then((code) => shutdown(code), (err) => fail(`failed to spawn upstream: ${err.message}`, 1));
|
|
238
|
+
}
|
|
239
|
+
void main();
|
package/dist/packs.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 策略包:既随包分发(package.json 的 files 含 packs/),也能被 init 落到用户目录。
|
|
3
|
+
*
|
|
4
|
+
* 这里只做「读文本 + 元数据」,不做校验 —— 校验统一走 loadPolicy,
|
|
5
|
+
* 这样包和用户手写的策略走的是同一条路,不会有第二套规则解释器。
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
export const PACKS = [
|
|
11
|
+
{
|
|
12
|
+
id: 'core',
|
|
13
|
+
title: '灾难性误操作',
|
|
14
|
+
summary: 'rm -rf 根目录/系统目录、强制推送、破坏性 SQL、下载即执行、写系统目录、磁盘级破坏',
|
|
15
|
+
defaultOn: true,
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
id: 'secrets',
|
|
19
|
+
title: '凭据泄漏',
|
|
20
|
+
summary: '读 .env / 私钥 / 云凭据、访问云元数据端点、把密钥发到外部',
|
|
21
|
+
defaultOn: true,
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
id: 'git',
|
|
25
|
+
title: '版本库破坏',
|
|
26
|
+
summary: 'reset --hard、clean -fdx、删除远端分支、丢弃工作区改动',
|
|
27
|
+
defaultOn: false,
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
id: 'net',
|
|
31
|
+
title: '误触内网与付费接口',
|
|
32
|
+
summary: '内网地址、支付类接口、单窗口调用上限',
|
|
33
|
+
defaultOn: false,
|
|
34
|
+
},
|
|
35
|
+
];
|
|
36
|
+
/** dist/packs.js → ../packs/ = 包根目录下的 packs/ */
|
|
37
|
+
export function packsDir() {
|
|
38
|
+
return fileURLToPath(new URL('../packs/', import.meta.url));
|
|
39
|
+
}
|
|
40
|
+
export function packPath(id) {
|
|
41
|
+
return join(packsDir(), `${id}.yaml`);
|
|
42
|
+
}
|
|
43
|
+
export function findPack(id) {
|
|
44
|
+
return PACKS.find((pack) => pack.id === id);
|
|
45
|
+
}
|
|
46
|
+
export function readPackText(id) {
|
|
47
|
+
if (findPack(id) === undefined) {
|
|
48
|
+
throw new Error(`未知的策略包 "${id}"(可用:${PACKS.map((p) => p.id).join(', ')})`);
|
|
49
|
+
}
|
|
50
|
+
return readFileSync(packPath(id), 'utf8');
|
|
51
|
+
}
|