@yagyeshvyas/vibeguard 1.0.0 → 1.2.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/engine.js CHANGED
@@ -1,234 +1,294 @@
1
- 'use strict';
2
-
3
- /*
4
- * Engine gaps:
5
- * 1. Sanitizer recognition — stop taint propagation when a sanitizer is applied
6
- * 2. Incremental/diff-aware scanning — only scan changed files
7
- * 3. Auth coverage map — enumerate routes → middleware → guards
8
- * 4. Python taint — basic Python source-to-sink taint detection
9
- */
10
-
11
- const fs = require('fs');
12
- const path = require('path');
13
- const crypto = require('crypto');
14
-
15
- // ---------------------------------------------------------------------------
16
- // 1. SANITIZER RECOGNITION
17
- // ---------------------------------------------------------------------------
18
-
19
- const SANITIZERS = {
20
- xss: [
21
- 'DOMPurify', 'sanitize', 'sanitizeHtml', 'escape', 'escapeHtml',
22
- 'encodeURIComponent', 'encodeURI', 'textEncode', 'he.encode',
23
- 'React.createElement', 'textContent',
24
- ],
25
- sql: [
26
- 'parameterize', 'prepare', 'placeholder', 'bind', 'sql`', 'sql.query',
27
- 'prisma.$queryRaw', 'pool.query', 'client.query',
28
- ],
29
- cmd: [
30
- 'execFile', 'spawn', 'shell-quote', 'shellescape', 'sanitizeShell',
31
- ],
32
- path: [
33
- 'path.resolve', 'path.join', 'path.normalize', 'sanitize',
34
- ],
35
- };
36
-
37
- function isSanitized(expr, type) {
38
- if (!expr || typeof expr !== 'string') return false;
39
- const sanitizers = SANITIZERS[type] || [];
40
- return sanitizers.some((s) => expr.includes(s));
41
- }
42
-
43
- // ---------------------------------------------------------------------------
44
- // 2. INCREMENTAL / DIFF-AWARE SCANNING
45
- // ---------------------------------------------------------------------------
46
-
47
- const HASH_CACHE_DIR = '.vibeguard/cache';
48
-
49
- function loadHashCache(root) {
50
- const p = path.join(root, HASH_CACHE_DIR, 'file-hashes.json');
51
- if (fs.existsSync(p)) {
52
- try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch {}
53
- }
54
- return {};
55
- }
56
-
57
- function saveHashCache(root, cache) {
58
- const dir = path.join(root, HASH_CACHE_DIR);
59
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
60
- fs.writeFileSync(path.join(dir, 'file-hashes.json'), JSON.stringify(cache, null, 2));
61
- }
62
-
63
- function hashContent(content) {
64
- return crypto.createHash('sha256').update(content).digest('hex');
65
- }
66
-
67
- function getChangedFiles(root, allFiles) {
68
- const cache = loadHashCache(root);
69
- const changed = [];
70
- const newCache = {};
71
-
72
- for (const file of allFiles) {
73
- try {
74
- const content = fs.readFileSync(file, 'utf8');
75
- const hash = hashContent(content);
76
- newCache[file] = hash;
77
- if (cache[file] !== hash) changed.push(file);
78
- } catch {
79
- // can't read, skip
80
- }
81
- }
82
-
83
- saveHashCache(root, newCache);
84
- return { changed, total: allFiles.length, cached: allFiles.length - changed.length };
85
- }
86
-
87
- // ---------------------------------------------------------------------------
88
- // 3. AUTH COVERAGE MAP
89
- // ---------------------------------------------------------------------------
90
-
91
- const ROUTE_RE = /(?:app|router|server)\.(?:get|post|put|delete|patch|all|use)\s*\(\s*['"`]([^'"`]+)['"`]/gi;
92
- const MIDDLEWARE_RE = /(?:app|router)\.use\s*\(\s*['"`]([^'"`]+)['"`]/gi;
93
- const AUTH_GUARD_RE = /(?:requireAuth|withAuth|protect|guard|authMiddleware|isAuthenticated|verifyToken|authenticate|clerkMiddleware|auth\(\)|getServerSession|getSession)/i;
94
-
95
- function buildAuthCoverage(root, files) {
96
- const routes = [];
97
- const middlewares = [];
98
-
99
- for (const file of files) {
100
- try {
101
- const content = fs.readFileSync(file, 'utf8');
102
- const relPath = path.relative(root, file);
103
-
104
- let m;
105
- while ((m = ROUTE_RE.exec(content)) !== null) {
106
- const routePath = m[1];
107
- const beforeLines = content.slice(0, m.index).split('\n');
108
- const lineNum = beforeLines.length;
109
- const currentLine = content.slice(m.index, m.index + 300).split('\n')[0];
110
- const hasAuth = AUTH_GUARD_RE.test(currentLine);
111
- routes.push({
112
- path: routePath,
113
- file: relPath,
114
- line: lineNum,
115
- protected: hasAuth,
116
- });
117
- }
118
-
119
- while ((m = MIDDLEWARE_RE.exec(content)) !== null) {
120
- const mwPath = m[1];
121
- const lines = content.slice(0, m.index).split('\n');
122
- const lineNum = lines.length;
123
- const surrounding = content.slice(m.index, m.index + 300);
124
- const isAuth = AUTH_GUARD_RE.test(surrounding);
125
- if (isAuth) {
126
- middlewares.push({ path: mwPath, file: relPath, line: lineNum });
127
- }
128
- }
129
- } catch {}
130
- }
131
-
132
- const unprotected = routes.filter((r) => !r.protected && r.path.startsWith('/api/'));
133
- const protectedRoutes = routes.filter((r) => r.protected);
134
-
135
- return {
136
- totalRoutes: routes.length,
137
- protectedRoutes: protectedRoutes.length,
138
- unprotectedRoutes: unprotected.length,
139
- unprotected,
140
- middlewares,
141
- coverage: routes.length > 0 ? Math.round((protectedRoutes.length / routes.length) * 100) : 100,
142
- };
143
- }
144
-
145
- // ---------------------------------------------------------------------------
146
- // 4. PYTHON TAINT (basic — regex-based, no AST)
147
- // ---------------------------------------------------------------------------
148
-
149
- const PY_SOURCES = [
150
- { re: /request\.(?:form|args|data|json|values|cookies|headers)(?:\.\w+)?\s*\(/g, name: 'request' },
151
- { re: /request\.get\s*\(/g, name: 'request' },
152
- { re: /\binput\s*\(/g, name: 'input()' },
153
- { re: /os\.environ\.get\s*\(/g, name: 'os.environ' },
154
- { re: /sys\.argv/g, name: 'sys.argv' },
155
- ];
156
-
157
- const PY_SINKS = [
158
- { re: /cursor\.execute\s*\(/g, name: 'cursor.execute', type: 'sql' },
159
- { re: /os\.system\s*\(/g, name: 'os.system', type: 'cmd' },
160
- { re: /subprocess\.(?:run|call|Popen)\s*\(/g, name: 'subprocess', type: 'cmd' },
161
- { re: /eval\s*\(/g, name: 'eval()', type: 'code' },
162
- { re: /exec\s*\(/g, name: 'exec()', type: 'code' },
163
- { re: /open\s*\(/g, name: 'open()', type: 'file' },
164
- { re: /pickle\.loads?\s*\(/g, name: 'pickle', type: 'deserialization' },
165
- ];
166
-
167
- function analyzePythonTaint(content, lines, relPath) {
168
- const findings = [];
169
- const sources = [];
170
- const sinks = [];
171
-
172
- for (let i = 0; i < lines.length; i++) {
173
- const line = lines[i];
174
- for (const src of PY_SOURCES) {
175
- src.re.lastIndex = 0;
176
- if (src.re.test(line)) {
177
- sources.push({ line: i + 1, name: src.name, var: extractVarName(line) });
178
- }
179
- }
180
- for (const sink of PY_SINKS) {
181
- sink.re.lastIndex = 0;
182
- if (sink.re.test(line)) {
183
- sinks.push({ line: i + 1, name: sink.name, type: sink.type });
184
- }
185
- }
186
- }
187
-
188
- for (const src of sources) {
189
- for (const sink of sinks) {
190
- if (sink.line >= src.line) {
191
- const varName = src.var;
192
- if (!varName) continue;
193
- const linesBetween = lines.slice(src.line - 1, sink.line).join('\n');
194
- if (linesBetween.includes(varName)) {
195
- findings.push({
196
- ruleId: 'py.taint-flow',
197
- file: relPath,
198
- line: sink.line,
199
- column: 1,
200
- severity: 'high',
201
- confidence: 'medium',
202
- title: `Python taint: ${src.name} → ${sink.name}`,
203
- snippet: lines[sink.line - 1]?.trim().slice(0, 120) || '',
204
- message: `User input (${src.name} at line ${src.line}) flows to ${sink.name} (line ${sink.line}) without sanitization.`,
205
- fix: `Sanitize or validate the input before passing it to ${sink.name}.`,
206
- owasp: 'A03:2025 Injection',
207
- cwe: sink.type === 'sql' ? 'CWE-89' : sink.type === 'cmd' ? 'CWE-77' : 'CWE-20',
208
- });
209
- }
210
- }
211
- }
212
- }
213
-
214
- return findings;
215
- }
216
-
217
- function extractVarName(line) {
218
- const m = /\b(\w+)\s*=\s*(?:request\.|input\(|os\.environ|sys\.argv)/.exec(line);
219
- if (m) return m[1];
220
- const m2 = /\b(?:for\s+)?(\w+)\s+in\s+request\./.exec(line);
221
- if (m2) return m2[1];
222
- return null;
223
- }
224
-
225
- module.exports = {
226
- isSanitized,
227
- SANITIZERS,
228
- getChangedFiles,
229
- loadHashCache,
230
- saveHashCache,
231
- hashContent,
232
- buildAuthCoverage,
233
- analyzePythonTaint,
234
- };
1
+ 'use strict';
2
+
3
+ /*
4
+ * Engine gaps:
5
+ * 1. Sanitizer recognition — stop taint propagation when a sanitizer is applied
6
+ * 2. Incremental/diff-aware scanning — only scan changed files
7
+ * 3. Auth coverage map — enumerate routes → middleware → guards
8
+ * 4. Python taint — basic Python source-to-sink taint detection
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const crypto = require('crypto');
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // 1. SANITIZER RECOGNITION
17
+ // ---------------------------------------------------------------------------
18
+
19
+ const SANITIZERS = {
20
+ xss: [
21
+ 'DOMPurify', 'sanitize', 'sanitizeHtml', 'escape', 'escapeHtml',
22
+ 'encodeURIComponent', 'encodeURI', 'textEncode', 'he.encode',
23
+ 'React.createElement', 'textContent',
24
+ ],
25
+ sql: [
26
+ 'parameterize', 'prepare', 'placeholder', 'bind', 'sql`', 'sql.query',
27
+ 'prisma.$queryRaw', 'pool.query', 'client.query',
28
+ ],
29
+ cmd: [
30
+ 'execFile', 'spawn', 'shell-quote', 'shellescape', 'sanitizeShell',
31
+ ],
32
+ path: [
33
+ 'path.resolve', 'path.join', 'path.normalize', 'sanitize',
34
+ ],
35
+ };
36
+
37
+ function isSanitized(expr, type) {
38
+ if (!expr || typeof expr !== 'string') return false;
39
+ const sanitizers = SANITIZERS[type] || [];
40
+ return sanitizers.some((s) => expr.includes(s));
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // 2. INCREMENTAL / DIFF-AWARE SCANNING
45
+ // ---------------------------------------------------------------------------
46
+
47
+ const HASH_CACHE_DIR = '.vibeguard/cache';
48
+
49
+ function loadHashCache(root) {
50
+ const p = path.join(root, HASH_CACHE_DIR, 'file-hashes.json');
51
+ if (fs.existsSync(p)) {
52
+ try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch {}
53
+ }
54
+ return {};
55
+ }
56
+
57
+ function saveHashCache(root, cache) {
58
+ const dir = path.join(root, HASH_CACHE_DIR);
59
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
60
+ fs.writeFileSync(path.join(dir, 'file-hashes.json'), JSON.stringify(cache, null, 2));
61
+ }
62
+
63
+ function hashContent(content) {
64
+ return crypto.createHash('sha256').update(content).digest('hex');
65
+ }
66
+
67
+ function getChangedFiles(root, allFiles) {
68
+ const cache = loadHashCache(root);
69
+ const changed = [];
70
+ const newCache = {};
71
+
72
+ for (const file of allFiles) {
73
+ try {
74
+ const content = fs.readFileSync(file, 'utf8');
75
+ const hash = hashContent(content);
76
+ newCache[file] = hash;
77
+ if (cache[file] !== hash) changed.push(file);
78
+ } catch {
79
+ // can't read, skip
80
+ }
81
+ }
82
+
83
+ saveHashCache(root, newCache);
84
+ return { changed, total: allFiles.length, cached: allFiles.length - changed.length };
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // 3. AUTH COVERAGE MAP
89
+ // ---------------------------------------------------------------------------
90
+
91
+ const ROUTE_RE = /(?:app|router|server)\.(?:get|post|put|delete|patch|all|use)\s*\(\s*['"`]([^'"`]+)['"`]/gi;
92
+ const MIDDLEWARE_RE = /(?:app|router)\.use\s*\(\s*['"`]([^'"`]+)['"`]/gi;
93
+ const AUTH_GUARD_RE = /(?:requireAuth|withAuth|protect|guard|authMiddleware|isAuthenticated|verifyToken|authenticate|clerkMiddleware|auth\(\)|getServerSession|getSession)/i;
94
+
95
+ function buildAuthCoverage(root, files) {
96
+ const routes = [];
97
+ const middlewares = [];
98
+
99
+ for (const file of files) {
100
+ try {
101
+ const content = fs.readFileSync(file, 'utf8');
102
+ const relPath = path.relative(root, file);
103
+
104
+ let m;
105
+ while ((m = ROUTE_RE.exec(content)) !== null) {
106
+ const routePath = m[1];
107
+ const beforeLines = content.slice(0, m.index).split('\n');
108
+ const lineNum = beforeLines.length;
109
+ const currentLine = content.slice(m.index, m.index + 300).split('\n')[0];
110
+ const hasAuth = AUTH_GUARD_RE.test(currentLine);
111
+ routes.push({
112
+ path: routePath,
113
+ file: relPath,
114
+ line: lineNum,
115
+ protected: hasAuth,
116
+ });
117
+ }
118
+
119
+ while ((m = MIDDLEWARE_RE.exec(content)) !== null) {
120
+ const mwPath = m[1];
121
+ const lines = content.slice(0, m.index).split('\n');
122
+ const lineNum = lines.length;
123
+ const surrounding = content.slice(m.index, m.index + 300);
124
+ const isAuth = AUTH_GUARD_RE.test(surrounding);
125
+ if (isAuth) {
126
+ middlewares.push({ path: mwPath, file: relPath, line: lineNum });
127
+ }
128
+ }
129
+ } catch {}
130
+ }
131
+
132
+ const unprotected = routes.filter((r) => !r.protected && r.path.startsWith('/api/'));
133
+ const protectedRoutes = routes.filter((r) => r.protected);
134
+
135
+ return {
136
+ totalRoutes: routes.length,
137
+ protectedRoutes: protectedRoutes.length,
138
+ unprotectedRoutes: unprotected.length,
139
+ unprotected,
140
+ middlewares,
141
+ coverage: routes.length > 0 ? Math.round((protectedRoutes.length / routes.length) * 100) : 100,
142
+ };
143
+ }
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // 4. PYTHON TAINT (basic — regex-based, no AST)
147
+ // ---------------------------------------------------------------------------
148
+
149
+ const PY_SOURCES = [
150
+ { re: /request\.(?:form|args|data|json|values|cookies|headers)(?:\.\w+)?\s*\(/g, name: 'request' },
151
+ { re: /request\.get\s*\(/g, name: 'request' },
152
+ { re: /\binput\s*\(/g, name: 'input()' },
153
+ { re: /os\.environ\.get\s*\(/g, name: 'os.environ' },
154
+ { re: /sys\.argv/g, name: 'sys.argv' },
155
+ ];
156
+
157
+ const PY_SINKS = [
158
+ { re: /cursor\.execute\s*\(/g, name: 'cursor.execute', type: 'sql' },
159
+ { re: /os\.system\s*\(/g, name: 'os.system', type: 'cmd' },
160
+ { re: /subprocess\.(?:run|call|Popen)\s*\(/g, name: 'subprocess', type: 'cmd' },
161
+ { re: /eval\s*\(/g, name: 'eval()', type: 'code' },
162
+ { re: /exec\s*\(/g, name: 'exec()', type: 'code' },
163
+ { re: /open\s*\(/g, name: 'open()', type: 'file' },
164
+ { re: /pickle\.loads?\s*\(/g, name: 'pickle', type: 'deserialization' },
165
+ ];
166
+
167
+ // Single-pass taint propagation (pure JS — no external parser, keeps VibeGuard
168
+ // zero-dependency and offline). Tracks tainted variables top-to-bottom:
169
+ // - a source assignment (v = request.form.get(...)) taints v;
170
+ // - an assignment whose RHS references a tainted var propagates the taint to
171
+ // the LHS (multi-hop: q = "..." + data → q is tainted);
172
+ // - reassigning a tainted var to a clean/sanitized value clears it;
173
+ // - a sink using a tainted var fires — UNLESS the value is parameterized
174
+ // (SQL) or wrapped in a sanitizer at the sink.
175
+ // This replaces the old "var appears anywhere between source and sink" heuristic,
176
+ // which false-positived when a tainted name merely appeared near an unrelated sink.
177
+ function analyzePythonTaint(content, lines, relPath) {
178
+ const findings = [];
179
+ const tainted = new Map(); // varName -> { name (source), line }
180
+ const seen = new Set(); // dedupe sink:line
181
+ const reOf = (v) => new RegExp('\\b' + escapeRe(v) + '\\b');
182
+
183
+ for (let i = 0; i < lines.length; i++) {
184
+ const line = lines[i];
185
+ const lineNo = i + 1;
186
+
187
+ // 1. Source assignment.
188
+ let matchedSource = null;
189
+ for (const src of PY_SOURCES) {
190
+ src.re.lastIndex = 0;
191
+ if (src.re.test(line)) { matchedSource = src.name; break; }
192
+ }
193
+ if (matchedSource) {
194
+ const v = extractVarName(line);
195
+ if (v) tainted.set(v, { name: matchedSource, line: lineNo });
196
+ }
197
+
198
+ // 2. Propagation / clearing via simple assignment `lhs = rhs`.
199
+ if (!matchedSource) {
200
+ const asn = /^\s*([A-Za-z_]\w*)\s*=\s*(.+)$/.exec(line);
201
+ if (asn) {
202
+ const lhs = asn[1];
203
+ const rhs = asn[2];
204
+ let carried = null;
205
+ for (const [tv, info] of tainted) {
206
+ if (reOf(tv).test(rhs) && !isSanitizedAtSink(rhs, tv)) { carried = info; break; }
207
+ }
208
+ if (carried) tainted.set(lhs, carried);
209
+ else if (tainted.has(lhs)) tainted.delete(lhs); // reassigned to clean value
210
+ }
211
+ }
212
+
213
+ // 3. Sinks.
214
+ for (const sink of PY_SINKS) {
215
+ sink.re.lastIndex = 0;
216
+ if (!sink.re.test(line)) continue;
217
+ for (const [tv, info] of tainted) {
218
+ if (!reOf(tv).test(line)) continue;
219
+ if (sink.type === 'sql' && isParameterizedExecute(line)) continue;
220
+ if (isSanitizedAtSink(line, tv)) continue;
221
+ const key = sink.name + ':' + lineNo;
222
+ if (seen.has(key)) break;
223
+ seen.add(key);
224
+ findings.push({
225
+ ruleId: 'py.taint-flow',
226
+ file: relPath,
227
+ line: lineNo,
228
+ column: 1,
229
+ severity: 'high',
230
+ confidence: 'medium',
231
+ title: `Python taint: ${info.name} → ${sink.name}`,
232
+ snippet: line.trim().slice(0, 120),
233
+ message: `User input (${info.name} at line ${info.line}) flows to ${sink.name} (line ${lineNo}) without sanitization.`,
234
+ fix: `Sanitize or validate the input before passing it to ${sink.name}.`,
235
+ owasp: 'A03:2025 Injection',
236
+ cwe: sink.type === 'sql' ? 'CWE-89' : sink.type === 'cmd' ? 'CWE-77' : 'CWE-20',
237
+ });
238
+ break;
239
+ }
240
+ }
241
+ }
242
+
243
+ return findings;
244
+ }
245
+
246
+ function escapeRe(s) {
247
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
248
+ }
249
+
250
+ // Parameterized DB call: a placeholder in the query AND a second argument to
251
+ // execute() = the driver binds/escapes the value, so it is NOT SQL injection.
252
+ function isParameterizedExecute(line) {
253
+ if (!/\.execute\s*\(/.test(line)) return false;
254
+ const hasPlaceholder = /%s|%\(|%d|\?|:\w+/.test(line);
255
+ const hasSecondArg = /\.execute\s*\([^)]*?,\s*[([{\w'"]/.test(line);
256
+ return hasPlaceholder && hasSecondArg;
257
+ }
258
+
259
+ // Python sanitizers that neutralize a tainted value. If the tainted var appears
260
+ // wrapped in one of these on the sink line, the flow is considered safe.
261
+ const PY_SANITIZER_FNS = [
262
+ 'int', 'float', 'bool', 'decimal.Decimal',
263
+ 'shlex.quote', 'pipes.quote', 'shlex.split',
264
+ 'html.escape', 'markupsafe.escape', 'escape', 'bleach.clean',
265
+ 'urllib.parse.quote', 'urllib.parse.quote_plus', 're.escape',
266
+ ];
267
+ function isSanitizedAtSink(sinkLine, varName) {
268
+ const v = varName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
269
+ for (const fn of PY_SANITIZER_FNS) {
270
+ const f = fn.replace(/\./g, '\\.');
271
+ // e.g. int(<var>) / shlex.quote(<var>) directly wrapping the tainted var
272
+ if (new RegExp('\\b' + f + '\\s*\\(\\s*' + v + '\\b').test(sinkLine)) return true;
273
+ }
274
+ return false;
275
+ }
276
+
277
+ function extractVarName(line) {
278
+ const m = /\b(\w+)\s*=\s*(?:request\.|input\(|os\.environ|sys\.argv)/.exec(line);
279
+ if (m) return m[1];
280
+ const m2 = /\b(?:for\s+)?(\w+)\s+in\s+request\./.exec(line);
281
+ if (m2) return m2[1];
282
+ return null;
283
+ }
284
+
285
+ module.exports = {
286
+ isSanitized,
287
+ SANITIZERS,
288
+ getChangedFiles,
289
+ loadHashCache,
290
+ saveHashCache,
291
+ hashContent,
292
+ buildAuthCoverage,
293
+ analyzePythonTaint,
294
+ };
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/integrity.js — self-integrity verification.
5
+ *
6
+ * A security tool that has been silently patched is worse than none: an
7
+ * attacker (or a compromised dependency's postinstall) could neuter a rule file
8
+ * or make the action firewall always return "allow". `self-check` used to only
9
+ * verify that modules *load* — this verifies their *content* against a manifest
10
+ * of SHA-256 hashes generated at publish time (scripts/gen-integrity.js).
11
+ *
12
+ * Limits (stated honestly): this detects tampering with the guard's source. It
13
+ * is not a full chain of trust — an attacker who rewrites both a module AND the
14
+ * manifest defeats it. It raises the bar and catches the common case (patched
15
+ * rules / neutered guard) that a load-only check misses. For a real trust
16
+ * anchor, verify the package's npm provenance / signature on install.
17
+ */
18
+
19
+ const crypto = require('crypto');
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+
23
+ // The modules whose integrity actually matters for security decisions.
24
+ const CRITICAL_MODULES = [
25
+ 'action-guard.js', 'shell-guard.js', 'interceptor.js', 'firewall.js',
26
+ 'pii.js', 'rules.js', 'scanner.js', 'engine.js',
27
+ 'mcp-audit.js', 'agent-scan.js', 'secure-prompt.js', 'ai-guard.js',
28
+ 'taint.js', 'taint-ast.js', 'ast.js',
29
+ ];
30
+
31
+ function hashFile(p) {
32
+ return crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
33
+ }
34
+
35
+ function computeManifest(srcDir) {
36
+ const hashes = {};
37
+ for (const f of CRITICAL_MODULES) {
38
+ const p = path.join(srcDir, f);
39
+ if (fs.existsSync(p)) hashes[f] = hashFile(p);
40
+ }
41
+ return { tool: 'vibeguard', generatedAt: new Date().toISOString(), algo: 'sha256', hashes };
42
+ }
43
+
44
+ // Verify the modules in `srcDir` against the shipped integrity.json.
45
+ function verifyIntegrity(srcDir) {
46
+ srcDir = srcDir || __dirname;
47
+ const manifestPath = path.join(srcDir, 'integrity.json');
48
+ let manifest;
49
+ try {
50
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
51
+ } catch {
52
+ return { available: false, intact: null, reason: 'no integrity manifest (integrity.json) found' };
53
+ }
54
+ const expected = (manifest && manifest.hashes) || {};
55
+ const modified = [];
56
+ const missing = [];
57
+ for (const [f, h] of Object.entries(expected)) {
58
+ const p = path.join(srcDir, f);
59
+ if (!fs.existsSync(p)) { missing.push(f); continue; }
60
+ let actual;
61
+ try { actual = hashFile(p); } catch { missing.push(f); continue; }
62
+ if (actual !== h) modified.push(f);
63
+ }
64
+ return {
65
+ available: true,
66
+ intact: modified.length === 0 && missing.length === 0,
67
+ modified,
68
+ missing,
69
+ checked: Object.keys(expected).length,
70
+ generatedAt: manifest.generatedAt,
71
+ };
72
+ }
73
+
74
+ module.exports = { verifyIntegrity, computeManifest, hashFile, CRITICAL_MODULES };
@@ -0,0 +1,22 @@
1
+ {
2
+ "tool": "vibeguard",
3
+ "generatedAt": "2026-07-13T18:38:30.609Z",
4
+ "algo": "sha256",
5
+ "hashes": {
6
+ "action-guard.js": "8b4142038b2614bd3da59c31cc9cecd7ccd1f002bec2e0a8f10bc423463cc625",
7
+ "shell-guard.js": "f16a0bd72d7e99feaae69bb20886ed2569d137bdc65240a6eacdfcf214831d9d",
8
+ "interceptor.js": "fd99360331111e7fbdee904206fd53989a7cbedbc784cd28c0a1523a41a3da7a",
9
+ "firewall.js": "06fb03919b17c62c5e42ca461e27f26a2aaf3a260a361fa1f721d0975e75b47e",
10
+ "pii.js": "51ea76de52b2c15d2cb34ab8125a5f67f725d1e7de43a4cef39136e25b276025",
11
+ "rules.js": "b14a78216654c399baa8d79b2c4052af5817dab524fa87056b74a8e25bb841f6",
12
+ "scanner.js": "3521b22024b60470b6969d61272e698c07bcdb7d7ccfbbf1e8885feeddb1961d",
13
+ "engine.js": "23666926e0e961633039b3fa7341e55e4607e027ea4e1a57773363df71dc19d3",
14
+ "mcp-audit.js": "8f38b2738ffedc23f61601a1c03d3cbaac8a38fb19390a898ffe32b30bf8ffc4",
15
+ "agent-scan.js": "018813166eb1e370bf452efaa92020cd4baea0a20f3826fed3f95ded312aa5c7",
16
+ "secure-prompt.js": "a4d8203ad2292e57b29f75a700f2837f12ba6c9067fd4d5f6731e55203e184b2",
17
+ "ai-guard.js": "9dd2c524dd704bbba69aacf7076e76ac966c6e0c773ee4b04ed7c8fb889db006",
18
+ "taint.js": "958decf89c32993e2c9a057ef7be9bbe592e7525fd0daa5fc5a278dcafe957af",
19
+ "taint-ast.js": "4c8dd6f365b7fd6c610fb4643619753531f2b5ecdc16feee135e2fccc66a2ad3",
20
+ "ast.js": "cba4db68368831845ed6c4481ea1e44a45c41cddef68993dc4c5908276636225"
21
+ }
22
+ }