nirium-cli 1.1.4 → 2.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 +44 -7
  2. package/bin/nirium.js +592 -22
  3. package/package.json +3 -3
package/README.md CHANGED
@@ -60,7 +60,7 @@ signals, which the autonomous loop produces on testnet. Defaults to `https://nir
60
60
  ## Pay an x402 endpoint from the terminal
61
61
 
62
62
  ```bash
63
- nirium pay https://your-api.example.com/premium/signals --secret S...
63
+ NIRIUM_SECRET_KEY=S... nirium pay https://your-api.example.com/premium/signals
64
64
  ```
65
65
 
66
66
  Signs and settles a real x402 payment against any endpoint that returns a
@@ -68,9 +68,14 @@ Signs and settles a real x402 payment against any endpoint that returns a
68
68
  server directly, useful for testing a `nirium serve` instance or someone
69
69
  else's paid API without writing a client.
70
70
 
71
+ There is no `--secret` flag: a key passed as a command-line argument sits
72
+ 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.
76
+
71
77
  | Option | Purpose |
72
78
  |---|---|
73
- | `-s, --secret <secret>` | Stellar secret key (`S...`) that pays. Also read from `NIRIUM_SECRET_KEY` or `nirium config set secretKey S...`, in that order. |
74
79
  | `-n, --network <network>` | `stellar:testnet` (default) or `stellar:pubnet` |
75
80
  | `-a, --amount <amount>` | Override the price the server advertises |
76
81
  | `--json` | Machine-readable result: status, duration, payer, tx hash, response body |
@@ -83,7 +88,8 @@ network call happens.
83
88
  ## Spin up a local x402 test server
84
89
 
85
90
  ```bash
86
- nirium serve --pay-to G... --api-key <facilitator-key>
91
+ FACILITATOR_API_KEY=<facilitator-key> nirium serve --pay-to G...
92
+ # or just `nirium serve --pay-to G...` in a terminal: it asks for the key with a hidden prompt
87
93
  ```
88
94
 
89
95
  A one-command x402 server for testing `nirium pay` (or any x402 client)
@@ -94,14 +100,16 @@ as `create x402`: get a free key at
94
100
  | Option | Values | Default |
95
101
  |---|---|---|
96
102
  | `-P, --pay-to <address>` | Stellar `G...` address that receives payments | required |
97
- | `-k, --api-key <key>` | facilitator API key | required |
98
103
  | `-p, --price <price>` | e.g. `$0.02` | `$0.02` |
99
104
  | `-port, --port <port>` | | `3000` |
100
105
  | `-r, --route <route>` | path to protect | `/api/v1/data` |
101
106
  | `-n, --network <network>` | `stellar:testnet` or `stellar:pubnet` | `stellar:testnet` |
102
107
 
103
- `--pay-to` and `--api-key` can also come from `nirium config set` instead
104
- of being passed every time.
108
+ There is no `--api-key` flag: a key passed as a command-line argument sits in
109
+ your shell history and in `ps`. The facilitator key comes from
110
+ `FACILITATOR_API_KEY`, from `nirium config set facilitatorApiKey` (hidden
111
+ prompt), or from a hidden prompt when `serve` runs in a terminal. `--pay-to`
112
+ can also come from `nirium config set payTo`.
105
113
 
106
114
  ## Check an agent
107
115
 
@@ -127,11 +135,39 @@ consistent. Reads from `.env` in the current directory by default.
127
135
  |---|---|
128
136
  | `-n, --network <network>` | `testnet` (default) or `pubnet` |
129
137
  | `-c, --config <path>` | custom `.env`/config path |
138
+ | `--seller <url>` | validate a remote x402 seller without paying |
130
139
  | `--json` | machine-readable report for CI |
131
140
 
132
141
  Exits non-zero if any check fails, so it's usable as a CI gate ahead of a
133
142
  deploy.
134
143
 
144
+ ### Check a remote seller
145
+
146
+ ```bash
147
+ nirium doctor --seller https://your-api.example.com/premium/signals
148
+ nirium doctor --seller https://your-api.example.com/premium/signals --json
149
+ ```
150
+
151
+ `--seller` does not read `.env` and does not run the local checks above. It
152
+ also does not pay: the probe is a `GET` plus an `OPTIONS` preflight, and it
153
+ never sends `PAYMENT-SIGNATURE`.
154
+
155
+ Each line is pass or fail:
156
+
157
+ | Check | Pass means |
158
+ |---|---|
159
+ | `challenge` | HTTP 402 with a decodable `PAYMENT-REQUIRED` header (base64 JSON, or raw JSON) |
160
+ | `network` | every `accepts[]` entry has a well-formed network (`stellar:testnet`, `stellar:pubnet`, or another CAIP-2 id) |
161
+ | `asset` | present; on Stellar, the SAC contract id (`C...`), not a symbol like `USDC` |
162
+ | `amount` | a positive integer string in atomic units (`"1000000"`, not `"$0.02"`) |
163
+ | `payTo` | present; on Stellar, a valid `G...` public key. A secret (`S...`) fails |
164
+ | `resource-url` | `resource.url` is `https://`. `http://` fails even if you probed `http://127.0.0.1` |
165
+ | `cors-preflight` | `OPTIONS` from a random `*.invalid` origin returns 2xx and allows that origin |
166
+ | `cors-expose` | the 402 response exposes `PAYMENT-REQUIRED` and `PAYMENT-RESPONSE`. Headers listed only on the preflight do not count |
167
+ | `cors-allow` | `PAYMENT-SIGNATURE` is listed in `Access-Control-Allow-Headers` |
168
+
169
+ `--json` prints the same report (`ok`, `seller`, `network`, `checks`) for CI.
170
+
135
171
  ## Verify an audit record
