nirium-cli 2.0.0 → 3.0.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 +77 -28
  2. package/bin/nirium.js +214 -47
  3. package/package.json +26 -6
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # nirium-cli
2
2
 
3
- Scaffold Stellar agent projects — including one that charges for itself.
3
+ Scaffold Stellar agent projects, including one that charges for itself.
4
4
 
5
5
  ```bash
6
6
  npm install -g nirium-cli
@@ -37,14 +37,15 @@ The generated server is about ten lines, because `x402Serve()` from the
37
37
  [`nirium`](https://www.npmjs.com/package/nirium) SDK carries the facilitator
38
38
  client, the scheme registration and the route shape.
39
39
 
40
- **Usage telemetry (disclosed, not hidden):** once running, `x402Serve()`
41
- sends Nirium a small, non-blocking usage ping — a SHA-256 hash of your
42
- `X402_FACILITATOR_API_KEY` (never the key itself), your `STELLAR_PAY_TO`
43
- address, network, route/request counts, and the SDK version, timestamped
44
- server-side. It never blocks, delays, or fails a charge if the ping fails.
45
- This is the only way Nirium knows whether a scaffolded server like this one
46
- is actually running in production — it doesn't authorize or gate anything.
47
- Set `NIRIUM_X402SERVE_TELEMETRY=false` in the generated `.env` to opt out.
40
+ **Usage telemetry (off by default):** `x402Serve()` sends Nirium nothing
41
+ unless you turn it on. If you set `NIRIUM_X402SERVE_TELEMETRY=true` in the
42
+ generated `.env`, it sends a small usage ping when the server starts and
43
+ again every 50 requests or 10 minutes: your `STELLAR_PAY_TO` address, the
44
+ network, the number of routes or requests, the SDK version, and a short hash
45
+ of your `X402_FACILITATOR_API_KEY` (the first 16 characters of its SHA-256,
46
+ never the key itself). The ping never blocks, delays or fails a charge, and
47
+ it does not authorize or gate anything. Leave the variable unset and nothing
48
+ is sent. (Checked against the code of `nirium` 0.16.1; `dist/` is identical to 0.16.0.)
48
49
 
49
50
  ## Listen to protocol signals
50
51
 
@@ -64,23 +65,36 @@ NIRIUM_SECRET_KEY=S... nirium pay https://your-api.example.com/premium/signals
64
65
  ```
65
66
 
66
67
  Signs and settles a real x402 payment against any endpoint that returns a
67
- 402, then prints the response. No scaffolding involved — this hits a live
68
+ 402, then prints the response. No scaffolding involved. This hits a live
68
69
  server directly, useful for testing a `nirium serve` instance or someone
69
70
  else's paid API without writing a client.
70
71
 
72
+ Exits 0 only when the request after payment succeeds (`response.ok`); a
73
+ 4xx or 5xx is printed and reported as a failure, in text and `--json`, and
74
+ exits 1. The response payload is still printed either way, so you can see
75
+ what the server said.
76
+
71
77
  There is no `--secret` flag: a key passed as a command-line argument sits
72
78
  in your shell history and in `ps`'s full command line for anyone else on
73
- the machine to read. Set `NIRIUM_SECRET_KEY`, run `nirium config set
74
- secretKey S...` once, or leave it unset — a real terminal prompts for it
75
- without echoing what you type.
79
+ the machine to read. There are three safe ways to give
80
+ it the key: set `NIRIUM_SECRET_KEY`; run `nirium config set secretKey` with
81
+ no value (a terminal asks for the key without showing it, or you can pipe
82
+ it in through stdin) to save it once; or leave it unset and a terminal
83
+ prompts for it each time. `nirium config set secretKey S...` with the key
84
+ on the command line is refused and nothing is saved.
76
85
 
77
86
  | Option | Purpose |
78
87
  |---|---|
79
88
  | `-n, --network <network>` | `stellar:testnet` (default) or `stellar:pubnet` |
80
- | `-a, --amount <amount>` | Override the price the server advertises |
89
+ | `--max-amount <usd>` | Refuse to pay more than this, e.g. `5` or `$0.50`. Rejects zero, negative and non-numeric values before any network call |
81
90
  | `--json` | Machine-readable result: status, duration, payer, tx hash, response body |
82
91
 
83
- The secret key never leaves your machine except as a signature — the CLI
92
+ `--max-amount` is compared in the units of whatever asset the server asks
93
+ for, not converted. `"$5"` is 5 dollars only when the payment is in a
94
+ dollar-pegged asset such as USDC, which is what Nirium's own endpoints
95
+ charge in.
96
+
97
+ The secret key never leaves your machine except as a signature: the CLI
84
98
  signs locally and sends the signed payment, not the key itself. Missing a
