@wasit-dev/cli 0.7.0 → 0.8.0-beta.2

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,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,28 @@ 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 { note, report } from "./output.js";
12
+ import { liveX402Test } from "./test-live.js";
13
+ import { colorDepth, colorEnabled, lineWidth, styler } from "./style.js";
14
+ import { executeRun } from "./run.js";
15
+ import { DEFAULT_CONFIG_FILE, executeInit } from "./init-command.js";
16
+ import { LIVE_KEY_SETUP } from "./init-keys.js";
17
+ import { CHECK_CATALOGUE, PROTOCOL_IDS, deniedEnvValues, paymentChainFor, runMppChannelSuite, runMppChargeSuite, runX402PaymentChecks, runX402ReadChecks, sanitizeText, } from "@wasit-dev/core";
18
+ const require = createRequire(import.meta.url);
19
+ /**
20
+ * Loads `.env` from the working directory exactly as `import "dotenv/config"`
21
+ * did when it sat at the top of this file (it reads the DOTENV_CONFIG_*
22
+ * variables and arguments too). A command runs it before its action; see the
23
+ * hook below for the commands that do not.
24
+ */
25
+ function loadDotenv() {
26
+ require("dotenv/config");
27
+ }
28
+ /** CI sets one of these; the value does not matter, `false` included: when in doubt, it is CI. */
29
+ function inCi(env) {
30
+ return (env["CI"] ?? "") !== "" || (env["GITHUB_ACTIONS"] ?? "") !== "";
31
+ }
11
32
  /** Which wasit subcommand runs each protocol's checks — for `wasit checks` output. */
