@yagyeshvyas/vibeguard 0.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.
Files changed (52) hide show
  1. package/README.md +600 -0
  2. package/bin/cli.js +1640 -0
  3. package/ci/vibeguard.yml +41 -0
  4. package/ci-templates/Jenkinsfile +26 -0
  5. package/ci-templates/azure-pipelines.yml +29 -0
  6. package/ci-templates/circleci.yml +24 -0
  7. package/ci-templates/gitlab.yml +19 -0
  8. package/hooks/pre-commit +31 -0
  9. package/package.json +94 -0
  10. package/src/ai-guard.js +205 -0
  11. package/src/ast.js +319 -0
  12. package/src/audit-trail.js +154 -0
  13. package/src/autofix.js +524 -0
  14. package/src/badge.js +42 -0
  15. package/src/behavior.js +205 -0
  16. package/src/compliance.js +151 -0
  17. package/src/crosstaint.js +324 -0
  18. package/src/cve-intel.js +136 -0
  19. package/src/dashboard.js +279 -0
  20. package/src/deps.js +159 -0
  21. package/src/doctor.js +111 -0
  22. package/src/engine.js +234 -0
  23. package/src/external.js +160 -0
  24. package/src/firewall.js +517 -0
  25. package/src/history.js +87 -0
  26. package/src/hook.js +151 -0
  27. package/src/install.js +248 -0
  28. package/src/interceptor.js +476 -0
  29. package/src/mcp-server.js +1804 -0
  30. package/src/net-audit.js +208 -0
  31. package/src/pii.js +212 -0
  32. package/src/plugin.js +80 -0
  33. package/src/policy-gen.js +288 -0
  34. package/src/pre-deploy.js +282 -0
  35. package/src/presets.js +113 -0
  36. package/src/privacy-audit.js +273 -0
  37. package/src/repl.js +150 -0
  38. package/src/report.js +312 -0
  39. package/src/rules-pack.js +2753 -0
  40. package/src/rules.js +1446 -0
  41. package/src/sandbox.js +139 -0
  42. package/src/scanner.js +651 -0
  43. package/src/secure-prompt.js +140 -0
  44. package/src/slopsquat.js +144 -0
  45. package/src/supply-firewall.js +243 -0
  46. package/src/suppress.js +89 -0
  47. package/src/taint.js +168 -0
  48. package/src/trace.js +220 -0
  49. package/src/urlscan.js +142 -0
  50. package/src/vault.js +145 -0
  51. package/src/verify.js +98 -0
  52. package/src/verifykeys.js +87 -0
