nirium-cli 3.2.5 → 3.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +25 -0
  2. package/bin/nirium.js +128 -6
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -46,12 +46,29 @@ client-supplied network field is rejected server-side anyway.
46
46
  | `--sign` | attach an ed25519 attestation of which key produced this anchor | off |
47
47
  | `--key-env <VAR>` | env var holding the secret key to sign with (`--sign` only) | config store's `secretKey` |
48
48
  | `-u, --url <url>` | agent URL | `https://nirium-agent.fly.dev` |
49
+ | `--save <file>` | save your own copy of the anchored document (see below) | off |
49
50
  | `--json` | machine-readable result | off |
50
51
 
51
52
  On success, prints the CID, the content hash, the gateway URL, and a
52
53
  `nirium verify <cid>` suggestion so the anchor can be independently
53
54
  re-checked right away.
54
55
 
56
+ ### Keep your own copy
57
+
58
+ ```bash
59
+ nirium anchor --hash <64-hex> --save receipt.json
60
+ nirium cid receipt.json --expect <CID> # any time later, no IPFS node needed
61
+ ```
62
+
63
+ The receipt lives on IPFS only while someone keeps it pinned. Nirium pins it,
64
+ but cannot promise that forever. `--save` writes the exact document that was
65
+ anchored, byte for byte, and only after checking that those bytes give back the
66
+ anchored CID. `nirium cid` recomputes the CID of a saved copy locally, so you
67
+ can show it is the original. If IPFS ever loses the receipt, add the file again
68
+ with `ipfs add --cid-version=0 receipt.json` (or any pinning service) and you
69
+ get the same CID back. Don't reformat the file: a changed space or a trailing
70
+ newline gives a different CID.
71
+
55
72
  ### Attesting who produced an anchor
56
73
 
57
74
  ```bash
@@ -114,6 +131,7 @@ nirium verify <cid> --gateway https://gateway.pinata.cloud --gateway https://ipf
114
131
  | `--json` | machine-readable result | off |
115
132
  | `--hash <hex>` | expected evidence hash for a hash-only anchor (`sha-256:` prefix optional) | none |
116
133
  | `--evidence <file>` | file whose SHA-256 is compared with the anchored hash | none |
134
+ | `--require-signature` | fail unless the document has a valid agent signature | off |
117
135
 
118
136
  If every gateway comes back 404 after exhausting retries, that's
119
137
  reported as **NOT YET AVAILABLE** (`availability: "not_yet_available"`
@@ -129,6 +147,13 @@ of the two checks actually ran and succeeded, a matching `--hash`/
129
147
  was verified, so `verify` prints `NOTHING VERIFIED`, exits non-zero, and
130
148
  sets `verified: false` in `--json`, instead of reporting a pass.
131
149
 
150
+ An unsigned record still passes on its recomputed hash, with the
151
+ signature reported as ABSENT. That also means someone can change a
152
+ record, re-hash it and drop the signature, and it still passes. If you
153
+ only trust receipts your agents signed, add `--require-signature`: an
154
+ unsigned document then fails with a "Signature required" error. Same
155
+ rule as the `require-signature` input of the verify-audit-cid Action.
156
+
132
157
  ## Charge for your API in five minutes
133
158
 
134
159
  ```bash
package/bin/nirium.js CHANGED
@@ -179,6 +179,7 @@ program
179
179
  .option('--json', 'Output result as JSON')
180
180
  .option('--hash <hex>', 'Expected sha-256 of the evidence (hex, optional sha-256: prefix), for hash-only anchors')
181
181
  .option('--evidence <file>', 'Original evidence file; its sha-256 is compared with the anchored hash')
182
+ .option('--require-signature', 'Fail unless the document carries a valid agent signature (an unsigned record otherwise passes on its hash alone)')
182
183
  .description('Independently verify IPFS audit document content hash & agent ed25519 signature')
