@glassbox-ai/engine 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.
Files changed (101) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -2
  3. package/dist/action/acc.d.ts +48 -0
  4. package/dist/action/acc.js +117 -0
  5. package/dist/action/builtin-tools.d.ts +5 -0
  6. package/dist/action/builtin-tools.js +74 -0
  7. package/dist/action/inline.d.ts +14 -0
  8. package/dist/action/inline.js +54 -0
  9. package/dist/action/paths.d.ts +71 -0
  10. package/dist/action/paths.js +398 -0
  11. package/dist/action/powershell.d.ts +9 -0
  12. package/dist/action/powershell.js +848 -0
  13. package/dist/action/protected-write.d.ts +11 -0
  14. package/dist/action/protected-write.js +113 -0
  15. package/dist/action/schedule.d.ts +43 -0
  16. package/dist/action/schedule.js +213 -0
  17. package/dist/action/shell/analyze.d.ts +28 -0
  18. package/dist/action/shell/analyze.js +2057 -0
  19. package/dist/action/shell/parse.d.ts +74 -0
  20. package/dist/action/shell/parse.js +1037 -0
  21. package/dist/action/shell/view.d.ts +6 -0
  22. package/dist/action/shell/view.js +89 -0
  23. package/dist/action/sql.d.ts +3 -0
  24. package/dist/action/sql.js +259 -0
  25. package/dist/action/tools.d.ts +20 -0
  26. package/dist/action/tools.js +305 -0
  27. package/dist/action/upload.d.ts +17 -0
  28. package/dist/action/upload.js +72 -0
  29. package/dist/analysis/fields.d.ts +14 -0
  30. package/dist/analysis/fields.js +136 -0
  31. package/dist/analysis/findings.d.ts +25 -0
  32. package/dist/analysis/findings.js +82 -0
  33. package/dist/analysis/gate.d.ts +16 -0
  34. package/dist/analysis/gate.js +662 -0
  35. package/dist/analysis/manifest.d.ts +3 -0
  36. package/dist/analysis/manifest.js +369 -0
  37. package/dist/analysis/match.d.ts +54 -0
  38. package/dist/analysis/match.js +352 -0
  39. package/dist/analysis/scan.d.ts +17 -0
  40. package/dist/analysis/scan.js +97 -0
  41. package/dist/canon/confusables.generated.d.ts +3 -0
  42. package/dist/canon/confusables.generated.js +6 -0
  43. package/dist/canon/decode.d.ts +11 -0
  44. package/dist/canon/decode.js +147 -0
  45. package/dist/canon/views.d.ts +36 -0
  46. package/dist/canon/views.js +283 -0
  47. package/dist/evidence/evidence.d.ts +12 -0
  48. package/dist/evidence/evidence.js +149 -0
  49. package/dist/fingerprint/diff.d.ts +3 -0
  50. package/dist/fingerprint/diff.js +273 -0
  51. package/dist/fingerprint/fingerprint.d.ts +4 -0
  52. package/dist/fingerprint/fingerprint.js +77 -0
  53. package/dist/grade/score.d.ts +19 -0
  54. package/dist/grade/score.js +89 -0
  55. package/dist/index.d.ts +26 -0
  56. package/dist/index.js +152 -0
  57. package/dist/intake/json.d.ts +17 -0
  58. package/dist/intake/json.js +284 -0
  59. package/dist/intake/snapshot.d.ts +14 -0
  60. package/dist/intake/snapshot.js +130 -0
  61. package/dist/limits.d.ts +4 -0
  62. package/dist/limits.js +30 -0
  63. package/dist/policy/decide.d.ts +32 -0
  64. package/dist/policy/decide.js +105 -0
  65. package/dist/rules/ids.d.ts +2 -0
  66. package/dist/rules/ids.js +99 -0
  67. package/dist/ruleset/baseline-tests.generated.d.ts +6 -0
  68. package/dist/ruleset/baseline-tests.generated.js +2935 -0
  69. package/dist/ruleset/baseline.d.ts +3 -0
  70. package/dist/ruleset/baseline.generated.d.ts +3 -0
  71. package/dist/ruleset/baseline.generated.js +5 -0
  72. package/dist/ruleset/baseline.js +44 -0
  73. package/dist/ruleset/fakes.d.ts +3 -0
  74. package/dist/ruleset/fakes.js +26 -0
  75. package/dist/ruleset/load.d.ts +13 -0
  76. package/dist/ruleset/load.js +187 -0
  77. package/dist/ruleset/schema.d.ts +120 -0
  78. package/dist/ruleset/schema.js +54 -0
  79. package/dist/ruleset/selftest.d.ts +18 -0
  80. package/dist/ruleset/selftest.js +42 -0
  81. package/dist/ruleset-entry.d.ts +5 -0
  82. package/dist/ruleset-entry.js +7 -0
  83. package/dist/secrets/detect.d.ts +17 -0
  84. package/dist/secrets/detect.js +236 -0
  85. package/dist/secrets/redact.d.ts +19 -0
  86. package/dist/secrets/redact.js +116 -0
  87. package/dist/types.d.ts +455 -0
  88. package/dist/types.js +10 -0
  89. package/dist/util/hash.d.ts +4 -0
  90. package/dist/util/hash.js +16 -0
  91. package/dist/util/initclock.d.ts +3 -0
  92. package/dist/util/initclock.js +17 -0
  93. package/dist/util/jcs.d.ts +4 -0
  94. package/dist/util/jcs.js +91 -0
  95. package/dist/util/misc.d.ts +17 -0
  96. package/dist/util/misc.js +77 -0
  97. package/dist/util/re.d.ts +14 -0
  98. package/dist/util/re.js +47 -0
  99. package/dist/version.d.ts +2 -0
  100. package/dist/version.js +2 -0
  101. package/package.json +57 -4