12
33
  const COMMAND_BY_PROTOCOL = {
13
34
  x402: "test",
@@ -39,6 +60,7 @@ program
39
60
  .addHelpText("after", `
40
61
  Examples:
41
62
  $ wasit checks
63
+ $ wasit init --url http://127.0.0.1:3000/api/weather --operated-by-me
42
64
  $ wasit test --target https://api.example.com/paid-endpoint --read-only
43
65
  $ wasit mpp-charge --target https://api.example.com/paid-endpoint --payer-key S...
44
66
  $ wasit mpp-channel --target https://api.example.com/paid-endpoint
@@ -49,62 +71,28 @@ Run "wasit <command> --help" for that command's own options and cost notes.
49
71
  Add --json to test/mpp-charge/mpp-channel for machine-readable output.
50
72
  Full check catalogue (every check ID, spec reference, pass criteria):
51
73
  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
- }
74
+ // `.env` is loaded before a command's action, as it always was, with three
75
+ // exceptions (spec A8 #2, A-A01, B5): `wasit run` does not load it in CI, where
76
+ // the working directory is a checked-out pull request and a `.env` it added
77
+ // could steer the run; nor with --mainnet, whose key comes from the shell's
78
+ // WASIT_MAINNET_PAYER_SECRET only, never from a file in the service's folder
79
+ // that an agent could read; `wasit ci-report` never does, it has no use for it.
80
+ // CI is read from the real environment, before any `.env` could change it.
81
+ program.hook("preAction", (_program, action) => {
82
+ const name = action.name();
83
+ if (name === "ci-report")
84
+ return;
85
+ if (name === "run" && (inCi(process.env) || action.opts()["mainnet"] === true))
86
+ return;
87
+ loadDotenv();
88
+ });
89
+ /** Waits until what was written to stdout and stderr has been handed to the system, so `process.exit` cannot cut a long report. */
90
+ async function flushOutput() {
91
+ await Promise.all([process.stdout, process.stderr].map((stream) => new Promise((resolve) => stream.write("", () => resolve()))));
65
92
  }
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;
93
+ /** A mistake on the command line learned nothing about a service: exit 2, not commander's 1. */
94
+ function exitTwoOnUsageError(error) {
95
+ process.exit(error.exitCode === 0 ? 0 : 2);
108
96
  }
109
97
  program
110
98
  .command("checks")
@@ -152,10 +140,11 @@ program
152
140
  .command("test")
153
141
  .description("Run x402 compliance checks against a target service")
154
142
  .requiredOption("--target <url>", "URL of the service to test")
155
- .option("--network <network>", "Network the payment checks pay on: stellar:testnet, stellar:pubnet, " +
143
+ .option("--network <network>", "Network the payment checks pay on: stellar:testnet, " +
156
144
  "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")
145
+ "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1 (Solana devnet). Test networks " +
146
+ "only: on any other network, stellar:pubnet included, the payment checks " +
147
+ "stop before anything is signed. X402-01..05 apply to a challenge on any chain.", "stellar:testnet")
159
148
  .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
149
  .option("--payer-key <key>", "Testnet payer key (overrides STELLAR_PRIVATE_KEY, EVM_PRIVATE_KEY on eip155 networks, " +
161
150
  "or SVM_PRIVATE_KEY on Solana, from .env)")
@@ -163,7 +152,7 @@ program
163
152
  "compute something usually take POST.")
164
153
  .option("--body <json>", "Request body, sent verbatim. Implies Content-Type: application/json.")
165
154
  .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)
155
+ .option("--read-only", "Skip the payment checks (X402-06..11)", false)
167
156
  .option("--json", "Print results as JSON instead of formatted text", false)
168
157
  .addHelpText("after", `
169
158
  Examples:
@@ -175,7 +164,13 @@ X402-01..05 (challenge/header checks) always run and cost nothing. X402-06..10
175
164
  (real payment checks) run only when a payer key is available and --read-only
176
165
  is not set: X402-06 settles a payment; X402-07..10 send payments the target
177
166
  must refuse (a corrupted signature, a replay, an underpayment, an expired
178
- authorization). See docs/CHECKS.md for what each check ID verifies.`)
167
+ authorization). X402-11 needs a request the service must refuse, the reject case
168
+ of a wasit.config.json endpoint: it runs in wasit run and is skipped here. See
169
+ docs/CHECKS.md for what each check ID verifies.
170
+
171
+ At a terminal the output is coloured and live: each check shows while it runs,
172
+ with its duration, and the run's duration comes at the end. A pipe, CI, --json
173
+ or NO_COLOR gives the plain text; FORCE_COLOR=1 colours a pipe.`)
179
174
  .action(async (opts) => {
180
175
  const jsonMode = opts.json === true;
181
176
  const shape = {
@@ -183,6 +178,11 @@ authorization). See docs/CHECKS.md for what each check ID verifies.`)
183
178
  ...(opts.body !== undefined ? { body: opts.body } : {}),
184
179
  ...(opts.header ? { headers: opts.header } : {}),
185
180
  };
181
+ // A person at a terminal gets the coloured, live output; a pipe, CI, NO_COLOR
182
+ // and --json get the plain text below, unchanged.
183
+ if (!jsonMode && colorEnabled(process.stdout, process.env)) {
184
+ process.exit(await liveX402Test(opts, shape, { stream: process.stdout, env: process.env }));
185
+ }
186
186
  const results = await runX402ReadChecks({ target: opts.target, ...shape });
187
187
  // Each chain reads its own payer key: a Stellar secret is no use on EVM.
188
188
  const keyEnv = paymentChainFor(opts.network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY";
@@ -204,7 +204,245 @@ authorization). See docs/CHECKS.md for what each check ID verifies.`)
204
204
  ...shape,
205
205
  })));
206
206
  }
