nirium-cli 1.0.5 → 1.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 (2) hide show
  1. package/bin/nirium.js +699 -4
  2. package/package.json +5 -2
package/bin/nirium.js CHANGED
@@ -1,20 +1,31 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // ═══════════════════════════════════════════════════════════════
4
- // Nirium — Autonomous Agent CLI (v1.0.5)
4
+ // Nirium — Autonomous Agent CLI (v1.1.0)
5
5
  // ═══════════════════════════════════════════════════════════════
6
+ //
7
+ // Everything below is one flat file on purpose, not a build artifact:
8
+ // "files" in package.json ships only bin/ + README.md, so any command
9
+ // implemented in a separate compiled module never reaches npm unless
10
+ // dist/ is added to that list too. Inlining avoids depending on a build
11
+ // step existing at publish time at all.
6
12
 
7
13
  import { Command } from 'commander';
8
14
  import fs from 'fs';
9
15
  import path from 'path';
16
+ import os from 'os';
17
+ import crypto from 'crypto';
10
18
  import { execSync } from 'child_process';
19
+ import express from 'express';
20
+ import NiriumAgent, { x402Serve } from 'nirium';
21
+ import { Keypair, StrKey } from '@stellar/stellar-sdk';
11
22
 
12
23
  const program = new Command();
13
24
 
14
25
  program
15
26
  .name('nirium')
16
27
  .description('Nirium protocol development tool')
17
- .version('1.0.5');
28
+ .version('1.1.0');
18
29
 
19
30
  // --- COMMAND: create bot ---
20
31
  program
@@ -64,6 +75,106 @@ program
64
75
  }
65
76
  });
66
77
 
78
+ // --- COMMAND: status ---
79
+ program
80
+ .command('status')
81
+ .description('Check agent connection status')
82
+ .option('-u, --url <url>', 'Agent URL', 'http://localhost:3001')
83
+ .action(async (options) => {
84
+ try {
85
+ const response = await fetch(`${options.url}/health`);
86
+ if (response.ok) {
87
+ const data = await response.json();
88
+ console.log('🟢 Agent is operational');
89
+ console.log(` Version: ${data.version}`);
90
+ console.log(` Network: ${data.network}`);
91
+ console.log(` Uptime: ${data.uptime}s`);
92
+ } else {
93
+ console.log('🔴 Agent returned error:', response.status);
94
+ }
95
+ } catch {
96
+ console.log('🔴 Agent unreachable at', options.url);
97
+ }
98
+ });
99
+
100
+ // --- COMMAND: verify ---
101
+ program
102
+ .command('verify')
103
+ .argument('<cid>', 'IPFS Content Identifier (CID) of the audit document')
104
+ .option('-g, --gateway <url>', 'IPFS gateway URL', 'https://gateway.pinata.cloud')
105
+ .option('--json', 'Output result as JSON')
106
+ .description('Independently verify IPFS audit document content hash & agent ed25519 signature')
107
+ .action(async (cid, options) => {
108
+ const result = await fetchAndVerifyCid(cid, options.gateway);
109
+ if (options.json) {
110
+ console.log(JSON.stringify(result, null, 2));
111
+ } else {
112
+ console.log(formatVerifyOutput(result));
113
+ }
114
+ if (!result.ok) {
115
+ process.exit(1);
116
+ }
117
+ });
118
+
119
+ // --- COMMAND: doctor ---
120
+ program
121
+ .command('doctor')
122
+ .description('CLI preflight diagnostics for x402/MPP misconfiguration')
123
+ .option('-n, --network <network>', 'Stellar network: testnet or pubnet', 'testnet')
124
+ .option('-c, --config <path>', 'Path to environment or config file')
125
+ .option('--json', 'Output results as JSON for CI integration')
126
+ .action(async (options) => {
127
+ const report = await runDoctorDiagnostics(options);
128
+ if (options.json) {
129
+ console.log(JSON.stringify(report, null, 2));
130
+ } else {
131
+ console.log(formatDoctorOutput(report));
132
+ }
133
+ if (!report.ok) {
134
+ process.exit(1);
135
+ }
136
+ });
137
+
138
+ // --- COMMAND: pay ---
139
+ program
140
+ .command('pay')
141
+ .description('💳 Pay an x402-protected endpoint straight from the terminal with Stellar auth entry signing')
142
+ .argument('<url>', 'URL of the x402-protected endpoint')
143
+ .option('-a, --amount <amount>', 'Payment amount override')
144
+ .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
+ .option('-c, --config <path>', 'Custom path to configuration file or .env')
147
+ .option('--json', 'Output execution result as JSON')
148
+ .action(async (url, options) => {
149
+ await executePayCommand(url, options);
150
+ });
151
+
152
+ // --- COMMAND: serve ---
153
+ program
154
+ .command('serve')
155
+ .description('🚀 Spin up a local x402-protected demo HTTP server to test payments against')
156
+ .option('-p, --price <price>', 'Price for access (e.g. $0.02)', '$0.02')
157
+ .option('-P, --pay-to <address>', 'Stellar public key (G...) to receive payments')
158
+ .option('-port, --port <port>', 'Port number to listen on', '3000')
159
+ .option('-n, --network <network>', 'CAIP-2 network ID (stellar:testnet or stellar:pubnet)', 'stellar:testnet')
160
+ .option('-r, --route <route>', 'Route path to protect', '/api/v1/data')
161
+ .option('-k, --api-key <key>', 'Facilitator API key')
162
+ .option('-c, --config <path>', 'Custom path to config file')
163
+ .action(async (options) => {
164
+ await executeServeCommand(options);
165
+ });
166
+
167
+ // --- COMMAND: config ---
168
+ program
169
+ .command('config')
170
+ .description('⚙️ Manage local CLI configuration store (~/.niriumrc.json)')
171
+ .argument('[action]', 'Action to perform: set, get, list, or delete', 'list')
172
+ .argument('[key]', 'Configuration key name')
173
+ .argument('[value]', 'Value to set for the configuration key')
174
+ .action(async (action, key, value) => {
175
+ executeConfigCommand(action, key, value);
176
+ });
177
+
67
178
  // Un servidor que COBRA, no uno que escucha. Es el camino corto de
