nirium-cli 3.0.1 → 3.1.0

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 +126 -1
  2. package/bin/nirium.js +456 -24
  3. package/package.json +5 -5
package/README.md CHANGED
@@ -202,6 +202,65 @@ Each line is pass or fail:
202
202
 
203
203
  `--json` prints the same report (`ok`, `seller`, `network`, `checks`) for CI.
204
204
 
205
+ ## Anchor a record
206
+
207
+ ```bash
208
+ nirium anchor --file evidence.json
209
+ nirium anchor --hash <64-hex-sha256>
210
+ nirium anchor --record '{"order":"A-12"}'
211
+ ```
212
+
213
+ Anchors a sha-256 hash (or a small JSON object, up to 8KB) to IPFS via an
214
+ Audit Trail node's `POST /api/audit/log`, and prints back the CID.
215
+
216
+ - `--file <path>` computes the sha-256 of the file locally and sends only
217
+ the hash - the file's contents are never uploaded. IPFS cannot delete
218
+ anything once pinned, so hashing locally means raw evidence never
219
+ leaves your machine.
220
+ - `--hash <hex>` sends a sha-256 you already have (64 hex chars, optional
221
+ `sha-256:` prefix).
222
+ - `--record <json>` anchors a small JSON object verbatim (max 8KB,
223
+ enforced here before the request, not just by the server). Don't put
224
+ personal data in it - an anchored record can never be deleted.
225
+
226
+ Exactly one of the three is required. `--tx <hash>` and `--tag <label>`
227
+ are optional and attached to the anchor as-is. There is no `--network`
228
+ flag: the agent box anchoring the record decides its own network, and a
229
+ client-supplied network field is rejected server-side anyway.
230
+
231
+ | Option | Purpose | Default |
232
+ |---|---|---|
233
+ | `--file <path>` | anchor this file's sha-256 | none |
234
+ | `--hash <hex>` | anchor this sha-256 directly | none |
235
+ | `--record <json>` | anchor this small JSON object verbatim | none |
236
+ | `--tx <hash>` | associate a transaction hash | none |
237
+ | `--tag <label>` | free-form label | none |
238
+ | `--sign` | attach an ed25519 attestation of which key produced this anchor | off |
239
+ | `--key-env <VAR>` | env var holding the secret key to sign with (`--sign` only) | config store's `secretKey` |
240
+ | `-u, --url <url>` | agent URL | `http://localhost:3002` |
241
+ | `--json` | machine-readable result | off |
242
+
243
+ On success, prints the CID, the content hash, the gateway URL, and a
244
+ `nirium verify <cid>` suggestion so the anchor can be independently
245
+ re-checked right away.
246
+
247
+ ### Attesting who produced an anchor
248
+
249
+ ```bash
250
+ nirium config set secretKey # hidden prompt, stored in ~/.niriumrc.json
251
+ nirium anchor --hash <64-hex> --sign
252
+ # or, without touching the config store:
253
+ NIRIUM_KEY=S... nirium anchor --hash <64-hex> --sign --key-env NIRIUM_KEY
254
+ ```
255
+
256
+ The CID alone proves the anchored fact wasn't altered; `--sign` proves
257
+ *who* declared it. The secret key signs `nirium-audit-v1:<content_sha256>`
258
+ locally with ed25519 - only the resulting signature and the derived
259
+ public key (`G...`) ever leave this process, never the secret itself. If
260
+ the node rejects the signature, nothing is anchored (`400`, exit non-zero).
261
+ `nirium verify <cid>` independently re-checks it afterward and reports
262
+ `SIGNATURE: VALID` against the same public key.
263
+
205
264
  ## Verify an audit record
206
265
 
207
266
  ```bash
@@ -224,13 +283,32 @@ and the signature is still verified over `nirium-audit-v1:<content_sha256>`.
224
283
  Signatures are accepted as base64 or hex, raw ed25519 or SEP-53
225
284
  (Freighter `signMessage`), like the anchoring node.
226
285
 
286
+ `-g, --gateway <url>` is repeatable and tried in order as fallbacks. A
287
+ `404` is retried on the *same* gateway up to `--retries` times with a
288
+ short backoff first - a fresh pin can take a moment to propagate, so a
289
+ 404 there doesn't mean the CID is wrong, just not there *yet*. Any other
290
+ failure (a real error, or a timed-out request) moves straight to the
291
+ next gateway instead, since retrying the same one won't help:
292
+
293
+ ```bash
294
+ nirium verify <cid> --gateway https://gateway.pinata.cloud --gateway https://ipfs.io --retries 3
295
+ ```
296
+
227
297
  | Option | Purpose | Default |
228
298
  |---|---|---|
229
- | `-g, --gateway <url>` | IPFS gateway to fetch from | `https://gateway.pinata.cloud` |
299
+ | `-g, --gateway <url>` | IPFS gateway to fetch from - repeat for fallbacks | `https://gateway.pinata.cloud` |
300
+ | `--retries <n>` | retries per gateway on a 404, with backoff | `2` |
301
+ | `--timeout <ms>` | per-request timeout | `8000` |
230
302
  | `--json` | machine-readable result | off |
