@wasit-dev/cli 0.7.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/README.md CHANGED
@@ -6,7 +6,9 @@ Protocol-compliance testing for **x402** and **MPP** on Stellar, from your termi
6
6
 
7
7
  For both MPP charge payments and x402 payments it verifies the settlement independently — via Stellar RPC and the token contract's own on-chain transfer event, rather than the response the service returns.
8
8
 
9
- **Testnet only.** Several checks settle real transactions — do not point this at pubnet or use production keys.
9
+ **Testnet only.** Several checks settle real transactions. The payment checks pay on test networks only: any other network, `stellar:pubnet` included, is refused before a key is read. Do not use production keys.
10
+
11
+ **This README describes 0.8.0-beta.1**, a pre-release on npm under the `beta` tag (`npm install -g @wasit-dev/cli@beta`). `latest` is still 0.7.0. New in the beta: `wasit run` for a whole service from a `wasit.config.json`, `wasit ci-report`, the GitHub Action, a seventeenth check (`X402-11`), and a cap on every payment Wasit signs.
10
12
 
11
13
  ## Install
12
14
 
@@ -48,7 +50,7 @@ wasit test --target <url> [options]
48
50
  | Option | Default | Notes |
49
51
  |---|---|---|
50
52
  | `--target <url>` | required | Must include the scheme |
51
- | `--network <id>` | `stellar:testnet` | Network the payment checks pay on (`stellar:testnet`, `stellar:pubnet`, `eip155:84532` for Base Sepolia, `eip155:11155111` for Ethereum Sepolia, or `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` for Solana devnet); `X402-01`–`05` apply on any chain |
53
+ | `--network <id>` | `stellar:testnet` | Network the payment checks pay on: `stellar:testnet`, `eip155:84532` (Base Sepolia), `eip155:11155111` (Ethereum Sepolia) or `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1` (Solana devnet). Any other network is refused before a key is read. `X402-01`–`05` apply on any chain |
52
54
  | `--payer-key <key>` | `STELLAR_PRIVATE_KEY`, `EVM_PRIVATE_KEY` on Base or Ethereum Sepolia, or `SVM_PRIVATE_KEY` on Solana devnet | A Stellar secret (`S...`), an EVM private key (`0x` + 64 hex), or a Solana keypair (base58 of its 64 bytes) |
53
55
  | `--rpc-url <url>` | testnet default | Soroban RPC used to verify `X402-06`'s settlement |
54
56
  | `--method <verb>` | `GET` | HTTP method the paid endpoint uses |
@@ -56,7 +58,7 @@ wasit test --target <url> [options]
56
58
  | `--header <name:value>` | — | Extra request header, repeatable |
57
59
  | `--read-only` | off | Restricts the run to `X402-01`–`05` (no payment) |
58
60
 
59
- Without a payer key, the payment checks are skipped automatically. When they run: **`X402-06` settles a real payment, `X402-07` attempts one with a corrupted signature** — testnet funds move on every call.
61
+ Without a payer key, the payment checks are skipped automatically. When they run: **`X402-06` settles a real payment, `X402-07` attempts one with a corrupted signature**, so testnet funds move on every call. A price above $1.00 is not paid: `X402-06` gets no verdict (`ERROR (setup)`) and nothing is signed. `X402-11` needs a request the service must refuse, which only `wasit run` reads from the config, so `wasit test` skips it.
60
62
 
61
63
  ### `wasit mpp-charge` — MPP, charge mode
62
64
 
@@ -68,8 +70,8 @@ wasit mpp-charge --target <url> [options]
68
70
  |---|---|---|
69
71
  | `--target <url>` | required | The paid resource |
70
72
  | `--payer-key <key>` | `MPP_PAYER_SECRET` | Secret key, `S...` |
71
- | `--network <id>` | `MPP_STELLAR_NETWORK` | CAIP-2. Only a challenge on this network is paid |
72
- | `--rpc-url <url>` | testnet default | Used for the payment and the settlement read; https only. Required for pubnet |
73
+ | `--network <id>` | `MPP_STELLAR_NETWORK` | CAIP-2. Only a challenge on this network is paid; `stellar:testnet` only, any other network is refused |
74
+ | `--rpc-url <url>` | testnet default | Used for the payment and the settlement read; https only |
73
75
 
74
76
  **Every run settles a real payment.** Charge mode has no dry run — a settlement that never happened cannot be verified on-chain.
