@yagyeshvyas/vibeguard 0.1.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,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
package/src/suppress.js CHANGED
@@ -1,14 +1,17 @@
1
1
  'use strict';
2
2
 
3
3
  /*
4
- * Context-aware false positive suppression.
4
+ * Context-aware false positive suppression + inline suppression comments.
5
5
  *
6
- * Scans nearby lines for "safe context" patterns that indicate a finding
7
- * is a false positive. For example:
8
- * - eval() inside a test file (test.js) → suppress
9
- * - secret that looks like a placeholder/example → suppress
10
- * - HTTP URL in a comment → suppress
11
- * - Variable named "testKey" or "mockToken" → suppress
6
+ * Inline suppression syntax (two forms):
7
+ * // vibeguard-ignore-line [rule1, rule2] -> suppress on this line
8
+ * // vibeguard-ignore-next-line [rule1, ...] -> suppress on the next line
9
+ * // vibeguard-ignore[ruleId]: reason -> suppress ruleId on this line
10
+ * // vibeguard-ignore-next[ruleId]: reason -> suppress ruleId on the next line
11
+ * No rule list = suppress everything on the target line. Works with //, #, /* *.
12
+ *
13
+ * Suppressed findings are dropped from output but counted as `suppressedCount`
14
+ * on the scan result (see scanner.js). --show-suppressed re-adds them.
12
15
  *
13
16
  * This runs AFTER rule matching, BEFORE findings are returned.
14
17
  */
@@ -86,4 +89,71 @@ function suppressFindings(findings, content, relPath) {
86
89
  });
87
90
  }
88
91
 
89
- module.exports = { suppressFindings, isPlaceholder, isTestFile, isDocsFile, hasSafeContext };
92
+ // Parse inline suppression comments from file lines.
93
+ // Returns a Map: targetLine(1-based) -> Set(ruleIds) | '*'
94
+ // Also returns the raw suppressed entries for --show-suppressed.
95
+ //
96
+ // Supports both forms:
97
+ // // vibeguard-ignore-line [rule1, rule2]
98
+ // // vibeguard-ignore-next-line [rule1, ...]
99
+ // // vibeguard-ignore[ruleId]: reason
100
+ // // vibeguard-ignore-next[ruleId]: reason
101
+ function buildIgnoreMap(lines) {
102
+ const map = new Map(); // targetLine(1-based) -> Set(ruleIds) | '*'
103
+ // Old syntax: vibeguard-ignore(-next)?-line [rules]
104
+ const reOld = /(?:\/\/|#|\/\*|\*)\s*vibeguard-ignore(-next)?-line\b([^*\n]*)/i;
105
+ // New syntax: vibeguard-ignore[ruleId]: reason (or vibeguard-ignore-next[ruleId]: reason)
106
+ // Must NOT match vibeguard-ignore-line or vibeguard-ignore-next-line (old syntax).
107
+ const reNew = /(?:\/\/|#|\/\*|\*)\s*vibeguard-ignore(?:-(next))?(?!\s*-line)\[([^\]]+)\]\s*:?\s*(.*)/i;
108
+
109
+ for (let i = 0; i < lines.length; i++) {
110
+ // Check new syntax first (more specific).
111
+ const mNew = reNew.exec(lines[i]);
112
+ if (mNew) {
113
+ const target = mNew[1] === 'next' ? i + 2 : i + 1;
114
+ const ruleId = mNew[2].trim();
115
+ const existing = map.get(target);
116
+ if (existing === '*') continue;
117
+ if (ruleId === '*') { map.set(target, '*'); continue; }
118
+ map.set(target, new Set([...(existing || []), ruleId]));
119
+ continue;
120
+ }
121
+ // Check old syntax.
122
+ const mOld = reOld.exec(lines[i]);
123
+ if (mOld) {
124
+ const target = mOld[1] ? i + 2 : i + 1;
125
+ const rulesPart = (mOld[2] || '').replace(/\*\/.*/, '').trim();
126
+ // Strip surrounding brackets if present: [rule1, rule2] -> rule1, rule2
127
+ const cleaned = rulesPart.replace(/^\[|\]$/g, '').trim();
128
+ const rules = cleaned ? cleaned.split(/[\s,]+/).filter(Boolean) : '*';
129
+ const existing = map.get(target);
130
+ if (existing === '*' || rules === '*') { map.set(target, '*'); continue; }
131
+ map.set(target, new Set([...(existing || []), ...rules]));
132
+ }
133
+ }
134
+ return map;
135
+ }
136
+
137
+ // Apply inline suppressions to findings. Returns { kept, suppressed }.
138
+ // `suppressed` findings are annotated with `suppressed: true` and `suppressionReason`.
139
+ function applyInlineSuppressionsWithCount(findings, contents) {
140
+ const byFile = new Map();
141
+ for (const c of contents) byFile.set(c.rel, buildIgnoreMap(c.lines));
142
+ const kept = [];
143
+ const suppressed = [];
144
+ for (const f of findings) {
145
+ const map = byFile.get(f.file);
146
+ if (!map) { kept.push(f); continue; }
147
+ const entry = map.get(f.line);
148
+ if (!entry) { kept.push(f); continue; }
149
+ const isSuppressed = entry === '*' || entry.has(f.ruleId);
150
+ if (isSuppressed) {
151
+ suppressed.push({ ...f, suppressed: true });
152
+ } else {
153
+ kept.push(f);
154
+ }
155
+ }
156
+ return { kept, suppressed };
157
+ }
158
+
159
+ module.exports = { suppressFindings, isPlaceholder, isTestFile, isDocsFile, hasSafeContext, buildIgnoreMap, applyInlineSuppressionsWithCount };