@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.
@@ -0,0 +1,127 @@
1
+ /**
2
+ * 策略文件的「开箱默认值」:dev 基线 + 各策略包的规则,拼成一份可直接加载的 YAML 文本。
3
+ *
4
+ * 被两处使用:
5
+ * - `agentguard init` 写盘
6
+ * - `agentguard demo` 在没有策略文件时临时构造一份(否则演示全是 deny,看不出效果)
7
+ *
8
+ * 之所以放在这里而不是 cli.ts:demo 也要用,而 cli → demo → cli 会形成循环依赖。
9
+ */
10
+ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
11
+ import { findPack, readPackText } from '../packs.js';
12
+ /**
13
+ * dev profile 的基线放行。
14
+ *
15
+ * 为什么需要它:fail-closed 意味着「没写 allow 的工具一律拒绝」,
16
+ * 如果生成的文件里一条 allow 都没有,用户接上去 agent 立刻瘫痪,
17
+ * 第一反应就是把这个东西卸了 —— 那安全价值等于 0。
18
+ * 所以基线放行「日常开发必用」的工具,危险动作交给各包的 deny 规则兜住。
19
+ *
20
+ * 想要「只跑白名单工具」的严格模式:`--profile strict`,不生成这些规则。
21
+ */
22
+ export function baselineRules() {
23
+ return [
24
+ {
25
+ id: 'base-allow-command',
26
+ match: { tool: ['bash', 'shell', 'run_command', 'execute_command', 'terminal', 'powershell'] },
27
+ decision: 'allow',
28
+ reason: '基线:放行命令工具(危险命令由各包的 deny 规则拦截)',
29
+ },
30
+ {
31
+ id: 'base-allow-argless',
32
+ match: {
33
+ tool: [
34
+ 'list_allowed_directories',
35
+ 'grep',
36
+ 'glob',
37
+ 'search',
38
+ 'codebase_search',
39
+ 'list_tools',
40
+ ],
41
+ },
42
+ decision: 'allow',
43
+ reason: '基线:放行无路径参数的只读工具',
44
+ },
45
+ {
46
+ id: 'base-allow-read',
47
+ match: {
48
+ tool: ['read_file', 'read_text_file', 'view_file', 'open_file', 'list_directory', 'directory_tree', 'get_file_info', 'search_files'],
49
+ 'args.path': { glob: '**' },
50
+ },
51
+ decision: 'allow',
52
+ reason: '基线:放行文件读取',
53
+ },
54
+ {
55
+ id: 'base-allow-read-multi',
56
+ match: { tool: ['read_multiple_files'], 'args.paths': { glob: '**' } },
57
+ decision: 'allow',
58
+ reason: '基线:放行批量文件读取',
59
+ },
60
+ {
61
+ id: 'base-allow-write',
62
+ match: {
63
+ tool: ['write_file', 'write_text_file', 'edit_file', 'create_directory', 'move_file', 'apply_patch'],
64
+ 'args.path': { glob: '**' },
65
+ },
66
+ decision: 'allow',
67
+ reason: '基线:放行文件写入(系统目录与凭据目录由 core/secrets 拦截)',
68
+ },
69
+ ];
70
+ }
71
+ function renderBlock(value) {
72
+ const text = stringifyYaml(value, { lineWidth: 0 }).replace(/\n+$/, '');
73
+ const lines = text.split('\n');
74
+ return [' - ' + lines[0], ...lines.slice(1).map((line) => ' ' + line)].join('\n');
75
+ }
76
+ /** 把若干组规则 + 限流渲染成一份完整的策略文本 */
77
+ export function buildPolicyText(options) {
78
+ const out = [
79
+ '# agentguard policy —— 由 `agentguard init` 生成,可以直接手改。',
80
+ '# 改完跑 `agentguard check --policy <本文件>`,确认它会拦什么再接入。',
81
+ '# 优先级:deny > ask > allow;同档取声明在前的一条。',
82
+ 'version: 1',
83
+ '',
84
+ 'defaults:',
85
+ ' # 没有任何规则命中时怎么办:deny | allow | ask(默认 deny,fail-closed)',
86
+ ' on_no_match: deny',
87
+ ' # 观察模式:true 时只记录不拦截。第一次接入建议先用 --observe 跑一周',
88
+ ` dry_run: ${options.dryRun}`,
89
+ '',
90
+ 'rules:',
91
+ ];
92
+ for (const group of options.groups) {
93
+ out.push(` # ── ${group.label}(${group.rules.length} 条)`);
94
+ for (const rule of group.rules)
95
+ out.push(renderBlock(rule));
96
+ }
97
+ if (options.limits.length > 0) {
98
+ out.push('');
99
+ out.push('limits:');
100
+ for (const limit of options.limits)
101
+ out.push(renderBlock(limit));
102
+ }
103
+ return out.join('\n') + '\n';
104
+ }
105
+ export function readPackDoc(id) {
106
+ const parsed = parseYaml(readPackText(id));
107
+ return {
108
+ rules: Array.isArray(parsed?.rules) ? parsed.rules : [],
109
+ limits: Array.isArray(parsed?.limits) ? parsed.limits : [],
110
+ };
111
+ }
112
+ /** init / demo 共用的「标准策略」:基线 + 指定包 */
113
+ export function buildDefaultPolicyText(packs, options = {}) {
114
+ const profile = options.profile ?? 'dev';
115
+ const groups = [];
116
+ if (profile === 'dev') {
117
+ groups.push({ label: '基线放行 · dev profile', rules: baselineRules() });
118
+ }
119
+ const limits = [];
120
+ for (const id of packs) {
121
+ const doc = readPackDoc(id);
122
+ const title = findPack(id)?.title ?? id;
123
+ groups.push({ label: `${title} · pack:${id}`, rules: doc.rules });
124
+ limits.push(...doc.limits);
125
+ }
126
+ return buildPolicyText({ dryRun: options.dryRun === true, groups, limits });
127
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * 判定层:给定 tool 与 args,输出 allow / deny / ask。
3
+ *
4
+ * 优先级 deny > ask > allow,同档按声明顺序取第一条。
5
+ * 这个顺序不是「再想一层」的优化,是为了消除「规则顺序决定结果」的意外:
6
+ * 用户在文件末尾补一条 allow 不会意外放开一条 deny。
7
+ *
8
+ * 没有任何规则命中时走 defaults.on_no_match(默认 deny)—— fail-closed。
9
+ */
10
+ const RANK = { allow: 1, ask: 2, deny: 3 };
11
+ export function decide(policy, tool, args) {
12
+ const started = process.hrtime.bigint();
13
+ let bestRule = null;
14
+ let bestRank = 0;
15
+ for (const rule of policy.rules) {
16
+ if (!rule.test(tool, args))
17
+ continue;
18
+ const rank = RANK[rule.decision];
19
+ // 严格大于才替换 → 同档自然保留「声明在前的第一条」
20
+ if (rank > bestRank) {
21
+ bestRank = rank;
22
+ bestRule = { decision: rule.decision, id: rule.id, reason: rule.reason };
23
+ if (rank === RANK.deny)
24
+ break; // deny 已经是最高的,后面的不可能翻盘
25
+ }
26
+ }
27
+ const raw = bestRule === null ? policy.defaults.onNoMatch : bestRule.decision;
28
+ const ruleId = bestRule === null ? null : bestRule.id;
29
+ const reason = bestRule === null
30
+ ? `没有规则命中(on_no_match: ${policy.defaults.onNoMatch})`
31
+ : bestRule.reason;
32
+ return {
33
+ // dry_run 只记录不拦截:审计里仍然保留 raw,才能看出「本会拦下什么」
34
+ decision: policy.defaults.dryRun ? 'allow' : raw,
35
+ raw,
36
+ ruleId,
37
+ reason,
38
+ dryRun: policy.defaults.dryRun,
39
+ elapsedMs: Number(process.hrtime.bigint() - started) / 1e6,
40
+ };
41
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 轻量 glob —— 只为策略匹配服务,不追求 shell glob 的完整语义。
3
+ *
4
+ * 支持:`*`(不跨路径分隔符)、`**`(跨分隔符)、`**\/`(零或多级目录)、`?`、`[abc]`、`[!abc]`
5
+ * 不支持:brace 展开 `{a,b}`、转义 `\*`(反斜杠一律当作路径分隔符,Windows 友好)
6
+ *
7
+ * 两个刻意的取舍:
8
+ * 1. 匹配前把反斜杠归一成 `/`,并去掉开头的 `./`。agent 传 `./.env` 还是 `.env`
9
+ * 取决于它的心情,规则不该关心这个。
10
+ * 2. 大小写不敏感。Windows 文件系统本来就不敏感,`.ENV` 被放行是不可接受的方向;
11
+ * Linux 上误伤 `.ENV` 的概率远低于漏放 `.ENV` 的代价。
12
+ */
13
+ const REGEX_SPECIAL = /[.*+?^${}()|[\]\\]/;
14
+ export function normalizeGlobInput(value) {
15
+ let out = value.replace(/\\/g, '/');
16
+ while (out.startsWith('./'))
17
+ out = out.slice(2);
18
+ out = out.replace(/\/{2,}/g, '/');
19
+ return out;
20
+ }
21
+ function translate(pattern) {
22
+ const src = pattern.replace(/\\/g, '/');
23
+ let out = '';
24
+ let i = 0;
25
+ while (i < src.length) {
26
+ const ch = src[i];
27
+ if (ch === '*') {
28
+ if (src[i + 1] === '*') {
29
+ if (src[i + 2] === '/') {
30
+ // `**/` 允许零级目录:`**/.env*` 必须能命中根目录的 `.env`。
31
+ // 用 `[^/]*`(可空)而不是 `[^/]+`:绝对路径 `/home/u/.env` 的第一个字符
32
+ // 就是 `/`,非空段匹配吃不下它,会导致整条规则对绝对路径完全失效。
33
+ out += '(?:[^/]*/)*';
34
+ i += 3;
35
+ continue;
36
+ }
37
+ out += '.*';
38
+ i += 2;
39
+ continue;
40
+ }
41
+ out += '[^/]*';
42
+ i += 1;
43
+ continue;
44
+ }
45
+ if (ch === '?') {
46
+ out += '[^/]';
47
+ i += 1;
48
+ continue;
49
+ }
50
+ if (ch === '[') {
51
+ const end = src.indexOf(']', i + 1);
52
+ if (end === -1) {
53
+ out += '\\[';
54
+ i += 1;
55
+ continue;
56
+ }
57
+ const body = src.slice(i + 1, end);
58
+ const negated = body.startsWith('!') || body.startsWith('^');
59
+ const inner = (negated ? body.slice(1) : body).replace(/[\\^]/g, '\\$&');
60
+ out += `[${negated ? '^' : ''}${inner}]`;
61
+ i = end + 1;
62
+ continue;
63
+ }
64
+ out += REGEX_SPECIAL.test(ch) ? `\\${ch}` : ch;
65
+ i += 1;
66
+ }
67
+ return out;
68
+ }
69
+ export function compileGlob(pattern) {
70
+ if (typeof pattern !== 'string' || pattern === '') {
71
+ throw new Error('glob 必须是非空字符串');
72
+ }
73
+ return {
74
+ source: pattern,
75
+ re: new RegExp(`^${translate(pattern)}$`, 'i'),
76
+ };
77
+ }
78
+ export function matchGlob(glob, value) {
79
+ return glob.re.test(normalizeGlobInput(value));
80
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * 策略加载:YAML → 校验 → 编译。
3
+ *
4
+ * 三条硬规则(方案第 4 章「三个必须坚持的设计决策」):
5
+ * 1. fail-closed 是默认值:没写 on_no_match 就是 deny。
6
+ * 2. 语法错误 = 加载失败。任何一条写错的规则都不允许被静默忽略 ——
7
+ * 静默忽略等于给用户假的安心。
8
+ * 3. 加载期就把 regex / glob 编译掉,写错立刻报,而不是等第一次调用。
9
+ *
10
+ * 多文件合并:按传入顺序拼接规则(先文件的规则先声明)。同档判定取第一条,
11
+ * 所以「项目 > 用户 > 内置」只要按这个顺序传路径即可。
12
+ */
13
+ import { readFileSync } from 'node:fs';
14
+ import { parse as parseYaml } from 'yaml';
15
+ import { compileRules } from './match.js';
16
+ import { PolicyError, } from './types.js';
17
+ const ROOT_KEYS = new Set(['version', 'defaults', 'rules', 'limits']);
18
+ const DEFAULTS_KEYS = new Set(['on_no_match', 'dry_run']);
19
+ const LIMIT_KEYS = new Set(['tool', 'max_calls', 'window']);
20
+ const DECISIONS = ['allow', 'deny', 'ask'];
21
+ const WINDOW_PATTERN = /^(\d+)(ms|s|m|h|d)$/;
22
+ const WINDOW_UNIT_MS = {
23
+ ms: 1,
24
+ s: 1000,
25
+ m: 60_000,
26
+ h: 3_600_000,
27
+ d: 86_400_000,
28
+ };
29
+ function isRecord(value) {
30
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
31
+ }
32
+ function parseWindow(value, origin, where) {
33
+ if (typeof value !== 'string') {
34
+ throw new PolicyError(`${where} 的 window 必须是字符串,例如 "1h"`, origin);
35
+ }
36
+ const m = WINDOW_PATTERN.exec(value.trim());
37
+ if (m === null) {
38
+ throw new PolicyError(`${where} 的 window "${value}" 无法识别(可用:30s / 5m / 1h / 1d)`, origin);
39
+ }
40
+ const unit = WINDOW_UNIT_MS[m[2]];
41
+ return { ms: Number(m[1]) * unit, raw: value };
42
+ }
43
+ function parseDefaults(raw, origin) {
44
+ if (raw === undefined)
45
+ return {};
46
+ if (!isRecord(raw)) {
47
+ throw new PolicyError('defaults 必须是对象', origin);
48
+ }
49
+ for (const key of Object.keys(raw)) {
50
+ if (!DEFAULTS_KEYS.has(key)) {
51
+ throw new PolicyError(`defaults 出现未知键 "${key}"(可用:on_no_match / dry_run)`, origin);
52
+ }
53
+ }
54
+ const out = {};
55
+ if (raw.on_no_match !== undefined) {
56
+ const value = raw.on_no_match;
57
+ if (typeof value !== 'string' || !DECISIONS.includes(value)) {
58
+ throw new PolicyError(`defaults.on_no_match 必须是 ${DECISIONS.join(' / ')},收到 ${JSON.stringify(value)}`, origin);
59
+ }
60
+ out.onNoMatch = value;
61
+ }
62
+ if (raw.dry_run !== undefined) {
63
+ if (typeof raw.dry_run !== 'boolean') {
64
+ throw new PolicyError('defaults.dry_run 必须是 true / false', origin);
65
+ }
66
+ out.dryRun = raw.dry_run;
67
+ }
68
+ return out;
69
+ }
70
+ function parseLimits(raw, origin) {
71
+ if (raw === undefined)
72
+ return [];
73
+ if (!Array.isArray(raw)) {
74
+ throw new PolicyError('limits 必须是数组', origin);
75
+ }
76
+ return raw.map((entry, index) => {
77
+ const where = `limits[${index}]`;
78
+ if (!isRecord(entry)) {
79
+ throw new PolicyError(`${where} 必须是对象`, origin);
80
+ }
81
+ for (const key of Object.keys(entry)) {
82
+ if (!LIMIT_KEYS.has(key)) {
83
+ throw new PolicyError(`${where} 出现未知键 "${key}"(可用:tool / max_calls / window)`, origin);
84
+ }
85
+ }
86
+ const tool = entry.tool;
87
+ const tools = Array.isArray(tool) ? tool : [tool];
88
+ if (tools.length === 0 || tools.some((t) => typeof t !== 'string' || t === '')) {
89
+ throw new PolicyError(`${where} 的 tool 必须是非空字符串或非空字符串数组`, origin);
90
+ }
91
+ const maxCalls = entry.max_calls;
92
+ if (typeof maxCalls !== 'number' || !Number.isInteger(maxCalls) || maxCalls <= 0) {
93
+ throw new PolicyError(`${where} 的 max_calls 必须是正整数`, origin);
94
+ }
95
+ const window = parseWindow(entry.window, origin, where);
96
+ return {
97
+ tools: tools,
98
+ maxCalls,
99
+ windowMs: window.ms,
100
+ window: window.raw,
101
+ origin,
102
+ };
103
+ });
104
+ }
105
+ function parseDocument(text, origin) {
106
+ let root;
107
+ try {
108
+ root = parseYaml(text);
109
+ }
110
+ catch (err) {
111
+ throw new PolicyError(`YAML 解析失败:${err.message}`, origin);
112
+ }
113
+ if (root === null || root === undefined) {
114
+ throw new PolicyError('策略文件是空的', origin);
115
+ }
116
+ if (!isRecord(root)) {
117
+ throw new PolicyError('策略文件顶层必须是对象(version / defaults / rules / limits)', origin);
118
+ }
119
+ for (const key of Object.keys(root)) {
120
+ if (!ROOT_KEYS.has(key)) {
121
+ throw new PolicyError(`顶层出现未知键 "${key}"(可用:version / defaults / rules / limits)`, origin);
122
+ }
123
+ }
124
+ if (root.version !== 1) {
125
+ throw new PolicyError(`version 必须是 1,收到 ${JSON.stringify(root.version)} —— 版本不对时拒绝加载,避免语义漂移`, origin);
126
+ }
127
+ const defaults = parseDefaults(root.defaults, origin);
128
+ const limits = parseLimits(root.limits, origin);
129
+ const rawRules = root.rules === undefined ? [] : root.rules;
130
+ if (!Array.isArray(rawRules)) {
131
+ throw new PolicyError('rules 必须是数组', origin);
132
+ }
133
+ const rules = compileRules(rawRules, origin);
134
+ const seen = new Set();
135
+ for (const rule of rules) {
136
+ if (seen.has(rule.id)) {
137
+ throw new PolicyError(`规则 id "${rule.id}" 重复`, origin, rule.id);
138
+ }
139
+ seen.add(rule.id);
140
+ }
141
+ return { version: 1, defaults, rules, limits };
142
+ }
143
+ /** 解析单个策略文本(测试与 `check` 子命令用) */
144
+ export function parsePolicy(text, origin = '<inline>') {
145
+ const doc = parseDocument(text, origin);
146
+ return {
147
+ version: doc.version,
148
+ defaults: {
149
+ onNoMatch: doc.defaults.onNoMatch ?? 'deny',
150
+ dryRun: doc.defaults.dryRun ?? false,
151
+ },
152
+ rules: doc.rules,
153
+ limits: doc.limits,
154
+ sources: [origin],
155
+ };
156
+ }
157
+ /**
158
+ * 按顺序加载并合并多个策略文件。
159
+ * 规则按文件顺序拼接;defaults 由后出现的文件覆盖(同键);sources 记录全部出处。
160
+ */
161
+ export function loadPolicy(paths) {
162
+ const list = typeof paths === 'string' ? [paths] : [...paths];
163
+ if (list.length === 0) {
164
+ throw new PolicyError('没有指定策略文件');
165
+ }
166
+ const rules = [];
167
+ const limits = [];
168
+ const sources = [];
169
+ let onNoMatch;
170
+ let dryRun;
171
+ const idOrigin = new Map();
172
+ for (const file of list) {
173
+ let text;
174
+ try {
175
+ text = readFileSync(file, 'utf8');
176
+ }
177
+ catch (err) {
178
+ throw new PolicyError(`无法读取策略文件:${err.message}`, file);
179
+ }
180
+ const doc = parseDocument(text.replace(/^\uFEFF/, ''), file);
181
+ sources.push(file);
182
+ if (doc.defaults.onNoMatch !== undefined)
183
+ onNoMatch = doc.defaults.onNoMatch;
184
+ if (doc.defaults.dryRun !== undefined)
185
+ dryRun = doc.defaults.dryRun;
186
+ for (const rule of doc.rules) {
187
+ const previous = idOrigin.get(rule.id);
188
+ if (previous !== undefined) {
189
+ throw new PolicyError(`规则 id "${rule.id}" 与 ${previous} 重复 —— id 会出现在审计日志里,必须全局唯一`, file, rule.id);
190
+ }
191
+ idOrigin.set(rule.id, file);
192
+ rules.push(rule);
193
+ }
194
+ limits.push(...doc.limits);
195
+ }
196
+ return {
197
+ version: 1,
198
+ defaults: { onNoMatch: onNoMatch ?? 'deny', dryRun: dryRun ?? false },
199
+ rules,
200
+ limits,
201
+ sources,
202
+ };
203
+ }