@yagyeshvyas/vibeguard 0.1.0 → 1.0.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.
package/src/rules.js CHANGED
@@ -63,13 +63,18 @@ function isPublicBaaSKey(fullLine, value) {
63
63
 
64
64
  // Build a fix-prompt-friendly one-liner.
65
65
  function makeFinding(rule, opts) {
66
+ // Confidence derivation:
67
+ // - If opts or rule explicitly sets confidence, keep it (taint=high, etc.).
68
+ // - Rules with a filter() function are multi-signal => medium.
69
+ // - Bare regex rules with no filter => low.
70
+ let conf = opts.confidence || rule.confidence;
71
+ if (!conf) {
72
+ conf = typeof rule.filter === 'function' ? 'medium' : 'low';
73
+ }
66
74
  return {
67
75
  ruleId: opts.ruleId || rule.id,
68
76
  severity: opts.severity || rule.severity,
69
- // Confidence: 'high' = mechanical match, safe to act on.
70
- // 'medium'= strong heuristic, glance before acting.
71
- // 'low' = "review this" — a hint, not a verdict.
72
- confidence: opts.confidence || rule.confidence || 'high',
77
+ confidence: conf,
73
78
  title: opts.title || rule.title,
74
79
  message: opts.message || rule.message,
75
80
  fix: opts.fix || rule.fix,
@@ -677,7 +682,7 @@ const robustnessRules = [
677
682
  confidence: 'medium',
678
683
  title: 'NoSQL query built from the request',
679
684
  // Model.find(req.body) / passing req.* straight as a query, or $where operator.
680
- re: /\.(?:find|findOne|findOneAndUpdate|findOneAndDelete|updateOne|updateMany|deleteOne|deleteMany|count|countDocuments)\s*\(\s*req\.(?:body|query|params)\s*[),]|\$where\s*:/,
685
+ re: /\.(?:find|findOne|findOneAndUpdate|findOneAndDelete|updateOne|updateMany|deleteOne|deleteMany|count|countDocuments)\s*\(\s*(?:req\.(?:body|query|params)\s*[)\],]|\{[^}]*req\.(?:body|query|params)\.|\{[^}]*\$where)|\$where\s*:/,
681
686
  skipComments: true,
682
687
  message: 'A database query object comes directly from the request — NoSQL/operator injection (e.g. { "$gt": "" } bypasses checks).',
683
688
  fix: 'Build the query explicitly from validated scalar fields; never pass req.body/query straight into find().',
@@ -842,7 +847,7 @@ const injectionRules = [
842
847
  severity: 'high',
843
848
  confidence: 'medium',
844
849
  title: 'Prototype pollution via deep merge of request data',
845
- re: /\b(?:_\.)?(?:merge|mergeWith|defaultsDeep|extend|set|setWith)\s*\([^)]*\breq\.(?:body|query|params)\b|deepmerge\s*\([^)]*\breq\.(?:body|query|params)\b/i,
850
+ re: /\b(?:_\.)?(?:merge|mergeWith|defaultsDeep|extend|set|setWith)\s*\([^)]*\breq\.(?:body|query|params)\b|deepmerge\s*\([^)]*\breq\.(?:body|query|params)\b|Object\.assign\s*\([^)]*\breq\.(?:body|query|params)\b/i,
846
851
  skipComments: true,
847
852
  message: 'A deep-merge/set of request data can set __proto__/constructor keys — prototype pollution.',
848
853
  fix: 'Validate keys, freeze prototypes, or use a merge that ignores __proto__/prototype/constructor.',
package/src/scanner.js CHANGED
@@ -149,7 +149,7 @@ function scanFileContent(absPath, relPath, content, tree) {
149
149
  }
150
150
  for (const hit of matchAll(rule.re, line)) {
151
151
  if (rule.skipInString && isInsideString(line, hit.index)) continue;
152
- if (rule.filter && !rule.filter(line, hit)) continue;
152
+ if (rule.filter && !rule.filter(line, hit, lines)) continue;
153
153
  findings.push(
154
154
  makeFinding(rule, {
155
155
  file: relPath,
@@ -165,7 +165,7 @@ function scanFileContent(absPath, relPath, content, tree) {
165
165
  // Dataflow/taint analysis: follows user input across lines to a dangerous sink.
166
166
  try {
167
167
  const { analyzeTaint } = require('./taint');
168
- for (const t of analyzeTaint(content, lines, relPath)) findings.push(t);
168
+ for (const t of analyzeTaint(content, lines, relPath, tree)) findings.push(t);
169
169
  } catch {
170
170
  /* taint is best-effort */
171
171
  }
@@ -440,6 +440,19 @@ function computeGrade(findings) {
440
440
  // Collapse noise: on a single file:line, a specific rule supersedes the generic
441
441
  // credential catch-all (e.g. a weak session secret shouldn't also report as a
442
442
  // bare "hardcoded credential"). Also drop exact duplicate (ruleId+file+line).
443
+ //
444
+ // Additionally: when a dataflow-confirmed taint.* finding and a structural ast.*
445
+ // finding land on the same file:line and describe the same vulnerability category,
446
+ // keep only the taint finding (higher confidence) and drop the ast.* duplicate.
447
+ // Map: taint.command-injection ↔ ast.command-injection, etc.
448
+ const TAINT_TO_AST = {
449
+ 'taint.command-injection': 'ast.command-injection',
450
+ 'taint.sql-injection': 'ast.sql-injection',
451
+ 'taint.code-injection': 'ast.eval-dynamic',
452
+ 'taint.path-traversal': 'ast.path-traversal',
453
+ 'taint.ssrf': 'ast.ssrf',
454
+ };
455
+
443
456
  function dedupeFindings(findings) {
444
457
  const linesWithSpecific = new Set();
445
458
  for (const f of findings) {
@@ -447,6 +460,16 @@ function dedupeFindings(findings) {
447
460
  linesWithSpecific.add(`${f.file}:${f.line}`);
448
461
  }
449
462
  }
463
+
464
+ // Build a set of taint.* ruleIds that fired, keyed by file:line, so we can
465
+ // drop the corresponding ast.* finding on the same file:line.
466
+ const taintKeys = new Set();
467
+ for (const f of findings) {
468
+ if (TAINT_TO_AST[f.ruleId]) {
469
+ taintKeys.add(`${f.file}:${f.line}:${TAINT_TO_AST[f.ruleId]}`);
470
+ }
471
+ }
472
+
450
473
  const seen = new Set();
451
474
  const out = [];
452
475
  for (const f of findings) {
@@ -456,6 +479,11 @@ function dedupeFindings(findings) {
456
479
  ) {
457
480
  continue; // superseded by a more specific rule
458
481
  }
482
+ // Drop ast.* finding when a taint.* finding already covers the same file:line.
483
+ const astCounterpart = Object.entries(TAINT_TO_AST).find(([, ast]) => ast === f.ruleId);
484
+ if (astCounterpart && taintKeys.has(`${f.file}:${f.line}:${f.ruleId}`)) {
485
+ continue; // superseded by the dataflow-confirmed taint finding
486
+ }
459
487
  const key = `${f.ruleId}:${f.file}:${f.line}:${f.column}`;
460
488
  if (seen.has(key)) continue;
461
489
  seen.add(key);
@@ -575,6 +603,10 @@ function scan(dir, opts = {}) {
575
603
  }
576
604
 
577
605
  findings = applyInlineSuppressions(findings, contents);
606
+ const { applyInlineSuppressionsWithCount } = require('./suppress');
607
+ const supResult = applyInlineSuppressionsWithCount(findings, contents);
608
+ findings = supResult.kept;
609
+ const suppressedFindings = supResult.suppressed;
578
610
  findings = applyConfigFilters(findings, config);
579
611
 
580
612
  // Merge plugin rules
@@ -632,6 +664,8 @@ function scan(dir, opts = {}) {
632
664
  root,
633
665
  scannedFiles: files.length,
634
666
  findings,
667
+ suppressedFindings,
668
+ suppressedCount: suppressedFindings.length,
635
669
  grade,
636
670
  counts,
637
671
  depsInfo,
@@ -0,0 +1,276 @@
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
+ function normalizeCommand(cmd) {
33
+ if (!cmd || typeof cmd !== 'string') return cmd || '';
34
+ let normalized = cmd;
35
+
36
+ // Layer 1: Base64 decode — catch "echo <base64> | base64 -d | sh"
37
+ const b64Match = normalized.match(/echo\s+["']?([A-Za-z0-9+/=]{8,})["']?\s*\|\s*(?:base64|b64)\s+-d\s*\|/i);
38
+ if (b64Match) {
39
+ try {
40
+ const decoded = Buffer.from(b64Match[1], 'base64').toString('utf8');
41
+ normalized = normalized.replace(b64Match[0], decoded);
42
+ } catch {}
43
+ }
44
+
45
+ // Layer 2: Env-var indirection — VAR="rm -rf"; $VAR /
46
+ // Extract assignments and substitute $VAR references
47
+ const assignMatch = normalized.match(/(\w+)=(["'])([^"']*)\2/);
48
+ if (assignMatch) {
49
+ const varName = assignMatch[1];
50
+ const varValue = assignMatch[3];
51
+ // If the variable contains a dangerous command fragment, substitute it
52
+ if (/rm|sudo|chmod|mkfs|dd\s|shutdown|reboot|curl|wget/i.test(varValue)) {
53
+ normalized = normalized.replace(new RegExp('\\$' + varName + '\\b', 'g'), varValue);
54
+ normalized = normalized.replace(assignMatch[0], ''); // remove the assignment
55
+ }
56
+ }
57
+
58
+ // Layer 3: Subshell expansion — $(echo rm) -> rm
59
+ normalized = normalized.replace(/\$\(\s*echo\s+([^)]+)\s*\)/g, '$1');
60
+ // $(printf "rm") -> rm
61
+ normalized = normalized.replace(/\$\(\s*printf\s+["']([^"']+)["']\s*\)/g, '$1');
62
+
63
+ // Layer 4: Backtick eval — `echo rm` -> rm
64
+ normalized = normalized.replace(/`\s*echo\s+([^`]+)\s*`/g, '$1');
65
+ normalized = normalized.replace(/`\s*printf\s+["']([^"']+)["']\s*`/g, '$1');
66
+
67
+ // Layer 5: Hex/unicode escapes — \x72\x6d -> rm
68
+ normalized = normalized.replace(/\\x([0-9a-f]{2})/gi, (m, hex) => {
69
+ try { return String.fromCharCode(parseInt(hex, 16)); } catch { return m; }
70
+ });
71
+ // \u0072 -> r
72
+ normalized = normalized.replace(/\\u([0-9a-f]{4})/gi, (m, hex) => {
73
+ try { return String.fromCharCode(parseInt(hex, 16)); } catch { return m; }
74
+ });
75
+
76
+ // Layer 6: rm obfuscation — rm -r -f, rm --recursive --force, /bin/rm, /sbin/rm
77
+ // Normalize rm flags: -r -f, -fr, -rf, -Rf, --recursive --force all -> -rf
78
+ 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');
79
+ normalized = normalized.replace(/\brm\s+-r\s+-f\b/i, 'rm -rf');
80
+ normalized = normalized.replace(/\brm\s+-f\s+-r\b/i, 'rm -rf');
81
+ normalized = normalized.replace(/\brm\s+--recursive\s+--force\b/i, 'rm -rf');
82
+ // /bin/rm, /sbin/rm -> rm
83
+ normalized = normalized.replace(/(?:\/bin\/|\/sbin\/)rm\b/g, 'rm');
84
+
85
+ // Layer 7: String concatenation — r""m, r''m, r\m -> rm
86
+ // Remove quotes and backslashes between letters to detect split commands
87
+ normalized = normalized.replace(/([a-zA-Z])["'\\]+([a-zA-Z])/g, '$1$2');
88
+
89
+ // Layer 8: Quoted command — "rm", 'rm' -> rm
90
+ normalized = normalized.replace(/["']([a-z]{2,})["']/gi, (m, inner) => inner);
91
+
92
+ // Layer 9: Variable concatenation — ${r}m, ${RM} -> rm
93
+ // If there's a var assignment followed by ${var}, substitute
94
+ const varAssigns = {};
95
+ const assignPattern = /(\w+)=(["']?)([^"'\s]*)\2/g;
96
+ let am;
97
+ while ((am = assignPattern.exec(cmd)) !== null) {
98
+ varAssigns[am[1]] = am[3];
99
+ }
100
+ normalized = normalized.replace(/\$\{(\w+)\}/g, (m, name) => varAssigns[name] || m);
101
+
102
+ return normalized.trim();
103
+ }
104
+
105
+ // ─── Danger patterns (matched against BOTH raw AND normalized) ───────────
106
+
107
+ const DANGEROUS_COMMANDS = [
108
+ { re: /\brm\s+-rf\b/i, reason: 'rm -rf can delete entire directory trees', severity: 'critical' },
109
+ { re: /\brm\s+-rf\s+\/(?:\s|$)/i, reason: 'rm -rf / — catastrophic deletion of root filesystem', severity: 'critical' },
110
+ { re: /\brm\s+-rf\s+~(?:\s|$|\/)/i, reason: 'rm -rf ~ — deleting home directory', severity: 'critical' },
111
+ { re: /\brm\s+-rf\s+\.(?:\s|$)/i, reason: 'rm -rf . — deleting current directory', severity: 'critical' },
112
+ { re: /\brm\s+-rf\s+\.\.(?:\s|$)/i, reason: 'rm -rf .. — deleting parent directory', severity: 'critical' },
113
+ { re: /\bsudo\b/i, reason: 'sudo escalates privileges — agents should not use sudo', severity: 'high' },
114
+ { re: /\bchmod\s+777\b/i, reason: 'chmod 777 grants world write — insecure', severity: 'high' },
115
+ { re: /\bmkfs\b/i, reason: 'mkfs formats filesystem — destructive', severity: 'critical' },
116
+ { re: /\bdd\s+if=/i, reason: 'dd can overwrite disks — destructive', severity: 'critical' },
117
+ { re: /\bdd\s+.*of=\/dev\//i, reason: 'dd writing directly to device — destructive', severity: 'critical' },
118
+ { re: /\bshutdown\b/i, reason: 'shutdown stops the machine', severity: 'critical' },
119
+ { re: /\breboot\b/i, reason: 'reboot restarts the machine', severity: 'critical' },
120
+ { re: /\bhalt\b/i, reason: 'halt stops the machine', severity: 'critical' },
121
+ { re: /\bpoweroff\b/i, reason: 'poweroff stops the machine', severity: 'critical' },
122
+ { re: /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;/i, reason: 'fork bomb detected', severity: 'critical' },
123
+ { re: /\b(?:curl|wget)\b.*\|\s*(?:sh|bash|zsh)\b/i, reason: 'curl|sh — remote code execution via pipe to shell', severity: 'critical' },
124
+ { re: /\b(?:curl|wget)\b.*(?:169\.254\.169\.254|metadata\.google\.internal)/i, reason: 'cloud metadata service access — credential theft', severity: 'critical' },
125
+ { re: /\bnc\s+-l/i, reason: 'nc -l opens a listener — reverse shell risk', severity: 'high' },
126
+ { 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' },
127
+ { re: /\bkill(?:\s+-9)?\s+-1\b/i, reason: 'kill -1 kills all processes — system-wide kill', severity: 'critical' },
128
+ { re: /\bpkill\s+-9\b/i, reason: 'pkill -9 force kills processes — destructive', severity: 'high' },
129
+ { re: /\biotop\s+--only\b/i, reason: 'iotop in batch mode can cause system instability', severity: 'low' },
130
+ // Anti-evasion: base64 pipe to shell
131
+ { re: /\|\s*(?:base64|b64)\s+-d\s*\|/i, reason: 'base64 decode piped to shell — obfuscated command execution', severity: 'critical' },
132
+ { re: /\|\s*(?:sh|bash|zsh|python|python3|node|perl|ruby)\b/i, reason: 'piping to interpreter — potential remote code execution', severity: 'high' },
133
+ ];
134
+
135
+ const SECRET_PATTERNS = [
136
+ { re: /\bsk-proj-[A-Za-z0-9_-]{20,}\b/i, type: 'OpenAI API key' },
137
+ { re: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/i, type: 'Anthropic API key' },
138
+ { re: /\bsk_live_[A-Za-z0-9]{16,}\b/i, type: 'Stripe secret key' },
139
+ { re: /\bAKIA[A-Z0-9]{16}\b/, type: 'AWS access key' },
140
+ { re: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/i, type: 'GitHub token' },
141
+ { re: /\bglpat-[A-Za-z0-9_-]{20,}\b/i, type: 'GitLab token' },
142
+ { re: /\bxox[bpoa]-[A-Za-z0-9-]{10,}\b/i, type: 'Slack token' },
143
+ { re: /-----BEGIN\s+(?:RSA\s+|EC\s+)?PRIVATE\s+KEY-----/i, type: 'Private key' },
144
+ ];
145
+
146
+ const SENSITIVE_PATHS = [
147
+ /\.env\b/i,
148
+ /\.ssh\b/i,
149
+ /\.aws\b/i,
150
+ /\.gnupg\b/i,
151
+ /\.npmrc\b/i,
152
+ /\.gitconfig\b/i,
153
+ /\/etc\/passwd/i,
154
+ /\/etc\/shadow/i,
155
+ /\/etc\/sudoers/i,
156
+ /\/etc\/ssh\//i,
157
+ /~\/\.ssh\//i,
158
+ ];
159
+
160
+ const EXFIL_PATTERNS = [
161
+ { re: /\b(?:curl|wget|nc|netcat)\b.*(?:\bapi\.|webhook|callback|exfil|upload|send)/i, reason: 'Potential data exfiltration via network tool to external endpoint' },
162
+ { re: /\b(?:curl|wget)\b.*-d\s.*(?:token|key|password|secret|credential)/i, reason: 'Sending secrets via curl/wget POST data' },
163
+ { re: /\b(?:curl|wget)\b.*--data\b.*(?:token|key|password|secret|credential)/i, reason: 'Sending secrets via curl/wget --data' },
164
+ { 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' },
165
+ { re: /\b(?:curl|wget)\b.*-F\s.*(?:token|key|password|secret)/i, reason: 'Sending secrets via curl/wget multipart form' },
166
+ ];
167
+
168
+ // ─── Main check function ──────────────────────────────────────────────────
169
+
170
+ function checkCommand(cmd) {
171
+ if (!cmd || typeof cmd !== 'string') return { blocked: false, allowed: true };
172
+ const trimmed = cmd.trim();
173
+
174
+ // Skip empty lines and comments
175
+ if (!trimmed || trimmed.startsWith('#')) return { blocked: false, allowed: true };
176
+
177
+ // Normalize for anti-evasion
178
+ const normalized = normalizeCommand(trimmed);
179
+
180
+ // Check BOTH the raw command AND the normalized version
181
+ const inputs = [trimmed, normalized];
182
+ const violations = [];
183
+ const seen = new Set(); // dedupe violations across raw + normalized
184
+
185
+ for (const input of inputs) {
186
+ // 1. Dangerous commands
187
+ for (const { re, reason, severity } of DANGEROUS_COMMANDS) {
188
+ if (re.test(input)) {
189
+ const key = reason;
190
+ if (!seen.has(key)) {
191
+ seen.add(key);
192
+ violations.push({ type: 'dangerous_command', reason, severity, pattern: re.source });
193
+ }
194
+ }
195
+ }
196
+
197
+ // 2. Secret exfiltration
198
+ for (const { re, reason } of EXFIL_PATTERNS) {
199
+ if (re.test(input)) {
200
+ const key = reason;
201
+ if (!seen.has(key)) {
202
+ seen.add(key);
203
+ violations.push({ type: 'exfiltration', reason, severity: 'high', pattern: re.source });
204
+ }
205
+ }
206
+ }
207
+
208
+ // 3. Secrets in command
209
+ for (const { re, type } of SECRET_PATTERNS) {
210
+ if (re.test(input)) {
211
+ const key = type;
212
+ if (!seen.has(key)) {
213
+ seen.add(key);
214
+ violations.push({ type: 'secret_exposure', reason: `Secret detected in command: ${type}`, severity: 'critical', pattern: re.source });
215
+ }
216
+ }
217
+ }
218
+
219
+ // 4. Sensitive file access
220
+ for (const re of SENSITIVE_PATHS) {
221
+ if (re.test(input)) {
222
+ const match = input.match(re)[0];
223
+ const key = 'path:' + match;
224
+ if (!seen.has(key)) {
225
+ seen.add(key);
226
+ violations.push({ type: 'sensitive_path', reason: `Access to sensitive path: ${match}`, severity: 'high', pattern: re.source });
227
+ }
228
+ }
229
+ }
230
+ }
231
+
232
+ // 5. Prompt injection in shell (e.g., agent putting LLM output into eval)
233
+ for (const input of inputs) {
234
+ if (/\beval\s+["'].*(?:ignore|disregard|forget|system prompt)/i.test(input)) {
235
+ violations.push({ type: 'prompt_injection', reason: 'eval with prompt injection pattern — agent may be compromised', severity: 'critical' });
236
+ break;
237
+ }
238
+ }
239
+
240
+ // 6. Obfuscation detection — flag suspicious patterns even if we can't decode them
241
+ if (/[a-zA-Z]\[([0-9a-f]{1,2})\]/i.test(trimmed)) {
242
+ violations.push({ type: 'obfuscation', reason: 'Bash escape sequence $\'\\xNN\' detected — possible command obfuscation', severity: 'high' });
243
+ }
244
+ if (trimmed.includes('eval ') && trimmed.includes('$((')) {
245
+ violations.push({ type: 'obfuscation', reason: 'eval with arithmetic expansion — possible obfuscation', severity: 'high' });
246
+ }
247
+
248
+ if (violations.length === 0) return { blocked: false, allowed: true };
249
+
250
+ return {
251
+ blocked: true,
252
+ allowed: false,
253
+ violations,
254
+ reason: violations[0].reason,
255
+ severity: violations[0].severity,
256
+ command: trimmed.slice(0, 200),
257
+ normalized: normalized !== trimmed ? normalized.slice(0, 200) : undefined,
258
+ };
259
+ }
260
+
261
+ // ─── Batch check (for scripts) ─────────────────────────────────────────────
262
+
263
+ function checkScript(content) {
264
+ if (!content || typeof content !== 'string') return { blocked: false, findings: [] };
265
+ const lines = content.split(/\r?\n/);
266
+ const findings = [];
267
+ for (let i = 0; i < lines.length; i++) {
268
+ const result = checkCommand(lines[i]);
269
+ if (result.blocked) {
270
+ findings.push({ line: i + 1, ...result });
271
+ }
272
+ }
273
+ return { blocked: findings.length > 0, findings };
274
+ }
275
+
276
+ module.exports = { checkCommand, checkScript, normalizeCommand, DANGEROUS_COMMANDS, SECRET_PATTERNS, SENSITIVE_PATHS, EXFIL_PATTERNS };
@@ -0,0 +1,135 @@
1
+ # VibeGuard preexec hook for PowerShell.
2
+ # Installed by `vibeguard auto` or `vibeguard install-shell-hook`.
3
+ # Scans every command BEFORE it runs. Blocks dangerous commands.
4
+ #
5
+ # POLICY: default-allow. Only block when checkCommand returns blocked=true.
6
+ # If VibeGuard cannot load (missing module, node error), ALLOW the command.
7
+
8
+ function Invoke-VibeGuardCheck {
9
+ param([string]$Command)
10
+
11
+ # Override bypass
12
+ if ($env:VG_OVERRIDE -eq "1") { return $true }
13
+ if (-not $Command -or $Command.Trim() -eq "") { return $true }
14
+
15
+ # Find shell-guard.js — try multiple paths
16
+ $vgPaths = @()
17
+ if ($VG_SCRIPT_DIR) { $vgPaths += Join-Path $VG_SCRIPT_DIR "shell-guard.js" }
18
+ try { $vgPaths += Join-Path (npm root -g 2>$null) "@yagyeshvyas\vibeguard\src\shell-guard.js" } catch {}
19
+ $vgPaths += Join-Path $PSScriptRoot "shell-guard.js"
20
+ $vgPaths += Join-Path $env:APPDATA "npm\node_modules\@yagyeshvyas\vibeguard\src\shell-guard.js"
21
+
22
+ $vgGuard = $null
23
+ foreach ($p in $vgPaths) {
24
+ if ($p -and (Test-Path $p)) { $vgGuard = $p; break }
25
+ }
26
+
27
+ # FAIL OPEN: if we can't find shell-guard.js, allow the command
28
+ if (-not $vgGuard) { return $true }
29
+
30
+ try {
31
+ $output = node -e "
32
+ try {
33
+ const { checkCommand } = require('$vgGuard');
34
+ const r = checkCommand(process.argv[1]);
35
+ if (r.blocked) {
36
+ process.stdout.write(JSON.stringify(r));
37
+ process.exit(1);
38
+ }
39
+ } catch(e) {
40
+ process.exit(0);
41
+ }
42
+ " $Command 2>$null
43
+
44
+ if ($LASTEXITCODE -eq 1 -and $output) {
45
+ $info = $output | ConvertFrom-Json
46
+ Write-Host ""
47
+ Write-Host " [VibeGuard] BLOCKED: $($Command.Substring(0, [Math]::Min(100, $Command.Length)))" -ForegroundColor Red
48
+ Write-Host " Reason: $($info.reason)" -ForegroundColor Red
49
+ Write-Host " Severity: $($info.severity)" -ForegroundColor Red
50
+ Write-Host ""
51
+ Write-Host " Override: `$env:VG_OVERRIDE=1" -ForegroundColor Yellow
52
+ Write-Host ""
53
+ return $false
54
+ }
55
+ } catch {
56
+ # FAIL OPEN: any error means allow
57
+ }
58
+ return $true
59
+ }
60
+
61
+ # Use PSReadLine to intercept Enter key
62
+ if (Get-Module -ListAvailable -Name PSReadLine) {
63
+ Set-PSReadLineKeyHandler -Key Enter -ScriptBlock {
64
+ param($key, $arg)
65
+
66
+ $line = $null
67
+ $cursor = $null
68
+ [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
69
+
70
+ if (-not $line -or $line.Trim() -eq "") {
71
+ [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
72
+ return
73
+ }
74
+
75
+ # Override bypass
76
+ if ($env:VG_OVERRIDE -eq "1") {
77
+ [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
78
+ return
79
+ }
80
+
81
+ # Find shell-guard.js
82
+ $vgPaths = @()
83
+ if ($VG_SCRIPT_DIR) { $vgPaths += Join-Path $VG_SCRIPT_DIR "shell-guard.js" }
84
+ try { $vgPaths += Join-Path (npm root -g 2>$null) "@yagyeshvyas\vibeguard\src\shell-guard.js" } catch {}
85
+ $vgPaths += Join-Path $PSScriptRoot "shell-guard.js"
86
+ $vgPaths += Join-Path $env:APPDATA "npm\node_modules\@yagyeshvyas\vibeguard\src\shell-guard.js"
87
+
88
+ $vgGuard = $null
89
+ foreach ($p in $vgPaths) {
90
+ if ($p -and (Test-Path $p)) { $vgGuard = $p; break }
91
+ }
92
+
93
+ # FAIL OPEN: if we can't find it, allow
94
+ if (-not $vgGuard) {
95
+ [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
96
+ return
97
+ }
98
+
99
+ $blocked = $false
100
+ try {
101
+ $output = node -e "
102
+ try {
103
+ const { checkCommand } = require('$vgGuard');
104
+ const r = checkCommand(process.argv[1]);
105
+ if (r.blocked) {
106
+ process.stdout.write(JSON.stringify(r));
107
+ process.exit(1);
108
+ }
109
+ } catch(e) {
110
+ process.exit(0);
111
+ }
112
+ " $line 2>$null
113
+
114
+ if ($LASTEXITCODE -eq 1 -and $output) {
115
+ $blocked = $true
116
+ $info = $output | ConvertFrom-Json
117
+ Write-Host ""
118
+ Write-Host " [VibeGuard] BLOCKED: $($line.Substring(0, [Math]::Min(100, $line.Length)))" -ForegroundColor Red
119
+ Write-Host " Reason: $($info.reason)" -ForegroundColor Red
120
+ Write-Host " Severity: $($info.severity)" -ForegroundColor Red
121
+ Write-Host ""
122
+ Write-Host " Override: `$env:VG_OVERRIDE=1" -ForegroundColor Yellow
123
+ Write-Host ""
124
+ [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
125
+ return
126
+ }
127
+ } catch {
128
+ # FAIL OPEN
129
+ }
130
+
131
+ if (-not $blocked) {
132
+ [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
133
+ }
134
+ }
135
+ }
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env bash
2
+ # VibeGuard preexec hook for bash/zsh.
3
+ # Installed by `vibeguard auto` or `vibeguard install-shell-hook`.
4
+ # Scans every command BEFORE it runs. Blocks dangerous commands.
5
+ #
6
+ # POLICY: default-allow. Only block when checkCommand returns blocked=true.
7
+ # If VibeGuard cannot load (missing module, node error), ALLOW the command.
8
+ # A guard that bricks the terminal is worse than no guard.
9
+
10
+ __vibeguard_check() {
11
+ local cmd="$1"
12
+
13
+ # Override bypass
14
+ if [ -n "$VG_OVERRIDE" ]; then return 0; fi
15
+
16
+ # Find shell-guard.js — try multiple paths
17
+ local vg_guard=""
18
+ for p in \
19
+ "$VG_SCRIPT_DIR/shell-guard.js" \
20
+ "$(npm root -g 2>/dev/null)/vibeguard/src/shell-guard.js" \
21
+ "$(dirname "$(readlink -f "$BASH_SOURCE" 2>/dev/null || echo "$0")")/shell-guard.js" \
22
+ "$HOME/.npm-global/lib/node_modules/vibeguard/src/shell-guard.js" \
23
+ "/usr/local/lib/node_modules/vibeguard/src/shell-guard.js" \
24
+ "/usr/lib/node_modules/vibeguard/src/shell-guard.js"; do
25
+ if [ -f "$p" ]; then vg_guard="$p"; break; fi
26
+ done
27
+
28
+ # FAIL OPEN: if we can't find shell-guard.js, allow the command
29
+ if [ -z "$vg_guard" ]; then return 0; fi
30
+
31
+ # Run checkCommand — only block on explicit blocked=true
32
+ local output
33
+ output=$(node -e "
34
+ try {
35
+ const { checkCommand } = require('$vg_guard');
36
+ const r = checkCommand(process.argv[1]);
37
+ if (r.blocked) {
38
+ process.stdout.write(JSON.stringify(r));
39
+ process.exit(1);
40
+ }
41
+ } catch(e) {
42
+ // FAIL OPEN: any error means allow
43
+ process.exit(0);
44
+ }
45
+ " "$cmd" 2>/dev/null)
46
+
47
+ local exitcode=$?
48
+
49
+ # Exit 0 = allowed, exit 1 = blocked (with JSON on stdout)
50
+ if [ $exitcode -eq 1 ] && [ -n "$output" ]; then
51
+ echo ""
52
+ echo -e " \033[31m[VibeGuard] BLOCKED:\033[0m \033[1m${cmd:0:100}\033[0m"
53
+ echo "$output" | node -e "
54
+ try {
55
+ const d = JSON.parse(require('fs').readFileSync(0,'utf8'));
56
+ console.log(' \033[31mReason:\033[0m ' + (d.reason || 'unknown'));
57
+ console.log(' \033[31mSeverity:\033[0m ' + (d.severity || 'unknown'));
58
+ } catch(e) {
59
+ console.log(' \033[31mReason:\033[0m blocked by VibeGuard');
60
+ }
61
+ " 2>/dev/null
62
+ echo ""
63
+ echo -e " \033[33mOverride:\033[0m VG_OVERRIDE=1 <command>"
64
+ echo ""
65
+ return 1
66
+ fi
67
+
68
+ # Exit 0 or empty output = allowed (fail open)
69
+ return 0
70
+ }
71
+
72
+ # bash: use DEBUG trap
73
+ if [ -n "$BASH_VERSION" ]; then
74
+ __vibeguard_preexec() {
75
+ if ! __vibeguard_check "$BASH_COMMAND"; then
76
+ return 1
77
+ fi
78
+ }
79
+ trap '__vibeguard_preexec' DEBUG
80
+ fi
81
+
82
+ # zsh: use preexec hook
83
+ if [ -n "$ZSH_VERSION" ]; then
84
+ __vibeguard_zsh_preexec() {
85
+ if ! __vibeguard_check "$1"; then
86
+ return 1
87
+ fi
88
+ }
89
+ preexec_functions+=(__vibeguard_zsh_preexec)
90
+ fi