207
- process.exit(report(results, jsonMode));
207
+ // One endpoint: a service Wasit could not grade exits 2, not 0 (spec A8 #3).
208
+ process.exit(report(results, jsonMode, { protocol: "x402" }));
209
+ });
210
+ program
211
+ .command("run")
212
+ .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")
213
+ .option("--config <path>", "The config file", "wasit.config.json")
214
+ .option("--env <name>", "The environment to run (default: defaultEnvironment, else the only one)")
215
+ .option("--endpoint <name>", "Run only this endpoint, by name. Repeatable.", (value, previous) => [...previous, value], [])
216
+ .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)
217
+ .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, " +
218
+ "against the caps ($1 a payment, $5 a run, lower with maxRunUsd). Reads each x402 endpoint's unpaid challenge, and " +
219
+ "on stellar:testnet each MPP charge endpoint's; " +
220
+ "uses no key, sends no payment, signs nothing. Exit 2 when a paying run would be refused. Not with --read-only.", false)
221
+ .option("--json", "Print the report as JSON instead of text", false)
222
+ .option("--out <file>", "Write the JSON report to this file as well")
223
+ .option("--start", "Run service.start from the config, wait for service.ready, run, and stop the service afterwards. " +
224
+ "The service does not receive Wasit's key variables, header variables or WASIT_RPC_URL.", false)
225
+ .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]); " +
226
+ "otherwise the configured baseUrl is read as it is, which is how a deployed endpoint is checked. Not with --start.", false)
227
+ .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)")
228
+ .option("--mainnet", "Pay real USDC on stellar:pubnet (x402 only). Runs only when every rule holds: the environment is on stellar:pubnet with " +
229
+ "operatedByMe true and pinned payTo and asset (mainnet USDC); the key is in WASIT_MAINNET_PAYER_SECRET and in no other " +
230
+ "variable; an https RPC for stellar:pubnet is set (rpcUrl or WASIT_RPC_URL); the payer holds at most $10.00 of USDC; " +
231
+ "no other mainnet run holds the lock; in GitHub Actions, the run is started by hand on the default branch on a " +
232
+ "GitHub-hosted runner, tests a deployed service and has no other key variable set. Otherwise exit 2 before anything " +
233
+ "is started, sent or signed. With --mainnet, wasit run does not read .env: the variables come from the shell. " +
234
+ "Not with --read-only.", false)
235
+ .option("--ledger-dir <dir>", "With --mainnet: the folder of the run ledger (wasit-ledger-<UTC time>.json, every signature written before the key " +
236
+ "signs) and of the lock that keeps a second mainnet run from starting beside it. Default: the working directory.")
237
+ .addHelpText("after", `
238
+ Examples:
239
+ $ wasit run --read-only
240
+ $ wasit run --read-only --env staging --endpoint weather --json --out wasit-report.json
241
+ $ wasit run --read-only --start
242
+ $ wasit run --read-only --start-if-local --env mainnet
243
+ $ wasit run --dry-run --start
244
+ $ wasit run --start (payment tier: STELLAR_PRIVATE_KEY on stellar:testnet)
245
+ $ wasit run --start (MPP: MPP_PAYER_SECRET, COMMITMENT_SECRET_HEX on stellar:testnet)
246
+ $ wasit run --dry-run --env mainnet (the plan on stellar:pubnet: no key is read)
247
+ $ wasit run --mainnet --env mainnet (real funds: WASIT_MAINNET_PAYER_SECRET on stellar:pubnet)
248
+
249
+ Exit codes: 0 every graded endpoint conforms; 1 an endpoint does not conform, or one
250
+ graded on the baseline is not graded now; 2 no verdict (nothing could be graded, a
251
+ check could not run, the config or the service could not be used, or the payment
252
+ tier was asked for and did not pay: no payer key, or operatedByMe not true).
253
+ The payment tier pays on test networks: at most $1.00 a payment and $5.00 a run
254
+ (lower with maxRunUsd), only the pinned payTo and asset when the config pins them.
255
+ On stellar:pubnet it pays only with --mainnet: the first line says MAINNET RUN; the
256
+ plan reads the payer's balances on the RPC and public Horizon first, and refuses a
257
+ payer holding less than the run needs to finish its checks (the prices plus the
258
+ highest price again; a warning below the worst case); every signature
259
+ is in the run ledger; one refusal stops the whole run (exit 2); at the end the run
260
+ waits until every authorization it signed has expired (up to about five minutes),
261
+ reads the payer's balances again and says whether they match the ledger: consistent;
262
+ explained (more USDC left than the run verified settled, within the payments of
263
+ checks that FAILed: exit 1, by the checks); or inconsistent (exit 2).
264
+ In GitHub Actions it pays only on push to the default branch, schedule and
265
+ workflow_dispatch; a pull request runs the read-only checks, and a payer key set on
266
+ a run that may not pay is refused before the service starts. In another CI (CI set,
267
+ not GitHub Actions) the payment tier is refused with exit 2: use --read-only there,
268
+ with no payer key in the job.
269
+ X402-11 runs for an endpoint with a reject case, on Stellar: it sends a valid payment
270
+ with the request the service must refuse, then reads the chain until that payment's
271
+ authorization has expired, up to six minutes; a lifetime above 300 s or below 30 s is
272
+ not signed, and an authorization signed to outlive 300 s is not sent.
273
+ MPP endpoints are paid in the payment tier on stellar:testnet only, by the same rules:
274
+ MPP-01 (charge) with MPP_PAYER_SECRET, planned from its unpaid challenge and held to the
275
+ same caps, in the same budget as x402; MPP-10, 11, 12 and 14 (channel) with
276
+ COMMITMENT_SECRET_HEX, with the channel and its expected terms from the config: with a
277
+ channel in the config, commitments are signed for it only, and a route whose challenge
278
+ names another gets none. MPP-13 (close) is never run by wasit run. The network and the
279
+ channel come from the config: MPP_STELLAR_NETWORK and CHANNEL_CONTRACT are not read. An
280
+ MPP endpoint is sent a plain GET: one with a method, a body or headers is not sent
281
+ anything. A mainnet run pays its x402 endpoints only.
282
+ In CI (CI or GITHUB_ACTIONS set) a .env file in the working directory is not read.`)
283
+ .exitOverride(exitTwoOnUsageError)
284
+ .action(async (opts) => {
285
+ let code;
286
+ try {
287
+ code = await executeRun({
288
+ config: opts.config,
289
+ ...(opts.env === undefined ? {} : { env: opts.env }),
290
+ endpoint: opts.endpoint,
291
+ readOnly: opts.readOnly === true,
292
+ dryRun: opts.dryRun === true,
293
+ json: opts.json === true,
294
+ ...(opts.out === undefined ? {} : { out: opts.out }),
295
+ start: opts.start === true,
296
+ startIfLocal: opts.startIfLocal === true,
297
+ ...(opts.baseline === undefined ? {} : { baseline: opts.baseline }),
298
+ mainnet: opts.mainnet === true,
299
+ ...(opts.ledgerDir === undefined ? {} : { ledgerDir: opts.ledgerDir }),
300
+ }, { env: process.env, stdout: (line) => console.log(line), stderr: (line) => console.error(line) });
301
+ }
302
+ catch (error) {
303
+ const message = error instanceof Error ? error.message : String(error);
304
+ console.error(sanitizeText(`wasit run: unexpected error: ${message}`, { redact: deniedEnvValues(process.env) }));
305
+ code = 2;
306
+ }
307
+ await flushOutput();
308
+ process.exit(code);
309
+ });
310
+ program
311
+ .command("init")
312
+ .description("Write a wasit.config.json for one paid route of a service you operate, from one unpaid request to the route")
313
+ .option("--url <url>", "The URL of one paid route, e.g. http://127.0.0.1:3000/api/weather (at a terminal, init asks for what you leave out)")
314
+ .option("--operated-by-me", "Confirm that you operate the service. Wasit tests only services their operator runs: without it nothing is written", false)
315
+ .option("--name <name>", "The endpoint's name (default: the last part of the path)")
316
+ .option("--method <method>", "The route's HTTP method (default: GET)")
317
+ .option("--body-file <file>", "A JSON file with the request body, written into the config as a JSON value (not with GET)")
318
+ .option("--network <id>", "Choose this test network (CAIP-2) among the ones the route offers; with --no-read, the network written (default: stellar:testnet)")
319
+ .option("--protocol <name>", "Choose this protocol among the ones the route offers: x402, mpp-charge or mpp-channel")
320
+ .option("--no-read", "Do not ask the route anything: write it as x402 from the flags alone")
321
+ .option("--env <name>", "The environment's name (default: local, for a URL on this machine)")
322
+ .option("--start <command>", "The command that starts the service, for wasit run --start")
323
+ .option("--ready-url <url>", "With --start: the address on this machine to wait for (default: the route's URL, on this machine)")
324
+ .option("--ready-timeout <seconds>", "With --start: how long to wait, 1 to 600 (default: 60)")
325
+ .option("--reject-header <header>", 'A header of the request the route must refuse (X402-11), as "Name: value". Repeatable.', (value, previous) => [...previous, value], [])
326
+ .option("--reject-body-file <file>", "A JSON file with the body of the request the route must refuse (X402-11)")
327
+ .option("--reject-note <text>", "One line on why the route must refuse that request")
328
+ .option("--config <path>", "The config file", DEFAULT_CONFIG_FILE)
329
+ .option("--force", "Replace the config file instead of adding the endpoint to it", false)
330
+ .option("--setup-keys", "Stellar testnet: set up the key the route's payment checks read, in .env (also adds .env to .gitignore when git does not ignore it)")
331
+ .option("--no-setup-keys", "Do not set up a key, and do not ask")
332
+ .addHelpText("after", `
333
+ Examples:
334
+ $ wasit init --url http://127.0.0.1:3000/api/weather --operated-by-me
335
+ $ wasit init --url http://127.0.0.1:3000/api/weather --operated-by-me --setup-keys
336
+ $ wasit init --url http://127.0.0.1:3000/api/chat --method POST --body-file body.json --operated-by-me --start "npm start"
337
+ $ wasit init --url http://127.0.0.1:3000/mpp/chat --operated-by-me --protocol mpp-charge
338
+
339
+ init sends the route one unpaid request (its method and body, and the
340
+ WASIT_HEADER_* headers wasit run sends), follows at most one redirect inside its
341
+ origin, and pays and signs nothing. Its 402 tells x402 from MPP and gives the
342
+ protocol, the network, the receiving address and asset (pinned) and an MPP
343
+ channel. A route that answers 200, 500 or 503, or does not answer, writes
344
+ nothing: --no-read writes it from the flags alone, as x402.
345
+ An existing config is added to (one more endpoint), never overwritten: --force
346
+ replaces it. A route the config already has exactly as given, in the same
347
+ environment, is left as it is, so init can run again (to set up its key, say).
348
+ Mainnet is not written in this version, and neither is a header of
349
+ the route: send a credential in a WASIT_HEADER_<NAME> variable. A URL whose query
350
+ has a parameter named like a credential (api_key, token, sig), given with --url or
351
+ reached by the redirect, is refused. After writing, init prints what it read from
352
+ your service, what you gave, what it filled in by default and what it did not read,
353
+ then the next command.
354
+
355
+ Key setup (Stellar testnet only; --setup-keys, or a yes at a terminal), after
356
+ the config is written: first it checks that git will not commit .env (not
357
+ tracked, and ignored: else .env is added to .gitignore, or no key is written).
358
+ A key already set is kept and its account only read. Otherwise init makes a
359
+ testnet key (x402: STELLAR_PRIVATE_KEY; MPP charge: MPP_PAYER_SECRET), adds it
360
+ to .env without showing the secret, funds it with Friendbot and swaps 10 test
361
+ XLM for test USDC on the public test exchange, then prints a status table. For
362
+ an MPP channel it makes no key: COMMITMENT_SECRET_HEX must be the key the
363
+ channel was opened with. On other test networks it names the variable and the
364
+ faucet. The key setup never changes the exit code.
365
+ Exit codes: 0 the config has the route (written now, or already there as
366
+ given); 2 init refused, and nothing was written.`)
367
+ .exitOverride(exitTwoOnUsageError)
368
+ .action(async (opts) => {
369
+ let code;
370
+ // Questions only at a terminal (C1); in a script or a pipe init asks nothing and names the missing flags (C5).
371
+ const rl = process.stdin.isTTY === true && process.stdout.isTTY === true
372
+ ? (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout })
373
+ : undefined;
374
+ try {
375
+ code = await executeInit({
376
+ ...(opts.url === undefined ? {} : { url: opts.url }),
377
+ operatedByMe: opts.operatedByMe === true,
378
+ ...(opts.name === undefined ? {} : { name: opts.name }),
379
+ ...(opts.method === undefined ? {} : { method: opts.method }),
380
+ ...(opts.bodyFile === undefined ? {} : { bodyFile: opts.bodyFile }),
381
+ ...(opts.network === undefined ? {} : { network: opts.network }),
382
+ ...(opts.protocol === undefined ? {} : { protocol: opts.protocol }),
383
+ ...(opts.env === undefined ? {} : { env: opts.env }),
384
+ ...(opts.start === undefined ? {} : { start: opts.start }),
385
+ ...(opts.readyUrl === undefined ? {} : { readyUrl: opts.readyUrl }),
386
+ ...(opts.readyTimeout === undefined ? {} : { readyTimeout: opts.readyTimeout }),
387
+ rejectHeader: opts.rejectHeader,
388
+ ...(opts.rejectBodyFile === undefined ? {} : { rejectBodyFile: opts.rejectBodyFile }),
389
+ ...(opts.rejectNote === undefined ? {} : { rejectNote: opts.rejectNote }),
390
+ config: opts.config,
391
+ force: opts.force === true,
392
+ read: opts.read !== false,
393
+ ...(typeof opts.setupKeys === "boolean" ? { setupKeys: opts.setupKeys } : {}),
394
+ }, {
395
+ env: process.env,
396
+ stdout: (line) => console.log(line),
397
+ stderr: (line) => console.error(line),
398
+ ...(rl === undefined ? {} : { ask: (question) => rl.question(question) }),
399
+ keys: LIVE_KEY_SETUP,
400
+ });
401
+ }
402
+ catch (error) {
403
+ const message = error instanceof Error ? error.message : String(error);
404
+ console.error(sanitizeText(`wasit init: unexpected error: ${message}`, { redact: deniedEnvValues(process.env) }));
405
+ code = 2;
406
+ }
407
+ finally {
408
+ rl?.close();
409
+ }
410
+ await flushOutput();
411
+ process.exit(code);
412
+ });
413
+ program
414
+ .command("ci-report")
415
+ .description("Write the pull request comment and the job summary from the report of wasit run")
416
+ .requiredOption("--report <file>", "The report written by wasit run --json --out")
417
+ .option("--baseline <file>", "The baseline of the default branch, for \"Changed since main\" and the recent failures")
418
+ .option("--comment <file>", "Where the comment goes", "comment.md")
419
+ .option("--summary <file>", "The job summary file, appended to (default: $GITHUB_STEP_SUMMARY)")
420
+ .option("--baseline-out <file>", "Write the next baseline here: this report with its history. For a run on the default branch.")
421
+ .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")
422
+ .option("--baseline-run <id>", "The id of the run the baseline came from, named in the comment")
423
+ .option("--check-run <file>", "Write the check run's title, summary and conclusion here, as JSON")
424
+ .exitOverride(exitTwoOnUsageError)
425
+ .action(async (opts) => {
426
+ let code;
427
+ try {
428
+ code = await executeCiReport({
429
+ report: opts.report,
430
+ ...(opts.baseline === undefined ? {} : { baseline: opts.baseline }),
431
+ comment: opts.comment,
432
+ ...(opts.summary === undefined ? {} : { summary: opts.summary }),
433
+ ...(opts.baselineOut === undefined ? {} : { baselineOut: opts.baselineOut }),
434
+ ...(opts.history === undefined ? {} : { history: opts.history }),
435
+ ...(opts.baselineRun === undefined ? {} : { baselineRun: opts.baselineRun }),
436
+ ...(opts.checkRun === undefined ? {} : { checkRun: opts.checkRun }),
437
+ }, { env: process.env, stdout: (line) => console.log(line), stderr: (line) => console.error(line) });
438
+ }
439
+ catch (error) {
440
+ const message = error instanceof Error ? error.message : String(error);
441
+ console.error(sanitizeText(`wasit ci-report: unexpected error: ${message}`, { redact: deniedEnvValues(process.env) }));
442
+ code = 2;
443
+ }
444
+ await flushOutput();
445
+ process.exit(code);
208
446
  });
