@yagyeshvyas/vibeguard 1.3.0 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/.vibeguard-mcp.example.json +51 -0
  2. package/CHANGELOG.md +604 -216
  3. package/MCP-FIREWALL.md +296 -0
  4. package/README.md +355 -31
  5. package/bin/cli.js +355 -27
  6. package/bin/cmd-agent-monitor.js +45 -0
  7. package/bin/cmd-agent-risk.js +64 -0
  8. package/bin/cmd-gif.js +62 -0
  9. package/bin/cmd-git-scan.js +74 -0
  10. package/bin/cmd-llm-proxy.js +164 -0
  11. package/bin/cmd-mcp-firewall.js +191 -0
  12. package/bin/cmd-pentest.js +103 -0
  13. package/bin/cmd-platform.js +137 -0
  14. package/bin/cmd-pr-scan.js +135 -0
  15. package/bin/cmd-sbom-diff.js +38 -0
  16. package/bin/cmd-skill-scan.js +35 -0
  17. package/docs/AISVS.md +25 -0
  18. package/docs/ARCHITECTURE.md +81 -0
  19. package/docs/INSTALLATION.md +139 -0
  20. package/docs/WINDOWS.md +74 -0
  21. package/docs/security-policy.strict.example.json +134 -0
  22. package/docs/security-policy.strict.example.pub.pem +3 -0
  23. package/package.json +45 -7
  24. package/src/.vibeguard/cache/file-hashes.json +60 -0
  25. package/src/.vibeguard/latest-snapshot.json +36 -0
  26. package/src/.vibeguard/mcp-pins.json +1 -0
  27. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +428 -0
  28. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +344 -0
  29. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +279 -0
  30. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +297 -0
  31. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +151 -0
  32. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +299 -0
  33. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +65 -0
  34. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +2051 -0
  35. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +168 -0
  36. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +362 -0
  37. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +150 -0
  38. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +1611 -0
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +164 -0
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +292 -0
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +144 -0
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +220 -0
  43. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +428 -0
  44. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +344 -0
  45. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +297 -0
  46. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +299 -0
  47. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +37 -0
  48. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +2055 -0
  49. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +168 -0
  50. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +362 -0
  51. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +220 -0
  52. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +428 -0
  53. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +344 -0
  54. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +279 -0
  55. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +297 -0
  56. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +151 -0
  57. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +299 -0
  58. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +65 -0
  59. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +2055 -0
  60. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +168 -0
  61. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +362 -0
  62. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +150 -0
  63. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +1611 -0
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +164 -0
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +292 -0
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +144 -0
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +220 -0
  68. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +428 -0
  69. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +344 -0
  70. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +279 -0
  71. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +297 -0
  72. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +151 -0
  73. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +299 -0
  74. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +65 -0
  75. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +2054 -0
  76. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +168 -0
  77. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +362 -0
  78. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +150 -0
  79. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +1611 -0
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +164 -0
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +292 -0
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +144 -0
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +220 -0
  84. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +428 -0
  85. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +344 -0
  86. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +297 -0
  87. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +299 -0
  88. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +37 -0
  89. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +2055 -0
  90. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +168 -0
  91. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +362 -0
  92. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +220 -0
  93. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +428 -0
  94. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +344 -0
  95. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +297 -0
  96. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +33 -0
  97. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +2055 -0
  98. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +1611 -0
  99. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +292 -0
  100. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +220 -0
  101. package/src/.vibeguard-baseline.json +5226 -0
  102. package/src/action-guard.js +84 -6
  103. package/src/agent-monitor.js +262 -0
  104. package/src/agent-policy.js +642 -0
  105. package/src/agent-risk.js +271 -0
  106. package/src/agentic.js +1513 -0
  107. package/src/ast.js +165 -7
  108. package/src/audit-trail.js +212 -67
  109. package/src/auto.js +427 -427
  110. package/src/autofix.js +11 -4
  111. package/src/bundles.js +198 -0
  112. package/src/daemon.js +343 -343
  113. package/src/dashboard.js +278 -278
  114. package/src/engine.js +3 -0
  115. package/src/entropy.js +187 -0
  116. package/src/firewall.js +19 -3
  117. package/src/gif.js +134 -0
  118. package/src/gitscan.js +282 -0
  119. package/src/hook.js +151 -151
  120. package/src/injection-decode.js +136 -0
  121. package/src/install.js +298 -280
  122. package/src/integrity.js +16 -1
  123. package/src/integrity.json +43 -13
  124. package/src/interceptor.js +12 -9
  125. package/src/llm-proxy.js +986 -0
  126. package/src/mcp-audit.js +61 -5
  127. package/src/mcp-firewall.js +971 -0
  128. package/src/mcp-server.js +2500 -2047
  129. package/src/obfuscation.js +315 -0
  130. package/src/owasp-agentic.js +314 -0
  131. package/src/pentest.js +589 -0
  132. package/src/pii.js +4 -0
  133. package/src/platform/aisvs.js +38 -0
  134. package/src/platform/approval.js +187 -0
  135. package/src/platform/canonical.js +73 -0
  136. package/src/platform/contracts.js +158 -0
  137. package/src/platform/delegation.js +73 -0
  138. package/src/platform/http-gateway.js +177 -0
  139. package/src/platform/identity.js +253 -0
  140. package/src/platform/jwt.js +86 -0
  141. package/src/platform/mcp-http-bridge.js +199 -0
  142. package/src/platform/memory-guard.js +64 -0
  143. package/src/platform/os-sandbox.js +144 -0
  144. package/src/platform/policy.js +332 -0
  145. package/src/platform/sandbox-manager.js +92 -0
  146. package/src/platform/signed-audit.js +357 -0
  147. package/src/platform/ssrf.js +129 -0
  148. package/src/plugin.js +182 -168
  149. package/src/pre-deploy.js +170 -55
  150. package/src/privacy-audit.js +272 -272
  151. package/src/repl.js +150 -150
  152. package/src/report.js +7 -1
  153. package/src/routes.js +1210 -0
  154. package/src/rules-2026.js +1407 -0
  155. package/src/rules-pack.js +3068 -3019
  156. package/src/rules.js +376 -60
  157. package/src/sandbox.js +200 -10
  158. package/src/sbom.js +193 -164
  159. package/src/scanner.js +189 -33
  160. package/src/shell-guard.js +11 -0
  161. package/src/skill-scan.js +477 -0
  162. package/src/slopsquat.js +144 -144
  163. package/src/surface.js +408 -0
  164. package/src/taint-ast.js +204 -37
  165. package/src/taint.js +15 -3
  166. package/src/tokenlean.js +579 -0
  167. package/src/trace.js +220 -220
