@strixgov/mcp-proxy 0.2.4 → 0.3.0
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/CHANGELOG.md +92 -1
- package/README.md +277 -38
- package/bin/strix-mcp-proxy.mjs +100 -5
- package/examples/controlled-launcher/README.md +33 -0
- package/examples/controlled-launcher/acceptance.mjs +337 -0
- package/examples/controlled-launcher/agent-client.mjs +18 -0
- package/examples/controlled-launcher/approval-relay.mjs +19 -0
- package/examples/controlled-launcher/approver.mjs +27 -0
- package/examples/controlled-launcher/authorizer.mjs +73 -0
- package/examples/controlled-launcher/bridge-client.mjs +8 -0
- package/examples/controlled-launcher/destination.mjs +18 -0
- package/examples/controlled-launcher/executor.mjs +74 -0
- package/examples/controlled-launcher/kernel-authority/acceptance.mjs +627 -0
- package/examples/controlled-launcher/kernel-authority/broker.mjs +83 -0
- package/examples/controlled-launcher/kernel-authority/derive.mjs +12 -0
- package/examples/controlled-launcher/kernel-authority/executor.mjs +105 -0
- package/examples/controlled-launcher/kernel-authority/reconcile.mjs +43 -0
- package/examples/controlled-launcher/kernel-authority/shim.mjs +38 -0
- package/examples/controlled-launcher/kernel-authority/signing-provider.mjs +137 -0
- package/examples/controlled-launcher/kernel-authority/strix-approver.mjs +73 -0
- package/examples/controlled-launcher/lib.mjs +63 -0
- package/examples/controlled-launcher/make-config.mjs +16 -0
- package/examples/controlled-launcher/proxy-host.mjs +19 -0
- package/examples/controlled-launcher/reconcile.mjs +30 -0
- package/examples/controlled-launcher/shim.mjs +32 -0
- package/examples/github-reference/README.md +1 -1
- package/examples/github-reference/acceptance.mjs +10 -3
- package/examples/github-reference/claims-matrix.md +3 -3
- package/examples/github-reference/package-lock.json +48 -44
- package/examples/github-reference/package.json +4 -4
- package/examples/github-reference/reuse-inventory.md +4 -4
- package/examples/synthetic-server/proxy-config.json +16 -0
- package/examples/synthetic-server/quickstart.mjs +98 -0
- package/examples/synthetic-server/server.mjs +54 -0
- package/package.json +5 -4
- package/src/config.mjs +152 -2
- package/src/content-guard.mjs +432 -0
- package/src/http-upstream.mjs +431 -0
- package/src/index.mjs +11 -2
- package/src/proxy.mjs +241 -33
- package/src/tool-guard.mjs +183 -0
- package/src/types.d.ts +83 -1
- package/test/content-guard-hardening.test.mjs +159 -0
- package/test/content-guard.test.mjs +387 -0
- package/test/http-upstream-config.test.mjs +115 -0
- package/test/http-upstream-e2e.test.mjs +279 -0
- package/test/http-upstream.test.mjs +304 -0
- package/test/synthetic-quickstart.test.mjs +44 -0
- package/test/tool-guard.test.mjs +243 -0
- package/test/validate-cli.test.mjs +171 -0
package/src/config.mjs
CHANGED
|
@@ -19,6 +19,17 @@
|
|
|
19
19
|
* "keyPath": "~/.strix-mcp-proxy/my-server/keys"
|
|
20
20
|
* }
|
|
21
21
|
*
|
|
22
|
+
* An HTTP upstream replaces `command`/`args` with `url`:
|
|
23
|
+
*
|
|
24
|
+
* "upstream": {
|
|
25
|
+
* "url": "https://mcp.example.com/mcp",
|
|
26
|
+
* "headers": { "Authorization": { "fromEnv": "EXAMPLE_TOKEN", "prefix": "Bearer " } },
|
|
27
|
+
* "timeoutMs": 60000
|
|
28
|
+
* }
|
|
29
|
+
*
|
|
30
|
+
* Credential-shaped header values must use `fromEnv`; a literal value for
|
|
31
|
+
* such a header is refused at load time.
|
|
32
|
+
*
|
|
22
33
|
* `keyPath` (optional): directory for the persistent Ed25519 signing key.
|
|
23
34
|
* When present, the proxy calls loadOrCreateSigningKey({ keyPath }) on startup:
|
|
24
35
|
* - If the key files don't exist they are generated + written there.
|
|
@@ -39,6 +50,8 @@
|
|
|
39
50
|
import fs from "node:fs/promises";
|
|
40
51
|
import path from "node:path";
|
|
41
52
|
import os from "node:os";
|
|
53
|
+
import { validateHttpUpstream } from "./http-upstream.mjs";
|
|
54
|
+
import { compileArgumentRules, ARGUMENT_MODES, RESULT_MODES } from "./content-guard.mjs";
|
|
42
55
|
|
|
43
56
|
/**
|
|
44
57
|
* @param {string} filePath
|
|
@@ -135,8 +148,24 @@ function validateConfig(cfg, abs) {
|
|
|
135
148
|
if (!cfg.upstream || typeof cfg.upstream !== "object") {
|
|
136
149
|
throw new Error(`loadConfig: '${abs}' is missing 'upstream' object`);
|
|
137
150
|
}
|
|
138
|
-
|
|
139
|
-
|
|
151
|
+
const hasCommand = typeof cfg.upstream.command === "string" && cfg.upstream.command !== "";
|
|
152
|
+
const hasUrl = typeof cfg.upstream.url === "string" && cfg.upstream.url !== "";
|
|
153
|
+
if (hasCommand === hasUrl) {
|
|
154
|
+
throw new Error(
|
|
155
|
+
`loadConfig: '${abs}' needs exactly one of 'upstream.command' (stdio upstream) or 'upstream.url' (HTTP upstream)`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
if (hasUrl) {
|
|
159
|
+
// Full validation (https, origins, literal-credential refusal) happens
|
|
160
|
+
// here so a bad config fails at load time, before anything connects.
|
|
161
|
+
try {
|
|
162
|
+
validateHttpUpstream(cfg.upstream);
|
|
163
|
+
} catch (err) {
|
|
164
|
+
throw new Error(`loadConfig: '${abs}' ${err.message}`);
|
|
165
|
+
}
|
|
166
|
+
if (cfg.upstream.args !== undefined || cfg.upstream.env !== undefined) {
|
|
167
|
+
throw new Error(`loadConfig: '${abs}' 'upstream.args' and 'upstream.env' apply only to a 'command' upstream`);
|
|
168
|
+
}
|
|
140
169
|
}
|
|
141
170
|
if (cfg.upstream.args !== undefined && !Array.isArray(cfg.upstream.args)) {
|
|
142
171
|
throw new Error(`loadConfig: '${abs}' 'upstream.args' must be an array of strings if present`);
|
|
@@ -144,6 +173,51 @@ function validateConfig(cfg, abs) {
|
|
|
144
173
|
if (cfg.policy !== undefined && (typeof cfg.policy !== "object" || cfg.policy === null)) {
|
|
145
174
|
throw new Error(`loadConfig: '${abs}' 'policy' must be an object if present`);
|
|
146
175
|
}
|
|
176
|
+
if (cfg.toolPinning !== undefined && !["block", "warn", "off"].includes(cfg.toolPinning)) {
|
|
177
|
+
throw new Error(`loadConfig: '${abs}' 'toolPinning' must be "block", "warn" or "off" if present`);
|
|
178
|
+
}
|
|
179
|
+
for (const flagName of ["hideDeniedTools", "repinTools"]) {
|
|
180
|
+
if (cfg[flagName] !== undefined && typeof cfg[flagName] !== "boolean") {
|
|
181
|
+
throw new Error(`loadConfig: '${abs}' '${flagName}' must be a boolean if present`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (cfg.auditLog !== undefined && typeof cfg.auditLog !== "boolean" && (typeof cfg.auditLog !== "string" || cfg.auditLog === "")) {
|
|
185
|
+
throw new Error(`loadConfig: '${abs}' 'auditLog' must be true, or a file path, if present`);
|
|
186
|
+
}
|
|
187
|
+
if (cfg.rateLimits !== undefined) {
|
|
188
|
+
if (typeof cfg.rateLimits !== "object" || cfg.rateLimits === null || Array.isArray(cfg.rateLimits)) {
|
|
189
|
+
throw new Error(`loadConfig: '${abs}' 'rateLimits' must be an object if present`);
|
|
190
|
+
}
|
|
191
|
+
for (const [key, rule] of Object.entries(cfg.rateLimits)) {
|
|
192
|
+
if (!rule || !Number.isInteger(rule.windowMs) || rule.windowMs <= 0 || !Number.isInteger(rule.max) || rule.max <= 0) {
|
|
193
|
+
throw new Error(`loadConfig: '${abs}' 'rateLimits["${key}"]' needs positive integer windowMs and max`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (cfg.secretScanning !== undefined && cfg.secretScanning !== false) {
|
|
198
|
+
const ss = cfg.secretScanning;
|
|
199
|
+
if (!ss || typeof ss !== "object" || Array.isArray(ss)) {
|
|
200
|
+
throw new Error(`loadConfig: '${abs}' 'secretScanning' must be false or an object if present`);
|
|
201
|
+
}
|
|
202
|
+
if (ss.arguments !== undefined && !ARGUMENT_MODES.includes(ss.arguments)) {
|
|
203
|
+
throw new Error(`loadConfig: '${abs}' 'secretScanning.arguments' must be one of ${ARGUMENT_MODES.join(", ")}`);
|
|
204
|
+
}
|
|
205
|
+
if (ss.results !== undefined && !RESULT_MODES.includes(ss.results)) {
|
|
206
|
+
throw new Error(`loadConfig: '${abs}' 'secretScanning.results' must be one of ${RESULT_MODES.join(", ")}`);
|
|
207
|
+
}
|
|
208
|
+
for (const k of Object.keys(ss)) {
|
|
209
|
+
if (k !== "arguments" && k !== "results") {
|
|
210
|
+
throw new Error(`loadConfig: '${abs}' 'secretScanning.${k}' is not a known setting (expected arguments, results)`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (cfg.argumentRules !== undefined) {
|
|
215
|
+
try {
|
|
216
|
+
compileArgumentRules(cfg.argumentRules);
|
|
217
|
+
} catch (err) {
|
|
218
|
+
throw new Error(`loadConfig: '${abs}' ${err.message}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
147
221
|
if (cfg.keyPath !== undefined && typeof cfg.keyPath !== "string") {
|
|
148
222
|
throw new Error(`loadConfig: '${abs}' 'keyPath' must be a string if present`);
|
|
149
223
|
}
|
|
@@ -176,3 +250,79 @@ function validateConfig(cfg, abs) {
|
|
|
176
250
|
}
|
|
177
251
|
}
|
|
178
252
|
}
|
|
253
|
+
|
|
254
|
+
// ─── validation report (no network, no upstream) ──────────────────────────
|
|
255
|
+
|
|
256
|
+
/** Every top-level key the proxy reads. Anything else in a config file is ignored at runtime. */
|
|
257
|
+
export const KNOWN_CONFIG_KEYS = Object.freeze([
|
|
258
|
+
"serverId", "upstream", "upstreamCredentials", "capabilities", "policy", "approval",
|
|
259
|
+
"storagePath", "keyPath", "toolPinning", "hideDeniedTools", "repinTools", "rateLimits",
|
|
260
|
+
"secretScanning", "argumentRules", "auditLog",
|
|
261
|
+
]);
|
|
262
|
+
|
|
263
|
+
/** Top-level keys the proxy would silently ignore (usually a typo in a security setting). */
|
|
264
|
+
export function unknownConfigKeys(cfg) {
|
|
265
|
+
return Object.keys(cfg ?? {}).filter((k) => !k.startsWith("_") && !KNOWN_CONFIG_KEYS.includes(k));
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* A description of what a config would do, with every credential left out:
|
|
270
|
+
* header values, environment values and upstream arguments are never printed.
|
|
271
|
+
* Used by `strix-mcp-proxy --validate`. Pure; connects to nothing.
|
|
272
|
+
*
|
|
273
|
+
* @param {object} cfg a config that already passed loadConfig
|
|
274
|
+
* @param {Array<object> | undefined} capabilities resolved capability list, if any
|
|
275
|
+
*/
|
|
276
|
+
export function describeConfig(cfg, capabilities) {
|
|
277
|
+
const upstream = cfg.upstream ?? {};
|
|
278
|
+
const isHttp = typeof upstream.url === "string";
|
|
279
|
+
let upstreamSummary;
|
|
280
|
+
if (isHttp) {
|
|
281
|
+
let origin = "(unparseable)";
|
|
282
|
+
try { origin = new URL(upstream.url).origin; } catch { /* validated at load; keep the placeholder */ }
|
|
283
|
+
upstreamSummary = {
|
|
284
|
+
transport: "http",
|
|
285
|
+
origin,
|
|
286
|
+
headerNames: Object.keys(upstream.headers ?? {}),
|
|
287
|
+
allowPrivateNetwork: upstream.allowPrivateNetwork === true,
|
|
288
|
+
};
|
|
289
|
+
} else {
|
|
290
|
+
upstreamSummary = { transport: "stdio", command: upstream.command, argCount: (upstream.args ?? []).length };
|
|
291
|
+
}
|
|
292
|
+
const approval = cfg.approval ?? {};
|
|
293
|
+
const approvalMode = approval.enabled
|
|
294
|
+
? approval.autoApprove || approval.type === "auto" ? "auto-approve (every approval is granted)" : approval.type ?? "terminal"
|
|
295
|
+
: "disabled (every approval-required call is denied)";
|
|
296
|
+
const sc = cfg.secretScanning === false ? { arguments: "off", results: "off" } : cfg.secretScanning ?? {};
|
|
297
|
+
const warnings = [];
|
|
298
|
+
const policyDefault = cfg.policy?.default ?? "DENY";
|
|
299
|
+
if (policyDefault === "ALLOW") warnings.push("policy.default is ALLOW: a tool no capability classifies is allowed. DENY is the safe default.");
|
|
300
|
+
if (approval.enabled && (approval.autoApprove || approval.type === "auto")) warnings.push("approval is auto: every approval-required call is approved without a person. Use for demos only.");
|
|
301
|
+
if (approval.enabled && (approval.type === undefined || approval.type === "terminal")) warnings.push("approval.type is terminal: it fails closed when the proxy is started by a client such as Claude Desktop (no TTY). Use \"file\" there.");
|
|
302
|
+
if (cfg.toolPinning === "off") warnings.push("toolPinning is off: a tool whose definition changes after review is not caught.");
|
|
303
|
+
if ((sc.arguments ?? "block") === "off") warnings.push("secretScanning.arguments is off: credentials in tool arguments are not checked.");
|
|
304
|
+
if (isHttp && upstream.allowPrivateNetwork === true) warnings.push("upstream.allowPrivateNetwork admits private-range addresses: only set it for a server you run on your own network.");
|
|
305
|
+
if (!capabilities || capabilities.length === 0) warnings.push("no capabilities are classified: every tool falls to policy.default.");
|
|
306
|
+
const unsetEnv = Object.values(upstream.headers ?? {}).filter(
|
|
307
|
+
(h) => h && typeof h === "object" && typeof h.fromEnv === "string" && !process.env[h.fromEnv],
|
|
308
|
+
).length;
|
|
309
|
+
if (unsetEnv > 0) warnings.push(`${unsetEnv} upstream header value(s) are read from the environment and not set in this shell: startup refuses a missing one.`);
|
|
310
|
+
if (cfg.auditLog === true && cfg.storagePath === null) warnings.push("auditLog is true but storagePath is null: startup refuses it. Give auditLog a file path, or set a storagePath.");
|
|
311
|
+
if (typeof cfg.auditLog === "string" && !/^(~[\\/]|[\\/]|[A-Za-z]:[\\/])/.test(cfg.auditLog)) warnings.push("auditLog is a relative path: startup refuses it. Use an absolute path or one that starts with ~/.");
|
|
312
|
+
for (const k of unknownConfigKeys(cfg)) warnings.push(`unknown config key '${k}' is ignored at runtime (typo?).`);
|
|
313
|
+
return {
|
|
314
|
+
serverId: cfg.serverId ?? "proxy",
|
|
315
|
+
upstream: upstreamSummary,
|
|
316
|
+
capabilityCount: capabilities?.length ?? 0,
|
|
317
|
+
policyDefault,
|
|
318
|
+
approval: approvalMode,
|
|
319
|
+
storagePath: cfg.storagePath === null ? "(ephemeral: nothing is kept)" : cfg.storagePath ?? "(default ~/.strix-mcp-proxy/<serverId>)",
|
|
320
|
+
toolPinning: cfg.toolPinning ?? "block",
|
|
321
|
+
hideDeniedTools: cfg.hideDeniedTools === true,
|
|
322
|
+
auditLog: cfg.auditLog === undefined || cfg.auditLog === false ? "off" : typeof cfg.auditLog === "string" ? "file" : "storagePath",
|
|
323
|
+
secretScanning: { arguments: sc.arguments ?? "block", results: sc.results ?? "warn" },
|
|
324
|
+
argumentRuleTools: Object.keys(cfg.argumentRules ?? {}),
|
|
325
|
+
rateLimitedTools: Object.keys(cfg.rateLimits ?? {}),
|
|
326
|
+
warnings,
|
|
327
|
+
};
|
|
328
|
+
}
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content guard: credential scanning of tool arguments and results, and
|
|
3
|
+
* argument rules. Both are checks on what a call CARRIES, which the policy
|
|
4
|
+
* engine (capability and risk class only) does not see.
|
|
5
|
+
*
|
|
6
|
+
* Secret scanning
|
|
7
|
+
* - Arguments, outbound (client -> upstream). Mode `block` refuses a call
|
|
8
|
+
* whose arguments contain a credential-shaped string, before the
|
|
9
|
+
* upstream is contacted, with a signed DENY (reason SECRET_IN_ARGUMENTS).
|
|
10
|
+
* `warn` reports and allows. `off` disables. Default: `block`.
|
|
11
|
+
* - Results, inbound (upstream -> client). Mode `redact` replaces matches
|
|
12
|
+
* with `[REDACTED:<pattern>]` before the client sees them; `warn` reports
|
|
13
|
+
* only; `off` disables. Default: `warn`, because silently rewriting a
|
|
14
|
+
* tool's output can break a legitimate workflow (a secrets-manager tool
|
|
15
|
+
* is supposed to return a secret) and the operator should choose that.
|
|
16
|
+
* - The patterns are high-precision credential FORMATS (cloud, source host,
|
|
17
|
+
* chat, payment, AI-provider keys, private-key blocks, JWTs). This is not
|
|
18
|
+
* a data-loss-prevention product: it does not find a password in prose,
|
|
19
|
+
* a card number, personal data, or a secret in a format not listed. A
|
|
20
|
+
* clean scan means "no listed format found", never "no secret present".
|
|
21
|
+
* - The matched text is never returned, logged or placed in a receipt;
|
|
22
|
+
* findings carry the pattern name and the JSON path only.
|
|
23
|
+
* - Fail closed: a value too deep or too large to scan completely is
|
|
24
|
+
* reported as `scan_limit_exceeded`, which `block` treats as a finding.
|
|
25
|
+
*
|
|
26
|
+
* Argument rules (`argumentRules`)
|
|
27
|
+
* Per tool name (or `*` for every tool), a list of constraints on the call's
|
|
28
|
+
* arguments. A violated rule refuses the call with a signed DENY (reason
|
|
29
|
+
* ARGUMENT_RULE_VIOLATION). Rules can only make a call stricter: they never
|
|
30
|
+
* turn a policy DENY or approval requirement into a pass.
|
|
31
|
+
* Rule fields: `path` (dot path into the arguments) plus exactly one of
|
|
32
|
+
* `required`, `max`, `min`, `maxLength`, `in` (array), `pattern` (regex the
|
|
33
|
+
* value must match), `notPattern` (regex it must not match), `withinPath`
|
|
34
|
+
* (the string is a filesystem path that, once normalized, stays inside the
|
|
35
|
+
* given directory; `..` escapes and backslash tricks are refused).
|
|
36
|
+
* A rule on a path that is absent passes, except `required`.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import path from "node:path";
|
|
40
|
+
|
|
41
|
+
export const SECRET_IN_ARGUMENTS = "SECRET_IN_ARGUMENTS";
|
|
42
|
+
export const ARGUMENT_RULE_VIOLATION = "ARGUMENT_RULE_VIOLATION";
|
|
43
|
+
export const ARGUMENT_MODES = Object.freeze(["block", "warn", "off"]);
|
|
44
|
+
export const RESULT_MODES = Object.freeze(["redact", "warn", "off"]);
|
|
45
|
+
|
|
46
|
+
const MAX_DEPTH = 32;
|
|
47
|
+
const MAX_NODES = 10_000;
|
|
48
|
+
const MAX_STRING_CHARS = 1_000_000;
|
|
49
|
+
|
|
50
|
+
/** Credential formats. Each is anchored on a distinctive prefix or block marker. */
|
|
51
|
+
export const SECRET_PATTERNS = Object.freeze([
|
|
52
|
+
// Leading boundary: no adjacent letter or digit (an underscore or hyphen before a key is a delimiter, so
|
|
53
|
+
// `TOKEN_ghp_...` and `secret_AKIA...` are found). Patterns with an open-ended class also exclude `_` and
|
|
54
|
+
// `-` before the prefix, so only one match can start per run of token characters (linear time).
|
|
55
|
+
{ name: "aws_access_key_id", re: /(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g },
|
|
56
|
+
{ name: "github_token", re: /(?<![A-Za-z0-9])gh[pousr]_[A-Za-z0-9]{36,}/g },
|
|
57
|
+
{ name: "github_fine_grained_token", re: /(?<![A-Za-z0-9])github_pat_[A-Za-z0-9_]{50,}/g },
|
|
58
|
+
{ name: "gitlab_token", re: /(?<![A-Za-z0-9_-])glpat-[A-Za-z0-9_-]{20,}/g },
|
|
59
|
+
{ name: "slack_token", re: /(?<![A-Za-z0-9_-])xox[abprs]-[A-Za-z0-9-]{10,}/g },
|
|
60
|
+
{ name: "stripe_key", re: /(?<![A-Za-z0-9])[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/g },
|
|
61
|
+
{ name: "stripe_webhook_secret", re: /(?<![A-Za-z0-9])whsec_[A-Za-z0-9]{24,}/g },
|
|
62
|
+
{ name: "google_api_key", re: /(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}/g },
|
|
63
|
+
{ name: "google_oauth_token", re: /(?<![A-Za-z0-9_-])ya29\.[A-Za-z0-9_-]{20,}/g },
|
|
64
|
+
{ name: "anthropic_api_key", re: /(?<![A-Za-z0-9_-])sk-ant-[A-Za-z0-9_-]{20,}/g },
|
|
65
|
+
{ name: "openai_api_key", re: /(?<![A-Za-z0-9_-])sk-(?:proj-|svcacct-)[A-Za-z0-9_-]{32,}|(?<![A-Za-z0-9_-])sk-[A-Za-z0-9]{48}(?![A-Za-z0-9])/g },
|
|
66
|
+
{ name: "huggingface_token", re: /(?<![A-Za-z0-9])hf_[A-Za-z0-9]{34,}/g },
|
|
67
|
+
{ name: "sendgrid_key", re: /(?<![A-Za-z0-9_-])SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g },
|
|
68
|
+
{ name: "npm_token", re: /(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g },
|
|
69
|
+
// From the BEGIN line through the END line; with no END line, to the end of the text, so key material
|
|
70
|
+
// is never left behind a redacted header.
|
|
71
|
+
{ name: "private_key_block", re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----|$)/g },
|
|
72
|
+
{ name: "jwt", re: /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*/g },
|
|
73
|
+
// scheme://user:password@host, the form database and broker URLs take.
|
|
74
|
+
{ name: "url_with_password", re: /(?<![A-Za-z0-9+.-])[a-z][a-z0-9+.-]{1,20}:\/\/[^\s:\/@]{1,100}:[^\s@\/]{3,200}@/g },
|
|
75
|
+
]);
|
|
76
|
+
|
|
77
|
+
// ─── secret scanning ───────────────────────────────────────────────────────
|
|
78
|
+
|
|
79
|
+
/** Pattern names found in one string. Never returns the matched text. */
|
|
80
|
+
function patternsIn(text) {
|
|
81
|
+
const found = [];
|
|
82
|
+
for (const { name, re } of SECRET_PATTERNS) {
|
|
83
|
+
re.lastIndex = 0;
|
|
84
|
+
if (re.test(text)) found.push(name);
|
|
85
|
+
re.lastIndex = 0;
|
|
86
|
+
}
|
|
87
|
+
return found;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Walk a JSON value and report every credential-shaped string.
|
|
92
|
+
* @param {unknown} value
|
|
93
|
+
* @returns {{ findings: Array<{ pattern: string, path: string }>, complete: boolean }}
|
|
94
|
+
*/
|
|
95
|
+
export function scanValue(value) {
|
|
96
|
+
const findings = [];
|
|
97
|
+
let nodes = 0;
|
|
98
|
+
let complete = true;
|
|
99
|
+
const walk = (v, p, depth) => {
|
|
100
|
+
if (nodes++ > MAX_NODES || depth > MAX_DEPTH) {
|
|
101
|
+
complete = false;
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (typeof v === "string") {
|
|
105
|
+
if (v.length > MAX_STRING_CHARS) {
|
|
106
|
+
complete = false;
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
for (const name of patternsIn(v)) findings.push({ pattern: name, path: p || "$" });
|
|
110
|
+
} else if (Array.isArray(v)) {
|
|
111
|
+
v.forEach((item, i) => walk(item, `${p}[${i}]`, depth + 1));
|
|
112
|
+
} else if (v && typeof v === "object") {
|
|
113
|
+
for (const [k, item] of Object.entries(v)) {
|
|
114
|
+
// Keys can carry a credential too (a map keyed by token).
|
|
115
|
+
for (const name of patternsIn(k)) findings.push({ pattern: name, path: p ? `${p}.<key>` : "<key>" });
|
|
116
|
+
walk(item, p ? `${p}.${patternsIn(k).length ? "<key>" : k}` : patternsIn(k).length ? "<key>" : k, depth + 1);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
walk(value, "", 0);
|
|
121
|
+
return { findings, complete };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Replace every credential-shaped substring in a string. */
|
|
125
|
+
export function redactText(text) {
|
|
126
|
+
let out = text;
|
|
127
|
+
const patterns = new Set();
|
|
128
|
+
let count = 0;
|
|
129
|
+
for (const { name, re } of SECRET_PATTERNS) {
|
|
130
|
+
re.lastIndex = 0;
|
|
131
|
+
out = out.replace(re, () => {
|
|
132
|
+
patterns.add(name);
|
|
133
|
+
count += 1;
|
|
134
|
+
return `[REDACTED:${name}]`;
|
|
135
|
+
});
|
|
136
|
+
re.lastIndex = 0;
|
|
137
|
+
}
|
|
138
|
+
return { text: out, patterns: [...patterns], count };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Deep copy of a JSON value with credential-shaped substrings redacted.
|
|
143
|
+
* Used so a receipt or audit event never carries the credential.
|
|
144
|
+
*/
|
|
145
|
+
export function redactValue(value) {
|
|
146
|
+
const patterns = new Set();
|
|
147
|
+
let count = 0;
|
|
148
|
+
let complete = true;
|
|
149
|
+
let nodes = 0;
|
|
150
|
+
const walk = (v, depth) => {
|
|
151
|
+
if (nodes++ > MAX_NODES || depth > MAX_DEPTH) {
|
|
152
|
+
// Never hand back what was not scanned: it may hold the credential.
|
|
153
|
+
complete = false;
|
|
154
|
+
return "[UNSCANNED:limit]";
|
|
155
|
+
}
|
|
156
|
+
if (typeof v === "string") {
|
|
157
|
+
if (v.length > MAX_STRING_CHARS) {
|
|
158
|
+
complete = false;
|
|
159
|
+
return "[UNSCANNED:string-too-large]";
|
|
160
|
+
}
|
|
161
|
+
const r = redactText(v);
|
|
162
|
+
r.patterns.forEach((n) => patterns.add(n));
|
|
163
|
+
count += r.count;
|
|
164
|
+
return r.text;
|
|
165
|
+
}
|
|
166
|
+
if (Array.isArray(v)) return v.map((x) => walk(x, depth + 1));
|
|
167
|
+
if (v && typeof v === "object") {
|
|
168
|
+
const out = {};
|
|
169
|
+
for (const [k, item] of Object.entries(v)) {
|
|
170
|
+
const rk = redactText(k);
|
|
171
|
+
rk.patterns.forEach((n) => patterns.add(n));
|
|
172
|
+
count += rk.count;
|
|
173
|
+
let key = rk.text;
|
|
174
|
+
// Two redacted keys must not overwrite each other, and `__proto__` must stay an own key.
|
|
175
|
+
for (let n = 2; Object.prototype.hasOwnProperty.call(out, key); n += 1) key = `${rk.text}#${n}`;
|
|
176
|
+
Object.defineProperty(out, key, { value: walk(item, depth + 1), enumerable: true, writable: true, configurable: true });
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
return v;
|
|
181
|
+
};
|
|
182
|
+
const value2 = walk(value, 0);
|
|
183
|
+
return { value: value2, patterns: [...patterns], count, complete };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ─── argument rules ────────────────────────────────────────────────────────
|
|
187
|
+
|
|
188
|
+
const RULE_KINDS = ["required", "max", "min", "maxLength", "in", "pattern", "notPattern", "withinPath"];
|
|
189
|
+
const REGEX_INPUT_CAP = 1_000;
|
|
190
|
+
// A group that holds a quantifier and is itself quantified (`(a+)+`, `(\w+\s?)*`) can take exponential time
|
|
191
|
+
// on a hostile string. Refused when the rule is compiled; the length cap above bounds the rest.
|
|
192
|
+
// Also refused: a quantified group that contains `|` (`(a|a)*`, `(a|aa)+`, `(\w|\d)+`), where the branches
|
|
193
|
+
// overlap. Write it as a character class (`[ab]+`) or without the repeat. This is a heuristic, not a proof of
|
|
194
|
+
// safety: patterns such as `\d+\d+` still run in polynomial time.
|
|
195
|
+
const NESTED_QUANTIFIER = /\((?:[^()\\]|\\.)*[+*](?:[^()\\]|\\.)*\)[+*{]|\((?:[^()\\]|\\.)*\|(?:[^()\\]|\\.)*\)[+*{]/;
|
|
196
|
+
|
|
197
|
+
/** Validate and compile `argumentRules`. Throws with the offending location. */
|
|
198
|
+
export function compileArgumentRules(spec) {
|
|
199
|
+
if (spec === undefined || spec === null) return new Map();
|
|
200
|
+
if (typeof spec !== "object" || Array.isArray(spec)) {
|
|
201
|
+
throw new TypeError("argumentRules must be an object mapping a tool name (or '*') to a list of rules");
|
|
202
|
+
}
|
|
203
|
+
const compiled = new Map();
|
|
204
|
+
for (const [tool, rules] of Object.entries(spec)) {
|
|
205
|
+
if (!Array.isArray(rules) || rules.length === 0) {
|
|
206
|
+
throw new TypeError(`argumentRules["${tool}"] must be a non-empty array of rules`);
|
|
207
|
+
}
|
|
208
|
+
compiled.set(
|
|
209
|
+
tool,
|
|
210
|
+
rules.map((rule, i) => compileRule(rule, `argumentRules["${tool}"][${i}]`)),
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
return compiled;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function compileRule(rule, where) {
|
|
217
|
+
if (!rule || typeof rule !== "object" || Array.isArray(rule)) {
|
|
218
|
+
throw new TypeError(`${where} must be an object`);
|
|
219
|
+
}
|
|
220
|
+
if (typeof rule.path !== "string" || rule.path === "") {
|
|
221
|
+
throw new TypeError(`${where}.path must be a non-empty dot path`);
|
|
222
|
+
}
|
|
223
|
+
const kinds = RULE_KINDS.filter((k) => rule[k] !== undefined);
|
|
224
|
+
if (kinds.length !== 1) {
|
|
225
|
+
throw new TypeError(`${where} needs exactly one of ${RULE_KINDS.join(", ")} (found ${kinds.length})`);
|
|
226
|
+
}
|
|
227
|
+
const kind = kinds[0];
|
|
228
|
+
const out = { path: rule.path, kind, segments: rule.path.split(".") };
|
|
229
|
+
const v = rule[kind];
|
|
230
|
+
if (kind === "required") {
|
|
231
|
+
if (v !== true) throw new TypeError(`${where}.required must be true`);
|
|
232
|
+
} else if (kind === "max" || kind === "min") {
|
|
233
|
+
if (typeof v !== "number" || !Number.isFinite(v)) throw new TypeError(`${where}.${kind} must be a finite number`);
|
|
234
|
+
out.limit = v;
|
|
235
|
+
} else if (kind === "maxLength") {
|
|
236
|
+
if (!Number.isInteger(v) || v < 0) throw new TypeError(`${where}.maxLength must be a non-negative integer`);
|
|
237
|
+
out.limit = v;
|
|
238
|
+
} else if (kind === "in") {
|
|
239
|
+
if (!Array.isArray(v) || v.length === 0) throw new TypeError(`${where}.in must be a non-empty array`);
|
|
240
|
+
out.allowed = v;
|
|
241
|
+
} else if (kind === "pattern" || kind === "notPattern") {
|
|
242
|
+
if (typeof v !== "string" || v === "") throw new TypeError(`${where}.${kind} must be a regular expression string`);
|
|
243
|
+
if (v.length > REGEX_INPUT_CAP) throw new TypeError(`${where}.${kind} is longer than ${REGEX_INPUT_CAP} characters`);
|
|
244
|
+
if (NESTED_QUANTIFIER.test(v)) {
|
|
245
|
+
throw new TypeError(`${where}.${kind} has a repeated group that contains a quantifier or an alternation, which can take exponential time on a hostile string; rewrite it as a character class or without the nesting`);
|
|
246
|
+
}
|
|
247
|
+
try {
|
|
248
|
+
out.re = new RegExp(v);
|
|
249
|
+
} catch (err) {
|
|
250
|
+
throw new TypeError(`${where}.${kind} is not a valid regular expression: ${err.message}`);
|
|
251
|
+
}
|
|
252
|
+
} else if (kind === "withinPath") {
|
|
253
|
+
if (typeof v !== "string" || !v.startsWith("/")) {
|
|
254
|
+
throw new TypeError(`${where}.withinPath must be an absolute POSIX directory path`);
|
|
255
|
+
}
|
|
256
|
+
out.base = path.posix.normalize(v).replace(/\/+$/, "") || "/";
|
|
257
|
+
}
|
|
258
|
+
return out;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function lookup(args, segments) {
|
|
262
|
+
let cur = args;
|
|
263
|
+
for (const seg of segments) {
|
|
264
|
+
if (cur === null || typeof cur !== "object" || !Object.prototype.hasOwnProperty.call(cur, seg)) {
|
|
265
|
+
return { present: false };
|
|
266
|
+
}
|
|
267
|
+
cur = cur[seg];
|
|
268
|
+
}
|
|
269
|
+
return { present: true, value: cur };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function withinBase(value, base) {
|
|
273
|
+
if (typeof value !== "string" || value === "" || value.includes("\0")) return false;
|
|
274
|
+
const normalized = path.posix.normalize(value.replace(/\\/g, "/"));
|
|
275
|
+
if (!normalized.startsWith("/")) return false;
|
|
276
|
+
if (base === "/") return true;
|
|
277
|
+
return normalized === base || normalized.startsWith(`${base}/`);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Evaluate the rules that apply to one tool.
|
|
282
|
+
* @returns {Array<{ path: string, rule: string }>} violations; never contains the offending value
|
|
283
|
+
*/
|
|
284
|
+
export function evaluateArgumentRules(compiled, toolName, args) {
|
|
285
|
+
const violations = [];
|
|
286
|
+
const applicable = [...(compiled.get("*") ?? []), ...(compiled.get(toolName) ?? [])];
|
|
287
|
+
for (const rule of applicable) {
|
|
288
|
+
const found = lookup(args ?? {}, rule.segments);
|
|
289
|
+
if (!found.present) {
|
|
290
|
+
if (rule.kind === "required") violations.push({ path: rule.path, rule: "required" });
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
const v = found.value;
|
|
294
|
+
let ok = true;
|
|
295
|
+
switch (rule.kind) {
|
|
296
|
+
case "required":
|
|
297
|
+
ok = v !== null && v !== undefined && v !== "";
|
|
298
|
+
break;
|
|
299
|
+
case "max":
|
|
300
|
+
ok = typeof v === "number" && Number.isFinite(v) && v <= rule.limit;
|
|
301
|
+
break;
|
|
302
|
+
case "min":
|
|
303
|
+
ok = typeof v === "number" && Number.isFinite(v) && v >= rule.limit;
|
|
304
|
+
break;
|
|
305
|
+
case "maxLength":
|
|
306
|
+
ok = typeof v === "string" && v.length <= rule.limit;
|
|
307
|
+
break;
|
|
308
|
+
case "in":
|
|
309
|
+
ok = rule.allowed.some((a) => a === v);
|
|
310
|
+
break;
|
|
311
|
+
case "pattern":
|
|
312
|
+
ok = typeof v === "string" && v.length <= REGEX_INPUT_CAP && rule.re.test(v);
|
|
313
|
+
break;
|
|
314
|
+
case "notPattern":
|
|
315
|
+
ok = typeof v === "string" ? v.length <= REGEX_INPUT_CAP && !rule.re.test(v) : false;
|
|
316
|
+
break;
|
|
317
|
+
case "withinPath":
|
|
318
|
+
ok = withinBase(v, rule.base);
|
|
319
|
+
break;
|
|
320
|
+
default:
|
|
321
|
+
ok = false;
|
|
322
|
+
}
|
|
323
|
+
if (!ok) violations.push({ path: rule.path, rule: rule.kind });
|
|
324
|
+
}
|
|
325
|
+
return violations;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ─── the guard the proxy holds ─────────────────────────────────────────────
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* @param {{
|
|
332
|
+
* secretScanning?: false | { arguments?: string, results?: string },
|
|
333
|
+
* argumentRules?: object,
|
|
334
|
+
* }} opts
|
|
335
|
+
*/
|
|
336
|
+
export function createContentGuard(opts = {}) {
|
|
337
|
+
const sc = opts.secretScanning === false ? { arguments: "off", results: "off" } : opts.secretScanning ?? {};
|
|
338
|
+
const argumentsMode = sc.arguments ?? "block";
|
|
339
|
+
const resultsMode = sc.results ?? "warn";
|
|
340
|
+
if (!ARGUMENT_MODES.includes(argumentsMode)) {
|
|
341
|
+
throw new TypeError(`secretScanning.arguments must be one of ${ARGUMENT_MODES.join(", ")}`);
|
|
342
|
+
}
|
|
343
|
+
if (!RESULT_MODES.includes(resultsMode)) {
|
|
344
|
+
throw new TypeError(`secretScanning.results must be one of ${RESULT_MODES.join(", ")}`);
|
|
345
|
+
}
|
|
346
|
+
const rules = compileArgumentRules(opts.argumentRules);
|
|
347
|
+
|
|
348
|
+
return {
|
|
349
|
+
argumentsMode,
|
|
350
|
+
resultsMode,
|
|
351
|
+
ruleCount: [...rules.values()].reduce((n, r) => n + r.length, 0),
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Inspect a call before it is sent.
|
|
355
|
+
* @returns {{ refuse: null | { code: string, message: string }, report: object[] , safeArgs: unknown }}
|
|
356
|
+
*/
|
|
357
|
+
checkCall(toolName, args) {
|
|
358
|
+
const report = [];
|
|
359
|
+
let refuse = null;
|
|
360
|
+
let safeArgs = args ?? {};
|
|
361
|
+
|
|
362
|
+
if (argumentsMode !== "off") {
|
|
363
|
+
const scan = scanValue(args ?? {});
|
|
364
|
+
const findings = [...scan.findings];
|
|
365
|
+
if (!scan.complete) findings.push({ pattern: "scan_limit_exceeded", path: "$" });
|
|
366
|
+
if (findings.length > 0) {
|
|
367
|
+
report.push({ kind: "call.secret_detected", detail: { name: toolName, mode: argumentsMode, findings } });
|
|
368
|
+
// The receipt and audit stream must never carry the credential.
|
|
369
|
+
safeArgs = redactValue(args ?? {}).value;
|
|
370
|
+
if (argumentsMode === "block") {
|
|
371
|
+
const names = [...new Set(findings.map((f) => f.pattern))].join(", ");
|
|
372
|
+
refuse = {
|
|
373
|
+
code: SECRET_IN_ARGUMENTS,
|
|
374
|
+
message:
|
|
375
|
+
`${SECRET_IN_ARGUMENTS}: the arguments to '${toolName}' contain what looks like a credential (${names}). ` +
|
|
376
|
+
"The call was refused and not sent. Remove the credential, or set secretScanning.arguments to \"warn\" or \"off\" if this is intended.",
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
if (!refuse && rules.size > 0) {
|
|
383
|
+
const violations = evaluateArgumentRules(rules, toolName, args);
|
|
384
|
+
if (violations.length > 0) {
|
|
385
|
+
report.push({ kind: "call.argument_rule_violation", detail: { name: toolName, violations } });
|
|
386
|
+
const where = violations.map((v) => `${v.path} (${v.rule})`).join(", ");
|
|
387
|
+
refuse = {
|
|
388
|
+
code: ARGUMENT_RULE_VIOLATION,
|
|
389
|
+
message: `${ARGUMENT_RULE_VIOLATION}: the arguments to '${toolName}' break a configured rule at ${where}. The call was refused and not sent.`,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return { refuse, report, safeArgs };
|
|
394
|
+
},
|
|
395
|
+
|
|
396
|
+
/** Error text from the upstream or the gateway, scrubbed before it is audited or (in redact mode) returned. */
|
|
397
|
+
scrubError(message) {
|
|
398
|
+
// Scrubbed for our own audit log in every mode; only the client's copy depends on `redact`.
|
|
399
|
+
if (typeof message !== "string") return { message, changed: false };
|
|
400
|
+
const r = redactText(message.length > MAX_STRING_CHARS ? message.slice(0, MAX_STRING_CHARS) : message);
|
|
401
|
+
return { message: r.text, changed: r.count > 0 };
|
|
402
|
+
},
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Inspect (and in `redact` mode rewrite) a tool result before the client sees it.
|
|
406
|
+
* @returns {{ result: unknown, report: object[] }}
|
|
407
|
+
*/
|
|
408
|
+
checkResult(toolName, result) {
|
|
409
|
+
if (resultsMode === "off" || result === null || typeof result !== "object") return { result, report: [] };
|
|
410
|
+
// Base64 payloads are not decoded: say so instead of implying they were checked.
|
|
411
|
+
const skipped = [];
|
|
412
|
+
if (Array.isArray(result.content)) {
|
|
413
|
+
for (const item of result.content) {
|
|
414
|
+
if (item && (item.type === "image" || item.type === "audio" || item.resource?.blob !== undefined)) {
|
|
415
|
+
skipped.push(item.type === "resource" ? "resource.blob" : item.type);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
const notes = skipped.length > 0 ? [{ kind: "result.unscanned_content", detail: { name: toolName, items: skipped.length, kinds: [...new Set(skipped)] } }] : [];
|
|
420
|
+
const scan = scanValue(result);
|
|
421
|
+
const findings = [...scan.findings];
|
|
422
|
+
if (!scan.complete) findings.push({ pattern: "scan_limit_exceeded", path: "$" });
|
|
423
|
+
if (findings.length === 0) return { result, report: notes };
|
|
424
|
+
const report = [...notes, { kind: "result.secret_detected", detail: { name: toolName, mode: resultsMode, findings } }];
|
|
425
|
+
if (resultsMode === "redact") {
|
|
426
|
+
const redacted = redactValue(result);
|
|
427
|
+
return { result: redacted.value, report };
|
|
428
|
+
}
|
|
429
|
+
return { result, report };
|
|
430
|
+
},
|
|
431
|
+
};
|
|
432
|
+
}
|