@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,2030 @@
1
+ // Shell classification (engine-spec §7.3, Q5/Q6 rev 4) over the parsed AST.
2
+ import { Acc } from "../acc.js";
3
+ import { allLoopback, classifyUpload, recordUpload } from "../upload.js";
4
+ import { commandFiles, schtasksJob } from "../schedule.js";
5
+ import { trimEndChars } from "../../util/misc.js";
6
+ import { analyzeInlineCode } from "../inline.js";
7
+ import { coversProtectedRead, homeTopLevel, isProtected, isProtectedRead, normalizePath, persistenceHit, sensitiveLabel, suffixOnly, } from "../paths.js";
8
+ import { analyzeSql } from "../sql.js";
9
+ import { isProtectedWrite } from "../protected-write.js";
10
+ import { parseShell, Unanalyzable } from "./parse.js";
11
+ export function wordInfo(w) {
12
+ let value = "";
13
+ let pathValue = "";
14
+ let dynamic = false;
15
+ let glob = false;
16
+ let suffix = "";
17
+ const substs = [];
18
+ for (const p of w.parts) {
19
+ switch (p.t) {
20
+ case "lit":
21
+ value += p.s;
22
+ if (pathValue !== null)
23
+ pathValue += p.s;
24
+ suffix += p.s;
25
+ break;
26
+ case "glob":
27
+ glob = true;
28
+ value += p.s;
29
+ if (pathValue !== null)
30
+ pathValue += p.s;
31
+ suffix += p.s;
32
+ break;
33
+ case "tilde":
34
+ dynamic = true;
35
+ if (pathValue !== null)
36
+ pathValue += "~" + p.user;
37
+ suffix = "";
38
+ break;
39
+ case "var":
40
+ dynamic = true;
41
+ if (pathValue !== null && (p.name === "HOME" || (p.braced && p.name === "HOME")))
42
+ pathValue += "$HOME";
43
+ else
44
+ pathValue = null;
45
+ suffix = "";
46
+ break;
47
+ case "subst":
48
+ dynamic = true;
49
+ substs.push(p.script);
50
+ pathValue = null;
51
+ suffix = "";
52
+ break;
53
+ case "arith":
54
+ dynamic = true;
55
+ pathValue = null;
56
+ suffix = "";
57
+ break;
58
+ }
59
+ }
60
+ if (w.brace)
61
+ dynamic = true;
62
+ return { word: w, value: dynamic ? null : value, pathValue: w.brace ? null : pathValue, suffix, dynamic, glob, substs };
63
+ }
64
+ const isOption = (s) => s !== null && s.startsWith("-") && s !== "-";
65
+ function looksLikePath(s) {
66
+ return s.includes("/") || s.includes("\\") || s.startsWith("~") || s.startsWith(".") || s.startsWith("$HOME") || /^[a-zA-Z]:[\\/]/.test(s.slice(0, 3));
67
+ }
68
+ function npOf(w, pctx) {
69
+ if (w.pathValue !== null)
70
+ return normalizePath(w.pathValue, pctx);
71
+ if (w.suffix.includes("/") || w.suffix.includes("\\"))
72
+ return suffixOnly(w.suffix, pctx);
73
+ if (w.suffix.length > 0)
74
+ return suffixOnly("/" + w.suffix, pctx);
75
+ return null; // fully unknown
76
+ }
77
+ // ── Tables ───────────────────────────────────────────────────────────────
78
+ const READ = new Set([
79
+ "ls", "ll", "dir", "cat", "head", "tail", "less", "more", "grep", "egrep", "fgrep", "rg", "ag", "ack", "wc", "sort", "uniq", "diff", "cmp", "comm",
80
+ "file", "stat", "pwd", "which", "whereis", "type", "echo", "printf", "date", "whoami", "id", "hostname", "uname", "tree", "jq", "yq", "cut", "tr",
81
+ "column", "basename", "dirname", "realpath", "readlink", "du", "df", "printenv", "true", "false", "test", "[", "[[", "seq", "nl", "od", "xxd",
82
+ "hexdump", "strings", "md5sum", "sha1sum", "sha256sum", "sha512sum", "shasum", "base64", "fold", "fmt", "rev", "tac", "paste", "join", "expand",
83
+ "unexpand", "look", "man", "help", "ps", "top", "htop", "lsof", "uptime", "free", "nproc", "arch", "locale", "tput", "sleep", "wait", "cd", "pushd",
84
+ "popd", "dirs", "export", "unset", "unalias", "local", "declare", "typeset", "readonly", "shift", "getopts", "read", "history", "jobs", "fg", "bg",
85
+ "hash", "umask", "ulimit", "set", "shopt", "exit", "return", "break", "continue", ":", "time", "clear", "cal", "bc", "expr", "awk", "gawk", "sed",
86
+ "tee_read_only", "zcat", "zgrep", "bzcat", "xzcat", "gzip_list", "printf", "getconf", "tty", "stty", "groups", "last", "w", "who", "env",
87
+ ]);
88
+ const WRITE = new Set(["cp", "mkdir", "touch", "tee", "mv", "ln", "install", "patch", "mktemp", "unzip", "gunzip", "gzip", "bzip2", "xz", "zip", "tar", "dos2unix", "unix2dos", "split", "csplit", "rename"]);
89
+ const REMOVE = new Set(["rm", "rmdir", "unlink", "shred", "truncate", "srm"]);
90
+ const NET = new Set(["curl", "wget", "nc", "ncat", "netcat", "socat", "ssh", "scp", "sftp", "ftp", "telnet", "ping", "dig", "nslookup", "host", "traceroute", "http", "https", "aria2c", "rsync_remote", "mosh"]);
91
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish", "ash", "mksh"]);
92
+ const INTERPRETERS = new Set(["python", "python2", "python3", "node", "nodejs", "perl", "ruby", "php", "deno", "bun", "Rscript", "osascript", "lua", "tclsh", "pwsh_inline"]);
93
+ const PROJECT = new Set(["make", "gmake", "cmake", "ninja", "pytest", "jest", "vitest", "mocha", "tsc", "eslint", "prettier", "biome", "mvn", "gradle", "gradlew", "dotnet", "rake", "tox", "nox", "ctest", "meson", "bazel", "turbo", "nx", "lerna", "playwright", "cypress", "webpack", "vite", "rollup", "esbuild", "swc", "babel", "ts-node", "tsx", "black", "ruff", "mypy", "flake8", "isort", "rubocop", "golangci-lint", "clippy", "rustfmt", "gofmt", "shellcheck", "hadolint", "phpunit", "pre-commit_run"]);
94
+ const HIJACK = new Set(["PATH", "BASH_ENV", "ENV", "PROMPT_COMMAND", "LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT", "NODE_OPTIONS", "NODE_PATH", "PYTHONSTARTUP", "PYTHONPATH", "PYTHONHOME", "PERL5OPT", "PERL5LIB", "RUBYOPT", "RUBYLIB", "IFS", "CDPATH", "GLOBIGNORE", "SHELLOPTS", "BASHOPTS", "PS4", "GIT_SSH", "GIT_SSH_COMMAND", "GIT_EXEC_PATH", "GIT_ASKPASS", "GIT_EDITOR", "GIT_PAGER", "GIT_CONFIG", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_TEMPLATE_DIR", "EDITOR", "VISUAL", "PAGER", "SSH_ASKPASS", "SUDO_ASKPASS", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "DOTNET_STARTUP_HOOKS"]);
95
+ const DANGEROUS_GIT_CONFIG = /^(alias\..*|core\.hookspath|core\.sshcommand|core\.pager|core\.editor|core\.fsmonitor|core\.gitproxy|credential\..*|diff\..*\.(textconv|command)|diff\.external|filter\..*|merge\..*\.driver|gpg\.program|sequence\.editor|uploadpack\..*|receivepack\..*)$/i;
96
+ // ── Analysis ─────────────────────────────────────────────────────────────
97
+ export function analyzeShellCommand(src, st) {
98
+ const acc = new Acc();
99
+ let script;
100
+ try {
101
+ script = parseShell(src, { maxBytes: st.maxBytes });
102
+ }
103
+ catch (e) {
104
+ acc.unanalyzable(e instanceof Unanalyzable ? e.reason : "parse error");
105
+ // Even unparseable commands get the cheap protected-path scan.
106
+ lexicalProtectedScan(src, st.pctx, acc);
107
+ return acc;
108
+ }
109
+ analyzeScript(script, st, acc);
110
+ return acc;
111
+ }
112
+ /** For commands we couldn't parse: look for protected-read/protected paths as plain text. */
113
+ function lexicalProtectedScan(src, pctx, acc) {
114
+ for (const tok of src.split(/[\s'"`;|&()<>=]+/).slice(0, 2000)) {
115
+ if (!tok || !looksLikePath(tok))
116
+ continue;
117
+ const np = normalizePath(tok, pctx);
118
+ if (isProtectedRead(np, pctx))
119
+ acc.protect("CP-SELF-002", "reads a Glassbox credential file");
120
+ else if (isProtected(np, pctx))
121
+ acc.protect("CP-SELF-001", "touches an agent or Glassbox control file");
122
+ }
123
+ }
124
+ export function analyzeScript(script, st, acc) {
125
+ const cwdStack = { cwd: st.pctx.cwd };
126
+ for (const cmd of script.commands)
127
+ analyzeSimple(cmd, st, acc, cwdStack, script.functions);
128
+ if (acc.network && acc.sensitiveArgs)
129
+ acc.find("CP-EXFIL-030", "sensitive file and network call in one command");
130
+ else if (acc.network && acc.envDump)
131
+ acc.find("CP-EXFIL-030", "environment variables and a network call in one command");
132
+ if (acc.newRemotes.length > 0 && acc.pushedTo.some((r) => acc.newRemotes.includes(r) || r === "\u0000dynamic" || acc.newRemotes.includes("\u0000dynamic"))) {
133
+ acc.find("CP-EXFIL-034", "adds or repoints a git remote and pushes to it in the same command");
134
+ }
135
+ }
136
+ function analyzeSubsts(w, st, acc, commandPosition) {
137
+ for (const s of w.substs) {
138
+ if (st.depth + 1 > 3) {
139
+ acc.unanalyzable("command substitution nested more than 3 levels");
140
+ continue;
141
+ }
142
+ const inner = new Acc();
143
+ analyzeScript(s, { ...st, depth: st.depth + 1 }, inner);
144
+ if (inner.selfProtection) {
145
+ acc.selfProtection = true;
146
+ acc.tags.add("self-protection");
147
+ for (const f of inner.findings)
148
+ if (f.ruleId.startsWith("CP-SELF"))
149
+ acc.find(f.ruleId, f.note);
150
+ acc.raise("high-risk");
151
+ }
152
+ if (inner.sensitive.length > 0) {
153
+ acc.sensitive.push(...inner.sensitive);
154
+ acc.sensitiveArgs = true;
155
+ }
156
+ if (inner.envDump)
157
+ acc.envDump = true;
158
+ if (commandPosition) {
159
+ acc.unanalyzable("command name comes from a command substitution");
160
+ continue;
161
+ }
162
+ if (inner.unanalyzableFlag) {
163
+ acc.unanalyzable("command substitution contains an unanalyzable command");
164
+ continue;
165
+ }
166
+ const unknown = inner.tags.has("exec.unknown") || inner.tags.has("exec.project-code") || inner.tags.has("exec.inline-code") || inner.tags.has("exec.nested-agent");
167
+ if (inner.level === "high-risk" || inner.sensitive.length > 0) {
168
+ for (const t of inner.tags)
169
+ acc.tags.add(t);
170
+ acc.network ||= inner.network;
171
+ acc.unanalyzable("command substitution runs a dangerous command");
172
+ continue;
173
+ }
174
+ if (unknown) {
175
+ acc.unanalyzable("command substitution runs an unknown command");
176
+ continue;
177
+ }
178
+ if (inner.level === "write-reversible") {
179
+ acc.raise("write-reversible");
180
+ for (const t of inner.tags)
181
+ acc.tags.add(t);
182
+ }
183
+ }
184
+ }
185
+ function analyzeSimple(cmd, st, acc, cwd, functions) {
186
+ const pctx = { ...st.pctx, cwd: cwd.cwd };
187
+ const envPrefix = [];
188
+ for (const a of cmd.assigns) {
189
+ const name = a.name;
190
+ envPrefix.push(name);
191
+ if (HIJACK.has(name) || name.startsWith("DYLD_") || name.startsWith("LD_"))
192
+ acc.unanalyzable(`assignment to ${name} changes what later commands run`);
193
+ if (a.value) {
194
+ const wi = wordInfo(a.value);
195
+ analyzeSubsts(wi, st, acc, false);
196
+ }
197
+ }
198
+ const words = cmd.words.map(wordInfo);
199
+ for (const r of cmd.redirects)
200
+ handleRedirect(r, st, acc, pctx, cmd);
201
+ if (words.length === 0)
202
+ return;
203
+ words.forEach((w, i) => analyzeSubsts(w, st, acc, i === 0));
204
+ const head = words[0];
205
+ if (head.value === null || head.glob) {
206
+ acc.unanalyzable("command name isn't a literal word");
207
+ // Still check arguments for protected paths.
208
+ for (const w of words.slice(1))
209
+ checkArgPaths(w, pctx, acc, false);
210
+ return;
211
+ }
212
+ classify(head.value, words.slice(1), cmd, st, acc, pctx, cwd, envPrefix, functions, 0);
213
+ }
214
+ function handleRedirect(r, st, acc, pctx, cmd) {
215
+ if (r.heredoc) {
216
+ if (r.heredoc.script) {
217
+ const inner = new Acc();
218
+ analyzeScript(r.heredoc.script, { ...st, depth: st.depth + 1 }, inner);
219
+ // Substitutions in an unquoted here-doc body follow the same rules (Q5).
220
+ const fake = { word: { parts: [], raw: "", brace: false }, value: null, pathValue: null, suffix: "", dynamic: true, glob: false, substs: [r.heredoc.script] };
221
+ analyzeSubsts(fake, st, acc, false);
222
+ }
223
+ return;
224
+ }
225
+ if (!r.target)
226
+ return;
227
+ const t = wordInfo(r.target);
228
+ analyzeSubsts(t, st, acc, false);
229
+ const isWrite = r.op.startsWith(">") || r.op.startsWith("&>") || r.op === "<>";
230
+ const val = t.pathValue ?? "";
231
+ if (/^\/dev\/(tcp|udp)\//.test(val) || /^\/dev\/(tcp|udp)\//.test(t.suffix)) {
232
+ acc.tag("high-risk", "net.egress");
233
+ acc.network = true;
234
+ acc.find("CP-SHELL-011");
235
+ acc.reason("redirects to a network socket via /dev/tcp");
236
+ return;
237
+ }
238
+ if (val === "/dev/null" || val === "/dev/stdout" || val === "/dev/stderr" || val === "&1" || val === "&2")
239
+ return;
240
+ if (r.op === "<<<")
241
+ return;
242
+ const np = npOf(t, pctx);
243
+ if (isWrite) {
244
+ if (np === null) {
245
+ acc.unanalyzable("writes to a path that isn't known statically");
246
+ return;
247
+ }
248
+ if (/^\/dev\/(sd|nvme|hd|disk|xvd|vd|mmcblk)/.test(np.path ?? "")) {
249
+ destroy(acc, "overwrites a disk device");
250
+ return;
251
+ }
252
+ if (np.path === "/proc/sysrq-trigger") {
253
+ acc.tag("high-risk", "infra.change");
254
+ acc.reason("triggers a kernel reboot, power-off or crash through sysrq");
255
+ return;
256
+ }
257
+ if ((r.op === ">" || r.op === ">|") && np.path !== null && isLogOrHistory(np.path)) {
258
+ acc.tag("high-risk", "fs.delete");
259
+ acc.find("CP-ACTION-030", "empties a log or shell history file");
260
+ }
261
+ writeTarget(np, acc, pctx);
262
+ acc.tag("write-reversible", "fs.write");
263
+ return;
264
+ }
265
+ if (np)
266
+ readTarget(np, acc, pctx, false);
267
+ void cmd;
268
+ }
269
+ function destroy(acc, why) {
270
+ acc.tag("high-risk", "fs.destroy", "fs.delete");
271
+ acc.find("CP-ACTION-001", why);
272
+ acc.reason(why);
273
+ }
274
+ /** Checks for a path that is written, created, moved, deleted, chmod-ed or linked. */
275
+ function writeTarget(np, acc, pctx, isGlob = false) {
276
+ if (isProtectedWrite(np, pctx, isGlob))
277
+ acc.protect("CP-SELF-001", "changes a file that controls the agent or Glassbox");
278
+ acc.persist(persistenceHit(np, pctx), "changes", np.path);
279
+ acc.wrote(np.path);
280
+ const p = (np.path ?? np.suffix ?? "").toLowerCase();
281
+ const home = trimEndChars(pctx.homeDir.replace(/\\/g, "/"), "/").toLowerCase();
282
+ const homeFiles = [".bashrc", ".zshrc", ".profile", ".bash_profile", ".bash_login", ".zprofile", ".zshenv", ".zlogin", ".config/fish/config.fish", ".ssh/rc", ".inputrc"];
283
+ const deferred = p.includes("/.git/hooks/") || p.endsWith("/.git/config") || p.includes("/.husky/") || p.endsWith("/.pre-commit-config.yaml") || p.endsWith("/.envrc") ||
284
+ p.includes("/.config/systemd/user/") || p.includes("/library/launchagents/") || p.endsWith("microsoft.powershell_profile.ps1") || p.endsWith("profile.ps1") ||
285
+ homeFiles.some((f) => p === `${home}/${f}` || (np.path === null && p.endsWith("/" + f) && f.startsWith(".")));
286
+ if (deferred) {
287
+ acc.tag("high-risk", "config.agent");
288
+ acc.reason("writes a file that runs commands later");
289
+ }
290
+ if (p.endsWith("/.ssh/authorized_keys") || p.endsWith("/.ssh/authorized_keys2")) {
291
+ acc.tag("high-risk", "perm.change");
292
+ acc.reason("changes SSH access");
293
+ }
294
+ }
295
+ function readTarget(np, acc, pctx, recursive) {
296
+ if (recursive ? coversProtectedRead(np, pctx) : isProtectedRead(np, pctx)) {
297
+ acc.protect("CP-SELF-002", "reads a Glassbox credential file");
298
+ return;
299
+ }
300
+ const label = sensitiveLabel(np, pctx);
301
+ if (label) {
302
+ acc.tags.add("fs.read.sensitive");
303
+ acc.sensitive.push(label);
304
+ acc.sensitiveArgs = true;
305
+ acc.find("CP-EXFIL-040", label);
306
+ acc.reason(`reads a sensitive file (${label})`);
307
+ }
308
+ }
309
+ /** Every path-like argument of any command: protected reads and sensitive reads. */
310
+ function checkArgPaths(w, pctx, acc, recursive, writeOnly = false) {
311
+ const text = w.pathValue ?? w.suffix;
312
+ if (!text)
313
+ return;
314
+ // `--opt=path` and `@path` forms.
315
+ const candidates = [text];
316
+ const eq = text.indexOf("=");
317
+ if (eq > 0 && text.startsWith("-"))
318
+ candidates.push(text.slice(eq + 1));
319
+ if (text.startsWith("@"))
320
+ candidates.push(text.slice(1));
321
+ for (const c of candidates) {
322
+ if (!looksLikePath(c) && !c.startsWith(".env") && !c.endsWith(".key") && !c.endsWith(".pem"))
323
+ continue;
324
+ const np = w.pathValue !== null ? normalizePath(c, pctx) : suffixOnly(c, pctx);
325
+ if (writeOnly) {
326
+ if (isProtectedRead(np, pctx))
327
+ acc.protect("CP-SELF-001", "changes a Glassbox credential file");
328
+ continue;
329
+ }
330
+ readTarget(np, acc, pctx, recursive);
331
+ }
332
+ }
333
+ function operands(args, takesValue = new Set()) {
334
+ const out = [];
335
+ let endOpts = false;
336
+ for (let i = 0; i < args.length; i++) {
337
+ const a = args[i];
338
+ const v = a.value;
339
+ if (!endOpts && v === "--") {
340
+ endOpts = true;
341
+ continue;
342
+ }
343
+ if (!endOpts && isOption(v)) {
344
+ if (v !== null && takesValue.has(v))
345
+ i++;
346
+ continue;
347
+ }
348
+ out.push(a);
349
+ }
350
+ return out;
351
+ }
352
+ function hasFlag(args, ...flags) {
353
+ return args.some((a) => {
354
+ const v = a.value;
355
+ if (v === null || !v.startsWith("-"))
356
+ return false;
357
+ if (flags.includes(v))
358
+ return true;
359
+ // Combined short flags: -rf contains r and f.
360
+ if (!v.startsWith("--"))
361
+ return flags.some((f) => f.length === 2 && f.startsWith("-") && !f.startsWith("--") && v.slice(1).includes(f[1]));
362
+ return flags.some((f) => f.startsWith("--") && v.startsWith(f + "="));
363
+ });
364
+ }
365
+ function stdinKind(cmd) {
366
+ if (cmd.pipedIn)
367
+ return "pipe";
368
+ for (const r of cmd.redirects) {
369
+ if (r.heredoc)
370
+ return "heredoc";
371
+ if (r.op === "<<<")
372
+ return "herestring";
373
+ if (r.op === "<" || r.op === "<>")
374
+ return "file";
375
+ }
376
+ return "none";
377
+ }
378
+ const NET_PIPE_SOURCES = new Set(["curl", "wget", "nc", "ncat", "fetch", "http", "https", "aria2c"]);
379
+ function classify(name0, args, cmd, st, acc, pctx, cwd, envPrefix, functions, unwrapDepth) {
380
+ const c = { cmd, st, acc, pctx, cwd, envPrefix, functions };
381
+ const name = name0.includes("/") && !name0.startsWith("./") && !name0.startsWith("../") ? (name0.split("/").pop() ?? name0) : name0;
382
+ const lower = name.toLowerCase();
383
+ // Every path-like argument: protected reads and sensitive reads. Destinations of
384
+ // copy/move/create commands are writes, not reads.
385
+ const writeOnly = new Set();
386
+ if (["cp", "mv", "ln", "install"].includes(lower)) {
387
+ const o = operands(args);
388
+ const last = o[o.length - 1];
389
+ if (last && o.length > 1)
390
+ writeOnly.add(last);
391
+ }
392
+ if (["touch", "mkdir", "rm", "rmdir", "unlink", "shred", "truncate", "tee"].includes(lower))
393
+ for (const o of operands(args))
394
+ writeOnly.add(o);
395
+ const recursiveRead = (["grep", "egrep", "fgrep", "rg", "ag", "ack"].includes(lower) && (hasFlag(args, "-r", "-R", "--recursive") || lower === "rg" || lower === "ag" || lower === "ack")) ||
396
+ ["tar", "zip", "rsync", "find", "du", "tree", "scp", "7z"].includes(lower) || (lower === "cp" && hasFlag(args, "-r", "-R", "-a", "--recursive", "--archive")) || (lower === "ls" && hasFlag(args, "-R"));
397
+ for (const a of args)
398
+ checkArgPaths(a, pctx, acc, recursiveRead, writeOnly.has(a));
399
+ // Version/help probes of any tool are reads.
400
+ if (args.length === 1 && ["--version", "-v", "-V", "--help", "-h"].includes(args[0]?.value ?? "") && !["rm", "sudo", "doas", "bash", "sh", "claude", "env"].includes(lower))
401
+ return;
402
+ if (functions.includes(name))
403
+ return; // body already analyzed
404
+ // Whole-environment dumps (correlated with network calls in analyzeScript).
405
+ const flagsOnly = (allowed) => args.every((a) => a.value !== null && allowed.includes(a.value));
406
+ if ((lower === "printenv" && args.length === 0) || (["set", "export", "declare", "typeset"].includes(lower) && flagsOnly(["-p", "-x", "-px", "-xp"])))
407
+ acc.envDump = true;
408
+ if (lower === "compgen" && hasFlag(args, "-e", "-v"))
409
+ acc.envDump = true;
410
+ // Credential dumping tools, run directly or as a script (python laZagne.py).
411
+ if ([name, ...args.map((a) => a.value ?? "")].some((v) => /^(lazagne|mimikatz|pypykatz|secretsdump|procdump)/i.test(v.slice(v.lastIndexOf("/") + 1)))) {
412
+ acc.tags.add("fs.read.sensitive");
413
+ acc.raise("high-risk");
414
+ acc.sensitive.push("credential-dump");
415
+ acc.sensitiveArgs = true;
416
+ acc.find("CP-EXFIL-040", "runs a credential dumping tool");
417
+ }
418
+ // Clearing shell history or system logs hides what happened (warn, CP-ACTION-030).
419
+ const clearsHistory = (lower === "history" && args.some((a) => /^-[a-z]*c/.test(a.value ?? "") || a.value === "-d")) ||
420
+ (lower === "unset" && args.some((a) => a.value === "HISTFILE")) ||
421
+ (lower === "journalctl" && args.some((a) => (a.value ?? "").startsWith("--vacuum") || a.value === "--rotate"));
422
+ if (clearsHistory) {
423
+ acc.tag("high-risk", "fs.delete");
424
+ acc.find("CP-ACTION-030", `${lower} clears shell history or system logs`);
425
+ acc.reason("clears shell history or logs");
426
+ return;
427
+ }
428
+ // DNS lookups of a name built from command output or variables: data smuggled out in DNS.
429
+ if (["nslookup", "dig", "host", "drill", "ping", "ping6", "resolvectl", "getent"].includes(lower)) {
430
+ if (operands(args).some((a) => a.substs.length > 0 || a.value === null)) {
431
+ acc.tag("high-risk", "net.egress");
432
+ acc.network = true;
433
+ acc.find("CP-EXFIL-033", `${lower} looks up a name built from command output or variables`);
434
+ }
435
+ }
436
+ // ── Wrappers ───────────────────────────────────────────────────────────
437
+ const unwrap = (rest) => {
438
+ if (unwrapDepth >= 4) {
439
+ acc.unanalyzable("too many nested wrapper commands");
440
+ return;
441
+ }
442
+ const h = rest[0];
443
+ if (!h)
444
+ return;
445
+ if (h.value === null || h.glob) {
446
+ acc.unanalyzable("wrapped command name isn't literal");
447
+ return;
448
+ }
449
+ classify(h.value, rest.slice(1), cmd, st, acc, pctx, cwd, envPrefix, functions, unwrapDepth + 1);
450
+ };
451
+ const skipOpts = (rest, withValue) => {
452
+ let i = 0;
453
+ while (i < rest.length) {
454
+ const v = rest[i]?.value ?? null;
455
+ if (v === "--") {
456
+ i++;
457
+ break;
458
+ }
459
+ if (!isOption(v))
460
+ break;
461
+ i += withValue.has(v) ? 2 : 1;
462
+ }
463
+ return rest.slice(i);
464
+ };
465
+ switch (lower) {
466
+ case "sudo":
467
+ case "doas":
468
+ case "su": {
469
+ acc.tag("high-risk", "perm.change");
470
+ acc.reason("runs with elevated privileges");
471
+ if (lower === "su") {
472
+ if (hasFlag(args, "-c"))
473
+ acc.unanalyzable("su -c runs a command string");
474
+ return;
475
+ }
476
+ return unwrap(skipOpts(args, new Set(["-u", "-g", "-h", "-p", "-C", "-D", "-r", "-t", "-U", "--user", "--group"])));
477
+ }
478
+ case "env": {
479
+ let i = 0;
480
+ while (i < args.length) {
481
+ const v = args[i]?.value ?? null;
482
+ if (v === "-i" || v === "--ignore-environment" || v === "-0" || v === "--null") {
483
+ i++;
484
+ continue;
485
+ }
486
+ if (v === "-u" || v === "--unset" || v === "-C" || v === "--chdir" || v === "-S") {
487
+ if (v === "-S")
488
+ acc.unanalyzable("env -S splits a command string");
489
+ i += 2;
490
+ continue;
491
+ }
492
+ if (v !== null && /^[A-Za-z_][A-Za-z0-9_]*=/.test(v)) {
493
+ const varName = v.split("=")[0];
494
+ envPrefix.push(varName);
495
+ if (HIJACK.has(varName) || varName.startsWith("DYLD_") || varName.startsWith("LD_"))
496
+ acc.unanalyzable(`env sets ${varName}, which changes what runs`);
497
+ i++;
498
+ continue;
499
+ }
500
+ if (args[i]?.value === null) {
501
+ acc.unanalyzable("env argument isn't literal");
502
+ return;
503
+ }
504
+ break;
505
+ }
506
+ const rest = args.slice(i);
507
+ if (rest.length === 0) {
508
+ acc.envDump = true;
509
+ return;
510
+ } // prints the environment
511
+ return unwrap(rest);
512
+ }
513
+ case "command":
514
+ case "builtin": {
515
+ if (hasFlag(args, "-v", "-V"))
516
+ return;
517
+ return unwrap(skipOpts(args, new Set()));
518
+ }
519
+ case "exec": {
520
+ if (args.length === 0)
521
+ return;
522
+ return unwrap(skipOpts(args, new Set(["-a"])));
523
+ }
524
+ case "nohup":
525
+ case "time":
526
+ case "caffeinate": return unwrap(skipOpts(args, new Set()));
527
+ case "nice": return unwrap(skipOpts(args, new Set(["-n", "--adjustment"])));
528
+ case "ionice": return unwrap(skipOpts(args, new Set(["-c", "-n", "-p", "-t"])));
529
+ case "stdbuf": return unwrap(skipOpts(args, new Set(["-i", "-o", "-e"])));
530
+ case "chrt":
531
+ case "taskset": return unwrap(skipOpts(args, new Set()).slice(1));
532
+ case "timeout":
533
+ case "gtimeout": {
534
+ const rest = skipOpts(args, new Set(["-s", "--signal", "-k", "--kill-after"]));
535
+ return unwrap(rest.slice(1));
536
+ }
537
+ case "watch": return unwrap(skipOpts(args, new Set(["-n", "--interval", "-d"])));
538
+ case "xargs": {
539
+ const rest = skipOpts(args, new Set(["-n", "-L", "-P", "-I", "-i", "-d", "-E", "-s", "-a", "--max-args", "--max-procs", "--delimiter", "--replace", "--arg-file"]));
540
+ if (rest.length === 0)
541
+ return;
542
+ // The arguments xargs adds come from stdin, so they're unknown (red team, Step 5).
543
+ const unknownArg = { word: { parts: [{ t: "var", name: "XARGS", braced: false, quoted: false }], raw: "<stdin>", brace: false }, value: null, pathValue: null, suffix: "", dynamic: true, glob: false, substs: [] };
544
+ return unwrap([...rest, unknownArg]);
545
+ }
546
+ case "parallel": return unwrap(skipOpts(args, new Set(["-j", "--jobs"])));
547
+ case "npx":
548
+ case "bunx":
549
+ case "pnpx": {
550
+ acc.tags.add("net.fetch.package-manager");
551
+ const rest = skipOpts(args, new Set(["-p", "--package", "-c"]));
552
+ if (hasFlag(args, "-c")) {
553
+ acc.unanalyzable("npx -c runs a command string");
554
+ return;
555
+ }
556
+ if (rest.length === 0)
557
+ return;
558
+ return projectTool(rest, c, unwrapDepth);
559
+ }
560
+ }
561
+ // ── Self-protection commands ───────────────────────────────────────────
562
+ if (lower === "glassbox" || lower === "glassbox.exe") {
563
+ const sub = operands(args)[0]?.value ?? "";
564
+ const mutating = ["mode", "allow", "uninstall", "logout", "login", "install", "pair", "unpair", "config", "set", "disable", "enable", "reset"].includes(sub) || (sub === "doctor" && hasFlag(args, "--fix"));
565
+ if (mutating || args.some((a) => a.value === null))
566
+ acc.protect("CP-SELF-003", "changes Glassbox protection settings");
567
+ return;
568
+ }
569
+ if (lower === "claude" || lower === "claude.exe")
570
+ return claudeCommand(args, c);
571
+ if (lower === "reg" || lower === "reg.exe") {
572
+ const flat = args.map((a) => (a.value ?? a.word.raw)).join(" ").toLowerCase().replace(/[\\/"']/g, "");
573
+ if (flat.includes("policiesclaudecode")) {
574
+ acc.protect("CP-SELF-003", "changes Claude Code policy in the registry");
575
+ return;
576
+ }
577
+ const sub = (args[0]?.value ?? "").toLowerCase();
578
+ if (["add", "delete", "import", "restore", "load", "copy"].includes(sub))
579
+ acc.tag("high-risk", "config.agent");
580
+ return;
581
+ }
582
+ // ── Shells and interpreters ────────────────────────────────────────────
583
+ if (SHELLS.has(lower))
584
+ return shellInvocation(args, c, unwrapDepth);
585
+ if (lower === "cmd" || lower === "cmd.exe") {
586
+ acc.unanalyzable("cmd.exe syntax isn't analyzed");
587
+ return;
588
+ }
589
+ if (lower === "powershell" || lower === "pwsh" || lower === "powershell.exe" || lower === "pwsh.exe") {
590
+ acc.unanalyzable("PowerShell started from a shell command");
591
+ return;
592
+ }
593
+ if (INTERPRETERS.has(lower) || /^python\d(\.\d+)?$/.test(lower))
594
+ return interpreter(lower, args, c);
595
+ if (lower === "eval" || lower === "source" || lower === "." || lower === "alias" || lower === "trap" || lower === "enable" || lower === "coproc") {
596
+ acc.unanalyzable(`'${lower}' runs code that can't be analyzed statically`);
597
+ return;
598
+ }
599
+ if (lower === "set") {
600
+ if (args.some((a) => /^[-+][a-zA-Z]*[fB]/.test(a.value ?? "") || /^(noglob|braceexpand)$/.test(a.value ?? "")))
601
+ acc.unanalyzable("set changes how later words expand");
602
+ return;
603
+ }
604
+ if (lower === "shopt") {
605
+ if (args.some((a) => ["expand_aliases", "extglob", "nullglob", "failglob", "dotglob"].includes(a.value ?? "")) && hasFlag(args, "-s"))
606
+ acc.unanalyzable("shopt changes how later commands expand");
607
+ return;
608
+ }
609
+ if (lower === "export" || lower === "declare" || lower === "typeset" || lower === "local" || lower === "readonly") {
610
+ for (const a of args) {
611
+ const v = a.value ?? a.word.raw;
612
+ const nm = v.split("=")[0] ?? "";
613
+ if (HIJACK.has(nm) || nm.startsWith("DYLD_") || nm.startsWith("LD_"))
614
+ acc.unanalyzable(`${lower} ${nm} changes what later commands run`);
615
+ if (v.startsWith("-f") || v === "-f")
616
+ acc.unanalyzable(`${lower} -f exports functions`);
617
+ }
618
+ return;
619
+ }
620
+ if (lower === "cd" || lower === "pushd" || lower === "popd") {
621
+ const target = args.find((a) => !isOption(a.value));
622
+ if (lower === "popd" || (target && target.value === "-")) {
623
+ cwd.cwd = null;
624
+ return;
625
+ }
626
+ if (!target) {
627
+ cwd.cwd = pctx.homeDir;
628
+ return;
629
+ }
630
+ if (target.pathValue === null) {
631
+ cwd.cwd = null;
632
+ return;
633
+ }
634
+ const np = normalizePath(target.pathValue, pctx);
635
+ cwd.cwd = np.path;
636
+ return;
637
+ }
638
+ // ── Version control ────────────────────────────────────────────────────
639
+ if (lower === "git")
640
+ return git(args, c);
641
+ if (lower === "gh")
642
+ return gh(args, c);
643
+ // ── Package managers and project tools ─────────────────────────────────
644
+ if (["npm", "pnpm", "yarn", "bun"].includes(lower))
645
+ return jsPm(lower, args, c);
646
+ if (["pip", "pip3", "pipx", "uv", "poetry", "pdm", "conda", "mamba", "cargo", "go", "gem", "bundle", "bundler", "composer", "apt", "apt-get", "brew", "yum", "dnf", "pacman", "apk", "choco", "winget", "scoop", "dotnet", "mvn", "gradle", "deno"].includes(lower))
647
+ return otherPm(lower, args, c);
648
+ if (name.startsWith("./") || name.startsWith("../") || PROJECT.has(lower) || lower === "gradlew") {
649
+ acc.tag("write-reversible", "exec.project-code");
650
+ return;
651
+ }
652
+ // ── Database CLIs ──────────────────────────────────────────────────────
653
+ if (["psql", "mysql", "sqlite3", "mariadb", "sqlcmd", "duckdb", "clickhouse-client"].includes(lower))
654
+ return dbCli(lower, args, c);
655
+ // ── Classes from the command table ─────────────────────────────────────
656
+ if (lower === "redis-cli" || lower === "valkey-cli" || lower === "keydb-cli") {
657
+ if (args.some((a) => ["flushall", "flushdb"].includes((a.value ?? "").toLowerCase()))) {
658
+ acc.tag("high-risk", "db.unscoped-write", "db.delete");
659
+ acc.reason("deletes every key in the Redis database");
660
+ return;
661
+ }
662
+ }
663
+ if (REMOVE.has(lower))
664
+ return remove(lower, args, c);
665
+ if (lower === "find")
666
+ return find(args, c, unwrapDepth);
667
+ if (lower === "dd") {
668
+ acc.tag("write-reversible", "fs.write");
669
+ for (const a of args) {
670
+ const v = a.value ?? "";
671
+ if (v.startsWith("of=")) {
672
+ const target = v.slice(3);
673
+ if (/^\/dev\/(sd|nvme|hd|disk|xvd|vd|mmcblk|rdisk)/.test(target))
674
+ destroy(acc, "overwrites a disk device");
675
+ else
676
+ writeTarget(normalizePath(target, pctx), acc, pctx);
677
+ }
678
+ if (a.value === null && (a.word.raw.startsWith("of=")))
679
+ acc.unanalyzable("dd output isn't known statically");
680
+ }
681
+ return;
682
+ }
683
+ if (lower.startsWith("mkfs") || lower === "diskpart" || lower === "fdisk" || lower === "parted" || lower === "wipefs" || lower === "format") {
684
+ destroy(acc, "formats or repartitions a disk");
685
+ return;
686
+ }
687
+ if (["chmod", "chown", "chgrp", "setfacl", "chattr", "icacls", "takeown", "attrib", "passwd", "usermod", "useradd", "visudo", "setcap"].includes(lower))
688
+ return perm(lower, args, c);
689
+ if (lower === "crontab") {
690
+ // Listing is a read; installing, editing or removing a crontab is a scheduled job (CP-SELF-006).
691
+ const flags = args.map((a) => a.value ?? "");
692
+ if (flags.every((f) => f === "-l" || f === "-u" || !f.startsWith("-")) && flags.includes("-l"))
693
+ return;
694
+ if (flags.includes("-r")) {
695
+ acc.scheduleJob({ kind: "cron", verb: "removes", path: null, schedule: "every job in this crontab", files: [] });
696
+ return;
697
+ }
698
+ const file = operands(args, new Set(["-u"]))[0];
699
+ const fileVal = file && file.value !== "-" ? file.pathValue : null;
700
+ const np = fileVal ? normalizePath(fileVal, pctx) : null;
701
+ // The schedule comes from the crontab text when it's in the command (echo … | crontab -).
702
+ acc.scheduleJob({ kind: "cron", verb: flags.includes("-e") ? "changes" : "creates", path: null, schedule: null, files: np?.path ? [np.path] : [] });
703
+ return;
704
+ }
705
+ if (lower === "rsync")
706
+ return rsync(args, c);
707
+ if (NET.has(lower))
708
+ return network(lower, args, c);
709
+ if (["docker", "podman"].includes(lower))
710
+ return docker(args, c);
711
+ if (["kubectl", "helm", "terraform", "tofu", "pulumi", "vercel", "netlify", "fly", "flyctl", "wrangler", "firebase", "heroku", "aws", "gcloud", "gsutil", "az", "doctl", "serverless", "sls", "cdk", "eb", "railway", "render"].includes(lower))
712
+ return deploy(lower, args, c);
713
+ if (["twine", "gem_push"].includes(lower)) {
714
+ acc.tag("high-risk", "publish.public", "net.egress");
715
+ acc.network = true;
716
+ return;
717
+ }
718
+ if (lower === "sed") {
719
+ if (!hasFlag(args, "-i", "--in-place"))
720
+ return;
721
+ let ops = operands(args, new Set(["-e", "-f", "--expression", "--file"]));
722
+ if (!hasFlag(args, "-e", "-f", "--expression", "--file"))
723
+ ops = ops.slice(1);
724
+ return writeOps(ops, c, "fs.write");
725
+ }
726
+ if (lower === "awk" || lower === "gawk") {
727
+ if (args.some((a) => a.value === "inplace"))
728
+ acc.tag("write-reversible", "fs.write");
729
+ if (args.some((a) => (a.value ?? "").includes("system(") || (a.value ?? "").includes("| getline")))
730
+ acc.unanalyzable("awk program runs commands");
731
+ return;
732
+ }
733
+ if (lower === "tee")
734
+ return writeOps(operands(args), c, "fs.write");
735
+ if (lower === "mv")
736
+ return writeOps(operands(args, new Set(["-t", "--target-directory", "-S", "--suffix"])), c, "fs.move");
737
+ if (lower === "ln")
738
+ return writeOps(operands(args, new Set(["-t", "--target-directory", "-S", "--suffix"])), c, "fs.write");
739
+ if (lower === "tar") {
740
+ const create = args.some((a) => /^-?[a-z]*c/.test(a.value ?? "") && !(a.value ?? "").startsWith("--"));
741
+ const extract = args.some((a) => /^-?[a-z]*x/.test(a.value ?? "") && !(a.value ?? "").startsWith("--"));
742
+ if (extract || create)
743
+ acc.tag("write-reversible", "fs.write");
744
+ return;
745
+ }
746
+ if (WRITE.has(lower))
747
+ return writeOps(operands(args, new Set(["-t", "--target-directory", "-m", "--mode", "-S", "--suffix", "-o", "-g", "-p"])), c, "fs.write");
748
+ if (READ.has(lower))
749
+ return;
750
+ // Scheduled jobs and services (rev 9): ask with the schedule and the command (CP-SELF-006).
751
+ if (scheduledJobCommand(lower, args, c))
752
+ return;
753
+ if (["kill", "pkill", "killall", "systemctl", "service", "launchctl", "shutdown", "reboot", "halt", "poweroff", "init", "telinit"].includes(lower)) {
754
+ const vals = args.map((a) => (a.value ?? "").toLowerCase());
755
+ const power = ["shutdown", "reboot", "halt", "poweroff"].includes(lower) || ((lower === "init" || lower === "telinit") && ["0", "6"].includes(vals[0] ?? ""));
756
+ const sysctlPower = lower === "systemctl" && vals.some((v) => ["poweroff", "reboot", "halt", "kexec", "suspend", "hibernate", "emergency", "rescue"].includes(v));
757
+ const stopsService = (lower === "systemctl" && vals.some((v) => ["stop", "disable", "mask", "kill"].includes(v))) || (lower === "service" && vals.includes("stop"));
758
+ if (power || sysctlPower) {
759
+ acc.tag("high-risk", "infra.change");
760
+ acc.reason("powers off or restarts the machine");
761
+ }
762
+ else if (stopsService) {
763
+ acc.tag("high-risk", "infra.change");
764
+ acc.reason("stops or disables a system service");
765
+ }
766
+ else
767
+ acc.tag("write-reversible", "exec.unknown");
768
+ return;
769
+ }
770
+ // Deleting backups, shadow copies or recovery settings: irreversible (ask).
771
+ if ((lower === "vssadmin" && args.some((a) => /^(delete|resize)$/i.test(a.value ?? ""))) || lower === "diskshadow" ||
772
+ (lower === "wbadmin" && args.some((a) => /^delete$/i.test(a.value ?? ""))) ||
773
+ (lower === "wmic" && args.some((a) => /^shadowcopy$/i.test(a.value ?? "")) && args.some((a) => /^delete$/i.test(a.value ?? ""))) ||
774
+ (lower === "bcdedit" && args.some((a) => /recoveryenabled|bootstatuspolicy/i.test(a.value ?? "")))) {
775
+ acc.tag("high-risk", "fs.destroy");
776
+ acc.reason("deletes backups, shadow copies or recovery settings");
777
+ return;
778
+ }
779
+ acc.tag("write-reversible", "exec.unknown");
780
+ acc.reason(`runs '${name.slice(0, 40)}', which Glassbox doesn't classify`);
781
+ // Red team (Step 4): an unclassified program (an editor, a custom tool) handed a
782
+ // protected path may write it. Known read-only commands are classified above and stay allowed.
783
+ for (const a of args) {
784
+ const v = a.pathValue;
785
+ if (v === null || !looksLikePath(v))
786
+ continue;
787
+ if (isProtectedWrite(normalizePath(v, pctx), pctx, a.glob)) {
788
+ acc.protect("CP-SELF-001", "hands a protected agent or Glassbox file to a program that may change it");
789
+ return;
790
+ }
791
+ }
792
+ }
793
+ function claudeCommand(args, c) {
794
+ const { acc } = c;
795
+ const vals = args.map((a) => a.value);
796
+ if (c.envPrefix.some((e) => e === "CLAUDE_CONFIG_DIR" || e.startsWith("CLAUDE_CODE_"))) {
797
+ acc.protect("CP-SELF-003", "starts a nested agent with a different configuration");
798
+ return;
799
+ }
800
+ const danger = ["--settings", "--setting-sources", "--plugin-dir", "--mcp-config", "--strict-mcp-config", "--dangerously-skip-permissions", "--allow-dangerously-skip-permissions"];
801
+ if (vals.some((v) => v !== null && danger.some((d) => v === d || v.startsWith(d + "=")))) {
802
+ acc.protect("CP-SELF-003", "starts a nested agent that overrides settings or permissions");
803
+ return;
804
+ }
805
+ const pm = vals.indexOf("--permission-mode");
806
+ if (pm >= 0 && (vals[pm + 1] === "bypassPermissions" || vals[pm + 1] === null)) {
807
+ acc.protect("CP-SELF-003", "starts a nested agent with permissions bypassed");
808
+ return;
809
+ }
810
+ if (vals.some((v) => v !== null && v.startsWith("--permission-mode=bypass"))) {
811
+ acc.protect("CP-SELF-003", "starts a nested agent with permissions bypassed");
812
+ return;
813
+ }
814
+ if (vals[0] === "plugin" || vals[0] === "plugins") {
815
+ if (["disable", "uninstall", "remove", "marketplace", "install", "enable"].includes(vals[1] ?? "")) {
816
+ acc.protect("CP-SELF-003", "changes agent plugins");
817
+ return;
818
+ }
819
+ return;
820
+ }
821
+ if (vals[0] === "mcp" && ["add", "remove", "add-json", "add-from-claude-desktop", "reset-project-choices"].includes(vals[1] ?? "")) {
822
+ acc.protect("CP-SELF-003", "changes the agent's MCP servers");
823
+ return;
824
+ }
825
+ if (vals[0] === "config" && ["set", "add", "remove"].includes(vals[1] ?? "")) {
826
+ acc.protect("CP-SELF-003", "changes agent configuration");
827
+ return;
828
+ }
829
+ if (args.length === 1 && ["--version", "-v", "--help", "-h"].includes(vals[0] ?? ""))
830
+ return;
831
+ if (vals.some((v) => v === null)) {
832
+ acc.tag("high-risk", "exec.nested-agent");
833
+ acc.reason("starts a nested agent");
834
+ return;
835
+ }
836
+ acc.tag("high-risk", "exec.nested-agent");
837
+ acc.reason("starts a nested agent");
838
+ }
839
+ function shellInvocation(args, c, unwrapDepth) {
840
+ const { acc, cmd, st } = c;
841
+ const ci = args.findIndex((a) => a.value === "-c" || (a.value !== null && /^-[a-z]*c$/.test(a.value)));
842
+ if (ci >= 0) {
843
+ const script = args[ci + 1];
844
+ if (!script || script.value === null) {
845
+ acc.unanalyzable("shell -c with a non-literal command string");
846
+ return;
847
+ }
848
+ if (st.depth + 1 > 3 || unwrapDepth >= 4) {
849
+ acc.unanalyzable("shell -c nested too deep");
850
+ return;
851
+ }
852
+ const inner = analyzeShellCommand(script.value, { ...st, depth: st.depth + 1 });
853
+ acc.merge(inner);
854
+ return;
855
+ }
856
+ const kind = stdinKind(cmd);
857
+ const fileArg = operands(args, new Set(["-o", "+o", "-O", "+O"]))[0];
858
+ if (fileArg) {
859
+ if (fileArg.value === null) {
860
+ acc.unanalyzable("shell runs a script whose name isn't literal");
861
+ return;
862
+ }
863
+ acc.tag("write-reversible", "exec.project-code");
864
+ return;
865
+ }
866
+ if (kind === "heredoc") {
867
+ const h = cmd.redirects.find((r) => r.heredoc)?.heredoc;
868
+ if (h) {
869
+ if (st.depth + 1 > 3) {
870
+ acc.unanalyzable("nested too deep");
871
+ return;
872
+ }
873
+ acc.merge(analyzeShellCommand(h.body, { ...st, depth: st.depth + 1 }));
874
+ return;
875
+ }
876
+ }
877
+ if (kind === "herestring") {
878
+ const r = cmd.redirects.find((x) => x.op === "<<<");
879
+ const v = r?.target ? wordInfo(r.target).value : null;
880
+ if (v === null) {
881
+ acc.unanalyzable("shell reads a non-literal here-string");
882
+ return;
883
+ }
884
+ acc.merge(analyzeShellCommand(v, { ...st, depth: st.depth + 1 }));
885
+ return;
886
+ }
887
+ if (kind === "pipe") {
888
+ const from = cmd.pipedFrom?.words[0];
889
+ const fromName = from ? (wordInfo(from).value ?? "") : "";
890
+ if (NET_PIPE_SOURCES.has(fromName.split("/").pop() ?? "")) {
891
+ acc.find("CP-SHELL-010");
892
+ acc.tag("high-risk", "net.egress");
893
+ acc.network = true;
894
+ }
895
+ acc.unanalyzable("a shell reads commands from a pipe");
896
+ return;
897
+ }
898
+ if (kind === "file") {
899
+ acc.unanalyzable("a shell reads commands from a file redirect");
900
+ return;
901
+ }
902
+ acc.tag("write-reversible", "exec.unknown");
903
+ }
904
+ function interpreter(lower, args, c) {
905
+ const { acc, cmd, pctx } = c;
906
+ // Red team (Step 4): an interpreter can write any path it's handed (perl -pi -e …, a
907
+ // script given ~/.claude/settings.json), and a here-doc or here-string body is inline code.
908
+ for (const a of args) {
909
+ const np = a.pathValue !== null && looksLikePath(a.pathValue) ? normalizePath(a.pathValue, pctx) : null;
910
+ if (np && isProtectedWrite(np, pctx, a.glob)) {
911
+ acc.protect("CP-SELF-001", "hands a protected agent or Glassbox file to an interpreter");
912
+ return;
913
+ }
914
+ }
915
+ const hereStr = cmd.redirects.find((r) => r.op === "<<<")?.target;
916
+ const body = cmd.redirects.find((r) => r.heredoc)?.heredoc?.body ?? (hereStr ? wordInfo(hereStr).value ?? "" : "");
917
+ if (body && protectedText(body, pctx)) {
918
+ acc.protect(body.includes(".key") ? "CP-SELF-002" : "CP-SELF-001", "inline code refers to a protected agent or Glassbox file");
919
+ return;
920
+ }
921
+ const flagsWithCode = new Set(["-c", "-e", "--eval", "-p", "--print", "-E", "-r"]);
922
+ const idx = args.findIndex((a) => a.value !== null && (flagsWithCode.has(a.value) || (lower.startsWith("python") && /^-[A-Za-z]*c$/.test(a.value))));
923
+ if (idx >= 0) {
924
+ const code = args[idx + 1];
925
+ acc.tag("write-reversible", "exec.inline-code");
926
+ if (!code || code.value === null) {
927
+ acc.unanalyzable("inline code isn't a literal string");
928
+ return;
929
+ }
930
+ // Protected paths inside the code → self-protection (spec §7.6.2).
931
+ if (protectedText(code.value, pctx)) {
932
+ const lowerCode = code.value.toLowerCase();
933
+ acc.protect(lowerCode.includes(".key") || lowerCode.includes("device") ? "CP-SELF-002" : "CP-SELF-001", "inline code refers to a protected agent or Glassbox file");
934
+ return;
935
+ }
936
+ // Module flags (perl -MLWP::Simple, ruby -rnet/http) count as part of the code.
937
+ const modules = args.filter((a) => a.value !== null && (/^-M./.test(a.value) || /^-r[a-z]/.test(a.value))).map((a) => a.value.slice(2));
938
+ const v = analyzeInlineCode(modules.length > 0 ? `${code.value} ${modules.join(" ")}` : code.value);
939
+ if (v.unanalyzable) {
940
+ acc.unanalyzable(v.unanalyzable);
941
+ return;
942
+ }
943
+ // Spec rev 6, Q3: what the code is aimed at.
944
+ if (v.network) {
945
+ acc.tag("high-risk", "net.egress");
946
+ acc.network = true;
947
+ }
948
+ if (v.sensitive) {
949
+ acc.sensitive.push("credentials or environment in inline code");
950
+ acc.sensitiveArgs = true;
951
+ }
952
+ // A tree delete aimed at home or the root destroys data (same bar as rm -rf ~); a tree
953
+ // delete of a named folder like 'build' stays at the ordinary delete level.
954
+ if (v.destroysTree && v.homeOrRoot) {
955
+ acc.tag("high-risk", "fs.destroy");
956
+ acc.find("CP-ACTION-001", "inline code deletes the home directory or the filesystem root");
957
+ }
958
+ if (v.dangerous) {
959
+ acc.raise("high-risk");
960
+ acc.reason("inline code deletes files, uses the network or runs processes");
961
+ if (/\b(requests|urllib|http|fetch|socket|axios|httpx)\b/.test(code.value)) {
962
+ acc.tags.add("net.egress");
963
+ acc.network = true;
964
+ }
965
+ else
966
+ acc.tags.add("fs.delete");
967
+ }
968
+ return;
969
+ }
970
+ if (args.some((a) => a.value === "-m")) {
971
+ acc.tag("write-reversible", "exec.project-code");
972
+ return;
973
+ }
974
+ const file = operands(args, new Set(["-W", "-X", "--require", "-r", "--import", "--loader", "-I"]))[0];
975
+ const kind = stdinKind(cmd);
976
+ if (file && file.value !== "-") {
977
+ if (file.value === null) {
978
+ acc.unanalyzable("interpreter runs a script whose name isn't literal");
979
+ return;
980
+ }
981
+ acc.tag("write-reversible", "exec.project-code");
982
+ return;
983
+ }
984
+ if (kind !== "none" || file?.value === "-") {
985
+ if (kind === "pipe") {
986
+ const from = cmd.pipedFrom?.words[0];
987
+ const fromName = from ? (wordInfo(from).value ?? "") : "";
988
+ if (NET_PIPE_SOURCES.has(fromName)) {
989
+ acc.find("CP-SHELL-010");
990
+ acc.tag("high-risk", "net.egress");
991
+ acc.network = true;
992
+ }
993
+ }
994
+ acc.unanalyzable("an interpreter reads code from stdin");
995
+ return;
996
+ }
997
+ acc.tag("write-reversible", "exec.inline-code");
998
+ acc.reason("starts an interactive interpreter");
999
+ }
1000
+ /** Does free text (inline code, a here-doc) mention a protected agent or Glassbox path? */
1001
+ function protectedText(text, pctx) {
1002
+ const norm = (x) => x.toLowerCase().split("\\").join("/");
1003
+ const t = norm(text);
1004
+ const needles = [".glassbox", ".claude/settings", ".claude.json", ".mcp.json", ".claude/hooks", ".claude/plugins", "claudecode/", "policies/claudecode"];
1005
+ if (pctx.claudeConfigDir)
1006
+ needles.push(norm(pctx.claudeConfigDir) + "/settings");
1007
+ for (const sp of pctx.secretPaths)
1008
+ needles.push(norm(sp));
1009
+ return needles.some((n) => n.length > 0 && t.includes(n));
1010
+ }
1011
+ function projectTool(rest, c, unwrapDepth) {
1012
+ const h = rest[0];
1013
+ if (!h || h.value === null) {
1014
+ c.acc.unanalyzable("package runner with a non-literal package");
1015
+ return;
1016
+ }
1017
+ const n = (() => { const v = h.value; const slash = v.lastIndexOf("/"); const at = v.indexOf("@", slash + 1); return (at >= 0 ? v.slice(0, at) : v).split("/").pop() ?? ""; })();
1018
+ if (PROJECT.has(n) || READ.has(n)) {
1019
+ c.acc.tag("write-reversible", "exec.project-code");
1020
+ return;
1021
+ }
1022
+ if (unwrapDepth < 4 && (n === "rimraf" || n === "del-cli")) {
1023
+ c.acc.tag("high-risk", "fs.delete");
1024
+ return;
1025
+ }
1026
+ c.acc.tag("write-reversible", "exec.project-code");
1027
+ }
1028
+ function writeOps(targets, c, tag) {
1029
+ const { acc, pctx } = c;
1030
+ acc.tag("write-reversible", tag);
1031
+ for (const t of targets) {
1032
+ const np = npOf(t, pctx);
1033
+ if (np === null) {
1034
+ acc.unanalyzable("writes to a path that isn't known statically");
1035
+ continue;
1036
+ }
1037
+ writeTarget(np, acc, pctx, t.glob);
1038
+ }
1039
+ }
1040
+ function remove(lower, args, c) {
1041
+ const { acc, pctx } = c;
1042
+ acc.tag("high-risk", "fs.delete");
1043
+ const recursive = lower === "rm" && hasFlag(args, "-r", "-R", "--recursive");
1044
+ const noPreserve = args.some((a) => a.value === "--no-preserve-root");
1045
+ if (noPreserve)
1046
+ destroy(acc, "deletes the filesystem root");
1047
+ const targets = operands(args, new Set(["-n", "--iterations", "-s", "--size"]));
1048
+ const home = normalizePath("~", pctx).path;
1049
+ for (const t of targets) {
1050
+ const np = npOf(t, pctx);
1051
+ if (np === null) {
1052
+ acc.unanalyzable("deletes a path that isn't known statically");
1053
+ continue;
1054
+ }
1055
+ writeTarget(np, acc, pctx, t.glob);
1056
+ const raw = t.pathValue ?? "";
1057
+ const p = np.path;
1058
+ const rootLevel = p !== null && /^(\/[^/]*|[a-z]:\/[^/]*)$/i.test(p);
1059
+ const isHome = p !== null && home !== null && (p === home || p === home + "/*");
1060
+ const star = raw === "*" || raw === "/*" || raw === "~/*" || raw === "$HOME/*" || raw === "." || raw === "./" || raw === ".." || raw === "./*";
1061
+ if ((recursive || raw.endsWith("*")) && (rootLevel || isHome || star || p === "/"))
1062
+ destroy(acc, "deletes a whole filesystem, home directory or project");
1063
+ else if (recursive && isGitDir(p))
1064
+ destroy(acc, "deletes a repository's .git directory, its whole history");
1065
+ else if (recursive && homeTopLevel(p, pctx))
1066
+ destroy(acc, "deletes a whole folder in the home directory");
1067
+ if (lower === "shred" && p !== null && !scratch(p, c.st.pctx.cwd))
1068
+ destroy(acc, "shreds files outside the project, which can't be recovered");
1069
+ if (p !== null && isLogOrHistory(p))
1070
+ acc.find("CP-ACTION-030", `${lower} on a log or shell history file`);
1071
+ }
1072
+ }
1073
+ /** scheme://…, file:… or scp-style user@host:path. String code, not a regex (ReDoS test). */
1074
+ function isRepoUrl(d) {
1075
+ const l = d.toLowerCase();
1076
+ if (l.startsWith("file:"))
1077
+ return true;
1078
+ const s = l.indexOf("://");
1079
+ if (s > 0 && /^[a-z][a-z0-9+.-]*$/.test(l.slice(0, s)))
1080
+ return true;
1081
+ const at = l.indexOf("@");
1082
+ const colon = l.indexOf(":");
1083
+ return at > 0 && colon > at + 1 && !l.slice(0, at).includes("/");
1084
+ }
1085
+ /** The .git directory of a repository, or everything in it. */
1086
+ function isGitDir(p) {
1087
+ if (p === null)
1088
+ return false;
1089
+ const lp = trimEndChars(p, "/");
1090
+ return lp === ".git" || lp.endsWith("/.git") || lp.endsWith("/.git/*");
1091
+ }
1092
+ /** Inside the session's project directory (not wherever a `cd` went) or a temp directory. */
1093
+ function scratch(p, cwd) {
1094
+ const lp = p.toLowerCase();
1095
+ if (lp.startsWith("/tmp/") || lp.startsWith("/var/tmp/") || lp.startsWith("/private/tmp/"))
1096
+ return true;
1097
+ if (cwd === null)
1098
+ return false;
1099
+ const lc = trimEndChars(cwd.toLowerCase(), "/");
1100
+ return lp.startsWith(lc + "/");
1101
+ }
1102
+ /** System logs and shell history files: clearing them hides what happened (warn, CP-ACTION-030). */
1103
+ function isLogOrHistory(p) {
1104
+ const lp = p.toLowerCase();
1105
+ const base = lp.slice(lp.lastIndexOf("/") + 1);
1106
+ return lp.startsWith("/var/log/") || base.endsWith("_history") || base === ".history" || base === "wtmp" || base === "btmp" || base === "lastlog";
1107
+ }
1108
+ const FIND_NARROWING = new Set(["-name", "-iname", "-path", "-ipath", "-wholename", "-iwholename", "-regex", "-iregex", "-newer", "-mtime", "-mmin", "-atime", "-amin", "-ctime", "-cmin", "-size", "-user", "-group", "-perm", "-empty", "-links", "-inum", "-samefile", "-lname", "-ilname", "-maxdepth"]);
1109
+ function find(args, c, unwrapDepth) {
1110
+ const { acc, pctx } = c;
1111
+ if (args.some((a) => a.value === "-delete"))
1112
+ acc.tag("high-risk", "fs.delete");
1113
+ // Red team (Step 5): `find . -delete` or `find ~ -exec rm -rf {} +` with nothing narrowing
1114
+ // the match deletes everything under the root, like `rm -rf .`.
1115
+ const deletes = args.some((a) => a.value === "-delete") || args.some((a, k) => (a.value === "-exec" || a.value === "-execdir") && ["rm", "unlink", "shred"].includes(args[k + 1]?.value ?? ""));
1116
+ if (deletes && !args.some((a) => FIND_NARROWING.has(a.value ?? ""))) {
1117
+ const roots = [];
1118
+ for (const a of args) {
1119
+ if ((a.value ?? "-").startsWith("-") || a.value === "(" || a.value === "!")
1120
+ break;
1121
+ roots.push(a);
1122
+ }
1123
+ if (roots.length === 0)
1124
+ roots.push({ word: { parts: [], raw: ".", brace: false }, value: ".", pathValue: ".", suffix: ".", dynamic: false, glob: false, substs: [] });
1125
+ const home = normalizePath("~", pctx).path;
1126
+ const cwd = pctx.cwd !== null ? normalizePath(pctx.cwd, pctx).path : null;
1127
+ for (const r of roots) {
1128
+ const np = npOf(r, pctx);
1129
+ const p = np?.path ?? null;
1130
+ if (r.pathValue === null || p === null || p === "/" || p === home || p === cwd || /^(\/[^/]*|[a-z]:\/[^/]*)$/i.test(p) || (cwd !== null && cwd.startsWith(p + "/"))) {
1131
+ destroy(acc, "deletes everything under a project, home or root directory");
1132
+ break;
1133
+ }
1134
+ }
1135
+ }
1136
+ for (let i = 0; i < args.length; i++) {
1137
+ const v = args[i]?.value;
1138
+ if (v === "-exec" || v === "-execdir" || v === "-ok" || v === "-okdir") {
1139
+ const inner = [];
1140
+ let j = i + 1;
1141
+ while (j < args.length && args[j]?.value !== ";" && args[j]?.value !== "+") {
1142
+ inner.push(args[j]);
1143
+ j++;
1144
+ }
1145
+ const h = inner[0];
1146
+ if (!h || h.value === null) {
1147
+ acc.unanalyzable("find -exec with a non-literal command");
1148
+ continue;
1149
+ }
1150
+ if (unwrapDepth >= 4) {
1151
+ acc.unanalyzable("too many nested wrappers");
1152
+ continue;
1153
+ }
1154
+ classify(h.value, inner.slice(1).filter((w) => w.value !== "{}"), c.cmd, c.st, acc, c.pctx, c.cwd, c.envPrefix, c.functions, unwrapDepth + 1);
1155
+ i = j;
1156
+ }
1157
+ if (v === "-fprint" || v === "-fprintf" || v === "-fls")
1158
+ acc.tag("write-reversible", "fs.write");
1159
+ }
1160
+ // find loops forever on `while j < … && args[j] !== ";"` only if inner never ends; bounded by args length.
1161
+ }
1162
+ /** systemd-run timers, at, schtasks, sc, launchctl and systemctl enable. True when handled. */
1163
+ function scheduledJobCommand(lower, args, c) {
1164
+ const { acc, pctx } = c;
1165
+ const vals = args.map((a) => a.value ?? "");
1166
+ const lv = vals.map((v) => v.toLowerCase());
1167
+ const abs = (f) => normalizePath(f, pctx).path ?? f;
1168
+ if (lower === "systemd-run") {
1169
+ const sched = [];
1170
+ const withValue = new Set(["--unit", "-u", "--property", "-p", "--description", "--slice", "--setenv", "-E", "--uid", "--gid", "--working-directory", "-M", "--machine", "--nice", "--timer-property"]);
1171
+ let i = 0;
1172
+ for (; i < vals.length; i++) {
1173
+ const v = vals[i];
1174
+ if (v.startsWith("--on-")) {
1175
+ const eq = v.indexOf("=");
1176
+ if (eq > 0)
1177
+ sched.push(v);
1178
+ else {
1179
+ sched.push(`${v} ${vals[i + 1] ?? ""}`.trim());
1180
+ i++;
1181
+ }
1182
+ continue;
1183
+ }
1184
+ if (withValue.has(v)) {
1185
+ i++;
1186
+ continue;
1187
+ }
1188
+ if (v.startsWith("-"))
1189
+ continue;
1190
+ break;
1191
+ }
1192
+ if (sched.length === 0)
1193
+ return false; // a transient unit that runs now, not later
1194
+ acc.scheduleJob({ kind: "systemd", verb: "creates", path: null, schedule: sched.join(", "), files: commandFiles(vals.slice(i).join(" ")).map(abs) });
1195
+ return true;
1196
+ }
1197
+ if (lower === "at" || lower === "batch") {
1198
+ if (vals.length === 0 && lower === "at")
1199
+ return false;
1200
+ if (vals.every((v) => v === "-l" || v === "-V"))
1201
+ return true; // listing
1202
+ if (vals.includes("-r") || vals.includes("-d")) {
1203
+ acc.scheduleJob({ kind: "at", verb: "removes", path: null, schedule: `job ${vals.filter((v) => !v.startsWith("-")).join(" ")}`, files: [] });
1204
+ return true;
1205
+ }
1206
+ const fIdx = vals.indexOf("-f");
1207
+ const file = fIdx >= 0 ? vals[fIdx + 1] : undefined;
1208
+ const spec = vals.filter((v, k) => !v.startsWith("-") && !(fIdx >= 0 && k === fIdx + 1)).join(" ");
1209
+ acc.scheduleJob({ kind: "at", verb: "creates", path: null, schedule: lower === "batch" ? "when the system load allows" : spec || null, files: file ? [abs(file)] : [] });
1210
+ return true;
1211
+ }
1212
+ if (lower === "schtasks" || lower === "schtasks.exe") {
1213
+ const op = lv.find((v) => ["/create", "-create", "/delete", "-delete", "/change", "-change", "/run", "-run"].includes(v));
1214
+ if (op === undefined)
1215
+ return true; // /query and the rest: listing
1216
+ if (op.endsWith("delete")) {
1217
+ acc.scheduleJob({ kind: "task-scheduler", verb: "removes", path: null, schedule: `task ${vals[lv.indexOf("/tn") + 1] ?? ""}`.trim(), files: [] });
1218
+ return true;
1219
+ }
1220
+ if (op.endsWith("run")) {
1221
+ acc.tag("high-risk", "exec.unknown");
1222
+ acc.reason("runs a scheduled task now");
1223
+ return true;
1224
+ }
1225
+ const j = schtasksJob(lv.map((v, k) => (v.startsWith("/") || v.startsWith("-") ? "/" + v.slice(1) : vals[k])));
1226
+ acc.scheduleJob({ kind: "task-scheduler", verb: op.endsWith("create") ? "creates" : "changes", path: null, schedule: j.schedule, files: j.files });
1227
+ return true;
1228
+ }
1229
+ if (lower === "sc" || lower === "sc.exe") {
1230
+ const sub = lv[0] ?? "";
1231
+ if (!["create", "config", "delete"].includes(sub))
1232
+ return false;
1233
+ const after = (key) => { const k = lv.findIndex((v) => v === key || v.startsWith(key)); if (k < 0)
1234
+ return null; const v = vals[k]; return v.length > key.length ? v.slice(key.length) : vals[k + 1] ?? null; };
1235
+ const bin = after("binpath=");
1236
+ const start = after("start=");
1237
+ acc.scheduleJob({ kind: "service", verb: sub === "delete" ? "removes" : sub === "create" ? "creates" : "changes", path: null, schedule: start ? `start=${start}` : sub === "delete" ? `service ${vals[1] ?? ""}` : "as a Windows service", files: bin ? commandFiles(bin) : [] });
1238
+ return true;
1239
+ }
1240
+ if (lower === "launchctl") {
1241
+ const sub = lv[0] ?? "";
1242
+ const plist = operands(args).slice(1).map((o) => o.pathValue).filter((p) => p !== null).pop();
1243
+ if (["load", "bootstrap", "enable", "submit"].includes(sub)) {
1244
+ acc.scheduleJob({ kind: "launchd", verb: "creates", path: plist ? abs(plist) : null, schedule: "as the plist says (loaded now)", files: plist ? [abs(plist)] : [] });
1245
+ return true;
1246
+ }
1247
+ if (["unload", "bootout", "remove", "disable"].includes(sub)) {
1248
+ acc.scheduleJob({ kind: "launchd", verb: "removes", path: plist ? abs(plist) : null, schedule: null, files: [] });
1249
+ return true;
1250
+ }
1251
+ return false;
1252
+ }
1253
+ if (lower === "systemctl") {
1254
+ const sub = lv.find((v) => !v.startsWith("-")) ?? "";
1255
+ const units = vals.filter((v) => !v.startsWith("-") && v.toLowerCase() !== sub);
1256
+ if (sub === "enable" || ((sub === "start" || sub === "restart") && units.some((u) => u.endsWith(".timer")))) {
1257
+ acc.scheduleJob({ kind: "systemd", verb: "creates", path: null, schedule: sub === "enable" ? `enabled at boot or login: ${units.join(", ")}` : `timer ${units.join(", ")}`, files: [] });
1258
+ return true;
1259
+ }
1260
+ return false;
1261
+ }
1262
+ return false;
1263
+ }
1264
+ /** Is `p` inside `dir` (the session's project directory)? */
1265
+ function insideDir(p, dir, pctx) {
1266
+ if (dir === null)
1267
+ return false;
1268
+ const fold = (s) => (pctx.caseInsensitive ? s.toLowerCase() : s);
1269
+ const root = fold(trimEndChars(dir, "/"));
1270
+ const lp = fold(p);
1271
+ return lp === root || lp.startsWith(root + "/");
1272
+ }
1273
+ /** Why a chmod mode is risky (world-writable, setuid/setgid), or null. Unknown modes are risky. */
1274
+ function chmodRisk(mode) {
1275
+ if (/^[0-7]{3,4}$/.test(mode)) {
1276
+ const d = mode.padStart(4, "0");
1277
+ if ((Number(d[0]) & 6) !== 0)
1278
+ return "sets the setuid or setgid bit";
1279
+ if ((Number(d[3]) & 2) !== 0)
1280
+ return "makes a file writable by everyone";
1281
+ return null;
1282
+ }
1283
+ // Symbolic: comma-separated clauses like u+x, go-w, a=rwx.
1284
+ for (const clause of mode.split(",")) {
1285
+ const m = /^([ugoa]*)([-+=])([rwxXst]*)$/.exec(clause);
1286
+ if (!m)
1287
+ return "uses a permission mode Glassbox can't read";
1288
+ const who = m[1] ?? "", op = m[2] ?? "", perms = m[3] ?? "";
1289
+ if (op === "-")
1290
+ continue;
1291
+ if (perms.includes("s"))
1292
+ return "sets the setuid or setgid bit";
1293
+ if (perms.includes("w") && (who.includes("o") || who.includes("a")))
1294
+ return "makes a file writable by everyone";
1295
+ }
1296
+ return null;
1297
+ }
1298
+ function perm(lower, args, c) {
1299
+ const { acc, pctx } = c;
1300
+ const targets = operands(args);
1301
+ if (lower === "chmod") {
1302
+ const ops = operands(args);
1303
+ const mode = ops[0]?.value ?? "";
1304
+ const files = ops.slice(1);
1305
+ // Rev 8 (Q2): chmod asks only when recursive, outside the project, world-writable or
1306
+ // setuid/setgid. Anything else is an ordinary, reversible change.
1307
+ const recursive = hasFlag(args, "-R", "--recursive") || args.some((a) => /^-[a-zA-Z]*R/.test(a.value ?? ""));
1308
+ let outside = false;
1309
+ for (const f of files) {
1310
+ const np = npOf(f, pctx);
1311
+ if (np === null) {
1312
+ acc.unanalyzable("changes permissions on a path that isn't known statically");
1313
+ continue;
1314
+ }
1315
+ writeTarget(np, acc, pctx);
1316
+ if (np.path === null || !insideDir(np.path, c.st.pctx.cwd, pctx))
1317
+ outside = true;
1318
+ }
1319
+ const risky = chmodRisk(mode);
1320
+ if (!recursive && !outside && risky === null) {
1321
+ acc.tag("write-reversible", "fs.write");
1322
+ return;
1323
+ }
1324
+ acc.tag("high-risk", "perm.change");
1325
+ acc.reason(risky ?? (recursive ? "changes permissions recursively" : "changes permissions outside the project"));
1326
+ return;
1327
+ }
1328
+ for (const t of targets) {
1329
+ const np = npOf(t, pctx);
1330
+ if (np)
1331
+ writeTarget(np, acc, pctx);
1332
+ }
1333
+ acc.tag("high-risk", "perm.change");
1334
+ acc.reason("changes ownership, permissions or accounts");
1335
+ }
1336
+ function rsync(args, c) {
1337
+ const ops = operands(args, new Set(["-e", "--rsh", "--exclude", "--include", "--filter", "-f"]));
1338
+ const remotes = ops.filter((o) => remoteOperand(o.value));
1339
+ const loop = remotes.length > 0 && allLoopback(remotes.map((o) => o.value));
1340
+ if (remotes.length > 0 && !loop) {
1341
+ c.acc.tag("high-risk", "net.egress");
1342
+ c.acc.network = true;
1343
+ }
1344
+ // Local sources sent to a remote destination are uploads.
1345
+ const last = ops[ops.length - 1];
1346
+ if (last && remoteOperand(last.value))
1347
+ for (const o of ops.slice(0, -1))
1348
+ if (!remoteOperand(o.value))
1349
+ uploadFile(o, c, loop);
1350
+ if (args.some((a) => a.value === "--delete" || (a.value ?? "").startsWith("--delete")))
1351
+ c.acc.tag("high-risk", "fs.delete");
1352
+ const dest = ops[ops.length - 1];
1353
+ if (dest)
1354
+ writeOps([dest], c, "fs.write");
1355
+ }
1356
+ /** Is this remote operand (scp/rsync) on another host? host:path, user@host:path, rsync://. */
1357
+ function remoteOperand(v) {
1358
+ if (v === null)
1359
+ return true;
1360
+ if (v.startsWith("rsync://"))
1361
+ return true;
1362
+ const colon = v.indexOf(":");
1363
+ const slash = v.indexOf("/");
1364
+ return colon > 0 && (slash < 0 || colon < slash) && !/^[A-Za-z]:$/.test(v.slice(0, 2));
1365
+ }
1366
+ function uploadFile(file, c, loop) {
1367
+ if (loop)
1368
+ return;
1369
+ const np = typeof file === "string" ? normalizePath(file, c.pctx) : npOf(file, c.pctx);
1370
+ const label = typeof file === "string" ? file : (file.pathValue ?? file.suffix ?? "?");
1371
+ recordUpload(c.acc, classifyUpload(np, c.pctx, c.st.pctx.cwd), label.slice(0, 80));
1372
+ }
1373
+ function network(lower, args, c) {
1374
+ const { acc, pctx } = c;
1375
+ // Every destination on this machine (curl http://localhost:3000, scp x localhost:) isn't egress.
1376
+ let dests = [];
1377
+ if (lower === "curl" || lower === "wget" || lower === "http" || lower === "https") {
1378
+ dests = args.filter((a) => a.value === null || (a.value.includes("://") && !a.value.startsWith("-"))).map((a) => a.value);
1379
+ const bare = operands(args, new Set(["-d", "--data", "--data-binary", "--data-raw", "--data-urlencode", "--json", "-T", "--upload-file", "-F", "--form", "-o", "--output", "-O", "-H", "--header", "-u", "--user", "-X", "--request", "-A", "--user-agent", "-e", "--referer", "-b", "--cookie", "-c", "--cookie-jar", "-x", "--proxy", "--post-file", "--body-file", "--post-data", "--header"]));
1380
+ for (const o of bare)
1381
+ if (o.value !== null && !o.value.includes("://") && /^(localhost|127\.|\[::1\])/i.test(o.value))
1382
+ dests.push(o.value);
1383
+ }
1384
+ else if (lower === "scp" || lower === "sftp") {
1385
+ dests = operands(args, new Set(["-P", "-i", "-o", "-F", "-c", "-l", "-S", "-J"])).filter((o) => remoteOperand(o.value)).map((o) => o.value);
1386
+ }
1387
+ const loop = allLoopback(dests);
1388
+ if (loop) {
1389
+ acc.reason("talks only to this machine (loopback)");
1390
+ }
1391
+ else {
1392
+ acc.tag("high-risk", "net.egress");
1393
+ acc.network = true;
1394
+ }
1395
+ if (lower === "curl" || lower === "wget" || lower === "http" || lower === "https") {
1396
+ for (let i = 0; i < args.length; i++) {
1397
+ const v0 = args[i]?.value ?? "";
1398
+ // wget accepts --opt=value; curl takes the value as the next word.
1399
+ const eq = v0.startsWith("--") ? v0.indexOf("=") : -1;
1400
+ const v = eq > 0 ? v0.slice(0, eq) : v0;
1401
+ const next = eq > 0 ? { ...args[i], value: v0.slice(eq + 1), pathValue: v0.slice(eq + 1) } : args[i + 1];
1402
+ if (!next)
1403
+ continue;
1404
+ const nv = next.value;
1405
+ let file;
1406
+ if (v === "-T" || v === "--upload-file" || v === "--post-file" || v === "--body-file")
1407
+ file = next.value === null ? null : next.pathValue ?? "";
1408
+ else if (v === "-d" || v === "--data" || v === "--data-binary" || v === "--json")
1409
+ file = nv === null ? undefined : nv.startsWith("@") ? nv.slice(1) : undefined;
1410
+ else if (v === "--data-urlencode") {
1411
+ if (nv !== null) {
1412
+ const at = nv.indexOf("@");
1413
+ const eqi = nv.indexOf("=");
1414
+ if (at >= 0 && (eqi < 0 || at < eqi))
1415
+ file = nv.slice(at + 1);
1416
+ }
1417
+ }
1418
+ else if (v === "-F" || v === "--form") {
1419
+ if (nv === null)
1420
+ file = null;
1421
+ else {
1422
+ const e = nv.indexOf("=");
1423
+ const rest = e >= 0 ? nv.slice(e + 1) : "";
1424
+ if (rest.startsWith("@") || rest.startsWith("<"))
1425
+ file = (rest.slice(1).split(";")[0] ?? "");
1426
+ }
1427
+ }
1428
+ if (file === null) {
1429
+ if (!loop)
1430
+ recordUpload(acc, "outside", "a file named at run time");
1431
+ }
1432
+ else if (file !== undefined && file !== "" && file !== "-") {
1433
+ readTarget(normalizePath(file, pctx), acc, pctx, false);
1434
+ uploadFile(file, c, loop);
1435
+ }
1436
+ if ((v === "-o" || v === "--output" || (v === "-O" && lower === "wget")) && args[i + 1]) {
1437
+ const np = npOf(args[i + 1], pctx);
1438
+ if (np)
1439
+ writeTarget(np, acc, pctx);
1440
+ }
1441
+ }
1442
+ }
1443
+ if (lower === "scp" || lower === "sftp") {
1444
+ const ops = operands(args, new Set(["-P", "-i", "-o", "-F", "-c", "-l", "-S", "-J"]));
1445
+ const last = ops[ops.length - 1];
1446
+ const toRemote = last !== undefined && remoteOperand(last.value);
1447
+ for (const o of ops.slice(0, -1)) {
1448
+ if (o.value !== null && remoteOperand(o.value))
1449
+ continue; // a remote source: a download
1450
+ if (o.value !== null)
1451
+ readTarget(normalizePath(o.value, pctx), acc, pctx, true);
1452
+ if (toRemote)
1453
+ uploadFile(o, c, loop);
1454
+ }
1455
+ }
1456
+ if (lower === "ssh") {
1457
+ const ops = operands(args, new Set(["-p", "-i", "-o", "-F", "-l", "-L", "-R", "-D", "-J", "-b", "-c", "-e", "-m", "-O", "-Q", "-S", "-W", "-w", "-E", "-B", "-I"]));
1458
+ if (ops.length > 1)
1459
+ acc.reason("runs a command on a remote host");
1460
+ }
1461
+ }
1462
+ function docker(args, c) {
1463
+ const { acc } = c;
1464
+ const sub = operands(args, new Set(["-H", "--host", "--context", "-c", "--config", "-l", "--log-level"]))[0]?.value ?? "";
1465
+ if (["pull", "login", "search"].includes(sub)) {
1466
+ acc.tag("high-risk", "net.egress");
1467
+ acc.network = true;
1468
+ return;
1469
+ }
1470
+ if (sub === "push") {
1471
+ acc.tag("high-risk", "publish.public", "net.egress");
1472
+ acc.network = true;
1473
+ return;
1474
+ }
1475
+ const vals = args.map((a) => a.value ?? "");
1476
+ if ((sub === "system" && vals.includes("prune")) || (sub === "volume" && (vals.includes("prune") || vals.includes("rm")))) {
1477
+ acc.tag("high-risk", "fs.destroy", "fs.delete");
1478
+ acc.reason("deletes Docker volumes or all unused data, which can't be recovered");
1479
+ return;
1480
+ }
1481
+ if (["rm", "rmi", "prune", "kill"].includes(sub) || args.some((a) => a.value === "prune")) {
1482
+ acc.tag("high-risk", "fs.delete");
1483
+ return;
1484
+ }
1485
+ if (["ps", "images", "inspect", "logs", "version", "info", "stats", "top", "history", "port", "diff"].includes(sub))
1486
+ return;
1487
+ if (sub === "run" && args.some((a) => a.value === "--privileged" || (a.value ?? "").startsWith("-v=/:") || a.value === "-v"))
1488
+ acc.reason("runs a container with host access");
1489
+ acc.tag("write-reversible", "exec.unknown");
1490
+ }
1491
+ /** aws s3 rm --recursive, aws s3 rb --force, gcloud storage rm -r, gsutil rm -r. */
1492
+ function cloudBulkDelete(lower, vals) {
1493
+ const recursive = vals.includes("--recursive") || vals.includes("-r") || vals.includes("-R");
1494
+ if (lower === "aws")
1495
+ return vals.includes("s3") && ((vals.includes("rm") && recursive) || (vals.includes("rb") && vals.includes("--force")));
1496
+ if (lower === "gcloud")
1497
+ return vals.includes("storage") && vals.includes("rm") && recursive;
1498
+ if (lower === "gsutil")
1499
+ return vals.includes("rm") && recursive;
1500
+ return false;
1501
+ }
1502
+ /** --context naming a local cluster (kind, minikube, Docker Desktop…) or --server on loopback. */
1503
+ function localKubeContext(args) {
1504
+ const vals = args.map((a) => a.value ?? "");
1505
+ const valueOf = (flag) => {
1506
+ for (let i = 0; i < vals.length; i++) {
1507
+ if (vals[i] === flag)
1508
+ return vals[i + 1] ?? "";
1509
+ if ((vals[i] ?? "").startsWith(flag + "="))
1510
+ return (vals[i] ?? "").slice(flag.length + 1);
1511
+ }
1512
+ return null;
1513
+ };
1514
+ const ctxName = (valueOf("--context") ?? "").toLowerCase();
1515
+ if (/^(kind|minikube|docker-desktop|docker-for-desktop|rancher-desktop|orbstack|colima|microk8s|k3d-.+|kind-.+)$/.test(ctxName))
1516
+ return true;
1517
+ const server = valueOf("--server") ?? valueOf("-s");
1518
+ return server !== null && allLoopback([server]);
1519
+ }
1520
+ function deploy(lower, args, c) {
1521
+ const { acc } = c;
1522
+ acc.network = true;
1523
+ const vals = args.map((a) => a.value ?? "");
1524
+ const sub = operands(args, new Set(["-n", "--namespace", "--context", "--kubeconfig", "--project", "--region", "--profile", "-c", "-f", "--chdir", "-o", "--output"]))[0]?.value ?? "";
1525
+ const readSubs = new Set(["get", "describe", "logs", "list", "ls", "show", "status", "plan", "validate", "fmt", "version", "init", "whoami", "config", "top", "explain", "diff", "history", "output", "preview", "info", "inspect", "help", "--version", "-v", "dev", "login"]);
1526
+ if (cloudBulkDelete(lower, vals)) {
1527
+ acc.tag("high-risk", "fs.destroy", "net.egress");
1528
+ acc.reason("deletes cloud storage objects in bulk, which can't be recovered");
1529
+ return;
1530
+ }
1531
+ if (lower === "kubectl") {
1532
+ // Rev 8 (Q2): label/annotate warn; delete/apply/scale ask unless the context is local.
1533
+ if (sub === "label" || sub === "annotate") {
1534
+ acc.tag("high-risk", "net.egress");
1535
+ acc.reason(`kubectl ${sub} changes object metadata`);
1536
+ return;
1537
+ }
1538
+ if (sub === "delete" || sub === "apply" || sub === "scale") {
1539
+ if (localKubeContext(args)) {
1540
+ acc.tag("high-risk", "net.egress");
1541
+ acc.reason(`kubectl ${sub} on a local cluster`);
1542
+ return;
1543
+ }
1544
+ acc.tag("high-risk", "infra.change", "net.egress");
1545
+ acc.reason(`kubectl ${sub} on a cluster that isn't known to be local`);
1546
+ return;
1547
+ }
1548
+ }
1549
+ if (lower === "vercel") {
1550
+ if (vals.includes("--prod") || vals.includes("--production") || sub === "promote") {
1551
+ acc.tag("high-risk", "deploy.prod", "net.egress");
1552
+ return;
1553
+ }
1554
+ if (["ls", "list", "inspect", "logs", "whoami", "env", "pull", "dev", "build", "link"].includes(sub)) {
1555
+ acc.tag("high-risk", "net.egress");
1556
+ return;
1557
+ }
1558
+ acc.tag("high-risk", "deploy.other", "net.egress");
1559
+ return;
1560
+ }
1561
+ if (lower === "netlify") {
1562
+ if (sub === "deploy" && (vals.includes("--prod") || vals.includes("--production"))) {
1563
+ acc.tag("high-risk", "deploy.prod", "net.egress");
1564
+ return;
1565
+ }
1566
+ acc.tag("high-risk", sub === "deploy" ? "deploy.other" : "net.egress", "net.egress");
1567
+ return;
1568
+ }
1569
+ if (["fly", "flyctl", "wrangler", "firebase", "heroku", "railway", "render", "eb", "serverless", "sls"].includes(lower)) {
1570
+ if (["deploy", "publish", "release", "promote"].includes(sub) || vals.includes("deploy")) {
1571
+ acc.tag("high-risk", "deploy.prod", "net.egress");
1572
+ return;
1573
+ }
1574
+ acc.tag("high-risk", "net.egress");
1575
+ return;
1576
+ }
1577
+ if (readSubs.has(sub)) {
1578
+ acc.tag("high-risk", "net.egress");
1579
+ return;
1580
+ }
1581
+ const mutating = ["apply", "delete", "destroy", "rollout", "scale", "patch", "edit", "replace", "create", "drain", "cordon", "taint", "install", "upgrade", "uninstall", "rollback", "up", "import", "state", "set", "run", "exec", "cp", "label", "annotate", "expose", "autoscale", "deploy", "remove", "update", "put", "terminate", "start", "stop"];
1582
+ if (mutating.includes(sub) || vals.some((v) => ["delete", "create", "update", "put", "terminate", "remove", "deploy", "apply", "destroy"].some((m) => v === m || v.startsWith(m + "-")))) {
1583
+ acc.tag("high-risk", "infra.change", "net.egress");
1584
+ return;
1585
+ }
1586
+ acc.tag("high-risk", "net.egress");
1587
+ }
1588
+ function git(args, c) {
1589
+ const { acc, pctx } = c;
1590
+ // Global options before the subcommand.
1591
+ let i = 0;
1592
+ while (i < args.length) {
1593
+ const v = args[i]?.value ?? null;
1594
+ if (v === null) {
1595
+ acc.unanalyzable("git option isn't literal");
1596
+ return;
1597
+ }
1598
+ if (v === "-C") {
1599
+ const p = args[i + 1];
1600
+ if (!p || p.pathValue === null) {
1601
+ c.cwd.cwd = null;
1602
+ }
1603
+ i += 2;
1604
+ continue;
1605
+ }
1606
+ if (v === "-c") {
1607
+ const kv = args[i + 1]?.value ?? null;
1608
+ if (kv === null) {
1609
+ acc.unanalyzable("git -c value isn't literal");
1610
+ return;
1611
+ }
1612
+ if (DANGEROUS_GIT_CONFIG.test(kv.split("=")[0] ?? "")) {
1613
+ acc.tag("high-risk", "config.agent");
1614
+ acc.reason("git -c sets a value git runs as a command");
1615
+ }
1616
+ i += 2;
1617
+ continue;
1618
+ }
1619
+ if (v.startsWith("--git-dir") || v.startsWith("--work-tree") || v.startsWith("--namespace") || v === "--no-pager" || v === "-P" || v === "--bare" || v === "-p" || v === "--paginate" || v === "--no-replace-objects" || v === "--literal-pathspecs" || v.startsWith("--exec-path") || v === "--no-optional-locks") {
1620
+ if ((v === "--git-dir" || v === "--work-tree" || v === "--namespace") && args[i + 1])
1621
+ i++;
1622
+ i++;
1623
+ continue;
1624
+ }
1625
+ break;
1626
+ }
1627
+ const sub = args[i]?.value ?? "";
1628
+ const rest = args.slice(i + 1);
1629
+ const rv = rest.map((a) => a.value);
1630
+ const ops = operands(rest, new Set(["-m", "-F", "--file", "-C", "-c", "--author", "--date", "-b", "-B", "--format", "--pretty", "-n", "--depth", "-o", "--origin", "-u", "-x", "--exclude", "-e"]));
1631
+ const commit = () => acc.tag("write-reversible", "vcs.commit");
1632
+ const discard = (why) => { acc.tag("high-risk", "vcs.discard-changes"); acc.reason(why); };
1633
+ const net = (...extra) => { acc.tag("high-risk", "net.egress", ...extra); acc.network = true; };
1634
+ switch (sub) {
1635
+ case "status":
1636
+ case "log":
1637
+ case "diff":
1638
+ case "show":
1639
+ case "rev-parse":
1640
+ case "describe":
1641
+ case "blame":
1642
+ case "ls-files":
1643
+ case "ls-tree":
1644
+ case "cat-file":
1645
+ case "shortlog":
1646
+ case "reflog":
1647
+ case "grep":
1648
+ case "merge-base":
1649
+ case "rev-list":
1650
+ case "name-rev":
1651
+ case "for-each-ref":
1652
+ case "version":
1653
+ case "help":
1654
+ case "count-objects":
1655
+ case "whatchanged":
1656
+ case "show-ref":
1657
+ case "check-ignore":
1658
+ case "var":
1659
+ case "show-branch":
1660
+ case "range-diff":
1661
+ case "cherry":
1662
+ case "verify-commit":
1663
+ case "verify-tag":
1664
+ case "fsck":
1665
+ if (sub === "reflog" && ["expire", "delete"].includes(rv[0] ?? ""))
1666
+ discard("deletes reflog entries");
1667
+ return;
1668
+ case "branch": {
1669
+ if (rv.some((v) => v === "-D" || v === "--delete" && rv.includes("--force") || v === "-df" || v === "-fd")) {
1670
+ discard("force-deletes a branch");
1671
+ return;
1672
+ }
1673
+ if (rv.some((v) => v === "-d" || v === "--delete" || v === "-m" || v === "-M" || v === "-c" || v === "-C" || v === "-u" || v === "--set-upstream-to" || v === "-f" || v === "--force")) {
1674
+ commit();
1675
+ return;
1676
+ }
1677
+ if (ops.length > 0 && !rv.some((v) => v === "--list" || v === "-l" || v === "--contains" || v === "--merged" || v === "--no-merged" || v === "--points-at")) {
1678
+ commit();
1679
+ return;
1680
+ }
1681
+ return;
1682
+ }
1683
+ case "tag": {
1684
+ if (rv.some((v) => v === "-d" || v === "--delete")) {
1685
+ commit();
1686
+ return;
1687
+ }
1688
+ if (ops.length > 0 && !rv.some((v) => v === "-l" || v === "--list"))
1689
+ commit();
1690
+ return;
1691
+ }
1692
+ case "remote": {
1693
+ if ((rv[0] === "add" || rv[0] === "set-url") && rv.length >= 3) {
1694
+ const name = operands(rest.slice(1), new Set(["-t", "-m", "--track", "--master"]))[0]?.value ?? null;
1695
+ acc.newRemotes.push(name ?? "\u0000dynamic");
1696
+ }
1697
+ if (["add", "remove", "rm", "rename", "set-url", "set-head", "prune"].includes(rv[0] ?? "")) {
1698
+ commit();
1699
+ return;
1700
+ }
1701
+ if (rv[0] === "update")
1702
+ net("net.fetch.vcs");
1703
+ return;
1704
+ }
1705
+ case "stash": {
1706
+ const s = rv[0] ?? "";
1707
+ if (s === "list" || s === "show")
1708
+ return;
1709
+ if (s === "drop" || s === "clear") {
1710
+ discard("deletes stashed changes");
1711
+ return;
1712
+ }
1713
+ commit();
1714
+ return;
1715
+ }
1716
+ case "config": {
1717
+ const getOnly = rv.some((v) => v === "--get" || v === "--get-all" || v === "--list" || v === "-l" || v === "--get-regexp" || v === "--show-origin" || v === "get" || v === "list");
1718
+ if (getOnly)
1719
+ return;
1720
+ const key = ops[0]?.value ?? null;
1721
+ if (key === null) {
1722
+ acc.unanalyzable("git config key isn't literal");
1723
+ return;
1724
+ }
1725
+ if (ops.length >= 2 || rv.some((v) => v === "--add" || v === "--unset" || v === "--replace-all")) {
1726
+ if (DANGEROUS_GIT_CONFIG.test(key)) {
1727
+ acc.tag("high-risk", "config.agent");
1728
+ acc.reason("sets a git value that git later runs as a command");
1729
+ return;
1730
+ }
1731
+ commit();
1732
+ }
1733
+ return;
1734
+ }
1735
+ case "add":
1736
+ case "commit":
1737
+ case "switch":
1738
+ case "merge":
1739
+ case "cherry-pick":
1740
+ case "revert":
1741
+ case "mv":
1742
+ case "apply":
1743
+ case "am":
1744
+ case "notes":
1745
+ case "init":
1746
+ case "bisect":
1747
+ case "sparse-checkout":
1748
+ case "update-index":
1749
+ case "worktree":
1750
+ case "gc":
1751
+ case "maintenance":
1752
+ case "pull_local":
1753
+ case "format-patch":
1754
+ case "bundle":
1755
+ case "archive":
1756
+ if (sub === "worktree" && (rv[0] === "remove" || rv[0] === "prune") && rv.includes("--force")) {
1757
+ discard("removes a worktree with uncommitted changes");
1758
+ return;
1759
+ }
1760
+ if (sub === "merge" && rv.includes("--abort")) {
1761
+ discard("aborts a merge, discarding its changes");
1762
+ return;
1763
+ }
1764
+ commit();
1765
+ return;
1766
+ case "checkout": {
1767
+ const dd = rv.indexOf("--");
1768
+ if (dd >= 0) {
1769
+ discard("discards uncommitted changes to files");
1770
+ return;
1771
+ }
1772
+ if (rv.some((v) => v === "-f" || v === "--force")) {
1773
+ discard("discards uncommitted changes");
1774
+ return;
1775
+ }
1776
+ if (rv.some((v) => v === "-b" || v === "-B" || v === "--orphan" || v === "-t" || v === "--track")) {
1777
+ commit();
1778
+ return;
1779
+ }
1780
+ if (ops.length === 1 && (ops[0]?.value === "." || ops[0]?.value === "./" || ops[0]?.value === "*")) {
1781
+ discard("discards uncommitted changes to files");
1782
+ return;
1783
+ }
1784
+ if (ops.length >= 2) {
1785
+ discard("discards uncommitted changes to files");
1786
+ return;
1787
+ }
1788
+ commit();
1789
+ return;
1790
+ }
1791
+ case "restore": {
1792
+ if (rv.includes("--staged") && !rv.includes("--worktree") && !rv.includes("-W")) {
1793
+ commit();
1794
+ return;
1795
+ }
1796
+ discard("discards uncommitted changes to files");
1797
+ return;
1798
+ }
1799
+ case "reset": {
1800
+ if (rv.includes("--hard") || rv.includes("--merge")) {
1801
+ discard("discards uncommitted changes");
1802
+ return;
1803
+ }
1804
+ commit();
1805
+ return;
1806
+ }
1807
+ case "clean": {
1808
+ if (rv.some((v) => v === "-n" || v === "--dry-run"))
1809
+ return;
1810
+ acc.tag("high-risk", "fs.delete", "vcs.discard-changes");
1811
+ acc.reason("deletes untracked files, which git can't restore");
1812
+ return;
1813
+ }
1814
+ case "rm": {
1815
+ if (rv.includes("--cached")) {
1816
+ commit();
1817
+ return;
1818
+ }
1819
+ acc.tag("high-risk", "fs.delete");
1820
+ for (const o of ops) {
1821
+ const np = npOf(o, pctx);
1822
+ if (np)
1823
+ writeTarget(np, acc, pctx);
1824
+ }
1825
+ return;
1826
+ }
1827
+ case "rebase": {
1828
+ if (rv.some((v) => v === "--abort" || v === "--quit" || v === "--skip")) {
1829
+ acc.tag("high-risk", "vcs.discard-changes");
1830
+ return;
1831
+ }
1832
+ acc.tag("high-risk", "vcs.commit");
1833
+ acc.reason("rebases, which rewrites local commits");
1834
+ return;
1835
+ }
1836
+ case "filter-branch":
1837
+ case "filter-repo":
1838
+ case "replace":
1839
+ acc.tag("high-risk", "vcs.history-rewrite");
1840
+ acc.reason("rewrites repository history");
1841
+ return;
1842
+ case "push": {
1843
+ net("vcs.push");
1844
+ const force = rv.some((v) => v !== null && (v === "-f" || v === "--force" || v.startsWith("--force-with-lease") || v === "--force-if-includes" || v === "--mirror" || v === "--delete" || v === "-d" || v === "--prune" || (/^-[a-zA-Z]+$/.test(v) && v.includes("f"))));
1845
+ const refspecs = operands(rest, new Set(["--repo", "-o", "--push-option", "--receive-pack", "--exec"])).slice(1);
1846
+ const plusOrColon = refspecs.some((r) => r.value === null || r.value.startsWith("+") || r.value.startsWith(":"));
1847
+ if (force || plusOrColon) {
1848
+ acc.tags.add("vcs.force-push");
1849
+ acc.reason("force-pushes or deletes remote history");
1850
+ }
1851
+ const target = operands(rest, new Set(["--repo", "-o", "--push-option", "--receive-pack", "--exec"]))[0];
1852
+ const repoOpt = rest.find((a) => (a.value ?? "").startsWith("--repo="))?.value?.slice(7);
1853
+ const dest = repoOpt ?? (target ? target.value : undefined);
1854
+ if (dest === null)
1855
+ acc.pushedTo.push("\u0000dynamic");
1856
+ else if (dest !== undefined) {
1857
+ if (isRepoUrl(dest))
1858
+ acc.find("CP-EXFIL-034", "pushes straight to a repository URL instead of a configured remote");
1859
+ else
1860
+ acc.pushedTo.push(dest);
1861
+ }
1862
+ return;
1863
+ }
1864
+ case "pull":
1865
+ case "fetch":
1866
+ case "clone":
1867
+ case "ls-remote":
1868
+ case "submodule":
1869
+ net("net.fetch.vcs");
1870
+ if (sub === "pull" && rv.includes("--force"))
1871
+ acc.tags.add("vcs.discard-changes");
1872
+ if (sub === "clone") {
1873
+ const dest = ops[1];
1874
+ if (dest) {
1875
+ const np = npOf(dest, pctx);
1876
+ if (np)
1877
+ writeTarget(np, acc, pctx);
1878
+ }
1879
+ }
1880
+ return;
1881
+ case "send-email":
1882
+ case "request-pull":
1883
+ acc.tag("high-risk", "message.send", "net.egress");
1884
+ acc.network = true;
1885
+ return;
1886
+ case "": return;
1887
+ case "lfs":
1888
+ if (["push", "pull", "fetch", "clone"].includes(rv[0] ?? "")) {
1889
+ net("net.fetch.vcs");
1890
+ return;
1891
+ }
1892
+ acc.tag("write-reversible", "exec.unknown");
1893
+ return;
1894
+ case "flow":
1895
+ case "absorb":
1896
+ case "annex":
1897
+ case "branchless":
1898
+ case "machete":
1899
+ case "town":
1900
+ case "extras":
1901
+ case "crypt":
1902
+ case "secret":
1903
+ acc.tag("write-reversible", "exec.unknown");
1904
+ return;
1905
+ default:
1906
+ if (args[i]?.value === null) {
1907
+ acc.unanalyzable("git subcommand isn't literal");
1908
+ return;
1909
+ }
1910
+ // Red team (Step 5): `git config alias.p 'push -f'` earlier, then `git p` now.
1911
+ // An unknown subcommand may be an alias for anything, including a force-push.
1912
+ acc.unanalyzable(`unknown git subcommand '${sub.slice(0, 30)}' (it could be an alias)`);
1913
+ }
1914
+ }
1915
+ function gh(args, c) {
1916
+ const { acc } = c;
1917
+ acc.tag("high-risk", "net.egress");
1918
+ acc.network = true;
1919
+ const vals = args.map((a) => a.value ?? "");
1920
+ const [a, b] = operands(args, new Set(["-R", "--repo", "-t", "--title", "-b", "--body", "-F", "--body-file", "-m", "--milestone", "-l", "--label", "-a", "--assignee", "-B", "--base", "-H", "--head", "-L", "--limit", "-q", "--jq", "--json", "-r", "--reviewer", "-n", "--notes"])).map((x) => x.value ?? "");
1921
+ const publish = (a === "pr" && ["create", "comment", "merge", "review", "close", "reopen", "edit", "ready"].includes(b ?? "")) ||
1922
+ (a === "issue" && ["create", "comment", "close", "reopen", "edit", "delete", "transfer", "lock"].includes(b ?? "")) ||
1923
+ (a === "release" && ["create", "upload", "edit", "delete"].includes(b ?? "")) ||
1924
+ (a === "gist" && ["create", "edit", "delete"].includes(b ?? "")) ||
1925
+ (a === "repo" && ["create", "delete", "edit", "rename", "archive", "fork"].includes(b ?? "")) ||
1926
+ (a === "secret" && ["set", "delete"].includes(b ?? "")) || (a === "variable" && ["set", "delete"].includes(b ?? "")) ||
1927
+ (a === "workflow" && ["run", "enable", "disable"].includes(b ?? "")) || (a === "run" && ["rerun", "cancel", "delete"].includes(b ?? ""));
1928
+ if (publish) {
1929
+ acc.tags.add("publish.public");
1930
+ acc.reason("posts or changes content on GitHub");
1931
+ }
1932
+ if (a === "api" && vals.some((v) => v === "-X" || v === "--method" || v.startsWith("--method=") || v === "-f" || v === "-F" || v === "--field" || v === "--raw-field")) {
1933
+ acc.tags.add("publish.public");
1934
+ acc.reason("calls the GitHub API with a write method");
1935
+ }
1936
+ if (a === "auth" && ["token", "status"].includes(b ?? ""))
1937
+ acc.reason("reads GitHub credentials");
1938
+ }
1939
+ function jsPm(lower, args, c) {
1940
+ const { acc } = c;
1941
+ const ops = operands(args, new Set(["--filter", "-F", "-C", "--dir", "--prefix", "-w", "--workspace", "--cwd", "--registry", "--tag", "--access", "--otp"]));
1942
+ const sub = ops[0]?.value ?? "";
1943
+ if (ops[0] && ops[0].value === null) {
1944
+ acc.unanalyzable("package manager subcommand isn't literal");
1945
+ return;
1946
+ }
1947
+ const network = () => { acc.tag("high-risk", "net.egress", "net.fetch.package-manager"); acc.network = true; };
1948
+ if (["publish", "unpublish", "deprecate", "dist-tag", "owner", "access"].includes(sub)) {
1949
+ acc.tag("high-risk", "publish.public", "net.egress");
1950
+ acc.network = true;
1951
+ return;
1952
+ }
1953
+ if (["install", "i", "ci", "add", "update", "up", "upgrade", "remove", "rm", "uninstall", "un", "unlink", "link", "dedupe", "import", "fetch", "rebuild", "audit", "outdated", "create", "init_remote", "patch-commit"].includes(sub)) {
1954
+ if (sub === "audit" && !args.some((a) => a.value === "fix")) {
1955
+ network();
1956
+ return;
1957
+ }
1958
+ network();
1959
+ return;
1960
+ }
1961
+ if (sub === "" && lower !== "npm") {
1962
+ network();
1963
+ return;
1964
+ } // bare `pnpm`/`yarn` installs
1965
+ if (["ls", "list", "why", "view", "info", "show", "config_get", "root", "bin", "prefix", "help", "-v", "--version", "version_show", "explain", "search", "doctor", "query", "licenses", "store_path"].includes(sub))
1966
+ return;
1967
+ if (sub === "config" && ops[1]?.value === "set") {
1968
+ acc.tag("write-reversible", "fs.write");
1969
+ return;
1970
+ }
1971
+ if (["dlx", "x", "exec", "create"].includes(sub)) {
1972
+ acc.tags.add("net.fetch.package-manager");
1973
+ return projectTool(ops.slice(1), c, 0);
1974
+ }
1975
+ acc.tag("write-reversible", "exec.project-code");
1976
+ }
1977
+ function otherPm(lower, args, c) {
1978
+ const { acc } = c;
1979
+ const ops = operands(args, new Set(["-r", "--requirement", "-c", "--constraint", "-t", "--target", "-p", "--package", "--manifest-path", "-C", "--directory"]));
1980
+ const sub = ops[0]?.value ?? "";
1981
+ const network = () => { acc.tag("high-risk", "net.egress", "net.fetch.package-manager"); acc.network = true; };
1982
+ if (["publish", "upload", "push", "release", "yank"].includes(sub) || (lower === "gem" && sub === "push") || (lower === "dotnet" && sub === "nuget" && ops[1]?.value === "push")) {
1983
+ acc.tag("high-risk", "publish.public", "net.egress");
1984
+ acc.network = true;
1985
+ return;
1986
+ }
1987
+ if (lower === "uv" && sub === "pip")
1988
+ return otherPm("pip", ops.slice(1), c);
1989
+ if (["install", "add", "get", "update", "upgrade", "sync", "download", "fetch", "lock", "remove", "uninstall", "tap"].includes(sub) || (lower === "go" && sub === "mod" && ["download", "tidy"].includes(ops[1]?.value ?? ""))) {
1990
+ if (["apt", "apt-get", "yum", "dnf", "pacman", "apk", "brew", "choco", "winget", "scoop"].includes(lower))
1991
+ acc.tags.add("perm.change");
1992
+ network();
1993
+ return;
1994
+ }
1995
+ if (["list", "show", "freeze", "check", "search", "info", "outdated", "env", "version", "--version", "-V", "help", "tree", "metadata", "doc_open"].includes(sub))
1996
+ return;
1997
+ acc.tag("write-reversible", "exec.project-code");
1998
+ }
1999
+ function dbCli(lower, args, c) {
2000
+ const { acc } = c;
2001
+ acc.tag("high-risk", "net.egress");
2002
+ acc.network = true;
2003
+ const flag = lower === "psql" ? ["-c", "--command"] : lower === "mysql" || lower === "mariadb" ? ["-e", "--execute"] : lower === "sqlcmd" ? ["-Q", "-q"] : [];
2004
+ let sql;
2005
+ for (let i = 0; i < args.length; i++)
2006
+ if (flag.includes(args[i]?.value ?? ""))
2007
+ sql = args[i + 1]?.value ?? null;
2008
+ if (lower === "sqlite3" || lower === "duckdb") {
2009
+ acc.tags.delete("net.egress");
2010
+ acc.network = false;
2011
+ acc.level = "read";
2012
+ const ops = operands(args);
2013
+ sql = ops.length >= 2 ? (ops[1]?.value ?? null) : undefined;
2014
+ }
2015
+ if (sql === undefined) {
2016
+ acc.tag("high-risk", "db.write");
2017
+ acc.reason("opens a database session");
2018
+ return;
2019
+ }
2020
+ if (sql === null) {
2021
+ acc.unanalyzable("SQL text isn't literal");
2022
+ return;
2023
+ }
2024
+ acc.merge(analyzeSql(sql, 64 * 1024));
2025
+ }
2026
+ /** Classify a native program invocation (used by the PowerShell analyzer). */
2027
+ export function classifyNative(name, args, cmd, st, acc, cwd) {
2028
+ classify(name, args, cmd, st, acc, { ...st.pctx, cwd: cwd.cwd }, cwd, [], [], 0);
2029
+ }
2030
+ //# sourceMappingURL=analyze.js.map