136
172
 
137
173
  ```bash
@@ -157,7 +193,8 @@ or the signature doesn't verify.
157
193
  ## Manage stored credentials
158
194
 
159
195
  ```bash
160
- nirium config set secretKey S...
196
+ nirium config set secretKey # hidden prompt; or pipe it: ... | nirium config set secretKey
197
+ nirium config set facilitatorApiKey # same: never as an argument
161
198
  nirium config list
162
199
  nirium config get payTo
163
200
  nirium config delete facilitatorApiKey
package/bin/nirium.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // ═══════════════════════════════════════════════════════════════
4
- // Nirium — Autonomous Agent CLI (v1.1.4)
4
+ // Nirium — Autonomous Agent CLI (v2.0.0)
5
5
  // ═══════════════════════════════════════════════════════════════
6
6
  //
7
7
  // Everything below is one flat file on purpose, not a build artifact:
@@ -10,22 +10,37 @@
10
10
  // dist/ is added to that list too. Inlining avoids depending on a build
11
11
  // step existing at publish time at all.
12
12
 
13
- import { Command } from 'commander';
13
+ import { Command, Option } from 'commander';
14
14
  import fs from 'fs';
15
15
  import path from 'path';
16
16
  import os from 'os';
17
17
  import crypto from 'crypto';
18
+ import readline from 'readline';
18
19
  import { execSync } from 'child_process';
20
+ import { fileURLToPath } from 'url';
19
21
  import express from 'express';
20
22
  import NiriumAgent, { x402Serve } from 'nirium';
21
23
  import { Keypair, StrKey } from '@stellar/stellar-sdk';
22
24
 
25
+ function readCliVersion() {
26
+ try {
27
+ const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
28
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
29
+ if (typeof pkg.version === 'string' && pkg.version.length > 0) return pkg.version;
30
+ } catch {
31
+ // bin/nirium.js ships next to package.json. A missing file must not crash doctor.
32
+ }
33
+ return '0.0.0';
34
+ }
35
+
36
+ const doctorUserAgent = `nirium-doctor/${readCliVersion()}`;
37
+
23
38
  const program = new Command();
24
39
 
25
40
  program
26
41
  .name('nirium')
27
42
  .description('Nirium protocol development tool')
28
- .version('1.1.4');
43
+ .version('2.0.0');
29
44
 
30
45
  // --- COMMAND: create bot ---
31
46
  program
@@ -119,12 +134,15 @@ program
119
134
  // --- COMMAND: doctor ---
120
135
  program
121
136
  .command('doctor')
122
- .description('CLI preflight diagnostics for x402/MPP misconfiguration')
137
+ .description('CLI preflight diagnostics for x402/MPP misconfiguration, or a remote seller with --seller')
123
138
  .option('-n, --network <network>', 'Stellar network: testnet or pubnet', 'testnet')
124
139
  .option('-c, --config <path>', 'Path to environment or config file')
140
+ .option('--seller <url>', 'Validate a remote x402 seller at this URL without paying')
125
141
  .option('--json', 'Output results as JSON for CI integration')