@@ -0,0 +1,369 @@
1
+ // analyzeServer: metadata-only analysis of an MCP manifest.
2
+ import { buildViews } from "../canon/views.js";
3
+ import { profileMcpTool, nameWords } from "../action/tools.js";
4
+ import { fingerprintOf } from "../fingerprint/fingerprint.js";
5
+ import { scoreFindings } from "../grade/score.js";
6
+ import { resolveLimits } from "../limits.js";
7
+ import { EMBEDDED_BASELINE } from "../ruleset/baseline.js";
8
+ import { get, getString, isRecord, trimEndChars, utf8Length } from "../util/misc.js";
9
+ import { ENGINE_VERSION } from "../version.js";
10
+ import { manifestFields } from "./fields.js";
11
+ import { dedupe, FindingFactory, sortFindings } from "./findings.js";
12
+ import { matchRule, scanField, tokenize } from "./match.js";
13
+ import { intake } from "./gate.js";
14
+ import { scanFields } from "./scan.js";
15
+ const BUILTIN_TOOL_NAMES = ["Bash", "PowerShell", "Write", "Edit", "MultiEdit", "Read", "WebFetch", "WebSearch", "Grep", "Glob", "Agent", "Task", "NotebookEdit"];
16
+ const DIRECTIVE_WORDS = new Set(["instead", "always", "before", "after", "deprecated", "must", "never", "don't", "dont", "should", "replace", "override", "first"]);
17
+ const STRONG_DIRECTIVES = new Set(["must", "always", "before", "instead", "first", "mandatory", "required", "never", "redirect", "redirected", "priority", "replace", "prior", "should", "change", "modify", "override", "rewrite", "append"]);
18
+ const SOFT_DIRECTIVES = new Set(["instead", "should", "replace"]);
19
+ const TOOL_LEAD = new Set(["using", "use", "call", "calling", "run", "running", "invoke", "invoking", "tool"]);
20
+ const CAMEL = /^[a-z]+(?:[A-Z][a-z0-9]*)+$/;
21
+ const IDENT = /^[A-Za-z][A-Za-z0-9]*(?:[_-][A-Za-z0-9]+)+$/;
22
+ /** Tool-shaped names inside backticks or quotes: `send_email`, 'read_file', "map-traffic", 'sendSimpleMail'. */
23
+ function quotedIdentifiers(text) {
24
+ const out = [];
25
+ for (let i = 0; i < text.length && out.length < 20; i++) {
26
+ const q = text[i];
27
+ if (q !== "`" && q !== "'" && q !== '"')
28
+ continue;
29
+ const end = text.indexOf(q, i + 1);
30
+ if (end < 0)
31
+ break;
32
+ if (end - i - 1 <= 64) {
33
+ const inner = text.slice(i + 1, end);
34
+ // camelCase in quotes is usually a field name ('endCursor'); it counts only when led (ledIdentifiers).
35
+ if (IDENT.test(inner))
36
+ out.push(inner);
37
+ }
38
+ i = end;
39
+ }
40
+ return out;
41
+ }
42
+ /** Tool-shaped names right after "using", "call", "run"…, quoted or not (Before using search_files, call write_file; use 'sendSimpleMail'). */
43
+ function ledIdentifiers(text) {
44
+ const words = text.slice(0, 20_000).split(/\s+/);
45
+ const out = [];
46
+ for (let i = 1; i < words.length && out.length < 20; i++) {
47
+ const prev = (words[i - 1] ?? "").toLowerCase();
48
+ const prev2 = (words[i - 2] ?? "").toLowerCase();
49
+ // "use X" or "use the X tool" ("use the 'endCursor' from…" names a field, not a tool).
50
+ const viaThe = prev === "the" && TOOL_LEAD.has(prev2) && (words[i + 1] ?? "").toLowerCase().startsWith("tool");
51
+ if (!TOOL_LEAD.has(prev) && !viaThe)
52
+ continue;
53
+ const w = trimEndChars((words[i] ?? "").replace(/^[(`'"]+/, ""), ".,;:)!?`'\"");
54
+ if (w.length <= 64 && (IDENT.test(w) || CAMEL.test(w)))
55
+ out.push(w);
56
+ }
57
+ return out;
58
+ }
59
+ /** Every property name and string value in a schema (bounded). */
60
+ function schemaStrings(schema) {
61
+ const out = [];
62
+ const stack = [schema];
63
+ while (stack.length > 0 && out.length < 2000) {
64
+ const v = stack.pop();
65
+ if (typeof v === "string")
66
+ out.push(v);
67
+ else if (Array.isArray(v))
68
+ stack.push(...v.slice(0, 200));
69
+ else if (isRecord(v))
70
+ for (const k of Object.keys(v).slice(0, 200)) {
71
+ out.push(k);
72
+ stack.push(v[k]);
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ const PURPOSE_HARMLESS = new Set(["time", "date", "clock", "timezone", "math", "calculate", "calculator", "add", "sum", "multiply", "convert", "format", "weather", "forecast", "random", "uuid", "echo", "ping", "joke", "quote", "temperature", "unit", "units", "color", "colour"]);
78
+ const CAP_PARAMS = [
79
+ [/^(command|cmd|shell|script|code|exec|eval|bash|powershell)$/i, "exec"],
80
+ [/^(path|file|filename|file_path|filepath|dir|directory)$/i, "path"],
81
+ [/^(url|uri|endpoint|webhook|callback|callback_url)$/i, "url"],
82
+ [/^(token|password|passwd|secret|api_?key|apikey|credential|credentials|private_?key|auth)$/i, "credentials"],
83
+ ];
84
+ function editDistance(a, b) {
85
+ if (Math.abs(a.length - b.length) > 2)
86
+ return 3;
87
+ const prev = Array.from({ length: b.length + 1 }, (_, i) => i);
88
+ for (let i = 1; i <= a.length; i++) {
89
+ let diag = prev[0];
90
+ prev[0] = i;
91
+ for (let j = 1; j <= b.length; j++) {
92
+ const tmp = prev[j];
93
+ prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
94
+ diag = tmp;
95
+ }
96
+ }
97
+ return prev[b.length];
98
+ }
99
+ /** Strings of one tool in document order, for split-payload detection. */
100
+ function toolStrings(tool, base) {
101
+ const out = [];
102
+ const stack = [{ v: tool, p: base }];
103
+ while (stack.length > 0 && out.length < 500) {
104
+ const { v, p } = stack.shift();
105
+ if (typeof v === "string") {
106
+ if (!p.endsWith("/name") && !p.endsWith("/type"))
107
+ out.push({ pointer: p, text: v });
108
+ }
109
+ else if (Array.isArray(v))
110
+ v.forEach((x, i) => stack.push({ v: x, p: `${p}/${i}` }));
111
+ else if (isRecord(v))
112
+ for (const k of Object.keys(v))
113
+ stack.push({ v: v[k], p: `${p}/${k.replace(/~/g, "~0").replace(/\//g, "~1")}` });
114
+ }
115
+ return out;
116
+ }
117
+ /** Widely used MCP server names that are worth imitating; known servers from the caller are added. */
118
+ const WELL_KNOWN_SERVERS = [
119
+ "github", "gitlab", "slack", "gmail", "google", "googledrive", "filesystem", "notion", "linear", "jira", "atlassian",
120
+ "stripe", "aws", "postgres", "sentry", "figma", "anthropic", "openai", "microsoft", "azure", "cloudflare", "vercel",
121
+ ];
122
+ export function analyzeServerImpl(manifestIn, opts, t0) {
123
+ const limits = resolveLimits(opts?.limits);
124
+ const ruleset = opts?.ruleset && Array.isArray(opts.ruleset.rules) ? opts.ruleset : EMBEDDED_BASELINE;
125
+ const ff = new FindingFactory(ruleset, opts?.evidenceMode === "none" ? "none" : "snippet");
126
+ const findings = [];
127
+ const degradedReasons = [];
128
+ const ink = intake(manifestIn, limits);
129
+ for (const i of ink.issues)
130
+ findings.push(ff.make({ ruleId: i.code, location: i.pointer ?? "" }));
131
+ if (ink.degraded)
132
+ degradedReasons.push(...new Set(ink.issues.map((i) => i.code)));
133
+ const m = isRecord(ink.value) ? ink.value : Object.create(null);
134
+ if (!isRecord(ink.value) && !ink.tooBig)
135
+ findings.push(ff.make({ ruleId: "CP-PARSE-010", location: "" }));
136
+ const toolsRaw = Array.isArray(get(m, "tools")) ? get(m, "tools") : [];
137
+ let partial = ink.degraded;
138
+ if (toolsRaw.length > limits.maxTools) {
139
+ partial = true;
140
+ degradedReasons.push("CP-LIMIT-004");
141
+ findings.push(ff.make({ ruleId: "CP-LIMIT-004", location: "/tools" }));
142
+ }
143
+ const tools = toolsRaw.slice(0, limits.maxTools);
144
+ // Layer 1 over every field.
145
+ const fields = manifestFields(m, limits.maxTools);
146
+ // The grader's time backstop.
147
+ const deadline = t0 + (opts?.limits?.hardStopMs ?? 2000);
148
+ const scan = scanFields(fields, "manifest", ff, ruleset.rules, limits, true, deadline);
149
+ findings.push(...scan.findings);
150
+ if (scan.timedOut) {
151
+ partial = true;
152
+ degradedReasons.push("CP-LIMIT-010");
153
+ findings.push(ff.make({ ruleId: "CP-LIMIT-010", location: "" }));
154
+ }
155
+ if (scan.windowed) {
156
+ partial = true;
157
+ degradedReasons.push("CP-LIMIT-006");
158
+ }
159
+ if (scan.decodeExhausted) {
160
+ degradedReasons.push("CP-LIMIT-007");
161
+ findings.push(ff.make({ ruleId: "CP-LIMIT-007", location: "" }));
162
+ }
163
+ // Per-field structural rules.
164
+ for (const f of fields) {
165
+ if (f.role === "tool.schema.enum" || f.role === "tool.schema.default" || f.role === "tool.schema.const" || f.role === "tool.schema.examples") {
166
+ const words = tokenize(f.text);
167
+ if (words.length >= 6 || (words.length >= 3 && /[.!?]\s*\S/.test(f.text.slice(0, 2000))))
168
+ findings.push(ff.make({ ruleId: "CP-POISON-020", location: f.pointer, text: f.text }));
169
+ }
170
+ if (f.role === "tool.schema.key" && (f.text.length > 40 || tokenize(f.text.replace(/_/g, " ")).length >= 5))
171
+ findings.push(ff.make({ ruleId: "CP-POISON-021", location: f.pointer, text: f.text }));
172
+ if (f.role === "tool.description" && utf8Length(f.text) > limits.maxDescriptionBytes)
173
+ findings.push(ff.make({ ruleId: "CP-LIMIT-005", location: f.pointer, text: f.text.slice(0, 200) }));
174
+ }
175
+ // Per tool.
176
+ const names = new Map();
177
+ const ownNames = new Set(tools.map((t) => getString(t, "name") ?? ""));
178
+ const known = (opts?.knownTools ?? []).filter((k) => isRecord(k) && typeof k.name === "string");
179
+ const capabilityProfile = [];
180
+ const poisonRules = ruleset.rules.filter((r) => ["CP-POISON-001", "CP-POISON-002", "CP-POISON-003", "CP-POISON-005"].includes(r.id));
181
+ let timeNoted = scan.timedOut;
182
+ tools.forEach((t, i) => {
183
+ const base = `/tools/${i}`;
184
+ const name = getString(t, "name");
185
+ const desc = getString(t, "description");
186
+ if (name === undefined) {
187
+ findings.push(ff.make({ ruleId: "CP-PARSE-010", location: `${base}/name` }));
188
+ return;
189
+ }
190
+ names.set(name, (names.get(name) ?? 0) + 1);
191
+ if (names.get(name) === 2)
192
+ findings.push(ff.make({ ruleId: "CP-PARSE-004", location: `${base}/name`, text: name }));
193
+ if (!desc || desc.trim().length === 0)
194
+ findings.push(ff.make({ ruleId: "CP-HYGIENE-001", location: base, text: name }));
195
+ if (!isRecord(get(t, "inputSchema")))
196
+ findings.push(ff.make({ ruleId: "CP-HYGIENE-003", location: base, text: name }));
197
+ if (!/^[A-Za-z0-9_.-]{1,128}$/.test(name))
198
+ findings.push(ff.make({ ruleId: "CP-HYGIENE-004", location: `${base}/name`, text: name }));
199
+ const prof = profileMcpTool(name, t);
200
+ const ann = get(t, "annotations");
201
+ if (prof.acc.level === "high-risk" && !isRecord(ann))
202
+ findings.push(ff.make({ ruleId: "CP-HYGIENE-002", location: base, text: name }));
203
+ if (prof.contradiction)
204
+ findings.push(ff.make({ ruleId: "CP-CAP-002", location: `${base}/annotations`, text: name }));
205
+ capabilityProfile.push({ tool: name, risk: { level: prof.acc.level, tags: [...prof.acc.tags].sort(), unanalyzable: false, selfProtection: false, reasons: ["what the metadata says the tool can do"] } });
206
+ // Past the grader's time budget, keep only the cheap per-tool checks above (red team, Step 5).
207
+ if (performance.now() > deadline) {
208
+ if (!timeNoted) {
209
+ timeNoted = true;
210
+ partial = true;
211
+ degradedReasons.push("CP-LIMIT-010");
212
+ findings.push(ff.make({ ruleId: "CP-LIMIT-010", location: "" }));
213
+ }
214
+ return;
215
+ }
216
+ // Capability mismatch: a harmless-sounding purpose asking for powerful inputs.
217
+ const purpose = [...nameWords(name), ...nameWords((desc ?? "").split(/[.\n]/)[0] ?? "").slice(0, 6)];
218
+ // Only short names state a single harmless purpose (get_time, add_numbers); in a longer name
219
+ // (add_pull_request_review_comment) the word is a verb about something else.
220
+ const harmless = nameWords(name).length <= 2 && purpose.some((w) => PURPOSE_HARMLESS.has(w)) && prof.acc.level !== "high-risk";
221
+ const props = get(get(t, "inputSchema"), "properties");
222
+ if (harmless && isRecord(props)) {
223
+ for (const k of Object.keys(props)) {
224
+ const cap = CAP_PARAMS.find(([re]) => re.test(k));
225
+ if (cap) {
226
+ findings.push(ff.make({ ruleId: "CP-CAP-001", location: `${base}/inputSchema/properties/${k.replace(/~/g, "~0").replace(/\//g, "~1")}`, text: k }));
227
+ break;
228
+ }
229
+ }
230
+ }
231
+ // Split payload: instruction phrases that only appear across fields.
232
+ const strs = toolStrings(t, base);
233
+ // Top-level text fields (title, description, …) together, then every string of the tool.
234
+ const top = strs.filter((x) => x.pointer.split("/").length === 4);
235
+ for (const group of [top, strs]) {
236
+ if (group.length < 2)
237
+ continue;
238
+ const joined = group.map((x) => x.text).join(" ");
239
+ const scanJ = scanField(joined, limits.maxFieldScanBytes, { bytes: 0 }, 0);
240
+ let reported = false;
241
+ for (const r of poisonRules) {
242
+ if (!matchRule(r, scanJ, undefined))
243
+ continue;
244
+ const single = group.some((x) => matchRule(r, scanField(x.text, limits.maxFieldScanBytes, { bytes: 0 }, 0), undefined));
245
+ if (!single) {
246
+ findings.push(ff.make({ ruleId: "CP-POISON-030", location: base, text: joined, via: ["concat"], related: group.map((x) => x.pointer).slice(0, 10) }));
247
+ reported = true;
248
+ break;
249
+ }
250
+ }
251
+ if (reported)
252
+ break;
253
+ }
254
+ // Shadowing: directives about a tool that isn't on this server.
255
+ for (const s of strs) {
256
+ const words = tokenize(s.text.slice(0, limits.maxFieldScanBytes));
257
+ const lower = new Set(words.map((w) => w.w.toLowerCase()));
258
+ if (![...DIRECTIVE_WORDS].some((d) => lower.has(d)))
259
+ continue;
260
+ const otherNames = new Set([...known.map((k) => k.name), ...BUILTIN_TOOL_NAMES].filter((n) => !ownNames.has(n)));
261
+ let hit = null;
262
+ for (const n of otherNames) {
263
+ const isBuiltin = BUILTIN_TOOL_NAMES.includes(n);
264
+ const idx = s.text.indexOf(n);
265
+ if (idx < 0)
266
+ continue;
267
+ const after = s.text.slice(idx + n.length, idx + n.length + 6).toLowerCase();
268
+ const beforeCh = s.text[idx - 1] ?? " ";
269
+ const boundary = !/[A-Za-z0-9_]/.test(beforeCh) && !/^[A-Za-z0-9_]/.test(s.text.slice(idx + n.length, idx + n.length + 1));
270
+ if (!boundary)
271
+ continue;
272
+ if (isBuiltin && !(after.startsWith(" tool") || after.startsWith("`") || after.startsWith("(") || beforeCh === "`"))
273
+ continue;
274
+ hit = n;
275
+ break;
276
+ }
277
+ if (hit) {
278
+ findings.push(ff.make({ ruleId: "CP-SHADOW-001", location: s.pointer, text: s.text, start: s.text.indexOf(hit), end: s.text.indexOf(hit) + hit.length }));
279
+ break;
280
+ }
281
+ }
282
+ // Directives about a tool named in quotes that isn't this tool (rev 7, from MCPTox): works
283
+ // without knowing the other server. Names and values from the tool's own schema don't count.
284
+ if (!findings.some((f) => f?.ruleId === "CP-SHADOW-001" && f.location.startsWith(base))) {
285
+ // Tools on this same server are its own business (a real scan grades the whole server).
286
+ const own = new Set([...[...ownNames].map((x) => x.toLowerCase()), ...schemaStrings(get(t, "inputSchema")).map((x) => x.toLowerCase())]);
287
+ for (const s of strs) {
288
+ const text = s.text.slice(0, limits.maxFieldScanBytes);
289
+ const lowerWords = new Set(tokenize(text).map((w) => w.w.toLowerCase()));
290
+ if (![...STRONG_DIRECTIVES].some((d) => lowerWords.has(d)))
291
+ continue;
292
+ // Unquoted names need a demand, not a recommendation ("use stream_file instead" is fine).
293
+ const demands = [...STRONG_DIRECTIVES].some((d) => !SOFT_DIRECTIVES.has(d) && lowerWords.has(d));
294
+ const ref = [...quotedIdentifiers(text), ...(demands ? ledIdentifiers(text) : [])].find((q) => !own.has(q.toLowerCase()));
295
+ if (ref) {
296
+ findings.push(ff.make({ ruleId: "CP-SHADOW-002", location: s.pointer, text, start: text.indexOf(ref), end: text.indexOf(ref) + ref.length }));
297
+ break;
298
+ }
299
+ }
300
+ }
301
+ // Collisions and typosquats against other servers' tools.
302
+ for (const k of known) {
303
+ if (k.name === name) {
304
+ findings.push(ff.make({ ruleId: "CP-SHADOW-010", location: `${base}/name`, text: name }));
305
+ break;
306
+ }
307
+ const skelA = buildViews(name).skeleton.text, skelB = buildViews(k.name).skeleton.text;
308
+ if (name.length >= 5 && (skelA === skelB || editDistance(name.toLowerCase(), k.name.toLowerCase()) <= 2)) {
309
+ findings.push(ff.make({ ruleId: "CP-SHADOW-010", location: `${base}/name`, text: name }));
310
+ break;
311
+ }
312
+ }
313
+ });
314
+ // Spoofed server names (rev 7): a name that isn't a known server's name but looks the same once
315
+ // look-alike letters are folded (ɡithub, gіthub, fiIesystem). Case alone (GitHub) doesn't count.
316
+ // Both sides are folded: the skeleton itself maps m → rn, and I and l only meet after lowercasing.
317
+ const fold = (s) => buildViews(s).skeleton.text.replace(/[i1|]/g, "l").replace(/0/g, "o");
318
+ const knownNames = [...new Set([...WELL_KNOWN_SERVERS, ...known.map((k) => (typeof k.serverId === "string" ? k.serverId.toLowerCase() : "")).filter(Boolean)])];
319
+ const knownFolded = new Set(knownNames.map(fold));
320
+ const info = get(get(m, "initialize"), "serverInfo");
321
+ for (const [ptr, n] of [["/initialize/serverInfo/name", getString(info, "name")], ["/serverId", getString(m, "serverId")]]) {
322
+ if (n === undefined || n.length > 200)
323
+ continue;
324
+ if (!knownNames.includes(n.toLowerCase()) && knownFolded.has(fold(n))) {
325
+ findings.push(ff.make({ ruleId: "CP-SHADOW-011", location: ptr, text: n }));
326
+ break;
327
+ }
328
+ }
329
+ // Split payloads across tools (red team, Step 5): every tool's description, in order.
330
+ const descs = tools.map((t, i) => ({ pointer: `/tools/${i}/description`, text: getString(t, "description") ?? "" })).filter((d) => d.text.length > 0);
331
+ if (descs.length >= 2 && performance.now() < deadline) {
332
+ const joined = descs.map((d) => d.text).join(" ");
333
+ const scanJ = scanField(joined, limits.maxFieldScanBytes, { bytes: 0 }, 0);
334
+ for (const r of poisonRules) {
335
+ if (!matchRule(r, scanJ, undefined))
336
+ continue;
337
+ const single = descs.some((d) => matchRule(r, scanField(d.text, limits.maxFieldScanBytes, { bytes: 0 }, 0), undefined));
338
+ if (!single) {
339
+ findings.push(ff.make({ ruleId: "CP-POISON-030", location: "/tools", text: joined, via: ["concat"], related: descs.map((d) => d.pointer).slice(0, 10) }));
340
+ break;
341
+ }
342
+ }
343
+ }
344
+ // Session id shape (caller-reported).
345
+ const sid = opts?.sessionIdShape;
346
+ if (sid && isRecord(sid) && (sid.length < 16 || sid.sequentialSuspected || sid.charset === "digits"))
347
+ findings.push(ff.make({ ruleId: "CP-AUTH-001", location: "" }));
348
+ const fpR = fingerprintOf(m, limits);
349
+ const fs = sortFindings(dedupe(findings)).slice(0, limits.maxFindings);
350
+ const s = scoreFindings(fs, { partial });
351
+ return {
352
+ grade: s.grade,
353
+ score: s.score,
354
+ partial,
355
+ caps: s.caps,
356
+ deductions: s.deductions,
357
+ findings: fs,
358
+ capabilityProfile,
359
+ scope: "metadata-only",
360
+ ...(sid && isRecord(sid) ? { sessionIdShape: { length: Number(sid.length) || 0, charset: sid.charset, sequentialSuspected: Boolean(sid.sequentialSuspected) } } : {}),
361
+ fingerprint: fpR,
362
+ rulesetVersion: `${ruleset.rulesetId}@${ruleset.version}+${ruleset.sequence}`,
363
+ engineVersion: ENGINE_VERSION,
364
+ degraded: degradedReasons.length > 0,
365
+ degradedReasons: [...new Set(degradedReasons)],
366
+ elapsedMs: Math.max(0, performance.now() - t0),
367
+ };
368
+ }
369
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1,54 @@
1
+ import { type Views } from "../canon/views.js";
2
+ import { type SecretMemo } from "../secrets/detect.js";
3
+ import type { RuleDef, Severity, ViaKind } from "../types.js";
4
+ /** A text segment with all its views (fields over the scan window are split in two). */
5
+ export interface Segment {
6
+ offset: number;
7
+ views: Views;
8
+ rawNorm: string;
9
+ decoded: {
10
+ start: number;
11
+ end: number;
12
+ via: ViaKind;
13
+ views: Views;
14
+ nested: boolean;
15
+ }[];
16
+ tagSpan: {
17
+ start: number;
18
+ end: number;
19
+ } | null;
20
+ }
21
+ export interface FieldScan {
22
+ segments: Segment[];
23
+ windowed: boolean;
24
+ decodeExhausted: boolean;
25
+ /** Secret-detection results per view text, shared by every secret rule on this field. */
26
+ secrets: SecretMemo;
27
+ /** Lowercased view texts for regex anchors, shared by every regex rule on this field. */
28
+ lower: Map<string, string>;
29
+ /** Token lists (plain, spelled-out joined, de-leeted) per view text, shared by phrase rules. */
30
+ tokens: Map<string, Token[][]>;
31
+ }
32
+ declare function tagSpan(s: string): {
33
+ start: number;
34
+ end: number;
35
+ } | null;
36
+ export declare function scanField(text: string, maxFieldScanBytes: number, budget: {
37
+ bytes: number;
38
+ }, maxDecodeDepth: number): FieldScan;
39
+ interface Token {
40
+ w: string;
41
+ start: number;
42
+ end: number;
43
+ }
44
+ export declare function tokenize(s: string): Token[];
45
+ export interface RuleMatch {
46
+ start: number;
47
+ end: number;
48
+ via: ViaKind[];
49
+ severity: Severity;
50
+ }
51
+ /** Run one declarative rule on a scanned field. Returns the first match with escalation applied. */
52
+ export declare function matchRule(rule: RuleDef, scan: FieldScan, keyName: string | undefined): RuleMatch | null;
53
+ export { tagSpan };
54
+ //# sourceMappingURL=match.d.ts.map