@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/CHANGELOG.md +63 -0
- package/README.md +302 -31
- package/bin/cli.js +318 -4
- package/package.json +14 -11
- package/src/ast.js +4 -0
- package/src/auto.js +422 -0
- package/src/crosstaint.js +154 -9
- package/src/daemon-run.js +12 -0
- package/src/daemon.js +342 -0
- package/src/guard.js +80 -0
- package/src/mcp-server.js +0 -5
- package/src/rules-pack.js +112 -12
- package/src/rules.js +11 -6
- package/src/scanner.js +36 -2
- package/src/shell-guard.js +276 -0
- package/src/shell-hook.ps1 +135 -0
- package/src/shell-hook.sh +90 -0
- package/src/suppress.js +78 -8
- package/src/taint-ast.js +852 -0
- package/src/taint.js +38 -12
package/src/auto.js
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* src/auto.js — One-command autonomous protection orchestrator.
|
|
5
|
+
*
|
|
6
|
+
* `vibeguard auto` → scan + daemon + hooks + shell guard (idempotent)
|
|
7
|
+
* `vibeguard auto --stop` → reverse everything, restore backups
|
|
8
|
+
* `vibeguard auto --status` → show what's active
|
|
9
|
+
*
|
|
10
|
+
* Composes existing modules: scanner, daemon, hook, shell-guard.
|
|
11
|
+
* All state under .vibeguard/auto.json.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
const os = require('os');
|
|
17
|
+
const { spawn, execSync } = require('child_process');
|
|
18
|
+
|
|
19
|
+
const STATE_DIR = '.vibeguard';
|
|
20
|
+
const STATE_FILE = path.join(STATE_DIR, 'auto.json');
|
|
21
|
+
const REPORT_FILE = path.join(STATE_DIR, 'report.json');
|
|
22
|
+
const SARIF_FILE = path.join(STATE_DIR, 'report.sarif');
|
|
23
|
+
const EVENTS_LOG = path.join(STATE_DIR, 'events.log');
|
|
24
|
+
const BACKUP_DIR = path.join(STATE_DIR, 'backups');
|
|
25
|
+
|
|
26
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────
|
|
27
|
+
|
|
28
|
+
function findProjectRoot(startDir) {
|
|
29
|
+
let dir = path.resolve(startDir);
|
|
30
|
+
for (let i = 0; i < 20; i++) {
|
|
31
|
+
if (fs.existsSync(path.join(dir, 'package.json')) || fs.existsSync(path.join(dir, '.git'))) {
|
|
32
|
+
return dir;
|
|
33
|
+
}
|
|
34
|
+
const parent = path.dirname(dir);
|
|
35
|
+
if (parent === dir) break;
|
|
36
|
+
dir = parent;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function ensureStateDir(root) {
|
|
42
|
+
const dir = path.join(root, STATE_DIR);
|
|
43
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
44
|
+
fs.mkdirSync(path.join(root, BACKUP_DIR), { recursive: true });
|
|
45
|
+
return dir;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function readState(root) {
|
|
49
|
+
const p = path.join(root, STATE_FILE);
|
|
50
|
+
if (!fs.existsSync(p)) return null;
|
|
51
|
+
try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return null; }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function writeState(root, state) {
|
|
55
|
+
ensureStateDir(root);
|
|
56
|
+
fs.writeFileSync(path.join(root, STATE_FILE), JSON.stringify(state, null, 2));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function removeState(root) {
|
|
60
|
+
try { fs.unlinkSync(path.join(root, STATE_FILE)); } catch {}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function logEvent(root, msg) {
|
|
64
|
+
const logPath = path.join(root, EVENTS_LOG);
|
|
65
|
+
const ts = new Date().toISOString();
|
|
66
|
+
fs.appendFileSync(logPath, `[${ts}] ${msg}\n`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function backupFile(src, dst) {
|
|
70
|
+
if (fs.existsSync(src)) {
|
|
71
|
+
fs.copyFileSync(src, dst);
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function restoreFile(dst, src) {
|
|
78
|
+
if (fs.existsSync(src)) {
|
|
79
|
+
fs.copyFileSync(src, dst);
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function isProcessAlive(pid) {
|
|
86
|
+
try { process.kill(pid, 0); return true; } catch { return false; }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ─── Auto Start ────────────────────────────────────────────────────────────
|
|
90
|
+
|
|
91
|
+
function autoStart(rootDir, opts) {
|
|
92
|
+
opts = opts || {};
|
|
93
|
+
const root = findProjectRoot(rootDir);
|
|
94
|
+
if (!root) {
|
|
95
|
+
return { ok: false, reason: 'No project root found (no package.json or .git). Run from a project directory.' };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Idempotent: if already running, report status
|
|
99
|
+
const existing = readState(root);
|
|
100
|
+
if (existing && existing.pid && isProcessAlive(existing.pid)) {
|
|
101
|
+
return { ok: true, alreadyRunning: true, state: existing };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
ensureStateDir(root);
|
|
105
|
+
const state = {
|
|
106
|
+
pid: process.pid,
|
|
107
|
+
root,
|
|
108
|
+
startedAt: new Date().toISOString(),
|
|
109
|
+
features: {},
|
|
110
|
+
backups: {},
|
|
111
|
+
lastScan: null,
|
|
112
|
+
findingsSinceStart: 0,
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const steps = [];
|
|
116
|
+
|
|
117
|
+
// 1. Initial full scan (always run — CI mode needs it too)
|
|
118
|
+
const { scan } = require('./scanner');
|
|
119
|
+
const result = scan(root, { deps: true, deep: !!opts.deep });
|
|
120
|
+
state.lastScan = new Date().toISOString();
|
|
121
|
+
state.findingsSinceStart = result.findings.length;
|
|
122
|
+
|
|
123
|
+
// Write report + SARIF
|
|
124
|
+
ensureStateDir(root);
|
|
125
|
+
fs.writeFileSync(path.join(root, REPORT_FILE), JSON.stringify(result, null, 2));
|
|
126
|
+
try {
|
|
127
|
+
const { renderSarif } = require('./report');
|
|
128
|
+
fs.writeFileSync(path.join(root, SARIF_FILE), renderSarif(result));
|
|
129
|
+
} catch {}
|
|
130
|
+
|
|
131
|
+
steps.push({
|
|
132
|
+
step: 'scan',
|
|
133
|
+
grade: result.grade,
|
|
134
|
+
counts: result.counts,
|
|
135
|
+
findings: result.findings.length,
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
// CI mode: exit non-zero on critical, no daemon
|
|
139
|
+
if (opts.ci) {
|
|
140
|
+
writeState(root, state);
|
|
141
|
+
return { ok: true, ci: true, steps, exitCode: result.counts.critical > 0 ? 1 : 0 };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// --fix: apply safe auto-fixes
|
|
145
|
+
if (opts.fix) {
|
|
146
|
+
try {
|
|
147
|
+
const { computeAutoFixes } = require('./autofix');
|
|
148
|
+
const fixes = computeAutoFixes(result.findings, result.root);
|
|
149
|
+
if (fixes && fixes.length > 0) {
|
|
150
|
+
steps.push({ step: 'fix', fixes: fixes.length, reversible: true });
|
|
151
|
+
}
|
|
152
|
+
} catch {}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// 2. Start daemon (file watcher)
|
|
156
|
+
if (!opts.ci) {
|
|
157
|
+
try {
|
|
158
|
+
const { startDaemon, isDaemonRunning } = require('./daemon');
|
|
159
|
+
if (!isDaemonRunning(root)) {
|
|
160
|
+
startDaemon(root, { verbose: opts.verbose }).then((r) => {
|
|
161
|
+
if (r.started) {
|
|
162
|
+
state.features.daemon = true;
|
|
163
|
+
state.daemonPid = r.pid;
|
|
164
|
+
logEvent(root, `daemon started (PID ${r.pid})`);
|
|
165
|
+
}
|
|
166
|
+
}).catch(() => {});
|
|
167
|
+
} else {
|
|
168
|
+
state.features.daemon = true;
|
|
169
|
+
}
|
|
170
|
+
steps.push({ step: 'daemon', started: state.features.daemon });
|
|
171
|
+
} catch (e) {
|
|
172
|
+
steps.push({ step: 'daemon', error: e.message });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// 3. Install git pre-commit hook (if .git exists)
|
|
177
|
+
const gitDir = path.join(root, '.git');
|
|
178
|
+
if (fs.existsSync(gitDir) && !opts.ci) {
|
|
179
|
+
const hooksDir = path.join(gitDir, 'hooks');
|
|
180
|
+
fs.mkdirSync(hooksDir, { recursive: true });
|
|
181
|
+
const preCommit = path.join(hooksDir, 'pre-commit');
|
|
182
|
+
const backupPath = path.join(root, BACKUP_DIR, 'pre-commit.bak');
|
|
183
|
+
|
|
184
|
+
// Backup existing hook if present
|
|
185
|
+
if (fs.existsSync(preCommit)) {
|
|
186
|
+
backupFile(preCommit, backupPath);
|
|
187
|
+
state.backups.preCommit = backupPath;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Write the hook
|
|
191
|
+
const nodeBin = process.execPath.replace(/\\/g, '/');
|
|
192
|
+
const cliPath = path.join(__dirname, '..', 'bin', 'cli.js').replace(/\\/g, '/');
|
|
193
|
+
const strictFlag = opts.strict ? ' --strict' : '';
|
|
194
|
+
const hook = `#!/usr/bin/env sh\n# VibeGuard pre-commit hook (auto-installed).\nNODE="${nodeBin}"\nCLI="${cliPath}"\nif [ ! -f "$CLI" ]; then exit 0; fi\n"$NODE" "$CLI" scan . --precommit${strictFlag}\nSTATUS=$?\nif [ "$STATUS" -eq 2 ]; then\n echo "VibeGuard: commit blocked — CRITICAL issue(s). Fix or use --no-verify."\n exit 1\nfi\nexit 0\n`;
|
|
195
|
+
fs.writeFileSync(preCommit, hook);
|
|
196
|
+
try { fs.chmodSync(preCommit, 0o755); } catch {}
|
|
197
|
+
state.features.preCommitHook = true;
|
|
198
|
+
steps.push({ step: 'pre-commit-hook', installed: true, backedUp: state.backups.preCommit ? true : false });
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// 4. Install PostToolUse hook (for AI agent edit scanning)
|
|
202
|
+
if (!opts.ci) {
|
|
203
|
+
try {
|
|
204
|
+
const hookMod = require('./hook');
|
|
205
|
+
const r = hookMod.installPostEditHook(root);
|
|
206
|
+
state.features.postEditHook = r.installed;
|
|
207
|
+
steps.push({ step: 'post-edit-hook', installed: r.installed, file: r.file });
|
|
208
|
+
} catch (e) {
|
|
209
|
+
steps.push({ step: 'post-edit-hook', error: e.message });
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// 5. Arm shell guard (install shell hook)
|
|
214
|
+
if (!opts.noShell && !opts.ci) {
|
|
215
|
+
try {
|
|
216
|
+
const srcDir = path.join(__dirname);
|
|
217
|
+
const home = os.homedir();
|
|
218
|
+
const marker = '# >>> VibeGuard shell hook >>>';
|
|
219
|
+
const endMarker = '# <<< VibeGuard shell hook <<<';
|
|
220
|
+
const psMarker = '### >>> VibeGuard shell hook >>>';
|
|
221
|
+
const psEndMarker = '### <<< VibeGuard shell hook <<<';
|
|
222
|
+
const hookContent = `${marker}\nVG_SCRIPT_DIR="${srcDir.replace(/\\/g, '\\\\')}"\nsource "${path.join(srcDir, 'shell-hook.sh').replace(/\\/g, '\\\\')}"\n${endMarker}`;
|
|
223
|
+
|
|
224
|
+
// bash
|
|
225
|
+
const bashrc = path.join(home, '.bashrc');
|
|
226
|
+
if (fs.existsSync(bashrc) || true) {
|
|
227
|
+
let content = fs.existsSync(bashrc) ? fs.readFileSync(bashrc, 'utf8') : '';
|
|
228
|
+
if (!content.includes(marker)) {
|
|
229
|
+
const backupPath = path.join(root, BACKUP_DIR, 'bashrc.bak');
|
|
230
|
+
if (fs.existsSync(bashrc)) backupFile(bashrc, backupPath);
|
|
231
|
+
state.backups.bashrc = backupPath;
|
|
232
|
+
content = content.trimEnd() + '\n' + hookContent + '\n';
|
|
233
|
+
fs.writeFileSync(bashrc, content);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// zsh
|
|
238
|
+
const zshrc = path.join(home, '.zshrc');
|
|
239
|
+
if (fs.existsSync(zshrc)) {
|
|
240
|
+
let content = fs.readFileSync(zshrc, 'utf8');
|
|
241
|
+
if (!content.includes(marker)) {
|
|
242
|
+
const backupPath = path.join(root, BACKUP_DIR, 'zshrc.bak');
|
|
243
|
+
backupFile(zshrc, backupPath);
|
|
244
|
+
state.backups.zshrc = backupPath;
|
|
245
|
+
content = content.trimEnd() + '\n' + hookContent + '\n';
|
|
246
|
+
fs.writeFileSync(zshrc, content);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// PowerShell (Windows)
|
|
251
|
+
if (process.platform === 'win32') {
|
|
252
|
+
const psDir = path.join(home, 'Documents', 'WindowsPowerShell');
|
|
253
|
+
fs.mkdirSync(psDir, { recursive: true });
|
|
254
|
+
const psProfile = path.join(psDir, 'Microsoft.PowerShell_profile.ps1');
|
|
255
|
+
let content = fs.existsSync(psProfile) ? fs.readFileSync(psProfile, 'utf8') : '';
|
|
256
|
+
if (!content.includes(psMarker)) {
|
|
257
|
+
const backupPath = path.join(root, BACKUP_DIR, 'ps-profile.bak');
|
|
258
|
+
if (fs.existsSync(psProfile)) backupFile(psProfile, backupPath);
|
|
259
|
+
state.backups.psProfile = backupPath;
|
|
260
|
+
const psHook = `${psMarker}\n$VG_SCRIPT_DIR = "${srcDir.replace(/\\/g, '\\\\')}"\n. "${path.join(srcDir, 'shell-hook.ps1').replace(/\\/g, '\\\\')}"\n${psEndMarker}`;
|
|
261
|
+
content = content.trimEnd() + '\n' + psHook + '\n';
|
|
262
|
+
fs.writeFileSync(psProfile, content);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
state.features.shellGuard = true;
|
|
267
|
+
steps.push({ step: 'shell-guard', installed: true });
|
|
268
|
+
} catch (e) {
|
|
269
|
+
steps.push({ step: 'shell-guard', error: e.message });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Add .vibeguard/ to .gitignore
|
|
274
|
+
const gitignore = path.join(root, '.gitignore');
|
|
275
|
+
try {
|
|
276
|
+
let content = fs.existsSync(gitignore) ? fs.readFileSync(gitignore, 'utf8') : '';
|
|
277
|
+
if (!content.includes('.vibeguard/')) {
|
|
278
|
+
content = content.trimEnd() + '\n.vibeguard/\n';
|
|
279
|
+
fs.writeFileSync(gitignore, content);
|
|
280
|
+
}
|
|
281
|
+
} catch {}
|
|
282
|
+
|
|
283
|
+
writeState(root, state);
|
|
284
|
+
logEvent(root, 'auto started');
|
|
285
|
+
|
|
286
|
+
return { ok: true, steps, state };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// ─── Auto Stop ─────────────────────────────────────────────────────────────
|
|
290
|
+
|
|
291
|
+
function autoStop(rootDir) {
|
|
292
|
+
const root = findProjectRoot(rootDir) || path.resolve(rootDir);
|
|
293
|
+
const state = readState(root);
|
|
294
|
+
if (!state) {
|
|
295
|
+
return { ok: false, reason: 'No auto state found. Was `vibeguard auto` run?' };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const reversed = [];
|
|
299
|
+
|
|
300
|
+
// 1. Kill daemon
|
|
301
|
+
if (state.daemonPid) {
|
|
302
|
+
try { process.kill(state.daemonPid, 'SIGTERM'); } catch {}
|
|
303
|
+
reversed.push('daemon stopped');
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// 2. Remove pre-commit hook (restore backup if exists)
|
|
307
|
+
const preCommit = path.join(root, '.git', 'hooks', 'pre-commit');
|
|
308
|
+
if (fs.existsSync(preCommit) && state.backups && state.backups.preCommit) {
|
|
309
|
+
restoreFile(preCommit, state.backups.preCommit);
|
|
310
|
+
reversed.push('pre-commit hook restored from backup');
|
|
311
|
+
} else if (fs.existsSync(preCommit)) {
|
|
312
|
+
// Only remove if we installed it
|
|
313
|
+
const content = fs.readFileSync(preCommit, 'utf8');
|
|
314
|
+
if (content.includes('VibeGuard')) {
|
|
315
|
+
fs.unlinkSync(preCommit);
|
|
316
|
+
reversed.push('pre-commit hook removed');
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// 3. Remove PostToolUse hook
|
|
321
|
+
try {
|
|
322
|
+
const hookMod = require('./hook');
|
|
323
|
+
const r = hookMod.uninstallPostEditHook(root);
|
|
324
|
+
if (r.uninstalled) reversed.push('post-edit hook removed');
|
|
325
|
+
} catch {}
|
|
326
|
+
|
|
327
|
+
// 4. Disarm shell guard (remove from shell profiles)
|
|
328
|
+
const marker = '# >>> VibeGuard shell hook >>>';
|
|
329
|
+
const endMarker = '# <<< VibeGuard shell hook <<<';
|
|
330
|
+
const psMarker = '### >>> VibeGuard shell hook >>>';
|
|
331
|
+
const psEndMarker = '### <<< VibeGuard shell hook <<<';
|
|
332
|
+
const home = os.homedir();
|
|
333
|
+
|
|
334
|
+
for (const profile of ['.bashrc', '.zshrc']) {
|
|
335
|
+
const p = path.join(home, profile);
|
|
336
|
+
try {
|
|
337
|
+
if (fs.existsSync(p)) {
|
|
338
|
+
let content = fs.readFileSync(p, 'utf8');
|
|
339
|
+
// Restore from backup if available
|
|
340
|
+
const backupKey = profile === '.bashrc' ? 'bashrc' : 'zshrc';
|
|
341
|
+
if (state.backups && state.backups[backupKey] && fs.existsSync(state.backups[backupKey])) {
|
|
342
|
+
content = fs.readFileSync(state.backups[backupKey], 'utf8');
|
|
343
|
+
fs.writeFileSync(p, content);
|
|
344
|
+
reversed.push(`${profile} restored from backup`);
|
|
345
|
+
} else {
|
|
346
|
+
// Just remove our block
|
|
347
|
+
const before = content;
|
|
348
|
+
content = content.replace(new RegExp(marker + '[\\s\\S]*?' + endMarker + '\\n?', 'g'), '');
|
|
349
|
+
if (content !== before) {
|
|
350
|
+
fs.writeFileSync(p, content);
|
|
351
|
+
reversed.push(`${profile} hook removed`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
} catch {}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (process.platform === 'win32') {
|
|
359
|
+
try {
|
|
360
|
+
const psProfile = path.join(home, 'Documents', 'WindowsPowerShell', 'Microsoft.PowerShell_profile.ps1');
|
|
361
|
+
if (fs.existsSync(psProfile)) {
|
|
362
|
+
let content = fs.readFileSync(psProfile, 'utf8');
|
|
363
|
+
if (state.backups && state.backups.psProfile && fs.existsSync(state.backups.psProfile)) {
|
|
364
|
+
content = fs.readFileSync(state.backups.psProfile, 'utf8');
|
|
365
|
+
fs.writeFileSync(psProfile, content);
|
|
366
|
+
reversed.push('PowerShell profile restored from backup');
|
|
367
|
+
} else {
|
|
368
|
+
const before = content;
|
|
369
|
+
content = content.replace(new RegExp(psMarker + '[\\s\\S]*?' + psEndMarker + '\\n?', 'g'), '');
|
|
370
|
+
if (content !== before) {
|
|
371
|
+
fs.writeFileSync(psProfile, content);
|
|
372
|
+
reversed.push('PowerShell profile hook removed');
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
} catch {}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// 5. Remove state file
|
|
380
|
+
removeState(root);
|
|
381
|
+
reversed.push('state file removed');
|
|
382
|
+
|
|
383
|
+
logEvent(root, 'auto stopped');
|
|
384
|
+
|
|
385
|
+
return { ok: true, reversed };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// ─── Auto Status ──────────────────────────────────────────────────────────
|
|
389
|
+
|
|
390
|
+
function autoStatus(rootDir) {
|
|
391
|
+
const root = findProjectRoot(rootDir) || path.resolve(rootDir);
|
|
392
|
+
const state = readState(root);
|
|
393
|
+
if (!state) {
|
|
394
|
+
return { running: false, reason: 'No auto state found' };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const daemonAlive = state.daemonPid ? isProcessAlive(state.daemonPid) : false;
|
|
398
|
+
const uptime = state.startedAt ? Date.now() - new Date(state.startedAt).getTime() : 0;
|
|
399
|
+
|
|
400
|
+
return {
|
|
401
|
+
running: true,
|
|
402
|
+
pid: state.pid,
|
|
403
|
+
daemonPid: state.daemonPid,
|
|
404
|
+
daemonAlive,
|
|
405
|
+
startedAt: state.startedAt,
|
|
406
|
+
uptimeMs: uptime,
|
|
407
|
+
features: state.features || {},
|
|
408
|
+
findingsSinceStart: state.findingsSinceStart || 0,
|
|
409
|
+
lastScan: state.lastScan,
|
|
410
|
+
root: state.root,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// ─── CI Mode ────────────────────────────────────────────────────────────────
|
|
415
|
+
|
|
416
|
+
function autoCI(rootDir, opts) {
|
|
417
|
+
opts = opts || {};
|
|
418
|
+
opts.ci = true;
|
|
419
|
+
return autoStart(rootDir, opts);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
module.exports = { autoStart, autoStop, autoStatus, autoCI, findProjectRoot };
|
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') {
|
|
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) {
|
|
83
|
-
|
|
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
|
-
|
|
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)) {
|
|
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)) {
|
|
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
|
-
|
|
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 });
|