package/src/ast.js CHANGED
@@ -21,8 +21,132 @@ const path = require('path');
21
21
  let acorn = null;
22
22
  let walk = null;
23
23
  let tsParser = null;
24
+ let jsxParser = null;
24
25
  let loaded = false;
25
26
 
27
+ // JSX walkers. acorn-walk's base has no visitor for JSX node types, so every
28
+ // walk.simple() over a .jsx/.tsx tree threw "No walker function defined for node
29
+ // type JSXElement" — which silently degraded the AST pass for every React/Next
30
+ // component (i.e. most files in the projects this tool exists to scan). These
31
+ // visitors are merged into walk.base so all existing walks (ast pass, intra-file
32
+ // taint, cross-file taint, import graphs) support JSX without touching them.
33
+ const JSX_WALKERS = {
34
+ JSXElement(node, st, c) {
35
+ c(node.openingElement, st);
36
+ for (const child of node.children || []) c(child, st);
37
+ if (node.closingElement) c(node.closingElement, st);
38
+ },
39
+ JSXFragment(node, st, c) {
40
+ c(node.openingFragment, st);
41
+ for (const child of node.children || []) c(child, st);
42
+ if (node.closingFragment) c(node.closingFragment, st);
43
+ },
44
+ JSXOpeningElement(node, st, c) {
45
+ c(node.name, st);
46
+ for (const attr of node.attributes || []) c(attr, st);
47
+ },
48
+ JSXClosingElement(node, st, c) {
49
+ c(node.name, st);
50
+ },
51
+ JSXAttribute(node, st, c) {
52
+ if (node.value) c(node.value, st);
53
+ },
54
+ JSXSpreadAttribute(node, st, c) {
55
+ c(node.argument, st);
56
+ },
57
+ JSXExpressionContainer(node, st, c) {
58
+ if (node.expression) c(node.expression, st);
59
+ },
60
+ JSXMemberExpression(node, st, c) {
61
+ c(node.object, st);
62
+ c(node.property, st);
63
+ },
64
+ JSXNamespacedName(node, st, c) {
65
+ c(node.namespace, st);
66
+ c(node.name, st);
67
+ },
68
+ JSXText() {},
69
+ JSXIdentifier() {},
70
+ JSXEmptyExpression() {},
71
+ };
72
+
73
+ // TS/ESTree node types that acorn-walk's base does not know. Type-only nodes
74
+ // are deliberately NOT descended into (their children are type syntax, not code);
75
+ // expression wrappers are unwrapped so taint/analysis still sees the value.
76
+ const EXTRA_WALKERS = {
77
+ // Expression wrappers produced by acorn-typescript.
78
+ TSAsExpression: (node, st, c) => c(node.expression, st),
79
+ TSTypeAssertion: (node, st, c) => c(node.expression, st),
80
+ TSNonNullExpression: (node, st, c) => c(node.expression, st),
81
+ TSSatisfiesExpression: (node, st, c) => c(node.expression, st),
82
+ TSInstantiationExpression: (node, st, c) => c(node.expression, st),
83
+ TSParameterProperty: (node, st, c) => c(node.parameter, st),
84
+ // Type-only nodes: nothing executable inside.
85
+ TSTypeAliasDeclaration() {},
86
+ TSInterfaceDeclaration() {},
87
+ TSTypeAnnotation() {},
88
+ TSTypeReference() {},
89
+ TSTypeParameterInstantiation() {},
90
+ TSTypeParameterDeclaration() {},
91
+ TSTypeParameter() {},
92
+ TSDeclareFunction() {},
93
+ TSIndexSignature() {},
94
+ TSPropertySignature() {},
95
+ TSMethodSignature() {},
96
+ TSLiteralType() {},
97
+ TSUnionType() {},
98
+ TSIntersectionType() {},
99
+ TSFunctionType() {},
100
+ TSArrayType() {},
101
+ TSTypeQuery() {},
102
+ TSTypeLiteral() {},
103
+ TSMappedType() {},
104
+ TSConditionalType() {},
105
+ TSInferType() {},
106
+ TSEnumMember() {},
107
+ TSAbstractMethodDefinition() {},
108
+ // Module/namespace: descend into the body when it holds statements.
109
+ TSModuleDeclaration: (node, st, c) => {
110
+ if (node.body && node.body.type === 'TSModuleBlock') c(node.body, st);
111
+ },
112
+ TSModuleBlock: (node, st, c) => {
113
+ for (const s of node.body || []) c(s, st);
114
+ },
115
+ TSEnumDeclaration: (node, st, c) => {
116
+ for (const m of node.members || []) c(m, st);
117
+ },
118
+ // JSX fragments (opening/closing tags carry no children).
119
+ JSXOpeningFragment() {},
120
+ JSXClosingFragment() {},
121
+ // Newer ESTree fields.
122
+ PropertyDefinition: (node, st, c) => {
123
+ if (node.value) c(node.value, st);
124
+ },
125
+ AccessorProperty: (node, st, c) => {
126
+ if (node.value) c(node.value, st);
127
+ },
128
+ StaticBlock: (node, st, c) => {
129
+ for (const s of node.body || []) c(s, st);
130
+ },
131
+ Decorator: (node, st, c) => c(node.expression, st),
132
+ PrivateIdentifier() {},
133
+ };
134
+
135
+ // Anything still unknown walks its child nodes generically, except type syntax.
136
+ // This is what keeps a future parser node from silently disabling the AST pass.
137
+ function genericWalker(node, st, c) {
138
+ if (String(node.type).startsWith('TS') && !EXTRA_WALKERS[node.type]) return;
139
+ for (const key of Object.keys(node)) {
140
+ if (key === 'type' || key === 'loc' || key === 'range' || key === 'start' || key === 'end') continue;
141
+ const value = node[key];
142
+ if (Array.isArray(value)) {
143
+ for (const item of value) if (item && typeof item.type === 'string') c(item, st);
144
+ } else if (value && typeof value === 'object' && typeof value.type === 'string') {
145
+ c(value, st);
146
+ }
147
+ }
148
+ }
149
+
26
150
  function load() {
27
151
  if (loaded) return acorn && walk;
28
152
  loaded = true;
@@ -33,6 +157,23 @@ function load() {
33
157
  acorn = walk = null;
34
158
  return false;
35
159
  }
160
+ Object.assign(walk.base, JSX_WALKERS, EXTRA_WALKERS);
161
+ // Future-proof fallback: any node type acorn-walk does not know walks its
162
+ // children instead of throwing and silently disabling the whole AST pass.
163
+ walk.base = new Proxy(walk.base, {
164
+ get(target, prop, receiver) {
165
+ if (prop in target) return target[prop];
166
+ if (typeof prop === 'string') return genericWalker;
167
+ return undefined;
168
+ },
169
+ });
170
+ try {
171
+ const jsx = require('acorn-jsx');
172
+ const jsxPlugin = jsx.jsx || jsx.default || jsx;
173
+ jsxParser = acorn.Parser.extend(jsxPlugin());
174
+ } catch {
175
+ jsxParser = null; // JSX parsing optional-on-top-of-optional
176
+ }
36
177
  try {
37
178
  const ts = require('acorn-typescript');
38
179
  const tsPlugin = ts.tsPlugin || ts.default || ts;
@@ -53,17 +194,28 @@ const TS_EXT = new Set(['.ts', '.tsx', '.mts', '.cts']);
53
194
  function parse(content, ext) {
54
195
  const opts = { ecmaVersion: 'latest', sourceType: 'module', locations: true, allowReturnOutsideFunction: true };
55
196
  const isTs = TS_EXT.has(ext);
56
- const parser = isTs ? tsParser : acorn.Parser;
197
+ const isJsx = ext === '.jsx';
57
198
  if (isTs && !tsParser) return null; // no TS plugin -> let regex handle it
58
- try {
59
- return parser.parse(content, opts);
60
- } catch {
199
+ // .jsx needs the JSX plugin; a .js file may also contain JSX (common in
200
+ // browser-script code), so it tries plain JS first and JSX as a fallback.
201
+ const candidates = isTs
202
+ ? [tsParser]
203
+ : isJsx
204
+ ? [jsxParser, acorn.Parser]
205
+ : [acorn.Parser, jsxParser];
206
+ for (const parser of candidates) {
207
+ if (!parser) continue;
61
208
  try {
62
- return parser.parse(content, Object.assign({}, opts, { sourceType: 'script' }));
209
+ return parser.parse(content, opts);
63
210
  } catch {
64
- return null;
211
+ try {
212
+ return parser.parse(content, Object.assign({}, opts, { sourceType: 'script' }));
213
+ } catch {
214
+ /* next candidate */
215
+ }
65
216
  }
66
217
  }
218
+ return null;
67
219
  }
68
220
 
69
221
  function isDynamic(node) {
@@ -195,7 +347,13 @@ function analyzeAst(content, relPath, preparsed) {
195
347
  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(...)' });
196
348
  }
197
349
  // new Model(req.body)
198
- if (node.callee && node.callee.type === 'Identifier' && /^[A-Z]/.test(node.callee.name) && isReqDerived(args[0])) {
350
+ if (
351
+ node.callee && node.callee.type === 'Identifier' &&
352
+ /^[A-Z]/.test(node.callee.name) && isReqDerived(args[0]) &&
353
+ // Exclude JS builtins/globals that are NOT data records — `new Date(req.x)`,
354
+ // `new RegExp(req.x)`, `new Function(code)` etc. are not mass assignment.
355
+ !/^(?:Function|Boolean|Number|String|RegExp|Date|Array|Object|Map|Set|WeakMap|WeakSet|Promise|Error|TypeError|RangeError|EvalError|SyntaxError|ReferenceError|URIError|Symbol|BigInt|DataView|ArrayBuffer|SharedArrayBuffer|Buffer|Blob|FormData|Headers|URL|URLSearchParams|TextEncoder|TextDecoder|AbortController|AbortSignal|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|BigInt64Array|BigUint64Array)$/.test(node.callee.name)
356
+ ) {
199
357
  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.*)` });
200
358
  }
201
359
  },
@@ -3,16 +3,17 @@
3
3
  /*
4
4
  * VibeGuard Audit Trail.
5
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.
6
+ * Append-only, hash-chained log of every security decision an agent makes:
7
+ * tool calls allowed or blocked, secrets found, tamper attempts, sandbox runs,
8
+ * firewall verdicts. Each entry commits to the previous entry's hash, so
9
+ * editing or deleting an entry breaks the chain and is detectable.
9
10
  *
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
11
+ * Two ways to use it:
12
+ * - The module-level API (log / verifyChain / summary / ...) for in-process
13
+ * logging, exactly as older callers expect.
14
+ * - createLogger(file) for a self-contained logger backed by a JSONL file.
15
+ * The MCP firewall, agent monitor and risk engine use this so their audit
16
+ * trail survives process restarts.
16
17
  *
17
18
  * 100% local. Zero network. Zero dependencies.
18
19
  */
@@ -21,97 +22,228 @@ const crypto = require('crypto');
21
22
  const fs = require('fs');
22
23
  const path = require('path');
23
24
 
24
- let entries = [];
25
- let lastHash = 'GENESIS';
25
+ const GENESIS = 'GENESIS';
26
26
 
27
- function hashEntry(entry) {
28
- const data = JSON.stringify(entry) + lastHash;
29
- return crypto.createHash('sha256').update(data).digest('hex');
27
+ function hashPayload(entry) {
28
+ // Deterministic: every field that matters is committed to. Object key order
29
+ // is fixed explicitly so a JSON round-trip cannot change the hash.
30
+ const canonical = JSON.stringify({
31
+ id: entry.id,
32
+ type: entry.type,
33
+ detail: entry.detail,
34
+ timestamp: entry.timestamp,
35
+ previousHash: entry.previousHash,
36
+ });
37
+ return crypto.createHash('sha256').update(canonical).digest('hex');
30
38
  }
31
39
 
32
- function log(type, detail = {}) {
40
+ function makeEntry(type, detail, previousHash, id, timestamp) {
33
41
  const entry = {
34
- id: entries.length + 1,
42
+ id,
35
43
  type,
36
- detail,
37
- timestamp: Date.now(),
38
- previousHash: lastHash,
44
+ detail: detail === undefined ? {} : detail,
45
+ timestamp,
46
+ previousHash,
39
47
  };
40
- entry.hash = hashEntry(entry);
41
- lastHash = entry.hash;
42
- entries.push(entry);
48
+ entry.hash = hashPayload(entry);
43
49
  return entry;
44
50
  }
45
51
 
46
- function verifyChain() {
47
- let prevHash = 'GENESIS';
48
- let valid = true;
52
+ function verifyEntries(entries) {
53
+ let prevHash = GENESIS;
49
54
  const brokenAt = [];
55
+ for (const entry of entries) {
56
+ let ok = true;
57
+ if (!entry || typeof entry !== 'object') {
58
+ brokenAt.push(entry && entry.id);
59
+ continue;
60
+ }
61
+ if (entry.previousHash !== prevHash) ok = false;
62
+ if (entry.hash !== hashPayload(entry)) ok = false;
63
+ if (!ok) brokenAt.push(entry.id);
64
+ prevHash = entry.hash;
65
+ }
66
+ return { valid: brokenAt.length === 0, brokenAt, total: entries.length };
67
+ }
68
+
69
+ function summarizeEntries(entries) {
70
+ const byType = {};
71
+ for (const e of entries) byType[e.type] = (byType[e.type] || 0) + 1;
72
+ return {
73
+ total: entries.length,
74
+ byType,
75
+ firstEntry: entries.length ? entries[0].timestamp : null,
76
+ lastEntry: entries.length ? entries[entries.length - 1].timestamp : null,
77
+ duration: entries.length > 1 ? entries[entries.length - 1].timestamp - entries[0].timestamp : 0,
78
+ };
79
+ }
50
80
 
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);
81
+ function readJsonl(filePath) {
82
+ const entries = [];
83
+ let raw;
84
+ try {
85
+ raw = fs.readFileSync(filePath, 'utf8');
86
+ } catch {
87
+ return entries;
88
+ }
89
+ for (const line of raw.split(/\r?\n/)) {
90
+ if (!line.trim()) continue;
91
+ try {
92
+ const parsed = JSON.parse(line);
93
+ if (parsed && parsed.hash) entries.push(parsed);
94
+ } catch {
95
+ // A malformed line is retained as evidence of tampering: stop and let
96
+ // verification fail rather than silently ignoring it.
97
+ entries.push({ id: entries.length + 1, type: 'corrupt_line', detail: { line: line.slice(0, 120) }, timestamp: 0, previousHash: 'CORRUPT', hash: 'CORRUPT' });
56
98
  }
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
99
+ }
100
+ return entries;
101
+ }
102
+
103
+ function appendJsonl(filePath, entry) {
104
+ try {
105
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
106
+ fs.appendFileSync(filePath, JSON.stringify(entry) + '\n', 'utf8');
107
+ return true;
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+
113
+ // ─── Self-contained logger (file-backed) ────────────────────────────────────
114
+
115
+ function createLogger(filePath) {
116
+ const entries = filePath ? readJsonl(filePath) : [];
117
+ let lastHash = entries.length ? entries[entries.length - 1].hash : GENESIS;
118
+ let writeFailures = 0;
119
+
120
+ function log(type, detail = {}) {
121
+ const entry = makeEntry(type, detail, lastHash, entries.length + 1, Date.now());
122
+ lastHash = entry.hash;
123
+ entries.push(entry);
124
+ if (filePath && !appendJsonl(filePath, entry)) writeFailures++;
125
+ return entry;
126
+ }
127
+
128
+ function verify() {
129
+ return verifyEntries(entries);
130
+ }
131
+
132
+ function getEntries(filter = {}) {
133
+ let filtered = entries;
134
+ if (filter.type) filtered = filtered.filter((e) => e.type === filter.type);
135
+ if (filter.since) filtered = filtered.filter((e) => e.timestamp >= filter.since);
136
+ const limit = Number(filter.limit || 0);
137
+ if (limit > 0) filtered = filtered.slice(-limit);
138
+ return filtered;
139
+ }
140
+
141
+ function summary() {
142
+ return summarizeEntries(entries);
143
+ }
144
+
145
+ function exportLog(outPath) {
146
+ const payload = JSON.stringify({ entries, lastHash, exportedAt: Date.now() }, null, 2);
147
+ if (outPath) {
148
+ fs.mkdirSync(path.dirname(path.resolve(outPath)), { recursive: true });
149
+ fs.writeFileSync(outPath, payload, 'utf8');
150
+ return { exported: true, path: outPath, entries: entries.length };
151
+ }
152
+ return payload;
153
+ }
154
+
155
+ return {
156
+ log,
157
+ verify,
158
+ summary,
159
+ getEntries,
160
+ exportLog,
161
+ file: filePath || null,
162
+ get writeFailures() { return writeFailures; },
163
+ get entries() { return entries.slice(); },
164
+ };
165
+ }
166
+
167
+ // ─── Module-level logger (legacy API, unchanged signatures) ─────────────────
168
+
169
+ const memory = {
170
+ entries: [],
171
+ lastHash: GENESIS,
172
+ file: null,
173
+ };
174
+
175
+ function log(type, detail = {}) {
176
+ const entry = makeEntry(type, detail, memory.lastHash, memory.entries.length + 1, Date.now());
177
+ memory.lastHash = entry.hash;
178
+ memory.entries.push(entry);
179
+ if (memory.file) appendJsonl(memory.file, entry);
180
+ return entry;
181
+ }
182
+
183
+ function setFile(filePath) {
184
+ memory.file = filePath || null;
185
+ if (filePath) {
186
+ // Resume the existing chain instead of appending a fresh GENESIS after
187
+ // yesterday's entries — otherwise a restart corrupts the audit log.
188
+ const existing = readJsonl(filePath);
189
+ if (existing.length) {
190
+ memory.entries = existing;
191
+ memory.lastHash = existing[existing.length - 1].hash;
61
192
  }
62
- prevHash = entry.hash;
63
193
  }
194
+ return { file: memory.file, entries: memory.entries.length };
195
+ }
196
+
197
+ function loadFile(filePath) {
198
+ memory.entries = readJsonl(filePath);
199
+ memory.lastHash = memory.entries.length ? memory.entries[memory.entries.length - 1].hash : GENESIS;
200
+ memory.file = filePath;
201
+ return { loaded: true, entries: memory.entries.length, verification: verifyChain() };
202
+ }
64
203
 
65
- return { valid, brokenAt, total: entries.length };
204
+ function verifyChain(entries) {
205
+ return verifyEntries(entries || memory.entries);
66
206
  }
67
207
 
68
208
  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);
209
+ let filtered = memory.entries;
210
+ if (filter.type) filtered = filtered.filter((e) => e.type === filter.type);
211
+ if (filter.since) filtered = filtered.filter((e) => e.timestamp >= filter.since);
72
212
  if (filter.limit) filtered = filtered.slice(-filter.limit);
73
213
  return filtered;
74
214
  }
75
215
 
76
216
  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
- };
217
+ return summarizeEntries(memory.entries);
88
218
  }
89
219
 
90
220
  function exportLog(filePath) {
91
- const data = JSON.stringify({ entries, lastHash, exportedAt: Date.now() }, null, 2);
221
+ const data = JSON.stringify({ entries: memory.entries, lastHash: memory.lastHash, exportedAt: Date.now() }, null, 2);
92
222
  if (filePath) {
93
- fs.writeFileSync(filePath, data);
94
- return { exported: true, path: filePath, entries: entries.length };
223
+ fs.mkdirSync(path.dirname(path.resolve(filePath)), { recursive: true });
224
+ fs.writeFileSync(filePath, data, 'utf8');
225
+ return { exported: true, path: filePath, entries: memory.entries.length };
95
226
  }
96
227
  return data;
97
228
  }
98
229
 
99
230
  function importLog(filePath) {
100
231
  const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
101
- entries = data.entries || [];
102
- lastHash = data.lastHash || 'GENESIS';
103
- return { imported: true, entries: entries.length };
232
+ memory.entries = data.entries || [];
233
+ memory.lastHash = data.lastHash || GENESIS;
234
+ return { imported: true, entries: memory.entries.length };
104
235
  }
105
236
 
106
237
  function clear() {
107
- entries = [];
108
- lastHash = 'GENESIS';
238
+ memory.entries = [];
239
+ memory.lastHash = GENESIS;
109
240
  return { cleared: true };
110
241
  }
111
242
 
112
- function renderAuditReport() {
243
+ function renderAuditReport(entriesArg) {
113
244
  const C = { red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', dim: '\x1b[2m', bold: '\x1b[1m', reset: '\x1b[0m' };
114
- const s = summary();
245
+ const entries = entriesArg || memory.entries;
246
+ const s = summarizeEntries(entries);
115
247
  const lines = [
116
248
  `${C.bold}VibeGuard Audit Trail${C.reset}`,
117
249
  `${C.dim}${'─'.repeat(60)}${C.reset}`,
@@ -126,11 +258,11 @@ function renderAuditReport() {
126
258
  ];
127
259
 
128
260
  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}`);
261
+ const color = type === 'blocked' || type === 'tamper' || type === 'mcp_blocked' ? C.red : type === 'warning' ? C.yellow : C.dim;
262
+ lines.push(` ${color}${type.padEnd(22)}${C.reset} ${count}`);
131
263
  }
132
264
 
133
- const verification = verifyChain();
265
+ const verification = verifyEntries(entries);
134
266
  lines.push('', `${C.bold}Chain Verification${C.reset}`, '');
135
267
  if (verification.valid) {
136
268
  lines.push(` ${C.green}PASS — Chain intact (${verification.total} entries)${C.reset}`);
@@ -138,17 +270,30 @@ function renderAuditReport() {
138
270
  lines.push(` ${C.red}FAIL — Chain broken at entries: ${verification.brokenAt.join(', ')}${C.reset}`);
139
271
  }
140
272
 
141
- // Recent entries
142
273
  if (entries.length > 0) {
143
274
  lines.push('', `${C.bold}Recent Entries${C.reset}`, '');
144
275
  for (const e of entries.slice(-10)) {
145
276
  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)}`);
277
+ const color = e.type === 'blocked' || e.type === 'mcp_blocked' ? C.red : e.type === 'tamper' ? C.red : e.type === 'warning' ? C.yellow : C.dim;
278
+ lines.push(` ${C.dim}${time}${C.reset} ${color}${e.type}${C.reset} ${JSON.stringify(e.detail).slice(0, 70)}`);
148
279
  }
149
280
  }
150
281
 
151
282
  return lines.join('\n');
152
283
  }
153
284
 
154
- module.exports = { log, verifyChain, getEntries, summary, exportLog, importLog, clear, renderAuditReport };
285
+ module.exports = {
286
+ log,
287
+ setFile,
288
+ loadFile,
289
+ createLogger,
290
+ verifyChain,
291
+ verifyEntries,
292
+ getEntries,
293
+ summary,
294
+ exportLog,
295
+ importLog,
296
+ clear,
297
+ renderAuditReport,
298
+ hashPayload,
299
+ };