@yagyeshvyas/vibeguard 1.3.0 → 1.11.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/.vibeguard-mcp.example.json +51 -0
- package/CHANGELOG.md +604 -216
- package/MCP-FIREWALL.md +296 -0
- package/README.md +355 -31
- package/bin/cli.js +355 -27
- package/bin/cmd-agent-monitor.js +45 -0
- package/bin/cmd-agent-risk.js +64 -0
- package/bin/cmd-gif.js +62 -0
- package/bin/cmd-git-scan.js +74 -0
- package/bin/cmd-llm-proxy.js +164 -0
- package/bin/cmd-mcp-firewall.js +191 -0
- package/bin/cmd-pentest.js +103 -0
- package/bin/cmd-platform.js +137 -0
- package/bin/cmd-pr-scan.js +135 -0
- package/bin/cmd-sbom-diff.js +38 -0
- package/bin/cmd-skill-scan.js +35 -0
- package/docs/AISVS.md +25 -0
- package/docs/ARCHITECTURE.md +81 -0
- package/docs/INSTALLATION.md +139 -0
- package/docs/WINDOWS.md +74 -0
- package/docs/security-policy.strict.example.json +134 -0
- package/docs/security-policy.strict.example.pub.pem +3 -0
- package/package.json +45 -7
- package/src/.vibeguard/cache/file-hashes.json +60 -0
- package/src/.vibeguard/latest-snapshot.json +36 -0
- package/src/.vibeguard/mcp-pins.json +1 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +279 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +151 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +65 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +2051 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +150 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +1611 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +164 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +292 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +144 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +37 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +2055 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +279 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +151 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +65 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +2055 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +150 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +1611 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +164 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +292 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +144 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +279 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +151 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +65 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +2054 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +150 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +1611 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +164 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +292 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +144 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +37 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +2055 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +33 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +2055 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +1611 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +292 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +220 -0
- package/src/.vibeguard-baseline.json +5226 -0
- package/src/action-guard.js +84 -6
- package/src/agent-monitor.js +262 -0
- package/src/agent-policy.js +642 -0
- package/src/agent-risk.js +271 -0
- package/src/agentic.js +1513 -0
- package/src/ast.js +165 -7
- package/src/audit-trail.js +212 -67
- package/src/auto.js +427 -427
- package/src/autofix.js +11 -4
- package/src/bundles.js +198 -0
- package/src/daemon.js +343 -343
- package/src/dashboard.js +278 -278
- package/src/engine.js +3 -0
- package/src/entropy.js +187 -0
- package/src/firewall.js +19 -3
- package/src/gif.js +134 -0
- package/src/gitscan.js +282 -0
- package/src/hook.js +151 -151
- package/src/injection-decode.js +136 -0
- package/src/install.js +298 -280
- package/src/integrity.js +16 -1
- package/src/integrity.json +43 -13
- package/src/interceptor.js +12 -9
- package/src/llm-proxy.js +986 -0
- package/src/mcp-audit.js +61 -5
- package/src/mcp-firewall.js +971 -0
- package/src/mcp-server.js +2500 -2047
- package/src/obfuscation.js +315 -0
- package/src/owasp-agentic.js +314 -0
- package/src/pentest.js +589 -0
- package/src/pii.js +4 -0
- package/src/platform/aisvs.js +38 -0
- package/src/platform/approval.js +187 -0
- package/src/platform/canonical.js +73 -0
- package/src/platform/contracts.js +158 -0
- package/src/platform/delegation.js +73 -0
- package/src/platform/http-gateway.js +177 -0
- package/src/platform/identity.js +253 -0
- package/src/platform/jwt.js +86 -0
- package/src/platform/mcp-http-bridge.js +199 -0
- package/src/platform/memory-guard.js +64 -0
- package/src/platform/os-sandbox.js +144 -0
- package/src/platform/policy.js +332 -0
- package/src/platform/sandbox-manager.js +92 -0
- package/src/platform/signed-audit.js +357 -0
- package/src/platform/ssrf.js +129 -0
- package/src/plugin.js +182 -168
- package/src/pre-deploy.js +170 -55
- package/src/privacy-audit.js +272 -272
- package/src/repl.js +150 -150
- package/src/report.js +7 -1
- package/src/routes.js +1210 -0
- package/src/rules-2026.js +1407 -0
- package/src/rules-pack.js +3068 -3019
- package/src/rules.js +376 -60
- package/src/sandbox.js +200 -10
- package/src/sbom.js +193 -164
- package/src/scanner.js +189 -33
- package/src/shell-guard.js +11 -0
- package/src/skill-scan.js +477 -0
- package/src/slopsquat.js +144 -144
- package/src/surface.js +408 -0
- package/src/taint-ast.js +204 -37
- package/src/taint.js +15 -3
- package/src/tokenlean.js +579 -0
- package/src/trace.js +220 -220
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* src/agent-policy.js — AI agent permission enforcement.
|
|
5
|
+
*
|
|
6
|
+
* A policy is a small JSON file that answers four questions before any MCP
|
|
7
|
+
* tool call reaches a server:
|
|
8
|
+
*
|
|
9
|
+
* 1. May this tool run at all? (tool rules / deny / approval)
|
|
10
|
+
* 2. May it touch this path? (filesystem scope + denied paths)
|
|
11
|
+
* 3. May it reach this host? (egress allowlist + metadata block)
|
|
12
|
+
* 4. May this data leave the machine? (secret / PII exfiltration checks)
|
|
13
|
+
*
|
|
14
|
+
* It is deliberately boring: no model, no network, no heuristics that need a
|
|
15
|
+
* GPU. Deterministic rules an operator can read and diff.
|
|
16
|
+
*
|
|
17
|
+
* Default policy is "safe but usable": unknown tools are allowed, but
|
|
18
|
+
* credential stores are denied, cloud metadata is denied, secrets in arguments
|
|
19
|
+
* are blocked, shell commands go through the shell guard, writes outside the
|
|
20
|
+
* project are blocked, and calls are rate-limited.
|
|
21
|
+
*
|
|
22
|
+
* 100% local. Zero network. Zero dependencies.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const fs = require('fs');
|
|
26
|
+
const path = require('path');
|
|
27
|
+
const os = require('os');
|
|
28
|
+
const crypto = require('crypto');
|
|
29
|
+
const { checkCommand } = require('./shell-guard');
|
|
30
|
+
const { checkPackage } = require('./firewall');
|
|
31
|
+
const { scanForLeaks, scanForLeaksDeep, sanitizeOutbound, isExternalHost, hostOf, shannonEntropy } = require('./action-guard');
|
|
32
|
+
const { scanTextForInjection } = require('./mcp-audit');
|
|
33
|
+
|
|
34
|
+
const POLICY_FILES = ['.vibeguard-mcp.json', '.vibeguard/mcp-policy.json', 'vibeguard.mcp.json', 'mcp-policy.json'];
|
|
35
|
+
|
|
36
|
+
const DEFAULT_POLICY = {
|
|
37
|
+
version: 1,
|
|
38
|
+
// Unknown tools are allowed by default so enabling the firewall does not
|
|
39
|
+
// silently break a working agent. Tighten with defaultAction: "block".
|
|
40
|
+
defaultAction: 'allow',
|
|
41
|
+
// Explicit tool rules: [{ match: "mcp__filesystem__write_*", action: "block", reason: "..." }]
|
|
42
|
+
toolRules: [],
|
|
43
|
+
// Tool name globs that always win, regardless of toolRules.
|
|
44
|
+
denyTools: [],
|
|
45
|
+
allowTools: [],
|
|
46
|
+
// Tools that require a human decision. A headless proxy converts these to a
|
|
47
|
+
// block with a clear reason instead of hanging forever.
|
|
48
|
+
approvalRequired: [],
|
|
49
|
+
// Capability names that are never allowed: shell, fs.write, network, ...
|
|
50
|
+
blockedCapabilities: [],
|
|
51
|
+
allowedCapabilities: [],
|
|
52
|
+
// Filesystem scope. Relative paths resolve against the project root.
|
|
53
|
+
allowedPaths: [],
|
|
54
|
+
deniedPaths: [
|
|
55
|
+
'**/.env',
|
|
56
|
+
'**/.env.*',
|
|
57
|
+
'**/.ssh/**',
|
|
58
|
+
'**/.aws/credentials',
|
|
59
|
+
'**/.aws/config',
|
|
60
|
+
'**/.npmrc',
|
|
61
|
+
'**/.netrc',
|
|
62
|
+
'**/.git-credentials',
|
|
63
|
+
'**/*.pem',
|
|
64
|
+
'**/*.key',
|
|
65
|
+
'**/id_rsa',
|
|
66
|
+
'**/id_ed25519',
|
|
67
|
+
'**/secrets/**',
|
|
68
|
+
'**/credentials.json',
|
|
69
|
+
'**/service-account*.json',
|
|
70
|
+
'**/AppData/Local/Google/Chrome/User Data/**',
|
|
71
|
+
'**/AppData/Roaming/Mozilla/Firefox/Profiles/**',
|
|
72
|
+
'**/.config/gh/hosts.yml',
|
|
73
|
+
],
|
|
74
|
+
// Reads outside the project are blocked unless listed in allowedPaths.
|
|
75
|
+
enforceProjectScope: true,
|
|
76
|
+
// Egress. An empty allowedHosts list means "any external host", but the
|
|
77
|
+
// secret/PII checks below still apply. Put hosts here to allowlist.
|
|
78
|
+
allowedHosts: [],
|
|
79
|
+
deniedHosts: ['169.254.169.254', 'metadata.google.internal', 'metadata.goog'],
|
|
80
|
+
// Hosts allowed to receive sensitive data (your own API, localhost, ...).
|
|
81
|
+
trustedHosts: [],
|
|
82
|
+
blockExternalNetwork: false,
|
|
83
|
+
// Secret and PII handling.
|
|
84
|
+
secretScan: true,
|
|
85
|
+
allowSecretsInArgs: false,
|
|
86
|
+
piiScan: true,
|
|
87
|
+
piiMode: 'warn', // warn | block
|
|
88
|
+
// Content defenses.
|
|
89
|
+
blockPromptInjection: true,
|
|
90
|
+
pinToolDefinitions: true,
|
|
91
|
+
scrubToolResults: true,
|
|
92
|
+
blockToolResultInjection: true,
|
|
93
|
+
// Volume controls.
|
|
94
|
+
maxArgumentBytes: 65536,
|
|
95
|
+
maxCallsPerMinute: 240,
|
|
96
|
+
// Logging.
|
|
97
|
+
logAllowedCalls: true,
|
|
98
|
+
// If the policy file itself cannot be parsed, fail closed instead of running
|
|
99
|
+
// with defaults. Configuring this to true is strongly recommended in CI.
|
|
100
|
+
failClosed: false,
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const CAPABILITY_PATTERNS = [
|
|
104
|
+
['shell', /(^|[_\-.])(exec|shell|command|terminal|powershell|bash|spawn|run|process)([_\-.]|$)/i],
|
|
105
|
+
['code-exec', /(^|[_\-.])(eval|execute|interpreter|python|repl|code)([_\-.]|$)/i],
|
|
106
|
+
['fs.write', /(^|[_\-.])(write|edit|create|delete|remove|move|rename|copy|mkdir|rm|patch)([_\-.]|$)/i],
|
|
107
|
+
['fs.read', /(^|[_\-.])(read|cat|list|glob|grep|search|find|stat|open|head|tail)([_\-.]|$)/i],
|
|
108
|
+
['network', /(^|[_\-.])(fetch|http|request|url|browse|crawl|web|download|upload|send|post|http_get)([_\-.]|$)/i],
|
|
109
|
+
['database', /(^|[_\-.])(sql|query|database|db|table|supabase|postgres|mysql|mongo)([_\-.]|$)/i],
|
|
110
|
+
['secrets', /(^|[_\-.])(secret|env|credential|key|token|vault|password)([_\-.]|$)/i],
|
|
111
|
+
];
|
|
112
|
+
|
|
113
|
+
function globToRegExp(glob) {
|
|
114
|
+
let out = '^';
|
|
115
|
+
let i = 0;
|
|
116
|
+
while (i < glob.length) {
|
|
117
|
+
const ch = glob[i];
|
|
118
|
+
if (ch === '*') {
|
|
119
|
+
if (glob[i + 1] === '*') {
|
|
120
|
+
out += '.*';
|
|
121
|
+
i += 2;
|
|
122
|
+
// "**/" may match zero directories.
|
|
123
|
+
if (glob[i] === '/') i++;
|
|
124
|
+
} else {
|
|
125
|
+
out += '[^/]*';
|
|
126
|
+
i++;
|
|
127
|
+
}
|
|
128
|
+
} else if (ch === '?') {
|
|
129
|
+
out += '[^/]';
|
|
130
|
+
i++;
|
|
131
|
+
} else if (ch === '[') {
|
|
132
|
+
const end = glob.indexOf(']', i + 1);
|
|
133
|
+
if (end === -1) {
|
|
134
|
+
out += '\\[';
|
|
135
|
+
i++;
|
|
136
|
+
} else {
|
|
137
|
+
out += glob.slice(i, end + 1);
|
|
138
|
+
i = end + 1;
|
|
139
|
+
}
|
|
140
|
+
} else {
|
|
141
|
+
out += ch.replace(/[.+^${}()|\\]/g, '\\$&');
|
|
142
|
+
i++;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
out += '$';
|
|
146
|
+
try {
|
|
147
|
+
return new RegExp(out, 'i');
|
|
148
|
+
} catch {
|
|
149
|
+
return /$^/;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function normalizeSlashes(p) {
|
|
154
|
+
return String(p == null ? '' : p).replace(/\\/g, '/');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function matchesGlob(value, glob) {
|
|
158
|
+
const v = normalizeSlashes(value);
|
|
159
|
+
const g = normalizeSlashes(glob);
|
|
160
|
+
if (!/[?*[\]]/.test(g)) return v.toLowerCase() === g.toLowerCase();
|
|
161
|
+
return globToRegExp(g).test(v);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function matchesAny(value, globs) {
|
|
165
|
+
if (!Array.isArray(globs)) return false;
|
|
166
|
+
for (const glob of globs) {
|
|
167
|
+
if (matchesGlob(value, glob)) return true;
|
|
168
|
+
}
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function mergePolicy(base, override) {
|
|
173
|
+
const out = { ...base };
|
|
174
|
+
if (!override || typeof override !== 'object') return out;
|
|
175
|
+
for (const [key, value] of Object.entries(override)) {
|
|
176
|
+
if (value === undefined) continue;
|
|
177
|
+
out[key] = value;
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function loadPolicy(root, explicitPath) {
|
|
183
|
+
const projectRoot = path.resolve(root || process.cwd());
|
|
184
|
+
const candidates = explicitPath ? [path.resolve(projectRoot, explicitPath)] : POLICY_FILES.map((f) => path.join(projectRoot, f));
|
|
185
|
+
let source = null;
|
|
186
|
+
let policy = { ...DEFAULT_POLICY, projectRoot };
|
|
187
|
+
|
|
188
|
+
for (const file of candidates) {
|
|
189
|
+
let raw;
|
|
190
|
+
try {
|
|
191
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
192
|
+
} catch {
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
const parsed = JSON.parse(raw);
|
|
197
|
+
policy = mergePolicy(policy, parsed);
|
|
198
|
+
source = file;
|
|
199
|
+
break;
|
|
200
|
+
} catch (err) {
|
|
201
|
+
return {
|
|
202
|
+
policy: { ...DEFAULT_POLICY, projectRoot, invalidPolicy: true, failClosed: true },
|
|
203
|
+
source: file,
|
|
204
|
+
error: `Invalid policy JSON in ${file}: ${err.message}`,
|
|
205
|
+
failedClosed: true,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Normalize the shapes we accept for tool rules.
|
|
211
|
+
if (policy.toolRules && !Array.isArray(policy.toolRules) && typeof policy.toolRules === 'object') {
|
|
212
|
+
policy.toolRules = Object.entries(policy.toolRules).map(([match, action]) => ({ match, action }));
|
|
213
|
+
}
|
|
214
|
+
policy.toolRules = (policy.toolRules || []).map((rule) => {
|
|
215
|
+
if (typeof rule === 'string') return { match: rule, action: 'block', reason: `tool rule: ${rule}` };
|
|
216
|
+
return { ...rule, match: String(rule.match || rule.tool || '*'), action: rule.action || 'block' };
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
for (const key of ['denyTools', 'allowTools', 'approvalRequired', 'blockedCapabilities', 'allowedCapabilities', 'allowedPaths', 'deniedPaths', 'allowedHosts', 'deniedHosts', 'trustedHosts']) {
|
|
220
|
+
if (!Array.isArray(policy[key])) policy[key] = policy[key] ? [policy[key]] : [];
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const validDefaultAction = ['allow', 'warn', 'block'].includes(policy.defaultAction);
|
|
224
|
+
if (!validDefaultAction) policy.invalidPolicy = true;
|
|
225
|
+
policy.defaultAction = validDefaultAction ? policy.defaultAction : 'block';
|
|
226
|
+
policy.piiMode = policy.piiMode === 'block' ? 'block' : 'warn';
|
|
227
|
+
policy.projectRoot = projectRoot;
|
|
228
|
+
|
|
229
|
+
return { policy, source, error: null, failedClosed: false };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function capabilityOf(toolName, args) {
|
|
233
|
+
const name = String(toolName || '');
|
|
234
|
+
const found = [];
|
|
235
|
+
for (const [cap, re] of CAPABILITY_PATTERNS) {
|
|
236
|
+
if (re.test(name)) found.push(cap);
|
|
237
|
+
}
|
|
238
|
+
// Argument shape can reveal what the tool name does not say.
|
|
239
|
+
const blob = JSON.stringify(args || {});
|
|
240
|
+
if (!found.length) {
|
|
241
|
+
if (/"(?:command|cmd)"\s*:/.test(blob)) found.push('shell');
|
|
242
|
+
else if (/https?:\/\//.test(blob)) found.push('network');
|
|
243
|
+
else if (/"(?:path|file|dir|filename)"\s*:/.test(blob)) found.push('fs.read');
|
|
244
|
+
}
|
|
245
|
+
if (found.includes('network') && found.includes('secrets')) found.push('exfil');
|
|
246
|
+
if (!found.length) found.push('generic');
|
|
247
|
+
return found[0];
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function walkStrings(value, key, out) {
|
|
251
|
+
if (value == null) return;
|
|
252
|
+
if (typeof value === 'string') {
|
|
253
|
+
out.push({ key: key || '', value });
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if (Array.isArray(value)) {
|
|
257
|
+
value.forEach((v) => walkStrings(v, key, out));
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (typeof value === 'object') {
|
|
261
|
+
for (const [k, v] of Object.entries(value)) walkStrings(v, k, out);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const PATH_KEY_RE = /(?:^|_)(?:path|file|filename|dir|directory|folder|root|cwd|target|source|dest|destination|location)s?$|^(?:path|paths|file|files|filename|dir|dirs|directory|folder|root|cwd|target|source|dest|destination|src|dst|location)$|(?:Path|File|Dir|Folder|Root|Target|Source|Dest|Destination)$/;
|
|
266
|
+
const COMMAND_KEY_RE = /^(?:command|cmd|script|shell|code|expression|eval|query|sql|input|args|arg|payload)$/i;
|
|
267
|
+
|
|
268
|
+
function expandHome(p) {
|
|
269
|
+
if (p === '~') return os.homedir();
|
|
270
|
+
if (typeof p === 'string' && p.startsWith('~/')) return path.join(os.homedir(), p.slice(2));
|
|
271
|
+
return p;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function resolveCandidate(root, value) {
|
|
275
|
+
const expanded = expandHome(String(value));
|
|
276
|
+
if (path.isAbsolute(expanded)) return path.resolve(expanded);
|
|
277
|
+
return path.resolve(root || process.cwd(), expanded);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function isInside(root, candidate) {
|
|
281
|
+
const rel = path.relative(root, candidate);
|
|
282
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Resolve junctions/symlinks and non-existent leaf paths against the nearest
|
|
286
|
+
// existing parent. The policy must decide on the real path, not the lexical one.
|
|
287
|
+
function canonicalPath(root, value) {
|
|
288
|
+
const resolved = resolveCandidate(root, value);
|
|
289
|
+
let existing = resolved;
|
|
290
|
+
const suffix = [];
|
|
291
|
+
for (let i = 0; i < 32; i++) {
|
|
292
|
+
try {
|
|
293
|
+
const real = fs.realpathSync.native(existing);
|
|
294
|
+
return path.join(real, ...suffix.reverse());
|
|
295
|
+
} catch {
|
|
296
|
+
const parent = path.dirname(existing);
|
|
297
|
+
if (parent === existing) break;
|
|
298
|
+
suffix.push(path.basename(existing));
|
|
299
|
+
existing = parent;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return resolved;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function canonicalRoot(root) {
|
|
306
|
+
try { return fs.realpathSync.native(root); } catch { return path.resolve(root); }
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function policyUrlCheck(url, p, add) {
|
|
310
|
+
const host = hostOf(url) || String(url).toLowerCase();
|
|
311
|
+
if (matchesAny(host, p.deniedHosts)) {
|
|
312
|
+
add('block', 'host-denied', `Tool is trying to reach denied host "${host}".`, 'Cloud metadata services are never a valid agent destination.');
|
|
313
|
+
}
|
|
314
|
+
if (p.blockExternalNetwork && isExternalHost(host) && !matchesAny(host, p.allowedHosts)) {
|
|
315
|
+
add('block', 'external-network-blocked', `Tool is trying to reach external host "${host}" while blockExternalNetwork is on.`, 'Add the host to allowedHosts or turn off blockExternalNetwork.');
|
|
316
|
+
}
|
|
317
|
+
if (p.allowedHosts.length > 0 && isExternalHost(host) && !matchesAny(host, p.allowedHosts)) {
|
|
318
|
+
add('block', 'host-not-allowlisted', `External host "${host}" is not in allowedHosts.`, 'Add the host to allowedHosts to permit egress.');
|
|
319
|
+
}
|
|
320
|
+
if (isExternalHost(host) && !matchesAny(host, p.trustedHosts)) {
|
|
321
|
+
const leaks = scanForLeaks(url);
|
|
322
|
+
if (leaks.secrets.length) add('block', 'secret-in-url', `${leaks.secrets.join(', ')} embedded in URL to ${host}.`, 'Never put credentials in a URL.');
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function inspectText(text, policy, add, context) {
|
|
327
|
+
if (typeof text !== 'string' || text.length === 0) return;
|
|
328
|
+
const deep = (policy.secretScan || policy.piiScan) ? scanForLeaksDeep(text) : null;
|
|
329
|
+
if (policy.secretScan && !policy.allowSecretsInArgs) {
|
|
330
|
+
const leaks = deep;
|
|
331
|
+
if (leaks.secrets.length) {
|
|
332
|
+
add('block', 'secret-in-arguments', `${leaks.secrets.join(', ')} would be passed to ${context}`, 'Never pass a live credential as a tool argument. Read it inside the trusted server or use a vault reference.');
|
|
333
|
+
}
|
|
334
|
+
if (leaks.namedSecrets.length) {
|
|
335
|
+
add('block', 'named-secret-in-arguments', `credential field(s) ${leaks.namedSecrets.join(', ')} would be passed to ${context}`, 'Move credentials out of tool arguments.');
|
|
336
|
+
}
|
|
337
|
+
if (leaks.entropy.length) {
|
|
338
|
+
add('block', 'high-entropy-secret-in-arguments', `unknown high-entropy credential material would be passed to ${context}`, 'Do not pass opaque secrets to tools; use a vault reference.');
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
if (policy.blockPromptInjection) {
|
|
342
|
+
const hits = scanTextForInjection(text);
|
|
343
|
+
if (hits.length) {
|
|
344
|
+
add('warn', 'prompt-injection-in-arguments', `prompt-injection pattern (${hits.slice(0, 3).join(', ')}) in text passed to ${context}`, 'Strip the injected instruction before the tool consumes it.');
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (policy.piiScan) {
|
|
348
|
+
const leaks = deep;
|
|
349
|
+
const personal = leaks.pii.filter((t) => t !== 'ipv4' && t !== 'ipv6');
|
|
350
|
+
if (personal.length) {
|
|
351
|
+
add(policy.piiMode === 'block' ? 'block' : 'warn', 'pii-in-arguments', `personal data (${personal.join(', ')}) passed to ${context}`, 'Redact PII unless the destination is trusted.');
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function evaluateToolCall({ root, policy, server, tool, args, strict = false }) {
|
|
357
|
+
const p = policy || { ...DEFAULT_POLICY };
|
|
358
|
+
const projectRoot = path.resolve(root || p.projectRoot || process.cwd());
|
|
359
|
+
const strictMode = strict === true || p.mode === 'strict';
|
|
360
|
+
const defaultAction = strictMode && p.defaultAction === 'allow' ? 'block' : p.defaultAction;
|
|
361
|
+
const toolName = String(tool || '');
|
|
362
|
+
const callArgs = args || {};
|
|
363
|
+
const violations = [];
|
|
364
|
+
const add = (level, id, message, fix) => violations.push({ level, id, message, fix: fix || null });
|
|
365
|
+
const capability = capabilityOf(toolName, callArgs);
|
|
366
|
+
|
|
367
|
+
if (p.invalidPolicy && p.failClosed) {
|
|
368
|
+
add('block', 'policy-failed-closed', 'The security policy file could not be parsed and failClosed is enabled.', 'Fix the policy file before running the agent.');
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// 1. Tool rules, deny/allow/approval lists.
|
|
372
|
+
if (matchesAny(toolName, p.denyTools)) {
|
|
373
|
+
add('block', 'tool-denied', `Tool "${toolName}" is denied by policy.`, 'Remove the tool from denyTools if it is meant to run.');
|
|
374
|
+
}
|
|
375
|
+
const explicitRule = (p.toolRules || []).find((rule) => matchesGlob(toolName, rule.match));
|
|
376
|
+
if (explicitRule) {
|
|
377
|
+
const action = explicitRule.action;
|
|
378
|
+
const validActions = ['allow', 'warn', 'block', 'approval', 'require-approval', 'ask'];
|
|
379
|
+
if (strictMode && !validActions.includes(action)) {
|
|
380
|
+
add('block', 'policy-invalid-rule', `Tool rule "${explicitRule.match}" has an invalid action "${action}".`, 'Fix the policy rule; strict mode does not guess.');
|
|
381
|
+
} else if (action === 'block') add('block', 'tool-rule-block', explicitRule.reason || `Tool "${toolName}" is blocked by policy rule "${explicitRule.match}".`, 'Review the rule in your MCP policy.');
|
|
382
|
+
else if (action === 'warn') add('warn', 'tool-rule-warn', explicitRule.reason || `Tool "${toolName}" matched a warn rule.`, 'Review the call.');
|
|
383
|
+
else if (action === 'approval' || action === 'require-approval' || action === 'ask') add('block', 'tool-approval-required', explicitRule.reason || `Tool "${toolName}" requires human approval and this proxy is headless.`, 'Approve the call interactively or remove it from approvalRequired.');
|
|
384
|
+
}
|
|
385
|
+
if (matchesAny(toolName, p.approvalRequired)) {
|
|
386
|
+
add('block', 'tool-approval-required', `Tool "${toolName}" requires human approval and this proxy is headless.`, 'Run with an approver, or remove the tool from approvalRequired.');
|
|
387
|
+
}
|
|
388
|
+
if (p.allowTools.length > 0 && !matchesAny(toolName, p.allowTools) && !explicitRule) {
|
|
389
|
+
add('block', 'tool-not-allowlisted', `Tool "${toolName}" is not in allowTools.`, 'Add the tool to allowTools to permit it.');
|
|
390
|
+
}
|
|
391
|
+
if (p.blockedCapabilities.includes(capability)) {
|
|
392
|
+
add('block', 'capability-blocked', `Capability "${capability}" is blocked by policy (tool "${toolName}").`, 'Remove the capability from blockedCapabilities to permit it.');
|
|
393
|
+
}
|
|
394
|
+
if (p.allowedCapabilities.length > 0 && !p.allowedCapabilities.includes(capability) && !p.allowedCapabilities.includes('generic')) {
|
|
395
|
+
add('block', 'capability-not-allowlisted', `Capability "${capability}" is not in allowedCapabilities.`, 'Add the capability to allowedCapabilities to permit it.');
|
|
396
|
+
}
|
|
397
|
+
if (defaultAction === 'block' && !explicitRule && !matchesAny(toolName, p.allowTools)) {
|
|
398
|
+
add('block', 'default-deny', `Tool "${toolName}" is denied by defaultAction: block.`, 'Add an explicit allow rule for this tool.');
|
|
399
|
+
} else if (defaultAction === 'warn' && !explicitRule && !matchesAny(toolName, p.allowTools)) {
|
|
400
|
+
add('warn', 'default-warn', `Tool "${toolName}" matched defaultAction: warn.`, 'Review the call.');
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// 2. Volume and shape.
|
|
404
|
+
const argBytes = Buffer.byteLength(JSON.stringify(callArgs));
|
|
405
|
+
if (p.maxArgumentBytes > 0 && argBytes > p.maxArgumentBytes) {
|
|
406
|
+
add('block', 'arguments-too-large', `Tool arguments are ${argBytes} bytes (limit ${p.maxArgumentBytes}).`, 'Reduce the payload or raise maxArgumentBytes.');
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const strings = [];
|
|
410
|
+
walkStrings(callArgs, '', strings);
|
|
411
|
+
const blob = strings.map((s) => s.value).join('\n');
|
|
412
|
+
const compactBlob = strings.map((s) => s.value).join('');
|
|
413
|
+
|
|
414
|
+
// 3. Every text/argument gets secret, PII and injection scrutiny. Scan the
|
|
415
|
+
// compact form too so a credential split across arguments cannot evade a
|
|
416
|
+
// pattern only because a newline was inserted.
|
|
417
|
+
inspectText(blob, p, add, `tool "${toolName}" (${server || 'unknown server'})`);
|
|
418
|
+
if (compactBlob !== blob) inspectText(compactBlob, p, add, `tool "${toolName}" (${server || 'unknown server'})`);
|
|
419
|
+
|
|
420
|
+
// 4. Filesystem scope (canonical paths; junctions/symlinks resolved).
|
|
421
|
+
const rootCanonical = canonicalRoot(projectRoot);
|
|
422
|
+
for (const { key, value } of strings) {
|
|
423
|
+
if (!PATH_KEY_RE.test(key)) continue;
|
|
424
|
+
if (/^https?:\/\//i.test(value)) continue;
|
|
425
|
+
if (!/[/\\]|\.(?:env|pem|key|json|ya?ml|toml|ini|conf|sql|db|txt|md|js|ts|py)$/i.test(value) && !path.isAbsolute(expandHome(value))) continue;
|
|
426
|
+
const resolved = canonicalPath(projectRoot, value);
|
|
427
|
+
const rel = normalizeSlashes(path.relative(rootCanonical, resolved));
|
|
428
|
+
if (matchesAny(value, p.deniedPaths) || matchesAny(rel, p.deniedPaths) || matchesAny(normalizeSlashes(resolved), p.deniedPaths)) {
|
|
429
|
+
add('block', 'path-denied', `Path "${value}" matches a denied path in policy.`, 'Credential stores are off-limits to agents. Remove the path from deniedPaths only if you truly intend to expose it.');
|
|
430
|
+
}
|
|
431
|
+
if (p.enforceProjectScope && !isInside(rootCanonical, resolved) && !matchesAny(resolved, p.allowedPaths) && !matchesAny(rel, p.allowedPaths)) {
|
|
432
|
+
const level = capability === 'fs.write' ? 'block' : 'warn';
|
|
433
|
+
add(level, 'path-outside-project', `Path "${value}" resolves outside the project root (${projectRoot}).`, 'Add an explicit allowedPaths entry if the agent must reach it.');
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// 5. URLs / egress.
|
|
438
|
+
const urls = [];
|
|
439
|
+
for (const { key, value } of strings) {
|
|
440
|
+
if (/^https?:\/\//i.test(value)) urls.push(value);
|
|
441
|
+
else if (/^(?:url|uri|endpoint|host|domain|webhook)$/i.test(key) && value) urls.push(value);
|
|
442
|
+
}
|
|
443
|
+
for (const url of urls) policyUrlCheck(url, p, add);
|
|
444
|
+
|
|
445
|
+
// 6. Commands.
|
|
446
|
+
if (capability === 'shell' || capability === 'code-exec') {
|
|
447
|
+
for (const { key, value } of strings) {
|
|
448
|
+
if (!COMMAND_KEY_RE.test(key) && capability !== 'shell') continue;
|
|
449
|
+
if (value.length < 2) continue;
|
|
450
|
+
const check = checkCommand(value);
|
|
451
|
+
if (check.blocked) {
|
|
452
|
+
add('block', 'dangerous-command', check.reason || 'Dangerous shell command blocked.', 'Use a scoped tool, or rewrite the command without the destructive/exfil component.');
|
|
453
|
+
const seenWarnings = new Set();
|
|
454
|
+
for (const v of (check.violations || []).slice(0, 3)) {
|
|
455
|
+
const label = v.reason || v.type || 'Shell command warning.';
|
|
456
|
+
if (seenWarnings.has(label) || label === check.reason) continue;
|
|
457
|
+
seenWarnings.add(label);
|
|
458
|
+
add('warn', `command-${v.type || 'warning'}`, label, null);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
// Egress policy applies to URLs embedded in shell commands too. Without
|
|
462
|
+
// this, a plain `curl https://host` bypasses the host allowlist.
|
|
463
|
+
for (const m of value.matchAll(/\bhttps?:\/\/[^\s"'<>]+/gi)) {
|
|
464
|
+
policyUrlCheck(m[0], p, add);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// 6b. Runtime package firewall — independent of the tool's capability name,
|
|
470
|
+
// because a "deploy" or "run" tool can still carry an install command.
|
|
471
|
+
for (const { value } of strings) {
|
|
472
|
+
if (value.length < 6) continue;
|
|
473
|
+
const installs = [
|
|
474
|
+
/(?:npm|pnpm|yarn|bun)\s+(?:i|install|add)\s+(?:--save\s+)?([@\w./-]+)/gi,
|
|
475
|
+
/(?:npx|bunx|pnpm\s+dlx)\s+(?:-y\s+|--yes\s+)?([@\w./-]+)/gi,
|
|
476
|
+
];
|
|
477
|
+
for (const re of installs) {
|
|
478
|
+
let m;
|
|
479
|
+
while ((m = re.exec(value)) !== null) {
|
|
480
|
+
const spec = m[1];
|
|
481
|
+
if (!spec || spec.startsWith('-')) continue;
|
|
482
|
+
const name = spec.startsWith('@') ? spec.split('@').slice(0, 2).join('@') : spec.split('@')[0];
|
|
483
|
+
const pkgCheck = checkPackage(name);
|
|
484
|
+
const bad = pkgCheck.risks.find((r) => r.action === 'block');
|
|
485
|
+
if (bad) {
|
|
486
|
+
add('block', 'malicious-package', `Package "${name}" looks malicious or typosquatted: ${bad.message}`, 'Verify the package on the registry before installing it.');
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
const warn = pkgCheck.risks.find((r) => r.severity === 'high');
|
|
490
|
+
if (warn) add('warn', 'risky-package', `Package "${name}": ${warn.message}`, 'Verify the package name and pin a version.');
|
|
491
|
+
const unpinned = !spec.includes('@') || (spec.startsWith('@') && !spec.slice(1).includes('@'));
|
|
492
|
+
if (unpinned) add('warn', 'unpinned-package', `Package "${name}" is installed without a version pin.`, 'Pin the version so the code cannot change between runs.');
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// 7. Destination-aware exfiltration: secrets + a network sink in one call.
|
|
498
|
+
if (urls.length && !p.allowSecretsInArgs) {
|
|
499
|
+
const leaks = scanForLeaks(blob);
|
|
500
|
+
if (leaks.secrets.length || leaks.namedSecrets.length) {
|
|
501
|
+
const host = hostOf(urls[0]) || urls[0];
|
|
502
|
+
if (!matchesAny(host, p.trustedHosts)) {
|
|
503
|
+
add('block', 'exfiltration-attempt', `Credentials plus an outbound destination (${host}) in one tool call — exfiltration shape.`, 'Separate credentials from network calls. Use a trusted host if this is intentional.');
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
let action = 'allow';
|
|
509
|
+
for (const v of violations) {
|
|
510
|
+
if (v.level === 'block') { action = 'block'; break; }
|
|
511
|
+
if (v.level === 'warn') action = 'warn';
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
const risk = violations.reduce((sum, v) => sum + (v.level === 'block' ? 35 : 8), 0);
|
|
515
|
+
|
|
516
|
+
return {
|
|
517
|
+
action,
|
|
518
|
+
blocked: action === 'block',
|
|
519
|
+
tool: toolName,
|
|
520
|
+
server: server || null,
|
|
521
|
+
capability,
|
|
522
|
+
risk: Math.min(100, risk),
|
|
523
|
+
violations,
|
|
524
|
+
reasons: violations.map((v) => v.message),
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function toolDefinitionHash(tool) {
|
|
529
|
+
const t = tool || {};
|
|
530
|
+
return crypto.createHash('sha256').update(JSON.stringify({
|
|
531
|
+
name: t.name,
|
|
532
|
+
description: t.description,
|
|
533
|
+
inputSchema: t.inputSchema,
|
|
534
|
+
})).digest('hex').slice(0, 16);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// Tool definitions are model-facing text. A poisoned description is an
|
|
538
|
+
// instruction the agent will read on every turn — inspect it like untrusted
|
|
539
|
+
// input, not like documentation.
|
|
540
|
+
function evaluateToolDefinition(tool, opts = {}) {
|
|
541
|
+
const currentHash = opts.hash || toolDefinitionHash(tool);
|
|
542
|
+
const t = tool || {};
|
|
543
|
+
const violations = [];
|
|
544
|
+
const add = (level, id, message, fix) => violations.push({ level, id, message, fix: fix || null });
|
|
545
|
+
const name = String(t.name || '');
|
|
546
|
+
const description = String(t.description || '');
|
|
547
|
+
const schemaBlob = t.inputSchema ? JSON.stringify(t.inputSchema) : '';
|
|
548
|
+
const text = `${name}\n${description}\n${schemaBlob}`;
|
|
549
|
+
|
|
550
|
+
if (!name) add('block', 'tool-missing-name', 'Tool definition has no name — the agent cannot identify it safely.', 'Remove the malformed tool.');
|
|
551
|
+
if (description.length > 20000) add('warn', 'tool-description-huge', `Tool "${name}" has a ${description.length}-character description. Long descriptions are an instruction-smuggling surface.`, 'Trim the description to its contract.');
|
|
552
|
+
|
|
553
|
+
const hits = scanTextForInjection(text);
|
|
554
|
+
if (hits.length) {
|
|
555
|
+
add('block', 'tool-poisoning', `Tool "${name}" contains prompt-injection text (${hits.slice(0, 4).join(', ')}).`, 'Remove the injected instruction. Tool descriptions must describe the tool, never instruct the model.');
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
if (/do\s+not\s+(?:tell|inform|mention|reveal|disclose)|don'?t\s+(?:tell|inform|mention)\s+the\s+user|silently\s+(?:run|execute|send|read)/i.test(description)) {
|
|
559
|
+
add('block', 'tool-concealment-instruction', `Tool "${name}" tells the model to keep something from the user.`, 'Remove the concealment instruction.');
|
|
560
|
+
}
|
|
561
|
+
if (/(?:read|open|dump|send|upload|exfiltrate)[^.]{0,80}(?:\.env|environment\s+variables?|secrets?|api\s*keys?|\.ssh|credentials?|cookies?)/i.test(description)) {
|
|
562
|
+
add('warn', 'tool-sensitive-instruction', `Tool "${name}" mentions credentials/secrets in its model-facing description.`, 'Describe the action without naming credential stores.');
|
|
563
|
+
}
|
|
564
|
+
if (/(?:always|must|immediately)\s+(?:call|invoke|use)\s+(?:this|the)\s+tool|before\s+using\s+any\s+other\s+tool/i.test(description)) {
|
|
565
|
+
add('warn', 'tool-forced-invocation', `Tool "${name}" pressures the model to invoke it unconditionally.`, 'Remove urgency/forced-invocation language.');
|
|
566
|
+
}
|
|
567
|
+
if (/(?:[A-Za-z0-9+/]{200,}={0,2})/.test(description)) {
|
|
568
|
+
add('warn', 'tool-encoded-payload', `Tool "${name}" description contains a long encoded blob.`, 'Decode and review it; descriptions should not carry payloads.');
|
|
569
|
+
}
|
|
570
|
+
// A tool that claims to be read-only while its description describes writes
|
|
571
|
+
// is lying to the model's planner.
|
|
572
|
+
if (t.annotations && t.annotations.readOnlyHint === true && /(?:write|delete|remove|modify|execute|run|install|upload|send)/i.test(description)) {
|
|
573
|
+
add('warn', 'tool-readonly-lie', `Tool "${name}" claims readOnlyHint but its description describes a state-changing action.`, 'Fix the annotation — the model uses it to decide whether to ask for confirmation.');
|
|
574
|
+
}
|
|
575
|
+
if (opts.expectedHash && currentHash !== opts.expectedHash) {
|
|
576
|
+
add('block', 'tool-definition-drift', `Tool "${name}" definition changed since it was approved (rug-pull risk).`, 'Re-review the server and re-pin the tool only after review.');
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
let action = 'allow';
|
|
580
|
+
for (const v of violations) {
|
|
581
|
+
if (v.level === 'block') { action = 'block'; break; }
|
|
582
|
+
if (v.level === 'warn') action = 'warn';
|
|
583
|
+
}
|
|
584
|
+
return { action, blocked: action === 'block', tool: name, violations, risk: Math.min(100, violations.reduce((s, v) => s + (v.level === 'block' ? 40 : 10), 0)) };
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// Rate limiter shared by the proxy. Mutates `session` so a long-lived firewall
|
|
588
|
+
// process can enforce a call budget per minute.
|
|
589
|
+
function checkRateLimit(session, policy, now = Date.now()) {
|
|
590
|
+
if (!session) return { allowed: true, remaining: null };
|
|
591
|
+
const limit = Number(policy.maxCallsPerMinute || 0);
|
|
592
|
+
if (!limit) return { allowed: true, remaining: null };
|
|
593
|
+
if (!session.rateWindow || now - session.rateWindow.start >= 60000) {
|
|
594
|
+
session.rateWindow = { start: now, count: 0 };
|
|
595
|
+
}
|
|
596
|
+
session.rateWindow.count++;
|
|
597
|
+
const allowed = session.rateWindow.count <= limit;
|
|
598
|
+
return { allowed, remaining: Math.max(0, limit - session.rateWindow.count), count: session.rateWindow.count, limit };
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function describePolicy(policy, source) {
|
|
602
|
+
const p = policy || DEFAULT_POLICY;
|
|
603
|
+
return {
|
|
604
|
+
source: source || null,
|
|
605
|
+
defaultAction: p.defaultAction,
|
|
606
|
+
toolRules: p.toolRules.length,
|
|
607
|
+
denyTools: p.denyTools,
|
|
608
|
+
approvalRequired: p.approvalRequired,
|
|
609
|
+
blockedCapabilities: p.blockedCapabilities,
|
|
610
|
+
enforceProjectScope: !!p.enforceProjectScope,
|
|
611
|
+
allowedPaths: p.allowedPaths,
|
|
612
|
+
deniedPaths: p.deniedPaths.length,
|
|
613
|
+
allowedHosts: p.allowedHosts,
|
|
614
|
+
deniedHosts: p.deniedHosts,
|
|
615
|
+
blockExternalNetwork: !!p.blockExternalNetwork,
|
|
616
|
+
secretScan: !!p.secretScan,
|
|
617
|
+
piiMode: p.piiMode,
|
|
618
|
+
blockPromptInjection: !!p.blockPromptInjection,
|
|
619
|
+
pinToolDefinitions: !!p.pinToolDefinitions,
|
|
620
|
+
scrubToolResults: !!p.scrubToolResults,
|
|
621
|
+
blockToolResultInjection: !!p.blockToolResultInjection,
|
|
622
|
+
maxArgumentBytes: p.maxArgumentBytes,
|
|
623
|
+
maxCallsPerMinute: p.maxCallsPerMinute,
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
module.exports = {
|
|
628
|
+
DEFAULT_POLICY,
|
|
629
|
+
POLICY_FILES,
|
|
630
|
+
loadPolicy,
|
|
631
|
+
mergePolicy,
|
|
632
|
+
evaluateToolCall,
|
|
633
|
+
evaluateToolDefinition,
|
|
634
|
+
capabilityOf,
|
|
635
|
+
checkRateLimit,
|
|
636
|
+
describePolicy,
|
|
637
|
+
matchesGlob,
|
|
638
|
+
matchesAny,
|
|
639
|
+
toolDefinitionHash,
|
|
640
|
+
sanitizeOutbound,
|
|
641
|
+
scanForLeaks,
|
|
642
|
+
};
|