Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
62 changes: 49 additions & 13 deletions examples/audit-forensic-bridge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -53,15 +54,50 @@ with `npx nirium-cli@latest verify <CID>` 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 <cid> --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 <cid> --json`.
The `pnpm export` output was:

```text
Verified: 2; failed: 0; total: 2
VERIFIED QmdG5F3ZVF7WJHQzz9DUhcZSsCfRxbAn1cCWHVy36nb9B5
VERIFIED QmTYLcQDYcbjd6FRtTX7F2LZqtP6wXUdrfEp5cNnnJcGAW
Report written to audit-verified-report.json
```
4 changes: 2 additions & 2 deletions examples/audit-forensic-bridge/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand All @@ -21,4 +21,4 @@
"tsx": "^4.23.15",
"typescript": "^5.9.3"
}
}
}
43 changes: 43 additions & 0 deletions examples/audit-forensic-bridge/src/anchors.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
await fs.appendFile(logPath, `${JSON.stringify(receipt)}\n`, { encoding: 'utf8', mode: 0o600 });
}

export async function readAnchors(logPath = DEFAULT_LOG_PATH): Promise<AnchoredReceipt[]> {
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<string, unknown>;
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 } : {}),
};
});
}
177 changes: 86 additions & 91 deletions examples/audit-forensic-bridge/src/export.ts
Original file line number Diff line number Diff line change
@@ -1,119 +1,114 @@
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 os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
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<any>;

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<CliVerification> {
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 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; });
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<CliVerification>;
} = {}): Promise<VerifiedAnchorReport> {
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<void> {
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);
}
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;
});
}
11 changes: 9 additions & 2 deletions examples/audit-forensic-bridge/src/server.ts
Original file line number Diff line number Diff line change
@@ -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();
Expand Down Expand Up @@ -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,
Expand All @@ -59,4 +66,4 @@ if (process.env.NODE_ENV !== 'test') {
});
}

export { app };
export { app };
Loading