209
447
  program
210
448
  .command("serve")
@@ -271,7 +509,8 @@ program
271
509
  .description("Run MPP channel-mode compliance checks against a target service")
272
510
  .requiredOption("--target <url>", "URL of the paid resource to test")
273
511
  .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)")
512
+ .option("--network <network>", "CAIP-2 network id, stellar:testnet only; any other network is refused before " +
513
+ "anything is sent (default: MPP_STELLAR_NETWORK, else stellar:testnet)")
275
514
  .option("--rpc-url <url>", "Override the default Soroban RPC endpoint")
276
515
  .option("--channel <address>", "Assert which channel the target bills through. Defaults to the channel " +
277
516
  "the target advertises; a mismatch fails MPP-10. (env: CHANNEL_CONTRACT)")
@@ -318,14 +557,22 @@ that channel.`)
318
557
  ...(Number.isInteger(refundWaitingPeriod) ? { refundWaitingPeriod } : {}),
319
558
  },
320
559
  });
321
- process.exit(report(results, jsonMode));
560
+ process.exit(report(results, jsonMode, terminalStyle(jsonMode)));
322
561
  });
562
+ /** Colours for the MPP commands' text output, when a person is at the terminal. */
563
+ function terminalStyle(jsonMode) {
564
+ return {
565
+ style: styler(!jsonMode && colorEnabled(process.stdout, process.env), colorDepth(process.env)),
566
+ width: lineWidth(process.stdout),
567
+ };
568
+ }
323
569
  program
324
570
  .command("mpp-charge")
325
571
  .description("Run the MPP charge-mode check (MPP-01) against a target service")
326
572
  .requiredOption("--target <url>", "URL of the paid resource to test")
327
573
  .option("--payer-key <key>", "Payer secret key, S... (default: MPP_PAYER_SECRET)")
328
- .option("--network <network>", "CAIP-2 network id (default: MPP_STELLAR_NETWORK)")
574
+ .option("--network <network>", "CAIP-2 network id, stellar:testnet only; any other network is refused before " +
575
+ "anything is sent (default: MPP_STELLAR_NETWORK, else stellar:testnet)")
329
576
  .option("--rpc-url <url>", "Override the default Soroban RPC endpoint")
330
577
  .option("--json", "Print results as JSON instead of formatted text", false)
331
578
  .addHelpText("after", `
