@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,6 @@
1
+ export interface ShellView {
2
+ analyzable: boolean;
3
+ commands: (string | null)[][];
4
+ }
5
+ export declare function shellArgvView(src: string): ShellView;
6
+ //# sourceMappingURL=view.d.ts.map
@@ -0,0 +1,89 @@
1
+ // T-DIFF support (engine-spec §13): the parser's view of which commands a shell string
2
+ // runs, as argv lists. Unknown words are null (they match zero or more real words).
3
+ import { analyzeShellCommand, wordInfo } from "./analyze.js";
4
+ import { parseShell } from "./parse.js";
5
+ const VIEW_CTX = {
6
+ pctx: { platform: "linux", homeDir: "/home/u", cwd: "/home/u/proj", caseInsensitive: false, glassboxDirs: ["/home/u/.glassbox"], extraProtected: [], extraSensitive: [], secretPaths: [] },
7
+ depth: 0,
8
+ maxBytes: 16 * 1024,
9
+ };
10
+ function expandBrace(w) {
11
+ if (!w.parts.every((p) => p.t === "lit"))
12
+ return null;
13
+ const s = w.parts.map((p) => p.s).join("");
14
+ const raw = w.raw;
15
+ const open = raw.indexOf("{");
16
+ const close = raw.indexOf("}", open);
17
+ if (open < 0 || close < 0 || raw.slice(open + 1).indexOf("{") >= 0 && raw.slice(open + 1).indexOf("{") < close - open - 1)
18
+ return null;
19
+ const inner = raw.slice(open + 1, close);
20
+ if (!inner.includes(",") || inner.includes("..") || /['"$`]/.test(raw))
21
+ return null;
22
+ const alts = inner.split(",");
23
+ if (alts.some((a) => a === ""))
24
+ return null;
25
+ const pre = raw.slice(0, open);
26
+ const post = raw.slice(close + 1);
27
+ if (post.includes("{"))
28
+ return null;
29
+ void s;
30
+ return alts.map((a) => pre + a + post);
31
+ }
32
+ function argvOf(c) {
33
+ const out = [];
34
+ for (const w of c.words) {
35
+ if (w.brace) {
36
+ const e = expandBrace(w);
37
+ if (e) {
38
+ out.push(...e);
39
+ continue;
40
+ }
41
+ out.push(null);
42
+ continue;
43
+ }
44
+ const info = wordInfo(w);
45
+ out.push(info.dynamic || info.glob || hasEqTilde(w) ? null : info.value);
46
+ }
47
+ return out;
48
+ }
49
+ function hasEqTilde(w) {
50
+ return w.parts.some((p) => p.t === "lit" && !p.quoted && /=~|:~/.test(p.s));
51
+ }
52
+ function collect(script, out) {
53
+ for (const c of script.commands) {
54
+ const argv = argvOf(c);
55
+ if (argv.length > 0) {
56
+ out.push(argv);
57
+ // `command x`, `builtin x`, `exec x`: bash runs x itself.
58
+ let k = 0;
59
+ while (["command", "builtin", "exec", "time"].includes(argv[k] ?? "") && k < 3) {
60
+ k++;
61
+ while ((argv[k] ?? "").startsWith("-") && k < argv.length)
62
+ k++;
63
+ if (k < argv.length)
64
+ out.push(argv.slice(k));
65
+ }
66
+ }
67
+ const words = [...c.words, ...c.assigns.flatMap((a) => (a.value ? [a.value] : [])), ...c.redirects.flatMap((r) => (r.target ? [r.target] : []))];
68
+ for (const w of words)
69
+ for (const p of w.parts)
70
+ if (p.t === "subst")
71
+ collect(p.script, out);
72
+ for (const r of c.redirects)
73
+ if (r.heredoc?.script)
74
+ collect(r.heredoc.script, out);
75
+ }
76
+ }
77
+ export function shellArgvView(src) {
78
+ try {
79
+ const script = parseShell(src, { maxBytes: VIEW_CTX.maxBytes });
80
+ const acc = analyzeShellCommand(src, VIEW_CTX);
81
+ const commands = [];
82
+ collect(script, commands);
83
+ return { analyzable: !acc.unanalyzableFlag, commands };
84
+ }
85
+ catch {
86
+ return { analyzable: false, commands: [] };
87
+ }
88
+ }
89
+ //# sourceMappingURL=view.js.map
@@ -0,0 +1,3 @@
1
+ import { Acc } from "./acc.js";
2
+ export declare function analyzeSql(sql: string, maxBytes: number): Acc;
3
+ //# sourceMappingURL=sql.d.ts.map
@@ -0,0 +1,259 @@
1
+ // SQL tokenizer and classifier (engine-spec §7.5). Linear, no regex on input.
2
+ import { Acc } from "./acc.js";
3
+ function tokenize(sql) {
4
+ const stmts = [[]];
5
+ let i = 0;
6
+ const n = sql.length;
7
+ const cur = () => stmts[stmts.length - 1];
8
+ while (i < n) {
9
+ const c = sql[i];
10
+ if (c === " " || c === "\t" || c === "\n" || c === "\r" || c === "\f") {
11
+ i++;
12
+ continue;
13
+ }
14
+ if (c === "-" && sql[i + 1] === "-") {
15
+ while (i < n && sql[i] !== "\n")
16
+ i++;
17
+ continue;
18
+ }
19
+ if (c === "#") {
20
+ while (i < n && sql[i] !== "\n")
21
+ i++;
22
+ continue;
23
+ }
24
+ if (c === "/" && sql[i + 1] === "*") {
25
+ const end = sql.indexOf("*/", i + 2);
26
+ if (end < 0)
27
+ return "unterminated comment";
28
+ if (sql.slice(i + 2, end).includes("/*"))
29
+ return "nested comment";
30
+ i = end + 2;
31
+ continue;
32
+ }
33
+ if (c === "'" || c === '"' || c === "`") {
34
+ let j = i + 1;
35
+ let v = "";
36
+ for (;;) {
37
+ if (j >= n)
38
+ return "unterminated string";
39
+ if (sql[j] === c) {
40
+ if (sql[j + 1] === c) {
41
+ v += c;
42
+ j += 2;
43
+ continue;
44
+ }
45
+ break;
46
+ }
47
+ if (sql[j] === "\\" && c === "'") {
48
+ v += sql[j + 1] ?? "";
49
+ j += 2;
50
+ continue;
51
+ }
52
+ v += sql[j];
53
+ j++;
54
+ }
55
+ cur().push({ k: c === "'" ? "str" : "word", v: c === "'" ? v : v.toUpperCase() });
56
+ i = j + 1;
57
+ continue;
58
+ }
59
+ if (c === "$") {
60
+ let j = i + 1;
61
+ while (j < n && /[A-Za-z0-9_]/.test(sql[j]))
62
+ j++;
63
+ if (sql[j] === "$") {
64
+ const tag = sql.slice(i, j + 1);
65
+ const end = sql.indexOf(tag, j + 1);
66
+ if (end < 0)
67
+ return "unterminated dollar quote";
68
+ cur().push({ k: "str", v: sql.slice(j + 1, end) });
69
+ i = end + tag.length;
70
+ continue;
71
+ }
72
+ }
73
+ if (c === ";") {
74
+ stmts.push([]);
75
+ i++;
76
+ continue;
77
+ }
78
+ if (/[A-Za-z_]/.test(c)) {
79
+ let j = i;
80
+ while (j < n && /[A-Za-z0-9_$]/.test(sql[j]))
81
+ j++;
82
+ cur().push({ k: "word", v: sql.slice(i, j).toUpperCase() });
83
+ i = j;
84
+ continue;
85
+ }
86
+ if (/[0-9]/.test(c)) {
87
+ let j = i;
88
+ while (j < n && /[0-9.eE]/.test(sql[j]))
89
+ j++;
90
+ cur().push({ k: "num", v: sql.slice(i, j) });
91
+ i = j;
92
+ continue;
93
+ }
94
+ cur().push({ k: "punct", v: c });
95
+ i++;
96
+ }
97
+ return stmts.filter((s) => s.length > 0);
98
+ }
99
+ function tautology(where) {
100
+ if (where.length === 0)
101
+ return true;
102
+ const first = where[0];
103
+ if (where.length === 1 && first && ((first.k === "word" && first.v === "TRUE") || (first.k === "num" && first.v !== "0")))
104
+ return true;
105
+ for (let i = 0; i + 2 < where.length; i++) {
106
+ const a = where[i], op = where[i + 1], b = where[i + 2];
107
+ if (op.k === "punct" && op.v === "=" && a.k === b.k && a.v === b.v && a.k !== "punct") {
108
+ const prev = where[i - 1];
109
+ const next = where[i + 3];
110
+ const standalone = (!prev || prev.v === "OR" || prev.v === "WHERE" || prev.v === "(" || i === 0) && (!next || next.v === "OR" || next.v === ")" || next.v === "AND" && i === 0);
111
+ if (standalone || where.length === 3)
112
+ return true;
113
+ }
114
+ if (a.v === "OR" && (b.v === "TRUE" || (op.k === "num" && op.v === "1" && !b)))
115
+ return true;
116
+ }
117
+ return where.some((t, k) => t.v === "OR" && (where[k + 1]?.v === "TRUE"));
118
+ }
119
+ export function analyzeSql(sql, maxBytes) {
120
+ const acc = new Acc();
121
+ if (sql.length > maxBytes) {
122
+ acc.unanalyzable("SQL longer than the analysis limit");
123
+ return acc;
124
+ }
125
+ const stmts = tokenize(sql);
126
+ if (typeof stmts === "string") {
127
+ acc.unanalyzable(`SQL ${stmts}`);
128
+ return acc;
129
+ }
130
+ for (const s of stmts) {
131
+ let k = 0;
132
+ while (s[k]?.v === "(")
133
+ k++;
134
+ const first = s[k]?.v ?? "";
135
+ const words = s.filter((t) => t.k === "word").map((t) => t.v);
136
+ const whereIdx = s.findIndex((t) => t.k === "word" && t.v === "WHERE");
137
+ const whereToks = whereIdx >= 0 ? s.slice(whereIdx + 1) : null;
138
+ switch (first) {
139
+ case "SELECT":
140
+ case "SHOW":
141
+ case "DESCRIBE":
142
+ case "DESC":
143
+ case "VALUES":
144
+ case "TABLE":
145
+ acc.tag("read", "db.read");
146
+ break;
147
+ case "EXPLAIN":
148
+ if (words.includes("ANALYZE"))
149
+ acc.tag("write-reversible", "db.write");
150
+ else
151
+ acc.tag("read", "db.read");
152
+ break;
153
+ case "WITH": {
154
+ const w = ["DELETE", "UPDATE", "INSERT", "MERGE"].find((x) => words.includes(x));
155
+ if (!w) {
156
+ acc.tag("read", "db.read");
157
+ break;
158
+ }
159
+ if (w === "DELETE" || w === "UPDATE") {
160
+ if (whereToks === null || tautology(whereToks)) {
161
+ acc.tag("high-risk", "db.unscoped-write");
162
+ acc.find("CP-ACTION-020");
163
+ }
164
+ else
165
+ acc.tag(w === "DELETE" ? "high-risk" : "write-reversible", w === "DELETE" ? "db.delete" : "db.write");
166
+ }
167
+ else
168
+ acc.tag("write-reversible", "db.write");
169
+ break;
170
+ }
171
+ case "INSERT":
172
+ case "UPSERT":
173
+ case "REPLACE":
174
+ case "MERGE":
175
+ acc.tag("write-reversible", "db.write");
176
+ break;
177
+ case "COPY":
178
+ if (words.includes("PROGRAM")) {
179
+ acc.unanalyzable("COPY … PROGRAM runs a shell command");
180
+ break;
181
+ }
182
+ acc.tag(words.includes("FROM") ? "write-reversible" : "read", words.includes("FROM") ? "db.write" : "db.read");
183
+ break;
184
+ case "UPDATE":
185
+ if (whereToks === null || tautology(whereToks)) {
186
+ acc.tag("high-risk", "db.unscoped-write");
187
+ acc.find("CP-ACTION-020");
188
+ acc.reason("updates every row");
189
+ }
190
+ else
191
+ acc.tag("write-reversible", "db.write");
192
+ break;
193
+ case "DELETE":
194
+ if (whereToks === null || tautology(whereToks)) {
195
+ acc.tag("high-risk", "db.unscoped-write", "db.delete");
196
+ acc.find("CP-ACTION-020");
197
+ acc.reason("deletes every row");
198
+ }
199
+ else
200
+ acc.tag("high-risk", "db.delete");
201
+ break;
202
+ case "DROP":
203
+ case "TRUNCATE":
204
+ acc.tag("high-risk", "db.ddl");
205
+ acc.find("CP-ACTION-021");
206
+ acc.reason("drops or truncates a table");
207
+ break;
208
+ case "ALTER":
209
+ if (s[k + 1]?.v === "ROLE" || s[k + 1]?.v === "USER")
210
+ acc.tag("high-risk", "perm.change");
211
+ else
212
+ acc.tag("high-risk", "db.ddl");
213
+ break;
214
+ case "CREATE":
215
+ if (s[k + 1]?.v === "ROLE" || s[k + 1]?.v === "USER")
216
+ acc.tag("high-risk", "perm.change");
217
+ else if (s[k + 1]?.v === "OR" && s[k + 2]?.v === "REPLACE")
218
+ acc.tag("high-risk", "db.ddl");
219
+ else if (words.includes("FUNCTION") || words.includes("PROCEDURE") || words.includes("TRIGGER"))
220
+ acc.tag("high-risk", "db.ddl");
221
+ else
222
+ acc.tag("write-reversible", "db.write");
223
+ break;
224
+ case "RENAME":
225
+ acc.tag("high-risk", "db.ddl");
226
+ break;
227
+ case "GRANT":
228
+ case "REVOKE":
229
+ acc.tag("high-risk", "perm.change");
230
+ break;
231
+ case "BEGIN":
232
+ case "COMMIT":
233
+ case "ROLLBACK":
234
+ case "START":
235
+ case "SAVEPOINT":
236
+ case "RELEASE":
237
+ case "USE":
238
+ case "SET":
239
+ case "END":
240
+ break;
241
+ case "ANALYZE":
242
+ case "VACUUM":
243
+ case "REINDEX":
244
+ case "CLUSTER":
245
+ acc.tag("write-reversible", "db.write");
246
+ break;
247
+ case "PRAGMA":
248
+ if (s.some((t) => t.v === "="))
249
+ acc.unanalyzable("PRAGMA that writes settings");
250
+ else
251
+ acc.tag("read", "db.read");
252
+ break;
253
+ default:
254
+ acc.unanalyzable(first ? `SQL statement ${first.slice(0, 20)} isn't analyzed` : "SQL statement couldn't be classified");
255
+ }
256
+ }
257
+ return acc;
258
+ }
259
+ //# sourceMappingURL=sql.js.map
@@ -0,0 +1,20 @@
1
+ import type { ToolDef } from "../types.js";
2
+ import { Acc } from "./acc.js";
3
+ import { type PathCtx } from "./paths.js";
4
+ export interface ToolCtx {
5
+ pctx: PathCtx;
6
+ maxCommandBytes: number;
7
+ maxSqlBytes: number;
8
+ }
9
+ export declare function writePath(path: string, acc: Acc, t: ToolCtx): void;
10
+ export declare function hostOf(url: string): string | null;
11
+ export declare function classifyBuiltin(toolName: string, args: unknown, t: ToolCtx): Acc;
12
+ export declare function nameWords(name: string): string[];
13
+ export interface McpProfile {
14
+ acc: Acc;
15
+ contradiction: boolean;
16
+ }
17
+ /** Vocabulary + annotation profile of an MCP tool (no arguments). */
18
+ export declare function profileMcpTool(name: string, descriptor: ToolDef | undefined): McpProfile;
19
+ export declare function classifyMcp(name: string, args: unknown, descriptor: ToolDef | undefined, t: ToolCtx): McpProfile;
20
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1,240 @@
1
+ import { get, getString, isRecord } from "../util/misc.js";
2
+ import { Acc } from "./acc.js";
3
+ import { coversProtectedRead, globCoversProtectedRead, isProtected, isProtectedRead, normalizePath, persistenceHit, sensitiveLabel, } from "./paths.js";
4
+ import { analyzePowerShell } from "./powershell.js";
5
+ import { isProtectedWrite } from "./protected-write.js";
6
+ import { analyzeShellCommand } from "./shell/analyze.js";
7
+ import { analyzeSql } from "./sql.js";
8
+ const READ_TOOLS = new Set(["read", "glob", "grep", "ls", "lsp", "websearch", "todowrite", "todoread", "askuserquestion", "exitplanmode", "notebookread", "bashoutput", "taskoutput", "listmcpresourcestool", "readmcpresourcetool", "toolsearch"]);
9
+ const WRITE_TOOLS = new Set(["write", "edit", "multiedit", "notebookedit"]);
10
+ export function writePath(path, acc, t) {
11
+ const np = normalizePath(path, t.pctx);
12
+ if (isProtectedWrite(np, t.pctx))
13
+ acc.protect("CP-SELF-001", "changes a file that controls the agent or Glassbox");
14
+ acc.persist(persistenceHit(np, t.pctx), "changes", np.path);
15
+ acc.wrote(np.path);
16
+ const p = (np.path ?? np.suffix ?? "").toLowerCase();
17
+ if (p.includes("/.git/hooks/") || p.endsWith("/.git/config") || p.includes("/.husky/") || p.endsWith("/.envrc") || p.endsWith("/.bashrc") || p.endsWith("/.zshrc") || p.endsWith("/.profile") || p.endsWith("/.bash_profile") || p.endsWith("/.pre-commit-config.yaml") || p.endsWith("profile.ps1") || p.includes("/library/launchagents/") || p.includes("/.config/systemd/user/")) {
18
+ acc.tag("high-risk", "config.agent");
19
+ acc.reason("writes a file that runs commands later");
20
+ }
21
+ }
22
+ function readPath(path, acc, t, recursive) {
23
+ const np = normalizePath(path, t.pctx);
24
+ if (recursive ? coversProtectedRead(np, t.pctx) : isProtectedRead(np, t.pctx)) {
25
+ acc.protect("CP-SELF-002", "reads a Glassbox credential file");
26
+ return;
27
+ }
28
+ const label = sensitiveLabel(np, t.pctx);
29
+ if (label) {
30
+ acc.tags.add("fs.read.sensitive");
31
+ acc.sensitive.push(label);
32
+ acc.sensitiveArgs = true;
33
+ acc.find("CP-EXFIL-040", label);
34
+ acc.reason(`reads a sensitive file (${label})`);
35
+ }
36
+ }
37
+ export function hostOf(url) {
38
+ const m = /^[a-z][a-z0-9+.-]*:\/\/([^/?#@\s]*@)?(\[[^\]]*\]|[^/?#:\s]+)/i.exec(url.slice(0, 2048));
39
+ return m ? m[2].toLowerCase() : null;
40
+ }
41
+ export function classifyBuiltin(toolName, args, t) {
42
+ const acc = new Acc();
43
+ const name = toolName.toLowerCase();
44
+ const str = (k) => getString(args, k);
45
+ if (name === "bash") {
46
+ const cmd = str("command");
47
+ if (cmd === undefined) {
48
+ acc.unanalyzable("Bash call without a command string");
49
+ return acc;
50
+ }
51
+ return analyzeShellCommand(cmd, { pctx: t.pctx, depth: 0, maxBytes: t.maxCommandBytes });
52
+ }
53
+ if (name === "powershell") {
54
+ const cmd = str("command");
55
+ if (cmd === undefined) {
56
+ acc.unanalyzable("PowerShell call without a command string");
57
+ return acc;
58
+ }
59
+ return analyzePowerShell(cmd, { pctx: t.pctx, depth: 0, maxBytes: t.maxCommandBytes });
60
+ }
61
+ if (WRITE_TOOLS.has(name)) {
62
+ acc.tag("write-reversible", "fs.write");
63
+ const p = str("file_path") ?? str("notebook_path") ?? str("path");
64
+ if (p === undefined) {
65
+ acc.unanalyzable("write tool without a file path");
66
+ return acc;
67
+ }
68
+ writePath(p, acc, t);
69
+ return acc;
70
+ }
71
+ if (name === "webfetch") {
72
+ acc.tag("high-risk", "net.egress");
73
+ acc.network = true;
74
+ const h = hostOf(str("url") ?? "");
75
+ acc.reason(h ? `destination host: ${h}` : "destination host unknown");
76
+ return acc;
77
+ }
78
+ if (READ_TOOLS.has(name)) {
79
+ if (name === "read" || name === "notebookread" || name === "lsp") {
80
+ const p = str("file_path") ?? str("filePath") ?? str("path") ?? str("notebook_path");
81
+ if (p !== undefined)
82
+ readPath(p, acc, t, false);
83
+ }
84
+ if (name === "grep") {
85
+ const p = str("path") ?? (t.pctx.cwd ?? ".");
86
+ readPath(p, acc, t, true);
87
+ const g = str("glob");
88
+ if (g && globCoversProtectedRead(g, p, t.pctx))
89
+ acc.protect("CP-SELF-002", "searches Glassbox credential files");
90
+ }
91
+ if (name === "glob") {
92
+ const pattern = str("pattern") ?? "";
93
+ if (globCoversProtectedRead(pattern, str("path") ?? null, t.pctx))
94
+ acc.protect("CP-SELF-002", "lists Glassbox credential files");
95
+ }
96
+ return acc;
97
+ }
98
+ acc.tag("write-reversible", "exec.unknown");
99
+ acc.reason(`runs the agent tool ${toolName.slice(0, 40)}`);
100
+ return acc;
101
+ }
102
+ // ── MCP tools ────────────────────────────────────────────────────────────
103
+ const HIGH_VERBS = new Set(["delete", "remove", "destroy", "drop", "truncate", "deploy", "publish", "post", "send", "transfer", "pay", "refund", "charge", "merge", "push", "grant", "revoke", "invite", "archive", "execute", "exec", "run", "purge", "wipe", "kill", "terminate", "erase", "unpublish", "release", "approve", "submit", "tweet", "email", "notify", "broadcast", "withdraw", "sell", "buy", "order", "book", "cancel", "reset", "overwrite", "shutdown", "restart", "reboot", "ban", "kick", "suspend", "disable", "uninstall"]);
104
+ const WRITE_VERBS = new Set(["create", "update", "set", "add", "edit", "write", "upload", "modify", "put", "patch", "save", "insert", "rename", "move", "copy", "upsert", "append", "make", "new", "change", "assign", "label", "tag", "comment", "reply", "star", "fork", "open", "close", "enable", "install", "configure", "register", "import", "sync", "store", "commit", "mark", "pin", "schedule", "generate", "build", "convert", "format", "translate"]);
105
+ const READ_VERBS = new Set(["get", "list", "read", "search", "fetch", "query", "describe", "show", "find", "view", "count", "lookup", "check", "status", "retrieve", "download", "browse", "inspect", "explain", "summarize", "analyze", "lint", "validate", "preview", "diff", "compare", "resolve", "info", "whoami", "ping", "echo", "calculate", "compute", "time", "weather", "forecast", "now"]);
106
+ export function nameWords(name) {
107
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
108
+ }
109
+ function verbTags(words) {
110
+ const has = (...xs) => xs.some((x) => words.includes(x));
111
+ const tags = [];
112
+ if (has("send", "email", "notify", "broadcast", "tweet", "dm") && has("email", "mail", "message", "messages", "sms", "slack", "chat", "notification", "tweet", "dm", "text", "post"))
113
+ tags.push("message.send");
114
+ if (has("transfer", "pay", "refund", "charge", "payment", "invoice", "withdraw", "payout", "sell", "buy", "order"))
115
+ tags.push("payment");
116
+ if (has("publish", "post", "tweet", "release", "unpublish"))
117
+ tags.push("publish.public");
118
+ if (has("deploy"))
119
+ tags.push(has("prod", "production") ? "deploy.prod" : "deploy.other");
120
+ if (has("merge", "push"))
121
+ tags.push("vcs.push");
122
+ if (has("grant", "revoke", "invite", "ban", "kick", "suspend"))
123
+ tags.push("perm.change");
124
+ if (has("delete", "remove", "destroy", "drop", "truncate", "purge", "wipe", "erase", "archive", "overwrite"))
125
+ tags.push(has("table", "database", "db", "row", "rows", "record", "records", "collection") ? "db.delete" : "fs.delete");
126
+ if (has("execute", "exec", "run", "kill", "terminate", "shutdown", "restart", "reboot"))
127
+ tags.push("exec.unknown");
128
+ return tags;
129
+ }
130
+ /** Vocabulary + annotation profile of an MCP tool (no arguments). */
131
+ export function profileMcpTool(name, descriptor) {
132
+ const acc = new Acc();
133
+ const desc = typeof descriptor?.description === "string" ? descriptor.description : "";
134
+ const firstSentence = desc.split(/[.\n]/)[0]?.slice(0, 300) ?? "";
135
+ const words = nameWords(name);
136
+ const descWords = nameWords(firstSentence).slice(0, 3);
137
+ const all = [...words, ...descWords];
138
+ // Tool names are verb-first (get_release_by_tag): after a read or write verb, a "high" word is
139
+ // a noun. A high verb counts when it leads the name, or when the name has no read/write verb.
140
+ const plainVerb = words.some((w) => READ_VERBS.has(w) || WRITE_VERBS.has(w));
141
+ const high = HIGH_VERBS.has(words[0] ?? "") || (!plainVerb && words.some((w) => HIGH_VERBS.has(w))) || (words.length > 0 && !plainVerb && descWords.some((w) => HIGH_VERBS.has(w)));
142
+ const write = all.some((w) => WRITE_VERBS.has(w));
143
+ const read = words.some((w) => READ_VERBS.has(w)) || (!high && !write && descWords.some((w) => READ_VERBS.has(w)));
144
+ if (high) {
145
+ acc.raise("high-risk");
146
+ const tags = verbTags(all);
147
+ for (const tg of tags)
148
+ acc.tags.add(tg);
149
+ if (tags.length === 0)
150
+ acc.tags.add("exec.unknown");
151
+ }
152
+ else if (write)
153
+ acc.tag("write-reversible", "fs.write");
154
+ else if (read)
155
+ acc.raise("read");
156
+ else
157
+ acc.tag("write-reversible", "exec.unknown");
158
+ const ann = isRecord(descriptor?.annotations) ? descriptor?.annotations : undefined;
159
+ let contradiction = false;
160
+ if (ann && get(ann, "destructiveHint") === true) {
161
+ acc.raise("high-risk");
162
+ if (acc.tags.size === 0)
163
+ acc.tags.add("fs.delete");
164
+ }
165
+ if (ann && get(ann, "readOnlyHint") === true && high)
166
+ contradiction = true;
167
+ if (ann && get(ann, "openWorldHint") === true && acc.level !== "read")
168
+ acc.tags.add("net.egress");
169
+ return { acc, contradiction };
170
+ }
171
+ const COMMAND_KEYS = new Set(["command", "cmd", "script", "shell", "bash", "commandline", "command_line"]);
172
+ const SQL_KEYS = new Set(["sql", "query", "statement", "stmt", "q"]);
173
+ const PATH_KEYS = new Set(["path", "file", "filename", "file_path", "filepath", "target", "destination", "dest", "dir", "directory", "output", "outfile", "output_path"]);
174
+ export function classifyMcp(name, args, descriptor, t) {
175
+ const prof = profileMcpTool(name, descriptor);
176
+ const acc = prof.acc;
177
+ const words = nameWords(name);
178
+ const sqlLike = words.some((w) => ["sql", "query", "execute", "exec", "db", "database", "postgres", "mysql", "sqlite", "select"].includes(w));
179
+ const isRead = acc.level === "read";
180
+ if (!isRecord(args))
181
+ return prof;
182
+ let sqlSeen = false;
183
+ const sqlAcc = new Acc();
184
+ for (const k of Object.keys(args)) {
185
+ const v = args[k];
186
+ if (typeof v !== "string")
187
+ continue;
188
+ const key = k.toLowerCase();
189
+ if (COMMAND_KEYS.has(key))
190
+ acc.merge(analyzeShellCommand(v, { pctx: t.pctx, depth: 0, maxBytes: t.maxCommandBytes }));
191
+ if (SQL_KEYS.has(key) && sqlLike) {
192
+ sqlSeen = true;
193
+ sqlAcc.merge(analyzeSql(v, t.maxSqlBytes));
194
+ }
195
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(v.slice(0, 20)) && /^https?:|^wss?:|^ftp:/i.test(v) && !isRead) {
196
+ acc.tag("high-risk", "net.egress");
197
+ acc.network = true;
198
+ }
199
+ if (PATH_KEYS.has(key)) {
200
+ const np = normalizePath(v, t.pctx);
201
+ if (isProtectedRead(np, t.pctx))
202
+ acc.protect("CP-SELF-002", "reads a Glassbox credential file");
203
+ else if (!isRead && isProtected(np, t.pctx))
204
+ acc.protect("CP-SELF-001", "changes a file that controls the agent or Glassbox");
205
+ else if (!isRead && persistenceHit(np, t.pctx))
206
+ acc.persist(persistenceHit(np, t.pctx), "changes", np.path);
207
+ if (!isRead)
208
+ acc.wrote(np.path);
209
+ else if (isRead) {
210
+ const label = sensitiveLabel(np, t.pctx);
211
+ if (label) {
212
+ acc.tags.add("fs.read.sensitive");
213
+ acc.sensitive.push(label);
214
+ acc.sensitiveArgs = true;
215
+ acc.find("CP-EXFIL-040", label);
216
+ }
217
+ }
218
+ }
219
+ }
220
+ if (sqlSeen) {
221
+ // The statement decides, not the tool's verb (§7.1 step 3).
222
+ const keep = new Acc();
223
+ keep.merge(sqlAcc);
224
+ for (const f of acc.findings)
225
+ keep.find(f.ruleId, f.note);
226
+ if (acc.selfProtection)
227
+ keep.selfProtection = true;
228
+ for (const tg of acc.tags)
229
+ if (tg === "net.egress" || tg === "self-protection")
230
+ keep.tags.add(tg);
231
+ for (const r of acc.unanalyzableReasons)
232
+ keep.unanalyzable(r);
233
+ const ann = isRecord(descriptor?.annotations) ? descriptor?.annotations : undefined;
234
+ if (ann && get(ann, "destructiveHint") === true)
235
+ keep.raise("high-risk");
236
+ return { acc: keep, contradiction: prof.contradiction };
237
+ }
238
+ return prof;
239
+ }
240
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +1,17 @@
1
+ import type { Acc } from "./acc.js";
2
+ import { type NormPath, type PathCtx } from "./paths.js";
3
+ export type UploadKind = "sensitive" | "outside" | "project";
4
+ /** True for loopback host names and addresses. */
5
+ export declare function isLoopbackHost(host: string): boolean;
6
+ /**
7
+ * The host of a URL, a bare host[:port][/path], or user@host:path. Null when there is none
8
+ * (for example a value with no host-like start). String code only.
9
+ */
10
+ export declare function hostOf(v: string): string | null;
11
+ /** Destinations are known and all on this machine. */
12
+ export declare function allLoopback(destinations: readonly (string | null)[]): boolean;
13
+ /** Classifies an uploaded file. `projectDir` is the session's project directory. */
14
+ export declare function classifyUpload(np: NormPath | null, pctx: PathCtx, projectDir: string | null): UploadKind;
15
+ /** Records one uploaded file (the caller has checked the destination isn't loopback). */
16
+ export declare function recordUpload(acc: Acc, kind: UploadKind, what: string): void;
17
+ //# sourceMappingURL=upload.d.ts.map