@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
@@ -0,0 +1,357 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/platform/signed-audit.js — authenticated, append-only audit events.
5
+ *
6
+ * Each event commits to its predecessor (previousHash), carries a SHA-256 hash
7
+ * over its canonical body, and is signed with Ed25519. A period checkpoint
8
+ * signs a Merkle root of the event hashes so an external verifier can anchor
9
+ * history without replaying every event.
10
+ *
11
+ * This is intentionally separate from the legacy src/audit-trail.js JSONL
12
+ * format; the legacy format remains readable via a compatibility importer.
13
+ */
14
+
15
+ const crypto = require('crypto');
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const { canonicalize, sha256Hex } = require('./canonical');
19
+ const { ERROR_CODES, VibeGuardError, newId } = require('./contracts');
20
+ const { loadPrivateKey, loadPublicKey, generateKeyPair } = require('./identity');
21
+
22
+ const GENESIS = 'GENESIS';
23
+ const SCHEMA_VERSION = '1.0';
24
+
25
+ function iso(clock) {
26
+ const d = clock && typeof clock.now === 'function' ? clock.now() : (typeof clock === 'function' ? clock() : new Date());
27
+ return (d instanceof Date ? d : new Date(d)).toISOString();
28
+ }
29
+
30
+ function eventBody(event) {
31
+ return {
32
+ schemaVersion: SCHEMA_VERSION,
33
+ eventId: event.eventId,
34
+ sequence: event.sequence,
35
+ timestamp: event.timestamp,
36
+ type: event.type,
37
+ tenant: event.tenant || null,
38
+ principal: event.principal || null,
39
+ agent: event.agent || null,
40
+ sessionId: event.sessionId || null,
41
+ server: event.server || null,
42
+ tool: event.tool || null,
43
+ actionDigest: event.actionDigest || null,
44
+ decision: event.decision || null,
45
+ reasonCode: event.reasonCode || null,
46
+ policyId: event.policyId || null,
47
+ policyVersion: event.policyVersion || null,
48
+ detail: event.detail || {},
49
+ previousHash: event.previousHash,
50
+ };
51
+ }
52
+
53
+ function signHash(hash, privateKey) {
54
+ return crypto.sign(null, Buffer.from(hash, 'utf8'), privateKey).toString('base64url');
55
+ }
56
+
57
+ function verifyHashSignature(hash, signature, publicKey) {
58
+ try {
59
+ return crypto.verify(null, Buffer.from(hash, 'utf8'), loadPublicKey(publicKey), Buffer.from(signature, 'base64url'));
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ class SignedAuditLog {
66
+ constructor(opts = {}) {
67
+ if (!opts.file) throw new Error('SignedAuditLog requires a file path');
68
+ this.file = path.resolve(opts.file);
69
+ let privateKey;
70
+ let publicKey;
71
+ if (opts.privateKey) {
72
+ privateKey = loadPrivateKey(opts.privateKey);
73
+ publicKey = opts.publicKey ? loadPublicKey(opts.publicKey) : crypto.createPublicKey(privateKey);
74
+ } else {
75
+ if (opts.publicKey) throw new Error('SignedAuditLog: publicKey without privateKey is not supported');
76
+ const pair = generateKeyPair();
77
+ privateKey = pair.privateKey;
78
+ publicKey = pair.publicKey;
79
+ }
80
+ this.privateKey = privateKey;
81
+ this.publicKey = publicKey;
82
+ this.keyId = opts.keyId || `audit_${crypto.randomBytes(4).toString('hex')}`;
83
+ this.clock = opts.clock || (() => new Date());
84
+ this.tenant = opts.tenant || null;
85
+ this.checkpointFile = opts.checkpointFile || `${this.file}.checkpoint.json`;
86
+ this.entries = [];
87
+ this.lastHash = GENESIS;
88
+ this._loadExisting(opts.verifyOnOpen !== false);
89
+ }
90
+
91
+ _loadExisting(verify) {
92
+ if (!fs.existsSync(this.file)) return;
93
+ const raw = fs.readFileSync(this.file, 'utf8');
94
+ const lines = raw.split(/\r?\n/).filter(Boolean);
95
+ for (let i = 0; i < lines.length; i++) {
96
+ let event;
97
+ try {
98
+ event = JSON.parse(lines[i]);
99
+ } catch {
100
+ throw new VibeGuardError(ERROR_CODES.AUDIT_INVALID, `audit line ${i + 1} is not valid JSON`);
101
+ }
102
+ this.entries.push(event);
103
+ }
104
+ if (this.entries.length) this.lastHash = this.entries[this.entries.length - 1].hash;
105
+ if (verify && this.entries.length) {
106
+ const result = SignedAuditLog.verifyEntries(this.entries, { publicKey: this.publicKey, requireEntries: true });
107
+ if (!result.valid) throw new VibeGuardError(ERROR_CODES.AUDIT_INVALID, 'existing audit log failed verification');
108
+ }
109
+ }
110
+
111
+ append(type, detail = {}, meta = {}) {
112
+ const sequence = this.entries.length + 1;
113
+ const event = {
114
+ schemaVersion: SCHEMA_VERSION,
115
+ eventId: meta.eventId || newId('evt'),
116
+ sequence,
117
+ timestamp: meta.timestamp || iso(this.clock),
118
+ type,
119
+ tenant: meta.tenant !== undefined ? meta.tenant : this.tenant,
120
+ principal: meta.principal || null,
121
+ agent: meta.agent || null,
122
+ sessionId: meta.sessionId || null,
123
+ server: meta.server || null,
124
+ tool: meta.tool || null,
125
+ actionDigest: meta.actionDigest || null,
126
+ decision: meta.decision || null,
127
+ reasonCode: meta.reasonCode || null,
128
+ policyId: meta.policyId || null,
129
+ policyVersion: meta.policyVersion || null,
130
+ detail,
131
+ previousHash: this.lastHash,
132
+ };
133
+ const body = eventBody(event);
134
+ const hash = sha256Hex(body);
135
+ const signature = {
136
+ alg: 'Ed25519',
137
+ keyId: this.keyId,
138
+ sig: signHash(hash, this.privateKey),
139
+ };
140
+ event.hash = hash;
141
+ event.signature = signature;
142
+
143
+ this._writeLine(event);
144
+ this.entries.push(event);
145
+ this.lastHash = hash;
146
+ this._writeCheckpoint();
147
+ return event;
148
+ }
149
+
150
+ _writeCheckpoint() {
151
+ try {
152
+ const cp = this.checkpoint();
153
+ fs.writeFileSync(this.checkpointFile, JSON.stringify(cp) + '\n', { mode: 0o600 });
154
+ try { fs.chmodSync(this.checkpointFile, 0o600); } catch { /* Windows/best effort */ }
155
+ } catch (err) {
156
+ throw new VibeGuardError(ERROR_CODES.AUDIT_INVALID, `audit checkpoint write failed: ${err.message}`);
157
+ }
158
+ }
159
+
160
+ _writeLine(event) {
161
+ fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
162
+ try { fs.chmodSync(path.dirname(this.file), 0o700); } catch { /* Windows/best effort */ }
163
+ const fd = fs.openSync(this.file, 'a', 0o600);
164
+ try {
165
+ fs.writeSync(fd, JSON.stringify(event) + '\n');
166
+ try { fs.fsyncSync(fd); } catch { /* platform may not support */ }
167
+ } finally {
168
+ fs.closeSync(fd);
169
+ }
170
+ try { fs.chmodSync(this.file, 0o600); } catch { /* Windows/best effort */ }
171
+ }
172
+
173
+ checkpoint() {
174
+ if (!this.entries.length) throw new VibeGuardError(ERROR_CODES.AUDIT_INVALID, 'cannot checkpoint an empty audit log');
175
+ const root = merkleRoot(this.entries.map((e) => e.hash));
176
+ const body = {
177
+ type: 'VGCHECKPOINT',
178
+ schemaVersion: SCHEMA_VERSION,
179
+ sequence: this.entries.length,
180
+ lastSequence: this.entries[this.entries.length - 1].sequence,
181
+ root,
182
+ timestamp: iso(this.clock),
183
+ keyId: this.keyId,
184
+ };
185
+ const sig = crypto.sign(null, Buffer.from(canonicalize(body), 'utf8'), this.privateKey).toString('base64url');
186
+ return { ...body, signature: { alg: 'Ed25519', keyId: this.keyId, sig } };
187
+ }
188
+
189
+ static verifyFile(file, opts = {}) {
190
+ if (!fs.existsSync(file)) {
191
+ return { valid: false, entries: 0, brokenAt: [], reasons: ['audit file does not exist'] };
192
+ }
193
+ let raw;
194
+ try { raw = fs.readFileSync(file, 'utf8'); } catch (exc) {
195
+ return { valid: false, entries: 0, brokenAt: [], reasons: [`cannot read audit file: ${exc.message}`] };
196
+ }
197
+ const lines = raw.split(/\r?\n/).filter(Boolean);
198
+ const entries = [];
199
+ const reasons = [];
200
+ for (let i = 0; i < lines.length; i++) {
201
+ try { entries.push(JSON.parse(lines[i])); } catch { reasons.push(`line ${i + 1}: invalid JSON`); }
202
+ }
203
+ const result = SignedAuditLog.verifyEntries(entries, { ...opts, requireEntries: opts.requireEntries !== false });
204
+ let checkpoint;
205
+ try {
206
+ if (opts.checkpoint) checkpoint = opts.checkpoint;
207
+ else if (opts.publicKey && fs.existsSync(`${path.resolve(file)}.checkpoint.json`)) {
208
+ checkpoint = JSON.parse(fs.readFileSync(`${path.resolve(file)}.checkpoint.json`, 'utf8'));
209
+ }
210
+ } catch { /* fall through to checkpoint failure below */ }
211
+ if (checkpoint && entries.length) {
212
+ if (!opts.publicKey) {
213
+ reasons.push('checkpoint present but no public key supplied; checkpoint signature not verified');
214
+ } else {
215
+ const cp = SignedAuditLog.verifyCheckpoint(checkpoint, opts.publicKey, entries);
216
+ if (!cp.valid) {
217
+ reasons.push(`checkpoint: ${cp.reason}`);
218
+ result.brokenAt.push(checkpoint.sequence || entries.length);
219
+ result.valid = false;
220
+ }
221
+ }
222
+ }
223
+ return { ...result, reasons: reasons.concat(result.reasons), file: path.resolve(file) };
224
+ }
225
+
226
+ static verifyEntries(entries, opts = {}) {
227
+ const brokenAt = [];
228
+ const reasons = [];
229
+ let prev = GENESIS;
230
+ const ids = new Set();
231
+ if (!Array.isArray(entries)) return { valid: false, entries: 0, brokenAt: [], reasons: ['entries is not an array'] };
232
+ if (opts.requireEntries && entries.length === 0) {
233
+ return { valid: false, entries: 0, brokenAt: [], reasons: ['audit log has no entries'] };
234
+ }
235
+ for (let i = 0; i < entries.length; i++) {
236
+ const e = entries[i];
237
+ if (!e || typeof e !== 'object') { brokenAt.push(i + 1); reasons.push(`entry ${i + 1}: not an object`); continue; }
238
+ if (e.schemaVersion !== SCHEMA_VERSION) { brokenAt.push(e.sequence || i + 1); reasons.push(`entry ${i + 1}: schema version`); }
239
+ if (e.sequence !== i + 1) { brokenAt.push(e.sequence || i + 1); reasons.push(`entry ${i + 1}: sequence mismatch`); }
240
+ if (e.previousHash !== prev) { brokenAt.push(e.sequence || i + 1); reasons.push(`entry ${i + 1}: previous hash mismatch`); }
241
+ if (ids.has(e.eventId)) { brokenAt.push(e.sequence || i + 1); reasons.push(`entry ${i + 1}: duplicate eventId`); }
242
+ ids.add(e.eventId);
243
+ const expected = sha256Hex(eventBody(e));
244
+ if (e.hash !== expected) { brokenAt.push(e.sequence || i + 1); reasons.push(`entry ${i + 1}: hash mismatch`); }
245
+ if (opts.publicKey) {
246
+ if (!e.signature || e.signature.alg !== 'Ed25519') {
247
+ brokenAt.push(e.sequence || i + 1); reasons.push(`entry ${i + 1}: missing signature`);
248
+ } else if (!verifyHashSignature(e.hash, e.signature.sig, opts.publicKey)) {
249
+ brokenAt.push(e.sequence || i + 1); reasons.push(`entry ${i + 1}: bad signature`);
250
+ }
251
+ }
252
+ prev = e.hash;
253
+ }
254
+ const unique = [...new Set(brokenAt)];
255
+ return { valid: unique.length === 0, entries: entries.length, brokenAt: unique, reasons };
256
+ }
257
+
258
+ static verifyCheckpoint(checkpoint, publicKey, entries) {
259
+ if (!checkpoint || checkpoint.type !== 'VGCHECKPOINT') return { valid: false, reason: 'not a checkpoint' };
260
+ const body = { ...checkpoint };
261
+ delete body.signature;
262
+ const sigOk = verifyHashSignature(canonicalize(body), checkpoint.signature && checkpoint.signature.sig, publicKey);
263
+ if (!sigOk) return { valid: false, reason: 'checkpoint signature invalid' };
264
+ if (!Array.isArray(entries) || entries.length !== checkpoint.sequence) return { valid: false, reason: 'checkpoint sequence mismatch' };
265
+ const root = merkleRoot(entries.map((e) => e.hash));
266
+ if (root !== checkpoint.root) return { valid: false, reason: 'checkpoint root mismatch' };
267
+ return { valid: true, root };
268
+ }
269
+ }
270
+
271
+ function merkleRoot(hashes) {
272
+ if (!hashes.length) return sha256Hex('EMPTY');
273
+ let level = hashes.slice();
274
+ while (level.length > 1) {
275
+ const next = [];
276
+ for (let i = 0; i < level.length; i += 2) {
277
+ const left = level[i];
278
+ const right = i + 1 < level.length ? level[i + 1] : left;
279
+ next.push(sha256Hex(left + right));
280
+ }
281
+ level = next;
282
+ }
283
+ return level[0];
284
+ }
285
+
286
+ /**
287
+ * Adapter with the legacy logger shape (`log`, `entries`, `writeFailures`) so
288
+ * the MCP gateway can use signed events without changing its call sites.
289
+ */
290
+ class SignedAuditLogger {
291
+ constructor(opts = {}) {
292
+ this.signed = new SignedAuditLog(opts);
293
+ this.file = this.signed.file;
294
+ this.writeFailures = 0;
295
+ }
296
+
297
+ log(type, detail = {}) {
298
+ try {
299
+ return this.signed.append(type, detail);
300
+ } catch (err) {
301
+ this.writeFailures++;
302
+ throw err;
303
+ }
304
+ }
305
+
306
+ get entries() { return this.signed.entries.slice(); }
307
+ verify() { return SignedAuditLog.verifyFile(this.file, { publicKey: this.signed.publicKey }); }
308
+ checkpoint() { return this.signed.checkpoint(); }
309
+ }
310
+
311
+ function ensureAuditKey(projectRoot, keyFile) {
312
+ const dir = path.join(projectRoot, '.vibeguard', 'audit');
313
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
314
+ try { fs.chmodSync(dir, 0o700); } catch { /* Windows */ }
315
+ const privatePath = keyFile || path.join(dir, 'ed25519.pem');
316
+ const publicPath = privatePath.replace(/\.pem$/i, '.pub.pem');
317
+ let privateKey;
318
+ let publicKey;
319
+ if (fs.existsSync(privatePath)) {
320
+ privateKey = loadPrivateKey(fs.readFileSync(privatePath));
321
+ publicKey = fs.existsSync(publicPath) ? loadPublicKey(fs.readFileSync(publicPath)) : crypto.createPublicKey(privateKey);
322
+ } else {
323
+ const pair = generateKeyPair();
324
+ privateKey = pair.privateKey;
325
+ publicKey = pair.publicKey;
326
+ fs.writeFileSync(privatePath, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
327
+ fs.writeFileSync(publicPath, publicKey.export({ type: 'spki', format: 'pem' }), { mode: 0o600 });
328
+ try { fs.chmodSync(privatePath, 0o600); } catch { /* Windows */ }
329
+ }
330
+ return { privateKey, publicKey, privatePath, publicPath };
331
+ }
332
+
333
+ function createSignedLogger(file, opts = {}) {
334
+ const projectRoot = opts.projectRoot || path.dirname(path.dirname(path.dirname(file)));
335
+ const key = ensureAuditKey(projectRoot, opts.auditKeyFile);
336
+ const logger = new SignedAuditLogger({
337
+ file,
338
+ privateKey: key.privateKey,
339
+ publicKey: key.publicKey,
340
+ keyId: opts.keyId || 'gateway-audit',
341
+ tenant: opts.tenant,
342
+ clock: opts.clock,
343
+ });
344
+ logger.keyInfo = key;
345
+ return logger;
346
+ }
347
+
348
+ module.exports = {
349
+ SignedAuditLog,
350
+ SignedAuditLogger,
351
+ createSignedLogger,
352
+ ensureAuditKey,
353
+ merkleRoot,
354
+ eventBody,
355
+ GENESIS,
356
+ SCHEMA_VERSION,
357
+ };
@@ -0,0 +1,129 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * src/platform/ssrf.js — destination validation for remote MCP/egress.
5
+ *
6
+ * Resolves a hostname and rejects private, loopback, link-local, metadata and
7
+ * other non-public ranges. Returns a pinned IP that callers should connect to
8
+ * (with the original Host/SNI) to reduce DNS-rebinding windows.
9
+ *
10
+ * This is a validation primitive, not a full HTTP client. It performs no
11
+ * request itself and has no external dependencies.
12
+ */
13
+
14
+ const dns = require('dns').promises;
15
+ const net = require('net');
16
+ const { ERROR_CODES, VibeGuardError } = require('./contracts');
17
+
18
+ const METADATA_HOSTS = new Set([
19
+ 'metadata.google.internal',
20
+ 'metadata.goog',
21
+ '169.254.169.254',
22
+ '100.100.100.200',
23
+ 'fd00:ec2::254',
24
+ ]);
25
+
26
+ function ipv4ToInt(ip) {
27
+ return ip.split('.').reduce((acc, n) => (acc << 8) + Number(n), 0) >>> 0;
28
+ }
29
+
30
+ function isPrivateIPv4(ip) {
31
+ if (!net.isIPv4(ip)) return false;
32
+ const v = ipv4ToInt(ip);
33
+ const inRange = (base, bits) => {
34
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
35
+ return (v & mask) === (ipv4ToInt(base) & mask);
36
+ };
37
+ return (
38
+ inRange('0.0.0.0', 8) ||
39
+ inRange('10.0.0.0', 8) ||
40
+ inRange('100.64.0.0', 10) ||
41
+ inRange('127.0.0.0', 8) ||
42
+ inRange('169.254.0.0', 16) ||
43
+ inRange('172.16.0.0', 12) ||
44
+ inRange('192.0.0.0', 24) ||
45
+ inRange('192.168.0.0', 16) ||
46
+ inRange('198.18.0.0', 15) ||
47
+ inRange('224.0.0.0', 4) ||
48
+ inRange('240.0.0.0', 4)
49
+ );
50
+ }
51
+
52
+ function isPrivateIPv6(ip) {
53
+ if (!net.isIPv6(ip)) return false;
54
+ const lower = ip.toLowerCase();
55
+ if (lower === '::' || lower === '::1') return true;
56
+ const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
57
+ if (mapped) return isPrivateIPv4(mapped[1]);
58
+ if (/^fc|^fd/.test(lower)) return true; // unique local fc00::/7
59
+ if (/^fe8|^fe9|^fea|^feb/.test(lower)) return true; // link-local fe80::/10
60
+ if (lower.startsWith('2001:db8:')) return true; // documentation
61
+ if (lower.startsWith('ff')) return true; // multicast
62
+ return false;
63
+ }
64
+
65
+ function isPrivateAddress(ip) {
66
+ return isPrivateIPv4(ip) || isPrivateIPv6(ip);
67
+ }
68
+
69
+ function hostMatches(host, patterns) {
70
+ return (patterns || []).some((p) => {
71
+ const pattern = String(p).toLowerCase();
72
+ const h = String(host).toLowerCase();
73
+ if (pattern === h) return true;
74
+ if (pattern.startsWith('*.')) return h.endsWith(pattern.slice(1));
75
+ return false;
76
+ });
77
+ }
78
+
79
+ async function assertAllowedUrl(raw, opts = {}) {
80
+ let url;
81
+ try { url = new URL(String(raw)); } catch { throw new VibeGuardError(ERROR_CODES.SSRF_BLOCKED, 'invalid URL'); }
82
+ if (!['http:', 'https:'].includes(url.protocol)) {
83
+ throw new VibeGuardError(ERROR_CODES.SSRF_BLOCKED, `unsupported URL scheme: ${url.protocol}`);
84
+ }
85
+ if (url.username || url.password) throw new VibeGuardError(ERROR_CODES.SSRF_BLOCKED, 'URL credentials are not allowed');
86
+ const host = url.hostname.replace(/^\[|\]$/g, '').toLowerCase();
87
+ if (METADATA_HOSTS.has(host)) throw new VibeGuardError(ERROR_CODES.SSRF_BLOCKED, 'cloud metadata endpoint is blocked by policy');
88
+ if (Array.isArray(opts.allowedHosts) && opts.allowedHosts.length && !hostMatches(host, opts.allowedHosts)) {
89
+ throw new VibeGuardError(ERROR_CODES.SSRF_BLOCKED, `host is not allowlisted: ${host}`);
90
+ }
91
+ if (hostMatches(host, opts.deniedHosts || [])) throw new VibeGuardError(ERROR_CODES.SSRF_BLOCKED, `host is denied: ${host}`);
92
+
93
+ let addresses;
94
+ if (net.isIP(host)) {
95
+ addresses = [{ address: host, family: net.isIPv4(host) ? 4 : 6 }];
96
+ } else {
97
+ const resolver = opts.resolve || ((h) => dns.lookup(h, { all: true, verbatim: true }));
98
+ try { addresses = await resolver(host); } catch (err) {
99
+ throw new VibeGuardError(ERROR_CODES.SSRF_BLOCKED, `DNS resolution failed: ${err.message}`);
100
+ }
101
+ }
102
+ if (!Array.isArray(addresses) || addresses.length === 0) {
103
+ throw new VibeGuardError(ERROR_CODES.SSRF_BLOCKED, 'no DNS addresses');
104
+ }
105
+ const allowLoopback = opts.allowLoopback === true;
106
+ const allowPrivate = opts.allowPrivate === true;
107
+ for (const entry of addresses) {
108
+ const ip = String(entry.address || entry);
109
+ if (isPrivateAddress(ip)) {
110
+ if (net.isIPv4(ip) && /^127\./.test(ip) && allowLoopback) continue;
111
+ if (!allowPrivate) throw new VibeGuardError(ERROR_CODES.SSRF_BLOCKED, `private/loopback address blocked: ${ip}`);
112
+ }
113
+ }
114
+ return {
115
+ url: url.toString(),
116
+ host,
117
+ port: url.port ? Number(url.port) : (url.protocol === 'https:' ? 443 : 80),
118
+ pinnedAddress: addresses[0].address || String(addresses[0]),
119
+ addresses: addresses.map((a) => a.address || String(a)),
120
+ };
121
+ }
122
+
123
+ module.exports = {
124
+ assertAllowedUrl,
125
+ isPrivateAddress,
126
+ isPrivateIPv4,
127
+ isPrivateIPv6,
128
+ METADATA_HOSTS,
129
+ };