231
303
  | `--hash <hex>` | expected evidence hash for a hash-only anchor (`sha-256:` prefix optional) | none |
232
304
  | `--evidence <file>` | file whose SHA-256 is compared with the anchored hash | none |
233
305
 
306
+ If every gateway comes back 404 after exhausting retries, that's
307
+ reported as **NOT YET AVAILABLE** (`availability: "not_yet_available"`
308
+ in `--json`) - distinct from a hash mismatch, because nothing was
309
+ actually fetched to compare. A mix of real errors across gateways is
310
+ reported as a gateway error instead. Both exit non-zero, same as before.
311
+
234
312
  Exits non-zero (and prints which check failed) if the hash doesn't match
235
313
  or the signature doesn't verify. A pass also requires that at least one
236
314
  of the two checks actually ran and succeeded, a matching `--hash`/
@@ -239,6 +317,53 @@ of the two checks actually ran and succeeded, a matching `--hash`/
239
317
  was verified, so `verify` prints `NOTHING VERIFIED`, exits non-zero, and
240
318
  sets `verified: false` in `--json`, instead of reporting a pass.
241
319
 
320
+ ## Reporting: summaries and exports
321
+
322
+ ```bash
323
+ nirium report summary [--from <date>] [--to <date>] [--network <testnet|mainnet>] [--json]
324
+ nirium report export anchors|payments|payroll [--from <date>] [--to <date>] [--limit <n>] [--csv out.csv] [--json]
325
+ ```
326
+
327
+ Thin client for the Reporting node's `GET /api/reporting/summary` and
328
+ `GET /api/reporting/export` - an aggregation layer over what the
329
+ protocol has already anchored (payroll runs, x402/MPP receipts, IPFS
330
+ anchors). **This is institutional-format output, not certified
331
+ regulatory reporting** - anything filed with an authority remains the
332
+ caller's own responsibility (the server's own disclaimer is reprinted in
333
+ both commands' output).
334
+
335
+ `report summary` prints settled payroll runs and totals, payment
336
+ receipts by gateway, and anchor counts for the period. `report export
337
+ <type>` pulls the underlying rows:
338
+
339
+ - Without `--csv`, rows print one per line on stdout. For `export
340
+ anchors` specifically, that line is **just the CID** - nothing else -
341
+ so it pipes straight into `nirium verify`:
342
+
343
+ ```bash
344
+ nirium report export anchors --from 2026-10-01 | xargs -n1 nirium verify
345
+ ```
346
+
347
+ The row count and disclaimer print to **stderr**, not stdout, so they
348
+ never end up in that pipe.
349
+ - With `--csv <file>`, the server's CSV is written to that file instead
350
+ (nothing on stdout but a confirmation).
351
+ - `--json` prints the full response (`type`, `period`, `rowCount`,
352
+ `rows`, `disclaimer`) instead of one row per line; mutually exclusive
353
+ with `--csv`.
354
+
355
+ | Option (both subcommands) | Purpose | Default |
356
+ |---|---|---|
357
+ | `--from <date>` / `--to <date>` | ISO date period | 30-day window |
358
+ | `--network <testnet\|mainnet>` | restrict to one network | all |
359
+ | `-u, --url <url>` | agent URL | `http://localhost:3002` |
360
+ | `--json` | machine-readable full response | off |
361
+
362
+ | Option (`export` only) | Purpose | Default |
363
+ |---|---|---|
364
+ | `--limit <n>` | max rows (server caps at 1000) | server default |
365
+ | `--csv <file>` | write the CSV export here instead of printing rows | off |
366
+
242
367
  ## Manage stored credentials
243
368
 
