@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
package/src/daemon.js CHANGED
@@ -1,344 +1,344 @@
1
- 'use strict';
2
-
3
- /*
4
- * src/daemon.js — VibeGuard background daemon.
5
- *
6
- * Runs as a persistent process. Watches the working directory for file changes,
7
- * auto-scans modified files in real-time, and blocks dangerous writes before
8
- * they hit disk.
9
- *
10
- * The daemon provides three protections simultaneously:
11
- * 1. File watcher: scans every file write (using fs.watch) in real-time
12
- * 2. Process spawner guard: wraps child_process to intercept spawned commands
13
- * 3. HTTP interceptor: wraps outbound requests from the daemon process
14
- *
15
- * Usage:
16
- * vibeguard auto-start [dir] Start daemon in background
17
- * vibeguard auto-stop [dir] Stop daemon
18
- * vibeguard auto-status [dir] Check if daemon is running
19
- *
20
- * The daemon writes a PID file to .vibeguard-daemon.json and logs to
21
- * .vibeguard-daemon.log in the working directory.
22
- *
23
- * 100% local. Zero network. Zero dependencies.
24
- */
25
-
26
- const fs = require('fs');
27
- const path = require('path');
28
- const os = require('os');
29
- const { spawn, execSync } = require('child_process');
30
-
31
- const DAEMON_FILE = '.vibeguard-daemon.json';
32
- const DAEMON_LOG = '.vibeguard-daemon.log';
33
- const PID_CHECK_INTERVAL = 5000; // check if process alive every 5s
34
-
35
- // ─── Daemon process ────────────────────────────────────────────────────────
36
-
37
- function runDaemon(rootDir, opts) {
38
- opts = opts || {};
39
- const logPath = path.join(rootDir, DAEMON_LOG);
40
- const logStream = fs.createWriteStream(logPath, { flags: 'a' });
41
-
42
- function log(msg) {
43
- const ts = new Date().toISOString();
44
- const line = `[${ts}] ${msg}\n`;
45
- logStream.write(line);
46
- if (opts.verbose) process.stderr.write(`[VibeGuard Daemon] ${msg}\n`);
47
- }
48
-
49
- log('daemon started');
50
- log(`watching: ${rootDir}`);
51
-
52
- // Write PID file
53
- const pidData = {
54
- pid: process.pid,
55
- root: rootDir,
56
- startedAt: new Date().toISOString(),
57
- findings: 0,
58
- blocked: 0,
59
- watched: 0,
60
- };
61
- fs.writeFileSync(path.join(rootDir, DAEMON_FILE), JSON.stringify(pidData, null, 2));
62
-
63
- // Activate interceptor (wraps exec, fetch, fs, http in THIS process)
64
- try {
65
- require('./interceptor').activate({ throwOnBlock: false, logBlocked: true });
66
- log('interceptor activated');
67
- } catch (e) {
68
- log(`interceptor failed: ${e.message}`);
69
- }
70
-
71
- // Activate guard (wraps execSync, spawn)
72
- try {
73
- require('./guard');
74
- log('guard activated');
75
- } catch (e) {
76
- log(`guard failed: ${e.message}`);
77
- }
78
-
79
- // File watcher — scan files on change
80
- let scanQueue = [];
81
- let scanTimer = null;
82
- const { scanFileContent } = require('./scanner');
83
-
84
- function scheduleScan(filePath) {
85
- // Only scan code files
86
- const ext = path.extname(filePath).toLowerCase();
87
- const codeExts = new Set(['.js', '.ts', '.jsx', '.tsx', '.py', '.go', '.rb', '.java', '.kt', '.swift', '.cs', '.rs', '.php', '.sql', '.sh', '.yml', '.yaml', '.json', '.env']);
88
- if (!codeExts.has(ext) && !filePath.endsWith('.env') && !filePath.includes('.env')) return;
89
-
90
- scanQueue.push(filePath);
91
- if (scanTimer) clearTimeout(scanTimer);
92
- scanTimer = setTimeout(() => {
93
- const files = [...new Set(scanQueue)];
94
- scanQueue = [];
95
- for (const f of files) {
96
- try {
97
- const content = fs.readFileSync(f, 'utf8');
98
- const relPath = path.relative(rootDir, f);
99
- const findings = scanFileContent(f, relPath, content, null);
100
- const critical = findings.filter((x) => x.severity === 'critical');
101
-
102
- if (critical.length > 0) {
103
- pidData.findings += findings.length;
104
- for (const finding of critical) {
105
- pidData.blocked++;
106
- log(`BLOCKED [critical] ${finding.ruleId}: ${finding.file}:${finding.line} — ${finding.message}`);
107
- const color = '\x1b[31m';
108
- process.stderr.write(`${color}[VibeGuard] BLOCKED [critical] ${finding.ruleId}: ${finding.file}:${finding.line}\x1b[0m\n`);
109
- process.stderr.write(`${color} ${finding.message}\x1b[0m\n`);
110
- process.stderr.write(`${color} Fix: ${finding.fix || 'Review this finding.'}\x1b[0m\n\n`);
111
- }
112
-
113
- // Auto-revert: restore from git if file is tracked, otherwise warn
114
- if (critical.length > 0 && !opts.noRevert) {
115
- try {
116
- const { execSync } = require('child_process');
117
- const gitResult = execSync(`git show HEAD:"${relPath}" 2>NUL`, {
118
- cwd: rootDir,
119
- encoding: 'utf8',
120
- stdio: 'pipe',
121
- timeout: 2000,
122
- });
123
- if (gitResult) {
124
- fs.writeFileSync(f, gitResult);
125
- process.stderr.write(`\x1b[31m[VibeGuard] REVERTED: ${relPath} restored from git HEAD\x1b[0m\n\n`);
126
- }
127
- } catch {
128
- // Not in git — can't revert, just warn
129
- process.stderr.write(`\x1b[33m[VibeGuard] WARNING: ${relPath} has critical findings but is not in git — cannot auto-revert\x1b[0m\n\n`);
130
- }
131
- }
132
- } else if (findings.length > 0) {
133
- // High/medium findings — alert but don't revert
134
- const high = findings.filter((x) => x.severity === 'high');
135
- if (high.length > 0) {
136
- pidData.findings += findings.length;
137
- for (const finding of high) {
138
- log(`ALERT [high] ${finding.ruleId}: ${finding.file}:${finding.line} — ${finding.message}`);
139
- process.stderr.write(`\x1b[33m[VibeGuard] ALERT [high] ${finding.ruleId}: ${finding.file}:${finding.line}\x1b[0m\n`);
140
- process.stderr.write(`\x1b[33m ${finding.message}\x1b[0m\n\n`);
141
- }
142
- }
143
- }
144
- // Update PID file
145
- fs.writeFileSync(path.join(rootDir, DAEMON_FILE), JSON.stringify(pidData, null, 2));
146
- } catch (e) {
147
- // File might be deleted or locked — skip
148
- }
149
- }
150
- }, 300); // debounce 300ms
151
- }
152
-
153
- // Watch the directory tree
154
- let watcher;
155
- try {
156
- watcher = fs.watch(rootDir, { recursive: true }, (eventType, filename) => {
157
- if (!filename) return;
158
- const fullPath = path.join(rootDir, filename);
159
- if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
160
- pidData.watched++;
161
- scheduleScan(fullPath);
162
- }
163
- });
164
- log('file watcher active');
165
- } catch (e) {
166
- log(`file watcher failed: ${e.message} — trying manual polling`);
167
- // Fallback: poll every 2 seconds
168
- const knownFiles = new Map();
169
- setInterval(() => {
170
- function walkDir(dir) {
171
- try {
172
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
173
- if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
174
- const fullPath = path.join(dir, entry.name);
175
- if (entry.isFile()) {
176
- try {
177
- const mtime = fs.statSync(fullPath).mtimeMs;
178
- const prev = knownFiles.get(fullPath);
179
- if (!prev || prev !== mtime) {
180
- knownFiles.set(fullPath, mtime);
181
- if (prev) scheduleScan(fullPath); // only scan changed files
182
- }
183
- } catch {}
184
- } else if (entry.isDirectory()) {
185
- walkDir(fullPath);
186
- }
187
- }
188
- } catch {}
189
- }
190
- walkDir(rootDir);
191
- }, 2000);
192
- log('polling fallback active (2s interval)');
193
- }
194
-
195
- // Keep process alive
196
- process.on('SIGTERM', () => {
197
- log('daemon stopping (SIGTERM)');
198
- if (watcher) watcher.close();
199
- try { fs.unlinkSync(path.join(rootDir, DAEMON_FILE)); } catch {}
200
- process.exit(0);
201
- });
202
-
203
- process.on('SIGINT', () => {
204
- log('daemon stopping (SIGINT)');
205
- if (watcher) watcher.close();
206
- try { fs.unlinkSync(path.join(rootDir, DAEMON_FILE)); } catch {}
207
- process.exit(0);
208
- });
209
-
210
- // Heartbeat — update PID file every 30s to prove we're alive
211
- setInterval(() => {
212
- pidData.heartbeat = new Date().toISOString();
213
- try {
214
- fs.writeFileSync(path.join(rootDir, DAEMON_FILE), JSON.stringify(pidData, null, 2));
215
- } catch {}
216
- }, 30000);
217
- }
218
-
219
- // ─── Daemon management ────────────────────────────────────────────────────
220
-
221
- function startDaemon(rootDir, opts) {
222
- opts = opts || {};
223
- const pidFile = path.join(rootDir, DAEMON_FILE);
224
-
225
- // Check if already running
226
- if (isDaemonRunning(rootDir)) {
227
- return { started: false, reason: 'daemon already running', pidFile };
228
- }
229
-
230
- // Spawn daemon as detached background process
231
- const nodeBin = process.execPath;
232
- const daemonScript = path.join(__dirname, 'daemon-run.js');
233
- const logPath = path.join(rootDir, DAEMON_LOG);
234
-
235
- const args = [daemonScript, rootDir];
236
- if (opts.verbose) args.push('--verbose');
237
-
238
- const logStream = fs.openSync(logPath, 'a');
239
-
240
- const child = spawn(nodeBin, args, {
241
- detached: true,
242
- stdio: ['ignore', logStream, logStream],
243
- cwd: rootDir,
244
- windowsHide: true,
245
- });
246
-
247
- child.unref();
248
- try { fs.closeSync(logStream); } catch {}
249
-
250
- // Wait a moment for PID file to appear
251
- return new Promise((resolve) => {
252
- setTimeout(() => {
253
- if (fs.existsSync(pidFile)) {
254
- const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
255
- resolve({ started: true, pid: data.pid, root: rootDir, logFile: logPath });
256
- } else {
257
- resolve({ started: false, reason: 'daemon failed to start — check log', logFile: logPath });
258
- }
259
- }, 1000);
260
- });
261
- }
262
-
263
- function stopDaemon(rootDir) {
264
- const pidFile = path.join(rootDir, DAEMON_FILE);
265
- if (!fs.existsSync(pidFile)) {
266
- return { stopped: false, reason: 'no daemon running' };
267
- }
268
-
269
- try {
270
- const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
271
- const pid = data.pid;
272
- if (pid) {
273
- try {
274
- process.kill(pid, 'SIGTERM');
275
- } catch (e) {
276
- // Process might already be dead
277
- }
278
- }
279
- // Wait for PID file to be removed
280
- return new Promise((resolve) => {
281
- let tries = 0;
282
- const interval = setInterval(() => {
283
- if (!fs.existsSync(pidFile) || tries > 10) {
284
- clearInterval(interval);
285
- try { fs.unlinkSync(pidFile); } catch {}
286
- resolve({ stopped: true, pid });
287
- }
288
- tries++;
289
- }, 200);
290
- });
291
- } catch (e) {
292
- try { fs.unlinkSync(pidFile); } catch {}
293
- return { stopped: false, reason: e.message };
294
- }
295
- }
296
-
297
- function isDaemonRunning(rootDir) {
298
- const pidFile = path.join(rootDir, DAEMON_FILE);
299
- if (!fs.existsSync(pidFile)) return false;
300
- try {
301
- const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
302
- const pid = data.pid;
303
- if (!pid) return false;
304
- // Check if process is alive
305
- try {
306
- process.kill(pid, 0);
307
- return true;
308
- } catch (e) {
309
- // Process is dead — clean up stale PID file
310
- try { fs.unlinkSync(pidFile); } catch {}
311
- return false;
312
- }
313
- } catch {
314
- try { fs.unlinkSync(pidFile); } catch {}
315
- return false;
316
- }
317
- }
318
-
319
- function getDaemonStatus(rootDir) {
320
- const pidFile = path.join(rootDir, DAEMON_FILE);
321
- const logPath = path.join(rootDir, DAEMON_LOG);
322
- if (!fs.existsSync(pidFile)) {
323
- return { running: false };
324
- }
325
- try {
326
- const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
327
- const running = isDaemonRunning(rootDir);
328
- return {
329
- running,
330
- pid: data.pid,
331
- root: data.root,
332
- startedAt: data.startedAt,
333
- findings: data.findings || 0,
334
- blocked: data.blocked || 0,
335
- watched: data.watched || 0,
336
- heartbeat: data.heartbeat,
337
- logFile: logPath,
338
- };
339
- } catch {
340
- return { running: false };
341
- }
342
- }
343
-
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/daemon.js — VibeGuard background daemon.
5
+ *
6
+ * Runs as a persistent process. Watches the working directory for file changes,
7
+ * auto-scans modified files in real-time, and blocks dangerous writes before
8
+ * they hit disk.
9
+ *
10
+ * The daemon provides three protections simultaneously:
11
+ * 1. File watcher: scans every file write (using fs.watch) in real-time
12
+ * 2. Process spawner guard: wraps child_process to intercept spawned commands
13
+ * 3. HTTP interceptor: wraps outbound requests from the daemon process
14
+ *
15
+ * Usage:
16
+ * vibeguard auto-start [dir] Start daemon in background
17
+ * vibeguard auto-stop [dir] Stop daemon
18
+ * vibeguard auto-status [dir] Check if daemon is running
19
+ *
20
+ * The daemon writes a PID file to .vibeguard-daemon.json and logs to
21
+ * .vibeguard-daemon.log in the working directory.
22
+ *
23
+ * 100% local. Zero network. Zero dependencies.
24
+ */
25
+
26
+ const fs = require('fs');
27
+ const path = require('path');
28
+ const os = require('os');
29
+ const { spawn, execSync } = require('child_process');
30
+
31
+ const DAEMON_FILE = '.vibeguard-daemon.json';
32
+ const DAEMON_LOG = '.vibeguard-daemon.log';
33
+ const PID_CHECK_INTERVAL = 5000; // check if process alive every 5s
34
+
35
+ // ─── Daemon process ────────────────────────────────────────────────────────
36
+
37
+ function runDaemon(rootDir, opts) {
38
+ opts = opts || {};
39
+ const logPath = path.join(rootDir, DAEMON_LOG);
40
+ const logStream = fs.createWriteStream(logPath, { flags: 'a' });
41
+
42
+ function log(msg) {
43
+ const ts = new Date().toISOString();
44
+ const line = `[${ts}] ${msg}\n`;
45
+ logStream.write(line);
46
+ if (opts.verbose) process.stderr.write(`[VibeGuard Daemon] ${msg}\n`);
47
+ }
48
+
49
+ log('daemon started');
50
+ log(`watching: ${rootDir}`);
51
+
52
+ // Write PID file
53
+ const pidData = {
54
+ pid: process.pid,
55
+ root: rootDir,
56
+ startedAt: new Date().toISOString(),
57
+ findings: 0,
58
+ blocked: 0,
59
+ watched: 0,
60
+ };
61
+ fs.writeFileSync(path.join(rootDir, DAEMON_FILE), JSON.stringify(pidData, null, 2));
62
+
63
+ // Activate interceptor (wraps exec, fetch, fs, http in THIS process)
64
+ try {
65
+ require('./interceptor').activate({ throwOnBlock: false, logBlocked: true });
66
+ log('interceptor activated');
67
+ } catch (e) {
68
+ log(`interceptor failed: ${e.message}`);
69
+ }
70
+
71
+ // Activate guard (wraps execSync, spawn)
72
+ try {
73
+ require('./guard');
74
+ log('guard activated');
75
+ } catch (e) {
76
+ log(`guard failed: ${e.message}`);
77
+ }
78
+
79
+ // File watcher — scan files on change
80
+ let scanQueue = [];
81
+ let scanTimer = null;
82
+ const { scanFileContent } = require('./scanner');
83
+
84
+ function scheduleScan(filePath) {
85
+ // Only scan code files
86
+ const ext = path.extname(filePath).toLowerCase();
87
+ const codeExts = new Set(['.js', '.ts', '.jsx', '.tsx', '.py', '.go', '.rb', '.java', '.kt', '.swift', '.cs', '.rs', '.php', '.sql', '.sh', '.yml', '.yaml', '.json', '.env']);
88
+ if (!codeExts.has(ext) && !filePath.endsWith('.env') && !filePath.includes('.env')) return;
89
+
90
+ scanQueue.push(filePath);
91
+ if (scanTimer) clearTimeout(scanTimer);
92
+ scanTimer = setTimeout(() => {
93
+ const files = [...new Set(scanQueue)];
94
+ scanQueue = [];
95
+ for (const f of files) {
96
+ try {
97
+ const content = fs.readFileSync(f, 'utf8');
98
+ const relPath = path.relative(rootDir, f);
99
+ const findings = scanFileContent(f, relPath, content, null);
100
+ const critical = findings.filter((x) => x.severity === 'critical');
101
+
102
+ if (critical.length > 0) {
103
+ pidData.findings += findings.length;
104
+ for (const finding of critical) {
105
+ pidData.blocked++;
106
+ log(`BLOCKED [critical] ${finding.ruleId}: ${finding.file}:${finding.line} — ${finding.message}`);
107
+ const color = '\x1b[31m';
108
+ process.stderr.write(`${color}[VibeGuard] BLOCKED [critical] ${finding.ruleId}: ${finding.file}:${finding.line}\x1b[0m\n`);
109
+ process.stderr.write(`${color} ${finding.message}\x1b[0m\n`);
110
+ process.stderr.write(`${color} Fix: ${finding.fix || 'Review this finding.'}\x1b[0m\n\n`);
111
+ }
112
+
113
+ // Auto-revert: restore from git if file is tracked, otherwise warn
114
+ if (critical.length > 0 && !opts.noRevert) {
115
+ try {
116
+ const { execSync } = require('child_process');
117
+ const gitResult = execSync(`git show HEAD:"${relPath}" 2>NUL`, {
118
+ cwd: rootDir,
119
+ encoding: 'utf8',
120
+ stdio: 'pipe',
121
+ timeout: 2000,
122
+ });
123
+ if (gitResult) {
124
+ fs.writeFileSync(f, gitResult);
125
+ process.stderr.write(`\x1b[31m[VibeGuard] REVERTED: ${relPath} restored from git HEAD\x1b[0m\n\n`);
126
+ }
127
+ } catch {
128
+ // Not in git — can't revert, just warn
129
+ process.stderr.write(`\x1b[33m[VibeGuard] WARNING: ${relPath} has critical findings but is not in git — cannot auto-revert\x1b[0m\n\n`);
130
+ }
131
+ }
132
+ } else if (findings.length > 0) {
133
+ // High/medium findings — alert but don't revert
134
+ const high = findings.filter((x) => x.severity === 'high');
135
+ if (high.length > 0) {
136
+ pidData.findings += findings.length;
137
+ for (const finding of high) {
138
+ log(`ALERT [high] ${finding.ruleId}: ${finding.file}:${finding.line} — ${finding.message}`);
139
+ process.stderr.write(`\x1b[33m[VibeGuard] ALERT [high] ${finding.ruleId}: ${finding.file}:${finding.line}\x1b[0m\n`);
140
+ process.stderr.write(`\x1b[33m ${finding.message}\x1b[0m\n\n`);
141
+ }
142
+ }
143
+ }
144
+ // Update PID file
145
+ fs.writeFileSync(path.join(rootDir, DAEMON_FILE), JSON.stringify(pidData, null, 2));
146
+ } catch (e) {
147
+ // File might be deleted or locked — skip
148
+ }
149
+ }
150
+ }, 300); // debounce 300ms
151
+ }
152
+
153
+ // Watch the directory tree
154
+ let watcher;
155
+ try {
156
+ watcher = fs.watch(rootDir, { recursive: true }, (eventType, filename) => {
157
+ if (!filename) return;
158
+ const fullPath = path.join(rootDir, filename);
159
+ if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
160
+ pidData.watched++;
161
+ scheduleScan(fullPath);
162
+ }
163
+ });
164
+ log('file watcher active');
165
+ } catch (e) {
166
+ log(`file watcher failed: ${e.message} — trying manual polling`);
167
+ // Fallback: poll every 2 seconds
168
+ const knownFiles = new Map();
169
+ setInterval(() => {
170
+ function walkDir(dir) {
171
+ try {
172
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
173
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
174
+ const fullPath = path.join(dir, entry.name);
175
+ if (entry.isFile()) {
176
+ try {
177
+ const mtime = fs.statSync(fullPath).mtimeMs;
178
+ const prev = knownFiles.get(fullPath);
179
+ if (!prev || prev !== mtime) {
180
+ knownFiles.set(fullPath, mtime);
181
+ if (prev) scheduleScan(fullPath); // only scan changed files
182
+ }
183
+ } catch {}
184
+ } else if (entry.isDirectory()) {
185
+ walkDir(fullPath);
186
+ }
187
+ }
188
+ } catch {}
189
+ }
190
+ walkDir(rootDir);
191
+ }, 2000);
192
+ log('polling fallback active (2s interval)');
193
+ }
194
+
195
+ // Keep process alive
196
+ process.on('SIGTERM', () => {
197
+ log('daemon stopping (SIGTERM)');
198
+ if (watcher) watcher.close();
199
+ try { fs.unlinkSync(path.join(rootDir, DAEMON_FILE)); } catch {}
200
+ process.exit(0);
201
+ });
202
+
203
+ process.on('SIGINT', () => {
204
+ log('daemon stopping (SIGINT)');
205
+ if (watcher) watcher.close();
206
+ try { fs.unlinkSync(path.join(rootDir, DAEMON_FILE)); } catch {}
207
+ process.exit(0);
208
+ });
209
+
210
+ // Heartbeat — update PID file every 30s to prove we're alive
211
+ setInterval(() => {
212
+ pidData.heartbeat = new Date().toISOString();
213
+ try {
214
+ fs.writeFileSync(path.join(rootDir, DAEMON_FILE), JSON.stringify(pidData, null, 2));
215
+ } catch {}
216
+ }, 30000);
217
+ }
218
+
219
+ // ─── Daemon management ────────────────────────────────────────────────────
220
+
221
+ function startDaemon(rootDir, opts) {
222
+ opts = opts || {};
223
+ const pidFile = path.join(rootDir, DAEMON_FILE);
224
+
225
+ // Check if already running
226
+ if (isDaemonRunning(rootDir)) {
227
+ return { started: false, reason: 'daemon already running', pidFile };
228
+ }
229
+
230
+ // Spawn daemon as detached background process
231
+ const nodeBin = process.execPath;
232
+ const daemonScript = path.join(__dirname, 'daemon-run.js');
233
+ const logPath = path.join(rootDir, DAEMON_LOG);
234
+
235
+ const args = [daemonScript, rootDir];
236
+ if (opts.verbose) args.push('--verbose');
237
+
238
+ const logStream = fs.openSync(logPath, 'a');
239
+
240
+ const child = spawn(nodeBin, args, {
241
+ detached: true,
242
+ stdio: ['ignore', logStream, logStream],
243
+ cwd: rootDir,
244
+ windowsHide: true,
245
+ });
246
+
247
+ child.unref();
248
+ try { fs.closeSync(logStream); } catch {}
249
+
250
+ // Wait a moment for PID file to appear
251
+ return new Promise((resolve) => {
252
+ setTimeout(() => {
253
+ if (fs.existsSync(pidFile)) {
254
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
255
+ resolve({ started: true, pid: data.pid, root: rootDir, logFile: logPath });
256
+ } else {
257
+ resolve({ started: false, reason: 'daemon failed to start — check log', logFile: logPath });
258
+ }
259
+ }, 1000);
260
+ });
261
+ }
262
+
263
+ function stopDaemon(rootDir) {
264
+ const pidFile = path.join(rootDir, DAEMON_FILE);
265
+ if (!fs.existsSync(pidFile)) {
266
+ return { stopped: false, reason: 'no daemon running' };
267
+ }
268
+
269
+ try {
270
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
271
+ const pid = data.pid;
272
+ if (pid) {
273
+ try {
274
+ process.kill(pid, 'SIGTERM');
275
+ } catch (e) {
276
+ // Process might already be dead
277
+ }
278
+ }
279
+ // Wait for PID file to be removed
280
+ return new Promise((resolve) => {
281
+ let tries = 0;
282
+ const interval = setInterval(() => {
283
+ if (!fs.existsSync(pidFile) || tries > 10) {
284
+ clearInterval(interval);
285
+ try { fs.unlinkSync(pidFile); } catch {}
286
+ resolve({ stopped: true, pid });
287
+ }
288
+ tries++;
289
+ }, 200);
290
+ });
291
+ } catch (e) {
292
+ try { fs.unlinkSync(pidFile); } catch {}
293
+ return { stopped: false, reason: e.message };
294
+ }
295
+ }
296
+
297
+ function isDaemonRunning(rootDir) {
298
+ const pidFile = path.join(rootDir, DAEMON_FILE);
299
+ if (!fs.existsSync(pidFile)) return false;
300
+ try {
301
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
302
+ const pid = data.pid;
303
+ if (!pid) return false;
304
+ // Check if process is alive
305
+ try {
306
+ process.kill(pid, 0);
307
+ return true;
308
+ } catch (e) {
309
+ // Process is dead — clean up stale PID file
310
+ try { fs.unlinkSync(pidFile); } catch {}
311
+ return false;
312
+ }
313
+ } catch {
314
+ try { fs.unlinkSync(pidFile); } catch {}
315
+ return false;
316
+ }
317
+ }
318
+
319
+ function getDaemonStatus(rootDir) {
320
+ const pidFile = path.join(rootDir, DAEMON_FILE);
321
+ const logPath = path.join(rootDir, DAEMON_LOG);
322
+ if (!fs.existsSync(pidFile)) {
323
+ return { running: false };
324
+ }
325
+ try {
326
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
327
+ const running = isDaemonRunning(rootDir);
328
+ return {
329
+ running,
330
+ pid: data.pid,
331
+ root: data.root,
332
+ startedAt: data.startedAt,
333
+ findings: data.findings || 0,
334
+ blocked: data.blocked || 0,
335
+ watched: data.watched || 0,
336
+ heartbeat: data.heartbeat,
337
+ logFile: logPath,
338
+ };
339
+ } catch {
340
+ return { running: false };
341
+ }
342
+ }
343
+
344
344
  module.exports = { runDaemon, startDaemon, stopDaemon, isDaemonRunning, getDaemonStatus, DAEMON_FILE, DAEMON_LOG };