85
99
  secret key fails immediately with the three ways to supply one, before any
86
100
  network call happens.
@@ -114,10 +128,29 @@ can also come from `nirium config set payTo`.
114
128
  ## Check an agent
115
129
 
116
130
  ```bash
117
- nirium status
131
+ nirium status --url https://nirium-agent.fly.dev
118
132
  ```
119
133
 
120
- ## Diagnose your x402/MPP setup
134
+ Calls the `/health` endpoint of an agent and prints whether it is running
135
+ and for how long. It also prints a version and a network line, but they only
136
+ carry a value when the agent reports one: the Nirium testnet agent's
137
+ `/health` returns just `status`, `service` and `uptime` today, so those two
138
+ lines are omitted rather than shown as `undefined`. `--url` points to the
139
+ agent you want to check; `https://nirium-agent.fly.dev` is the Nirium
140
+ testnet agent. Without `--url` it looks for an agent on your own machine at
141
+ `http://localhost:3001`, so it reports "unreachable" if you are not running
142
+ one.
143
+
144
+ Exits 0 only when `/health` answers 2xx; exits 1 if the agent is
145
+ unreachable, times out, or answers with anything else.
146
+
147
+ | Option | Purpose | Default |
148
+ |---|---|---|
149
+ | `-u, --url <url>` | Agent to check | `http://localhost:3001` |
150
+ | `--json` | The raw `/health` fields plus `ok` | off |
151
+ | `--timeout <ms>` | Give up after this many milliseconds instead of hanging | `5000` |
152
+
153
+ ## Diagnose your x402 setup
121
154
 
122
155
  ```bash
123
156
  nirium doctor --network testnet
@@ -125,11 +158,12 @@ nirium doctor --network testnet
125
158
 
126
159
  Five checks against your actual environment before you find out the hard
127
160
  way in production: `payTo` is a well-formed public key (not a secret key
128
- pasted in the wrong field — a real mistake this catches), the facilitator
161
+ pasted in the wrong field, a real mistake this catches), the facilitator
129
162
  API key authenticates against `channels.openzeppelin.com`, the Soroban RPC
130
163
  endpoint for your target network is reachable, `STELLAR_SECRET_KEY` (if
131
164
  set) is validly formatted, and MPP config (if set) is internally
132
- consistent. Reads from `.env` in the current directory by default.
165
+ consistent. The MPP check only validates the values in your config; Nirium
166
+ does not charge MPP payments on mainnet today. Reads from `.env` in the current directory by default.
133
167
 
134
168
  | Option | Purpose |
135
169
  |---|---|
@@ -175,20 +209,35 @@ nirium verify <cid>
175
209
  ```
176
210
 
177
211
  Independently re-checks a Nirium audit document anchored to IPFS: fetches
178
- it from a gateway, recomputes its SHA-256 content hash, and — if the
179
- document carries an agent attestation — verifies the ed25519 signature
212
+ it from a gateway, recomputes its SHA-256 content hash, and, if the
213
+ document carries an agent attestation, verifies the ed25519 signature
180
214
  over `nirium-audit-v1:<content_sha256>` against the declared signer's
181
215
  Stellar public key. Nothing here trusts the document's own claims about
182
216
  itself; both the hash and the signed statement are recomputed from the
183
217
  raw content, not read off the document.
184
218
 
185
- | Option | Purpose |
186
- |---|---|
219
+ Hash-only anchors (no `record`, the recommended mode) have nothing to
220
+ recompute: the document's `content_sha256` is the hash you submitted. Pass
221
+ `--hash <hex>` or `--evidence <file>` to compare it with your own evidence;
222
+ without either, the hash is reported as NOT CHECKED (not as a mismatch)
223
+ and the signature is still verified over `nirium-audit-v1:<content_sha256>`.
224
+ Signatures are accepted as base64 or hex, raw ed25519 or SEP-53
225
+ (Freighter `signMessage`), like the anchoring node.
226
+
227
+ | Option | Purpose | Default |
228
+ |---|---|---|
187
229
  | `-g, --gateway <url>` | IPFS gateway to fetch from | `https://gateway.pinata.cloud` |
188
- | `--json` | machine-readable result |
230
+ | `--json` | machine-readable result | off |
231
+ | `--hash <hex>` | expected evidence hash for a hash-only anchor (`sha-256:` prefix optional) | none |
232
+ | `--evidence <file>` | file whose SHA-256 is compared with the anchored hash | none |
189
233
 
190
234
  Exits non-zero (and prints which check failed) if the hash doesn't match