75
77
 
@@ -97,6 +99,28 @@ wasit mpp-channel --target <url> [options]
97
99
 
98
100
  `--channel` **asserts**, it does not select: the channel under test is resolved from the target's own 402 challenge, so every check in a run reports on the same contract. When `--channel` differs from what the target advertises, `MPP-10` fails and inspects nothing.
99
101
 
102
+ ### `wasit run`: a whole service from `wasit.config.json` (new in 0.8.0-beta.1)
103
+
104
+ ```bash
105
+ wasit run --read-only --start # the free checks, X402-01 to 05, with the service started from the config
106
+ wasit run --dry-run --start # what the payment checks would sign; no key, nothing sent
107
+ wasit run --start # the payment tier, on a test network
108
+ ```
109
+
110
+ `wasit.config.json` (version 1) holds a service's endpoints, methods, request bodies and environments. The loader is strict: an unknown key is an error, and secrets, the mainnet opt-in and per-payment caps have no place in it. `wasit run` runs every endpoint (`--env`, `--endpoint`) and writes one report (`--json`, `--out`); it can start the service itself (`--start`, `--start-if-local`) and compare with the report of the default branch (`--baseline`).
111
+
112
+ Without `--read-only` or `--dry-run` the run is the payment tier. It pays on test networks only, when the environment has `operatedByMe: true` and the chain's key variable is set: at most $1.00 a payment and $5.00 a run (`maxRunUsd` can only lower it), only to the `payTo` and asset the config pins. In GitHub Actions it pays only on a push to the default branch, a schedule and `workflow_dispatch`; a pull request runs the read-only checks. In another CI the payment tier is refused with exit 2: use `--read-only` there. `--mainnet` is refused in this version. `wasit run --help` lists every option.
113
+
114
+ For an endpoint with a `reject` case in the config, on Stellar, the payment tier also runs `X402-11`: a valid payment is sent with the request the service must refuse, and the chain is read until that payment's authorization has expired, up to six minutes.
115
+
116
+ ### `wasit ci-report`: the pull request comment and the job summary (new in 0.8.0-beta.1)
117
+
118
+ ```bash
119
+ wasit ci-report --report wasit-report.json --comment comment.md
120
+ ```
121
+
122
+ Turns the report of `wasit run --json --out` into the pull request comment and the job summary, compared with the default branch's report (`--baseline`). `--check-run <file>` also writes the title, summary and conclusion of a GitHub check run. The GitHub Action in the repository's `action/` directory runs `wasit run` and `wasit ci-report` in a workflow and comments on the pull request; pin it by full commit SHA.
123
+
100
124
  ### `wasit checks` — the catalogue
101
125
 
102
126
  ```bash
@@ -154,6 +178,8 @@ SKIP X402-02 Payment Header Present
154
178
  7 passed.
155
179
  ```
156
180
 
181
+ At a terminal, `wasit test` shows the checks live and in colour, in two blocks (challenge and payment). A pipe, CI, `--json` and `NO_COLOR` get the plain text above.
182
+
157
183
  `PREFLIGHT` appears in place of the checks when the target URL or network identifier itself is invalid — both are wrong for every check in the suite, so it's reported once rather than repeated identically.
158
184
 
159
185
  ## Exit codes
@@ -184,7 +210,7 @@ All keys are **testnet only**. `wasit` also reads a `.env` file in the current w
184
210
 
185
211
  ## What's checked
186
212
 
