nirium-cli 3.2.6 → 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 +17 -0
  2. package/bin/nirium.js +110 -1
  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
package/bin/nirium.js CHANGED
@@ -227,11 +227,23 @@ program
227
227
  .option('--sign', 'Attach an ed25519 attestation of which key produced this anchor')
228
228
  .option('--key-env <VAR>', 'Environment variable holding the Stellar secret key to sign with (--sign only; default: the config store\'s secretKey)')
229
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')
230
231
  .option('--json', 'Output result as JSON')
231
232
  .action(async (options) => {
232
233
  await executeAnchorCommand(options);
233
234
  });
234
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
+
235
247
  // --- COMMAND: doctor ---
236
248
  program
237
249
  .command('doctor')
@@ -1824,6 +1836,94 @@ function formatVerifyOutput(result) {
1824
1836
  return lines.join('\n');
1825
1837
  }
1826
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
+
1827
1927
  // ═══════════════════════════════════════════════════════════════
1828
1928
  // anchor — anchor a hash or small record to IPFS via the Audit Trail node
1829
1929
  // ═══════════════════════════════════════════════════════════════
@@ -1927,8 +2027,11 @@ async function executeAnchorCommand(options) {
1927
2027
  return;
1928
2028
  }
1929
2029
 
2030
+ const saved = options.save ? await saveReceiptCopy(data, options.save) : undefined;
2031
+ if (saved && !saved.saved) process.exitCode = 1;
2032
+
1930
2033
  if (options.json) {
1931
- console.log(JSON.stringify({ ok: true, ...data }, null, 2));
2034
+ console.log(JSON.stringify({ ok: true, ...data, ...(saved ? { saved } : {}) }, null, 2));
1932
2035
  return;
1933
2036
  }
1934
2037
 
@@ -1938,7 +2041,13 @@ async function executeAnchorCommand(options) {
1938
2041
  if (data.gatewayUrl) console.log(` Gateway URL: ${data.gatewayUrl}`);
1939
2042
  if (data.attestedBy) console.log(` Attested by: ${data.attestedBy}`);
1940
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
+ }
1941
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}`);
1942
2051
  }
1943
2052
 
1944
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.6",
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-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"
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",