183
184
  .action(async (cid, options) => {
184
185
  let expectedHash;
@@ -203,7 +204,7 @@ program
203
204
  }
204
205
 
205
206
  const gateways = options.gateway.length > 0 ? options.gateway : DEFAULT_GATEWAYS;
206
- const result = await fetchAndVerifyCid(cid, gateways, globalThis.fetch, { expectedHash, retries, timeoutMs });
207
+ const result = await fetchAndVerifyCid(cid, gateways, globalThis.fetch, { expectedHash, requireSignature: !!options.requireSignature, retries, timeoutMs });
207
208
  if (options.json) {
208
209
  console.log(JSON.stringify(result, null, 2));
209
210
  } else {
@@ -226,11 +227,23 @@ program
226
227
  .option('--sign', 'Attach an ed25519 attestation of which key produced this anchor')
227
228
  .option('--key-env <VAR>', 'Environment variable holding the Stellar secret key to sign with (--sign only; default: the config store\'s secretKey)')
228
229
  .option('-u, --url <url>', 'Agent URL', 'https://nirium-agent.fly.dev')
230
+ .option('--save <file>', 'Save your own copy of the anchored document; its bytes give back the same CID if IPFS ever loses it')
229
231
  .option('--json', 'Output result as JSON')
230
232
  .action(async (options) => {
231
233
  await executeAnchorCommand(options);
232
234
  });
233
235
 
236
+ // --- COMMAND: cid ---
237
+ program
238
+ .command('cid')
239
+ .argument('<file>', 'A saved receipt (from `nirium anchor --save`) or any file up to 256 KiB')
240
+ .option('--expect <cid>', 'Exit non-zero unless the file gives back this CID')
241
+ .option('--json', 'Output result as JSON')
242
+ .description('Recompute a file\'s IPFS CID (CIDv0) locally, no IPFS node needed: proves a saved copy is the original')
243
+ .action((file, options) => {
244
+ executeCidCommand(file, options);
245
+ });
246
+
234
247
  // --- COMMAND: doctor ---
235
248
  program
236
249
  .command('doctor')
@@ -1642,7 +1655,7 @@ function verifyEd25519Signature(pubKeyGAddress, statement, signature) {
1642
1655
  }
1643
1656
  }
1644
1657
 
1645
- function verifyAuditDocument(doc, cid, { expectedHash } = {}) {
1658
+ function verifyAuditDocument(doc, cid, { expectedHash, requireSignature } = {}) {
1646
1659
  const fail = (error) => ({ ok: false, verified: false, cid, hashMatch: false, hashStatus: 'mismatch', expectedHash: '', computedHash: '', signatureStatus: 'absent', error });
1647
1660
  if (!doc || typeof doc !== 'object') return fail('Invalid audit document format');
1648
1661
  const anchoredHash = typeof doc.content_sha256 === 'string' ? doc.content_sha256.toLowerCase() : '';
@@ -1652,7 +1665,12 @@ function verifyAuditDocument(doc, cid, { expectedHash } = {}) {
1652
1665
  // hash-only mode: the node stores the submitted hash as content_sha256 and
1653
1666
  // has nothing to recompute it from, so compare against --hash/--evidence
1654
1667
  // when given, otherwise report the hash as unchecked (not as a mismatch).
1655
- const mode = doc.record ? 'record' : 'hash-only';
1668
+ // Hash-only means the `record` field is missing, same rule as the
1669
+ // verify-audit-cid Action. A present but falsy record (null, "", 0) is a
1670
+ // changed document, not a hash-only one: before, `record: null` with the
1671
+ // original hash and signature kept passed here as a hash-only anchor while
1672
+ // the Action rejected it (holistis vector 10).
1673
+ const mode = doc.record === undefined ? 'hash-only' : 'record';
1656
1674
  let computedHash = '';
1657
1675
  let hashStatus;
1658
1676
  if (mode === 'record') {
@@ -1685,8 +1703,15 @@ function verifyAuditDocument(doc, cid, { expectedHash } = {}) {
1685
1703
  // signature absent), which is not the same as the evidence being verified.
1686
1704
  const anyFailed = hashStatus === 'mismatch' || signatureStatus === 'invalid';
1687
1705
  const anyPassed = hashStatus === 'match' || signatureStatus === 'valid';
1688
- const ok = !anyFailed && anyPassed;
1689
- return { ok, verified: ok, cid, mode, hashMatch: hashStatus === 'match', hashStatus, expectedHash: anchoredHash, computedHash, providedHash: expectedHash || '', signatureStatus, signatureScheme, signerKey, statement, declaredStatement, agentId };
1706
+ // --require-signature (opt-in, same as the Action's require-signature
1707
+ // input): an unsigned record otherwise passes on its hash alone, which also
1708
+ // means a record changed, re-hashed and stripped of its signature passes.
1709
+ const signatureMissing = !!requireSignature && signatureStatus === 'absent';
1710
+ const ok = !anyFailed && anyPassed && !signatureMissing;
1711
+ return {
1712
+ ok, verified: ok, cid, mode, hashMatch: hashStatus === 'match', hashStatus, expectedHash: anchoredHash, computedHash, providedHash: expectedHash || '', signatureStatus, signatureScheme, signerKey, statement, declaredStatement, agentId,
1713
+ ...(signatureMissing && !anyFailed ? { error: 'Signature required (--require-signature), but this document has no agent signature.' } : {}),
1714
+ };
1690
1715
  }
1691
1716
 
1692
1717
  // `gateways` may be a single URL string (back-compat for direct callers)
@@ -1811,6 +1836,94 @@ function formatVerifyOutput(result) {
1811
1836
  return lines.join('\n');
1812
1837
  }
1813
1838
 
1839
+ // ═══════════════════════════════════════════════════════════════
1840
+ // cid — CIDv0 of a small file, computed locally
1841
+ // ═══════════════════════════════════════════════════════════════
1842
+ //
1843
+ // A receipt is one IPFS block: a dag-pb node wrapping a UnixFS File whose data
1844
+ // is the whole document (files up to 256 KiB fit in one block). Its CIDv0 is
1845
+ // base58btc(0x12 0x20 || sha256(node)), the same result `ipfs add` gives with its
1846
+ // defaults (CIDv0, 256 KiB chunks). Checked on 21 Nov 2026 against three real
1847
+ // mainnet receipts. No IPFS library needed.
1848
+
1849
+ const UNIXFS_BLOCK_BYTES = 262144;
1850
+ const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
1851
+
1852
+ function protobufVarint(n) {
1853
+ const out = [];
1854
+ while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n = Math.floor(n / 128); }
1855
+ out.push(n);
1856
+ return Buffer.from(out);
1857
+ }
1858
+
1859
+ function protobufBytesField(tag, buf) {
1860
+ return Buffer.concat([Buffer.from([tag]), protobufVarint(buf.length), buf]);
1861
+ }
1862
+
1863
+ function base58btc(buf) {
1864
+ let n = BigInt('0x' + buf.toString('hex'));
1865
+ let out = '';
1866
+ while (n > 0n) { out = BASE58_ALPHABET[Number(n % 58n)] + out; n /= 58n; }
1867
+ for (const b of buf) { if (b !== 0) break; out = '1' + out; }
1868
+ return out;
1869
+ }
1870
+
1871
+ function cidV0OfSmallFile(bytes) {
1872
+ if (bytes.length === 0) throw new Error('The file is empty.');
1873
+ if (bytes.length > UNIXFS_BLOCK_BYTES) {
1874
+ 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).`);
1875
+ }
1876
+ const unixfs = Buffer.concat([Buffer.from([0x08, 0x02]), protobufBytesField(0x12, bytes), Buffer.from([0x18]), protobufVarint(bytes.length)]);
1877
+ const node = protobufBytesField(0x0a, unixfs);
1878
+ const digest = crypto.createHash('sha256').update(node).digest();
1879
+ return base58btc(Buffer.concat([Buffer.from([0x12, 0x20]), digest]));
1880
+ }
1881
+
1882
+ function executeCidCommand(file, options) {
1883
+ let cid;
1884
+ try {
1885
+ cid = cidV0OfSmallFile(fs.readFileSync(file));
1886
+ } catch (err) {
1887
+ const error = err?.code === 'ENOENT' ? `File not found: ${file}` : (err?.message || String(err));
1888
+ if (options.json) console.log(JSON.stringify({ ok: false, error }));
1889
+ else console.error(`❌ ${error}`);
1890
+ process.exit(1);
1891
+ }
1892
+ const expected = options.expect ? String(options.expect).trim() : undefined;
1893
+ const matches = expected === undefined ? undefined : cid === expected;
1894
+ if (options.json) {
1895
+ console.log(JSON.stringify({ ok: matches !== false, cid, ...(expected ? { expected, matches } : {}) }, null, 2));
1896
+ } else {
1897
+ console.log(`CID: ${cid}`);
1898
+ if (expected) console.log(matches ? `✔ MATCH: this file is the document behind ${expected}` : `❌ MISMATCH: expected ${expected}`);
1899
+ }
1900
+ if (matches === false) process.exit(1);
1901
+ }
1902
+
1903
+ // Writes the anchored document to `file`, byte for byte. Uses the `document` the
1904
+ // node returns; older nodes don't return it, so fall back to the gateway, which
1905
+ // serves the same bytes. Only writes when the bytes give back the anchored CID.
1906
+ async function saveReceiptCopy(data, file) {
1907
+ const fromDocument = data.document && typeof data.document === 'object';
1908
+ let bytes;
1909
+ try {
1910
+ if (fromDocument) {
1911
+ bytes = Buffer.from(JSON.stringify(data.document), 'utf8');
1912
+ } else {
1913
+ const url = data.gatewayUrl || `https://nirium.myfilebase.com/ipfs/${data.cid}`;
1914
+ const res = await fetch(url, { signal: AbortSignal.timeout(15000) });
1915
+ if (!res.ok) throw new Error(`gateway answered HTTP ${res.status}`);
1916
+ bytes = Buffer.from(await res.arrayBuffer());
1917
+ }
1918
+ const cid = cidV0OfSmallFile(bytes);
1919
+ if (cid !== data.cid) return { path: file, saved: false, cid, error: `the copy gives ${cid}, not ${data.cid}; not saved` };
1920
+ fs.writeFileSync(file, bytes);
1921
+ return { path: file, saved: true, cid, source: fromDocument ? 'response' : 'gateway' };
1922
+ } catch (err) {
1923
+ return { path: file, saved: false, error: err?.message || String(err) };
1924
+ }
1925
+ }
1926
+
1814
1927
  // ═══════════════════════════════════════════════════════════════
1815
1928
  // anchor — anchor a hash or small record to IPFS via the Audit Trail node
1816
1929
  // ═══════════════════════════════════════════════════════════════
@@ -1914,8 +2027,11 @@ async function executeAnchorCommand(options) {
1914
2027
  return;
1915
2028
  }
1916
2029
 
2030
+ const saved = options.save ? await saveReceiptCopy(data, options.save) : undefined;
2031
+ if (saved && !saved.saved) process.exitCode = 1;
2032
+
1917
2033
  if (options.json) {
1918
- console.log(JSON.stringify({ ok: true, ...data }, null, 2));
2034
+ console.log(JSON.stringify({ ok: true, ...data, ...(saved ? { saved } : {}) }, null, 2));
1919
2035
  return;
1920
2036
  }
1921
2037
 
@@ -1925,7 +2041,13 @@ async function executeAnchorCommand(options) {
1925
2041
  if (data.gatewayUrl) console.log(` Gateway URL: ${data.gatewayUrl}`);
1926
2042
  if (data.attestedBy) console.log(` Attested by: ${data.attestedBy}`);
1927
2043
  console.log(` Anchored at: ${data.anchoredAt}`);
2044
+ if (saved?.saved) {
2045
+ console.log(` Saved copy: ${saved.path} (gives back ${saved.cid})`);
2046
+ } else if (saved) {
2047
+ console.log(` ⚠ Not saved: ${saved.error}`);
2048
+ }
1928
2049
  console.log(`\n Verify independently: nirium verify ${data.cid}`);
2050
+ if (saved?.saved) console.log(` Check your copy any time: nirium cid ${saved.path} --expect ${data.cid}`);
1929
2051
  }
1930
2052
 
1931
2053
  // Returns the `agent` object for the request body, `undefined` when
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nirium-cli",
3
- "version": "3.2.5",
3
+ "version": "3.2.7",
4
4
  "description": "Nirium from the terminal: pay or serve an x402 API on Stellar, anchor and verify receipts, check an agent and export reports.",
5
5
  "main": "bin/nirium.js",
6
6
  "type": "module",
@@ -9,7 +9,7 @@
9
9
  },
10
10
  "scripts": {
11
11
  "prepublishOnly": "node --check bin/nirium.js",
12
- "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-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"
12
+ "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"
13
13
  },
14
14
  "keywords": [
15
15
  "stellar",