@wasit-dev/cli 0.6.0 → 0.8.0-beta.1

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/dist/index.js CHANGED
@@ -1,12 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import "dotenv/config";
2
+ import { createRequire } from "node:module";
3
3
  import { createElement } from "react";
4
4
  import { render } from "ink";
5
5
  import { Command } from "commander";
6
6
  import { App } from "./dashboard/App.js";
7
7
  import { CLI_VERSION } from "./version.js";
8
8
  import { registerWalletCommand } from "./wallet-command.js";
9
- import { CHECK_CATALOGUE, PROTOCOL_IDS, checkStatus, runMppChannelSuite, runMppChargeSuite, runX402PaymentChecks, runX402ReadChecks, summarize, toStructuredRun, } from "@wasit-dev/core";
9
+ import { DEFAULT_SERVE_NETWORK, MODE_DESCRIPTIONS, SERVE_MODES, SERVE_NETWORKS, createServeServer, validateServeOptions, } from "./serve.js";
10
+ import { executeCiReport } from "./ci-report-command.js";
11
+ import { exitCodeFor, note, report, verdictNotes } from "./output.js";
12
+ import { LiveReport } from "./live.js";
13
+ import { colorDepth, colorEnabled, lineWidth, liveEnabled, styler } from "./style.js";
14
+ import { executeRun } from "./run.js";
15
+ import { CHECK_CATALOGUE, PROTOCOL_IDS, X402_PAYMENT_CHECK_IDS, catalogueEntry, deniedEnvValues, endpointOutcome, networkClass, paymentChainFor, runMppChannelSuite, runMppChargeSuite, runX402PaymentChecks, runX402ReadChecks, sanitizeText, } from "@wasit-dev/core";
16
+ const require = createRequire(import.meta.url);
17
+ /**
18
+ * Loads `.env` from the working directory exactly as `import "dotenv/config"`
19
+ * did when it sat at the top of this file (it reads the DOTENV_CONFIG_*
20
+ * variables and arguments too). A command runs it before its action; see the
21
+ * hook below for the commands that do not.
22
+ */
23
+ function loadDotenv() {
24
+ require("dotenv/config");
25
+ }
26
+ /** CI sets one of these; the value does not matter, `false` included: when in doubt, it is CI. */
27
+ function inCi(env) {
28
+ return (env["CI"] ?? "") !== "" || (env["GITHUB_ACTIONS"] ?? "") !== "";
29
+ }
10
30
  /** Which wasit subcommand runs each protocol's checks — for `wasit checks` output. */
