neuralbridge-gateway 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Guigui Wang (Correctover)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # NeuralBridge
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The problem:** your AI agent called a tool. Now someone asks you to prove it — an auditor, an insurer, a regulator, your own security team. The log is a story the application tells about itself: the platform that ran the agent also wrote the log, and you have no way to check either.
4
+
5
+ **NeuralBridge fixes exactly that.** It is an MCP gateway that signs a verifiable, hash-chained receipt for **every tool call** your agent makes — Ed25519, digest-only arguments (SHA-256/JCS, prompts never in plaintext), and a failure mode that still produces evidence: *fail-with-evidence*. Any third party can re-verify the chain offline, without trusting the agent, the gateway, or us.
6
+
7
+ > Automation tools prove what the agent *did*. NeuralBridge proves what the agent *was allowed to do* — and makes the difference independently checkable.
8
+
9
+ ## Quickstart (2 minutes)
10
+
11
+ ```bash
12
+ npx neuralbridge-gateway --target http://localhost:8000/mcp --port 8080
13
+ # your agent connects to :8080 instead of :8000 — everything else unchanged
14
+ ```
15
+
16
+ Every `tools/call` gets: allowlist check → Ed25519 receipt over `{tool, args_digest, verdict, prev_hash}` → hash-chained into `receipts/chain.jsonl` → forwarded with the receipt attached.
17
+
18
+ Then:
19
+
20
+ ```bash
21
+ npx neuralbridge-gateway nb verify # chain integrity + every signature
22
+ npx neuralbridge-gateway nb report # shareable HTML audit report
23
+ ```
24
+
25
+ The report page is generated from the chain itself — open it, send it to whoever asked "prove what the agent did". Tamper test: change one byte of any receipt, re-run `nb verify`, watch it go red.
26
+
27
+ ## Who this is for
28
+
29
+ - **Audit & assurance** — workpapers citing agent work need agent-action evidence, not platform self-testimony. See the working demo: [`audit/`](audit/) — a reconciliation agent whose policy-rejected write is itself receipted.
30
+ - **Insurance & compliance** — standalone AI liability products underwrite on observability and autonomy; a receipt chain turns self-reported governance into verifiable telemetry.
31
+ - **Anyone shipping agents** — the receipt chain is the artifact that survives "prove it later".
32
+
33
+ ## Receipts, not logs
34
+
35
+ | log | receipt |
36
+ |---|---|
37
+ | written by the app that ran the agent | signed by the gateway, before forwarding |
38
+ | editable by anyone with access | hash-chained: edit one receipt, everything after stops verifying |
39
+ | "trust us" | third party re-verifies with one command, offline |
40
+
41
+ Spec: [draft-correctover-ccs](https://datatracker.ietf.org/doc/draft-correctover-ccs/) (individual submission, not an RFC or IETF endorsement). Zero dependencies: `node:http` + `node:crypto` only.
42
+
43
+ ## Scale evidence
44
+
45
+ The receipt engine replays the entire public MCP tool census — **229,827 tools** (13,120 servers, [mcp-atlas](https://github.com/DSHCorrectover/mcp-atlas), SHA-256 `2350dc77…`) — with **zero** synthesis, digest, or chain failures (24.7 s, single process). Report: [`test/scale-report.json`](test/scale-report.json).
46
+
47
+ ## Sibling projects
48
+
49
+ The gateway does in-band enforcement. For the post-hoc half of the problem — verifier divergence, corpus-locked judgment vectors — see [mcp-session-audit](https://github.com/DSHCorrectover/mcp-session-audit) and [verifier-divergence-corpus](https://github.com/DSHCorrectover/verifier-divergence-corpus).
50
+
51
+ MIT. Guigui Wang | Correctover.
@@ -0,0 +1,29 @@
1
+ # Audit Workbench (demo)
2
+
3
+ **The gap this fills:** Big Four audit platforms (Deloitte Omnia's "connected agentic intelligence", EY Canvas) are putting AI agents into live audit engagements. An audit workpaper that cites agent work needs **agent-action evidence** — not a log the agent tells about itself, but a signed, chain-linked, independently verifiable record of every tool call, what was allowed, and what was refused.
4
+
5
+ NeuralBridge already signs every tool call. This demo wires it into an audit scenario:
6
+
7
+ ## What runs (one command)
8
+
9
+ ```bash
10
+ bash audit/run-demo.sh
11
+ ```
12
+
13
+ 1. `audit/ledger-mcp.mjs` — a deterministic 5-invoice AP ledger (INV-2026-0043 duplicates INV-2026-0007; fixture is fixed, replays anywhere)
14
+ 2. `gateway/gateway.mjs` — NeuralBridge in front of the ledger; **every tool call the agent makes is signed (Ed25519, digest-only args) and hash-chained** into `receipts/chain.jsonl`
15
+ 3. `audit/agent.mjs` — reconciliation agent: duplicate-payment detection, open-item total, and a policy boundary (**it flags the duplicate for human review instead of auto-settling** — the authorization decision is part of the evidence)
16
+ 4. `audit/task-result.json` — the workpaper: task, checks, findings, proposed-write decision, and per-step receipt linkage (by args_digest)
17
+ 5. `audit/verify.mjs` — **independent offline verifier** (zero trust in agent or gateway): chain integrity, every Ed25519 signature, workpaper-to-receipt consistency, and the write-rejection invariant (a step the workpaper claims was policy-rejected must not appear as an executed call)
18
+
19
+ ## Verified claims
20
+
21
+ - `VERIFY PASS: N receipts, chain intact, all signatures valid, workpaper consistent`
22
+ - **Mutation self-proof**: edit one byte of any receipt (e.g. verdict `ALLOW`→`BLOCK`) → verifier goes red (signature AND hash both fail). The evidence cannot be quietly rewritten — including by us.
23
+ - Deterministic fixture: no LLM API required, replays byte-identically in any CI. (LLM-provider pluggable later; the receipts don't care which brain drove the calls.)
24
+
25
+ ## Why receipts, not logs
26
+
27
+ A log is a story the application tells about itself. A workpaper is a professional deliverable someone will rely on. Between those two sits a signature: `draft-correctover-ccs` (IETF rev 11) and the gateway that implements it. The auditor re-verifies; the agent cannot rewrite what it did; and the "agent wanted to settle the duplicate but policy said no" decision is *itself* a signed receipt.
28
+
29
+ Scale evidence for the receipt engine: 229,827 public tools replayed with zero synthesis/chain failures — see [`test/scale-report.json`](../test/scale-report.json).
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ // Audit agent (demo): reconciliation task with duplicate-payment detection.
3
+ // Rule-driven and deterministic (LLM provider pluggable later); every tool call it makes
4
+ // goes through the NeuralBridge gateway, so the whole task leaves a signed receipt chain.
5
+ // Usage: node audit/agent.mjs --gateway http://127.0.0.1:8080/mcp --out audit/task-result.json
6
+ import http from 'node:http';
7
+ import { writeFileSync, mkdirSync } from 'node:fs';
8
+
9
+ const arg = (n, d) => { const i = process.argv.indexOf(n); return i >= 0 ? process.argv[i + 1] : d; };
10
+ const GATEWAY = new URL(arg('--gateway', 'http://127.0.0.1:8080/mcp'));
11
+ const OUT = arg('--out', 'audit/task-result.json');
12
+ const DUP_TOLERANCE = 0; // zero tolerance for identical vendor+amount pairs
13
+
14
+ function rpc(method, params) {
15
+ return new Promise((resolve, reject) => {
16
+ const body = JSON.stringify({ jsonrpc: '2.0', id: Math.floor(Math.random() * 1e9), method, params: params ?? {} });
17
+ const req = http.request({ hostname: GATEWAY.hostname, port: GATEWAY.port, path: GATEWAY.pathname, method: 'POST', headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) } }, (res) => {
18
+ let b = ''; res.on('data', c => b += c); res.on('end', () => { try { resolve(JSON.parse(b)); } catch (e) { reject(e); } });
19
+ });
20
+ req.on('error', reject); req.write(body); req.end();
21
+ });
22
+ }
23
+
24
+ const steps = [];
25
+ async function call(tool, args) {
26
+ const r = await rpc('tools/call', { name: tool, arguments: args });
27
+ steps.push({ step: steps.length + 1, tool, args, result: r?.result ?? r?.error ?? null,
28
+ receipt: r?.headers?.['x-neuralbridge-receipt'] ?? null });
29
+ return r?.result ?? null;
30
+ }
31
+
32
+ // Task: month-end AP reconciliation — find duplicate submissions, check the open-item total.
33
+ await rpc('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'audit-agent-demo', version: '0.1.0' } });
34
+ const listed = await call('list_invoices', {});
35
+ const invoices = JSON.parse(listed?.content?.[0]?.text ?? '[]');
36
+
37
+ // check 1: duplicate submissions (same vendor + same amount, different ids)
38
+ const seen = new Map(); const duplicates = [];
39
+ for (const inv of invoices) {
40
+ const key = inv.vendor + '|' + inv.amount.toFixed(2);
41
+ if (seen.has(key)) duplicates.push({ original: seen.get(key), duplicate: inv.id, amount: inv.amount });
42
+ else seen.set(key, inv.id);
43
+ }
44
+
45
+ // check 2: open-item total (submitted/open, not settled)
46
+ const openTotal = invoices.filter(i => i.status !== 'settled').reduce((s, i) => s + i.amount, 0);
47
+
48
+ // confirm the duplicate's current state via a targeted read (signed, digest-only)
49
+ let dupState = null;
50
+ if (duplicates.length) {
51
+ const got = await call('get_invoice', { id: duplicates[0].duplicate });
52
+ dupState = got?.content?.[0]?.text ? JSON.parse(got.content[0].text) : null;
53
+ }
54
+
55
+ // decision: agent wants to settle the duplicate? NO — that is the authorisation boundary this demo shows.
56
+ const proposedWrite = duplicates.length ? { tool: 'settle_invoice', args: { id: duplicates[0].duplicate }, decision: 'REJECTED_BY_POLICY', reason: 'duplicate submissions must go to human review, not auto-settled' } : null;
57
+
58
+ mkdirSync('audit', { recursive: true });
59
+ const result = { task: 'month-end AP reconciliation', fixture: 'ledger-demo 5-invoice set (INV-2026-0043 duplicates INV-2026-0007)',
60
+ checks: { duplicate_policy: DUP_TOLERANCE, duplicates_found: duplicates, open_items_total: openTotal },
61
+ proposed_write: proposedWrite, duplicate_state_confirmed: dupState, conclusion: duplicates.length ? 'FLAG_FOR_HUMAN_REVIEW' : 'CLEAN', steps, receipts_note: 'full signed chain in receipts/chain.jsonl; digest-only args (prompts never in plaintext)' };
62
+ writeFileSync(OUT, JSON.stringify(result, null, 2));
63
+ console.log('task complete:', result.conclusion, '| duplicates:', duplicates.length, '| open total:', openTotal, '| steps signed:', steps.length);
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ // Audit Workbench demo upstream: a minimal MCP server standing in for a finance system.
3
+ // Fixed test data (no randomness) so the demo replays byte-identically anywhere.
4
+ import http from 'node:http';
5
+
6
+ // Deterministic fixture: 5 invoices; INV-2026-0043 is a duplicate submission of INV-2026-0007.
7
+ const INVOICES = [
8
+ { id: 'INV-2026-0001', vendor: 'Cloudline Hosting Ltd', amount: 4200.00, date: '2026-11-03', status: 'settled' },
9
+ { id: 'INV-2026-0002', vendor: 'Meridian Data Co', amount: 18750.00, date: '2026-11-07', status: 'settled' },
10
+ { id: 'INV-2026-0007', vendor: 'Northbeam Consulting', amount: 9600.00, date: '2026-11-12', status: 'settled' },
11
+ { id: 'INV-2026-0021', vendor: 'Atlas Freight GmbH', amount: 2310.50, date: '2026-11-19', status: 'open' },
12
+ { id: 'INV-2026-0043', vendor: 'Northbeam Consulting', amount: 9600.00, date: '2026-11-24', status: 'submitted' },
13
+ ];
14
+
15
+ const jcs = (o) => JSON.stringify(o);
16
+ const server = http.createServer((req, res) => {
17
+ let body = '';
18
+ req.on('data', c => body += c);
19
+ req.on('end', () => {
20
+ let rpc; try { rpc = JSON.parse(body); } catch { rpc = {}; }
21
+ const out = (result) => {
22
+ res.writeHead(200, { 'content-type': 'application/json' });
23
+ res.end(jcs({ jsonrpc: '2.0', id: rpc.id ?? null, result }));
24
+ };
25
+ if (rpc.method === 'initialize') return out({ protocolVersion: '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'ledger-demo', version: '0.1.0' } });
26
+ if (rpc.method === 'tools/list') return out({ tools: [
27
+ { name: 'list_invoices', description: 'List all invoices in the ledger', inputSchema: { type: 'object', properties: {} } },
28
+ { name: 'get_invoice', description: 'Fetch one invoice by id', inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },
29
+ { name: 'settle_invoice', description: 'Mark an invoice as settled (write operation)', inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },
30
+ ] });
31
+ if (rpc.method === 'tools/call') {
32
+ const { name, arguments: a = {} } = rpc.params ?? {};
33
+ if (name === 'list_invoices') return out({ content: [{ type: 'text', text: jcs(INVOICES) }] });
34
+ if (name === 'get_invoice') return out({ content: [{ type: 'text', text: jcs(INVOICES.find(i => i.id === a.id) ?? null) }] });
35
+ if (name === 'settle_invoice') {
36
+ const inv = INVOICES.find(i => i.id === a.id);
37
+ if (inv) inv.status = 'settled';
38
+ return out({ content: [{ type: 'text', text: jcs({ settled: !!inv, id: a.id }) }] });
39
+ }
40
+ return out({ error: { code: -32602, message: 'unknown tool ' + name } });
41
+ }
42
+ res.writeHead(400); res.end();
43
+ });
44
+ });
45
+ server.listen(Number(process.env.LEDGER_PORT || 8001), '127.0.0.1', () => console.log('ledger-demo upstream on :' + (process.env.LEDGER_PORT || 8001)));
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env bash
2
+ # Audit Workbench demo — one command, deterministic, fully signed.
3
+ # Agent reconciles a 5-invoice AP ledger through the gateway; every tool call gets an
4
+ # Ed25519 receipt; workpaper + receipt chain are independently verifiable offline.
5
+ set -euo pipefail
6
+ cd "$(dirname "$0")/.."
7
+ rm -rf receipts audit/task-result.json gateway/demo-seed.hex
8
+ node audit/ledger-mcp.mjs & LEDGER_PID=$!
9
+ sleep 0.5
10
+ NEURALBRIDGE_ALLOW="list_invoices,get_invoice,settle_invoice" node gateway/gateway.mjs --target http://127.0.0.1:8001/mcp --port 8080 --key gateway/demo-seed.hex & GW_PID=$!
11
+ sleep 0.7
12
+ node audit/agent.mjs --gateway http://127.0.0.1:8080/mcp --out audit/task-result.json
13
+ kill $GW_PID $LEDGER_PID 2>/dev/null || true
14
+ node audit/verify.mjs --chain receipts/chain.jsonl --workpaper audit/task-result.json
15
+ echo "--- workpaper head ---"
16
+ head -c 400 audit/task-result.json; echo
@@ -0,0 +1,64 @@
1
+ {
2
+ "task": "month-end AP reconciliation",
3
+ "fixture": "ledger-demo 5-invoice set (INV-2026-0043 duplicates INV-2026-0007)",
4
+ "checks": {
5
+ "duplicate_policy": 0,
6
+ "duplicates_found": [
7
+ {
8
+ "original": "INV-2026-0007",
9
+ "duplicate": "INV-2026-0043",
10
+ "amount": 9600
11
+ }
12
+ ],
13
+ "open_items_total": 11910.5
14
+ },
15
+ "proposed_write": {
16
+ "tool": "settle_invoice",
17
+ "args": {
18
+ "id": "INV-2026-0043"
19
+ },
20
+ "decision": "REJECTED_BY_POLICY",
21
+ "reason": "duplicate submissions must go to human review, not auto-settled"
22
+ },
23
+ "duplicate_state_confirmed": {
24
+ "id": "INV-2026-0043",
25
+ "vendor": "Northbeam Consulting",
26
+ "amount": 9600,
27
+ "date": "2026-11-24",
28
+ "status": "submitted"
29
+ },
30
+ "conclusion": "FLAG_FOR_HUMAN_REVIEW",
31
+ "steps": [
32
+ {
33
+ "step": 1,
34
+ "tool": "list_invoices",
35
+ "args": {},
36
+ "result": {
37
+ "content": [
38
+ {
39
+ "type": "text",
40
+ "text": "[{\"id\":\"INV-2026-0001\",\"vendor\":\"Cloudline Hosting Ltd\",\"amount\":4200,\"date\":\"2026-11-03\",\"status\":\"settled\"},{\"id\":\"INV-2026-0002\",\"vendor\":\"Meridian Data Co\",\"amount\":18750,\"date\":\"2026-11-07\",\"status\":\"settled\"},{\"id\":\"INV-2026-0007\",\"vendor\":\"Northbeam Consulting\",\"amount\":9600,\"date\":\"2026-11-12\",\"status\":\"settled\"},{\"id\":\"INV-2026-0021\",\"vendor\":\"Atlas Freight GmbH\",\"amount\":2310.5,\"date\":\"2026-11-19\",\"status\":\"open\"},{\"id\":\"INV-2026-0043\",\"vendor\":\"Northbeam Consulting\",\"amount\":9600,\"date\":\"2026-11-24\",\"status\":\"submitted\"}]"
41
+ }
42
+ ]
43
+ },
44
+ "receipt": null
45
+ },
46
+ {
47
+ "step": 2,
48
+ "tool": "get_invoice",
49
+ "args": {
50
+ "id": "INV-2026-0043"
51
+ },
52
+ "result": {
53
+ "content": [
54
+ {
55
+ "type": "text",
56
+ "text": "{\"id\":\"INV-2026-0043\",\"vendor\":\"Northbeam Consulting\",\"amount\":9600,\"date\":\"2026-11-24\",\"status\":\"submitted\"}"
57
+ }
58
+ ]
59
+ },
60
+ "receipt": null
61
+ }
62
+ ],
63
+ "receipts_note": "full signed chain in receipts/chain.jsonl; digest-only args (prompts never in plaintext)"
64
+ }
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ // Independent workpaper verifier — offline, zero trust in the agent or the gateway.
3
+ // (1) chain integrity + Ed25519 signature per receipt; (2) workpaper consistency:
4
+ // every agent step must match a receipt by args_digest; (3) tamper-detectable.
5
+ // Usage: node audit/verify.mjs [--chain receipts/chain.jsonl] [--workpaper audit/task-result.json]
6
+ import { readFileSync, existsSync } from 'node:fs';
7
+ import { createHash, createPublicKey, verify } from 'node:crypto';
8
+
9
+ const arg = (n, d) => { const i = process.argv.indexOf(n); return i >= 0 ? process.argv[i + 1] : d; };
10
+ const CHAIN = arg('--chain', 'receipts/chain.jsonl');
11
+ const WP = arg('--workpaper', 'audit/task-result.json');
12
+ const jcs = (o) => Array.isArray(o) ? '[' + o.map(jcs).join(',') + ']'
13
+ : (o && typeof o === 'object') ? '{' + Object.keys(o).sort().map(k => JSON.stringify(k) + ':' + jcs(o[k])).join(',') + '}'
14
+ : JSON.stringify(o);
15
+
16
+ const fails = [];
17
+ const lines = readFileSync(CHAIN, 'utf8').trim().split('\n').map(l => JSON.parse(l));
18
+ let prev = '0'.repeat(64);
19
+ for (const [i, r] of lines.entries()) {
20
+ if (r.prev_hash !== prev) fails.push(`line ${i + 1}: chain break (prev_hash mismatch)`);
21
+ prev = r.receipt_hash;
22
+ // signature covers the 8 gateway-payload fields exactly (gateway.mjs receipt()):
23
+ const payload = { correlation_id: r.correlation_id, decided_at: r.decided_at, tool: r.tool,
24
+ verdict: r.verdict, reason: r.reason, args_digest: r.args_digest, signer_key_id: r.signer_key_id, prev_hash: r.prev_hash };
25
+ const sigBuf = Buffer.from(jcs(payload), 'utf8');
26
+ // signer_pubkey is the RAW 32-byte Ed25519 public key (SPKI header stripped by gateway)
27
+ const SPKI = Buffer.from('302a300506032b6570032100', 'hex');
28
+ const pk = createPublicKey({ key: Buffer.concat([SPKI, Buffer.from(r.signer_pubkey, 'base64')]), format: 'der', type: 'spki' });
29
+ if (!verify(null, sigBuf, pk, Buffer.from(r.signature, 'base64'))) fails.push(`line ${i + 1}: Ed25519 signature INVALID`);
30
+ // receipt_hash covers the full record minus receipt_hash itself (incl. signature & pubkey)
31
+ const { receipt_hash, ...rec } = r;
32
+ if (createHash('sha256').update(jcs(rec)).digest('hex') !== receipt_hash) fails.push(`line ${i + 1}: receipt_hash mismatch`);
33
+ }
34
+
35
+ if (existsSync(WP)) {
36
+ const wp = JSON.parse(readFileSync(WP, 'utf8'));
37
+ const digests = new Set(lines.map(r => r.args_digest));
38
+ for (const s of wp.steps ?? []) {
39
+ const d = 'sha256-' + createHash('sha256').update(jcs(s.args ?? {})).digest('base64');
40
+ if (!digests.has(d)) fails.push(`workpaper step ${s.step} (${s.tool}): no matching signed receipt for args_digest`);
41
+ }
42
+ const executed = (wp.steps ?? []).filter(s => s.tool === 'settle_invoice');
43
+ if (executed.length && wp.proposed_write?.decision === 'REJECTED_BY_POLICY')
44
+ fails.push('workpaper says write was REJECTED_BY_POLICY but a settle_invoice call was actually executed');
45
+ }
46
+
47
+ console.log(fails.length ? 'VERIFY FAIL:\n' + fails.join('\n')
48
+ : `VERIFY PASS: ${lines.length} receipts, chain intact, all signatures valid${existsSync(WP) ? ', workpaper consistent' : ''}`);
49
+ process.exit(fails.length ? 1 : 0);
package/bin/nb.mjs ADDED
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env node
2
+ // nb — NeuralBridge receipt toolkit.
3
+ // nb verify [--chain receipts/chain.jsonl] [--workpaper workpaper.json]
4
+ // nb report [--chain receipts/chain.jsonl] [--out receipts/report.html]
5
+ // Zero dependencies. The verifier trusts only the Ed25519 signatures and the hash chain.
6
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
7
+ import { createHash, createPublicKey, verify } from 'node:crypto';
8
+
9
+ const args = process.argv.slice(2);
10
+ const cmd = args[0];
11
+ const arg = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
12
+ const jcs = (o) => Array.isArray(o) ? '[' + o.map(jcs).join(',') + ']'
13
+ : (o && typeof o === 'object') ? '{' + Object.keys(o).sort().map(k => JSON.stringify(k) + ':' + jcs(o[k])).join(',') + '}'
14
+ : JSON.stringify(o);
15
+
16
+ const CHAIN = arg('--chain', 'receipts/chain.jsonl');
17
+ if (!cmd || !['verify', 'report'].includes(cmd)) {
18
+ console.log(`nb — NeuralBridge receipt toolkit
19
+
20
+ neuralbridge-gateway --target http://host/mcp --port 8080 run the signing gateway
21
+ nb verify [--chain receipts/chain.jsonl] [--workpaper wp.json]
22
+ verify chain integrity + every Ed25519 signature + workpaper consistency
23
+ nb report [--chain receipts/chain.jsonl] [--out receipts/report.html]
24
+ generate a shareable HTML audit report (verifies, then renders)
25
+
26
+ A log is a story the application tells about itself. A receipt is a signed
27
+ commitment anyone can re-verify offline — same discipline as
28
+ draft-correctover-ccs (individual submission, not an RFC or IETF endorsement).`);
29
+ process.exit(cmd ? 1 : 0);
30
+ }
31
+
32
+ function loadChain() {
33
+ if (!existsSync(CHAIN)) { console.error(`no chain at ${CHAIN} — run the gateway first`); process.exit(1); }
34
+ return readFileSync(CHAIN, 'utf8').trim().split('\n').map(l => JSON.parse(l));
35
+ }
36
+ function verifyChain(lines, workpaperPath) {
37
+ const fails = [];
38
+ let prev = '0'.repeat(64);
39
+ const SPKI = Buffer.from('302a300506032b6570032100', 'hex');
40
+ for (const [i, r] of lines.entries()) {
41
+ if (r.prev_hash !== prev) fails.push(`line ${i + 1}: chain break (prev_hash mismatch)`);
42
+ prev = r.receipt_hash;
43
+ const payload = { correlation_id: r.correlation_id, decided_at: r.decided_at, tool: r.tool, verdict: r.verdict,
44
+ reason: r.reason, args_digest: r.args_digest, signer_key_id: r.signer_key_id, prev_hash: r.prev_hash };
45
+ const pk = createPublicKey({ key: Buffer.concat([SPKI, Buffer.from(r.signer_pubkey, 'base64')]), format: 'der', type: 'spki' });
46
+ if (!verify(null, Buffer.from(jcs(payload), 'utf8'), pk, Buffer.from(r.signature, 'base64')))
47
+ fails.push(`line ${i + 1}: Ed25519 signature INVALID`);
48
+ const { receipt_hash, ...rec } = r;
49
+ if (createHash('sha256').update(jcs(rec)).digest('hex') !== receipt_hash) fails.push(`line ${i + 1}: receipt_hash mismatch`);
50
+ }
51
+ if (workpaperPath && existsSync(workpaperPath)) {
52
+ const wp = JSON.parse(readFileSync(workpaperPath, 'utf8'));
53
+ const digests = new Set(lines.map(r => r.args_digest));
54
+ for (const s of wp.steps ?? []) {
55
+ const d = 'sha256-' + createHash('sha256').update(jcs(s.args ?? {})).digest('base64');
56
+ if (!digests.has(d)) fails.push(`workpaper step ${s.step} (${s.tool}): no matching signed receipt`);
57
+ }
58
+ const executed = (wp.steps ?? []).filter(s => s.tool === 'settle_invoice');
59
+ if (executed.length && wp.proposed_write?.decision === 'REJECTED_BY_POLICY')
60
+ fails.push('workpaper claims write REJECTED_BY_POLICY but it was executed');
61
+ }
62
+ return fails;
63
+ }
64
+
65
+ if (cmd === 'verify') {
66
+ const wp = arg('--workpaper', null);
67
+ const fails = verifyChain(loadChain(), wp);
68
+ console.log(fails.length ? 'VERIFY FAIL:\n' + fails.join('\n')
69
+ : `VERIFY PASS: ${loadChain().length} receipts, chain intact, all signatures valid${wp ? ', workpaper consistent' : ''}`);
70
+ process.exit(fails.length ? 1 : 0);
71
+ }
72
+
73
+ if (cmd === 'report') {
74
+ const lines = loadChain();
75
+ const fails = verifyChain(lines, null);
76
+ const rows = lines.map((r, i) => `<tr><td>${i + 1}</td><td>${r.tool}</td><td><span class="v ${r.verdict === 'ALLOW' ? 'ok' : 'no'}">${r.verdict}</span></td><td class="mono">${String(r.args_digest).slice(0, 22)}…</td><td class="mono">${String(r.receipt_hash).slice(0, 16)}…</td><td>${r.decided_at}</td></tr>`).join('\n');
77
+ const status = fails.length
78
+ ? `<div class="banner fail">VERIFY FAIL — ${fails.length} issue(s):<br>${fails.join('<br>')}</div>`
79
+ : `<div class="banner ok">✔ VERIFY PASS — ${lines.length} receipts, hash chain intact, every Ed25519 signature valid. This page was generated from the chain itself; anyone can re-verify with: <code>npx neuralbridge-gateway nb verify --chain chain.jsonl</code></div>`;
80
+ const html = `<!doctype html><html><head><meta charset="utf-8"><title>NeuralBridge receipt chain — audit report</title><style>
81
+ body{font:14px/1.5 -apple-system,sans-serif;margin:40px auto;max-width:960px;color:#1a1a2e}
82
+ h1{font-size:20px} .mono{font-family:ui-monospace,monospace;font-size:12px}
83
+ table{width:100%;border-collapse:collapse;margin-top:16px} td,th{padding:6px 10px;border-bottom:1px solid #e2e2ea;text-align:left}
84
+ .banner{padding:14px 18px;border-radius:8px;margin:16px 0;font-size:14px}
85
+ .ok{background:#e8f7ee;border:1px solid #28a745;color:#14532d} .fail{background:#fdeaea;border:1px solid #dc3545;color:#7f1d1d}
86
+ .v{padding:2px 8px;border-radius:4px;font-size:12px} .v.ok{background:#d1f2df} .v.no{background:#f8d0d4}
87
+ footer{margin-top:28px;color:#666;font-size:12px}</style></head><body>
88
+ <h1>Agent tool-call receipt chain — audit report</h1>
89
+ <p>Generated by <code>nb report</code> (neuralbridge-gateway). Every tool call made by the agent through the gateway is signed (Ed25519), hash-chained, and carries digest-only arguments (SHA-256/JCS — no plaintext parameters). Verdicts: the gateway's allowlist decision at call time.</p>
90
+ ${status}
91
+ <table><tr><th>#</th><th>tool</th><th>verdict</th><th>args digest</th><th>receipt hash</th><th>signed at (UTC)</th></tr>
92
+ ${rows}</table>
93
+ <footer>Spec: draft-correctover-ccs (individual submission, not an RFC or IETF endorsement) · Code: github.com/DSHCorrectover/neuralbridge (MIT) · Tamper test: change one byte of any receipt above and re-run <code>nb verify</code> — the chain goes red.</footer>
94
+ </body></html>`;
95
+ const out = arg('--out', 'receipts/report.html');
96
+ writeFileSync(out, html);
97
+ console.log(`report written: ${out} (${lines.length} receipts, ${fails.length} issues)`);
98
+ process.exit(0);
99
+ }
@@ -0,0 +1 @@
1
+ b202bed1208a79e7eceef36b916b3e4bf78808ee1f865783b27fdfa3ed572832
@@ -0,0 +1,133 @@
1
+ #!/usr/bin/env node
2
+ // NeuralBridge Gateway v0.1 — MCP proxy that signs a CCS-verifiable receipt for every tool call.
3
+ // Every action your agent takes comes with a receipt anyone can verify.
4
+ // Zero dependencies: node:http + node:crypto only.
5
+ //
6
+ // node gateway/gateway.mjs --target http://localhost:8000/mcp --port 8080 [--key gateway/demo-seed.hex]
7
+ //
8
+ // What it does per POST /mcp request:
9
+ // 1. Parse the JSON-RPC body. If it is a tools/call:
10
+ // 2. Check the tool against the allowlist (NEURALBRIDGE_ALLOW env, comma-separated; default: allow all, log only).
11
+ // 3. Sign a CCS receipt: Ed25519 over {correlation_id, decided_at, tool, args_digest=SHA-256(JCS(args)), verdict, prev_hash}.
12
+ // 4. Forward to the upstream MCP server; attach the receipt base64 in the X-NeuralBridge-Receipt response header.
13
+ // 5. Receipts append to receipts/chain.jsonl — a hash-chained, offline-verifiable audit log.
14
+ import http from 'node:http';
15
+ import { createHash, createPrivateKey, createPublicKey, sign, randomUUID } from 'node:crypto';
16
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, appendFileSync } from 'node:fs';
17
+
18
+ const arg = (n, d) => { const i = process.argv.indexOf(n); return i >= 0 ? process.argv[i + 1] : d; };
19
+ const TARGET = new URL(arg('--target', 'http://localhost:8000/mcp'));
20
+ const PORT = Number(arg('--port', 8080));
21
+ const KEYFILE = arg('--key', 'gateway/demo-seed.hex');
22
+
23
+ const PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
24
+ if (!existsSync(KEYFILE)) writeFileSync(KEYFILE, createHash('sha256').update(String(process.pid) + String(Date.now())).digest('hex'));
25
+ const seed = Buffer.from(readFileSync(KEYFILE, 'utf8').trim(), 'hex');
26
+ const priv = createPrivateKey({ key: Buffer.concat([PKCS8_PREFIX, seed]), format: 'der', type: 'pkcs8' });
27
+ const PUB_RAW = createPublicKey(priv).export({ format: 'der', type: 'spki' }).subarray(12).toString('base64');
28
+
29
+ const ALLOW = (process.env.NEURALBRIDGE_ALLOW || '').split(',').map(s => s.trim()).filter(Boolean);
30
+ // Resilience layer (v0.2) — semantics re-implemented from legacy python SelfHealingEngine:
31
+ // L1 = same-model retry, exponential backoff + jitter; L2/L3 fields reserved in receipts.
32
+ const RB_MAX = Number(process.env.NEURALBRIDGE_RETRIES || 3); // L1 attempts
33
+ const RB_BASE = Number(process.env.NEURALBRIDGE_BACKOFF_MS || 200);
34
+ const CB_THRESHOLD = Number(process.env.NEURALBRIDGE_BREAKER_THRESHOLD || 5);
35
+ const CB_COOLDOWN = Number(process.env.NEURALBRIDGE_COOLDOWN_MS || 3000);
36
+ const CB_TIMEOUT = Number(process.env.NEURALBRIDGE_UPSTREAM_TIMEOUT_MS || 5000);
37
+ const breaker = { state: 'closed', fails: 0, openedAt: 0 }; // closed|open|half-open
38
+ mkdirSync('receipts', { recursive: true });
39
+ const CHAIN = 'receipts/chain.jsonl';
40
+ const jcs = (o) => Array.isArray(o) ? '[' + o.map(jcs).join(',') + ']'
41
+ : (o && typeof o === 'object') ? '{' + Object.keys(o).sort().map(k => JSON.stringify(k) + ':' + jcs(o[k])).join(',') + '}'
42
+ : JSON.stringify(o);
43
+ const prevHash = () => { try { return JSON.parse(readFileSync(CHAIN, 'utf8').trim().split('\n').pop()).receipt_hash; } catch { return '0'.repeat(64); } };
44
+
45
+ function receipt(tool, args, verdict, reason) {
46
+ const payload = {
47
+ correlation_id: randomUUID(),
48
+ decided_at: new Date().toISOString(),
49
+ tool, verdict, reason: reason || null,
50
+ args_digest: 'sha256-' + createHash('sha256').update(jcs(args ?? {})).digest('base64'),
51
+ signer_key_id: 'neuralbridge-gateway-' + PUB_RAW.slice(0, 8),
52
+ prev_hash: prevHash(),
53
+ };
54
+ const sig = sign(null, Buffer.from(jcs(payload), 'utf8'), priv);
55
+ const rec = { ...payload, algorithm: 'Ed25519', signer_pubkey: PUB_RAW, signature: sig.toString('base64') };
56
+ rec.receipt_hash = createHash('sha256').update(jcs(rec)).digest('hex');
57
+ appendFileSync(CHAIN, JSON.stringify(rec) + '\n');
58
+ return Buffer.from(JSON.stringify(rec)).toString('base64');
59
+ }
60
+
61
+ const server = http.createServer(async (req, res) => {
62
+ if (req.method !== 'POST') { res.writeHead(405).end(); return; }
63
+ let body = [];
64
+ req.on('data', c => body.push(c));
65
+ req.on('end', async () => {
66
+ const raw = Buffer.concat(body);
67
+ let verdict = 'ALLOW', reason = null, tool = null, args = null;
68
+ try {
69
+ const rpc = JSON.parse(raw.toString('utf8'));
70
+ if (rpc.method === 'tools/call') {
71
+ tool = rpc.params?.name; args = rpc.params?.arguments;
72
+ if (ALLOW.length && tool && !ALLOW.includes(tool)) { verdict = 'BLOCK'; reason = 'tool-not-in-allowlist'; }
73
+ }
74
+ } catch { /* non-JSON: forward untouched */ }
75
+ const r64 = receipt(tool || 'unknown', args, verdict, reason);
76
+ if (verdict === 'BLOCK') {
77
+ res.writeHead(403, { 'Content-Type': 'application/json', 'X-NeuralBridge-Receipt': r64 });
78
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32602, message: 'blocked by neuralbridge gateway: ' + reason, receipt: JSON.parse(Buffer.from(r64, 'base64').toString()) } }));
79
+ return;
80
+ }
81
+ // B: dignified refusal — breaker open (before cooldown) => structured receipt, never naked 503
82
+ if (breaker.state === 'open') {
83
+ const since = Date.now() - breaker.openedAt;
84
+ if (since < CB_COOLDOWN) {
85
+ // re-sign with breaker reason
86
+ const rr = JSON.parse(Buffer.from(r64, 'base64').toString());
87
+ rr.reason = 'breaker-open-cooldown-' + Math.ceil((CB_COOLDOWN - since) / 1000) + 's'; rr.verdict = 'BLOCK';
88
+ const rr2 = Buffer.from(JSON.stringify(rr)).toString('base64');
89
+ res.writeHead(503, { 'Content-Type': 'application/json', 'X-NeuralBridge-Receipt': rr2 });
90
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32003, message: 'neuralbridge gateway: circuit open, cooldown ' + Math.ceil((CB_COOLDOWN - since) / 1000) + 's', receipt: rr } }));
91
+ return;
92
+ }
93
+ breaker.state = 'half-open'; // single probe: exactly one in-flight request validates recovery
94
+ }
95
+ // A: L1 retry with exponential backoff + jitter; hang detection via timeout
96
+ let attempt = 0, lastErr = null, upstreamRes = null;
97
+ while (attempt <= RB_MAX) {
98
+ upstreamRes = await new Promise((resolve) => {
99
+ const up = http.request({ hostname: TARGET.hostname, port: TARGET.port || 80, path: TARGET.pathname, method: 'POST', headers: { ...req.headers, host: TARGET.host } }, ur => {
100
+ let b = []; ur.on('data', c => b.push(c));
101
+ ur.on('end', () => resolve({ status: ur.statusCode, headers: ur.headers, body: Buffer.concat(b) }));
102
+ });
103
+ up.setTimeout(CB_TIMEOUT, () => { up.destroy(); resolve({ status: 0, headers: {}, body: null, timeout: true }); });
104
+ up.on('error', e => resolve({ status: 0, headers: {}, body: null, err: e.code }));
105
+ up.end(raw);
106
+ }).catch(() => ({ status: 0, headers: {}, body: null }));
107
+ const transient = upstreamRes.status === 0 || upstreamRes.status === 500 || upstreamRes.status === 502 || upstreamRes.status === 503 || upstreamRes.status === 504;
108
+ if (!transient || breaker.state === 'half-open') break; // half-open probe: no retry storm
109
+ breaker.fails++;
110
+ attempt++;
111
+ if (attempt <= RB_MAX) {
112
+ const backoff = RB_BASE * Math.pow(2, attempt - 1) + Math.floor(Math.random() * RB_BASE); // exp + jitter
113
+ await new Promise(r => setTimeout(r, backoff));
114
+ }
115
+ }
116
+ if (upstreamRes.status === 0 || (upstreamRes.status >= 500 && breaker.state !== 'half-open')) breaker.fails++; else if (upstreamRes.status && upstreamRes.status < 500) { breaker.fails = 0; breaker.state = 'closed'; }
117
+ if (breaker.fails >= CB_THRESHOLD && breaker.state !== 'open') { breaker.state = 'open'; breaker.openedAt = Date.now(); }
118
+ if (breaker.state === 'half-open') {
119
+ if (upstreamRes.status && upstreamRes.status < 500) { breaker.state = 'closed'; breaker.fails = 0; }
120
+ else { breaker.state = 'open'; breaker.openedAt = Date.now(); }
121
+ }
122
+ // final response — receipt always attached, even on failure (A2: fail-closed chain)
123
+ const finalRec = (() => { try { const rr = JSON.parse(Buffer.from(r64, 'base64').toString()); rr.l1_attempts = attempt; rr.breaker_state = breaker.state; rr.l2_downgraded = false; rr.l3_failed_over = false; return Buffer.from(JSON.stringify(rr)).toString('base64'); } catch { return r64; } })();
124
+ if (upstreamRes.status === 0) {
125
+ res.writeHead(502, { 'Content-Type': 'application/json', 'X-NeuralBridge-Receipt': finalRec });
126
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32002, message: 'upstream unreachable after L1 retries', receipt: JSON.parse(Buffer.from(finalRec, 'base64').toString()) } }));
127
+ } else {
128
+ res.writeHead(upstreamRes.status, { ...upstreamRes.headers, 'X-NeuralBridge-Receipt': finalRec });
129
+ res.end(upstreamRes.body);
130
+ }
131
+ });
132
+ });
133
+ server.listen(PORT, () => console.log(`neuralbridge gateway :${PORT} -> ${TARGET.href} | pubkey ${PUB_RAW.slice(0, 8)}… | receipts -> ${CHAIN}`));
package/package.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "name": "neuralbridge-gateway",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "MCP gateway that signs a verifiable, hash-chained receipt for every agent tool call — fail-with-evidence, offline-verifiable by any third party.",
5
+ "license": "MIT",
6
+ "author": "Guigui Wang <wangguigui@correctover.com>",
7
+ "repository": { "type": "git", "url": "git+https://github.com/DSHCorrectover/neuralbridge.git" },
8
+ "keywords": ["mcp", "agent", "receipt", "audit", "ed25519", "gateway", "evidence", "fail-closed"],
9
+ "type": "module",
10
+ "bin": {
11
+ "neuralbridge-gateway": "./gateway/gateway.mjs",
12
+ "nb": "./bin/nb.mjs"
13
+ },
14
+ "files": ["gateway/", "bin/", "audit/", "README.md", "LICENSE"],
15
+ "engines": { "node": ">=18" }
16
+ }