@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.
package/src/crosstaint.js CHANGED
@@ -9,7 +9,10 @@
9
9
  * - local variable reassignment inside a helper (param -> local -> sink);
10
10
  * - transitive sink-reaching (depth > 1) via a per-parameter-slot fixpoint;
11
11
  * - barrel / re-exports (export * / export {x} from / module.exports = require);
12
- * - return-value taint (exec(getInput(req)) where getInput returns its input).
12
+ * - return-value taint (exec(getInput(req)) where getInput returns its input);
13
+ * - object property propagation (const obj = {k: input}; helper(obj.k));
14
+ * - async/await and Promise.then chains (const d = await getInput(req); exec(d));
15
+ * - conditional returns (if tainted in either branch, function returns tainted).
13
16
  *
14
17
  * Bounded/best-effort: relative imports, positional argument->parameter mapping.
15
18
  * Confidence medium.
@@ -56,11 +59,53 @@ function bindingNames(param, out) {
56
59
  }
57
60
 
58
61
  // All identifier names referenced in an expression subtree.
62
+ // Tracks object property reads: {k: input} -> obj.k references `obj` which
63
+ // carries taint from the property assignment.
59
64
  function collectRefs(node, out) {
60
65
  out = out || new Set();
61
66
  if (!node || typeof node !== 'object') return out;
62
67
  if (node.type === 'Identifier') { out.add(node.name); return out; }
63
- if (node.type === 'MemberExpression') { const r = ast.rootName(node); if (r) out.add(r); return out; }
68
+ if (node.type === 'MemberExpression') {
69
+ // obj.prop or obj[expr] — the root identifier carries taint.
70
+ const r = ast.rootName(node);
71
+ if (r) out.add(r);
72
+ // Also collect refs in computed property: obj[someVar]
73
+ if (node.computed && node.property) collectRefs(node.property, out);
74
+ return out;
75
+ }
76
+ // Await expression — the awaited value's refs matter.
77
+ if (node.type === 'AwaitExpression') return collectRefs(node.argument, out);
78
+ // Conditional expression — both branches can carry taint.
79
+ if (node.type === 'ConditionalExpression') {
80
+ collectRefs(node.consequent, out);
81
+ collectRefs(node.alternate, out);
82
+ return out;
83
+ }
84
+ // Logical expression — both sides can carry taint.
85
+ if (node.type === 'LogicalExpression') {
86
+ collectRefs(node.left, out);
87
+ collectRefs(node.right, out);
88
+ return out;
89
+ }
90
+ // Template literal — expressions inside can carry taint.
91
+ if (node.type === 'TemplateLiteral') {
92
+ for (const expr of node.expressions || []) collectRefs(expr, out);
93
+ return out;
94
+ }
95
+ // Binary expression — string concat propagates taint.
96
+ if (node.type === 'BinaryExpression') {
97
+ collectRefs(node.left, out);
98
+ collectRefs(node.right, out);
99
+ return out;
100
+ }
101
+ // Call expression — a sanitizer call clears, but otherwise args propagate.
102
+ if (node.type === 'CallExpression') {
103
+ // Check for Promise.then chain: getInput(req).then(d => exec(d))
104
+ // The callee refs matter (it could be a taint-returning function).
105
+ collectRefs(node.callee, out);
106
+ for (const arg of node.arguments || []) collectRefs(arg, out);
107
+ return out;
108
+ }
64
109
  for (const k in node) {
65
110
  if (k === 'type' || k === 'loc' || k === 'start' || k === 'end' || k === 'range') continue;
66
111
  const v = node[k];
@@ -71,22 +116,53 @@ function collectRefs(node, out) {
71
116
  }
72
117
 
73
118
  // Analyze one function: which parameter SLOTS reach a sink, what it forwards, and
74
- // which slots it returns. Tracks taint through local reassignments (fixpoint).
119
+ // which slots it returns. Tracks taint through local reassignments (fixpoint),
120
+ // object property writes (const o = {k: param}; exec(o.k)), and async/await.
75
121
  function analyzeFunction(node, walk, resolveCallee) {
76
122
  const params = node.params || [];
77
123
  const taintOf = new Map(); // varName -> Set(paramSlot)
124
+ // Track object property taint: Map(objectName -> Map(propKey -> Set(paramSlot)))
125
+ const propTaintOf = new Map();
78
126
  params.forEach((p, i) => bindingNames(p).forEach((n) => { if (!taintOf.has(n)) taintOf.set(n, new Set([i])); }));
79
127
 
80
128
  const assigns = [];
129
+ const propAssigns = []; // { objName, propName, expr }
81
130
  walk.simple(node, {
82
- VariableDeclarator(n) { if (n.id && n.id.type === 'Identifier' && n.init) assigns.push({ t: n.id.name, e: n.init }); },
83
- AssignmentExpression(n) { if (n.left && n.left.type === 'Identifier') assigns.push({ t: n.left.name, e: n.right }); },
131
+ VariableDeclarator(n) {
132
+ if (n.id && n.id.type === 'Identifier' && n.init) assigns.push({ t: n.id.name, e: n.init });
133
+ // Object property writes: const obj = { key: param } or { ...param }
134
+ if (n.id && n.id.type === 'Identifier' && n.init && n.init.type === 'ObjectExpression') {
135
+ for (const prop of n.init.properties || []) {
136
+ if (prop.value && prop.key) {
137
+ const keyName = prop.key.name || prop.key.value;
138
+ if (keyName) propAssigns.push({ objName: n.id.name, propName: keyName, expr: prop.value });
139
+ }
140
+ }
141
+ }
142
+ },
143
+ AssignmentExpression(n) {
144
+ if (n.left && n.left.type === 'Identifier') assigns.push({ t: n.left.name, e: n.right });
145
+ // obj.prop = tainted
146
+ if (n.left && n.left.type === 'MemberExpression' && n.left.object && n.left.object.type === 'Identifier' && n.left.property) {
147
+ const propName = n.left.property.name || n.left.property.value;
148
+ if (propName) propAssigns.push({ objName: n.left.object.name, propName, expr: n.right });
149
+ }
150
+ },
84
151
  });
85
- for (let pass = 0; pass < 5; pass++) {
152
+
153
+ // Fixpoint: propagate taint through local assignments + property writes.
154
+ for (let pass = 0; pass < 8; pass++) {
86
155
  let changed = false;
156
+ // Local var assignments.
87
157
  for (const a of assigns) {
88
158
  const slots = new Set();
89
- for (const r of collectRefs(a.e)) { const s = taintOf.get(r); if (s) for (const x of s) slots.add(x); }
159
+ for (const r of collectRefs(a.e)) {
160
+ const s = taintOf.get(r);
161
+ if (s) for (const x of s) slots.add(x);
162
+ // Also check if this ref is an object property that carries taint.
163
+ const pt = propTaintOf.get(r);
164
+ if (pt) for (const ps of pt.values()) for (const x of ps) slots.add(x);
165
+ }
90
166
  if (slots.size) {
91
167
  let cur = taintOf.get(a.t);
92
168
  if (!cur) { cur = new Set(); taintOf.set(a.t, cur); }
@@ -95,11 +171,35 @@ function analyzeFunction(node, walk, resolveCallee) {
95
171
  if (cur.size !== before) changed = true;
96
172
  }
97
173
  }
174
+ // Object property assignments: obj.prop = expr -> track taint on obj.prop
175
+ for (const pa of propAssigns) {
176
+ const slots = new Set();
177
+ for (const r of collectRefs(pa.expr)) {
178
+ const s = taintOf.get(r);
179
+ if (s) for (const x of s) slots.add(x);
180
+ }
181
+ if (slots.size) {
182
+ if (!propTaintOf.has(pa.objName)) propTaintOf.set(pa.objName, new Map());
183
+ const propMap = propTaintOf.get(pa.objName);
184
+ const before = (propMap.get(pa.propName) || new Set()).size;
185
+ let cur = propMap.get(pa.propName);
186
+ if (!cur) { cur = new Set(); propMap.set(pa.propName, cur); }
187
+ for (const x of slots) cur.add(x);
188
+ if (cur.size !== before) changed = true;
189
+ }
190
+ }
98
191
  if (!changed) break;
99
192
  }
193
+
194
+ // Check if a var is tainted (either directly or through a property).
100
195
  const slotsFor = (n) => {
101
196
  const s = new Set();
102
- for (const r of collectRefs(n)) { const t = taintOf.get(r); if (t) for (const x of t) s.add(x); }
197
+ for (const r of collectRefs(n)) {
198
+ const t = taintOf.get(r);
199
+ if (t) for (const x of t) s.add(x);
200
+ const pt = propTaintOf.get(r);
201
+ if (pt) for (const ps of pt.values()) for (const x of ps) s.add(x);
202
+ }
103
203
  return s;
104
204
  };
105
205
 
@@ -113,7 +213,12 @@ function analyzeFunction(node, walk, resolveCallee) {
113
213
  const target = resolveCallee(call.callee);
114
214
  if (target) (call.arguments || []).forEach((arg, k) => { for (const slot of slotsFor(arg)) forwards.push({ toArgIndex: k, fromSlot: slot, target }); });
115
215
  },
116
- ReturnStatement(r) { for (const slot of slotsFor(r.argument)) returnsSlots.add(slot); },
216
+ // Handle return statements including conditional returns.
217
+ ReturnStatement(r) { if (r.argument) for (const slot of slotsFor(r.argument)) returnsSlots.add(slot); },
218
+ // Handle arrow functions with expression bodies (implicit return).
219
+ ArrowFunctionExpression(fn) {
220
+ if (fn.body && fn.expression) for (const slot of slotsFor(fn.body)) returnsSlots.add(slot);
221
+ },
117
222
  });
118
223
  return { sinkSlots, forwards, returnsSlots };
119
224
  }
@@ -288,6 +393,40 @@ function analyzeCrossFile(files, treesCache) {
288
393
  if (c.type === 'MemberExpression' && c.object.type === 'Identifier' && ns.has(c.object.name) && c.property.name) { const mod = ns.get(c.object.name); return { key: `${mod}::${c.property.name}`, name: `${c.object.name}.${c.property.name}`, mod }; }
289
394
  return null;
290
395
  };
396
+
397
+ // (3) Build a map of local variables that hold tainted return values from
398
+ // imported functions. Handles: const x = importedFn(req) and
399
+ // const x = await importedFn(req).
400
+ const taintedReturnVars = new Map(); // varName -> { funcName, mod }
401
+ walk.simple(tree, {
402
+ VariableDeclarator(n) {
403
+ if (!n.id || n.id.type !== 'Identifier' || !n.init) return;
404
+ // Unwrap AwaitExpression: const x = await fn(req) -> fn(req)
405
+ let init = n.init;
406
+ if (init.type === 'AwaitExpression') init = init.argument;
407
+ if (!init || init.type !== 'CallExpression') return;
408
+ const ir = resolve(init.callee);
409
+ if (!ir || !returnsExport.has(ir.key)) return;
410
+ const retSlots = returnsExport.get(ir.key);
411
+ const inner = init.arguments || [];
412
+ if (inner.some((x, j) => isReq(x) && retSlots.has(j))) {
413
+ taintedReturnVars.set(n.id.name, { funcName: ir.name, mod: ir.mod });
414
+ }
415
+ },
416
+ AssignmentExpression(n) {
417
+ if (!n.left || n.left.type !== 'Identifier') return;
418
+ let init = n.right;
419
+ if (init && init.type === 'AwaitExpression') init = init.argument;
420
+ if (!init || init.type !== 'CallExpression') return;
421
+ const ir = resolve(init.callee);
422
+ if (!ir || !returnsExport.has(ir.key)) return;
423
+ const retSlots = returnsExport.get(ir.key);
424
+ const inner = init.arguments || [];
425
+ if (inner.some((x, j) => isReq(x) && retSlots.has(j))) {
426
+ taintedReturnVars.set(n.left.name, { funcName: ir.name, mod: ir.mod });
427
+ }
428
+ },
429
+ });
291
430
  walk.simple(tree, {
292
431
  CallExpression(node) {
293
432
  const args = node.arguments || [];
@@ -313,6 +452,12 @@ function analyzeCrossFile(files, treesCache) {
313
452
  }
314
453
  }
315
454
  }
455
+ // (3) indirect return-value taint: arg is a local variable that was
456
+ // assigned from an imported taint-returning call (possibly via await).
457
+ if (a && a.type === 'Identifier' && taintedReturnVars.has(a.name)) {
458
+ const info = taintedReturnVars.get(a.name);
459
+ emit(rel, node, `Variable \`${a.name}\` carries request data from ${info.funcName}() (from ${info.mod}) into ${ast.sinkKindOfCall(node).label} — cross-file taint via return value assigned to a local.`, `Sanitize ${a.name} before using it in the sink, or sanitize inside ${info.funcName}().`);
460
+ }
316
461
  }
317
462
  }
318
463
  },
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // daemon-run.js — entry point for the background daemon process.
4
+ // Spawned by daemon.js startDaemon(). Runs the daemon loop.
5
+
6
+ const path = require('path');
7
+ const { runDaemon } = require('./daemon');
8
+
9
+ const rootDir = path.resolve(process.argv[2] || '.');
10
+ const verbose = process.argv.includes('--verbose');
11
+
12
+ runDaemon(rootDir, { verbose });
package/src/daemon.js ADDED
@@ -0,0 +1,342 @@
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
+ });
245
+
246
+ child.unref();
247
+
248
+ // Wait a moment for PID file to appear
249
+ return new Promise((resolve) => {
250
+ setTimeout(() => {
251
+ if (fs.existsSync(pidFile)) {
252
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
253
+ resolve({ started: true, pid: data.pid, root: rootDir, logFile: logPath });
254
+ } else {
255
+ resolve({ started: false, reason: 'daemon failed to start — check log', logFile: logPath });
256
+ }
257
+ }, 1000);
258
+ });
259
+ }
260
+
261
+ function stopDaemon(rootDir) {
262
+ const pidFile = path.join(rootDir, DAEMON_FILE);
263
+ if (!fs.existsSync(pidFile)) {
264
+ return { stopped: false, reason: 'no daemon running' };
265
+ }
266
+
267
+ try {
268
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
269
+ const pid = data.pid;
270
+ if (pid) {
271
+ try {
272
+ process.kill(pid, 'SIGTERM');
273
+ } catch (e) {
274
+ // Process might already be dead
275
+ }
276
+ }
277
+ // Wait for PID file to be removed
278
+ return new Promise((resolve) => {
279
+ let tries = 0;
280
+ const interval = setInterval(() => {
281
+ if (!fs.existsSync(pidFile) || tries > 10) {
282
+ clearInterval(interval);
283
+ try { fs.unlinkSync(pidFile); } catch {}
284
+ resolve({ stopped: true, pid });
285
+ }
286
+ tries++;
287
+ }, 200);
288
+ });
289
+ } catch (e) {
290
+ try { fs.unlinkSync(pidFile); } catch {}
291
+ return { stopped: false, reason: e.message };
292
+ }
293
+ }
294
+
295
+ function isDaemonRunning(rootDir) {
296
+ const pidFile = path.join(rootDir, DAEMON_FILE);
297
+ if (!fs.existsSync(pidFile)) return false;
298
+ try {
299
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
300
+ const pid = data.pid;
301
+ if (!pid) return false;
302
+ // Check if process is alive
303
+ try {
304
+ process.kill(pid, 0);
305
+ return true;
306
+ } catch (e) {
307
+ // Process is dead — clean up stale PID file
308
+ try { fs.unlinkSync(pidFile); } catch {}
309
+ return false;
310
+ }
311
+ } catch {
312
+ try { fs.unlinkSync(pidFile); } catch {}
313
+ return false;
314
+ }
315
+ }
316
+
317
+ function getDaemonStatus(rootDir) {
318
+ const pidFile = path.join(rootDir, DAEMON_FILE);
319
+ const logPath = path.join(rootDir, DAEMON_LOG);
320
+ if (!fs.existsSync(pidFile)) {
321
+ return { running: false };
322
+ }
323
+ try {
324
+ const data = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
325
+ const running = isDaemonRunning(rootDir);
326
+ return {
327
+ running,
328
+ pid: data.pid,
329
+ root: data.root,
330
+ startedAt: data.startedAt,
331
+ findings: data.findings || 0,
332
+ blocked: data.blocked || 0,
333
+ watched: data.watched || 0,
334
+ heartbeat: data.heartbeat,
335
+ logFile: logPath,
336
+ };
337
+ } catch {
338
+ return { running: false };
339
+ }
340
+ }
341
+
342
+ module.exports = { runDaemon, startDaemon, stopDaemon, isDaemonRunning, getDaemonStatus, DAEMON_FILE, DAEMON_LOG };