11
31
  const COMMAND_BY_PROTOCOL = {
12
32
  x402: "test",
@@ -42,60 +62,32 @@ Examples:
42
62
  $ wasit mpp-charge --target https://api.example.com/paid-endpoint --payer-key S...
43
63
  $ wasit mpp-channel --target https://api.example.com/paid-endpoint
44
64
  $ wasit wallet create --role mpp-charge --fund
65
+ $ wasit serve --mode no-settle # a lying paywall, to test an agent that pays
45
66
 
46
67
  Run "wasit <command> --help" for that command's own options and cost notes.
47
68
  Add --json to test/mpp-charge/mpp-channel for machine-readable output.
48
69
  Full check catalogue (every check ID, spec reference, pass criteria):
49
70
  https://github.com/wasit-dev/wasit/blob/main/docs/CHECKS.md`);
50
- /**
51
- * Prints an advisory/status line meant for a human watching the terminal —
52
- * never part of the run's actual result. Routed to stderr when --json is
53
- * set, so stdout stays parseable JSON and a script piping it (jq, etc.)
54
- * never has to skip past prose first.
55
- */
56
- function note(json, message) {
57
- if (json) {
58
- console.error(message);
59
- }
60
- else {
61
- console.log(message);
62
- }
71
+ // `.env` is loaded before a command's action, as it always was, with two
72
+ // exceptions (spec A8 #2, A-A01): `wasit run` does not load it in CI, where the
73
+ // working directory is a checked-out pull request and a `.env` it added could
74
+ // steer the run; `wasit ci-report` never does, it has no use for it. CI is read
75
+ // from the real environment, before any `.env` could change it.
76
+ program.hook("preAction", (_program, action) => {
77
+ const name = action.name();
78
+ if (name === "ci-report")
79
+ return;
80
+ if (name === "run" && inCi(process.env))
81
+ return;
82
+ loadDotenv();
83
+ });
84
+ /** Waits until what was written to stdout and stderr has been handed to the system, so `process.exit` cannot cut a long report. */
85
+ async function flushOutput() {
86
+ await Promise.all([process.stdout, process.stderr].map((stream) => new Promise((resolve) => stream.write("", () => resolve()))));
63
87
  }
64
- /**
65
- * Prints results and returns the process exit code.
66
- *
67
- * A skipped check carries `pass: false` so it can never be counted as
68
- * conformance, but it is not a failure and must not fail the run. An errored
69
- * check produced no verdict at all and is reported separately again.
70
- *
71
- * `--json` reuses `toStructuredRun()` from core — the same reshape the MCP
72
- * server calls for its own structured output — rather than defining a
73
- * second JSON shape here that could drift from it.
74
- */
75
- function report(results, json) {
76
- const counts = summarize(results);
77
- if (json) {
78
- console.log(JSON.stringify(toStructuredRun(results), null, 2));
79
- return counts.exitCode;
80
- }
81
- for (const result of results) {
82
- const flag = result.destructive ? " [destructive]" : "";
83
- console.log(`${checkStatus(result)} ${result.id} ${result.name}${flag}`);
84
- console.log(` ${result.detail}\n`);
85
- }
86
- const line = [`${counts.passed} passed`];
87
- if (counts.failed > 0)
88
- line.push(`${counts.failed} failed`);
89
- if (counts.errored > 0)
90
- line.push(`${counts.errored} could not run`);
91
- if (counts.skipped > 0)
92
- line.push(`${counts.skipped} skipped`);
93
- console.log(`${line.join(", ")}.`);
94
- if (counts.errored > 0 && counts.failed === 0) {
95
- console.log("\nNo verdict: some checks never reached the target or the run is " +
96
- "misconfigured. This is not a statement about the target's conformance.");
97
- }
98
- return counts.exitCode;
88
+ /** A mistake on the command line learned nothing about a service: exit 2, not commander's 1. */
89
+ function exitTwoOnUsageError(error) {
90
+ process.exit(error.exitCode === 0 ? 0 : 2);
99
91
  }
100
92
  program
101
93
  .command("checks")
@@ -143,14 +135,19 @@ program
143
135
  .command("test")
144
136
  .description("Run x402 compliance checks against a target service")
145
137
  .requiredOption("--target <url>", "URL of the service to test")
146
- .option("--network <network>", "Network identifier", "stellar:testnet")
147
- .option("--rpc-url <url>", "Override the Soroban RPC endpoint used to verify X402-06's settlement")
148
- .option("--payer-key <key>", "Testnet payer secret key (overrides STELLAR_PRIVATE_KEY from .env)")
138
+ .option("--network <network>", "Network the payment checks pay on: stellar:testnet, " +
139
+ "eip155:84532 (Base Sepolia), eip155:11155111 (Ethereum Sepolia) or " +
140
+ "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 (Solana devnet). Test networks " +
141
+ "only: on any other network, stellar:pubnet included, the payment checks " +
142
+ "stop before anything is signed. X402-01..05 apply to a challenge on any chain.", "stellar:testnet")
143
+ .option("--rpc-url <url>", "Override the RPC endpoint used to verify X402-06's settlement (Soroban RPC on Stellar, JSON-RPC on EVM and Solana)")
144
+ .option("--payer-key <key>", "Testnet payer key (overrides STELLAR_PRIVATE_KEY, EVM_PRIVATE_KEY on eip155 networks, " +
145
+ "or SVM_PRIVATE_KEY on Solana, from .env)")
149
146
  .option("--method <verb>", "HTTP method the paid endpoint uses (default: GET). Paid endpoints that " +
150
147
  "compute something usually take POST.")
151
148
  .option("--body <json>", "Request body, sent verbatim. Implies Content-Type: application/json.")
152
149
  .option("--header <name:value>", "Extra request header the endpoint needs before it will issue a challenge. Repeatable.", collectHeader)
153
- .option("--read-only", "Skip payment checks (X402-06/07)", false)
150
+ .option("--read-only", "Skip the payment checks (X402-06..11)", false)
154
151
  .option("--json", "Print results as JSON instead of formatted text", false)
155
152
  .addHelpText("after", `
156
153
  Examples:
@@ -158,10 +155,17 @@ Examples:
158
155
  $ wasit test --target https://api.example.com/paid-endpoint --payer-key S...
159
156
  $ wasit test --target https://api.example.com/paid-endpoint --read-only --json
160
157
 
161
- X402-01..05 (challenge/header checks) always run and cost nothing. X402-06/07
158
+ X402-01..05 (challenge/header checks) always run and cost nothing. X402-06..10
162
159
  (real payment checks) run only when a payer key is available and --read-only
163
- is not set: X402-06 settles a payment, X402-07 attempts one with a corrupted
164
- signature. See docs/CHECKS.md for what each check ID verifies.`)
160
+ is not set: X402-06 settles a payment; X402-07..10 send payments the target
161
+ must refuse (a corrupted signature, a replay, an underpayment, an expired
162
+ authorization). X402-11 needs a request the service must refuse, the reject case
163
+ of a wasit.config.json endpoint: it runs in wasit run and is skipped here. See
164
+ docs/CHECKS.md for what each check ID verifies.
165
+
166
+ At a terminal the output is coloured and live: each check shows while it runs,
167
+ with its duration, and the run's duration comes at the end. A pipe, CI, --json
168
+ or NO_COLOR gives the plain text; FORCE_COLOR=1 colours a pipe.`)
165
169
  .action(async (opts) => {
166
170
  const jsonMode = opts.json === true;
167
171
  const shape = {
@@ -169,16 +173,24 @@ signature. See docs/CHECKS.md for what each check ID verifies.`)
169
173
  ...(opts.body !== undefined ? { body: opts.body } : {}),
170
174
  ...(opts.header ? { headers: opts.header } : {}),
171
175
  };
176
+ // A person at a terminal gets the coloured, live output; a pipe, CI, NO_COLOR
177
+ // and --json get the plain text below, unchanged.
178
+ if (!jsonMode && colorEnabled(process.stdout, process.env)) {
179
+ process.exit(await liveX402Test(opts, shape));
180
+ }
172
181
  const results = await runX402ReadChecks({ target: opts.target, ...shape });
173
- const payerKey = opts.payerKey ?? process.env.STELLAR_PRIVATE_KEY;
182
+ // Each chain reads its own payer key: a Stellar secret is no use on EVM.
183
+ const keyEnv = paymentChainFor(opts.network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY";
184
+ const payerKey = opts.payerKey ?? process.env[keyEnv];
174
185
  if (opts.readOnly) {
175
186
  note(jsonMode, "(--read-only set: skipping payment checks)\n");
176
187
  }
177
188
  else if (!payerKey) {
178
- note(jsonMode, "(no payer key: set STELLAR_PRIVATE_KEY in .env or pass --payer-key — skipping payment checks)\n");
189
+ note(jsonMode, `(no payer key: set ${keyEnv} in .env or pass --payer-key — skipping payment checks)\n`);
179
190
  }
180
191
  else {
181
- note(jsonMode, "X402-06 settles a real payment and X402-07 attempts one. Testnet funds will move.\n");
192
+ note(jsonMode, `When the target offers a ${opts.network} option, X402-06 settles a real ` +
193
+ "payment and X402-07..10 send payments it must refuse. Testnet funds will move.\n");
182
194
  results.push(...(await runX402PaymentChecks({
183
195
  target: opts.target,
184
196
  network: opts.network,
@@ -187,14 +199,179 @@ signature. See docs/CHECKS.md for what each check ID verifies.`)
187
199
  ...shape,
188
200
  })));
189
201
  }
190
- process.exit(report(results, jsonMode));
202
+ // One endpoint: a service Wasit could not grade exits 2, not 0 (spec A8 #3).
203
+ process.exit(report(results, jsonMode, { protocol: "x402" }));
204
+ });
205
+ program
206
+ .command("run")
207
+ .description("Run the endpoints of a wasit.config.json and write one report: the payment tier on a test network, --read-only, or --dry-run")
208
+ .option("--config <path>", "The config file", "wasit.config.json")
209
+ .option("--env <name>", "The environment to run (default: defaultEnvironment, else the only one)")
210
+ .option("--endpoint <name>", "Run only this endpoint, by name. Repeatable.", (value, previous) => [...previous, value], [])
211
+ .option("--read-only", "Run the unpaid challenge checks (X402-01..05) only. They send no payment and sign nothing. Without it (and without --dry-run) the run is the payment tier.", false)
212
+ .option("--dry-run", "Print what the payment checks would sign: per endpoint the payee, the asset, the amount of each signature and the worst case, " +
213
+ "against the caps ($1 a payment, $5 a run, lower with maxRunUsd). Reads each x402 endpoint's unpaid challenge; " +
214
+ "uses no key, sends no payment, signs nothing. Exit 2 when a paying run would be refused. Not with --read-only.", false)
215
+ .option("--json", "Print the report as JSON instead of text", false)
216
+ .option("--out <file>", "Write the JSON report to this file as well")
217
+ .option("--start", "Run service.start from the config, wait for service.ready, run, and stop the service afterwards. " +
218
+ "The service does not receive Wasit's key variables, header variables or WASIT_RPC_URL.", false)
219
+ .option("--start-if-local", "Like --start, but only when service.start is set and the environment is on this machine (localhost, 127.x.x.x or [::1]); " +
220
+ "otherwise the configured baseUrl is read as it is, which is how a deployed endpoint is checked. Not with --start.", false)
221
+ .option("--baseline <file>", "The report of the default branch: an endpoint graded there that is unsupported or without a verdict now is a regression (exit 1)")
222
+ .option("--mainnet", "Refused in this version: the mainnet opt-in is not part of it. The run stops with exit 2 before the config is read; nothing is started, sent or signed.", false)
223
+ .addHelpText("after", `
224
+ Examples:
225
+ $ wasit run --read-only
226
+ $ wasit run --read-only --env staging --endpoint weather --json --out wasit-report.json
227
+ $ wasit run --read-only --start
228
+ $ wasit run --read-only --start-if-local --env mainnet
229
+ $ wasit run --dry-run --start
230
+ $ wasit run --start (payment tier: STELLAR_PRIVATE_KEY on stellar:testnet)
231
+
232
+ Exit codes: 0 every graded endpoint conforms; 1 an endpoint does not conform, or one
233
+ graded on the baseline is not graded now; 2 no verdict (nothing could be graded, a
234
+ check could not run, the config or the service could not be used, or the payment
235
+ tier was asked for and did not pay: no payer key, or operatedByMe not true).
236
+ The payment tier pays on test networks only: at most $1.00 a payment and $5.00 a run
237
+ (lower with maxRunUsd), only the pinned payTo and asset when the config pins them.
238
+ In GitHub Actions it pays only on push to the default branch, schedule and
239
+ workflow_dispatch; a pull request runs the read-only checks, and a payer key set on
240
+ a run that may not pay is refused before the service starts. In another CI (CI set,
241
+ not GitHub Actions) the payment tier is refused with exit 2: use --read-only there,
242
+ with no payer key in the job.
243
+ X402-11 runs for an endpoint with a reject case, on Stellar: it sends a valid payment
244
+ with the request the service must refuse, then reads the chain until that payment's
245
+ authorization has expired, up to six minutes; a lifetime above 300 s or below 30 s is
246
+ not signed, and an authorization signed to outlive 300 s is not sent.
247
+ In CI (CI or GITHUB_ACTIONS set) a .env file in the working directory is not read.`)
248
+ .exitOverride(exitTwoOnUsageError)
249
+ .action(async (opts) => {
250
+ let code;
251
+ try {
252
+ code = await executeRun({
253
+ config: opts.config,
254
+ ...(opts.env === undefined ? {} : { env: opts.env }),
255
+ endpoint: opts.endpoint,
256
+ readOnly: opts.readOnly === true,
257
+ dryRun: opts.dryRun === true,
258
+ json: opts.json === true,
259
+ ...(opts.out === undefined ? {} : { out: opts.out }),
260
+ start: opts.start === true,
261
+ startIfLocal: opts.startIfLocal === true,
262
+ ...(opts.baseline === undefined ? {} : { baseline: opts.baseline }),
263
+ mainnet: opts.mainnet === true,
264
+ }, { env: process.env, stdout: (line) => console.log(line), stderr: (line) => console.error(line) });
265
+ }
266
+ catch (error) {
267
+ const message = error instanceof Error ? error.message : String(error);
268
+ console.error(sanitizeText(`wasit run: unexpected error: ${message}`, { redact: deniedEnvValues(process.env) }));
269
+ code = 2;
270
+ }
271
+ await flushOutput();
272
+ process.exit(code);
273
+ });
274
+ program
275
+ .command("ci-report")
276
+ .description("Write the pull request comment and the job summary from the report of wasit run")
277
+ .requiredOption("--report <file>", "The report written by wasit run --json --out")
278
+ .option("--baseline <file>", "The baseline of the default branch, for \"Changed since main\" and the recent failures")
279
+ .option("--comment <file>", "Where the comment goes", "comment.md")
280
+ .option("--summary <file>", "The job summary file, appended to (default: $GITHUB_STEP_SUMMARY)")
281
+ .option("--baseline-out <file>", "Write the next baseline here: this report with its history. For a run on the default branch.")
282
+ .option("--history <file>", "The baseline file of the newest completed run on the default branch, failed or not: the recent failures are counted from its history")
283
+ .option("--baseline-run <id>", "The id of the run the baseline came from, named in the comment")
284
+ .option("--check-run <file>", "Write the check run's title, summary and conclusion here, as JSON")
285
+ .exitOverride(exitTwoOnUsageError)
286
+ .action(async (opts) => {
287
+ let code;
288
+ try {
289
+ code = await executeCiReport({
290
+ report: opts.report,
291
+ ...(opts.baseline === undefined ? {} : { baseline: opts.baseline }),
292
+ comment: opts.comment,
293
+ ...(opts.summary === undefined ? {} : { summary: opts.summary }),
294
+ ...(opts.baselineOut === undefined ? {} : { baselineOut: opts.baselineOut }),
295
+ ...(opts.history === undefined ? {} : { history: opts.history }),
296
+ ...(opts.baselineRun === undefined ? {} : { baselineRun: opts.baselineRun }),
297
+ ...(opts.checkRun === undefined ? {} : { checkRun: opts.checkRun }),
298
+ }, { env: process.env, stdout: (line) => console.log(line), stderr: (line) => console.error(line) });
299
+ }
300
+ catch (error) {
301
+ const message = error instanceof Error ? error.message : String(error);
302
+ console.error(sanitizeText(`wasit ci-report: unexpected error: ${message}`, { redact: deniedEnvValues(process.env) }));
303
+ code = 2;
304
+ }
305
+ await flushOutput();
306
+ process.exit(code);
307
+ });
308
+ program
309
+ .command("serve")
310
+ .description("Run a local x402 paywall that misbehaves on purpose, to test an agent that pays")
311
+ .requiredOption("--mode <mode>", `How the paywall misbehaves: ${SERVE_MODES.join(", ")}`)
312
+ .option("--network <network>", `Testnet to pose on: ${Object.keys(SERVE_NETWORKS).join(" or ")}`, DEFAULT_SERVE_NETWORK)
313
+ .option("--port <port>", "Port to listen on", "4020")
314
+ .option("--host <host>", "Interface to bind (local only by default)", "127.0.0.1")
315
+ .option("--pay-to <address>", "Payee: a Stellar account (G...) with a USDC trustline, an EVM address (0x...) " +
316
+ "on Base or Ethereum Sepolia, or a Solana address on devnet (overrides " +
317
+ "STELLAR_PAYEE_ADDRESS, EVM_PAYEE_ADDRESS or SVM_PAYEE_ADDRESS)")
318
+ .option("--amount <units>", "Price in base units for every mode except overprice", "10000")
319
+ .option("--asset <contract>", "Token contract (default: the network's testnet USDC)")
320
+ .option("--settlement-tx <hash>", "wrong-settlement: transaction to cite (default: a random hash that exists nowhere)")
321
+ .addHelpText("after", `
322
+ Modes:
323
+ ${SERVE_MODES.map((mode) => ` ${mode.padEnd(17)} ${MODE_DESCRIPTIONS[mode].does}`).join("\n")}
324
+
325
+ Point your agent at http://127.0.0.1:4020/ (any path) and watch what it does.
326
+ The server never settles and never forwards a payment, so nothing it receives
327
+ moves funds. On Stellar your agent still needs a funded testnet wallet:
328
+ payment clients simulate the transfer to --pay-to before signing.
329
+
330
+ Examples:
331
+ $ wasit serve --mode no-settle
332
+ $ wasit serve --mode wrong-settlement --settlement-tx <hash of an unrelated tx>
333
+ $ wasit serve --mode overprice --port 4021
334
+ $ wasit serve --mode no-settle --network eip155:84532 # Base Sepolia
335
+ $ wasit serve --mode no-settle --network solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 # Solana devnet`)
336
+ .action((opts) => {
337
+ const network = opts.network;
338
+ const payeeEnv = SERVE_NETWORKS[network]?.payeeEnv ?? "STELLAR_PAYEE_ADDRESS";
339
+ const options = {
340
+ mode: opts.mode,
341
+ network,
342
+ payTo: opts.payTo ?? process.env[payeeEnv] ?? "",
343
+ amount: opts.amount,
344
+ ...(opts.asset ? { asset: opts.asset } : {}),
345
+ ...(opts.settlementTx ? { settlementTx: opts.settlementTx } : {}),
346
+ log: (line) => console.log(`${new Date().toISOString().slice(11, 19)} ${line}`),
347
+ };
348
+ const problem = validateServeOptions(options);
349
+ if (problem !== undefined) {
350
+ console.error(problem);
351
+ process.exit(2);
352
+ }
353
+ const port = Number(opts.port);
354
+ const server = createServeServer(options);
355
+ server.on("error", (error) => {
356
+ console.error(`Could not listen on ${opts.host}:${opts.port}: ${error.message}`);
357
+ process.exit(2);
358
+ });
359
+ server.listen(port, opts.host, () => {
360
+ const description = MODE_DESCRIPTIONS[options.mode];
361
+ console.log(`wasit serve: ${options.mode} on ${network}, http://${opts.host}:${port}/ (any path)`);
362
+ console.log(` This paywall ${description.does}`);
363
+ console.log(` An agent that pays carefully ${description.careful}`);
364
+ console.log(" Nothing is settled or forwarded; no funds move. Ctrl+C to stop.\n");
365
+ });
366
+ process.on("SIGINT", () => server.close(() => process.exit(0)));
191
367
  });
192
368
  program
193
369
  .command("mpp-channel")
194
370
  .description("Run MPP channel-mode compliance checks against a target service")
195
371
  .requiredOption("--target <url>", "URL of the paid resource to test")
196
372
  .option("--commitment-key <hex>", "Raw ed25519 commitment seed, hex (default: COMMITMENT_SECRET_HEX)")
197
- .option("--network <network>", "CAIP-2 network id (default: MPP_STELLAR_NETWORK)")
373
+ .option("--network <network>", "CAIP-2 network id, stellar:testnet only; any other network is refused before " +
374
+ "anything is sent (default: MPP_STELLAR_NETWORK, else stellar:testnet)")
198
375
  .option("--rpc-url <url>", "Override the default Soroban RPC endpoint")
199
376
  .option("--channel <address>", "Assert which channel the target bills through. Defaults to the channel " +
200
377
  "the target advertises; a mismatch fails MPP-10. (env: CHANNEL_CONTRACT)")
@@ -241,14 +418,91 @@ that channel.`)
241
418
  ...(Number.isInteger(refundWaitingPeriod) ? { refundWaitingPeriod } : {}),
242
419
  },
243
420
  });
244
- process.exit(report(results, jsonMode));
421
+ process.exit(report(results, jsonMode, terminalStyle(jsonMode)));
245
422
  });
423
+ /** Colours for the MPP commands' text output, when a person is at the terminal. */
424
+ function terminalStyle(jsonMode) {
425
+ return {
426
+ style: styler(!jsonMode && colorEnabled(process.stdout, process.env), colorDepth(process.env)),
427
+ width: lineWidth(process.stdout),
428
+ };
429
+ }
430
+ /**
431
+ * `wasit test` for a person at a terminal: the same checks, notes and exit code
432
+ * as the plain output, drawn live (a RUNNING line with a timer while a check is
433
+ * in flight, each result as it arrives, the counts and the duration at the end).
434
+ */
435
+ async function liveX402Test(opts, shape) {
436
+ const secrets = deniedEnvValues(process.env);
437
+ const live = new LiveReport({
438
+ stream: process.stdout,
439
+ live: liveEnabled(process.stdout, process.env),
440
+ depth: colorDepth(process.env),
441
+ clean: (text) => sanitizeText(text, { redact: secrets }),
442
+ });
443
+ const target = opts["target"];
444
+ const network = opts["network"];
445
+ live.header(CLI_VERSION, "x402 conformance", [
446
+ ["target", `${target}${shape.method !== undefined ? ` ${shape.method.toUpperCase()}` : ""}`],
447
+ ["network", network],
448
+ ]);
449
+ live.phase("challenge", [["no payment"]]);
450
+ live.running("X402-01..05", "Challenge checks");
451
+ const results = await runX402ReadChecks({ target, ...shape, onResult: (result) => live.result(result) });
452
+ live.gap();
453
+ const keyEnv = paymentChainFor(network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY";
454
+ const payerKey = opts["payerKey"] ?? process.env[keyEnv];
455
+ if (opts["readOnly"] === true) {
456
+ live.phase("payment", [["not run"]]);
457
+ live.note("--read-only set: the payment checks were not run.");
458
+ }
459
+ else if (!payerKey) {
460
+ live.phase("payment", [["not run"]]);
461
+ live.note(`No payer key: set ${keyEnv} in .env or pass --payer-key. The payment checks were not run.`);
462
+ }
463
+ else if (networkClass(network) !== "test") {
464
+ // Not a test network: the guard refuses the payment checks before anything
465
+ // is signed (the PREFLIGHT line says why), so no money moves.
466
+ live.phase("payment", [[network], ["not a test network: refused", "danger"]]);
467
+ }
468
+ else {
469
+ live.phase("payment", [[network], ["testnet funds move", "warning"]]);
470
+ live.note(`When the target offers a ${network} option, X402-06 settles a real payment and X402-07..10 send ` +
471
+ "payments it must refuse.");
472
+ }
473
+ if (opts["readOnly"] !== true && payerKey) {
474
+ const order = X402_PAYMENT_CHECK_IDS;
475
+ const startAt = (index) => {
476
+ const id = order[index];
477
+ if (id !== undefined)
478
+ live.running(id, catalogueEntry(id)?.name ?? id);
479
+ };
480
+ startAt(0);
481
+ results.push(...(await runX402PaymentChecks({
482
+ target,
483
+ network,
484
+ payerSecretKey: payerKey,
485
+ ...(opts["rpcUrl"] ? { rpcUrl: opts["rpcUrl"] } : {}),
486
+ ...shape,
487
+ onResult: (result) => {
488
+ live.result(result);
489
+ const index = order.indexOf(result.id);
490
+ if (index >= 0)
491
+ startAt(index + 1);
492
+ },
493
+ onProgress: (line) => live.progress(line),
494
+ })));
495
+ }
496
+ live.finish(results, endpointOutcome(results, "x402"), verdictNotes(results, "x402"));
497
+ return exitCodeFor(results, "x402");
498
+ }
246
499
  program
247
500
  .command("mpp-charge")
248
501
  .description("Run the MPP charge-mode check (MPP-01) against a target service")
249
502
  .requiredOption("--target <url>", "URL of the paid resource to test")
250
503
  .option("--payer-key <key>", "Payer secret key, S... (default: MPP_PAYER_SECRET)")
251
- .option("--network <network>", "CAIP-2 network id (default: MPP_STELLAR_NETWORK)")
504
+ .option("--network <network>", "CAIP-2 network id, stellar:testnet only; any other network is refused before " +
505
+ "anything is sent (default: MPP_STELLAR_NETWORK, else stellar:testnet)")
252
506
  .option("--rpc-url <url>", "Override the default Soroban RPC endpoint")
253
507
  .option("--json", "Print results as JSON instead of formatted text", false)
254
508
  .addHelpText("after", `
@@ -272,11 +526,12 @@ a real payment and moves testnet funds, because charge mode has no dry run.`)
272
526
  payerSecretKey,
273
527
  ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}),
274
528
  });
275
- process.exit(report(results, jsonMode));
529
+ process.exit(report(results, jsonMode, terminalStyle(jsonMode)));
276
530
  });
277
531
  registerWalletCommand(program);
278
532
  const isBareInteractiveInvocation = process.argv.length <= 2 && process.stdout.isTTY === true;
279
533
  if (isBareInteractiveInvocation) {
534
+ loadDotenv();
280
535
  render(createElement(App));
281
536
  }
282
537
  else {
package/dist/live.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The coloured, live text output of a check run (Najmi, 2026-11-19), in
3
+ * Wasit's own look: a header, the checks in two blocks (challenge, payment),
4
+ * one line per check with its mark (✓ pass, ✗ fail, ○ skip, ! error) and its
5
+ * duration flush right, a spinner line saying what the check in flight is doing,
6
+ * and the verdict, the counts and the run's duration at the end.
7
+ *
8
+ * It only arranges what the plain output says: the same checks, details, fixes
9
+ * and notes, in the same order. It is used only when colour is on
10
+ * (`colorEnabled`); `live` adds the spinner line, rewritten in place, on a real
11
+ * terminal. That line is cut to the terminal's width so it never wraps: a
12
+ * wrapped line cannot be rewritten in place. Every text passes through `clean`
13
+ * (the sanitiser, with the secrets redacted) before it is styled.
14
+ */
15
+ import { type CheckResult, type EndpointOutcome } from "@wasit-dev/core";
16
+ import { type ColorDepth, type Role, type Styler, type StyleStream } from "./style.js";
17
+ export interface LiveStream extends StyleStream {
18
+ write(chunk: string): unknown;
19
+ }
20
+ export interface LiveOptions {
21
+ readonly stream: LiveStream;
22
+ /** Rewrite the spinner line in place. Off: lines are only appended. */
23
+ readonly live: boolean;
24
+ /** The sanitiser, with the run's secrets redacted. */
25
+ readonly clean: (text: string) => string;
26
+ /** The terminal's colour depth (`colorDepth`): 24-bit gives the exact brand colours. Default 16. */
27
+ readonly depth?: ColorDepth;
28
+ /** Shorthand for `depth: 24`. */
29
+ readonly truecolor?: boolean;
30
+ readonly now?: () => number;
31
+ /** How often the spinner line is redrawn. */
32
+ readonly tickMs?: number;
33
+ }
34
+ /**
35
+ * The lines of one check: its line (mark, ID, name, duration, badge), then its
36
+ * detail, its fix and its docs. `withDetail` false leaves the detail out: a
37
+ * skip whose reason the skip just above it already gave.
38
+ */
39
+ export declare function resultLines(result: CheckResult, style: Styler, width: number, clean: (text: string) => string, ms?: number, withDetail?: boolean): string[];
40
+ /** "10 passed", "1 failed", "1 could not run", "1 skipped": each count in its colour. */
41
+ export declare function countsParts(results: readonly CheckResult[], style: Styler): string[];
42
+ /** "10 passed · 1 failed · 1 could not run · 1 skipped". */
43
+ export declare function countsLine(results: readonly CheckResult[], style: Styler): string;
44
+ export declare class LiveReport {
45
+ #private;
46
+ constructor(options: LiveOptions);
47
+ /** ` ◆ wasit <version> · x402 conformance`, then `label value` rows. */
48
+ header(version: string, subject: string, rows?: ReadonlyArray<readonly [string, string]>): void;
49
+ /** A block heading: ` payment · stellar:testnet · testnet funds move`. */
50
+ phase(name: string, parts?: ReadonlyArray<readonly [string, Role?]>): void;
51
+ /** A note under a block: why checks were left out, or that money moves. */
52
+ note(text: string): void;
53
+ /** A check (or a group of checks) starts: its spinner line, on a real terminal. */
54
+ running(id: string, name: string): void;
55
+ /** A progress line from the check in flight, dimmed, above its spinner line. */
56
+ progress(text: string): void;
57
+ /**
58
+ * A check's result replaces its spinner line and carries the time since it
59
+ * started. Results computed together with an earlier one (the challenge
60
+ * checks, or the checks skipped after a failed payment) carry none, and a
61
+ * skipped check never does.
62
+ */
63
+ result(result: CheckResult): void;
64
+ /** A blank line between blocks. */
65
+ gap(): void;
66
+ /** The verdict, the counts, the run's duration, and the plain output's closing notes. */
67
+ finish(results: readonly CheckResult[], outcome: EndpointOutcome | undefined, notes: readonly string[]): void;
68
+ }