191
- or the signature doesn't verify.
235
+ or the signature doesn't verify. A pass also requires that at least one
236
+ of the two checks actually ran and succeeded, a matching `--hash`/
237
+ `--evidence`, a valid agent signature, or both. If both were skipped
238
+ (an unsigned hash-only anchor with no `--hash` or `--evidence`), nothing
239
+ was verified, so `verify` prints `NOTHING VERIFIED`, exits non-zero, and
240
+ sets `verified: false` in `--json`, instead of reporting a pass.
192
241
 
193
242
  ## Manage stored credentials
194
243
 
@@ -202,7 +251,7 @@ nirium config delete facilitatorApiKey
202
251
 
203
252
  Stores `secretKey`, `payTo`, `network`, and `facilitatorApiKey` in
204
253
  `~/.niriumrc.json` (mode `600`) so `pay`, `serve`, and `doctor` don't need
205
- them repeated on every invocation — command-line flags and environment
254
+ them repeated on every invocation. Command-line flags and environment
206
255
  variables still take priority when present. `list` and `get` mask secret
207
256
  values in their output; the raw file is never printed.
208
257
 
@@ -211,7 +260,7 @@ values in their output; the raw file is never printed.
211
260
  | Option | Values | Default |
212
261
  |---|---|---|
213
262
  | `-n, --name <name>` | project directory name | `nirium-bot-v1` |
214
- | `-t, --template <template>` | `ts` or `py` — `bot` only | `ts` |
263
+ | `-t, --template <template>` | `ts` or `py` (`bot` only) | `ts` |
215
264
 
216
265
  ## Links
217
266
 
@@ -221,4 +270,4 @@ values in their output; the raw file is never printed.
221
270
 
222
271
  ## License
223
272
 
224
- Apache 2.0 — Nirium Protocol
273
+ Apache 2.0, Nirium Protocol
package/bin/nirium.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // ═══════════════════════════════════════════════════════════════
4
- // Nirium — Autonomous Agent CLI (v2.0.0)
4
+ // Nirium — Autonomous Agent CLI (v2.0.1)
5
5
  // ═══════════════════════════════════════════════════════════════
6
6
  //
7
7
  // Everything below is one flat file on purpose, not a build artifact:
@@ -19,7 +19,7 @@ import readline from 'readline';
19
19
  import { execSync } from 'child_process';
20
20
  import { fileURLToPath } from 'url';
21
21
  import express from 'express';
22
- import NiriumAgent, { x402Serve } from 'nirium';
22
+ import { Agent as NiriumAgent, x402Serve } from 'nirium';
23
23
  import { Keypair, StrKey } from '@stellar/stellar-sdk';
24
24
 