126
142
  .action(async (options) => {
127
- const report = await runDoctorDiagnostics(options);
143
+ const report = options.seller
144
+ ? await runDoctorSeller(options.seller)
145
+ : await runDoctorDiagnostics(options);
128
146
  if (options.json) {
129
147
  console.log(JSON.stringify(report, null, 2));
130
148
  } else {
@@ -142,7 +160,6 @@ program
142
160
  .argument('<url>', 'URL of the x402-protected endpoint')
143
161
  .option('-a, --amount <amount>', 'Payment amount override')
144
162
  .option('-n, --network <network>', 'CAIP-2 network ID (stellar:testnet or stellar:pubnet)', 'stellar:testnet')
145
- .option('-s, --secret <secret>', 'Stellar secret key (S...) for signing')
146
163
  .option('-c, --config <path>', 'Custom path to configuration file or .env')
147
164
  .option('--json', 'Output execution result as JSON')
148
165
  .action(async (url, options) => {
@@ -158,7 +175,9 @@ program
158
175
  .option('-port, --port <port>', 'Port number to listen on', '3000')
159
176
  .option('-n, --network <network>', 'CAIP-2 network ID (stellar:testnet or stellar:pubnet)', 'stellar:testnet')
160
177
  .option('-r, --route <route>', 'Route path to protect', '/api/v1/data')
161
- .option('-k, --api-key <key>', 'Facilitator API key')
178
+ // Kept only to refuse it with a clear message: commander's own
179
+ // "unknown option" would not tell the user the key is now exposed.
180
+ .addOption(new Option('-k, --api-key <key>').hideHelp())
162
181
  .option('-c, --config <path>', 'Custom path to config file')
163
182
  .action(async (options) => {
164
183
  await executeServeCommand(options);
@@ -172,7 +191,7 @@ program
172
191
  .argument('[key]', 'Configuration key name')
173
192
  .argument('[value]', 'Value to set for the configuration key')
174
193
  .action(async (action, key, value) => {
175
- executeConfigCommand(action, key, value);
194
+ await executeConfigCommand(action, key, value);
176
195
  });
177
196
 
178
197
  // Un servidor que COBRA, no uno que escucha. Es el camino corto de
@@ -186,7 +205,7 @@ function scaffoldX402(dir, name) {
186
205
  type: 'module',
187
206
  scripts: { dev: 'tsx watch src/server.ts', build: 'tsc' },
188
207
  dependencies: {
189
- nirium: '^0.14.0',
208
+ nirium: '^0.16.0',
190
209
  express: '^5.1.0',
191
210
  '@x402/express': '^2.17.0',
192
211
  '@x402/core': '^2.17.0',
@@ -252,7 +271,7 @@ function scaffoldTS(dir, name) {
252
271
  "build": "tsc"
253
272
  },
254
273
  dependencies: {
255
- "nirium": "^0.14.0",
274
+ "nirium": "^0.16.0",
256
275
  "tsx": "^4.19.0",
257
276
  "typescript": "^5.7.0",
258
277
  "dotenv": "^16.4.5"
@@ -373,7 +392,77 @@ function maskSecret(secret) {
373
392
  return `${secret.slice(0, 4)}...${secret.slice(-4)}`;
374
393
  }
375
394
 
376
- function executeConfigCommand(action, key, value) {
395
+ // A secret passed as a CLI argument sits in the shell history file and
396
+ // in `ps`'s full command line for anyone else on the machine to read —
397
+ // true for any process, not just this one. `pay` used to take `--secret`
398
+ // for exactly that reason, so this prompt is the replacement: it reads
399
+ // from the terminal without echoing the input and without it ever
400
+ // becoming a process argument. Only used when neither NIRIUM_SECRET_KEY
401
+ // nor the config store already has a key.
402
+ function promptHiddenSecret(question) {
403
+ return new Promise((resolve, reject) => {
404
+ if (!process.stdin.isTTY) {
405
+ reject(new Error('no interactive terminal to prompt on'));
406
+ return;
407
+ }
408
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
409
+ // readline always echoes keystrokes to `output`; the only hook it
410
+ // gives you to stop that is overriding the writer it calls internally.
411
+ const realWrite = rl._writeToOutput;
412
+ rl._writeToOutput = function (str) {
413
+ // Pass the prompt text itself through once, then swallow every
414
+ // character typed after it — nothing from the secret reaches
415
+ // the terminal, not even asterisks that could leak its length.
416
+ if (str === question) realWrite.call(rl, str);
417
+ };
418
+ rl.question(question, (answer) => {
419
+ rl.history = rl.history.slice(1); // readline records the answer in its own history buffer
420
+ rl._writeToOutput = realWrite;
421
+ rl.close();
422
+ process.stdout.write('\n');
423
+ resolve(answer.trim());
424
+ });
425
+ });
426
+ }
427
+
428
+ // Credentials that `config set` never takes as an argument.
429
+ const SECRET_CONFIG_KEYS = {
430
+ secretKey: {
431
+ prompt: 'Stellar secret key (S...): ',
432
+ valid: (v) => StrKey.isValidEd25519SecretSeed(v),
433
+ invalid: 'not a valid Stellar secret key (expected S...).',
434
+ },
435
+ facilitatorApiKey: {
436
+ prompt: 'Facilitator API key: ',
437
+ valid: (v) => typeof v === 'string' && v.length > 0,
438
+ invalid: 'the facilitator API key is empty.',
439
+ },
440
+ };
441
+
442
+ // Hidden prompt on a terminal, stdin otherwise. Never a process argument.
443
+ // `timeoutMs` (stdin only) resolves to '' when nothing finishes arriving in
444
+ // time, so a caller that has no other source for the value can fail with its
445
+ // own "missing key" error instead of waiting on a pipe that never closes.
446
+ async function readSecretInput(question, { timeoutMs } = {}) {
447
+ if (process.stdin.isTTY) return promptHiddenSecret(question);
448
+ const read = (async () => {
449
+ const chunks = [];
450
+ for await (const chunk of process.stdin) chunks.push(chunk);
451
+ return Buffer.concat(chunks).toString('utf8').trim();
452
+ })();
453
+ if (!timeoutMs) return read;
454
+ let timer;
455
+ const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(''), timeoutMs); });
456
+ try {
457
+ return await Promise.race([read, timeout]);
458
+ } finally {
459
+ clearTimeout(timer);
460
+ }
461
+ }
462
+
463
+ const SERVE_STDIN_TIMEOUT_MS = Number(process.env.NIRIUM_STDIN_TIMEOUT_MS) || 10_000;
464
+
465
+ async function executeConfigCommand(action, key, value) {
377
466
  const currentConfig = loadConfig();
378
467
 
379
468
  if (!action || action === 'list') {
@@ -399,9 +488,32 @@ function executeConfigCommand(action, key, value) {
399
488
  return;
400
489
  }
401
490
 
491
+ const secretSpec = action === 'set' ? SECRET_CONFIG_KEYS[key] : undefined;
492
+ if (secretSpec) {
493
+ // Same reason `pay` has no --secret: an argument ends up in the shell
494
+ // history file and in `ps` output. Refuse it instead of storing it.
495
+ if (value !== undefined) {
496
+ console.error(`❌ Error: \`nirium config set ${key}\` does not take the value as an argument.\n`
497
+ + 'A credential typed on the command line stays in your shell history and is visible in `ps` '
498
+ + 'to other users on this machine, so it was NOT saved. Treat the value you typed as exposed.\n'
499
+ + `Run \`nirium config set ${key}\` with no value to get a hidden prompt, `
500
+ + 'or pipe it on stdin from a file or secret manager.');
501
+ process.exit(1);
502
+ }
503
+ const secret = await readSecretInput(secretSpec.prompt);
504
+ if (!secretSpec.valid(secret)) {
505
+ console.error(`❌ Error: ${secretSpec.invalid} Nothing was saved.`);
506
+ process.exit(1);
507
+ }
508
+ saveConfig({ ...currentConfig, [key]: secret });
509
+ console.log(`✅ Configuration updated: ${key} set successfully.`);
510
+ return;
511
+ }
512
+
402
513
  if (action === 'set') {
403
514
  if (!key || value === undefined) {
404
- console.error('❌ Error: Usage: `nirium config set <key> <value>` (e.g., `nirium config set secretKey S...`)');
515
+ console.error('❌ Error: Usage: `nirium config set <key> <value>` (e.g., `nirium config set payTo G...`). '
516
+ + 'For secretKey or facilitatorApiKey, run `nirium config set <key>` with no value.');
405
517
  process.exit(1);
406
518
  }
407
519
  const updatedConfig = { ...currentConfig, [key]: value };
@@ -431,15 +543,32 @@ function executeConfigCommand(action, key, value) {
431
543
 
432
544
  async function executePayCommand(url, options) {
433
545
  const config = loadConfig(options.config);
434
- const secretKey = options.secret || process.env.NIRIUM_SECRET_KEY || config.secretKey;
435
546
  const network = options.network || process.env.NIRIUM_NETWORK || config.network || 'stellar:testnet';
436
547
 
548
+ let secretKey = process.env.NIRIUM_SECRET_KEY || config.secretKey;
549
+
550
+ // `pay` no longer takes the secret as a flag (see #104): a --secret
551
+ // argument sits in the shell history and in `ps`'s full command line
552
+ // for anyone else on the box to read. Env var and config store are
553
+ // both still fine — neither is visible that way. The remaining gap is
554
+ // a one-off call with nothing configured yet, so prompt for it
555
+ // instead of failing outright, same as any CLI handling a real secret.
556
+ if (!secretKey && !options.json && process.stdin.isTTY) {
557
+ try {
558
+ secretKey = await promptHiddenSecret('Stellar secret key (S...): ');
559
+ } catch {
560
+ // falls through to the same missing-key error below
561
+ }
562
+ }
563
+
437
564
  if (!secretKey) {
438
565
  const errorMsg = 'Missing secret key for x402 payment authorization.\n'
439
- + 'Please provide a secret key using:\n'
440
- + ' - `--secret S...` option\n'
566
+ + 'Provide a secret key using:\n'
441
567
  + ' - `NIRIUM_SECRET_KEY` environment variable\n'
442
- + ' - `nirium config set secretKey S...`';
568
+ + ' - the interactive prompt (run without --json, in a real terminal)\n'
569
+ + 'There is no --secret flag: a key passed as a command-line argument '
570
+ + 'would sit in your shell history and in `ps` output for anyone else '
571
+ + 'on the machine to read.';
443
572
  if (options.json) {
444
573
  console.log(JSON.stringify({ status: 'error', error: errorMsg }));
445
574
  process.exit(1);
@@ -556,13 +685,21 @@ async function executeServeCommand(options) {
556
685
  const port = Number(options.port || process.env.PORT || 3000);
557
686
  const network = options.network || process.env.NIRIUM_NETWORK || config.network || 'stellar:testnet';
558
687
  const routePath = options.route || '/api/v1/data';
559
- const facilitatorApiKey = options.apiKey || process.env.FACILITATOR_API_KEY || config.facilitatorApiKey;
688
+ if (options.apiKey !== undefined) {
689
+ console.error('❌ Error: `nirium serve` no longer takes --api-key.\n'
690
+ + 'A key passed as a command-line argument stays in your shell history and is visible in `ps` '
691
+ + 'to other users on this machine, so it was NOT used. Treat the key you typed as exposed.\n'
692
+ + 'Set FACILITATOR_API_KEY, or run `nirium serve` in a terminal to get a hidden prompt.');
693
+ process.exit(1);
694
+ }
695
+ let facilitatorApiKey = process.env.FACILITATOR_API_KEY || config.facilitatorApiKey;
696
+ if (!facilitatorApiKey) facilitatorApiKey = await readSecretInput('Facilitator API key: ', { timeoutMs: SERVE_STDIN_TIMEOUT_MS });
560
697
 
561
698
  if (!facilitatorApiKey) {
562
699
  console.error('❌ Error: Missing facilitator API key.');
563
700
  console.error('Get a free key at https://channels.openzeppelin.com/testnet/gen (testnet)');
564
- console.error('or https://channels.openzeppelin.com/gen (mainnet), then pass it via');
565
- console.error('--api-key, FACILITATOR_API_KEY, or `nirium config set facilitatorApiKey ...`');
701
+ console.error('or https://channels.openzeppelin.com/gen (mainnet), then set FACILITATOR_API_KEY');
702
+ console.error('or run `nirium serve` in a terminal to get a hidden prompt.');
566
703
  process.exit(1);
567
704
  }
568
705
  if (!payTo) {
@@ -604,7 +741,7 @@ async function executeServeCommand(options) {
604
741
  console.log(` Pay To: ${payTo}`);
605
742
  console.log(` Network: ${network}\n`);
606
743
  console.log(`💡 Test this server using:`);
607
- console.log(` nirium pay http://localhost:${port}${routePath} --secret S...\n`);
744
+ console.log(` NIRIUM_SECRET_KEY=S... nirium pay http://localhost:${port}${routePath}\n`);
608
745
  resolve({ app, server });
609
746
  });
610
747
  server.on('error', (err) => {
@@ -801,10 +938,443 @@ async function runDoctorDiagnostics(options) {
801
938
  return { ok, network: canonicalNetwork, checks, timestamp: new Date().toISOString() };
802
939
  }
803
940
 
941
+ // ═══════════════════════════════════════════════════════════════
942
+ // doctor --seller — probe a remote x402 seller without paying
943
+ // ═══════════════════════════════════════════════════════════════
944
+ //
945
+ // The probe URL may be plain http (a local fixture). resource.url inside
946
+ // PAYMENT-REQUIRED may not: browsers and x402 clients follow that URL, and
947
+ // an http:// resource is a real production failure. Nothing here sends
948
+ // PAYMENT-SIGNATURE or X-PAYMENT.
949
+
950
+ const STELLAR_SELLER_NETWORKS = new Set(['stellar:testnet', 'stellar:pubnet']);
951
+
952
+ function headerTokens(value) {
953
+ if (!value || typeof value !== 'string') return [];
954
+ return value.split(',').map((part) => part.trim()).filter(Boolean);
955
+ }
956
+
957
+ function tokenListIncludes(value, expected) {
958
+ const tokens = headerTokens(value).map((token) => token.toLowerCase());
959
+ return tokens.includes('*') || tokens.includes(expected.toLowerCase());
960
+ }
961
+
962
+ function missingExposedHeaders(value) {
963
+ const tokens = headerTokens(value).map((token) => token.toLowerCase());
964
+ if (tokens.includes('*')) return [];
965
+ const missing = [];
966
+ if (!tokens.includes('payment-required')) missing.push('PAYMENT-REQUIRED');
967
+ if (!tokens.includes('payment-response')) missing.push('PAYMENT-RESPONSE');
968
+ return missing;
969
+ }
970
+
971
+ function isPaymentRequiredPayload(value) {
972
+ return Boolean(value)
973
+ && typeof value === 'object'
974
+ && !Array.isArray(value)
975
+ && (Array.isArray(value.accepts) || (value.resource && typeof value.resource === 'object'));
976
+ }
977
+
978
+ function decodePaymentRequiredHeader(headerValue) {
979
+ if (typeof headerValue !== 'string') return null;
980
+ const trimmed = headerValue.trim();
981
+ if (!trimmed) return null;
982
+ const candidates = [];
983
+ if (trimmed.startsWith('{')) candidates.push(trimmed);
984
+ candidates.push(Buffer.from(trimmed.replace(/\s+/g, ''), 'base64').toString('utf8'));
985
+ for (const candidate of candidates) {
986
+ try {
987
+ const parsed = JSON.parse(candidate);
988
+ if (isPaymentRequiredPayload(parsed)) return parsed;
989
+ } catch {
990
+ // try the next encoding
991
+ }
992
+ }
993
+ return null;
994
+ }
995
+
996
+ function isPositiveAtomicAmount(amount) {
997
+ return typeof amount === 'string' && /^[1-9]\d*$/.test(amount);
998
+ }
999
+
1000
+ function isWellFormedSellerNetwork(network) {
1001
+ if (typeof network !== 'string') return false;
1002
+ if (network.startsWith('stellar:')) return STELLAR_SELLER_NETWORKS.has(network);
1003
+ return /^[a-z0-9]{3,32}:[A-Za-z0-9._-]{1,64}$/.test(network);
1004
+ }
1005
+
1006
+ function isWellFormedSellerAsset(asset, network) {
1007
+ if (typeof asset !== 'string' || asset.length === 0 || asset.length > 200 || /\s/.test(asset)) return false;
1008
+ if (typeof network === 'string' && network.startsWith('stellar:')) return StrKey.isValidContract(asset);
1009
+ return true;
1010
+ }
1011
+
1012
+ function payToProblem(payTo, network) {
1013
+ if (typeof payTo !== 'string' || payTo.length === 0) return 'missing';
1014
+ if (payTo.startsWith('S')) return 'secret';
1015
+ const stellar = typeof network === 'string' && network.startsWith('stellar:');
1016
+ if (stellar || payTo.startsWith('G')) {
1017
+ return StrKey.isValidEd25519PublicKey(payTo) ? null : 'invalid';
1018
+ }
1019
+ if (/\s/.test(payTo) || payTo.length < 8 || payTo.length > 200) return 'invalid';
1020
+ return null;
1021
+ }
1022
+
1023
+ function resourceUrlProblem(resourceUrl) {
1024
+ if (typeof resourceUrl !== 'string' || resourceUrl.length === 0) return 'missing';
1025
+ if (/^http:\/\//i.test(resourceUrl)) return 'http';
1026
+ try {
1027
+ const parsed = new URL(resourceUrl);
1028
+ if (parsed.protocol !== 'https:') return 'not-https';
1029
+ } catch {
1030
+ return 'invalid';
1031
+ }
1032
+ return null;
1033
+ }
1034
+
1035
+ function sellerCheck(name, status, message, fix, detail) {
1036
+ const check = { name, status, message };
1037
+ if (fix) check.fix = fix;
1038
+ if (detail) check.detail = detail;
1039
+ return check;
1040
+ }
1041
+
1042
+ function sellerReport(seller, checks, network) {
1043
+ return {
1044
+ ok: checks.every((check) => check.status === 'pass'),
1045
+ seller,
1046
+ network: network || null,
1047
+ checks,
1048
+ timestamp: new Date().toISOString(),
1049
+ };
1050
+ }
1051
+
1052
+ function unreachableSellerReport(seller, message) {
1053
+ const names = ['challenge', 'network', 'asset', 'amount', 'payTo', 'resource-url', 'cors-preflight', 'cors-expose', 'cors-allow'];
1054
+ return sellerReport(seller, names.map((name) => sellerCheck(
1055
+ name,
1056
+ 'fail',
1057
+ message,
1058
+ name === 'challenge' ? 'Pass an absolute http(s) URL, for example https://example.com/premium' : undefined,
1059
+ )), null);
1060
+ }
1061
+
1062
+ function probeErrorMessage(err) {
1063
+ if (!err) return 'unknown error';
1064
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') return 'request timed out after 10s';
1065
+ return err.message || String(err);
1066
+ }
1067
+
1068
+ async function probeSeller(url, init) {
1069
+ try {
1070
+ const response = await fetch(url, {
1071
+ ...init,
1072
+ redirect: 'manual',
1073
+ signal: AbortSignal.timeout(10000),
1074
+ });
1075
+ try {
1076
+ await response.body?.cancel();
1077
+ } catch {
1078
+ // headers are already available
1079
+ }
1080
+ return { response };
1081
+ } catch (err) {
1082
+ return { error: err };
1083
+ }
1084
+ }
1085
+
1086
+ function firstAdvertisedNetwork(payment) {
1087
+ const accepts = payment?.accepts;
1088
+ if (!Array.isArray(accepts)) return null;
1089
+ for (const entry of accepts) {
1090
+ if (entry && typeof entry.network === 'string' && entry.network) return entry.network;
1091
+ }
1092
+ return null;
1093
+ }
1094
+
1095
+ function fieldFailures(payment, readProblem) {
1096
+ const accepts = payment?.accepts;
1097
+ if (!Array.isArray(accepts) || accepts.length === 0) {
1098
+ return { ok: false, message: 'PAYMENT-REQUIRED accepts[] is missing or empty' };
1099
+ }
1100
+ for (let i = 0; i < accepts.length; i++) {
1101
+ const entry = accepts[i];
1102
+ const problem = readProblem(entry && typeof entry === 'object' ? entry : {});
1103
+ if (problem) return { ok: false, index: i, ...problem };
1104
+ }
1105
+ return { ok: true };
1106
+ }
1107
+
1108
+ async function runDoctorSeller(sellerUrl) {
1109
+ let parsed;
1110
+ try {
1111
+ parsed = new URL(sellerUrl);
1112
+ } catch {
1113
+ parsed = null;
1114
+ }
1115
+ if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {
1116
+ return unreachableSellerReport(sellerUrl, 'seller URL is not an absolute http(s) URL');
1117
+ }
1118
+
1119
+ // A reserved .invalid origin so the preflight cannot collide with a real
1120
+ // site, and so a seller that 500s on an unknown Origin fails closed.
1121
+ const origin = `https://nirium-doctor-${crypto.randomBytes(8).toString('hex')}.invalid`;
1122
+ const [challenge, preflight] = await Promise.all([
1123
+ probeSeller(sellerUrl, {
1124
+ method: 'GET',
1125
+ headers: {
1126
+ Accept: 'application/json',
1127
+ Origin: origin,
1128
+ 'User-Agent': doctorUserAgent,
1129
+ },
1130
+ }),
1131
+ probeSeller(sellerUrl, {
1132
+ method: 'OPTIONS',
1133
+ headers: {
1134
+ Origin: origin,
1135
+ 'Access-Control-Request-Method': 'GET',
1136
+ 'Access-Control-Request-Headers': 'PAYMENT-SIGNATURE',
1137
+ 'User-Agent': doctorUserAgent,
1138
+ },
1139
+ }),
1140
+ ]);
1141
+
1142
+ const checks = [];
1143
+ let payment = null;
1144
+ if (challenge.error || !challenge.response) {
1145
+ checks.push(sellerCheck(
1146
+ 'challenge',
1147
+ 'fail',
1148
+ `seller unreachable: ${probeErrorMessage(challenge.error)}`,
1149
+ 'Confirm the URL is reachable. doctor does not retry and does not pay.',
1150
+ ));
1151
+ } else if (challenge.response.status !== 402) {
1152
+ checks.push(sellerCheck(
1153
+ 'challenge',
1154
+ 'fail',
1155
+ `expected HTTP 402, got HTTP ${challenge.response.status}`,
1156
+ 'The seller must answer an unpaid request with 402 and a PAYMENT-REQUIRED header.',
1157
+ `status ${challenge.response.status}`,
1158
+ ));
1159
+ } else {
1160
+ payment = decodePaymentRequiredHeader(challenge.response.headers.get('payment-required'));
1161
+ if (!payment) {
1162
+ checks.push(sellerCheck(
1163
+ 'challenge',
1164
+ 'fail',
1165
+ 'HTTP 402 but PAYMENT-REQUIRED is missing or not decodable',
1166
+ 'Serve the x402 v2 challenge as base64 JSON in the PAYMENT-REQUIRED header.',
1167
+ ));
1168
+ } else {
1169
+ checks.push(sellerCheck(
1170
+ 'challenge',
1171
+ 'pass',
1172
+ 'HTTP 402 with a decodable PAYMENT-REQUIRED header',
1173
+ undefined,
1174
+ payment.x402Version != null ? `x402Version ${payment.x402Version}` : undefined,
1175
+ ));
1176
+ }
1177
+ }
1178
+
1179
+ const networkResult = fieldFailures(payment, (entry) => {
1180
+ if (entry.network == null || entry.network === '') {
1181
+ return { message: 'network is missing', fix: 'Set accepts[].network, for example stellar:pubnet or stellar:testnet.' };
1182
+ }
1183
+ if (!isWellFormedSellerNetwork(entry.network)) {
1184
+ const stellarTypo = typeof entry.network === 'string' && entry.network.startsWith('stellar:');
1185
+ return {
1186
+ message: `network "${entry.network}" is not well formed`,
1187
+ fix: stellarTypo
1188
+ ? 'Stellar sellers must advertise stellar:testnet or stellar:pubnet.'
1189
+ : 'network must be a CAIP-2 identifier such as stellar:pubnet.',
1190
+ detail: String(entry.network),
1191
+ };
1192
+ }
1193
+ return null;
1194
+ });
1195
+ checks.push(networkResult.ok
1196
+ ? sellerCheck('network', 'pass', 'network is present and well formed', undefined, firstAdvertisedNetwork(payment))
1197
+ : sellerCheck('network', 'fail', networkResult.index != null ? `accepts[${networkResult.index}].${networkResult.message}` : networkResult.message, networkResult.fix, networkResult.detail));
1198
+
1199
+ const assetResult = fieldFailures(payment, (entry) => {
1200
+ if (!isWellFormedSellerAsset(entry.asset, entry.network)) {
1201
+ const stellar = typeof entry.network === 'string' && entry.network.startsWith('stellar:');
1202
+ return {
1203
+ message: entry.asset == null || entry.asset === '' ? 'asset is missing' : 'asset is not well formed',
1204
+ fix: stellar
1205
+ ? 'Stellar asset must be the SAC contract id (C...), not a symbol.'
1206
+ : 'Set accepts[].asset to the token the seller settles.',
1207
+ detail: entry.asset == null ? undefined : String(entry.asset).slice(0, 80),
1208
+ };
1209
+ }
1210
+ return null;
1211
+ });
1212
+ checks.push(assetResult.ok
1213
+ ? sellerCheck('asset', 'pass', 'asset is present and well formed')
1214
+ : sellerCheck('asset', 'fail', assetResult.index != null ? `accepts[${assetResult.index}].${assetResult.message}` : assetResult.message, assetResult.fix, assetResult.detail));
1215
+
1216
+ const amountResult = fieldFailures(payment, (entry) => {
1217
+ if (!isPositiveAtomicAmount(entry.amount)) {
1218
+ return {
1219
+ message: entry.amount == null || entry.amount === '' ? 'amount is missing' : 'amount is not a positive integer string',
1220
+ fix: 'Set accepts[].amount to atomic units, for example "1000000". Do not send "$0.02" or "0".',
1221
+ detail: entry.amount == null ? undefined : String(entry.amount).slice(0, 80),
1222
+ };
1223
+ }
1224
+ return null;
1225
+ });
1226
+ checks.push(amountResult.ok
1227
+ ? sellerCheck('amount', 'pass', 'amount is a positive integer string')
1228
+ : sellerCheck('amount', 'fail', amountResult.index != null ? `accepts[${amountResult.index}].${amountResult.message}` : amountResult.message, amountResult.fix, amountResult.detail));
1229
+
1230
+ const payToResult = fieldFailures(payment, (entry) => {
1231
+ const problem = payToProblem(entry.payTo, entry.network);
1232
+ if (!problem) return null;
1233
+ if (problem === 'secret') {
1234
+ return {
1235
+ message: 'payTo is a secret key (S...), not a public key',
1236
+ fix: 'accepts[].payTo must be the public key that receives funds (G... on Stellar). Never publish a secret.',
1237
+ detail: 'value starts with S',
1238
+ };
1239
+ }
1240
+ if (problem === 'missing') {
1241
+ return { message: 'payTo is missing', fix: 'Set accepts[].payTo to the account that receives the payment.' };
1242
+ }
1243
+ return {
1244
+ message: 'payTo is not well formed',
1245
+ fix: 'On Stellar, payTo must be a valid 56-character G... public key.',
1246
+ detail: typeof entry.payTo === 'string' ? `length ${entry.payTo.length}` : undefined,
1247
+ };
1248
+ });
1249
+ checks.push(payToResult.ok
1250
+ ? sellerCheck('payTo', 'pass', 'payTo is present and well formed')
1251
+ : sellerCheck('payTo', 'fail', payToResult.index != null ? `accepts[${payToResult.index}].${payToResult.message}` : payToResult.message, payToResult.fix, payToResult.detail));
1252
+
1253
+ const urlProblem = payment ? resourceUrlProblem(payment.resource?.url) : 'missing';
1254
+ if (!payment) {
1255
+ checks.push(sellerCheck(
1256
+ 'resource-url',
1257
+ 'fail',
1258
+ 'resource.url was not checked because PAYMENT-REQUIRED did not decode',
1259
+ 'Fix the 402 challenge first. resource.url must be an https:// URL.',
1260
+ ));
1261
+ } else if (urlProblem === 'http') {
1262
+ checks.push(sellerCheck(
1263
+ 'resource-url',
1264
+ 'fail',
1265
+ 'resource.url uses http://',
1266
+ 'Serve resource.url as https://. Browsers and x402 clients will not treat an http resource as the paid URL.',
1267
+ String(payment.resource?.url).slice(0, 120),
1268
+ ));
1269
+ } else if (urlProblem) {
1270
+ checks.push(sellerCheck(
1271
+ 'resource-url',
1272
+ 'fail',
1273
+ 'resource.url is missing or not https://',
1274
+ 'Set resource.url to an absolute https:// URL.',
1275
+ payment.resource?.url == null ? undefined : String(payment.resource.url).slice(0, 120),
1276
+ ));
1277
+ } else {
1278
+ checks.push(sellerCheck('resource-url', 'pass', 'resource.url is https://', undefined, payment.resource.url));
1279
+ }
1280
+
1281
+ const preflightResponse = preflight.response;
1282
+ let allowCheck;
1283
+ if (preflight.error || !preflightResponse) {
1284
+ checks.push(sellerCheck(
1285
+ 'cors-preflight',
1286
+ 'fail',
1287
+ `CORS preflight failed: ${probeErrorMessage(preflight.error)}`,
1288
+ 'The seller must answer OPTIONS for an unknown Origin without crashing.',
1289
+ ));
1290
+ allowCheck = sellerCheck(
1291
+ 'cors-allow',
1292
+ 'fail',
1293
+ 'PAYMENT-SIGNATURE was not allowed because the preflight did not complete',
1294
+ 'Answer OPTIONS with Access-Control-Allow-Headers including PAYMENT-SIGNATURE.',
1295
+ );
1296
+ } else if (preflightResponse.status >= 500) {
1297
+ checks.push(sellerCheck(
1298
+ 'cors-preflight',
1299
+ 'fail',
1300
+ `CORS preflight returned HTTP ${preflightResponse.status} for an unknown origin`,
1301
+ 'An unknown Origin must not 500. Handle OPTIONS before route auth.',
1302
+ origin,
1303
+ ));
1304
+ allowCheck = sellerCheck(
1305
+ 'cors-allow',
1306
+ 'fail',
1307
+ 'PAYMENT-SIGNATURE was not allowed because the preflight failed',
1308
+ 'Answer OPTIONS with 2xx and Access-Control-Allow-Headers: PAYMENT-SIGNATURE.',
1309
+ );
1310
+ } else if (preflightResponse.status < 200 || preflightResponse.status >= 300) {
1311
+ checks.push(sellerCheck(
1312
+ 'cors-preflight',
1313
+ 'fail',
1314
+ `CORS preflight returned HTTP ${preflightResponse.status}`,
1315
+ 'Answer OPTIONS with 204 or another 2xx, including Access-Control-Allow-Origin.',
1316
+ origin,
1317
+ ));
1318
+ allowCheck = sellerCheck(
1319
+ 'cors-allow',
1320
+ 'fail',
1321
+ 'PAYMENT-SIGNATURE was not allowed because the preflight was not successful',
1322
+ 'Include PAYMENT-SIGNATURE in Access-Control-Allow-Headers on the OPTIONS response.',
1323
+ );
1324
+ } else {
1325
+ const allowOrigin = preflightResponse.headers.get('access-control-allow-origin') || '';
1326
+ const originAllowed = allowOrigin === '*' || allowOrigin === origin;
1327
+ checks.push(originAllowed
1328
+ ? sellerCheck('cors-preflight', 'pass', `CORS preflight returned HTTP ${preflightResponse.status} for a random origin`, undefined, origin)
1329
+ : sellerCheck(
1330
+ 'cors-preflight',
1331
+ 'fail',
1332
+ 'CORS preflight did not allow the random origin',
1333
+ 'Send Access-Control-Allow-Origin: * or echo the request Origin. An unknown origin must not be dropped.',
1334
+ allowOrigin ? `got ${allowOrigin}` : 'Access-Control-Allow-Origin missing',
1335
+ ));
1336
+ const allowed = tokenListIncludes(preflightResponse.headers.get('access-control-allow-headers'), 'PAYMENT-SIGNATURE');
1337
+ allowCheck = allowed
1338
+ ? sellerCheck('cors-allow', 'pass', 'PAYMENT-SIGNATURE is allowed on the preflight')
1339
+ : sellerCheck(
1340
+ 'cors-allow',
1341
+ 'fail',
1342
+ 'PAYMENT-SIGNATURE is not listed in Access-Control-Allow-Headers',
1343
+ 'Add PAYMENT-SIGNATURE to Access-Control-Allow-Headers. Browsers drop the payment header otherwise.',
1344
+ preflightResponse.headers.get('access-control-allow-headers') || 'header missing',
1345
+ );
1346
+ }
1347
+
1348
+ // Browsers only honor Access-Control-Expose-Headers on the actual response.
1349
+ // A preflight that lists the headers does not make the 402 readable.
1350
+ const exposeMissing = missingExposedHeaders(challenge.response?.headers.get('access-control-expose-headers'));
1351
+ if (challenge.response && exposeMissing.length === 0) {
1352
+ checks.push(sellerCheck(
1353
+ 'cors-expose',
1354
+ 'pass',
1355
+ 'PAYMENT-REQUIRED and PAYMENT-RESPONSE are exposed on the 402 response',
1356
+ ));
1357
+ } else {
1358
+ const missing = exposeMissing.length ? exposeMissing : ['PAYMENT-REQUIRED', 'PAYMENT-RESPONSE'];
1359
+ checks.push(sellerCheck(
1360
+ 'cors-expose',
1361
+ 'fail',
1362
+ `browser clients cannot read ${missing.join(' and ')}`,
1363
+ 'Set Access-Control-Expose-Headers: PAYMENT-REQUIRED, PAYMENT-RESPONSE on the 402 response. The preflight does not count.',
1364
+ ));
1365
+ }
1366
+ checks.push(allowCheck);
1367
+
1368
+ return sellerReport(sellerUrl, checks, payment ? firstAdvertisedNetwork(payment) : null);
1369
+ }
1370
+
804
1371
  function formatDoctorOutput(report) {
805
1372
  const lines = [];
806
- lines.push(`🩺 Nirium Doctor — x402/MPP Diagnostic Report`);
807
- lines.push(`Target Network: ${report.network}`);
1373
+ lines.push(report.seller
1374
+ ? `🩺 Nirium Doctor — remote x402 seller`
1375
+ : `🩺 Nirium Doctor — x402/MPP Diagnostic Report`);
1376
+ if (report.seller) lines.push(`Seller: ${report.seller}`);
1377
+ lines.push(`Target Network: ${report.network || 'n/a'}`);
808
1378
  lines.push(`Timestamp: ${report.timestamp}`);
809
1379
  lines.push(`--------------------------------------------------`);
810
1380
  for (const check of report.checks) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nirium-cli",
3
- "version": "1.1.4",
3
+ "version": "2.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,7 @@
8
8
  "nirium": "bin/nirium.js"
9
9
  },
10
10
  "scripts": {
11
- "test": "echo \"Error: no test specified\" && exit 1"
11
+ "test": "node --test test/doctor-seller.test.js test/config-secret.test.js test/serve-api-key.test.js"
12
12
  },
13
13
  "keywords": [
14
14
  "stellar",
@@ -23,7 +23,7 @@
23
23
  "dependencies": {
24
24
  "axios": "^1.13.6",
25
25
  "commander": "^11.0.0",
26
- "nirium": "^0.14.0",
26
+ "nirium": "^0.16.0",
27
27
  "express": "^5.1.0",
28
28
  "@stellar/stellar-sdk": "^14.5.0"
29
29
  },