@yagyeshvyas/vibeguard 1.12.0 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +34 -17
  3. package/bin/cli.js +2753 -2753
  4. package/bin/cmd-mcp-firewall.js +1 -0
  5. package/bin/cmd-platform.js +3 -0
  6. package/ci/vibeguard.yml +42 -42
  7. package/package.json +2 -2
  8. package/scripts/counts.js +93 -93
  9. package/scripts/postinstall.js +26 -26
  10. package/src/auto.js +427 -427
  11. package/src/daemon.js +343 -343
  12. package/src/dashboard.js +278 -278
  13. package/src/engine.js +297 -297
  14. package/src/hook.js +151 -151
  15. package/src/install.js +298 -298
  16. package/src/integrity.js +1 -0
  17. package/src/integrity.json +9 -6
  18. package/src/mcp-firewall.js +11 -0
  19. package/src/platform/approval-service.js +124 -0
  20. package/src/platform/approval.js +16 -0
  21. package/src/platform/oauth-server.js +89 -0
  22. package/src/platform/os-sandbox.js +52 -1
  23. package/src/platform/runtime-monitor.js +69 -0
  24. package/src/platform/sandbox-manager.js +5 -0
  25. package/src/plugin.js +182 -182
  26. package/src/privacy-audit.js +272 -272
  27. package/src/repl.js +150 -150
  28. package/src/report.js +331 -331
  29. package/src/rules-pack.js +3068 -3068
  30. package/src/rules.js +1822 -1822
  31. package/src/sbom.js +193 -193
  32. package/src/scanner.js +1032 -1032
  33. package/src/shell-guard.js +302 -302
  34. package/src/slopsquat.js +144 -144
  35. package/src/trace.js +220 -220
  36. package/src/.vibeguard/cache/file-hashes.json +0 -60
  37. package/src/.vibeguard/latest-snapshot.json +0 -36
  38. package/src/.vibeguard/mcp-pins.json +0 -1
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +0 -428
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +0 -344
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +0 -279
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +0 -297
  43. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +0 -151
  44. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +0 -299
  45. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +0 -65
  46. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +0 -2051
  47. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +0 -168
  48. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +0 -362
  49. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +0 -150
  50. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +0 -1611
  51. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +0 -164
  52. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +0 -292
  53. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +0 -144
  54. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +0 -220
  55. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +0 -428
  56. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +0 -344
  57. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +0 -297
  58. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +0 -299
  59. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +0 -37
  60. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +0 -2055
  61. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +0 -168
  62. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +0 -362
  63. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +0 -220
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +0 -428
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +0 -344
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +0 -279
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +0 -297
  68. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +0 -151
  69. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +0 -299
  70. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +0 -65
  71. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +0 -2055
  72. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +0 -168
  73. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +0 -362
  74. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +0 -150
  75. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +0 -1611
  76. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +0 -164
  77. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +0 -292
  78. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +0 -144
  79. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +0 -220
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +0 -428
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +0 -344
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +0 -279
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +0 -297
  84. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +0 -151
  85. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +0 -299
  86. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +0 -65
  87. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +0 -2054
  88. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +0 -168
  89. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +0 -362
  90. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +0 -150
  91. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +0 -1611
  92. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +0 -164
  93. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +0 -292
  94. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +0 -144
  95. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +0 -220
  96. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +0 -428
  97. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +0 -344
  98. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +0 -297
  99. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +0 -299
  100. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +0 -37
  101. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +0 -2055
  102. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +0 -168
  103. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +0 -362
  104. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +0 -220
  105. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +0 -428
  106. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +0 -344
  107. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +0 -297
  108. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +0 -33
  109. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +0 -2055
  110. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +0 -1611
  111. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +0 -292
  112. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +0 -220
  113. package/src/.vibeguard-baseline.json +0 -5226