25
25
  function readCliVersion() {
@@ -40,7 +40,7 @@ const program = new Command();
40
40
  program
41
41
  .name('nirium')
42
42
  .description('Nirium protocol development tool')
43
- .version('2.0.0');
43
+ .version(readCliVersion());
44
44
 
45
45
  // --- COMMAND: create bot ---
46
46
  program
@@ -95,20 +95,66 @@ program
95
95
  .command('status')
96
96
  .description('Check agent connection status')
97
97
  .option('-u, --url <url>', 'Agent URL', 'http://localhost:3001')
98
+ .option('--json', 'Output the raw /health fields plus ok, as JSON')
99
+ .option('--timeout <ms>', 'Give up after this many milliseconds', '5000')
98
100
  .action(async (options) => {
101
+ const timeoutMs = Number(options.timeout);
102
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
103
+ const msg = `Invalid --timeout '${options.timeout}': must be a positive number of milliseconds.`;
104
+ if (options.json) {
105
+ console.log(JSON.stringify({ ok: false, error: msg }));
106
+ process.exit(1);
107
+ }
108
+ console.error(`❌ Error: ${msg}`);
109
+ process.exit(1);
110
+ }
111
+
112
+ let response;
99
113
  try {
100
- const response = await fetch(`${options.url}/health`);
101
- if (response.ok) {
102
- const data = await response.json();
103
- console.log('🟢 Agent is operational');
114
+ response = await fetch(`${options.url}/health`, { signal: AbortSignal.timeout(timeoutMs) });
115
+ } catch (err) {
116
+ const networkError = (err?.name === 'TimeoutError' || err?.name === 'AbortError')
117
+ ? `Timed out after ${timeoutMs}ms waiting for ${options.url}/health`
118
+ : `Agent unreachable at ${options.url}`;
119
+ if (options.json) {
120
+ console.log(JSON.stringify({ ok: false, error: networkError }, null, 2));
121
+ process.exit(1);
122
+ }
123
+ console.log(`🔴 ${networkError}`);
124
+ process.exit(1);
125
+ }
126
+
127
+ // A non-2xx body can still carry JSON worth showing; an unreadable
128
+ // body is not the same failure as being unreachable, so it is its
129
+ // own `data: null` instead of falling into the catch above.
130
+ let data = null;
131
+ try {
132
+ data = await response.json();
133
+ } catch { /* empty or non-JSON body */ }
134
+
135
+ if (options.json) {
136
+ console.log(JSON.stringify({ ...(data || {}), ok: response.ok }, null, 2));
137
+ if (!response.ok) process.exit(1);
138
+ return;
139
+ }
140
+
141
+ if (response.ok) {
142
+ console.log('🟢 Agent is operational');
143
+ if (data?.service) {
144
+ console.log(` Service: ${data.service}`);
145
+ }
146
+ if (data?.version !== undefined && data.version !== null) {
104
147
  console.log(` Version: ${data.version}`);
148
+ }
149
+ if (data?.network !== undefined && data.network !== null) {
105
150
  console.log(` Network: ${data.network}`);
151
+ }
152
+ if (data?.uptime !== undefined && data.uptime !== null) {
106
153
  console.log(` Uptime: ${data.uptime}s`);
107
- } else {
108
- console.log('🔴 Agent returned error:', response.status);
109
154
  }
110
- } catch {
111
- console.log('🔴 Agent unreachable at', options.url);
155
+ } else {
156
+ console.log('🔴 Agent returned error:', response.status);
157
+ process.exit(1);
112
158
  }
113
159
  });
114
160
 
@@ -118,9 +164,20 @@ program
118
164
  .argument('<cid>', 'IPFS Content Identifier (CID) of the audit document')
119
165
  .option('-g, --gateway <url>', 'IPFS gateway URL', 'https://gateway.pinata.cloud')
120
166
  .option('--json', 'Output result as JSON')
167
+ .option('--hash <hex>', 'Expected sha-256 of the evidence (hex, optional sha-256: prefix), for hash-only anchors')
168
+ .option('--evidence <file>', 'Original evidence file; its sha-256 is compared with the anchored hash')
121
169
  .description('Independently verify IPFS audit document content hash & agent ed25519 signature')
122
170
  .action(async (cid, options) => {
123
- const result = await fetchAndVerifyCid(cid, options.gateway);
171
+ let expectedHash;
172
+ try {
173
+ if (options.hash && options.evidence) throw new Error('Use either --hash or --evidence, not both');
174
+ if (options.hash) expectedHash = normalizeHashInput(options.hash);
175
+ if (options.evidence) expectedHash = crypto.createHash('sha256').update(fs.readFileSync(options.evidence)).digest('hex');
176
+ } catch (err) {
177
+ console.error(`❌ ${err.message}`);
178
+ process.exit(1);
179
+ }
180
+ const result = await fetchAndVerifyCid(cid, options.gateway, globalThis.fetch, { expectedHash });
124
181
  if (options.json) {
125
182
  console.log(JSON.stringify(result, null, 2));
126
183
  } else {
@@ -134,7 +191,7 @@ program
134
191
  // --- COMMAND: doctor ---
135
192
  program
136
193
  .command('doctor')
137
- .description('CLI preflight diagnostics for x402/MPP misconfiguration, or a remote seller with --seller')
194
+ .description('CLI preflight diagnostics for x402 misconfiguration (the MPP check only validates config), or a remote seller with --seller')
138
195
  .option('-n, --network <network>', 'Stellar network: testnet or pubnet', 'testnet')
139
196
  .option('-c, --config <path>', 'Path to environment or config file')
140
197
  .option('--seller <url>', 'Validate a remote x402 seller at this URL without paying')
@@ -158,7 +215,7 @@ program
158
215
  .command('pay')
159
216
  .description('💳 Pay an x402-protected endpoint straight from the terminal with Stellar auth entry signing')
160
217
  .argument('<url>', 'URL of the x402-protected endpoint')
161
- .option('-a, --amount <amount>', 'Payment amount override')
218
+ .option('--max-amount <usd>', 'Refuse to pay more than this, e.g. 5 or $0.50 (default: no cap beyond the SDK default)')
162
219
  .option('-n, --network <network>', 'CAIP-2 network ID (stellar:testnet or stellar:pubnet)', 'stellar:testnet')
163
220
  .option('-c, --config <path>', 'Custom path to configuration file or .env')
164
221
  .option('--json', 'Output execution result as JSON')
@@ -392,6 +449,19 @@ function maskSecret(secret) {
392
449
  return `${secret.slice(0, 4)}...${secret.slice(-4)}`;
393
450
  }
394
451
 
452
+ // `--max-amount` is a USD figure ("5", "$5", "0.50"), not atomic units.
453
+ // Rejects 0, negative and non-numeric so a typo fails before any network
454
+ // call instead of silently capping at $0 or NaN (which compares false to
455
+ // everything and would let every payment through).
456
+ function parseMaxAmountUsd(raw) {
457
+ const stripped = raw.startsWith('$') ? raw.slice(1) : raw;
458
+ const usd = Number(stripped);
459
+ if (!Number.isFinite(usd) || usd <= 0) {
460
+ throw new Error(`Invalid --max-amount '${raw}': must be a positive USD amount, e.g. --max-amount 5 or --max-amount '$0.50'.`);
461
+ }
462
+ return usd;
463
+ }
464
+
395
465
  // A secret passed as a CLI argument sits in the shell history file and
396
466
  // in `ps`'s full command line for anyone else on the machine to read —
397
467
  // true for any process, not just this one. `pay` used to take `--secret`
@@ -545,6 +615,20 @@ async function executePayCommand(url, options) {
545
615
  const config = loadConfig(options.config);
546
616
  const network = options.network || process.env.NIRIUM_NETWORK || config.network || 'stellar:testnet';
547
617
 
618
+ let maxAmountUsd;
619
+ if (options.maxAmount !== undefined) {
620
+ try {
621
+ maxAmountUsd = parseMaxAmountUsd(options.maxAmount);
622
+ } catch (err) {
623
+ if (options.json) {
624
+ console.log(JSON.stringify({ status: 'error', error: err.message }));
625
+ process.exit(1);
626
+ }
627
+ console.error(`❌ Error: ${err.message}`);
628
+ process.exit(1);
629
+ }
630
+ }
631
+
548
632
  let secretKey = process.env.NIRIUM_SECRET_KEY || config.secretKey;
549
633
 
550
634
  // `pay` no longer takes the secret as a flag (see #104): a --secret
@@ -601,7 +685,31 @@ async function executePayCommand(url, options) {
601
685
 
602
686
  try {
603
687
  const agent = new NiriumAgent({ apiKey: 'nirium-cli-pay' });
604
- agent.initX402({ secretKey, network });
688
+ if (maxAmountUsd !== undefined) {
689
+ // `initX402({ maxAmountPerPayment })` does not exist in any published
690
+ // `nirium` version yet (it is unreleased SDK source as of this PR), so
691
+ // --max-amount is enforced with the pre-sign policy hook instead, which
692
+ // IS published (0.16.0+) and runs before anything is signed. Stellar
693
+ // amounts are always int64 scaled by 1e7 regardless of asset, so the
694
+ // USD figure maps directly to atomic units without an asset lookup.
695
+ const capAtomic = BigInt(Math.round(maxAmountUsd * 1e7));
696
+ agent.initX402({
697
+ secretKey, network,
698
+ policy: {
699
+ evaluate: async (ctx) => {
700
+ if (BigInt(ctx.authorization.amount) <= capAtomic) {
701
+ return { decision: 'ALLOW', contextHash: ctx.contextHash };
702
+ }
703
+ return {
704
+ decision: 'DENY',
705
+ reason: `payment of ${ctx.authorization.amount} atomic units exceeds --max-amount ($${maxAmountUsd})`,
706
+ };
707
+ },
708
+ },
709
+ });
710
+ } else {
711
+ agent.initX402({ secretKey, network });
712
+ }
605
713
 
606
714
  const startTime = Date.now();
607
715
  const response = await agent.x402Fetch(url, {
@@ -652,10 +760,15 @@ async function executePayCommand(url, options) {
652
760
  headers: responseHeaders,
653
761
  data: responseBody,
654
762
  }, null, 2));
763
+ if (!response.ok) process.exit(1);
655
764
  return;
656
765
  }
657
766
 
658
- console.log(`✅ Payment Negotiated & Request Completed (${response.status} ${response.statusText})`);
767
+ if (response.ok) {
768
+ console.log(`✅ Payment Negotiated & Request Completed (${response.status} ${response.statusText})`);
769
+ } else {
770
+ console.log(`❌ Request Failed After Payment (${response.status} ${response.statusText})`);
771
+ }
659
772
  console.log(` Response Time: ${durationMs}ms`);
660
773
  if (txHash) {
661
774
  console.log(` Tx Reference: ${txHash}`);
@@ -663,6 +776,7 @@ async function executePayCommand(url, options) {
663
776
  }
664
777
  console.log(`\n--- Response Payload ---`);
665
778
  console.log(typeof responseBody === 'object' ? JSON.stringify(responseBody, null, 2) : responseBody);
779
+ if (!response.ok) process.exit(1);
666
780
  } catch (err) {
667
781
  const errorDetail = err?.message || String(err);
668
782
  if (options.json) {
@@ -1372,7 +1486,7 @@ function formatDoctorOutput(report) {
1372
1486
  const lines = [];
1373
1487
  lines.push(report.seller
1374
1488
  ? `🩺 Nirium Doctor — remote x402 seller`
1375
- : `🩺 Nirium Doctor — x402/MPP Diagnostic Report`);
1489
+ : `🩺 Nirium Doctor — x402 Diagnostic Report`);
1376
1490
  if (report.seller) lines.push(`Seller: ${report.seller}`);
1377
1491
  lines.push(`Target Network: ${report.network || 'n/a'}`);
1378
1492
  lines.push(`Timestamp: ${report.timestamp}`);
@@ -1399,7 +1513,28 @@ function decodeStellarPublicKey(gAddress) {
1399
1513
  return Buffer.from(StrKey.decodeEd25519PublicKey(gAddress));
1400
1514
  }
1401
1515
 
1402
- function verifyEd25519Signature(pubKeyGAddress, statement, base64Signature) {
1516
+ const HEX64 = /^[0-9a-f]{64}$/;
1517
+ const SEP53_PREFIX = 'Stellar Signed Message:\n';
1518
+
1519
+ // Accepts `<hex>` or `sha-256:<hex>`, any case. Returns lowercase hex or throws.
1520
+ function normalizeHashInput(value) {
1521
+ const hex = String(value).trim().replace(/^sha-?256:/i, '').toLowerCase();
1522
+ if (!HEX64.test(hex)) throw new Error(`Invalid sha-256 hash: ${value}`);
1523
+ return hex;
1524
+ }
1525
+
1526
+ // The node accepts the signature as hex or base64. Returns a 64-byte buffer or null.
1527
+ function decodeSignature(signature) {
1528
+ if (typeof signature !== 'string') return null;
1529
+ const s = signature.trim();
1530
+ const buf = /^[0-9a-fA-F]{128}$/.test(s) ? Buffer.from(s, 'hex') : Buffer.from(s, 'base64');
1531
+ return buf.length === 64 ? buf : null;
1532
+ }
1533
+
1534
+ // Mirrors the node: raw ed25519 over the utf8 statement first, then SEP-53
1535
+ // (Freighter signMessage): ed25519 over sha256("Stellar Signed Message:\n" + statement).
1536
+ // Returns 'ed25519', 'sep53' or null.
1537
+ function verifyEd25519Signature(pubKeyGAddress, statement, signature) {
1403
1538
  try {
1404
1539
  const rawPubKey = decodeStellarPublicKey(pubKeyGAddress);
1405
1540
  const spkiHeader = Buffer.from('302a300506032b6570032100', 'hex');
@@ -1408,52 +1543,75 @@ function verifyEd25519Signature(pubKeyGAddress, statement, base64Signature) {
1408
1543
  format: 'der',
1409
1544
  type: 'spki',
1410
1545
  });
1411
- const signatureBuf = Buffer.from(base64Signature, 'base64');
1412
- return crypto.verify(null, Buffer.from(statement), keyObject, signatureBuf);
1546
+ const signatureBuf = decodeSignature(signature);
1547
+ if (!signatureBuf) return null;
1548
+ if (crypto.verify(null, Buffer.from(statement, 'utf8'), keyObject, signatureBuf)) return 'ed25519';
1549
+ const sep53Digest = crypto.createHash('sha256').update(Buffer.from(SEP53_PREFIX + statement, 'utf8')).digest();
1550
+ if (crypto.verify(null, sep53Digest, keyObject, signatureBuf)) return 'sep53';
1551
+ return null;
1413
1552
  } catch {
1414
- return false;
1553
+ return null;
1415
1554
  }
1416
1555
  }
1417
1556
 
1418
- function verifyAuditDocument(doc, cid) {
1419
- if (!doc || typeof doc !== 'object') {
1420
- return { ok: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: 'Invalid audit document format' };
1557
+ function verifyAuditDocument(doc, cid, { expectedHash } = {}) {
1558
+ const fail = (error) => ({ ok: false, verified: false, cid, hashMatch: false, hashStatus: 'mismatch', expectedHash: '', computedHash: '', signatureStatus: 'absent', error });
1559
+ if (!doc || typeof doc !== 'object') return fail('Invalid audit document format');
1560
+ const anchoredHash = typeof doc.content_sha256 === 'string' ? doc.content_sha256.toLowerCase() : '';
1561
+ if (!HEX64.test(anchoredHash)) return fail('Audit document has no valid content_sha256');
1562
+
1563
+ // record mode: recompute from the embedded record (unchanged behavior).
1564
+ // hash-only mode: the node stores the submitted hash as content_sha256 and
1565
+ // has nothing to recompute it from, so compare against --hash/--evidence
1566
+ // when given, otherwise report the hash as unchecked (not as a mismatch).
1567
+ const mode = doc.record ? 'record' : 'hash-only';
1568
+ let computedHash = '';
1569
+ let hashStatus;
1570
+ if (mode === 'record') {
1571
+ computedHash = crypto.createHash('sha256').update(JSON.stringify(doc.record)).digest('hex');
1572
+ hashStatus = computedHash === anchoredHash ? 'match' : 'mismatch';
1573
+ if (hashStatus === 'match' && expectedHash && expectedHash !== anchoredHash) hashStatus = 'mismatch';
1574
+ } else if (expectedHash) {
1575
+ computedHash = expectedHash;
1576
+ hashStatus = expectedHash === anchoredHash ? 'match' : 'mismatch';
1577
+ } else {
1578
+ hashStatus = 'unchecked';
1421
1579
  }
1422
- const expectedHash = doc.content_sha256 || '';
1423
- const recordStr = doc.record ? JSON.stringify(doc.record) : '';
1424
- const computedHash = crypto.createHash('sha256').update(recordStr).digest('hex');
1425
- const hashMatch = expectedHash.length > 0 && expectedHash === computedHash;
1426
1580
 
1427
1581
  let signatureStatus = 'absent';
1428
- let signerKey, statement, declaredStatement, agentId;
1582
+ let signatureScheme, signerKey, statement, declaredStatement, agentId;
1429
1583
  if (doc.agent && doc.agent.key && doc.agent.signature) {
1430
1584
  signerKey = doc.agent.key;
1431
1585
  agentId = doc.agent.id;
1432
- // Always recompute — never trust the document's own statement field.
1433
- // The protocol signs `nirium-audit-v1:<content_sha256>`, derived
1434
- // exclusively from the record hash. Trusting doc.agent.statement
1435
- // would let an attacker reuse a valid signature after swapping the
1436
- // record content.
1437
- statement = `nirium-audit-v1:${computedHash}`;
1586
+ // Never trust the document's own statement field. In record mode the
1587
+ // statement is built from the recomputed record hash; in hash-only mode
1588
+ // from content_sha256 (a swapped content_sha256 breaks the signature).
1589
+ statement = `nirium-audit-v1:${mode === 'record' ? computedHash : anchoredHash}`;
1438
1590
  declaredStatement = doc.agent.statement;
1439
- signatureStatus = verifyEd25519Signature(signerKey, statement, doc.agent.signature) ? 'valid' : 'invalid';
1591
+ signatureScheme = verifyEd25519Signature(signerKey, statement, doc.agent.signature) || undefined;
1592
+ signatureStatus = signatureScheme ? 'valid' : 'invalid';
1440
1593
  }
1441
1594
 
1442
- const ok = hashMatch && signatureStatus !== 'invalid';
1443
- return { ok, cid, hashMatch, expectedHash, computedHash, signatureStatus, signerKey, statement, declaredStatement, agentId };
1595
+ // A pass requires at least one check to have actually run and succeeded.
1596
+ // "No check failed" alone is true when both were skipped (hash unchecked,
1597
+ // signature absent), which is not the same as the evidence being verified.
1598
+ const anyFailed = hashStatus === 'mismatch' || signatureStatus === 'invalid';
1599
+ const anyPassed = hashStatus === 'match' || signatureStatus === 'valid';
1600
+ const ok = !anyFailed && anyPassed;
1601
+ return { ok, verified: ok, cid, mode, hashMatch: hashStatus === 'match', hashStatus, expectedHash: anchoredHash, computedHash, signatureStatus, signatureScheme, signerKey, statement, declaredStatement, agentId };
1444
1602
  }
1445
1603
 
1446
- async function fetchAndVerifyCid(cid, gatewayUrl = 'https://gateway.pinata.cloud', fetchFn = globalThis.fetch) {
1604
+ async function fetchAndVerifyCid(cid, gatewayUrl = 'https://gateway.pinata.cloud', fetchFn = globalThis.fetch, opts = {}) {
1447
1605
  const url = `${gatewayUrl.replace(/\/$/, '')}/ipfs/${cid}`;
1448
1606
  try {
1449
1607
  const res = await fetchFn(url);
1450
1608
  if (!res.ok) {
1451
- return { ok: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: `IPFS gateway returned HTTP ${res.status}` };
1609
+ return { ok: false, verified: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: `IPFS gateway returned HTTP ${res.status}` };
1452
1610
  }
1453
1611
  const doc = await res.json();
1454
- return verifyAuditDocument(doc, cid);
1612
+ return verifyAuditDocument(doc, cid, opts);
1455
1613
  } catch (err) {
1456
- return { ok: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: `Failed to fetch CID from gateway: ${err?.message || String(err)}` };
1614
+ return { ok: false, verified: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: `Failed to fetch CID from gateway: ${err?.message || String(err)}` };
1457
1615
  }
1458
1616
  }
1459
1617
 
@@ -1462,11 +1620,16 @@ function formatVerifyOutput(result) {
1462
1620
  lines.push(`🔍 Nirium Audit Verifier`);
1463
1621
  if (result.cid) lines.push(`CID: ${result.cid}`);
1464
1622
  lines.push(`--------------------------------------------------`);
1465
- lines.push(result.hashMatch
1466
- ? `✔ HASH: MATCH (${result.computedHash.slice(0, 16)}...)`
1467
- : `❌ HASH: MISMATCH (Expected: ${result.expectedHash}, Computed: ${result.computedHash})`);
1623
+ if (result.hashStatus === 'unchecked') {
1624
+ lines.push(`ℹ HASH: NOT CHECKED (hash-only anchor: ${result.expectedHash.slice(0, 16)}...)`);
1625
+ lines.push(` Pass --hash <hex> or --evidence <file> to compare it with your original evidence.`);
1626
+ } else if (result.hashMatch) {
1627
+ lines.push(`✔ HASH: MATCH (${result.expectedHash.slice(0, 16)}...)${result.mode === 'hash-only' ? ' [hash-only]' : ''}`);
1628
+ } else {
1629
+ lines.push(`❌ HASH: MISMATCH (Anchored: ${result.expectedHash}, Computed: ${result.computedHash})`);
1630
+ }
1468
1631
  if (result.signatureStatus === 'valid') {
1469
- lines.push(`✔ SIGNATURE: VALID (Signed by ${result.signerKey})`);
1632
+ lines.push(`✔ SIGNATURE: VALID${result.signatureScheme === 'sep53' ? ' (SEP-53)' : ''} (Signed by ${result.signerKey})`);
1470
1633
  if (result.statement) lines.push(` Statement: ${result.statement}`);
1471
1634
  if (result.agentId) lines.push(` Agent ID: ${result.agentId}`);
1472
1635
  } else if (result.signatureStatus === 'invalid') {
@@ -1477,8 +1640,12 @@ function formatVerifyOutput(result) {
1477
1640
  lines.push(`--------------------------------------------------`);
1478
1641
  if (result.error) {
1479
1642
  lines.push(`❌ ERROR: ${result.error}`);
1643
+ } else if (result.ok) {
1644
+ lines.push(`✅ VERIFICATION PASSED`);
1645
+ } else if (result.hashStatus === 'unchecked' && result.signatureStatus === 'absent') {
1646
+ lines.push(`❌ NOTHING VERIFIED (pass --hash, --evidence, or anchor with an agent signature)`);
1480
1647
  } else {
1481
- lines.push(result.ok ? `✅ VERIFICATION PASSED` : `❌ VERIFICATION FAILED`);
1648
+ lines.push(`❌ VERIFICATION FAILED`);
1482
1649
  }
1483
1650
  return lines.join('\n');
1484
1651
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nirium-cli",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "Nirium CLI — scaffold Stellar agent projects and check agent status",
5
5
  "main": "bin/nirium.js",
6
6
  "type": "module",
@@ -8,7 +8,8 @@
8
8
  "nirium": "bin/nirium.js"
9
9
  },
10
10
  "scripts": {
11
- "test": "node --test test/doctor-seller.test.js test/config-secret.test.js test/serve-api-key.test.js"
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
13
  },
13
14
  "keywords": [
14
15
  "stellar",
@@ -21,11 +22,30 @@
21
22
  "author": "Nirium Team",
22
23
  "license": "Apache-2.0",
23
24
  "dependencies": {
24
- "axios": "^1.13.6",
25
+ "axios": "^1.20.0",
25
26
  "commander": "^11.0.0",
26
- "nirium": "^0.16.0",
27
+ "nirium": "^0.16.1",
27
28
  "express": "^5.1.0",
28
- "@stellar/stellar-sdk": "^14.5.0"
29
+ "@stellar/stellar-sdk": "^16.3.0",
30
+ "@x402/express": "^2.28.0"
31
+ },
32
+ "overrides": {
33
+ "@stellar/stellar-sdk": {
34
+ "axios": ">=1.20.0"
35
+ },
36
+ "follow-redirects": ">=1.16.1",
37
+ "proxy-addr": ">=2.0.8",
38
+ "toml": ">=5.0.1",
39
+ "qs": ">=6.16.0",
40
+ "mppx": {
41
+ "zod": "^4.6.6"
42
+ },
43
+ "@stellar/mpp": {
44
+ "zod": "^4.6.6"
45
+ },
46
+ "viem": {
47
+ "zod": "^4.6.6"
48
+ }
29
49
  },
30
50
  "devDependencies": {
31
51
  "@types/node": "^20.19.30",
@@ -41,6 +61,6 @@
41
61
  },
42
62
  "homepage": "https://nirium.xyz",
43
63
  "engines": {
44
- "node": ">=18"
64
+ "node": ">=22.12.0"
45
65
  }
46
66
  }