From 7f327fb34b4c2202e1c9ef26e48493b5efb7c8f2 Mon Sep 17 00:00:00 2001 From: Storm Date: Sat, 21 Nov 2026 22:47:11 +0100 Subject: [PATCH 1/2] fix(example): verify locally logged audit CIDs --- .gitignore | 2 + examples/audit-forensic-bridge/README.md | 62 +++++-- examples/audit-forensic-bridge/package.json | 4 +- examples/audit-forensic-bridge/src/anchors.ts | 43 +++++ examples/audit-forensic-bridge/src/export.ts | 168 ++++++++---------- examples/audit-forensic-bridge/src/server.ts | 11 +- .../audit-forensic-bridge/test/export.test.ts | 73 ++++++++ examples/audit-forensic-bridge/tsconfig.json | 13 ++ 8 files changed, 270 insertions(+), 106 deletions(-) create mode 100644 examples/audit-forensic-bridge/src/anchors.ts create mode 100644 examples/audit-forensic-bridge/test/export.test.ts create mode 100644 examples/audit-forensic-bridge/tsconfig.json diff --git a/.gitignore b/.gitignore index 47dcf033..50e2b083 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,5 @@ actions/verify-audit-cid/lib/ !actions/verify-audit-cid/dist/ !actions/verify-audit-cid/dist/** .next/ +examples/audit-forensic-bridge/anchors.jsonl +examples/audit-forensic-bridge/audit-verified-report.json diff --git a/examples/audit-forensic-bridge/README.md b/examples/audit-forensic-bridge/README.md index e7111a09..d6c0f776 100644 --- a/examples/audit-forensic-bridge/README.md +++ b/examples/audit-forensic-bridge/README.md @@ -9,10 +9,11 @@ Contributed by [Santia2004](https://github.com/Santia2004) in [#69](https://github.com/nirium-protocol/nirium/pull/69) (Aug 2026). ``` -src/server.ts POST /webhook -> anchorAuditRecord({ record, tag: 'webhook-event', agent? }) +src/server.ts POST /webhook -> anchorAuditRecord({ record, tag: 'wave11-forensic-bridge', agent? }) src/attestation.ts sha256 of the record, domain-prefixed message, sign and verify -src/export.ts reporting export + re-check (see the limit below) -test/bridge.test.ts offline tests for the signing and verification +src/anchors.ts local, git-ignored receipt log (anchors.jsonl) +src/export.ts verify each logged CID with the published Nirium CLI +test/*.test.ts offline tests for signing, storage and export ``` ## Setup @@ -53,15 +54,50 @@ with `npx nirium-cli@latest verify ` or at [nirium.xyz/verify](https://niri pnpm test ``` -Four offline tests: the hash is computed over the record as sent (key order matters), a signature -verifies, a changed record fails verification, and the message carries the `nirium-audit-v1:` -prefix. No network. +The tests use placeholders and make no network calls. They cover signing, a changed record, an +invalid signature, the local receipt log, and export results. -## Limit: `pnpm export` does not work against the hosted agent +## Export your own anchors -`src/export.ts` reads the anchors export and re-checks each CID. It was written when the export -returned a CID and hash per row. The Reporting export no longer returns CIDs (a CID belongs to -whoever anchored it): today each row has only `anchored_at`, `source` and `network`, so there is -nothing to fetch. It also hashes the whole IPFS document and compares that with the record's -`content_sha256`, which would not match even with a CID. To re-check what you anchored, keep the -CIDs from the `/webhook` responses and run `nirium verify` on them. +Each successful webhook appends its CID, `contentSha256`, and optional `attestedBy` to the local +`anchors.jsonl`. The file is git-ignored and stays on this machine. Back it up if you need a +lasting record of your anchors. The public Reporting export lists dates, sources and networks; +it does not return other people's CIDs. + +```bash +pnpm export +``` + +Export invokes `npx nirium-cli@latest verify --json` for every locally logged CID. The CLI +retrieves the IPFS document and checks its record hash and any agent signature. The bridge also +compares the verified document's hash to the one it logged at anchor time. It writes +`audit-verified-report.json` locally, prints verified and failed counts and a reason for every +failure, and exits nonzero if any record fails. Neither the webhook nor export sends raw records +to the Reporting service. + +A verified receipt proves that the record in the IPFS document has not changed since it was +anchored and, when an agent signature is present, which Stellar key signed it. It does **not** +prove that the record is true. `anchoredAt` is the Nirium node's clock, not a ledger timestamp. +Anchor only hashes or small non-personal records: IPFS content cannot be deleted. + +## Testnet run (21 November 2026) + +I generated a new Stellar key locally for this run; its public key is +`GBBQIOW2ACAHEGY6QJ7Z64ZMT4RDTUYH5ZC5HUV3CD72CWXMGPD5GUO2`. The secret stays in the +git-ignored `.env`. Two non-personal placeholder events were posted to the local `/webhook` +against `https://nirium-agent.fly.dev`, using the `wave11-forensic-bridge` tag: + +| CID | `nirium verify` | +|---|---| +| `QmdG5F3ZVF7WJHQzz9DUhcZSsCfRxbAn1cCWHVy36nb9B5` | `verified: true`, hash match, valid ed25519 signature | +| `QmTYLcQDYcbjd6FRtTX7F2LZqtP6wXUdrfEp5cNnnJcGAW` | `verified: true`, hash match, valid ed25519 signature | + +Both were checked independently with `npx --yes nirium-cli@latest verify --json`. +The `pnpm export` output was: + +```text +Verified: 2; failed: 0; total: 2 +VERIFIED QmdG5F3ZVF7WJHQzz9DUhcZSsCfRxbAn1cCWHVy36nb9B5 +VERIFIED QmTYLcQDYcbjd6FRtTX7F2LZqtP6wXUdrfEp5cNnnJcGAW +Report written to audit-verified-report.json +``` diff --git a/examples/audit-forensic-bridge/package.json b/examples/audit-forensic-bridge/package.json index f13edadc..7e9c41d9 100644 --- a/examples/audit-forensic-bridge/package.json +++ b/examples/audit-forensic-bridge/package.json @@ -6,7 +6,7 @@ "scripts": { "dev": "tsx src/server.ts", "export": "tsx src/export.ts", - "test": "tsx --test test/bridge.test.ts", + "test": "tsx --test test/*.test.ts", "typecheck": "tsc --noEmit" }, "dependencies": { @@ -21,4 +21,4 @@ "tsx": "^4.23.15", "typescript": "^5.9.3" } -} \ No newline at end of file +} diff --git a/examples/audit-forensic-bridge/src/anchors.ts b/examples/audit-forensic-bridge/src/anchors.ts new file mode 100644 index 00000000..f9367332 --- /dev/null +++ b/examples/audit-forensic-bridge/src/anchors.ts @@ -0,0 +1,43 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; + +export interface AnchoredReceipt { + cid: string; + contentSha256: string; + attestedBy?: string; +} + +export const DEFAULT_LOG_PATH = path.resolve(process.cwd(), 'anchors.jsonl'); + +export async function appendAnchor(receipt: AnchoredReceipt, logPath = DEFAULT_LOG_PATH): Promise { + await fs.appendFile(logPath, `${JSON.stringify(receipt)}\n`, { encoding: 'utf8', mode: 0o600 }); +} + +export async function readAnchors(logPath = DEFAULT_LOG_PATH): Promise { + let contents: string; + try { + contents = await fs.readFile(logPath, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; + throw error; + } + + return contents.split(/\r?\n/).filter(Boolean).map((line, index) => { + let value: unknown; + try { + value = JSON.parse(line); + } catch { + throw new Error(`Invalid anchor log at line ${index + 1}`); + } + if (!value || typeof value !== 'object') throw new Error(`Invalid anchor log at line ${index + 1}`); + const receipt = value as Record; + if (typeof receipt.cid !== 'string' || typeof receipt.contentSha256 !== 'string') { + throw new Error(`Invalid anchor log at line ${index + 1}`); + } + return { + cid: receipt.cid, + contentSha256: receipt.contentSha256, + ...(typeof receipt.attestedBy === 'string' ? { attestedBy: receipt.attestedBy } : {}), + }; + }); +} diff --git a/examples/audit-forensic-bridge/src/export.ts b/examples/audit-forensic-bridge/src/export.ts index e39c3e07..f6620e87 100644 --- a/examples/audit-forensic-bridge/src/export.ts +++ b/examples/audit-forensic-bridge/src/export.ts @@ -1,119 +1,109 @@ -import { Agent } from 'nirium'; -import { createHash } from 'node:crypto'; -import { verifyAuditAttestation } from './attestation.js'; -import dotenv from 'dotenv'; +import { spawn } from 'node:child_process'; import fs from 'node:fs/promises'; import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import dotenv from 'dotenv'; +import { DEFAULT_LOG_PATH, readAnchors, type AnchoredReceipt } from './anchors.js'; dotenv.config(); -const NIRIUM_API_KEY = process.env.NIRIUM_API_KEY || 'nrm_test_key'; -const NIRIUM_BASE_URL = process.env.NIRIUM_BASE_URL || 'http://localhost:3002'; -const IPFS_GATEWAY = process.env.IPFS_GATEWAY || 'https://ipfs.io/ipfs/'; - -const agent = new Agent({ - apiKey: NIRIUM_API_KEY, - baseUrl: NIRIUM_BASE_URL, -}); +export interface CliVerification { + verified: boolean; + expectedHash?: string; + hashStatus?: string; + signatureStatus?: string; + error?: string; +} -export interface VerifiedAnchorReportItem { - cid: string; - contentSha256: string; +export interface VerifiedAnchorReportItem extends AnchoredReceipt { verified: boolean; - tamperDetected: boolean; - signatureValid?: boolean; - attestedBy?: string; reason?: string; } -export async function fetchAndVerifyAnchors(options?: { from?: string; to?: string }): Promise<{ +export interface VerifiedAnchorReport { totalExported: number; verifiedCount: number; flaggedCount: number; records: VerifiedAnchorReportItem[]; -}> { - const exportData = await agent.getReportingExport('anchors', options); - const rows = (exportData.rows || exportData.anchors || []) as Array; - - const records: VerifiedAnchorReportItem[] = []; - - for (const row of rows) { - const cid = row.cid; - const claimedSha = row.contentSha256 || row.hash; - const gatewayUrl = `${IPFS_GATEWAY.replace(/\/$/, '')}/${cid}`; - - try { - const response = await fetch(gatewayUrl, { signal: AbortSignal.timeout(10000) }); - if (!response.ok) { - records.push({ - cid, - contentSha256: claimedSha, - verified: false, - tamperDetected: false, - reason: `Gateway returned ${response.status}`, - }); - continue; - } - - const rawText = await response.text(); - const actualSha = createHash('sha256').update(rawText, 'utf8').digest('hex'); +} - if (actualSha !== claimedSha) { - records.push({ - cid, - contentSha256: claimedSha, - verified: false, - tamperDetected: true, - reason: `SHA256 mismatch: claimed ${claimedSha} vs fetched ${actualSha}`, - }); - continue; +/** The published verifier owns IPFS retrieval, record hashing and signature checks. */ +export function verifyCid(cid: string): Promise { + if (!/^[a-zA-Z0-9]+$/.test(cid)) return Promise.reject(new Error('Invalid CID in anchor log')); + + return new Promise((resolve, reject) => { + const windows = process.platform === 'win32'; + const command = windows ? (process.env.ComSpec || 'cmd.exe') : 'npx'; + const args = windows + ? ['/d', '/s', '/c', `npx --yes nirium-cli@latest verify ${cid} --json`] + : ['--yes', 'nirium-cli@latest', 'verify', cid, '--json']; + const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; + let stderr = ''; + child.stdout.setEncoding('utf8').on('data', (chunk: string) => { stdout += chunk; }); + child.stderr.setEncoding('utf8').on('data', (chunk: string) => { stderr += chunk; }); + child.on('error', reject); + child.on('close', (code) => { + try { + const parsed: unknown = JSON.parse(stdout); + if (!parsed || typeof parsed !== 'object' || typeof (parsed as CliVerification).verified !== 'boolean') { + throw new Error('Verifier returned an invalid result'); + } + const result = parsed as CliVerification; + resolve({ ...result, verified: code === 0 && result.verified }); + } catch { + reject(new Error(`Verifier failed for CID ${cid}: ${stderr.trim() || 'invalid JSON output'}`)); } + }); + }); +} - let signatureValid: boolean | undefined = undefined; - if (row.attestedBy && row.signature) { - const parsedRecord = JSON.parse(rawText); - signatureValid = verifyAuditAttestation(parsedRecord, row.attestedBy, row.signature); - } +export async function fetchAndVerifyAnchors(options: { + logPath?: string; + verify?: (cid: string) => Promise; +} = {}): Promise { + const receipts = await readAnchors(options.logPath ?? DEFAULT_LOG_PATH); + const verify = options.verify ?? verifyCid; + const records: VerifiedAnchorReportItem[] = []; + for (const receipt of receipts) { + try { + const result = await verify(receipt.cid); + const hashMatchesLog = result.expectedHash?.toLowerCase() === receipt.contentSha256.toLowerCase(); + const verified = result.verified && hashMatchesLog; records.push({ - cid, - contentSha256: actualSha, - verified: signatureValid !== false, - tamperDetected: false, - signatureValid, - attestedBy: row.attestedBy, - }); - } catch (err: any) { - records.push({ - cid, - contentSha256: claimedSha, - verified: false, - tamperDetected: false, - reason: err.message || 'Fetch failed', + ...receipt, + verified, + ...(!verified ? { + reason: result.expectedHash && !hashMatchesLog + ? 'Verified document hash differs from the local anchor log' + : result.error || `Hash: ${result.hashStatus ?? 'unknown'}; signature: ${result.signatureStatus ?? 'unknown'}`, + } : {}), }); + } catch (error) { + records.push({ ...receipt, verified: false, reason: error instanceof Error ? error.message : 'Verifier failed' }); } } - const verifiedCount = records.filter(r => r.verified).length; - const flaggedCount = records.length - verifiedCount; - - return { - totalExported: records.length, - verifiedCount, - flaggedCount, - records, - }; + const verifiedCount = records.filter((record) => record.verified).length; + return { totalExported: records.length, verifiedCount, flaggedCount: records.length - verifiedCount, records }; } -async function run() { - console.log('[Forensic Audit] Generating verified export...'); +async function run(): Promise { const report = await fetchAndVerifyAnchors(); const outputPath = path.resolve(process.cwd(), 'audit-verified-report.json'); await fs.writeFile(outputPath, JSON.stringify(report, null, 2), 'utf8'); - console.log(`[Forensic Audit] Report written to ${outputPath}`); - console.log(`[Forensic Audit] Verified: ${report.verifiedCount} / ${report.totalExported}`); + console.log(`Verified: ${report.verifiedCount}; failed: ${report.flaggedCount}; total: ${report.totalExported}`); + for (const record of report.records) { + console.log(`${record.verified ? 'VERIFIED' : 'FAILED'} ${record.cid}${record.reason ? `: ${record.reason}` : ''}`); + } + console.log(`Report written to ${outputPath}`); + if (report.flaggedCount) process.exitCode = 1; } -if (process.env.NODE_ENV !== 'test') { - run().catch(console.error); -} \ No newline at end of file +if (process.env.NODE_ENV !== 'test' && process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) { + run().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : 'Export failed'); + process.exitCode = 1; + }); +} diff --git a/examples/audit-forensic-bridge/src/server.ts b/examples/audit-forensic-bridge/src/server.ts index 16bf170b..16879cea 100644 --- a/examples/audit-forensic-bridge/src/server.ts +++ b/examples/audit-forensic-bridge/src/server.ts @@ -1,6 +1,7 @@ import express from 'express'; import { Agent } from 'nirium'; import { signAuditRecord } from './attestation.js'; +import { appendAnchor } from './anchors.js'; import dotenv from 'dotenv'; dotenv.config(); @@ -37,10 +38,16 @@ app.post('/webhook', async (req, res) => { const anchor = await agentClient.anchorAuditRecord({ record: event, - tag: 'webhook-event', + tag: 'wave11-forensic-bridge', agent: agentAttestation, }); + await appendAnchor({ + cid: anchor.cid, + contentSha256: anchor.contentSha256, + ...(anchor.attestedBy ? { attestedBy: anchor.attestedBy } : {}), + }); + return res.status(200).json({ status: 'anchored', cid: anchor.cid, @@ -59,4 +66,4 @@ if (process.env.NODE_ENV !== 'test') { }); } -export { app }; \ No newline at end of file +export { app }; diff --git a/examples/audit-forensic-bridge/test/export.test.ts b/examples/audit-forensic-bridge/test/export.test.ts new file mode 100644 index 00000000..e2afc4c1 --- /dev/null +++ b/examples/audit-forensic-bridge/test/export.test.ts @@ -0,0 +1,73 @@ +import { afterEach, test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { appendAnchor, readAnchors } from '../src/anchors.js'; +import { fetchAndVerifyAnchors, type CliVerification } from '../src/export.js'; + +const tempDirs: string[] = []; + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); +}); + +async function logPath(): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'audit-bridge-test-')); + tempDirs.push(dir); + return path.join(dir, 'anchors.jsonl'); +} + +const hash = 'a'.repeat(64); + +test('writes only receipt metadata and verifies each logged CID through the verifier', async () => { + const file = await logPath(); + await appendAnchor({ cid: 'QmSampleOne', contentSha256: hash, attestedBy: 'GSAMPLE' }, file); + await appendAnchor({ cid: 'QmSampleTwo', contentSha256: hash }, file); + assert.deepEqual((await readAnchors(file)).map((item) => item.cid), ['QmSampleOne', 'QmSampleTwo']); + + const called: string[] = []; + const report = await fetchAndVerifyAnchors({ + logPath: file, + verify: async (cid): Promise => { + called.push(cid); + return { verified: true, expectedHash: hash, hashStatus: 'match', signatureStatus: 'valid' }; + }, + }); + assert.deepEqual(called, ['QmSampleOne', 'QmSampleTwo']); + assert.equal(report.verifiedCount, 2); + assert.equal(report.flaggedCount, 0); +}); + +test('reports a changed record as failed', async () => { + const file = await logPath(); + await appendAnchor({ cid: 'QmChangedRecord', contentSha256: hash }, file); + const report = await fetchAndVerifyAnchors({ + logPath: file, + verify: async () => ({ verified: false, expectedHash: hash, hashStatus: 'mismatch', signatureStatus: 'absent' }), + }); + assert.equal(report.flaggedCount, 1); + assert.match(report.records[0].reason ?? '', /Hash: mismatch/); +}); + +test('reports an invalid signature as failed', async () => { + const file = await logPath(); + await appendAnchor({ cid: 'QmBadSignature', contentSha256: hash, attestedBy: 'GSAMPLE' }, file); + const report = await fetchAndVerifyAnchors({ + logPath: file, + verify: async () => ({ verified: false, expectedHash: hash, hashStatus: 'match', signatureStatus: 'invalid' }), + }); + assert.equal(report.flaggedCount, 1); + assert.match(report.records[0].reason ?? '', /signature: invalid/); +}); + +test('fails when the verified document does not match the local receipt', async () => { + const file = await logPath(); + await appendAnchor({ cid: 'QmWrongLog', contentSha256: hash }, file); + const report = await fetchAndVerifyAnchors({ + logPath: file, + verify: async () => ({ verified: true, expectedHash: 'b'.repeat(64), hashStatus: 'match' }), + }); + assert.equal(report.flaggedCount, 1); + assert.match(report.records[0].reason ?? '', /differs from the local anchor log/); +}); diff --git a/examples/audit-forensic-bridge/tsconfig.json b/examples/audit-forensic-bridge/tsconfig.json new file mode 100644 index 00000000..336b0401 --- /dev/null +++ b/examples/audit-forensic-bridge/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +} From ec813c85ba0cd2d197e49d594a8881bc79214bb0 Mon Sep 17 00:00:00 2001 From: Storm Date: Sun, 22 Nov 2026 12:34:44 +0100 Subject: [PATCH 2/2] fix(example): isolate verifier from signing credentials --- examples/audit-forensic-bridge/src/export.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/examples/audit-forensic-bridge/src/export.ts b/examples/audit-forensic-bridge/src/export.ts index f6620e87..8559daad 100644 --- a/examples/audit-forensic-bridge/src/export.ts +++ b/examples/audit-forensic-bridge/src/export.ts @@ -1,12 +1,10 @@ import { spawn } from 'node:child_process'; import fs from 'node:fs/promises'; +import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import dotenv from 'dotenv'; import { DEFAULT_LOG_PATH, readAnchors, type AnchoredReceipt } from './anchors.js'; -dotenv.config(); - export interface CliVerification { verified: boolean; expectedHash?: string; @@ -37,7 +35,14 @@ export function verifyCid(cid: string): Promise { const args = windows ? ['/d', '/s', '/c', `npx --yes nirium-cli@latest verify ${cid} --json`] : ['--yes', 'nirium-cli@latest', 'verify', cid, '--json']; - const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] }); + const verificationEnv = { ...process.env }; + delete verificationEnv.STELLAR_SECRET_KEY; + delete verificationEnv.NIRIUM_API_KEY; + const child = spawn(command, args, { + cwd: os.tmpdir(), + env: verificationEnv, + stdio: ['ignore', 'pipe', 'pipe'], + }); let stdout = ''; let stderr = ''; child.stdout.setEncoding('utf8').on('data', (chunk: string) => { stdout += chunk; });