@@ -1,292 +0,0 @@
1
- 'use strict';
2
-
3
- /*
4
- * src/shell-guard.js — Shell-level pre-execution guard with anti-evasion.
5
- *
6
- * Scans a command string BEFORE it runs. Normalizes obfuscation attempts,
7
- * then matches against danger patterns. If blocked, returns { blocked: true }.
8
- *
9
- * Anti-evasion layers (applied in order, all checked):
10
- * 1. Base64 decode: echo "cm0gLXJmIC8" | base64 -d | sh -> rm -rf /
11
- * 2. Env-var indirection: RM="rm -rf"; $RM / -> blocked
12
- * 3. Subshell expansion: $(echo rm) -rf / -> rm -rf /
13
- * 4. Backtick eval: `echo rm` -rf / -> rm -rf /
14
- * 5. Hex/unicode escapes: \x72\x6d -> rm
15
- * 6. rm obfuscation: rm -r -f, rm --recursive --force, /bin/rm, r""m
16
- * 7. Path splitting: /bin/r""m -rf /, /sbin/r''m
17
- * 8. Quoted command: "rm" -rf /, 'rm' -rf /
18
- * 9. Variable concatenation: r=m; ${r}m -rf / -> blocked
19
- *
20
- * IMPORTANT: This catches accidental/AI-mistake dangerous commands. A
21
- * determined adversary with knowledge of the patterns can still evade
22
- * (no static guard is unbreakable). This stops the agent from nuking
23
- * your machine — it is NOT sandbox escape prevention.
24
- *
25
- * 100% local. Zero network. Zero dependencies.
26
- */
27
-
28
- const path = require('path');
29
-
30
- // ─── Anti-evasion normalizer ──────────────────────────────────────────────
31
-
32
- // One normalization pass. Run repeatedly to a fixpoint by normalizeCommand so
33
- // layered obfuscation (a var expanding to another var, base64 decoding to a
34
- // quoted command) unwinds step by step instead of in one brittle sweep.
35
- function normalizeOnce(cmd) {
36
- let normalized = cmd;
37
-
38
- // Layer 1: Base64 decode — catch "echo <base64> | base64 -d | sh"
39
- const b64Match = normalized.match(/echo\s+["']?([A-Za-z0-9+/=]{8,})["']?\s*\|\s*(?:base64|b64)\s+-d\s*\|/i);
40
- if (b64Match) {
41
- try {
42
- const decoded = Buffer.from(b64Match[1], 'base64').toString('utf8');
43
- normalized = normalized.replace(b64Match[0], decoded);
44
- } catch {}
45
- }
46
-
47
- // Layer 2: Env-var indirection — collect EVERY assignment and substitute all
48
- // references. The original code matched only the FIRST assignment (non-global),
49
- // so `A=rm; B=-rf; $A $B /` slipped through. We now sweep all of them, quoted
50
- // and bare, then substitute $VAR and ${VAR}.
51
- const assignAll = {};
52
- const quotedAssign = /(\w+)=(["'])([^"']*)\2/g;
53
- let qa;
54
- while ((qa = quotedAssign.exec(normalized)) !== null) assignAll[qa[1]] = qa[3];
55
- const bareAssign = /(?:^|[;\s])(\w+)=([^"'\s;|&]+)/g;
56
- let ba;
57
- while ((ba = bareAssign.exec(normalized)) !== null) {
58
- if (!(ba[1] in assignAll)) assignAll[ba[1]] = ba[2];
59
- }
60
- for (const [name, value] of Object.entries(assignAll)) {
61
- if (/rm|sudo|chmod|mkfs|dd\s|shutdown|reboot|curl|wget|-rf?\b/i.test(value)) {
62
- normalized = normalized.replace(new RegExp('\\$\\{?' + name + '\\}?\\b', 'g'), value);
63
- }
64
- }
65
- // Strip the assignment statements themselves so they don't linger as noise.
66
- normalized = normalized.replace(/(?:^|[;\s])(\w+)=(?:(["'])[^"']*\2|[^"'\s;|&]+)\s*/g, ' ');
67
-
68
- // Layer 3: Subshell expansion — $(echo rm) -> rm
69
- normalized = normalized.replace(/\$\(\s*echo\s+([^)]+)\s*\)/g, '$1');
70
- // $(printf "rm") -> rm
71
- normalized = normalized.replace(/\$\(\s*printf\s+["']([^"']+)["']\s*\)/g, '$1');
72
-
73
- // Layer 4: Backtick eval — `echo rm` -> rm
74
- normalized = normalized.replace(/`\s*echo\s+([^`]+)\s*`/g, '$1');
75
- normalized = normalized.replace(/`\s*printf\s+["']([^"']+)["']\s*`/g, '$1');
76
-
77
- // Layer 5: Hex/unicode escapes — \x72\x6d -> rm
78
- normalized = normalized.replace(/\\x([0-9a-f]{2})/gi, (m, hex) => {
79
- try { return String.fromCharCode(parseInt(hex, 16)); } catch { return m; }
80
- });
81
- // \u0072 -> r
82
- normalized = normalized.replace(/\\u([0-9a-f]{4})/gi, (m, hex) => {
83
- try { return String.fromCharCode(parseInt(hex, 16)); } catch { return m; }
84
- });
85
-
86
- // Layer 5b: $IFS word-splitting — rm$IFS-rf$IFS/ -> rm -rf /
87
- normalized = normalized.replace(/\$\{?IFS\}?/g, ' ');
88
-
89
- // Layer 6: rm obfuscation — rm -r -f, rm --recursive --force, /bin/rm, /sbin/rm
90
- // Normalize rm flags: -r -f, -fr, -rf, -Rf, --recursive --force all -> -rf
91
- normalized = normalized.replace(/\brm\s+(?:-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*|-[a-zA-Z]*f[a-zA-Z]*r[a-zA-Z]*|--recursive(?:\s+--force)?)\b/i, 'rm -rf');
92
- normalized = normalized.replace(/\brm\s+-r\s+-f\b/i, 'rm -rf');
93
- normalized = normalized.replace(/\brm\s+-f\s+-r\b/i, 'rm -rf');
94
- normalized = normalized.replace(/\brm\s+--recursive\s+--force\b/i, 'rm -rf');
95
- // /bin/rm, /sbin/rm, /usr/bin/rm -> rm
96
- normalized = normalized.replace(/(?:\/usr)?(?:\/bin\/|\/sbin\/)rm\b/g, 'rm');
97
-
98
- // Layer 7: String concatenation — r""m, r''m, r\m -> rm
99
- // Remove quotes and backslashes between letters to detect split commands
100
- normalized = normalized.replace(/([a-zA-Z])["'\\]+([a-zA-Z])/g, '$1$2');
101
-
102
- // Layer 8: Quoted command — "rm", 'rm' -> rm
103
- normalized = normalized.replace(/["']([a-z]{2,})["']/gi, (m, inner) => inner);
104
-
105
- return normalized;
106
- }
107
-
108
- function normalizeCommand(cmd) {
109
- if (!cmd || typeof cmd !== 'string') return cmd || '';
110
- let current = cmd;
111
- // Iterate to a fixpoint (bounded at 5) so layered obfuscation unwinds fully.
112
- // The bound guards against pathological input causing an unbounded loop.
113
- for (let i = 0; i < 5; i++) {
114
- const next = normalizeOnce(current);
115
- if (next === current) break;
116
- current = next;
117
- }
118
- return current.replace(/[ \t]+/g, ' ').trim();
119
- }
120
-
121
- // ─── Danger patterns (matched against BOTH raw AND normalized) ───────────
122
-
123
- const DANGEROUS_COMMANDS = [
124
- { re: /\brm\s+-rf\b/i, reason: 'rm -rf can delete entire directory trees', severity: 'critical' },
125
- { re: /\brm\s+-rf\s+\/(?:\s|$)/i, reason: 'rm -rf / — catastrophic deletion of root filesystem', severity: 'critical' },
126
- { re: /\brm\s+-rf\s+~(?:\s|$|\/)/i, reason: 'rm -rf ~ — deleting home directory', severity: 'critical' },
127
- { re: /\brm\s+-rf\s+\.(?:\s|$)/i, reason: 'rm -rf . — deleting current directory', severity: 'critical' },
128
- { re: /\brm\s+-rf\s+\.\.(?:\s|$)/i, reason: 'rm -rf .. — deleting parent directory', severity: 'critical' },
129
- { re: /\bsudo\b/i, reason: 'sudo escalates privileges — agents should not use sudo', severity: 'high' },
130
- { re: /\bchmod\s+777\b/i, reason: 'chmod 777 grants world write — insecure', severity: 'high' },
131
- { re: /\bmkfs\b/i, reason: 'mkfs formats filesystem — destructive', severity: 'critical' },
132
- { re: /\bdd\s+if=/i, reason: 'dd can overwrite disks — destructive', severity: 'critical' },
133
- { re: /\bdd\s+.*of=\/dev\//i, reason: 'dd writing directly to device — destructive', severity: 'critical' },
134
- { re: /\bshutdown\b/i, reason: 'shutdown stops the machine', severity: 'critical' },
135
- { re: /\breboot\b/i, reason: 'reboot restarts the machine', severity: 'critical' },
136
- { re: /\bhalt\b/i, reason: 'halt stops the machine', severity: 'critical' },
137
- { re: /\bpoweroff\b/i, reason: 'poweroff stops the machine', severity: 'critical' },
138
- { re: /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;/i, reason: 'fork bomb detected', severity: 'critical' },
139
- { re: /\b(?:curl|wget)\b.*\|\s*(?:sh|bash|zsh)\b/i, reason: 'curl|sh — remote code execution via pipe to shell', severity: 'critical' },
140
- { re: /\b(?:curl|wget)\b.*(?:169\.254\.169\.254|metadata\.google\.internal)/i, reason: 'cloud metadata service access — credential theft', severity: 'critical' },
141
- { re: /\bnc\s+-l/i, reason: 'nc -l opens a listener — reverse shell risk', severity: 'high' },
142
- { re: /\b(?:python|python3|node|ruby|perl)\s+-c\s+['"]\s*(?:import|require)\s+(?:os|subprocess|child_process)/i, reason: 'inline script importing OS modules — potential injection', severity: 'high' },
143
- { re: /\bkill(?:\s+-9)?\s+-1\b/i, reason: 'kill -1 kills all processes — system-wide kill', severity: 'critical' },
144
- { re: /\bpkill\s+-9\b/i, reason: 'pkill -9 force kills processes — destructive', severity: 'high' },
145
- { re: /\biotop\s+--only\b/i, reason: 'iotop in batch mode can cause system instability', severity: 'low' },
146
- // Anti-evasion: base64 pipe to shell
147
- { re: /\|\s*(?:base64|b64)\s+-d\s*\|/i, reason: 'base64 decode piped to shell — obfuscated command execution', severity: 'critical' },
148
- { re: /\|\s*(?:sh|bash|zsh|python|python3|node|perl|ruby)\b/i, reason: 'piping to interpreter — potential remote code execution', severity: 'high' },
149
- ];
150
-
151
- const SECRET_PATTERNS = [
152
- { re: /\bsk-proj-[A-Za-z0-9_-]{20,}\b/i, type: 'OpenAI API key' },
153
- { re: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/i, type: 'Anthropic API key' },
154
- { re: /\bsk_live_[A-Za-z0-9]{16,}\b/i, type: 'Stripe secret key' },
155
- { re: /\bAKIA[A-Z0-9]{16}\b/, type: 'AWS access key' },
156
- { re: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/i, type: 'GitHub token' },
157
- { re: /\bglpat-[A-Za-z0-9_-]{20,}\b/i, type: 'GitLab token' },
158
- { re: /\bxox[bpoa]-[A-Za-z0-9-]{10,}\b/i, type: 'Slack token' },
159
- { re: /-----BEGIN\s+(?:RSA\s+|EC\s+)?PRIVATE\s+KEY-----/i, type: 'Private key' },
160
- ];
161
-
162
- const SENSITIVE_PATHS = [
163
- /\.env\b/i,
164
- /\.ssh\b/i,
165
- /\.aws\b/i,
166
- /\.gnupg\b/i,
167
- /\.npmrc\b/i,
168
- /\.gitconfig\b/i,
169
- /\/etc\/passwd/i,
170
- /\/etc\/shadow/i,
171
- /\/etc\/sudoers/i,
172
- /\/etc\/ssh\//i,
173
- /~\/\.ssh\//i,
174
- ];
175
-
176
- const EXFIL_PATTERNS = [
177
- { re: /\b(?:curl|wget|nc|netcat)\b.*(?:\bapi\.|webhook|callback|exfil|upload|send)/i, reason: 'Potential data exfiltration via network tool to external endpoint' },
178
- { re: /\b(?:curl|wget)\b.*-d\s.*(?:token|key|password|secret|credential)/i, reason: 'Sending secrets via curl/wget POST data' },
179
- { re: /\b(?:curl|wget)\b.*--data\b.*(?:token|key|password|secret|credential)/i, reason: 'Sending secrets via curl/wget --data' },
180
- { re: /\b(?:scp|rsync)\b.*@(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/i, reason: 'File transfer to raw IP — potential exfiltration' },
181
- { re: /\b(?:curl|wget)\b.*-F\s.*(?:token|key|password|secret)/i, reason: 'Sending secrets via curl/wget multipart form' },
182
- ];
183
-
184
- // ─── Main check function ──────────────────────────────────────────────────
185
-
186
- function checkCommand(cmd) {
187
- if (!cmd || typeof cmd !== 'string') return { blocked: false, allowed: true };
188
- const trimmed = cmd.trim();
189
-
190
- // Skip empty lines and comments
191
- if (!trimmed || trimmed.startsWith('#')) return { blocked: false, allowed: true };
192
-
193
- // Normalize for anti-evasion
194
- const normalized = normalizeCommand(trimmed);
195
-
196
- // Check BOTH the raw command AND the normalized version
197
- const inputs = [trimmed, normalized];
198
- const violations = [];
199
- const seen = new Set(); // dedupe violations across raw + normalized
200
-
201
- for (const input of inputs) {
202
- // 1. Dangerous commands
203
- for (const { re, reason, severity } of DANGEROUS_COMMANDS) {
204
- if (re.test(input)) {
205
- const key = reason;
206
- if (!seen.has(key)) {
207
- seen.add(key);
208
- violations.push({ type: 'dangerous_command', reason, severity, pattern: re.source });
209
- }
210
- }
211
- }
212
-
213
- // 2. Secret exfiltration
214
- for (const { re, reason } of EXFIL_PATTERNS) {
215
- if (re.test(input)) {
216
- const key = reason;
217
- if (!seen.has(key)) {
218
- seen.add(key);
219
- violations.push({ type: 'exfiltration', reason, severity: 'high', pattern: re.source });
220
- }
221
- }
222
- }
223
-
224
- // 3. Secrets in command
225
- for (const { re, type } of SECRET_PATTERNS) {
226
- if (re.test(input)) {
227
- const key = type;
228
- if (!seen.has(key)) {
229
- seen.add(key);
230
- violations.push({ type: 'secret_exposure', reason: `Secret detected in command: ${type}`, severity: 'critical', pattern: re.source });
231
- }
232
- }
233
- }
234
-
235
- // 4. Sensitive file access
236
- for (const re of SENSITIVE_PATHS) {
237
- if (re.test(input)) {
238
- const match = input.match(re)[0];
239
- const key = 'path:' + match;
240
- if (!seen.has(key)) {
241
- seen.add(key);
242
- violations.push({ type: 'sensitive_path', reason: `Access to sensitive path: ${match}`, severity: 'high', pattern: re.source });
243
- }
244
- }
245
- }
246
- }
247
-
248
- // 5. Prompt injection in shell (e.g., agent putting LLM output into eval)
249
- for (const input of inputs) {
250
- if (/\beval\s+["'].*(?:ignore|disregard|forget|system prompt)/i.test(input)) {
251
- violations.push({ type: 'prompt_injection', reason: 'eval with prompt injection pattern — agent may be compromised', severity: 'critical' });
252
- break;
253
- }
254
- }
255
-
256
- // 6. Obfuscation detection — flag suspicious patterns even if we can't decode them
257
- if (/[a-zA-Z]\[([0-9a-f]{1,2})\]/i.test(trimmed)) {
258
- violations.push({ type: 'obfuscation', reason: 'Bash escape sequence $\'\\xNN\' detected — possible command obfuscation', severity: 'high' });
259
- }
260
- if (trimmed.includes('eval ') && trimmed.includes('$((')) {
261
- violations.push({ type: 'obfuscation', reason: 'eval with arithmetic expansion — possible obfuscation', severity: 'high' });
262
- }
263
-
264
- if (violations.length === 0) return { blocked: false, allowed: true };
265
-
266
- return {
267
- blocked: true,
268
- allowed: false,
269
- violations,
270
- reason: violations[0].reason,
271
- severity: violations[0].severity,
272
- command: trimmed.slice(0, 200),
273
- normalized: normalized !== trimmed ? normalized.slice(0, 200) : undefined,
274
- };
275
- }
276
-
277
- // ─── Batch check (for scripts) ─────────────────────────────────────────────
278
-
279
- function checkScript(content) {
280
- if (!content || typeof content !== 'string') return { blocked: false, findings: [] };
281
- const lines = content.split(/\r?\n/);
282
- const findings = [];
283
- for (let i = 0; i < lines.length; i++) {
284
- const result = checkCommand(lines[i]);
285
- if (result.blocked) {
286
- findings.push({ line: i + 1, ...result });
287
- }
288
- }
289
- return { blocked: findings.length > 0, findings };
290
- }
291
-
292
- module.exports = { checkCommand, checkScript, normalizeCommand, DANGEROUS_COMMANDS, SECRET_PATTERNS, SENSITIVE_PATHS, EXFIL_PATTERNS };
@@ -1,220 +0,0 @@
1
- 'use strict';
2
-
3
- /*
4
- * Prompt tracing — link findings back to the AI prompt that generated them.
5
- *
6
- * Reads Cursor (.cursor/), Claude Code, and Windsurf session history files.
7
- * Scans for security-relevant behavior patterns in AI agent transcripts.
8
- *
9
- * Two capabilities:
10
- * 1. Trace a finding back to the AI prompt that likely generated the code
11
- * 2. Behavior analysis: detect blind approvals, high delegation, risky patterns
12
- */
13
-
14
- const fs = require('fs');
15
- const path = require('path');
16
-
17
- const SESSION_DIRS = [
18
- '.cursor',
19
- '.cursor/projects',
20
- '.windsurf',
21
- '.claude',
22
- '.continue',
23
- ];
24
-
25
- function findSessionFiles(root) {
26
- const files = [];
27
- for (const dir of SESSION_DIRS) {
28
- const absDir = path.join(root, dir);
29
- if (!fs.existsSync(absDir)) continue;
30
- try {
31
- walkAndCollect(absDir, files, /\.(?:json|jsonl|md|txt)$/i);
32
- } catch (err) { console.error(err); }
33
- }
34
- return files;
35
- }
36
-
37
- function walkAndCollect(dir, out, extRe) {
38
- let entries;
39
- try {
40
- entries = fs.readdirSync(dir, { withFileTypes: true });
41
- } catch { return; }
42
- for (const e of entries) {
43
- const full = path.join(dir, e.name);
44
- if (e.isDirectory()) walkAndCollect(full, out, extRe);
45
- else if (e.isFile() && extRe.test(e.name)) out.push(full);
46
- }
47
- }
48
-
49
- function parseSession(filepath) {
50
- const content = fs.readFileSync(filepath, 'utf8');
51
- const messages = [];
52
-
53
- // Try JSONL format (one JSON object per line)
54
- if (filepath.endsWith('.jsonl')) {
55
- for (const line of content.split('\n')) {
56
- try {
57
- const obj = JSON.parse(line);
58
- if (obj.role || obj.type || obj.message) messages.push(obj);
59
- } catch (err) { console.error(err); }
60
- }
61
- }
62
-
63
- // Try JSON array
64
- if (messages.length === 0 && filepath.endsWith('.json')) {
65
- try {
66
- const arr = JSON.parse(content);
67
- if (Array.isArray(arr)) messages.push(...arr);
68
- else messages.push(arr);
69
- } catch {}
70
- }
71
-
72
- // Try markdown/text (split by user/assistant markers)
73
- if (messages.length === 0) {
74
- const parts = content.split(/^(?:User|Human|Assistant|AI|>>>)[:\s]/m);
75
- parts.forEach((p, i) => {
76
- if (p.trim()) messages.push({ role: i % 2 === 0 ? 'user' : 'assistant', content: p.trim() });
77
- });
78
- }
79
-
80
- return { file: filepath, messages };
81
- }
82
-
83
- const RISKY_BEHAVIORS = [
84
- {
85
- id: 'behavior.blind-approval',
86
- re: /(?:yes|ok|sure|go ahead|do it|approve|sounds good|perfect|great)\s*[!.?\s]*$/i,
87
- risk: 'medium',
88
- desc: 'Blind approval of AI suggestion without review',
89
- },
90
- {
91
- id: 'behavior.high-delegation',
92
- re: /(?:do\s+(?:all|everything|the\s+whole)|build\s+(?:the\s+entire|all)|write\s+(?:all|every|the\s+complete)|implement\s+(?:all|everything|the\s+entire))/i,
93
- risk: 'medium',
94
- desc: 'High delegation — asking AI to do everything at once reduces review quality',
95
- },
96
- {
97
- id: 'behavior.skip-tests',
98
- re: /(?:skip|don'?t\s+need|no\s+need\s+for)\s+(?:tests?|testing|validation)/i,
99
- risk: 'high',
100
- desc: 'Requesting code without tests',
101
- },
102
- {
103
- id: 'behavior.skip-auth',
104
- re: /(?:skip|don'?t\s+(?:need|worry\s+about)|no\s+need\s+for)\s+(?:auth|authentication|authorization|security)/i,
105
- risk: 'high',
106
- desc: 'Explicitly requesting to skip authentication/security',
107
- },
108
- {
109
- id: 'behavior.hardcode-secrets',
110
- re: /(?:just\s+)?(?:hardcode|hard-code|put\s+(?:the\s+)?(?:password|secret|token|key|api\s+key)\s+(?:directly\s+)?(?:in|here))/i,
111
- risk: 'high',
112
- desc: 'Asking AI to hardcode secrets',
113
- },
114
- {
115
- id: 'behavior.disable-security',
116
- re: /(?:disable|turn\s+off|remove|skip|bypass)\s+(?:security|validation|sanitization|escaping|CORS|helmet|CSRF)/i,
117
- risk: 'high',
118
- desc: 'Asking AI to disable security features',
119
- },
120
- {
121
- id: 'behavior.trust-input',
122
- re: /(?:trust\s+the\s+(?:user|client|input)|user\s+input\s+is\s+(?:safe|trusted|fine)|don'?t\s+validate)/i,
123
- risk: 'high',
124
- desc: 'Expressing trust in user/client input without validation',
125
- },
126
- {
127
- id: 'behavior.excessive-iter',
128
- re: /(?:again|redo|try\s+again|different\s+approach|start\s+over)/i,
129
- risk: 'low',
130
- desc: 'Excessive iteration on AI output — possible degradation of review quality',
131
- threshold: 10,
132
- },
133
- ];
134
-
135
- function analyzeBehavior(messages) {
136
- const behaviors = [];
137
- let userMessages = 0;
138
- let approvals = 0;
139
- let iterations = 0;
140
-
141
- for (const msg of messages) {
142
- const role = msg.role || msg.type || '';
143
- const content = msg.content || msg.message || msg.text || '';
144
- if (typeof content !== 'string') continue;
145
- if (!/user|human/i.test(role)) continue;
146
- userMessages++;
147
-
148
- for (const b of RISKY_BEHAVIORS) {
149
- if (b.re.test(content)) {
150
- if (b.id === 'behavior.blind-approval') approvals++;
151
- if (b.id === 'behavior.excessive-iter') iterations++;
152
- if (b.id === 'behavior.excessive-iter' && iterations < (b.threshold || 10)) continue;
153
- behaviors.push({
154
- id: b.id,
155
- risk: b.risk,
156
- message: b.desc,
157
- snippet: content.slice(0, 200),
158
- });
159
- }
160
- }
161
- }
162
-
163
- const delegationRatio = userMessages > 0 ? approvals / userMessages : 0;
164
- const risk = delegationRatio > 0.6 ? 'high' : delegationRatio > 0.3 ? 'medium' : 'low';
165
-
166
- return {
167
- totalUserMessages: userMessages,
168
- approvals,
169
- iterations,
170
- delegationRatio: Math.round(delegationRatio * 100) / 100,
171
- risk,
172
- behaviors,
173
- recommendation:
174
- risk === 'high'
175
- ? 'High blind-approval ratio — review AI suggestions more carefully before accepting'
176
- : risk === 'medium'
177
- ? 'Moderate delegation — ensure each AI suggestion is reviewed'
178
- : 'Good review discipline — keep validating AI output',
179
- };
180
- }
181
-
182
- function traceFindingsToPrompts(findings, sessions) {
183
- const traces = [];
184
- for (const f of findings) {
185
- const matching = [];
186
- for (const session of sessions) {
187
- for (const msg of session.messages) {
188
- const content = msg.content || msg.message || '';
189
- if (typeof content !== 'string') continue;
190
- const snippet = f.snippet || '';
191
- if (snippet && content.includes(snippet.slice(0, 30))) {
192
- matching.push({ file: session.file, role: msg.role, snippet: content.slice(0, 200) });
193
- }
194
- const titleWords = (f.title || '').split(/\s+/).filter((w) => w.length > 4);
195
- if (titleWords.length > 0 && titleWords.every((w) => content.toLowerCase().includes(w.toLowerCase()))) {
196
- matching.push({ file: session.file, role: msg.role, snippet: content.slice(0, 200) });
197
- }
198
- }
199
- }
200
- if (matching.length > 0) {
201
- traces.push({ finding: f.ruleId, file: f.file, line: f.line, matches: matching });
202
- }
203
- }
204
- return traces;
205
- }
206
-
207
- function trace(root, findings) {
208
- const sessionFiles = findSessionFiles(root);
209
- if (sessionFiles.length === 0) {
210
- return { sessions: 0, behavior: null, traces: [] };
211
- }
212
-
213
- const sessions = sessionFiles.map(parseSession);
214
- const behavior = analyzeBehavior(sessions.flatMap((s) => s.messages));
215
- const traces = traceFindingsToPrompts(findings, sessions);
216
-
217
- return { sessions: sessions.length, behavior, traces };
218
- }
219
-
220
- module.exports = { trace, analyzeBehavior, findSessionFiles, parseSession, RISKY_BEHAVIORS };