187
- Thirteen checks across x402 and MPP, each traced to a written spec clause — the full catalogue, with pass criteria and spec references, is in [`docs/CHECKS.md`](https://github.com/wasit-dev/wasit/blob/main/docs/CHECKS.md).
213
+ Seventeen checks across x402 and MPP (`X402-11` is new in 0.8.0-beta.1), each traced to a written spec clause — the full catalogue, with pass criteria and spec references, is in [`docs/CHECKS.md`](https://github.com/wasit-dev/wasit/blob/main/docs/CHECKS.md).
188
214
 
189
215
  ## Related
190
216
 
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `wasit ci-report`: the run report (and the baseline of the default branch, if
3
+ * there is one) in; `comment.md`, the job summary and, when asked, the next
4
+ * baseline out (spec A4, A5).
5
+ *
6
+ * It is a pure function over files. It decides nothing about the job: the job's
7
+ * result is the exit code of `wasit run`. When the run left no usable report (the
8
+ * service never started, never answered, or the config was unusable) it still
9
+ * writes a fixed "no verdict" comment and summary, so the comment of the push
10
+ * before does not stay next to a red check, and it writes no baseline. It exits 2
11
+ * when the report is there but unusable, or when it cannot write what it was asked.
12
+ */
13
+ export interface CiReportOptions {
14
+ /** The `wasit run --json --out` file. */
15
+ readonly report: string;
16
+ /** The baseline file of the default branch: absent or unusable, the comment says so. */
17
+ readonly baseline?: string;
18
+ /** Where the pull request comment goes. */
19
+ readonly comment: string;
20
+ /** The job summary file, appended to. Default: `$GITHUB_STEP_SUMMARY`, if set. */
21
+ readonly summary?: string;
22
+ /** Where the next baseline goes: the report with its history. The caller uploads it on a run on the default branch. */
23
+ readonly baselineOut?: string;
24
+ /**
25
+ * The baseline file of the newest completed run on the default branch, failed
26
+ * or not (D-022b): its history is the one the recent-failures line counts and
27
+ * the next baseline carries on. Absent or unusable: the baseline's own.
28
+ */
29
+ readonly history?: string;
30
+ /** The id of the run the baseline came from, named in the comment. Only a whole number above 0 is used. */
31
+ readonly baselineRun?: string;
32
+ /** Where the check run's title, summary and conclusion go, as JSON, for the step that completes it. */
33
+ readonly checkRun?: string;
34
+ }
35
+ export interface CiReportContext {
36
+ readonly env: Readonly<Record<string, string | undefined>>;
37
+ readonly stdout: (line: string) => void;
38
+ readonly stderr: (line: string) => void;
39
+ }
40
+ export declare function executeCiReport(options: CiReportOptions, context: CiReportContext): Promise<number>;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * `wasit ci-report`: the run report (and the baseline of the default branch, if
3
+ * there is one) in; `comment.md`, the job summary and, when asked, the next
4
+ * baseline out (spec A4, A5).
5
+ *
6
+ * It is a pure function over files. It decides nothing about the job: the job's
7
+ * result is the exit code of `wasit run`. When the run left no usable report (the
8
+ * service never started, never answered, or the config was unusable) it still
9
+ * writes a fixed "no verdict" comment and summary, so the comment of the push
10
+ * before does not stay next to a red check, and it writes no baseline. It exits 2
11
+ * when the report is there but unusable, or when it cannot write what it was asked.
12
+ */
13
+ import { appendFileSync, readFileSync, statSync, writeFileSync } from "node:fs";
14
+ import { MAX_BASELINE_BYTES, ReportFormatError, baselineProblem, deniedEnvValues, parseRunReport, readBaseline, readBuildCommit, readToolVersions, renderCheckRun, renderComment, renderNoReportCheckRun, renderNoReportComment, renderNoReportSummary, renderSummary, sanitizeText, selectBaseline, serializeBaseline, updateHistory, } from "@wasit-dev/core";
15
+ import { CLI_VERSION } from "./version.js";
16
+ function readFileText(path, max) {
17
+ if (statSync(path).size > max)
18
+ throw Object.assign(new Error("too large"), { code: "E2BIG" });
19
+ return readFileSync(path, "utf-8");
20
+ }
21
+ function readBaselineFile(path) {
22
+ try {
23
+ return readBaseline(readFileText(path, MAX_BASELINE_BYTES));
24
+ }
25
+ catch (error) {
26
+ const code = error.code;
27
+ return { ok: false, reason: `the baseline file cannot be read${typeof code === "string" ? ` (${code})` : ""}` };
28
+ }
29
+ }
30
+ export async function executeCiReport(options, context) {
31
+ const secrets = deniedEnvValues(context.env);
32
+ const fail = (message) => {
33
+ context.stderr(sanitizeText(message, { redact: secrets }));
34
+ return 2;
35
+ };
36
+ /** The run left nothing to render: say so in the comment and the summary, and write no baseline. */
37
+ const writeNoReport = (message, code) => {
38
+ context.stderr(sanitizeText(message, { redact: secrets }));
39
+ try {
40
+ const versions = readToolVersions(CLI_VERSION, readBuildCommit(context.env));
41
+ writeFileSync(options.comment, renderNoReportComment(versions));
42
+ context.stdout(`Wrote ${options.comment}`);
43
+ const summary = options.summary ?? context.env["GITHUB_STEP_SUMMARY"];
44
+ if (summary !== undefined && summary !== "") {
45
+ appendFileSync(summary, renderNoReportSummary(versions));
46
+ context.stdout(`Appended the summary to ${summary}`);
47
+ }
48
+ if (options.checkRun !== undefined) {
49
+ writeFileSync(options.checkRun, JSON.stringify(renderNoReportCheckRun(versions)));
50
+ context.stdout(`Wrote ${options.checkRun}`);
51
+ }
52
+ }
53
+ catch (error) {
54
+ const errno = error.code;
55
+ return fail(`wasit ci-report: cannot write a file${typeof errno === "string" ? ` (${errno})` : ""}`);
56
+ }
57
+ return code;
58
+ };
59
+ let report;
60
+ try {
61
+ report = parseRunReport(JSON.parse(readFileText(options.report, MAX_BASELINE_BYTES)));
62
+ }
63
+ catch (error) {
64
+ // Nothing from the file is quoted: it is data, and it may be broken or hostile.
65
+ if (error instanceof ReportFormatError)
66
+ return writeNoReport("wasit ci-report: the report is not a Wasit report", 2);
67
+ if (error instanceof SyntaxError)
68
+ return writeNoReport("wasit ci-report: the report is not valid JSON", 2);
69
+ const code = error.code;
70
+ if (code === "ENOENT") {
71
+ return writeNoReport("wasit ci-report: wasit run wrote no report, so the comment says no verdict (the reason is in the log of the run step)", 0);
72
+ }
73
+ return writeNoReport(`wasit ci-report: cannot read the report${typeof code === "string" ? ` (${code})` : ""}`, 2);
74
+ }
75
+ const selected = selectBaseline(report, options.baseline === undefined ? undefined : readBaselineFile(options.baseline));
76
+ // D-022b: the history of every completed run on main, when the newest one is given.
77
+ let history = selected.baseline?.history;
78
+ let historyGiven = false;
79
+ if (options.history !== undefined) {
80
+ const read = readBaselineFile(options.history);
81
+ const problem = read.ok ? baselineProblem(report, read.baseline.report) : read.reason;
82
+ if (read.ok && problem === undefined) {
83
+ history = read.baseline.history;
84
+ historyGiven = true;
85
+ }
86
+ else {
87
+ context.stderr(sanitizeText(`wasit ci-report: the history file is not used (${problem ?? "unknown"}); the history of the baseline is used`, {
88
+ redact: secrets,
89
+ }));
90
+ }
91
+ }
92
+ const run = options.baselineRun !== undefined && /^[1-9][0-9]{0,15}$/.test(options.baselineRun) ? Number(options.baselineRun) : undefined;
93
+ const input = {
94
+ report,
95
+ ...(selected.baseline === undefined ? {} : { baseline: selected.baseline }),
96
+ ...(selected.note === undefined ? {} : { baselineNote: selected.note }),
97
+ ...(run === undefined || !Number.isSafeInteger(run) ? {} : { baselineRun: run }),
98
+ ...(historyGiven && history !== undefined ? { history } : {}),
99
+ secrets,
100
+ };
101
+ try {
102
+ writeFileSync(options.comment, renderComment(input));
103
+ context.stdout(`Wrote ${options.comment}`);
104
+ const summary = options.summary ?? context.env["GITHUB_STEP_SUMMARY"];
105
+ if (summary !== undefined && summary !== "") {
106
+ appendFileSync(summary, `${renderSummary(input)}\n`);
107
+ context.stdout(`Appended the summary to ${summary}`);
108
+ }
109
+ if (options.baselineOut !== undefined) {
110
+ writeFileSync(options.baselineOut, serializeBaseline(report, updateHistory(history, report)));
111
+ context.stdout(`Wrote ${options.baselineOut}`);
112
+ }
113
+ if (options.checkRun !== undefined) {
114
+ writeFileSync(options.checkRun, JSON.stringify(renderCheckRun(input)));
115
+ context.stdout(`Wrote ${options.checkRun}`);
116
+ }
117
+ }
118
+ catch (error) {
119
+ const code = error.code;
120
+ return fail(`wasit ci-report: cannot write a file${typeof code === "string" ? ` (${code})` : ""}`);
121
+ }
122
+ return 0;
123
+ }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import "dotenv/config";
2
+ export {};
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
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";
@@ -7,7 +7,26 @@ import { App } from "./dashboard/App.js";
7
7
  import { CLI_VERSION } from "./version.js";
8
8
  import { registerWalletCommand } from "./wallet-command.js";
9
9
  import { DEFAULT_SERVE_NETWORK, MODE_DESCRIPTIONS, SERVE_MODES, SERVE_NETWORKS, createServeServer, validateServeOptions, } from "./serve.js";
10
- import { CHECK_CATALOGUE, PROTOCOL_IDS, checkStatus, fixFor, paymentChainFor, runMppChannelSuite, runMppChargeSuite, runX402PaymentChecks, runX402ReadChecks, summarize, toStructuredRun, } from "@wasit-dev/core";
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
+ }
11
30
  /** Which wasit subcommand runs each protocol's checks — for `wasit checks` output. */
12
31
  const COMMAND_BY_PROTOCOL = {
13
32
  x402: "test",
@@ -49,62 +68,26 @@ Run "wasit <command> --help" for that command's own options and cost notes.
49
68
  Add --json to test/mpp-charge/mpp-channel for machine-readable output.
50
69
  Full check catalogue (every check ID, spec reference, pass criteria):
51
70
  https://github.com/wasit-dev/wasit/blob/main/docs/CHECKS.md`);
52
- /**
53
- * Prints an advisory/status line meant for a human watching the terminal —
54
- * never part of the run's actual result. Routed to stderr when --json is
55
- * set, so stdout stays parseable JSON and a script piping it (jq, etc.)
56
- * never has to skip past prose first.
57
- */
58
- function note(json, message) {
59
- if (json) {
60
- console.error(message);
61
- }
62
- else {
63
- console.log(message);
64
- }
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()))));
65
87
  }
