@yagyeshvyas/vibeguard 1.3.0 → 1.11.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 (167) hide show
  1. package/.vibeguard-mcp.example.json +51 -0
  2. package/CHANGELOG.md +604 -216
  3. package/MCP-FIREWALL.md +296 -0
  4. package/README.md +355 -31
  5. package/bin/cli.js +355 -27
  6. package/bin/cmd-agent-monitor.js +45 -0
  7. package/bin/cmd-agent-risk.js +64 -0
  8. package/bin/cmd-gif.js +62 -0
  9. package/bin/cmd-git-scan.js +74 -0
  10. package/bin/cmd-llm-proxy.js +164 -0
  11. package/bin/cmd-mcp-firewall.js +191 -0
  12. package/bin/cmd-pentest.js +103 -0
  13. package/bin/cmd-platform.js +137 -0
  14. package/bin/cmd-pr-scan.js +135 -0
  15. package/bin/cmd-sbom-diff.js +38 -0
  16. package/bin/cmd-skill-scan.js +35 -0
  17. package/docs/AISVS.md +25 -0
  18. package/docs/ARCHITECTURE.md +81 -0
  19. package/docs/INSTALLATION.md +139 -0
  20. package/docs/WINDOWS.md +74 -0
  21. package/docs/security-policy.strict.example.json +134 -0
  22. package/docs/security-policy.strict.example.pub.pem +3 -0
  23. package/package.json +45 -7
  24. package/src/.vibeguard/cache/file-hashes.json +60 -0
  25. package/src/.vibeguard/latest-snapshot.json +36 -0
  26. package/src/.vibeguard/mcp-pins.json +1 -0
  27. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +428 -0
  28. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +344 -0
  29. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +279 -0
  30. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +297 -0
  31. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +151 -0
  32. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +299 -0
  33. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +65 -0
  34. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +2051 -0
  35. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +168 -0
  36. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +362 -0
  37. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +150 -0
  38. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +1611 -0
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +164 -0
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +292 -0
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +144 -0
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +220 -0
  43. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +428 -0
  44. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +344 -0
  45. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +297 -0
  46. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +299 -0
  47. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +37 -0
  48. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +2055 -0
  49. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +168 -0
  50. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +362 -0
  51. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +220 -0
  52. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +428 -0
  53. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +344 -0
  54. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +279 -0
  55. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +297 -0
  56. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +151 -0
  57. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +299 -0
  58. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +65 -0
  59. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +2055 -0
  60. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +168 -0
  61. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +362 -0
  62. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +150 -0
  63. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +1611 -0
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +164 -0
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +292 -0
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +144 -0
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +220 -0
  68. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +428 -0
  69. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +344 -0
  70. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +279 -0
  71. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +297 -0
  72. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +151 -0
  73. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +299 -0
  74. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +65 -0
  75. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +2054 -0
  76. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +168 -0
  77. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +362 -0
  78. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +150 -0
  79. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +1611 -0
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +164 -0
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +292 -0
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +144 -0
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +220 -0
  84. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +428 -0
  85. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +344 -0
  86. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +297 -0
  87. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +299 -0
  88. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +37 -0
  89. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +2055 -0
  90. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +168 -0
  91. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +362 -0
  92. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +220 -0
  93. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +428 -0
  94. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +344 -0
  95. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +297 -0
  96. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +33 -0
  97. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +2055 -0
  98. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +1611 -0
  99. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +292 -0
  100. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +220 -0
  101. package/src/.vibeguard-baseline.json +5226 -0
  102. package/src/action-guard.js +84 -6
  103. package/src/agent-monitor.js +262 -0
  104. package/src/agent-policy.js +642 -0
  105. package/src/agent-risk.js +271 -0
  106. package/src/agentic.js +1513 -0
  107. package/src/ast.js +165 -7
  108. package/src/audit-trail.js +212 -67
  109. package/src/auto.js +427 -427
  110. package/src/autofix.js +11 -4
  111. package/src/bundles.js +198 -0
  112. package/src/daemon.js +343 -343
  113. package/src/dashboard.js +278 -278
  114. package/src/engine.js +3 -0
  115. package/src/entropy.js +187 -0
  116. package/src/firewall.js +19 -3
  117. package/src/gif.js +134 -0
  118. package/src/gitscan.js +282 -0
  119. package/src/hook.js +151 -151
  120. package/src/injection-decode.js +136 -0
  121. package/src/install.js +298 -280
  122. package/src/integrity.js +16 -1
  123. package/src/integrity.json +43 -13
  124. package/src/interceptor.js +12 -9
  125. package/src/llm-proxy.js +986 -0
  126. package/src/mcp-audit.js +61 -5
  127. package/src/mcp-firewall.js +971 -0
  128. package/src/mcp-server.js +2500 -2047
  129. package/src/obfuscation.js +315 -0
  130. package/src/owasp-agentic.js +314 -0
  131. package/src/pentest.js +589 -0
  132. package/src/pii.js +4 -0
  133. package/src/platform/aisvs.js +38 -0
  134. package/src/platform/approval.js +187 -0
  135. package/src/platform/canonical.js +73 -0
  136. package/src/platform/contracts.js +158 -0
  137. package/src/platform/delegation.js +73 -0
  138. package/src/platform/http-gateway.js +177 -0
  139. package/src/platform/identity.js +253 -0
  140. package/src/platform/jwt.js +86 -0
  141. package/src/platform/mcp-http-bridge.js +199 -0
  142. package/src/platform/memory-guard.js +64 -0
  143. package/src/platform/os-sandbox.js +144 -0
  144. package/src/platform/policy.js +332 -0
  145. package/src/platform/sandbox-manager.js +92 -0
  146. package/src/platform/signed-audit.js +357 -0
  147. package/src/platform/ssrf.js +129 -0
  148. package/src/plugin.js +182 -168
  149. package/src/pre-deploy.js +170 -55
  150. package/src/privacy-audit.js +272 -272
  151. package/src/repl.js +150 -150
  152. package/src/report.js +7 -1
  153. package/src/routes.js +1210 -0
  154. package/src/rules-2026.js +1407 -0
  155. package/src/rules-pack.js +3068 -3019
  156. package/src/rules.js +376 -60
  157. package/src/sandbox.js +200 -10
  158. package/src/sbom.js +193 -164
  159. package/src/scanner.js +189 -33
  160. package/src/shell-guard.js +11 -0
  161. package/src/skill-scan.js +477 -0
  162. package/src/slopsquat.js +144 -144
  163. package/src/surface.js +408 -0
  164. package/src/taint-ast.js +204 -37
  165. package/src/taint.js +15 -3
  166. package/src/tokenlean.js +579 -0
  167. package/src/trace.js +220 -220
