diff --git a/docs/verify-audit-cid.md b/docs/verify-audit-cid.md index cf9a7903..ff1d70e3 100644 --- a/docs/verify-audit-cid.md +++ b/docs/verify-audit-cid.md @@ -210,6 +210,20 @@ nirium verify QmZDVSxEfi3TLmcK1wLNydUHgGebfnTQ8i2EaEYfg2RUD6 --json A mainnet (`stellar:pubnet`) anchor signed with a demo key (`throwaway-demo-key`). It stores only `content_sha256`, so without the original evidence the CLI reports `signatureStatus: "valid"` and `hashStatus: "unchecked"`: the signature checks out, but the content can't be checked until someone presents the bytes with `--hash` or `--evidence`. That is how private evidence works: the receipt is public, the file is not. +## If IPFS Loses a Receipt + +A CID is the hash of the document, so the document can come back from any copy. +Keep the receipt when you anchor it (`nirium anchor ... --save receipt.json`; the +API's `POST /api/audit/log` response also includes the exact `document`), then: + +```bash +nirium cid receipt.json --expect # recomputes the CID locally +ipfs add --cid-version=0 receipt.json # puts it back on IPFS, same CID +``` + +Save the bytes as they are. `JSON.stringify(document)` with no trailing newline +is exactly what was pinned; any reformatting changes the CID. + ## What This Proves - **Hash match**: The record has not been altered since anchoring. diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 23a42fdc..9dd8e700 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes to the `nirium-cli` package are documented here. ## Unreleased +Keep your own copy of a receipt. `nirium anchor --save ` writes the exact anchored document, byte for byte, after checking that it gives back the anchored CID (it uses the `document` the node returns, or the gateway on older nodes). New `nirium cid [--expect ]` recomputes a file's CIDv0 locally with no IPFS node, so a saved copy can be shown to be the original and re-added to IPFS with the same CID. + ## 3.2.6 - 2026-11-20 `nirium verify` now decides hash-only mode the same way as the verify-audit-cid Action: only when the `record` field is missing. Before, a document with `record: null` and the original hash and signature kept passed as a hash-only anchor (HASH NOT CHECKED, signature valid) while the Action rejected it. It now fails here too. Found by github.com/holistis in an outside check of 3.2.5 (case 10 of 21). diff --git a/packages/cli/README.md b/packages/cli/README.md index 38eb161e..42865f20 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -46,12 +46,29 @@ client-supplied network field is rejected server-side anyway. | `--sign` | attach an ed25519 attestation of which key produced this anchor | off | | `--key-env ` | env var holding the secret key to sign with (`--sign` only) | config store's `secretKey` | | `-u, --url ` | agent URL | `https://nirium-agent.fly.dev` | +| `--save ` | save your own copy of the anchored document (see below) | off | | `--json` | machine-readable result | off | On success, prints the CID, the content hash, the gateway URL, and a `nirium verify ` suggestion so the anchor can be independently re-checked right away. +### Keep your own copy + +```bash +nirium anchor --hash <64-hex> --save receipt.json +nirium cid receipt.json --expect # any time later, no IPFS node needed +``` + +The receipt lives on IPFS only while someone keeps it pinned. Nirium pins it, +but cannot promise that forever. `--save` writes the exact document that was +anchored, byte for byte, and only after checking that those bytes give back the +anchored CID. `nirium cid` recomputes the CID of a saved copy locally, so you +can show it is the original. If IPFS ever loses the receipt, add the file again +with `ipfs add --cid-version=0 receipt.json` (or any pinning service) and you +get the same CID back. Don't reformat the file: a changed space or a trailing +newline gives a different CID. + ### Attesting who produced an anchor ```bash diff --git a/packages/cli/bin/nirium.js b/packages/cli/bin/nirium.js index acf14e76..810bf878 100755 --- a/packages/cli/bin/nirium.js +++ b/packages/cli/bin/nirium.js @@ -227,11 +227,23 @@ program .option('--sign', 'Attach an ed25519 attestation of which key produced this anchor') .option('--key-env ', 'Environment variable holding the Stellar secret key to sign with (--sign only; default: the config store\'s secretKey)') .option('-u, --url ', 'Agent URL', 'https://nirium-agent.fly.dev') + .option('--save ', 'Save your own copy of the anchored document; its bytes give back the same CID if IPFS ever loses it') .option('--json', 'Output result as JSON') .action(async (options) => { await executeAnchorCommand(options); }); +// --- COMMAND: cid --- +program + .command('cid') + .argument('', 'A saved receipt (from `nirium anchor --save`) or any file up to 256 KiB') + .option('--expect ', 'Exit non-zero unless the file gives back this CID') + .option('--json', 'Output result as JSON') + .description('Recompute a file\'s IPFS CID (CIDv0) locally, no IPFS node needed: proves a saved copy is the original') + .action((file, options) => { + executeCidCommand(file, options); + }); + // --- COMMAND: doctor --- program .command('doctor') @@ -1824,6 +1836,94 @@ function formatVerifyOutput(result) { return lines.join('\n'); } +// ═══════════════════════════════════════════════════════════════ +// cid — CIDv0 of a small file, computed locally +// ═══════════════════════════════════════════════════════════════ +// +// A receipt is one IPFS block: a dag-pb node wrapping a UnixFS File whose data +// is the whole document (files up to 256 KiB fit in one block). Its CIDv0 is +// base58btc(0x12 0x20 || sha256(node)), the same result `ipfs add` gives with its +// defaults (CIDv0, 256 KiB chunks). Checked on 21 Nov 2026 against three real +// mainnet receipts. No IPFS library needed. + +const UNIXFS_BLOCK_BYTES = 262144; +const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +function protobufVarint(n) { + const out = []; + while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n = Math.floor(n / 128); } + out.push(n); + return Buffer.from(out); +} + +function protobufBytesField(tag, buf) { + return Buffer.concat([Buffer.from([tag]), protobufVarint(buf.length), buf]); +} + +function base58btc(buf) { + let n = BigInt('0x' + buf.toString('hex')); + let out = ''; + while (n > 0n) { out = BASE58_ALPHABET[Number(n % 58n)] + out; n /= 58n; } + for (const b of buf) { if (b !== 0) break; out = '1' + out; } + return out; +} + +function cidV0OfSmallFile(bytes) { + if (bytes.length === 0) throw new Error('The file is empty.'); + if (bytes.length > UNIXFS_BLOCK_BYTES) { + throw new Error(`The file is ${bytes.length} bytes; this check covers single-block files up to ${UNIXFS_BLOCK_BYTES} bytes (every Audit Trail receipt fits).`); + } + const unixfs = Buffer.concat([Buffer.from([0x08, 0x02]), protobufBytesField(0x12, bytes), Buffer.from([0x18]), protobufVarint(bytes.length)]); + const node = protobufBytesField(0x0a, unixfs); + const digest = crypto.createHash('sha256').update(node).digest(); + return base58btc(Buffer.concat([Buffer.from([0x12, 0x20]), digest])); +} + +function executeCidCommand(file, options) { + let cid; + try { + cid = cidV0OfSmallFile(fs.readFileSync(file)); + } catch (err) { + const error = err?.code === 'ENOENT' ? `File not found: ${file}` : (err?.message || String(err)); + if (options.json) console.log(JSON.stringify({ ok: false, error })); + else console.error(`❌ ${error}`); + process.exit(1); + } + const expected = options.expect ? String(options.expect).trim() : undefined; + const matches = expected === undefined ? undefined : cid === expected; + if (options.json) { + console.log(JSON.stringify({ ok: matches !== false, cid, ...(expected ? { expected, matches } : {}) }, null, 2)); + } else { + console.log(`CID: ${cid}`); + if (expected) console.log(matches ? `✔ MATCH: this file is the document behind ${expected}` : `❌ MISMATCH: expected ${expected}`); + } + if (matches === false) process.exit(1); +} + +// Writes the anchored document to `file`, byte for byte. Uses the `document` the +// node returns; older nodes don't return it, so fall back to the gateway, which +// serves the same bytes. Only writes when the bytes give back the anchored CID. +async function saveReceiptCopy(data, file) { + const fromDocument = data.document && typeof data.document === 'object'; + let bytes; + try { + if (fromDocument) { + bytes = Buffer.from(JSON.stringify(data.document), 'utf8'); + } else { + const url = data.gatewayUrl || `https://nirium.myfilebase.com/ipfs/${data.cid}`; + const res = await fetch(url, { signal: AbortSignal.timeout(15000) }); + if (!res.ok) throw new Error(`gateway answered HTTP ${res.status}`); + bytes = Buffer.from(await res.arrayBuffer()); + } + const cid = cidV0OfSmallFile(bytes); + if (cid !== data.cid) return { path: file, saved: false, cid, error: `the copy gives ${cid}, not ${data.cid}; not saved` }; + fs.writeFileSync(file, bytes); + return { path: file, saved: true, cid, source: fromDocument ? 'response' : 'gateway' }; + } catch (err) { + return { path: file, saved: false, error: err?.message || String(err) }; + } +} + // ═══════════════════════════════════════════════════════════════ // anchor — anchor a hash or small record to IPFS via the Audit Trail node // ═══════════════════════════════════════════════════════════════ @@ -1927,8 +2027,11 @@ async function executeAnchorCommand(options) { return; } + const saved = options.save ? await saveReceiptCopy(data, options.save) : undefined; + if (saved && !saved.saved) process.exitCode = 1; + if (options.json) { - console.log(JSON.stringify({ ok: true, ...data }, null, 2)); + console.log(JSON.stringify({ ok: true, ...data, ...(saved ? { saved } : {}) }, null, 2)); return; } @@ -1938,7 +2041,13 @@ async function executeAnchorCommand(options) { if (data.gatewayUrl) console.log(` Gateway URL: ${data.gatewayUrl}`); if (data.attestedBy) console.log(` Attested by: ${data.attestedBy}`); console.log(` Anchored at: ${data.anchoredAt}`); + if (saved?.saved) { + console.log(` Saved copy: ${saved.path} (gives back ${saved.cid})`); + } else if (saved) { + console.log(` ⚠ Not saved: ${saved.error}`); + } console.log(`\n Verify independently: nirium verify ${data.cid}`); + if (saved?.saved) console.log(` Check your copy any time: nirium cid ${saved.path} --expect ${data.cid}`); } // Returns the `agent` object for the request body, `undefined` when diff --git a/packages/cli/package.json b/packages/cli/package.json index a4da8895..dc42912e 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -9,7 +9,7 @@ }, "scripts": { "prepublishOnly": "node --check bin/nirium.js", - "test": "node --test test/doctor-seller.test.js test/config-secret.test.js test/serve-api-key.test.js test/verify-hash-only.test.js test/verify-holistis-vectors.test.js test/verify-retry-gateway.test.js test/pay-agent-construction.test.js test/pay-status-and-cap.test.js test/pay-payment-response-parsing.test.js test/status.test.js test/anchor.test.js test/anchor-sign.test.js test/report.test.js" + "test": "node --test test/doctor-seller.test.js test/config-secret.test.js test/serve-api-key.test.js test/verify-hash-only.test.js test/verify-holistis-vectors.test.js test/keep-receipt.test.js test/verify-retry-gateway.test.js test/pay-agent-construction.test.js test/pay-status-and-cap.test.js test/pay-payment-response-parsing.test.js test/status.test.js test/anchor.test.js test/anchor-sign.test.js test/report.test.js" }, "keywords": [ "stellar", diff --git a/packages/cli/test/fixtures/receipts/QmS5q2NvZ2K2StLB3KCWRdkBtnZ5rHAJrQAez2PnKAPwTk.json b/packages/cli/test/fixtures/receipts/QmS5q2NvZ2K2StLB3KCWRdkBtnZ5rHAJrQAez2PnKAPwTk.json new file mode 100644 index 00000000..9619c497 --- /dev/null +++ b/packages/cli/test/fixtures/receipts/QmS5q2NvZ2K2StLB3KCWRdkBtnZ5rHAJrQAez2PnKAPwTk.json @@ -0,0 +1 @@ +{"version":"1.1.0","node":"audit-external","content_sha256":"9902a6cc07c9859e6fbe39e55b9c485c0a6a1f42d696d84686e921eeaa0d2ea5","agent":{"id":"agentledger-attest","key":"GA634V35VWPSRQ3AREV27Q2F24RYSXKBTGRS5RENYNOVFTJ3QW24JVPK","alg":"ed25519","statement":"nirium-audit-v1:9902a6cc07c9859e6fbe39e55b9c485c0a6a1f42d696d84686e921eeaa0d2ea5","signature":"Ia3FVT5UahTM2VARQfsdnCOUyA9EJUbUuD5RH+easJQzMwRkBh9KhZfmP6Ot6B1A5l5r/hiv6Tzl36xSpPUcCA=="},"network":"stellar:pubnet","tag":"agentledger-seq-867-block","anchoredAt":"2026-11-18T20:02:37.202Z"} \ No newline at end of file diff --git a/packages/cli/test/fixtures/receipts/QmSSZdtt3dQ8BqUm62zrKQ85E4BUHYiVfvDgZmHfJsqU1U.json b/packages/cli/test/fixtures/receipts/QmSSZdtt3dQ8BqUm62zrKQ85E4BUHYiVfvDgZmHfJsqU1U.json new file mode 100644 index 00000000..c2638bf8 --- /dev/null +++ b/packages/cli/test/fixtures/receipts/QmSSZdtt3dQ8BqUm62zrKQ85E4BUHYiVfvDgZmHfJsqU1U.json @@ -0,0 +1 @@ +{"version":"1.1.0","node":"audit-external","content_sha256":"ab44f8883af819f7496f2cef29eaea0651f6d97af78aa8088fd8ef4dc4b753c9","agent":{"id":"arcusx-dispute-resolver","key":"GD5AFNPTKVZPNWZWKLOULOE7BN4E7ZC73WV5YMBCULYQXWFCGDESUNOZ","alg":"ed25519","statement":"nirium-audit-v1:ab44f8883af819f7496f2cef29eaea0651f6d97af78aa8088fd8ef4dc4b753c9","signature":"kQu3tK3ZsDR0HMo1EFB13qa/bLiJa4AuX1yJSZq9/2MEgGVGJImFrtXH2SItfBWHW3bWTbB8qFeBUf/QkSkGAw=="},"record":{"schema":"arcusx.dispute.resolution.v1","dispute":"dispute-118","outcome":"released_to_worker","case_file_sha256":"1794c699bce4e06d33857cc34f2974ac2bfff500bdc41b002b219a154b698ac0","note":"Hashes only — no personal data anchored."},"network":"mainnet","tag":"arcusx-dispute","anchoredAt":"2026-07-30T22:26:02.857Z"} \ No newline at end of file diff --git a/packages/cli/test/keep-receipt.test.js b/packages/cli/test/keep-receipt.test.js new file mode 100644 index 00000000..cc09827b --- /dev/null +++ b/packages/cli/test/keep-receipt.test.js @@ -0,0 +1,119 @@ +/** + * Keeping your own copy of a receipt: `nirium anchor --save ` and + * `nirium cid `. The fixtures are two real mainnet receipts, byte for + * byte as the gateway serves them, so the CIDs below are the real ones. + * A local HTTP server stands in for the Audit Trail node and the gateway. + */ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawn } from 'node:child_process'; +import http from 'node:http'; +import { once } from 'node:events'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; + +const cliRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const cli = path.join(cliRoot, 'bin/nirium.js'); +const fixtures = path.join(cliRoot, 'test/fixtures/receipts'); +const CID_RECORD = 'QmSSZdtt3dQ8BqUm62zrKQ85E4BUHYiVfvDgZmHfJsqU1U'; +const CID_HASH_ONLY = 'QmS5q2NvZ2K2StLB3KCWRdkBtnZ5rHAJrQAez2PnKAPwTk'; +const bytesOf = (cid) => fs.readFileSync(path.join(fixtures, `${cid}.json`)); + +let scenario = 'with-document'; +const server = http.createServer((req, res) => { + if (req.method === 'GET' && req.url.startsWith('/ipfs/')) { + const cid = req.url.slice('/ipfs/'.length); + const file = path.join(fixtures, `${cid}.json`); + if (!/^Qm\w+$/.test(cid) || !fs.existsSync(file)) { res.writeHead(404).end(); return; } + res.writeHead(200, { 'content-type': 'application/json' }).end(fs.readFileSync(file)); + return; + } + req.resume(); + req.on('end', () => { + const base = `http://127.0.0.1:${server.address().port}`; + const doc = JSON.parse(bytesOf(CID_RECORD).toString('utf8')); + const body = { + cid: CID_RECORD, + gatewayUrl: `${base}/ipfs/${CID_RECORD}`, + content_sha256: doc.content_sha256, + anchoredAt: doc.anchoredAt, + }; + if (scenario === 'with-document') body.document = doc; + if (scenario === 'wrong-cid') { body.document = doc; body.cid = CID_HASH_ONLY; } + res.writeHead(201, { 'content-type': 'application/json' }).end(JSON.stringify(body)); + }); +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const base = `http://127.0.0.1:${server.address().port}`; +test.after(() => new Promise((resolve) => server.close(() => resolve()))); + +function run(args) { + return new Promise((resolve) => { + const child = spawn(process.execPath, [cli, ...args], { stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (d) => { stdout += d; }); + child.stderr.on('data', (d) => { stderr += d; }); + child.on('close', (code) => resolve({ code, stdout, stderr })); + }); +} + +const tmp = (name) => path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'nirium-keep-')), name); +const HASH = 'ab44f8883af819f7496f2cef29eaea0651f6d97af78aa8088fd8ef4dc4b753c9'; + +test('cid recomputes the CID of real mainnet receipts', async () => { + for (const cid of [CID_RECORD, CID_HASH_ONLY]) { + const { code, stdout } = await run(['cid', path.join(fixtures, `${cid}.json`), '--expect', cid]); + assert.equal(code, 0, stdout); + assert.match(stdout, new RegExp(`CID: ${cid}`)); + assert.match(stdout, /MATCH/); + } +}); + +test('cid exits 1 when the file is not the expected document', async () => { + const { code, stdout } = await run(['cid', path.join(fixtures, `${CID_RECORD}.json`), '--expect', CID_HASH_ONLY]); + assert.equal(code, 1); + assert.match(stdout, /MISMATCH/); +}); + +test('cid notices a single changed byte', async () => { + const file = tmp('changed.json'); + const bytes = Buffer.from(bytesOf(CID_RECORD)); + bytes[bytes.length - 2] ^= 1; + fs.writeFileSync(file, bytes); + const { code } = await run(['cid', file, '--expect', CID_RECORD]); + assert.equal(code, 1); +}); + +test('anchor --save writes the returned document, byte for byte', async () => { + scenario = 'with-document'; + const file = tmp('receipt.json'); + const { code, stdout } = await run(['anchor', '--hash', HASH, '--url', base, '--save', file]); + assert.equal(code, 0, stdout); + assert.deepEqual(fs.readFileSync(file), bytesOf(CID_RECORD)); + assert.match(stdout, /Saved copy:/); + assert.match(stdout, /nirium cid .* --expect QmSSZdtt/); +}); + +test('anchor --save falls back to the gateway when the node returns no document', async () => { + scenario = 'no-document'; + const file = tmp('receipt.json'); + const { code, stdout } = await run(['anchor', '--hash', HASH, '--url', base, '--save', file, '--json']); + assert.equal(code, 0, stdout); + const out = JSON.parse(stdout); + assert.equal(out.saved.saved, true); + assert.equal(out.saved.source, 'gateway'); + assert.deepEqual(fs.readFileSync(file), bytesOf(CID_RECORD)); +}); + +test('anchor --save refuses a copy that does not give back the anchored CID', async () => { + scenario = 'wrong-cid'; + const file = tmp('receipt.json'); + const { code, stdout } = await run(['anchor', '--hash', HASH, '--url', base, '--save', file]); + assert.equal(code, 1); + assert.equal(fs.existsSync(file), false); + assert.match(stdout, /Not saved/); +}); diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md index c30abffd..595c4616 100644 --- a/packages/sdk/CHANGELOG.md +++ b/packages/sdk/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes to the `nirium` package are documented here. ## Unreleased +`AuditAnchor` gains an optional `document`: the exact JSON pinned to IPFS, returned by Audit Trail nodes deployed after 21 Nov 2026. Keeping it lets you re-add the receipt to IPFS with the same CID. + ## 0.19.6 - 2026-11-17 README: a short note on what a receipt adds over the ledger, with a link to the design FAQ. No code change. diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index 565eeeea..02923b8c 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -376,6 +376,12 @@ export interface AuditAnchor { anchoredAt: string; /** Present when the anchor carried a verified agent attestation. */ attestedBy?: string; + /** + * The exact document pinned to IPFS (nodes deployed after 21 Nov 2026). + * Keep it: `JSON.stringify(document)`, with no trailing newline, gives back + * the same CID if you ever add it to IPFS again. + */ + document?: Record; [key: string]: unknown; }