@glassbox-ai/engine 0.0.0-stage → 0.1.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.
Files changed (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +31 -2
  3. package/dist/action/acc.d.ts +48 -0
  4. package/dist/action/acc.js +117 -0
  5. package/dist/action/inline.d.ts +14 -0
  6. package/dist/action/inline.js +54 -0
  7. package/dist/action/paths.d.ts +71 -0
  8. package/dist/action/paths.js +398 -0
  9. package/dist/action/powershell.d.ts +9 -0
  10. package/dist/action/powershell.js +848 -0
  11. package/dist/action/protected-write.d.ts +11 -0
  12. package/dist/action/protected-write.js +113 -0
  13. package/dist/action/schedule.d.ts +43 -0
  14. package/dist/action/schedule.js +213 -0
  15. package/dist/action/shell/analyze.d.ts +28 -0
  16. package/dist/action/shell/analyze.js +2030 -0
  17. package/dist/action/shell/parse.d.ts +74 -0
  18. package/dist/action/shell/parse.js +1037 -0
  19. package/dist/action/shell/view.d.ts +6 -0
  20. package/dist/action/shell/view.js +89 -0
  21. package/dist/action/sql.d.ts +3 -0
  22. package/dist/action/sql.js +259 -0
  23. package/dist/action/tools.d.ts +20 -0
  24. package/dist/action/tools.js +240 -0
  25. package/dist/action/upload.d.ts +17 -0
  26. package/dist/action/upload.js +72 -0
  27. package/dist/analysis/fields.d.ts +14 -0
  28. package/dist/analysis/fields.js +136 -0
  29. package/dist/analysis/findings.d.ts +25 -0
  30. package/dist/analysis/findings.js +82 -0
  31. package/dist/analysis/gate.d.ts +16 -0
  32. package/dist/analysis/gate.js +660 -0
  33. package/dist/analysis/manifest.d.ts +3 -0
  34. package/dist/analysis/manifest.js +369 -0
  35. package/dist/analysis/match.d.ts +54 -0
  36. package/dist/analysis/match.js +352 -0
  37. package/dist/analysis/scan.d.ts +17 -0
  38. package/dist/analysis/scan.js +97 -0
  39. package/dist/canon/confusables.generated.d.ts +3 -0
  40. package/dist/canon/confusables.generated.js +6 -0
  41. package/dist/canon/decode.d.ts +11 -0
  42. package/dist/canon/decode.js +147 -0
  43. package/dist/canon/views.d.ts +36 -0
  44. package/dist/canon/views.js +283 -0
  45. package/dist/evidence/evidence.d.ts +12 -0
  46. package/dist/evidence/evidence.js +149 -0
  47. package/dist/fingerprint/diff.d.ts +3 -0
  48. package/dist/fingerprint/diff.js +273 -0
  49. package/dist/fingerprint/fingerprint.d.ts +4 -0
  50. package/dist/fingerprint/fingerprint.js +77 -0
  51. package/dist/grade/score.d.ts +19 -0
  52. package/dist/grade/score.js +89 -0
  53. package/dist/index.d.ts +22 -0
  54. package/dist/index.js +148 -0
  55. package/dist/intake/json.d.ts +17 -0
  56. package/dist/intake/json.js +284 -0
  57. package/dist/intake/snapshot.d.ts +14 -0
  58. package/dist/intake/snapshot.js +130 -0
  59. package/dist/limits.d.ts +4 -0
  60. package/dist/limits.js +30 -0
  61. package/dist/policy/decide.d.ts +26 -0
  62. package/dist/policy/decide.js +74 -0
  63. package/dist/rules/ids.d.ts +2 -0
  64. package/dist/rules/ids.js +99 -0
  65. package/dist/ruleset/baseline-tests.generated.d.ts +6 -0
  66. package/dist/ruleset/baseline-tests.generated.js +2935 -0
  67. package/dist/ruleset/baseline.d.ts +3 -0
  68. package/dist/ruleset/baseline.generated.d.ts +3 -0
  69. package/dist/ruleset/baseline.generated.js +5 -0
  70. package/dist/ruleset/baseline.js +44 -0
  71. package/dist/ruleset/fakes.d.ts +3 -0
  72. package/dist/ruleset/fakes.js +26 -0
  73. package/dist/ruleset/load.d.ts +14 -0
  74. package/dist/ruleset/load.js +173 -0
  75. package/dist/ruleset/schema.d.ts +120 -0
  76. package/dist/ruleset/schema.js +54 -0
  77. package/dist/ruleset/selftest.d.ts +18 -0
  78. package/dist/ruleset/selftest.js +42 -0
  79. package/dist/ruleset-entry.d.ts +5 -0
  80. package/dist/ruleset-entry.js +7 -0
  81. package/dist/secrets/detect.d.ts +17 -0
  82. package/dist/secrets/detect.js +236 -0
  83. package/dist/secrets/redact.d.ts +19 -0
  84. package/dist/secrets/redact.js +116 -0
  85. package/dist/types.d.ts +434 -0
  86. package/dist/types.js +10 -0
  87. package/dist/util/hash.d.ts +4 -0
  88. package/dist/util/hash.js +16 -0
  89. package/dist/util/initclock.d.ts +3 -0
  90. package/dist/util/initclock.js +17 -0
  91. package/dist/util/jcs.d.ts +4 -0
  92. package/dist/util/jcs.js +91 -0
  93. package/dist/util/misc.d.ts +17 -0
  94. package/dist/util/misc.js +77 -0
  95. package/dist/util/re.d.ts +14 -0
  96. package/dist/util/re.js +47 -0
  97. package/dist/version.d.ts +2 -0
  98. package/dist/version.js +2 -0
  99. package/package.json +55 -3
@@ -0,0 +1,660 @@
1
+ // The gate: checkToolCall / checkToolResult / checkServerRequest (engine-spec §4, §6).
2
+ import { Acc } from "../action/acc.js";
3
+ import { normalizePath, pathCtxFrom } from "../action/paths.js";
4
+ import { commandFiles, cronLines, desktopJob, JOB_LABEL, plistJob, psTaskJob, unitJob } from "../action/schedule.js";
5
+ import { classifyBuiltin, classifyMcp } from "../action/tools.js";
6
+ import { snapshot } from "../intake/snapshot.js";
7
+ import { parseJsonStrict } from "../intake/json.js";
8
+ import { resolveLimits } from "../limits.js";
9
+ import { decide } from "../policy/decide.js";
10
+ import { detectSecrets } from "../secrets/detect.js";
11
+ import { redactString, redactValue } from "../secrets/redact.js";
12
+ import { sha256Hex } from "../util/hash.js";
13
+ import { jcs } from "../util/jcs.js";
14
+ import { get, getString, isRecord, utf8Length } from "../util/misc.js";
15
+ import { ENGINE_VERSION } from "../version.js";
16
+ import { initMs } from "../util/initclock.js";
17
+ import { genericFields } from "./fields.js";
18
+ import { dedupe, FindingFactory, sevRank, sortFindings } from "./findings.js";
19
+ import { tokenize } from "./match.js";
20
+ import { scanFields } from "./scan.js";
21
+ const now = () => performance.now();
22
+ /**
23
+ * The gate's time backstop (spec §11, hardStopMs): true once this call has run longer than
24
+ * the limit, not counting one-time initialization (regex compiles, tables), which the first
25
+ * call in a process pays and later calls don't.
26
+ */
27
+ function overdue(t0, hardStopMs) {
28
+ const init0 = initMs();
29
+ return () => now() - t0 - (initMs() - init0) > hardStopMs;
30
+ }
31
+ export const HIGH_RISK_UNKNOWN = Object.freeze({ level: "high-risk", tags: Object.freeze(["exec.unknown"]), unanalyzable: false, selfProtection: false, reasons: Object.freeze(["the action couldn't be classified"]) });
32
+ function validateCtx(c) {
33
+ if (!isRecord(c))
34
+ return null;
35
+ const policy = get(c, "policy");
36
+ const mode = getString(policy, "mode");
37
+ const ruleset = get(c, "ruleset");
38
+ if (mode !== "strict" && mode !== "balanced" && mode !== "autopilot")
39
+ return null;
40
+ if (!isRecord(ruleset) || !Array.isArray(get(ruleset, "rules")) || !Array.isArray(get(ruleset, "irreversibleTags")))
41
+ return null;
42
+ if (typeof get(c, "homeDir") !== "string" || typeof get(c, "cwd") !== "string" || !Array.isArray(get(c, "glassboxDirs")))
43
+ return null;
44
+ const platform = get(c, "platform");
45
+ if (platform !== "linux" && platform !== "darwin" && platform !== "win32")
46
+ return null;
47
+ const raw = c;
48
+ const limits = resolveLimits(raw.limits);
49
+ const all = Array.isArray(raw.signals) ? raw.signals.filter((s) => isRecord(s) && typeof get(s, "kind") === "string" && typeof get(s, "atCall") === "number") : [];
50
+ const callIndex = all.reduce((m, s) => Math.max(m, s.atCall), 0) + 1;
51
+ const signals = all.filter((s) => s.kind === "protection-degraded" || s.kind === "scheduled-job" || callIndex - s.atCall <= limits.signalTtlCalls);
52
+ const rs = raw.ruleset;
53
+ return {
54
+ raw,
55
+ limits,
56
+ ruleset: rs,
57
+ mode,
58
+ evidenceMode: raw.evidenceMode === "none" ? "none" : "snippet",
59
+ signals,
60
+ callIndex,
61
+ protectionDegraded: rs.protectionDegraded === true || signals.some((s) => s.kind === "protection-degraded"),
62
+ };
63
+ }
64
+ /** Why protection is degraded: the ruleset's own cause, else the reason carried by the session signal. */
65
+ function degradedReason(c) {
66
+ if (c.ruleset.degradedCause)
67
+ return c.ruleset.degradedCause;
68
+ const s = c.signals.find((x) => x.kind === "protection-degraded");
69
+ return s?.kind === "protection-degraded" ? s.reason : "tampered";
70
+ }
71
+ function toolCtx(c) {
72
+ const r = c.raw;
73
+ return {
74
+ pctx: pathCtxFrom({ ...r, cwd: r.cwd }),
75
+ maxCommandBytes: c.limits.maxCommandBytes,
76
+ maxSqlBytes: c.limits.maxSqlBytes,
77
+ };
78
+ }
79
+ export function intake(input, limits) {
80
+ if (typeof input === "string" || input instanceof Uint8Array) {
81
+ const size = typeof input === "string" ? utf8Length(input) : input.length;
82
+ if (size > limits.maxInputBytes)
83
+ return { value: undefined, issues: [{ code: "CP-LIMIT-001" }], degraded: true, tooBig: true };
84
+ const r = parseJsonStrict(input, { maxDepth: limits.maxDepth, maxNodes: limits.maxNodes });
85
+ return { value: r.value, issues: r.issues, degraded: r.degraded, tooBig: false };
86
+ }
87
+ const s = snapshot(input, { maxDepth: limits.maxDepth, maxNodes: limits.maxNodes, maxBytes: limits.maxInputBytes });
88
+ return { value: s.value, issues: s.issues, degraded: s.degraded, tooBig: false };
89
+ }
90
+ function issueFindings(issues, ff) {
91
+ const out = [];
92
+ const seen = new Set();
93
+ for (const i of issues) {
94
+ const k = i.code + (i.pointer ?? "");
95
+ if (seen.has(k))
96
+ continue;
97
+ seen.add(k);
98
+ out.push(ff.make({ ruleId: i.code, location: i.pointer ?? "" }));
99
+ }
100
+ return out.filter((x) => x !== null);
101
+ }
102
+ // ── Shared finishing ─────────────────────────────────────────────────────
103
+ function digest(v) {
104
+ try {
105
+ return sha256Hex(jcs(v ?? null));
106
+ }
107
+ catch {
108
+ return sha256Hex("");
109
+ }
110
+ }
111
+ function rulesetVersion(r) {
112
+ return `${r.rulesetId}@${r.version}+${r.sequence}`;
113
+ }
114
+ function suppress(findings, c, ff) {
115
+ const disabled = new Set(Array.isArray(c.raw.policy.disabledRules) ? c.raw.policy.disabledRules : []);
116
+ const counts = new Map();
117
+ const kept = findings.filter((f) => {
118
+ const r = ff.rule(f.ruleId);
119
+ if (!disabled.has(f.ruleId) || !r || !r.suppressible)
120
+ return true;
121
+ counts.set(f.ruleId, (counts.get(f.ruleId) ?? 0) + 1);
122
+ return false;
123
+ });
124
+ return { kept, suppressed: [...counts].map(([ruleId, count]) => ({ ruleId, count })) };
125
+ }
126
+ function integrityFindings(c, ff) {
127
+ const out = [];
128
+ if (c.protectionDegraded)
129
+ out.push(ff.make({ ruleId: c.ruleset.degradedCause === "downgrade" ? "CP-INTEGRITY-002" : "CP-INTEGRITY-001", location: "" }));
130
+ if (c.ruleset.expired)
131
+ out.push(ff.make({ ruleId: "CP-INTEGRITY-004", location: "" }));
132
+ return out.filter((x) => x !== null);
133
+ }
134
+ function capFindings(fs, c, ff) {
135
+ const sorted = sortFindings(fs);
136
+ if (sorted.length <= c.limits.maxFindings)
137
+ return { findings: sorted, capped: false };
138
+ const kept = sorted.slice(0, c.limits.maxFindings - 1);
139
+ const f = ff.make({ ruleId: "CP-LIMIT-008", location: "" });
140
+ if (f)
141
+ kept.push(f);
142
+ return { findings: kept, capped: true };
143
+ }
144
+ function riskOf(acc) {
145
+ return {
146
+ level: acc.level,
147
+ tags: [...acc.tags].sort(),
148
+ unanalyzable: acc.unanalyzableFlag,
149
+ selfProtection: acc.selfProtection,
150
+ reasons: [...acc.reasons, ...acc.unanalyzableReasons].slice(0, 20),
151
+ };
152
+ }
153
+ export function errorDecision(t0, mode, risk) {
154
+ const r = risk ?? HIGH_RISK_UNKNOWN;
155
+ const verdict = r.level === "high-risk" ? "deny" : "warn"; // R12 / R11
156
+ return {
157
+ verdict,
158
+ actionRisk: r,
159
+ findings: [],
160
+ rulesetVersion: "unknown",
161
+ engineVersion: ENGINE_VERSION,
162
+ degraded: true,
163
+ degradedReasons: ["internal-error"],
164
+ // Q4 (rev 6): the verdict stays as is (warn for a result), but the session is marked
165
+ // protection-degraded, so R16 makes the next high-risk call ask (deny in autopilot).
166
+ // This signal never expires; atCall is unknown here and doesn't matter.
167
+ protectionDegraded: true,
168
+ signals: [{ kind: "protection-degraded", reason: "internal-error", atCall: 0 }],
169
+ suppressed: [],
170
+ mode: mode === "strict" || mode === "autopilot" ? mode : "balanced",
171
+ inputDigest: sha256Hex(""),
172
+ elapsedMs: Math.max(0, now() - t0),
173
+ };
174
+ }
175
+ // ── checkToolCall ────────────────────────────────────────────────────────
176
+ const EGRESS_TAGS = ["net.egress", "publish.public", "message.send"];
177
+ /**
178
+ * Q2 (rev 6): secrets precise enough to ask about when they go to a non-read tool
179
+ * (CP-EXFIL-032). Test-mode keys, example values, JWTs and generic high-entropy strings
180
+ * stay at their usual (warn) level.
181
+ */
182
+ const LIVE_SECRET_TYPES = new Set([
183
+ "private-key", "db-connection-string", "stripe-key", "github-token", "gitlab-token", "slack-token", "slack-webhook",
184
+ "aws-access-key-id", "aws-secret-access-key", "gcp-api-key", "anthropic-key", "openai-key", "azure-storage-key", "azure-conn-string",
185
+ ]);
186
+ const isLiveSecret = (s) => !s.example && LIVE_SECRET_TYPES.has(s.type) && !(s.type === "stripe-key" && (s.value.startsWith("sk_test_") || s.value.startsWith("rk_test_")));
187
+ const ISSUERS = {
188
+ "github-token": "github", "gitlab-token": "gitlab", "slack-token": "slack", "slack-webhook": "slack", "stripe-key": "stripe", "aws-access-key-id": "aws",
189
+ "aws-secret-access-key": "aws", "gcp-api-key": "google", "openai-key": "openai", "anthropic-key": "anthropic", "azure-storage-key": "azure", "azure-conn-string": "azure",
190
+ };
191
+ function callFields(call) {
192
+ const isShell = call.serverId === "builtin" && (call.toolName === "Bash" || call.toolName === "PowerShell");
193
+ const fields = genericFields(call.arguments, "/arguments", "call.arg", "call.arg.key");
194
+ if (isShell)
195
+ for (const f of fields)
196
+ if (f.pointer === "/arguments/command")
197
+ f.role = "call.arg.command";
198
+ return fields;
199
+ }
200
+ export function checkToolCallImpl(input, ctxIn, t0) {
201
+ const init0 = initMs();
202
+ const c = validateCtx(ctxIn);
203
+ if (!c)
204
+ return errorDecision(t0, undefined);
205
+ const ff = new FindingFactory(c.ruleset, c.evidenceMode);
206
+ const ink = intake(input, c.limits);
207
+ const issueFs = issueFindings(ink.issues, ff);
208
+ const v = ink.value;
209
+ const serverId = getString(v, "serverId");
210
+ const toolName = getString(v, "toolName");
211
+ if (ink.tooBig || serverId === undefined || toolName === undefined) {
212
+ const d = errorDecision(t0, c.mode);
213
+ const shape = ff.make({ ruleId: "CP-PARSE-010", location: "" });
214
+ return { ...d, findings: sortFindings([...issueFs, ...(shape && !ink.tooBig ? [shape] : [])]), rulesetVersion: rulesetVersion(c.ruleset), degradedReasons: ink.tooBig ? ["CP-LIMIT-001"] : ["CP-PARSE-010"] };
215
+ }
216
+ const args = get(v, "arguments") ?? Object.create(null);
217
+ const descriptor = isRecord(get(v, "descriptor")) ? get(v, "descriptor") : undefined;
218
+ const call = { serverId, toolName, arguments: args };
219
+ // Action risk.
220
+ const tc = toolCtx(c);
221
+ let acc;
222
+ let contradiction = false;
223
+ if (serverId === "builtin")
224
+ acc = classifyBuiltin(toolName, args, tc);
225
+ else {
226
+ const p = classifyMcp(toolName, args, descriptor, tc);
227
+ acc = p.acc;
228
+ contradiction = p.contradiction;
229
+ }
230
+ const risk = riskOf(acc);
231
+ // Layer 1 on the arguments.
232
+ const scan = scanFields(callFields(call), "call", ff, c.ruleset.rules, c.limits, true, overdue(t0, c.limits.hardStopMs));
233
+ const findings = [...issueFs, ...scan.findings, ...integrityFindings(c, ff)];
234
+ const cmdText = getString(args, "command") ?? getString(args, "query") ?? "";
235
+ for (const cf of acc.findings) {
236
+ if (cf.ruleId === "CP-SELF-006")
237
+ continue; // added below, one per job, with schedule and command
238
+ findings.push(ff.make({ ruleId: cf.ruleId, location: cf.ruleId === "CP-EXFIL-040" ? "/arguments" : "/arguments", text: cmdText.slice(0, 2000), ...(cf.note && cf.ruleId === "CP-SHELL-001" ? {} : {}) }));
239
+ }
240
+ if (contradiction)
241
+ findings.push(ff.make({ ruleId: "CP-CAP-002", location: "/descriptor/annotations" }));
242
+ // Layer 2: correlation with secrets, destinations and session signals.
243
+ const secretFindings = scan.findings.filter((f) => f.ruleId === "CP-SECRET-002" && f.confidence >= 0.5);
244
+ const secretTypes = new Set();
245
+ let liveSecret = false;
246
+ for (const f of callFields(call)) {
247
+ for (const s of detectSecrets(f.text, f.keyName)) {
248
+ if (!s.example)
249
+ secretTypes.add(s.type);
250
+ if (isLiveSecret(s))
251
+ liveSecret = true;
252
+ }
253
+ }
254
+ if (liveSecret && risk.level !== "read")
255
+ findings.push(ff.make({ ruleId: "CP-EXFIL-032", location: secretFindings[0]?.location ?? "/arguments" }));
256
+ const egress = risk.tags.some((t) => EGRESS_TAGS.includes(t));
257
+ if (secretTypes.size > 0 && egress)
258
+ findings.push(ff.make({ ruleId: "CP-EXFIL-031", location: secretFindings[0]?.location ?? "/arguments" }));
259
+ const server = c.raw.servers?.find((s) => s.serverId === serverId);
260
+ const issuerTags = server?.identity?.issuerTags;
261
+ if (issuerTags && issuerTags.length > 0) {
262
+ for (const t of secretTypes) {
263
+ const iss = ISSUERS[t];
264
+ if (iss && !issuerTags.includes(iss)) {
265
+ findings.push(ff.make({ ruleId: "CP-EXFIL-050", location: secretFindings[0]?.location ?? "/arguments" }));
266
+ break;
267
+ }
268
+ }
269
+ }
270
+ const sig = c.signals;
271
+ const has = (k) => sig.some((s) => s.kind === k);
272
+ const chain = (kinds) => sig.filter((s) => kinds.includes(s.kind)).map((s) => `call #${s.atCall}`).slice(0, 6).join(", ");
273
+ if (has("private-data-read") && has("untrusted-content-seen") && egress) {
274
+ const why = `Earlier calls in this session (${chain(["private-data-read", "untrusted-content-seen"])}) read private data and untrusted content.`;
275
+ findings.push(ff.make({ ruleId: "CP-FLOW-001", location: "/arguments", explanation: `${ff.rule("CP-FLOW-001")?.explanation ?? ""} ${why}`.trim() }));
276
+ if (secretTypes.size > 0 || acc.sensitiveArgs)
277
+ findings.push(ff.make({ ruleId: "CP-FLOW-002", location: "/arguments", explanation: `${ff.rule("CP-FLOW-002")?.explanation ?? ""} ${why}`.trim() }));
278
+ }
279
+ if (has("untrusted-content-seen") && (has("secret-seen") || has("sensitive-read")) && risk.tags.includes("net.egress")) {
280
+ const why = `Chain: ${chain(["untrusted-content-seen", "secret-seen", "sensitive-read"])}.`;
281
+ findings.push(ff.make({ ruleId: "CP-FLOW-003", location: "/arguments", explanation: `${ff.rule("CP-FLOW-003")?.explanation ?? ""} ${why}`.trim() }));
282
+ }
283
+ if (sig.some((s) => s.kind === "injection-seen" && s.mentionedTools.includes(toolName)))
284
+ findings.push(ff.make({ ruleId: "CP-INJECT-021", location: "" }));
285
+ // Scheduled jobs (rev 9): show what runs, when, and the full command; record the files it runs.
286
+ const jobs = acc.scheduledJobs.map((j) => enrichJob(j, toolName, args, cmdText, tc.pctx));
287
+ for (const j of jobs) {
288
+ findings.push(ff.make({ ruleId: "CP-SELF-006", location: "/arguments", text: cmdText.slice(0, 2000), explanation: jobExplanation(ff.rule("CP-SELF-006")?.explanation ?? "", j, toolName, args, cmdText, c.limits) }));
289
+ }
290
+ // Agent edits, moves or deletes of files an earlier, approved scheduled job runs (CP-SELF-007).
291
+ const fold = (s) => (c.raw.caseInsensitiveFs ? s.toLowerCase() : s);
292
+ for (const s of sig) {
293
+ if (s.kind !== "scheduled-job" || !Array.isArray(s.files))
294
+ continue; // signals come from the caller
295
+ const hit = s.files.filter((f) => typeof f === "string").slice(0, 100).find((f) => acc.writes.some((w) => fold(w) === fold(f) || fold(f).startsWith(fold(w) + "/")));
296
+ if (hit !== undefined) {
297
+ findings.push(ff.make({ ruleId: "CP-SELF-007", location: "/arguments", text: hit, explanation: `This file runs as a scheduled job: ${hit} (${JOB_LABEL[s.job] ?? "scheduled job"}${s.schedule ? `, ${s.schedule}` : ""}; approved at call #${s.atCall}). Changing, moving or deleting it changes what the job runs.` }));
298
+ break;
299
+ }
300
+ }
301
+ // Any local file upload once the session has read untrusted content (rev 8, Q1).
302
+ if (acc.uploads.length > 0 && has("untrusted-content-seen")) {
303
+ findings.push(ff.make({ ruleId: "CP-EXFIL-036", location: "/arguments", explanation: `${ff.rule("CP-EXFIL-036")?.explanation ?? ""} Untrusted content: ${chain(["untrusted-content-seen"])}.`.trim() }));
304
+ }
305
+ // Limits / degraded.
306
+ const degradedReasons = [];
307
+ if (ink.degraded)
308
+ degradedReasons.push(...new Set(ink.issues.map((i) => i.code)));
309
+ if (scan.windowed)
310
+ degradedReasons.push("CP-LIMIT-006");
311
+ if (scan.decodeExhausted) {
312
+ degradedReasons.push("CP-LIMIT-007");
313
+ findings.push(ff.make({ ruleId: "CP-LIMIT-007", location: "" }));
314
+ }
315
+ // One-time initialization (regex compiles, tables) doesn't count against the backstop.
316
+ if (scan.timedOut || now() - t0 - (initMs() - init0) > c.limits.hardStopMs) {
317
+ degradedReasons.push("CP-LIMIT-010");
318
+ findings.push(ff.make({ ruleId: "CP-LIMIT-010", location: "" }));
319
+ }
320
+ let fs = dedupe(findings);
321
+ const sup = suppress(fs, c, ff);
322
+ fs = sup.kept;
323
+ const capped = capFindings(fs, c, ff);
324
+ fs = capped.findings;
325
+ const degraded = degradedReasons.length > 0;
326
+ // Signals.
327
+ const signals = [];
328
+ const at = c.callIndex;
329
+ for (const label of new Set(acc.sensitive)) {
330
+ signals.push({ kind: "sensitive-read", label, atCall: at });
331
+ signals.push({ kind: "private-data-read", source: "sensitive-path", serverId, toolName, atCall: at });
332
+ }
333
+ for (const t of secretTypes)
334
+ signals.push({ kind: "secret-seen", secretType: t, atCall: at });
335
+ const ext = risk.tags.filter((t) => EGRESS_TAGS.includes(t));
336
+ if (ext.length > 0)
337
+ signals.push({ kind: "external-write", serverId, toolName, tags: ext, atCall: at });
338
+ if (c.protectionDegraded)
339
+ signals.push({ kind: "protection-degraded", reason: degradedReason(c), atCall: at });
340
+ // A job that creates or changes something runs its files later. The caller keeps this signal
341
+ // only if the call is approved and runs (engine-spec §4.5); it doesn't expire.
342
+ for (const j of jobs)
343
+ if (j.verb !== "removes" && j.files.length > 0)
344
+ signals.push({ kind: "scheduled-job", job: j.kind, schedule: j.schedule, files: j.files, atCall: at });
345
+ const out = decide({
346
+ kind: "call", risk, findings: fs, degraded, protectionDegraded: c.protectionDegraded, ruleset: c.ruleset, policy: c.raw.policy,
347
+ minConfidence: c.limits.minConfidenceForVerdict, serverId, toolName, remembered: Array.isArray(c.raw.remembered) ? c.raw.remembered : [],
348
+ });
349
+ return {
350
+ verdict: out.verdict,
351
+ actionRisk: risk,
352
+ findings: fs,
353
+ rulesetVersion: rulesetVersion(c.ruleset),
354
+ engineVersion: ENGINE_VERSION,
355
+ degraded,
356
+ degradedReasons,
357
+ protectionDegraded: c.protectionDegraded,
358
+ signals,
359
+ suppressed: sup.suppressed,
360
+ mode: c.mode,
361
+ ...(out.verdictBeforeMode !== undefined ? { verdictBeforeMode: out.verdictBeforeMode } : {}),
362
+ inputDigest: digest(args),
363
+ elapsedMs: Math.max(0, now() - t0),
364
+ };
365
+ }
366
+ // ── checkToolResult ──────────────────────────────────────────────────────
367
+ const DIRECTIVES = new Set(["call", "run", "use", "invoke", "execute", "delete", "send", "now", "immediately", "must", "should", "always", "next", "then", "please"]);
368
+ const UNTRUSTED_BUILTINS = new Set(["WebFetch", "WebSearch"]);
369
+ export function checkToolResultImpl(input, ctxIn, t0) {
370
+ const c = validateCtx(ctxIn);
371
+ if (!c)
372
+ return errorDecision(t0, undefined, { ...HIGH_RISK_UNKNOWN, level: "read" });
373
+ const ff = new FindingFactory(c.ruleset, c.evidenceMode);
374
+ const ink = intake(input, c.limits);
375
+ const issueFs = issueFindings(ink.issues, ff);
376
+ const v = ink.value;
377
+ const call = get(v, "call");
378
+ const serverId = getString(call, "serverId");
379
+ const toolName = getString(call, "toolName");
380
+ if (ink.tooBig || serverId === undefined || toolName === undefined || !isRecord(v) || !Object.prototype.hasOwnProperty.call(v, "result")) {
381
+ const d = errorDecision(t0, c.mode, { ...HIGH_RISK_UNKNOWN, level: "read" });
382
+ return { ...d, findings: issueFs, rulesetVersion: rulesetVersion(c.ruleset), degradedReasons: ink.tooBig ? ["CP-LIMIT-001"] : ["CP-PARSE-010"] };
383
+ }
384
+ const result = get(v, "result");
385
+ const args = get(call, "arguments") ?? Object.create(null);
386
+ const tc = toolCtx(c);
387
+ const acc = serverId === "builtin" ? classifyBuiltin(toolName, args, tc) : classifyMcp(toolName, args, isRecord(get(call, "descriptor")) ? get(call, "descriptor") : undefined, tc).acc;
388
+ const risk = riskOf(acc);
389
+ const fields = genericFields(result, "/result", "result.text", "result.key").filter((f) => f.kind === "string");
390
+ const late = overdue(t0, c.limits.hardStopMs);
391
+ const scan = scanFields(fields, "result", ff, c.ruleset.rules, c.limits, true, late);
392
+ const findings = [...issueFs, ...scan.findings, ...integrityFindings(c, ff)];
393
+ // CP-INJECT-020: a session tool named next to directive language.
394
+ const sessionTools = new Map();
395
+ for (const s of c.raw.servers ?? [])
396
+ for (const t of s.toolNames ?? [])
397
+ sessionTools.set(t, (s.highRiskTools ?? []).includes(t));
398
+ // Red team (Step 5): "use the GitHub tool to …" names a server, not a tool.
399
+ for (const s of c.raw.servers ?? []) {
400
+ if (s.serverId === serverId)
401
+ continue;
402
+ for (const n of [s.serverId, ...(s.identity?.issuerTags ?? [])])
403
+ if (typeof n === "string" && n.length >= 4)
404
+ sessionTools.set(n, false);
405
+ }
406
+ const mentioned = new Set();
407
+ // After a timeout, only fields the scan reached are examined (empty fields are never
408
+ // scanned and can't match, so without a timeout this is every field).
409
+ const reached = fields.filter((f) => scan.scans.has(f));
410
+ for (const f of reached) {
411
+ const words = tokenize(f.text.slice(0, c.limits.maxFieldScanBytes));
412
+ const lowerWords = new Set(words.map((w) => w.w.toLowerCase()));
413
+ const directive = [...DIRECTIVES].some((d) => lowerWords.has(d));
414
+ for (const name of sessionTools.keys()) {
415
+ if (name.length >= 3 && directive && (f.text.includes(name) || (name.length >= 4 && lowerWords.has(name.toLowerCase())))) {
416
+ mentioned.add(name);
417
+ const at = Math.max(0, f.text.toLowerCase().indexOf(name.toLowerCase()));
418
+ findings.push(ff.make({ ruleId: "CP-INJECT-020", location: f.pointer, text: f.text, start: at, end: at + name.length, ...(sessionTools.get(name) ? { severity: "critical" } : {}) }));
419
+ }
420
+ }
421
+ }
422
+ const degradedReasons = [];
423
+ if (ink.degraded)
424
+ degradedReasons.push(...new Set(ink.issues.map((i) => i.code)));
425
+ if (scan.windowed)
426
+ degradedReasons.push("CP-LIMIT-006");
427
+ if (scan.decodeExhausted)
428
+ degradedReasons.push("CP-LIMIT-007");
429
+ if (scan.timedOut || late()) {
430
+ degradedReasons.push("CP-LIMIT-010");
431
+ findings.push(ff.make({ ruleId: "CP-LIMIT-010", location: "" }));
432
+ }
433
+ let fs = dedupe(findings);
434
+ const sup = suppress(fs, c, ff);
435
+ fs = capFindings(sup.kept, c, ff).findings;
436
+ const degraded = degradedReasons.length > 0;
437
+ // Signals.
438
+ const at = c.callIndex;
439
+ const signals = [];
440
+ const injected = fs.some((f) => f.ruleId.startsWith("CP-INJECT-") && sevRank(f.severity) >= 3);
441
+ if (injected) {
442
+ for (const f of reached)
443
+ for (const name of sessionTools.keys())
444
+ if (f.text.includes(name))
445
+ mentioned.add(name);
446
+ signals.push({ kind: "injection-seen", serverId, mentionedTools: [...mentioned].sort(), atCall: at });
447
+ }
448
+ const secretTypes = new Set();
449
+ for (const f of reached) {
450
+ // Reuse the scan's secret results when the field was scanned whole (same text, same key).
451
+ const memo = scan.scans.get(f)?.windowed === false ? scan.scans.get(f)?.secrets : undefined;
452
+ for (const s of detectSecrets(f.text.slice(0, c.limits.maxFieldScanBytes), f.keyName, memo))
453
+ if (!s.example)
454
+ secretTypes.add(s.type);
455
+ }
456
+ for (const t of secretTypes)
457
+ signals.push({ kind: "secret-seen", secretType: t, atCall: at });
458
+ const untrusted = serverId !== "builtin" || UNTRUSTED_BUILTINS.has(toolName) || risk.tags.includes("net.egress") || degraded || injected;
459
+ if (untrusted)
460
+ signals.push({ kind: "untrusted-content-seen", serverId, toolName, atCall: at });
461
+ if (c.protectionDegraded)
462
+ signals.push({ kind: "protection-degraded", reason: degradedReason(c), atCall: at });
463
+ const out = decide({
464
+ kind: "result", risk, findings: fs, degraded, protectionDegraded: c.protectionDegraded, ruleset: c.ruleset, policy: c.raw.policy,
465
+ minConfidence: c.limits.minConfidenceForVerdict, serverId, toolName, remembered: [],
466
+ });
467
+ let resultRewrite;
468
+ if (out.verdict === "deny") {
469
+ const top = fs[0];
470
+ resultRewrite = { kind: "replace-with-notice", value: `[Glassbox withheld this tool output: ${top ? `${top.ruleId}. ${top.explanation}` : "it failed a check"}]` };
471
+ }
472
+ else if (c.mode === "strict" && fs.some((f) => f.category === "secret-exposure" && f.confidence >= 0.9)) {
473
+ resultRewrite = { kind: "redact-secrets", value: redactValue(result, c.limits, 0.9).value };
474
+ }
475
+ return {
476
+ verdict: out.verdict,
477
+ actionRisk: risk,
478
+ findings: fs,
479
+ rulesetVersion: rulesetVersion(c.ruleset),
480
+ engineVersion: ENGINE_VERSION,
481
+ degraded,
482
+ degradedReasons,
483
+ protectionDegraded: c.protectionDegraded,
484
+ signals,
485
+ suppressed: sup.suppressed,
486
+ mode: c.mode,
487
+ ...(out.verdictBeforeMode !== undefined ? { verdictBeforeMode: out.verdictBeforeMode } : {}),
488
+ inputDigest: digest(result),
489
+ ...(resultRewrite ? { resultRewrite } : {}),
490
+ elapsedMs: Math.max(0, now() - t0),
491
+ };
492
+ }
493
+ // ── checkServerRequest ───────────────────────────────────────────────────
494
+ const DEFAULT_REQUEST = { sampling: "deny", elicitation: "deny", roots: "deny", unknown: "deny", ping: "allow", notification: "allow" };
495
+ export function checkServerRequestImpl(input, ctxIn, t0) {
496
+ const c = validateCtx(ctxIn);
497
+ if (!c)
498
+ return errorDecision(t0, undefined);
499
+ const ff = new FindingFactory(c.ruleset, c.evidenceMode);
500
+ const ink = intake(input, c.limits);
501
+ const v = ink.value;
502
+ const serverId = getString(v, "serverId") ?? "unknown";
503
+ const msg = get(v, "message");
504
+ const method = getString(msg, "method") ?? "";
505
+ const params = get(msg, "params");
506
+ const kind = method === "sampling/createMessage" ? "sampling" : method === "elicitation/create" ? "elicitation" : method === "roots/list" ? "roots" : method === "ping" ? "ping" : method.startsWith("notifications/") ? "notification" : "unknown";
507
+ const fields = [];
508
+ if (kind === "sampling") {
509
+ fields.push(...genericFields(get(params, "messages"), "/message/params/messages", "srvreq.sampling", "srvreq.key").filter((f) => f.kind === "string"));
510
+ const sp = getString(params, "systemPrompt");
511
+ if (sp !== undefined)
512
+ fields.push({ pointer: "/message/params/systemPrompt", kind: "string", role: "srvreq.sampling", text: sp, keyName: "systemPrompt" });
513
+ }
514
+ else if (kind === "elicitation") {
515
+ const m = getString(params, "message");
516
+ if (m !== undefined)
517
+ fields.push({ pointer: "/message/params/message", kind: "string", role: "srvreq.elicitation", text: m, keyName: "message" });
518
+ fields.push(...genericFields(get(params, "requestedSchema"), "/message/params/requestedSchema", "srvreq.elicitation", "srvreq.elicitation.key"));
519
+ }
520
+ else {
521
+ fields.push(...genericFields(params, "/message/params", "srvreq.other", "srvreq.key").filter((f) => f.kind === "string"));
522
+ }
523
+ const late = overdue(t0, c.limits.hardStopMs);
524
+ const scan = scanFields(fields, "server-request", ff, c.ruleset.rules, c.limits, false, late);
525
+ const timeFinding = scan.timedOut || late() ? ff.make({ ruleId: "CP-LIMIT-010", location: "" }) : null;
526
+ if (timeFinding)
527
+ scan.findings.push(timeFinding);
528
+ const findings = [...issueFindings(ink.issues, ff), ...scan.findings, ...integrityFindings(c, ff)];
529
+ if (kind === "sampling") {
530
+ const inc = getString(params, "includeContext");
531
+ if (inc !== undefined && inc !== "none")
532
+ findings.push(ff.make({ ruleId: "CP-SRVREQ-001", location: "/message/params/includeContext" }));
533
+ }
534
+ if (kind === "roots")
535
+ findings.push(ff.make({ ruleId: "CP-SRVREQ-020", location: "/message" }));
536
+ if (kind === "unknown")
537
+ findings.push(ff.make({ ruleId: "CP-SRVREQ-030", location: "/message/method" }));
538
+ if (method === "notifications/tools/list_changed")
539
+ findings.push(ff.make({ ruleId: "CP-SRVREQ-040", location: "/message/method" }));
540
+ const pol = c.raw.policy.serverRequests;
541
+ let choice = DEFAULT_REQUEST[kind];
542
+ if (kind === "sampling" || kind === "elicitation" || kind === "roots") {
543
+ const per = pol?.perServer?.[serverId]?.[kind];
544
+ const def = pol?.default?.[kind];
545
+ const pick = per ?? def;
546
+ if (pick === "allow" || pick === "ask" || pick === "deny")
547
+ choice = pick;
548
+ }
549
+ const locked = kind === "unknown" || ink.tooBig;
550
+ if (locked)
551
+ choice = "deny";
552
+ let fs = dedupe(findings);
553
+ const sup = suppress(fs, c, ff);
554
+ fs = capFindings(sup.kept, c, ff).findings;
555
+ const risk = kind === "sampling" || kind === "elicitation" ? { level: "high-risk", tags: ["exec.unknown"], unanalyzable: false, selfProtection: false, reasons: [`server request: ${kind}`] } : { level: "read", tags: [], unanalyzable: false, selfProtection: false, reasons: [`server request: ${kind}`] };
556
+ const degraded = ink.degraded || scan.windowed || scan.timedOut;
557
+ const out = decide({
558
+ kind: "server-request", risk, findings: fs, degraded, protectionDegraded: c.protectionDegraded, ruleset: c.ruleset, policy: c.raw.policy,
559
+ minConfidence: c.limits.minConfidenceForVerdict, serverId, toolName: method, remembered: [], requestVerdict: { verdict: choice, locked },
560
+ });
561
+ return {
562
+ verdict: out.verdict,
563
+ actionRisk: risk,
564
+ findings: fs,
565
+ rulesetVersion: rulesetVersion(c.ruleset),
566
+ engineVersion: ENGINE_VERSION,
567
+ degraded,
568
+ degradedReasons: degraded ? [...new Set(ink.issues.map((i) => i.code))] : [],
569
+ protectionDegraded: c.protectionDegraded,
570
+ signals: c.protectionDegraded ? [{ kind: "protection-degraded", reason: degradedReason(c), atCall: c.callIndex }] : [],
571
+ suppressed: sup.suppressed,
572
+ mode: c.mode,
573
+ ...(out.verdictBeforeMode !== undefined ? { verdictBeforeMode: out.verdictBeforeMode } : {}),
574
+ inputDigest: digest(msg),
575
+ elapsedMs: Math.max(0, now() - t0),
576
+ };
577
+ }
578
+ // ── Scheduled jobs (rev 9) ───────────────────────────────────────────────
579
+ /** The text a tool call writes: Write content, Edit new_string, MultiEdit edits, MCP content. */
580
+ function writtenContent(args) {
581
+ if (!isRecord(args))
582
+ return "";
583
+ const parts = [];
584
+ for (const k of ["content", "new_string", "text", "body", "data"]) {
585
+ const v = getString(args, k);
586
+ if (v)
587
+ parts.push(v);
588
+ }
589
+ const edits = get(args, "edits");
590
+ if (Array.isArray(edits))
591
+ for (const e of edits.slice(0, 50)) {
592
+ const v = getString(e, "new_string");
593
+ if (v)
594
+ parts.push(v);
595
+ }
596
+ return parts.join("\n").slice(0, 200_000);
597
+ }
598
+ function enrichJob(j, toolName, args, cmdText, pctx) {
599
+ const content = writtenContent(args);
600
+ const source = content || cmdText;
601
+ let schedule = j.schedule;
602
+ const files = [...j.files];
603
+ const p = (j.path ?? "").toLowerCase();
604
+ const fromDef = j.kind === "launchd" && j.path ? plistJob(source)
605
+ : j.kind === "systemd" && j.path ? unitJob(source)
606
+ : j.kind === "autostart" && j.path ? desktopJob(source)
607
+ : j.kind === "task-scheduler" && schedule === null ? psTaskJob(cmdText)
608
+ : null;
609
+ if (fromDef) {
610
+ schedule ??= fromDef.schedule;
611
+ files.push(...fromDef.files);
612
+ }
613
+ if (j.kind === "cron" && j.verb !== "removes") {
614
+ const period = ["hourly", "daily", "weekly", "monthly"].find((x) => p.includes(`/etc/cron.${x}/`));
615
+ if (period)
616
+ schedule ??= period;
617
+ else {
618
+ const lines = cronLines(source);
619
+ if (lines.length > 0) {
620
+ schedule ??= lines.map((l) => l.schedule).join("; ");
621
+ for (const l of lines)
622
+ files.push(...commandFiles(l.command));
623
+ }
624
+ }
625
+ }
626
+ if (j.kind === "at" && files.length === 0)
627
+ files.push(...commandFiles(quoted(cmdText)));
628
+ if (j.kind === "boot-script")
629
+ schedule ??= "at boot";
630
+ if (j.kind === "startup-folder")
631
+ schedule ??= "at login";
632
+ const abs = (f) => normalizePath(f, pctx).path ?? f;
633
+ void toolName;
634
+ return { ...j, schedule, files: [...new Set(files.map(abs))].slice(0, 20) };
635
+ }
636
+ /** The text inside quotes (what `echo '…' | at …` runs). */
637
+ function quoted(text) {
638
+ const out = [];
639
+ for (const q of ["'", '"']) {
640
+ let i = text.indexOf(q);
641
+ while (i >= 0 && out.length < 20) {
642
+ const e = text.indexOf(q, i + 1);
643
+ if (e < 0)
644
+ break;
645
+ out.push(text.slice(i + 1, e));
646
+ i = text.indexOf(q, e + 1);
647
+ }
648
+ }
649
+ return out.join(" ");
650
+ }
651
+ function jobExplanation(base, j, toolName, args, cmdText, limits) {
652
+ const what = `${j.verb} a ${JOB_LABEL[j.kind]}${j.path ? ` (${j.path})` : ""}`;
653
+ const runs = j.files.length > 0 ? j.files.join(", ") : "not visible in the call";
654
+ const full = cmdText || `${toolName} ${getString(args, "file_path") ?? getString(args, "path") ?? ""}\n${writtenContent(args)}`.trim();
655
+ const red = redactString(full, undefined, limits).text;
656
+ const cap = 4000;
657
+ const shown = red.length > cap ? `${red.slice(0, cap)} … (${red.length - cap} more characters)` : red;
658
+ return `${base} This call ${what}. Schedule: ${j.schedule ?? "not visible in the call"}. Runs: ${runs}. Full command: ${shown}`;
659
+ }
660
+ //# sourceMappingURL=gate.js.map
@@ -0,0 +1,3 @@
1
+ import type { AnalyzeOptions, ServerReport } from "../types.js";
2
+ export declare function analyzeServerImpl(manifestIn: unknown, opts: AnalyzeOptions | undefined, t0: number): ServerReport;
3
+ //# sourceMappingURL=manifest.d.ts.map