66
- /**
67
- * Prints results and returns the process exit code.
68
- *
69
- * A skipped check carries `pass: false` so it can never be counted as
70
- * conformance, but it is not a failure and must not fail the run. An errored
71
- * check produced no verdict at all and is reported separately again.
72
- *
73
- * `--json` reuses `toStructuredRun()` from core — the same reshape the MCP
74
- * server calls for its own structured output — rather than defining a
75
- * second JSON shape here that could drift from it.
76
- */
77
- function report(results, json) {
78
- const counts = summarize(results);
79
- if (json) {
80
- console.log(JSON.stringify(toStructuredRun(results), null, 2));
81
- return counts.exitCode;
82
- }
83
- for (const result of results) {
84
- const flag = result.destructive ? " [destructive]" : "";
85
- console.log(`${checkStatus(result)} ${result.id} ${result.name}${flag}`);
86
- console.log(` ${result.detail}`);
87
- const guidance = fixFor(result);
88
- if (guidance !== undefined) {
89
- console.log(` Fix: ${guidance.fix}`);
90
- if (guidance.docs !== undefined)
91
- console.log(` Docs: ${guidance.docs}`);
92
- }
93
- console.log("");
94
- }
95
- const line = [`${counts.passed} passed`];
96
- if (counts.failed > 0)
97
- line.push(`${counts.failed} failed`);
98
- if (counts.errored > 0)
99
- line.push(`${counts.errored} could not run`);
100
- if (counts.skipped > 0)
101
- line.push(`${counts.skipped} skipped`);
102
- console.log(`${line.join(", ")}.`);
103
- if (counts.errored > 0 && counts.failed === 0) {
104
- console.log("\nNo verdict: some checks never reached the target or the run is " +
105
- "misconfigured. This is not a statement about the target's conformance.");
106
- }
107
- 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);
108
91
  }