@@ -349,11 +596,12 @@ a real payment and moves testnet funds, because charge mode has no dry run.`)
349
596
  payerSecretKey,
350
597
  ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}),
351
598
  });
352
- process.exit(report(results, jsonMode));
599
+ process.exit(report(results, jsonMode, terminalStyle(jsonMode)));
353
600
  });
354
601
  registerWalletCommand(program);
355
602
  const isBareInteractiveInvocation = process.argv.length <= 2 && process.stdout.isTTY === true;
356
603
  if (isBareInteractiveInvocation) {
604
+ loadDotenv();
357
605
  render(createElement(App));
358
606
  }
359
607
  else {
@@ -0,0 +1,98 @@
1
+ /**
2
+ * `wasit init`: a `wasit.config.json` for one paid route of a service its
3
+ * operator runs (spec C; W3-2 slices 2 and 3).
4
+ *
5
+ * Every answer is a flag, so the same command works in a script, in
6
+ * PowerShell and in cmd.exe: no answer needs shell quoting (a body comes from
7
+ * a file). The file is written by core's config writer, which takes only data
8
+ * that is certain and checks the result with the validator `wasit run` reads
9
+ * the file with (Najmi, 2026-11-15). What the writer is not given, this
10
+ * command fills from a fixed fallback table (init-skeleton-plan.md section 6),
11
+ * and says so: after writing it prints what it read from the service, what was
12
+ * given, what was filled in by default, and what was NOT read.
13
+ *
14
+ * Reading the route (C2, slice 3) is the default: one unpaid request with the
15
+ * route's method and body (and the `WASIT_HEADER_*` headers `wasit run` would
16
+ * send), one redirect inside the origin at most, no payment, no signature, no
17
+ * key. Its 402 tells x402 from MPP and fills in the protocol, the network, the
18
+ * pin (receiving address and asset) and an MPP channel. A route that answers
19
+ * 200, 500 or 503, or nothing, is said in plain words and nothing is written;
20
+ * `--no-read` writes the route from the flags alone, as x402 (slice 2).
21
+ *
22
+ * The testnet key setup (C4, slice 5, `init-keys.ts`) comes last, for a route
23
+ * on Stellar testnet: with `--setup-keys`, or a yes at a terminal. It writes the
24
+ * key the route's payment checks read into `.env` (never into the config, and
25
+ * never printed) after checking that git will not commit `.env`.
26
+ *
27
+ * Nothing is sent and nothing is written without `--operated-by-me`: Wasit
28
+ * tests only services their operator runs. Every flag is checked before the
29
+ * route is asked anything. An existing config is added to, never overwritten
30
+ * silently; `--force` replaces it. A route it already has exactly as given, in
31
+ * the same environment, is left as it is, byte for byte, and the run goes on
32
+ * (to the key setup): init can be run again on the same route. Mainnet is not written in this version, and
33
+ * nothing that could hold a secret is: an endpoint's headers are not written (a
34
+ * credential goes in `WASIT_HEADER_*`). What the service answered is data:
35
+ * printed through the sanitiser, never followed or run.
36
+ *
37
+ * `executeInit` does not call `process.exit` and does not read the process:
38
+ * the environment and the output are passed in, so it can be tested in-process.
39
+ */
40
+ import { type KeySetupDeps } from "./init-keys.js";
41
+ export declare const DEFAULT_CONFIG_FILE = "wasit.config.json";
42
+ export interface InitCommandOptions {
43
+ readonly url?: string;
44
+ readonly operatedByMe: boolean;
45
+ readonly name?: string;
46
+ readonly method?: string;
47
+ readonly bodyFile?: string;
48
+ /** Chooses among the ways the route offers to pay; without reading, the network written. */
49
+ readonly network?: string;
50
+ /** Chooses among the ways the route offers to pay. */
51
+ readonly protocol?: string;
52
+ readonly env?: string;
53
+ readonly start?: string;
54
+ readonly readyUrl?: string;
55
+ readonly readyTimeout?: string;
56
+ /** `Name: value`, repeatable: the headers of the request the route must refuse (X402-11). */
57
+ readonly rejectHeader: readonly string[];
58
+ readonly rejectBodyFile?: string;
59
+ readonly rejectNote?: string;
60
+ readonly config: string;
61
+ readonly force: boolean;
62
+ /** Read the route's 402 (the default); false is `--no-read`: no request, x402 from the flags. */
63
+ readonly read: boolean;
64
+ /**
65
+ * The testnet key setup (C4): true is `--setup-keys`, false `--no-setup-keys`.
66
+ * Undefined: asked at a terminal, else not done.
67
+ */
68
+ readonly setupKeys?: boolean;
69
+ }
70
+ export interface InitContext {
71
+ /** The `WASIT_HEADER_*` variables the read sends, and the values kept out of every printed line. */
72
+ readonly env: Readonly<Record<string, string | undefined>>;
73
+ /** One line at a time, the line break added by the caller. */
74
+ readonly stdout: (line: string) => void;
75
+ readonly stderr: (line: string) => void;
76
+ /** Where relative paths are read from and the config is written. Default: the working directory. */
77
+ readonly cwd?: string;
78
+ /** Tests only: how long the read waits for the route. Index never sets it. */
79
+ readonly readTimeoutMs?: number;
80
+ /**
81
+ * Asks one question and returns the answer. Given only when stdin and stdout
82
+ * are terminals (C1): without it, init asks nothing and names the flags that
83
+ * are missing (C5). Rejects when the input ends.
84
+ */
85
+ readonly ask?: (question: string) => Promise<string>;
86
+ /** The outside world of the key setup (git, Friendbot, Horizon, the key generator). Needed when the key setup runs. */
87
+ readonly keys?: KeySetupDeps;
88
+ }
89
+ /**
90
+ * Runs `wasit init`. Returns the exit code: 0 the file has the route (written
91
+ * now, or already there as given and left as it is); 2 nothing was written (a
92
+ * flag is missing or wrong, the service is not yours, the route is not a
93
+ * paywall init can read, or the writer refused the data). The key setup runs
94
+ * after the file is written and never changes the exit code: what
95
+ * it could not do is in its status table, with the command that finishes it
96
+ * (Najmi, 2026-11-27).
97
+ */
98
+ export declare function executeInit(given: InitCommandOptions, context: InitContext): Promise<number>;