68
179
  // "instalé algo" a "me pagaron": levantas esto, le pegas con un cliente
69
180
  // x402 y el pago se liquida on-chain antes de que salga la respuesta.
@@ -75,7 +186,7 @@ function scaffoldX402(dir, name) {
75
186
  type: 'module',
76
187
  scripts: { dev: 'tsx watch src/server.ts', build: 'tsc' },
77
188
  dependencies: {
78
- nirium: '^0.10.0',
189
+ nirium: '^0.13.0',
79
190
  express: '^5.1.0',
80
191
  '@x402/express': '^2.17.0',
81
192
  '@x402/core': '^2.17.0',
@@ -141,7 +252,7 @@ function scaffoldTS(dir, name) {
141
252
  "build": "tsc"
142
253
  },
143
254
  dependencies: {
144
- "nirium": "^0.10.0",
255
+ "nirium": "^0.13.0",
145
256
  "tsx": "^4.19.0",
146
257
  "typescript": "^5.7.0",
147
258
  "dotenv": "^16.4.5"
@@ -218,4 +329,588 @@ if __name__ == "__main__":
218
329
  fs.writeFileSync(path.join(dir, '.env'), 'NIRIUM_API_URL=https://nirium-agent.fly.dev\nNIRIUM_API_KEY=');
219
330
  }
220
331
 
332
+ // ═══════════════════════════════════════════════════════════════
333
+ // config — ~/.niriumrc.json store, shared by pay/serve/config
334
+ // ═══════════════════════════════════════════════════════════════
335
+
336
+ const CONFIG_FILE = path.join(os.homedir(), '.niriumrc.json');
337
+
338
+ function loadConfig(customPath) {
339
+ const filePath = customPath || CONFIG_FILE;
340
+ try {
341
+ if (fs.existsSync(filePath)) {
342
+ const raw = fs.readFileSync(filePath, 'utf8');
343
+ return JSON.parse(raw);
344
+ }
345
+ } catch {
346
+ // Ignore read errors gracefully
347
+ }
348
+ return {};
349
+ }
350
+
351
+ function saveConfig(config, customPath) {
352
+ const filePath = customPath || CONFIG_FILE;
353
+ try {
354
+ fs.writeFileSync(filePath, JSON.stringify(config, null, 2), {
355
+ encoding: 'utf8',
356
+ mode: 0o600,
357
+ });
358
+ // Enforce permissions even on pre-existing files (writeFileSync mode
359
+ // only applies when the file is created, not when it already exists).
360
+ try {
361
+ fs.chmodSync(filePath, 0o600);
362
+ } catch {
363
+ // best effort on platforms without POSIX permissions (e.g. some Windows setups)
364
+ }
365
+ } catch (err) {
366
+ throw new Error(`Failed to save config to ${filePath}: ${err?.message || String(err)}`);
367
+ }
368
+ }
369
+
370
+ function maskSecret(secret) {
371
+ if (!secret) return '(not set)';
372
+ if (secret.length <= 8) return 'S****';
373
+ return `${secret.slice(0, 4)}...${secret.slice(-4)}`;
374
+ }
375
+
376
+ function executeConfigCommand(action, key, value) {
377
+ const currentConfig = loadConfig();
378
+
379
+ if (!action || action === 'list') {
380
+ console.log('⚙️ Nirium CLI Configuration:');
381
+ console.log(` secretKey: ${maskSecret(currentConfig.secretKey)}`);
382
+ console.log(` payTo: ${currentConfig.payTo || '(not set)'}`);
383
+ console.log(` network: ${currentConfig.network || '(default: stellar:testnet)'}`);
384
+ console.log(` facilitatorApiKey: ${maskSecret(currentConfig.facilitatorApiKey)}`);
385
+ return;
386
+ }
387
+
388
+ if (action === 'get') {
389
+ if (!key) {
390
+ console.error('❌ Error: Please specify a configuration key (e.g. `nirium config get secretKey`)');
391
+ process.exit(1);
392
+ }
393
+ const val = currentConfig[key];
394
+ if (key.toLowerCase().includes('secret') || key.toLowerCase().includes('key')) {
395
+ console.log(`${key}: ${maskSecret(val)}`);
396
+ } else {
397
+ console.log(`${key}: ${val || '(not set)'}`);
398
+ }
399
+ return;
400
+ }
401
+
402
+ if (action === 'set') {
403
+ if (!key || value === undefined) {
404
+ console.error('❌ Error: Usage: `nirium config set <key> <value>` (e.g., `nirium config set secretKey S...`)');
405
+ process.exit(1);
406
+ }
407
+ const updatedConfig = { ...currentConfig, [key]: value };
408
+ saveConfig(updatedConfig);
409
+ console.log(`✅ Configuration updated: ${key} set successfully.`);
410
+ return;
411
+ }
412
+
413
+ if (action === 'delete' || action === 'remove') {
414
+ if (!key) {
415
+ console.error('❌ Error: Please specify a configuration key to delete.');
416
+ process.exit(1);
417
+ }
418
+ delete currentConfig[key];
419
+ saveConfig(currentConfig);
420
+ console.log(`✅ Removed ${key} from configuration.`);
421
+ return;
422
+ }
423
+
424
+ console.error(`❌ Unknown config action: ${action}. Use set, get, list, or delete.`);
425
+ process.exit(1);
426
+ }
427
+
428
+ // ═══════════════════════════════════════════════════════════════
429
+ // pay — sign and settle an x402 payment from the terminal
430
+ // ═══════════════════════════════════════════════════════════════
431
+
432
+ async function executePayCommand(url, options) {
433
+ const config = loadConfig(options.config);
434
+ const secretKey = options.secret || process.env.NIRIUM_SECRET_KEY || config.secretKey;
435
+ const network = options.network || process.env.NIRIUM_NETWORK || config.network || 'stellar:testnet';
436
+
437
+ if (!secretKey) {
438
+ const errorMsg = 'Missing secret key for x402 payment authorization.\n'
439
+ + 'Please provide a secret key using:\n'
440
+ + ' - `--secret S...` option\n'
441
+ + ' - `NIRIUM_SECRET_KEY` environment variable\n'
442
+ + ' - `nirium config set secretKey S...`';
443
+ if (options.json) {
444
+ console.log(JSON.stringify({ status: 'error', error: errorMsg }));
445
+ process.exit(1);
446
+ }
447
+ console.error(`❌ Error: ${errorMsg}`);
448
+ process.exit(1);
449
+ }
450
+
451
+ let publicKey = '';
452
+ try {
453
+ const kp = Keypair.fromSecret(secretKey);
454
+ publicKey = kp.publicKey();
455
+ } catch (err) {
456
+ const invalidMsg = `Invalid Stellar secret key format: ${err?.message || 'must start with S'}`;
457
+ if (options.json) {
458
+ console.log(JSON.stringify({ status: 'error', error: invalidMsg }));
459
+ process.exit(1);
460
+ }
461
+ console.error(`❌ Error: ${invalidMsg}`);
462
+ process.exit(1);
463
+ }
464
+
465
+ if (!options.json) {
466
+ console.log(`⚡ Initiating x402 Payment Request`);
467
+ console.log(` Target URL: ${url}`);
468
+ console.log(` Network: ${network}`);
469
+ console.log(` Payer Key: ${publicKey}`);
470
+ console.log(` Secret: ${maskSecret(secretKey)}\n`);
471
+ }
472
+
473
+ try {
474
+ const agent = new NiriumAgent({ apiKey: 'nirium-cli-pay' });
475
+ agent.initX402({ secretKey, network });
476
+
477
+ const startTime = Date.now();
478
+ const response = await agent.x402Fetch(url, {
479
+ method: 'GET',
480
+ headers: { 'User-Agent': 'Nirium-CLI-Pay/1.0' },
481
+ });
482
+ const durationMs = Date.now() - startTime;
483
+
484
+ const responseHeaders = Object.fromEntries(response.headers.entries());
485
+ const paymentResponseHeader = response.headers.get('payment-response')
486
+ || response.headers.get('x-payment-response')
487
+ || response.headers.get('payment-tx-hash')
488
+ || '';
489
+
490
+ let txHash = '';
491
+ let paymentMeta = null;
492
+ if (paymentResponseHeader) {
493
+ try {
494
+ if (paymentResponseHeader.startsWith('{')) {
495
+ const parsed = JSON.parse(paymentResponseHeader);
496
+ txHash = parsed.txHash || parsed.transactionHash || parsed.hash || '';
497
+ paymentMeta = parsed;
498
+ } else {
499
+ txHash = paymentResponseHeader;
500
+ }
501
+ } catch {
502
+ txHash = paymentResponseHeader;
503
+ }
504
+ }
505
+
506
+ let responseBody;
507
+ const contentType = response.headers.get('content-type') || '';
508
+ if (contentType.includes('application/json')) {
509
+ responseBody = await response.json();
510
+ } else {
511
+ responseBody = await response.text();
512
+ }
513
+
514
+ if (options.json) {
515
+ console.log(JSON.stringify({
516
+ status: response.ok ? 'success' : 'failed',
517
+ statusCode: response.status,
518
+ durationMs,
519
+ payer: publicKey,
520
+ network,
521
+ txHash: txHash || undefined,
522
+ paymentMeta: paymentMeta || undefined,
523
+ headers: responseHeaders,
524
+ data: responseBody,
525
+ }, null, 2));
526
+ return;
527
+ }
528
+
529
+ console.log(`✅ Payment Negotiated & Request Completed (${response.status} ${response.statusText})`);
530
+ console.log(` Response Time: ${durationMs}ms`);
531
+ if (txHash) {
532
+ console.log(` Tx Reference: ${txHash}`);
533
+ console.log(` Explorer: https://stellar.expert/explorer/${network.includes('testnet') ? 'testnet' : 'public'}/tx/${txHash}`);
534
+ }
535
+ console.log(`\n--- Response Payload ---`);
536
+ console.log(typeof responseBody === 'object' ? JSON.stringify(responseBody, null, 2) : responseBody);
537
+ } catch (err) {
538
+ const errorDetail = err?.message || String(err);
539
+ if (options.json) {
540
+ console.log(JSON.stringify({ status: 'error', error: errorDetail, payer: publicKey, network }));
541
+ process.exit(1);
542
+ }
543
+ console.error(`❌ Payment Failed: ${errorDetail}`);
544
+ process.exit(1);
545
+ }
546
+ }
547
+
548
+ // ═══════════════════════════════════════════════════════════════
549
+ // serve — local x402-protected demo server
550
+ // ═══════════════════════════════════════════════════════════════
551
+
552
+ async function executeServeCommand(options) {
553
+ const config = loadConfig(options.config);
554
+ const payTo = options.payTo || process.env.NIRIUM_PAY_TO || config.payTo;
555
+ const price = options.price || '$0.02';
556
+ const port = Number(options.port || process.env.PORT || 3000);
557
+ const network = options.network || process.env.NIRIUM_NETWORK || config.network || 'stellar:testnet';
558
+ const routePath = options.route || '/api/v1/data';
559
+ const facilitatorApiKey = options.apiKey || process.env.FACILITATOR_API_KEY || config.facilitatorApiKey;
560
+
561
+ if (!facilitatorApiKey) {
562
+ console.error('❌ Error: Missing facilitator API key.');
563
+ 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 ...`');
566
+ process.exit(1);
567
+ }
568
+ if (!payTo) {
569
+ console.error('❌ Error: Missing `--pay-to` Stellar address (G...).');
570
+ console.error('Please specify a recipient address using `--pay-to G...` or setting `payTo` in config.');
571
+ process.exit(1);
572
+ }
573
+
574
+ const app = express();
575
+ app.use(express.json());
576
+
577
+ const middleware = x402Serve({
578
+ payTo,
579
+ network,
580
+ facilitatorApiKey,
581
+ routes: {
582
+ [`GET ${routePath}`]: { price, description: 'Nirium CLI x402 Demo Endpoint' },
583
+ },
584
+ });
585
+ app.use(middleware);
586
+
587
+ app.get(routePath, (req, res) => {
588
+ res.json({
589
+ status: 'success',
590
+ message: 'x402 Payment Verified! Access Granted.',
591
+ endpoint: routePath,
592
+ price,
593
+ paidTo: payTo,
594
+ timestamp: new Date().toISOString(),
595
+ sampleData: { signal: 'CETES_REBALANCE_OPPORTUNITY', yieldApy: '5.57%', network },
596
+ });
597
+ });
598
+
599
+ return new Promise((resolve, reject) => {
600
+ const server = app.listen(port, () => {
601
+ console.log(`\n🚀 Nirium x402 Demo Server Listening on http://localhost:${port}`);
602
+ console.log(` Protected Route: http://localhost:${port}${routePath}`);
603
+ console.log(` Price: ${price}`);
604
+ console.log(` Pay To: ${payTo}`);
605
+ console.log(` Network: ${network}\n`);
606
+ console.log(`💡 Test this server using:`);
607
+ console.log(` nirium pay http://localhost:${port}${routePath} --secret S...\n`);
608
+ resolve({ app, server });
609
+ });
610
+ server.on('error', (err) => {
611
+ console.error(`❌ Server startup failed: ${err.message}`);
612
+ reject(err);
613
+ });
614
+ });
615
+ }
616
+
617
+ // ═══════════════════════════════════════════════════════════════
618
+ // doctor — x402/MPP preflight diagnostics
619
+ // ═══════════════════════════════════════════════════════════════
620
+
621
+ function loadEnvFile(filePath) {
622
+ const env = {};
623
+ const targetPath = filePath ? path.resolve(process.cwd(), filePath) : path.resolve(process.cwd(), '.env');
624
+ if (fs.existsSync(targetPath)) {
625
+ try {
626
+ const content = fs.readFileSync(targetPath, 'utf8');
627
+ for (const line of content.split('\n')) {
628
+ const trimmed = line.trim();
629
+ if (!trimmed || trimmed.startsWith('#')) continue;
630
+ const eqIdx = trimmed.indexOf('=');
631
+ if (eqIdx !== -1) {
632
+ const key = trimmed.slice(0, eqIdx).trim();
633
+ let val = trimmed.slice(eqIdx + 1).trim();
634
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
635
+ val = val.slice(1, -1);
636
+ }
637
+ env[key] = val;
638
+ }
639
+ }
640
+ } catch {
641
+ // Ignore file read errors
642
+ }
643
+ }
644
+ return env;
645
+ }
646
+
647
+ function normalizeNetwork(inputNet) {
648
+ const net = (inputNet || '').toLowerCase();
649
+ if (net === 'pubnet' || net === 'mainnet' || net === 'stellar:pubnet' || net === 'stellar:mainnet') {
650
+ return 'stellar:pubnet';
651
+ }
652
+ return 'stellar:testnet';
653
+ }
654
+
655
+ async function runDoctorDiagnostics(options) {
656
+ const fileEnv = loadEnvFile(options.config);
657
+ const getEnv = (key) => process.env[key] || fileEnv[key] || '';
658
+
659
+ const rawNetwork = options.network || getEnv('STELLAR_NETWORK') || getEnv('NETWORK') || 'testnet';
660
+ const canonicalNetwork = normalizeNetwork(rawNetwork);
661
+ const isTestnet = canonicalNetwork === 'stellar:testnet';
662
+ const checks = [];
663
+
664
+ // Check 1: payTo address
665
+ const payTo = getEnv('STELLAR_PAY_TO') || getEnv('PAY_TO') || getEnv('NIRIUM_X402_PAY_TO') || getEnv('STELLAR_PAYTO');
666
+ if (!payTo) {
667
+ checks.push({
668
+ name: 'payTo', status: 'fail', message: 'payTo address is missing',
669
+ fix: 'Set STELLAR_PAY_TO in .env to a valid Stellar public key starting with G...',
670
+ });
671
+ } else if (payTo.startsWith('S')) {
672
+ checks.push({
673
+ name: 'payTo', status: 'fail', message: 'payTo address is a secret key (S...), not a public key',
674
+ fix: 'Replace STELLAR_PAY_TO with your public key (G...). Secret keys must never be exposed as payTo.',
675
+ detail: `Value starts with '${payTo.slice(0, 4)}...'`,
676
+ });
677
+ } else if (!/^G[A-Z2-7]{55}$/.test(payTo)) {
678
+ checks.push({
679
+ name: 'payTo', status: 'fail', message: 'payTo address is invalid (must be a 56-character Stellar G... address)',
680
+ fix: 'Ensure STELLAR_PAY_TO is a valid 56-char Stellar public key.',
681
+ detail: `Length: ${payTo.length}`,
682
+ });
683
+ } else {
684
+ checks.push({
685
+ name: 'payTo', status: 'pass',
686
+ message: `payTo address is a valid Stellar public key (${payTo.slice(0, 4)}...${payTo.slice(-4)})`,
687
+ detail: payTo,
688
+ });
689
+ }
690
+
691
+ // Check 2: Facilitator API key & reachability
692
+ const facilitatorApiKey = getEnv('X402_FACILITATOR_API_KEY') || getEnv('STELLAR_FACILITATOR_API_KEY') || getEnv('FACILITATOR_API_KEY');
693
+ const defaultFacilitatorUrl = isTestnet ? 'https://channels.openzeppelin.com/x402/testnet' : 'https://channels.openzeppelin.com/x402';
694
+ const facilitatorUrl = getEnv('FACILITATOR_URL') || getEnv('X402_FACILITATOR_URL') || defaultFacilitatorUrl;
695
+ const customFetch = options.fetchFn || globalThis.fetch;
696
+
697
+ if (!facilitatorApiKey && !getEnv('FACILITATOR_URL')) {
698
+ const genUrl = isTestnet ? 'https://channels.openzeppelin.com/testnet/gen' : 'https://channels.openzeppelin.com/gen';
699
+ checks.push({
700
+ name: 'facilitator', status: 'fail',
701
+ message: 'facilitatorApiKey is missing — OpenZeppelin Channels facilitator rejects unauthenticated requests',
702
+ fix: `Get a free ${rawNetwork} key at ${genUrl} and set X402_FACILITATOR_API_KEY in .env`,
703
+ });
704
+ } else {
705
+ try {
706
+ const headers = {};
707
+ if (facilitatorApiKey) headers['Authorization'] = `Bearer ${facilitatorApiKey}`;
708
+ const response = await customFetch(`${facilitatorUrl}/supported`, { headers, signal: AbortSignal.timeout(5000) });
709
+ if (response.ok) {
710
+ checks.push({
711
+ name: 'facilitator', status: 'pass',
712
+ message: `Facilitator reachable and API key authenticated on ${rawNetwork}`,
713
+ detail: facilitatorUrl,
714
+ });
715
+ } else if (response.status === 401 || response.status === 403) {
716
+ const genUrl = isTestnet ? 'https://channels.openzeppelin.com/testnet/gen' : 'https://channels.openzeppelin.com/gen';
717
+ checks.push({
718
+ name: 'facilitator', status: 'fail',
719
+ message: `Facilitator rejected API key (HTTP ${response.status})`,
720
+ fix: `Verify X402_FACILITATOR_API_KEY is valid for ${rawNetwork}. Keys are per-network: get one at ${genUrl}`,
721
+ detail: `Status ${response.status} from ${facilitatorUrl}`,
722
+ });
723
+ } else {
724
+ checks.push({
725
+ name: 'facilitator', status: 'fail', message: `Facilitator returned HTTP ${response.status}`,
726
+ fix: `Check facilitator service status at ${facilitatorUrl}`,
727
+ });
728
+ }
729
+ } catch (err) {
730
+ checks.push({
731
+ name: 'facilitator', status: 'fail', message: `Facilitator endpoint unreachable at ${facilitatorUrl}`,
732
+ fix: 'Check network connectivity or custom FACILITATOR_URL setting.',
733
+ detail: err?.message || String(err),
734
+ });
735
+ }
736
+ }
737
+
738
+ // Check 3: Network & RPC consistency
739
+ const defaultRpcUrl = isTestnet ? 'https://soroban-testnet.stellar.org' : 'https://soroban-rpc.mainnet.stellar.gateway.fm';
740
+ const rpcUrl = getEnv('STELLAR_RPC_URL') || getEnv('RPC_URL') || defaultRpcUrl;
741
+ const expectedPassphrase = isTestnet ? 'Test SDF Network ; July 2015' : 'Public Global Stellar Network ; September 2015';
742
+ try {
743
+ const rpcRes = await customFetch(rpcUrl, {
744
+ method: 'POST',
745
+ headers: { 'Content-Type': 'application/json' },
746
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getHealth' }),
747
+ signal: AbortSignal.timeout(5000),
748
+ });
749
+ if (rpcRes.ok) {
750
+ checks.push({
751
+ name: 'network', status: 'pass', message: `Soroban RPC endpoint operational for ${canonicalNetwork}`,
752
+ detail: `${rpcUrl} (Passphrase: "${expectedPassphrase}")`,
753
+ });
754
+ } else {
755
+ checks.push({
756
+ name: 'network', status: 'fail', message: `Soroban RPC endpoint returned HTTP ${rpcRes.status}`,
757
+ fix: `Verify STELLAR_RPC_URL for network ${canonicalNetwork}`,
758
+ });
759
+ }
760
+ } catch (err) {
761
+ checks.push({
762
+ name: 'network', status: 'fail', message: `Soroban RPC endpoint unreachable at ${rpcUrl}`,
763
+ fix: `Check network connection or set a working STELLAR_RPC_URL for ${canonicalNetwork}`,
764
+ detail: err?.message || String(err),
765
+ });
766
+ }
767
+
768
+ // Check 4: Secret Key check (if configured)
769
+ const secretKey = getEnv('STELLAR_SECRET_KEY') || getEnv('SECRET_KEY') || getEnv('NIRIUM_SECRET_KEY');
770
+ if (secretKey) {
771
+ if (!/^S[A-Z2-7]{55}$/.test(secretKey)) {
772
+ checks.push({
773
+ name: 'secretKey', status: 'fail', message: 'Secret key format is invalid (must be a 56-character Stellar S... key)',
774
+ fix: 'Ensure STELLAR_SECRET_KEY is a valid Stellar secret key starting with S...',
775
+ });
776
+ } else {
777
+ checks.push({ name: 'secretKey', status: 'pass', message: 'Secret key format is valid (S...)' });
778
+ }
779
+ }
780
+
781
+ // Check 5: MPP Configuration (if configured)
782
+ const mppMode = getEnv('MPP_MODE');
783
+ const mppSecret = getEnv('MPP_SECRET_KEY');
784
+ if (mppMode || mppSecret) {
785
+ if (mppMode && mppMode !== 'pull' && mppMode !== 'push') {
786
+ checks.push({
787
+ name: 'mpp', status: 'fail', message: `Invalid MPP_MODE: "${mppMode}" (must be "pull" or "push")`,
788
+ fix: 'Set MPP_MODE=pull or MPP_MODE=push in .env',
789
+ });
790
+ } else if (mppSecret && !/^S[A-Z2-7]{55}$/.test(mppSecret)) {
791
+ checks.push({
792
+ name: 'mpp', status: 'fail', message: 'Invalid MPP_SECRET_KEY format (must be a 56-character S... key)',
793
+ fix: 'Check MPP_SECRET_KEY in .env',
794
+ });
795
+ } else {
796
+ checks.push({ name: 'mpp', status: 'pass', message: `MPP protocol configuration valid (mode: ${mppMode || 'pull'})` });
797
+ }
798
+ }
799
+
800
+ const ok = checks.every((c) => c.status === 'pass');
801
+ return { ok, network: canonicalNetwork, checks, timestamp: new Date().toISOString() };
802
+ }
803
+
804
+ function formatDoctorOutput(report) {
805
+ const lines = [];
806
+ lines.push(`🩺 Nirium Doctor — x402/MPP Diagnostic Report`);
807
+ lines.push(`Target Network: ${report.network}`);
808
+ lines.push(`Timestamp: ${report.timestamp}`);
809
+ lines.push(`--------------------------------------------------`);
810
+ for (const check of report.checks) {
811
+ const symbol = check.status === 'pass' ? '✔' : '❌';
812
+ lines.push(`${symbol} [${check.name.toUpperCase()}] ${check.message}`);
813
+ if (check.detail && check.status === 'pass') lines.push(` Detail: ${check.detail}`);
814
+ if (check.fix) lines.push(` 💡 Fix: ${check.fix}`);
815
+ }
816
+ lines.push(`--------------------------------------------------`);
817
+ lines.push(report.ok ? `✅ All checks passed!` : `❌ Diagnostic failed. See fix suggestions above.`);
818
+ return lines.join('\n');
819
+ }
820
+
821
+ // ═══════════════════════════════════════════════════════════════
822
+ // verify — independently check an audit CID's hash + agent signature
823
+ // ═══════════════════════════════════════════════════════════════
824
+
825
+ function decodeStellarPublicKey(gAddress) {
826
+ if (!/^G[A-Z2-7]{55}$/.test(gAddress)) {
827
+ throw new Error(`Invalid Stellar public key format: ${gAddress}`);
828
+ }
829
+ return Buffer.from(StrKey.decodeEd25519PublicKey(gAddress));
830
+ }
831
+
832
+ function verifyEd25519Signature(pubKeyGAddress, statement, base64Signature) {
833
+ try {
834
+ const rawPubKey = decodeStellarPublicKey(pubKeyGAddress);
835
+ const spkiHeader = Buffer.from('302a300506032b6570032100', 'hex');
836
+ const keyObject = crypto.createPublicKey({
837
+ key: Buffer.concat([spkiHeader, rawPubKey]),
838
+ format: 'der',
839
+ type: 'spki',
840
+ });
841
+ const signatureBuf = Buffer.from(base64Signature, 'base64');
842
+ return crypto.verify(null, Buffer.from(statement), keyObject, signatureBuf);
843
+ } catch {
844
+ return false;
845
+ }
846
+ }
847
+
848
+ function verifyAuditDocument(doc, cid) {
849
+ if (!doc || typeof doc !== 'object') {
850
+ return { ok: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: 'Invalid audit document format' };
851
+ }
852
+ const expectedHash = doc.content_sha256 || '';
853
+ const recordStr = doc.record ? JSON.stringify(doc.record) : '';
854
+ const computedHash = crypto.createHash('sha256').update(recordStr).digest('hex');
855
+ const hashMatch = expectedHash.length > 0 && expectedHash === computedHash;
856
+
857
+ let signatureStatus = 'absent';
858
+ let signerKey, statement, declaredStatement, agentId;
859
+ if (doc.agent && doc.agent.key && doc.agent.signature) {
860
+ signerKey = doc.agent.key;
861
+ agentId = doc.agent.id;
862
+ // Always recompute — never trust the document's own statement field.
863
+ // The protocol signs `nirium-audit-v1:<content_sha256>`, derived
864
+ // exclusively from the record hash. Trusting doc.agent.statement
865
+ // would let an attacker reuse a valid signature after swapping the
866
+ // record content.
867
+ statement = `nirium-audit-v1:${computedHash}`;
868
+ declaredStatement = doc.agent.statement;
869
+ signatureStatus = verifyEd25519Signature(signerKey, statement, doc.agent.signature) ? 'valid' : 'invalid';
870
+ }
871
+
872
+ const ok = hashMatch && signatureStatus !== 'invalid';
873
+ return { ok, cid, hashMatch, expectedHash, computedHash, signatureStatus, signerKey, statement, declaredStatement, agentId };
874
+ }
875
+
876
+ async function fetchAndVerifyCid(cid, gatewayUrl = 'https://gateway.pinata.cloud', fetchFn = globalThis.fetch) {
877
+ const url = `${gatewayUrl.replace(/\/$/, '')}/ipfs/${cid}`;
878
+ try {
879
+ const res = await fetchFn(url);
880
+ if (!res.ok) {
881
+ return { ok: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: `IPFS gateway returned HTTP ${res.status}` };
882
+ }
883
+ const doc = await res.json();
884
+ return verifyAuditDocument(doc, cid);
885
+ } catch (err) {
886
+ return { ok: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent', error: `Failed to fetch CID from gateway: ${err?.message || String(err)}` };
887
+ }
888
+ }
889
+
890
+ function formatVerifyOutput(result) {
891
+ const lines = [];
892
+ lines.push(`🔍 Nirium Audit Verifier`);
893
+ if (result.cid) lines.push(`CID: ${result.cid}`);
894
+ lines.push(`--------------------------------------------------`);
895
+ lines.push(result.hashMatch
896
+ ? `✔ HASH: MATCH (${result.computedHash.slice(0, 16)}...)`
897
+ : `❌ HASH: MISMATCH (Expected: ${result.expectedHash}, Computed: ${result.computedHash})`);
898
+ if (result.signatureStatus === 'valid') {
899
+ lines.push(`✔ SIGNATURE: VALID (Signed by ${result.signerKey})`);
900
+ if (result.statement) lines.push(` Statement: ${result.statement}`);
901
+ if (result.agentId) lines.push(` Agent ID: ${result.agentId}`);
902
+ } else if (result.signatureStatus === 'invalid') {
903
+ lines.push(`❌ SIGNATURE: INVALID (Signature check failed for key ${result.signerKey})`);
904
+ } else {
905
+ lines.push(`ℹ SIGNATURE: ABSENT (No agent attestation embedded)`);
906
+ }
907
+ lines.push(`--------------------------------------------------`);
908
+ if (result.error) {
909
+ lines.push(`❌ ERROR: ${result.error}`);
910
+ } else {
911
+ lines.push(result.ok ? `✅ VERIFICATION PASSED` : `❌ VERIFICATION FAILED`);
912
+ }
913
+ return lines.join('\n');
914
+ }
915
+
221
916
  program.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nirium-cli",
3
- "version": "1.0.5",
3
+ "version": "1.1.0",
4
4
  "description": "Nirium CLI — scaffold Stellar agent projects and check agent status",
5
5
  "main": "bin/nirium.js",
6
6
  "type": "module",
@@ -22,7 +22,10 @@
22
22
  "license": "Apache-2.0",
23
23
  "dependencies": {
24
24
  "axios": "^1.13.6",
25
- "commander": "^11.0.0"
25
+ "commander": "^11.0.0",
26
+ "nirium": "^0.13.0",
27
+ "express": "^5.1.0",
28
+ "@stellar/stellar-sdk": "^14.5.0"
26
29
  },
27
30
  "devDependencies": {
28
31
  "@types/node": "^20.19.30",