109
92
  program
110
93
  .command("checks")
@@ -152,10 +135,11 @@ program
152
135
  .command("test")
153
136
  .description("Run x402 compliance checks against a target service")
154
137
  .requiredOption("--target <url>", "URL of the service to test")
155
- .option("--network <network>", "Network the payment checks pay on: stellar:testnet, stellar:pubnet, " +
138
+ .option("--network <network>", "Network the payment checks pay on: stellar:testnet, " +
156
139
  "eip155:84532 (Base Sepolia), eip155:11155111 (Ethereum Sepolia) or " +
157
- "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 (Solana devnet). X402-01..05 " +
158
- "apply to a challenge on any chain.", "stellar:testnet")
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")
159
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)")
160
144
  .option("--payer-key <key>", "Testnet payer key (overrides STELLAR_PRIVATE_KEY, EVM_PRIVATE_KEY on eip155 networks, " +
161
145
  "or SVM_PRIVATE_KEY on Solana, from .env)")
@@ -163,7 +147,7 @@ program
163
147
  "compute something usually take POST.")
164
148
  .option("--body <json>", "Request body, sent verbatim. Implies Content-Type: application/json.")
165
149
  .option("--header <name:value>", "Extra request header the endpoint needs before it will issue a challenge. Repeatable.", collectHeader)