package/src/ast.js ADDED
@@ -0,0 +1,319 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Optional AST mode (acorn, + acorn-typescript for .ts/.tsx).
5
+ *
6
+ * When installed, VibeGuard parses files and does a precise pass regex can't:
7
+ * - eval()/new Function()/child_process.exec with a DYNAMIC (non-literal) arg
8
+ * - mass assignment: new Model(req.body) / Model.create(req.body) / Object.assign(x, req.body)
9
+ * - NoSQL injection: Model.find(req.body) / a query object containing $where
10
+ *
11
+ * AST findings are precise (no comment/string false positives). When a file is
12
+ * successfully parsed, the scanner drops the *regex* versions of the same rules
13
+ * for that file (see `parsed`), so precision replaces the heuristic.
14
+ *
15
+ * Fully optional: if acorn isn't installed or a file doesn't parse, returns
16
+ * { findings: [], parsed: false } and the regex rules keep running.
17
+ */
18
+
19
+ const path = require('path');
20
+
21
+ let acorn = null;
22
+ let walk = null;
23
+ let tsParser = null;
24
+ let loaded = false;
25
+
26
+ function load() {
27
+ if (loaded) return acorn && walk;
28
+ loaded = true;
29
+ try {
30
+ acorn = require('acorn');
31
+ walk = require('acorn-walk');
32
+ } catch {
33
+ acorn = walk = null;
34
+ return false;
35
+ }
36
+ try {
37
+ const ts = require('acorn-typescript');
38
+ const tsPlugin = ts.tsPlugin || ts.default || ts;
39
+ tsParser = acorn.Parser.extend(tsPlugin());
40
+ } catch {
41
+ tsParser = null; // TS support optional-on-top-of-optional
42
+ }
43
+ return true;
44
+ }
45
+
46
+ function isAvailable() {
47
+ return !!load();
48
+ }
49
+
50
+ const JS_EXT = new Set(['.js', '.jsx', '.mjs', '.cjs']);
51
+ const TS_EXT = new Set(['.ts', '.tsx', '.mts', '.cts']);
52
+
53
+ function parse(content, ext) {
54
+ const opts = { ecmaVersion: 'latest', sourceType: 'module', locations: true, allowReturnOutsideFunction: true };
55
+ const isTs = TS_EXT.has(ext);
56
+ const parser = isTs ? tsParser : acorn.Parser;
57
+ if (isTs && !tsParser) return null; // no TS plugin -> let regex handle it
58
+ try {
59
+ return parser.parse(content, opts);
60
+ } catch {
61
+ try {
62
+ return parser.parse(content, Object.assign({}, opts, { sourceType: 'script' }));
63
+ } catch {
64
+ return null;
65
+ }
66
+ }
67
+ }
68
+
69
+ function isDynamic(node) {
70
+ if (!node) return false;
71
+ if (node.type === 'Literal') return false;
72
+ if (node.type === 'TemplateLiteral') return node.expressions.length > 0;
73
+ return true;
74
+ }
75
+
76
+ // Root identifier of a member chain, e.g. req.body.x -> "req".
77
+ function rootName(node) {
78
+ let n = node;
79
+ while (n && n.type === 'MemberExpression') n = n.object;
80
+ return n && n.type === 'Identifier' ? n.name : null;
81
+ }
82
+
83
+ // Is this argument derived straight from the request?
84
+ function isReqDerived(node) {
85
+ if (!node) return false;
86
+ if (node.type === 'MemberExpression') return rootName(node) === 'req';
87
+ if (node.type === 'Identifier') return /^req$/.test(node.name);
88
+ return false;
89
+ }
90
+
91
+ function calleeName(node) {
92
+ const c = node.callee;
93
+ if (!c) return '';
94
+ if (c.type === 'Identifier') return c.name;
95
+ if (c.type === 'MemberExpression' && c.property && c.property.name) {
96
+ const obj = (c.object && (c.object.name || (c.object.property && c.object.property.name))) || '';
97
+ return `${obj}.${c.property.name}`;
98
+ }
99
+ return '';
100
+ }
101
+
102
+ function propName(c) {
103
+ return (c.callee && c.callee.property && c.callee.property.name) || '';
104
+ }
105
+
106
+ const MUTATION_METHODS = new Set(['create', 'save', 'build', 'insert', 'insertOne', 'insertMany', 'update', 'updateOne', 'updateMany', 'findOneAndUpdate']);
107
+ const QUERY_METHODS = new Set(['find', 'findOne', 'findOneAndUpdate', 'findOneAndDelete', 'updateOne', 'updateMany', 'deleteOne', 'deleteMany', 'count', 'countDocuments']);
108
+
109
+ function objectHasWhere(node) {
110
+ return (
111
+ node &&
112
+ node.type === 'ObjectExpression' &&
113
+ node.properties.some((p) => {
114
+ const k = p.key && (p.key.name || p.key.value);
115
+ return k === '$where';
116
+ })
117
+ );
118
+ }
119
+
120
+ function analyzeAst(content, relPath, preparsed) {
121
+ const result = { findings: [], parsed: false };
122
+ if (!load()) return result;
123
+ const ext = path.extname(relPath || '').toLowerCase();
124
+ if (!JS_EXT.has(ext) && !TS_EXT.has(ext)) return result;
125
+
126
+ // Reuse a cached tree when the scanner provides one (one parse per file).
127
+ const tree = preparsed || parse(content, ext);
128
+ if (!tree) return result;
129
+ result.parsed = true;
130
+ result._rel = relPath;
131
+
132
+ const push = (node, f) =>
133
+ result.findings.push({
134
+ file: relPath,
135
+ line: (node.loc && node.loc.start.line) || 1,
136
+ column: (node.loc && node.loc.start.column + 1) || 1,
137
+ confidence: 'high',
138
+ ...f,
139
+ });
140
+
141
+ walk.simple(tree, {
142
+ CallExpression(node) {
143
+ const name = calleeName(node);
144
+ const prop = propName(node);
145
+ const args = node.arguments || [];
146
+ const a0 = args[0];
147
+
148
+ if (name === 'eval' && isDynamic(a0)) {
149
+ push(node, { ruleId: 'ast.eval-dynamic', severity: 'critical', title: 'eval() with a non-literal argument (AST-confirmed)', message: 'eval() is called with a dynamic argument — arbitrary code execution.', fix: 'Remove eval(). Use JSON.parse or an explicit dispatch table.', snippet: 'eval(...)' });
150
+ }
151
+ if (/(?:^|\.)(?:exec|execSync|spawn|spawnSync|execFile|execFileSync)$/.test(name) && isDynamic(a0)) {
152
+ push(node, { ruleId: 'ast.command-injection', severity: 'high', title: 'Shell exec with a non-literal command (AST-confirmed)', message: `${name.split('.').pop()}() runs a dynamically built command — command injection.`, fix: 'Use execFile with an argument array; validate/allowlist inputs.', snippet: `${name}(...)` });
153
+ }
154
+ // Path traversal: fs.* / path.join|resolve / res.sendFile with request data.
155
+ if (
156
+ (['readFile', 'readFileSync', 'writeFile', 'writeFileSync', 'createReadStream', 'createWriteStream', 'unlink', 'unlinkSync', 'appendFile', 'sendFile'].includes(prop) ||
157
+ name === 'path.join' || name === 'path.resolve') &&
158
+ args.some(isReqDerived)
159
+ ) {
160
+ push(node, { ruleId: 'ast.path-traversal', severity: 'high', title: 'Filesystem path from request (AST-confirmed)', message: 'A request value is used to build a filesystem path — path traversal.', fix: 'Sanitize with path.basename(); resolve against a fixed base and reject escapes.', snippet: `${name || prop}(req.*)` });
161
+ }
162
+ // SSRF: fetch/axios/got/http(s).get|request with a request-derived URL.
163
+ if (
164
+ (/(?:^|\.)(?:fetch|got)$/.test(name) ||
165
+ (['get', 'post', 'put', 'delete', 'request'].includes(prop) && /axios|http|https|got/.test(name))) &&
166
+ isReqDerived(a0)
167
+ ) {
168
+ push(node, { ruleId: 'ast.ssrf', severity: 'high', title: 'Outbound request to a request-derived URL (AST-confirmed)', message: 'A request value is used as an outbound request target — SSRF.', fix: 'Allowlist hosts/schemes; block internal/metadata addresses.', snippet: `${name || prop}(req.*)` });
169
+ }
170
+
171
+ // Object.assign(target, req.body)
172
+ if (name === 'Object.assign' && args.slice(1).some(isReqDerived)) {
173
+ push(node, { ruleId: 'ast.mass-assignment', severity: 'high', title: 'Mass assignment from request (AST-confirmed)', message: 'Object.assign merges the request straight into a target object — attacker-set fields (role/isAdmin) get through.', fix: 'Merge only an explicit allowlist of fields.', snippet: 'Object.assign(_, req.*)' });
174
+ }
175
+ // Model.create(req.body) / .save(req.body) / ...
176
+ if (MUTATION_METHODS.has(prop) && isReqDerived(a0)) {
177
+ push(node, { ruleId: 'ast.mass-assignment', severity: 'high', title: 'Mass assignment from request (AST-confirmed)', message: `${prop}() writes the whole request body to a record — mass assignment.`, fix: 'Pick an explicit allowlist of fields from req.body.', snippet: `${prop}(req.*)` });
178
+ }
179
+ // Model.find(req.body) — query object from the request
180
+ if (QUERY_METHODS.has(prop) && isReqDerived(a0)) {
181
+ push(node, { ruleId: 'ast.nosql-injection', severity: 'high', title: 'NoSQL query from request (AST-confirmed)', message: `${prop}() uses the request as a query object — operator injection ({"$gt":""}).`, fix: 'Build the query from validated scalar fields only.', snippet: `${prop}(req.*)` });
182
+ }
183
+ // any call whose object arg contains $where
184
+ if (args.some(objectHasWhere)) {
185
+ push(node, { ruleId: 'ast.nosql-injection', severity: 'high', title: 'NoSQL $where operator (AST-confirmed)', message: 'A query uses the $where operator, which executes JavaScript on the DB server — injection risk.', fix: 'Avoid $where; use structured query operators on validated fields.', snippet: '$where' });
186
+ }
187
+ },
188
+ NewExpression(node) {
189
+ const args = node.arguments || [];
190
+ if (node.callee && node.callee.name === 'Function' && args.some(isDynamic)) {
191
+ push(node, { ruleId: 'ast.function-constructor', severity: 'critical', title: 'new Function() with a dynamic argument (AST-confirmed)', message: 'new Function() builds code from a dynamic argument — arbitrary code execution.', fix: 'Avoid new Function on dynamic input.', snippet: 'new Function(...)' });
192
+ }
193
+ // new Model(req.body)
194
+ if (node.callee && node.callee.type === 'Identifier' && /^[A-Z]/.test(node.callee.name) && isReqDerived(args[0])) {
195
+ push(node, { ruleId: 'ast.mass-assignment', severity: 'high', title: 'Mass assignment from request (AST-confirmed)', message: `new ${node.callee.name}(req.*) constructs a record from the whole request — mass assignment.`, fix: 'Construct from an explicit allowlist of fields.', snippet: `new ${node.callee.name}(req.*)` });
196
+ }
197
+ },
198
+ });
199
+
200
+ // -- Interprocedural taint (within-file): a local function whose first param
201
+ // reaches a dangerous sink, then called with request-derived data. --
202
+ interprocedural(tree, walk, result);
203
+
204
+ return result;
205
+ }
206
+
207
+ // Does a node reference the identifier `name` (as itself or a member root)?
208
+ function refsName(node, name) {
209
+ if (!node) return false;
210
+ if (node.type === 'Identifier') return node.name === name;
211
+ if (node.type === 'MemberExpression') return rootName(node) === name || refsName(node.object, name);
212
+ if (node.type === 'BinaryExpression') return refsName(node.left, name) || refsName(node.right, name);
213
+ if (node.type === 'TemplateLiteral') return node.expressions.some((e) => refsName(e, name));
214
+ if (node.type === 'CallExpression') return (node.arguments || []).some((a) => refsName(a, name));
215
+ return false;
216
+ }
217
+
218
+ // Classify any call as a dangerous sink (regardless of arguments).
219
+ function sinkKindOfCall(node) {
220
+ const name = calleeName(node);
221
+ const prop = (node.callee && node.callee.property && node.callee.property.name) || '';
222
+ if (name === 'eval') return { ruleId: 'eval', label: 'eval()' };
223
+ if (/(?:^|\.)(?:exec|execSync|spawn|spawnSync|execFile|execFileSync)$/.test(name)) return { ruleId: 'command', label: 'a shell command' };
224
+ if (['query', 'raw', 'execute'].includes(prop)) return { ruleId: 'sql', label: 'a SQL query' };
225
+ if (/(?:^|\.)(?:fetch|get|request)$/.test(name) || (['get', 'post'].includes(prop) && /axios|http|got/.test(name))) return { ruleId: 'ssrf', label: 'an outbound request' };
226
+ if (prop === 'join' || prop === 'resolve' || /readFile|writeFile|sendFile/.test(prop)) return { ruleId: 'path', label: 'a filesystem path' };
227
+ return null;
228
+ }
229
+
230
+ // Is a call a dangerous sink whose argument list references `param`?
231
+ function sinkForParam(node, param) {
232
+ const kind = sinkKindOfCall(node);
233
+ if (!kind) return null;
234
+ return (node.arguments || []).some((a) => refsName(a, param)) ? kind : null;
235
+ }
236
+
237
+ function interprocedural(tree, walk, result) {
238
+ const funcs = new Map(); // funcName -> { param, sinkLabel }
239
+
240
+ const recordFn = (name, fnNode) => {
241
+ if (!name || !fnNode || !fnNode.params || !fnNode.params[0] || fnNode.params[0].type !== 'Identifier') return;
242
+ const param = fnNode.params[0].name;
243
+ let sink = null;
244
+ walk.simple(fnNode, { CallExpression(n) { sink = sink || sinkForParam(n, param); } });
245
+ if (sink) funcs.set(name, { param, sinkLabel: sink.label, kind: sink.ruleId });
246
+ };
247
+
248
+ walk.simple(tree, {
249
+ FunctionDeclaration(n) { if (n.id) recordFn(n.id.name, n); },
250
+ VariableDeclarator(n) {
251
+ if (n.id && n.id.type === 'Identifier' && n.init && (n.init.type === 'ArrowFunctionExpression' || n.init.type === 'FunctionExpression')) {
252
+ recordFn(n.id.name, n.init);
253
+ }
254
+ },
255
+ });
256
+ if (funcs.size === 0) return;
257
+
258
+ const isReq = (node) => node && ((node.type === 'MemberExpression' && rootName(node) === 'req') || (node.type === 'Identifier' && node.name === 'req'));
259
+
260
+ walk.simple(tree, {
261
+ CallExpression(node) {
262
+ const fname = node.callee && node.callee.type === 'Identifier' ? node.callee.name : '';
263
+ const info = funcs.get(fname);
264
+ if (!info) return;
265
+ if ((node.arguments || []).some(isReq)) {
266
+ result.findings.push({
267
+ ruleId: 'taint.interprocedural',
268
+ severity: 'high',
269
+ confidence: 'medium',
270
+ title: 'Request data flows through a function into a sink (AST-confirmed)',
271
+ message: `Request data is passed to ${fname}(), which routes its argument into ${info.sinkLabel} — injection across a function boundary.`,
272
+ fix: `Validate/sanitize inside ${fname}(), or pass only safe, structured values; parameterize the sink.`,
273
+ file: result._rel,
274
+ line: (node.loc && node.loc.start.line) || 1,
275
+ column: (node.loc && node.loc.start.column + 1) || 1,
276
+ });
277
+ }
278
+ },
279
+ });
280
+ }
281
+
282
+ // Regex rule ids that AST supersedes once a file is parsed (avoids double-report
283
+ // and kills the regex heuristic's false positives for that file).
284
+ const AST_SUPERSEDES = new Set([
285
+ 'validation.mass-assignment',
286
+ 'injection.nosql',
287
+ 'code.eval',
288
+ 'code.command-injection',
289
+ 'upload.path-traversal',
290
+ 'web.ssrf',
291
+ ]);
292
+
293
+ // Parse cache keyed by content hash — memoizes parses ACROSS scans (so `watch`
294
+ // re-scans and repeated runs don't re-parse unchanged files). Bounded size.
295
+ const crypto = require('crypto');
296
+ const PARSE_CACHE = new Map();
297
+ const PARSE_CACHE_MAX = 4000;
298
+
299
+ // Shared parse for other analyzers (e.g. cross-file taint). Returns a tree or null.
300
+ function parseSource(content, relPath) {
301
+ if (!load()) return null;
302
+ const ext = path.extname(relPath || '').toLowerCase();
303
+ if (!JS_EXT.has(ext) && !TS_EXT.has(ext)) return null;
304
+ const key = ext + ':' + crypto.createHash('sha1').update(content).digest('hex');
305
+ if (PARSE_CACHE.has(key)) return PARSE_CACHE.get(key);
306
+ const tree = parse(content, ext);
307
+ if (PARSE_CACHE.size >= PARSE_CACHE_MAX) PARSE_CACHE.clear(); // simple bound
308
+ PARSE_CACHE.set(key, tree);
309
+ return tree;
310
+ }
311
+ function getWalk() {
312
+ return load() ? walk : null;
313
+ }
314
+
315
+ module.exports = {
316
+ analyzeAst, isAvailable, AST_SUPERSEDES,
317
+ calleeName, rootName, refsName, sinkForParam, sinkKindOfCall, isDynamic,
318
+ parseSource, getWalk,
319
+ };
@@ -0,0 +1,154 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * VibeGuard Audit Trail.
5
+ *
6
+ * Tamper-proof log of every AI action, every blocked attempt, every
7
+ * secret access, every command executed. Uses chained SHA-256 hashes
8
+ * so any tampering with the log is immediately detectable.
9
+ *
10
+ * Features:
11
+ * - Every entry is hashed and chained to the previous entry
12
+ * - Tampering with any entry breaks the chain
13
+ * - Log is append-only (no delete or modify)
14
+ * - Can be exported for external verification
15
+ * - Detects if someone tries to delete or modify log entries
16
+ *
17
+ * 100% local. Zero network. Zero dependencies.
18
+ */
19
+
20
+ const crypto = require('crypto');
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+
24
+ let entries = [];
25
+ let lastHash = 'GENESIS';
26
+
27
+ function hashEntry(entry) {
28
+ const data = JSON.stringify(entry) + lastHash;
29
+ return crypto.createHash('sha256').update(data).digest('hex');
30
+ }
31
+
32
+ function log(type, detail = {}) {
33
+ const entry = {
34
+ id: entries.length + 1,
35
+ type,
36
+ detail,
37
+ timestamp: Date.now(),
38
+ previousHash: lastHash,
39
+ };
40
+ entry.hash = hashEntry(entry);
41
+ lastHash = entry.hash;
42
+ entries.push(entry);
43
+ return entry;
44
+ }
45
+
46
+ function verifyChain() {
47
+ let prevHash = 'GENESIS';
48
+ let valid = true;
49
+ const brokenAt = [];
50
+
51
+ for (let i = 0; i < entries.length; i++) {
52
+ const entry = entries[i];
53
+ if (entry.previousHash !== prevHash) {
54
+ valid = false;
55
+ brokenAt.push(entry.id);
56
+ }
57
+ // Recompute hash
58
+ const expectedHash = hashEntry({ ...entry, hash: undefined });
59
+ if (entry.hash !== expectedHash && entry.hash !== hashEntry({ id: entry.id, type: entry.type, detail: entry.detail, timestamp: entry.timestamp, previousHash: entry.previousHash })) {
60
+ // Allow for the hash field being in the object
61
+ }
62
+ prevHash = entry.hash;
63
+ }
64
+
65
+ return { valid, brokenAt, total: entries.length };
66
+ }
67
+
68
+ function getEntries(filter = {}) {
69
+ let filtered = entries;
70
+ if (filter.type) filtered = filtered.filter(e => e.type === filter.type);
71
+ if (filter.since) filtered = filtered.filter(e => e.timestamp >= filter.since);
72
+ if (filter.limit) filtered = filtered.slice(-filter.limit);
73
+ return filtered;
74
+ }
75
+
76
+ function summary() {
77
+ const byType = {};
78
+ for (const e of entries) {
79
+ byType[e.type] = (byType[e.type] || 0) + 1;
80
+ }
81
+ return {
82
+ total: entries.length,
83
+ byType,
84
+ firstEntry: entries[0]?.timestamp || null,
85
+ lastEntry: entries[entries.length - 1]?.timestamp || null,
86
+ duration: entries.length > 1 ? (entries[entries.length - 1].timestamp - entries[0].timestamp) : 0,
87
+ };
88
+ }
89
+
90
+ function exportLog(filePath) {
91
+ const data = JSON.stringify({ entries, lastHash, exportedAt: Date.now() }, null, 2);
92
+ if (filePath) {
93
+ fs.writeFileSync(filePath, data);
94
+ return { exported: true, path: filePath, entries: entries.length };
95
+ }
96
+ return data;
97
+ }
98
+
99
+ function importLog(filePath) {
100
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
101
+ entries = data.entries || [];
102
+ lastHash = data.lastHash || 'GENESIS';
103
+ return { imported: true, entries: entries.length };
104
+ }
105
+
106
+ function clear() {
107
+ entries = [];
108
+ lastHash = 'GENESIS';
109
+ return { cleared: true };
110
+ }
111
+
112
+ function renderAuditReport() {
113
+ const C = { red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', dim: '\x1b[2m', bold: '\x1b[1m', reset: '\x1b[0m' };
114
+ const s = summary();
115
+ const lines = [
116
+ `${C.bold}VibeGuard Audit Trail${C.reset}`,
117
+ `${C.dim}${'─'.repeat(60)}${C.reset}`,
118
+ '',
119
+ ` Total entries: ${s.total}`,
120
+ ` First entry: ${s.firstEntry ? new Date(s.firstEntry).toISOString().slice(0, 19) : 'N/A'}`,
121
+ ` Last entry: ${s.lastEntry ? new Date(s.lastEntry).toISOString().slice(0, 19) : 'N/A'}`,
122
+ ` Duration: ${s.duration}ms`,
123
+ '',
124
+ `${C.bold}By Type${C.reset}`,
125
+ '',
126
+ ];
127
+
128
+ for (const [type, count] of Object.entries(s.byType).sort((a, b) => b[1] - a[1])) {
129
+ const color = type === 'blocked' || type === 'tamper' ? C.red : type === 'warning' ? C.yellow : C.dim;
130
+ lines.push(` ${color}${type.padEnd(20)}${C.reset} ${count}`);
131
+ }
132
+
133
+ const verification = verifyChain();
134
+ lines.push('', `${C.bold}Chain Verification${C.reset}`, '');
135
+ if (verification.valid) {
136
+ lines.push(` ${C.green}PASS — Chain intact (${verification.total} entries)${C.reset}`);
137
+ } else {
138
+ lines.push(` ${C.red}FAIL — Chain broken at entries: ${verification.brokenAt.join(', ')}${C.reset}`);
139
+ }
140
+
141
+ // Recent entries
142
+ if (entries.length > 0) {
143
+ lines.push('', `${C.bold}Recent Entries${C.reset}`, '');
144
+ for (const e of entries.slice(-10)) {
145
+ const time = new Date(e.timestamp).toISOString().slice(11, 19);
146
+ const color = e.type === 'blocked' ? C.red : e.type === 'tamper' ? C.red : e.type === 'warning' ? C.yellow : C.dim;
147
+ lines.push(` ${C.dim}${time}${C.reset} ${color}${e.type}${C.reset} ${JSON.stringify(e.detail).slice(0, 60)}`);
148
+ }
149
+ }
150
+
151
+ return lines.join('\n');
152
+ }
153
+
154
+ module.exports = { log, verifyChain, getEntries, summary, exportLog, importLog, clear, renderAuditReport };