nirium-cli 3.1.1 → 3.2.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.
- package/README.md +399 -402
- package/bin/nirium.js +2109 -2103
- package/package.json +66 -66
package/bin/nirium.js
CHANGED
|
@@ -1,2103 +1,2109 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// ═══════════════════════════════════════════════════════════════
|
|
4
|
-
// Nirium — Autonomous Agent CLI (v2.0.1)
|
|
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.
|
|
12
|
-
|
|
13
|
-
import { Command, Option } from 'commander';
|
|
14
|
-
import fs from 'fs';
|
|
15
|
-
import path from 'path';
|
|
16
|
-
import os from 'os';
|
|
17
|
-
import crypto from 'crypto';
|
|
18
|
-
import readline from 'readline';
|
|
19
|
-
import { execSync } from 'child_process';
|
|
20
|
-
import { fileURLToPath } from 'url';
|
|
21
|
-
import express from 'express';
|
|
22
|
-
import { Agent as NiriumAgent, x402Serve } from 'nirium';
|
|
23
|
-
import { Keypair, StrKey } from '@stellar/stellar-sdk';
|
|
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
|
-
|
|
38
|
-
const program = new Command();
|
|
39
|
-
|
|
40
|
-
program
|
|
41
|
-
.name('nirium')
|
|
42
|
-
.description('Nirium protocol development tool')
|
|
43
|
-
.version(readCliVersion());
|
|
44
|
-
|
|
45
|
-
// --- COMMAND: create bot ---
|
|
46
|
-
program
|
|
47
|
-
.command('create')
|
|
48
|
-
.argument('<type>', 'What to create: x402 (a server that charges) or bot (a signal listener)')
|
|
49
|
-
.option('-n, --name <name>', 'Name of the project', 'nirium-bot-v1')
|
|
50
|
-
.option('-t, --template <template>', 'Language template (ts, py) — bot only', 'ts')
|
|
51
|
-
.description('Scaffold a new Nirium project')
|
|
52
|
-
.action(async (type, options) => {
|
|
53
|
-
if (type !== 'bot' && type !== 'x402') {
|
|
54
|
-
console.error('❌ Error: type must be "x402" (charge for your API) or "bot" (listen to signals).');
|
|
55
|
-
process.exit(1);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const targetDir = path.join(process.cwd(), options.name);
|
|
59
|
-
|
|
60
|
-
if (fs.existsSync(targetDir)) {
|
|
61
|
-
console.error(`❌ Error: Directory ${options.name} already exists.`);
|
|
62
|
-
process.exit(1);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
console.log(type === 'x402'
|
|
66
|
-
? `\n💸 [Scaffold] Creating x402 paid API: ${options.name}...`
|
|
67
|
-
: `\n🧬 [Scaffold] Creating ${options.template === 'ts' ? 'TypeScript' : 'Python'} bot: ${options.name}...`);
|
|
68
|
-
|
|
69
|
-
fs.mkdirSync(targetDir, { recursive: true });
|
|
70
|
-
|
|
71
|
-
if (type === 'x402') {
|
|
72
|
-
scaffoldX402(targetDir, options.name);
|
|
73
|
-
} else if (options.template === 'ts') {
|
|
74
|
-
scaffoldTS(targetDir, options.name);
|
|
75
|
-
} else {
|
|
76
|
-
scaffoldPY(targetDir, options.name);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
console.log(`\n✅ Project initialized in ./${options.name}`);
|
|
80
|
-
console.log(`\n🚀 Get started:`);
|
|
81
|
-
console.log(` cd ${options.name}`);
|
|
82
|
-
if (options.template === 'ts') {
|
|
83
|
-
console.log(` npm install`);
|
|
84
|
-
console.log(` npm run dev`);
|
|
85
|
-
} else {
|
|
86
|
-
console.log(` python -m venv venv`);
|
|
87
|
-
console.log(` source venv/bin/activate`);
|
|
88
|
-
console.log(` pip install -r requirements.txt`);
|
|
89
|
-
console.log(` python main.py`);
|
|
90
|
-
}
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
// --- COMMAND: status ---
|
|
94
|
-
program
|
|
95
|
-
.command('status')
|
|
96
|
-
.description('Check agent connection status')
|
|
97
|
-
.option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
|
|
98
|
-
.option('--json', 'Output the raw /health fields plus ok, as JSON')
|
|
99
|
-
.option('--timeout <ms>', 'Give up after this many milliseconds', '5000')
|
|
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;
|
|
113
|
-
try {
|
|
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) {
|
|
147
|
-
console.log(` Version: ${data.version}`);
|
|
148
|
-
}
|
|
149
|
-
if (data?.network !== undefined && data.network !== null) {
|
|
150
|
-
console.log(` Network: ${data.network}`);
|
|
151
|
-
}
|
|
152
|
-
if (data?.uptime !== undefined && data.uptime !== null) {
|
|
153
|
-
console.log(` Uptime: ${data.uptime}s`);
|
|
154
|
-
}
|
|
155
|
-
} else {
|
|
156
|
-
console.log('🔴 Agent returned error:', response.status);
|
|
157
|
-
process.exit(1);
|
|
158
|
-
}
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
// Tried in order when no --gateway is given. ipfs.io and dweb.link answer 429
|
|
162
|
-
// for healthy CIDs under load (#185), and Pinata serves our pins but often
|
|
163
|
-
// takes 5-7s, so a dedicated gateway goes first. Same chain as the
|
|
164
|
-
// verify-audit-cid Action (#259), plus Pinata.
|
|
165
|
-
const DEFAULT_GATEWAYS = [
|
|
166
|
-
'https://nirium.myfilebase.com',
|
|
167
|
-
'https://gateway.pinata.cloud',
|
|
168
|
-
'https://ipfs.io',
|
|
169
|
-
'https://dweb.link',
|
|
170
|
-
];
|
|
171
|
-
|
|
172
|
-
// --- COMMAND: verify ---
|
|
173
|
-
program
|
|
174
|
-
.command('verify')
|
|
175
|
-
.argument('<cid>', 'IPFS Content Identifier (CID) of the audit document')
|
|
176
|
-
.option('-g, --gateway <url>', 'IPFS gateway URL - repeatable, tried in order as fallbacks (default: Filebase, Pinata, ipfs.io, dweb.link)', (val, prev) => [...(prev || []), val], [])
|
|
177
|
-
.option('--retries <n>', 'Retries per gateway on a 404 (content may not be propagated yet), with backoff', '2')
|
|
178
|
-
.option('--timeout <ms>', 'Per-request timeout in milliseconds', '8000')
|
|
179
|
-
.option('--json', 'Output result as JSON')
|
|
180
|
-
.option('--hash <hex>', 'Expected sha-256 of the evidence (hex, optional sha-256: prefix), for hash-only anchors')
|
|
181
|
-
.option('--evidence <file>', 'Original evidence file; its sha-256 is compared with the anchored hash')
|
|
182
|
-
.description('Independently verify IPFS audit document content hash & agent ed25519 signature')
|
|
183
|
-
.action(async (cid, options) => {
|
|
184
|
-
let expectedHash;
|
|
185
|
-
try {
|
|
186
|
-
if (options.hash && options.evidence) throw new Error('Use either --hash or --evidence, not both');
|
|
187
|
-
if (options.hash) expectedHash = normalizeHashInput(options.hash);
|
|
188
|
-
if (options.evidence) expectedHash = crypto.createHash('sha256').update(fs.readFileSync(options.evidence)).digest('hex');
|
|
189
|
-
} catch (err) {
|
|
190
|
-
console.error(`❌ ${err.message}`);
|
|
191
|
-
process.exit(1);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
const retries = Number(options.retries);
|
|
195
|
-
const timeoutMs = Number(options.timeout);
|
|
196
|
-
if (!Number.isInteger(retries) || retries < 0) {
|
|
197
|
-
console.error(`❌ Error: Invalid --retries '${options.retries}': must be a non-negative integer.`);
|
|
198
|
-
process.exit(1);
|
|
199
|
-
}
|
|
200
|
-
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
201
|
-
console.error(`❌ Error: Invalid --timeout '${options.timeout}': must be a positive number of milliseconds.`);
|
|
202
|
-
process.exit(1);
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
const gateways = options.gateway.length > 0 ? options.gateway : DEFAULT_GATEWAYS;
|
|
206
|
-
const result = await fetchAndVerifyCid(cid, gateways, globalThis.fetch, { expectedHash, retries, timeoutMs });
|
|
207
|
-
if (options.json) {
|
|
208
|
-
console.log(JSON.stringify(result, null, 2));
|
|
209
|
-
} else {
|
|
210
|
-
console.log(formatVerifyOutput(result));
|
|
211
|
-
}
|
|
212
|
-
if (!result.ok) {
|
|
213
|
-
process.exit(1);
|
|
214
|
-
}
|
|
215
|
-
});
|
|
216
|
-
|
|
217
|
-
// --- COMMAND: anchor ---
|
|
218
|
-
program
|
|
219
|
-
.command('anchor')
|
|
220
|
-
.description('Anchor a sha-256 hash (or a small JSON record) to IPFS via an Audit Trail node')
|
|
221
|
-
.option('--file <path>', 'Anchor the sha-256 of this file - the file itself is never uploaded')
|
|
222
|
-
.option('--hash <hex>', 'sha-256 hex of your evidence (64 chars, optional sha-256: prefix)')
|
|
223
|
-
.option('--record <json>', 'Small JSON object (max 8KB) to anchor verbatim, e.g. \'{"order":"A-12"}\'')
|
|
224
|
-
.option('--tx <hash>', 'Transaction hash to associate with this anchor')
|
|
225
|
-
.option('--tag <tag>', 'Free-form label for this anchor')
|
|
226
|
-
.option('--sign', 'Attach an ed25519 attestation of which key produced this anchor')
|
|
227
|
-
.option('--key-env <VAR>', 'Environment variable holding the Stellar secret key to sign with (--sign only; default: the config store\'s secretKey)')
|
|
228
|
-
.option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
|
|
229
|
-
.option('--json', 'Output result as JSON')
|
|
230
|
-
.action(async (options) => {
|
|
231
|
-
await executeAnchorCommand(options);
|
|
232
|
-
});
|
|
233
|
-
|
|
234
|
-
// --- COMMAND: doctor ---
|
|
235
|
-
program
|
|
236
|
-
.command('doctor')
|
|
237
|
-
.description('CLI preflight diagnostics for x402 misconfiguration (the MPP check only validates config), or a remote seller with --seller')
|
|
238
|
-
.option('-n, --network <network>', 'Stellar network: testnet or pubnet', 'testnet')
|
|
239
|
-
.option('-c, --config <path>', 'Path to environment or config file')
|
|
240
|
-
.option('--seller <url>', 'Validate a remote x402 seller at this URL without paying')
|
|
241
|
-
.option('--json', 'Output results as JSON for CI integration')
|
|
242
|
-
.action(async (options) => {
|
|
243
|
-
const report = options.seller
|
|
244
|
-
? await runDoctorSeller(options.seller)
|
|
245
|
-
: await runDoctorDiagnostics(options);
|
|
246
|
-
if (options.json) {
|
|
247
|
-
console.log(JSON.stringify(report, null, 2));
|
|
248
|
-
} else {
|
|
249
|
-
console.log(formatDoctorOutput(report));
|
|
250
|
-
}
|
|
251
|
-
if (!report.ok) {
|
|
252
|
-
process.exit(1);
|
|
253
|
-
}
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
// --- COMMAND: pay ---
|
|
257
|
-
program
|
|
258
|
-
.command('pay')
|
|
259
|
-
.description('💳 Pay an x402-protected endpoint straight from the terminal with Stellar auth entry signing')
|
|
260
|
-
.argument('<url>', 'URL of the x402-protected endpoint')
|
|
261
|
-
.option('--max-amount <usd>', 'Refuse to pay more than this, e.g. 5 or $0.50 (default: no cap beyond the SDK default)')
|
|
262
|
-
.option('-n, --network <network>', 'CAIP-2 network ID (stellar:testnet or stellar:pubnet)', 'stellar:testnet')
|
|
263
|
-
.option('-c, --config <path>', 'Custom path to configuration file or .env')
|
|
264
|
-
.option('--json', 'Output execution result as JSON')
|
|
265
|
-
.action(async (url, options) => {
|
|
266
|
-
await executePayCommand(url, options);
|
|
267
|
-
});
|
|
268
|
-
|
|
269
|
-
// --- COMMAND: serve ---
|
|
270
|
-
program
|
|
271
|
-
.command('serve')
|
|
272
|
-
.description('🚀 Spin up a local x402-protected demo HTTP server to test payments against')
|
|
273
|
-
.option('-p, --price <price>', 'Price for access (e.g. $0.02)', '$0.02')
|
|
274
|
-
.option('-P, --pay-to <address>', 'Stellar public key (G...) to receive payments')
|
|
275
|
-
.option('--port <port>', 'Port number to listen on', '3000')
|
|
276
|
-
.option('-n, --network <network>', 'CAIP-2 network ID (stellar:testnet or stellar:pubnet)', 'stellar:testnet')
|
|
277
|
-
.option('-r, --route <route>', 'Route path to protect', '/api/v1/data')
|
|
278
|
-
// Kept only to refuse it with a clear message: commander's own
|
|
279
|
-
// "unknown option" would not tell the user the key is now exposed.
|
|
280
|
-
.addOption(new Option('-k, --api-key <key>').hideHelp())
|
|
281
|
-
.option('-c, --config <path>', 'Custom path to config file')
|
|
282
|
-
.action(async (options) => {
|
|
283
|
-
await executeServeCommand(options);
|
|
284
|
-
});
|
|
285
|
-
|
|
286
|
-
// --- COMMAND: config ---
|
|
287
|
-
program
|
|
288
|
-
.command('config')
|
|
289
|
-
.description('⚙️ Manage local CLI configuration store (~/.niriumrc.json)')
|
|
290
|
-
.argument('[action]', 'Action to perform: set, get, list, or delete', 'list')
|
|
291
|
-
.argument('[key]', 'Configuration key name')
|
|
292
|
-
.argument('[value]', 'Value to set for the configuration key')
|
|
293
|
-
.action(async (action, key, value) => {
|
|
294
|
-
await executeConfigCommand(action, key, value);
|
|
295
|
-
});
|
|
296
|
-
|
|
297
|
-
// --- COMMAND: report ---
|
|
298
|
-
const reportCommand = program
|
|
299
|
-
.command('report')
|
|
300
|
-
.description('📊 Institutional-format summaries and exports from the Reporting node - not certified regulatory reporting');
|
|
301
|
-
|
|
302
|
-
reportCommand
|
|
303
|
-
.command('summary')
|
|
304
|
-
.description('Aggregate payroll, payments, and anchors for a period')
|
|
305
|
-
.option('--from <date>', 'ISO date, start of period (default: a 30-day window)')
|
|
306
|
-
.option('--to <date>', 'ISO date, end of period')
|
|
307
|
-
.option('--network <network>', 'testnet or mainnet (default: all)')
|
|
308
|
-
.option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
|
|
309
|
-
.option('--json', 'Output as JSON')
|
|
310
|
-
.action(async (options) => {
|
|
311
|
-
await executeReportSummaryCommand(options);
|
|
312
|
-
});
|
|
313
|
-
|
|
314
|
-
reportCommand
|
|
315
|
-
.command('export')
|
|
316
|
-
.argument('<type>', 'anchors, payments, or payroll')
|
|
317
|
-
.description('Export rows for a period - "export anchors" prints one CID per line, pipeable to `nirium verify`')
|
|
318
|
-
.option('--from <date>', 'ISO date, start of period (default: a 30-day window)')
|
|
319
|
-
.option('--to <date>', 'ISO date, end of period')
|
|
320
|
-
.option('--limit <n>', 'Max rows (server caps at 1000)')
|
|
321
|
-
.option('--network <network>', 'testnet or mainnet (default: all)')
|
|
322
|
-
.option('--csv <file>', 'Write the CSV export to this file instead of printing rows')
|
|
323
|
-
.option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
|
|
324
|
-
.option('--json', 'Output the full JSON response instead of one row per line')
|
|
325
|
-
.action(async (type, options) => {
|
|
326
|
-
await executeReportExportCommand(type, options);
|
|
327
|
-
});
|
|
328
|
-
|
|
329
|
-
// Un servidor que COBRA, no uno que escucha. Es el camino corto de
|
|
330
|
-
// "instalé algo" a "me pagaron": levantas esto, le pegas con un cliente
|
|
331
|
-
// x402 y el pago se liquida on-chain antes de que salga la respuesta.
|
|
332
|
-
function scaffoldX402(dir, name) {
|
|
333
|
-
const pkgJson = {
|
|
334
|
-
name,
|
|
335
|
-
version: '0.1.0',
|
|
336
|
-
private: true,
|
|
337
|
-
type: 'module',
|
|
338
|
-
scripts: { dev: 'tsx watch src/server.ts', build: 'tsc' },
|
|
339
|
-
dependencies: {
|
|
340
|
-
nirium: '^0.16.0',
|
|
341
|
-
express: '^5.1.0',
|
|
342
|
-
'@x402/express': '^2.17.0',
|
|
343
|
-
'@x402/core': '^2.17.0',
|
|
344
|
-
'@x402/stellar': '^2.17.0',
|
|
345
|
-
tsx: '^4.19.0',
|
|
346
|
-
typescript: '^5.7.0',
|
|
347
|
-
dotenv: '^16.4.5',
|
|
348
|
-
},
|
|
349
|
-
devDependencies: { '@types/node': '^20.19.0', '@types/express': '^5.0.0' },
|
|
350
|
-
};
|
|
351
|
-
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkgJson, null, 2));
|
|
352
|
-
|
|
353
|
-
fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
|
|
354
|
-
fs.writeFileSync(path.join(dir, 'src', 'server.ts'), `
|
|
355
|
-
import express from 'express';
|
|
356
|
-
import { x402Serve } from 'nirium';
|
|
357
|
-
import 'dotenv/config';
|
|
358
|
-
|
|
359
|
-
const app = express();
|
|
360
|
-
|
|
361
|
-
// Todo lo que va debajo de /premium cobra antes de responder.
|
|
362
|
-
// El pago se liquida on-chain: si no pagaron, tu handler nunca corre.
|
|
363
|
-
app.use('/premium', x402Serve({
|
|
364
|
-
payTo: process.env.STELLAR_PAY_TO!, // tu cuenta G...
|
|
365
|
-
facilitatorApiKey: process.env.X402_FACILITATOR_API_KEY!,
|
|
366
|
-
network: (process.env.STELLAR_NETWORK === 'mainnet' ? 'stellar:pubnet' : 'stellar:testnet'),
|
|
367
|
-
routes: {
|
|
368
|
-
'GET /signals': '$0.02',
|
|
369
|
-
},
|
|
370
|
-
}));
|
|
371
|
-
|
|
372
|
-
app.get('/premium/signals', (_req, res) => {
|
|
373
|
-
res.json({ signals: [{ pair: 'USDC/CETES', edge: '0.42%' }] });
|
|
374
|
-
});
|
|
375
|
-
|
|
376
|
-
app.listen(3000, () => console.log('💸 cobrando en http://localhost:3000/premium/signals'));
|
|
377
|
-
`.trimStart());
|
|
378
|
-
|
|
379
|
-
fs.writeFileSync(path.join(dir, '.env'),
|
|
380
|
-
'STELLAR_PAY_TO=\n'
|
|
381
|
-
+ '# Llave GRATIS y POR RED — una de mainnet da 401 contra testnet:\n'
|
|
382
|
-
+ '# testnet https://channels.openzeppelin.com/testnet/gen\n'
|
|
383
|
-
+ '# mainnet https://channels.openzeppelin.com/gen\n'
|
|
384
|
-
+ 'X402_FACILITATOR_API_KEY=\n'
|
|
385
|
-
+ 'STELLAR_NETWORK=testnet\n');
|
|
386
|
-
|
|
387
|
-
fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
|
|
388
|
-
compilerOptions: {
|
|
389
|
-
target: 'ES2022', module: 'ESNext', moduleResolution: 'bundler',
|
|
390
|
-
strict: true, esModuleInterop: true, skipLibCheck: true, outDir: 'dist',
|
|
391
|
-
},
|
|
392
|
-
include: ['src'],
|
|
393
|
-
}, null, 2));
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
function scaffoldTS(dir, name) {
|
|
397
|
-
const pkgJson = {
|
|
398
|
-
name,
|
|
399
|
-
version: '0.1.0',
|
|
400
|
-
private: true,
|
|
401
|
-
scripts: {
|
|
402
|
-
"dev": "tsx watch src/index.ts",
|
|
403
|
-
"build": "tsc"
|
|
404
|
-
},
|
|
405
|
-
dependencies: {
|
|
406
|
-
"nirium": "^0.16.0",
|
|
407
|
-
"tsx": "^4.19.0",
|
|
408
|
-
"typescript": "^5.7.0",
|
|
409
|
-
"dotenv": "^16.4.5"
|
|
410
|
-
},
|
|
411
|
-
devDependencies: {
|
|
412
|
-
"@types/node": "^20.19.0"
|
|
413
|
-
}
|
|
414
|
-
};
|
|
415
|
-
|
|
416
|
-
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkgJson, null, 2));
|
|
417
|
-
fs.mkdirSync(path.join(dir, 'src'));
|
|
418
|
-
|
|
419
|
-
const indexSrc = `
|
|
420
|
-
import { Agent } from 'nirium';
|
|
421
|
-
import 'dotenv/config';
|
|
422
|
-
|
|
423
|
-
const agent = new Agent({
|
|
424
|
-
baseUrl: process.env.NIRIUM_API_URL || 'https://nirium-agent.fly.dev',
|
|
425
|
-
apiKey: process.env.NIRIUM_API_KEY
|
|
426
|
-
});
|
|
427
|
-
|
|
428
|
-
agent.subscribe((signal) => {
|
|
429
|
-
console.log('🧬 [Signal Received]:', signal.signal_type, signal.pair);
|
|
430
|
-
// Logic to execute on signals...
|
|
431
|
-
});
|
|
432
|
-
|
|
433
|
-
console.log('✅ Listening for Nirium signals...');
|
|
434
|
-
`;
|
|
435
|
-
fs.writeFileSync(path.join(dir, 'src', 'index.ts'), indexSrc);
|
|
436
|
-
fs.writeFileSync(path.join(dir, '.env'), 'NIRIUM_API_URL=https://nirium-agent.fly.dev\nNIRIUM_API_KEY=');
|
|
437
|
-
fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
|
|
438
|
-
compilerOptions: {
|
|
439
|
-
target: "es2022",
|
|
440
|
-
module: "nodenext",
|
|
441
|
-
strict: true,
|
|
442
|
-
esModuleInterop: true,
|
|
443
|
-
skipLibCheck: true
|
|
444
|
-
}
|
|
445
|
-
}, null, 2));
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
function scaffoldPY(dir, name) {
|
|
449
|
-
const reqs = "nirium>=0.9.0\npython-dotenv>=1.0.0";
|
|
450
|
-
fs.writeFileSync(path.join(dir, 'requirements.txt'), reqs);
|
|
451
|
-
|
|
452
|
-
const mainSrc = `
|
|
453
|
-
import asyncio
|
|
454
|
-
import os
|
|
455
|
-
from nirium import Agent
|
|
456
|
-
from dotenv import load_dotenv
|
|
457
|
-
|
|
458
|
-
load_dotenv()
|
|
459
|
-
|
|
460
|
-
async def main():
|
|
461
|
-
agent = Agent(
|
|
462
|
-
api_url=os.getenv("NIRIUM_API_URL", "https://nirium-agent.fly.dev"),
|
|
463
|
-
api_key=os.getenv("NIRIUM_API_KEY")
|
|
464
|
-
)
|
|
465
|
-
|
|
466
|
-
@agent.on("signal")
|
|
467
|
-
async def handle_signal(signal):
|
|
468
|
-
print(f"🧬 [Signal]: {signal['signal_type']} on {signal['pair']}")
|
|
469
|
-
|
|
470
|
-
@agent.on("connected")
|
|
471
|
-
async def on_connect(data):
|
|
472
|
-
print("✅ Connected to Nirium Neural Loop")
|
|
473
|
-
|
|
474
|
-
await agent.subscribe()
|
|
475
|
-
|
|
476
|
-
if __name__ == "__main__":
|
|
477
|
-
asyncio.run(main())
|
|
478
|
-
`;
|
|
479
|
-
fs.writeFileSync(path.join(dir, 'main.py'), mainSrc);
|
|
480
|
-
fs.writeFileSync(path.join(dir, '.env'), 'NIRIUM_API_URL=https://nirium-agent.fly.dev\nNIRIUM_API_KEY=');
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
// ═══════════════════════════════════════════════════════════════
|
|
484
|
-
// config — ~/.niriumrc.json store, shared by pay/serve/config
|
|
485
|
-
// ═══════════════════════════════════════════════════════════════
|
|
486
|
-
|
|
487
|
-
const CONFIG_FILE = path.join(os.homedir(), '.niriumrc.json');
|
|
488
|
-
|
|
489
|
-
function loadConfig(customPath) {
|
|
490
|
-
const filePath = customPath || CONFIG_FILE;
|
|
491
|
-
try {
|
|
492
|
-
if (fs.existsSync(filePath)) {
|
|
493
|
-
const raw = fs.readFileSync(filePath, 'utf8');
|
|
494
|
-
return JSON.parse(raw);
|
|
495
|
-
}
|
|
496
|
-
} catch {
|
|
497
|
-
// Ignore read errors gracefully
|
|
498
|
-
}
|
|
499
|
-
return {};
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
function saveConfig(config, customPath) {
|
|
503
|
-
const filePath = customPath || CONFIG_FILE;
|
|
504
|
-
try {
|
|
505
|
-
fs.writeFileSync(filePath, JSON.stringify(config, null, 2), {
|
|
506
|
-
encoding: 'utf8',
|
|
507
|
-
mode: 0o600,
|
|
508
|
-
});
|
|
509
|
-
// Enforce permissions even on pre-existing files (writeFileSync mode
|
|
510
|
-
// only applies when the file is created, not when it already exists).
|
|
511
|
-
try {
|
|
512
|
-
fs.chmodSync(filePath, 0o600);
|
|
513
|
-
} catch {
|
|
514
|
-
// best effort on platforms without POSIX permissions (e.g. some Windows setups)
|
|
515
|
-
}
|
|
516
|
-
} catch (err) {
|
|
517
|
-
throw new Error(`Failed to save config to ${filePath}: ${err?.message || String(err)}`);
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
function maskSecret(secret) {
|
|
522
|
-
if (!secret) return '(not set)';
|
|
523
|
-
if (secret.length <= 8) return 'S****';
|
|
524
|
-
return `${secret.slice(0, 4)}...${secret.slice(-4)}`;
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
// `--max-amount` is a USD figure ("5", "$5", "0.50"), not atomic units.
|
|
528
|
-
// Rejects 0, negative and non-numeric so a typo fails before any network
|
|
529
|
-
// call instead of silently capping at $0 or NaN (which compares false to
|
|
530
|
-
// everything and would let every payment through).
|
|
531
|
-
function parseMaxAmountUsd(raw) {
|
|
532
|
-
const stripped = raw.startsWith('$') ? raw.slice(1) : raw;
|
|
533
|
-
const usd = Number(stripped);
|
|
534
|
-
if (!Number.isFinite(usd) || usd <= 0) {
|
|
535
|
-
throw new Error(`Invalid --max-amount '${raw}': must be a positive USD amount, e.g. --max-amount 5 or --max-amount '$0.50'.`);
|
|
536
|
-
}
|
|
537
|
-
return usd;
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
// A secret passed as a CLI argument sits in the shell history file and
|
|
541
|
-
// in `ps`'s full command line for anyone else on the machine to read —
|
|
542
|
-
// true for any process, not just this one. `pay` used to take `--secret`
|
|
543
|
-
// for exactly that reason, so this prompt is the replacement: it reads
|
|
544
|
-
// from the terminal without echoing the input and without it ever
|
|
545
|
-
// becoming a process argument. Only used when neither NIRIUM_SECRET_KEY
|
|
546
|
-
// nor the config store already has a key.
|
|
547
|
-
function promptHiddenSecret(question) {
|
|
548
|
-
return new Promise((resolve, reject) => {
|
|
549
|
-
if (!process.stdin.isTTY) {
|
|
550
|
-
reject(new Error('no interactive terminal to prompt on'));
|
|
551
|
-
return;
|
|
552
|
-
}
|
|
553
|
-
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
554
|
-
// readline always echoes keystrokes to `output`; the only hook it
|
|
555
|
-
// gives you to stop that is overriding the writer it calls internally.
|
|
556
|
-
const realWrite = rl._writeToOutput;
|
|
557
|
-
rl._writeToOutput = function (str) {
|
|
558
|
-
// Pass the prompt text itself through once, then swallow every
|
|
559
|
-
// character typed after it — nothing from the secret reaches
|
|
560
|
-
// the terminal, not even asterisks that could leak its length.
|
|
561
|
-
if (str === question) realWrite.call(rl, str);
|
|
562
|
-
};
|
|
563
|
-
rl.question(question, (answer) => {
|
|
564
|
-
rl.history = rl.history.slice(1); // readline records the answer in its own history buffer
|
|
565
|
-
rl._writeToOutput = realWrite;
|
|
566
|
-
rl.close();
|
|
567
|
-
process.stdout.write('\n');
|
|
568
|
-
resolve(answer.trim());
|
|
569
|
-
});
|
|
570
|
-
});
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
// Credentials that `config set` never takes as an argument.
|
|
574
|
-
const SECRET_CONFIG_KEYS = {
|
|
575
|
-
secretKey: {
|
|
576
|
-
prompt: 'Stellar secret key (S...): ',
|
|
577
|
-
valid: (v) => StrKey.isValidEd25519SecretSeed(v),
|
|
578
|
-
invalid: 'not a valid Stellar secret key (expected S...).',
|
|
579
|
-
},
|
|
580
|
-
facilitatorApiKey: {
|
|
581
|
-
prompt: 'Facilitator API key: ',
|
|
582
|
-
valid: (v) => typeof v === 'string' && v.length > 0,
|
|
583
|
-
invalid: 'the facilitator API key is empty.',
|
|
584
|
-
},
|
|
585
|
-
};
|
|
586
|
-
|
|
587
|
-
// Hidden prompt on a terminal, stdin otherwise. Never a process argument.
|
|
588
|
-
// `timeoutMs` (stdin only) resolves to '' when nothing finishes arriving in
|
|
589
|
-
// time, so a caller that has no other source for the value can fail with its
|
|
590
|
-
// own "missing key" error instead of waiting on a pipe that never closes.
|
|
591
|
-
async function readSecretInput(question, { timeoutMs } = {}) {
|
|
592
|
-
if (process.stdin.isTTY) return promptHiddenSecret(question);
|
|
593
|
-
const read = (async () => {
|
|
594
|
-
const chunks = [];
|
|
595
|
-
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
596
|
-
return Buffer.concat(chunks).toString('utf8').trim();
|
|
597
|
-
})();
|
|
598
|
-
if (!timeoutMs) return read;
|
|
599
|
-
let timer;
|
|
600
|
-
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(''), timeoutMs); });
|
|
601
|
-
try {
|
|
602
|
-
return await Promise.race([read, timeout]);
|
|
603
|
-
} finally {
|
|
604
|
-
clearTimeout(timer);
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
const SERVE_STDIN_TIMEOUT_MS = Number(process.env.NIRIUM_STDIN_TIMEOUT_MS) || 10_000;
|
|
609
|
-
|
|
610
|
-
async function executeConfigCommand(action, key, value) {
|
|
611
|
-
const currentConfig = loadConfig();
|
|
612
|
-
|
|
613
|
-
if (!action || action === 'list') {
|
|
614
|
-
console.log('⚙️ Nirium CLI Configuration:');
|
|
615
|
-
console.log(` secretKey: ${maskSecret(currentConfig.secretKey)}`);
|
|
616
|
-
console.log(` payTo: ${currentConfig.payTo || '(not set)'}`);
|
|
617
|
-
console.log(` network: ${currentConfig.network || '(default: stellar:testnet)'}`);
|
|
618
|
-
console.log(` facilitatorApiKey: ${maskSecret(currentConfig.facilitatorApiKey)}`);
|
|
619
|
-
return;
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
if (action === 'get') {
|
|
623
|
-
if (!key) {
|
|
624
|
-
console.error('❌ Error: Please specify a configuration key (e.g. `nirium config get secretKey`)');
|
|
625
|
-
process.exit(1);
|
|
626
|
-
}
|
|
627
|
-
const val = currentConfig[key];
|
|
628
|
-
if (key.toLowerCase().includes('secret') || key.toLowerCase().includes('key')) {
|
|
629
|
-
console.log(`${key}: ${maskSecret(val)}`);
|
|
630
|
-
} else {
|
|
631
|
-
console.log(`${key}: ${val || '(not set)'}`);
|
|
632
|
-
}
|
|
633
|
-
return;
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
const secretSpec = action === 'set' ? SECRET_CONFIG_KEYS[key] : undefined;
|
|
637
|
-
if (secretSpec) {
|
|
638
|
-
// Same reason `pay` has no --secret: an argument ends up in the shell
|
|
639
|
-
// history file and in `ps` output. Refuse it instead of storing it.
|
|
640
|
-
if (value !== undefined) {
|
|
641
|
-
console.error(`❌ Error: \`nirium config set ${key}\` does not take the value as an argument.\n`
|
|
642
|
-
+ 'A credential typed on the command line stays in your shell history and is visible in `ps` '
|
|
643
|
-
+ 'to other users on this machine, so it was NOT saved. Treat the value you typed as exposed.\n'
|
|
644
|
-
+ `Run \`nirium config set ${key}\` with no value to get a hidden prompt, `
|
|
645
|
-
+ 'or pipe it on stdin from a file or secret manager.');
|
|
646
|
-
process.exit(1);
|
|
647
|
-
}
|
|
648
|
-
const secret = await readSecretInput(secretSpec.prompt);
|
|
649
|
-
if (!secretSpec.valid(secret)) {
|
|
650
|
-
console.error(`❌ Error: ${secretSpec.invalid} Nothing was saved.`);
|
|
651
|
-
process.exit(1);
|
|
652
|
-
}
|
|
653
|
-
saveConfig({ ...currentConfig, [key]: secret });
|
|
654
|
-
console.log(`✅ Configuration updated: ${key} set successfully.`);
|
|
655
|
-
return;
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
if (action === 'set') {
|
|
659
|
-
if (!key || value === undefined) {
|
|
660
|
-
console.error('❌ Error: Usage: `nirium config set <key> <value>` (e.g., `nirium config set payTo G...`). '
|
|
661
|
-
+ 'For secretKey or facilitatorApiKey, run `nirium config set <key>` with no value.');
|
|
662
|
-
process.exit(1);
|
|
663
|
-
}
|
|
664
|
-
const updatedConfig = { ...currentConfig, [key]: value };
|
|
665
|
-
saveConfig(updatedConfig);
|
|
666
|
-
console.log(`✅ Configuration updated: ${key} set successfully.`);
|
|
667
|
-
return;
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
if (action === 'delete' || action === 'remove') {
|
|
671
|
-
if (!key) {
|
|
672
|
-
console.error('❌ Error: Please specify a configuration key to delete.');
|
|
673
|
-
process.exit(1);
|
|
674
|
-
}
|
|
675
|
-
delete currentConfig[key];
|
|
676
|
-
saveConfig(currentConfig);
|
|
677
|
-
console.log(`✅ Removed ${key} from configuration.`);
|
|
678
|
-
return;
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
console.error(`❌ Unknown config action: ${action}. Use set, get, list, or delete.`);
|
|
682
|
-
process.exit(1);
|
|
683
|
-
}
|
|
684
|
-
|
|
685
|
-
// ═══════════════════════════════════════════════════════════════
|
|
686
|
-
// pay — sign and settle an x402 payment from the terminal
|
|
687
|
-
// ═══════════════════════════════════════════════════════════════
|
|
688
|
-
|
|
689
|
-
async function executePayCommand(url, options) {
|
|
690
|
-
const config = loadConfig(options.config);
|
|
691
|
-
const network = options.network || process.env.NIRIUM_NETWORK || config.network || 'stellar:testnet';
|
|
692
|
-
|
|
693
|
-
let maxAmountUsd;
|
|
694
|
-
if (options.maxAmount !== undefined) {
|
|
695
|
-
try {
|
|
696
|
-
maxAmountUsd = parseMaxAmountUsd(options.maxAmount);
|
|
697
|
-
} catch (err) {
|
|
698
|
-
if (options.json) {
|
|
699
|
-
console.log(JSON.stringify({ status: 'error', error: err.message }));
|
|
700
|
-
process.exit(1);
|
|
701
|
-
}
|
|
702
|
-
console.error(`❌ Error: ${err.message}`);
|
|
703
|
-
process.exit(1);
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
let secretKey = process.env.NIRIUM_SECRET_KEY || config.secretKey;
|
|
708
|
-
|
|
709
|
-
// `pay` no longer takes the secret as a flag (see #104): a --secret
|
|
710
|
-
// argument sits in the shell history and in `ps`'s full command line
|
|
711
|
-
// for anyone else on the box to read. Env var and config store are
|
|
712
|
-
// both still fine — neither is visible that way. The remaining gap is
|
|
713
|
-
// a one-off call with nothing configured yet, so prompt for it
|
|
714
|
-
// instead of failing outright, same as any CLI handling a real secret.
|
|
715
|
-
if (!secretKey && !options.json && process.stdin.isTTY) {
|
|
716
|
-
try {
|
|
717
|
-
secretKey = await promptHiddenSecret('Stellar secret key (S...): ');
|
|
718
|
-
} catch {
|
|
719
|
-
// falls through to the same missing-key error below
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
if (!secretKey) {
|
|
724
|
-
const errorMsg = 'Missing secret key for x402 payment authorization.\n'
|
|
725
|
-
+ 'Provide a secret key using:\n'
|
|
726
|
-
+ ' - `NIRIUM_SECRET_KEY` environment variable\n'
|
|
727
|
-
+ ' - the interactive prompt (run without --json, in a real terminal)\n'
|
|
728
|
-
+ 'There is no --secret flag: a key passed as a command-line argument '
|
|
729
|
-
+ 'would sit in your shell history and in `ps` output for anyone else '
|
|
730
|
-
+ 'on the machine to read.';
|
|
731
|
-
if (options.json) {
|
|
732
|
-
console.log(JSON.stringify({ status: 'error', error: errorMsg }));
|
|
733
|
-
process.exit(1);
|
|
734
|
-
}
|
|
735
|
-
console.error(`❌ Error: ${errorMsg}`);
|
|
736
|
-
process.exit(1);
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
let publicKey = '';
|
|
740
|
-
try {
|
|
741
|
-
const kp = Keypair.fromSecret(secretKey);
|
|
742
|
-
publicKey = kp.publicKey();
|
|
743
|
-
} catch (err) {
|
|
744
|
-
const invalidMsg = `Invalid Stellar secret key format: ${err?.message || 'must start with S'}`;
|
|
745
|
-
if (options.json) {
|
|
746
|
-
console.log(JSON.stringify({ status: 'error', error: invalidMsg }));
|
|
747
|
-
process.exit(1);
|
|
748
|
-
}
|
|
749
|
-
console.error(`❌ Error: ${invalidMsg}`);
|
|
750
|
-
process.exit(1);
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
if (!options.json) {
|
|
754
|
-
console.log(`⚡ Initiating x402 Payment Request`);
|
|
755
|
-
console.log(` Target URL: ${url}`);
|
|
756
|
-
console.log(` Network: ${network}`);
|
|
757
|
-
console.log(` Payer Key: ${publicKey}`);
|
|
758
|
-
console.log(` Secret: ${maskSecret(secretKey)}\n`);
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
try {
|
|
762
|
-
const agent = new NiriumAgent({ apiKey: 'nirium-cli-pay' });
|
|
763
|
-
if (maxAmountUsd !== undefined) {
|
|
764
|
-
// `initX402({ maxAmountPerPayment })` does not exist in any published
|
|
765
|
-
// `nirium` version yet (it is unreleased SDK source as of this PR), so
|
|
766
|
-
// --max-amount is enforced with the pre-sign policy hook instead, which
|
|
767
|
-
// IS published (0.16.0+) and runs before anything is signed. Stellar
|
|
768
|
-
// amounts are always int64 scaled by 1e7 regardless of asset, so the
|
|
769
|
-
// USD figure maps directly to atomic units without an asset lookup.
|
|
770
|
-
const capAtomic = BigInt(Math.round(maxAmountUsd * 1e7));
|
|
771
|
-
agent.initX402({
|
|
772
|
-
secretKey, network,
|
|
773
|
-
policy: {
|
|
774
|
-
evaluate: async (ctx) => {
|
|
775
|
-
if (BigInt(ctx.authorization.amount) <= capAtomic) {
|
|
776
|
-
return { decision: 'ALLOW', contextHash: ctx.contextHash };
|
|
777
|
-
}
|
|
778
|
-
return {
|
|
779
|
-
decision: 'DENY',
|
|
780
|
-
reason: `payment of ${ctx.authorization.amount} atomic units exceeds --max-amount ($${maxAmountUsd})`,
|
|
781
|
-
};
|
|
782
|
-
},
|
|
783
|
-
},
|
|
784
|
-
});
|
|
785
|
-
} else {
|
|
786
|
-
agent.initX402({ secretKey, network });
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
const startTime = Date.now();
|
|
790
|
-
const response = await agent.x402Fetch(url, {
|
|
791
|
-
method: 'GET',
|
|
792
|
-
headers: { 'User-Agent': 'Nirium-CLI-Pay/1.0' },
|
|
793
|
-
});
|
|
794
|
-
const durationMs = Date.now() - startTime;
|
|
795
|
-
|
|
796
|
-
const responseHeaders = Object.fromEntries(response.headers.entries());
|
|
797
|
-
const paymentResponseHeader = response.headers.get('payment-response')
|
|
798
|
-
|| response.headers.get('x-payment-response')
|
|
799
|
-
|| response.headers.get('payment-tx-hash')
|
|
800
|
-
|| '';
|
|
801
|
-
|
|
802
|
-
let txHash = '';
|
|
803
|
-
let paymentMeta = null;
|
|
804
|
-
if (paymentResponseHeader) {
|
|
805
|
-
try {
|
|
806
|
-
if (paymentResponseHeader.startsWith('{')) {
|
|
807
|
-
const parsed = JSON.parse(paymentResponseHeader);
|
|
808
|
-
txHash = parsed.txHash || parsed.transactionHash || parsed.hash || '';
|
|
809
|
-
paymentMeta = parsed;
|
|
810
|
-
} else {
|
|
811
|
-
txHash = paymentResponseHeader;
|
|
812
|
-
}
|
|
813
|
-
} catch {
|
|
814
|
-
txHash = paymentResponseHeader;
|
|
815
|
-
}
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
let responseBody;
|
|
819
|
-
const contentType = response.headers.get('content-type') || '';
|
|
820
|
-
if (contentType.includes('application/json')) {
|
|
821
|
-
responseBody = await response.json();
|
|
822
|
-
} else {
|
|
823
|
-
responseBody = await response.text();
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
if (options.json) {
|
|
827
|
-
console.log(JSON.stringify({
|
|
828
|
-
status: response.ok ? 'success' : 'failed',
|
|
829
|
-
statusCode: response.status,
|
|
830
|
-
durationMs,
|
|
831
|
-
payer: publicKey,
|
|
832
|
-
network,
|
|
833
|
-
txHash: txHash || undefined,
|
|
834
|
-
paymentMeta: paymentMeta || undefined,
|
|
835
|
-
headers: responseHeaders,
|
|
836
|
-
data: responseBody,
|
|
837
|
-
}, null, 2));
|
|
838
|
-
if (!response.ok) process.exit(1);
|
|
839
|
-
return;
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
if (response.ok) {
|
|
843
|
-
console.log(`✅ Payment Negotiated & Request Completed (${response.status} ${response.statusText})`);
|
|
844
|
-
} else {
|
|
845
|
-
console.log(`❌ Request Failed After Payment (${response.status} ${response.statusText})`);
|
|
846
|
-
}
|
|
847
|
-
console.log(` Response Time: ${durationMs}ms`);
|
|
848
|
-
if (txHash) {
|
|
849
|
-
console.log(` Tx Reference: ${txHash}`);
|
|
850
|
-
console.log(` Explorer: https://stellar.expert/explorer/${network.includes('testnet') ? 'testnet' : 'public'}/tx/${txHash}`);
|
|
851
|
-
}
|
|
852
|
-
console.log(`\n--- Response Payload ---`);
|
|
853
|
-
console.log(typeof responseBody === 'object' ? JSON.stringify(responseBody, null, 2) : responseBody);
|
|
854
|
-
if (!response.ok) process.exit(1);
|
|
855
|
-
} catch (err) {
|
|
856
|
-
const errorDetail = err?.message || String(err);
|
|
857
|
-
if (options.json) {
|
|
858
|
-
console.log(JSON.stringify({ status: 'error', error: errorDetail, payer: publicKey, network }));
|
|
859
|
-
process.exit(1);
|
|
860
|
-
}
|
|
861
|
-
console.error(`❌ Payment Failed: ${errorDetail}`);
|
|
862
|
-
process.exit(1);
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
// ═══════════════════════════════════════════════════════════════
|
|
867
|
-
// serve — local x402-protected demo server
|
|
868
|
-
// ═══════════════════════════════════════════════════════════════
|
|
869
|
-
|
|
870
|
-
async function executeServeCommand(options) {
|
|
871
|
-
const config = loadConfig(options.config);
|
|
872
|
-
const payTo = options.payTo || process.env.NIRIUM_PAY_TO || config.payTo;
|
|
873
|
-
const price = options.price || '$0.02';
|
|
874
|
-
const port = Number(options.port || process.env.PORT || 3000);
|
|
875
|
-
const network = options.network || process.env.NIRIUM_NETWORK || config.network || 'stellar:testnet';
|
|
876
|
-
const routePath = options.route || '/api/v1/data';
|
|
877
|
-
if (options.apiKey !== undefined) {
|
|
878
|
-
console.error('❌ Error: `nirium serve` no longer takes --api-key.\n'
|
|
879
|
-
+ 'A key passed as a command-line argument stays in your shell history and is visible in `ps` '
|
|
880
|
-
+ 'to other users on this machine, so it was NOT used. Treat the key you typed as exposed.\n'
|
|
881
|
-
+ 'Set FACILITATOR_API_KEY, or run `nirium serve` in a terminal to get a hidden prompt.');
|
|
882
|
-
process.exit(1);
|
|
883
|
-
}
|
|
884
|
-
let facilitatorApiKey = process.env.FACILITATOR_API_KEY || config.facilitatorApiKey;
|
|
885
|
-
if (!facilitatorApiKey) facilitatorApiKey = await readSecretInput('Facilitator API key: ', { timeoutMs: SERVE_STDIN_TIMEOUT_MS });
|
|
886
|
-
|
|
887
|
-
if (!facilitatorApiKey) {
|
|
888
|
-
console.error('❌ Error: Missing facilitator API key.');
|
|
889
|
-
console.error('Get a free key at https://channels.openzeppelin.com/testnet/gen (testnet)');
|
|
890
|
-
console.error('or https://channels.openzeppelin.com/gen (mainnet), then set FACILITATOR_API_KEY');
|
|
891
|
-
console.error('or run `nirium serve` in a terminal to get a hidden prompt.');
|
|
892
|
-
process.exit(1);
|
|
893
|
-
}
|
|
894
|
-
if (!payTo) {
|
|
895
|
-
console.error('❌ Error: Missing `--pay-to` Stellar address (G...).');
|
|
896
|
-
console.error('Please specify a recipient address using `--pay-to G...` or setting `payTo` in config.');
|
|
897
|
-
process.exit(1);
|
|
898
|
-
}
|
|
899
|
-
|
|
900
|
-
const app = express();
|
|
901
|
-
app.use(express.json());
|
|
902
|
-
|
|
903
|
-
const middleware = x402Serve({
|
|
904
|
-
payTo,
|
|
905
|
-
network,
|
|
906
|
-
facilitatorApiKey,
|
|
907
|
-
routes: {
|
|
908
|
-
[`GET ${routePath}`]: { price, description: 'Nirium CLI x402 Demo Endpoint' },
|
|
909
|
-
},
|
|
910
|
-
});
|
|
911
|
-
app.use(middleware);
|
|
912
|
-
|
|
913
|
-
app.get(routePath, (req, res) => {
|
|
914
|
-
res.json({
|
|
915
|
-
status: 'success',
|
|
916
|
-
message: 'x402 Payment Verified! Access Granted.',
|
|
917
|
-
endpoint: routePath,
|
|
918
|
-
price,
|
|
919
|
-
paidTo: payTo,
|
|
920
|
-
timestamp: new Date().toISOString(),
|
|
921
|
-
sampleData: { signal: 'CETES_REBALANCE_OPPORTUNITY', yieldApy: '5.57%', network },
|
|
922
|
-
});
|
|
923
|
-
});
|
|
924
|
-
|
|
925
|
-
return new Promise((resolve, reject) => {
|
|
926
|
-
const server = app.listen(port, () => {
|
|
927
|
-
console.log(`\n🚀 Nirium x402 Demo Server Listening on http://localhost:${port}`);
|
|
928
|
-
console.log(` Protected Route: http://localhost:${port}${routePath}`);
|
|
929
|
-
console.log(` Price: ${price}`);
|
|
930
|
-
console.log(` Pay To: ${payTo}`);
|
|
931
|
-
console.log(` Network: ${network}\n`);
|
|
932
|
-
console.log(`💡 Test this server using:`);
|
|
933
|
-
console.log(` NIRIUM_SECRET_KEY=S... nirium pay http://localhost:${port}${routePath}\n`);
|
|
934
|
-
resolve({ app, server });
|
|
935
|
-
});
|
|
936
|
-
server.on('error', (err) => {
|
|
937
|
-
console.error(`❌ Server startup failed: ${err.message}`);
|
|
938
|
-
reject(err);
|
|
939
|
-
});
|
|
940
|
-
});
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
// ═══════════════════════════════════════════════════════════════
|
|
944
|
-
// doctor — x402/MPP preflight diagnostics
|
|
945
|
-
// ═══════════════════════════════════════════════════════════════
|
|
946
|
-
|
|
947
|
-
function loadEnvFile(filePath) {
|
|
948
|
-
const env = {};
|
|
949
|
-
const targetPath = filePath ? path.resolve(process.cwd(), filePath) : path.resolve(process.cwd(), '.env');
|
|
950
|
-
if (fs.existsSync(targetPath)) {
|
|
951
|
-
try {
|
|
952
|
-
const content = fs.readFileSync(targetPath, 'utf8');
|
|
953
|
-
for (const line of content.split('\n')) {
|
|
954
|
-
const trimmed = line.trim();
|
|
955
|
-
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
956
|
-
const eqIdx = trimmed.indexOf('=');
|
|
957
|
-
if (eqIdx !== -1) {
|
|
958
|
-
const key = trimmed.slice(0, eqIdx).trim();
|
|
959
|
-
let val = trimmed.slice(eqIdx + 1).trim();
|
|
960
|
-
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
|
|
961
|
-
val = val.slice(1, -1);
|
|
962
|
-
}
|
|
963
|
-
env[key] = val;
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
} catch {
|
|
967
|
-
// Ignore file read errors
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
return env;
|
|
971
|
-
}
|
|
972
|
-
|
|
973
|
-
function normalizeNetwork(inputNet) {
|
|
974
|
-
const net = (inputNet || '').toLowerCase();
|
|
975
|
-
if (net === 'pubnet' || net === 'mainnet' || net === 'stellar:pubnet' || net === 'stellar:mainnet') {
|
|
976
|
-
return 'stellar:pubnet';
|
|
977
|
-
}
|
|
978
|
-
return 'stellar:testnet';
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
async function runDoctorDiagnostics(options) {
|
|
982
|
-
const fileEnv = loadEnvFile(options.config);
|
|
983
|
-
const getEnv = (key) => process.env[key] || fileEnv[key] || '';
|
|
984
|
-
|
|
985
|
-
const rawNetwork = options.network || getEnv('STELLAR_NETWORK') || getEnv('NETWORK') || 'testnet';
|
|
986
|
-
const canonicalNetwork = normalizeNetwork(rawNetwork);
|
|
987
|
-
const isTestnet = canonicalNetwork === 'stellar:testnet';
|
|
988
|
-
const checks = [];
|
|
989
|
-
|
|
990
|
-
// Check 1: payTo address
|
|
991
|
-
const payTo = getEnv('STELLAR_PAY_TO') || getEnv('PAY_TO') || getEnv('NIRIUM_X402_PAY_TO') || getEnv('STELLAR_PAYTO');
|
|
992
|
-
if (!payTo) {
|
|
993
|
-
checks.push({
|
|
994
|
-
name: 'payTo', status: 'fail', message: 'payTo address is missing',
|
|
995
|
-
fix: 'Set STELLAR_PAY_TO in .env to a valid Stellar public key starting with G...',
|
|
996
|
-
});
|
|
997
|
-
} else if (payTo.startsWith('S')) {
|
|
998
|
-
checks.push({
|
|
999
|
-
name: 'payTo', status: 'fail', message: 'payTo address is a secret key (S...), not a public key',
|
|
1000
|
-
fix: 'Replace STELLAR_PAY_TO with your public key (G...). Secret keys must never be exposed as payTo.',
|
|
1001
|
-
detail: `Value starts with '${payTo.slice(0, 4)}...'`,
|
|
1002
|
-
});
|
|
1003
|
-
} else if (!/^G[A-Z2-7]{55}$/.test(payTo)) {
|
|
1004
|
-
checks.push({
|
|
1005
|
-
name: 'payTo', status: 'fail', message: 'payTo address is invalid (must be a 56-character Stellar G... address)',
|
|
1006
|
-
fix: 'Ensure STELLAR_PAY_TO is a valid 56-char Stellar public key.',
|
|
1007
|
-
detail: `Length: ${payTo.length}`,
|
|
1008
|
-
});
|
|
1009
|
-
} else {
|
|
1010
|
-
checks.push({
|
|
1011
|
-
name: 'payTo', status: 'pass',
|
|
1012
|
-
message: `payTo address is a valid Stellar public key (${payTo.slice(0, 4)}...${payTo.slice(-4)})`,
|
|
1013
|
-
detail: payTo,
|
|
1014
|
-
});
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
// Check 2: Facilitator API key & reachability
|
|
1018
|
-
const facilitatorApiKey = getEnv('X402_FACILITATOR_API_KEY') || getEnv('STELLAR_FACILITATOR_API_KEY') || getEnv('FACILITATOR_API_KEY');
|
|
1019
|
-
const defaultFacilitatorUrl = isTestnet ? 'https://channels.openzeppelin.com/x402/testnet' : 'https://channels.openzeppelin.com/x402';
|
|
1020
|
-
const facilitatorUrl = getEnv('FACILITATOR_URL') || getEnv('X402_FACILITATOR_URL') || defaultFacilitatorUrl;
|
|
1021
|
-
const customFetch = options.fetchFn || globalThis.fetch;
|
|
1022
|
-
|
|
1023
|
-
if (!facilitatorApiKey && !getEnv('FACILITATOR_URL')) {
|
|
1024
|
-
const genUrl = isTestnet ? 'https://channels.openzeppelin.com/testnet/gen' : 'https://channels.openzeppelin.com/gen';
|
|
1025
|
-
checks.push({
|
|
1026
|
-
name: 'facilitator', status: 'fail',
|
|
1027
|
-
message: 'facilitatorApiKey is missing — OpenZeppelin Channels facilitator rejects unauthenticated requests',
|
|
1028
|
-
fix: `Get a free ${rawNetwork} key at ${genUrl} and set X402_FACILITATOR_API_KEY in .env`,
|
|
1029
|
-
});
|
|
1030
|
-
} else {
|
|
1031
|
-
try {
|
|
1032
|
-
const headers = {};
|
|
1033
|
-
if (facilitatorApiKey) headers['Authorization'] = `Bearer ${facilitatorApiKey}`;
|
|
1034
|
-
const response = await customFetch(`${facilitatorUrl}/supported`, { headers, signal: AbortSignal.timeout(5000) });
|
|
1035
|
-
if (response.ok) {
|
|
1036
|
-
checks.push({
|
|
1037
|
-
name: 'facilitator', status: 'pass',
|
|
1038
|
-
message: `Facilitator reachable and API key authenticated on ${rawNetwork}`,
|
|
1039
|
-
detail: facilitatorUrl,
|
|
1040
|
-
});
|
|
1041
|
-
} else if (response.status === 401 || response.status === 403) {
|
|
1042
|
-
const genUrl = isTestnet ? 'https://channels.openzeppelin.com/testnet/gen' : 'https://channels.openzeppelin.com/gen';
|
|
1043
|
-
checks.push({
|
|
1044
|
-
name: 'facilitator', status: 'fail',
|
|
1045
|
-
message: `Facilitator rejected API key (HTTP ${response.status})`,
|
|
1046
|
-
fix: `Verify X402_FACILITATOR_API_KEY is valid for ${rawNetwork}. Keys are per-network: get one at ${genUrl}`,
|
|
1047
|
-
detail: `Status ${response.status} from ${facilitatorUrl}`,
|
|
1048
|
-
});
|
|
1049
|
-
} else {
|
|
1050
|
-
checks.push({
|
|
1051
|
-
name: 'facilitator', status: 'fail', message: `Facilitator returned HTTP ${response.status}`,
|
|
1052
|
-
fix: `Check facilitator service status at ${facilitatorUrl}`,
|
|
1053
|
-
});
|
|
1054
|
-
}
|
|
1055
|
-
} catch (err) {
|
|
1056
|
-
checks.push({
|
|
1057
|
-
name: 'facilitator', status: 'fail', message: `Facilitator endpoint unreachable at ${facilitatorUrl}`,
|
|
1058
|
-
fix: 'Check network connectivity or custom FACILITATOR_URL setting.',
|
|
1059
|
-
detail: err?.message || String(err),
|
|
1060
|
-
});
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
|
-
|
|
1064
|
-
// Check 3: Network & RPC consistency
|
|
1065
|
-
const defaultRpcUrl = isTestnet ? 'https://soroban-testnet.stellar.org' : 'https://soroban-rpc.mainnet.stellar.gateway.fm';
|
|
1066
|
-
const rpcUrl = getEnv('STELLAR_RPC_URL') || getEnv('RPC_URL') || defaultRpcUrl;
|
|
1067
|
-
const expectedPassphrase = isTestnet ? 'Test SDF Network ; July 2015' : 'Public Global Stellar Network ; September 2015';
|
|
1068
|
-
try {
|
|
1069
|
-
const rpcRes = await customFetch(rpcUrl, {
|
|
1070
|
-
method: 'POST',
|
|
1071
|
-
headers: { 'Content-Type': 'application/json' },
|
|
1072
|
-
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getHealth' }),
|
|
1073
|
-
signal: AbortSignal.timeout(5000),
|
|
1074
|
-
});
|
|
1075
|
-
if (rpcRes.ok) {
|
|
1076
|
-
checks.push({
|
|
1077
|
-
name: 'network', status: 'pass', message: `Soroban RPC endpoint operational for ${canonicalNetwork}`,
|
|
1078
|
-
detail: `${rpcUrl} (Passphrase: "${expectedPassphrase}")`,
|
|
1079
|
-
});
|
|
1080
|
-
} else {
|
|
1081
|
-
checks.push({
|
|
1082
|
-
name: 'network', status: 'fail', message: `Soroban RPC endpoint returned HTTP ${rpcRes.status}`,
|
|
1083
|
-
fix: `Verify STELLAR_RPC_URL for network ${canonicalNetwork}`,
|
|
1084
|
-
});
|
|
1085
|
-
}
|
|
1086
|
-
} catch (err) {
|
|
1087
|
-
checks.push({
|
|
1088
|
-
name: 'network', status: 'fail', message: `Soroban RPC endpoint unreachable at ${rpcUrl}`,
|
|
1089
|
-
fix: `Check network connection or set a working STELLAR_RPC_URL for ${canonicalNetwork}`,
|
|
1090
|
-
detail: err?.message || String(err),
|
|
1091
|
-
});
|
|
1092
|
-
}
|
|
1093
|
-
|
|
1094
|
-
// Check 4: Secret Key check (if configured)
|
|
1095
|
-
const secretKey = getEnv('STELLAR_SECRET_KEY') || getEnv('SECRET_KEY') || getEnv('NIRIUM_SECRET_KEY');
|
|
1096
|
-
if (secretKey) {
|
|
1097
|
-
if (!/^S[A-Z2-7]{55}$/.test(secretKey)) {
|
|
1098
|
-
checks.push({
|
|
1099
|
-
name: 'secretKey', status: 'fail', message: 'Secret key format is invalid (must be a 56-character Stellar S... key)',
|
|
1100
|
-
fix: 'Ensure STELLAR_SECRET_KEY is a valid Stellar secret key starting with S...',
|
|
1101
|
-
});
|
|
1102
|
-
} else {
|
|
1103
|
-
checks.push({ name: 'secretKey', status: 'pass', message: 'Secret key format is valid (S...)' });
|
|
1104
|
-
}
|
|
1105
|
-
}
|
|
1106
|
-
|
|
1107
|
-
// Check 5: MPP Configuration (if configured)
|
|
1108
|
-
const mppMode = getEnv('MPP_MODE');
|
|
1109
|
-
const mppSecret = getEnv('MPP_SECRET_KEY');
|
|
1110
|
-
if (mppMode || mppSecret) {
|
|
1111
|
-
if (mppMode && mppMode !== 'pull' && mppMode !== 'push') {
|
|
1112
|
-
checks.push({
|
|
1113
|
-
name: 'mpp', status: 'fail', message: `Invalid MPP_MODE: "${mppMode}" (must be "pull" or "push")`,
|
|
1114
|
-
fix: 'Set MPP_MODE=pull or MPP_MODE=push in .env',
|
|
1115
|
-
});
|
|
1116
|
-
} else if (mppSecret && !/^S[A-Z2-7]{55}$/.test(mppSecret)) {
|
|
1117
|
-
checks.push({
|
|
1118
|
-
name: 'mpp', status: 'fail', message: 'Invalid MPP_SECRET_KEY format (must be a 56-character S... key)',
|
|
1119
|
-
fix: 'Check MPP_SECRET_KEY in .env',
|
|
1120
|
-
});
|
|
1121
|
-
} else {
|
|
1122
|
-
checks.push({ name: 'mpp', status: 'pass', message: `MPP protocol configuration valid (mode: ${mppMode || 'pull'})` });
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
|
|
1126
|
-
const ok = checks.every((c) => c.status === 'pass');
|
|
1127
|
-
return { ok, network: canonicalNetwork, checks, timestamp: new Date().toISOString() };
|
|
1128
|
-
}
|
|
1129
|
-
|
|
1130
|
-
// ═══════════════════════════════════════════════════════════════
|
|
1131
|
-
// doctor --seller — probe a remote x402 seller without paying
|
|
1132
|
-
// ═══════════════════════════════════════════════════════════════
|
|
1133
|
-
//
|
|
1134
|
-
// The probe URL may be plain http (a local fixture). resource.url inside
|
|
1135
|
-
// PAYMENT-REQUIRED may not: browsers and x402 clients follow that URL, and
|
|
1136
|
-
// an http:// resource is a real production failure. Nothing here sends
|
|
1137
|
-
// PAYMENT-SIGNATURE or X-PAYMENT.
|
|
1138
|
-
|
|
1139
|
-
const STELLAR_SELLER_NETWORKS = new Set(['stellar:testnet', 'stellar:pubnet']);
|
|
1140
|
-
|
|
1141
|
-
function headerTokens(value) {
|
|
1142
|
-
if (!value || typeof value !== 'string') return [];
|
|
1143
|
-
return value.split(',').map((part) => part.trim()).filter(Boolean);
|
|
1144
|
-
}
|
|
1145
|
-
|
|
1146
|
-
function tokenListIncludes(value, expected) {
|
|
1147
|
-
const tokens = headerTokens(value).map((token) => token.toLowerCase());
|
|
1148
|
-
return tokens.includes('*') || tokens.includes(expected.toLowerCase());
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
function missingExposedHeaders(value) {
|
|
1152
|
-
const tokens = headerTokens(value).map((token) => token.toLowerCase());
|
|
1153
|
-
if (tokens.includes('*')) return [];
|
|
1154
|
-
const missing = [];
|
|
1155
|
-
if (!tokens.includes('payment-required')) missing.push('PAYMENT-REQUIRED');
|
|
1156
|
-
if (!tokens.includes('payment-response')) missing.push('PAYMENT-RESPONSE');
|
|
1157
|
-
return missing;
|
|
1158
|
-
}
|
|
1159
|
-
|
|
1160
|
-
function isPaymentRequiredPayload(value) {
|
|
1161
|
-
return Boolean(value)
|
|
1162
|
-
&& typeof value === 'object'
|
|
1163
|
-
&& !Array.isArray(value)
|
|
1164
|
-
&& (Array.isArray(value.accepts) || (value.resource && typeof value.resource === 'object'));
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
function decodePaymentRequiredHeader(headerValue) {
|
|
1168
|
-
if (typeof headerValue !== 'string') return null;
|
|
1169
|
-
const trimmed = headerValue.trim();
|
|
1170
|
-
if (!trimmed) return null;
|
|
1171
|
-
const candidates = [];
|
|
1172
|
-
if (trimmed.startsWith('{')) candidates.push(trimmed);
|
|
1173
|
-
candidates.push(Buffer.from(trimmed.replace(/\s+/g, ''), 'base64').toString('utf8'));
|
|
1174
|
-
for (const candidate of candidates) {
|
|
1175
|
-
try {
|
|
1176
|
-
const parsed = JSON.parse(candidate);
|
|
1177
|
-
if (isPaymentRequiredPayload(parsed)) return parsed;
|
|
1178
|
-
} catch {
|
|
1179
|
-
// try the next encoding
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
return null;
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
function isPositiveAtomicAmount(amount) {
|
|
1186
|
-
return typeof amount === 'string' && /^[1-9]\d*$/.test(amount);
|
|
1187
|
-
}
|
|
1188
|
-
|
|
1189
|
-
function isWellFormedSellerNetwork(network) {
|
|
1190
|
-
if (typeof network !== 'string') return false;
|
|
1191
|
-
if (network.startsWith('stellar:')) return STELLAR_SELLER_NETWORKS.has(network);
|
|
1192
|
-
return /^[a-z0-9]{3,32}:[A-Za-z0-9._-]{1,64}$/.test(network);
|
|
1193
|
-
}
|
|
1194
|
-
|
|
1195
|
-
function isWellFormedSellerAsset(asset, network) {
|
|
1196
|
-
if (typeof asset !== 'string' || asset.length === 0 || asset.length > 200 || /\s/.test(asset)) return false;
|
|
1197
|
-
if (typeof network === 'string' && network.startsWith('stellar:')) return StrKey.isValidContract(asset);
|
|
1198
|
-
return true;
|
|
1199
|
-
}
|
|
1200
|
-
|
|
1201
|
-
function payToProblem(payTo, network) {
|
|
1202
|
-
if (typeof payTo !== 'string' || payTo.length === 0) return 'missing';
|
|
1203
|
-
if (payTo.startsWith('S')) return 'secret';
|
|
1204
|
-
const stellar = typeof network === 'string' && network.startsWith('stellar:');
|
|
1205
|
-
if (stellar || payTo.startsWith('G')) {
|
|
1206
|
-
return StrKey.isValidEd25519PublicKey(payTo) ? null : 'invalid';
|
|
1207
|
-
}
|
|
1208
|
-
if (/\s/.test(payTo) || payTo.length < 8 || payTo.length > 200) return 'invalid';
|
|
1209
|
-
return null;
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
|
-
function resourceUrlProblem(resourceUrl) {
|
|
1213
|
-
if (typeof resourceUrl !== 'string' || resourceUrl.length === 0) return 'missing';
|
|
1214
|
-
if (/^http:\/\//i.test(resourceUrl)) return 'http';
|
|
1215
|
-
try {
|
|
1216
|
-
const parsed = new URL(resourceUrl);
|
|
1217
|
-
if (parsed.protocol !== 'https:') return 'not-https';
|
|
1218
|
-
} catch {
|
|
1219
|
-
return 'invalid';
|
|
1220
|
-
}
|
|
1221
|
-
return null;
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
function sellerCheck(name, status, message, fix, detail) {
|
|
1225
|
-
const check = { name, status, message };
|
|
1226
|
-
if (fix) check.fix = fix;
|
|
1227
|
-
if (detail) check.detail = detail;
|
|
1228
|
-
return check;
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
function sellerReport(seller, checks, network) {
|
|
1232
|
-
return {
|
|
1233
|
-
ok: checks.every((check) => check.status === 'pass'),
|
|
1234
|
-
seller,
|
|
1235
|
-
network: network || null,
|
|
1236
|
-
checks,
|
|
1237
|
-
timestamp: new Date().toISOString(),
|
|
1238
|
-
};
|
|
1239
|
-
}
|
|
1240
|
-
|
|
1241
|
-
function unreachableSellerReport(seller, message) {
|
|
1242
|
-
const names = ['challenge', 'network', 'asset', 'amount', 'payTo', 'resource-url', 'cors-preflight', 'cors-expose', 'cors-allow'];
|
|
1243
|
-
return sellerReport(seller, names.map((name) => sellerCheck(
|
|
1244
|
-
name,
|
|
1245
|
-
'fail',
|
|
1246
|
-
message,
|
|
1247
|
-
name === 'challenge' ? 'Pass an absolute http(s) URL, for example https://example.com/premium' : undefined,
|
|
1248
|
-
)), null);
|
|
1249
|
-
}
|
|
1250
|
-
|
|
1251
|
-
function probeErrorMessage(err) {
|
|
1252
|
-
if (!err) return 'unknown error';
|
|
1253
|
-
if (err.name === 'TimeoutError' || err.name === 'AbortError') return 'request timed out after 10s';
|
|
1254
|
-
return err.message || String(err);
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
async function probeSeller(url, init) {
|
|
1258
|
-
try {
|
|
1259
|
-
const response = await fetch(url, {
|
|
1260
|
-
...init,
|
|
1261
|
-
redirect: 'manual',
|
|
1262
|
-
signal: AbortSignal.timeout(10000),
|
|
1263
|
-
});
|
|
1264
|
-
try {
|
|
1265
|
-
await response.body?.cancel();
|
|
1266
|
-
} catch {
|
|
1267
|
-
// headers are already available
|
|
1268
|
-
}
|
|
1269
|
-
return { response };
|
|
1270
|
-
} catch (err) {
|
|
1271
|
-
return { error: err };
|
|
1272
|
-
}
|
|
1273
|
-
}
|
|
1274
|
-
|
|
1275
|
-
function firstAdvertisedNetwork(payment) {
|
|
1276
|
-
const accepts = payment?.accepts;
|
|
1277
|
-
if (!Array.isArray(accepts)) return null;
|
|
1278
|
-
for (const entry of accepts) {
|
|
1279
|
-
if (entry && typeof entry.network === 'string' && entry.network) return entry.network;
|
|
1280
|
-
}
|
|
1281
|
-
return null;
|
|
1282
|
-
}
|
|
1283
|
-
|
|
1284
|
-
function fieldFailures(payment, readProblem) {
|
|
1285
|
-
const accepts = payment?.accepts;
|
|
1286
|
-
if (!Array.isArray(accepts) || accepts.length === 0) {
|
|
1287
|
-
return { ok: false, message: 'PAYMENT-REQUIRED accepts[] is missing or empty' };
|
|
1288
|
-
}
|
|
1289
|
-
for (let i = 0; i < accepts.length; i++) {
|
|
1290
|
-
const entry = accepts[i];
|
|
1291
|
-
const problem = readProblem(entry && typeof entry === 'object' ? entry : {});
|
|
1292
|
-
if (problem) return { ok: false, index: i, ...problem };
|
|
1293
|
-
}
|
|
1294
|
-
return { ok: true };
|
|
1295
|
-
}
|
|
1296
|
-
|
|
1297
|
-
async function runDoctorSeller(sellerUrl) {
|
|
1298
|
-
let parsed;
|
|
1299
|
-
try {
|
|
1300
|
-
parsed = new URL(sellerUrl);
|
|
1301
|
-
} catch {
|
|
1302
|
-
parsed = null;
|
|
1303
|
-
}
|
|
1304
|
-
if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {
|
|
1305
|
-
return unreachableSellerReport(sellerUrl, 'seller URL is not an absolute http(s) URL');
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
// A reserved .invalid origin so the preflight cannot collide with a real
|
|
1309
|
-
// site, and so a seller that 500s on an unknown Origin fails closed.
|
|
1310
|
-
const origin = `https://nirium-doctor-${crypto.randomBytes(8).toString('hex')}.invalid`;
|
|
1311
|
-
const [challenge, preflight] = await Promise.all([
|
|
1312
|
-
probeSeller(sellerUrl, {
|
|
1313
|
-
method: 'GET',
|
|
1314
|
-
headers: {
|
|
1315
|
-
Accept: 'application/json',
|
|
1316
|
-
Origin: origin,
|
|
1317
|
-
'User-Agent': doctorUserAgent,
|
|
1318
|
-
},
|
|
1319
|
-
}),
|
|
1320
|
-
probeSeller(sellerUrl, {
|
|
1321
|
-
method: 'OPTIONS',
|
|
1322
|
-
headers: {
|
|
1323
|
-
Origin: origin,
|
|
1324
|
-
'Access-Control-Request-Method': 'GET',
|
|
1325
|
-
'Access-Control-Request-Headers': 'PAYMENT-SIGNATURE',
|
|
1326
|
-
'User-Agent': doctorUserAgent,
|
|
1327
|
-
},
|
|
1328
|
-
}),
|
|
1329
|
-
]);
|
|
1330
|
-
|
|
1331
|
-
const checks = [];
|
|
1332
|
-
let payment = null;
|
|
1333
|
-
if (challenge.error || !challenge.response) {
|
|
1334
|
-
checks.push(sellerCheck(
|
|
1335
|
-
'challenge',
|
|
1336
|
-
'fail',
|
|
1337
|
-
`seller unreachable: ${probeErrorMessage(challenge.error)}`,
|
|
1338
|
-
'Confirm the URL is reachable. doctor does not retry and does not pay.',
|
|
1339
|
-
));
|
|
1340
|
-
} else if (challenge.response.status !== 402) {
|
|
1341
|
-
checks.push(sellerCheck(
|
|
1342
|
-
'challenge',
|
|
1343
|
-
'fail',
|
|
1344
|
-
`expected HTTP 402, got HTTP ${challenge.response.status}`,
|
|
1345
|
-
'The seller must answer an unpaid request with 402 and a PAYMENT-REQUIRED header.',
|
|
1346
|
-
`status ${challenge.response.status}`,
|
|
1347
|
-
));
|
|
1348
|
-
} else {
|
|
1349
|
-
payment = decodePaymentRequiredHeader(challenge.response.headers.get('payment-required'));
|
|
1350
|
-
if (!payment) {
|
|
1351
|
-
checks.push(sellerCheck(
|
|
1352
|
-
'challenge',
|
|
1353
|
-
'fail',
|
|
1354
|
-
'HTTP 402 but PAYMENT-REQUIRED is missing or not decodable',
|
|
1355
|
-
'Serve the x402 v2 challenge as base64 JSON in the PAYMENT-REQUIRED header.',
|
|
1356
|
-
));
|
|
1357
|
-
} else {
|
|
1358
|
-
checks.push(sellerCheck(
|
|
1359
|
-
'challenge',
|
|
1360
|
-
'pass',
|
|
1361
|
-
'HTTP 402 with a decodable PAYMENT-REQUIRED header',
|
|
1362
|
-
undefined,
|
|
1363
|
-
payment.x402Version != null ? `x402Version ${payment.x402Version}` : undefined,
|
|
1364
|
-
));
|
|
1365
|
-
}
|
|
1366
|
-
}
|
|
1367
|
-
|
|
1368
|
-
const networkResult = fieldFailures(payment, (entry) => {
|
|
1369
|
-
if (entry.network == null || entry.network === '') {
|
|
1370
|
-
return { message: 'network is missing', fix: 'Set accepts[].network, for example stellar:pubnet or stellar:testnet.' };
|
|
1371
|
-
}
|
|
1372
|
-
if (!isWellFormedSellerNetwork(entry.network)) {
|
|
1373
|
-
const stellarTypo = typeof entry.network === 'string' && entry.network.startsWith('stellar:');
|
|
1374
|
-
return {
|
|
1375
|
-
message: `network "${entry.network}" is not well formed`,
|
|
1376
|
-
fix: stellarTypo
|
|
1377
|
-
? 'Stellar sellers must advertise stellar:testnet or stellar:pubnet.'
|
|
1378
|
-
: 'network must be a CAIP-2 identifier such as stellar:pubnet.',
|
|
1379
|
-
detail: String(entry.network),
|
|
1380
|
-
};
|
|
1381
|
-
}
|
|
1382
|
-
return null;
|
|
1383
|
-
});
|
|
1384
|
-
checks.push(networkResult.ok
|
|
1385
|
-
? sellerCheck('network', 'pass', 'network is present and well formed', undefined, firstAdvertisedNetwork(payment))
|
|
1386
|
-
: sellerCheck('network', 'fail', networkResult.index != null ? `accepts[${networkResult.index}].${networkResult.message}` : networkResult.message, networkResult.fix, networkResult.detail));
|
|
1387
|
-
|
|
1388
|
-
const assetResult = fieldFailures(payment, (entry) => {
|
|
1389
|
-
if (!isWellFormedSellerAsset(entry.asset, entry.network)) {
|
|
1390
|
-
const stellar = typeof entry.network === 'string' && entry.network.startsWith('stellar:');
|
|
1391
|
-
return {
|
|
1392
|
-
message: entry.asset == null || entry.asset === '' ? 'asset is missing' : 'asset is not well formed',
|
|
1393
|
-
fix: stellar
|
|
1394
|
-
? 'Stellar asset must be the SAC contract id (C...), not a symbol.'
|
|
1395
|
-
: 'Set accepts[].asset to the token the seller settles.',
|
|
1396
|
-
detail: entry.asset == null ? undefined : String(entry.asset).slice(0, 80),
|
|
1397
|
-
};
|
|
1398
|
-
}
|
|
1399
|
-
return null;
|
|
1400
|
-
});
|
|
1401
|
-
checks.push(assetResult.ok
|
|
1402
|
-
? sellerCheck('asset', 'pass', 'asset is present and well formed')
|
|
1403
|
-
: sellerCheck('asset', 'fail', assetResult.index != null ? `accepts[${assetResult.index}].${assetResult.message}` : assetResult.message, assetResult.fix, assetResult.detail));
|
|
1404
|
-
|
|
1405
|
-
const amountResult = fieldFailures(payment, (entry) => {
|
|
1406
|
-
if (!isPositiveAtomicAmount(entry.amount)) {
|
|
1407
|
-
return {
|
|
1408
|
-
message: entry.amount == null || entry.amount === '' ? 'amount is missing' : 'amount is not a positive integer string',
|
|
1409
|
-
fix: 'Set accepts[].amount to atomic units, for example "1000000". Do not send "$0.02" or "0".',
|
|
1410
|
-
detail: entry.amount == null ? undefined : String(entry.amount).slice(0, 80),
|
|
1411
|
-
};
|
|
1412
|
-
}
|
|
1413
|
-
return null;
|
|
1414
|
-
});
|
|
1415
|
-
checks.push(amountResult.ok
|
|
1416
|
-
? sellerCheck('amount', 'pass', 'amount is a positive integer string')
|
|
1417
|
-
: sellerCheck('amount', 'fail', amountResult.index != null ? `accepts[${amountResult.index}].${amountResult.message}` : amountResult.message, amountResult.fix, amountResult.detail));
|
|
1418
|
-
|
|
1419
|
-
const payToResult = fieldFailures(payment, (entry) => {
|
|
1420
|
-
const problem = payToProblem(entry.payTo, entry.network);
|
|
1421
|
-
if (!problem) return null;
|
|
1422
|
-
if (problem === 'secret') {
|
|
1423
|
-
return {
|
|
1424
|
-
message: 'payTo is a secret key (S...), not a public key',
|
|
1425
|
-
fix: 'accepts[].payTo must be the public key that receives funds (G... on Stellar). Never publish a secret.',
|
|
1426
|
-
detail: 'value starts with S',
|
|
1427
|
-
};
|
|
1428
|
-
}
|
|
1429
|
-
if (problem === 'missing') {
|
|
1430
|
-
return { message: 'payTo is missing', fix: 'Set accepts[].payTo to the account that receives the payment.' };
|
|
1431
|
-
}
|
|
1432
|
-
return {
|
|
1433
|
-
message: 'payTo is not well formed',
|
|
1434
|
-
fix: 'On Stellar, payTo must be a valid 56-character G... public key.',
|
|
1435
|
-
detail: typeof entry.payTo === 'string' ? `length ${entry.payTo.length}` : undefined,
|
|
1436
|
-
};
|
|
1437
|
-
});
|
|
1438
|
-
checks.push(payToResult.ok
|
|
1439
|
-
? sellerCheck('payTo', 'pass', 'payTo is present and well formed')
|
|
1440
|
-
: sellerCheck('payTo', 'fail', payToResult.index != null ? `accepts[${payToResult.index}].${payToResult.message}` : payToResult.message, payToResult.fix, payToResult.detail));
|
|
1441
|
-
|
|
1442
|
-
const urlProblem = payment ? resourceUrlProblem(payment.resource?.url) : 'missing';
|
|
1443
|
-
if (!payment) {
|
|
1444
|
-
checks.push(sellerCheck(
|
|
1445
|
-
'resource-url',
|
|
1446
|
-
'fail',
|
|
1447
|
-
'resource.url was not checked because PAYMENT-REQUIRED did not decode',
|
|
1448
|
-
'Fix the 402 challenge first. resource.url must be an https:// URL.',
|
|
1449
|
-
));
|
|
1450
|
-
} else if (urlProblem === 'http') {
|
|
1451
|
-
checks.push(sellerCheck(
|
|
1452
|
-
'resource-url',
|
|
1453
|
-
'fail',
|
|
1454
|
-
'resource.url uses http://',
|
|
1455
|
-
'Serve resource.url as https://. Browsers and x402 clients will not treat an http resource as the paid URL.',
|
|
1456
|
-
String(payment.resource?.url).slice(0, 120),
|
|
1457
|
-
));
|
|
1458
|
-
} else if (urlProblem) {
|
|
1459
|
-
checks.push(sellerCheck(
|
|
1460
|
-
'resource-url',
|
|
1461
|
-
'fail',
|
|
1462
|
-
'resource.url is missing or not https://',
|
|
1463
|
-
'Set resource.url to an absolute https:// URL.',
|
|
1464
|
-
payment.resource?.url == null ? undefined : String(payment.resource.url).slice(0, 120),
|
|
1465
|
-
));
|
|
1466
|
-
} else {
|
|
1467
|
-
checks.push(sellerCheck('resource-url', 'pass', 'resource.url is https://', undefined, payment.resource.url));
|
|
1468
|
-
}
|
|
1469
|
-
|
|
1470
|
-
const preflightResponse = preflight.response;
|
|
1471
|
-
let allowCheck;
|
|
1472
|
-
if (preflight.error || !preflightResponse) {
|
|
1473
|
-
checks.push(sellerCheck(
|
|
1474
|
-
'cors-preflight',
|
|
1475
|
-
'fail',
|
|
1476
|
-
`CORS preflight failed: ${probeErrorMessage(preflight.error)}`,
|
|
1477
|
-
'The seller must answer OPTIONS for an unknown Origin without crashing.',
|
|
1478
|
-
));
|
|
1479
|
-
allowCheck = sellerCheck(
|
|
1480
|
-
'cors-allow',
|
|
1481
|
-
'fail',
|
|
1482
|
-
'PAYMENT-SIGNATURE was not allowed because the preflight did not complete',
|
|
1483
|
-
'Answer OPTIONS with Access-Control-Allow-Headers including PAYMENT-SIGNATURE.',
|
|
1484
|
-
);
|
|
1485
|
-
} else if (preflightResponse.status >= 500) {
|
|
1486
|
-
checks.push(sellerCheck(
|
|
1487
|
-
'cors-preflight',
|
|
1488
|
-
'fail',
|
|
1489
|
-
`CORS preflight returned HTTP ${preflightResponse.status} for an unknown origin`,
|
|
1490
|
-
'An unknown Origin must not 500. Handle OPTIONS before route auth.',
|
|
1491
|
-
origin,
|
|
1492
|
-
));
|
|
1493
|
-
allowCheck = sellerCheck(
|
|
1494
|
-
'cors-allow',
|
|
1495
|
-
'fail',
|
|
1496
|
-
'PAYMENT-SIGNATURE was not allowed because the preflight failed',
|
|
1497
|
-
'Answer OPTIONS with 2xx and Access-Control-Allow-Headers: PAYMENT-SIGNATURE.',
|
|
1498
|
-
);
|
|
1499
|
-
} else if (preflightResponse.status < 200 || preflightResponse.status >= 300) {
|
|
1500
|
-
checks.push(sellerCheck(
|
|
1501
|
-
'cors-preflight',
|
|
1502
|
-
'fail',
|
|
1503
|
-
`CORS preflight returned HTTP ${preflightResponse.status}`,
|
|
1504
|
-
'Answer OPTIONS with 204 or another 2xx, including Access-Control-Allow-Origin.',
|
|
1505
|
-
origin,
|
|
1506
|
-
));
|
|
1507
|
-
allowCheck = sellerCheck(
|
|
1508
|
-
'cors-allow',
|
|
1509
|
-
'fail',
|
|
1510
|
-
'PAYMENT-SIGNATURE was not allowed because the preflight was not successful',
|
|
1511
|
-
'Include PAYMENT-SIGNATURE in Access-Control-Allow-Headers on the OPTIONS response.',
|
|
1512
|
-
);
|
|
1513
|
-
} else {
|
|
1514
|
-
const allowOrigin = preflightResponse.headers.get('access-control-allow-origin') || '';
|
|
1515
|
-
const originAllowed = allowOrigin === '*' || allowOrigin === origin;
|
|
1516
|
-
checks.push(originAllowed
|
|
1517
|
-
? sellerCheck('cors-preflight', 'pass', `CORS preflight returned HTTP ${preflightResponse.status} for a random origin`, undefined, origin)
|
|
1518
|
-
: sellerCheck(
|
|
1519
|
-
'cors-preflight',
|
|
1520
|
-
'fail',
|
|
1521
|
-
'CORS preflight did not allow the random origin',
|
|
1522
|
-
'Send Access-Control-Allow-Origin: * or echo the request Origin. An unknown origin must not be dropped.',
|
|
1523
|
-
allowOrigin ? `got ${allowOrigin}` : 'Access-Control-Allow-Origin missing',
|
|
1524
|
-
));
|
|
1525
|
-
const allowed = tokenListIncludes(preflightResponse.headers.get('access-control-allow-headers'), 'PAYMENT-SIGNATURE');
|
|
1526
|
-
allowCheck = allowed
|
|
1527
|
-
? sellerCheck('cors-allow', 'pass', 'PAYMENT-SIGNATURE is allowed on the preflight')
|
|
1528
|
-
: sellerCheck(
|
|
1529
|
-
'cors-allow',
|
|
1530
|
-
'fail',
|
|
1531
|
-
'PAYMENT-SIGNATURE is not listed in Access-Control-Allow-Headers',
|
|
1532
|
-
'Add PAYMENT-SIGNATURE to Access-Control-Allow-Headers. Browsers drop the payment header otherwise.',
|
|
1533
|
-
preflightResponse.headers.get('access-control-allow-headers') || 'header missing',
|
|
1534
|
-
);
|
|
1535
|
-
}
|
|
1536
|
-
|
|
1537
|
-
// Browsers only honor Access-Control-Expose-Headers on the actual response.
|
|
1538
|
-
// A preflight that lists the headers does not make the 402 readable.
|
|
1539
|
-
const exposeMissing = missingExposedHeaders(challenge.response?.headers.get('access-control-expose-headers'));
|
|
1540
|
-
if (challenge.response && exposeMissing.length === 0) {
|
|
1541
|
-
checks.push(sellerCheck(
|
|
1542
|
-
'cors-expose',
|
|
1543
|
-
'pass',
|
|
1544
|
-
'PAYMENT-REQUIRED and PAYMENT-RESPONSE are exposed on the 402 response',
|
|
1545
|
-
));
|
|
1546
|
-
} else {
|
|
1547
|
-
const missing = exposeMissing.length ? exposeMissing : ['PAYMENT-REQUIRED', 'PAYMENT-RESPONSE'];
|
|
1548
|
-
checks.push(sellerCheck(
|
|
1549
|
-
'cors-expose',
|
|
1550
|
-
'fail',
|
|
1551
|
-
`browser clients cannot read ${missing.join(' and ')}`,
|
|
1552
|
-
'Set Access-Control-Expose-Headers: PAYMENT-REQUIRED, PAYMENT-RESPONSE on the 402 response. The preflight does not count.',
|
|
1553
|
-
));
|
|
1554
|
-
}
|
|
1555
|
-
checks.push(allowCheck);
|
|
1556
|
-
|
|
1557
|
-
return sellerReport(sellerUrl, checks, payment ? firstAdvertisedNetwork(payment) : null);
|
|
1558
|
-
}
|
|
1559
|
-
|
|
1560
|
-
function formatDoctorOutput(report) {
|
|
1561
|
-
const lines = [];
|
|
1562
|
-
lines.push(report.seller
|
|
1563
|
-
? `🩺 Nirium Doctor — remote x402 seller`
|
|
1564
|
-
: `🩺 Nirium Doctor — x402 Diagnostic Report`);
|
|
1565
|
-
if (report.seller) lines.push(`Seller: ${report.seller}`);
|
|
1566
|
-
lines.push(`Target Network: ${report.network || 'n/a'}`);
|
|
1567
|
-
lines.push(`Timestamp: ${report.timestamp}`);
|
|
1568
|
-
lines.push(`--------------------------------------------------`);
|
|
1569
|
-
for (const check of report.checks) {
|
|
1570
|
-
const symbol = check.status === 'pass' ? '✔' : '❌';
|
|
1571
|
-
lines.push(`${symbol} [${check.name.toUpperCase()}] ${check.message}`);
|
|
1572
|
-
if (check.detail && check.status === 'pass') lines.push(` Detail: ${check.detail}`);
|
|
1573
|
-
if (check.fix) lines.push(` 💡 Fix: ${check.fix}`);
|
|
1574
|
-
}
|
|
1575
|
-
lines.push(`--------------------------------------------------`);
|
|
1576
|
-
lines.push(report.ok ? `✅ All checks passed!` : `❌ Diagnostic failed. See fix suggestions above.`);
|
|
1577
|
-
return lines.join('\n');
|
|
1578
|
-
}
|
|
1579
|
-
|
|
1580
|
-
// ═══════════════════════════════════════════════════════════════
|
|
1581
|
-
// verify — independently check an audit CID's hash + agent signature
|
|
1582
|
-
// ═══════════════════════════════════════════════════════════════
|
|
1583
|
-
|
|
1584
|
-
function decodeStellarPublicKey(gAddress) {
|
|
1585
|
-
if (!/^G[A-Z2-7]{55}$/.test(gAddress)) {
|
|
1586
|
-
throw new Error(`Invalid Stellar public key format: ${gAddress}`);
|
|
1587
|
-
}
|
|
1588
|
-
return Buffer.from(StrKey.decodeEd25519PublicKey(gAddress));
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
const HEX64 = /^[0-9a-f]{64}$/;
|
|
1592
|
-
const SEP53_PREFIX = 'Stellar Signed Message:\n';
|
|
1593
|
-
|
|
1594
|
-
// Accepts `<hex>` or `sha-256:<hex>`, any case. Returns lowercase hex or throws.
|
|
1595
|
-
function normalizeHashInput(value) {
|
|
1596
|
-
const hex = String(value).trim().replace(/^sha-?256:/i, '').toLowerCase();
|
|
1597
|
-
if (!HEX64.test(hex)) throw new Error(`Invalid sha-256 hash: ${value}`);
|
|
1598
|
-
return hex;
|
|
1599
|
-
}
|
|
1600
|
-
|
|
1601
|
-
// The node accepts the signature as hex or base64. Returns a 64-byte buffer or null.
|
|
1602
|
-
function decodeSignature(signature) {
|
|
1603
|
-
if (typeof signature !== 'string') return null;
|
|
1604
|
-
const s = signature.trim();
|
|
1605
|
-
const buf = /^[0-9a-fA-F]{128}$/.test(s) ? Buffer.from(s, 'hex') : Buffer.from(s, 'base64');
|
|
1606
|
-
return buf.length === 64 ? buf : null;
|
|
1607
|
-
}
|
|
1608
|
-
|
|
1609
|
-
// Mirrors the node: raw ed25519 over the utf8 statement first, then SEP-53
|
|
1610
|
-
// (Freighter signMessage): ed25519 over sha256("Stellar Signed Message:\n" + statement).
|
|
1611
|
-
// Returns 'ed25519', 'sep53' or null.
|
|
1612
|
-
function verifyEd25519Signature(pubKeyGAddress, statement, signature) {
|
|
1613
|
-
try {
|
|
1614
|
-
const rawPubKey = decodeStellarPublicKey(pubKeyGAddress);
|
|
1615
|
-
const spkiHeader = Buffer.from('302a300506032b6570032100', 'hex');
|
|
1616
|
-
const keyObject = crypto.createPublicKey({
|
|
1617
|
-
key: Buffer.concat([spkiHeader, rawPubKey]),
|
|
1618
|
-
format: 'der',
|
|
1619
|
-
type: 'spki',
|
|
1620
|
-
});
|
|
1621
|
-
const signatureBuf = decodeSignature(signature);
|
|
1622
|
-
if (!signatureBuf) return null;
|
|
1623
|
-
if (crypto.verify(null, Buffer.from(statement, 'utf8'), keyObject, signatureBuf)) return 'ed25519';
|
|
1624
|
-
const sep53Digest = crypto.createHash('sha256').update(Buffer.from(SEP53_PREFIX + statement, 'utf8')).digest();
|
|
1625
|
-
if (crypto.verify(null, sep53Digest, keyObject, signatureBuf)) return 'sep53';
|
|
1626
|
-
return null;
|
|
1627
|
-
} catch {
|
|
1628
|
-
return null;
|
|
1629
|
-
}
|
|
1630
|
-
}
|
|
1631
|
-
|
|
1632
|
-
function verifyAuditDocument(doc, cid, { expectedHash } = {}) {
|
|
1633
|
-
const fail = (error) => ({ ok: false, verified: false, cid, hashMatch: false, hashStatus: 'mismatch', expectedHash: '', computedHash: '', signatureStatus: 'absent', error });
|
|
1634
|
-
if (!doc || typeof doc !== 'object') return fail('Invalid audit document format');
|
|
1635
|
-
const anchoredHash = typeof doc.content_sha256 === 'string' ? doc.content_sha256.toLowerCase() : '';
|
|
1636
|
-
if (!HEX64.test(anchoredHash)) return fail('Audit document has no valid content_sha256');
|
|
1637
|
-
|
|
1638
|
-
// record mode: recompute from the embedded record (unchanged behavior).
|
|
1639
|
-
// hash-only mode: the node stores the submitted hash as content_sha256 and
|
|
1640
|
-
// has nothing to recompute it from, so compare against --hash/--evidence
|
|
1641
|
-
// when given, otherwise report the hash as unchecked (not as a mismatch).
|
|
1642
|
-
const mode = doc.record ? 'record' : 'hash-only';
|
|
1643
|
-
let computedHash = '';
|
|
1644
|
-
let hashStatus;
|
|
1645
|
-
if (mode === 'record') {
|
|
1646
|
-
computedHash = crypto.createHash('sha256').update(JSON.stringify(doc.record)).digest('hex');
|
|
1647
|
-
hashStatus = computedHash === anchoredHash ? 'match' : 'mismatch';
|
|
1648
|
-
if (hashStatus === 'match' && expectedHash && expectedHash !== anchoredHash) hashStatus = 'mismatch';
|
|
1649
|
-
} else if (expectedHash) {
|
|
1650
|
-
computedHash = expectedHash;
|
|
1651
|
-
hashStatus = expectedHash === anchoredHash ? 'match' : 'mismatch';
|
|
1652
|
-
} else {
|
|
1653
|
-
hashStatus = 'unchecked';
|
|
1654
|
-
}
|
|
1655
|
-
|
|
1656
|
-
let signatureStatus = 'absent';
|
|
1657
|
-
let signatureScheme, signerKey, statement, declaredStatement, agentId;
|
|
1658
|
-
if (doc.agent && doc.agent.key && doc.agent.signature) {
|
|
1659
|
-
signerKey = doc.agent.key;
|
|
1660
|
-
agentId = doc.agent.id;
|
|
1661
|
-
// Never trust the document's own statement field. In record mode the
|
|
1662
|
-
// statement is built from the recomputed record hash; in hash-only mode
|
|
1663
|
-
// from content_sha256 (a swapped content_sha256 breaks the signature).
|
|
1664
|
-
statement = `nirium-audit-v1:${mode === 'record' ? computedHash : anchoredHash}`;
|
|
1665
|
-
declaredStatement = doc.agent.statement;
|
|
1666
|
-
signatureScheme = verifyEd25519Signature(signerKey, statement, doc.agent.signature) || undefined;
|
|
1667
|
-
signatureStatus = signatureScheme ? 'valid' : 'invalid';
|
|
1668
|
-
}
|
|
1669
|
-
|
|
1670
|
-
// A pass requires at least one check to have actually run and succeeded.
|
|
1671
|
-
// "No check failed" alone is true when both were skipped (hash unchecked,
|
|
1672
|
-
// signature absent), which is not the same as the evidence being verified.
|
|
1673
|
-
const anyFailed = hashStatus === 'mismatch' || signatureStatus === 'invalid';
|
|
1674
|
-
const anyPassed = hashStatus === 'match' || signatureStatus === 'valid';
|
|
1675
|
-
const ok = !anyFailed && anyPassed;
|
|
1676
|
-
return { ok, verified: ok, cid, mode, hashMatch: hashStatus === 'match', hashStatus, expectedHash: anchoredHash, computedHash, signatureStatus, signatureScheme, signerKey, statement, declaredStatement, agentId };
|
|
1677
|
-
}
|
|
1678
|
-
|
|
1679
|
-
// `gateways` may be a single URL string (back-compat for direct callers)
|
|
1680
|
-
// or an array tried in order. On a 404, the SAME gateway is retried up to
|
|
1681
|
-
// `retries` times with a flat backoff before moving to the next gateway -
|
|
1682
|
-
// a 404 can mean "not propagated to this gateway yet", which a moment's
|
|
1683
|
-
// wait often resolves, unlike a real 4xx/5xx or network failure, which
|
|
1684
|
-
// moves on immediately since retrying the same gateway won't help.
|
|
1685
|
-
// `sleepFn` exists only so tests don't have to sit through real backoff.
|
|
1686
|
-
async function fetchAndVerifyCid(cid, gateways = 'https://gateway.pinata.cloud', fetchFn = globalThis.fetch, opts = {}) {
|
|
1687
|
-
const list = Array.isArray(gateways) ? gateways : [gateways];
|
|
1688
|
-
const retries = Number.isInteger(opts.retries) && opts.retries >= 0 ? opts.retries : 2;
|
|
1689
|
-
const timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : 8000;
|
|
1690
|
-
const sleep = opts.sleepFn || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1691
|
-
const BACKOFF_MS = 300;
|
|
1692
|
-
|
|
1693
|
-
const attempts = [];
|
|
1694
|
-
for (const gatewayUrl of list) {
|
|
1695
|
-
const url = `${gatewayUrl.replace(/\/$/, '')}/ipfs/${cid}`;
|
|
1696
|
-
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
|
1697
|
-
if (attempt > 0) await sleep(BACKOFF_MS);
|
|
1698
|
-
try {
|
|
1699
|
-
const res = await fetchFn(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
1700
|
-
if (res.status === 404) {
|
|
1701
|
-
attempts.push({ gateway: gatewayUrl, attempt, status: 404 });
|
|
1702
|
-
continue; // worth retrying THIS gateway: may just not be propagated yet
|
|
1703
|
-
}
|
|
1704
|
-
if (!res.ok) {
|
|
1705
|
-
attempts.push({ gateway: gatewayUrl, attempt, status: res.status });
|
|
1706
|
-
break; // a real error from this gateway - try the next one, not more retries here
|
|
1707
|
-
}
|
|
1708
|
-
const doc = await res.json();
|
|
1709
|
-
return { ...verifyAuditDocument(doc, cid, opts), gateway: gatewayUrl, attempts: [...attempts, { gateway: gatewayUrl, attempt, status: 200 }] };
|
|
1710
|
-
} catch (err) {
|
|
1711
|
-
attempts.push({ gateway: gatewayUrl, attempt, error: err?.message || String(err) });
|
|
1712
|
-
break; // network-level failure (unreachable, timeout) - try the next gateway
|
|
1713
|
-
}
|
|
1714
|
-
}
|
|
1715
|
-
}
|
|
1716
|
-
|
|
1717
|
-
// Every gateway exhausted without a usable (200) response. All-404
|
|
1718
|
-
// means the content plausibly just isn't propagated anywhere yet -
|
|
1719
|
-
// a different situation from a gateway being unreachable or erroring,
|
|
1720
|
-
// which this reports distinctly so a caller doesn't read "not found
|
|
1721
|
-
// anywhere" as "the hash doesn't match" (it was never fetched at all).
|
|
1722
|
-
const allNotFound = attempts.length > 0 && attempts.every((a) => a.status === 404);
|
|
1723
|
-
return {
|
|
1724
|
-
ok: false, verified: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent',
|
|
1725
|
-
availability: allNotFound ? 'not_yet_available' : 'gateway_error',
|
|
1726
|
-
error: allNotFound
|
|
1727
|
-
? `CID not found on ${list.length} gateway(s) after ${retries} retr${retries === 1 ? 'y' : 'ies'} each - it may not be propagated yet, not necessarily wrong`
|
|
1728
|
-
: `Could not fetch the CID from any of ${list.length} gateway(s) - see attempts for each failure`,
|
|
1729
|
-
attempts,
|
|
1730
|
-
};
|
|
1731
|
-
}
|
|
1732
|
-
|
|
1733
|
-
function formatVerifyOutput(result) {
|
|
1734
|
-
const lines = [];
|
|
1735
|
-
lines.push(`🔍 Nirium Audit Verifier`);
|
|
1736
|
-
if (result.cid) lines.push(`CID: ${result.cid}`);
|
|
1737
|
-
lines.push(`--------------------------------------------------`);
|
|
1738
|
-
|
|
1739
|
-
// The document was never fetched at all (every gateway failed), so
|
|
1740
|
-
// there is no hash or signature to report on - printing those sections
|
|
1741
|
-
// would show a false "MISMATCH" for a CID that was simply never
|
|
1742
|
-
// retrieved. `availability` tells apart "not found anywhere yet"
|
|
1743
|
-
// (may just not be propagated) from an actual gateway/network error.
|
|
1744
|
-
if (result.hashStatus === undefined && result.error) {
|
|
1745
|
-
lines.push(result.availability === 'not_yet_available'
|
|
1746
|
-
? `ℹ NOT YET AVAILABLE: ${result.error}`
|
|
1747
|
-
: `❌ GATEWAY ERROR: ${result.error}`);
|
|
1748
|
-
if (Array.isArray(result.attempts) && result.attempts.length > 0) {
|
|
1749
|
-
lines.push(`--------------------------------------------------`);
|
|
1750
|
-
lines.push('Attempts:');
|
|
1751
|
-
for (const a of result.attempts) {
|
|
1752
|
-
lines.push(` ${a.gateway} (try ${a.attempt + 1}): ${a.error ? a.error : `HTTP ${a.status}`}`);
|
|
1753
|
-
}
|
|
1754
|
-
}
|
|
1755
|
-
lines.push(`--------------------------------------------------`);
|
|
1756
|
-
lines.push(result.availability === 'not_yet_available'
|
|
1757
|
-
? `❌ NOT YET AVAILABLE (not a hash mismatch - try again shortly, or add --gateway for another source)`
|
|
1758
|
-
: `❌ VERIFICATION FAILED (could not reach the content, not a hash mismatch)`);
|
|
1759
|
-
return lines.join('\n');
|
|
1760
|
-
}
|
|
1761
|
-
|
|
1762
|
-
if (result.hashStatus === 'unchecked') {
|
|
1763
|
-
lines.push(`ℹ HASH: NOT CHECKED (hash-only anchor: ${result.expectedHash.slice(0, 16)}...)`);
|
|
1764
|
-
lines.push(` Pass --hash <hex> or --evidence <file> to compare it with your original evidence.`);
|
|
1765
|
-
} else if (result.hashMatch) {
|
|
1766
|
-
lines.push(`✔ HASH: MATCH (${result.expectedHash.slice(0, 16)}...)${result.mode === 'hash-only' ? ' [hash-only]' : ''}`);
|
|
1767
|
-
} else {
|
|
1768
|
-
lines.push(`❌ HASH: MISMATCH (Anchored: ${result.expectedHash}, Computed: ${result.computedHash})`);
|
|
1769
|
-
}
|
|
1770
|
-
if (result.signatureStatus === 'valid') {
|
|
1771
|
-
lines.push(`✔ SIGNATURE: VALID${result.signatureScheme === 'sep53' ? ' (SEP-53)' : ''} (Signed by ${result.signerKey})`);
|
|
1772
|
-
if (result.statement) lines.push(` Statement: ${result.statement}`);
|
|
1773
|
-
if (result.agentId) lines.push(` Agent ID: ${result.agentId}`);
|
|
1774
|
-
} else if (result.signatureStatus === 'invalid') {
|
|
1775
|
-
lines.push(`❌ SIGNATURE: INVALID (Signature check failed for key ${result.signerKey})`);
|
|
1776
|
-
} else {
|
|
1777
|
-
lines.push(`ℹ SIGNATURE: ABSENT (No agent attestation embedded)`);
|
|
1778
|
-
}
|
|
1779
|
-
lines.push(`--------------------------------------------------`);
|
|
1780
|
-
if (result.error) {
|
|
1781
|
-
lines.push(`❌ ERROR: ${result.error}`);
|
|
1782
|
-
} else if (result.ok) {
|
|
1783
|
-
lines.push(`✅ VERIFICATION PASSED`);
|
|
1784
|
-
} else if (result.hashStatus === 'unchecked' && result.signatureStatus === 'absent') {
|
|
1785
|
-
lines.push(`❌ NOTHING VERIFIED (pass --hash, --evidence, or anchor with an agent signature)`);
|
|
1786
|
-
} else {
|
|
1787
|
-
lines.push(`❌ VERIFICATION FAILED`);
|
|
1788
|
-
}
|
|
1789
|
-
return lines.join('\n');
|
|
1790
|
-
}
|
|
1791
|
-
|
|
1792
|
-
// ═══════════════════════════════════════════════════════════════
|
|
1793
|
-
// anchor — anchor a hash or small record to IPFS via the Audit Trail node
|
|
1794
|
-
// ═══════════════════════════════════════════════════════════════
|
|
1795
|
-
|
|
1796
|
-
const ANCHOR_MAX_RECORD_BYTES = 8 * 1024;
|
|
1797
|
-
|
|
1798
|
-
// `nirium anchor` deliberately has no `--network` flag: the agent box
|
|
1799
|
-
// decides its own network (STELLAR_NETWORK) and the server already
|
|
1800
|
-
// rejects a `network` field in the body. A client-side flag here would
|
|
1801
|
-
// only ever be ignored, which is worse than not having it.
|
|
1802
|
-
async function executeAnchorCommand(options) {
|
|
1803
|
-
const fail = (error, hint) => {
|
|
1804
|
-
if (options.json) {
|
|
1805
|
-
console.log(JSON.stringify({ ok: false, error, ...(hint ? { hint } : {}) }));
|
|
1806
|
-
} else {
|
|
1807
|
-
console.error(`❌ Error: ${error}${hint ? `\n ${hint}` : ''}`);
|
|
1808
|
-
}
|
|
1809
|
-
process.exit(1);
|
|
1810
|
-
};
|
|
1811
|
-
|
|
1812
|
-
const given = ['file', 'hash', 'record'].filter((k) => options[k] !== undefined);
|
|
1813
|
-
if (given.length === 0) {
|
|
1814
|
-
fail('Provide exactly one of --file, --hash, or --record.');
|
|
1815
|
-
return;
|
|
1816
|
-
}
|
|
1817
|
-
if (given.length > 1) {
|
|
1818
|
-
fail(`--${given[0]} and --${given[1]} were both given - use exactly one.`);
|
|
1819
|
-
return;
|
|
1820
|
-
}
|
|
1821
|
-
|
|
1822
|
-
const body = {};
|
|
1823
|
-
if (options.file !== undefined) {
|
|
1824
|
-
let fileBuf;
|
|
1825
|
-
try {
|
|
1826
|
-
fileBuf = fs.readFileSync(options.file);
|
|
1827
|
-
} catch (err) {
|
|
1828
|
-
fail(`Could not read --file '${options.file}': ${err?.message || String(err)}`);
|
|
1829
|
-
return;
|
|
1830
|
-
}
|
|
1831
|
-
body.hash = crypto.createHash('sha256').update(fileBuf).digest('hex');
|
|
1832
|
-
} else if (options.hash !== undefined) {
|
|
1833
|
-
try {
|
|
1834
|
-
body.hash = normalizeHashInput(options.hash);
|
|
1835
|
-
} catch (err) {
|
|
1836
|
-
fail(err.message);
|
|
1837
|
-
return;
|
|
1838
|
-
}
|
|
1839
|
-
} else {
|
|
1840
|
-
let record;
|
|
1841
|
-
try {
|
|
1842
|
-
record = JSON.parse(options.record);
|
|
1843
|
-
} catch (err) {
|
|
1844
|
-
fail(`--record is not valid JSON: ${err?.message || String(err)}`);
|
|
1845
|
-
return;
|
|
1846
|
-
}
|
|
1847
|
-
if (typeof record !== 'object' || record === null || Array.isArray(record)) {
|
|
1848
|
-
fail('--record must be a JSON object, e.g. \'{"order":"A-12"}\'');
|
|
1849
|
-
return;
|
|
1850
|
-
}
|
|
1851
|
-
// Mirrors the server's own 8KB limit (MAX_RECORD_BYTES in
|
|
1852
|
-
// auditRoutes.ts) so an oversized record fails locally, before any
|
|
1853
|
-
// network call, instead of round-tripping for a 413.
|
|
1854
|
-
const raw = JSON.stringify(record);
|
|
1855
|
-
if (Buffer.byteLength(raw, 'utf8') > ANCHOR_MAX_RECORD_BYTES) {
|
|
1856
|
-
fail(`--record exceeds ${ANCHOR_MAX_RECORD_BYTES / 1024}KB - anchor a sha-256 hash instead (--hash or --file).`);
|
|
1857
|
-
return;
|
|
1858
|
-
}
|
|
1859
|
-
body.record = record;
|
|
1860
|
-
}
|
|
1861
|
-
|
|
1862
|
-
if (options.tx !== undefined) body.txHash = options.tx;
|
|
1863
|
-
if (options.tag !== undefined) body.tag = options.tag;
|
|
1864
|
-
|
|
1865
|
-
const agentAttestation = await maybeBuildAgentAttestation(options, body, fail);
|
|
1866
|
-
if (agentAttestation === 'failed') return; // fail() already called and exited
|
|
1867
|
-
if (agentAttestation) body.agent = agentAttestation;
|
|
1868
|
-
|
|
1869
|
-
let response;
|
|
1870
|
-
try {
|
|
1871
|
-
response = await fetch(`${options.url}/api/audit/log`, {
|
|
1872
|
-
method: 'POST',
|
|
1873
|
-
headers: { 'content-type': 'application/json' },
|
|
1874
|
-
body: JSON.stringify(body),
|
|
1875
|
-
signal: AbortSignal.timeout(20_000),
|
|
1876
|
-
});
|
|
1877
|
-
} catch (err) {
|
|
1878
|
-
const msg = (err?.name === 'TimeoutError' || err?.name === 'AbortError')
|
|
1879
|
-
? `Timed out waiting for ${options.url}/api/audit/log`
|
|
1880
|
-
: `Agent unreachable at ${options.url}: ${err?.message || String(err)}`;
|
|
1881
|
-
fail(msg);
|
|
1882
|
-
return;
|
|
1883
|
-
}
|
|
1884
|
-
|
|
1885
|
-
let data = null;
|
|
1886
|
-
try {
|
|
1887
|
-
data = await response.json();
|
|
1888
|
-
} catch { /* empty or non-JSON body */ }
|
|
1889
|
-
|
|
1890
|
-
if (!response.ok) {
|
|
1891
|
-
fail(data?.error || `Agent returned HTTP ${response.status}`, data?.sign ? `Sign this statement instead: ${data.sign}` : undefined);
|
|
1892
|
-
return;
|
|
1893
|
-
}
|
|
1894
|
-
|
|
1895
|
-
if (options.json) {
|
|
1896
|
-
console.log(JSON.stringify({ ok: true, ...data }, null, 2));
|
|
1897
|
-
return;
|
|
1898
|
-
}
|
|
1899
|
-
|
|
1900
|
-
console.log('✅ Anchored to IPFS');
|
|
1901
|
-
console.log(` CID: ${data.cid}`);
|
|
1902
|
-
console.log(` Content sha256: ${data.content_sha256}`);
|
|
1903
|
-
if (data.gatewayUrl) console.log(` Gateway URL: ${data.gatewayUrl}`);
|
|
1904
|
-
if (data.attestedBy) console.log(` Attested by: ${data.attestedBy}`);
|
|
1905
|
-
console.log(` Anchored at: ${data.anchoredAt}`);
|
|
1906
|
-
console.log(`\n Verify independently: nirium verify ${data.cid}`);
|
|
1907
|
-
}
|
|
1908
|
-
|
|
1909
|
-
// Returns the `agent` object for the request body, `undefined` when
|
|
1910
|
-
// `--sign` was not passed, or the string 'failed' when fail() already
|
|
1911
|
-
// ran (caller must return without doing anything else).
|
|
1912
|
-
//
|
|
1913
|
-
// Signs locally and never sends the secret key anywhere - only the
|
|
1914
|
-
// resulting signature and the derived public key leave this process.
|
|
1915
|
-
// The statement signed, `nirium-audit-v1:<content_sha256>`, must match
|
|
1916
|
-
// exactly what the server itself computes as contentSha before it
|
|
1917
|
-
// verifies: the hash as-is for `--hash`/`--file` (already normalized to
|
|
1918
|
-
// lowercase hex at this point), or sha-256 of the record's JSON text for
|
|
1919
|
-
// `--record` - never the file's own content, which the server never sees.
|
|
1920
|
-
async function maybeBuildAgentAttestation(options, body, fail) {
|
|
1921
|
-
if (!options.sign) return undefined;
|
|
1922
|
-
|
|
1923
|
-
let secretKey;
|
|
1924
|
-
if (options.keyEnv !== undefined) {
|
|
1925
|
-
secretKey = process.env[options.keyEnv];
|
|
1926
|
-
if (!secretKey) {
|
|
1927
|
-
fail(`--key-env ${options.keyEnv} is not set (or is empty) in the environment.`);
|
|
1928
|
-
return 'failed';
|
|
1929
|
-
}
|
|
1930
|
-
} else {
|
|
1931
|
-
secretKey = loadConfig().secretKey;
|
|
1932
|
-
if (!secretKey) {
|
|
1933
|
-
fail('--sign needs a key: run `nirium config set secretKey`, or pass --key-env <VAR> '
|
|
1934
|
-
+ 'with the secret key in that environment variable.');
|
|
1935
|
-
return 'failed';
|
|
1936
|
-
}
|
|
1937
|
-
}
|
|
1938
|
-
|
|
1939
|
-
let keypair;
|
|
1940
|
-
try {
|
|
1941
|
-
keypair = Keypair.fromSecret(secretKey);
|
|
1942
|
-
} catch (err) {
|
|
1943
|
-
fail(`--sign: invalid Stellar secret key - ${err?.message || String(err)}`);
|
|
1944
|
-
return 'failed';
|
|
1945
|
-
}
|
|
1946
|
-
|
|
1947
|
-
const contentSha = body.hash
|
|
1948
|
-
? body.hash
|
|
1949
|
-
: crypto.createHash('sha256').update(JSON.stringify(body.record)).digest('hex');
|
|
1950
|
-
const statement = `nirium-audit-v1:${contentSha}`;
|
|
1951
|
-
const signature = Buffer.from(keypair.sign(Buffer.from(statement, 'utf8'))).toString('base64');
|
|
1952
|
-
|
|
1953
|
-
return { key: keypair.publicKey(), signature };
|
|
1954
|
-
}
|
|
1955
|
-
|
|
1956
|
-
// ═══════════════════════════════════════════════════════════════
|
|
1957
|
-
// report — summaries and exports from the Reporting node
|
|
1958
|
-
// ═══════════════════════════════════════════════════════════════
|
|
1959
|
-
|
|
1960
|
-
function buildQueryString(params) {
|
|
1961
|
-
const qs = new URLSearchParams();
|
|
1962
|
-
for (const [k, v] of Object.entries(params)) {
|
|
1963
|
-
if (v !== undefined && v !== null && v !== '') qs.set(k, String(v));
|
|
1964
|
-
}
|
|
1965
|
-
const str = qs.toString();
|
|
1966
|
-
return str ? `?${str}` : '';
|
|
1967
|
-
}
|
|
1968
|
-
|
|
1969
|
-
async function fetchReportJson(url, fail) {
|
|
1970
|
-
let response;
|
|
1971
|
-
try {
|
|
1972
|
-
response = await fetch(url, { signal: AbortSignal.timeout(20_000) });
|
|
1973
|
-
} catch (err) {
|
|
1974
|
-
const msg = (err?.name === 'TimeoutError' || err?.name === 'AbortError')
|
|
1975
|
-
? `Timed out waiting for ${url}`
|
|
1976
|
-
: `Agent unreachable: ${err?.message || String(err)}`;
|
|
1977
|
-
fail(msg);
|
|
1978
|
-
return null;
|
|
1979
|
-
}
|
|
1980
|
-
let data = null;
|
|
1981
|
-
try {
|
|
1982
|
-
data = await response.json();
|
|
1983
|
-
} catch { /* empty or non-JSON body */ }
|
|
1984
|
-
if (!response.ok) {
|
|
1985
|
-
fail(data?.error || `Agent returned HTTP ${response.status}`);
|
|
1986
|
-
return null;
|
|
1987
|
-
}
|
|
1988
|
-
return data;
|
|
1989
|
-
}
|
|
1990
|
-
|
|
1991
|
-
async function executeReportSummaryCommand(options) {
|
|
1992
|
-
const fail = (error) => {
|
|
1993
|
-
if (options.json) {
|
|
1994
|
-
console.log(JSON.stringify({ ok: false, error }));
|
|
1995
|
-
} else {
|
|
1996
|
-
console.error(`❌ Error: ${error}`);
|
|
1997
|
-
}
|
|
1998
|
-
process.exit(1);
|
|
1999
|
-
};
|
|
2000
|
-
|
|
2001
|
-
const qs = buildQueryString({ from: options.from, to: options.to, network: options.network });
|
|
2002
|
-
const data = await fetchReportJson(`${options.url}/api/reporting/summary${qs}`, fail);
|
|
2003
|
-
if (!data) return; // fail() already exited
|
|
2004
|
-
|
|
2005
|
-
if (options.json) {
|
|
2006
|
-
console.log(JSON.stringify(data, null, 2));
|
|
2007
|
-
return;
|
|
2008
|
-
}
|
|
2009
|
-
|
|
2010
|
-
console.log('📊 Nirium Reporting Summary');
|
|
2011
|
-
console.log(` Network: ${data.network}`);
|
|
2012
|
-
console.log(` Period: ${data.period?.from || '(default window)'} -> ${data.period?.to || 'now'}`);
|
|
2013
|
-
console.log(` Payroll: ${data.payroll?.settledRuns ?? 0} settled run(s), ${data.payroll?.recipientsPaid ?? 0} recipient(s) paid`);
|
|
2014
|
-
for (const [asset, amount] of Object.entries(data.payroll?.totalsByAsset || {})) {
|
|
2015
|
-
console.log(` ${asset}: ${amount}`);
|
|
2016
|
-
}
|
|
2017
|
-
console.log(` Payments: ${data.payments?.count ?? 0} receipt(s), ${data.payments?.totalUsdc ?? '0'} USDC total`);
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
console.log(
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
const
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
}
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
}
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// ═══════════════════════════════════════════════════════════════
|
|
4
|
+
// Nirium — Autonomous Agent CLI (v2.0.1)
|
|
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.
|
|
12
|
+
|
|
13
|
+
import { Command, Option } from 'commander';
|
|
14
|
+
import fs from 'fs';
|
|
15
|
+
import path from 'path';
|
|
16
|
+
import os from 'os';
|
|
17
|
+
import crypto from 'crypto';
|
|
18
|
+
import readline from 'readline';
|
|
19
|
+
import { execSync } from 'child_process';
|
|
20
|
+
import { fileURLToPath } from 'url';
|
|
21
|
+
import express from 'express';
|
|
22
|
+
import { Agent as NiriumAgent, x402Serve } from 'nirium';
|
|
23
|
+
import { Keypair, StrKey } from '@stellar/stellar-sdk';
|
|
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
|
+
|
|
38
|
+
const program = new Command();
|
|
39
|
+
|
|
40
|
+
program
|
|
41
|
+
.name('nirium')
|
|
42
|
+
.description('Nirium protocol development tool')
|
|
43
|
+
.version(readCliVersion());
|
|
44
|
+
|
|
45
|
+
// --- COMMAND: create bot ---
|
|
46
|
+
program
|
|
47
|
+
.command('create')
|
|
48
|
+
.argument('<type>', 'What to create: x402 (a server that charges) or bot (a signal listener)')
|
|
49
|
+
.option('-n, --name <name>', 'Name of the project', 'nirium-bot-v1')
|
|
50
|
+
.option('-t, --template <template>', 'Language template (ts, py) — bot only', 'ts')
|
|
51
|
+
.description('Scaffold a new Nirium project')
|
|
52
|
+
.action(async (type, options) => {
|
|
53
|
+
if (type !== 'bot' && type !== 'x402') {
|
|
54
|
+
console.error('❌ Error: type must be "x402" (charge for your API) or "bot" (listen to signals).');
|
|
55
|
+
process.exit(1);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const targetDir = path.join(process.cwd(), options.name);
|
|
59
|
+
|
|
60
|
+
if (fs.existsSync(targetDir)) {
|
|
61
|
+
console.error(`❌ Error: Directory ${options.name} already exists.`);
|
|
62
|
+
process.exit(1);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
console.log(type === 'x402'
|
|
66
|
+
? `\n💸 [Scaffold] Creating x402 paid API: ${options.name}...`
|
|
67
|
+
: `\n🧬 [Scaffold] Creating ${options.template === 'ts' ? 'TypeScript' : 'Python'} bot: ${options.name}...`);
|
|
68
|
+
|
|
69
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
70
|
+
|
|
71
|
+
if (type === 'x402') {
|
|
72
|
+
scaffoldX402(targetDir, options.name);
|
|
73
|
+
} else if (options.template === 'ts') {
|
|
74
|
+
scaffoldTS(targetDir, options.name);
|
|
75
|
+
} else {
|
|
76
|
+
scaffoldPY(targetDir, options.name);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
console.log(`\n✅ Project initialized in ./${options.name}`);
|
|
80
|
+
console.log(`\n🚀 Get started:`);
|
|
81
|
+
console.log(` cd ${options.name}`);
|
|
82
|
+
if (options.template === 'ts') {
|
|
83
|
+
console.log(` npm install`);
|
|
84
|
+
console.log(` npm run dev`);
|
|
85
|
+
} else {
|
|
86
|
+
console.log(` python -m venv venv`);
|
|
87
|
+
console.log(` source venv/bin/activate`);
|
|
88
|
+
console.log(` pip install -r requirements.txt`);
|
|
89
|
+
console.log(` python main.py`);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// --- COMMAND: status ---
|
|
94
|
+
program
|
|
95
|
+
.command('status')
|
|
96
|
+
.description('Check agent connection status')
|
|
97
|
+
.option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
|
|
98
|
+
.option('--json', 'Output the raw /health fields plus ok, as JSON')
|
|
99
|
+
.option('--timeout <ms>', 'Give up after this many milliseconds', '5000')
|
|
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;
|
|
113
|
+
try {
|
|
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) {
|
|
147
|
+
console.log(` Version: ${data.version}`);
|
|
148
|
+
}
|
|
149
|
+
if (data?.network !== undefined && data.network !== null) {
|
|
150
|
+
console.log(` Network: ${data.network}`);
|
|
151
|
+
}
|
|
152
|
+
if (data?.uptime !== undefined && data.uptime !== null) {
|
|
153
|
+
console.log(` Uptime: ${data.uptime}s`);
|
|
154
|
+
}
|
|
155
|
+
} else {
|
|
156
|
+
console.log('🔴 Agent returned error:', response.status);
|
|
157
|
+
process.exit(1);
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// Tried in order when no --gateway is given. ipfs.io and dweb.link answer 429
|
|
162
|
+
// for healthy CIDs under load (#185), and Pinata serves our pins but often
|
|
163
|
+
// takes 5-7s, so a dedicated gateway goes first. Same chain as the
|
|
164
|
+
// verify-audit-cid Action (#259), plus Pinata.
|
|
165
|
+
const DEFAULT_GATEWAYS = [
|
|
166
|
+
'https://nirium.myfilebase.com',
|
|
167
|
+
'https://gateway.pinata.cloud',
|
|
168
|
+
'https://ipfs.io',
|
|
169
|
+
'https://dweb.link',
|
|
170
|
+
];
|
|
171
|
+
|
|
172
|
+
// --- COMMAND: verify ---
|
|
173
|
+
program
|
|
174
|
+
.command('verify')
|
|
175
|
+
.argument('<cid>', 'IPFS Content Identifier (CID) of the audit document')
|
|
176
|
+
.option('-g, --gateway <url>', 'IPFS gateway URL - repeatable, tried in order as fallbacks (default: Filebase, Pinata, ipfs.io, dweb.link)', (val, prev) => [...(prev || []), val], [])
|
|
177
|
+
.option('--retries <n>', 'Retries per gateway on a 404 (content may not be propagated yet), with backoff', '2')
|
|
178
|
+
.option('--timeout <ms>', 'Per-request timeout in milliseconds', '8000')
|
|
179
|
+
.option('--json', 'Output result as JSON')
|
|
180
|
+
.option('--hash <hex>', 'Expected sha-256 of the evidence (hex, optional sha-256: prefix), for hash-only anchors')
|
|
181
|
+
.option('--evidence <file>', 'Original evidence file; its sha-256 is compared with the anchored hash')
|
|
182
|
+
.description('Independently verify IPFS audit document content hash & agent ed25519 signature')
|
|
183
|
+
.action(async (cid, options) => {
|
|
184
|
+
let expectedHash;
|
|
185
|
+
try {
|
|
186
|
+
if (options.hash && options.evidence) throw new Error('Use either --hash or --evidence, not both');
|
|
187
|
+
if (options.hash) expectedHash = normalizeHashInput(options.hash);
|
|
188
|
+
if (options.evidence) expectedHash = crypto.createHash('sha256').update(fs.readFileSync(options.evidence)).digest('hex');
|
|
189
|
+
} catch (err) {
|
|
190
|
+
console.error(`❌ ${err.message}`);
|
|
191
|
+
process.exit(1);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const retries = Number(options.retries);
|
|
195
|
+
const timeoutMs = Number(options.timeout);
|
|
196
|
+
if (!Number.isInteger(retries) || retries < 0) {
|
|
197
|
+
console.error(`❌ Error: Invalid --retries '${options.retries}': must be a non-negative integer.`);
|
|
198
|
+
process.exit(1);
|
|
199
|
+
}
|
|
200
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
201
|
+
console.error(`❌ Error: Invalid --timeout '${options.timeout}': must be a positive number of milliseconds.`);
|
|
202
|
+
process.exit(1);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const gateways = options.gateway.length > 0 ? options.gateway : DEFAULT_GATEWAYS;
|
|
206
|
+
const result = await fetchAndVerifyCid(cid, gateways, globalThis.fetch, { expectedHash, retries, timeoutMs });
|
|
207
|
+
if (options.json) {
|
|
208
|
+
console.log(JSON.stringify(result, null, 2));
|
|
209
|
+
} else {
|
|
210
|
+
console.log(formatVerifyOutput(result));
|
|
211
|
+
}
|
|
212
|
+
if (!result.ok) {
|
|
213
|
+
process.exit(1);
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// --- COMMAND: anchor ---
|
|
218
|
+
program
|
|
219
|
+
.command('anchor')
|
|
220
|
+
.description('Anchor a sha-256 hash (or a small JSON record) to IPFS via an Audit Trail node')
|
|
221
|
+
.option('--file <path>', 'Anchor the sha-256 of this file - the file itself is never uploaded')
|
|
222
|
+
.option('--hash <hex>', 'sha-256 hex of your evidence (64 chars, optional sha-256: prefix)')
|
|
223
|
+
.option('--record <json>', 'Small JSON object (max 8KB) to anchor verbatim, e.g. \'{"order":"A-12"}\'')
|
|
224
|
+
.option('--tx <hash>', 'Transaction hash to associate with this anchor')
|
|
225
|
+
.option('--tag <tag>', 'Free-form label for this anchor')
|
|
226
|
+
.option('--sign', 'Attach an ed25519 attestation of which key produced this anchor')
|
|
227
|
+
.option('--key-env <VAR>', 'Environment variable holding the Stellar secret key to sign with (--sign only; default: the config store\'s secretKey)')
|
|
228
|
+
.option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
|
|
229
|
+
.option('--json', 'Output result as JSON')
|
|
230
|
+
.action(async (options) => {
|
|
231
|
+
await executeAnchorCommand(options);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
// --- COMMAND: doctor ---
|
|
235
|
+
program
|
|
236
|
+
.command('doctor')
|
|
237
|
+
.description('CLI preflight diagnostics for x402 misconfiguration (the MPP check only validates config), or a remote seller with --seller')
|
|
238
|
+
.option('-n, --network <network>', 'Stellar network: testnet or pubnet', 'testnet')
|
|
239
|
+
.option('-c, --config <path>', 'Path to environment or config file')
|
|
240
|
+
.option('--seller <url>', 'Validate a remote x402 seller at this URL without paying')
|
|
241
|
+
.option('--json', 'Output results as JSON for CI integration')
|
|
242
|
+
.action(async (options) => {
|
|
243
|
+
const report = options.seller
|
|
244
|
+
? await runDoctorSeller(options.seller)
|
|
245
|
+
: await runDoctorDiagnostics(options);
|
|
246
|
+
if (options.json) {
|
|
247
|
+
console.log(JSON.stringify(report, null, 2));
|
|
248
|
+
} else {
|
|
249
|
+
console.log(formatDoctorOutput(report));
|
|
250
|
+
}
|
|
251
|
+
if (!report.ok) {
|
|
252
|
+
process.exit(1);
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
// --- COMMAND: pay ---
|
|
257
|
+
program
|
|
258
|
+
.command('pay')
|
|
259
|
+
.description('💳 Pay an x402-protected endpoint straight from the terminal with Stellar auth entry signing')
|
|
260
|
+
.argument('<url>', 'URL of the x402-protected endpoint')
|
|
261
|
+
.option('--max-amount <usd>', 'Refuse to pay more than this, e.g. 5 or $0.50 (default: no cap beyond the SDK default)')
|
|
262
|
+
.option('-n, --network <network>', 'CAIP-2 network ID (stellar:testnet or stellar:pubnet)', 'stellar:testnet')
|
|
263
|
+
.option('-c, --config <path>', 'Custom path to configuration file or .env')
|
|
264
|
+
.option('--json', 'Output execution result as JSON')
|
|
265
|
+
.action(async (url, options) => {
|
|
266
|
+
await executePayCommand(url, options);
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
// --- COMMAND: serve ---
|
|
270
|
+
program
|
|
271
|
+
.command('serve')
|
|
272
|
+
.description('🚀 Spin up a local x402-protected demo HTTP server to test payments against')
|
|
273
|
+
.option('-p, --price <price>', 'Price for access (e.g. $0.02)', '$0.02')
|
|
274
|
+
.option('-P, --pay-to <address>', 'Stellar public key (G...) to receive payments')
|
|
275
|
+
.option('--port <port>', 'Port number to listen on', '3000')
|
|
276
|
+
.option('-n, --network <network>', 'CAIP-2 network ID (stellar:testnet or stellar:pubnet)', 'stellar:testnet')
|
|
277
|
+
.option('-r, --route <route>', 'Route path to protect', '/api/v1/data')
|
|
278
|
+
// Kept only to refuse it with a clear message: commander's own
|
|
279
|
+
// "unknown option" would not tell the user the key is now exposed.
|
|
280
|
+
.addOption(new Option('-k, --api-key <key>').hideHelp())
|
|
281
|
+
.option('-c, --config <path>', 'Custom path to config file')
|
|
282
|
+
.action(async (options) => {
|
|
283
|
+
await executeServeCommand(options);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
// --- COMMAND: config ---
|
|
287
|
+
program
|
|
288
|
+
.command('config')
|
|
289
|
+
.description('⚙️ Manage local CLI configuration store (~/.niriumrc.json)')
|
|
290
|
+
.argument('[action]', 'Action to perform: set, get, list, or delete', 'list')
|
|
291
|
+
.argument('[key]', 'Configuration key name')
|
|
292
|
+
.argument('[value]', 'Value to set for the configuration key')
|
|
293
|
+
.action(async (action, key, value) => {
|
|
294
|
+
await executeConfigCommand(action, key, value);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
// --- COMMAND: report ---
|
|
298
|
+
const reportCommand = program
|
|
299
|
+
.command('report')
|
|
300
|
+
.description('📊 Institutional-format summaries and exports from the Reporting node - not certified regulatory reporting');
|
|
301
|
+
|
|
302
|
+
reportCommand
|
|
303
|
+
.command('summary')
|
|
304
|
+
.description('Aggregate payroll, payments, and anchors for a period')
|
|
305
|
+
.option('--from <date>', 'ISO date, start of period (default: a 30-day window)')
|
|
306
|
+
.option('--to <date>', 'ISO date, end of period')
|
|
307
|
+
.option('--network <network>', 'testnet or mainnet (default: all)')
|
|
308
|
+
.option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
|
|
309
|
+
.option('--json', 'Output as JSON')
|
|
310
|
+
.action(async (options) => {
|
|
311
|
+
await executeReportSummaryCommand(options);
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
reportCommand
|
|
315
|
+
.command('export')
|
|
316
|
+
.argument('<type>', 'anchors, payments, or payroll')
|
|
317
|
+
.description('Export rows for a period - "export anchors" prints one CID per line, pipeable to `nirium verify`')
|
|
318
|
+
.option('--from <date>', 'ISO date, start of period (default: a 30-day window)')
|
|
319
|
+
.option('--to <date>', 'ISO date, end of period')
|
|
320
|
+
.option('--limit <n>', 'Max rows (server caps at 1000)')
|
|
321
|
+
.option('--network <network>', 'testnet or mainnet (default: all)')
|
|
322
|
+
.option('--csv <file>', 'Write the CSV export to this file instead of printing rows')
|
|
323
|
+
.option('-u, --url <url>', 'Agent URL', 'http://localhost:3002')
|
|
324
|
+
.option('--json', 'Output the full JSON response instead of one row per line')
|
|
325
|
+
.action(async (type, options) => {
|
|
326
|
+
await executeReportExportCommand(type, options);
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
// Un servidor que COBRA, no uno que escucha. Es el camino corto de
|
|
330
|
+
// "instalé algo" a "me pagaron": levantas esto, le pegas con un cliente
|
|
331
|
+
// x402 y el pago se liquida on-chain antes de que salga la respuesta.
|
|
332
|
+
function scaffoldX402(dir, name) {
|
|
333
|
+
const pkgJson = {
|
|
334
|
+
name,
|
|
335
|
+
version: '0.1.0',
|
|
336
|
+
private: true,
|
|
337
|
+
type: 'module',
|
|
338
|
+
scripts: { dev: 'tsx watch src/server.ts', build: 'tsc' },
|
|
339
|
+
dependencies: {
|
|
340
|
+
nirium: '^0.16.0',
|
|
341
|
+
express: '^5.1.0',
|
|
342
|
+
'@x402/express': '^2.17.0',
|
|
343
|
+
'@x402/core': '^2.17.0',
|
|
344
|
+
'@x402/stellar': '^2.17.0',
|
|
345
|
+
tsx: '^4.19.0',
|
|
346
|
+
typescript: '^5.7.0',
|
|
347
|
+
dotenv: '^16.4.5',
|
|
348
|
+
},
|
|
349
|
+
devDependencies: { '@types/node': '^20.19.0', '@types/express': '^5.0.0' },
|
|
350
|
+
};
|
|
351
|
+
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkgJson, null, 2));
|
|
352
|
+
|
|
353
|
+
fs.mkdirSync(path.join(dir, 'src'), { recursive: true });
|
|
354
|
+
fs.writeFileSync(path.join(dir, 'src', 'server.ts'), `
|
|
355
|
+
import express from 'express';
|
|
356
|
+
import { x402Serve } from 'nirium';
|
|
357
|
+
import 'dotenv/config';
|
|
358
|
+
|
|
359
|
+
const app = express();
|
|
360
|
+
|
|
361
|
+
// Todo lo que va debajo de /premium cobra antes de responder.
|
|
362
|
+
// El pago se liquida on-chain: si no pagaron, tu handler nunca corre.
|
|
363
|
+
app.use('/premium', x402Serve({
|
|
364
|
+
payTo: process.env.STELLAR_PAY_TO!, // tu cuenta G...
|
|
365
|
+
facilitatorApiKey: process.env.X402_FACILITATOR_API_KEY!,
|
|
366
|
+
network: (process.env.STELLAR_NETWORK === 'mainnet' ? 'stellar:pubnet' : 'stellar:testnet'),
|
|
367
|
+
routes: {
|
|
368
|
+
'GET /signals': '$0.02',
|
|
369
|
+
},
|
|
370
|
+
}));
|
|
371
|
+
|
|
372
|
+
app.get('/premium/signals', (_req, res) => {
|
|
373
|
+
res.json({ signals: [{ pair: 'USDC/CETES', edge: '0.42%' }] });
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
app.listen(3000, () => console.log('💸 cobrando en http://localhost:3000/premium/signals'));
|
|
377
|
+
`.trimStart());
|
|
378
|
+
|
|
379
|
+
fs.writeFileSync(path.join(dir, '.env'),
|
|
380
|
+
'STELLAR_PAY_TO=\n'
|
|
381
|
+
+ '# Llave GRATIS y POR RED — una de mainnet da 401 contra testnet:\n'
|
|
382
|
+
+ '# testnet https://channels.openzeppelin.com/testnet/gen\n'
|
|
383
|
+
+ '# mainnet https://channels.openzeppelin.com/gen\n'
|
|
384
|
+
+ 'X402_FACILITATOR_API_KEY=\n'
|
|
385
|
+
+ 'STELLAR_NETWORK=testnet\n');
|
|
386
|
+
|
|
387
|
+
fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
|
|
388
|
+
compilerOptions: {
|
|
389
|
+
target: 'ES2022', module: 'ESNext', moduleResolution: 'bundler',
|
|
390
|
+
strict: true, esModuleInterop: true, skipLibCheck: true, outDir: 'dist',
|
|
391
|
+
},
|
|
392
|
+
include: ['src'],
|
|
393
|
+
}, null, 2));
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function scaffoldTS(dir, name) {
|
|
397
|
+
const pkgJson = {
|
|
398
|
+
name,
|
|
399
|
+
version: '0.1.0',
|
|
400
|
+
private: true,
|
|
401
|
+
scripts: {
|
|
402
|
+
"dev": "tsx watch src/index.ts",
|
|
403
|
+
"build": "tsc"
|
|
404
|
+
},
|
|
405
|
+
dependencies: {
|
|
406
|
+
"nirium": "^0.16.0",
|
|
407
|
+
"tsx": "^4.19.0",
|
|
408
|
+
"typescript": "^5.7.0",
|
|
409
|
+
"dotenv": "^16.4.5"
|
|
410
|
+
},
|
|
411
|
+
devDependencies: {
|
|
412
|
+
"@types/node": "^20.19.0"
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkgJson, null, 2));
|
|
417
|
+
fs.mkdirSync(path.join(dir, 'src'));
|
|
418
|
+
|
|
419
|
+
const indexSrc = `
|
|
420
|
+
import { Agent } from 'nirium';
|
|
421
|
+
import 'dotenv/config';
|
|
422
|
+
|
|
423
|
+
const agent = new Agent({
|
|
424
|
+
baseUrl: process.env.NIRIUM_API_URL || 'https://nirium-agent.fly.dev',
|
|
425
|
+
apiKey: process.env.NIRIUM_API_KEY
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
agent.subscribe((signal) => {
|
|
429
|
+
console.log('🧬 [Signal Received]:', signal.signal_type, signal.pair);
|
|
430
|
+
// Logic to execute on signals...
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
console.log('✅ Listening for Nirium signals...');
|
|
434
|
+
`;
|
|
435
|
+
fs.writeFileSync(path.join(dir, 'src', 'index.ts'), indexSrc);
|
|
436
|
+
fs.writeFileSync(path.join(dir, '.env'), 'NIRIUM_API_URL=https://nirium-agent.fly.dev\nNIRIUM_API_KEY=');
|
|
437
|
+
fs.writeFileSync(path.join(dir, 'tsconfig.json'), JSON.stringify({
|
|
438
|
+
compilerOptions: {
|
|
439
|
+
target: "es2022",
|
|
440
|
+
module: "nodenext",
|
|
441
|
+
strict: true,
|
|
442
|
+
esModuleInterop: true,
|
|
443
|
+
skipLibCheck: true
|
|
444
|
+
}
|
|
445
|
+
}, null, 2));
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function scaffoldPY(dir, name) {
|
|
449
|
+
const reqs = "nirium>=0.9.0\npython-dotenv>=1.0.0";
|
|
450
|
+
fs.writeFileSync(path.join(dir, 'requirements.txt'), reqs);
|
|
451
|
+
|
|
452
|
+
const mainSrc = `
|
|
453
|
+
import asyncio
|
|
454
|
+
import os
|
|
455
|
+
from nirium import Agent
|
|
456
|
+
from dotenv import load_dotenv
|
|
457
|
+
|
|
458
|
+
load_dotenv()
|
|
459
|
+
|
|
460
|
+
async def main():
|
|
461
|
+
agent = Agent(
|
|
462
|
+
api_url=os.getenv("NIRIUM_API_URL", "https://nirium-agent.fly.dev"),
|
|
463
|
+
api_key=os.getenv("NIRIUM_API_KEY")
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
@agent.on("signal")
|
|
467
|
+
async def handle_signal(signal):
|
|
468
|
+
print(f"🧬 [Signal]: {signal['signal_type']} on {signal['pair']}")
|
|
469
|
+
|
|
470
|
+
@agent.on("connected")
|
|
471
|
+
async def on_connect(data):
|
|
472
|
+
print("✅ Connected to Nirium Neural Loop")
|
|
473
|
+
|
|
474
|
+
await agent.subscribe()
|
|
475
|
+
|
|
476
|
+
if __name__ == "__main__":
|
|
477
|
+
asyncio.run(main())
|
|
478
|
+
`;
|
|
479
|
+
fs.writeFileSync(path.join(dir, 'main.py'), mainSrc);
|
|
480
|
+
fs.writeFileSync(path.join(dir, '.env'), 'NIRIUM_API_URL=https://nirium-agent.fly.dev\nNIRIUM_API_KEY=');
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// ═══════════════════════════════════════════════════════════════
|
|
484
|
+
// config — ~/.niriumrc.json store, shared by pay/serve/config
|
|
485
|
+
// ═══════════════════════════════════════════════════════════════
|
|
486
|
+
|
|
487
|
+
const CONFIG_FILE = path.join(os.homedir(), '.niriumrc.json');
|
|
488
|
+
|
|
489
|
+
function loadConfig(customPath) {
|
|
490
|
+
const filePath = customPath || CONFIG_FILE;
|
|
491
|
+
try {
|
|
492
|
+
if (fs.existsSync(filePath)) {
|
|
493
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
494
|
+
return JSON.parse(raw);
|
|
495
|
+
}
|
|
496
|
+
} catch {
|
|
497
|
+
// Ignore read errors gracefully
|
|
498
|
+
}
|
|
499
|
+
return {};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function saveConfig(config, customPath) {
|
|
503
|
+
const filePath = customPath || CONFIG_FILE;
|
|
504
|
+
try {
|
|
505
|
+
fs.writeFileSync(filePath, JSON.stringify(config, null, 2), {
|
|
506
|
+
encoding: 'utf8',
|
|
507
|
+
mode: 0o600,
|
|
508
|
+
});
|
|
509
|
+
// Enforce permissions even on pre-existing files (writeFileSync mode
|
|
510
|
+
// only applies when the file is created, not when it already exists).
|
|
511
|
+
try {
|
|
512
|
+
fs.chmodSync(filePath, 0o600);
|
|
513
|
+
} catch {
|
|
514
|
+
// best effort on platforms without POSIX permissions (e.g. some Windows setups)
|
|
515
|
+
}
|
|
516
|
+
} catch (err) {
|
|
517
|
+
throw new Error(`Failed to save config to ${filePath}: ${err?.message || String(err)}`);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function maskSecret(secret) {
|
|
522
|
+
if (!secret) return '(not set)';
|
|
523
|
+
if (secret.length <= 8) return 'S****';
|
|
524
|
+
return `${secret.slice(0, 4)}...${secret.slice(-4)}`;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// `--max-amount` is a USD figure ("5", "$5", "0.50"), not atomic units.
|
|
528
|
+
// Rejects 0, negative and non-numeric so a typo fails before any network
|
|
529
|
+
// call instead of silently capping at $0 or NaN (which compares false to
|
|
530
|
+
// everything and would let every payment through).
|
|
531
|
+
function parseMaxAmountUsd(raw) {
|
|
532
|
+
const stripped = raw.startsWith('$') ? raw.slice(1) : raw;
|
|
533
|
+
const usd = Number(stripped);
|
|
534
|
+
if (!Number.isFinite(usd) || usd <= 0) {
|
|
535
|
+
throw new Error(`Invalid --max-amount '${raw}': must be a positive USD amount, e.g. --max-amount 5 or --max-amount '$0.50'.`);
|
|
536
|
+
}
|
|
537
|
+
return usd;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// A secret passed as a CLI argument sits in the shell history file and
|
|
541
|
+
// in `ps`'s full command line for anyone else on the machine to read —
|
|
542
|
+
// true for any process, not just this one. `pay` used to take `--secret`
|
|
543
|
+
// for exactly that reason, so this prompt is the replacement: it reads
|
|
544
|
+
// from the terminal without echoing the input and without it ever
|
|
545
|
+
// becoming a process argument. Only used when neither NIRIUM_SECRET_KEY
|
|
546
|
+
// nor the config store already has a key.
|
|
547
|
+
function promptHiddenSecret(question) {
|
|
548
|
+
return new Promise((resolve, reject) => {
|
|
549
|
+
if (!process.stdin.isTTY) {
|
|
550
|
+
reject(new Error('no interactive terminal to prompt on'));
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
554
|
+
// readline always echoes keystrokes to `output`; the only hook it
|
|
555
|
+
// gives you to stop that is overriding the writer it calls internally.
|
|
556
|
+
const realWrite = rl._writeToOutput;
|
|
557
|
+
rl._writeToOutput = function (str) {
|
|
558
|
+
// Pass the prompt text itself through once, then swallow every
|
|
559
|
+
// character typed after it — nothing from the secret reaches
|
|
560
|
+
// the terminal, not even asterisks that could leak its length.
|
|
561
|
+
if (str === question) realWrite.call(rl, str);
|
|
562
|
+
};
|
|
563
|
+
rl.question(question, (answer) => {
|
|
564
|
+
rl.history = rl.history.slice(1); // readline records the answer in its own history buffer
|
|
565
|
+
rl._writeToOutput = realWrite;
|
|
566
|
+
rl.close();
|
|
567
|
+
process.stdout.write('\n');
|
|
568
|
+
resolve(answer.trim());
|
|
569
|
+
});
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// Credentials that `config set` never takes as an argument.
|
|
574
|
+
const SECRET_CONFIG_KEYS = {
|
|
575
|
+
secretKey: {
|
|
576
|
+
prompt: 'Stellar secret key (S...): ',
|
|
577
|
+
valid: (v) => StrKey.isValidEd25519SecretSeed(v),
|
|
578
|
+
invalid: 'not a valid Stellar secret key (expected S...).',
|
|
579
|
+
},
|
|
580
|
+
facilitatorApiKey: {
|
|
581
|
+
prompt: 'Facilitator API key: ',
|
|
582
|
+
valid: (v) => typeof v === 'string' && v.length > 0,
|
|
583
|
+
invalid: 'the facilitator API key is empty.',
|
|
584
|
+
},
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
// Hidden prompt on a terminal, stdin otherwise. Never a process argument.
|
|
588
|
+
// `timeoutMs` (stdin only) resolves to '' when nothing finishes arriving in
|
|
589
|
+
// time, so a caller that has no other source for the value can fail with its
|
|
590
|
+
// own "missing key" error instead of waiting on a pipe that never closes.
|
|
591
|
+
async function readSecretInput(question, { timeoutMs } = {}) {
|
|
592
|
+
if (process.stdin.isTTY) return promptHiddenSecret(question);
|
|
593
|
+
const read = (async () => {
|
|
594
|
+
const chunks = [];
|
|
595
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
596
|
+
return Buffer.concat(chunks).toString('utf8').trim();
|
|
597
|
+
})();
|
|
598
|
+
if (!timeoutMs) return read;
|
|
599
|
+
let timer;
|
|
600
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(''), timeoutMs); });
|
|
601
|
+
try {
|
|
602
|
+
return await Promise.race([read, timeout]);
|
|
603
|
+
} finally {
|
|
604
|
+
clearTimeout(timer);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
const SERVE_STDIN_TIMEOUT_MS = Number(process.env.NIRIUM_STDIN_TIMEOUT_MS) || 10_000;
|
|
609
|
+
|
|
610
|
+
async function executeConfigCommand(action, key, value) {
|
|
611
|
+
const currentConfig = loadConfig();
|
|
612
|
+
|
|
613
|
+
if (!action || action === 'list') {
|
|
614
|
+
console.log('⚙️ Nirium CLI Configuration:');
|
|
615
|
+
console.log(` secretKey: ${maskSecret(currentConfig.secretKey)}`);
|
|
616
|
+
console.log(` payTo: ${currentConfig.payTo || '(not set)'}`);
|
|
617
|
+
console.log(` network: ${currentConfig.network || '(default: stellar:testnet)'}`);
|
|
618
|
+
console.log(` facilitatorApiKey: ${maskSecret(currentConfig.facilitatorApiKey)}`);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
if (action === 'get') {
|
|
623
|
+
if (!key) {
|
|
624
|
+
console.error('❌ Error: Please specify a configuration key (e.g. `nirium config get secretKey`)');
|
|
625
|
+
process.exit(1);
|
|
626
|
+
}
|
|
627
|
+
const val = currentConfig[key];
|
|
628
|
+
if (key.toLowerCase().includes('secret') || key.toLowerCase().includes('key')) {
|
|
629
|
+
console.log(`${key}: ${maskSecret(val)}`);
|
|
630
|
+
} else {
|
|
631
|
+
console.log(`${key}: ${val || '(not set)'}`);
|
|
632
|
+
}
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const secretSpec = action === 'set' ? SECRET_CONFIG_KEYS[key] : undefined;
|
|
637
|
+
if (secretSpec) {
|
|
638
|
+
// Same reason `pay` has no --secret: an argument ends up in the shell
|
|
639
|
+
// history file and in `ps` output. Refuse it instead of storing it.
|
|
640
|
+
if (value !== undefined) {
|
|
641
|
+
console.error(`❌ Error: \`nirium config set ${key}\` does not take the value as an argument.\n`
|
|
642
|
+
+ 'A credential typed on the command line stays in your shell history and is visible in `ps` '
|
|
643
|
+
+ 'to other users on this machine, so it was NOT saved. Treat the value you typed as exposed.\n'
|
|
644
|
+
+ `Run \`nirium config set ${key}\` with no value to get a hidden prompt, `
|
|
645
|
+
+ 'or pipe it on stdin from a file or secret manager.');
|
|
646
|
+
process.exit(1);
|
|
647
|
+
}
|
|
648
|
+
const secret = await readSecretInput(secretSpec.prompt);
|
|
649
|
+
if (!secretSpec.valid(secret)) {
|
|
650
|
+
console.error(`❌ Error: ${secretSpec.invalid} Nothing was saved.`);
|
|
651
|
+
process.exit(1);
|
|
652
|
+
}
|
|
653
|
+
saveConfig({ ...currentConfig, [key]: secret });
|
|
654
|
+
console.log(`✅ Configuration updated: ${key} set successfully.`);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
if (action === 'set') {
|
|
659
|
+
if (!key || value === undefined) {
|
|
660
|
+
console.error('❌ Error: Usage: `nirium config set <key> <value>` (e.g., `nirium config set payTo G...`). '
|
|
661
|
+
+ 'For secretKey or facilitatorApiKey, run `nirium config set <key>` with no value.');
|
|
662
|
+
process.exit(1);
|
|
663
|
+
}
|
|
664
|
+
const updatedConfig = { ...currentConfig, [key]: value };
|
|
665
|
+
saveConfig(updatedConfig);
|
|
666
|
+
console.log(`✅ Configuration updated: ${key} set successfully.`);
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
if (action === 'delete' || action === 'remove') {
|
|
671
|
+
if (!key) {
|
|
672
|
+
console.error('❌ Error: Please specify a configuration key to delete.');
|
|
673
|
+
process.exit(1);
|
|
674
|
+
}
|
|
675
|
+
delete currentConfig[key];
|
|
676
|
+
saveConfig(currentConfig);
|
|
677
|
+
console.log(`✅ Removed ${key} from configuration.`);
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
console.error(`❌ Unknown config action: ${action}. Use set, get, list, or delete.`);
|
|
682
|
+
process.exit(1);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// ═══════════════════════════════════════════════════════════════
|
|
686
|
+
// pay — sign and settle an x402 payment from the terminal
|
|
687
|
+
// ═══════════════════════════════════════════════════════════════
|
|
688
|
+
|
|
689
|
+
async function executePayCommand(url, options) {
|
|
690
|
+
const config = loadConfig(options.config);
|
|
691
|
+
const network = options.network || process.env.NIRIUM_NETWORK || config.network || 'stellar:testnet';
|
|
692
|
+
|
|
693
|
+
let maxAmountUsd;
|
|
694
|
+
if (options.maxAmount !== undefined) {
|
|
695
|
+
try {
|
|
696
|
+
maxAmountUsd = parseMaxAmountUsd(options.maxAmount);
|
|
697
|
+
} catch (err) {
|
|
698
|
+
if (options.json) {
|
|
699
|
+
console.log(JSON.stringify({ status: 'error', error: err.message }));
|
|
700
|
+
process.exit(1);
|
|
701
|
+
}
|
|
702
|
+
console.error(`❌ Error: ${err.message}`);
|
|
703
|
+
process.exit(1);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
let secretKey = process.env.NIRIUM_SECRET_KEY || config.secretKey;
|
|
708
|
+
|
|
709
|
+
// `pay` no longer takes the secret as a flag (see #104): a --secret
|
|
710
|
+
// argument sits in the shell history and in `ps`'s full command line
|
|
711
|
+
// for anyone else on the box to read. Env var and config store are
|
|
712
|
+
// both still fine — neither is visible that way. The remaining gap is
|
|
713
|
+
// a one-off call with nothing configured yet, so prompt for it
|
|
714
|
+
// instead of failing outright, same as any CLI handling a real secret.
|
|
715
|
+
if (!secretKey && !options.json && process.stdin.isTTY) {
|
|
716
|
+
try {
|
|
717
|
+
secretKey = await promptHiddenSecret('Stellar secret key (S...): ');
|
|
718
|
+
} catch {
|
|
719
|
+
// falls through to the same missing-key error below
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
if (!secretKey) {
|
|
724
|
+
const errorMsg = 'Missing secret key for x402 payment authorization.\n'
|
|
725
|
+
+ 'Provide a secret key using:\n'
|
|
726
|
+
+ ' - `NIRIUM_SECRET_KEY` environment variable\n'
|
|
727
|
+
+ ' - the interactive prompt (run without --json, in a real terminal)\n'
|
|
728
|
+
+ 'There is no --secret flag: a key passed as a command-line argument '
|
|
729
|
+
+ 'would sit in your shell history and in `ps` output for anyone else '
|
|
730
|
+
+ 'on the machine to read.';
|
|
731
|
+
if (options.json) {
|
|
732
|
+
console.log(JSON.stringify({ status: 'error', error: errorMsg }));
|
|
733
|
+
process.exit(1);
|
|
734
|
+
}
|
|
735
|
+
console.error(`❌ Error: ${errorMsg}`);
|
|
736
|
+
process.exit(1);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
let publicKey = '';
|
|
740
|
+
try {
|
|
741
|
+
const kp = Keypair.fromSecret(secretKey);
|
|
742
|
+
publicKey = kp.publicKey();
|
|
743
|
+
} catch (err) {
|
|
744
|
+
const invalidMsg = `Invalid Stellar secret key format: ${err?.message || 'must start with S'}`;
|
|
745
|
+
if (options.json) {
|
|
746
|
+
console.log(JSON.stringify({ status: 'error', error: invalidMsg }));
|
|
747
|
+
process.exit(1);
|
|
748
|
+
}
|
|
749
|
+
console.error(`❌ Error: ${invalidMsg}`);
|
|
750
|
+
process.exit(1);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
if (!options.json) {
|
|
754
|
+
console.log(`⚡ Initiating x402 Payment Request`);
|
|
755
|
+
console.log(` Target URL: ${url}`);
|
|
756
|
+
console.log(` Network: ${network}`);
|
|
757
|
+
console.log(` Payer Key: ${publicKey}`);
|
|
758
|
+
console.log(` Secret: ${maskSecret(secretKey)}\n`);
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
try {
|
|
762
|
+
const agent = new NiriumAgent({ apiKey: 'nirium-cli-pay' });
|
|
763
|
+
if (maxAmountUsd !== undefined) {
|
|
764
|
+
// `initX402({ maxAmountPerPayment })` does not exist in any published
|
|
765
|
+
// `nirium` version yet (it is unreleased SDK source as of this PR), so
|
|
766
|
+
// --max-amount is enforced with the pre-sign policy hook instead, which
|
|
767
|
+
// IS published (0.16.0+) and runs before anything is signed. Stellar
|
|
768
|
+
// amounts are always int64 scaled by 1e7 regardless of asset, so the
|
|
769
|
+
// USD figure maps directly to atomic units without an asset lookup.
|
|
770
|
+
const capAtomic = BigInt(Math.round(maxAmountUsd * 1e7));
|
|
771
|
+
agent.initX402({
|
|
772
|
+
secretKey, network,
|
|
773
|
+
policy: {
|
|
774
|
+
evaluate: async (ctx) => {
|
|
775
|
+
if (BigInt(ctx.authorization.amount) <= capAtomic) {
|
|
776
|
+
return { decision: 'ALLOW', contextHash: ctx.contextHash };
|
|
777
|
+
}
|
|
778
|
+
return {
|
|
779
|
+
decision: 'DENY',
|
|
780
|
+
reason: `payment of ${ctx.authorization.amount} atomic units exceeds --max-amount ($${maxAmountUsd})`,
|
|
781
|
+
};
|
|
782
|
+
},
|
|
783
|
+
},
|
|
784
|
+
});
|
|
785
|
+
} else {
|
|
786
|
+
agent.initX402({ secretKey, network });
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
const startTime = Date.now();
|
|
790
|
+
const response = await agent.x402Fetch(url, {
|
|
791
|
+
method: 'GET',
|
|
792
|
+
headers: { 'User-Agent': 'Nirium-CLI-Pay/1.0' },
|
|
793
|
+
});
|
|
794
|
+
const durationMs = Date.now() - startTime;
|
|
795
|
+
|
|
796
|
+
const responseHeaders = Object.fromEntries(response.headers.entries());
|
|
797
|
+
const paymentResponseHeader = response.headers.get('payment-response')
|
|
798
|
+
|| response.headers.get('x-payment-response')
|
|
799
|
+
|| response.headers.get('payment-tx-hash')
|
|
800
|
+
|| '';
|
|
801
|
+
|
|
802
|
+
let txHash = '';
|
|
803
|
+
let paymentMeta = null;
|
|
804
|
+
if (paymentResponseHeader) {
|
|
805
|
+
try {
|
|
806
|
+
if (paymentResponseHeader.startsWith('{')) {
|
|
807
|
+
const parsed = JSON.parse(paymentResponseHeader);
|
|
808
|
+
txHash = parsed.txHash || parsed.transactionHash || parsed.hash || '';
|
|
809
|
+
paymentMeta = parsed;
|
|
810
|
+
} else {
|
|
811
|
+
txHash = paymentResponseHeader;
|
|
812
|
+
}
|
|
813
|
+
} catch {
|
|
814
|
+
txHash = paymentResponseHeader;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
let responseBody;
|
|
819
|
+
const contentType = response.headers.get('content-type') || '';
|
|
820
|
+
if (contentType.includes('application/json')) {
|
|
821
|
+
responseBody = await response.json();
|
|
822
|
+
} else {
|
|
823
|
+
responseBody = await response.text();
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
if (options.json) {
|
|
827
|
+
console.log(JSON.stringify({
|
|
828
|
+
status: response.ok ? 'success' : 'failed',
|
|
829
|
+
statusCode: response.status,
|
|
830
|
+
durationMs,
|
|
831
|
+
payer: publicKey,
|
|
832
|
+
network,
|
|
833
|
+
txHash: txHash || undefined,
|
|
834
|
+
paymentMeta: paymentMeta || undefined,
|
|
835
|
+
headers: responseHeaders,
|
|
836
|
+
data: responseBody,
|
|
837
|
+
}, null, 2));
|
|
838
|
+
if (!response.ok) process.exit(1);
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
if (response.ok) {
|
|
843
|
+
console.log(`✅ Payment Negotiated & Request Completed (${response.status} ${response.statusText})`);
|
|
844
|
+
} else {
|
|
845
|
+
console.log(`❌ Request Failed After Payment (${response.status} ${response.statusText})`);
|
|
846
|
+
}
|
|
847
|
+
console.log(` Response Time: ${durationMs}ms`);
|
|
848
|
+
if (txHash) {
|
|
849
|
+
console.log(` Tx Reference: ${txHash}`);
|
|
850
|
+
console.log(` Explorer: https://stellar.expert/explorer/${network.includes('testnet') ? 'testnet' : 'public'}/tx/${txHash}`);
|
|
851
|
+
}
|
|
852
|
+
console.log(`\n--- Response Payload ---`);
|
|
853
|
+
console.log(typeof responseBody === 'object' ? JSON.stringify(responseBody, null, 2) : responseBody);
|
|
854
|
+
if (!response.ok) process.exit(1);
|
|
855
|
+
} catch (err) {
|
|
856
|
+
const errorDetail = err?.message || String(err);
|
|
857
|
+
if (options.json) {
|
|
858
|
+
console.log(JSON.stringify({ status: 'error', error: errorDetail, payer: publicKey, network }));
|
|
859
|
+
process.exit(1);
|
|
860
|
+
}
|
|
861
|
+
console.error(`❌ Payment Failed: ${errorDetail}`);
|
|
862
|
+
process.exit(1);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// ═══════════════════════════════════════════════════════════════
|
|
867
|
+
// serve — local x402-protected demo server
|
|
868
|
+
// ═══════════════════════════════════════════════════════════════
|
|
869
|
+
|
|
870
|
+
async function executeServeCommand(options) {
|
|
871
|
+
const config = loadConfig(options.config);
|
|
872
|
+
const payTo = options.payTo || process.env.NIRIUM_PAY_TO || config.payTo;
|
|
873
|
+
const price = options.price || '$0.02';
|
|
874
|
+
const port = Number(options.port || process.env.PORT || 3000);
|
|
875
|
+
const network = options.network || process.env.NIRIUM_NETWORK || config.network || 'stellar:testnet';
|
|
876
|
+
const routePath = options.route || '/api/v1/data';
|
|
877
|
+
if (options.apiKey !== undefined) {
|
|
878
|
+
console.error('❌ Error: `nirium serve` no longer takes --api-key.\n'
|
|
879
|
+
+ 'A key passed as a command-line argument stays in your shell history and is visible in `ps` '
|
|
880
|
+
+ 'to other users on this machine, so it was NOT used. Treat the key you typed as exposed.\n'
|
|
881
|
+
+ 'Set FACILITATOR_API_KEY, or run `nirium serve` in a terminal to get a hidden prompt.');
|
|
882
|
+
process.exit(1);
|
|
883
|
+
}
|
|
884
|
+
let facilitatorApiKey = process.env.FACILITATOR_API_KEY || config.facilitatorApiKey;
|
|
885
|
+
if (!facilitatorApiKey) facilitatorApiKey = await readSecretInput('Facilitator API key: ', { timeoutMs: SERVE_STDIN_TIMEOUT_MS });
|
|
886
|
+
|
|
887
|
+
if (!facilitatorApiKey) {
|
|
888
|
+
console.error('❌ Error: Missing facilitator API key.');
|
|
889
|
+
console.error('Get a free key at https://channels.openzeppelin.com/testnet/gen (testnet)');
|
|
890
|
+
console.error('or https://channels.openzeppelin.com/gen (mainnet), then set FACILITATOR_API_KEY');
|
|
891
|
+
console.error('or run `nirium serve` in a terminal to get a hidden prompt.');
|
|
892
|
+
process.exit(1);
|
|
893
|
+
}
|
|
894
|
+
if (!payTo) {
|
|
895
|
+
console.error('❌ Error: Missing `--pay-to` Stellar address (G...).');
|
|
896
|
+
console.error('Please specify a recipient address using `--pay-to G...` or setting `payTo` in config.');
|
|
897
|
+
process.exit(1);
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
const app = express();
|
|
901
|
+
app.use(express.json());
|
|
902
|
+
|
|
903
|
+
const middleware = x402Serve({
|
|
904
|
+
payTo,
|
|
905
|
+
network,
|
|
906
|
+
facilitatorApiKey,
|
|
907
|
+
routes: {
|
|
908
|
+
[`GET ${routePath}`]: { price, description: 'Nirium CLI x402 Demo Endpoint' },
|
|
909
|
+
},
|
|
910
|
+
});
|
|
911
|
+
app.use(middleware);
|
|
912
|
+
|
|
913
|
+
app.get(routePath, (req, res) => {
|
|
914
|
+
res.json({
|
|
915
|
+
status: 'success',
|
|
916
|
+
message: 'x402 Payment Verified! Access Granted.',
|
|
917
|
+
endpoint: routePath,
|
|
918
|
+
price,
|
|
919
|
+
paidTo: payTo,
|
|
920
|
+
timestamp: new Date().toISOString(),
|
|
921
|
+
sampleData: { signal: 'CETES_REBALANCE_OPPORTUNITY', yieldApy: '5.57%', network },
|
|
922
|
+
});
|
|
923
|
+
});
|
|
924
|
+
|
|
925
|
+
return new Promise((resolve, reject) => {
|
|
926
|
+
const server = app.listen(port, () => {
|
|
927
|
+
console.log(`\n🚀 Nirium x402 Demo Server Listening on http://localhost:${port}`);
|
|
928
|
+
console.log(` Protected Route: http://localhost:${port}${routePath}`);
|
|
929
|
+
console.log(` Price: ${price}`);
|
|
930
|
+
console.log(` Pay To: ${payTo}`);
|
|
931
|
+
console.log(` Network: ${network}\n`);
|
|
932
|
+
console.log(`💡 Test this server using:`);
|
|
933
|
+
console.log(` NIRIUM_SECRET_KEY=S... nirium pay http://localhost:${port}${routePath}\n`);
|
|
934
|
+
resolve({ app, server });
|
|
935
|
+
});
|
|
936
|
+
server.on('error', (err) => {
|
|
937
|
+
console.error(`❌ Server startup failed: ${err.message}`);
|
|
938
|
+
reject(err);
|
|
939
|
+
});
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// ═══════════════════════════════════════════════════════════════
|
|
944
|
+
// doctor — x402/MPP preflight diagnostics
|
|
945
|
+
// ═══════════════════════════════════════════════════════════════
|
|
946
|
+
|
|
947
|
+
function loadEnvFile(filePath) {
|
|
948
|
+
const env = {};
|
|
949
|
+
const targetPath = filePath ? path.resolve(process.cwd(), filePath) : path.resolve(process.cwd(), '.env');
|
|
950
|
+
if (fs.existsSync(targetPath)) {
|
|
951
|
+
try {
|
|
952
|
+
const content = fs.readFileSync(targetPath, 'utf8');
|
|
953
|
+
for (const line of content.split('\n')) {
|
|
954
|
+
const trimmed = line.trim();
|
|
955
|
+
if (!trimmed || trimmed.startsWith('#')) continue;
|
|
956
|
+
const eqIdx = trimmed.indexOf('=');
|
|
957
|
+
if (eqIdx !== -1) {
|
|
958
|
+
const key = trimmed.slice(0, eqIdx).trim();
|
|
959
|
+
let val = trimmed.slice(eqIdx + 1).trim();
|
|
960
|
+
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
|
|
961
|
+
val = val.slice(1, -1);
|
|
962
|
+
}
|
|
963
|
+
env[key] = val;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
} catch {
|
|
967
|
+
// Ignore file read errors
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
return env;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
function normalizeNetwork(inputNet) {
|
|
974
|
+
const net = (inputNet || '').toLowerCase();
|
|
975
|
+
if (net === 'pubnet' || net === 'mainnet' || net === 'stellar:pubnet' || net === 'stellar:mainnet') {
|
|
976
|
+
return 'stellar:pubnet';
|
|
977
|
+
}
|
|
978
|
+
return 'stellar:testnet';
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
async function runDoctorDiagnostics(options) {
|
|
982
|
+
const fileEnv = loadEnvFile(options.config);
|
|
983
|
+
const getEnv = (key) => process.env[key] || fileEnv[key] || '';
|
|
984
|
+
|
|
985
|
+
const rawNetwork = options.network || getEnv('STELLAR_NETWORK') || getEnv('NETWORK') || 'testnet';
|
|
986
|
+
const canonicalNetwork = normalizeNetwork(rawNetwork);
|
|
987
|
+
const isTestnet = canonicalNetwork === 'stellar:testnet';
|
|
988
|
+
const checks = [];
|
|
989
|
+
|
|
990
|
+
// Check 1: payTo address
|
|
991
|
+
const payTo = getEnv('STELLAR_PAY_TO') || getEnv('PAY_TO') || getEnv('NIRIUM_X402_PAY_TO') || getEnv('STELLAR_PAYTO');
|
|
992
|
+
if (!payTo) {
|
|
993
|
+
checks.push({
|
|
994
|
+
name: 'payTo', status: 'fail', message: 'payTo address is missing',
|
|
995
|
+
fix: 'Set STELLAR_PAY_TO in .env to a valid Stellar public key starting with G...',
|
|
996
|
+
});
|
|
997
|
+
} else if (payTo.startsWith('S')) {
|
|
998
|
+
checks.push({
|
|
999
|
+
name: 'payTo', status: 'fail', message: 'payTo address is a secret key (S...), not a public key',
|
|
1000
|
+
fix: 'Replace STELLAR_PAY_TO with your public key (G...). Secret keys must never be exposed as payTo.',
|
|
1001
|
+
detail: `Value starts with '${payTo.slice(0, 4)}...'`,
|
|
1002
|
+
});
|
|
1003
|
+
} else if (!/^G[A-Z2-7]{55}$/.test(payTo)) {
|
|
1004
|
+
checks.push({
|
|
1005
|
+
name: 'payTo', status: 'fail', message: 'payTo address is invalid (must be a 56-character Stellar G... address)',
|
|
1006
|
+
fix: 'Ensure STELLAR_PAY_TO is a valid 56-char Stellar public key.',
|
|
1007
|
+
detail: `Length: ${payTo.length}`,
|
|
1008
|
+
});
|
|
1009
|
+
} else {
|
|
1010
|
+
checks.push({
|
|
1011
|
+
name: 'payTo', status: 'pass',
|
|
1012
|
+
message: `payTo address is a valid Stellar public key (${payTo.slice(0, 4)}...${payTo.slice(-4)})`,
|
|
1013
|
+
detail: payTo,
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
// Check 2: Facilitator API key & reachability
|
|
1018
|
+
const facilitatorApiKey = getEnv('X402_FACILITATOR_API_KEY') || getEnv('STELLAR_FACILITATOR_API_KEY') || getEnv('FACILITATOR_API_KEY');
|
|
1019
|
+
const defaultFacilitatorUrl = isTestnet ? 'https://channels.openzeppelin.com/x402/testnet' : 'https://channels.openzeppelin.com/x402';
|
|
1020
|
+
const facilitatorUrl = getEnv('FACILITATOR_URL') || getEnv('X402_FACILITATOR_URL') || defaultFacilitatorUrl;
|
|
1021
|
+
const customFetch = options.fetchFn || globalThis.fetch;
|
|
1022
|
+
|
|
1023
|
+
if (!facilitatorApiKey && !getEnv('FACILITATOR_URL')) {
|
|
1024
|
+
const genUrl = isTestnet ? 'https://channels.openzeppelin.com/testnet/gen' : 'https://channels.openzeppelin.com/gen';
|
|
1025
|
+
checks.push({
|
|
1026
|
+
name: 'facilitator', status: 'fail',
|
|
1027
|
+
message: 'facilitatorApiKey is missing — OpenZeppelin Channels facilitator rejects unauthenticated requests',
|
|
1028
|
+
fix: `Get a free ${rawNetwork} key at ${genUrl} and set X402_FACILITATOR_API_KEY in .env`,
|
|
1029
|
+
});
|
|
1030
|
+
} else {
|
|
1031
|
+
try {
|
|
1032
|
+
const headers = {};
|
|
1033
|
+
if (facilitatorApiKey) headers['Authorization'] = `Bearer ${facilitatorApiKey}`;
|
|
1034
|
+
const response = await customFetch(`${facilitatorUrl}/supported`, { headers, signal: AbortSignal.timeout(5000) });
|
|
1035
|
+
if (response.ok) {
|
|
1036
|
+
checks.push({
|
|
1037
|
+
name: 'facilitator', status: 'pass',
|
|
1038
|
+
message: `Facilitator reachable and API key authenticated on ${rawNetwork}`,
|
|
1039
|
+
detail: facilitatorUrl,
|
|
1040
|
+
});
|
|
1041
|
+
} else if (response.status === 401 || response.status === 403) {
|
|
1042
|
+
const genUrl = isTestnet ? 'https://channels.openzeppelin.com/testnet/gen' : 'https://channels.openzeppelin.com/gen';
|
|
1043
|
+
checks.push({
|
|
1044
|
+
name: 'facilitator', status: 'fail',
|
|
1045
|
+
message: `Facilitator rejected API key (HTTP ${response.status})`,
|
|
1046
|
+
fix: `Verify X402_FACILITATOR_API_KEY is valid for ${rawNetwork}. Keys are per-network: get one at ${genUrl}`,
|
|
1047
|
+
detail: `Status ${response.status} from ${facilitatorUrl}`,
|
|
1048
|
+
});
|
|
1049
|
+
} else {
|
|
1050
|
+
checks.push({
|
|
1051
|
+
name: 'facilitator', status: 'fail', message: `Facilitator returned HTTP ${response.status}`,
|
|
1052
|
+
fix: `Check facilitator service status at ${facilitatorUrl}`,
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
} catch (err) {
|
|
1056
|
+
checks.push({
|
|
1057
|
+
name: 'facilitator', status: 'fail', message: `Facilitator endpoint unreachable at ${facilitatorUrl}`,
|
|
1058
|
+
fix: 'Check network connectivity or custom FACILITATOR_URL setting.',
|
|
1059
|
+
detail: err?.message || String(err),
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// Check 3: Network & RPC consistency
|
|
1065
|
+
const defaultRpcUrl = isTestnet ? 'https://soroban-testnet.stellar.org' : 'https://soroban-rpc.mainnet.stellar.gateway.fm';
|
|
1066
|
+
const rpcUrl = getEnv('STELLAR_RPC_URL') || getEnv('RPC_URL') || defaultRpcUrl;
|
|
1067
|
+
const expectedPassphrase = isTestnet ? 'Test SDF Network ; July 2015' : 'Public Global Stellar Network ; September 2015';
|
|
1068
|
+
try {
|
|
1069
|
+
const rpcRes = await customFetch(rpcUrl, {
|
|
1070
|
+
method: 'POST',
|
|
1071
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1072
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getHealth' }),
|
|
1073
|
+
signal: AbortSignal.timeout(5000),
|
|
1074
|
+
});
|
|
1075
|
+
if (rpcRes.ok) {
|
|
1076
|
+
checks.push({
|
|
1077
|
+
name: 'network', status: 'pass', message: `Soroban RPC endpoint operational for ${canonicalNetwork}`,
|
|
1078
|
+
detail: `${rpcUrl} (Passphrase: "${expectedPassphrase}")`,
|
|
1079
|
+
});
|
|
1080
|
+
} else {
|
|
1081
|
+
checks.push({
|
|
1082
|
+
name: 'network', status: 'fail', message: `Soroban RPC endpoint returned HTTP ${rpcRes.status}`,
|
|
1083
|
+
fix: `Verify STELLAR_RPC_URL for network ${canonicalNetwork}`,
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
} catch (err) {
|
|
1087
|
+
checks.push({
|
|
1088
|
+
name: 'network', status: 'fail', message: `Soroban RPC endpoint unreachable at ${rpcUrl}`,
|
|
1089
|
+
fix: `Check network connection or set a working STELLAR_RPC_URL for ${canonicalNetwork}`,
|
|
1090
|
+
detail: err?.message || String(err),
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// Check 4: Secret Key check (if configured)
|
|
1095
|
+
const secretKey = getEnv('STELLAR_SECRET_KEY') || getEnv('SECRET_KEY') || getEnv('NIRIUM_SECRET_KEY');
|
|
1096
|
+
if (secretKey) {
|
|
1097
|
+
if (!/^S[A-Z2-7]{55}$/.test(secretKey)) {
|
|
1098
|
+
checks.push({
|
|
1099
|
+
name: 'secretKey', status: 'fail', message: 'Secret key format is invalid (must be a 56-character Stellar S... key)',
|
|
1100
|
+
fix: 'Ensure STELLAR_SECRET_KEY is a valid Stellar secret key starting with S...',
|
|
1101
|
+
});
|
|
1102
|
+
} else {
|
|
1103
|
+
checks.push({ name: 'secretKey', status: 'pass', message: 'Secret key format is valid (S...)' });
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
// Check 5: MPP Configuration (if configured)
|
|
1108
|
+
const mppMode = getEnv('MPP_MODE');
|
|
1109
|
+
const mppSecret = getEnv('MPP_SECRET_KEY');
|
|
1110
|
+
if (mppMode || mppSecret) {
|
|
1111
|
+
if (mppMode && mppMode !== 'pull' && mppMode !== 'push') {
|
|
1112
|
+
checks.push({
|
|
1113
|
+
name: 'mpp', status: 'fail', message: `Invalid MPP_MODE: "${mppMode}" (must be "pull" or "push")`,
|
|
1114
|
+
fix: 'Set MPP_MODE=pull or MPP_MODE=push in .env',
|
|
1115
|
+
});
|
|
1116
|
+
} else if (mppSecret && !/^S[A-Z2-7]{55}$/.test(mppSecret)) {
|
|
1117
|
+
checks.push({
|
|
1118
|
+
name: 'mpp', status: 'fail', message: 'Invalid MPP_SECRET_KEY format (must be a 56-character S... key)',
|
|
1119
|
+
fix: 'Check MPP_SECRET_KEY in .env',
|
|
1120
|
+
});
|
|
1121
|
+
} else {
|
|
1122
|
+
checks.push({ name: 'mpp', status: 'pass', message: `MPP protocol configuration valid (mode: ${mppMode || 'pull'})` });
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
const ok = checks.every((c) => c.status === 'pass');
|
|
1127
|
+
return { ok, network: canonicalNetwork, checks, timestamp: new Date().toISOString() };
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1131
|
+
// doctor --seller — probe a remote x402 seller without paying
|
|
1132
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1133
|
+
//
|
|
1134
|
+
// The probe URL may be plain http (a local fixture). resource.url inside
|
|
1135
|
+
// PAYMENT-REQUIRED may not: browsers and x402 clients follow that URL, and
|
|
1136
|
+
// an http:// resource is a real production failure. Nothing here sends
|
|
1137
|
+
// PAYMENT-SIGNATURE or X-PAYMENT.
|
|
1138
|
+
|
|
1139
|
+
const STELLAR_SELLER_NETWORKS = new Set(['stellar:testnet', 'stellar:pubnet']);
|
|
1140
|
+
|
|
1141
|
+
function headerTokens(value) {
|
|
1142
|
+
if (!value || typeof value !== 'string') return [];
|
|
1143
|
+
return value.split(',').map((part) => part.trim()).filter(Boolean);
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
function tokenListIncludes(value, expected) {
|
|
1147
|
+
const tokens = headerTokens(value).map((token) => token.toLowerCase());
|
|
1148
|
+
return tokens.includes('*') || tokens.includes(expected.toLowerCase());
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
function missingExposedHeaders(value) {
|
|
1152
|
+
const tokens = headerTokens(value).map((token) => token.toLowerCase());
|
|
1153
|
+
if (tokens.includes('*')) return [];
|
|
1154
|
+
const missing = [];
|
|
1155
|
+
if (!tokens.includes('payment-required')) missing.push('PAYMENT-REQUIRED');
|
|
1156
|
+
if (!tokens.includes('payment-response')) missing.push('PAYMENT-RESPONSE');
|
|
1157
|
+
return missing;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
function isPaymentRequiredPayload(value) {
|
|
1161
|
+
return Boolean(value)
|
|
1162
|
+
&& typeof value === 'object'
|
|
1163
|
+
&& !Array.isArray(value)
|
|
1164
|
+
&& (Array.isArray(value.accepts) || (value.resource && typeof value.resource === 'object'));
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
function decodePaymentRequiredHeader(headerValue) {
|
|
1168
|
+
if (typeof headerValue !== 'string') return null;
|
|
1169
|
+
const trimmed = headerValue.trim();
|
|
1170
|
+
if (!trimmed) return null;
|
|
1171
|
+
const candidates = [];
|
|
1172
|
+
if (trimmed.startsWith('{')) candidates.push(trimmed);
|
|
1173
|
+
candidates.push(Buffer.from(trimmed.replace(/\s+/g, ''), 'base64').toString('utf8'));
|
|
1174
|
+
for (const candidate of candidates) {
|
|
1175
|
+
try {
|
|
1176
|
+
const parsed = JSON.parse(candidate);
|
|
1177
|
+
if (isPaymentRequiredPayload(parsed)) return parsed;
|
|
1178
|
+
} catch {
|
|
1179
|
+
// try the next encoding
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
return null;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
function isPositiveAtomicAmount(amount) {
|
|
1186
|
+
return typeof amount === 'string' && /^[1-9]\d*$/.test(amount);
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
function isWellFormedSellerNetwork(network) {
|
|
1190
|
+
if (typeof network !== 'string') return false;
|
|
1191
|
+
if (network.startsWith('stellar:')) return STELLAR_SELLER_NETWORKS.has(network);
|
|
1192
|
+
return /^[a-z0-9]{3,32}:[A-Za-z0-9._-]{1,64}$/.test(network);
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
function isWellFormedSellerAsset(asset, network) {
|
|
1196
|
+
if (typeof asset !== 'string' || asset.length === 0 || asset.length > 200 || /\s/.test(asset)) return false;
|
|
1197
|
+
if (typeof network === 'string' && network.startsWith('stellar:')) return StrKey.isValidContract(asset);
|
|
1198
|
+
return true;
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
function payToProblem(payTo, network) {
|
|
1202
|
+
if (typeof payTo !== 'string' || payTo.length === 0) return 'missing';
|
|
1203
|
+
if (payTo.startsWith('S')) return 'secret';
|
|
1204
|
+
const stellar = typeof network === 'string' && network.startsWith('stellar:');
|
|
1205
|
+
if (stellar || payTo.startsWith('G')) {
|
|
1206
|
+
return StrKey.isValidEd25519PublicKey(payTo) ? null : 'invalid';
|
|
1207
|
+
}
|
|
1208
|
+
if (/\s/.test(payTo) || payTo.length < 8 || payTo.length > 200) return 'invalid';
|
|
1209
|
+
return null;
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
function resourceUrlProblem(resourceUrl) {
|
|
1213
|
+
if (typeof resourceUrl !== 'string' || resourceUrl.length === 0) return 'missing';
|
|
1214
|
+
if (/^http:\/\//i.test(resourceUrl)) return 'http';
|
|
1215
|
+
try {
|
|
1216
|
+
const parsed = new URL(resourceUrl);
|
|
1217
|
+
if (parsed.protocol !== 'https:') return 'not-https';
|
|
1218
|
+
} catch {
|
|
1219
|
+
return 'invalid';
|
|
1220
|
+
}
|
|
1221
|
+
return null;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
function sellerCheck(name, status, message, fix, detail) {
|
|
1225
|
+
const check = { name, status, message };
|
|
1226
|
+
if (fix) check.fix = fix;
|
|
1227
|
+
if (detail) check.detail = detail;
|
|
1228
|
+
return check;
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
function sellerReport(seller, checks, network) {
|
|
1232
|
+
return {
|
|
1233
|
+
ok: checks.every((check) => check.status === 'pass'),
|
|
1234
|
+
seller,
|
|
1235
|
+
network: network || null,
|
|
1236
|
+
checks,
|
|
1237
|
+
timestamp: new Date().toISOString(),
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
function unreachableSellerReport(seller, message) {
|
|
1242
|
+
const names = ['challenge', 'network', 'asset', 'amount', 'payTo', 'resource-url', 'cors-preflight', 'cors-expose', 'cors-allow'];
|
|
1243
|
+
return sellerReport(seller, names.map((name) => sellerCheck(
|
|
1244
|
+
name,
|
|
1245
|
+
'fail',
|
|
1246
|
+
message,
|
|
1247
|
+
name === 'challenge' ? 'Pass an absolute http(s) URL, for example https://example.com/premium' : undefined,
|
|
1248
|
+
)), null);
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
function probeErrorMessage(err) {
|
|
1252
|
+
if (!err) return 'unknown error';
|
|
1253
|
+
if (err.name === 'TimeoutError' || err.name === 'AbortError') return 'request timed out after 10s';
|
|
1254
|
+
return err.message || String(err);
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
async function probeSeller(url, init) {
|
|
1258
|
+
try {
|
|
1259
|
+
const response = await fetch(url, {
|
|
1260
|
+
...init,
|
|
1261
|
+
redirect: 'manual',
|
|
1262
|
+
signal: AbortSignal.timeout(10000),
|
|
1263
|
+
});
|
|
1264
|
+
try {
|
|
1265
|
+
await response.body?.cancel();
|
|
1266
|
+
} catch {
|
|
1267
|
+
// headers are already available
|
|
1268
|
+
}
|
|
1269
|
+
return { response };
|
|
1270
|
+
} catch (err) {
|
|
1271
|
+
return { error: err };
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
function firstAdvertisedNetwork(payment) {
|
|
1276
|
+
const accepts = payment?.accepts;
|
|
1277
|
+
if (!Array.isArray(accepts)) return null;
|
|
1278
|
+
for (const entry of accepts) {
|
|
1279
|
+
if (entry && typeof entry.network === 'string' && entry.network) return entry.network;
|
|
1280
|
+
}
|
|
1281
|
+
return null;
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
function fieldFailures(payment, readProblem) {
|
|
1285
|
+
const accepts = payment?.accepts;
|
|
1286
|
+
if (!Array.isArray(accepts) || accepts.length === 0) {
|
|
1287
|
+
return { ok: false, message: 'PAYMENT-REQUIRED accepts[] is missing or empty' };
|
|
1288
|
+
}
|
|
1289
|
+
for (let i = 0; i < accepts.length; i++) {
|
|
1290
|
+
const entry = accepts[i];
|
|
1291
|
+
const problem = readProblem(entry && typeof entry === 'object' ? entry : {});
|
|
1292
|
+
if (problem) return { ok: false, index: i, ...problem };
|
|
1293
|
+
}
|
|
1294
|
+
return { ok: true };
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
async function runDoctorSeller(sellerUrl) {
|
|
1298
|
+
let parsed;
|
|
1299
|
+
try {
|
|
1300
|
+
parsed = new URL(sellerUrl);
|
|
1301
|
+
} catch {
|
|
1302
|
+
parsed = null;
|
|
1303
|
+
}
|
|
1304
|
+
if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {
|
|
1305
|
+
return unreachableSellerReport(sellerUrl, 'seller URL is not an absolute http(s) URL');
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
// A reserved .invalid origin so the preflight cannot collide with a real
|
|
1309
|
+
// site, and so a seller that 500s on an unknown Origin fails closed.
|
|
1310
|
+
const origin = `https://nirium-doctor-${crypto.randomBytes(8).toString('hex')}.invalid`;
|
|
1311
|
+
const [challenge, preflight] = await Promise.all([
|
|
1312
|
+
probeSeller(sellerUrl, {
|
|
1313
|
+
method: 'GET',
|
|
1314
|
+
headers: {
|
|
1315
|
+
Accept: 'application/json',
|
|
1316
|
+
Origin: origin,
|
|
1317
|
+
'User-Agent': doctorUserAgent,
|
|
1318
|
+
},
|
|
1319
|
+
}),
|
|
1320
|
+
probeSeller(sellerUrl, {
|
|
1321
|
+
method: 'OPTIONS',
|
|
1322
|
+
headers: {
|
|
1323
|
+
Origin: origin,
|
|
1324
|
+
'Access-Control-Request-Method': 'GET',
|
|
1325
|
+
'Access-Control-Request-Headers': 'PAYMENT-SIGNATURE',
|
|
1326
|
+
'User-Agent': doctorUserAgent,
|
|
1327
|
+
},
|
|
1328
|
+
}),
|
|
1329
|
+
]);
|
|
1330
|
+
|
|
1331
|
+
const checks = [];
|
|
1332
|
+
let payment = null;
|
|
1333
|
+
if (challenge.error || !challenge.response) {
|
|
1334
|
+
checks.push(sellerCheck(
|
|
1335
|
+
'challenge',
|
|
1336
|
+
'fail',
|
|
1337
|
+
`seller unreachable: ${probeErrorMessage(challenge.error)}`,
|
|
1338
|
+
'Confirm the URL is reachable. doctor does not retry and does not pay.',
|
|
1339
|
+
));
|
|
1340
|
+
} else if (challenge.response.status !== 402) {
|
|
1341
|
+
checks.push(sellerCheck(
|
|
1342
|
+
'challenge',
|
|
1343
|
+
'fail',
|
|
1344
|
+
`expected HTTP 402, got HTTP ${challenge.response.status}`,
|
|
1345
|
+
'The seller must answer an unpaid request with 402 and a PAYMENT-REQUIRED header.',
|
|
1346
|
+
`status ${challenge.response.status}`,
|
|
1347
|
+
));
|
|
1348
|
+
} else {
|
|
1349
|
+
payment = decodePaymentRequiredHeader(challenge.response.headers.get('payment-required'));
|
|
1350
|
+
if (!payment) {
|
|
1351
|
+
checks.push(sellerCheck(
|
|
1352
|
+
'challenge',
|
|
1353
|
+
'fail',
|
|
1354
|
+
'HTTP 402 but PAYMENT-REQUIRED is missing or not decodable',
|
|
1355
|
+
'Serve the x402 v2 challenge as base64 JSON in the PAYMENT-REQUIRED header.',
|
|
1356
|
+
));
|
|
1357
|
+
} else {
|
|
1358
|
+
checks.push(sellerCheck(
|
|
1359
|
+
'challenge',
|
|
1360
|
+
'pass',
|
|
1361
|
+
'HTTP 402 with a decodable PAYMENT-REQUIRED header',
|
|
1362
|
+
undefined,
|
|
1363
|
+
payment.x402Version != null ? `x402Version ${payment.x402Version}` : undefined,
|
|
1364
|
+
));
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
const networkResult = fieldFailures(payment, (entry) => {
|
|
1369
|
+
if (entry.network == null || entry.network === '') {
|
|
1370
|
+
return { message: 'network is missing', fix: 'Set accepts[].network, for example stellar:pubnet or stellar:testnet.' };
|
|
1371
|
+
}
|
|
1372
|
+
if (!isWellFormedSellerNetwork(entry.network)) {
|
|
1373
|
+
const stellarTypo = typeof entry.network === 'string' && entry.network.startsWith('stellar:');
|
|
1374
|
+
return {
|
|
1375
|
+
message: `network "${entry.network}" is not well formed`,
|
|
1376
|
+
fix: stellarTypo
|
|
1377
|
+
? 'Stellar sellers must advertise stellar:testnet or stellar:pubnet.'
|
|
1378
|
+
: 'network must be a CAIP-2 identifier such as stellar:pubnet.',
|
|
1379
|
+
detail: String(entry.network),
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
return null;
|
|
1383
|
+
});
|
|
1384
|
+
checks.push(networkResult.ok
|
|
1385
|
+
? sellerCheck('network', 'pass', 'network is present and well formed', undefined, firstAdvertisedNetwork(payment))
|
|
1386
|
+
: sellerCheck('network', 'fail', networkResult.index != null ? `accepts[${networkResult.index}].${networkResult.message}` : networkResult.message, networkResult.fix, networkResult.detail));
|
|
1387
|
+
|
|
1388
|
+
const assetResult = fieldFailures(payment, (entry) => {
|
|
1389
|
+
if (!isWellFormedSellerAsset(entry.asset, entry.network)) {
|
|
1390
|
+
const stellar = typeof entry.network === 'string' && entry.network.startsWith('stellar:');
|
|
1391
|
+
return {
|
|
1392
|
+
message: entry.asset == null || entry.asset === '' ? 'asset is missing' : 'asset is not well formed',
|
|
1393
|
+
fix: stellar
|
|
1394
|
+
? 'Stellar asset must be the SAC contract id (C...), not a symbol.'
|
|
1395
|
+
: 'Set accepts[].asset to the token the seller settles.',
|
|
1396
|
+
detail: entry.asset == null ? undefined : String(entry.asset).slice(0, 80),
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
return null;
|
|
1400
|
+
});
|
|
1401
|
+
checks.push(assetResult.ok
|
|
1402
|
+
? sellerCheck('asset', 'pass', 'asset is present and well formed')
|
|
1403
|
+
: sellerCheck('asset', 'fail', assetResult.index != null ? `accepts[${assetResult.index}].${assetResult.message}` : assetResult.message, assetResult.fix, assetResult.detail));
|
|
1404
|
+
|
|
1405
|
+
const amountResult = fieldFailures(payment, (entry) => {
|
|
1406
|
+
if (!isPositiveAtomicAmount(entry.amount)) {
|
|
1407
|
+
return {
|
|
1408
|
+
message: entry.amount == null || entry.amount === '' ? 'amount is missing' : 'amount is not a positive integer string',
|
|
1409
|
+
fix: 'Set accepts[].amount to atomic units, for example "1000000". Do not send "$0.02" or "0".',
|
|
1410
|
+
detail: entry.amount == null ? undefined : String(entry.amount).slice(0, 80),
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
return null;
|
|
1414
|
+
});
|
|
1415
|
+
checks.push(amountResult.ok
|
|
1416
|
+
? sellerCheck('amount', 'pass', 'amount is a positive integer string')
|
|
1417
|
+
: sellerCheck('amount', 'fail', amountResult.index != null ? `accepts[${amountResult.index}].${amountResult.message}` : amountResult.message, amountResult.fix, amountResult.detail));
|
|
1418
|
+
|
|
1419
|
+
const payToResult = fieldFailures(payment, (entry) => {
|
|
1420
|
+
const problem = payToProblem(entry.payTo, entry.network);
|
|
1421
|
+
if (!problem) return null;
|
|
1422
|
+
if (problem === 'secret') {
|
|
1423
|
+
return {
|
|
1424
|
+
message: 'payTo is a secret key (S...), not a public key',
|
|
1425
|
+
fix: 'accepts[].payTo must be the public key that receives funds (G... on Stellar). Never publish a secret.',
|
|
1426
|
+
detail: 'value starts with S',
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
if (problem === 'missing') {
|
|
1430
|
+
return { message: 'payTo is missing', fix: 'Set accepts[].payTo to the account that receives the payment.' };
|
|
1431
|
+
}
|
|
1432
|
+
return {
|
|
1433
|
+
message: 'payTo is not well formed',
|
|
1434
|
+
fix: 'On Stellar, payTo must be a valid 56-character G... public key.',
|
|
1435
|
+
detail: typeof entry.payTo === 'string' ? `length ${entry.payTo.length}` : undefined,
|
|
1436
|
+
};
|
|
1437
|
+
});
|
|
1438
|
+
checks.push(payToResult.ok
|
|
1439
|
+
? sellerCheck('payTo', 'pass', 'payTo is present and well formed')
|
|
1440
|
+
: sellerCheck('payTo', 'fail', payToResult.index != null ? `accepts[${payToResult.index}].${payToResult.message}` : payToResult.message, payToResult.fix, payToResult.detail));
|
|
1441
|
+
|
|
1442
|
+
const urlProblem = payment ? resourceUrlProblem(payment.resource?.url) : 'missing';
|
|
1443
|
+
if (!payment) {
|
|
1444
|
+
checks.push(sellerCheck(
|
|
1445
|
+
'resource-url',
|
|
1446
|
+
'fail',
|
|
1447
|
+
'resource.url was not checked because PAYMENT-REQUIRED did not decode',
|
|
1448
|
+
'Fix the 402 challenge first. resource.url must be an https:// URL.',
|
|
1449
|
+
));
|
|
1450
|
+
} else if (urlProblem === 'http') {
|
|
1451
|
+
checks.push(sellerCheck(
|
|
1452
|
+
'resource-url',
|
|
1453
|
+
'fail',
|
|
1454
|
+
'resource.url uses http://',
|
|
1455
|
+
'Serve resource.url as https://. Browsers and x402 clients will not treat an http resource as the paid URL.',
|
|
1456
|
+
String(payment.resource?.url).slice(0, 120),
|
|
1457
|
+
));
|
|
1458
|
+
} else if (urlProblem) {
|
|
1459
|
+
checks.push(sellerCheck(
|
|
1460
|
+
'resource-url',
|
|
1461
|
+
'fail',
|
|
1462
|
+
'resource.url is missing or not https://',
|
|
1463
|
+
'Set resource.url to an absolute https:// URL.',
|
|
1464
|
+
payment.resource?.url == null ? undefined : String(payment.resource.url).slice(0, 120),
|
|
1465
|
+
));
|
|
1466
|
+
} else {
|
|
1467
|
+
checks.push(sellerCheck('resource-url', 'pass', 'resource.url is https://', undefined, payment.resource.url));
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
const preflightResponse = preflight.response;
|
|
1471
|
+
let allowCheck;
|
|
1472
|
+
if (preflight.error || !preflightResponse) {
|
|
1473
|
+
checks.push(sellerCheck(
|
|
1474
|
+
'cors-preflight',
|
|
1475
|
+
'fail',
|
|
1476
|
+
`CORS preflight failed: ${probeErrorMessage(preflight.error)}`,
|
|
1477
|
+
'The seller must answer OPTIONS for an unknown Origin without crashing.',
|
|
1478
|
+
));
|
|
1479
|
+
allowCheck = sellerCheck(
|
|
1480
|
+
'cors-allow',
|
|
1481
|
+
'fail',
|
|
1482
|
+
'PAYMENT-SIGNATURE was not allowed because the preflight did not complete',
|
|
1483
|
+
'Answer OPTIONS with Access-Control-Allow-Headers including PAYMENT-SIGNATURE.',
|
|
1484
|
+
);
|
|
1485
|
+
} else if (preflightResponse.status >= 500) {
|
|
1486
|
+
checks.push(sellerCheck(
|
|
1487
|
+
'cors-preflight',
|
|
1488
|
+
'fail',
|
|
1489
|
+
`CORS preflight returned HTTP ${preflightResponse.status} for an unknown origin`,
|
|
1490
|
+
'An unknown Origin must not 500. Handle OPTIONS before route auth.',
|
|
1491
|
+
origin,
|
|
1492
|
+
));
|
|
1493
|
+
allowCheck = sellerCheck(
|
|
1494
|
+
'cors-allow',
|
|
1495
|
+
'fail',
|
|
1496
|
+
'PAYMENT-SIGNATURE was not allowed because the preflight failed',
|
|
1497
|
+
'Answer OPTIONS with 2xx and Access-Control-Allow-Headers: PAYMENT-SIGNATURE.',
|
|
1498
|
+
);
|
|
1499
|
+
} else if (preflightResponse.status < 200 || preflightResponse.status >= 300) {
|
|
1500
|
+
checks.push(sellerCheck(
|
|
1501
|
+
'cors-preflight',
|
|
1502
|
+
'fail',
|
|
1503
|
+
`CORS preflight returned HTTP ${preflightResponse.status}`,
|
|
1504
|
+
'Answer OPTIONS with 204 or another 2xx, including Access-Control-Allow-Origin.',
|
|
1505
|
+
origin,
|
|
1506
|
+
));
|
|
1507
|
+
allowCheck = sellerCheck(
|
|
1508
|
+
'cors-allow',
|
|
1509
|
+
'fail',
|
|
1510
|
+
'PAYMENT-SIGNATURE was not allowed because the preflight was not successful',
|
|
1511
|
+
'Include PAYMENT-SIGNATURE in Access-Control-Allow-Headers on the OPTIONS response.',
|
|
1512
|
+
);
|
|
1513
|
+
} else {
|
|
1514
|
+
const allowOrigin = preflightResponse.headers.get('access-control-allow-origin') || '';
|
|
1515
|
+
const originAllowed = allowOrigin === '*' || allowOrigin === origin;
|
|
1516
|
+
checks.push(originAllowed
|
|
1517
|
+
? sellerCheck('cors-preflight', 'pass', `CORS preflight returned HTTP ${preflightResponse.status} for a random origin`, undefined, origin)
|
|
1518
|
+
: sellerCheck(
|
|
1519
|
+
'cors-preflight',
|
|
1520
|
+
'fail',
|
|
1521
|
+
'CORS preflight did not allow the random origin',
|
|
1522
|
+
'Send Access-Control-Allow-Origin: * or echo the request Origin. An unknown origin must not be dropped.',
|
|
1523
|
+
allowOrigin ? `got ${allowOrigin}` : 'Access-Control-Allow-Origin missing',
|
|
1524
|
+
));
|
|
1525
|
+
const allowed = tokenListIncludes(preflightResponse.headers.get('access-control-allow-headers'), 'PAYMENT-SIGNATURE');
|
|
1526
|
+
allowCheck = allowed
|
|
1527
|
+
? sellerCheck('cors-allow', 'pass', 'PAYMENT-SIGNATURE is allowed on the preflight')
|
|
1528
|
+
: sellerCheck(
|
|
1529
|
+
'cors-allow',
|
|
1530
|
+
'fail',
|
|
1531
|
+
'PAYMENT-SIGNATURE is not listed in Access-Control-Allow-Headers',
|
|
1532
|
+
'Add PAYMENT-SIGNATURE to Access-Control-Allow-Headers. Browsers drop the payment header otherwise.',
|
|
1533
|
+
preflightResponse.headers.get('access-control-allow-headers') || 'header missing',
|
|
1534
|
+
);
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
// Browsers only honor Access-Control-Expose-Headers on the actual response.
|
|
1538
|
+
// A preflight that lists the headers does not make the 402 readable.
|
|
1539
|
+
const exposeMissing = missingExposedHeaders(challenge.response?.headers.get('access-control-expose-headers'));
|
|
1540
|
+
if (challenge.response && exposeMissing.length === 0) {
|
|
1541
|
+
checks.push(sellerCheck(
|
|
1542
|
+
'cors-expose',
|
|
1543
|
+
'pass',
|
|
1544
|
+
'PAYMENT-REQUIRED and PAYMENT-RESPONSE are exposed on the 402 response',
|
|
1545
|
+
));
|
|
1546
|
+
} else {
|
|
1547
|
+
const missing = exposeMissing.length ? exposeMissing : ['PAYMENT-REQUIRED', 'PAYMENT-RESPONSE'];
|
|
1548
|
+
checks.push(sellerCheck(
|
|
1549
|
+
'cors-expose',
|
|
1550
|
+
'fail',
|
|
1551
|
+
`browser clients cannot read ${missing.join(' and ')}`,
|
|
1552
|
+
'Set Access-Control-Expose-Headers: PAYMENT-REQUIRED, PAYMENT-RESPONSE on the 402 response. The preflight does not count.',
|
|
1553
|
+
));
|
|
1554
|
+
}
|
|
1555
|
+
checks.push(allowCheck);
|
|
1556
|
+
|
|
1557
|
+
return sellerReport(sellerUrl, checks, payment ? firstAdvertisedNetwork(payment) : null);
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
function formatDoctorOutput(report) {
|
|
1561
|
+
const lines = [];
|
|
1562
|
+
lines.push(report.seller
|
|
1563
|
+
? `🩺 Nirium Doctor — remote x402 seller`
|
|
1564
|
+
: `🩺 Nirium Doctor — x402 Diagnostic Report`);
|
|
1565
|
+
if (report.seller) lines.push(`Seller: ${report.seller}`);
|
|
1566
|
+
lines.push(`Target Network: ${report.network || 'n/a'}`);
|
|
1567
|
+
lines.push(`Timestamp: ${report.timestamp}`);
|
|
1568
|
+
lines.push(`--------------------------------------------------`);
|
|
1569
|
+
for (const check of report.checks) {
|
|
1570
|
+
const symbol = check.status === 'pass' ? '✔' : '❌';
|
|
1571
|
+
lines.push(`${symbol} [${check.name.toUpperCase()}] ${check.message}`);
|
|
1572
|
+
if (check.detail && check.status === 'pass') lines.push(` Detail: ${check.detail}`);
|
|
1573
|
+
if (check.fix) lines.push(` 💡 Fix: ${check.fix}`);
|
|
1574
|
+
}
|
|
1575
|
+
lines.push(`--------------------------------------------------`);
|
|
1576
|
+
lines.push(report.ok ? `✅ All checks passed!` : `❌ Diagnostic failed. See fix suggestions above.`);
|
|
1577
|
+
return lines.join('\n');
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1581
|
+
// verify — independently check an audit CID's hash + agent signature
|
|
1582
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1583
|
+
|
|
1584
|
+
function decodeStellarPublicKey(gAddress) {
|
|
1585
|
+
if (!/^G[A-Z2-7]{55}$/.test(gAddress)) {
|
|
1586
|
+
throw new Error(`Invalid Stellar public key format: ${gAddress}`);
|
|
1587
|
+
}
|
|
1588
|
+
return Buffer.from(StrKey.decodeEd25519PublicKey(gAddress));
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
1592
|
+
const SEP53_PREFIX = 'Stellar Signed Message:\n';
|
|
1593
|
+
|
|
1594
|
+
// Accepts `<hex>` or `sha-256:<hex>`, any case. Returns lowercase hex or throws.
|
|
1595
|
+
function normalizeHashInput(value) {
|
|
1596
|
+
const hex = String(value).trim().replace(/^sha-?256:/i, '').toLowerCase();
|
|
1597
|
+
if (!HEX64.test(hex)) throw new Error(`Invalid sha-256 hash: ${value}`);
|
|
1598
|
+
return hex;
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
// The node accepts the signature as hex or base64. Returns a 64-byte buffer or null.
|
|
1602
|
+
function decodeSignature(signature) {
|
|
1603
|
+
if (typeof signature !== 'string') return null;
|
|
1604
|
+
const s = signature.trim();
|
|
1605
|
+
const buf = /^[0-9a-fA-F]{128}$/.test(s) ? Buffer.from(s, 'hex') : Buffer.from(s, 'base64');
|
|
1606
|
+
return buf.length === 64 ? buf : null;
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
// Mirrors the node: raw ed25519 over the utf8 statement first, then SEP-53
|
|
1610
|
+
// (Freighter signMessage): ed25519 over sha256("Stellar Signed Message:\n" + statement).
|
|
1611
|
+
// Returns 'ed25519', 'sep53' or null.
|
|
1612
|
+
function verifyEd25519Signature(pubKeyGAddress, statement, signature) {
|
|
1613
|
+
try {
|
|
1614
|
+
const rawPubKey = decodeStellarPublicKey(pubKeyGAddress);
|
|
1615
|
+
const spkiHeader = Buffer.from('302a300506032b6570032100', 'hex');
|
|
1616
|
+
const keyObject = crypto.createPublicKey({
|
|
1617
|
+
key: Buffer.concat([spkiHeader, rawPubKey]),
|
|
1618
|
+
format: 'der',
|
|
1619
|
+
type: 'spki',
|
|
1620
|
+
});
|
|
1621
|
+
const signatureBuf = decodeSignature(signature);
|
|
1622
|
+
if (!signatureBuf) return null;
|
|
1623
|
+
if (crypto.verify(null, Buffer.from(statement, 'utf8'), keyObject, signatureBuf)) return 'ed25519';
|
|
1624
|
+
const sep53Digest = crypto.createHash('sha256').update(Buffer.from(SEP53_PREFIX + statement, 'utf8')).digest();
|
|
1625
|
+
if (crypto.verify(null, sep53Digest, keyObject, signatureBuf)) return 'sep53';
|
|
1626
|
+
return null;
|
|
1627
|
+
} catch {
|
|
1628
|
+
return null;
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1632
|
+
function verifyAuditDocument(doc, cid, { expectedHash } = {}) {
|
|
1633
|
+
const fail = (error) => ({ ok: false, verified: false, cid, hashMatch: false, hashStatus: 'mismatch', expectedHash: '', computedHash: '', signatureStatus: 'absent', error });
|
|
1634
|
+
if (!doc || typeof doc !== 'object') return fail('Invalid audit document format');
|
|
1635
|
+
const anchoredHash = typeof doc.content_sha256 === 'string' ? doc.content_sha256.toLowerCase() : '';
|
|
1636
|
+
if (!HEX64.test(anchoredHash)) return fail('Audit document has no valid content_sha256');
|
|
1637
|
+
|
|
1638
|
+
// record mode: recompute from the embedded record (unchanged behavior).
|
|
1639
|
+
// hash-only mode: the node stores the submitted hash as content_sha256 and
|
|
1640
|
+
// has nothing to recompute it from, so compare against --hash/--evidence
|
|
1641
|
+
// when given, otherwise report the hash as unchecked (not as a mismatch).
|
|
1642
|
+
const mode = doc.record ? 'record' : 'hash-only';
|
|
1643
|
+
let computedHash = '';
|
|
1644
|
+
let hashStatus;
|
|
1645
|
+
if (mode === 'record') {
|
|
1646
|
+
computedHash = crypto.createHash('sha256').update(JSON.stringify(doc.record)).digest('hex');
|
|
1647
|
+
hashStatus = computedHash === anchoredHash ? 'match' : 'mismatch';
|
|
1648
|
+
if (hashStatus === 'match' && expectedHash && expectedHash !== anchoredHash) hashStatus = 'mismatch';
|
|
1649
|
+
} else if (expectedHash) {
|
|
1650
|
+
computedHash = expectedHash;
|
|
1651
|
+
hashStatus = expectedHash === anchoredHash ? 'match' : 'mismatch';
|
|
1652
|
+
} else {
|
|
1653
|
+
hashStatus = 'unchecked';
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
let signatureStatus = 'absent';
|
|
1657
|
+
let signatureScheme, signerKey, statement, declaredStatement, agentId;
|
|
1658
|
+
if (doc.agent && doc.agent.key && doc.agent.signature) {
|
|
1659
|
+
signerKey = doc.agent.key;
|
|
1660
|
+
agentId = doc.agent.id;
|
|
1661
|
+
// Never trust the document's own statement field. In record mode the
|
|
1662
|
+
// statement is built from the recomputed record hash; in hash-only mode
|
|
1663
|
+
// from content_sha256 (a swapped content_sha256 breaks the signature).
|
|
1664
|
+
statement = `nirium-audit-v1:${mode === 'record' ? computedHash : anchoredHash}`;
|
|
1665
|
+
declaredStatement = doc.agent.statement;
|
|
1666
|
+
signatureScheme = verifyEd25519Signature(signerKey, statement, doc.agent.signature) || undefined;
|
|
1667
|
+
signatureStatus = signatureScheme ? 'valid' : 'invalid';
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
// A pass requires at least one check to have actually run and succeeded.
|
|
1671
|
+
// "No check failed" alone is true when both were skipped (hash unchecked,
|
|
1672
|
+
// signature absent), which is not the same as the evidence being verified.
|
|
1673
|
+
const anyFailed = hashStatus === 'mismatch' || signatureStatus === 'invalid';
|
|
1674
|
+
const anyPassed = hashStatus === 'match' || signatureStatus === 'valid';
|
|
1675
|
+
const ok = !anyFailed && anyPassed;
|
|
1676
|
+
return { ok, verified: ok, cid, mode, hashMatch: hashStatus === 'match', hashStatus, expectedHash: anchoredHash, computedHash, signatureStatus, signatureScheme, signerKey, statement, declaredStatement, agentId };
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
// `gateways` may be a single URL string (back-compat for direct callers)
|
|
1680
|
+
// or an array tried in order. On a 404, the SAME gateway is retried up to
|
|
1681
|
+
// `retries` times with a flat backoff before moving to the next gateway -
|
|
1682
|
+
// a 404 can mean "not propagated to this gateway yet", which a moment's
|
|
1683
|
+
// wait often resolves, unlike a real 4xx/5xx or network failure, which
|
|
1684
|
+
// moves on immediately since retrying the same gateway won't help.
|
|
1685
|
+
// `sleepFn` exists only so tests don't have to sit through real backoff.
|
|
1686
|
+
async function fetchAndVerifyCid(cid, gateways = 'https://gateway.pinata.cloud', fetchFn = globalThis.fetch, opts = {}) {
|
|
1687
|
+
const list = Array.isArray(gateways) ? gateways : [gateways];
|
|
1688
|
+
const retries = Number.isInteger(opts.retries) && opts.retries >= 0 ? opts.retries : 2;
|
|
1689
|
+
const timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : 8000;
|
|
1690
|
+
const sleep = opts.sleepFn || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1691
|
+
const BACKOFF_MS = 300;
|
|
1692
|
+
|
|
1693
|
+
const attempts = [];
|
|
1694
|
+
for (const gatewayUrl of list) {
|
|
1695
|
+
const url = `${gatewayUrl.replace(/\/$/, '')}/ipfs/${cid}`;
|
|
1696
|
+
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
|
1697
|
+
if (attempt > 0) await sleep(BACKOFF_MS);
|
|
1698
|
+
try {
|
|
1699
|
+
const res = await fetchFn(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
1700
|
+
if (res.status === 404) {
|
|
1701
|
+
attempts.push({ gateway: gatewayUrl, attempt, status: 404 });
|
|
1702
|
+
continue; // worth retrying THIS gateway: may just not be propagated yet
|
|
1703
|
+
}
|
|
1704
|
+
if (!res.ok) {
|
|
1705
|
+
attempts.push({ gateway: gatewayUrl, attempt, status: res.status });
|
|
1706
|
+
break; // a real error from this gateway - try the next one, not more retries here
|
|
1707
|
+
}
|
|
1708
|
+
const doc = await res.json();
|
|
1709
|
+
return { ...verifyAuditDocument(doc, cid, opts), gateway: gatewayUrl, attempts: [...attempts, { gateway: gatewayUrl, attempt, status: 200 }] };
|
|
1710
|
+
} catch (err) {
|
|
1711
|
+
attempts.push({ gateway: gatewayUrl, attempt, error: err?.message || String(err) });
|
|
1712
|
+
break; // network-level failure (unreachable, timeout) - try the next gateway
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
// Every gateway exhausted without a usable (200) response. All-404
|
|
1718
|
+
// means the content plausibly just isn't propagated anywhere yet -
|
|
1719
|
+
// a different situation from a gateway being unreachable or erroring,
|
|
1720
|
+
// which this reports distinctly so a caller doesn't read "not found
|
|
1721
|
+
// anywhere" as "the hash doesn't match" (it was never fetched at all).
|
|
1722
|
+
const allNotFound = attempts.length > 0 && attempts.every((a) => a.status === 404);
|
|
1723
|
+
return {
|
|
1724
|
+
ok: false, verified: false, cid, hashMatch: false, expectedHash: '', computedHash: '', signatureStatus: 'absent',
|
|
1725
|
+
availability: allNotFound ? 'not_yet_available' : 'gateway_error',
|
|
1726
|
+
error: allNotFound
|
|
1727
|
+
? `CID not found on ${list.length} gateway(s) after ${retries} retr${retries === 1 ? 'y' : 'ies'} each - it may not be propagated yet, not necessarily wrong`
|
|
1728
|
+
: `Could not fetch the CID from any of ${list.length} gateway(s) - see attempts for each failure`,
|
|
1729
|
+
attempts,
|
|
1730
|
+
};
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
function formatVerifyOutput(result) {
|
|
1734
|
+
const lines = [];
|
|
1735
|
+
lines.push(`🔍 Nirium Audit Verifier`);
|
|
1736
|
+
if (result.cid) lines.push(`CID: ${result.cid}`);
|
|
1737
|
+
lines.push(`--------------------------------------------------`);
|
|
1738
|
+
|
|
1739
|
+
// The document was never fetched at all (every gateway failed), so
|
|
1740
|
+
// there is no hash or signature to report on - printing those sections
|
|
1741
|
+
// would show a false "MISMATCH" for a CID that was simply never
|
|
1742
|
+
// retrieved. `availability` tells apart "not found anywhere yet"
|
|
1743
|
+
// (may just not be propagated) from an actual gateway/network error.
|
|
1744
|
+
if (result.hashStatus === undefined && result.error) {
|
|
1745
|
+
lines.push(result.availability === 'not_yet_available'
|
|
1746
|
+
? `ℹ NOT YET AVAILABLE: ${result.error}`
|
|
1747
|
+
: `❌ GATEWAY ERROR: ${result.error}`);
|
|
1748
|
+
if (Array.isArray(result.attempts) && result.attempts.length > 0) {
|
|
1749
|
+
lines.push(`--------------------------------------------------`);
|
|
1750
|
+
lines.push('Attempts:');
|
|
1751
|
+
for (const a of result.attempts) {
|
|
1752
|
+
lines.push(` ${a.gateway} (try ${a.attempt + 1}): ${a.error ? a.error : `HTTP ${a.status}`}`);
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
lines.push(`--------------------------------------------------`);
|
|
1756
|
+
lines.push(result.availability === 'not_yet_available'
|
|
1757
|
+
? `❌ NOT YET AVAILABLE (not a hash mismatch - try again shortly, or add --gateway for another source)`
|
|
1758
|
+
: `❌ VERIFICATION FAILED (could not reach the content, not a hash mismatch)`);
|
|
1759
|
+
return lines.join('\n');
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
if (result.hashStatus === 'unchecked') {
|
|
1763
|
+
lines.push(`ℹ HASH: NOT CHECKED (hash-only anchor: ${result.expectedHash.slice(0, 16)}...)`);
|
|
1764
|
+
lines.push(` Pass --hash <hex> or --evidence <file> to compare it with your original evidence.`);
|
|
1765
|
+
} else if (result.hashMatch) {
|
|
1766
|
+
lines.push(`✔ HASH: MATCH (${result.expectedHash.slice(0, 16)}...)${result.mode === 'hash-only' ? ' [hash-only]' : ''}`);
|
|
1767
|
+
} else {
|
|
1768
|
+
lines.push(`❌ HASH: MISMATCH (Anchored: ${result.expectedHash}, Computed: ${result.computedHash})`);
|
|
1769
|
+
}
|
|
1770
|
+
if (result.signatureStatus === 'valid') {
|
|
1771
|
+
lines.push(`✔ SIGNATURE: VALID${result.signatureScheme === 'sep53' ? ' (SEP-53)' : ''} (Signed by ${result.signerKey})`);
|
|
1772
|
+
if (result.statement) lines.push(` Statement: ${result.statement}`);
|
|
1773
|
+
if (result.agentId) lines.push(` Agent ID: ${result.agentId}`);
|
|
1774
|
+
} else if (result.signatureStatus === 'invalid') {
|
|
1775
|
+
lines.push(`❌ SIGNATURE: INVALID (Signature check failed for key ${result.signerKey})`);
|
|
1776
|
+
} else {
|
|
1777
|
+
lines.push(`ℹ SIGNATURE: ABSENT (No agent attestation embedded)`);
|
|
1778
|
+
}
|
|
1779
|
+
lines.push(`--------------------------------------------------`);
|
|
1780
|
+
if (result.error) {
|
|
1781
|
+
lines.push(`❌ ERROR: ${result.error}`);
|
|
1782
|
+
} else if (result.ok) {
|
|
1783
|
+
lines.push(`✅ VERIFICATION PASSED`);
|
|
1784
|
+
} else if (result.hashStatus === 'unchecked' && result.signatureStatus === 'absent') {
|
|
1785
|
+
lines.push(`❌ NOTHING VERIFIED (pass --hash, --evidence, or anchor with an agent signature)`);
|
|
1786
|
+
} else {
|
|
1787
|
+
lines.push(`❌ VERIFICATION FAILED`);
|
|
1788
|
+
}
|
|
1789
|
+
return lines.join('\n');
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1793
|
+
// anchor — anchor a hash or small record to IPFS via the Audit Trail node
|
|
1794
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1795
|
+
|
|
1796
|
+
const ANCHOR_MAX_RECORD_BYTES = 8 * 1024;
|
|
1797
|
+
|
|
1798
|
+
// `nirium anchor` deliberately has no `--network` flag: the agent box
|
|
1799
|
+
// decides its own network (STELLAR_NETWORK) and the server already
|
|
1800
|
+
// rejects a `network` field in the body. A client-side flag here would
|
|
1801
|
+
// only ever be ignored, which is worse than not having it.
|
|
1802
|
+
async function executeAnchorCommand(options) {
|
|
1803
|
+
const fail = (error, hint) => {
|
|
1804
|
+
if (options.json) {
|
|
1805
|
+
console.log(JSON.stringify({ ok: false, error, ...(hint ? { hint } : {}) }));
|
|
1806
|
+
} else {
|
|
1807
|
+
console.error(`❌ Error: ${error}${hint ? `\n ${hint}` : ''}`);
|
|
1808
|
+
}
|
|
1809
|
+
process.exit(1);
|
|
1810
|
+
};
|
|
1811
|
+
|
|
1812
|
+
const given = ['file', 'hash', 'record'].filter((k) => options[k] !== undefined);
|
|
1813
|
+
if (given.length === 0) {
|
|
1814
|
+
fail('Provide exactly one of --file, --hash, or --record.');
|
|
1815
|
+
return;
|
|
1816
|
+
}
|
|
1817
|
+
if (given.length > 1) {
|
|
1818
|
+
fail(`--${given[0]} and --${given[1]} were both given - use exactly one.`);
|
|
1819
|
+
return;
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
const body = {};
|
|
1823
|
+
if (options.file !== undefined) {
|
|
1824
|
+
let fileBuf;
|
|
1825
|
+
try {
|
|
1826
|
+
fileBuf = fs.readFileSync(options.file);
|
|
1827
|
+
} catch (err) {
|
|
1828
|
+
fail(`Could not read --file '${options.file}': ${err?.message || String(err)}`);
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1831
|
+
body.hash = crypto.createHash('sha256').update(fileBuf).digest('hex');
|
|
1832
|
+
} else if (options.hash !== undefined) {
|
|
1833
|
+
try {
|
|
1834
|
+
body.hash = normalizeHashInput(options.hash);
|
|
1835
|
+
} catch (err) {
|
|
1836
|
+
fail(err.message);
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
} else {
|
|
1840
|
+
let record;
|
|
1841
|
+
try {
|
|
1842
|
+
record = JSON.parse(options.record);
|
|
1843
|
+
} catch (err) {
|
|
1844
|
+
fail(`--record is not valid JSON: ${err?.message || String(err)}`);
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
if (typeof record !== 'object' || record === null || Array.isArray(record)) {
|
|
1848
|
+
fail('--record must be a JSON object, e.g. \'{"order":"A-12"}\'');
|
|
1849
|
+
return;
|
|
1850
|
+
}
|
|
1851
|
+
// Mirrors the server's own 8KB limit (MAX_RECORD_BYTES in
|
|
1852
|
+
// auditRoutes.ts) so an oversized record fails locally, before any
|
|
1853
|
+
// network call, instead of round-tripping for a 413.
|
|
1854
|
+
const raw = JSON.stringify(record);
|
|
1855
|
+
if (Buffer.byteLength(raw, 'utf8') > ANCHOR_MAX_RECORD_BYTES) {
|
|
1856
|
+
fail(`--record exceeds ${ANCHOR_MAX_RECORD_BYTES / 1024}KB - anchor a sha-256 hash instead (--hash or --file).`);
|
|
1857
|
+
return;
|
|
1858
|
+
}
|
|
1859
|
+
body.record = record;
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
if (options.tx !== undefined) body.txHash = options.tx;
|
|
1863
|
+
if (options.tag !== undefined) body.tag = options.tag;
|
|
1864
|
+
|
|
1865
|
+
const agentAttestation = await maybeBuildAgentAttestation(options, body, fail);
|
|
1866
|
+
if (agentAttestation === 'failed') return; // fail() already called and exited
|
|
1867
|
+
if (agentAttestation) body.agent = agentAttestation;
|
|
1868
|
+
|
|
1869
|
+
let response;
|
|
1870
|
+
try {
|
|
1871
|
+
response = await fetch(`${options.url}/api/audit/log`, {
|
|
1872
|
+
method: 'POST',
|
|
1873
|
+
headers: { 'content-type': 'application/json' },
|
|
1874
|
+
body: JSON.stringify(body),
|
|
1875
|
+
signal: AbortSignal.timeout(20_000),
|
|
1876
|
+
});
|
|
1877
|
+
} catch (err) {
|
|
1878
|
+
const msg = (err?.name === 'TimeoutError' || err?.name === 'AbortError')
|
|
1879
|
+
? `Timed out waiting for ${options.url}/api/audit/log`
|
|
1880
|
+
: `Agent unreachable at ${options.url}: ${err?.message || String(err)}`;
|
|
1881
|
+
fail(msg);
|
|
1882
|
+
return;
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
let data = null;
|
|
1886
|
+
try {
|
|
1887
|
+
data = await response.json();
|
|
1888
|
+
} catch { /* empty or non-JSON body */ }
|
|
1889
|
+
|
|
1890
|
+
if (!response.ok) {
|
|
1891
|
+
fail(data?.error || `Agent returned HTTP ${response.status}`, data?.sign ? `Sign this statement instead: ${data.sign}` : undefined);
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
if (options.json) {
|
|
1896
|
+
console.log(JSON.stringify({ ok: true, ...data }, null, 2));
|
|
1897
|
+
return;
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
console.log('✅ Anchored to IPFS');
|
|
1901
|
+
console.log(` CID: ${data.cid}`);
|
|
1902
|
+
console.log(` Content sha256: ${data.content_sha256}`);
|
|
1903
|
+
if (data.gatewayUrl) console.log(` Gateway URL: ${data.gatewayUrl}`);
|
|
1904
|
+
if (data.attestedBy) console.log(` Attested by: ${data.attestedBy}`);
|
|
1905
|
+
console.log(` Anchored at: ${data.anchoredAt}`);
|
|
1906
|
+
console.log(`\n Verify independently: nirium verify ${data.cid}`);
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
// Returns the `agent` object for the request body, `undefined` when
|
|
1910
|
+
// `--sign` was not passed, or the string 'failed' when fail() already
|
|
1911
|
+
// ran (caller must return without doing anything else).
|
|
1912
|
+
//
|
|
1913
|
+
// Signs locally and never sends the secret key anywhere - only the
|
|
1914
|
+
// resulting signature and the derived public key leave this process.
|
|
1915
|
+
// The statement signed, `nirium-audit-v1:<content_sha256>`, must match
|
|
1916
|
+
// exactly what the server itself computes as contentSha before it
|
|
1917
|
+
// verifies: the hash as-is for `--hash`/`--file` (already normalized to
|
|
1918
|
+
// lowercase hex at this point), or sha-256 of the record's JSON text for
|
|
1919
|
+
// `--record` - never the file's own content, which the server never sees.
|
|
1920
|
+
async function maybeBuildAgentAttestation(options, body, fail) {
|
|
1921
|
+
if (!options.sign) return undefined;
|
|
1922
|
+
|
|
1923
|
+
let secretKey;
|
|
1924
|
+
if (options.keyEnv !== undefined) {
|
|
1925
|
+
secretKey = process.env[options.keyEnv];
|
|
1926
|
+
if (!secretKey) {
|
|
1927
|
+
fail(`--key-env ${options.keyEnv} is not set (or is empty) in the environment.`);
|
|
1928
|
+
return 'failed';
|
|
1929
|
+
}
|
|
1930
|
+
} else {
|
|
1931
|
+
secretKey = loadConfig().secretKey;
|
|
1932
|
+
if (!secretKey) {
|
|
1933
|
+
fail('--sign needs a key: run `nirium config set secretKey`, or pass --key-env <VAR> '
|
|
1934
|
+
+ 'with the secret key in that environment variable.');
|
|
1935
|
+
return 'failed';
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
let keypair;
|
|
1940
|
+
try {
|
|
1941
|
+
keypair = Keypair.fromSecret(secretKey);
|
|
1942
|
+
} catch (err) {
|
|
1943
|
+
fail(`--sign: invalid Stellar secret key - ${err?.message || String(err)}`);
|
|
1944
|
+
return 'failed';
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
const contentSha = body.hash
|
|
1948
|
+
? body.hash
|
|
1949
|
+
: crypto.createHash('sha256').update(JSON.stringify(body.record)).digest('hex');
|
|
1950
|
+
const statement = `nirium-audit-v1:${contentSha}`;
|
|
1951
|
+
const signature = Buffer.from(keypair.sign(Buffer.from(statement, 'utf8'))).toString('base64');
|
|
1952
|
+
|
|
1953
|
+
return { key: keypair.publicKey(), signature };
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1957
|
+
// report — summaries and exports from the Reporting node
|
|
1958
|
+
// ═══════════════════════════════════════════════════════════════
|
|
1959
|
+
|
|
1960
|
+
function buildQueryString(params) {
|
|
1961
|
+
const qs = new URLSearchParams();
|
|
1962
|
+
for (const [k, v] of Object.entries(params)) {
|
|
1963
|
+
if (v !== undefined && v !== null && v !== '') qs.set(k, String(v));
|
|
1964
|
+
}
|
|
1965
|
+
const str = qs.toString();
|
|
1966
|
+
return str ? `?${str}` : '';
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
async function fetchReportJson(url, fail) {
|
|
1970
|
+
let response;
|
|
1971
|
+
try {
|
|
1972
|
+
response = await fetch(url, { signal: AbortSignal.timeout(20_000) });
|
|
1973
|
+
} catch (err) {
|
|
1974
|
+
const msg = (err?.name === 'TimeoutError' || err?.name === 'AbortError')
|
|
1975
|
+
? `Timed out waiting for ${url}`
|
|
1976
|
+
: `Agent unreachable: ${err?.message || String(err)}`;
|
|
1977
|
+
fail(msg);
|
|
1978
|
+
return null;
|
|
1979
|
+
}
|
|
1980
|
+
let data = null;
|
|
1981
|
+
try {
|
|
1982
|
+
data = await response.json();
|
|
1983
|
+
} catch { /* empty or non-JSON body */ }
|
|
1984
|
+
if (!response.ok) {
|
|
1985
|
+
fail(data?.error || `Agent returned HTTP ${response.status}`);
|
|
1986
|
+
return null;
|
|
1987
|
+
}
|
|
1988
|
+
return data;
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
async function executeReportSummaryCommand(options) {
|
|
1992
|
+
const fail = (error) => {
|
|
1993
|
+
if (options.json) {
|
|
1994
|
+
console.log(JSON.stringify({ ok: false, error }));
|
|
1995
|
+
} else {
|
|
1996
|
+
console.error(`❌ Error: ${error}`);
|
|
1997
|
+
}
|
|
1998
|
+
process.exit(1);
|
|
1999
|
+
};
|
|
2000
|
+
|
|
2001
|
+
const qs = buildQueryString({ from: options.from, to: options.to, network: options.network });
|
|
2002
|
+
const data = await fetchReportJson(`${options.url}/api/reporting/summary${qs}`, fail);
|
|
2003
|
+
if (!data) return; // fail() already exited
|
|
2004
|
+
|
|
2005
|
+
if (options.json) {
|
|
2006
|
+
console.log(JSON.stringify(data, null, 2));
|
|
2007
|
+
return;
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
console.log('📊 Nirium Reporting Summary');
|
|
2011
|
+
console.log(` Network: ${data.network}`);
|
|
2012
|
+
console.log(` Period: ${data.period?.from || '(default window)'} -> ${data.period?.to || 'now'}`);
|
|
2013
|
+
console.log(` Payroll: ${data.payroll?.settledRuns ?? 0} settled run(s), ${data.payroll?.recipientsPaid ?? 0} recipient(s) paid`);
|
|
2014
|
+
for (const [asset, amount] of Object.entries(data.payroll?.totalsByAsset || {})) {
|
|
2015
|
+
console.log(` ${asset}: ${amount}`);
|
|
2016
|
+
}
|
|
2017
|
+
console.log(` Payments: ${data.payments?.count ?? 0} receipt(s), ${data.payments?.totalUsdc ?? '0'} USDC total`);
|
|
2018
|
+
// Nodes since 8 Nov 2026 send lastAnchoredAt instead of latestCid (the latest
|
|
2019
|
+
// anchor is usually someone else's evidence). Older nodes still send latestCid.
|
|
2020
|
+
const lastAnchor = data.anchors?.lastAnchoredAt
|
|
2021
|
+
? `last: ${String(data.anchors.lastAnchoredAt).slice(0, 10)}`
|
|
2022
|
+
: `latest: ${data.anchors?.latestCid || 'none'}`;
|
|
2023
|
+
console.log(` Anchors: ${data.anchors?.count ?? 0} (${lastAnchor})`);
|
|
2024
|
+
if (Array.isArray(data.warnings) && data.warnings.length > 0) {
|
|
2025
|
+
console.log(' ⚠ Warnings:');
|
|
2026
|
+
for (const w of data.warnings) console.log(` - ${w}`);
|
|
2027
|
+
}
|
|
2028
|
+
console.log(`\n ${data.disclaimer || ''}`);
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
const REPORT_EXPORT_TYPES = new Set(['payroll', 'payments', 'anchors']);
|
|
2032
|
+
|
|
2033
|
+
async function executeReportExportCommand(type, options) {
|
|
2034
|
+
const fail = (error) => {
|
|
2035
|
+
if (options.json) {
|
|
2036
|
+
console.log(JSON.stringify({ ok: false, error }));
|
|
2037
|
+
} else {
|
|
2038
|
+
console.error(`❌ Error: ${error}`);
|
|
2039
|
+
}
|
|
2040
|
+
process.exit(1);
|
|
2041
|
+
};
|
|
2042
|
+
|
|
2043
|
+
if (!REPORT_EXPORT_TYPES.has(type)) {
|
|
2044
|
+
fail('`type` must be one of: payroll | payments | anchors');
|
|
2045
|
+
return;
|
|
2046
|
+
}
|
|
2047
|
+
if (options.csv && options.json) {
|
|
2048
|
+
fail('--csv and --json are mutually exclusive - --csv writes a file, --json prints the response.');
|
|
2049
|
+
return;
|
|
2050
|
+
}
|
|
2051
|
+
if (options.limit !== undefined) {
|
|
2052
|
+
const n = Number(options.limit);
|
|
2053
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
2054
|
+
fail(`Invalid --limit '${options.limit}': must be a positive integer.`);
|
|
2055
|
+
return;
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
const format = options.csv ? 'csv' : 'json';
|
|
2060
|
+
const qs = buildQueryString({
|
|
2061
|
+
type, format, from: options.from, to: options.to, limit: options.limit, network: options.network,
|
|
2062
|
+
});
|
|
2063
|
+
const url = `${options.url}/api/reporting/export${qs}`;
|
|
2064
|
+
|
|
2065
|
+
if (format === 'csv') {
|
|
2066
|
+
let response;
|
|
2067
|
+
try {
|
|
2068
|
+
response = await fetch(url, { signal: AbortSignal.timeout(30_000) });
|
|
2069
|
+
} catch (err) {
|
|
2070
|
+
fail(`Agent unreachable: ${err?.message || String(err)}`);
|
|
2071
|
+
return;
|
|
2072
|
+
}
|
|
2073
|
+
if (!response.ok) {
|
|
2074
|
+
let data = null;
|
|
2075
|
+
try { data = await response.json(); } catch { /* non-JSON error body */ }
|
|
2076
|
+
fail(data?.error || `Agent returned HTTP ${response.status}`);
|
|
2077
|
+
return;
|
|
2078
|
+
}
|
|
2079
|
+
const text = await response.text();
|
|
2080
|
+
try {
|
|
2081
|
+
fs.writeFileSync(options.csv, text);
|
|
2082
|
+
} catch (err) {
|
|
2083
|
+
fail(`Could not write --csv '${options.csv}': ${err?.message || String(err)}`);
|
|
2084
|
+
return;
|
|
2085
|
+
}
|
|
2086
|
+
console.log(`✅ Wrote ${options.csv}`);
|
|
2087
|
+
return;
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
const data = await fetchReportJson(url, fail);
|
|
2091
|
+
if (!data) return; // fail() already exited
|
|
2092
|
+
|
|
2093
|
+
if (options.json) {
|
|
2094
|
+
console.log(JSON.stringify(data, null, 2));
|
|
2095
|
+
return;
|
|
2096
|
+
}
|
|
2097
|
+
|
|
2098
|
+
// `export anchors` prints one line per anchor: when and on which network,
|
|
2099
|
+
// tab-separated. No CID: the public Reporting export stopped returning them
|
|
2100
|
+
// on 8 Nov 2026 (an anchor's CID belongs to whoever made it), and this never
|
|
2101
|
+
// prints one even if an older node still sends it. Row count and the
|
|
2102
|
+
// disclaimer go to stderr so stdout stays clean for piping.
|
|
2103
|
+
for (const row of data.rows || []) {
|
|
2104
|
+
console.log(type === 'anchors' ? `${row.anchored_at || ''}\t${row.network || ''}` : JSON.stringify(row));
|
|
2105
|
+
}
|
|
2106
|
+
console.error(`# ${data.rowCount ?? (data.rows || []).length} row(s). ${data.disclaimer || ''}`);
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
program.parse();
|