244
369
  ```bash
package/bin/nirium.js CHANGED
@@ -162,7 +162,9 @@ program
162
162
  program
163
163
  .command('verify')
164
164
  .argument('<cid>', 'IPFS Content Identifier (CID) of the audit document')
165
- .option('-g, --gateway <url>', 'IPFS gateway URL', 'https://gateway.pinata.cloud')
165
+ .option('-g, --gateway <url>', 'IPFS gateway URL - repeatable, tried in order as fallbacks', (val, prev) => [...(prev || []), val], [])
166
+ .option('--retries <n>', 'Retries per gateway on a 404 (content may not be propagated yet), with backoff', '2')
167
+ .option('--timeout <ms>', 'Per-request timeout in milliseconds', '8000')
166
168
  .option('--json', 'Output result as JSON')
167
169
  .option('--hash <hex>', 'Expected sha-256 of the evidence (hex, optional sha-256: prefix), for hash-only anchors')
168
170
  .option('--evidence <file>', 'Original evidence file; its sha-256 is compared with the anchored hash')
@@ -177,7 +179,20 @@ program
177
179
  console.error(`❌ ${err.message}`);
178
180
  process.exit(1);
179
181
  }
180
- const result = await fetchAndVerifyCid(cid, options.gateway, globalThis.fetch, { expectedHash });
182
+
183
+ const retries = Number(options.retries);
184
+ const timeoutMs = Number(options.timeout);
185
+ if (!Number.isInteger(retries) || retries < 0) {
186
+ console.error(`❌ Error: Invalid --retries '${options.retries}': must be a non-negative integer.`);
187
+ process.exit(1);
188
+ }
189
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
190
+ console.error(`❌ Error: Invalid --timeout '${options.timeout}': must be a positive number of milliseconds.`);
191
+ process.exit(1);
192
+ }
193
+
194
+ const gateways = options.gateway.length > 0 ? options.gateway : ['https://gateway.pinata.cloud'];
195
+ const result = await fetchAndVerifyCid(cid, gateways, globalThis.fetch, { expectedHash, retries, timeoutMs });
181
196
  if (options.json) {
182
197
  console.log(JSON.stringify(result, null, 2));
183
198
  } else {
@@ -188,6 +203,23 @@ program
188
203
  }
189
204
  });
190
205
 
206
+ // --- COMMAND: anchor ---
207
+ program
208
+ .command('anchor')
209
+ .description('Anchor a sha-256 hash (or a small JSON record) to IPFS via an Audit Trail node')
210
+ .option('--file <path>', 'Anchor the sha-256 of this file - the file itself is never uploaded')
211
+ .option('--hash <hex>', 'sha-256 hex of your evidence (64 chars, optional sha-256: prefix)')
212
+ .option('--record <json>', 'Small JSON object (max 8KB) to anchor verbatim, e.g. \'{"order":"A-12"}\'')
213
+ .option('--tx <hash>', 'Transaction hash to associate with this anchor')
214
+ .option('--tag <tag>', 'Free-form label for this anchor')
215
+ .option('--sign', 'Attach an ed25519 attestation of which key produced this anchor')
216
+ .option('--key-env <VAR>', 'Environment variable holding the Stellar secret key to sign with (--sign only; default: the config store\'s secretKey)')
217
+ .option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
218
+ .option('--json', 'Output result as JSON')
219
+ .action(async (options) => {
220
+ await executeAnchorCommand(options);
221
+ });
222
+
191
223
  // --- COMMAND: doctor ---
192
224
  program
193
225
  .command('doctor')
@@ -229,7 +261,7 @@ program
229
261
  .description('🚀 Spin up a local x402-protected demo HTTP server to test payments against')
230
262
  .option('-p, --price <price>', 'Price for access (e.g. $0.02)', '$0.02')
231
263
  .option('-P, --pay-to <address>', 'Stellar public key (G...) to receive payments')
232
- .option('-port, --port <port>', 'Port number to listen on', '3000')
264
+ .option('--port <port>', 'Port number to listen on', '3000')
233
265
  .option('-n, --network <network>', 'CAIP-2 network ID (stellar:testnet or stellar:pubnet)', 'stellar:testnet')
234
266
  .option('-r, --route <route>', 'Route path to protect', '/api/v1/data')
235
267
  // Kept only to refuse it with a clear message: commander's own
@@ -251,6 +283,38 @@ program
251
283
  await executeConfigCommand(action, key, value);
252
284
  });
253
285
 
286
+ // --- COMMAND: report ---
287
+ const reportCommand = program
288
+ .command('report')
289
+ .description('📊 Institutional-format summaries and exports from the Reporting node - not certified regulatory reporting');
290
+
291
+ reportCommand
292
+ .command('summary')
293
+ .description('Aggregate payroll, payments, and anchors for a period')
294
+ .option('--from <date>', 'ISO date, start of period (default: a 30-day window)')
295
+ .option('--to <date>', 'ISO date, end of period')
296
+ .option('--network <network>', 'testnet or mainnet (default: all)')
297
+ .option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
298
+ .option('--json', 'Output as JSON')
299
+ .action(async (options) => {
300
+ await executeReportSummaryCommand(options);
301
+ });
302
+
303
+ reportCommand
304
+ .command('export')
305
+ .argument('<type>', 'anchors, payments, or payroll')
306
+ .description('Export rows for a period - "export anchors" prints one CID per line, pipeable to `nirium verify`')
307
+ .option('--from <date>', 'ISO date, start of period (default: a 30-day window)')
308
+ .option('--to <date>', 'ISO date, end of period')
309
+ .option('--limit <n>', 'Max rows (server caps at 1000)')
310
+ .option('--network <network>', 'testnet or mainnet (default: all)')
311
+ .option('--csv <file>', 'Write the CSV export to this file instead of printing rows')
312
+ .option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
313
+ .option('--json', 'Output the full JSON response instead of one row per line')
314
+ .action(async (type, options) => {
315
+ await executeReportExportCommand(type, options);
316
+ });
317
+
254
318
  // Un servidor que COBRA, no uno que escucha. Es el camino corto de
255
319
  // "instalé algo" a "me pagaron": levantas esto, le pegas con un cliente
256
320
  // x402 y el pago se liquida on-chain antes de que salga la respuesta.
@@ -1566,18 +1630,11 @@ function verifyAuditDocument(doc, cid, { expectedHash } = {}) {
1566
1630
  // when given, otherwise report the hash as unchecked (not as a mismatch).
1567
1631
  const mode = doc.record ? 'record' : 'hash-only';
1568
1632
  let computedHash = '';
1569
- let recordHash = '';
1570
1633
  let hashStatus;
1571
1634
  if (mode === 'record') {
1572
- recordHash = crypto.createHash('sha256').update(JSON.stringify(doc.record)).digest('hex');
1573
- computedHash = recordHash;
1574
- hashStatus = recordHash === anchoredHash ? 'match' : 'mismatch';
1575
- // --hash/--evidence that disagrees with the anchor is what the user is
1576
- // asking about: report its hash, not the record's (which can equal the anchor).
1577
- if (expectedHash && expectedHash !== anchoredHash) {
1578
- hashStatus = 'mismatch';
1579
- computedHash = expectedHash;
1580
- }
1635
+ computedHash = crypto.createHash('sha256').update(JSON.stringify(doc.record)).digest('hex');
1636
+ hashStatus = computedHash === anchoredHash ? 'match' : 'mismatch';
1637
+ if (hashStatus === 'match' && expectedHash && expectedHash !== anchoredHash) hashStatus = 'mismatch';
1581
1638
  } else if (expectedHash) {
1582
1639
  computedHash = expectedHash;
1583
1640
  hashStatus = expectedHash === anchoredHash ? 'match' : 'mismatch';
@@ -1593,7 +1650,7 @@ function verifyAuditDocument(doc, cid, { expectedHash } = {}) {
1593
1650
  // Never trust the document's own statement field. In record mode the
1594
1651
  // statement is built from the recomputed record hash; in hash-only mode
1595
1652
  // from content_sha256 (a swapped content_sha256 breaks the signature).
1596
- statement = `nirium-audit-v1:${mode === 'record' ? recordHash : anchoredHash}`;
1653
+ statement = `nirium-audit-v1:${mode === 'record' ? computedHash : anchoredHash}`;
1597
1654
  declaredStatement = doc.agent.statement;
1598
1655
  signatureScheme = verifyEd25519Signature(signerKey, statement, doc.agent.signature) || undefined;
1599
1656
  signatureStatus = signatureScheme ? 'valid' : 'invalid';
@@ -1608,18 +1665,58 @@ function verifyAuditDocument(doc, cid, { expectedHash } = {}) {
1608
1665
  return { ok, verified: ok, cid, mode, hashMatch: hashStatus === 'match', hashStatus, expectedHash: anchoredHash, computedHash, signatureStatus, signatureScheme, signerKey, statement, declaredStatement, agentId };
1609
1666
  }
1610
1667
 
1611
- async function fetchAndVerifyCid(cid, gatewayUrl = 'https://gateway.pinata.cloud', fetchFn = globalThis.fetch, opts = {}) {
1612
- const url = `${gatewayUrl.replace(/\/$/, '')}/ipfs/${cid}`;
1613
- try {
1614
- const res = await fetchFn(url);
1615
- if (!res.ok) {
1616
- return { ok: false, verified: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: `IPFS gateway returned HTTP ${res.status}` };
1668
+ // `gateways` may be a single URL string (back-compat for direct callers)
1669
+ // or an array tried in order. On a 404, the SAME gateway is retried up to
1670
+ // `retries` times with a flat backoff before moving to the next gateway -
1671
+ // a 404 can mean "not propagated to this gateway yet", which a moment's
1672
+ // wait often resolves, unlike a real 4xx/5xx or network failure, which
1673
+ // moves on immediately since retrying the same gateway won't help.
1674
+ // `sleepFn` exists only so tests don't have to sit through real backoff.
1675
+ async function fetchAndVerifyCid(cid, gateways = 'https://gateway.pinata.cloud', fetchFn = globalThis.fetch, opts = {}) {
1676
+ const list = Array.isArray(gateways) ? gateways : [gateways];
1677
+ const retries = Number.isInteger(opts.retries) && opts.retries >= 0 ? opts.retries : 2;
1678
+ const timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : 8000;
1679
+ const sleep = opts.sleepFn || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1680
+ const BACKOFF_MS = 300;
1681
+
1682
+ const attempts = [];
1683
+ for (const gatewayUrl of list) {
1684
+ const url = `${gatewayUrl.replace(/\/$/, '')}/ipfs/${cid}`;
1685
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
1686
+ if (attempt > 0) await sleep(BACKOFF_MS);
1687
+ try {
1688
+ const res = await fetchFn(url, { signal: AbortSignal.timeout(timeoutMs) });
1689
+ if (res.status === 404) {
1690
+ attempts.push({ gateway: gatewayUrl, attempt, status: 404 });
1691
+ continue; // worth retrying THIS gateway: may just not be propagated yet
1692
+ }
1693
+ if (!res.ok) {
1694
+ attempts.push({ gateway: gatewayUrl, attempt, status: res.status });
1695
+ break; // a real error from this gateway - try the next one, not more retries here
1696
+ }
1697
+ const doc = await res.json();
1698
+ return { ...verifyAuditDocument(doc, cid, opts), gateway: gatewayUrl, attempts: [...attempts, { gateway: gatewayUrl, attempt, status: 200 }] };
1699
+ } catch (err) {
1700
+ attempts.push({ gateway: gatewayUrl, attempt, error: err?.message || String(err) });
1701
+ break; // network-level failure (unreachable, timeout) - try the next gateway
1702
+ }
1617
1703
  }
1618
- const doc = await res.json();
1619
- return verifyAuditDocument(doc, cid, opts);
1620
- } catch (err) {
1621
- return { ok: false, verified: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: `Failed to fetch CID from gateway: ${err?.message || String(err)}` };
1622
1704
  }
1705
+
1706
+ // Every gateway exhausted without a usable (200) response. All-404
1707
+ // means the content plausibly just isn't propagated anywhere yet -
1708
+ // a different situation from a gateway being unreachable or erroring,
1709
+ // which this reports distinctly so a caller doesn't read "not found
1710
+ // anywhere" as "the hash doesn't match" (it was never fetched at all).
1711
+ const allNotFound = attempts.length > 0 && attempts.every((a) => a.status === 404);
1712
+ return {
1713
+ ok: false, verified: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent',
1714
+ availability: allNotFound ? 'not_yet_available' : 'gateway_error',
1715
+ error: allNotFound
1716
+ ? `CID not found on ${list.length} gateway(s) after ${retries} retr${retries === 1 ? 'y' : 'ies'} each - it may not be propagated yet, not necessarily wrong`
1717
+ : `Could not fetch the CID from any of ${list.length} gateway(s) - see attempts for each failure`,
1718
+ attempts,
1719
+ };
1623
1720
  }
1624
1721
 
1625
1722
  function formatVerifyOutput(result) {
@@ -1627,6 +1724,30 @@ function formatVerifyOutput(result) {
1627
1724
  lines.push(`🔍 Nirium Audit Verifier`);
1628
1725
  if (result.cid) lines.push(`CID: ${result.cid}`);
1629
1726
  lines.push(`--------------------------------------------------`);
1727
+
1728
+ // The document was never fetched at all (every gateway failed), so
1729
+ // there is no hash or signature to report on - printing those sections
1730
+ // would show a false "MISMATCH" for a CID that was simply never
1731
+ // retrieved. `availability` tells apart "not found anywhere yet"
1732
+ // (may just not be propagated) from an actual gateway/network error.
1733
+ if (result.hashStatus === undefined && result.error) {
1734
+ lines.push(result.availability === 'not_yet_available'
1735
+ ? `ℹ NOT YET AVAILABLE: ${result.error}`
1736
+ : `❌ GATEWAY ERROR: ${result.error}`);
1737
+ if (Array.isArray(result.attempts) && result.attempts.length > 0) {
1738
+ lines.push(`--------------------------------------------------`);
1739
+ lines.push('Attempts:');
1740
+ for (const a of result.attempts) {
1741
+ lines.push(` ${a.gateway} (try ${a.attempt + 1}): ${a.error ? a.error : `HTTP ${a.status}`}`);
1742
+ }
1743
+ }
1744
+ lines.push(`--------------------------------------------------`);
1745
+ lines.push(result.availability === 'not_yet_available'
1746
+ ? `❌ NOT YET AVAILABLE (not a hash mismatch - try again shortly, or add --gateway for another source)`
1747
+ : `❌ VERIFICATION FAILED (could not reach the content, not a hash mismatch)`);
1748
+ return lines.join('\n');
1749
+ }
1750
+
1630
1751
  if (result.hashStatus === 'unchecked') {
1631
1752
  lines.push(`ℹ HASH: NOT CHECKED (hash-only anchor: ${result.expectedHash.slice(0, 16)}...)`);
1632
1753
  lines.push(` Pass --hash <hex> or --evidence <file> to compare it with your original evidence.`);
@@ -1657,4 +1778,315 @@ function formatVerifyOutput(result) {
1657
1778
  return lines.join('\n');
1658
1779
  }
1659
1780
 
1781
+ // ═══════════════════════════════════════════════════════════════
1782
+ // anchor — anchor a hash or small record to IPFS via the Audit Trail node
1783
+ // ═══════════════════════════════════════════════════════════════
1784
+
1785
+ const ANCHOR_MAX_RECORD_BYTES = 8 * 1024;
1786
+
1787
+ // `nirium anchor` deliberately has no `--network` flag: the agent box
1788
+ // decides its own network (STELLAR_NETWORK) and the server already
1789
+ // rejects a `network` field in the body. A client-side flag here would
1790
+ // only ever be ignored, which is worse than not having it.
1791
+ async function executeAnchorCommand(options) {
1792
+ const fail = (error, hint) => {
1793
+ if (options.json) {
1794
+ console.log(JSON.stringify({ ok: false, error, ...(hint ? { hint } : {}) }));
1795
+ } else {
1796
+ console.error(`❌ Error: ${error}${hint ? `\n ${hint}` : ''}`);
1797
+ }
1798
+ process.exit(1);
1799
+ };
1800
+
1801
+ const given = ['file', 'hash', 'record'].filter((k) => options[k] !== undefined);
1802
+ if (given.length === 0) {
1803
+ fail('Provide exactly one of --file, --hash, or --record.');
1804
+ return;
1805
+ }
1806
+ if (given.length > 1) {
1807
+ fail(`--${given[0]} and --${given[1]} were both given - use exactly one.`);
1808
+ return;
1809
+ }
1810
+
1811
+ const body = {};
1812
+ if (options.file !== undefined) {
1813
+ let fileBuf;
1814
+ try {
1815
+ fileBuf = fs.readFileSync(options.file);
1816
+ } catch (err) {
1817
+ fail(`Could not read --file '${options.file}': ${err?.message || String(err)}`);
1818
+ return;
1819
+ }
1820
+ body.hash = crypto.createHash('sha256').update(fileBuf).digest('hex');
1821
+ } else if (options.hash !== undefined) {
1822
+ try {
1823
+ body.hash = normalizeHashInput(options.hash);
1824
+ } catch (err) {
1825
+ fail(err.message);
1826
+ return;
1827
+ }
1828
+ } else {
1829
+ let record;
1830
+ try {
1831
+ record = JSON.parse(options.record);
1832
+ } catch (err) {
1833
+ fail(`--record is not valid JSON: ${err?.message || String(err)}`);
1834
+ return;
1835
+ }
1836
+ if (typeof record !== 'object' || record === null || Array.isArray(record)) {
1837
+ fail('--record must be a JSON object, e.g. \'{"order":"A-12"}\'');
1838
+ return;
1839
+ }
1840
+ // Mirrors the server's own 8KB limit (MAX_RECORD_BYTES in
1841
+ // auditRoutes.ts) so an oversized record fails locally, before any
1842
+ // network call, instead of round-tripping for a 413.
1843
+ const raw = JSON.stringify(record);
1844
+ if (Buffer.byteLength(raw, 'utf8') > ANCHOR_MAX_RECORD_BYTES) {
1845
+ fail(`--record exceeds ${ANCHOR_MAX_RECORD_BYTES / 1024}KB - anchor a sha-256 hash instead (--hash or --file).`);
1846
+ return;
1847
+ }
1848
+ body.record = record;
1849
+ }
1850
+
1851
+ if (options.tx !== undefined) body.txHash = options.tx;
1852
+ if (options.tag !== undefined) body.tag = options.tag;
1853
+
1854
+ const agentAttestation = await maybeBuildAgentAttestation(options, body, fail);
1855
+ if (agentAttestation === 'failed') return; // fail() already called and exited
1856
+ if (agentAttestation) body.agent = agentAttestation;
1857
+
1858
+ let response;
1859
+ try {
1860
+ response = await fetch(`${options.url}/api/audit/log`, {
1861
+ method: 'POST',
1862
+ headers: { 'content-type': 'application/json' },
1863
+ body: JSON.stringify(body),
1864
+ signal: AbortSignal.timeout(20_000),
1865
+ });
1866
+ } catch (err) {
1867
+ const msg = (err?.name === 'TimeoutError' || err?.name === 'AbortError')
1868
+ ? `Timed out waiting for ${options.url}/api/audit/log`
1869
+ : `Agent unreachable at ${options.url}: ${err?.message || String(err)}`;
1870
+ fail(msg);
1871
+ return;
1872
+ }
1873
+
1874
+ let data = null;
1875
+ try {
1876
+ data = await response.json();
1877
+ } catch { /* empty or non-JSON body */ }
1878
+
1879
+ if (!response.ok) {
1880
+ fail(data?.error || `Agent returned HTTP ${response.status}`, data?.sign ? `Sign this statement instead: ${data.sign}` : undefined);
1881
+ return;
1882
+ }
1883
+
1884
+ if (options.json) {
1885
+ console.log(JSON.stringify({ ok: true, ...data }, null, 2));
1886
+ return;
1887
+ }
1888
+
1889
+ console.log('✅ Anchored to IPFS');
1890
+ console.log(` CID: ${data.cid}`);
1891
+ console.log(` Content sha256: ${data.content_sha256}`);
1892
+ if (data.gatewayUrl) console.log(` Gateway URL: ${data.gatewayUrl}`);
1893
+ if (data.attestedBy) console.log(` Attested by: ${data.attestedBy}`);
1894
+ console.log(` Anchored at: ${data.anchoredAt}`);
1895
+ console.log(`\n Verify independently: nirium verify ${data.cid}`);
1896
+ }
1897
+
1898
+ // Returns the `agent` object for the request body, `undefined` when
1899
+ // `--sign` was not passed, or the string 'failed' when fail() already
1900
+ // ran (caller must return without doing anything else).
1901
+ //
1902
+ // Signs locally and never sends the secret key anywhere - only the
1903
+ // resulting signature and the derived public key leave this process.
1904
+ // The statement signed, `nirium-audit-v1:<content_sha256>`, must match
1905
+ // exactly what the server itself computes as contentSha before it
1906
+ // verifies: the hash as-is for `--hash`/`--file` (already normalized to
1907
+ // lowercase hex at this point), or sha-256 of the record's JSON text for
1908
+ // `--record` - never the file's own content, which the server never sees.
1909
+ async function maybeBuildAgentAttestation(options, body, fail) {
1910
+ if (!options.sign) return undefined;
1911
+
1912
+ let secretKey;
1913
+ if (options.keyEnv !== undefined) {
1914
+ secretKey = process.env[options.keyEnv];
1915
+ if (!secretKey) {
1916
+ fail(`--key-env ${options.keyEnv} is not set (or is empty) in the environment.`);
1917
+ return 'failed';
1918
+ }
1919
+ } else {
1920
+ secretKey = loadConfig().secretKey;
1921
+ if (!secretKey) {
1922
+ fail('--sign needs a key: run `nirium config set secretKey`, or pass --key-env <VAR> '
1923
+ + 'with the secret key in that environment variable.');
1924
+ return 'failed';
1925
+ }
1926
+ }
1927
+
1928
+ let keypair;
1929
+ try {
1930
+ keypair = Keypair.fromSecret(secretKey);
1931
+ } catch (err) {
1932
+ fail(`--sign: invalid Stellar secret key - ${err?.message || String(err)}`);
1933
+ return 'failed';
1934
+ }
1935
+
1936
+ const contentSha = body.hash
1937
+ ? body.hash
1938
+ : crypto.createHash('sha256').update(JSON.stringify(body.record)).digest('hex');
1939
+ const statement = `nirium-audit-v1:${contentSha}`;
1940
+ const signature = Buffer.from(keypair.sign(Buffer.from(statement, 'utf8'))).toString('base64');
1941
+
1942
+ return { key: keypair.publicKey(), signature };
1943
+ }
1944
+
1945
+ // ═══════════════════════════════════════════════════════════════
1946
+ // report — summaries and exports from the Reporting node
1947
+ // ═══════════════════════════════════════════════════════════════
1948
+
1949
+ function buildQueryString(params) {
1950
+ const qs = new URLSearchParams();
1951
+ for (const [k, v] of Object.entries(params)) {
1952
+ if (v !== undefined && v !== null && v !== '') qs.set(k, String(v));
1953
+ }
1954
+ const str = qs.toString();
1955
+ return str ? `?${str}` : '';
1956
+ }
1957
+
1958
+ async function fetchReportJson(url, fail) {
1959
+ let response;
1960
+ try {
1961
+ response = await fetch(url, { signal: AbortSignal.timeout(20_000) });
1962
+ } catch (err) {
1963
+ const msg = (err?.name === 'TimeoutError' || err?.name === 'AbortError')
1964
+ ? `Timed out waiting for ${url}`
1965
+ : `Agent unreachable: ${err?.message || String(err)}`;
1966
+ fail(msg);
1967
+ return null;
1968
+ }
1969
+ let data = null;
1970
+ try {
1971
+ data = await response.json();
1972
+ } catch { /* empty or non-JSON body */ }
1973
+ if (!response.ok) {
1974
+ fail(data?.error || `Agent returned HTTP ${response.status}`);
1975
+ return null;
1976
+ }
1977
+ return data;
1978
+ }
1979
+
1980
+ async function executeReportSummaryCommand(options) {
1981
+ const fail = (error) => {
1982
+ if (options.json) {
1983
+ console.log(JSON.stringify({ ok: false, error }));
1984
+ } else {
1985
+ console.error(`❌ Error: ${error}`);
1986
+ }
1987
+ process.exit(1);
1988
+ };
1989
+
1990
+ const qs = buildQueryString({ from: options.from, to: options.to, network: options.network });
1991
+ const data = await fetchReportJson(`${options.url}/api/reporting/summary${qs}`, fail);
1992
+ if (!data) return; // fail() already exited
1993
+
1994
+ if (options.json) {
1995
+ console.log(JSON.stringify(data, null, 2));
1996
+ return;
1997
+ }
1998
+
1999
+ console.log('📊 Nirium Reporting Summary');
2000
+ console.log(` Network: ${data.network}`);
2001
+ console.log(` Period: ${data.period?.from || '(default window)'} -> ${data.period?.to || 'now'}`);
2002
+ console.log(` Payroll: ${data.payroll?.settledRuns ?? 0} settled run(s), ${data.payroll?.recipientsPaid ?? 0} recipient(s) paid`);
2003
+ for (const [asset, amount] of Object.entries(data.payroll?.totalsByAsset || {})) {
2004
+ console.log(` ${asset}: ${amount}`);
2005
+ }
2006
+ console.log(` Payments: ${data.payments?.count ?? 0} receipt(s), ${data.payments?.totalUsdc ?? '0'} USDC total`);
2007
+ console.log(` Anchors: ${data.anchors?.count ?? 0} (latest: ${data.anchors?.latestCid || 'none'})`);
2008
+ if (Array.isArray(data.warnings) && data.warnings.length > 0) {
2009
+ console.log(' ⚠ Warnings:');
2010
+ for (const w of data.warnings) console.log(` - ${w}`);
2011
+ }
2012
+ console.log(`\n ${data.disclaimer || ''}`);
2013
+ }
2014
+
2015
+ const REPORT_EXPORT_TYPES = new Set(['payroll', 'payments', 'anchors']);
2016
+
2017
+ async function executeReportExportCommand(type, options) {
2018
+ const fail = (error) => {
2019
+ if (options.json) {
2020
+ console.log(JSON.stringify({ ok: false, error }));
2021
+ } else {
2022
+ console.error(`❌ Error: ${error}`);
2023
+ }
2024
+ process.exit(1);
2025
+ };
2026
+
2027
+ if (!REPORT_EXPORT_TYPES.has(type)) {
2028
+ fail('`type` must be one of: payroll | payments | anchors');
2029
+ return;
2030
+ }
2031
+ if (options.csv && options.json) {
2032
+ fail('--csv and --json are mutually exclusive - --csv writes a file, --json prints the response.');
2033
+ return;
2034
+ }
2035
+ if (options.limit !== undefined) {
2036
+ const n = Number(options.limit);
2037
+ if (!Number.isInteger(n) || n <= 0) {
2038
+ fail(`Invalid --limit '${options.limit}': must be a positive integer.`);
2039
+ return;
2040
+ }
2041
+ }
2042
+
2043
+ const format = options.csv ? 'csv' : 'json';
2044
+ const qs = buildQueryString({
2045
+ type, format, from: options.from, to: options.to, limit: options.limit, network: options.network,
2046
+ });
2047
+ const url = `${options.url}/api/reporting/export${qs}`;
2048
+
2049
+ if (format === 'csv') {
2050
+ let response;
2051
+ try {
2052
+ response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
2053
+ } catch (err) {
2054
+ fail(`Agent unreachable: ${err?.message || String(err)}`);
2055
+ return;
2056
+ }
2057
+ if (!response.ok) {
2058
+ let data = null;
2059
+ try { data = await response.json(); } catch { /* non-JSON error body */ }
2060
+ fail(data?.error || `Agent returned HTTP ${response.status}`);
2061
+ return;
2062
+ }
2063
+ const text = await response.text();
2064
+ try {
2065
+ fs.writeFileSync(options.csv, text);
2066
+ } catch (err) {
2067
+ fail(`Could not write --csv '${options.csv}': ${err?.message || String(err)}`);
2068
+ return;
2069
+ }
2070
+ console.log(`✅ Wrote ${options.csv}`);
2071
+ return;
2072
+ }
2073
+
2074
+ const data = await fetchReportJson(url, fail);
2075
+ if (!data) return; // fail() already exited
2076
+
2077
+ if (options.json) {
2078
+ console.log(JSON.stringify(data, null, 2));
2079
+ return;
2080
+ }
2081
+
2082
+ // `export anchors` prints exactly one CID per line on stdout - nothing
2083
+ // else - so it pipes straight into `nirium verify` (xargs -n1 or a
2084
+ // while-read loop). Row count and the disclaimer go to stderr instead
2085
+ // of stdout for the same reason: stdout must stay pure for piping.
2086
+ for (const row of data.rows || []) {
2087
+ console.log(type === 'anchors' ? (row.cid || '') : JSON.stringify(row));
2088
+ }
2089
+ console.error(`# ${data.rowCount ?? (data.rows || []).length} row(s). ${data.disclaimer || ''}`);
2090
+ }
2091
+
1660
2092
  program.parse();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nirium-cli",
3
- "version": "3.0.1",
4
- "description": "Nirium CLI — scaffold Stellar agent projects and check agent status",
3
+ "version": "3.1.0",
4
+ "description": "Nirium CLI \u2014 scaffold Stellar agent projects and check agent status",
5
5
  "main": "bin/nirium.js",
6
6
  "type": "module",
7
7
  "bin": {
@@ -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/pay-agent-construction.test.js test/pay-status-and-cap.test.js test/status.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-retry-gateway.test.js test/pay-agent-construction.test.js test/pay-status-and-cap.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",
@@ -23,7 +23,7 @@
23
23
  "license": "Apache-2.0",
24
24
  "dependencies": {
25
25
  "axios": "^1.20.0",
26
- "commander": "^11.0.0",
26
+ "commander": "^14.0.3",
27
27
  "nirium": "^0.16.1",
28
28
  "express": "^5.1.0",
29
29
  "@stellar/stellar-sdk": "^16.3.0",
@@ -48,7 +48,7 @@
48
48
  }
49
49
  },
50
50
  "devDependencies": {
51
- "@types/node": "^20.19.30",
51
+ "@types/node": "^25.9.9",
52
52
  "typescript": "^5.0.0"
53
53
  },
54
54
  "files": [