@@ -0,0 +1,164 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * VibeGuard SBOM Generator.
5
+ *
6
+ * Generates a CycloneDX 1.5 Software Bill of Materials from:
7
+ * - package-lock.json (dependency tree with integrity hashes)
8
+ * - Source code import/require graph (actual usage)
9
+ *
10
+ * 100% local. Zero network. Zero dependencies.
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+ const crypto = require('crypto');
16
+
17
+ function readJsonSafe(filePath) {
18
+ try {
19
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ function extractPackageName(spec) {
26
+ // Handle scoped and non-scoped, strip version range chars
27
+ const cleaned = spec.replace(/^[@\w/.-]+/, '').trim();
28
+ return spec.split('@').filter(Boolean)[0] ? spec.startsWith('@')
29
+ ? '@' + spec.split('@')[1]
30
+ : spec.split('@')[0] : spec;
31
+ }
32
+
33
+ function parseLockfile(lockfile) {
34
+ if (!lockfile) return [];
35
+ const components = [];
36
+
37
+ // lockfileVersion 2/3 (npm 7+)
38
+ if (lockfile.packages) {
39
+ for (const [pkgPath, info] of Object.entries(lockfile.packages)) {
40
+ if (!pkgPath || pkgPath === '') continue;
41
+ const name = pkgPath.replace(/^node_modules\//, '');
42
+ if (!name || name.includes('node_modules/')) continue; // skip nested transitive for now
43
+ components.push({
44
+ name,
45
+ version: info.version || 'unknown',
46
+ type: 'library',
47
+ 'bom-ref': `pkg:npm/${name}@${info.version || 'unknown'}`,
48
+ ...(info.license ? { licenses: [{ license: { id: info.license } }] } : {}),
49
+ ...(info.resolved ? { externalReferences: [{ type: 'distribution', url: info.resolved }] } : {}),
50
+ ...(info.integrity ? { hashes: [{ alg: info.integrity.split('-')[0] || 'sha512', content: info.integrity.split('-')[1] || '' }] } : {}),
51
+ });
52
+ }
53
+ return components;
54
+ }
55
+
56
+ // lockfileVersion 1 (npm 5-6)
57
+ if (lockfile.dependencies) {
58
+ for (const [name, info] of Object.entries(lockfile.dependencies)) {
59
+ components.push({
60
+ name,
61
+ version: info.version || 'unknown',
62
+ type: 'library',
63
+ 'bom-ref': `pkg:npm/${name}@${info.version || 'unknown'}`,
64
+ ...(info.resolved ? { externalReferences: [{ type: 'distribution', url: info.resolved }] } : {}),
65
+ ...(info.integrity ? { hashes: [{ alg: info.integrity.split('-')[0] || 'sha512', content: info.integrity.split('-')[1] || '' }] } : {}),
66
+ });
67
+ }
68
+ return components;
69
+ }
70
+
71
+ return components;
72
+ }
73
+
74
+ function parsePackageJson(pkgJson) {
75
+ if (!pkgJson) return null;
76
+ return {
77
+ name: pkgJson.name || 'unnamed-project',
78
+ version: pkgJson.version || '0.0.0',
79
+ type: 'application',
80
+ 'bom-ref': `pkg:npm/${pkgJson.name || 'unnamed'}@${pkgJson.version || '0.0.0'}`,
81
+ ...(pkgJson.license ? { licenses: [{ license: { id: pkgJson.license } }] } : {}),
82
+ };
83
+ }
84
+
85
+ function buildImportGraph(dir) {
86
+ const { walk } = require('./scanner');
87
+ const files = walk(dir, []);
88
+ const imports = {};
89
+
90
+ for (const file of files) {
91
+ if (!/\.(js|jsx|ts|tsx|mjs|cjs)$/.test(file)) continue;
92
+ try {
93
+ const content = fs.readFileSync(file, 'utf8');
94
+ const relPath = path.relative(dir, file);
95
+
96
+ // require('x') and require("x")
97
+ const requireMatches = content.match(/require\(\s*['"]([^'"]+)['"]\s*\)/g) || [];
98
+ for (const m of requireMatches) {
99
+ const dep = m.match(/require\(\s*['"]([^'"]+)['"]\s*\)/);
100
+ if (dep && !dep[1].startsWith('.') && !dep[1].startsWith('/')) {
101
+ const pkgName = dep[1].startsWith('@') ? dep[1].split('/').slice(0, 2).join('/') : dep[1].split('/')[0];
102
+ if (!imports[pkgName]) imports[pkgName] = [];
103
+ if (!imports[pkgName].includes(relPath)) imports[pkgName].push(relPath);
104
+ }
105
+ }
106
+
107
+ // import ... from 'x' and import 'x'
108
+ const importMatches = content.match(/import\s+[^'"]*['"]([^'"]+)['"]/g) || [];
109
+ for (const m of importMatches) {
110
+ const dep = m.match(/['"]([^'"]+)['"]/);
111
+ if (dep && !dep[1].startsWith('.') && !dep[1].startsWith('/')) {
112
+ const pkgName = dep[1].startsWith('@') ? dep[1].split('/').slice(0, 2).join('/') : dep[1].split('/')[0];
113
+ if (!imports[pkgName]) imports[pkgName] = [];
114
+ if (!imports[pkgName].includes(relPath)) imports[pkgName].push(relPath);
115
+ }
116
+ }
117
+ } catch {}
118
+ }
119
+
120
+ return imports;
121
+ }
122
+
123
+ function generateSBOM(dir) {
124
+ const pkgJson = readJsonSafe(path.join(dir, 'package.json'));
125
+ const lockfile = readJsonSafe(path.join(dir, 'package-lock.json'));
126
+ const importGraph = buildImportGraph(dir);
127
+
128
+ const rootComponent = parsePackageJson(pkgJson);
129
+ const components = parseLockfile(lockfile);
130
+
131
+ // Mark components as "used" if they appear in the import graph
132
+ for (const comp of components) {
133
+ if (importGraph[comp.name]) {
134
+ comp.properties = comp.properties || [];
135
+ comp.properties.push({ name: 'vibeguard:imported', value: 'true' });
136
+ comp.properties.push({ name: 'vibeguard:imported_by', value: importGraph[comp.name].join(', ') });
137
+ }
138
+ }
139
+
140
+ const bom = {
141
+ bomFormat: 'CycloneDX',
142
+ specVersion: '1.5',
143
+ serialNumber: 'urn:uuid:' + crypto.randomUUID(),
144
+ version: 1,
145
+ metadata: {
146
+ timestamp: new Date().toISOString(),
147
+ tools: [{ vendor: 'VibeGuard', name: 'vibeguard-sbom', version: '1.0.0' }],
148
+ component: rootComponent || undefined,
149
+ },
150
+ components,
151
+ };
152
+
153
+ // Dependency references (flat — just root → each component)
154
+ if (rootComponent && components.length > 0) {
155
+ bom.dependencies = components.map(c => ({
156
+ ref: rootComponent['bom-ref'],
157
+ dependsOn: [c['bom-ref']],
158
+ }));
159
+ }
160
+
161
+ return bom;
162
+ }
163
+
164
+ module.exports = { generateSBOM, parseLockfile, parsePackageJson, buildImportGraph };
@@ -0,0 +1,292 @@
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 };
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Slopsquat detection — detect hallucinated/fictional npm packages.
5
+ *
6
+ * AI coding assistants sometimes "invent" package names that don't exist
7
+ * on the npm registry. If a developer installs one, an attacker can register
8
+ * it and plant malicious code (dependency confusion at the slopsquat level).
9
+ *
10
+ * Strategy:
11
+ * 1. Parse imports/requires from source files
12
+ * 2. Check each package against a known-good list (top 1000 npm packages)
13
+ * 3. Query npm registry (HEAD /package-name) to verify existence
14
+ * 4. Flag packages that don't exist on the registry
15
+ */
16
+
17
+ const https = require('https');
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+
21
+ const IMPORT_RE = /(?:require\s*\(\s*['"]([^'"]+)['"]\s*\)|import\s+(?:[\s\S]*?\s+from\s+)?['"]([^'"]+)['"])/g;
22
+ const SCOPED_RE = /^@([^/]+)\/([^/]+)/;
23
+
24
+ // Top npm packages that are definitely real — short-circuit registry calls
25
+ const KNOWN_PACKAGES = new Set([
26
+ 'react', 'react-dom', 'next', 'vue', 'vue-router', '@vue/server-renderer',
27
+ 'express', 'fastify', 'koa', 'hapi', '@hapi/hapi', 'polka',
28
+ 'axios', 'node-fetch', 'got', 'superagent', 'undici',
29
+ 'lodash', 'ramda', 'date-fns', 'dayjs', 'luxon', 'moment',
30
+ 'chalk', 'colorette', 'kleur', 'picocolors',
31
+ 'zod', 'joi', 'yup', 'ajv', 'io-ts',
32
+ 'prisma', '@prisma/client', 'drizzle-orm', 'kysely', 'mikro-orm',
33
+ 'hono', '@hono/node-server',
34
+ 'jsonwebtoken', 'bcrypt', 'bcryptjs', 'argon2', 'passport',
35
+ 'stripe', '@stripe/stripe-js',
36
+ 'openai', 'anthropic-ai/sdk', '@anthropic-ai/sdk',
37
+ 'dotenv', 'cross-env', 'rimraf', 'nanoid', 'uuid',
38
+ 'typescript', 'ts-node', 'tsx', 'esbuild', 'vite', 'webpack',
39
+ 'eslint', 'prettier', 'jest', 'vitest', 'mocha', 'chai',
40
+ 'tailwindcss', 'postcss', 'autoprefixer',
41
+ 'framer-motion', 'motion', '@radix-ui/react-dialog',
42
+ 'clsx', 'tailwind-merge', 'cva', 'class-variance-authority',
43
+ 'ws', 'socket.io', 'socket.io-client',
44
+ 'mongoose', 'mongodb', 'pg', 'mysql2', 'sqlite3', 'better-sqlite3',
45
+ 'redis', 'ioredis', '@upstash/redis',
46
+ 'graphql', '@apollo/server', 'urql', '@urql/core',
47
+ 'nexus', 'tRPC', '@trpc/server', '@trpc/client',
48
+ 'zustand', 'jotai', 'recoil', 'redux', '@reduxjs/toolkit', 'react-query', '@tanstack/react-query',
49
+ 'dompurify', 'sanitize-html', 'xss',
50
+ 'helmet', 'cors', 'compression', 'morgan', 'body-parser',
51
+ 'sharp', 'canvas', 'jimp',
52
+ 'resend', '@resend/resend-node',
53
+ 'convex', 'turso', '@libsql/client',
54
+ 'expo', 'expo-secure-store', 'expo-constants',
55
+ 'react-native', 'react-native-web',
56
+ 'clerk', '@clerk/nextjs', '@clerk/backend',
57
+ 'next-auth', '@auth/core',
58
+ 'better-auth',
59
+ 'firebase', 'firebase-admin',
60
+ 'pino', 'winston', 'debug',
61
+ 'glob', 'fast-glob', 'tinyglobby', 'chokidar',
62
+ 'commander', 'yargs', 'meow', 'cac',
63
+ 'ajv', 'ajv-formats',
64
+ 'seedrandom', 'nanoid-dictionary',
65
+ ]);
66
+
67
+ function extractImports(content) {
68
+ const pkgs = new Set();
69
+ let m;
70
+ while ((m = IMPORT_RE.exec(content)) !== null) {
71
+ const pkg = m[1] || m[2];
72
+ if (!pkg) continue;
73
+ if (pkg.startsWith('.')) continue;
74
+ if (pkg.startsWith('node:') || pkg.startsWith('bun:')) continue;
75
+ const bare = pkg.split('/')[0];
76
+ if (pkg.startsWith('@')) {
77
+ const sm = SCOPED_RE.exec(pkg);
78
+ if (sm) pkgs.add(`@${sm[1]}/${sm[2]}`);
79
+ } else {
80
+ pkgs.add(bare);
81
+ }
82
+ }
83
+ return [...pkgs];
84
+ }
85
+
86
+ function checkNpmExists(pkgName) {
87
+ return new Promise((resolve) => {
88
+ if (KNOWN_PACKAGES.has(pkgName)) return resolve(true);
89
+ const url = `https://registry.npmjs.org/${encodeURIComponent(pkgName).replace(/%2F/g, '/')}`;
90
+ https
91
+ .get(url, { timeout: 8000 }, (res) => {
92
+ resolve(res.statusCode === 200);
93
+ })
94
+ .on('error', () => resolve(null))
95
+ .on('timeout', function () {
96
+ this.destroy();
97
+ resolve(null);
98
+ });
99
+ });
100
+ }
101
+
102
+ async function scanSlopsquat(root, files) {
103
+ const imports = new Set();
104
+ for (const file of files) {
105
+ try {
106
+ const content = fs.readFileSync(file, 'utf8');
107
+ for (const pkg of extractImports(content)) imports.add(pkg);
108
+ } catch {}
109
+ }
110
+
111
+ const findings = [];
112
+ const batch = [...imports];
113
+ for (let i = 0; i < batch.length; i += 10) {
114
+ const chunk = batch.slice(i, i + 10);
115
+ const results = await Promise.all(
116
+ chunk.map(async (pkg) => {
117
+ const exists = await checkNpmExists(pkg);
118
+ return { pkg, exists };
119
+ })
120
+ );
121
+ for (const r of results) {
122
+ if (r.exists === false) {
123
+ findings.push({
124
+ ruleId: 'supply-chain.slopsquat',
125
+ file: 'imports',
126
+ line: 1,
127
+ column: 1,
128
+ severity: 'medium',
129
+ confidence: 'medium',
130
+ title: `Possibly hallucinated package: ${r.pkg}`,
131
+ snippet: r.pkg,
132
+ message: `Package "${r.pkg}" does not exist on the npm registry. An attacker can register it and inject malicious code. If this is a private/internal package, configure your registry correctly.`,
133
+ fix: `Verify the package name spelling. If internal, configure .npmrc scopes. If from an AI suggestion, remove it.`,
134
+ owasp: 'A08:2025 Software and Data Integrity Failures',
135
+ cwe: 'CWE-494',
136
+ });
137
+ }
138
+ }
139
+ }
140
+
141
+ return { findings, checked: batch.length };
142
+ }
143
+
144
+ module.exports = { scanSlopsquat, extractImports, checkNpmExists, KNOWN_PACKAGES };