166
- .option("--read-only", "Skip the payment checks (X402-06..10)", false)
150
+ .option("--read-only", "Skip the payment checks (X402-06..11)", false)
167
151
  .option("--json", "Print results as JSON instead of formatted text", false)
168
152
  .addHelpText("after", `
169
153
  Examples:
@@ -175,7 +159,13 @@ X402-01..05 (challenge/header checks) always run and cost nothing. X402-06..10
175
159
  (real payment checks) run only when a payer key is available and --read-only
176
160
  is not set: X402-06 settles a payment; X402-07..10 send payments the target
177
161
  must refuse (a corrupted signature, a replay, an underpayment, an expired
178
- authorization). See docs/CHECKS.md for what each check ID verifies.`)
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.`)
179
169
  .action(async (opts) => {
180
170
  const jsonMode = opts.json === true;
181
171
  const shape = {
@@ -183,6 +173,11 @@ authorization). See docs/CHECKS.md for what each check ID verifies.`)
183
173
  ...(opts.body !== undefined ? { body: opts.body } : {}),
184
174
  ...(opts.header ? { headers: opts.header } : {}),
185
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
+ }
186
181
  const results = await runX402ReadChecks({ target: opts.target, ...shape });
187
182
  // Each chain reads its own payer key: a Stellar secret is no use on EVM.
188
183
  const keyEnv = paymentChainFor(opts.network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY";
@@ -204,7 +199,111 @@ authorization). See docs/CHECKS.md for what each check ID verifies.`)
204
199
  ...shape,
205
200
  })));
206
201
  }
207
- 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);
208
307
  });
209
308
  program
210
309
  .command("serve")
@@ -271,7 +370,8 @@ program
271
370
  .description("Run MPP channel-mode compliance checks against a target service")
272
371
  .requiredOption("--target <url>", "URL of the paid resource to test")
273
372
  .option("--commitment-key <hex>", "Raw ed25519 commitment seed, hex (default: COMMITMENT_SECRET_HEX)")
274
- .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)")
275
375
  .option("--rpc-url <url>", "Override the default Soroban RPC endpoint")
276
376
  .option("--channel <address>", "Assert which channel the target bills through. Defaults to the channel " +
277
377
  "the target advertises; a mismatch fails MPP-10. (env: CHANNEL_CONTRACT)")
@@ -318,14 +418,91 @@ that channel.`)
318
418
  ...(Number.isInteger(refundWaitingPeriod) ? { refundWaitingPeriod } : {}),
319
419
  },
320
420
  });
321
- process.exit(report(results, jsonMode));
421
+ process.exit(report(results, jsonMode, terminalStyle(jsonMode)));
322
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
+ }
323
499
  program
324
500
  .command("mpp-charge")
325
501
  .description("Run the MPP charge-mode check (MPP-01) against a target service")
326
502
  .requiredOption("--target <url>", "URL of the paid resource to test")
327
503
  .option("--payer-key <key>", "Payer secret key, S... (default: MPP_PAYER_SECRET)")
328
- .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)")
329
506
  .option("--rpc-url <url>", "Override the default Soroban RPC endpoint")
330
507
  .option("--json", "Print results as JSON instead of formatted text", false)
331
508
  .addHelpText("after", `
@@ -349,11 +526,12 @@ a real payment and moves testnet funds, because charge mode has no dry run.`)
349
526
  payerSecretKey,
350
527
  ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}),
351
528
  });
352
- process.exit(report(results, jsonMode));
529
+ process.exit(report(results, jsonMode, terminalStyle(jsonMode)));
353
530
  });
354
531
  registerWalletCommand(program);
355
532
  const isBareInteractiveInvocation = process.argv.length <= 2 && process.stdout.isTTY === true;
356
533
  if (isBareInteractiveInvocation) {
534
+ loadDotenv();
357
535
  render(createElement(App));
358
536
  }
359
537
  else {