diff --git a/CHANGELOG.md b/CHANGELOG.md index 34eba18..0dd73ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,129 @@ All notable changes to Wasit are recorded here. Versions follow [Semantic Versioning](https://semver.org/): patch releases are fixes, minor releases add checks or features without breaking existing usage, major releases break something. +## [0.8.0-beta.1] - 2026-11-20 + +A pre-release for beta testers, on npm under the `beta` tag +(`npm install -g @wasit-dev/cli@beta`); `latest` stays at 0.7.0. All three +packages, versioned together. New: a config file for a whole service +(`wasit.config.json`), `wasit run` with a read-only tier and a payment tier, +`wasit ci-report`, a GitHub Action that runs them, and a seventeenth check, +`X402-11`. Payments are made on test networks only, and every payment Wasit +signs is held to $1.00, to $5.00 a run, and to a plan read before the run. The +mainnet opt-in is not part of this version: the switches that would ask for it +refuse. The guides on usewasit.dev still describe 0.7.0; this entry, the +package READMEs and `wasit run --help` describe the beta. + +**Results can change on upgrade.** +- Payment checks pay on test networks only: `stellar:testnet`, Base Sepolia + (`eip155:84532`), Ethereum Sepolia (`eip155:11155111`) and Solana devnet, and + the MPP checks on `stellar:testnet` only. Any other network, `stellar:pubnet` + included, is refused before a key is read, in + `wasit test`, `wasit mpp-charge`, `wasit mpp-channel`, the MCP tools and core. +- A price above $1.00 is not paid: `X402-06` gets no verdict (`ERROR (setup)`), + the other payment checks are skipped, and nothing is signed. +- A paid request, and every MPP request, no longer follows a redirect: a 3xx + gives that check no verdict, and the payment is not sent again. +- The RPC must serve the run's network (the Stellar network passphrase, the EVM + chain id, the Solana genesis hash) before anything is signed; another network, + or no answer, stops the payment checks with no verdict. +- An x402 v1 challenge is reported as unsupported, not as a failure, and a run + that could grade nothing exits 2. + +**Fixed: two MPP defects of 0.7.0.** In 0.7.0 `MPP-01` paid on `stellar:pubnet` +when the run named it (`--network`, or the MCP tool's `network` argument), with +no cap (read from the code, not run: it would need mainnet funds). And a channel commitment +was signed without checking the bytes the RPC returned for it, so a run on the +test network pointed at a mainnet RPC signed a commitment valid on mainnet +(shown offline, against a stand-in RPC). Both are fixed: every network but the +test networks is refused before a key is read, and a commitment is signed only +when it names the run's channel, amount and network. See the advisory +[GHSA-7c36-rg54-r3v8](https://github.com/wasit-dev/wasit/security/advisories/GHSA-7c36-rg54-r3v8). + +**Added: `wasit.config.json`, `wasit run` and `wasit ci-report`.** The config +(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 the file. `wasit run` +runs every endpoint of it (`--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`). `wasit run --read-only` runs `X402-01` to `X402-05`, which send +no payment. `wasit run --dry-run` prints, without a key, what the payment +checks would sign. `wasit ci-report` turns a report into the pull request +comment and the job summary. + +**Added: the payment tier.** `wasit run` without `--read-only` pays, on test +networks only, when the environment has `operatedByMe: true` and the chain's +key variable is set. Each signature is held to $1.00 and the run to $5.00 +(`maxRunUsd` can only lower it), to the `payTo` and asset the config pins, and +to the plan read before the run; the x402 client is handed the one option +checked, and what it signed is compared before it is sent. 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 and says "payment checks not run: pull +request", and a payer key given to a run that may not pay stops it with exit 2 +before the service starts. On a GitHub-hosted runner with a payer key, a +service Wasit starts (`--start`) runs as a separate user, `wasit-service`. In another CI (`CI` set, not +GitHub Actions) the payment tier stops with exit 2: use `--read-only` there. + +**Added: the GitHub Action** (`action/`, pinned by full commit SHA). A +composite action for Linux runners with Node 22, which builds Wasit from the +ref it is pinned to. Inputs: `config`, `environment`, `tier` (`read-only` or +`payment`), `endpoints`, and `mainnet`, which is refused. It comments on the +pull request (one comment, updated on each push), compares with the last green +run on the default branch and names it, and writes the job summary. + +**Added: the run on the pull request.** The comment shows a table of each +endpoint's checks with a mark for each result (✅ PASS, ❌ FAIL, ⚪ SKIP, +⚠️ ERROR), and every check's detail folded at the end. On `stellar:testnet`, +when `X402-06` passed, it links that payment's transaction on Stellar Expert, as +the check read it back from the chain (the new `reference` field of a passing +result, also in `--json` and the MCP tools' output). While Wasit runs, the +comment says "⏳ Wasit is running", with a link to the run. With the permission +`checks: write`, the Action also adds a check run, "Wasit conformance", +completed at the end with the verdict and the job summary (`wasit ci-report +--check-run`); without it, that check is left out. A pull request from a fork +gets neither. `NODE_OPTIONS` is set empty in every step of the Action, so a +`NODE_OPTIONS` in the workflow's `env` no longer reaches Wasit or a service it +starts: put the options a service needs in `service.start`. The example workflow (`action/examples/wasit.yml`) +asks for `checks: write` and runs one Wasit job per pull request, a newer push +cancelling the older one. + +**Added: `X402-11`, "Rejected Request Not Settled".** For an endpoint with a +`reject` case in the config, on Stellar: a valid payment is sent with the +request the service must refuse, and the chain is read until that payment's +authorization has expired. Unused, with no transfer, passes; used, or the +request served, fails. A lifetime above 300 s, or below 30 s, is skipped before +anything is signed, and the wait stops 360 s after the payment was sent. See +`docs/CHECKS.md`. + +**Added: the mainnet switches, which refuse.** `wasit run --mainnet`, the +Action input `mainnet: true`, and the MCP server's `WASIT_MAINNET_OPT_IN`, +`WASIT_MAINNET_CONFIG` and `--mainnet` stop with exit 2 and "the mainnet opt-in +is not part of this version". Nothing is started, sent or signed. + +**Added: the MCP server's RPC lock.** `WASIT_RPC_URL`, read when the server +starts, fixes the RPC of every tool call, and the `rpcUrl` argument is then +refused before anything is sent. A result that reads the chain names its RPC +by origin, where it came from, and when it is not Wasit's default (in the text +and in `structuredContent.rpc`). + +**Added: coloured, live output at a terminal.** `wasit test` shows its checks +in two blocks, challenge and payment. Each line has a mark and a badge that +agree (✓ PASS on green, ✗ FAIL on red, ○ SKIP on yellow, ! ERROR on magenta) +and its duration. A spinner line says what the check in flight is +doing, and the verdict, the counts and the run's duration come at the end. The +colours are Wasit's own, exact on a terminal with 24-bit colour. `wasit +mpp-charge` and `wasit mpp-channel` mark their results the same way. A pipe, CI, +`--json` and `NO_COLOR` get the plain text as before; `FORCE_COLOR=1` colours a +pipe. + +**Changed:** `@stellar/stellar-sdk` 16.4.1: the test network is on protocol +30, and 16.1.0 cannot read its ledger headers. + +**Not in this version:** the mainnet opt-in; paying MPP from `wasit run` and +the Action (an MPP endpoint's payment checks are skipped, with the reason); +`wasit init`. + ## [0.7.0] — 2026-10-08 All three packages, versioned together as usual. The x402 payment checks now diff --git a/README.md b/README.md index 30f5c98..6d48484 100644 --- a/README.md +++ b/README.md @@ -185,17 +185,20 @@ Wasit exists so these are found by a tool, before they are found by a user. | x402 payment checks (`X402-06`–`10`) | Done on Stellar testnet, Base Sepolia, Ethereum Sepolia and Solana devnet, settlement verified from each chain's own record | | MPP charge mode (`MPP-01`) | Done, settlement verified from contract events; pays only on the run's network | | MPP channel mode (`MPP-10`–`14`) | Done, including destructive close | -| CLI | Done — six subcommands, `wasit serve` among them, plus an interactive dashboard | +| CLI | Done — six subcommands in 0.7.0, `wasit serve` among them, and eight in 0.8.0-beta.1 (`wasit run`, `wasit ci-report`), plus an interactive dashboard | | Testnet wallet tooling | Done — `wasit wallet` create/fund/status on Stellar testnet, and for the x402 payer on Base Sepolia, Ethereum Sepolia and Solana devnet | | MCP server | Done, three tools + one behind an opt-in | +| `wasit.config.json`, `wasit run`, `wasit ci-report` | In 0.8.0-beta.1 (npm tag `beta`): every endpoint of a service from one config, a read-only tier and a payment tier, and the pull request comment and job summary from the report | +| GitHub Action (`action/`) | In 0.8.0-beta.1: runs `wasit run` in a workflow; on a pull request it comments and, with `checks: write`, adds a check, "Wasit conformance"; it pays only on a push to the default branch, a schedule or a run started by hand, on test networks | +| `X402-11`, rejected request not settled | In 0.8.0-beta.1: on Stellar, through `wasit run`, for an endpoint with a `reject` case | | Error taxonomy and exit codes | Done | | Wasit's own test suite | Done — offline (no keys, no target, no network); type-check and tests both run in CI | | Testing against third-party services | Done — one third-party service, [defi-copilot](docs/evidence/2026-09-28-authorized-third-party-run.md), tested with its operator's written authorization as a local instance, plus Stellar's own reference implementations ([x402](docs/evidence/2026-09-06-reference-implementation-run.md), [MPP](docs/evidence/2026-09-24-official-sdk-reference-run.md)); reported in aggregate in [conformance-findings.md](docs/findings/conformance-findings.md) | | Upstream reports to SDK maintainers | Filed — [stellar-mpp-sdk#66](https://github.com/stellar/stellar-mpp-sdk/issues/66), [#67](https://github.com/stellar/stellar-mpp-sdk/issues/67), [#70](https://github.com/stellar/stellar-mpp-sdk/issues/70) (closed; fix merged, unreleased), [#82](https://github.com/stellar/stellar-mpp-sdk/issues/82) (fixed in [#83](https://github.com/stellar/stellar-mpp-sdk/pull/83), verified), [#89](https://github.com/stellar/stellar-mpp-sdk/issues/89) | -| Published to npm | Yes — `@wasit-dev/core`, `@wasit-dev/cli`, `@wasit-dev/server` | -| Mainnet | Out of scope — see [Design Notes](#design-notes) | +| Published to npm | Yes — `@wasit-dev/core`, `@wasit-dev/cli`, `@wasit-dev/server`: 0.7.0 under `latest`, 0.8.0-beta.1 under `beta` | +| Mainnet | Out of scope — see [Design Notes](#design-notes). In 0.8.0-beta.1 a payment on any network but the test networks is refused before a key is read | -Sixteen checks are implemented and reachable from both front ends. Every one is +Seventeen checks are implemented. Sixteen are reachable from both front ends; `X402-11`, new in 0.8.0-beta.1, runs through `wasit run`. Every one is traced to a written spec clause in [docs/CHECKS.md](docs/CHECKS.md); a check that cannot be traced is out of scope by construction. @@ -212,6 +215,9 @@ npx @wasit-dev/cli test --target https://your-service.example/paid --read-only # or keep it around npm install -g @wasit-dev/cli wasit test --target https://your-service.example/paid --read-only + +# the pre-release, 0.8.0-beta.1: wasit run, wasit ci-report and X402-11 +npm install -g @wasit-dev/cli@beta ``` That runs `X402-01` through `X402-05` against your own service. It costs diff --git a/action/action.yml b/action/action.yml index 1f86d84..43bcadf 100644 --- a/action/action.yml +++ b/action/action.yml @@ -1,9 +1,10 @@ name: Wasit description: >- - Runs Wasit's read-only x402 challenge checks against your service inside the - job, comments the result on the pull request, and compares it with main. - Linux runners. Needs Node 22 or later (add actions/setup-node before this - step). The payment tier is not available in this version. + Runs Wasit's x402 checks against your service inside the job, comments the + result on the pull request, and compares it with main. The payment tier pays + on test networks only, on push to the default branch, schedule and + workflow_dispatch. Linux runners. Needs Node 22 or later (add + actions/setup-node before this step). inputs: config: @@ -17,25 +18,56 @@ inputs: tier: description: >- read-only runs the unpaid challenge checks (X402-01 to X402-05): they send - no payment and sign nothing. payment is not available in this version and - is refused. + no payment and sign nothing. payment also runs the payment checks (X402-06 + to X402-11; X402-11 for an endpoint with a reject case, which can add up to + six minutes) on a test network, at most $1.00 a payment and $5.00 a run, on + push to the default branch, schedule and workflow_dispatch only; on a pull + request it runs the read-only checks and says so. Give the payer key in the + env: of this step only, and only to runs that may pay; a key given to a + pull request run is refused before your service starts. required: false default: read-only endpoints: description: Names of the endpoints to run, separated by commas or line breaks. Default is every endpoint of the config. required: false default: "" + mainnet: + description: >- + Refused in this version: the mainnet opt-in is not part of it. true stops + the job with exit 2 before Wasit is installed or your service starts, and + the job summary says so; nothing is sent or signed. The payment tier pays + on test networks only. + required: false + default: "false" runs: using: composite steps: # Each step gets only what it needs, as env. No input and no event value is # written into a run block: they reach the scripts as environment variables. - # The token (GH_TOKEN) is given to the two steps that call gh and to no other, - # and never to the step that starts the service. + # The token (GH_TOKEN) is given to the steps that call gh (the baseline, the + # announcement, the comment and the check run) and to no other, and never to + # the step that starts the service. The env a workflow puts on + # this action reaches every one of its steps: the payer key variables are set + # empty in each step but Run Wasit, the only one that needs a key. + # NODE_OPTIONS is set empty in every step. The workflow's own env (on the + # workflow, the job, or the step that uses this action) reaches every step + # here, and a `--require ` in it would have Node load that file in the + # steps that hold the token or the key. (The runner refuses NODE_OPTIONS + # through GITHUB_ENV: seen on runner 2.338.2, 2026-11-20.) A service Wasit + # starts no longer inherits NODE_OPTIONS from the workflow's env: put the + # options it needs in its service.start command. - name: Check the runner shell: bash + env: + STELLAR_PRIVATE_KEY: "" + EVM_PRIVATE_KEY: "" + SVM_PRIVATE_KEY: "" + MPP_PAYER_SECRET: "" + COMMITMENT_SECRET_HEX: "" + WASIT_MAINNET_PAYER_SECRET: "" + NODE_OPTIONS: "" run: | if [ "$RUNNER_OS" != "Linux" ]; then echo "Wasit: this action runs on Linux runners in this version." >&2 @@ -55,10 +87,18 @@ runs: shell: bash env: ACTION_PATH: ${{ github.action_path }} + STELLAR_PRIVATE_KEY: "" + EVM_PRIVATE_KEY: "" + SVM_PRIVATE_KEY: "" + MPP_PAYER_SECRET: "" + COMMITMENT_SECRET_HEX: "" + WASIT_MAINNET_PAYER_SECRET: "" + NODE_OPTIONS: "" INPUT_CONFIG: ${{ inputs.config }} INPUT_ENVIRONMENT: ${{ inputs.environment }} INPUT_TIER: ${{ inputs.tier }} INPUT_ENDPOINTS: ${{ inputs.endpoints }} + INPUT_MAINNET: ${{ inputs.mainnet }} run: node "$ACTION_PATH/scripts/wasit.mjs" check # Wasit is built from the ref this action was fetched at, with the lockfile @@ -67,6 +107,13 @@ runs: shell: bash env: ACTION_PATH: ${{ github.action_path }} + STELLAR_PRIVATE_KEY: "" + EVM_PRIVATE_KEY: "" + SVM_PRIVATE_KEY: "" + MPP_PAYER_SECRET: "" + COMMITMENT_SECRET_HEX: "" + WASIT_MAINNET_PAYER_SECRET: "" + NODE_OPTIONS: "" run: | cd "$ACTION_PATH/.." npm ci --ignore-scripts --no-audit --no-fund @@ -74,11 +121,39 @@ runs: npm run build -w packages/cli npm run build -w packages/server + # The run's status on the pull request: a check run "Wasit conformance", in + # progress, and on a pull request from this repository a comment that says + # Wasit is running. This step holds the token and never the payer key; Run + # Wasit holds the key and never the token, so the check run is completed at + # the end and not updated check by check. Nothing here fails the job. + - name: Announce the run + id: announce + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + STELLAR_PRIVATE_KEY: "" + EVM_PRIVATE_KEY: "" + SVM_PRIVATE_KEY: "" + MPP_PAYER_SECRET: "" + COMMITMENT_SECRET_HEX: "" + WASIT_MAINNET_PAYER_SECRET: "" + NODE_OPTIONS: "" + GH_TOKEN: ${{ github.token }} + INPUT_ENVIRONMENT: ${{ inputs.environment }} + run: node "$ACTION_PATH/scripts/announce.mjs" start + - name: Find the baseline id: baseline shell: bash env: ACTION_PATH: ${{ github.action_path }} + STELLAR_PRIVATE_KEY: "" + EVM_PRIVATE_KEY: "" + SVM_PRIVATE_KEY: "" + MPP_PAYER_SECRET: "" + COMMITMENT_SECRET_HEX: "" + WASIT_MAINNET_PAYER_SECRET: "" + NODE_OPTIONS: "" GH_TOKEN: ${{ github.token }} run: node "$ACTION_PATH/scripts/baseline.mjs" @@ -89,36 +164,86 @@ runs: shell: bash env: ACTION_PATH: ${{ github.action_path }} + NODE_OPTIONS: "" INPUT_CONFIG: ${{ inputs.config }} INPUT_ENVIRONMENT: ${{ inputs.environment }} INPUT_TIER: ${{ inputs.tier }} INPUT_ENDPOINTS: ${{ inputs.endpoints }} + INPUT_MAINNET: ${{ inputs.mainnet }} BASELINE_PATH: ${{ steps.baseline.outputs.path }} WASIT_BUILD_COMMIT: ${{ github.action_ref }} run: node "$ACTION_PATH/scripts/wasit.mjs" run + # Also when Run Wasit was skipped after the announcement (a cancelled job): the + # report then says no verdict, so "Wasit is running" never stays on the PR. - name: Write the report - if: ${{ always() && steps.run.conclusion != 'skipped' }} + id: report + if: ${{ always() && (steps.run.conclusion != 'skipped' || steps.announce.outcome == 'success') }} shell: bash env: ACTION_PATH: ${{ github.action_path }} + STELLAR_PRIVATE_KEY: "" + EVM_PRIVATE_KEY: "" + SVM_PRIVATE_KEY: "" + MPP_PAYER_SECRET: "" + COMMITMENT_SECRET_HEX: "" + WASIT_MAINNET_PAYER_SECRET: "" + NODE_OPTIONS: "" BASELINE_PATH: ${{ steps.baseline.outputs.path }} + HISTORY_PATH: ${{ steps.baseline.outputs.history }} + BASELINE_RUN: ${{ steps.baseline.outputs.run }} WASIT_BUILD_COMMIT: ${{ github.action_ref }} run: node "$ACTION_PATH/scripts/wasit.mjs" report - name: Comment on the pull request - if: ${{ always() && steps.run.conclusion != 'skipped' && github.event_name == 'pull_request' }} + if: ${{ always() && github.event_name == 'pull_request' && (steps.run.conclusion != 'skipped' || steps.announce.outcome == 'success') }} shell: bash env: ACTION_PATH: ${{ github.action_path }} + STELLAR_PRIVATE_KEY: "" + EVM_PRIVATE_KEY: "" + SVM_PRIVATE_KEY: "" + MPP_PAYER_SECRET: "" + COMMITMENT_SECRET_HEX: "" + WASIT_MAINNET_PAYER_SECRET: "" + NODE_OPTIONS: "" GH_TOKEN: ${{ github.token }} WASIT_COMMENT_FILE: ${{ runner.temp }}/wasit/comment.md run: node "$ACTION_PATH/scripts/comment.mjs" + # Completes the check run the announcement started, with what the report step + # wrote; a fixed neutral text when that step did not succeed. + - name: Finish the check run + if: ${{ always() && steps.announce.outputs.check_run_id != '' }} + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + STELLAR_PRIVATE_KEY: "" + EVM_PRIVATE_KEY: "" + SVM_PRIVATE_KEY: "" + MPP_PAYER_SECRET: "" + COMMITMENT_SECRET_HEX: "" + WASIT_MAINNET_PAYER_SECRET: "" + NODE_OPTIONS: "" + GH_TOKEN: ${{ github.token }} + CHECK_RUN_ID: ${{ steps.announce.outputs.check_run_id }} + REPORT_OUTCOME: ${{ steps.report.outcome }} + WASIT_CHECK_RUN_FILE: ${{ runner.temp }}/wasit/check-run.json + run: node "$ACTION_PATH/scripts/announce.mjs" finish + # Pinned to the commit of v4.6.2 (read from the GitHub API on 2026-11-15). - name: Upload the baseline - if: ${{ always() && steps.run.conclusion != 'skipped' && github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} + if: ${{ always() && steps.run.conclusion != 'skipped' && (github.event_name == 'schedule' || ((github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == format('refs/heads/{0}', github.event.repository.default_branch))) }} uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + # It runs on the events that pay, when the workflow gives the key: blanked here too. + env: + STELLAR_PRIVATE_KEY: "" + EVM_PRIVATE_KEY: "" + SVM_PRIVATE_KEY: "" + MPP_PAYER_SECRET: "" + COMMITMENT_SECRET_HEX: "" + WASIT_MAINNET_PAYER_SECRET: "" + NODE_OPTIONS: "" with: name: wasit-baseline path: ${{ runner.temp }}/wasit/baseline-next.json diff --git a/action/examples/wasit.yml b/action/examples/wasit.yml index 123f675..0d765cf 100644 --- a/action/examples/wasit.yml +++ b/action/examples/wasit.yml @@ -31,6 +31,17 @@ permissions: contents: read pull-requests: write actions: read + # Optional: lets Wasit add its own check, "Wasit conformance", with the result + # of each check. Without it the action works the same and skips that check. + checks: write + +# One Wasit run per pull request: a newer push cancels the older run, so two runs +# never write the pull request's comment over each other. Any other run (a push to +# main, a schedule, a run started by hand) has a group of its own: nothing waits +# for it and nothing cancels it, since a run there may be paying. +concurrency: + group: ${{ github.event_name == 'pull_request' && format('wasit-pr-{0}', github.event.pull_request.number) || format('wasit-run-{0}', github.run_id) }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: wasit: @@ -45,6 +56,22 @@ jobs: with: node-version: 22 + # The payment tier (test networks only, at most $1.00 a payment and $5.00 a + # run) also runs X402-06 to X402-10. It pays on push to main, schedule and + # workflow_dispatch; on a pull request it runs the read-only checks. To use + # it, store a dedicated testnet payer as a repository secret and change this + # step to: + # with: + # config: wasit.config.json + # tier: payment + # env: + # STELLAR_PRIVATE_KEY: ${{ github.event_name != 'pull_request' && secrets.WASIT_TESTNET_PAYER || '' }} + # Give the key on this step only, never in a job-level env: the earlier + # steps of this job (an npm ci with install scripts) would get it too. A key + # given to a pull request run is refused before your service starts. On a + # GitHub-hosted runner your service then runs as a separate user, so it + # cannot read the key from Wasit's process; code that ran earlier in the job + # as the runner's user is not kept from it. - uses: wasit-dev/wasit/action@ with: config: wasit.config.json diff --git a/action/scripts/announce.mjs b/action/scripts/announce.mjs new file mode 100644 index 0000000..7d03117 --- /dev/null +++ b/action/scripts/announce.mjs @@ -0,0 +1,233 @@ +/** + * The run's status on the pull request (Najmi, 2026-11-20): a check run named + * "Wasit conformance", and a comment that says Wasit is running. + * + * - `start`: creates the check run, in progress, on the commit under test, and, + * on a pull request from this repository, writes the running comment: the same + * comment, found by the same marker, that the result replaces at the end. + * - `finish`: completes the check run with the title, summary and conclusion + * that `wasit ci-report --check-run` wrote, and only when the report step + * succeeded; otherwise with a fixed neutral text. + * + * What keeps the key and the token apart: this step holds the job's token and + * never the payer key (the action sets the key variables empty here), and the + * step that runs Wasit and the service holds the key and never the token. So the + * check run is not updated check by check during the run: that would put a + * write token in the run step, beside a service that on a pull request may be + * the author's own code. The job log shows each check as it runs. + * + * A pull request from a fork gets a read-only token, so nothing is tried. No + * failure here fails the job: the job's result is the exit code of `wasit run`. + */ + +import { appendFileSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { renderRunningComment } from "../../packages/core/dist/ci-report.js"; +import { httpStatus, isForkPullRequest, upsertComment } from "./comment.mjs"; +import { REPOSITORY, oneLine, positiveInteger } from "./common.mjs"; +import { realGh } from "./gh.mjs"; + +/** The name the check run shows in the pull request's checks. */ +export const CHECK_NAME = "Wasit conformance"; + +const SHA = /^[0-9a-f]{40}$/; +const SERVER = /^https:\/\/[A-Za-z0-9.-]+(?::[0-9]{1,5})?$/; +const RUN_ID = /^[0-9]{1,20}$/; +const CONCLUSIONS = new Set(["success", "failure", "neutral"]); +/** GitHub's limits on a check run's output. */ +const MAX_TITLE = 255; +const MAX_SUMMARY = 65_535; + +/** What the check run says when there is no report to show, or the report step did not succeed. */ +export const NO_REPORT_OUTPUT = Object.freeze({ + title: "⚠️ no verdict · Wasit wrote no report", + summary: "The run ended before Wasit wrote a report, so nothing was graded. The reason is in the job log.", + conclusion: "neutral", +}); + +/** The run's page, from the three variables GitHub sets; undefined when one has another shape. */ +export function runUrl(env) { + const server = env["GITHUB_SERVER_URL"]; + const repository = env["GITHUB_REPOSITORY"]; + const id = env["GITHUB_RUN_ID"]; + if (typeof server !== "string" || !SERVER.test(server)) return undefined; + if (typeof repository !== "string" || !REPOSITORY.test(repository)) return undefined; + if (typeof id !== "string" || !RUN_ID.test(id)) return undefined; + return `${server}/${repository}/actions/runs/${id}`; +} + +/** The commit under test: the pull request's head on a pull request, else GITHUB_SHA; undefined unless 40 hex characters. */ +export function headSha(env, event) { + const sha = env["GITHUB_EVENT_NAME"] === "pull_request" ? event?.pull_request?.head?.sha : env["GITHUB_SHA"]; + return typeof sha === "string" && SHA.test(sha) ? sha : undefined; +} + +function readEvent(env) { + try { + return JSON.parse(readFileSync(env["GITHUB_EVENT_PATH"] ?? "", "utf-8")); + } catch { + return undefined; + } +} + +function writeOutput(env, name, value) { + const file = env["GITHUB_OUTPUT"]; + if (typeof file === "string" && file !== "") appendFileSync(file, `${name}=${value}\n`); +} + +/** The check run's output from the file the report step wrote: each field checked, cut to GitHub's limits, neutral when unusable. */ +export function checkRunOutput(text) { + if (typeof text !== "string") return { ...NO_REPORT_OUTPUT }; + let value; + try { + value = JSON.parse(text); + } catch { + return { ...NO_REPORT_OUTPUT }; + } + if (value === null || typeof value !== "object" || Array.isArray(value)) return { ...NO_REPORT_OUTPUT }; + return { + title: typeof value.title === "string" && value.title !== "" ? value.title.slice(0, MAX_TITLE) : NO_REPORT_OUTPUT.title, + summary: typeof value.summary === "string" && value.summary !== "" ? value.summary.slice(0, MAX_SUMMARY) : NO_REPORT_OUTPUT.summary, + conclusion: CONCLUSIONS.has(value.conclusion) ? value.conclusion : "neutral", + }; +} + +/** + * The start step: the check run, then the running comment. Always exits 0. + * + * @param {Record} env + * @param {{ gh?: Function, log?: (line: string) => void, now?: () => Date }} deps + */ +export async function start(env = process.env, deps = {}) { + const log = deps.log ?? ((line) => console.log(line)); + const now = deps.now ?? (() => new Date()); + try { + const repository = env["GITHUB_REPOSITORY"]; + if (typeof repository !== "string" || !REPOSITORY.test(repository)) { + log("Wasit warning: no check run and no running comment, the repository is not what a workflow gives."); + return 0; + } + const event = readEvent(env); + const pullRequest = env["GITHUB_EVENT_NAME"] === "pull_request"; + if (pullRequest && isForkPullRequest(event)) { + log("Wasit: this pull request is from a fork, so the token is read-only: no check run and no running comment. The job's own check shows the run."); + return 0; + } + const gh = deps.gh ?? realGh(env); + const url = runUrl(env); + const startedAt = now().toISOString(); + + const sha = headSha(env, event); + if (sha === undefined) { + log("Wasit warning: no check run, the commit under test is not named the way GitHub names it."); + } else { + const input = JSON.stringify({ + name: CHECK_NAME, + head_sha: sha, + status: "in_progress", + started_at: startedAt, + ...(url === undefined ? {} : { details_url: url }), + output: { + title: "Running Wasit", + summary: "Wasit is running. The result replaces this when the run ends; the job log shows each check as it runs.", + }, + }); + const result = await gh(["api", `repos/${repository}/check-runs`, "--method", "POST", "-H", "Content-Type: application/json", "--input", "-"], { + input, + }); + if (result.code !== 0) { + log( + httpStatus(result) === 403 + ? "Wasit: GitHub answered 403 to the check run, so the workflow does not give `checks: write`: there is no Wasit conformance check. The job's own check shows the run." + : `Wasit warning: could not create the check run: ${oneLine(result.stderr || result.stdout || "no answer")}`, + ); + } else { + let id; + try { + id = positiveInteger(JSON.parse(result.stdout)?.id); + } catch { + id = undefined; + } + if (id === undefined) { + log("Wasit warning: GitHub's answer names no check run id, so the check run cannot be completed."); + } else { + writeOutput(env, "check_run_id", String(id)); + log(`Wasit: check run "${CHECK_NAME}" started.`); + } + } + } + + if (pullRequest) { + const environment = env["INPUT_ENVIRONMENT"]; + await upsertComment({ + gh, + repository, + pullNumber: event?.pull_request?.number, + body: renderRunningComment({ + startedAt, + ...(url === undefined ? {} : { runUrl: url }), + ...(typeof environment === "string" && environment !== "" ? { environment } : {}), + }), + log, + }); + } + } catch (error) { + log(`Wasit warning: the start step failed: ${oneLine(error instanceof Error ? error.message : error)}`); + } + return 0; +} + +/** + * The finish step: completes the check run. Always exits 0. + * + * @param {Record} env + * @param {{ gh?: Function, log?: (line: string) => void, now?: () => Date }} deps + */ +export async function finish(env = process.env, deps = {}) { + const log = deps.log ?? ((line) => console.log(line)); + const now = deps.now ?? (() => new Date()); + try { + const repository = env["GITHUB_REPOSITORY"]; + const id = positiveInteger(env["CHECK_RUN_ID"]); + if (typeof repository !== "string" || !REPOSITORY.test(repository) || id === undefined) { + log("Wasit warning: the check run is not completed, the repository or its id is not what a workflow gives."); + return 0; + } + // Only a file the report step wrote is used: if that step did not succeed, a + // file in its place could have been left by anything that ran before it. + let text; + if (env["REPORT_OUTCOME"] === "success") { + try { + text = readFileSync(env["WASIT_CHECK_RUN_FILE"] ?? "", "utf-8"); + } catch { + text = undefined; + } + } + const output = checkRunOutput(text); + const input = JSON.stringify({ + status: "completed", + conclusion: output.conclusion, + completed_at: now().toISOString(), + output: { title: output.title, summary: output.summary }, + }); + const gh = deps.gh ?? realGh(env); + const result = await gh(["api", `repos/${repository}/check-runs/${id}`, "--method", "PATCH", "-H", "Content-Type: application/json", "--input", "-"], { + input, + }); + if (result.code !== 0) { + log(`Wasit warning: could not complete the check run: ${oneLine(result.stderr || result.stdout || "no answer")}`); + } else { + log(`Wasit: check run "${CHECK_NAME}" completed (${output.conclusion}).`); + } + } catch (error) { + log(`Wasit warning: the finish step failed: ${oneLine(error instanceof Error ? error.message : error)}`); + } + return 0; +} + +if (process.argv[1] !== undefined && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) { + const mode = process.argv[2]; + process.exitCode = mode === "start" ? await start(process.env) : mode === "finish" ? await finish(process.env) : 0; +} diff --git a/action/scripts/baseline.mjs b/action/scripts/baseline.mjs index 485d6b0..5bbd01a 100644 --- a/action/scripts/baseline.mjs +++ b/action/scripts/baseline.mjs @@ -1,8 +1,9 @@ /** * Choosing the baseline for a run (spec A5, A8 #4, A-A05). * - * The RUN is chosen first: the latest successful `push` run of this workflow on - * the default branch, from this repository. Only then is that run's + * The RUN is chosen first: the latest successful run of this workflow on the + * default branch, from this repository, started by a push, a schedule or a + * workflow_dispatch. Only then is that run's * `wasit-baseline` artifact downloaded, by run id. Never "the newest artifact * with that name": a pull request run (a fork's too, which runs the fork's copy * of the workflow file) can upload an artifact with that name, and a fork can @@ -30,6 +31,13 @@ export const BASELINE_ARTIFACT = "wasit-baseline"; */ export const ACCEPTED_CONCLUSIONS = Object.freeze(["success"]); +/** + * The events whose runs may be a baseline: those that run merged code on the + * default branch, which are also the only ones where the payment tier pays + * (D-022a). A pull request run, a merge queue run and a workflow_run never are. + */ +export const BASELINE_EVENTS = Object.freeze(["push", "schedule", "workflow_dispatch"]); + const sameName = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase(); /** @@ -37,18 +45,19 @@ const sameName = (a, b) => typeof a === "string" && typeof b === "string" && a.t * * @param {unknown[] | undefined} runs * @param {{ repository: string, defaultBranch: string, workflowId: number, currentRunId: number }} context + * @param {readonly string[]} [conclusions] the conclusions that count; default the green ones */ -export function selectBaselineRun(runs, context) { +export function selectBaselineRun(runs, context, conclusions = ACCEPTED_CONCLUSIONS) { const eligible = (Array.isArray(runs) ? runs : []).filter( (run) => run !== null && typeof run === "object" && Number.isSafeInteger(run.id) && run.id !== context.currentRunId && - run.event === "push" && + BASELINE_EVENTS.includes(run.event) && run.head_branch === context.defaultBranch && run.status === "completed" && - ACCEPTED_CONCLUSIONS.includes(run.conclusion) && + conclusions.includes(run.conclusion) && run.workflow_id === context.workflowId && sameName(run.head_repository?.full_name, context.repository) && sameName(run.repository?.full_name, context.repository), @@ -58,12 +67,22 @@ export function selectBaselineRun(runs, context) { } /** - * Finds and downloads the baseline. + * The conclusions of a run whose history counts (D-022b option 2): every run + * that finished with a verdict, failed ones included, so the recent-failures + * line can count a failure. Not cancelled, skipped or timed out. + */ +export const HISTORY_CONCLUSIONS = Object.freeze(["success", "failure"]); + +/** + * Finds and downloads the baseline (D-022b option 2): the comparison from the + * last green run on the default branch, the history from the newest run there + * that finished, failed or not. Each run is chosen first and its own artifact + * downloaded by run id. When both are the same run it is downloaded once. * - * @param {{ gh: Function, repository: string, runId: number | string, directory: string, defaultBranch?: string, log?: (line: string) => void }} options - * @returns {Promise<{ path?: string }>} the downloaded file, if there is one + * @param {{ gh: Function, repository: string, runId: number | string, directory: string, historyDirectory?: string, defaultBranch?: string, log?: (line: string) => void }} options + * @returns {Promise<{ path?: string, run?: number, history?: string }>} */ -export async function findBaseline({ gh, repository, runId, directory, defaultBranch, log = console.log }) { +export async function findBaseline({ gh, repository, runId, directory, historyDirectory, defaultBranch, log = console.log }) { const none = (reason) => { log(`Wasit: no baseline (${reason}). The comment will say there is nothing to compare with.`); return {}; @@ -81,34 +100,68 @@ export async function findBaseline({ gh, repository, runId, directory, defaultBr const workflowId = positiveInteger((await api(gh, `repos/${repository}/actions/runs/${currentRunId}`)).workflow_id); if (workflowId === undefined) return none("this run does not name its workflow"); - // `status=success` keeps the newest successful runs on the first page of a busy repository. - const conclusion = ACCEPTED_CONCLUSIONS.length === 1 ? `&status=${ACCEPTED_CONCLUSIONS[0]}` : ""; - const listing = await api( - gh, - `repos/${repository}/actions/workflows/${workflowId}/runs?branch=${encodeURIComponent(branch)}&event=push${conclusion}&per_page=50`, - ); - const chosen = selectBaselineRun(listing.workflow_runs, { repository, defaultBranch: branch, workflowId, currentRunId }); - if (chosen === undefined) return none(`no successful push run of this workflow on ${oneLine(branch, 60)} yet`); - - const artifacts = await api(gh, `repos/${repository}/actions/runs/${chosen.id}/artifacts?per_page=100&name=${BASELINE_ARTIFACT}`); - const found = (Array.isArray(artifacts.artifacts) ? artifacts.artifacts : []) - .filter( - (artifact) => - artifact?.name === BASELINE_ARTIFACT && - artifact.expired !== true && - (artifact.workflow_run?.id === undefined || artifact.workflow_run.id === chosen.id), - ) - .sort((a, b) => (Date.parse(b.created_at) || 0) - (Date.parse(a.created_at) || 0))[0]; - if (found === undefined) return none(`run ${chosen.id} has no ${BASELINE_ARTIFACT} artifact, or it has expired`); - - await mkdir(directory, { recursive: true }); - const download = await gh(["run", "download", String(chosen.id), "--repo", repository, "--name", BASELINE_ARTIFACT, "--dir", directory]); - if (download.code !== 0) return none(`the download failed: ${oneLine(download.stderr)}`); - - const files = (await readdir(directory)).filter((name) => name.endsWith(".json")).sort(); - if (files.length === 0) return none("the artifact held no JSON file"); - log(`Wasit: baseline from run ${chosen.id} on ${oneLine(branch, 60)}.`); - return { path: path.join(directory, files[0]) }; + const context = { repository, defaultBranch: branch, workflowId, currentRunId }; + const listed = async (status) => + ( + await api( + gh, + // `status=` keeps the runs wanted on the first page of a busy repository. The API + // takes one event at a time, so the events are filtered here. + `repos/${repository}/actions/workflows/${workflowId}/runs?branch=${encodeURIComponent(branch)}&status=${status}&per_page=50`, + ) + ).workflow_runs; + + /** The run's baseline file, downloaded into `into`, or the reason there is none. */ + const download = async (chosen, into) => { + const artifacts = await api(gh, `repos/${repository}/actions/runs/${chosen.id}/artifacts?per_page=100&name=${BASELINE_ARTIFACT}`); + const found = (Array.isArray(artifacts.artifacts) ? artifacts.artifacts : []) + .filter( + (artifact) => + artifact?.name === BASELINE_ARTIFACT && + artifact.expired !== true && + (artifact.workflow_run?.id === undefined || artifact.workflow_run.id === chosen.id), + ) + .sort((a, b) => (Date.parse(b.created_at) || 0) - (Date.parse(a.created_at) || 0))[0]; + if (found === undefined) return { reason: `run ${chosen.id} has no ${BASELINE_ARTIFACT} artifact, or it has expired` }; + await mkdir(into, { recursive: true }); + const result = await gh(["run", "download", String(chosen.id), "--repo", repository, "--name", BASELINE_ARTIFACT, "--dir", into]); + if (result.code !== 0) return { reason: `the download failed: ${oneLine(result.stderr)}` }; + const files = (await readdir(into)).filter((name) => name.endsWith(".json")).sort(); + if (files.length === 0) return { reason: "the artifact held no JSON file" }; + return { path: path.join(into, files[0]) }; + }; + + const result = {}; + const green = selectBaselineRun(await listed("success"), context); + if (green === undefined) { + log(`Wasit: no baseline (no successful push, schedule or workflow_dispatch run of this workflow on ${oneLine(branch, 60)} yet). The comment will say there is nothing to compare with.`); + } else { + const got = await download(green, directory); + if (got.path === undefined) { + log(`Wasit: no baseline (${got.reason}). The comment will say there is nothing to compare with.`); + } else { + log(`Wasit: baseline from run ${green.id} on ${oneLine(branch, 60)}, the last green run there.`); + result.path = got.path; + result.run = green.id; + } + } + + const finished = selectBaselineRun(await listed("completed"), context, HISTORY_CONCLUSIONS); + if (finished !== undefined) { + if (green !== undefined && finished.id === green.id) { + if (result.path !== undefined) result.history = result.path; + } else { + const got = await download(finished, historyDirectory ?? `${directory}-history`); + if (got.path === undefined) { + log(`Wasit: the history of run ${finished.id} is not used (${got.reason}).`); + } else { + log(`Wasit: history from run ${finished.id} on ${oneLine(branch, 60)}, the newest finished run there.`); + result.history = got.path; + } + } + } + if (result.history === undefined && result.path !== undefined) result.history = result.path; + return result; } catch (error) { return none(oneLine(error instanceof Error ? error.message : error)); } @@ -142,6 +195,7 @@ export async function main(env = process.env, deps = {}) { repository: env["GITHUB_REPOSITORY"], runId: env["GITHUB_RUN_ID"], directory: path.join(temp, "wasit", "baseline"), + historyDirectory: path.join(temp, "wasit", "history"), ...(defaultBranch === undefined ? {} : { defaultBranch }), log, }); @@ -151,7 +205,8 @@ export async function main(env = process.env, deps = {}) { } const output = env["GITHUB_OUTPUT"]; if (typeof output === "string" && output !== "") { - await new Promise((resolve) => appendFile(output, `path=${result.path ?? ""}\n`, () => resolve(undefined))); + const lines = `path=${result.path ?? ""}\nrun=${result.run ?? ""}\nhistory=${result.history ?? ""}\n`; + await new Promise((resolve) => appendFile(output, lines, () => resolve(undefined))); } return 0; } diff --git a/action/scripts/inputs.mjs b/action/scripts/inputs.mjs index 9373304..591d3d0 100644 --- a/action/scripts/inputs.mjs +++ b/action/scripts/inputs.mjs @@ -21,16 +21,48 @@ export class InputError extends Error { } } +/** + * The input asked for mainnet (spec B5). This version has no mainnet opt-in, so + * the input exists only to be refused, before Wasit is installed (spec B12). The + * step that checks the inputs writes this message to the job summary too. + */ +export class MainnetRefusedError extends InputError { + constructor(message) { + super(message); + this.name = "MainnetRefusedError"; + } +} + +/** An event name as GitHub writes them; anything else is never echoed. */ +const EVENT_NAME = /^[a-z_]{1,64}$/; + function trimmed(value) { return typeof value === "string" ? value.trim() : ""; } +/** Refuses `mainnet: true`, always; refuses a value that is not true or false. */ +function checkMainnet(env) { + const value = trimmed(env["INPUT_MAINNET"]).toLowerCase(); + if (value === "" || value === "false") return; + if (value !== "true") throw new InputError("mainnet must be true or false."); + const event = typeof env["GITHUB_EVENT_NAME"] === "string" ? env["GITHUB_EVENT_NAME"] : ""; + const eventRule = + event === "workflow_dispatch" + ? "" + : ` The input is also refused on every event but workflow_dispatch, and this run's event is ${EVENT_NAME.test(event) ? event : "another event"}.`; + throw new MainnetRefusedError( + "mainnet: true is refused: the mainnet opt-in is not part of this version. Wasit pays on test networks only." + + `${eventRule} Nothing was installed, started, sent or signed.`, + ); +} + /** * Reads and checks the inputs from the step's environment (`INPUT_CONFIG`, - * `INPUT_ENVIRONMENT`, `INPUT_TIER`, `INPUT_ENDPOINTS`, and the event name). + * `INPUT_ENVIRONMENT`, `INPUT_TIER`, `INPUT_ENDPOINTS`, `INPUT_MAINNET`, and the + * event name). `mainnet: true` is refused here, so it never reaches the CLI. * * @param {Record} env - * @returns {{ config: string, environment: string | undefined, tier: "read-only", endpoints: string[] }} + * @returns {{ config: string, environment: string | undefined, tier: "read-only" | "payment", endpoints: string[] }} */ export function parseInputs(env) { // pull_request_target hands the base repository's token and secrets to a workflow that runs a pull request's code. @@ -40,9 +72,13 @@ export function parseInputs(env) { ); } + // B12: no mainnet opt-in in this version. Refused before anything else is read. + checkMainnet(env); + + // Whether this event may pay is the CLI's to say (D-022a): on a pull request it runs the + // read-only checks and says so, and it refuses a payer key given to a run that may not pay. const tier = trimmed(env["INPUT_TIER"]) || "read-only"; - if (tier === "payment") throw new InputError("tier: payment is not available in this version. Use tier: read-only."); - if (tier !== "read-only") throw new InputError("tier must be read-only."); + if (tier !== "read-only" && tier !== "payment") throw new InputError("tier must be read-only or payment."); const config = trimmed(env["INPUT_CONFIG"]) || DEFAULT_CONFIG; if (/[\u0000-\u001f\u007f]/.test(config) || config.length > MAX_CONFIG_PATH || config.startsWith("-")) { @@ -67,12 +103,12 @@ export function parseInputs(env) { throw new InputError("each entry of endpoints must be a name: letters, digits, dot, underscore and hyphen, at most 64 characters; separate them with commas or line breaks."); } - return { config, environment: environment === "" ? undefined : environment, tier: "read-only", endpoints }; + return { config, environment: environment === "" ? undefined : environment, tier, endpoints }; } /** - * The one call that runs Wasit: `wasit run --read-only --start-if-local --json --out`: the CLI starts service.start only when it is set and the environment is on this machine. - * No flag that pays, signs or opts into mainnet is offered by this version. + * The one call that runs Wasit: `wasit run [--read-only] --start-if-local --json --out`: the CLI starts service.start only when it is set and the environment is on this machine. + * The payment tier is the same call without --read-only. No flag that opts into mainnet or carries a key is offered. * * @param {ReturnType} inputs * @param {{ cli: string, report: string, baseline?: string }} paths @@ -82,7 +118,7 @@ export function buildRunArgs(inputs, paths) { return [ paths.cli, "run", - "--read-only", + ...(inputs.tier === "payment" ? [] : ["--read-only"]), "--start-if-local", "--json", "--out", @@ -98,7 +134,10 @@ export function buildRunArgs(inputs, paths) { /** * The call that turns the report into the comment, the summary and the next baseline. * - * @param {{ cli: string, report: string, comment: string, baselineOut: string, baseline?: string }} paths + * The history file and the run id (D-022b) come after the baseline; each is left + * out when it is empty. + * + * @param {{ cli: string, report: string, comment: string, baselineOut: string, checkRun?: string, baseline?: string, history?: string, baselineRun?: string }} paths * @returns {string[]} */ export function buildReportArgs(paths) { @@ -111,7 +150,10 @@ export function buildReportArgs(paths) { paths.comment, "--baseline-out", paths.baselineOut, + ...(paths.checkRun === undefined || paths.checkRun === "" ? [] : ["--check-run", paths.checkRun]), ...(paths.baseline === undefined || paths.baseline === "" ? [] : ["--baseline", paths.baseline]), + ...(paths.history === undefined || paths.history === "" ? [] : ["--history", paths.history]), + ...(paths.baselineRun === undefined || paths.baselineRun === "" ? [] : ["--baseline-run", paths.baselineRun]), ]; } diff --git a/action/scripts/wasit.mjs b/action/scripts/wasit.mjs index 772bccf..3646ef1 100644 --- a/action/scripts/wasit.mjs +++ b/action/scripts/wasit.mjs @@ -12,12 +12,12 @@ */ import { spawn } from "node:child_process"; -import { existsSync, mkdirSync, statSync } from "node:fs"; +import { appendFileSync, existsSync, mkdirSync, statSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { InputError, buildReportArgs, buildRunArgs, parseInputs, scrubTokens } from "./inputs.mjs"; +import { InputError, MainnetRefusedError, buildReportArgs, buildRunArgs, parseInputs, scrubTokens } from "./inputs.mjs"; const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"]; @@ -35,9 +35,9 @@ function cliPath(env) { return path.resolve(actionPath, "..", "packages", "cli", "dist", "index.js"); } -/** The baseline file the earlier step downloaded, if it is a file inside the work directory. Anything else is ignored. */ -function baselineFile(env, work) { - const given = env["BASELINE_PATH"]; +/** A file the baseline step downloaded (`BASELINE_PATH`, `HISTORY_PATH`), if it is a file inside the work directory. Anything else is ignored. */ +function baselineFile(env, work, name = "BASELINE_PATH") { + const given = env[name]; if (typeof given !== "string" || given === "") return undefined; const resolved = path.resolve(given); if (!resolved.startsWith(`${work}${path.sep}`)) return undefined; @@ -48,6 +48,17 @@ function baselineFile(env, work) { } } +/** Appends `text` to the job summary, when the runner gives one. A summary that cannot be written is not an error. */ +function writeSummary(env, text) { + const file = env["GITHUB_STEP_SUMMARY"]; + if (typeof file !== "string" || !path.isAbsolute(file)) return; + try { + appendFileSync(file, text); + } catch { + // The refusal is in the log already. + } +} + /** Runs the CLI with `args`, passes signals on to it, and resolves to its exit code. */ function runCli(args, env) { return new Promise((resolve) => { @@ -87,7 +98,11 @@ export async function main(command, env = process.env, io = {}) { report: path.join(work, "report.json"), comment: path.join(work, "comment.md"), baselineOut: path.join(work, "baseline-next.json"), + checkRun: path.join(work, "check-run.json"), baseline: baselineFile(env, work), + history: baselineFile(env, work, "HISTORY_PATH"), + // A run id is digits only; anything else is not passed on. + baselineRun: /^[1-9][0-9]{0,15}$/.test(env["BASELINE_RUN"] ?? "") ? env["BASELINE_RUN"] : undefined, }; const args = command === "run" ? buildRunArgs(parseInputs(env), paths) : buildReportArgs(paths); return await runCli(args, env); @@ -97,6 +112,8 @@ export async function main(command, env = process.env, io = {}) { } catch (error) { if (error instanceof InputError) { stderr(`Wasit: ${error.message}`); + // Spec B5: a run that asked for mainnet says in its summary that it was refused. + if (error instanceof MainnetRefusedError) writeSummary(env, `## Wasit: refused\n\n${error.message}\n`); return 2; } throw error; diff --git a/action/test/action-yaml.test.mjs b/action/test/action-yaml.test.mjs index a658d93..ee43d64 100644 --- a/action/test/action-yaml.test.mjs +++ b/action/test/action-yaml.test.mjs @@ -22,6 +22,7 @@ const read = (file) => readFileSync(path.join(ACTION_DIR, file), "utf-8"); const action = parse(read("action.yml")); const steps = action.runs.steps; +const KEY_NAMES = ["STELLAR_PRIVATE_KEY", "EVM_PRIVATE_KEY", "SVM_PRIVATE_KEY", "MPP_PAYER_SECRET", "COMMITMENT_SECRET_HEX", "WASIT_MAINNET_PAYER_SECRET"]; const stepByName = (name) => { const step = steps.find((candidate) => candidate.name === name); assert.ok(step !== undefined, `a step named ${name}`); @@ -30,19 +31,34 @@ const stepByName = (name) => { const index = (name) => steps.indexOf(stepByName(name)); describe("action.yml", () => { - it("is a composite action with a name, a description and the four inputs", () => { + it("is a composite action with a name, a description and the five inputs", () => { assert.equal(action.runs.using, "composite"); assert.ok(typeof action.name === "string" && action.name.length > 0); assert.ok(typeof action.description === "string" && action.description.length > 0); - assert.deepEqual(Object.keys(action.inputs).sort(), ["config", "endpoints", "environment", "tier"]); + assert.deepEqual(Object.keys(action.inputs).sort(), ["config", "endpoints", "environment", "mainnet", "tier"]); assert.equal(action.inputs.config.default, "wasit.config.json"); assert.equal(action.inputs.tier.default, "read-only"); for (const [name, input] of Object.entries(action.inputs)) assert.ok(typeof input.description === "string" && input.description.length > 0, name); - assert.match(action.inputs.tier.description, /payment.*not available in this version/i); + assert.match(action.inputs.tier.description, /payment/); + assert.match(action.inputs.tier.description, /pull request/); + assert.match(action.inputs.tier.description, /env: of this step/); }); - it("offers no input that pays, signs or opts into mainnet", () => { - assert.ok(!Object.keys(action.inputs).some((name) => /key|secret|mainnet|dry|destructive|payer/i.test(name))); + it("offers no input that carries a key or enables a destructive check", () => { + assert.ok(!Object.keys(action.inputs).some((name) => /key|secret|dry|destructive|payer/i.test(name))); + }); + + it("has one input about mainnet, mainnet, off by default and refused in this version (B12)", () => { + assert.deepEqual(Object.keys(action.inputs).filter((name) => /mainnet|pubnet|optin/i.test(name)), ["mainnet"]); + assert.equal(action.inputs.mainnet.default, "false"); + assert.match(action.inputs.mainnet.description, /^Refused in this version: the mainnet opt-in is not part of it\./); + assert.match(action.inputs.mainnet.description, /exit 2/); + }); + + it("hands the mainnet input to the step that checks the inputs and to the run step, and to no other", () => { + const withIt = steps.filter((step) => step.env?.INPUT_MAINNET !== undefined).map((step) => step.name); + assert.deepEqual(withIt, ["Check the inputs", "Run Wasit"]); + for (const name of withIt) assert.equal(stepByName(name).env.INPUT_MAINNET, "${{ inputs.mainnet }}"); }); it("gives every step a name, and a shell to every step that runs a command", () => { @@ -94,7 +110,12 @@ describe("action.yml", () => { it("is passed as GH_TOKEN, as github.token, to the steps that call gh and to no other", () => { const withToken = steps.filter((step) => step.env !== undefined && Object.keys(step.env).some((key) => /token/i.test(key))); - assert.deepEqual(withToken.map((step) => step.name).sort(), ["Comment on the pull request", "Find the baseline"]); + assert.deepEqual(withToken.map((step) => step.name).sort(), [ + "Announce the run", + "Comment on the pull request", + "Find the baseline", + "Finish the check run", + ]); for (const step of withToken) { assert.deepEqual(Object.keys(step.env).filter((key) => /token/i.test(key)), ["GH_TOKEN"], step.name); assert.equal(step.env.GH_TOKEN, "${{ github.token }}", step.name); @@ -104,14 +125,54 @@ describe("action.yml", () => { it("never reaches the step that runs the service, nor the install, the report or the checks", () => { for (const name of ["Check the runner", "Check the inputs", "Install Wasit", "Run Wasit", "Write the report"]) { const step = stepByName(name); - assert.ok(!JSON.stringify(step).match(/token|secret|password/i), name); + // The payer key variables these steps blank (below) carry no value. + const env = Object.fromEntries(Object.entries(step.env ?? {}).filter(([key, value]) => !(KEY_NAMES.includes(key) && value === ""))); + assert.ok(!JSON.stringify({ ...step, env }).match(/token|secret|password/i), name); } }); it("refers to no secret and no token by any other name", () => { assert.ok(!/secrets\./i.test(text)); assert.ok(!/GITHUB_TOKEN/.test(text)); - assert.equal((text.match(/github\.token/g) ?? []).length, 2); + assert.equal((text.match(/github\.token/g) ?? []).length, 4); + }); + }); + + describe("NODE_OPTIONS (2026-11-20 screening, class B-A10)", () => { + it("is set empty in every step, so a --require in the workflow's env does not run with the token or the key", () => { + for (const step of steps) assert.equal(step.env?.NODE_OPTIONS, "", step.name); + }); + }); + + describe("the running comment is always replaced (2026-11-20 screening)", () => { + it("writes the report and the comment whenever the announcement ran, even if Run Wasit was skipped", () => { + for (const name of ["Write the report", "Comment on the pull request"]) { + const condition = stepByName(name).if ?? ""; + assert.match(condition, /always\(\)/, name); + assert.match(condition, /steps\.announce\.outcome == 'success'/, `${name}: a skipped run would leave "Wasit is running" on the pull request`); + } + }); + }); + + describe("the payer key (screening S-4)", () => { + it("is blanked in every step but the run step, the steps that use another action too (week 2 check F-1)", () => { + const others = steps.filter((step) => step.name !== "Run Wasit"); + assert.equal(others.length, steps.length - 1, "the run step is missing"); + assert.ok(others.some((step) => step.uses !== undefined), "no step that uses another action was checked"); + for (const step of others) { + for (const name of KEY_NAMES) assert.equal(step.env?.[name], "", `${step.name}: ${name}`); + } + }); + + it("reaches the run step as the workflow gives it", () => { + const run = stepByName("Run Wasit"); + for (const name of KEY_NAMES) assert.equal(run.env?.[name], undefined, name); + }); + + it("names exactly the key variables core keeps from the service", () => { + const source = readFileSync(path.join(ACTION_DIR, "..", "packages", "core", "src", "denied-env.ts"), "utf-8"); + const list = source.slice(source.indexOf("DENIED_ENV_NAMES"), source.indexOf("];", source.indexOf("DENIED_ENV_NAMES"))); + assert.deepEqual([...list.matchAll(/"([A-Z0-9_]+)"/g)].map((match) => match[1]), KEY_NAMES); }); }); @@ -179,13 +240,22 @@ describe("action.yml", () => { assert.equal(stepByName("Write the report").env.BASELINE_PATH, "${{ steps.baseline.outputs.path }}"); }); - it("uploads the baseline only on a push to the default branch", () => { + it("uploads the baseline on a push or a dispatch on the default branch, and on a schedule, never on a pull request", () => { const upload = stepByName("Upload the baseline"); assert.match(upload.if, /github\.event_name == 'push'/); + assert.match(upload.if, /github\.event_name == 'workflow_dispatch'/); + assert.match(upload.if, /github\.event_name == 'schedule'/); assert.match(upload.if, /github\.ref == format\('refs\/heads\/\{0\}', github\.event\.repository\.default_branch\)/); + assert.ok(!/pull_request/.test(upload.if)); assert.equal(upload.with.name, "wasit-baseline"); }); + it("hands the report step the history and the run it compares with (D-022b)", () => { + const report = stepByName("Write the report").env; + assert.equal(report.HISTORY_PATH, "${{ steps.baseline.outputs.history }}"); + assert.equal(report.BASELINE_RUN, "${{ steps.baseline.outputs.run }}"); + }); + it("comments only on a pull request", () => { assert.match(stepByName("Comment on the pull request").if, /github\.event_name == 'pull_request'/); }); @@ -214,8 +284,17 @@ describe("the template workflow for builders", () => { const text = read("examples/wasit.yml"); const workflow = parse(text); - it("asks for contents: read, pull-requests: write and actions: read, and nothing else", () => { - assert.deepEqual(workflow.permissions, { contents: "read", "pull-requests": "write", actions: "read" }); + it("asks for contents: read, pull-requests: write, actions: read and the optional checks: write, and nothing else", () => { + assert.deepEqual(workflow.permissions, { contents: "read", "pull-requests": "write", actions: "read", checks: "write" }); + }); + + it("runs one Wasit job per pull request, a newer push cancelling the older run, and never queues or cancels a run on main (2026-11-20)", () => { + assert.equal( + workflow.concurrency?.group, + "${{ github.event_name == 'pull_request' && format('wasit-pr-{0}', github.event.pull_request.number) || format('wasit-run-{0}', github.run_id) }}", + "a run that is not on a pull request has a group of its own, so nothing waits for it and nothing cancels it", + ); + assert.equal(workflow.concurrency?.["cancel-in-progress"], "${{ github.event_name == 'pull_request' }}"); }); it("never uses pull_request_target, not even in a comment that could be copied", () => { diff --git a/action/test/announce.test.mjs b/action/test/announce.test.mjs new file mode 100644 index 0000000..c5f603f --- /dev/null +++ b/action/test/announce.test.mjs @@ -0,0 +1,233 @@ +/** + * The run's status on the pull request (Najmi, 2026-11-20): the check run + * "Wasit conformance" and the running comment. Written before the code. + * + * What the tests hold it to: nothing is tried on a pull request from a fork; the + * check run is created on the commit under test and completed with what the + * report step wrote, and only when that step succeeded; a 403 (no `checks: + * write`) or any failure never fails the step; the running comment carries no + * link but the run's own page and no key; nothing here reads a key. + */ + +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; + +import { COMMENT_MARKER } from "../../packages/core/dist/ci-report.js"; +import { CHECK_NAME, NO_REPORT_OUTPUT, checkRunOutput, finish, headSha, runUrl, start } from "../scripts/announce.mjs"; + +const REPOSITORY = "acme/paywall"; +const HEAD = "a".repeat(40); +const PUSHED = "b".repeat(40); +const CANARY = "SCANARYKEYNEVERPRINTED"; + +function fakeGh(handlers) { + const calls = []; + const gh = async (args, options = {}) => { + calls.push({ args, input: options.input }); + const key = `${args.includes("--method") ? args[args.indexOf("--method") + 1] : "GET"} ${args[1]}`; + for (const [pattern, answer] of handlers) { + if (key.startsWith(pattern)) return typeof answer === "function" ? answer(args, options) : answer; + } + throw new Error(`unexpected gh call: ${key}`); + }; + return { gh, calls }; +} + +const ok = (value) => ({ code: 0, stdout: JSON.stringify(value), stderr: "" }); +const http = (status) => ({ code: 1, stdout: "", stderr: `gh: error (HTTP ${status})` }); +const quiet = () => { + const lines = []; + return { lines, log: (line) => lines.push(line) }; +}; +const NOW = () => new Date("2026-11-20T08:54:10.000Z"); + +describe("announce.mjs", () => { + let dir; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-announce-")); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + async function eventFile(name, value) { + const file = path.join(dir, `${name}.json`); + await writeFile(file, JSON.stringify(value)); + return file; + } + const pullEvent = (headRepo = REPOSITORY) => ({ + repository: { full_name: REPOSITORY }, + pull_request: { number: 7, head: { sha: HEAD, repo: { full_name: headRepo } } }, + }); + + async function env(name, extra = {}, event = pullEvent()) { + const output = path.join(dir, `${name}.output`); + await writeFile(output, ""); + return { + GITHUB_REPOSITORY: REPOSITORY, + GITHUB_EVENT_NAME: "pull_request", + GITHUB_EVENT_PATH: await eventFile(name, event), + GITHUB_SERVER_URL: "https://github.com", + GITHUB_RUN_ID: "123456789", + GITHUB_SHA: PUSHED, + GITHUB_OUTPUT: output, + // The action blanks these in this step; a key here must still never be read or written. + STELLAR_PRIVATE_KEY: CANARY, + ...extra, + }; + } + + describe("start", () => { + it("on a pull request from this repository: creates the check run on the head commit, saves its id, writes the running comment", async () => { + const e = await env("same-repo", { INPUT_ENVIRONMENT: "staging" }); + const { gh, calls } = fakeGh([ + ["POST repos/acme/paywall/check-runs", ok({ id: 4242 })], + ["GET repos/acme/paywall/issues/7/comments", ok([])], + ["POST repos/acme/paywall/issues/7/comments", ok({ id: 1 })], + ]); + const { log } = quiet(); + assert.equal(await start(e, { gh, log, now: NOW }), 0); + const created = JSON.parse(calls[0].input); + assert.equal(created.name, CHECK_NAME); + assert.equal(created.head_sha, HEAD, "the pull request's head, not the merge commit"); + assert.equal(created.status, "in_progress"); + assert.equal(created.details_url, "https://github.com/acme/paywall/actions/runs/123456789"); + assert.equal(await readFile(e.GITHUB_OUTPUT, "utf-8"), "check_run_id=4242\n"); + const body = JSON.parse(calls.at(-1).input).body; + assert.ok(body.startsWith(COMMENT_MARKER)); + assert.match(body, /⏳ \*\*Wasit is running\*\* on staging · started 2026-11-20 08:54 UTC · \[follow the run\]\(https:\/\/github\.com\/acme\/paywall\/actions\/runs\/123456789\)/); + for (const call of calls) assert.ok(!JSON.stringify(call).includes(CANARY), "a key reached GitHub"); + }); + + it("on a pull request from a fork: calls nothing at all", async () => { + const e = await env("fork", {}, pullEvent("someone/paywall")); + const { gh, calls } = fakeGh([]); + const { lines, log } = quiet(); + assert.equal(await start(e, { gh, log, now: NOW }), 0); + assert.equal(calls.length, 0); + assert.match(lines.join("\n"), /from a fork/); + }); + + it("on a push: creates the check run on GITHUB_SHA, and writes no comment", async () => { + const e = await env("push", { GITHUB_EVENT_NAME: "push" }, { repository: { full_name: REPOSITORY } }); + const { gh, calls } = fakeGh([["POST repos/acme/paywall/check-runs", ok({ id: 7 })]]); + assert.equal(await start(e, { gh, log: quiet().log, now: NOW }), 0); + assert.equal(calls.length, 1); + assert.equal(JSON.parse(calls[0].input).head_sha, PUSHED); + }); + + it("without checks: write (a 403): logs it, saves no id, still writes the running comment, and does not fail", async () => { + const e = await env("forbidden"); + const { gh, calls } = fakeGh([ + ["POST repos/acme/paywall/check-runs", http(403)], + ["GET repos/acme/paywall/issues/7/comments", ok([])], + ["POST repos/acme/paywall/issues/7/comments", ok({ id: 1 })], + ]); + const { lines, log } = quiet(); + assert.equal(await start(e, { gh, log, now: NOW }), 0); + assert.match(lines.join("\n"), /checks: write/); + assert.equal(await readFile(e.GITHUB_OUTPUT, "utf-8"), ""); + assert.equal(calls.length, 3); + }); + + it("saves no id GitHub did not give as a whole number, and creates no check run on a commit that is not 40 hex characters", async () => { + const bad = await env("bad-id"); + const { gh } = fakeGh([ + ["POST repos/acme/paywall/check-runs", ok({ id: "1\ncheck_run_id=9" })], + ["GET repos/acme/paywall/issues/7/comments", ok([])], + ["POST repos/acme/paywall/issues/7/comments", ok({ id: 1 })], + ]); + await start(bad, { gh, log: quiet().log, now: NOW }); + assert.equal(await readFile(bad.GITHUB_OUTPUT, "utf-8"), "", "nothing that could add a second output line"); + const sha = await env("bad-sha", {}, { ...pullEvent(), pull_request: { ...pullEvent().pull_request, head: { sha: "HEAD; rm -rf /", repo: { full_name: REPOSITORY } } } }); + const second = fakeGh([ + ["GET repos/acme/paywall/issues/7/comments", ok([])], + ["POST repos/acme/paywall/issues/7/comments", ok({ id: 1 })], + ]); + await start(sha, { gh: second.gh, log: quiet().log, now: NOW }); + assert.ok(!second.calls.some((call) => call.args[1].includes("check-runs"))); + }); + + it("puts no link in the running comment unless the run's page has GitHub's shape, and sanitises the environment", async () => { + const e = await env("hostile", { + GITHUB_SERVER_URL: "javascript:alert(1)//", + INPUT_ENVIRONMENT: "@octocat [x](https://evil.example) ", + }); + const { gh, calls } = fakeGh([ + ["POST repos/acme/paywall/check-runs", ok({ id: 1 })], + ["GET repos/acme/paywall/issues/7/comments", ok([])], + ["POST repos/acme/paywall/issues/7/comments", ok({ id: 1 })], + ]); + await start(e, { gh, log: quiet().log, now: NOW }); + const body = JSON.parse(calls.at(-1).input).body; + assert.ok(!body.includes("follow the run")); + assert.ok(!body.includes("evil.example") && !/@octocat| { + async function finishEnv(name, extra) { + const file = path.join(dir, `${name}.check-run.json`); + return { GITHUB_REPOSITORY: REPOSITORY, CHECK_RUN_ID: "4242", WASIT_CHECK_RUN_FILE: file, REPORT_OUTCOME: "success", ...extra }; + } + + it("completes the check run with the title, summary and conclusion the report step wrote", async () => { + const e = await finishEnv("done"); + await writeFile(e.WASIT_CHECK_RUN_FILE, JSON.stringify({ title: "✅ conformant · 10 passed, 1 skipped", summary: "**Wasit: ✅ conformant.**", conclusion: "success" })); + const { gh, calls } = fakeGh([["PATCH repos/acme/paywall/check-runs/4242", ok({ id: 4242 })]]); + assert.equal(await finish(e, { gh, log: quiet().log, now: NOW }), 0); + const sent = JSON.parse(calls[0].input); + assert.equal(sent.status, "completed"); + assert.equal(sent.conclusion, "success"); + assert.equal(sent.output.title, "✅ conformant · 10 passed, 1 skipped"); + }); + + it("uses no file when the report step did not succeed: a file in its place could be anyone's", async () => { + const e = await finishEnv("planted", { REPORT_OUTCOME: "failure" }); + await writeFile(e.WASIT_CHECK_RUN_FILE, JSON.stringify({ title: "✅ all good [x](https://evil.example)", summary: "@octocat", conclusion: "success" })); + const { gh, calls } = fakeGh([["PATCH repos/acme/paywall/check-runs/4242", ok({})]]); + await finish(e, { gh, log: quiet().log, now: NOW }); + const sent = JSON.parse(calls[0].input); + assert.equal(sent.conclusion, "neutral"); + assert.equal(sent.output.title, NO_REPORT_OUTPUT.title); + assert.ok(!calls[0].input.includes("evil.example")); + }); + + it("is neutral for a missing or broken file, an unknown conclusion, and cuts the title and summary to GitHub's limits", () => { + assert.deepEqual(checkRunOutput(undefined), { ...NO_REPORT_OUTPUT }); + assert.deepEqual(checkRunOutput("not json"), { ...NO_REPORT_OUTPUT }); + assert.equal(checkRunOutput(JSON.stringify({ title: "t", summary: "s", conclusion: "action_required" })).conclusion, "neutral"); + const long = checkRunOutput(JSON.stringify({ title: "t".repeat(400), summary: "s".repeat(70_000), conclusion: "failure" })); + assert.equal(long.title.length, 255); + assert.equal(long.summary.length, 65_535); + assert.equal(long.conclusion, "failure"); + }); + + it("does nothing without a check run id that is a whole number, and never fails the step", async () => { + const { gh, calls } = fakeGh([]); + assert.equal(await finish({ GITHUB_REPOSITORY: REPOSITORY, CHECK_RUN_ID: "1; echo pwned" }, { gh, log: quiet().log, now: NOW }), 0); + assert.equal(calls.length, 0); + const failing = fakeGh([["PATCH repos/acme/paywall/check-runs/5", http(500)]]); + assert.equal(await finish({ GITHUB_REPOSITORY: REPOSITORY, CHECK_RUN_ID: "5" }, { gh: failing.gh, log: quiet().log, now: NOW }), 0); + }); + }); + + describe("the parts it builds from GitHub's variables", () => { + it("builds the run's page only from a GitHub server, an owner/repo and a numeric run id", () => { + assert.equal(runUrl({ GITHUB_SERVER_URL: "https://github.com", GITHUB_REPOSITORY: REPOSITORY, GITHUB_RUN_ID: "42" }), "https://github.com/acme/paywall/actions/runs/42"); + assert.equal(runUrl({ GITHUB_SERVER_URL: "http://github.com", GITHUB_REPOSITORY: REPOSITORY, GITHUB_RUN_ID: "42" }), undefined); + assert.equal(runUrl({ GITHUB_SERVER_URL: "https://github.com", GITHUB_REPOSITORY: "a/b/c", GITHUB_RUN_ID: "42" }), undefined); + assert.equal(runUrl({ GITHUB_SERVER_URL: "https://github.com", GITHUB_REPOSITORY: REPOSITORY, GITHUB_RUN_ID: "42x" }), undefined); + }); + + it("takes the commit under test from the pull request's head on a pull request, else GITHUB_SHA", () => { + assert.equal(headSha({ GITHUB_EVENT_NAME: "pull_request" }, pullEvent()), HEAD); + assert.equal(headSha({ GITHUB_EVENT_NAME: "push", GITHUB_SHA: PUSHED }, {}), PUSHED); + assert.equal(headSha({ GITHUB_EVENT_NAME: "push", GITHUB_SHA: "HEAD" }, {}), undefined); + }); + }); +}); diff --git a/action/test/baseline.test.mjs b/action/test/baseline.test.mjs index 68c2779..300fec2 100644 --- a/action/test/baseline.test.mjs +++ b/action/test/baseline.test.mjs @@ -45,6 +45,13 @@ describe("selectBaselineRun", () => { assert.equal(chosen?.id, 3); }); + it("takes a schedule or a workflow_dispatch run on the default branch as well: the payment tier runs there (D-022a)", () => { + for (const event of ["schedule", "workflow_dispatch"]) { + const chosen = selectBaselineRun([run({ id: 1, created_at: "2026-11-01T00:00:00Z" }), run({ id: 2, event, created_at: "2026-11-12T00:00:00Z" })], CONTEXT); + assert.equal(chosen?.id, 2, event); + } + }); + it("breaks a tie in time by the higher run id", () => { assert.equal(selectBaselineRun([run({ id: 5 }), run({ id: 6 })], CONTEXT)?.id, 6); }); @@ -62,14 +69,14 @@ describe("selectBaselineRun", () => { "a pull request run whose head repository is a fork": run({ ...newer, id: 3, event: "pull_request", head_repository: { full_name: "mallory/paywall" } }), "a push run whose head repository is another one": run({ ...newer, id: 4, head_repository: { full_name: "mallory/paywall" } }), "a run of another repository": run({ ...newer, id: 5, repository: { full_name: "mallory/paywall" } }), - "a workflow_dispatch run": run({ ...newer, id: 6, event: "workflow_dispatch" }), - "a schedule run": run({ ...newer, id: 7, event: "schedule" }), "a run on another branch": run({ ...newer, id: 8, head_branch: "feature" }), "a run on a branch whose name only starts with main": run({ ...newer, id: 9, head_branch: "main-evil" }), "a failed run": run({ ...newer, id: 10, conclusion: "failure" }), "a cancelled run": run({ ...newer, id: 11, conclusion: "cancelled" }), "a run that is not finished": run({ ...newer, id: 12, status: "in_progress", conclusion: null }), "a run of another workflow": run({ ...newer, id: 13, workflow_id: 7 }), + "a merge_group run": run({ ...newer, id: 16, event: "merge_group" }), + "a workflow_run run": run({ ...newer, id: 17, event: "workflow_run" }), "the run that is running now": run({ ...newer, id: 900 }), "a run with no head repository": run({ ...newer, id: 14, head_repository: null }), "a run whose id is not a whole number": run({ ...newer, id: "15; rm -rf /" }), @@ -145,12 +152,12 @@ describe("findBaseline", () => { assert.equal(download[download.indexOf("--name") + 1], BASELINE_ARTIFACT); }); - it("asks the API for push runs of this workflow on the default branch, that succeeded", async () => { + it("asks the API for runs of this workflow on the default branch that succeeded, of any event (it filters the events itself)", async () => { const { gh, calls } = fakeGh({ runs: [] }); await findBaseline({ ...base(), gh, log: () => {} }); const listing = calls.map((args) => args[1]).find((route) => route?.includes("/workflows/")); assert.match(listing, /\/workflows\/4242\/runs\?/); - assert.match(listing, /event=push/); + assert.doesNotMatch(listing, /event=/); assert.match(listing, /branch=main/); assert.match(listing, /status=success/); }); @@ -291,3 +298,90 @@ describe("main, the step as the workflow runs it", () => { assert.equal(await main({}, { gh: async () => ({ code: 1, stdout: "", stderr: "" }), log: () => {} }), 0); }); }); + +// D-022b option 2 (Najmi, 2026-11-16): the comparison comes from the last green +// run on main, the history from the newest completed run on main, failed or not. +// Written before the code. +describe("two lookups: the green run to compare with, the newest finished run for the history", () => { + let dir; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-history-")); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + const input = () => { + const directory = path.join(dir, `d-${Math.random().toString(16).slice(2)}`); + return { repository: REPOSITORY, defaultBranch: "main", runId: 900, directory, historyDirectory: `${directory}-history` }; + }; + + it("takes the history from a newer failed run, and the comparison from the older green one, each by run id", async () => { + const green = run({ id: 200, created_at: "2026-11-10T10:00:00Z" }); + const red = run({ id: 300, conclusion: "failure", created_at: "2026-11-12T10:00:00Z" }); + const { gh, calls } = fakeGh({ runs: [red, green], artifacts: { 200: [artifact(200)], 300: [artifact(300)] } }); + const result = await findBaseline({ ...input(), gh, log: () => {} }); + assert.equal(result.run, 200); + assert.ok(result.path?.endsWith("baseline.json")); + assert.ok(result.history?.endsWith("baseline.json")); + assert.notEqual(path.dirname(result.history), path.dirname(result.path)); + const downloads = calls.filter((args) => args[0] === "run").map((args) => args[2]); + assert.deepEqual(downloads.sort(), ["200", "300"]); + }); + + it("downloads once when the newest finished run is the green one", async () => { + const { gh, calls } = fakeGh({ runs: [run({ id: 200 })], artifacts: { 200: [artifact(200)] } }); + const result = await findBaseline({ ...input(), gh, log: () => {} }); + assert.equal(result.history, result.path); + assert.equal(calls.filter((args) => args[0] === "run").length, 1); + }); + + it("never takes the history from a cancelled run, a pull request run or a run of a fork", async () => { + const green = run({ id: 200, created_at: "2026-11-10T10:00:00Z" }); + const newer = { created_at: "2026-11-14T10:00:00Z" }; + for (const forged of [ + run({ ...newer, id: 301, conclusion: "cancelled" }), + run({ ...newer, id: 302, conclusion: "timed_out" }), + run({ ...newer, id: 303, event: "pull_request", conclusion: "failure" }), + run({ ...newer, id: 304, conclusion: "failure", head_repository: { full_name: "mallory/paywall" } }), + ]) { + const { gh } = fakeGh({ runs: [forged, green], artifacts: { 200: [artifact(200)], [forged.id]: [artifact(forged.id)] } }); + const result = await findBaseline({ ...input(), gh, log: () => {} }); + assert.equal(result.history, result.path, String(forged.id)); + } + }); + + it("asks the API for the completed runs as well as the successful ones", async () => { + const { gh, calls } = fakeGh({ runs: [] }); + await findBaseline({ ...input(), gh, log: () => {} }); + const listings = calls.map((args) => args[1]).filter((route) => route?.includes("/workflows/")); + assert.ok(listings.some((route) => /status=success/.test(route)), listings.join("\n")); + assert.ok(listings.some((route) => /status=completed/.test(route)), listings.join("\n")); + }); + + it("has a history and no comparison when main never passed but did fail", async () => { + const red = run({ id: 300, conclusion: "failure" }); + const { gh } = fakeGh({ runs: [red], artifacts: { 300: [artifact(300)] } }); + const result = await findBaseline({ ...input(), gh, log: () => {} }); + assert.equal(result.path, undefined); + assert.equal(result.run, undefined); + assert.ok(result.history?.endsWith("baseline.json")); + }); + + it("writes path=, run= and history= to the step output", async () => { + const temp = await mkdtemp(path.join(dir, "runner-")); + const environment = { + RUNNER_TEMP: temp, + GITHUB_REPOSITORY: REPOSITORY, + GITHUB_RUN_ID: "900", + GITHUB_OUTPUT: path.join(temp, "output.txt"), + }; + const green = run({ id: 200, created_at: "2026-11-10T10:00:00Z" }); + const red = run({ id: 300, conclusion: "failure", created_at: "2026-11-12T10:00:00Z" }); + const { gh } = fakeGh({ runs: [red, green], artifacts: { 200: [artifact(200)], 300: [artifact(300)] } }); + assert.equal(await main(environment, { gh, log: () => {} }), 0); + const output = (await readFile(environment.GITHUB_OUTPUT, "utf-8")).split("\n"); + assert.ok(output.includes("run=200"), output.join("\n")); + const history = output.find((line) => line.startsWith("history="))?.slice("history=".length) ?? ""; + assert.ok(history.startsWith(path.join(temp, "wasit", "history")), history); + }); +}); diff --git a/action/test/inputs.test.mjs b/action/test/inputs.test.mjs index 326966d..3ee8a25 100644 --- a/action/test/inputs.test.mjs +++ b/action/test/inputs.test.mjs @@ -35,13 +35,76 @@ describe("parseInputs", () => { }); describe("tier", () => { - it("refuses payment: not available in this version", () => { - assert.throws(() => parseInputs(env({ INPUT_TIER: "payment" })), (error) => error instanceof InputError && /not available in this version/.test(error.message)); + it("takes payment, on any event: the CLI decides whether the event may pay (D-022a)", () => { + for (const name of ["push", "pull_request", "schedule", "workflow_dispatch"]) { + assert.equal(parseInputs(env({ INPUT_TIER: "payment", GITHUB_EVENT_NAME: name })).tier, "payment", name); + } + }); + + it("refuses anything that is not read-only or payment, without quoting the value", () => { + for (const tier of ["Payment", "full", "read-only; id", "mainnet", "payment\n"]) { + if (tier.trim() === "payment") continue; + assert.throws( + () => parseInputs(env({ INPUT_TIER: tier })), + (error) => error instanceof InputError && /tier must be read-only or payment/.test(error.message) && !error.message.includes(tier), + tier, + ); + } + }); + }); + + describe("mainnet (spec B5, B12: an input that is refused in this version)", () => { + const SENTENCE = /^mainnet: true is refused: the mainnet opt-in is not part of this version\. Wasit pays on test networks only\./; + + it("is off by default, and takes false", () => { + for (const value of [undefined, "", "false", "False", " false "]) { + assert.deepEqual( + parseInputs(env(value === undefined ? {} : { INPUT_MAINNET: value })), + { config: "wasit.config.json", environment: undefined, tier: "read-only", endpoints: [] }, + String(value), + ); + } + }); + + it("refuses true on every event and every tier, and says nothing was installed, started, sent or signed", () => { + for (const value of ["true", "TRUE", " true "]) { + for (const name of ["push", "pull_request", "schedule", "workflow_dispatch"]) { + for (const tier of ["read-only", "payment"]) { + assert.throws( + () => parseInputs(env({ INPUT_MAINNET: value, GITHUB_EVENT_NAME: name, INPUT_TIER: tier })), + (error) => error instanceof InputError && SENTENCE.test(error.message) && /Nothing was installed, started, sent or signed\.$/.test(error.message), + `${value} ${name} ${tier}`, + ); + } + } + } + }); + + it("adds the workflow_dispatch rule on any other event, and names the event", () => { + for (const name of ["push", "schedule", "pull_request"]) { + assert.throws( + () => parseInputs(env({ INPUT_MAINNET: "true", GITHUB_EVENT_NAME: name })), + (error) => error.message.includes(`The input is also refused on every event but workflow_dispatch, and this run's event is ${name}.`), + name, + ); + } + assert.throws( + () => parseInputs(env({ INPUT_MAINNET: "true", GITHUB_EVENT_NAME: "workflow_dispatch" })), + (error) => SENTENCE.test(error.message) && !/also refused/.test(error.message), + ); + assert.throws( + () => parseInputs(env({ INPUT_MAINNET: "true", GITHUB_EVENT_NAME: "push; id" })), + (error) => !error.message.includes("push; id") && /this run's event is another event\./.test(error.message), + ); }); - it("refuses anything that is not read-only, naming the value as data", () => { - for (const tier of ["Payment", "full", "read-only; id", "mainnet"]) { - assert.throws(() => parseInputs(env({ INPUT_TIER: tier })), InputError, tier); + it("refuses any other value, without quoting it", () => { + for (const value of ["yes", "1", "on", "true; id", "mainnet"]) { + assert.throws( + () => parseInputs(env({ INPUT_MAINNET: value })), + (error) => error instanceof InputError && /^mainnet must be true or false\.$/.test(error.message), + value, + ); } }); }); @@ -95,9 +158,17 @@ describe("buildRunArgs", () => { ]); }); - it("offers no flag that pays, signs or opts in", () => { - const joined = buildRunArgs(parseInputs(env()), paths).join(" "); - assert.ok(!/--dry-run|--mainnet|--payer-key|--commitment-key|--allow-destructive/.test(joined)); + it("offers no flag that opts in or carries a key, on either tier", () => { + for (const tier of ["read-only", "payment"]) { + const joined = buildRunArgs(parseInputs(env({ INPUT_TIER: tier })), paths).join(" "); + assert.ok(!/--dry-run|--mainnet|--payer-key|--commitment-key|--allow-destructive/.test(joined), tier); + } + }); + + it("drops --read-only for the payment tier, and changes nothing else", () => { + const read = buildRunArgs(parseInputs(env()), paths); + const pay = buildRunArgs(parseInputs(env({ INPUT_TIER: "payment" })), paths); + assert.deepEqual(pay, read.filter((arg) => arg !== "--read-only")); }); it("keeps a value that looks like a flag a single argument after its option", () => { @@ -113,6 +184,13 @@ describe("buildReportArgs", () => { assert.deepEqual(buildReportArgs(paths), [paths.cli, "ci-report", "--report", paths.report, "--comment", paths.comment, "--baseline-out", paths.baselineOut]); }); + it("adds --history and --baseline-run when there are, after the baseline (D-022b)", () => { + const args = buildReportArgs({ ...paths, baseline: "/tmp/w/baseline/baseline.json", history: "/tmp/w/history/baseline.json", baselineRun: "200" }); + assert.deepEqual(args.slice(-6), ["--baseline", "/tmp/w/baseline/baseline.json", "--history", "/tmp/w/history/baseline.json", "--baseline-run", "200"]); + const none = buildReportArgs({ ...paths, history: "", baselineRun: "" }); + assert.ok(!none.includes("--history") && !none.includes("--baseline-run")); + }); + it("adds --baseline only when there is one", () => { assert.deepEqual(buildReportArgs({ ...paths, baseline: "/tmp/w/baseline/baseline.json" }).slice(-2), ["--baseline", "/tmp/w/baseline/baseline.json"]); assert.ok(!buildReportArgs({ ...paths, baseline: "" }).includes("--baseline")); diff --git a/action/test/wasit-script.test.mjs b/action/test/wasit-script.test.mjs index dd70c42..8e77084 100644 --- a/action/test/wasit-script.test.mjs +++ b/action/test/wasit-script.test.mjs @@ -49,10 +49,9 @@ describe("wasit.mjs check", () => { assert.ok(existsSync(path.join(temp, "wasit"))); }); - it("refuses the payment tier with the sentence the guide will quote, exit 2", async () => { + it("accepts the payment tier: whether the event may pay is the CLI's to say", async () => { const result = await runMain("check", { ...env(), INPUT_TIER: "payment" }); - assert.equal(result.code, 2); - assert.match(result.stderr, /tier: payment is not available in this version/); + assert.equal(result.code, 0, result.stderr); }); it("refuses pull_request_target, exit 2", async () => { @@ -173,11 +172,13 @@ if (process.env.FAKE_WAIT) { } }); - it("run: refuses the payment tier itself, before it starts the CLI", async () => { + it("run: the payment tier calls the CLI without --read-only, and with no key flag", async () => { await clearRecord(); - const result = await runMain("run", env({ INPUT_TIER: "payment" })); - assert.equal(result.code, 2); - assert.equal((await readFile(record, "utf-8")).trim(), ""); + await runMain("run", env({ INPUT_TIER: "payment" })); + const argv = (await lastCall()).argv; + assert.equal(argv[0], "run"); + assert.ok(!argv.includes("--read-only")); + assert.ok(!argv.some((arg) => /key|secret|mainnet/i.test(arg)), argv.join(" ")); }); it("run: exits 2 when the CLI is not where the action's checkout says (the install did not happen)", async () => { @@ -190,7 +191,17 @@ if (process.env.FAKE_WAIT) { await clearRecord(); await runMain("report", env()); const w = (name) => path.join(temp, "wasit", name); - assert.deepEqual((await lastCall()).argv, ["ci-report", "--report", w("report.json"), "--comment", w("comment.md"), "--baseline-out", w("baseline-next.json")]); + assert.deepEqual((await lastCall()).argv, [ + "ci-report", + "--report", + w("report.json"), + "--comment", + w("comment.md"), + "--baseline-out", + w("baseline-next.json"), + "--check-run", + w("check-run.json"), + ]); }); it("report: adds the baseline when there is one, and gives the CLI no token", async () => { @@ -203,6 +214,28 @@ if (process.env.FAKE_WAIT) { assert.ok(!JSON.stringify(call.env).includes("canary")); }); + it("report: adds the history and the compared run when they are a file under the temp directory and a run id (D-022b)", async () => { + await clearRecord(); + const baseline = path.join(temp, "wasit", "baseline", "baseline.json"); + await writeFile(baseline, "{}"); + await mkdir(path.join(temp, "wasit", "history"), { recursive: true }); + const history = path.join(temp, "wasit", "history", "baseline.json"); + await writeFile(history, "{}"); + await runMain("report", env({ BASELINE_PATH: baseline, HISTORY_PATH: history, BASELINE_RUN: "43724229283" })); + const argv = (await lastCall()).argv; + assert.equal(argv[argv.indexOf("--history") + 1], history); + assert.equal(argv[argv.indexOf("--baseline-run") + 1], "43724229283"); + }); + + it("report: leaves out a history outside the temp directory, and a run id that is not one", async () => { + for (const [HISTORY_PATH, BASELINE_RUN] of [["/etc/passwd", "12; rm"], [path.join(root, "outside.json"), "-1"], ["", ""]]) { + await clearRecord(); + await runMain("report", env({ HISTORY_PATH, BASELINE_RUN })); + const argv = (await lastCall()).argv; + assert.ok(!argv.includes("--history") && !argv.includes("--baseline-run"), `${HISTORY_PATH} ${BASELINE_RUN}`); + } + }); + it("report: returns the exit code of the CLI", async () => { await clearRecord(); assert.equal((await runMain("report", env({ FAKE_EXIT: "2" }))).code, 2); @@ -307,6 +340,13 @@ http.createServer((req, res) => { return { config: `${name}.config.json`, envFile }; } + /** The event file of a push to main, as the runner writes it. */ + async function pushEvent() { + const file = path.join(root, "push-event.json"); + await writeFile(file, JSON.stringify({ ref: "refs/heads/main", repository: { default_branch: "main" } })); + return file; + } + const stepEnv = (extra = {}) => ({ PATH: process.env.PATH, HOME: root, @@ -336,6 +376,9 @@ http.createServer((req, res) => { const env = stepEnv({ INPUT_CONFIG: config, GITHUB_EVENT_NAME: "push", + // A push the payment gate reads as one to the default branch: a key on any other run is refused (D-022a). + GITHUB_REF: "refs/heads/main", + GITHUB_EVENT_PATH: await pushEvent(), GH_TOKEN: "canary-gh-token", GITHUB_TOKEN: "canary-github-token", WASIT_HEADER_X_API_KEY: "canary-header-value", @@ -362,8 +405,8 @@ http.createServer((req, res) => { assert.equal(write.code, 0, write.stderr); const comment = await readFile(path.join(temp, "wasit", "comment.md"), "utf-8"); assert.equal(comment.split("\n")[0], COMMENT_MARKER); - assert.match(comment, /Wasit: conformant/); - assert.match(await readFile(summary, "utf-8"), /Wasit: conformant/, "the job summary was written"); + assert.match(comment, /Wasit: ✅ conformant/); + assert.match(await readFile(summary, "utf-8"), /Wasit: ✅ conformant/, "the job summary was written"); const next = JSON.parse(await readFile(path.join(temp, "wasit", "baseline-next.json"), "utf-8")); assert.equal(next.history.weather["X402-01"], "P"); }); @@ -384,7 +427,7 @@ http.createServer((req, res) => { const write = await runScript("report", env, workspace); assert.equal(write.code, 0, write.stderr); const comment = await readFile(path.join(temp, "wasit", "comment.md"), "utf-8"); - assert.match(comment, /Wasit: regression/); + assert.match(comment, /Wasit: ❌ regression/); assert.match(comment, /Regression: weather was conformant on main and is now unsupported/); }); @@ -419,13 +462,33 @@ http.createServer((req, res) => { assert.equal(write.code, 0, write.stderr); const comment = await readFile(path.join(temp, "wasit", "comment.md"), "utf-8"); assert.equal(comment.split("\n")[0], COMMENT_MARKER, "same marker, so the earlier comment is the one that is replaced"); - assert.match(comment, /Wasit: no verdict\./); - assert.match(await readFile(summary, "utf-8"), /Wasit: no verdict\./, "the job summary says it too"); + assert.match(comment, /Wasit: ⚠️ no verdict\./); + assert.match(await readFile(summary, "utf-8"), /Wasit: ⚠️ no verdict\./, "the job summary says it too"); assert.equal(existsSync(path.join(temp, "wasit", "baseline-next.json")), false, "a run that graded nothing is never a baseline"); }); - it("refuses the payment tier and pull_request_target as a process, exit 2", async () => { - assert.equal((await runScript("check", stepEnv({ INPUT_CONFIG: "x.json", INPUT_TIER: "payment" }), workspace)).code, 2); + it("refuses mainnet: true in the check step, exit 2, and writes the refusal to the job summary (B5: the report says so)", async () => { + await writeFile(summary, ""); + const check = await runScript("check", stepEnv({ INPUT_CONFIG: "x.json", INPUT_MAINNET: "true", GITHUB_EVENT_NAME: "push" }), workspace); + assert.equal(check.code, 2, check.stderr); + assert.match(check.stderr, /^Wasit: mainnet: true is refused: the mainnet opt-in is not part of this version\./); + assert.match(check.stderr, /this run's event is push\./); + const written = await readFile(summary, "utf-8"); + assert.match(written, /^## Wasit: refused\n\nmainnet: true is refused: the mainnet opt-in is not part of this version\./); + assert.match(written, /Nothing was installed, started, sent or signed\./); + }); + + it("refuses mainnet: true in the run step as well, before the CLI runs: no report is written", async () => { + await rm(path.join(temp, "wasit", "report.json"), { force: true }); + const run = await runScript("run", stepEnv({ INPUT_CONFIG: "x.json", INPUT_MAINNET: "true", GITHUB_EVENT_NAME: "workflow_dispatch" }), workspace); + assert.equal(run.code, 2, run.stderr); + assert.match(run.stderr, /mainnet: true is refused/); + assert.equal(existsSync(path.join(temp, "wasit", "report.json")), false, "the CLI ran"); + }); + + it("accepts the payment tier and refuses pull_request_target as a process", async () => { + assert.equal((await runScript("check", stepEnv({ INPUT_CONFIG: "x.json", INPUT_TIER: "payment" }), workspace)).code, 0); assert.equal((await runScript("check", stepEnv({ INPUT_CONFIG: "x.json", GITHUB_EVENT_NAME: "pull_request_target" }), workspace)).code, 2); + assert.equal((await runScript("check", stepEnv({ INPUT_CONFIG: "x.json", INPUT_TIER: "mainnet" }), workspace)).code, 2); }); }); diff --git a/docs/CHECKS.md b/docs/CHECKS.md index fc9c578..964c943 100644 --- a/docs/CHECKS.md +++ b/docs/CHECKS.md @@ -13,7 +13,7 @@ in every test report. | ID | Check Name | Spec Reference | What It Checks | Pass Criteria | |---|---|---|---|---| | `X402-01` | 402 Response Status | x402 spec, HTTP semantics | An unpaid request must be answered with status code `402` | Response status is exactly `402`, not `401`/`403`/other | -| `X402-02` | Payment Header Present | x402 built-on-stellar guide | The 402 response must include a payment header | Either `PAYMENT-REQUIRED` or `X-Payment` header is present (both are checked — the spec itself is not yet consistent, see note in README). An x402 v1 challenge in the response body fails this check, and `X402-03`–`05` still inspect it; see the note on v1 below | +| `X402-02` | Payment Header Present | x402 built-on-stellar guide | The 402 response must include a payment header | Either `PAYMENT-REQUIRED` or `X-Payment` header is present (both are checked — the spec itself is not yet consistent, see note in README). An x402 v1 challenge in the response body is not graded: `X402-02`–`05` are skipped as `unsupported` instead of failing; see the revision note on v1 below | | `X402-03` | Header Payload Decodable | x402 spec §payment-required-object | The header value must be valid base64 that decodes to JSON | `atob()` + `JSON.parse()` succeed without error | | `X402-04` | Required Fields Present | x402 spec §payment-required-object | The payload must include the core payment terms, under the field names its own advertised version requires | Checked in **every** payment option in `accepts`, each reported by its index when the challenge offers more than one; a challenge with no options fails. In each option, every field the advertised `x402Version` requires is present: for v2 `scheme`, `network`, `amount`, `asset`, `payTo` and `maxTimeoutSeconds` (spec 5.1.2); for v1 `scheme`, `network`, `maxAmountRequired`, `asset`, `payTo`, `resource`, `description` and `maxTimeoutSeconds` (v1 spec 5.1). Each is a non-empty string, except `maxTimeoutSeconds`, a positive number of seconds; a field present with the wrong type is reported as such rather than as missing. The price field follows the version: `maxAmountRequired` for v1, `amount` for v2 (renamed in v2, which also moves the resource out of the option). The version is read from the challenge rather than accepting whichever name happens to appear, because a service advertising `x402Version: 2` while emitting the v1 field name is not conformant to the version it claims — and reporting that as a merely absent price would hide the actual defect. An unrecognised version fails: the field names cannot be checked against a version whose schema is unknown. | | `X402-05` | Network Identifier Valid | x402 v2 spec §11.1; CAIP-2 | Every advertised network id is CAIP-2 | Every option's `network` is a CAIP-2 identifier, `namespace:reference` with a 3 to 8 character lowercase namespace and a reference of at most 32 characters, as x402 v2 requires. Where the namespace's own CAIP-2 definition fixes the reference, that is checked too: `stellar` is `testnet` or `pubnet`; `eip155` is the chain id in base 10 (`eip155:84532`, not `eip155:0x14a34`); `solana` is the first 32 characters of the base58 genesis hash. A well-formed id in another namespace passes, and the result says only the format was checked there: x402 v2 asks for CAIP-2 and nothing more, so failing it would report Wasit's own lack of rules as the target's defect. An option without a `network` is left to `X402-04`. | @@ -22,6 +22,7 @@ in every test report. | `X402-08` | Payment Replay Rejected *(negative)* | x402 v2 spec §10.1; `exact` scheme, one-time use | A payment that was already accepted must not be accepted again | The headers `X402-06`'s accepted payment was sent with are sent again, byte for byte, and the target answers with a non-2xx status. Each authorization is single-use: once the payment settles, its EIP-3009 nonce, or its Soroban auth entry's nonce, is spent, or on Solana the transaction has already executed, and the facilitator refuses it, at verify or at settlement: the public facilitator on Base Sepolia lets a replayed EIP-3009 authorization through verify and refuses it at settlement (`settlement failed: invalid_exact_evm_nonce_already_used`, measured 2026-10-06). A 2xx means one payment bought the resource twice. Nothing can settle twice, so this costs nothing. **Skipped** when the challenge advertises the `payment-identifier` extension, under which a server may legitimately answer a repeated payment with its cached response. | | `X402-09` | Underpayment Rejected *(negative)* | `exact` scheme verification: amount | A validly signed payment for less than the advertised amount must be rejected | The payment is signed for half the advertised amount, while its `accepted` still claims the advertised terms, so the signature is valid and only the amount is wrong; the target answers with a non-2xx status. On Stellar the facilitator must hold the transfer to `requirements.amount` exactly; on EVM, verification step 3 holds the authorization's value to it; on Solana the scheme forbids a transfer below it (§1.4), and the reference facilitator's static path requires the exact amount (§3.1). **Skipped** when the price is 1 base unit, since nothing smaller can be offered. A target that accepts may settle the lower amount. | | `X402-10` | Expired Authorization Rejected *(negative)* | x402 v2 spec §10.1 (time constraints); `exact` scheme verification: validity window | A payment whose authorization has expired must be rejected | The payment is signed with a one-second lifetime, which both SDK clients derive from `maxTimeoutSeconds` (EVM `validBefore`, the Stellar auth entry's expiration ledger), held until that has passed (5 seconds on Base Sepolia, 20 on Stellar, three or more ledgers), and sent claiming the advertised terms. On Solana a payment's lifetime is its recent blockhash, which the SDK client does not take from `maxTimeoutSeconds`: the payment is built, through the client's `extra.recentBlockhash` hint, on a blockhash 300 slots old that the RPC confirms is no longer valid, and sent at once. The target answers with a non-2xx status. An expired authorization cannot settle, so a target that serves it serves for nothing. | +| `X402-11` | Rejected Request Not Settled *(negative)* | x402 v2 spec §6.1 (verify, run the resource, settle); Soroban authorization nonces | A valid payment sent with a request the service must refuse must not settle | Runs only with a reject case in `wasit.config.json` (`endpoints[].reject`, read by `wasit run`), after `X402-06` passed, on Stellar. The reject request is the endpoint's request with the reject case's method, headers or body over it. It is first sent without payment: a service that refuses it before asking for payment gives the check nothing to watch, and the check is **skipped** with nothing signed. Otherwise a payment for the advertised terms exactly is signed, through the same plan, pin and caps as the other payment checks, and sent with the reject request. Wasit then reads, once a ledger with `getLedgerEntries`, the nonce entry the Soroban host writes when an authorization is used, in the same call as the nonce of `X402-06`'s payment, which was used and must be found: a read that cannot find it cannot show that the other is absent. A 2xx answer to the reject request fails, whatever the chain shows. Refused and the nonce found: fails, the payment was taken, and the transaction is named. Refused, and a read after the authorization's expiration ledger (decoded from the signed entry, never computed) finds it unused: passes. The payer's balance before and after, and the token's `transfer` events from the payer to `payTo` for the amount (`getEvents`), are second readings: when they disagree with the nonce, or cannot be read, there is no verdict. A payment whose advertised lifetime (`maxTimeoutSeconds`) is at most 300 seconds is waited out, with a hard stop 360 seconds after it was sent (a 300-second lifetime is 60 ledgers of 5 seconds); still valid then, the check is **skipped**: "not settled by ledger N; still valid until ledger M". A lifetime above 300 seconds or below 30 seconds (too short for an unused authorization to show anything), on the first read or on the read the payment is signed from, is **skipped** before anything is signed; an authorization the client signs to stay valid longer than 300 seconds, or with fewer than 3 ledgers left when it would be sent, is discarded unsent, with no verdict. On other chains the check is skipped and nothing is signed. A service that settles a refused request takes the payment: at most the price, once. *(New in 0.8.0-beta.1.)* | **Note on the x402 payment checks' cost (Week 2).** `X402-06` and `X402-07` are not free. `X402-06` settles a real payment against the target, and `X402-07` @@ -72,7 +73,29 @@ any challenge the payment client cannot read. Before 0.5.0 both reported FAIL in that case, contradicting the `X402-07` row above, and a v1 challenge left `X402-03`–`05` skipped. -**Note on networks (0.7.0).** `X402-01`–`05` read the challenge only, so they +**Revision note, `X402-02` (0.8.0-beta.1).** The note above describes +0.5.0 to 0.7.0. A challenge in the response body is no longer an `X402-02` FAIL. +Wasit grades x402 v2, so a v1 service is reported as **unsupported**, which is +neither a failure nor a pass: `X402-01` keeps its verdict, and `X402-02`–`05` +are SKIP results with the reason and `skipKind: "unsupported"` (the field +carries the kind in `--json` and MCP output; the four statuses are unchanged). +What `X402-04` and `X402-05` used to report as verdicts on the v1 terms stays +visible in the skip's detail, labelled as a note, so an operator still sees +which terms diverge. The same kind is used for the payment checks when the run +names a network no payment adapter pays on (for example `eip155:97`): +`X402-06`–`11` are skipped as `unsupported`, where 0.7.0 stopped with a +`PREFLIGHT` error. The run still exits 2 ("no verdict"): payment checks were +asked for and none could be graded, so it is not green. `stellar:pubnet` is not that case: it has an adapter and +the network guard still refuses it before anything is signed. For the read +checks (`X402-01`–`05`), a route that redirects to another origin gives `X402-01` +no verdict (`ERROR (configuration)`) and nothing is sent there; a redirect inside +the origin is followed once. A paid request (`X402-06`–`11`) and every MPP +request follow no redirect at all: a 3xx gives that check no verdict, and the +payment is not sent again. + +**Note on networks (0.7.0).** In 0.8.0-beta.1 the payment checks pay on test +networks only: `stellar:pubnet` and any other network are refused before a key +is read (see the revision note above). In 0.7.0: `X402-01`–`05` read the challenge only, so they apply to an x402 service on any chain. The payment checks pay through the `exact` scheme on the network the run names: `stellar:testnet` (the default), `stellar:pubnet`, `eip155:84532` (Base Sepolia, with the EIP-3009 or Permit2 @@ -244,9 +267,10 @@ implementation, it links the write-up. ### There is no payment header (`X402-02`) x402 v2 carries the challenge base64-encoded in the `PAYMENT-REQUIRED` response -header. A service that puts an x402 v1 challenge in the response body fails -here, and the result says it found one; its terms are still checked. The -`exact` scheme on Stellar is defined for v2 only. This is the divergence Wasit +header. A service that puts an x402 v1 challenge in the response body is +reported as unsupported (not a failure; see the revision note above), and the +result says it found one; the v1 terms are shown as notes. The `exact` scheme on +Stellar is defined for v2 only. This is the divergence Wasit has met in a real implementation ([conformance findings](findings/conformance-findings.md), class 1). @@ -388,7 +412,7 @@ The official x402 client, which Wasit pays through, refuses a price above $1 and outside the SDK's defaults (Circle's USDC on Ethereum Sepolia is allowed too). Such a target gets `ERROR (setup)` saying which, and nothing is sent: the cap keeps a paywall from charging a payer more than it meant to, and Wasit pays automatically, on -`stellar:pubnet` with real money +`stellar:pubnet` with real money in 0.7.0 (0.8.0-beta.1 refuses that network) ([evidence](evidence/2026-10-06-0.7.0-verification-runs.md#part-2-the-clients-spend-controls)). On Stellar, the payment checks need a testnet payer holding testnet USDC. diff --git a/package-lock.json b/package-lock.json index 17fc253..86cfc19 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5567,10 +5567,10 @@ }, "packages/cli": { "name": "@wasit-dev/cli", - "version": "0.7.0", + "version": "0.8.0-beta.1", "license": "Apache-2.0", "dependencies": { - "@wasit-dev/core": "^0.7.0", + "@wasit-dev/core": "^0.8.0-beta.1", "cfonts": "^3.3.1", "commander": "^15.0.0", "dotenv": "^17.4.2", @@ -5594,7 +5594,7 @@ }, "packages/core": { "name": "@wasit-dev/core", - "version": "0.7.0", + "version": "0.8.0-beta.1", "license": "Apache-2.0", "dependencies": { "@solana/kit": "^5.5.1", @@ -6600,11 +6600,11 @@ }, "packages/server": { "name": "@wasit-dev/server", - "version": "0.7.0", + "version": "0.8.0-beta.1", "license": "Apache-2.0", "dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", - "@wasit-dev/core": "^0.7.0", + "@wasit-dev/core": "^0.8.0-beta.1", "zod": "^4.4.3" }, "bin": { diff --git a/packages/cli/README.md b/packages/cli/README.md index d906350..a78569a 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -6,7 +6,9 @@ Protocol-compliance testing for **x402** and **MPP** on Stellar, from your termi 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. -**Testnet only.** Several checks settle real transactions — do not point this at pubnet or use production keys. +**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. + +**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. ## Install @@ -48,7 +50,7 @@ wasit test --target [options] | Option | Default | Notes | |---|---|---| | `--target ` | required | Must include the scheme | -| `--network ` | `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 | +| `--network ` | `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 | | `--payer-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) | | `--rpc-url ` | testnet default | Soroban RPC used to verify `X402-06`'s settlement | | `--method ` | `GET` | HTTP method the paid endpoint uses | @@ -56,7 +58,7 @@ wasit test --target [options] | `--header ` | — | Extra request header, repeatable | | `--read-only` | off | Restricts the run to `X402-01`–`05` (no payment) | -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. +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. ### `wasit mpp-charge` — MPP, charge mode @@ -68,8 +70,8 @@ wasit mpp-charge --target [options] |---|---|---| | `--target ` | required | The paid resource | | `--payer-key ` | `MPP_PAYER_SECRET` | Secret key, `S...` | -| `--network ` | `MPP_STELLAR_NETWORK` | CAIP-2. Only a challenge on this network is paid | -| `--rpc-url ` | testnet default | Used for the payment and the settlement read; https only. Required for pubnet | +| `--network ` | `MPP_STELLAR_NETWORK` | CAIP-2. Only a challenge on this network is paid; `stellar:testnet` only, any other network is refused | +| `--rpc-url ` | testnet default | Used for the payment and the settlement read; https only | **Every run settles a real payment.** Charge mode has no dry run — a settlement that never happened cannot be verified on-chain. @@ -97,6 +99,28 @@ wasit mpp-channel --target [options] `--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. +### `wasit run`: a whole service from `wasit.config.json` (new in 0.8.0-beta.1) + +```bash +wasit run --read-only --start # the free checks, X402-01 to 05, with the service started from the config +wasit run --dry-run --start # what the payment checks would sign; no key, nothing sent +wasit run --start # the payment tier, on a test network +``` + +`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`). + +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. + +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. + +### `wasit ci-report`: the pull request comment and the job summary (new in 0.8.0-beta.1) + +```bash +wasit ci-report --report wasit-report.json --comment comment.md +``` + +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 ` 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. + ### `wasit checks` — the catalogue ```bash @@ -154,6 +178,8 @@ SKIP X402-02 Payment Header Present 7 passed. ``` +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. + `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. ## Exit codes @@ -184,7 +210,7 @@ All keys are **testnet only**. `wasit` also reads a `.env` file in the current w ## What's checked -Sixteen 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). +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). ## Related diff --git a/packages/cli/package.json b/packages/cli/package.json index 351f5b1..ec0d7ab 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@wasit-dev/cli", - "version": "0.7.0", + "version": "0.8.0-beta.1", "description": "CLI for x402/MPP protocol-conformance testing on Stellar — verifies a service's payment flow settles on-chain per spec.", "type": "module", "bin": { @@ -41,7 +41,7 @@ "typecheck": "tsc -p test/tsconfig.json" }, "dependencies": { - "@wasit-dev/core": "^0.7.0", + "@wasit-dev/core": "^0.8.0-beta.1", "cfonts": "^3.3.1", "commander": "^15.0.0", "dotenv": "^17.4.2", diff --git a/packages/cli/src/ci-report-command.ts b/packages/cli/src/ci-report-command.ts index 1a36fc9..3e3aaa2 100644 --- a/packages/cli/src/ci-report-command.ts +++ b/packages/cli/src/ci-report-command.ts @@ -16,12 +16,15 @@ import { appendFileSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { MAX_BASELINE_BYTES, ReportFormatError, + baselineProblem, deniedEnvValues, parseRunReport, readBaseline, readBuildCommit, readToolVersions, + renderCheckRun, renderComment, + renderNoReportCheckRun, renderNoReportComment, renderNoReportSummary, renderSummary, @@ -30,6 +33,7 @@ import { serializeBaseline, updateHistory, type BaselineResult, + type History, type RunReport, } from "@wasit-dev/core"; @@ -44,8 +48,18 @@ export interface CiReportOptions { readonly comment: string; /** The job summary file, appended to. Default: `$GITHUB_STEP_SUMMARY`, if set. */ readonly summary?: string; - /** Where the next baseline goes: the report with its history. The caller uploads it on a push to the default branch. */ + /** Where the next baseline goes: the report with its history. The caller uploads it on a run on the default branch. */ readonly baselineOut?: string; + /** + * The baseline file of the newest completed run on the default branch, failed + * or not (D-022b): its history is the one the recent-failures line counts and + * the next baseline carries on. Absent or unusable: the baseline's own. + */ + readonly history?: string; + /** The id of the run the baseline came from, named in the comment. Only a whole number above 0 is used. */ + readonly baselineRun?: string; + /** Where the check run's title, summary and conclusion go, as JSON, for the step that completes it. */ + readonly checkRun?: string; } export interface CiReportContext { @@ -87,6 +101,10 @@ export async function executeCiReport(options: CiReportOptions, context: CiRepor appendFileSync(summary, renderNoReportSummary(versions)); context.stdout(`Appended the summary to ${summary}`); } + if (options.checkRun !== undefined) { + writeFileSync(options.checkRun, JSON.stringify(renderNoReportCheckRun(versions))); + context.stdout(`Wrote ${options.checkRun}`); + } } catch (error) { const errno = (error as NodeJS.ErrnoException).code; return fail(`wasit ci-report: cannot write a file${typeof errno === "string" ? ` (${errno})` : ""}`); @@ -109,10 +127,32 @@ export async function executeCiReport(options: CiReportOptions, context: CiRepor } const selected = selectBaseline(report, options.baseline === undefined ? undefined : readBaselineFile(options.baseline)); + + // D-022b: the history of every completed run on main, when the newest one is given. + let history: History | undefined = selected.baseline?.history; + let historyGiven = false; + if (options.history !== undefined) { + const read = readBaselineFile(options.history); + const problem = read.ok ? baselineProblem(report, read.baseline.report) : read.reason; + if (read.ok && problem === undefined) { + history = read.baseline.history; + historyGiven = true; + } else { + context.stderr( + sanitizeText(`wasit ci-report: the history file is not used (${problem ?? "unknown"}); the history of the baseline is used`, { + redact: secrets, + }), + ); + } + } + const run = options.baselineRun !== undefined && /^[1-9][0-9]{0,15}$/.test(options.baselineRun) ? Number(options.baselineRun) : undefined; + const input = { report, ...(selected.baseline === undefined ? {} : { baseline: selected.baseline }), ...(selected.note === undefined ? {} : { baselineNote: selected.note }), + ...(run === undefined || !Number.isSafeInteger(run) ? {} : { baselineRun: run }), + ...(historyGiven && history !== undefined ? { history } : {}), secrets, }; @@ -127,9 +167,14 @@ export async function executeCiReport(options: CiReportOptions, context: CiRepor } if (options.baselineOut !== undefined) { - writeFileSync(options.baselineOut, serializeBaseline(report, updateHistory(selected.baseline?.history, report))); + writeFileSync(options.baselineOut, serializeBaseline(report, updateHistory(history, report))); context.stdout(`Wrote ${options.baselineOut}`); } + + if (options.checkRun !== undefined) { + writeFileSync(options.checkRun, JSON.stringify(renderCheckRun(input))); + context.stdout(`Wrote ${options.checkRun}`); + } } catch (error) { const code = (error as NodeJS.ErrnoException).code; return fail(`wasit ci-report: cannot write a file${typeof code === "string" ? ` (${code})` : ""}`); diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 70e172d..db71aa3 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -16,12 +16,18 @@ import { type ServeMode, } from "./serve.js"; import { executeCiReport } from "./ci-report-command.js"; -import { note, report } from "./output.js"; +import { exitCodeFor, note, report, verdictNotes } from "./output.js"; +import { LiveReport } from "./live.js"; +import { colorDepth, colorEnabled, lineWidth, liveEnabled, styler } from "./style.js"; import { executeRun } from "./run.js"; import { CHECK_CATALOGUE, PROTOCOL_IDS, + X402_PAYMENT_CHECK_IDS, + catalogueEntry, deniedEnvValues, + endpointOutcome, + networkClass, paymentChainFor, runMppChannelSuite, runMppChargeSuite, @@ -210,7 +216,7 @@ program "Extra request header the endpoint needs before it will issue a challenge. Repeatable.", collectHeader, ) - .option("--read-only", "Skip the payment checks (X402-06..10)", false) + .option("--read-only", "Skip the payment checks (X402-06..11)", false) .option("--json", "Print results as JSON instead of formatted text", false) .addHelpText( "after", @@ -224,7 +230,13 @@ X402-01..05 (challenge/header checks) always run and cost nothing. X402-06..10 (real payment checks) run only when a payer key is available and --read-only is not set: X402-06 settles a payment; X402-07..10 send payments the target must refuse (a corrupted signature, a replay, an underpayment, an expired -authorization). See docs/CHECKS.md for what each check ID verifies.`, +authorization). X402-11 needs a request the service must refuse, the reject case +of a wasit.config.json endpoint: it runs in wasit run and is skipped here. See +docs/CHECKS.md for what each check ID verifies. + +At a terminal the output is coloured and live: each check shows while it runs, +with its duration, and the run's duration comes at the end. A pipe, CI, --json +or NO_COLOR gives the plain text; FORCE_COLOR=1 colours a pipe.`, ) .action(async (opts) => { const jsonMode = opts.json === true; @@ -234,6 +246,12 @@ authorization). See docs/CHECKS.md for what each check ID verifies.`, ...(opts.header ? { headers: opts.header as Record } : {}), }; + // A person at a terminal gets the coloured, live output; a pipe, CI, NO_COLOR + // and --json get the plain text below, unchanged. + if (!jsonMode && colorEnabled(process.stdout, process.env)) { + process.exit(await liveX402Test(opts, shape)); + } + const results = await runX402ReadChecks({ target: opts.target, ...shape }); // Each chain reads its own payer key: a Stellar secret is no use on EVM. const keyEnv = paymentChainFor(opts.network as string)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY"; @@ -269,7 +287,7 @@ authorization). See docs/CHECKS.md for what each check ID verifies.`, program .command("run") - .description("Run the endpoints of a wasit.config.json and write one report (read-only in this version)") + .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") .option("--config ", "The config file", "wasit.config.json") .option("--env ", "The environment to run (default: defaultEnvironment, else the only one)") .option( @@ -280,7 +298,14 @@ program ) .option( "--read-only", - "Run the unpaid challenge checks (X402-01..05). They send no payment and sign nothing. The only tier in this version, so it is required.", + "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, + ) + .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, " + + "against the caps ($1 a payment, $5 a run, lower with maxRunUsd). Reads each x402 endpoint's unpaid challenge; " + + "uses no key, sends no payment, signs nothing. Exit 2 when a paying run would be refused. Not with --read-only.", false, ) .option("--json", "Print the report as JSON instead of text", false) @@ -301,6 +326,11 @@ program "--baseline ", "The report of the default branch: an endpoint graded there that is unsupported or without a verdict now is a regression (exit 1)", ) + .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, + ) .addHelpText( "after", ` @@ -309,10 +339,24 @@ Examples: $ wasit run --read-only --env staging --endpoint weather --json --out wasit-report.json $ wasit run --read-only --start $ wasit run --read-only --start-if-local --env mainnet + $ wasit run --dry-run --start + $ wasit run --start (payment tier: STELLAR_PRIVATE_KEY on stellar:testnet) Exit codes: 0 every graded endpoint conforms; 1 an endpoint does not conform, or one graded on the baseline is not graded now; 2 no verdict (nothing could be graded, a -check could not run, the config or the service could not be used). +check could not run, the config or the service could not be used, or the payment +tier was asked for and did not pay: no payer key, or operatedByMe not true). +The payment tier pays on test networks only: at most $1.00 a payment and $5.00 a run +(lower with maxRunUsd), only the pinned payTo and asset when the config pins them. +In GitHub Actions it pays only on push to the default branch, schedule and +workflow_dispatch; a pull request runs the read-only checks, and a payer key set on +a run that may not pay is refused before the service starts. In another CI (CI set, +not GitHub Actions) the payment tier is refused with exit 2: use --read-only there, +with no payer key in the job. +X402-11 runs for an endpoint with a reject case, on Stellar: it sends a valid payment +with the request the service must refuse, then reads the chain until that payment's +authorization has expired, up to six minutes; a lifetime above 300 s or below 30 s is +not signed, and an authorization signed to outlive 300 s is not sent. In CI (CI or GITHUB_ACTIONS set) a .env file in the working directory is not read.`, ) .exitOverride(exitTwoOnUsageError) @@ -325,11 +369,13 @@ In CI (CI or GITHUB_ACTIONS set) a .env file in the working directory is not rea ...(opts.env === undefined ? {} : { env: opts.env as string }), endpoint: opts.endpoint as string[], readOnly: opts.readOnly === true, + dryRun: opts.dryRun === true, json: opts.json === true, ...(opts.out === undefined ? {} : { out: opts.out as string }), start: opts.start === true, startIfLocal: opts.startIfLocal === true, ...(opts.baseline === undefined ? {} : { baseline: opts.baseline as string }), + mainnet: opts.mainnet === true, }, { env: process.env, stdout: (line) => console.log(line), stderr: (line) => console.error(line) }, ); @@ -351,8 +397,14 @@ program .option("--summary ", "The job summary file, appended to (default: $GITHUB_STEP_SUMMARY)") .option( "--baseline-out ", - "Write the next baseline here: this report with its history. For a push to the default branch.", + "Write the next baseline here: this report with its history. For a run on the default branch.", + ) + .option( + "--history ", + "The baseline file of the newest completed run on the default branch, failed or not: the recent failures are counted from its history", ) + .option("--baseline-run ", "The id of the run the baseline came from, named in the comment") + .option("--check-run ", "Write the check run's title, summary and conclusion here, as JSON") .exitOverride(exitTwoOnUsageError) .action(async (opts) => { let code: number; @@ -364,6 +416,9 @@ program comment: opts.comment as string, ...(opts.summary === undefined ? {} : { summary: opts.summary as string }), ...(opts.baselineOut === undefined ? {} : { baselineOut: opts.baselineOut as string }), + ...(opts.history === undefined ? {} : { history: opts.history as string }), + ...(opts.baselineRun === undefined ? {} : { baselineRun: opts.baselineRun as string }), + ...(opts.checkRun === undefined ? {} : { checkRun: opts.checkRun as string }), }, { env: process.env, stdout: (line) => console.log(line), stderr: (line) => console.error(line) }, ); @@ -532,8 +587,92 @@ that channel.`, }, }); - process.exit(report(results, jsonMode)); + process.exit(report(results, jsonMode, terminalStyle(jsonMode))); + }); + + +/** Colours for the MPP commands' text output, when a person is at the terminal. */ +function terminalStyle(jsonMode: boolean): { style: ReturnType; width: number } { + return { + style: styler(!jsonMode && colorEnabled(process.stdout, process.env), colorDepth(process.env)), + width: lineWidth(process.stdout), + }; +} + +/** + * `wasit test` for a person at a terminal: the same checks, notes and exit code + * as the plain output, drawn live (a RUNNING line with a timer while a check is + * in flight, each result as it arrives, the counts and the duration at the end). + */ +async function liveX402Test( + opts: Record, + shape: { method?: string; body?: string; headers?: Record }, +): Promise { + const secrets = deniedEnvValues(process.env); + const live = new LiveReport({ + stream: process.stdout, + live: liveEnabled(process.stdout, process.env), + depth: colorDepth(process.env), + clean: (text) => sanitizeText(text, { redact: secrets }), }); + const target = opts["target"] as string; + const network = opts["network"] as string; + live.header(CLI_VERSION, "x402 conformance", [ + ["target", `${target}${shape.method !== undefined ? ` ${shape.method.toUpperCase()}` : ""}`], + ["network", network], + ]); + + live.phase("challenge", [["no payment"]]); + live.running("X402-01..05", "Challenge checks"); + const results = await runX402ReadChecks({ target, ...shape, onResult: (result) => live.result(result) }); + live.gap(); + + const keyEnv = paymentChainFor(network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY"; + const payerKey = (opts["payerKey"] as string | undefined) ?? process.env[keyEnv]; + if (opts["readOnly"] === true) { + live.phase("payment", [["not run"]]); + live.note("--read-only set: the payment checks were not run."); + } else if (!payerKey) { + live.phase("payment", [["not run"]]); + live.note(`No payer key: set ${keyEnv} in .env or pass --payer-key. The payment checks were not run.`); + } else if (networkClass(network) !== "test") { + // Not a test network: the guard refuses the payment checks before anything + // is signed (the PREFLIGHT line says why), so no money moves. + live.phase("payment", [[network], ["not a test network: refused", "danger"]]); + } else { + live.phase("payment", [[network], ["testnet funds move", "warning"]]); + live.note( + `When the target offers a ${network} option, X402-06 settles a real payment and X402-07..10 send ` + + "payments it must refuse.", + ); + } + if (opts["readOnly"] !== true && payerKey) { + const order = X402_PAYMENT_CHECK_IDS; + const startAt = (index: number): void => { + const id = order[index]; + if (id !== undefined) live.running(id, catalogueEntry(id)?.name ?? id); + }; + startAt(0); + results.push( + ...(await runX402PaymentChecks({ + target, + network, + payerSecretKey: payerKey, + ...(opts["rpcUrl"] ? { rpcUrl: opts["rpcUrl"] as string } : {}), + ...shape, + onResult: (result) => { + live.result(result); + const index = order.indexOf(result.id); + if (index >= 0) startAt(index + 1); + }, + onProgress: (line) => live.progress(line), + })), + ); + } + + live.finish(results, endpointOutcome(results, "x402"), verdictNotes(results, "x402")); + return exitCodeFor(results, "x402"); +} program .command("mpp-charge") @@ -577,7 +716,7 @@ a real payment and moves testnet funds, because charge mode has no dry run.`, ...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}), }); - process.exit(report(results, jsonMode)); + process.exit(report(results, jsonMode, terminalStyle(jsonMode))); }); registerWalletCommand(program); diff --git a/packages/cli/src/live.ts b/packages/cli/src/live.ts new file mode 100644 index 0000000..1d87d4e --- /dev/null +++ b/packages/cli/src/live.ts @@ -0,0 +1,302 @@ +/** + * The coloured, live text output of a check run (Najmi, 2026-11-19), in + * Wasit's own look: a header, the checks in two blocks (challenge, payment), + * one line per check with its mark (✓ pass, ✗ fail, ○ skip, ! error) and its + * duration flush right, a spinner line saying what the check in flight is doing, + * and the verdict, the counts and the run's duration at the end. + * + * It only arranges what the plain output says: the same checks, details, fixes + * and notes, in the same order. It is used only when colour is on + * (`colorEnabled`); `live` adds the spinner line, rewritten in place, on a real + * terminal. That line is cut to the terminal's width so it never wraps: a + * wrapped line cannot be rewritten in place. Every text passes through `clean` + * (the sanitiser, with the secrets redacted) before it is styled. + */ + +import { checkStatus, fixFor, summarize, type CheckResult, type EndpointOutcome } from "@wasit-dev/core"; + +import { + MARKS, + SPINNER_FRAMES, + SPINNER_MS, + duration, + lineWidth, + spread, + styler, + truncate, + visibleLength, + wrap, + type BadgeRole, + type ColorDepth, + type Role, + type Styler, + type StyleStream, +} from "./style.js"; + +export interface LiveStream extends StyleStream { + write(chunk: string): unknown; +} + +export interface LiveOptions { + readonly stream: LiveStream; + /** Rewrite the spinner line in place. Off: lines are only appended. */ + readonly live: boolean; + /** The sanitiser, with the run's secrets redacted. */ + readonly clean: (text: string) => string; + /** The terminal's colour depth (`colorDepth`): 24-bit gives the exact brand colours. Default 16. */ + readonly depth?: ColorDepth; + /** Shorthand for `depth: 24`. */ + readonly truecolor?: boolean; + readonly now?: () => number; + /** How often the spinner line is redrawn. */ + readonly tickMs?: number; +} + +/** What a check does while it runs, for its spinner line. */ +const DOING: Readonly> = { + "X402-01..05": "reading the challenge, no payment", + "X402-06": "paying once, then reading the transfer on chain", + "X402-07": "sending a payment with a corrupted signature", + "X402-08": "sending the same payment again", + "X402-09": "sending a validly signed payment for half the price", + "X402-10": "waiting for an authorization to expire, then sending it", + "X402-11": "sending a payment with the request the service must refuse", +}; + +/** The indent of a check's detail lines, under its ID. */ +const DETAIL = " "; +/** The indent of the lines after the first of a fix. */ +const FIX = " "; + +const STATUS_ROLE: Record = { PASS: "dim", FAIL: "danger", SKIP: "warning", ERROR: "error" }; + +/** + * The lines of one check: its line (mark, ID, name, duration, badge), then its + * detail, its fix and its docs. `withDetail` false leaves the detail out: a + * skip whose reason the skip just above it already gave. + */ +export function resultLines( + result: CheckResult, + style: Styler, + width: number, + clean: (text: string) => string, + ms?: number, + withDetail = true, +): string[] { + const status = checkStatus(result); + const marks = MARKS[status]; + const flag = result.destructive ? style.paint(" [destructive]", "warning") : ""; + const left = ` ${style.paint(marks.mark, "bold", marks.markRole)} ${style.paint(clean(result.id), "bold")} ${clean(result.name)}${flag}`; + const time = ms === undefined ? "" : style.paint(duration(ms), "muted"); + const right = [time, style.badge(marks.badge, marks.badgeRole)].filter((part) => part !== "").join(" "); + const lines = [spread(left, right, width)]; + if (withDetail) { + for (const line of wrap(clean(result.detail), width, DETAIL)) lines.push(style.paint(line, STATUS_ROLE[status] ?? "dim")); + } + const guidance = fixFor(result); + if (guidance !== undefined) { + const fix = wrap(clean(guidance.fix), width, FIX); + fix[0] = `${DETAIL}${style.paint("fix", "bold")} ${fix[0]?.trimStart() ?? ""}`; + lines.push(...fix); + if (guidance.docs !== undefined) lines.push(`${DETAIL}${style.paint(`docs ${clean(guidance.docs)}`, "muted")}`); + } + return lines; +} + +/** "10 passed", "1 failed", "1 could not run", "1 skipped": each count in its colour. */ +export function countsParts(results: readonly CheckResult[], style: Styler): string[] { + const counts = summarize([...results]); + const parts = [style.paint(`${counts.passed} passed`, "bold", "success")]; + if (counts.failed > 0) parts.push(style.paint(`${counts.failed} failed`, "bold", "danger")); + if (counts.errored > 0) parts.push(style.paint(`${counts.errored} could not run`, "bold", "error")); + if (counts.skipped > 0) parts.push(style.paint(`${counts.skipped} skipped`, "bold", "warning")); + return parts; +} + +/** "10 passed · 1 failed · 1 could not run · 1 skipped". */ +export function countsLine(results: readonly CheckResult[], style: Styler): string { + return countsParts(results, style).join(style.paint(" · ", "muted")); +} + +/** Parts joined by " · " into lines of at most `width` columns, each after `indent`. */ +function packParts(parts: readonly string[], width: number, indent: string, style: Styler): string[] { + const separator = style.paint(" · ", "muted"); + const lines: string[] = []; + let current = ""; + for (const part of parts) { + const next = current === "" ? `${indent}${part}` : `${current}${separator}${part}`; + if (current !== "" && visibleLength(next) > width) { + lines.push(current); + current = `${indent}${part}`; + } else { + current = next; + } + } + if (current !== "") lines.push(current); + return lines; +} + +const VERDICT: Record = { + conformant: { text: "CONFORMANT", role: "success" }, + "non-conformant": { text: "NOT CONFORMANT", role: "danger" }, + "no-verdict": { text: "NO VERDICT", role: "error" }, + unsupported: { text: "UNSUPPORTED", role: "warning" }, +}; + +export class LiveReport { + readonly #stream: LiveStream; + readonly #live: boolean; + readonly #clean: (text: string) => string; + readonly #now: () => number; + readonly #tickMs: number; + readonly #style: Styler; + readonly #startedAt: number; + #running: { readonly id: string; readonly name: string; readonly startedAt: number } | undefined; + #drawn = false; + #timer: ReturnType | undefined; + /** The reason of the skip printed just before, so the next skip with the same reason does not repeat it. */ + #lastSkip: string | undefined; + + public constructor(options: LiveOptions) { + this.#stream = options.stream; + this.#live = options.live; + this.#clean = options.clean; + this.#now = options.now ?? Date.now; + this.#tickMs = options.tickMs ?? SPINNER_MS; + this.#style = styler(true, options.depth ?? (options.truecolor === true ? 24 : 16)); + this.#startedAt = this.#now(); + } + + get #width(): number { + return lineWidth(this.#stream); + } + + #line(text = ""): void { + this.#stream.write(`${text}\n`); + } + + /** Clears the spinner line from the screen, if one is drawn. */ + #clearRunning(): void { + if (this.#drawn) this.#stream.write("\r\u001b[2K"); + this.#drawn = false; + } + + /** The spinner line: the frame, the ID, what the check is doing, the time so far; never wider than the terminal. */ + #drawRunning(): void { + const running = this.#running; + if (!this.#live || running === undefined) return; + const elapsed = this.#now() - running.startedAt; + const frame = SPINNER_FRAMES[Math.floor(elapsed / SPINNER_MS) % SPINNER_FRAMES.length] ?? SPINNER_FRAMES[0]; + const id = this.#clean(running.id); + const time = duration(elapsed); + const max = this.#width; + const fixed = 3 + 2 + [...id].length + 2 + 2 + [...time].length; + const doing = truncate(this.#clean(DOING[running.id] ?? running.name), Math.max(1, max - fixed)); + const left = ` ${this.#style.paint(frame, "accent")} ${this.#style.paint(id, "bold")} ${this.#style.paint(doing, "muted")}`; + let line = spread(left, this.#style.paint(time, "muted"), max); + if (visibleLength(line) > max) line = left; + this.#stream.write(`\r\u001b[2K${line}`); + this.#drawn = true; + } + + #stopTimer(): void { + if (this.#timer !== undefined) clearInterval(this.#timer); + this.#timer = undefined; + } + + /** ` ◆ wasit · x402 conformance`, then `label value` rows. */ + public header(version: string, subject: string, rows: ReadonlyArray = []): void { + const s = this.#style; + this.#line(` ${s.paint("◆", "accent")} ${s.paint("wasit", "bold")} ${s.paint(`${this.#clean(version)} · ${this.#clean(subject)}`, "muted")}`); + const pad = Math.max(0, ...rows.map(([label]) => label.length)); + for (const [label, value] of rows) this.#line(` ${s.paint(label.padEnd(pad), "muted")} ${this.#clean(value)}`); + this.#line(); + } + + /** A block heading: ` payment · stellar:testnet · testnet funds move`. */ + public phase(name: string, parts: ReadonlyArray = []): void { + this.#clearRunning(); + const s = this.#style; + const rest = parts.map(([text, role]) => `${s.paint("·", "muted")} ${s.paint(this.#clean(text), role ?? "muted")}`).join(" "); + this.#line(` ${s.paint(this.#clean(name), "bold", "accent")}${rest === "" ? "" : ` ${rest}`}`); + this.#drawRunning(); + } + + /** A note under a block: why checks were left out, or that money moves. */ + public note(text: string): void { + this.#clearRunning(); + for (const line of wrap(this.#clean(text), this.#width, " ")) this.#line(this.#style.paint(line, "warning")); + this.#drawRunning(); + } + + /** A check (or a group of checks) starts: its spinner line, on a real terminal. */ + public running(id: string, name: string): void { + this.#clearRunning(); + this.#stopTimer(); + this.#running = { id, name, startedAt: this.#now() }; + this.#drawRunning(); + if (this.#live) { + this.#timer = setInterval(() => this.#drawRunning(), this.#tickMs); + this.#timer.unref?.(); + } + } + + /** A progress line from the check in flight, dimmed, above its spinner line. */ + public progress(text: string): void { + this.#clearRunning(); + for (const line of wrap(`↳ ${this.#clean(text)}`, this.#width, DETAIL)) this.#line(this.#style.paint(line, "dim")); + this.#drawRunning(); + } + + /** + * A check's result replaces its spinner line and carries the time since it + * started. Results computed together with an earlier one (the challenge + * checks, or the checks skipped after a failed payment) carry none, and a + * skipped check never does. + */ + public result(result: CheckResult): void { + let ms: number | undefined; + if (this.#running !== undefined) { + ms = this.#now() - this.#running.startedAt; + this.#clearRunning(); + this.#stopTimer(); + this.#running = undefined; + } + const skip = checkStatus(result) === "SKIP"; + if (skip) ms = undefined; + const repeated = skip && this.#lastSkip === result.detail; + this.#lastSkip = skip ? result.detail : undefined; + for (const line of resultLines(result, this.#style, this.#width, this.#clean, ms, !repeated)) this.#line(line); + } + + /** A blank line between blocks. */ + public gap(): void { + this.#clearRunning(); + this.#line(); + this.#drawRunning(); + } + + /** The verdict, the counts, the run's duration, and the plain output's closing notes. */ + public finish(results: readonly CheckResult[], outcome: EndpointOutcome | undefined, notes: readonly string[]): void { + this.#clearRunning(); + this.#stopTimer(); + this.#running = undefined; + const s = this.#style; + const verdict = outcome === undefined ? "" : `${s.badge(VERDICT[outcome].text, VERDICT[outcome].role)} `; + this.#line(); + const parts = [...countsParts(results, s), s.paint(duration(this.#now() - this.#startedAt), "bold")]; + const oneLine = ` ${verdict}${parts.join(s.paint(" · ", "muted"))}`; + if (visibleLength(oneLine) <= this.#width) { + this.#line(oneLine); + } else { + if (verdict !== "") this.#line(` ${verdict.trimEnd()}`); + for (const line of packParts(parts, this.#width, " ", s)) this.#line(line); + } + for (const note of notes) { + this.#line(); + const lines = wrap(this.#clean(note), this.#width, " "); + lines[0] = ` ${s.paint("note", "bold", "warning")} ${lines[0]?.trimStart() ?? ""}`; + for (const line of lines) this.#line(line); + } + } +} diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts index 093da64..f03a87b 100644 --- a/packages/cli/src/output.ts +++ b/packages/cli/src/output.ts @@ -14,6 +14,9 @@ import { type ProtocolId, } from "@wasit-dev/core"; +import { countsLine, resultLines } from "./live.js"; +import { lineWidth, type Styler } from "./style.js"; + /** * Prints an advisory/status line meant for a human watching the terminal, * never part of the run's actual result. Routed to stderr when --json is @@ -40,6 +43,41 @@ export interface ReportOptions { readonly emit?: (line: string) => void; /** Values no output may carry. Default: the keys and header values in the environment. */ readonly secrets?: readonly string[]; + /** Colours for a person at a terminal (`colorEnabled`). Absent or off: the plain text, unchanged. */ + readonly style?: Styler; + /** The width coloured lines are laid out to. Default 80. */ + readonly width?: number; +} + +/** The exit code of a run, by the same rule `report` uses. */ +export function exitCodeFor(results: CheckResult[], protocol?: ProtocolId): number { + return protocol === undefined ? summarize(results).exitCode : exitCodeForEndpoint(results, protocol); +} + +/** The notes that close a run's text output, when it has no verdict. */ +export function verdictNotes(results: CheckResult[], protocol?: ProtocolId): string[] { + const counts = summarize(results); + const exitCode = exitCodeFor(results, protocol); + if (counts.errored > 0 && counts.failed === 0) { + return [ + "No verdict: some checks never reached the target or the run is " + + "misconfigured. This is not a statement about the target's conformance.", + ]; + } + if (protocol !== undefined && exitCode === 2 && paymentGroupUnsupported(results, protocol)) { + return [ + "No verdict: the payment checks were asked for and Wasit cannot pay on this network " + + "(unsupported; the skipped checks say why), so nothing was signed. This is not a failure " + + "of the service, and not a pass.", + ]; + } + if (protocol !== undefined && exitCode === 2 && endpointOutcome(results, protocol) === "unsupported") { + return [ + "No verdict: Wasit could not grade this service (unsupported; the skipped checks say why). " + + "This is not a failure of the service, and not a pass.", + ]; + } + return []; } /** @@ -62,7 +100,7 @@ export function report(results: CheckResult[], json: boolean, options: ReportOpt const secrets = options.secrets ?? deniedEnvValues(process.env); const clean = (text: string): string => sanitizeText(text, { redact: secrets }); const counts = summarize(results); - const exitCode = options.protocol === undefined ? counts.exitCode : exitCodeForEndpoint(results, options.protocol); + const exitCode = exitCodeFor(results, options.protocol); if (json) { const run = options.protocol === undefined ? toStructuredRun(results) : toGradedRun(results, options.protocol); @@ -70,6 +108,24 @@ export function report(results: CheckResult[], json: boolean, options: ReportOpt return exitCode; } + // Coloured, for a person at a terminal: the same checks, details, fixes and + // notes, laid out like a test runner. + const style = options.style; + if (style !== undefined && style.enabled) { + const width = options.width ?? lineWidth({}); + let lastSkip: string | undefined; + for (const result of results) { + const skip = checkStatus(result) === "SKIP"; + const repeated = skip && lastSkip === result.detail; + lastSkip = skip ? result.detail : undefined; + for (const line of resultLines(result, style, width, clean, undefined, !repeated)) emit(line); + } + emit(""); + emit(` ${countsLine(results, style)}`); + for (const message of verdictNotes(results, options.protocol)) emit(`\n ${style.paint("note", "bold", "warning")} ${clean(message)}`); + return exitCode; + } + for (const result of results) { const flag = result.destructive ? " [destructive]" : ""; emit(clean(`${checkStatus(result)} ${result.id} ${result.name}${flag}`)); @@ -88,27 +144,7 @@ export function report(results: CheckResult[], json: boolean, options: ReportOpt if (counts.skipped > 0) line.push(`${counts.skipped} skipped`); emit(`${line.join(", ")}.`); - if (counts.errored > 0 && counts.failed === 0) { - emit( - "\nNo verdict: some checks never reached the target or the run is " + - "misconfigured. This is not a statement about the target's conformance.", - ); - } else if (options.protocol !== undefined && exitCode === 2 && paymentGroupUnsupported(results, options.protocol)) { - emit( - "\nNo verdict: the payment checks were asked for and Wasit cannot pay on this network " + - "(unsupported; the skipped checks say why), so nothing was signed. This is not a failure " + - "of the service, and not a pass.", - ); - } else if ( - options.protocol !== undefined && - exitCode === 2 && - endpointOutcome(results, options.protocol) === "unsupported" - ) { - emit( - "\nNo verdict: Wasit could not grade this service (unsupported; the skipped checks say why). " + - "This is not a failure of the service, and not a pass.", - ); - } + for (const message of verdictNotes(results, options.protocol)) emit(`\n${message}`); return exitCode; } diff --git a/packages/cli/src/run-format.ts b/packages/cli/src/run-format.ts index c41cb86..2e85c3c 100644 --- a/packages/cli/src/run-format.ts +++ b/packages/cli/src/run-format.ts @@ -33,7 +33,9 @@ function blocks(endpoint: EndpointReport): Array<{ ids: string[]; first: Endpoin * passes them through the sanitiser (they hold text a service sent). */ export function formatRun(resolved: ResolvedRun, report: RunReport, verdict: RunVerdict): string[] { - const lines: string[] = [describeRun(resolved), "Tier: read-only. No payment is made and nothing is signed.", ""]; + // The first note is the tier: what the run paid, or why it did not. + const tier = report.notes[0]; + const lines: string[] = [describeRun(resolved), ...(tier === undefined ? [] : [tier]), ""]; for (const endpoint of report.endpoints) { lines.push(`${endpoint.name} ${endpoint.protocol} ${endpoint.method} ${endpoint.path}: ${endpoint.outcome}`); @@ -50,7 +52,7 @@ export function formatRun(resolved: ResolvedRun, report: RunReport, verdict: Run } lines.push(`Summary: ${describeTotals(report.totals)}.`); - for (const note of report.notes) lines.push(`Note: ${note}`); + for (const note of report.notes.slice(1)) lines.push(`Note: ${note}`); lines.push(`Result: ${verdict.reason} (exit ${verdict.code}).`); if (verdict.code === 2) { lines.push("No verdict is neither a pass nor a failure of the service: see the endpoints that were not graded."); diff --git a/packages/cli/src/run.ts b/packages/cli/src/run.ts index 584f120..3e57914 100644 --- a/packages/cli/src/run.ts +++ b/packages/cli/src/run.ts @@ -2,12 +2,25 @@ * `wasit run`: the endpoints of a `wasit.config.json`, one after another, with * one report (spec A2, A8). * - * In this version every run is read-only. The payment tier is refused before a - * config is read or anything is sent; the flags that would open it (`--dry-run`, - * `--mainnet`, a key) are not registered. An x402 endpoint gets its unpaid - * challenge checks (X402-01..05) and nothing else; its payment checks, and every - * MPP check, are reported as skipped for the tier, so the report says which - * checks need a payer instead of leaving them out. + * Three tiers. `--read-only`: an x402 endpoint gets its unpaid challenge checks + * (X402-01..05); its payment checks, and every MPP check, are reported as + * skipped for the tier, so the report says which checks need a payer. + * `--dry-run` (spec B5): L0 and L1 only, the plan of the payment checks + * printed; no key, no payment, no signature. Neither flag: the payment tier. + * + * The payment tier pays only when every one of these holds (D-022a, B3, A1): + * the GitHub event may pay (push to the default branch, schedule, + * workflow_dispatch on it; outside GitHub Actions always), the network is a + * test network (L0; the mainnet opt-in is not part of this version), the + * environment has `operatedByMe: true`, the chain's key variable is set, and + * the plan (L1) fits the caps. Then one budget is shared by every endpoint, each + * endpoint's checks get its entry of the plan, and the pin and `maxRunUsd` come + * from the config; L2 and L3 hold every signature in core. On a pull request the + * run is the read-only tier and says so. A key variable that is set on a run that + * may not pay is refused before the service starts (Najmi, 2026-11-16). + * + * `--mainnet` asks for the mainnet opt-in, which this version does not have: + * the run is refused at once, exit 2, before the config is read (spec B12). * * `executeRun` does not call `process.exit` and does not read the process: the * environment and the output are passed in, so it can be tested in-process. @@ -17,19 +30,35 @@ import { readFileSync, statSync, writeFileSync } from "node:fs"; import { ConfigError, + ConfigurationError, MAX_BASELINE_BYTES, + PER_PAYMENT_CAP_USD, + RunBudget, + assertPaymentNetworkAllowed, buildEndpointReport, buildRunReport, deniedEnvValues, + describePlan, + describeRun, errored, + formatUsd, + inGithubActions, isLoopbackUrl, + payerKeyVariables, + paymentChainFor, + paymentChecksSkipped, + paymentEventGate, + planX402Run, readBaseline, readConfigFile, readBuildCommit, + readGithubEvent, readToolVersions, redactReport, + refuseMainnetSwitch, resolveRun, runExitCode, + runX402PaymentChecks, runX402ReadChecks, sanitizeText, selectBaseline, @@ -37,12 +66,21 @@ import { urlOrigin, type BaselineResult, type CheckResult, + type PaymentChain, + type PinTerms, type ResolvedEndpoint, type ResolvedRun, + type RunPlan, + type RunVerdict, + type SkipKind, + MainnetOptInRefusedError, + RpcIdentityError, + UnsupportedPaymentNetworkError, + assertRpcServesNetwork, } from "@wasit-dev/core"; import { formatRun } from "./run-format.js"; -import { ServiceError, startService, type StartedService } from "./service.js"; +import { ServiceError, serviceUserFor, startService, type StartedService } from "./service.js"; import { CLI_VERSION } from "./version.js"; export interface RunCommandOptions { @@ -50,6 +88,8 @@ export interface RunCommandOptions { readonly env?: string; readonly endpoint?: readonly string[]; readonly readOnly: boolean; + /** L0 and L1 only: print the plan of the payment checks and exit. No key, no payment, no signature. */ + readonly dryRun?: boolean; readonly json: boolean; readonly out?: string; readonly start: boolean; @@ -60,6 +100,12 @@ export interface RunCommandOptions { */ readonly startIfLocal?: boolean; readonly baseline?: string; + /** + * `--mainnet`: the switch of the mainnet opt-in (spec B5). This version has no + * opt-in, so it always refuses, exit 2, before anything else is done (B12). + * Never read from the config or the environment. + */ + readonly mainnet?: boolean; } export interface RunContext { @@ -71,30 +117,132 @@ export interface RunContext { readonly now?: () => Date; /** Where `service.start` runs. Default: the working directory. */ readonly cwd?: string; + /** Tests only: the sudo `--start` uses for a separate service user. Index never sets it; no flag or variable reaches it. */ + readonly sudo?: string; } const TIER_NOTE = "Tier: read-only. The payment checks were not run, and nothing was signed."; -/** What the read-only tier does for one endpoint. */ -async function runEndpoint(endpoint: ResolvedEndpoint): Promise { +const MPP_NOT_IN_RUN = + "wasit run does not pay MPP in this version: run wasit mpp-charge or wasit mpp-channel against this endpoint"; + +/** What one endpoint's payment checks do in this run. */ +type PaymentStep = + /** Skipped: with the read-only tier's own words when `reason` is absent. */ + | { readonly pay: false; readonly kind: SkipKind; readonly reason?: string } + /** Paid, through the run's one budget and its plan. */ + | { + readonly pay: true; + readonly network: string; + readonly key: string; + readonly rpcUrl?: string; + readonly budget: RunBudget; + readonly pin?: PinTerms; + readonly plan: RunPlan; + /** Where a check's progress line goes (X402-11's wait): the same channel as the tier line. */ + readonly progress?: (line: string) => void; + }; + +function skippedFor(protocol: ResolvedEndpoint["protocol"], step: Extract): CheckResult[] { + if (step.reason === undefined && (step.kind === "read-only" || step.kind === "needs-payer")) { + return skippedPaymentChecks(protocol, step.kind); + } + return paymentChecksSkipped(protocol, step.kind, step.reason ?? "the payment checks were not run"); +} + +/** What the run does for one endpoint. */ +async function runEndpoint(endpoint: ResolvedEndpoint, step: PaymentStep): Promise { try { if (endpoint.protocol === "x402") { - const challenge = await runX402ReadChecks({ - target: endpoint.url, + const shape = { method: endpoint.method, ...(endpoint.body === undefined ? {} : { body: endpoint.body }), ...(Object.keys(endpoint.headers).length === 0 ? {} : { headers: endpoint.headers }), + }; + const challenge = await runX402ReadChecks({ target: endpoint.url, ...shape }); + if (!step.pay) return [...challenge, ...skippedFor("x402", step)]; + // Every endpoint of the run was planned; one that is not in the plan is not paid. + const plan = step.plan.endpoints.find((entry) => entry.name === endpoint.name); + if (plan === undefined) throw new Error(`the plan of this run has no entry for ${endpoint.name}`); + const payment = await runX402PaymentChecks({ + target: endpoint.url, + network: step.network, + payerSecretKey: step.key, + ...(step.rpcUrl === undefined ? {} : { rpcUrl: step.rpcUrl }), + budget: step.budget, + ...(step.pin === undefined ? {} : { pin: step.pin }), + plan, + ...shape, + // X402-11 sends a payment with the request the config says the service must refuse. + ...(endpoint.reject === undefined ? {} : { reject: endpoint.reject }), + ...(step.progress === undefined ? {} : { onProgress: step.progress }), }); - return [...challenge, ...skippedPaymentChecks("x402", "read-only")]; + return [...challenge, ...payment]; } - // Every MPP check pays or signs: the read-only tier has none to run. - return skippedPaymentChecks(endpoint.protocol, "read-only"); + // Every MPP check pays or signs. The read-only tier has none to run, and the + // payment tier of wasit run does not run them in this version. + if (step.pay) return paymentChecksSkipped(endpoint.protocol, "not-applicable", MPP_NOT_IN_RUN); + return skippedFor(endpoint.protocol, step); } catch (error) { // A check that throws is a defect in Wasit, not a finding about the service. return [errored("PREFLIGHT", "Run Preflight", error)]; } } +/** The x402 endpoints of a run, as the plan reads them. */ +function planEndpoints(resolved: ResolvedRun) { + return resolved.endpoints + .filter((endpoint) => endpoint.protocol === "x402") + .map((endpoint) => ({ + name: endpoint.name, + target: endpoint.url, + method: endpoint.method, + ...(endpoint.body === undefined ? {} : { body: endpoint.body }), + ...(Object.keys(endpoint.headers).length === 0 ? {} : { headers: endpoint.headers }), + ...(endpoint.reject === undefined ? {} : { reject: endpoint.reject }), + })); +} + +/** + * A key variable is set on a run that may not pay (Najmi, 2026-11-16): refused + * before the service starts, because the service would run in the same job as + * the key. A fork's pull request has empty secrets and is not refused. + */ +function keyOnRefusedEvent(keys: readonly string[], reason: string): string { + const why = reason.replace(/^payment checks not run: /, ""); + const first = keys[0] ?? "STELLAR_PRIVATE_KEY"; + return ( + `wasit run: ${keys.join(", ")} ${keys.length === 1 ? "is" : "are"} set, and this run may not pay (${why}). ` + + `Nothing was started or sent: the service of this run would run in the same job as the key. ` + + `Give the key only to runs that may pay (push to the default branch, schedule, workflow_dispatch), ` + + `for example in the env: of the Wasit step:\n` + + ` ${first}: \${{ github.event_name != 'pull_request' && secrets.WASIT_TESTNET_PAYER || '' }}` + ); +} + +/** Why `wasit run` stops in a CI that is not GitHub Actions. */ +function otherCiRefusal(keys: readonly string[]): string { + const key = + keys.length === 0 + ? "" + : ` ${keys.join(", ")} ${keys.length === 1 ? "is" : "are"} set: remove ${keys.length === 1 ? "it" : "them"} from ` + + `this job, since the service of this run would run in the same job as the key.`; + return ( + `wasit run: CI is set, and this is not GitHub Actions. In this version the payment tier runs outside CI, or in ` + + `GitHub Actions, where it pays only on a push to the default branch, a schedule and workflow_dispatch. ` + + `In this CI, run wasit run --read-only, with no payer key in the job.${key} Nothing was started, sent or signed.` + ); +} + +/** The payer's address for the first line of a paying run; the checks report a key that is not valid. */ +function payerAddress(chain: PaymentChain, key: string): string { + try { + return chain.payerAddress(key); + } catch { + return "(the key is not valid: see the results)"; + } +} + /** The baseline file, read; the reason when it cannot be. A file that is not there is the first run on main: no reason. */ function readBaselineFile(path: string): BaselineResult | undefined { try { @@ -108,6 +256,47 @@ function readBaselineFile(path: string): BaselineResult | undefined { } } +/** + * The dry run: the plan of the x402 payment checks (L0, L1), printed. Exit 0 + * when a paying run could start as planned, 2 when it would be refused. + */ +async function printPlan( + resolved: ResolvedRun, + stdout: (line: string) => void, + clean: (text: string) => string, + fail: (message: string) => number, +): Promise { + let plan; + try { + plan = await planX402Run({ + network: resolved.network, + ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }), + ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }), + endpoints: planEndpoints(resolved), + }); + } catch (error) { + // L0: a network that is not a test network, refused before any request. + if (error instanceof ConfigurationError) return fail(`wasit run --dry-run: ${error.message}`); + throw error; + } + + const lines = [...describeRun(resolved).split("\n"), ...describePlan(plan)]; + for (const endpoint of resolved.endpoints) { + if (endpoint.protocol !== "x402") { + lines.push(` ${endpoint.name}: not planned: the dry run plans the x402 payment checks; ${endpoint.protocol} is not planned in this version.`); + } + } + const refused = plan.refusal !== undefined || plan.endpoints.some((endpoint) => endpoint.status === "refused"); + if (!resolved.operatedByMe) { + lines.push( + `Refused: operatedByMe is not true for environment ${resolved.environment}, so a paying run would be ` + + `refused: Wasit pays only a service its operator runs. Nothing was signed.`, + ); + } + for (const line of lines) stdout(clean(line)); + return refused || !resolved.operatedByMe ? 2 : 0; +} + export async function executeRun(options: RunCommandOptions, context: RunContext): Promise { const secrets = deniedEnvValues(context.env); const clean = (text: string): string => sanitizeText(text, { redact: secrets }); @@ -117,13 +306,23 @@ export async function executeRun(options: RunCommandOptions, context: RunContext return 2; }; - if (!options.readOnly) { - return fail( - "wasit run: the payment tier is not available in this version. Pass --read-only to run the " + - "unpaid challenge checks, which send no payment and sign nothing.", - ); + // B12: the switch exists only to refuse. First, so nothing is read, started, sent or signed. + if (options.mainnet === true) { + try { + refuseMainnetSwitch("--mainnet", inGithubActions(context.env) ? { event: context.env["GITHUB_EVENT_NAME"] ?? "" } : {}); + } catch (error) { + if (error instanceof MainnetOptInRefusedError) return fail(`wasit run ${error.message}`); + throw error; + } } + const dryRun = options.dryRun === true; + if (dryRun && options.readOnly) { + return fail("wasit run: choose --dry-run or --read-only, not both."); + } + if (dryRun && (options.json || options.out !== undefined || options.baseline !== undefined)) { + return fail("wasit run --dry-run prints a plan and writes no report: it takes no --json, --out or --baseline."); + } if (options.start && options.startIfLocal === true) { return fail("wasit run: choose --start or --start-if-local, not both."); } @@ -143,6 +342,59 @@ export async function executeRun(options: RunCommandOptions, context: RunContext throw error; } + // D-022a: which GitHub events may pay. A key given to a run that may not pay is + // refused here, before the service of this run (code that may not be reviewed + // yet) starts in the same job as the key. Every tier, the read-only one too. + const gate = paymentEventGate(context.env, readGithubEvent(context.env)); + if (gate.ciOutsideGithub === true) { + // In a CI that is not GitHub Actions the payment tier does not run at all, and + // no tier runs beside a payer key (Najmi, 2026-11-17, review R9 a). + const keys = payerKeyVariables(context.env); + if (keys.length > 0 || (!options.readOnly && options.dryRun !== true)) return fail(otherCiRefusal(keys)); + } else if (!gate.allowed) { + const keys = payerKeyVariables(context.env); + if (keys.length > 0) return fail(keyOnRefusedEvent(keys, gate.reason ?? "this event")); + } + + // The payment tier: neither --read-only nor --dry-run. On an event that may not + // pay it is the read-only tier, and the report says why. + const paymentAsked = !options.readOnly && !dryRun; + const paying = paymentAsked && gate.allowed; + const chain = paying ? paymentChainFor(resolved.network) : undefined; + if (paying && (chain !== undefined || resolved.networkClass !== "unknown")) { + // L0, before the service starts or anything is sent: a test network only. + try { + assertPaymentNetworkAllowed("x402", resolved.network); + } catch (error) { + if (error instanceof ConfigurationError) return fail(`wasit run: ${error.message} Nothing was started, sent or signed.`); + throw error; + } + } + const keyEnv = chain?.payerKeyEnv; + const keyValue = keyEnv === undefined ? undefined : context.env[keyEnv]; + const key = keyValue === undefined || keyValue.trim() === "" ? undefined : keyValue; + const hasX402 = resolved.endpoints.some((endpoint) => endpoint.protocol === "x402"); + /** Why the payment tier that was asked for does not pay, on an event that may pay. */ + const notPaid: string | undefined = !paying + ? undefined + : !resolved.operatedByMe + ? `operatedByMe is not true for environment ${resolved.environment}: Wasit pays only a service its operator runs` + : chain !== undefined && key === undefined + ? `no payer key: set ${keyEnv} on the Wasit step` + : undefined; + + // D-023a+b: a run that will pay checks its RPC before the service starts or + // anything is sent to it: the payments are built and their settlements read + // through it, so it must serve the run's own network. + if (paying && notPaid === undefined && chain !== undefined && key !== undefined && hasX402) { + try { + await assertRpcServesNetwork(resolved.network, chain.resolveRpcUrl(resolved.network, resolved.rpcUrl)); + } catch (error) { + if (error instanceof RpcIdentityError) return fail(`wasit run: ${error.message} The service was not started.`); + throw error; + } + } + // The decision is the CLI's, in one place: --start always starts, --start-if-local starts only // when service.start is set and the environment is on this machine, and says which it did. let shouldStart = options.start; @@ -161,6 +413,8 @@ export async function executeRun(options: RunCommandOptions, context: RunContext } let service: StartedService | undefined; + // D-022a option 2: on a GitHub-hosted runner, a service started while a payer key is set runs as its own user. + const serviceUser = serviceUserFor(context.env); if (shouldStart) { const { start, ready } = resolved.service ?? {}; if (start === undefined) { @@ -179,6 +433,7 @@ export async function executeRun(options: RunCommandOptions, context: RunContext env: context.env, log: (line) => context.stderr(line), ...(context.cwd === undefined ? {} : { cwd: context.cwd }), + ...(serviceUser === undefined ? {} : { separateUser: { name: serviceUser, ...(context.sudo === undefined ? {} : { sudo: context.sudo }) } }), }); } catch (error) { if (error instanceof ServiceError) return fail(error.message); @@ -186,11 +441,71 @@ export async function executeRun(options: RunCommandOptions, context: RunContext } } + if (dryRun) { + try { + return await printPlan(resolved, context.stdout, clean, fail); + } finally { + await service?.stop(); + } + } + const startedAt = (context.now?.() ?? new Date()).toISOString(); + // Lines about money go where the report is not: stderr with --json, else stdout. + const say = (line: string): void => (options.json ? stderr(line) : context.stdout(clean(line))); try { + let step: PaymentStep; + let tierNote: string; + let budget: RunBudget | undefined; + if (!paymentAsked) { + step = { pay: false, kind: "read-only" }; + tierNote = TIER_NOTE; + } else if (!gate.allowed) { + const reason = gate.reason ?? "payment checks not run"; + step = { pay: false, kind: "read-only", reason }; + tierNote = `Tier: read-only (${reason}). Nothing was signed.`; + } else if (notPaid !== undefined) { + step = { pay: false, kind: resolved.operatedByMe ? "needs-payer" : "read-only", reason: `payment checks not run: ${notPaid}` }; + tierNote = `Tier: payment on ${resolved.network}, and the payment checks were not run: ${notPaid}. Nothing was signed.`; + } else if (chain === undefined || key === undefined) { + // No payment adapter for this network: the payment group is unsupported (spec A3), so the + // endpoint has no verdict (Najmi, 2026-11-15). Nothing is fetched for it beyond the challenge. + step = { pay: false, kind: "unsupported", reason: new UnsupportedPaymentNetworkError(resolved.network).message }; + tierNote = `Tier: payment on ${resolved.network}, a network Wasit does not pay on. Nothing was signed.`; + } else { + // L1: the plan, read before anything is signed. A run above its cap does not start. + const plan = await planX402Run({ + network: resolved.network, + ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }), + ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }), + endpoints: planEndpoints(resolved), + }); + if (plan.refusal !== undefined) { + for (const line of describePlan(plan)) stderr(line); + return fail(`wasit run: ${plan.refusal}`); + } + budget = new RunBudget(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }); + say( + `Payment tier on ${resolved.network} (test network): test funds. Payer ${payerAddress(chain, key)}; ` + + `at most ${formatUsd(plan.perPaymentCapUsd)} per payment; this run could spend up to ` + + `${formatUsd(plan.worstCaseUsd)} of the ${formatUsd(budget.capUsd)} cap.`, + ); + for (const line of describePlan(plan).slice(1)) say(line); + step = { + pay: true, + network: resolved.network, + key, + ...(resolved.rpcUrl === undefined ? {} : { rpcUrl: resolved.rpcUrl }), + budget, + ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }), + plan, + progress: say, + }; + tierNote = ""; + } + const endpoints = []; for (const endpoint of resolved.endpoints) { - const results = await runEndpoint(endpoint); + const results = await runEndpoint(endpoint, step); endpoints.push( buildEndpointReport({ name: endpoint.name, @@ -202,6 +517,13 @@ export async function executeRun(options: RunCommandOptions, context: RunContext ); } + if (budget !== undefined) { + // Charged before each signature and never credited back: what the run may have spent. + tierNote = + `Tier: payment on ${resolved.network}. The run charged ${formatUsd(budget.spentUsd)} of the ` + + `${formatUsd(budget.capUsd)} cap, at most $${PER_PAYMENT_CAP_USD}.00 a payment; every signature is counted as if it settled.`; + } + const input = { environment: resolved.environment, network: resolved.network, @@ -209,7 +531,7 @@ export async function executeRun(options: RunCommandOptions, context: RunContext versions: readToolVersions(CLI_VERSION, readBuildCommit(context.env)), endpoints, }; - const preliminary = buildRunReport({ ...input, notes: [TIER_NOTE] }); + const preliminary = buildRunReport({ ...input, notes: [tierNote] }); const selected = selectBaseline( preliminary, options.baseline === undefined ? undefined : readBaselineFile(options.baseline), @@ -217,10 +539,15 @@ export async function executeRun(options: RunCommandOptions, context: RunContext const report = redactReport( selected.note === undefined ? preliminary - : buildRunReport({ ...input, notes: [TIER_NOTE, `Baseline not used: ${selected.note}.`] }), + : buildRunReport({ ...input, notes: [tierNote, `Baseline not used: ${selected.note}.`] }), secrets, ); - const verdict = runExitCode(report, selected.baseline?.report); + let verdict: RunVerdict = runExitCode(report, selected.baseline?.report); + // The payment tier was asked for on an event that may pay and did not pay: + // not green (a FAIL still outranks it). + if (notPaid !== undefined && hasX402 && verdict.code === 0) { + verdict = { ...verdict, code: 2, reason: `the payment tier was asked for and its payment checks were not run: ${notPaid}` }; + } const json = `${JSON.stringify(report, null, 2)}\n`; if (options.out !== undefined) { diff --git a/packages/cli/src/service.ts b/packages/cli/src/service.ts index 312ebf5..463ad9f 100644 --- a/packages/cli/src/service.ts +++ b/packages/cli/src/service.ts @@ -22,9 +22,40 @@ */ import { spawn, spawnSync, type ChildProcess } from "node:child_process"; +import { existsSync, realpathSync } from "node:fs"; import { constants as osConstants } from "node:os"; +import path from "node:path"; -import { deniedEnvValues, isLoopbackUrl, sanitizeText, scrubEnv, urlOrigin } from "@wasit-dev/core"; +import { deniedEnvValues, isLoopbackUrl, payerKeyVariables, sanitizeText, scrubEnv, urlOrigin } from "@wasit-dev/core"; + +/** + * The OS user a service runs as when it must not share a user with the payer + * key (D-022a option 2). Fixed in code: a config or a variable never chooses it. + */ +export const SERVICE_USER = "wasit-service"; + +/** + * The user to run the service as, or undefined for the runner's own user. + * + * Najmi, 2026-11-16: a separate user only when a payer key variable is set AND + * the runner is GitHub-hosted (`RUNNER_ENVIRONMENT`, which GitHub documents as + * `github-hosted` or `self-hosted`; not re-read on the day). A hosted runner's + * user has passwordless sudo, which makes the user; a self-hosted runner or a + * laptop may not, and there the service runs as today. What this separates is + * the service's own processes from the Wasit process that holds the key: on + * Linux the environment of a process (`/proc//environ`) is readable by its + * own user and root only. It does NOT separate code that ran earlier in the job + * as the runner's user (install scripts), which the guide says. + */ +export function serviceUserFor(env: Readonly>): string | undefined { + return payerKeyVariables(env).length > 0 && env["RUNNER_ENVIRONMENT"] === "github-hosted" ? SERVICE_USER : undefined; +} + +/** The service runs as `name`, through `sudo -n`. `sudo` is the program to run: a test passes a stand-in. */ +export interface SeparateUser { + readonly name: string; + readonly sudo?: string; +} /** The service did not start, did not answer, or exited. Nothing was learned about the target: exit 2. */ export class ServiceError extends Error { @@ -50,6 +81,110 @@ export interface ServiceOptions { readonly maxLogBytes?: number; /** Default 250. */ readonly pollIntervalMs?: number; + /** Run the service as this user (see {@link serviceUserFor}). POSIX only; no fallback when it cannot be had. */ + readonly separateUser?: SeparateUser; +} + +const SUDO_TIMEOUT_MS = 120_000; + +/** + * Runs as the service's user: reads `{ command, env }` as JSON from stdin, runs + * the command with `sh -c` and exactly that environment, passes signals on and + * exits with the command's code. CommonJS, for `node -e`. + */ +const SERVICE_LAUNCHER = [ + 'let input = "";', + 'process.stdin.setEncoding("utf8");', + 'process.stdin.on("data", (chunk) => { input += chunk; });', + 'process.stdin.on("end", () => {', + ' let request;', + ' try { request = JSON.parse(input); } catch { process.exit(64); }', + ' const child = require("node:child_process").spawn("sh", ["-c", String(request.command)], { env: request.env, stdio: ["ignore", "inherit", "inherit"] });', + ' for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) process.on(signal, () => { try { child.kill(signal); } catch {} });', + ' child.on("error", () => process.exit(127));', + ' child.on("exit", (code) => process.exit(code === null ? 1 : code));', + '});', +].join("\n"); + +/** Runs `sudo -n `, collects its stderr, and never throws: a sudo that cannot be run is code 127. */ +function runSudo(sudo: string, args: readonly string[]): Promise<{ code: number; stderr: string }> { + return new Promise((resolve) => { + let stderr = ""; + const child = spawn(sudo, ["-n", ...args], { stdio: ["ignore", "ignore", "pipe"], windowsHide: true }); + const timer = setTimeout(() => child.kill("SIGKILL"), SUDO_TIMEOUT_MS); + child.stderr?.setEncoding("utf-8"); + child.stderr?.on("data", (chunk: string) => { + if (stderr.length < 2000) stderr += chunk; + }); + child.once("error", () => { + clearTimeout(timer); + resolve({ code: 127, stderr: "sudo could not be run" }); + }); + child.once("close", (code) => { + clearTimeout(timer); + resolve({ code: code ?? 1, stderr }); + }); + }); +} + +/** + * Makes the user when it does not exist, and lets it reach the working + * directory, by ACL for that one user: traverse (`x`) on each directory above + * it, read and write inside it, nothing on its `.git` (where actions/checkout + * keeps the job's token unless persist-credentials is false). Write access is + * given to the working directory only; beyond it the user can read what the + * directories already let any user read. + */ +async function prepareUser(user: SeparateUser, cwd: string, secrets: readonly string[]): Promise { + const sudo = user.sudo ?? "sudo"; + const home = `/home/${user.name}`; + const refuse = (what: string, result: { code: number; stderr: string }): never => { + const said = sanitizeText(result.stderr.trim().replace(/\s+/g, " "), { redact: secrets }).slice(0, 300); + throw new ServiceError( + `the service must run as a separate user (${user.name}) on a GitHub-hosted runner when a payer key is set, ` + + `and ${what} failed (sudo -n, exit ${result.code}${said === "" ? "" : `: ${said}`}). It was not started as ` + + `the runner's own user instead. This needs passwordless sudo, useradd and setfacl, as GitHub-hosted Linux runners have.`, + ); + }; + + const exists = await runSudo(sudo, ["id", "-u", user.name]); + if (exists.code === 127) refuse("running sudo", exists); + if (exists.code !== 0) { + const made = await runSudo(sudo, [ + "useradd", + "--system", + "--create-home", + "--home-dir", + home, + "--shell", + "/usr/sbin/nologin", + user.name, + ]); + if (made.code !== 0) refuse(`making the user (useradd)`, made); + } + + let directory: string; + try { + directory = realpathSync(cwd); + } catch { + throw new ServiceError(`the working directory of the service cannot be read, so the separate user ${user.name} cannot be given it`); + } + const above: string[] = []; + for (let parent = path.dirname(directory); parent !== path.dirname(parent); parent = path.dirname(parent)) { + above.push(parent); + } + if (above.length > 0) { + const traverse = await runSudo(sudo, ["setfacl", "-m", `u:${user.name}:x`, ...above]); + if (traverse.code !== 0) refuse("letting the user reach the working directory (setfacl)", traverse); + } + const grant = await runSudo(sudo, ["setfacl", "-R", "-m", `u:${user.name}:rwX,d:u:${user.name}:rwX`, directory]); + if (grant.code !== 0) refuse("giving the user the working directory (setfacl)", grant); + const git = path.join(directory, ".git"); + if (existsSync(git)) { + const deny = await runSudo(sudo, ["setfacl", "-R", "-m", `u:${user.name}:---`, git]); + if (deny.code !== 0) refuse("keeping the user out of .git (setfacl)", deny); + } + return home; } export interface StartedService { @@ -103,15 +238,49 @@ export async function startService(options: ServiceOptions): Promise undefined); + child.stdin?.end( + JSON.stringify({ + command, + env: { + ...childEnv, + PATH: childEnv["PATH"] ?? "/usr/local/bin:/usr/bin:/bin", + HOME: home, + USER: separate.name, + LOGNAME: separate.name, + }, + }), + ); + } let spawnError: Error | undefined; let exitInfo: { code: number | null; signal: NodeJS.Signals | null } | undefined; @@ -169,7 +338,16 @@ export async function startService(options: ServiceOptions): Promise + spawnSync(sudo, ["-n", "pgrep", "-u", name], { stdio: "ignore", timeout: 10_000 }).status === 0; + const signalUser = (name: string, signal: NodeJS.Signals): void => { + spawnSync(sudo, ["-n", "pkill", `-${signal.replace(/^SIG/, "")}`, "-u", name], { stdio: "ignore", timeout: 10_000 }); + }; const groupAlive = (): boolean => { + if (separate !== undefined) return userAlive(separate.name); try { process.kill(-pid, 0); return true; @@ -178,6 +356,10 @@ export async function startService(options: ServiceOptions): Promise { + if (separate !== undefined) { + signalUser(separate.name, signal); + return; + } try { process.kill(-pid, signal); } catch { diff --git a/packages/cli/src/style.ts b/packages/cli/src/style.ts new file mode 100644 index 0000000..41eed2f --- /dev/null +++ b/packages/cli/src/style.ts @@ -0,0 +1,222 @@ +/** + * Colours and line layout for a person watching the terminal (Najmi, + * 2026-11-19): Wasit's own look, in the palette the site and the dashboard use + * (`dashboard/theme.ts`), a spinner while a check runs, and the run's duration. + * + * Colour is a layer over the plain text, never a second wording: every line is + * sanitised first (`sanitizeText`), then styled, so nothing a service sent can + * carry an escape sequence of its own. Output that a program reads stays plain: + * `--json`, a pipe, CI and `NO_COLOR` all get the exact text Wasit printed + * before colours existed. + */ + +import { THEME } from "./dashboard/theme.js"; + +/** The parts of a stream this module reads. */ +export interface StyleStream { + readonly isTTY?: boolean; + readonly columns?: number; +} + +type Env = Readonly>; + +function set(value: string | undefined): boolean { + return value !== undefined && value !== ""; +} + +/** + * True when lines may carry colour: `NO_COLOR` set turns it off, `FORCE_COLOR` + * set (and not "0") turns it on, a dumb terminal and CI are plain, otherwise a + * TTY is coloured and anything else is not. + */ +export function colorEnabled(stream: StyleStream, env: Env): boolean { + if (set(env["NO_COLOR"])) return false; + if (set(env["FORCE_COLOR"]) && env["FORCE_COLOR"] !== "0") return true; + if (env["TERM"] === "dumb") return false; + if (set(env["CI"]) || set(env["GITHUB_ACTIONS"])) return false; + return stream.isTTY === true; +} + +/** + * True when a line may be rewritten in place (the running line and its + * spinner): colour on, and a real terminal. A forced colour into a pipe gets + * colour but no cursor movement. + */ +export function liveEnabled(stream: StyleStream, env: Env): boolean { + return colorEnabled(stream, env) && stream.isTTY === true && !set(env["CI"]) && !set(env["GITHUB_ACTIONS"]); +} + +/** True when the terminal says it shows 24-bit colour; the brand colours are then exact. */ +export function truecolorEnabled(env: Env): boolean { + const value = (env["COLORTERM"] ?? "").toLowerCase(); + return value === "truecolor" || value === "24bit"; +} + +/** How many colours the terminal says it shows: 24-bit, 256, or the 16 of every terminal. */ +export type ColorDepth = 16 | 256 | 24; + +export function colorDepth(env: Env): ColorDepth { + if (truecolorEnabled(env)) return 24; + if ((env["TERM"] ?? "").includes("256")) return 256; + return 16; +} + +/** The roles a line's parts are painted in. */ +export type Role = "accent" | "muted" | "success" | "warning" | "danger" | "error" | "bold" | "dim"; + +/** Each role: its brand colour, and the 16-colour code a plain terminal gets instead. */ +const ROLES: Record, { readonly hex: string; readonly basic: number }> = { + accent: { hex: THEME.accent, basic: 35 }, + muted: { hex: THEME.muted, basic: 90 }, + success: { hex: THEME.success, basic: 32 }, + warning: { hex: THEME.warning, basic: 33 }, + danger: { hex: THEME.danger, basic: 31 }, + error: { hex: "#d946ef", basic: 95 }, +}; + +function rgb(hex: string): string { + const value = Number.parseInt(hex.slice(1), 16); + return `${(value >> 16) & 255};${(value >> 8) & 255};${value & 255}`; +} + +/** Applies roles to text, or returns it unchanged when colour is off. */ +export interface Styler { + readonly enabled: boolean; + paint(text: string, ...roles: Role[]): string; + /** ` LABEL ` on a background in the role's colour; the bare label when colour is off. */ + badge(label: string, role: BadgeRole): string; +} + +/** The roles a badge's background can take. */ +export type BadgeRole = "success" | "danger" | "warning" | "error"; + +/** Black ink on the light backgrounds (green, yellow), white on the dark ones (red, magenta). */ +const BADGE_DARK_INK: Record = { success: true, warning: true, danger: false, error: false }; +/** The 256-colour backgrounds nearest the brand colours. */ +const BADGE_256: Record = { success: 41, warning: 214, danger: 203, error: 171 }; +const BADGE_16: Record = { success: 42, warning: 43, danger: 41, error: 45 }; + +/** + * The SGR parameters of a badge. The ink is given exactly (24-bit or 256-colour + * black and white), never as a bold colour of the 16: a terminal that draws bold + * text in bright colours (VS Code and iTerm2 by default) turns bold black into + * grey, which melts into a green or yellow background. On a 16-colour terminal + * black ink is not bold, for the same reason. + */ +function badgeParams(role: BadgeRole, depth: ColorDepth): string { + const dark = BADGE_DARK_INK[role]; + if (depth === 24) return `1;${dark ? "38;2;0;0;0" : "38;2;255;255;255"};48;2;${rgb(ROLES[role].hex)}`; + if (depth === 256) return `1;${dark ? "38;5;16" : "38;5;231"};48;5;${BADGE_256[role]}`; + return dark ? `30;${BADGE_16[role]}` : `1;97;${BADGE_16[role]}`; +} + +/** + * A styler. `depth` is the terminal's colour depth (`colorDepth`); `true` is + * read as 24-bit, `false` or nothing as the 16 colours of every terminal. + */ +export function styler(enabled: boolean, depth: ColorDepth | boolean = 16): Styler { + const bits: ColorDepth = depth === true ? 24 : depth === false ? 16 : depth; + const truecolor = bits === 24; + return { + enabled, + badge(label, role) { + if (!enabled) return label; + return `\u001b[${badgeParams(role, bits)}m ${label} \u001b[22;39;49m`; + }, + paint(text, ...roles) { + if (!enabled || roles.length === 0 || text === "") return text; + let open = ""; + let close = ""; + for (const role of roles) { + if (role === "bold" || role === "dim") { + open += role === "bold" ? "\u001b[1m" : "\u001b[2m"; + close = `\u001b[22m${close}`; + continue; + } + const { hex, basic } = ROLES[role]; + open += truecolor ? `\u001b[38;2;${rgb(hex)}m` : `\u001b[${basic}m`; + close = `\u001b[39m${close}`; + } + return `${open}${text}${close}`; + }, + }; +} + +/** The SGR sequences this module writes, and only those, for measuring a line. */ +const SGR = /\u001b\[[0-9;]*m/g; + +/** The width a line takes on screen: its length without the colour codes. */ +export function visibleLength(text: string): number { + return [...text.replace(SGR, "")].length; +} + +/** + * A check's status as a mark and a badge that agree (Najmi, 2026-11-20): + * ✓ PASS, ✗ FAIL, ○ SKIP, ! ERROR (the check could not run). Text marks, not + * emoji: an emoji takes two columns in many terminals and breaks the columns. + */ +export const MARKS = { + PASS: { mark: "✓", markRole: "success", badge: "PASS", badgeRole: "success" }, + FAIL: { mark: "✗", markRole: "danger", badge: "FAIL", badgeRole: "danger" }, + SKIP: { mark: "○", markRole: "warning", badge: "SKIP", badgeRole: "warning" }, + ERROR: { mark: "!", markRole: "error", badge: "ERROR", badgeRole: "error" }, +} as const satisfies Record; + +/** The spinner's frames, as the dashboard draws them, one every 80 ms. */ +export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const; +export const SPINNER_MS = 80; + +/** "12ms" under a second, "6.82s" from a second on. */ +export function duration(ms: number): string { + if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`; + return `${(ms / 1000).toFixed(2)}s`; +} + +/** + * `left` and `right` on one line, `right` flush with the width. A line that + * does not fit keeps two spaces between them and runs over. + */ +export function spread(left: string, right: string, width: number): string { + if (right === "") return left; + const gap = Math.max(2, width - visibleLength(left) - visibleLength(right)); + return `${left}${" ".repeat(gap)}${right}`; +} + +/** Cuts plain text to `max` characters, ending in "…". */ +export function truncate(text: string, max: number): string { + const chars = [...text]; + if (chars.length <= max) return text; + if (max <= 1) return "…".slice(0, Math.max(0, max)); + return `${chars.slice(0, max - 1).join("")}…`; +} + +/** + * Plain text wrapped to `width` columns, every line after `indent`. A word + * longer than a line (a URL, a hash) is kept whole and runs over. + */ +export function wrap(text: string, width: number, indent: string): string[] { + const room = Math.max(20, width - [...indent].length); + const lines: string[] = []; + let current = ""; + for (const word of text.split(/\s+/).filter((part) => part !== "")) { + if (current === "") current = word; + else if ([...current].length + 1 + [...word].length <= room) current += ` ${word}`; + else { + lines.push(current); + current = word; + } + } + if (current !== "") lines.push(current); + return lines.map((line) => `${indent}${line}`); +} + +/** + * The width lines are laid out to: one column less than the terminal's (a line + * as wide as the screen makes some terminals start a new line), at most 100, + * 80 when unknown. + */ +export function lineWidth(stream: StyleStream): number { + const columns = stream.columns; + if (columns === undefined || !Number.isFinite(columns) || columns <= 0) return 80; + return Math.max(20, Math.min(100, Math.floor(columns) - 1)); +} diff --git a/packages/cli/test/unit/canary-output.test.ts b/packages/cli/test/unit/canary-output.test.ts new file mode 100644 index 0000000..8b2e592 --- /dev/null +++ b/packages/cli/test/unit/canary-output.test.ts @@ -0,0 +1,208 @@ +/** + * The canary test (spec B6, safety rules 1 and 3), for what slice 3 adds: + * `wasit run` (payment tier, read-only tier, dry run, refusals), the service it + * starts, and `wasit ci-report` on what the run wrote. + * + * A fresh random Stellar key, which holds nothing, is set as every key + * variable at once; the payment chain (the recording one: it signs nothing + * real) reads it from STELLAR_PRIVATE_KEY. The RPC url carries a made-up API + * key. Every line printed and every file written is then searched for the key, + * its raw seed in hex and in base64, and the RPC key. Any hit fails. + * + * The MCP tools have their own canary (packages/server/test/unit/canary-output.test.ts). + * Not covered here: the mainnet ledger (a later version). + */ + +import assert from "node:assert/strict"; +import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import net from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; +import { DENIED_ENV_NAMES } from "@wasit-dev/core"; + +import { executeCiReport } from "../../src/ci-report-command.js"; +import { executeRun, type RunCommandOptions } from "../../src/run.js"; +import { NETWORK, installRecordingChain, multiPaywall, option, type MultiPaywall, type Recorder } from "./payment-helpers.js"; + +const CANARY = Keypair.random(); +const KEY = CANARY.secret(); +const SEED = CANARY.rawSecretKey(); +const RPC_KEY = `rpckey${Math.random().toString(36).slice(2)}canary`; +const NEEDLES = [KEY, SEED.toString("hex"), SEED.toString("base64"), SEED.toString("base64url"), RPC_KEY]; + +/** Every key variable holds the canary. */ +const KEYS = Object.fromEntries(DENIED_ENV_NAMES.map((name) => [name, KEY])); +const RPC = { WASIT_RPC_URL: `http://127.0.0.1:9/rpc?apikey=${RPC_KEY}` }; + +function assertClean(label: string, text: string): void { + for (const needle of NEEDLES) assert.ok(!text.includes(needle), `${label} carries a key value`); +} + +async function freePort(): Promise { + return new Promise((resolve, reject) => { + const probe = net.createServer(); + probe.once("error", reject); + probe.listen(0, "127.0.0.1", () => { + const { port } = probe.address() as net.AddressInfo; + probe.close(() => resolve(port)); + }); + }); +} + +describe("canary: no key and no RPC key in any output of wasit run and wasit ci-report", () => { + let dir: string; + let paywall: MultiPaywall; + let undo: () => void; + const recorder: Recorder = { signed: [] }; + const printed: string[] = []; + + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-canary-")); + undo = installRecordingChain(recorder, { keyEnv: "STELLAR_PRIVATE_KEY", anyKey: true }); + paywall = await multiPaywall({ "/weather": [option("10000")], "/dear": [option("2000000")] }); + }); + after(async () => { + undo(); + await paywall.close(); + await rm(dir, { recursive: true, force: true }); + }); + + async function config(name: string, environment: Record = {}, extra: Record = {}): Promise { + const file = path.join(dir, `${name}.config.json`); + await writeFile( + file, + JSON.stringify({ + version: 1, + environments: { local: { baseUrl: paywall.base, network: NETWORK, operatedByMe: true, ...environment } }, + endpoints: [ + { name: "weather", protocol: "x402", path: "/weather", method: "GET" }, + { name: "dear", protocol: "x402", path: "/dear", method: "GET" }, + ], + ...extra, + }), + ); + return file; + } + + async function run(options: Partial & { config: string }, env: Record = {}): Promise { + return executeRun( + { readOnly: false, json: false, start: false, ...options }, + { + env: { PATH: process.env["PATH"] ?? "", ...KEYS, ...RPC, ...env }, + stdout: (line) => printed.push(line), + stderr: (line) => printed.push(line), + cwd: dir, + }, + ); + } + + it("the payment tier, as text and as --json with --out, then ci-report on its report", async () => { + const file = await config("pay"); + const report = path.join(dir, "pay.report.json"); + await run({ config: file }); + await run({ config: file, json: true, out: report }); + assert.ok(recorder.signed.length > 0, "the canary run did not reach a signature"); + const code = await executeCiReport( + { + report, + comment: path.join(dir, "pay.comment.md"), + summary: path.join(dir, "pay.summary.md"), + baselineOut: path.join(dir, "pay.baseline.json"), + baseline: report, + history: report, + // The check run's payload (2026-11-20) is scanned with every other file below. + checkRun: path.join(dir, "pay.check-run.json"), + }, + { env: { PATH: process.env["PATH"] ?? "", ...KEYS, ...RPC }, stdout: (line) => printed.push(line), stderr: (line) => printed.push(line) }, + ); + assert.equal(code, 0); + }); + + it("the read-only tier and the dry run", async () => { + const file = await config("read"); + await run({ config: file, readOnly: true, json: true, out: path.join(dir, "read.report.json") }); + await run({ config: file, dryRun: true }); + }); + + it("every refusal: a pull request with a key, a plan above maxRunUsd, stellar:pubnet, a pin mismatch, a bad config", async () => { + const pr = { GITHUB_ACTIONS: "true", GITHUB_EVENT_NAME: "pull_request", GITHUB_REF: "refs/pull/1/merge" }; + assert.equal(await run({ config: await config("pr") }, pr), 2); + assert.equal(await run({ config: await config("cap", { maxRunUsd: 0.01 }) }), 2); + assert.equal( + await run({ + config: await config("pubnet", { + network: "stellar:pubnet", + pinned: { payTo: Keypair.random().publicKey(), asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75" }, + }), + }), + 2, + ); + await run({ + config: await config("pin", { pinned: { payTo: "0x1111111111111111111111111111111111111111", asset: option("1").asset } }), + json: true, + out: path.join(dir, "pin.report.json"), + }); + const bad = path.join(dir, "bad.config.json"); + await writeFile(bad, JSON.stringify({ version: 1, environments: { local: { baseUrl: paywall.base, apiKey: KEY } }, endpoints: [] })); + assert.equal(await run({ config: bad }), 2); + }); + + it("an unreachable target", async () => { + const file = path.join(dir, "gone.config.json"); + await writeFile( + file, + JSON.stringify({ + version: 1, + environments: { local: { baseUrl: `http://127.0.0.1:${await freePort()}`, network: NETWORK, operatedByMe: true } }, + endpoints: [{ name: "weather", protocol: "x402", path: "/weather", method: "GET" }], + }), + ); + await run({ config: file, json: true, out: path.join(dir, "gone.report.json") }); + }); + + it("a service started with --start: its environment holds no key and no RPC url", async () => { + const port = await freePort(); + const envFile = path.join(dir, "service-env.json"); + const script = path.join(dir, "service.mjs"); + await writeFile( + script, + `import http from "node:http"; +import { writeFileSync } from "node:fs"; +writeFileSync(${JSON.stringify(envFile)}, JSON.stringify(process.env)); +http.createServer((q, s) => { s.writeHead(404); s.end(); }).listen(${port}, "127.0.0.1"); +`, + ); + const file = await config("start", {}, { service: { start: `node ${JSON.stringify(script)}`, ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 15 } } }); + await run({ config: file, readOnly: true, start: true }); + const childEnv = JSON.parse(await readFile(envFile, "utf-8")) as Record; + for (const name of [...DENIED_ENV_NAMES, "WASIT_RPC_URL"]) assert.ok(!(name in childEnv), name); + }); + + it("X402-11 on an endpoint with a reject case, as text and as --json (review R7)", async () => { + // A chain with an X402-11 watch that reads nothing: the check is planned, starts, and stops with no verdict. + undo(); + undo = installRecordingChain(recorder, { keyEnv: "STELLAR_PRIVATE_KEY", anyKey: true, stubWatch: true }); + const file = await config("reject", {}, { + endpoints: [{ name: "weather", protocol: "x402", path: "/weather", method: "GET", reject: { headers: { "x-lang": "xx" } } }], + }); + await run({ config: file }); + await run({ config: file, json: true, out: path.join(dir, "reject.report.json") }); + const report = JSON.parse(await readFile(path.join(dir, "reject.report.json"), "utf-8")) as { + endpoints: Array<{ results: Array<{ id: string }> }>; + }; + assert.ok(report.endpoints[0]!.results.some((result) => result.id === "X402-11"), "X402-11 did not run"); + }); + + it("left no key and no RPC key in anything printed or written", async () => { + // The config files hold no key except bad.config.json, which the test wrote itself. + for (const name of await readdir(dir)) { + if (name === "bad.config.json") continue; + assertClean(`file ${name}`, await readFile(path.join(dir, name), "utf-8")); + } + assert.ok(printed.length > 20, "too little output was searched"); + assertClean("printed output", printed.join("\n")); + }); +}); diff --git a/packages/cli/test/unit/ci-report-command.test.ts b/packages/cli/test/unit/ci-report-command.test.ts index 02f5e0b..8dc77f3 100644 --- a/packages/cli/test/unit/ci-report-command.test.ts +++ b/packages/cli/test/unit/ci-report-command.test.ts @@ -15,6 +15,8 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { after, before, describe, it } from "node:test"; +import { parseRunReport, serializeBaseline, updateHistory } from "@wasit-dev/core"; + import { executeCiReport, type CiReportOptions } from "../../src/ci-report-command.js"; import { executeRun } from "../../src/run.js"; import { startPaywall, v1Handler, writeConfig, type Handler } from "./run-helpers.js"; @@ -69,7 +71,7 @@ describe("wasit ci-report", () => { assert.equal(result.code, 0, result.stderr); const text = await readFile(comment, "utf-8"); assert.equal(text.split("\n")[0], ""); - assert.match(text.split("\n")[1] ?? "", /Wasit: conformant/); + assert.match(text.split("\n")[1] ?? "", /Wasit: ✅ conformant/); assert.match(text, /No baseline on main yet/); }); @@ -80,13 +82,13 @@ describe("wasit ci-report", () => { await ciReport({ report, summary, comment: path.join(dir, "s1.md") }); const viaFlag = await readFile(summary, "utf-8"); assert.ok(viaFlag.startsWith("earlier step\n")); - assert.match(viaFlag, /Wasit: nothing graded/); + assert.match(viaFlag, /Wasit: ⚪ nothing graded/); assert.ok(!viaFlag.includes("")); const other = path.join(dir, "step-summary-env.md"); appendFileSync(other, ""); await ciReport({ report, comment: path.join(dir, "s2.md") }, { GITHUB_STEP_SUMMARY: other }); - assert.match(await readFile(other, "utf-8"), /Wasit: nothing graded/); + assert.match(await readFile(other, "utf-8"), /Wasit: ⚪ nothing graded/); }); it("compares with the baseline, and carries the history into --baseline-out", async () => { @@ -116,9 +118,9 @@ describe("wasit ci-report", () => { const comment = path.join(dir, "c3.md"); assert.equal((await ciReport({ report: bad, baseline: second, comment })).code, 0, "a failing run is the run's exit code, not ci-report's"); const text = await readFile(comment, "utf-8"); - assert.match(text, /Wasit: non-conformant/); + assert.match(text, /Wasit: ❌ non-conformant/); assert.match(text, /New FAIL: weather X402-01 \(was PASS on main\)/); - assert.ok(!/Recent failures/.test(text), "main never failed, so there is no recent-failures line"); + assert.ok(!/### Recent failures/.test(text), "main never failed, so there is no recent-failures section"); }); it("says the baseline could not be used, and still writes the comment, when the file is not a report", async () => { @@ -145,18 +147,39 @@ describe("wasit ci-report", () => { // The run left no usable report: the comment says "no verdict" (ci-report-no-report.test.ts // holds the detail), so the comment of the push before does not stay next to a red check. + it("writes the check run's title, summary and conclusion with --check-run, and a neutral one when there is no report", async () => { + const report = await reportFor(async (_request, response) => { + const { challengeHeader } = await import("./run-helpers.js"); + response.writeHead(402, { "payment-required": challengeHeader() }); + response.end("{}"); + }, "check-run"); + const checkRun = path.join(dir, "check-run.json"); + const result = await ciReport({ report, comment: path.join(dir, "check-run.comment.md"), checkRun }); + assert.equal(result.code, 0, result.stderr); + const output = JSON.parse(await readFile(checkRun, "utf-8")) as { title: string; summary: string; conclusion: string }; + assert.equal(output.conclusion, "success"); + assert.match(output.title, /^✅ conformant · 5 passed, 6 skipped$/); + assert.match(output.summary, /Wasit: ✅ conformant/); + assert.ok(!output.summary.includes(""), "the summary is the job summary, without the marker"); + const missing = path.join(dir, "check-run-missing.json"); + await ciReport({ report: path.join(dir, "no-such-report.json"), comment: path.join(dir, "missing.comment.md"), checkRun: missing }); + const neutral = JSON.parse(await readFile(missing, "utf-8")) as { conclusion: string; title: string }; + assert.equal(neutral.conclusion, "neutral"); + assert.match(neutral.title, /no verdict/); + }); + it("says no verdict when the report is missing (exit 0: the run step carries the failure) or is not a report (exit 2)", async () => { const comment = path.join(dir, "never.md"); const missing = await ciReport({ report: path.join(dir, "no-such-report.json"), comment }); assert.equal(missing.code, 0); assert.match(missing.stderr, /wrote no report/); - assert.match(await readFile(comment, "utf-8"), /Wasit: no verdict\./); + assert.match(await readFile(comment, "utf-8"), /Wasit: ⚠️ no verdict\./); const notReport = path.join(dir, "not-a-report.json"); await writeFile(notReport, JSON.stringify({ schema: 7 })); const result = await ciReport({ report: notReport, comment }); assert.equal(result.code, 2); assert.match(result.stderr, /not a Wasit report/); - assert.match(await readFile(comment, "utf-8"), /Wasit: no verdict\./); + assert.match(await readFile(comment, "utf-8"), /Wasit: ⚠️ no verdict\./); }); describe("a hostile service, from the run to the comment", () => { @@ -246,3 +269,99 @@ describe("wasit ci-report", () => { } }); }); + + +// D-022b option 2 (Najmi, 2026-11-16): the comparison from the last green run on +// main (--baseline), the history from the newest completed run on main, failed +// or not (--history), and the comment names the run compared with +// (--baseline-run). Written before the code. +describe("wasit ci-report --history --baseline-run", () => { + let dir: string; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-ci-history-")); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + async function runReport(handler: Handler, name: string, environment = "local") { + const paywall = await startPaywall(handler); + try { + const config = await writeConfig(dir, { baseUrl: paywall.base, environment }, `${name}.config.json`); + const file = path.join(dir, `${name}.report.json`); + await executeRun( + { config, readOnly: true, json: true, start: false, out: file }, + { env: { PATH: process.env["PATH"] ?? "" }, stdout: () => {}, stderr: () => {} }, + ); + return { file, report: parseRunReport(JSON.parse(await readFile(file, "utf-8"))) }; + } finally { + await paywall.close(); + } + } + const conformantHandler: Handler = async (_request, response) => { + const { challengeHeader } = await import("./run-helpers.js"); + response.writeHead(402, { "payment-required": challengeHeader() }); + response.end("{}"); + }; + // X402-01 fails: the paid route answers 200 without a payment. + const openHandler: Handler = (_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end("{}"); + }; + + async function run(options: Partial & { report: string }) { + const err: string[] = []; + const comment = path.join(dir, `comment-${Math.random().toString(36).slice(2)}.md`); + const code = await executeCiReport( + { comment, ...options }, + { env: { PATH: process.env["PATH"] ?? "" }, stdout: () => {}, stderr: (line) => err.push(line) }, + ); + return { code, comment: await readFile(comment, "utf-8"), stderr: err.join("\n") }; + } + + it("compares with --baseline, counts recent failures from --history, and names the run", async () => { + const green = await runReport(conformantHandler, "green"); + const red = await runReport(openHandler, "red"); + const baseline = path.join(dir, "baseline.json"); + await writeFile(baseline, serializeBaseline(green.report, updateHistory(undefined, green.report))); + const history = path.join(dir, "history.json"); + await writeFile(history, serializeBaseline(red.report, updateHistory(updateHistory(updateHistory(undefined, green.report), red.report), red.report))); + const next = path.join(dir, "next.json"); + + const result = await run({ report: green.file, baseline, history, baselineRun: "43724229283", baselineOut: next }); + assert.equal(result.code, 0, result.stderr); + assert.match(result.comment, /Compared with the last green run on main: run 43724229283, started /); + assert.match(result.comment, /No change since main\./); + assert.match(result.comment, /weather X402-01: failed in 2 of the last 3 runs on main/); + // The next baseline carries the history of every run on, with this run added. + const written = JSON.parse(await readFile(next, "utf-8")); + assert.equal(written.history.weather["X402-01"], "PFFP"); + }); + + it("ignores a history from another environment, or one it cannot read, and keeps the baseline's own", async () => { + const green = await runReport(conformantHandler, "green2"); + const other = await runReport(openHandler, "other", "staging"); + const baseline = path.join(dir, "baseline2.json"); + await writeFile(baseline, serializeBaseline(green.report, updateHistory(undefined, green.report))); + const foreign = path.join(dir, "foreign-history.json"); + await writeFile(foreign, serializeBaseline(other.report, updateHistory(undefined, other.report))); + for (const history of [foreign, path.join(dir, "missing.json")]) { + const next = path.join(dir, "next2.json"); + const result = await run({ report: green.file, baseline, history, baselineOut: next }); + assert.equal(result.code, 0, result.stderr); + assert.doesNotMatch(result.comment, /### Recent failures on main/); + assert.match(result.stderr, /history .*not used/); + assert.equal(JSON.parse(await readFile(next, "utf-8")).history.weather["X402-01"], "PP"); + } + }); + + it("does not print a run id that is not a whole number", async () => { + const green = await runReport(conformantHandler, "green3"); + const baseline = path.join(dir, "baseline3.json"); + await writeFile(baseline, serializeBaseline(green.report, updateHistory(undefined, green.report))); + for (const baselineRun of ["12; rm", "-1", "0x10", ""]) { + const result = await run({ report: green.file, baseline, baselineRun }); + assert.match(result.comment, /Compared with the last green run on main, started /, baselineRun); + } + }); +}); diff --git a/packages/cli/test/unit/ci-report-no-report.test.ts b/packages/cli/test/unit/ci-report-no-report.test.ts index ca181f5..d5bdcbc 100644 --- a/packages/cli/test/unit/ci-report-no-report.test.ts +++ b/packages/cli/test/unit/ci-report-no-report.test.ts @@ -46,13 +46,13 @@ describe("wasit ci-report without a usable report", () => { assert.equal(result.code, 0, result.stderr); const comment = await readFile(result.comment, "utf-8"); assert.ok(comment.startsWith(`${MARKER}\n`), "the marker is the first line, so the comment replaces the earlier one"); - assert.match(comment, /Wasit: no verdict\./); + assert.match(comment, /Wasit: ⚠️ no verdict\./); assert.match(comment, /nothing was graded/i); assert.match(comment, /job log/); assert.ok(!/conformant\./.test(comment.replace("non-conformant", "")), "it never says conformant"); const summary = await readFile(result.summary, "utf-8"); assert.ok(!summary.includes(MARKER), "the summary has no marker"); - assert.match(summary, /Wasit: no verdict\./); + assert.match(summary, /Wasit: ⚠️ no verdict\./); }); it("names the Wasit and SDK versions, as every result does", async () => { @@ -81,7 +81,7 @@ describe("wasit ci-report without a usable report", () => { assert.equal(result.code, 2); const comment = await readFile(result.comment, "utf-8"); assert.ok(comment.startsWith(`${MARKER}\n`)); - assert.match(comment, /Wasit: no verdict\./); + assert.match(comment, /Wasit: ⚠️ no verdict\./); assert.ok(!comment.includes("canary-from-the-file"), "nothing from the file reaches the comment"); assert.ok(!result.stderr.includes("canary-from-the-file")); assert.equal(existsSync(result.baselineOut), false); diff --git a/packages/cli/test/unit/live-output.test.ts b/packages/cli/test/unit/live-output.test.ts new file mode 100644 index 0000000..b00f7b5 --- /dev/null +++ b/packages/cli/test/unit/live-output.test.ts @@ -0,0 +1,329 @@ +/** + * The coloured, live text output (Najmi, 2026-11-19), in Wasit's own look: a + * header, two blocks of checks, each line with a mark and a badge that agree + * (✓ PASS on green, ✗ FAIL on red, ○ SKIP on yellow, ! ERROR on magenta), + * each check's duration, a spinner line saying what the check in flight is + * doing, and the verdict, the counts and the run's duration at the end. + * + * What must not change: output a program reads. A pipe, CI, NO_COLOR and + * --json get the plain text, byte for byte; a service's text is sanitised + * before it is coloured, so the only escape sequences on screen are Wasit's own; + * and the spinner line never wraps, since a wrapped line cannot be rewritten. + */ + +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { spawn } from "node:child_process"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; +import { type CheckResult, errored, sanitizeText, skipped } from "@wasit-dev/core"; + +import { LiveReport } from "../../src/live.js"; +import { report } from "../../src/output.js"; +import { colorEnabled, liveEnabled, spread, styler, truncate, visibleLength, wrap } from "../../src/style.js"; +import { startPaywall, type Paywall } from "./run-helpers.js"; + +const CLI = fileURLToPath(new URL("../../dist/index.js", import.meta.url)); +const SECRET = "canary-secret-value-91c2"; +const SPINNER = /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]/; +const SGR = /\u001b\[[0-9;]*m/g; + +const pass: CheckResult = { id: "X402-01", name: "402 Response Status", pass: true, detail: "Server responded with 402 as required." }; +const fail: CheckResult = { + id: "X402-08", + name: "Payment Replay Rejected", + pass: false, + detail: `The same payment was accepted again (HTTP 200). ${SECRET}`, +}; +const skip = skipped("X402-11", "Rejected Request Not Settled", "no request the service must refuse is configured."); +const error = errored("X402-06", "Signature Resubmit Accepted", new Error("Stellar simulation failed")); +const hostile: CheckResult = { + id: "X402-04", + name: "Required Fields Present", + pass: false, + detail: "bad \u001b]0;title\u0007 body \u001b[2J\u001b[31mred::set-output name=x::1", +}; + +/** A stream that records what is written, as a terminal of `columns` would get it. */ +function terminal(columns = 80, isTTY = true) { + const writes: string[] = []; + return { stream: { isTTY, columns, write: (chunk: string) => writes.push(chunk) }, writes, text: () => writes.join("") }; +} + +const clean = (text: string) => sanitizeText(text, { redact: [SECRET] }); +const plainText = (text: string) => text.replace(SGR, ""); + +describe("when colour is on", () => { + it("is off for a pipe, NO_COLOR, CI, GitHub Actions and a dumb terminal; FORCE_COLOR turns it on", () => { + assert.equal(colorEnabled({ isTTY: true }, {}), true); + assert.equal(colorEnabled({ isTTY: false }, {}), false); + assert.equal(colorEnabled({ isTTY: true }, { NO_COLOR: "1" }), false); + assert.equal(colorEnabled({ isTTY: true }, { CI: "true" }), false); + assert.equal(colorEnabled({ isTTY: true }, { GITHUB_ACTIONS: "true" }), false); + assert.equal(colorEnabled({ isTTY: true }, { TERM: "dumb" }), false); + assert.equal(colorEnabled({ isTTY: false }, { FORCE_COLOR: "1" }), true); + assert.equal(colorEnabled({ isTTY: false }, { FORCE_COLOR: "0" }), false); + assert.equal(colorEnabled({ isTTY: true }, { FORCE_COLOR: "1", NO_COLOR: "1" }), false, "NO_COLOR wins"); + }); + + it("rewrites lines in place only on a real terminal, never in a pipe or CI, even with FORCE_COLOR", () => { + assert.equal(liveEnabled({ isTTY: true }, {}), true); + assert.equal(liveEnabled({ isTTY: false }, { FORCE_COLOR: "1" }), false); + assert.equal(liveEnabled({ isTTY: true }, { FORCE_COLOR: "1", CI: "true" }), false); + }); +}); + +describe("the line layout", () => { + it("puts the right part flush with the width, whatever the colours", () => { + const style = styler(true); + const line = spread(` ${style.paint("✓", "success")} ${style.paint("X402-01", "bold")} 402 Response Status`, style.paint("8ms", "muted"), 79); + assert.equal(visibleLength(line), 79); + }); + + it("wraps text under an indent and cuts a long line with an ellipsis", () => { + const lines = wrap("one two three four five six seven eight nine ten eleven twelve", 30, " "); + assert.ok(lines.length > 1); + for (const line of lines) assert.ok(line.startsWith(" ") && line.length <= 30, line); + assert.equal(truncate("abcdefgh", 5), "abcd…"); + }); +}); + +describe("LiveReport", () => { + it("draws a spinner line saying what the check is doing, then replaces it with ✓, the check and its time", async () => { + const t = terminal(); + let now = 1000; + const live = new LiveReport({ stream: t.stream, live: true, clean, now: () => now, tickMs: 5 }); + live.running("X402-06", "Signature Resubmit Accepted"); + now = 1400; + await new Promise((resolve) => setTimeout(resolve, 30)); + const drawn = t.writes.filter((chunk) => SPINNER.test(chunk)); + assert.ok(drawn.length >= 2, "the spinner was not redrawn"); + assert.match(plainText(drawn.at(-1) ?? ""), /X402-06 {2}paying once, then reading the transfer on chain +400ms$/); + now = 7820; + live.result({ ...pass, id: "X402-06", name: "Signature Resubmit Accepted" }); + const text = t.text(); + assert.match(text, /\r\u001b\[2K/, "the spinner line was not cleared"); + assert.match(plainText(text), /✓ X402-06 {2}Signature Resubmit Accepted +6\.82s {2} PASS \n/); + }); + + it("never draws a spinner line wider than the terminal, so it never wraps", () => { + for (const columns of [30, 50, 80, 200]) { + const t = terminal(columns); + const live = new LiveReport({ stream: t.stream, live: true, clean }); + live.running("X402-10", "Expired Authorization Rejected"); + live.result(pass); + const spinnerLines = t.writes.filter((chunk) => chunk.startsWith("\r\u001b[2K") && SPINNER.test(chunk)); + assert.ok(spinnerLines.length >= 1, `${columns}: no spinner line`); + for (const chunk of spinnerLines) { + assert.ok(!chunk.includes("\n"), `${columns}: a spinner line holds a newline`); + assert.ok(visibleLength(chunk.replace("\r\u001b[2K", "")) < columns, `${columns}: ${JSON.stringify(plainText(chunk))}`); + } + } + }); + + it("marks and badges each status alike: ✓ PASS, ✗ FAIL, ○ SKIP, ! ERROR", () => { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: true, clean }); + live.result(pass); + live.result(fail); + live.running("X402-11", "Rejected Request Not Settled"); + live.result(skip); + live.result(error); + const text = t.text(); + assert.match(text, /\u001b\[30;42m PASS /, "PASS in black on green"); + assert.match(text, /\u001b\[1;97;41m FAIL /, "FAIL in white on red"); + assert.match(text, /\u001b\[30;43m SKIP /, "SKIP in black on yellow"); + assert.match(text, /\u001b\[1;97;45m ERROR /, "ERROR in white on magenta"); + assert.match(text, /\u001b\[32m✓/); + assert.match(text, /\u001b\[31m✗/); + assert.match(text, /\u001b\[33m○/); + assert.match(text, /\u001b\[95m!/); + const plain = plainText(text); + assert.match(plain, /✓ X402-01 {2}402 Response Status +PASS \n/); + assert.match(plain, /✗ X402-08 {2}Payment Replay Rejected +FAIL \n/, "a FAIL is marked ✗, like its badge"); + assert.match(plain, /○ X402-11 {2}Rejected Request Not Settled +SKIP \n/, "a skipped check carries no time"); + assert.match(plain, /! X402-06 {2}Signature Resubmit Accepted +ERROR \n/, "a check that could not run: !"); + assert.ok(!/✓ X402-08/.test(plain), "a FAIL is never marked ✓"); + assert.match(plain, /\n {5}fix {2}/); + }); + + it("gives a skip's reason once when the skips that follow it have the same reason", () => { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: false, clean }); + const reason = "the target was never reached, so it issued no challenge to inspect."; + for (const [id, name] of [["X402-02", "Payment Header Present"], ["X402-03", "Header Payload Decodable"], ["X402-04", "Required Fields Present"]]) { + live.result(skipped(id!, name!, reason)); + } + live.result(skipped("X402-05", "Network Identifier Valid", "another reason entirely.")); + const plain = plainText(t.text()); + assert.equal(plain.split("the target was never reached").length - 1, 1, plain); + for (const id of ["X402-02", "X402-03", "X402-04", "X402-05"]) assert.match(plain, new RegExp(`○ ${id} `)); + assert.match(plain, /another reason entirely/); + }); + + it("uses the exact brand colours when the terminal shows 24-bit colour", () => { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: false, clean, truecolor: true }); + live.result(pass); + assert.match(t.text(), /\u001b\[38;2;40;200;64m✓/, "the site's green, #28c840"); + assert.match(t.text(), /\u001b\[1;38;2;0;0;0;48;2;40;200;64m PASS /, "PASS in exact black on the site's green"); + }); + + it("writes badge ink that stays black or white when bold: never a bold colour of the 16, which some terminals draw bright", () => { + for (const depth of [16, 256, 24] as const) { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: false, clean, depth }); + for (const result of [pass, fail, skip, error]) live.result(result); + live.finish([pass], "conformant", []); + assert.ok(!/\u001b\[1;3[0-7];/.test(t.text()), `${depth}: a bold 16-colour ink`); + assert.ok(!/\u001b\[1;30m|\u001b\[1;30;/.test(t.text()), `${depth}: bold black`); + } + const t = terminal(); + new LiveReport({ stream: t.stream, live: false, clean, depth: 256 }).result(pass); + assert.match(t.text(), /\u001b\[1;38;5;16;48;5;41m PASS /, "256 colours: exact black on green"); + }); + + it("ends with the verdict, the counts and the run's duration, and the notes of the plain output", () => { + const t = terminal(); + let now = 0; + const live = new LiveReport({ stream: t.stream, live: false, clean, now: () => now }); + now = 45_650; + live.finish([pass, fail, skip, error], "non-conformant", ["No verdict: a note."]); + const plain = plainText(t.text()); + assert.match(plain, / NOT CONFORMANT {2}1 passed · 1 failed · 1 could not run · 1 skipped · 45\.65s/); + assert.match(plain, /note {2}No verdict: a note\./); + const ok = terminal(); + new LiveReport({ stream: ok.stream, live: false, clean }).finish([pass], "conformant", []); + assert.match(plainText(ok.text()), / CONFORMANT {2}1 passed · \d+ms/); + assert.match(ok.text(), /\u001b\[30;42m CONFORMANT /); + const narrow = terminal(40); + new LiveReport({ stream: narrow.stream, live: false, clean }).finish([pass, fail, skip, error], "no-verdict", []); + for (const line of plainText(narrow.text()).split("\n")) assert.ok(line.length < 40, `the closing line runs over: ${JSON.stringify(line)}`); + }); + + it("writes no cursor movement and no spinner when it is not live", () => { + const t = terminal(80, false); + const live = new LiveReport({ stream: t.stream, live: false, clean }); + live.running("X402-06", "Signature Resubmit Accepted"); + live.progress("reading the chain"); + live.result(pass); + assert.ok(!t.text().includes("\u001b[2K")); + assert.ok(!SPINNER.test(t.text())); + }); + + it("sanitises a service's text before colouring it: Wasit's own colour codes are the only escapes, and no secret", () => { + const t = terminal(); + const live = new LiveReport({ stream: t.stream, live: true, clean, truecolor: true }); + live.running("X402-04", "Required Fields Present"); + live.progress(`progress ${SECRET} \u001b]8;;http://x\u0007`); + live.result(hostile); + live.result(fail); + const text = t.text(); + assert.ok(!text.includes("\u0007"), "a BEL reached the terminal"); + // The sanitiser drops the escape characters; a printable leftover such as "]0;title" is plain text. + assert.ok(!text.includes("\u001b]"), "an OSC sequence reached the terminal"); + assert.ok(!text.includes("\u001b[2J"), "a screen clear reached the terminal"); + for (const sequence of text.match(/\u001b[^a-zA-Z]*[a-zA-Z]/g) ?? []) { + assert.match(sequence, /^\u001b\[[0-9;]*[mK]$/, JSON.stringify(sequence)); + } + assert.ok(!text.includes(SECRET), "a secret reached the terminal"); + for (const line of plainText(text).replace(/\r\u001b\[2K/g, "").split("\n")) assert.ok(!/^\s*(::|##\[)/.test(line), line); + }); +}); + +describe("report, with colours", () => { + function render(style?: ReturnType) { + const lines: string[] = []; + const code = report([pass, fail, skip], false, { emit: (line) => lines.push(line), secrets: [SECRET], ...(style ? { style } : {}) }); + return { code, text: lines.join("\n") }; + } + + it("is the plain text, unchanged, when colour is off", () => { + assert.deepEqual(render(styler(false)), render()); + assert.match(render().text, /^PASS {2}X402-01 {2}402 Response Status$/m); + }); + + it("marks the same checks, and keeps the exit code", () => { + const plain = render(); + const coloured = render(styler(true)); + assert.equal(coloured.code, plain.code); + assert.match(plainText(coloured.text), /✗ X402-08 {2}Payment Replay Rejected +FAIL /); + assert.ok(!coloured.text.includes(SECRET)); + }); +}); + +describe("wasit test, as the built binary", () => { + let paywall: Paywall; + let cwd: string; + before(async () => { + paywall = await startPaywall(); + cwd = await mkdtemp(path.join(tmpdir(), "wasit-live-")); + }); + after(async () => { + await paywall.close(); + await rm(cwd, { recursive: true, force: true }); + }); + + function wasit(args: string[], env: Record): Promise<{ code: number | null; out: string }> { + return new Promise((resolve) => { + const child = spawn(process.execPath, [CLI, ...args], { cwd, env: { PATH: process.env["PATH"] ?? "", HOME: cwd, ...env } }); + let out = ""; + child.stdout.on("data", (chunk) => (out += chunk)); + child.stderr.on("data", (chunk) => (out += chunk)); + child.on("close", (code) => resolve({ code, out })); + }); + } + + const read = () => ["test", "--target", `${paywall.base}/paid`, "--read-only"]; + + it("is in Wasit's look with FORCE_COLOR: header, blocks, marks, verdict and duration; same exit code; no cursor movement", async () => { + const plain = await wasit(read(), { NO_COLOR: "1" }); + const coloured = await wasit(read(), { FORCE_COLOR: "1" }); + assert.equal(coloured.code, plain.code); + const text = plainText(coloured.out); + assert.match(text, /◆ wasit 0\.8\.0-beta\.1 · x402 conformance/); + assert.match(text, /^ challenge · no payment$/m); + assert.match(text, /✓ X402-01 {2}402 Response Status .*PASS /); + assert.match(text, / CONFORMANT {2}5 passed · \d/); + assert.match(coloured.out, /\u001b\[32m✓/); + assert.match(coloured.out, /\u001b\[30;42m PASS /); + const term256 = await wasit(read(), { FORCE_COLOR: "1", TERM: "xterm-256color" }); + assert.match(term256.out, /\u001b\[1;38;5;16;48;5;41m PASS /); + assert.ok(!coloured.out.includes("\u001b[2K"), "a pipe got cursor movement"); + const truecolor = await wasit(read(), { FORCE_COLOR: "1", COLORTERM: "truecolor" }); + assert.match(truecolor.out, /\u001b\[38;2;40;200;64m✓/); + }); + + it("is the plain text with NO_COLOR, in CI, and in a pipe", async () => { + const envs: Array> = [{ NO_COLOR: "1", FORCE_COLOR: "1" }, { CI: "true" }, {}]; + for (const env of envs) { + const result = await wasit(read(), env); + assert.ok(!result.out.includes("\u001b["), JSON.stringify(env)); + assert.match(result.out, /^PASS {2}X402-01 {2}402 Response Status$/m, JSON.stringify(env)); + assert.match(result.out, /^5 passed\.$/m, JSON.stringify(env)); + } + }); + + it("on a network that is not a test network, says the payment checks are refused, not that funds move", async () => { + const result = await wasit(["test", "--target", `${paywall.base}/paid`, "--network", "stellar:pubnet"], { + FORCE_COLOR: "1", + STELLAR_PRIVATE_KEY: Keypair.random().secret(), + }); + const text = plainText(result.out); + assert.match(text, /^ payment · stellar:pubnet · not a test network: refused$/m); + assert.ok(!/funds move|settles a real payment/.test(text), "a mainnet run was told that money moves"); + assert.match(text, /! PREFLIGHT .*ERROR /); + assert.match(text, /Nothing was sent and\s+nothing was signed\./); + }); + + it("keeps --json plain JSON, even with FORCE_COLOR", async () => { + const result = await wasit([...read(), "--json"], { FORCE_COLOR: "1" }); + assert.ok(!result.out.includes("\u001b[")); + const start = result.out.indexOf("{"); + assert.doesNotThrow(() => JSON.parse(result.out.slice(start))); + }); +}); diff --git a/packages/cli/test/unit/no-allow-path.test.ts b/packages/cli/test/unit/no-allow-path.test.ts new file mode 100644 index 0000000..57c40d2 --- /dev/null +++ b/packages/cli/test/unit/no-allow-path.test.ts @@ -0,0 +1,276 @@ +/** + * The "no allow path" property test of spec B11 and B12, through `wasit run`: + * for random combinations of flags, variables and config values, a payment on + * `stellar:pubnet` is refused and the signer is never called. + * + * The chain installed into the built core stands in for Stellar's adapter and + * opens every gate that is not Wasit's own: it takes any key, its RPC answers + * the mainnet passphrase, its scheme signs whatever it is asked and records it, + * and the paywall settles every paid request. A control run on stellar:testnet + * shows the recorder sees a signature when one is made. + * + * Seeded, so a failure is reproducible: set WASIT_PROPERTY_SEED to the seed in + * the message. Every key is made up; nothing leaves 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import http from "node:http"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, afterEach, before, beforeEach, describe, it } from "node:test"; + +import { Keypair, Networks } from "@stellar/stellar-sdk"; +import type { PaymentRequirements } from "@x402/core/types"; + +import { setRpcIdentityTransportForTesting } from "@wasit-dev/core/dist/guard/rpc-identity.js"; +import { setPaymentChainsForTesting } from "@wasit-dev/core/dist/x402/chains/index.js"; +import type { PaymentChain } from "@wasit-dev/core/dist/x402/chains/types.js"; + +import { executeRun, type RunCommandOptions } from "../../src/run.js"; + +const PUBNET = "stellar:pubnet"; +const TESTNET = "stellar:testnet"; +const PUBNET_USDC = "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75"; +const TESTNET_USDC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; +const PAY_TO = Keypair.random().publicKey(); +const PAYER = Keypair.random().publicKey(); +const PASSPHRASES: Record = { [PUBNET]: Networks.PUBLIC, [TESTNET]: Networks.TESTNET }; + +/** mulberry32: small, seeded, good enough to pick test cases. */ +function random(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function pick(next: () => number, values: readonly T[]): T { + return values[Math.floor(next() * values.length)]!; +} + +const signed: PaymentRequirements[] = []; + +function permissiveStellar(): PaymentChain { + const asset = (network: string): string => (network === PUBNET ? PUBNET_USDC : TESTNET_USDC); + return { + name: "Recording Stellar", + networks: [TESTNET, PUBNET], + payerKeyEnv: "STELLAR_PRIVATE_KEY", + referenceKind: "a test reference", + resolveRpcUrl: (network, override) => override || `http://127.0.0.1:9/${network}`, + registerPayer(client) { + for (const network of [TESTNET, PUBNET] as const) { + client.register(network, { + scheme: "exact", + findDefaultAsset: (wanted, on) => (on === network && wanted === asset(network) ? { asset: wanted, decimals: 7, symbol: "USDC" } : undefined), + async createPaymentPayload(version, requirements) { + signed.push(requirements); + return { x402Version: version, payload: { signature: `sig-${signed.length}` } }; + }, + }); + } + }, + expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 0 }), + payerAddress: () => PAYER, + generatePayerKey: () => Keypair.random().secret(), + payerBalance: async () => 10n ** 30n, + isSettlementReference: (reference) => reference.startsWith("tx-"), + verifySettlement: async () => ({ pass: true, detail: "settled (recording chain)" }), + corruptPayload: (payload) => ({ ...payload, signature: "corrupted" }), + }; +} + +interface Wall { + readonly base: string; + readonly requests: () => number; + readonly paid: () => number; + readonly close: () => Promise; +} + +/** Answers every unpaid request with `accepts` and settles every paid one. */ +async function wall(accepts: PaymentRequirements[]): Promise { + let requests = 0; + let paid = 0; + const server = http.createServer((request, response) => { + request.on("data", () => undefined); + request.on("end", () => { + requests += 1; + if (typeof request.headers["payment-signature"] === "string" || typeof request.headers["x-payment"] === "string") { + paid += 1; + const settled = { success: true, transaction: `tx-${paid}`, network: accepts[0]?.network, payer: PAYER }; + response.writeHead(200, { "content-type": "application/json", "payment-response": Buffer.from(JSON.stringify(settled)).toString("base64") }); + response.end("{}"); + return; + } + const challenge = { x402Version: 2, resource: { url: "http://127.0.0.1/paid" }, accepts }; + response.writeHead(402, { "content-type": "application/json", "payment-required": Buffer.from(JSON.stringify(challenge)).toString("base64") }); + response.end("{}"); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + base: `http://127.0.0.1:${port}`, + requests: () => requests, + paid: () => paid, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +function challengeOption(network: string, amount: bigint): PaymentRequirements { + return { + scheme: "exact", + network: network as PaymentRequirements["network"], + amount: amount.toString(), + asset: network === PUBNET ? PUBNET_USDC : TESTNET_USDC, + payTo: PAY_TO, + maxTimeoutSeconds: 60, + extra: { areFeesSponsored: true }, + }; +} + +async function execute(options: RunCommandOptions, env: Record) { + const out: string[] = []; + const err: string[] = []; + const code = await executeRun(options, { env: { PATH: process.env["PATH"] ?? "", ...env }, stdout: (line) => out.push(line), stderr: (line) => err.push(line) }); + return { code, stdout: out.join("\n"), stderr: err.join("\n") }; +} + +const PAYMENT_CHECK = /^X402-(0[6-9]|1[01])$/; + +describe("no allow path for stellar:pubnet (B11, B12), through wasit run", () => { + let dir: string; + let eventFile: string; + let target: Wall | undefined; + + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-no-allow-")); + eventFile = path.join(dir, "event.json"); + await writeFile(eventFile, JSON.stringify({ repository: { default_branch: "main" } })); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + beforeEach(() => { + signed.length = 0; + setPaymentChainsForTesting([permissiveStellar()]); + setRpcIdentityTransportForTesting(async (url: string, method: string) => + method === "getNetwork" ? { passphrase: PASSPHRASES[new URL(url).pathname.slice(1)] ?? Networks.PUBLIC } : undefined, + ); + }); + afterEach(async () => { + setPaymentChainsForTesting(undefined); + setRpcIdentityTransportForTesting(undefined); + await target?.close(); + target = undefined; + }); + + async function config(network: string, base: string, next: () => number): Promise { + const file = path.join(dir, `config-${Math.random().toString(36).slice(2)}.json`); + const environment: Record = { baseUrl: base, network }; + const operated = pick(next, [true, false, undefined]); + if (operated !== undefined) environment["operatedByMe"] = operated; + if (next() < 0.5) environment["pinned"] = { payTo: PAY_TO, asset: network === PUBNET ? PUBNET_USDC : TESTNET_USDC }; + if (next() < 0.5) environment["maxRunUsd"] = pick(next, [0.5, 1, 5]); + // A key the config may never hold: the loader refuses it, and the run stops there. + if (next() < 0.15) environment[pick(next, ["mainnet", "optIn", "pubnetOptIn"])] = true; + const count = 1 + Math.floor(next() * 3); + const endpoints = Array.from({ length: count }, (_, index) => ({ + name: `e${index}`, + protocol: "x402", + path: `/e${index}`, + method: "GET", + ...(next() < 0.5 ? { reject: { headers: { "x-lang": "xx" } } } : {}), + })); + await writeFile(file, JSON.stringify({ version: 1, defaultEnvironment: "env", environments: { env: environment }, endpoints })); + return file; + } + + it("control: the same chain on stellar:testnet signs through wasit run, so the recorder sees a signature when one is made", async () => { + target = await wall([challengeOption(TESTNET, 100_000n)]); + const file = path.join(dir, "control.json"); + await writeFile( + file, + JSON.stringify({ + version: 1, + defaultEnvironment: "env", + environments: { env: { baseUrl: target.base, network: TESTNET, operatedByMe: true } }, + endpoints: [{ name: "e0", protocol: "x402", path: "/e0", method: "GET" }], + }), + ); + const result = await execute({ config: file, readOnly: false, json: true, start: false }, { STELLAR_PRIVATE_KEY: Keypair.random().secret() }); + assert.ok(signed.length > 0, `the control signed nothing: ${result.stderr}`); + assert.ok(target.paid() > 0, "the control sent no payment"); + }); + + it("refuses every random combination: no signature, no paid request, no payment check passes; --mainnet stops before any request", async () => { + const seed = Number(process.env["WASIT_PROPERTY_SEED"] ?? Date.now() % 2 ** 31); + const next = random(seed); + for (let round = 0; round < 40; round += 1) { + const amount = BigInt(1 + Math.floor(next() * 10_000_000)); + target = await wall( + pick(next, [[challengeOption(PUBNET, amount)], [challengeOption(PUBNET, amount), challengeOption(TESTNET, amount)]]), + ); + const file = await config(PUBNET, target.base, next); + const dryRun = next() < 0.25; + const readOnly = !dryRun && next() < 0.25; + const mainnet = next() < 0.5; + const options: RunCommandOptions = { + config: file, + readOnly, + dryRun, + mainnet, + json: !dryRun && next() < 0.5, + start: false, + }; + const env: Record = {}; + if (next() < 0.6) env["STELLAR_PRIVATE_KEY"] = Keypair.random().secret(); + if (next() < 0.5) env["WASIT_MAINNET_PAYER_SECRET"] = Keypair.random().secret(); + if (next() < 0.3) env["WASIT_MAINNET_OPT_IN"] = pick(next, ["1", "true", "yes"]); + if (next() < 0.3) env["WASIT_MAINNET_CONFIG"] = file; + if (next() < 0.3) env["WASIT_RPC_URL"] = pick(next, [`http://127.0.0.1:9/${PUBNET}`, `http://127.0.0.1:9/${TESTNET}`]); + const event = pick(next, [undefined, "push", "schedule", "workflow_dispatch", "pull_request"]); + if (event !== undefined) { + Object.assign(env, { GITHUB_ACTIONS: "true", CI: "true", GITHUB_EVENT_NAME: event, GITHUB_REF: "refs/heads/main", GITHUB_EVENT_PATH: eventFile }); + } + + const result = await execute(options, env); + const label = `seed ${seed}, round ${round}: ${JSON.stringify({ ...options, config: "(file)", env: Object.keys(env) })}`; + assert.equal(signed.length, 0, `${label}: signed ${signed.length}\n${result.stderr}`); + assert.equal(target.paid(), 0, `${label}: a paid request reached the target`); + assert.doesNotMatch(result.stdout + result.stderr, /MAINNET RUN/, label); + if (mainnet) { + assert.equal(result.code, 2, label); + assert.equal(target.requests(), 0, `${label}: --mainnet let a request through`); + assert.match(result.stderr, /--mainnet is refused: the mainnet opt-in is not part of this version/, label); + } + // A run that asks to pay on pubnet exits 2. On a pull request the payment tier is the + // read-only tier (D-022a), which may pass: it pays nothing. + if (mainnet || dryRun || (!readOnly && event !== "pull_request")) { + assert.equal(result.code, 2, `${label}: a run that asked to pay on pubnet did not exit 2\n${result.stderr}`); + } + if (options.json && result.stdout.startsWith("{")) { + const report = JSON.parse(result.stdout) as { endpoints: Array<{ results: Array<{ id: string; status: string }> }> }; + for (const endpoint of report.endpoints) { + for (const entry of endpoint.results) { + assert.ok(!(PAYMENT_CHECK.test(entry.id) && entry.status === "PASS"), `${label}: ${entry.id} passed`); + } + } + } + for (const key of [env["STELLAR_PRIVATE_KEY"], env["WASIT_MAINNET_PAYER_SECRET"]]) { + if (key !== undefined) assert.ok(!(result.stdout + result.stderr).includes(key), `${label}: a key was printed`); + } + await target.close(); + target = undefined; + } + }); +}); diff --git a/packages/cli/test/unit/payment-helpers.ts b/packages/cli/test/unit/payment-helpers.ts new file mode 100644 index 0000000..ba1e53e --- /dev/null +++ b/packages/cli/test/unit/payment-helpers.ts @@ -0,0 +1,191 @@ +/** + * Tests only: the recording chain of core's tests (`packages/core/test/support/ + * recording-chain.ts`), installed into the BUILT core the CLI imports, and a + * paywall on loopback with one challenge per path that settles every paid + * request it gets. The chain records every signature and holds nothing; no + * request leaves 127.0.0.1 and no key is real. + * + * The seams are deep imports of core's dist, which the package index does not + * export: no flag, setting or tool argument of the CLI reaches them. + */ + +import http from "node:http"; + +import type { PaymentRequirements } from "@x402/core/types"; + +import { setRpcIdentityTransportForTesting } from "@wasit-dev/core/dist/guard/rpc-identity.js"; +import { setPaymentChainsForTesting } from "@wasit-dev/core/dist/x402/chains/index.js"; +import type { PaymentChain } from "@wasit-dev/core/dist/x402/chains/types.js"; + +export const NETWORK = "eip155:84532"; +/** Base Sepolia USDC, 6 decimals: $1 is 1,000,000 base units. */ +export const USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; +export const PAY_TO = "0x209693Bc6afc0C5328bA36FaF03C514EF312287C"; +export const OTHER_PAY_TO = "0x1111111111111111111111111111111111111111"; +export const PAYER = "0x2222222222222222222222222222222222222222"; +/** The variable the recording chain reads its key from. */ +export const KEY_ENV = "TEST_PAYER_KEY"; + +export interface Recorder { + readonly signed: PaymentRequirements[]; +} + +export interface RecordingChainOptions { + /** The variable the chain reads its key from. Default {@link KEY_ENV}. */ + readonly keyEnv?: string; + /** Take any non-empty key, as a real chain takes any valid one. Default: only "test-payer-key". */ + readonly anyKey?: boolean; + /** Give the chain an X402-11 watch that only exists: the plan counts X402-11; any read of it throws. */ + readonly stubWatch?: boolean; +} + +function recordingChain(recorder: Recorder, options: RecordingChainOptions = {}): PaymentChain { + return { + name: "Recording", + networks: [NETWORK], + payerKeyEnv: options.keyEnv ?? KEY_ENV, + referenceKind: "a test reference", + resolveRpcUrl: (_network, override) => override || "http://127.0.0.1:9/rpc", + registerPayer(client) { + client.register(NETWORK, { + scheme: "exact", + findDefaultAsset: (asset, network) => + network === NETWORK && asset.toLowerCase() === USDC.toLowerCase() + ? { asset: USDC, decimals: 6, symbol: "USDC" } + : undefined, + async createPaymentPayload(version, requirements) { + recorder.signed.push(requirements); + return { x402Version: version, payload: { signature: `sig-${recorder.signed.length}` } }; + }, + }); + }, + expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 0 }), + payerAddress: (key) => { + if (options.anyKey === true ? key === "" : key !== "test-payer-key") throw new Error("not a test key"); + return PAYER; + }, + generatePayerKey: () => "test-payer-key", + payerBalance: async () => 10n ** 30n, + isSettlementReference: (reference) => reference.startsWith("tx-"), + verifySettlement: async () => ({ pass: true, detail: "settled (recording chain)" }), + corruptPayload: (payload) => ({ ...payload, signature: "corrupted" }), + ...(options.stubWatch === true + ? { + authorizations: { + unit: "ledger", + unitMs: 1, + unitSeconds: 5, + decode: () => { + throw new Error("the stub watch reads nothing"); + }, + read: async () => { + throw new Error("the stub watch reads nothing"); + }, + transfers: async () => { + throw new Error("the stub watch reads nothing"); + }, + }, + } + : {}), + }; +} + +/** Installs the recording chain and an RPC that serves Base Sepolia. Returns the undo. */ +export function installRecordingChain(recorder: Recorder, options: RecordingChainOptions = {}): () => void { + setPaymentChainsForTesting([recordingChain(recorder, options)]); + setRpcIdentityTransportForTesting(async (_url, method) => (method === "eth_chainId" ? "0x14a34" : undefined)); + return () => { + setPaymentChainsForTesting(undefined); + setRpcIdentityTransportForTesting(undefined); + }; +} + +export function option(amount: string, payTo = PAY_TO): PaymentRequirements { + return { + scheme: "exact", + network: NETWORK as PaymentRequirements["network"], + amount, + asset: USDC, + payTo, + maxTimeoutSeconds: 60, + extra: { name: "USDC", version: "2" }, + }; +} + +export interface MultiPaywall { + readonly base: string; + /** What each path answers unpaid requests with. */ + readonly accepts: Map; + /** Paid requests received, by path. */ + readonly paid: Map; + /** Every request received, paid or not. */ + readonly requests: number; + /** Called before an unpaid request on `path` is answered, with how many that path has had: lets a test change the terms mid-run. */ + onChallenge?: (path: string, count: number) => void; + close(): Promise; +} + +/** A paywall that answers 402 on each configured path and settles every paid request. */ +export async function multiPaywall(paths: Record): Promise { + const accepts = new Map(Object.entries(paths)); + const paid = new Map(); + const challenges = new Map(); + const hooks: { onChallenge?: (path: string, count: number) => void } = {}; + let requests = 0; + const server = http.createServer((request, response) => { + request.on("data", () => undefined); + request.on("end", () => { + requests += 1; + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + if (!accepts.has(url.pathname)) { + response.writeHead(404); + response.end(); + return; + } + if (typeof request.headers["payment-signature"] !== "string") { + const count = (challenges.get(url.pathname) ?? 0) + 1; + challenges.set(url.pathname, count); + hooks.onChallenge?.(url.pathname, count); + } + const options = accepts.get(url.pathname) ?? []; + if (typeof request.headers["payment-signature"] === "string") { + const count = (paid.get(url.pathname) ?? 0) + 1; + paid.set(url.pathname, count); + const settled = { success: true, transaction: `tx-${url.pathname}-${count}`, network: NETWORK, payer: PAYER }; + response.writeHead(200, { + "content-type": "application/json", + "payment-response": Buffer.from(JSON.stringify(settled)).toString("base64"), + }); + response.end("{}"); + return; + } + const challenge = { x402Version: 2, resource: { url: `http://127.0.0.1${url.pathname}` }, accepts: options }; + response.writeHead(402, { + "content-type": "application/json", + "payment-required": Buffer.from(JSON.stringify(challenge)).toString("base64"), + }); + response.end("{}"); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + base: `http://127.0.0.1:${port}`, + accepts, + paid, + get requests() { + return requests; + }, + get onChallenge() { + return hooks.onChallenge; + }, + set onChallenge(hook) { + hooks.onChallenge = hook; + }, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} diff --git a/packages/cli/test/unit/run-cli.test.ts b/packages/cli/test/unit/run-cli.test.ts index 24e9c6d..274e6a6 100644 --- a/packages/cli/test/unit/run-cli.test.ts +++ b/packages/cli/test/unit/run-cli.test.ts @@ -76,7 +76,7 @@ describe("the wasit binary", () => { }); describe("flags that are not offered", () => { - for (const flag of [["--dry-run"], ["--mainnet"], ["--payer-key", "x"], ["--commitment-key", "x"], ["--allow-destructive"]]) { + for (const flag of [["--payer-key", "x"], ["--commitment-key", "x"], ["--allow-destructive"]]) { it(`wasit run ${flag[0]} is an unknown option, exit 2`, async () => { const result = await wasit(["run", "--read-only", ...flag], cwd); assert.equal(result.code, 2, result.stderr); @@ -84,28 +84,77 @@ describe("the wasit binary", () => { }); } + it("wasit run --mainnet is a switch that always refuses (B12): exit 2, the sentence, nothing read", async () => { + for (const args of [["run", "--mainnet"], ["run", "--read-only", "--mainnet"], ["run", "--dry-run", "--mainnet", "--config", "nope.json"]]) { + const result = await wasit(args, cwd); + assert.equal(result.code, 2, result.stderr); + assert.match(result.stderr, /^wasit run --mainnet is refused: the mainnet opt-in is not part of this version\./); + assert.doesNotMatch(result.stderr, /nope\.json|unknown option/); + } + }); + + it("wasit run --mainnet takes no value", async () => { + const result = await wasit(["run", "--mainnet=true"], cwd); + assert.equal(result.code, 2); + }); + + for (const command of [["test", "--target", "http://127.0.0.1:9/paid"], ["mpp-charge", "--target", "http://127.0.0.1:9/paid"]]) { + it(`wasit ${command[0]} --mainnet is an unknown option: the switch is on wasit run only`, async () => { + const result = await wasit([...command, "--mainnet"], cwd); + // These commands keep commander's own exit code for a usage error, as in 0.7.0. + assert.notEqual(result.code, 0, result.stderr); + assert.match(result.stderr, /unknown option/); + }); + } + it("wasit ci-report without --report is a usage error, exit 2", async () => { assert.equal((await wasit(["ci-report"], cwd)).code, 2); }); - it("the payment tier is refused with a message, exit 2, nothing sent", async () => { + it("the payment tier with no payer key sends no payment and exits 2, with the variable to set", async () => { const paywall = await startPaywall(); try { const config = await writeConfig(cwd, { baseUrl: paywall.base }); const result = await wasit(["run", "--config", config], cwd); assert.equal(result.code, 2); - assert.match(result.stderr, /not available in this version/); + assert.match(result.stdout, /no payer key: set STELLAR_PRIVATE_KEY/); + for (const request of paywall.received) assert.equal(request.headers["payment-signature"], undefined); + } finally { + await paywall.close(); + } + }); + + it("a pull request run with a payer key is refused before anything is sent, exit 2", async () => { + const paywall = await startPaywall(); + try { + const config = await writeConfig(cwd, { baseUrl: paywall.base }); + const result = await wasit(["run", "--config", config], cwd, { + GITHUB_ACTIONS: "true", + GITHUB_EVENT_NAME: "pull_request", + GITHUB_REF: "refs/pull/1/merge", + STELLAR_PRIVATE_KEY: "SNOTAKEY", + }); + assert.equal(result.code, 2); + assert.match(result.stderr, /STELLAR_PRIVATE_KEY is set, and this run may not pay \(pull request\)/); assert.equal(paywall.received.length, 0); } finally { await paywall.close(); } }); - it("--help works and exits 0", async () => { + it("--help works and exits 0, offers --dry-run, shows --mainnet as refused in this version, and no key flag", async () => { const result = await wasit(["run", "--help"], cwd); assert.equal(result.code, 0); assert.match(result.stdout, /--start/); - assert.ok(!/--mainnet|--dry-run|--payer-key/.test(result.stdout)); + assert.match(result.stdout, /--dry-run/); + assert.match(result.stdout, /--mainnet\s+Refused in this version/); + assert.ok(!/--payer-key/.test(result.stdout)); + }); + + it("wasit run --dry-run with --read-only is refused, exit 2", async () => { + const result = await wasit(["run", "--read-only", "--dry-run"], cwd); + assert.equal(result.code, 2, result.stderr); + assert.match(result.stderr, /choose --dry-run or --read-only/); }); }); diff --git a/packages/cli/test/unit/run-dry-run.test.ts b/packages/cli/test/unit/run-dry-run.test.ts new file mode 100644 index 0000000..a1c42c3 --- /dev/null +++ b/packages/cli/test/unit/run-dry-run.test.ts @@ -0,0 +1,202 @@ +/** + * `wasit run --dry-run` (spec B5, safety rule 5): L0 and L1 only. It reads each + * x402 endpoint's unpaid challenge, prints the plan (network, destination, + * asset, amount per check, caps, worst case) and exits. It needs no key, sends + * no payment and signs nothing. + * + * Exit 0: a paying run could start as planned. Exit 2: it would be refused + * (worst case above the cap, an endpoint the guard refuses, a network that is + * not a test network, `operatedByMe` not set). + */ + +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, beforeEach, describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; + +import { executeRun, type RunCommandOptions } from "../../src/run.js"; +import { startPaywall, writeConfig, type Handler, type Paywall } from "./run-helpers.js"; + +const USDC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; +const PAY_TO = Keypair.random().publicKey(); + +function priced(amount: string, payTo = PAY_TO): Handler { + const header = Buffer.from( + JSON.stringify({ + x402Version: 2, + resource: { url: "http://127.0.0.1/paid" }, + accepts: [{ scheme: "exact", network: "stellar:testnet", amount, asset: USDC, payTo, maxTimeoutSeconds: 60, extra: {} }], + }), + ).toString("base64"); + return (_request, response) => { + response.writeHead(402, { "payment-required": header, "content-type": "application/json" }); + response.end("{}"); + }; +} + +async function dryRun(options: Partial & { config: string }, env: Record = {}) { + const out: string[] = []; + const err: string[] = []; + const code = await executeRun( + { readOnly: false, dryRun: true, json: false, start: false, ...options }, + { env: { PATH: process.env["PATH"] ?? "", ...env }, stdout: (line) => out.push(line), stderr: (line) => err.push(line) }, + ); + return { code, stdout: out.join("\n"), stderr: err.join("\n") }; +} + +describe("wasit run --dry-run", () => { + let dir: string; + let paywall: Paywall | undefined; + + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-dry-run-")); + }); + after(async () => { + await paywall?.close(); + await rm(dir, { recursive: true, force: true }); + }); + beforeEach(async () => { + await paywall?.close(); + paywall = undefined; + }); + + it("prints the plan with no key in the environment, sends only unpaid requests, and exits 0", async () => { + paywall = await startPaywall(priced("100000")); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const result = await dryRun({ config }); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /Plan \(dry run\): x402 payment checks on stellar:testnet\. Nothing is signed or sent\./); + assert.match(result.stdout, /Caps: \$1\.00 a payment, \$5\.00 this run\./); + assert.match(result.stdout, new RegExp(`weather: pays "${PAY_TO}" in "${USDC}", up to \\$0\\.035`)); + assert.match(result.stdout, /X402-06 100000, X402-07 100000, X402-09 50000, X402-10 100000 \(base units\)/); + assert.match(result.stdout, /Worst case: \$0\.035 of \$5\.00\./); + assert.ok(paywall.received.length > 0); + for (const request of paywall.received) { + assert.equal(request.headers["payment-signature"], undefined, "a dry run sent a payment"); + } + }); + + it("never prints a key that is in the environment", async () => { + paywall = await startPaywall(priced("100000")); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + const canary = Keypair.random().secret(); + const result = await dryRun({ config }, { STELLAR_PRIVATE_KEY: canary, WASIT_MAINNET_PAYER_SECRET: canary }); + assert.equal(result.code, 0, result.stderr); + assert.ok(!`${result.stdout}\n${result.stderr}`.includes(canary)); + }); + + it("refuses a run whose worst case is above the cap, and exits 2", async () => { + paywall = await startPaywall(priced("10000000")); + const config = await writeConfig(dir, { + baseUrl: paywall.base, + endpoints: [ + { name: "weather", protocol: "x402", path: "/weather", method: "GET" }, + { name: "summarize", protocol: "x402", path: "/summarize", method: "GET" }, + ], + }); + const result = await dryRun({ config }); + assert.equal(result.code, 2); + assert.match( + result.stdout, + /Refused: This run could spend up to \$7\.00 \(weather \$3\.50, summarize \$3\.50\), above the \$5\.00 per run\. Nothing was signed\./, + ); + }); + + it("uses the lower cap of maxRunUsd, and the pin, from the config", async () => { + paywall = await startPaywall(priced("10000000")); + const config = path.join(dir, "pinned.json"); + await writeFile( + config, + JSON.stringify({ + version: 1, + environments: { + local: { + baseUrl: paywall.base, + network: "stellar:testnet", + operatedByMe: true, + maxRunUsd: 2, + pinned: { payTo: PAY_TO, asset: USDC }, + }, + }, + endpoints: [{ name: "weather", protocol: "x402", path: "/weather", method: "GET" }], + }), + ); + const result = await dryRun({ config }); + assert.equal(result.code, 2); + assert.match(result.stdout, /Caps: \$1\.00 a payment, \$2\.00 this run \(maxRunUsd\)\./); + assert.match(result.stdout, new RegExp(`Pinned: payTo ${PAY_TO}, asset ${USDC}\\.`)); + assert.match(result.stdout, /above the \$2\.00 per run set by maxRunUsd/); + }); + + it("refuses an endpoint off the pin, and exits 2", async () => { + paywall = await startPaywall(priced("100000", Keypair.random().publicKey())); + const config = path.join(dir, "off-pin.json"); + await writeFile( + config, + JSON.stringify({ + version: 1, + environments: { + local: { baseUrl: paywall.base, network: "stellar:testnet", operatedByMe: true, pinned: { payTo: PAY_TO, asset: USDC } }, + }, + endpoints: [{ name: "weather", protocol: "x402", path: "/weather", method: "GET" }], + }), + ); + const result = await dryRun({ config }); + assert.equal(result.code, 2); + assert.match(result.stdout, /weather: refused: .*payTo/); + }); + + it("refuses a network that is not a test network before anything is sent", async () => { + paywall = await startPaywall(priced("100000")); + const config = await writeConfig(dir, { baseUrl: paywall.base, network: "stellar:pubnet" }); + const result = await dryRun({ config }); + assert.equal(result.code, 2); + assert.match(result.stderr, /the mainnet opt-in is not part of this version/); + assert.equal(paywall.received.length, 0); + }); + + it("says a paying run would be refused when operatedByMe is not set", async () => { + paywall = await startPaywall(priced("100000")); + const config = path.join(dir, "not-mine.json"); + await writeFile( + config, + JSON.stringify({ + version: 1, + environments: { local: { baseUrl: paywall.base, network: "stellar:testnet" } }, + endpoints: [{ name: "weather", protocol: "x402", path: "/weather", method: "GET" }], + }), + ); + const result = await dryRun({ config }); + assert.equal(result.code, 2); + assert.match(result.stdout, /operatedByMe/); + }); + + it("names MPP endpoints as not planned, and sends them nothing", async () => { + paywall = await startPaywall(priced("100000")); + const config = await writeConfig(dir, { + baseUrl: paywall.base, + endpoints: [ + { name: "weather", protocol: "x402", path: "/weather", method: "GET" }, + { name: "metered", protocol: "mpp-charge", path: "/metered", method: "GET" }, + ], + }); + const result = await dryRun({ config }); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /metered: not planned/); + assert.ok(paywall.received.every((request) => request.url === "/weather")); + }); + + it("takes neither --read-only nor --json, --out or --baseline", async () => { + paywall = await startPaywall(priced("100000")); + const config = await writeConfig(dir, { baseUrl: paywall.base }); + for (const extra of [{ readOnly: true }, { json: true }, { out: path.join(dir, "out.json") }, { baseline: path.join(dir, "b.json") }]) { + const result = await dryRun({ config, ...extra }); + assert.equal(result.code, 2, JSON.stringify(extra)); + assert.match(result.stderr, /--dry-run/); + } + assert.equal(paywall.received.length, 0); + }); +}); diff --git a/packages/cli/test/unit/run-mainnet.test.ts b/packages/cli/test/unit/run-mainnet.test.ts new file mode 100644 index 0000000..50c0b40 --- /dev/null +++ b/packages/cli/test/unit/run-mainnet.test.ts @@ -0,0 +1,172 @@ +/** + * `wasit run --mainnet` in this version (spec B5, B12): a switch that always + * refuses, exit 2, before anything else is done. The config is not read, the + * service is not started, no request is sent and nothing is signed, whatever + * else the run was given: a pubnet environment with operatedByMe and a pin, a + * payer key, the mainnet payer variable, --dry-run or --read-only. + * + * In GitHub Actions on an event that is not workflow_dispatch the message says + * that rule too (spec B5: the switch is taken only on a run started by hand). + * + * Written before the code (CONTEXT rule 3). Every key is made up; nothing + * leaves 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, afterEach, before, beforeEach, describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; + +import { executeRun, type RunCommandOptions } from "../../src/run.js"; +import { installRecordingChain, multiPaywall, option, type MultiPaywall, type Recorder } from "./payment-helpers.js"; + +const SENTENCE = "wasit run --mainnet is refused: the mainnet opt-in is not part of this version."; +const PUBNET_USDC = "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75"; + +async function run(options: Partial & { config: string }, env: Record = {}, cwd?: string) { + const out: string[] = []; + const err: string[] = []; + const code = await executeRun( + { readOnly: false, json: false, start: false, mainnet: true, ...options }, + { env: { PATH: process.env["PATH"] ?? "", ...env }, stdout: (line) => out.push(line), stderr: (line) => err.push(line), ...(cwd === undefined ? {} : { cwd }) }, + ); + return { code, stdout: out.join("\n"), stderr: err.join("\n") }; +} + +describe("wasit run --mainnet (B12: a switch that always refuses)", () => { + let dir: string; + let paywall: MultiPaywall | undefined; + let recorder: Recorder; + let undo: (() => void) | undefined; + let eventFile: string; + + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-run-mainnet-")); + eventFile = path.join(dir, "event.json"); + await writeFile(eventFile, JSON.stringify({ repository: { default_branch: "main" } })); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + beforeEach(() => { + recorder = { signed: [] }; + undo = installRecordingChain(recorder); + }); + afterEach(async () => { + undo?.(); + await paywall?.close(); + paywall = undefined; + }); + + async function pubnetConfig(base: string, service?: { start: string }): Promise { + const file = path.join(dir, `config-${Math.random().toString(36).slice(2)}.json`); + await writeFile( + file, + JSON.stringify({ + version: 1, + defaultEnvironment: "mainnet", + environments: { + mainnet: { + baseUrl: base, + network: "stellar:pubnet", + operatedByMe: true, + pinned: { payTo: Keypair.random().publicKey(), asset: PUBNET_USDC }, + maxRunUsd: 1, + }, + }, + ...(service === undefined ? {} : { service: { ...service, ready: { url: `${base}/weather`, timeoutSeconds: 5 } } }), + endpoints: [{ name: "weather", protocol: "x402", path: "/weather", method: "GET", reject: { headers: { "x-lang": "xx" } } }], + }), + ); + return file; + } + + it("refuses at once, exit 2, with the sentence of B12, and says nothing was done", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const result = await run({ config: await pubnetConfig(paywall.base) }); + assert.equal(result.code, 2); + assert.ok(result.stderr.startsWith(SENTENCE), result.stderr); + assert.match(result.stderr, /Wasit pays on test networks only \(stellar:testnet, /); + assert.match(result.stderr, /The config was not read, and nothing was started, sent or signed\.$/); + assert.equal(result.stdout, ""); + assert.equal(paywall.requests, 0); + assert.equal(recorder.signed.length, 0); + }); + + it("does not read the config: a file that does not exist gets the same refusal", async () => { + const result = await run({ config: path.join(dir, "nope.json") }); + assert.equal(result.code, 2); + assert.ok(result.stderr.startsWith(SENTENCE), result.stderr); + assert.doesNotMatch(result.stderr, /nope\.json|cannot|not found/i); + }); + + for (const flags of [{ dryRun: true }, { readOnly: true }, { json: true, out: "report.json" }, { start: true }, { startIfLocal: true }, { endpoint: ["weather"] }] as const) { + it(`refuses with ${JSON.stringify(flags)} too: nothing started, sent or signed, no report written`, async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const marker = path.join(dir, `started-${Math.random().toString(36).slice(2)}`); + const config = await pubnetConfig(paywall.base, { start: `node -e "require('fs').writeFileSync(${JSON.stringify(marker)}, '1')"` }); + const out = path.join(dir, `report-${Math.random().toString(36).slice(2)}.json`); + const result = await run({ config, ...flags, ...("out" in flags ? { out } : {}) }, {}, dir); + assert.equal(result.code, 2); + assert.ok(result.stderr.startsWith(SENTENCE), result.stderr); + assert.equal(paywall.requests, 0); + assert.equal(recorder.signed.length, 0); + assert.ok(!existsSync(marker), "the service was started"); + assert.ok(!existsSync(out), "a report was written"); + }); + } + + it("never prints the keys it was given, the mainnet payer variable included", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const testnetKey = Keypair.random().secret(); + const mainnetKey = Keypair.random().secret(); + const result = await run( + { config: await pubnetConfig(paywall.base) }, + { STELLAR_PRIVATE_KEY: testnetKey, WASIT_MAINNET_PAYER_SECRET: mainnetKey, WASIT_MAINNET_OPT_IN: "1" }, + ); + assert.equal(result.code, 2); + for (const key of [testnetKey, mainnetKey]) assert.ok(!(result.stdout + result.stderr).includes(key)); + assert.equal(paywall.requests, 0); + }); + + for (const event of ["push", "schedule", "pull_request"]) { + it(`in GitHub Actions on ${event}: refused, and the message adds the workflow_dispatch rule and names the event`, async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const result = await run( + { config: await pubnetConfig(paywall.base) }, + { GITHUB_ACTIONS: "true", CI: "true", GITHUB_EVENT_NAME: event, GITHUB_REF: "refs/heads/main", GITHUB_EVENT_PATH: eventFile }, + ); + assert.equal(result.code, 2); + assert.ok(result.stderr.startsWith(SENTENCE), result.stderr); + assert.ok( + result.stderr.includes(`--mainnet is also refused on every GitHub event but workflow_dispatch, and this run's event is ${event}.`), + result.stderr, + ); + assert.equal(paywall.requests, 0); + }); + } + + it("in GitHub Actions on workflow_dispatch: still refused, without the event rule", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const result = await run( + { config: await pubnetConfig(paywall.base) }, + { GITHUB_ACTIONS: "true", CI: "true", GITHUB_EVENT_NAME: "workflow_dispatch", GITHUB_REF: "refs/heads/main", GITHUB_EVENT_PATH: eventFile }, + ); + assert.equal(result.code, 2); + assert.ok(result.stderr.startsWith(SENTENCE), result.stderr); + assert.doesNotMatch(result.stderr, /also refused/); + assert.equal(paywall.requests, 0); + }); + + it("is not read from the environment: WASIT_MAINNET_OPT_IN without the flag changes nothing", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const result = await run({ config: await pubnetConfig(paywall.base), mainnet: false, readOnly: true }, { WASIT_MAINNET_OPT_IN: "1" }); + assert.doesNotMatch(result.stderr, /--mainnet/); + assert.equal(recorder.signed.length, 0); + assert.equal(paywall.paid.size, 0); + }); +}); diff --git a/packages/cli/test/unit/run-payment.test.ts b/packages/cli/test/unit/run-payment.test.ts new file mode 100644 index 0000000..e171748 --- /dev/null +++ b/packages/cli/test/unit/run-payment.test.ts @@ -0,0 +1,475 @@ +/** + * The payment tier of `wasit run` (slice 3a; spec A1, A2, A8 #9, B3, B4; D-022a + * option 2 and Najmi's answers of 2026-11-16, s2-build-plan.md). + * + * A run without --read-only and without --dry-run is the payment tier. It pays + * only when every one of these holds: the network is a test network (L0), the + * environment has `operatedByMe: true`, the chain's key variable is set, the + * GitHub event may pay (push to the default branch, schedule, workflow_dispatch + * on the default branch; outside GitHub Actions always), and the plan (L1) fits + * the caps. One budget is shared by every endpoint, the plan's entry for each + * endpoint goes to its checks, and the pin and `maxRunUsd` come from the config. + * + * Written before the code (CONTEXT rule 3). The chain is a recorder that signs + * nothing real; the paywall is on 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, afterEach, before, beforeEach, describe, it } from "node:test"; + +import { setRpcIdentityTransportForTesting } from "@wasit-dev/core/dist/guard/rpc-identity.js"; + +import { executeRun, type RunCommandOptions } from "../../src/run.js"; +import { + KEY_ENV, + NETWORK, + OTHER_PAY_TO, + PAY_TO, + USDC, + installRecordingChain, + multiPaywall, + option, + type MultiPaywall, + type Recorder, +} from "./payment-helpers.js"; + +interface EnvironmentSpec { + readonly network?: string; + readonly operatedByMe?: boolean; + readonly pinned?: { payTo: string; asset: string }; + readonly maxRunUsd?: number; +} + +async function writePaymentConfig( + dir: string, + base: string, + environment: EnvironmentSpec = {}, + endpoints: ReadonlyArray> = [{ name: "weather", protocol: "x402", path: "/weather", method: "GET" }], +): Promise { + const file = path.join(dir, `config-${Math.random().toString(36).slice(2)}.json`); + await writeFile( + file, + JSON.stringify({ + version: 1, + defaultEnvironment: "local", + environments: { + local: { + baseUrl: base, + network: environment.network ?? NETWORK, + operatedByMe: environment.operatedByMe ?? true, + ...(environment.pinned === undefined ? {} : { pinned: environment.pinned }), + ...(environment.maxRunUsd === undefined ? {} : { maxRunUsd: environment.maxRunUsd }), + }, + }, + endpoints, + }), + ); + return file; +} + +const KEY = { [KEY_ENV]: "test-payer-key" }; + +async function pay(options: Partial & { config: string }, env: Record = {}) { + const out: string[] = []; + const err: string[] = []; + const code = await executeRun( + { readOnly: false, json: true, start: false, ...options }, + { env: { PATH: process.env["PATH"] ?? "", ...env }, stdout: (line) => out.push(line), stderr: (line) => err.push(line) }, + ); + const stdout = out.join("\n"); + let report: any; + try { + report = JSON.parse(stdout); + } catch { + report = undefined; + } + return { code, stdout, stderr: err.join("\n"), report }; +} + +function results(report: any, endpoint = "weather"): Array<{ id: string; status: string; skipKind?: string; detail: string; errorKind?: string }> { + const found = report.endpoints.find((entry: any) => entry.name === endpoint); + assert.ok(found, `no endpoint ${endpoint} in the report`); + return found.results; +} + +function result(report: any, id: string, endpoint = "weather") { + const found = results(report, endpoint).find((entry) => entry.id === id); + assert.ok(found, `no ${id} for ${endpoint}`); + return found; +} + +describe("wasit run, payment tier", () => { + let dir: string; + let paywall: MultiPaywall | undefined; + let recorder: Recorder; + let undo: (() => void) | undefined; + + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-run-payment-")); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + beforeEach(() => { + recorder = { signed: [] }; + undo = installRecordingChain(recorder); + }); + afterEach(async () => { + undo?.(); + await paywall?.close(); + paywall = undefined; + }); + + it("pays on a test network with the key, operatedByMe and no CI: every signature to the endpoint's payTo in USDC", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config }, KEY); + assert.ok(run.report, run.stderr); + assert.equal(result(run.report, "X402-06").status, "PASS", run.stderr); + assert.ok(recorder.signed.length >= 3, "the payment checks did not sign"); + for (const signed of recorder.signed) { + assert.equal(signed.payTo, PAY_TO); + assert.equal(signed.asset, USDC); + assert.equal(signed.network, NETWORK); + } + assert.ok((paywall.paid.get("/weather") ?? 0) > 0); + }); + + it("says in its notes and on stderr that it pays, on which network, and what it charged of the cap", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config }, KEY); + const notes: string[] = run.report.notes; + assert.ok(notes.some((note) => /^Tier: payment on eip155:84532\b/.test(note)), notes.join(" | ")); + assert.ok(notes.some((note) => /\$0\.035 of the \$5\.00/.test(note)), notes.join(" | ")); + assert.match(run.stderr, /Payment tier on eip155:84532 \(test network\)/); + assert.match(run.stderr, /at most \$1\.00 per payment/); + }); + + it("shares one budget across the endpoints: the charge in the notes is the sum", async () => { + paywall = await multiPaywall({ "/a": [option("10000")], "/b": [option("20000")] }); + const config = await writePaymentConfig(dir, paywall.base, {}, [ + { name: "a", protocol: "x402", path: "/a", method: "GET" }, + { name: "b", protocol: "x402", path: "/b", method: "GET" }, + ]); + const run = await pay({ config }, KEY); + // a: 3.5 x $0.01, b: 3.5 x $0.02. + assert.ok(run.report.notes.some((note: string) => /\$0\.105 of the \$5\.00/.test(note)), run.report.notes.join(" | ")); + }); + + it("refuses the whole run before any signature when the plan is above maxRunUsd", async () => { + paywall = await multiPaywall({ "/a": [option("10000")], "/b": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base, { maxRunUsd: 0.05 }, [ + { name: "a", protocol: "x402", path: "/a", method: "GET" }, + { name: "b", protocol: "x402", path: "/b", method: "GET" }, + ]); + const run = await pay({ config }, KEY); + assert.equal(run.code, 2); + assert.match(run.stderr, /could spend up to \$0\.07 .*above the \$0\.05 per run set by maxRunUsd\. Nothing was signed\./); + assert.equal(recorder.signed.length, 0); + assert.equal(paywall.paid.size, 0); + }); + + it("gives the payment group ERROR (setup) with both values when the service does not pay the pinned payTo", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base, { pinned: { payTo: OTHER_PAY_TO, asset: USDC } }); + const run = await pay({ config }, KEY); + assert.equal(run.code, 2, run.stderr); + const first = result(run.report, "X402-06"); + assert.equal(first.status, "ERROR"); + assert.equal(first.errorKind, "setup"); + assert.ok(first.detail.includes(PAY_TO) && first.detail.includes(OTHER_PAY_TO), first.detail); + assert.equal(recorder.signed.length, 0); + }); + + it("refuses to sign above $1 on a test network: that endpoint is ERROR (setup), the others still run", async () => { + paywall = await multiPaywall({ "/dear": [option("2000000")], "/cheap": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base, {}, [ + { name: "dear", protocol: "x402", path: "/dear", method: "GET" }, + { name: "cheap", protocol: "x402", path: "/cheap", method: "GET" }, + ]); + const run = await pay({ config }, KEY); + const dear = result(run.report, "X402-06", "dear"); + assert.equal(dear.status, "ERROR"); + assert.equal(dear.errorKind, "setup"); + assert.match(dear.detail, /\$1\.00/); + assert.equal(result(run.report, "X402-06", "cheap").status, "PASS"); + for (const signed of recorder.signed) assert.notEqual(signed.amount, "2000000"); + }); + + it("hands each endpoint its entry of the plan: a price raised after the plan is refused at signing", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const wall = paywall; + // The plan reads the first challenge; every later one asks for twice the price, still under $1. + wall.onChallenge = (_path, count) => { + if (count === 1) return; + wall.accepts.set("/weather", [option("20000")]); + }; + const config = await writePaymentConfig(dir, wall.base); + const run = await pay({ config }, KEY); + const first = result(run.report, "X402-06"); + assert.equal(first.status, "ERROR", first.detail); + assert.match(first.detail, /after the plan/); + for (const signed of recorder.signed) assert.notEqual(signed.amount, "20000"); + }); + + it("hands the pin to every signature: a second option to another payTo, added after the plan, is refused", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const wall = paywall; + wall.onChallenge = (_path, count) => { + if (count === 1) return; + wall.accepts.set("/weather", [option("10000"), option("10000", OTHER_PAY_TO)]); + }; + const config = await writePaymentConfig(dir, wall.base, { pinned: { payTo: PAY_TO, asset: USDC } }); + const run = await pay({ config }, KEY); + const first = result(run.report, "X402-06"); + assert.equal(first.status, "ERROR", first.detail); + assert.ok(first.detail.includes(OTHER_PAY_TO), first.detail); + assert.equal(recorder.signed.length, 0); + }); + + it("does not pay without the chain's key: needs-payer naming the variable, and exit 2, since the tier asked for was not run", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config }); + assert.equal(run.code, 2, run.stderr); + assert.match(run.stderr, /payment checks were not run/); + for (const id of ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]) { + const entry = result(run.report, id); + assert.equal(entry.status, "SKIP"); + assert.equal(entry.skipKind, "needs-payer"); + assert.match(entry.detail, new RegExp(KEY_ENV)); + } + assert.equal(recorder.signed.length, 0); + }); + + it("does not pay a service whose environment is not operatedByMe: read-only checks only, the report says why, exit 2", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base, { operatedByMe: false }); + const run = await pay({ config }, KEY); + assert.equal(run.code, 2, run.stderr); + const entry = result(run.report, "X402-06"); + assert.equal(entry.status, "SKIP"); + assert.match(entry.detail, /operatedByMe/); + assert.equal(recorder.signed.length, 0); + assert.equal(paywall.paid.size, 0); + }); + + it("refuses stellar:pubnet before any request: the mainnet opt-in is not part of this version", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base, { + network: "stellar:pubnet", + pinned: { payTo: "GBRPYHIL2CI3FNQ4BXLFMNDLFJUNPU2HY3ZMFSHONUCEOASW7QC7OX2H", asset: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75" }, + }); + const run = await pay({ config }, { STELLAR_PRIVATE_KEY: "SXXX" }); + assert.equal(run.code, 2); + assert.match(run.stderr, /mainnet opt-in is not part of this version/); + assert.equal(paywall.requests, 0, "a request was sent on a network the payment tier refuses"); + assert.equal(recorder.signed.length, 0); + }); + + it("refuses an RPC of another network before the service starts or any request is sent (review R4)", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + // The RPC answers Ethereum mainnet's chain id; the run is on Base Sepolia. + setRpcIdentityTransportForTesting(async (_url, method) => (method === "eth_chainId" ? "0x1" : undefined)); + const run = await pay({ config }, KEY); + assert.equal(run.code, 2, run.stderr); + assert.match(run.stderr, /serves eip155:1,/); + assert.match(run.stderr, /no payment was sent and nothing was signed/i); + assert.match(run.stderr, /The service was not started\./); + assert.equal(paywall.requests, 0, "a request reached the service before the RPC was checked"); + assert.equal(recorder.signed.length, 0); + }); + + describe("in a CI that is not GitHub Actions (review R9 a, Najmi 2026-11-17)", () => { + const otherCi = { CI: "true" }; + + for (const [label, env] of [["with a payer key", KEY], ["without a payer key", {}]] as const) { + it(`refuses the payment tier ${label}: exit 2 before any request, and says to use --read-only`, async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config }, { ...otherCi, ...env }); + assert.equal(run.code, 2, run.stderr); + assert.match(run.stderr, /CI is set, and this is not GitHub Actions/); + assert.match(run.stderr, /--read-only/); + assert.match(run.stderr, /Nothing was started, sent or signed\./); + assert.equal(paywall.requests, 0); + assert.equal(recorder.signed.length, 0); + }); + } + + it("runs --read-only without a payer key", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config, readOnly: true }, otherCi); + assert.ok(run.report, run.stderr); + assert.ok(paywall.requests > 0); + assert.equal(recorder.signed.length, 0); + }); + + it("refuses --read-only with a payer key in the job: the service would run beside it", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config, readOnly: true }, { ...otherCi, STELLAR_PRIVATE_KEY: "SXXX" }); + assert.equal(run.code, 2, run.stderr); + assert.match(run.stderr, /STELLAR_PRIVATE_KEY is set: remove it from this job/); + assert.equal(paywall.requests, 0); + }); + }); + + it("skips the MPP endpoints with the reason: wasit run does not pay MPP in this version", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base, {}, [ + { name: "weather", protocol: "x402", path: "/weather", method: "GET" }, + { name: "chat", protocol: "mpp-charge", path: "/mpp/chat" }, + ]); + const run = await pay({ config }, KEY); + const mpp = result(run.report, "MPP-01", "chat"); + assert.equal(mpp.status, "SKIP"); + assert.match(mpp.detail, /wasit mpp-charge/); + }); + + describe("in GitHub Actions", () => { + let eventFile: string; + before(async () => { + eventFile = path.join(dir, "event.json"); + await writeFile(eventFile, JSON.stringify({ repository: { default_branch: "main" } })); + }); + const actions = (event: string, ref = "refs/heads/main") => ({ + GITHUB_ACTIONS: "true", + CI: "true", + GITHUB_EVENT_NAME: event, + GITHUB_REF: ref, + GITHUB_EVENT_PATH: eventFile, + }); + + for (const event of ["push", "schedule", "workflow_dispatch"]) { + it(`pays on ${event} on the default branch`, async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config }, { ...KEY, ...actions(event) }); + assert.equal(result(run.report, "X402-06").status, "PASS", run.stderr); + assert.ok(recorder.signed.length > 0); + }); + } + + it("runs the read-only tier on a pull request without a key: payment checks not run: pull request", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config }, actions("pull_request", "refs/pull/3/merge")); + assert.equal(run.code, 0, run.stderr); + const entry = result(run.report, "X402-06"); + assert.equal(entry.status, "SKIP"); + assert.equal(entry.skipKind, "read-only"); + assert.match(entry.detail, /payment checks not run: pull request/); + assert.equal(result(run.report, "X402-01").status, "PASS"); + assert.equal(recorder.signed.length, 0); + assert.equal(paywall.paid.size, 0); + }); + + it("runs a fork's pull request, whose secrets are empty, as read-only", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config }, { ...actions("pull_request", "refs/pull/3/merge"), STELLAR_PRIVATE_KEY: "", [KEY_ENV]: "" }); + assert.equal(run.code, 0, run.stderr); + assert.equal(recorder.signed.length, 0); + }); + + for (const tier of ["payment", "read-only"] as const) { + it(`refuses a ${tier} run on a pull request that has a payer key, before any request, and says how to give the key`, async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay( + { config, readOnly: tier === "read-only" }, + { ...actions("pull_request", "refs/pull/3/merge"), STELLAR_PRIVATE_KEY: "SCANARY" }, + ); + assert.equal(run.code, 2); + assert.match(run.stderr, /STELLAR_PRIVATE_KEY is set/); + assert.match(run.stderr, /pull request/); + assert.match(run.stderr, /github\.event_name != 'pull_request'/); + assert.doesNotMatch(run.stderr + run.stdout, /SCANARY/); + assert.equal(paywall.requests, 0, "a request was sent before the refusal"); + }); + } + + it("on a GitHub-hosted runner with a key, --start runs the service as a separate user, and refuses when it cannot", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const file = path.join(dir, `start-${Math.random().toString(36).slice(2)}.json`); + await writeFile( + file, + JSON.stringify({ + version: 1, + service: { start: "node -e 0", ready: { url: "http://127.0.0.1:9/", timeoutSeconds: 5 } }, + environments: { local: { baseUrl: paywall.base, network: NETWORK, operatedByMe: true } }, + endpoints: [{ name: "weather", protocol: "x402", path: "/weather", method: "GET" }], + }), + ); + const out: string[] = []; + const err: string[] = []; + const code = await executeRun( + { config: file, readOnly: false, json: true, start: true }, + { + env: { PATH: process.env["PATH"] ?? "", ...KEY, ...actions("push"), RUNNER_ENVIRONMENT: "github-hosted", EVM_PRIVATE_KEY: "0xabc" }, + stdout: (line) => out.push(line), + stderr: (line) => err.push(line), + sudo: path.join(dir, "no-such-sudo"), + }, + ); + assert.equal(code, 2); + assert.match(err.join("\n"), /separate user \(wasit-service\)/); + assert.equal(paywall.requests, 0, "the run went on without the separate user"); + assert.equal(recorder.signed.length, 0); + }); + + it("refuses a run on a push to another branch that has a key, before any request", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const run = await pay({ config }, { ...KEY, ...actions("push", "refs/heads/feature"), EVM_PRIVATE_KEY: "0xabc" }); + assert.equal(run.code, 2); + assert.match(run.stderr, /not the default branch/); + assert.equal(paywall.requests, 0); + assert.equal(recorder.signed.length, 0); + }); + }); + + it("hands the endpoint's reject case to X402-11; without one, X402-11 says the config has none", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")], "/plain": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base, {}, [ + { name: "weather", protocol: "x402", path: "/weather", method: "GET", reject: { headers: { "x-lang": "xx" } } }, + { name: "plain", protocol: "x402", path: "/plain", method: "GET" }, + ]); + const run = await pay({ config }, KEY); + assert.ok(run.report, run.stderr); + // The recording chain has no X402-11 watch: with a reject case the check gets as far as the chain. + assert.match(result(run.report, "X402-11").detail, /cannot read on Recording/); + assert.match(result(run.report, "X402-11", "plain").detail, /no request the service must refuse is configured/); + }); + + it("plans X402-11 for an endpoint with a reject case, on a chain it can read: the dry run lists it", async () => { + undo?.(); + undo = installRecordingChain(recorder, { stubWatch: true }); + paywall = await multiPaywall({ "/weather": [option("10000")], "/plain": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base, {}, [ + { name: "weather", protocol: "x402", path: "/weather", method: "GET", reject: { headers: { "x-lang": "xx" } } }, + { name: "plain", protocol: "x402", path: "/plain", method: "GET" }, + ]); + const run = await pay({ config, dryRun: true, json: false }); + assert.equal(run.code, 0, run.stderr); + assert.match(run.stdout, /X402-06 10000, X402-07 10000, X402-09 5000, X402-10 10000, X402-11 10000 \(base units\)/); + assert.match(run.stdout, /X402-06 10000, X402-07 10000, X402-09 5000, X402-10 10000 \(base units\)\n/); + assert.equal(recorder.signed.length, 0, "a dry run signs nothing"); + }); + + it("writes the report it printed to --out, with the payment results", async () => { + paywall = await multiPaywall({ "/weather": [option("10000")] }); + const config = await writePaymentConfig(dir, paywall.base); + const out = path.join(dir, "report.json"); + const run = await pay({ config, out }, KEY); + const written = JSON.parse(await readFile(out, "utf-8")); + assert.deepEqual(written, run.report); + }); +}); diff --git a/packages/cli/test/unit/run.test.ts b/packages/cli/test/unit/run.test.ts index ce1c960..43c8a6b 100644 --- a/packages/cli/test/unit/run.test.ts +++ b/packages/cli/test/unit/run.test.ts @@ -72,15 +72,14 @@ describe("wasit run", () => { paywall = undefined; }); - it("refuses the payment tier before it reads a config or sends anything", async () => { + it("runs the payment tier without --read-only; with no payer key it signs nothing and exits 2", async () => { paywall = await startPaywall(); const config = await writeConfig(dir, { baseUrl: paywall.base }); const result = await run({ config, readOnly: false }); assert.equal(result.code, 2); - assert.match(result.stderr, /not available in this version/); - assert.match(result.stderr, /--read-only/); - assert.equal(paywall.received.length, 0); - assert.equal((await run({ config: path.join(dir, "missing.json"), readOnly: false })).code, 2, "even for a missing config"); + assert.match(result.stdout, /no payer key: set STELLAR_PRIVATE_KEY/); + for (const request of paywall.received) assert.equal(request.headers["payment-signature"], undefined, "a payment was sent"); + assert.equal((await run({ config: path.join(dir, "missing.json"), readOnly: false })).code, 2, "a missing config"); }); describe("a conformant paywall", () => { @@ -98,9 +97,9 @@ describe("wasit run", () => { const [weather] = report.endpoints; assert.equal(weather?.outcome, "conformant"); assert.equal(weather?.groups.challenge?.passed, 5); - assert.equal(weather?.groups.payment?.skipped, 5); + assert.equal(weather?.groups.payment?.skipped, 6); const payment = weather?.results.filter((check) => check.status === "SKIP") ?? []; - assert.deepEqual(payment.map((check) => check.id), ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]); + assert.deepEqual(payment.map((check) => check.id), ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"]); for (const check of payment) assert.equal(check.skipKind, "read-only", check.id); assert.equal(report.totals.graded, 1); assert.ok(report.notes.some((note) => /read-only/.test(note))); diff --git a/packages/cli/test/unit/service-user.test.ts b/packages/cli/test/unit/service-user.test.ts new file mode 100644 index 0000000..ab5205f --- /dev/null +++ b/packages/cli/test/unit/service-user.test.ts @@ -0,0 +1,234 @@ +/** + * The service as a separate OS user (D-022a option 2; Najmi, 2026-11-16: only + * when a payer key variable is set AND the runner is GitHub-hosted). + * + * What these tests can show: when the run wants a separate user, Wasit makes + * the user with passwordless sudo, gives it access to the working directory + * only, starts the command through `sudo -n -u ` with the scrubbed + * environment on stdin (the hosted runner's sudo ignores -E), refuses to start when sudo or the user cannot be had (no + * fallback to the runner's own user), and stops the service through sudo. + * The sudo here is a stand-in script that records each call and runs the + * command as the same user: what these tests CANNOT show is the separation + * itself, which only a GitHub-hosted runner can (the example repository's run). + * + * Written before the code (CONTEXT rule 3). No key is real. + */ + +import assert from "node:assert/strict"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import net from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; + +import { SERVICE_USER, ServiceError, serviceUserFor, startService, type StartedService } from "../../src/service.js"; + +const POSIX = process.platform !== "win32"; +// A fresh random key, which holds nothing (review R8: no key-shaped literal in the repo). +const CANARY = Keypair.random().secret(); + +async function freePort(): Promise { + return new Promise((resolve, reject) => { + const probe = net.createServer(); + probe.once("error", reject); + probe.listen(0, "127.0.0.1", () => { + const { port } = probe.address() as net.AddressInfo; + probe.close(() => resolve(port)); + }); + }); +} + +async function waitUntil(condition: () => boolean, ms: number): Promise { + const end = Date.now() + ms; + while (Date.now() < end) { + if (condition()) return true; + await new Promise((resolve) => setTimeout(resolve, 25)); + } + return condition(); +} + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +describe("serviceUserFor", () => { + const hosted = { RUNNER_ENVIRONMENT: "github-hosted", GITHUB_ACTIONS: "true" }; + + it("wants a separate user when a payer key is set on a GitHub-hosted runner", () => { + assert.equal(serviceUserFor({ ...hosted, STELLAR_PRIVATE_KEY: "S" }), SERVICE_USER); + assert.equal(serviceUserFor({ ...hosted, EVM_PRIVATE_KEY: "0x1" }), SERVICE_USER); + }); + + it("does not without a key, with a blank key, on a self-hosted runner, or outside GitHub", () => { + assert.equal(serviceUserFor(hosted), undefined); + assert.equal(serviceUserFor({ ...hosted, STELLAR_PRIVATE_KEY: "" }), undefined); + assert.equal(serviceUserFor({ RUNNER_ENVIRONMENT: "self-hosted", GITHUB_ACTIONS: "true", STELLAR_PRIVATE_KEY: "S" }), undefined); + assert.equal(serviceUserFor({ STELLAR_PRIVATE_KEY: "S" }), undefined); + }); + + it("is a fixed name, not one a config or a variable can choose", () => { + assert.equal(SERVICE_USER, "wasit-service"); + }); +}); + +describe("startService as a separate user", { skip: !POSIX && "needs POSIX; not run on Windows" }, () => { + let dir: string; + let work: string; + const started: StartedService[] = []; + + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-service-user-")); + work = path.join(dir, "work"); + await writeFile(path.join(dir, ".keep"), ""); + await import("node:fs/promises").then((fs) => fs.mkdir(work)); + }); + after(async () => { + await Promise.all(started.map((service) => service.stop())); + await rm(dir, { recursive: true, force: true }); + }); + + /** + * A stand-in for sudo: records its arguments, one call a line, in `log`. + * `id -u` fails (no such user yet) unless `userExists`; `useradd` and + * `setfacl` succeed unless `failOn` names them; `-E -u -- ` runs + * the command (as the same user) after writing its pid; `pkill` and `pgrep` + * act on that pid's process group. + */ + async function fakeSudo(name: string, options: { failOn?: string; userExists?: boolean } = {}) { + const log = path.join(dir, `${name}.log`); + const pidFile = path.join(dir, `${name}.pid`); + const script = path.join(dir, `${name}.sh`); + await writeFile( + script, + `#!/bin/sh +printf '%s\\n' "$*" >> '${log}' +[ "$1" = "-n" ] || { echo "sudo stand-in: expected -n first" >&2; exit 64; } +shift +case "$1" in + id) ${options.userExists === true ? "exit 0" : "exit 1"} ;; + useradd|setfacl) [ "$1" = '${options.failOn ?? "-"}' ] && { echo "$1: refused by the test" >&2; exit 1; }; exit 0 ;; + pgrep) [ -f '${pidFile}' ] && kill -0 "-$(cat '${pidFile}')" 2>/dev/null && exit 0; exit 1 ;; + pkill) sig="$2"; [ -f '${pidFile}' ] && kill "$sig" "-$(cat '${pidFile}')" 2>/dev/null; exit 0 ;; + -E) echo "sudo stand-in: -E is not supported, as on the hosted runner's sudo" >&2; exit 68 ;; + -u) shift 2; [ "$1" = "--" ] || exit 66; shift + echo $$ > '${pidFile}' + exec "$@" ;; + *) echo "sudo stand-in: unexpected $1" >&2; exit 67 ;; +esac +`, + ); + await chmod(script, 0o755); + return { script, log, pidFile, calls: async () => (await readFile(log, "utf-8")).trim().split("\n") }; + } + + async function serverScript(port: number): Promise { + const file = path.join(dir, `server-${port}.mjs`); + await writeFile( + file, + `import http from "node:http"; +import { writeFileSync } from "node:fs"; +writeFileSync(${JSON.stringify(path.join(dir, `env-${port}.json`))}, JSON.stringify(process.env)); +http.createServer((q, s) => { s.writeHead(200); s.end("ok"); }).listen(${port}, "127.0.0.1"); +`, + ); + return file; + } + + it("makes the user, grants it the working directory, starts the command through sudo -u, without the key", async () => { + const sudo = await fakeSudo("ok"); + const port = await freePort(); + const script = await serverScript(port); + const service = await startService({ + command: `node ${JSON.stringify(script)}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 15 }, + env: { PATH: process.env["PATH"] ?? "", STELLAR_PRIVATE_KEY: CANARY, WASIT_HEADER_X_KEY: "hdr-secret", KEEP_ME: "yes" }, + cwd: work, + separateUser: { name: SERVICE_USER, sudo: sudo.script }, + log: () => undefined, + }); + started.push(service); + + const calls = await sudo.calls(); + assert.ok(calls.some((call) => /^-n id -u wasit-service$/.test(call)), calls.join("\n")); + assert.ok(calls.some((call) => /^-n useradd .*--system.*wasit-service$/.test(call)), calls.join("\n")); + assert.ok(calls.some((call) => call.startsWith("-n setfacl -R -m u:wasit-service:rwX") && call.endsWith(work.split(path.sep).pop() ?? "")), calls.join("\n")); + // The hosted runner's sudo ignores -E (run 43815743541, 2026-11-16): the environment goes on stdin. + const launch = calls.find((call) => call.startsWith(`-n -u wasit-service -- ${process.execPath} -e `)); + assert.ok(launch, calls.join("\n")); + assert.ok(!calls.some((call) => call.includes(" -E ")), "sudo -E is not used"); + assert.ok(!launch.includes(CANARY) && !launch.includes("hdr-secret"), "a secret was put on the command line"); + assert.ok(!launch.includes("KEEP_ME") && !launch.includes(script), "the environment and the command are passed on stdin, not on the command line"); + + const childEnv = JSON.parse(await readFile(path.join(dir, `env-${port}.json`), "utf-8")); + assert.equal(childEnv["KEEP_ME"], "yes"); + assert.equal(childEnv["HOME"], "/home/wasit-service"); + assert.equal(childEnv["USER"], "wasit-service"); + assert.equal(childEnv["STELLAR_PRIVATE_KEY"], undefined); + assert.equal(childEnv["WASIT_HEADER_X_KEY"], undefined); + assert.ok(!JSON.stringify(childEnv).includes(CANARY)); + + await service.stop(); + const after = await sudo.calls(); + assert.ok(after.some((call) => call === "-n pkill -TERM -u wasit-service"), after.join("\n")); + const pid = Number((await readFile(sudo.pidFile, "utf-8")).trim()); + assert.ok(await waitUntil(() => !alive(pid), 5000), "the service is still running"); + }); + + it("does not make the user again when it exists", async () => { + const sudo = await fakeSudo("exists", { userExists: true }); + const port = await freePort(); + const service = await startService({ + command: `node ${JSON.stringify(await serverScript(port))}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 15 }, + env: { PATH: process.env["PATH"] ?? "" }, + cwd: work, + separateUser: { name: SERVICE_USER, sudo: sudo.script }, + log: () => undefined, + }); + started.push(service); + assert.ok(!(await sudo.calls()).some((call) => call.includes("useradd"))); + await service.stop(); + }); + + for (const step of ["useradd", "setfacl"]) { + it(`refuses to start when ${step} fails, and does not fall back to the runner's own user`, async () => { + const sudo = await fakeSudo(`fail-${step}`, { failOn: step }); + const port = await freePort(); + await assert.rejects( + startService({ + command: `node ${JSON.stringify(await serverScript(port))}`, + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 5 }, + env: { PATH: process.env["PATH"] ?? "", STELLAR_PRIVATE_KEY: CANARY }, + cwd: work, + separateUser: { name: SERVICE_USER, sudo: sudo.script }, + log: () => undefined, + }), + (error: unknown) => + error instanceof ServiceError && /separate user/.test(error.message) && !error.message.includes(CANARY), + ); + assert.ok(!(await sudo.calls()).some((call) => call.startsWith("-n -u")), "the service was started"); + }); + } + + it("refuses when sudo itself cannot be run", async () => { + const port = await freePort(); + await assert.rejects( + startService({ + command: "node -e 0", + ready: { url: `http://127.0.0.1:${port}/`, timeoutSeconds: 5 }, + env: { PATH: process.env["PATH"] ?? "" }, + cwd: work, + separateUser: { name: SERVICE_USER, sudo: path.join(dir, "no-such-sudo") }, + log: () => undefined, + }), + (error: unknown) => error instanceof ServiceError && /separate user/.test(error.message), + ); + }); +}); diff --git a/packages/core/README.md b/packages/core/README.md index 82dd6f6..e510945 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -4,7 +4,7 @@ The check suite behind [`@wasit-dev/cli`](https://www.npmjs.com/package/@wasit-d This package holds the actual check logic. The CLI and the MCP server are thin adapters over these same functions, so a CLI run and an agent's run can never disagree about the same target — there is only one implementation of each check. -**Testnet only.** Several checks settle real transactions on-chain. +**Testnet only.** Several checks settle real transactions on-chain. In 0.8.0-beta.1 (npm tag `beta`; `latest` is 0.7.0) every payment check pays on test networks only: any other network, `stellar:pubnet` included, is refused before a key is read. Most people should reach for [`@wasit-dev/cli`](https://www.npmjs.com/package/@wasit-dev/cli) (terminal) or [`@wasit-dev/server`](https://www.npmjs.com/package/@wasit-dev/server) (MCP / agents) instead of this package directly. Install `@wasit-dev/core` yourself only if you're building your own tooling on top of the check suite. diff --git a/packages/core/package.json b/packages/core/package.json index 6bedb92..20cd252 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@wasit-dev/core", - "version": "0.7.0", + "version": "0.8.0-beta.1", "description": "Check suite for x402/MPP protocol-conformance testing on Stellar. Powers the wasit CLI and wasit-mcp server.", "type": "module", "main": "dist/index.js", diff --git a/packages/core/src/baseline.ts b/packages/core/src/baseline.ts index 8667b87..9767079 100644 --- a/packages/core/src/baseline.ts +++ b/packages/core/src/baseline.ts @@ -100,6 +100,7 @@ function readResult(raw: unknown, path: string): StructuredCheckResult { ...(entry["skipKind"] === undefined ? {} : { skipKind: oneOf(entry["skipKind"], SKIP_KINDS, at(path, "skipKind")) }), ...(entry["expected"] === undefined ? {} : { expected: text(entry["expected"], at(path, "expected"), 500) }), ...(entry["actual"] === undefined ? {} : { actual: text(entry["actual"], at(path, "actual"), 500) }), + ...(entry["reference"] === undefined ? {} : { reference: text(entry["reference"], at(path, "reference"), 120) }), ...(entry["fix"] === undefined ? {} : { fix: text(entry["fix"], at(path, "fix"), 2000) }), ...(entry["docs"] === undefined ? {} : { docs: text(entry["docs"], at(path, "docs"), 300) }), }; @@ -368,6 +369,15 @@ function statuses(endpoint: EndpointReport): Map { return map; } +/** The checks of an endpoint that its run skipped because of the tier: read-only, or no payer key. */ +function notRunByTier(endpoint: EndpointReport): Set { + return new Set( + endpoint.results + .filter((result) => result.status === "SKIP" && (result.skipKind === "read-only" || result.skipKind === "needs-payer")) + .map((result) => result.id), + ); +} + /** * What changed against the baseline, by endpoint name: new and removed * endpoints, an endpoint that is no longer graded (a regression) or is now, and @@ -394,9 +404,14 @@ export function diffReports(report: RunReport, baseline: RunReport): Change[] { } const was = statuses(earlier); + const notRunBefore = notRunByTier(earlier); + const notRunNow = notRunByTier(endpoint); for (const [check, status] of statuses(endpoint)) { const from = was.get(check); if (from === undefined || from === status) continue; + // A check one of the two runs did not run because of its tier (a pull request + // runs the read-only checks, main may pay, D-022a) says nothing about the service. + if (notRunBefore.has(check) || notRunNow.has(check)) continue; const kind: ChangeKind = status === "FAIL" ? "new-failure" : from === "FAIL" && status === "PASS" ? "fixed" : "status-changed"; changes.push({ kind, endpoint: endpoint.name, check, from, to: status }); } diff --git a/packages/core/src/catalogue.ts b/packages/core/src/catalogue.ts index f7af46c..8c2af83 100644 --- a/packages/core/src/catalogue.ts +++ b/packages/core/src/catalogue.ts @@ -130,6 +130,17 @@ export const CHECK_CATALOGUE: readonly CheckCatalogueEntry[] = [ negative: true, fix: "Verify each payment with the facilitator before serving: it refuses an authorization past its window (validBefore on EVM, the auth entry's expiration ledger on Stellar).", }, + { + id: "X402-11", + name: "Rejected Request Not Settled", + protocol: "x402", + specRef: "x402 v2 spec §6.1 (verify, run the resource, settle); Soroban authorization nonces", + summary: + "A valid payment sent with a request the config declares invalid must not settle: the chain still holds its authorization unused after it expires.", + negative: true, + costsFunds: true, + fix: "Validate a request before its payment is settled, and settle only once the request has been accepted; a refused request must not cost the payer.", + }, { id: "MPP-01", name: "Charge Settlement On-Chain", diff --git a/packages/core/src/check.ts b/packages/core/src/check.ts index 7dae23d..8f8fd98 100644 --- a/packages/core/src/check.ts +++ b/packages/core/src/check.ts @@ -60,6 +60,13 @@ export interface CheckResult { */ expected?: string; actual?: string; + /** + * The settlement a check read back from the chain and found to be this + * payment (X402-06's transaction: a Stellar or EVM transaction hash, a Solana + * signature). Set only on a PASS whose settlement was verified on chain; a + * report may link it to an explorer after checking its shape. + */ + reference?: string; /** * True when the check did not run. A skipped check is neither a pass nor a * failure: `pass` is false so it can never be counted as conformance, and @@ -257,6 +264,8 @@ export interface StructuredCheckResult { readonly expected?: string; /** Present only when `status` is "FAIL" and the check recorded it: what the service sent. */ readonly actual?: string; + /** Present only when `status` is "PASS" and the check verified a settlement on chain: its reference. */ + readonly reference?: string; /** Present only when `status` is "FAIL": what to change (see {@link fixFor}). */ readonly fix?: string; /** Present only when `status` is "FAIL": the check's docs page. */ @@ -314,6 +323,7 @@ export function toStructuredRun(results: CheckResult[]): StructuredRun { ...(status === "SKIP" && result.skipKind !== undefined ? { skipKind: result.skipKind } : {}), ...(status === "FAIL" && result.expected !== undefined ? { expected: sanitizeText(result.expected) } : {}), ...(status === "FAIL" && result.actual !== undefined ? { actual: sanitizeText(result.actual) } : {}), + ...(status === "PASS" && result.reference !== undefined ? { reference: sanitizeText(result.reference) } : {}), ...(guidance === undefined ? {} : { diff --git a/packages/core/src/ci-report.ts b/packages/core/src/ci-report.ts index 5e2bc76..6de601b 100644 --- a/packages/core/src/ci-report.ts +++ b/packages/core/src/ci-report.ts @@ -17,9 +17,17 @@ import { type Baseline, type Change, type ChangeKind, + type History, } from "./baseline.js"; -import type { SkipKind } from "./check.js"; -import { checkGroup, describeTotals, type CheckGroup, type EndpointReport, type RunReport } from "./report.js"; +import type { CheckStatus, SkipKind } from "./check.js"; +import { + checkGroup, + describeTotals, + type CheckGroup, + type EndpointOutcome, + type EndpointReport, + type RunReport, +} from "./report.js"; import { sanitizeForMarkdown } from "./sanitize.js"; import { isShortCommit, type ToolVersions } from "./versions.js"; import { runExitCode } from "./verdict.js"; @@ -39,12 +47,43 @@ export interface CiReportInput { readonly baseline?: Baseline; /** Why no baseline could be used, when one was looked for: shown in place of "no baseline yet". */ readonly baselineNote?: string; + /** The id of the run on main the baseline came from: the last green one (D-022b). */ + readonly baselineRun?: number; + /** + * The history of every completed run on main, failed ones included (D-022b), + * for the recent-failures line. Absent: the baseline's own history. + */ + readonly history?: History; /** Values no output may carry (a header value, a key, an RPC url). */ readonly secrets?: readonly string[]; } /** Docs links go in only if they point at the site: the file they come from is data. */ const DOCS_LINK = /^https:\/\/usewasit\.dev\/[A-Za-z0-9/_.-]*$/; + +/** A check's status at a glance (Najmi, 2026-11-20): emoji are safe in a comment, which is HTML. */ +const STATUS_MARK: Readonly> = { PASS: "✅", FAIL: "❌", SKIP: "⚪", ERROR: "⚠️" }; +const OUTCOME_MARK: Readonly> = { + conformant: "✅", + "non-conformant": "❌", + "no-verdict": "⚠️", + unsupported: "⚪", +}; +/** The run's verdict words, as the headline says them. */ +type VerdictWord = "conformant" | "non-conformant" | "regression" | "nothing graded" | "no verdict"; +const VERDICT_MARK: Readonly> = { + conformant: "✅", + "non-conformant": "❌", + regression: "❌", + "nothing graded": "⚪", + "no verdict": "⚠️", +}; +/** Endpoints shown with a table of their checks; a config with more points at the report file for the rest. */ +const MAX_ENDPOINT_SECTIONS = 10; +/** A Stellar transaction hash: the only reference a payment proof links, and only on the test network. */ +const STELLAR_TX = /^[0-9a-f]{64}$/; +/** A run's page, as `GITHUB_SERVER_URL/GITHUB_REPOSITORY/actions/runs/GITHUB_RUN_ID` gives it. */ +const RUN_URL = /^https:\/\/[A-Za-z0-9.-]+(?::[0-9]{1,5})?\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/actions\/runs\/[0-9]{1,20}$/; const VERSION = /^[0-9A-Za-z.+-]{1,40}$/; const GROUP_LABEL: Readonly> = { @@ -112,10 +151,14 @@ function checksCell(endpoint: EndpointReport): string { return GROUP_ORDER.map((group) => groupText(endpoint, group)).filter((text) => text !== undefined).join("; "); } -function renderBody(input: CiReportInput): string { +/** The baseline the run is compared with (one of another environment is not), and the run's verdict. */ +function verdictOf(input: CiReportInput): { + readonly baseline: Baseline | undefined; + readonly note: string | undefined; + readonly code: number; + readonly word: VerdictWord; +} { const { report } = input; - const md = (value: string): string => sanitizeForMarkdown(value, { redact: input.secrets ?? [] }); - // A baseline from another environment is another service: it is not compared. const problem = input.baseline === undefined ? undefined : baselineProblem(report, input.baseline.report); const baseline = problem === undefined ? input.baseline : undefined; @@ -123,7 +166,7 @@ function renderBody(input: CiReportInput): string { const verdict = runExitCode(report, baseline?.report); const couldNotRun = report.endpoints.some((endpoint) => endpoint.results.some((result) => result.status === "ERROR")); - const word = + const word: VerdictWord = verdict.code === 0 ? "conformant" : verdict.code === 1 @@ -133,10 +176,69 @@ function renderBody(input: CiReportInput): string { : report.totals.graded === 0 && !couldNotRun ? "nothing graded" : "no verdict"; + return { baseline, note, code: verdict.code, word }; +} + +/** + * The payment proof under an endpoint: a link to X402-06's transaction on + * Stellar Expert, and only when every part is Wasit's own and checked: the run + * is on `stellar:testnet`, X402-06 passed, and its reference (read back from the + * chain by the check) is a 64-character lower-case hex hash. Never a link built + * from a service's text. + */ +function paymentProof(endpoint: EndpointReport, network: string): string | undefined { + if (network !== "stellar:testnet") return undefined; + const honest = endpoint.results.find((result) => result.id === "X402-06" && result.status === "PASS"); + const reference = honest?.reference; + if (reference === undefined || !STELLAR_TX.test(reference)) return undefined; + return ( + `**Payment proof**: X402-06 settled on stellar:testnet, ` + + `[tx ${reference.slice(0, 4)}…${reference.slice(-4)} on Stellar Expert](https://stellar.expert/explorer/testnet/tx/${reference}).` + ); +} + +/** An endpoint's heading and the table of its checks, each with its mark, then its payment proof. */ +function endpointSection(endpoint: EndpointReport, network: string, md: (value: string) => string): string[] { + const out = [ + "", + `### ${OUTCOME_MARK[endpoint.outcome]} ${md(endpoint.name)} · ${endpoint.protocol} · ${endpoint.outcome}`, + "", + "| | Check | Result |", + "| --- | --- | --- |", + ...endpoint.results.map((result) => `| ${STATUS_MARK[result.status]} | ${md(result.id)} ${md(result.name)} | ${result.status} |`), + ]; + const proof = paymentProof(endpoint, network); + if (proof !== undefined) out.push("", proof); + return out; +} + +/** Every check's detail, folded away at the end, so a long report cuts here and not in the verdict. */ +function detailsBlock(report: RunReport, md: (value: string) => string): string[] { + const out = ["", "
Details of each check", ""]; + for (const endpoint of report.endpoints.slice(0, MAX_ENDPOINT_SECTIONS)) { + out.push(`**${md(endpoint.name)}**`, ""); + let lastSkip: string | undefined; + for (const result of endpoint.results) { + // A skip with the reason of the skip just above it says so instead of repeating it. + const repeated = result.status === "SKIP" && lastSkip === result.detail; + lastSkip = result.status === "SKIP" ? result.detail : undefined; + const detail = repeated ? "the same reason as above." : md(result.detail); + out.push(`- ${STATUS_MARK[result.status]} ${md(result.id)} ${md(result.name)}: ${detail}`); + } + out.push(""); + } + out.push("
"); + return out; +} + +function renderBody(input: CiReportInput): string { + const { report } = input; + const md = (value: string): string => sanitizeForMarkdown(value, { redact: input.secrets ?? [] }); + const { baseline, note, word } = verdictOf(input); const sdk = report.sdk; const out: string[] = [ - `**Wasit: ${word}.** ${describeTotals(report.totals)} on ${md(report.environment)}, ${md(report.network)}. ` + + `**Wasit: ${VERDICT_MARK[word]} ${word}.** ${describeTotals(report.totals)} on ${md(report.environment)}, ${md(report.network)}. ` + `${wasitText(report.wasit)}, x402 v2, ` + `@x402/core ${version(sdk["@x402/core"])}, @x402/stellar ${version(sdk["@x402/stellar"])}, ` + `@stellar/mpp ${version(sdk["@stellar/mpp"])}, mppx ${version(sdk.mppx)}, ` + @@ -145,10 +247,21 @@ function renderBody(input: CiReportInput): string { "| Endpoint | Protocol | Outcome | Checks |", "| --- | --- | --- | --- |", ...report.endpoints.map( - (endpoint) => `| ${md(endpoint.name)} | ${endpoint.protocol} | ${endpoint.outcome} | ${checksCell(endpoint)} |`, + (endpoint) => + `| ${md(endpoint.name)} | ${endpoint.protocol} | ${OUTCOME_MARK[endpoint.outcome]} ${endpoint.outcome} | ${checksCell(endpoint)} |`, ), ]; + for (const endpoint of report.endpoints.slice(0, MAX_ENDPOINT_SECTIONS)) out.push(...endpointSection(endpoint, report.network, md)); + if (report.endpoints.length > MAX_ENDPOINT_SECTIONS) { + const rest = report.endpoints.length - MAX_ENDPOINT_SECTIONS; + out.push( + "", + `${rest} more endpoint${rest === 1 ? " is" : "s are"} not shown check by check here; ` + + "the JSON report of wasit run has every check (in the Action, the log of the step Run Wasit).", + ); + } + const notGraded = report.endpoints.filter( (endpoint) => (endpoint.outcome === "unsupported" || endpoint.outcome === "no-verdict") && endpoint.reason !== undefined, ); @@ -168,6 +281,7 @@ function renderBody(input: CiReportInput): string { const changes = diffReports(report, baseline.report).sort( (a: Change, b: Change) => CHANGE_ORDER.indexOf(a.kind) - CHANGE_ORDER.indexOf(b.kind), ); + out.push(comparedWith(baseline.report.startedAt, input.baselineRun)); if (changes.length === 0) out.push("No change since main."); for (const change of changes.slice(0, MAX_CHANGES_SHOWN)) out.push(`- ${describeChange(change, md)}`); if (changes.length > MAX_CHANGES_SHOWN) out.push(`- ${changes.length - MAX_CHANGES_SHOWN} more changes not shown.`); @@ -192,7 +306,7 @@ function renderBody(input: CiReportInput): string { } } - const recent = baseline === undefined ? [] : recentFailures(baseline.history); + const recent = baseline === undefined ? [] : recentFailures(input.history ?? baseline.history); if (recent.length > 0) { out.push("", "### Recent failures on main"); for (const item of recent.slice(0, MAX_RECENT_SHOWN)) { @@ -205,9 +319,29 @@ function renderBody(input: CiReportInput): string { for (const item of report.notes) out.push(`- ${md(item)}`); } + out.push(...detailsBlock(report, md)); return out.join("\n"); } +/** "2026-11-15 10:00 UTC", from the report's own start time; nothing that is not a time. */ +function utcMinute(iso: string): string | undefined { + const time = Date.parse(iso); + if (!Number.isFinite(time)) return undefined; + return `${new Date(time).toISOString().slice(0, 16).replace("T", " ")} UTC`; +} + +/** + * The line that says what "Changed since main" compares with (D-022b): the last + * green run on main, so a FAIL that main has now is not read as this run's. + */ +function comparedWith(startedAt: string, run: number | undefined): string { + const when = utcMinute(startedAt); + const id = run !== undefined && Number.isSafeInteger(run) && run > 0 ? run : undefined; + const started = when === undefined ? "" : `started ${when}`; + const which = id !== undefined ? `: run ${id}${started === "" ? "" : `, ${started}`}` : started === "" ? "" : `, ${started}`; + return `Compared with the last green run on main${which}. Runs on main that failed after it are counted under Recent failures on main, not here.`; +} + function describeChange(change: Change, md: (value: string) => string): string { const endpoint = md(change.endpoint); const check = md(change.check ?? ""); @@ -233,7 +367,7 @@ function describeChange(change: Change, md: (value: string) => string): string { function withinLimit(text: string): string { if (text.length <= MAX_COMMENT_CHARACTERS) return text; const cut = text.lastIndexOf("\n", MAX_COMMENT_CHARACTERS - 200); - return `${text.slice(0, cut > 0 ? cut : MAX_COMMENT_CHARACTERS - 200)}\n\n(The rest is cut: the full report is in the job's wasit-report.json.)`; + return `${text.slice(0, cut > 0 ? cut : MAX_COMMENT_CHARACTERS - 200)}\n\n(The rest is cut: the JSON report of wasit run has all of it; in the Action, the log of the step Run Wasit.)`; } /** The pull request comment: the marker, then the report. */ @@ -256,7 +390,7 @@ export function renderSummary(input: CiReportInput): string { function renderNoReportBody(versions: ToolVersions): string { const sdk = versions.sdk; return [ - "**Wasit: no verdict.** The run ended before it wrote a report, so nothing was graded. " + + "**Wasit: ⚠️ no verdict.** The run ended before it wrote a report, so nothing was graded. " + `${wasitText(versions.wasit)}, x402 v2, ` + `@x402/core ${version(sdk["@x402/core"])}, @x402/stellar ${version(sdk["@x402/stellar"])}, ` + `@stellar/mpp ${version(sdk["@stellar/mpp"])}, mppx ${version(sdk.mppx)}, ` + @@ -276,3 +410,77 @@ export function renderNoReportComment(versions: ToolVersions): string { export function renderNoReportSummary(versions: ToolVersions): string { return `${renderNoReportBody(versions)}\n`; } + +/** What a GitHub check run shows: its title, its summary and how it ended. */ +export interface CheckRunOutput { + /** At most 255 characters: the verdict and the counts, nothing a service chose. */ + readonly title: string; + /** The job summary's text: the same sanitised report. */ + readonly summary: string; + readonly conclusion: "success" | "failure" | "neutral"; +} + +/** The check run's limits, as GitHub sets them. */ +const MAX_CHECK_TITLE = 255; +const MAX_CHECK_SUMMARY = 65_535; + +/** "10 passed, 1 failed, 1 could not run, 1 skipped", over every endpoint. */ +function statusCounts(report: RunReport): string { + const all = report.endpoints.flatMap((endpoint) => endpoint.results); + const count = (status: CheckStatus): number => all.filter((result) => result.status === status).length; + const parts = [`${count("PASS")} passed`]; + if (count("FAIL") > 0) parts.push(`${count("FAIL")} failed`); + if (count("ERROR") > 0) parts.push(`${count("ERROR")} could not run`); + if (count("SKIP") > 0) parts.push(`${count("SKIP")} skipped`); + return parts.join(", "); +} + +/** + * The check run "Wasit conformance" at the end of a run: success for a run that + * exits 0, failure for 1, neutral for no verdict. The title holds only the + * verdict word and counts; the summary is the job summary. + */ +export function renderCheckRun(input: CiReportInput): CheckRunOutput { + const { code, word } = verdictOf(input); + return { + title: `${VERDICT_MARK[word]} ${word} · ${statusCounts(input.report)}`.slice(0, MAX_CHECK_TITLE), + summary: renderSummary(input).slice(0, MAX_CHECK_SUMMARY), + conclusion: code === 0 ? "success" : code === 1 ? "failure" : "neutral", + }; +} + +/** The check run for a run that left no report: neutral, with the fixed text of the no-report comment. */ +export function renderNoReportCheckRun(versions: ToolVersions): CheckRunOutput { + return { + title: "⚠️ no verdict · the run ended before it wrote a report", + summary: renderNoReportSummary(versions).slice(0, MAX_CHECK_SUMMARY), + conclusion: "neutral", + }; +} + +export interface RunningCommentInput { + /** When the run started, as an ISO time; anything else is left out. */ + readonly startedAt: string; + /** The run's page; left out unless it has the shape GitHub gives it. */ + readonly runUrl?: string; + /** The environment the run tests, when the workflow names one. */ + readonly environment?: string; + /** Values no output may carry. */ + readonly secrets?: readonly string[]; +} + +/** + * The pull request comment while Wasit runs (Najmi, 2026-11-20): the marker, + * then a fixed line with the start time and a link to the run. The result + * replaces it when the run ends. The only value from outside is the + * environment's name, which goes through the sanitiser; the link is used only + * when it has the shape of a GitHub run page. + */ +export function renderRunningComment(input: RunningCommentInput): string { + const md = (value: string): string => sanitizeForMarkdown(value, { redact: input.secrets ?? [] }); + const when = utcMinute(input.startedAt); + const environment = input.environment !== undefined && input.environment.trim() !== "" ? ` on ${md(input.environment)}` : ""; + const started = when === undefined ? "" : ` · started ${when}`; + const link = input.runUrl !== undefined && RUN_URL.test(input.runUrl) ? ` · [follow the run](${input.runUrl})` : ""; + return `${COMMENT_MARKER}\n⏳ **Wasit is running**${environment}${started}${link}\n\nThe result replaces this comment when the run ends.\n`; +} diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts index 4de1103..be6925a 100644 --- a/packages/core/src/errors.ts +++ b/packages/core/src/errors.ts @@ -195,13 +195,17 @@ function baseFetch(): typeof fetch { /** How `fetchTarget` treats a redirect. */ export interface FetchTargetOptions { /** - * `"follow"` (the default) is fetch's own behaviour, any redirect to any - * host, and is what every call that carries or precedes a payment still - * uses. `"same-origin"` is the rule for the read-only tier: a redirect inside - * the origin of `target` is followed once, anything else is refused with a - * {@link RedirectRefusedError} and nothing is sent to the other origin. + * `"never"` (the default): one request, and a redirect answer is refused + * with a {@link RedirectRefusedError}; nothing is sent to its Location. Every + * request that carries a payment uses it (D-022c): `fetch` would keep a + * header such as `PAYMENT-SIGNATURE` on the way, and deliver the signed + * payment to a second URL that can settle it while the check grades the + * first. Being the default, a call that forgets to choose cannot leak one. + * `"same-origin"` is the rule for the read-only tier: a redirect inside the + * origin of `target` is followed once, anything else is refused and nothing + * is sent to the other origin. */ - readonly redirects?: "follow" | "same-origin"; + readonly redirects?: "never" | "same-origin"; } const REDIRECT_STATUSES: ReadonlySet = new Set([301, 302, 303, 307, 308]); @@ -240,13 +244,18 @@ function redirectLocation(response: Response, from: URL): URL | undefined { return next; } -/** The request a redirect leads to: a POST on 301 to 303, and any non-HEAD on 303, becomes a GET without a body. */ -function redirectedInit(init: RequestInit | undefined, status: number): RequestInit { +/** Whether fetch would turn the request into a GET on this redirect: a POST on 301 to 303, any non-HEAD on 303. */ +function redirectBecomesGet(init: RequestInit | undefined, status: number): boolean { const method = (init?.method ?? "GET").toUpperCase(); - const becomesGet = + return ( (status === 303 && method !== "GET" && method !== "HEAD") || - ((status === 301 || status === 302) && method === "POST"); - if (!becomesGet) return init ?? {}; + ((status === 301 || status === 302) && method === "POST") + ); +} + +/** The request a redirect leads to: a POST on 301 to 303, and any non-HEAD on 303, becomes a GET without a body. */ +function redirectedInit(init: RequestInit | undefined, status: number): RequestInit { + if (!redirectBecomesGet(init, status)) return init ?? {}; const { body: _body, headers, ...rest } = init ?? {}; const kept = new Headers(headers); @@ -278,11 +287,15 @@ async function discard(response: Response): Promise { * A second redirect is refused even when it stays inside the origin: a chain * is not something a paywall needs, and a loop must end. */ -async function fetchSameOrigin(target: string, init: RequestInit | undefined): Promise { +async function followSameOrigin( + target: string, + init: RequestInit | undefined, + keepRequest: boolean, +): Promise<{ readonly response: Response; readonly url: string }> { const from = new URL(target); const first = await fetchOnce(target, init); const next = redirectLocation(first, from); - if (next === undefined) return first; + if (next === undefined) return { response: first, url: target }; await discard(first); if (next.origin !== from.origin || (next.protocol !== "http:" && next.protocol !== "https:")) { @@ -292,10 +305,18 @@ async function fetchSameOrigin(target: string, init: RequestInit | undefined): P `Point the run at the URL the redirect leads to, if that is the service you operate.`, ); } + if (keepRequest && redirectBecomesGet(init, first.status)) { + throw new RedirectRefusedError( + `The route answers ${first.status} with a redirect that turns this ` + + `${(init?.method ?? "GET").toUpperCase()} into a GET. Wasit pays only where the request ` + + `arrives unchanged, so it did not follow it and nothing was paid. Point the run at the ` + + `URL the route answers on.`, + ); + } const second = await fetchOnce(next.href, redirectedInit(init, first.status)); const again = redirectLocation(second, next); - if (again === undefined) return second; + if (again === undefined) return { response: second, url: next.href }; await discard(second); throw new RedirectRefusedError( again.origin === from.origin @@ -306,6 +327,54 @@ async function fetchSameOrigin(target: string, init: RequestInit | undefined): P ); } +/** Refuses `response` when it is a redirect, after freeing its connection; returns it otherwise. */ +async function refuseRedirect(response: Response, from: URL): Promise { + const next = redirectLocation(response, from); + if (next === undefined) return response; + await discard(response); + throw new RedirectRefusedError( + `The route answers ${response.status} with a redirect to ` + + `${sanitizeText(describeOrigin(next))}. Wasit does not follow a redirect on a request that ` + + `pays, so nothing was sent there and the payment was not sent again. Point the run at the ` + + `URL the route answers on.`, + ); +} + +/** + * The unpaid request a payment check reads its fresh challenge from, and the + * URL the payment is then sent to (D-022c). + * + * One redirect inside the origin is followed, as the read-only tier does, but + * only when it keeps the request: a POST that a 301, 302 or 303 turns into a + * GET would have the payment signed for one request and sent with another. The + * payment goes to `url`, with redirects refused ({@link fetchTarget}'s default). + */ +export async function fetchPaymentChallenge( + target: string, + init: RequestInit | undefined, +): Promise<{ readonly response: Response; readonly url: string }> { + assertHttpUrl(target); + return followSameOrigin(target, init, true); +} + +/** + * A `fetch` that never follows a redirect, for a payment client that makes + * its own requests (mppx): every request it makes refuses a redirect answer. + * MPP pays at the URL it read the challenge from, so a route that redirects + * gets no verdict rather than a payment delivered to a second URL. + */ +export const fetchWithoutRedirects: typeof fetch = async (input, init) => { + const target = input instanceof Request ? input.url : input instanceof URL ? input.href : String(input); + assertHttpUrl(target); + let response: Response; + try { + response = await baseFetch()(input, { ...init, redirect: "manual" }); + } catch (error) { + throw new TargetUnreachableError(target, error); + } + return refuseRedirect(response, new URL(target)); +}; + export async function fetchTarget( target: string, init?: Parameters[1], @@ -313,13 +382,9 @@ export async function fetchTarget( ): Promise>> { assertHttpUrl(target); - if (options?.redirects === "same-origin") return fetchSameOrigin(target, init); + if (options?.redirects === "same-origin") return (await followSameOrigin(target, init, false)).response; - try { - return await baseFetch()(target, init); - } catch (error) { - throw new TargetUnreachableError(target, error); - } + return refuseRedirect(await fetchOnce(target, init), new URL(target)); } /** Maps a thrown value onto the taxonomy. */ diff --git a/packages/core/src/guard/budget.ts b/packages/core/src/guard/budget.ts new file mode 100644 index 0000000..e8b6809 --- /dev/null +++ b/packages/core/src/guard/budget.ts @@ -0,0 +1,283 @@ +/** + * The caps of spec B4, in code: at most $1 a payment and $5 a run, the run's + * total charged BEFORE each signature and never credited back (B3, B-A08). + * + * A cap in dollars needs an asset whose dollar value is known. Wasit pays only + * in USDC (the SDK client's default assets, plus Circle's USDC on Ethereum + * Sepolia), so the table below lists USDC on each test network with its + * decimals, and a payment in any other asset is refused: Wasit cannot hold it + * to the cap. Nothing on mainnet is listed: this version pays on test networks + * only, and the mainnet USDC constant waits for the opt-in (B4, B12). + * + * Amounts in dollars are bigints at 10^-18 of a dollar, so 6 and 7 decimal + * tokens add up exactly. + * + * Pure: no network, no key. + */ + +import { CheckSetupError, ConfigurationError } from "../errors.js"; +import { sanitizeText } from "../sanitize.js"; + +/** At most this many dollars in one payment. Fixed; nothing raises it. */ +export const PER_PAYMENT_CAP_USD = 1; + +/** At most this many dollars signed in one run. A config may only lower it (`maxRunUsd`). */ +export const PER_RUN_CAP_USD = 5; + +/** A dollar, in the units this module counts in. */ +const DOLLAR = 10n ** 18n; + +export interface UsdAsset { + readonly network: string; + readonly asset: string; + readonly decimals: number; + readonly symbol: string; +} + +/** + * USDC on each test network. Sources (read 2026-11-16): `@x402/stellar` 2.28.0 + * `USDC_TESTNET_ADDRESS`, `DEFAULT_TOKEN_DECIMALS = 7`; `@x402/evm` 2.28.0 default + * asset of `eip155:84532`, decimals 6; Circle's USDC on Ethereum Sepolia as + * `chains/evm.ts` (`ETHEREUM_SEPOLIA_USDC`, 6 decimals read from the contract + * 2026-10-05); `@x402/svm` 2.28.0 `USDC_DEVNET_ADDRESS`, decimals 6. + */ +export const USD_ASSETS: readonly UsdAsset[] = [ + { network: "stellar:testnet", asset: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", decimals: 7, symbol: "USDC" }, + { network: "eip155:84532", asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", decimals: 6, symbol: "USDC" }, + { network: "eip155:11155111", asset: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", decimals: 6, symbol: "USDC" }, + { network: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", asset: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU", decimals: 6, symbol: "USDC" }, +]; + +/** Whether two addresses on `network` are the same: an EVM address in any letter case, others exactly. */ +export function sameAddress(network: string, a: string, b: string): boolean { + if (network.startsWith("eip155:")) return a.toLowerCase() === b.toLowerCase(); + return a === b; +} + +/** The dollar asset `asset` is on `network`, if Wasit knows it. */ +export function usdAsset(network: string, asset: string): UsdAsset | undefined { + return USD_ASSETS.find((entry) => entry.network === network && sameAddress(network, entry.asset, asset)); +} + +/** `amount` base units of `asset`, in this module's dollar units. */ +function toUsd(asset: UsdAsset, amount: bigint): bigint { + return (amount * DOLLAR) / 10n ** BigInt(asset.decimals); +} + +/** Whole and fractional dollars, rounded down to a millionth: a cap is never rounded up. */ +export function usdFromDollars(dollars: number): bigint { + return (BigInt(Math.floor(dollars * 1_000_000)) * DOLLAR) / 1_000_000n; +} + +/** "$4.50", "$0.0000001": exact, at least two decimals. */ +export function formatUsd(amount: bigint): string { + const sign = amount < 0n ? "-" : ""; + const absolute = amount < 0n ? -amount : amount; + const whole = absolute / DOLLAR; + let fraction = (absolute % DOLLAR).toString().padStart(18, "0").replace(/0+$/, ""); + if (fraction.length < 2) fraction = fraction.padEnd(2, "0"); + return `${sign}$${whole}.${fraction}`; +} + +export type GuardRefusal = "price" | "asset" | "amount" | "pin" | "plan" | "run-cap" | "accepted"; + +/** + * A payment the guard will not sign, or, with `signed`, a signed payment it + * will not send. A setup error: it says nothing about the target, and the + * check that hit it has no verdict. + */ +export class PaymentGuardRefusedError extends CheckSetupError { + public readonly reason: GuardRefusal; + + public constructor(reason: GuardRefusal, message: string, options: { readonly signed?: boolean } = {}) { + super(options.signed === true ? `${message} It was signed and discarded; it was not sent.` : `${message} Nothing was signed.`); + this.name = "PaymentGuardRefusedError"; + this.reason = reason; + } +} + +/** A value the target chose, for a message: one line, no control characters, bounded. */ +export function shown(value: unknown): string { + const text = sanitizeText(String(value)).replace(/\s+/g, " "); + return JSON.stringify(text.length > 80 ? `${text.slice(0, 77)}...` : text); +} + +/** A base-unit amount as the challenge gives it: digits only, at most 78 (a uint256). */ +const AMOUNT = /^\d{1,78}$/; + +export function parseAmount(amount: unknown): bigint { + if (typeof amount !== "string" || !AMOUNT.test(amount)) { + throw new PaymentGuardRefusedError( + "amount", + `The amount to sign, ${shown(amount)}, is not a whole number of base units.`, + ); + } + return BigInt(amount); +} + +export interface PinTerms { + readonly payTo: string; + readonly asset: string; +} + +interface OptionTerms { + readonly scheme: string; + readonly network: string; + readonly payTo: string; + readonly asset: string; +} + +/** + * Refuses unless EVERY `exact` option on `network` pays the pinned `payTo` in + * the pinned asset (B-A02): the SDK picks among the options by its own rules, + * so a check of the first one alone would not cover what it signs. Options on + * other networks or schemes are never signed and are not judged. + */ +export function assertPinned(network: string, accepts: readonly OptionTerms[], pin: PinTerms | undefined): void { + if (pin === undefined) return; + for (const [index, requirement] of accepts.entries()) { + if (requirement.scheme !== "exact" || requirement.network !== network) continue; + for (const field of ["payTo", "asset"] as const) { + if (!sameAddress(network, String(requirement[field]), pin[field])) { + throw new PaymentGuardRefusedError( + "pin", + `Option ${index + 1} of the challenge (exact, ${network}) has ${field} ${shown(requirement[field])}, ` + + `not the pinned ${pin[field]}.`, + ); + } + } + } +} + +/** One signature a run makes, and its amount in base units. */ +export interface PlannedSignature { + readonly check: string; + readonly amount: bigint; +} + +/** + * What the payment checks sign for an endpoint priced `price` (B0 fact 8): + * X402-06 the price (settles), X402-07 the price (signature then corrupted), + * X402-09 half the price, rounded down (none when there is no smaller amount), + * X402-10 the price with a short lifetime. X402-08 resends X402-06 and signs + * nothing. 3.5 times the price. With `rejectedRequest`, X402-11 the price as + * well (a valid payment sent with a request the service must refuse): 4.5 times. + */ +export function plannedSignatures(price: bigint, options: { readonly rejectedRequest?: boolean } = {}): PlannedSignature[] { + return [ + { check: "X402-06", amount: price }, + { check: "X402-07", amount: price }, + ...(price >= 2n ? [{ check: "X402-09", amount: price / 2n }] : []), + { check: "X402-10", amount: price }, + ...(options.rejectedRequest === true ? [{ check: "X402-11", amount: price }] : []), + ]; +} + +export interface BudgetOptions { + /** A lower per-run cap in dollars; a value above {@link PER_RUN_CAP_USD} is read as it. */ + readonly maxRunUsd?: number; +} + +export interface Charge { + readonly check: string; + readonly network: string; + readonly asset: string; + /** Base units, as the payment states them. */ + readonly amount: string; + /** What the plan allowed for this check, in base units, when the run has a plan. */ + readonly planned?: bigint; +} + +export interface ChargedEntry { + readonly check: string; + readonly network: string; + readonly asset: string; + readonly amount: bigint; +} + +/** + * The dollars one run may sign. Every signature is charged here first; a + * charge that does not fit is refused and nothing is signed. Nothing is ever + * credited back: a payment that failed after it was signed may still settle. + * Once the cap refuses a payment, the budget is spent: every later charge is + * refused too, so a run never signs a smaller payment after a larger one did + * not fit. + */ +export class RunBudget { + readonly #cap: bigint; + #spent = 0n; + #exhausted: string | undefined; + readonly #entries: ChargedEntry[] = []; + + public constructor(options: BudgetOptions = {}) { + const lower = options.maxRunUsd; + if (lower !== undefined && (!Number.isFinite(lower) || lower <= 0)) { + throw new ConfigurationError("maxRunUsd must be a number above 0: it can only lower the per-run cap."); + } + this.#cap = usdFromDollars(Math.min(lower ?? PER_RUN_CAP_USD, PER_RUN_CAP_USD)); + } + + /** The run's cap, in dollar units. */ + public get capUsd(): bigint { + return this.#cap; + } + + /** What the run has charged so far, in dollar units. */ + public get spentUsd(): bigint { + return this.#spent; + } + + public get entries(): readonly ChargedEntry[] { + return [...this.#entries]; + } + + /** + * Charges one payment, or refuses it. Called before the signature, with the + * amount that will be signed. + */ + public charge(charge: Charge): void { + const amount = parseAmount(charge.amount); + const asset = usdAsset(charge.network, charge.asset); + if (asset === undefined) { + throw new PaymentGuardRefusedError( + "asset", + `The target asks to be paid in ${shown(charge.asset)} on ${charge.network}, an asset Wasit does not ` + + `value in US dollars, so it cannot hold the payment to the $${PER_PAYMENT_CAP_USD}.00 cap.`, + ); + } + const usd = toUsd(asset, amount); + const perPayment = usdFromDollars(PER_PAYMENT_CAP_USD); + if (usd > perPayment) { + throw new PaymentGuardRefusedError( + "price", + `${charge.check} would sign ${amount} base units of ${asset.symbol} (${formatUsd(usd)}), above the ` + + `${formatUsd(perPayment)} per payment fixed in Wasit. A route priced at ` + + `${formatUsd(perPayment)} or less is checked as usual.`, + ); + } + if (charge.planned !== undefined && amount > charge.planned) { + throw new PaymentGuardRefusedError( + "plan", + `${charge.check} would sign ${amount} base units, more than the ${charge.planned} the plan allowed ` + + `for it before the run started: the service changed its price after the plan.`, + ); + } + if (this.#exhausted !== undefined) { + throw new PaymentGuardRefusedError("run-cap", this.#exhausted); + } + if (this.#spent + usd > this.#cap) { + this.#exhausted = + `The run reached its ${formatUsd(this.#cap)} cap: ${charge.check} would have taken it from ` + + `${formatUsd(this.#spent)} to ${formatUsd(this.#spent + usd)}, so the run signs nothing more.`; + throw new PaymentGuardRefusedError("run-cap", this.#exhausted); + } + this.#spent += usd; + this.#entries.push({ check: charge.check, network: charge.network, asset: asset.asset, amount }); + } + + /** The dollar value of `amount` base units of `asset` on `network`, if Wasit can value it. */ + public static valueOf(network: string, asset: string, amount: bigint): bigint | undefined { + const known = usdAsset(network, asset); + return known === undefined ? undefined : toUsd(known, amount); + } +} diff --git a/packages/core/src/guard/ci-event.ts b/packages/core/src/guard/ci-event.ts new file mode 100644 index 0000000..f7dcc87 --- /dev/null +++ b/packages/core/src/guard/ci-event.ts @@ -0,0 +1,141 @@ +/** + * Which GitHub events may run the payment tier (D-022a option 2, D-032). + * + * The payment tier runs only where the code that runs is code that was merged: + * a push to the default branch, a schedule (GitHub runs it on the default + * branch), and workflow_dispatch on the default branch. Every pull request event + * is refused, a same-repository one too: its branch's code and new dependencies + * would run in the same job as the payer key before anyone reviewed them. Every + * other event is refused as well (merge_group and workflow_run run code that is + * not on the default branch yet). Outside GitHub Actions the gate is open: a run + * on a laptop is the builder's own choice. + * + * What this stops is a mistake in a workflow, not its author (B-A10): a step + * can hide the runner's variables from the CLI. The control that holds is + * where the workflow gives the secret, which the guide explains. + */ + +import { readFileSync, statSync } from "node:fs"; + +import { DENIED_ENV_NAMES } from "../denied-env.js"; + +export interface PaymentEventGate { + readonly allowed: boolean; + /** Set when not allowed: the reason a skipped payment check gives, "payment checks not run: ...". */ + readonly reason?: string; + /** + * Not allowed because the run is in a CI that is not GitHub Actions (`CI` + * set): there the service of the run would share its job with the key, and + * nothing keeps them apart. `wasit run` refuses the payment tier there. + */ + readonly ciOutsideGithub?: true; +} + +const ALLOWED_EVENTS = "Wasit pays on push to the default branch, schedule and workflow_dispatch only"; +/** An event name or a branch, as far as it is ever printed. Anything else is not echoed. */ +const PRINTABLE_EVENT = /^[a-z_]{1,64}$/; +const PRINTABLE_REF = /^[A-Za-z0-9._/-]{1,200}$/; +const MAX_EVENT_BYTES = 1024 * 1024; + +function nonEmpty(value: string | undefined): value is string { + return typeof value === "string" && value !== ""; +} + +function shownEvent(event: string): string { + return PRINTABLE_EVENT.test(event) ? event : "(an event name Wasit does not print)"; +} + +function shownRef(ref: string): string { + if (ref === "") return "no ref"; + return PRINTABLE_REF.test(ref) ? ref : "(a ref Wasit does not print)"; +} + +/** The default branch the event payload names, or undefined. */ +function defaultBranch(event: unknown): string | undefined { + if (event === null || typeof event !== "object") return undefined; + const repository = (event as { repository?: unknown }).repository; + if (repository === null || typeof repository !== "object") return undefined; + const branch = (repository as { default_branch?: unknown }).default_branch; + return typeof branch === "string" && PRINTABLE_REF.test(branch) ? branch : undefined; +} + +/** + * True when the process runs as a step of GitHub Actions, or says it does. + * Fail closed: either variable counts, with any value that is not empty, as + * the CLI's own CI test reads `GITHUB_ACTIONS`. + */ +export function inGithubActions(env: Readonly>): boolean { + return nonEmpty(env["GITHUB_ACTIONS"]) || nonEmpty(env["GITHUB_EVENT_NAME"]); +} + +/** + * May this run pay? `event` is the parsed payload of `GITHUB_EVENT_PATH` + * ({@link readGithubEvent}), or undefined when there is none. + */ +export function paymentEventGate(env: Readonly>, event: unknown): PaymentEventGate { + if (!inGithubActions(env)) { + // Najmi, 2026-11-17 (review R9 a): outside GitHub Actions only a run outside CI pays. + if (nonEmpty(env["CI"])) { + return { allowed: false, reason: "payment checks not run: CI is set, and this is not GitHub Actions", ciOutsideGithub: true }; + } + return { allowed: true }; + } + + const name = env["GITHUB_EVENT_NAME"] ?? ""; + if (name.startsWith("pull_request")) return { allowed: false, reason: "payment checks not run: pull request" }; + if (name !== "push" && name !== "schedule" && name !== "workflow_dispatch") { + return { + allowed: false, + reason: `payment checks not run: the ${shownEvent(name)} event (${ALLOWED_EVENTS})`, + }; + } + + const ref = env["GITHUB_REF"] ?? ""; + const branch = defaultBranch(event); + if (branch === undefined) { + // GitHub runs a schedule on the default branch, and its payload may not name + // the repository; its ref must still be a branch. + if (name === "schedule" && ref.startsWith("refs/heads/")) return { allowed: true }; + return { + allowed: false, + reason: `payment checks not run: the ${name} event does not name the default branch, so Wasit cannot tell that ${shownRef(ref)} is it`, + }; + } + if (ref !== `refs/heads/${branch}`) { + return { + allowed: false, + reason: `payment checks not run: ${name} on ${shownRef(ref)}, not the default branch ${branch} (${ALLOWED_EVENTS})`, + }; + } + return { allowed: true }; +} + +/** + * The payload of the event that started the workflow, from the file + * `GITHUB_EVENT_PATH` names; undefined when there is none, it cannot be read, + * it is not JSON, or it is above 1 MiB. + */ +export function readGithubEvent(env: Readonly>): unknown { + const file = env["GITHUB_EVENT_PATH"]; + if (!nonEmpty(file)) return undefined; + try { + if (statSync(file).size > MAX_EVENT_BYTES) return undefined; + return JSON.parse(readFileSync(file, "utf-8")) as unknown; + } catch { + return undefined; + } +} + +/** + * The key variables that hold a value, by their fixed names in upper case. A + * blank value is not a key: a pull request from a fork gets every secret as an + * empty string. + */ +export function payerKeyVariables(env: Readonly>): string[] { + const names = new Set(); + for (const [name, value] of Object.entries(env)) { + const upper = name.toUpperCase(); + if (DENIED_ENV_NAMES.includes(upper) && typeof value === "string" && value.trim() !== "") names.add(upper); + } + return [...names]; +} diff --git a/packages/core/src/guard/mainnet-optin.ts b/packages/core/src/guard/mainnet-optin.ts new file mode 100644 index 0000000..1aa5465 --- /dev/null +++ b/packages/core/src/guard/mainnet-optin.ts @@ -0,0 +1,113 @@ +/** + * The mainnet opt-in switches (spec B5), as this version has them: switches + * that always refuse (spec B12). + * + * A later version may let an x402 run pay on `stellar:pubnet` behind an + * explicit opt-in. This one does not, and it has no code path that answers + * "allowed" for it. The switches that opt-in would read exist here only so + * that a run, a workflow or a server that asks for mainnet is stopped and told + * why, instead of being run on whatever else it was given: + * + * - `--mainnet` on `wasit run` (never read from the config or the environment); + * - `WASIT_MAINNET_OPT_IN` and `WASIT_MAINNET_CONFIG`, the MCP server's + * start-up variables, and `--mainnet` among its arguments: the server does + * not start. + * + * The Action's `mainnet` input is refused by the Action's own input check, + * which runs before Wasit is installed and so cannot import this module. + * + * Every function here throws, or only says which switches are set. + */ + +import { ConfigurationError } from "../errors.js"; +import { NETWORK_CLASSES } from "./networks.js"; + +/** The sentence of spec B12. */ +export const MAINNET_OPT_IN_ABSENT = "the mainnet opt-in is not part of this version"; + +/** A switch that asks for mainnet: the CLI's flag, or one of the MCP server's start-up settings. */ +export type MainnetSwitch = "--mainnet" | "WASIT_MAINNET_OPT_IN" | "WASIT_MAINNET_CONFIG"; + +/** The MCP server's start-up variables that ask for mainnet. */ +const STARTUP_VARIABLES = ["WASIT_MAINNET_OPT_IN", "WASIT_MAINNET_CONFIG"] as const; + +/** An event name as GitHub writes them; anything else is never echoed. */ +const EVENT_NAME = /^[a-z_]{1,64}$/; + +/** + * A switch asked for mainnet, and this version has no mainnet opt-in. A + * `ConfigurationError`: it says nothing about any service. Nothing was read, + * sent or signed when it is thrown. + */ +export class MainnetOptInRefusedError extends ConfigurationError { + public readonly switchName: MainnetSwitch; + + public constructor(switchName: MainnetSwitch, message: string) { + super(message); + this.name = "MainnetOptInRefusedError"; + this.switchName = switchName; + } +} + +function testNetworks(): string { + return [...NETWORK_CLASSES] + .filter(([, kind]) => kind === "test") + .map(([network]) => network) + .join(", "); +} + +/** + * Refuses a switch that asks for mainnet. Always throws. + * + * For `--mainnet`, `context.event` is the GitHub event of the run when it runs + * in GitHub Actions: on any event but `workflow_dispatch` the message says that + * rule as well, so a push or a schedule with the switch set reads as refused for + * that reason too. + * + * @throws {MainnetOptInRefusedError} Always. + */ +export function refuseMainnetSwitch(switchName: MainnetSwitch, context: { readonly event?: string } = {}): never { + const networks = `Wasit pays on test networks only (${testNetworks()}).`; + if (switchName === "--mainnet") { + const event = context.event; + const eventRule = + event === undefined || event === "workflow_dispatch" + ? "" + : ` --mainnet is also refused on every GitHub event but workflow_dispatch, and this run's event is ` + + `${EVENT_NAME.test(event) ? event : "another event"}.`; + throw new MainnetOptInRefusedError( + switchName, + `--mainnet is refused: ${MAINNET_OPT_IN_ABSENT}. ${networks}${eventRule} ` + + `The config was not read, and nothing was started, sent or signed.`, + ); + } + throw new MainnetOptInRefusedError( + switchName, + `${switchName} is set: ${MAINNET_OPT_IN_ABSENT}, so this server does not start. ${networks} ` + + `Nothing was read, sent or signed. Remove ${switchName} from the server's environment to start it.`, + ); +} + +/** + * The switches that ask the MCP server for mainnet at start-up: `--mainnet` + * among its arguments (with or without a value), and each start-up variable + * that holds a value that is not blank. Any value counts, "0" included: the + * variable is there to be removed. Names are compared in upper case, as a + * Windows environment does. + * + * @param env the server's environment + * @param args the server's arguments, after the script (`process.argv.slice(2)`) + */ +export function mainnetStartupSwitches( + env: Readonly>, + args: readonly string[], +): MainnetSwitch[] { + const found: MainnetSwitch[] = []; + if (args.some((arg) => arg === "--mainnet" || arg.startsWith("--mainnet="))) found.push("--mainnet"); + const set = new Set(); + for (const [name, value] of Object.entries(env)) { + if (typeof value === "string" && value.trim() !== "") set.add(name.toUpperCase()); + } + for (const name of STARTUP_VARIABLES) if (set.has(name)) found.push(name); + return found; +} diff --git a/packages/core/src/guard/rpc-identity.ts b/packages/core/src/guard/rpc-identity.ts new file mode 100644 index 0000000..640420a --- /dev/null +++ b/packages/core/src/guard/rpc-identity.ts @@ -0,0 +1,174 @@ +/** + * The RPC identity check (D-032, D-023a+b): before a run signs anything or + * reads a settlement, the RPC it was given must say which network it serves, + * and it must be the run's. + * + * L0 judges the network the run is labelled with. The RPC is a separate input + * (`--rpc-url`, the MCP tool argument `rpcUrl`, the config), and nothing tied + * the two together: a `stellar:testnet` run pointed at a mainnet RPC signed a + * mainnet-valid channel commitment in 0.7.0, and every settlement read of such + * a run comes from another chain. So each entry point that signs or reads a + * settlement asks the RPC first: + * + * - Stellar: `getNetwork`, whose `passphrase` must be the run's network's; + * - EVM: `eth_chainId`, which must equal the CAIP-2 reference; + * - Solana: `getGenesisHash`, whose first characters are the CAIP-2 reference. + * + * A mismatch, no answer, or an answer that cannot be read refuses the run + * before any request reaches the target (fail closed). This guards against a + * mistake or a wrong default, not against an RPC that lies: an RPC that answers + * the right identity and then serves another chain is outside what any client + * check can see. + */ + +import { Networks } from "@stellar/stellar-sdk"; + +import { ConfigurationError } from "../errors.js"; +import { sanitizeText } from "../sanitize.js"; + +/** The RPC does not serve the run's network, or would not say which one it serves. Nothing was sent or signed. */ +export class RpcIdentityError extends ConfigurationError { + public constructor(message: string) { + super(message); + this.name = "RpcIdentityError"; + } +} + +/** One JSON-RPC call: the `result`, or a throw. */ +export type RpcIdentityTransport = (rpcUrl: string, method: string) => Promise; + +const TIMEOUT_MS = 10_000; + +/** The origin of the RPC for a message: its path or query may hold an API key. */ +function origin(rpcUrl: string): string { + try { + const parsed = new URL(rpcUrl); + return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : "an RPC that is not an http URL"; + } catch { + return "an RPC that is not a URL"; + } +} + +const jsonRpc: RpcIdentityTransport = async (rpcUrl, method) => { + const response = await fetch(rpcUrl, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method }), + // An RPC that redirects is not followed: the identity must come from the + // URL the run will use. + redirect: "manual", + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + if (response.status !== 200) { + await response.body?.cancel().catch(() => undefined); + throw new Error(`HTTP ${response.status}`); + } + const body = (await response.json()) as { result?: unknown; error?: { message?: unknown } }; + if (body.error !== undefined) { + throw new Error(typeof body.error.message === "string" ? body.error.message : "a JSON-RPC error"); + } + return body.result; +}; + +let transport: RpcIdentityTransport = jsonRpc; + +/** + * Tests only: replaces the JSON-RPC call (an SDK that accepts only https RPCs + * cannot be given a loopback stand-in). `undefined` restores the real one. Not + * exported from the package index, and reachable from no flag, setting or tool + * argument. + */ +export function setRpcIdentityTransportForTesting(replacement: RpcIdentityTransport | undefined): void { + transport = replacement ?? jsonRpc; +} + +const STELLAR_PASSPHRASES: ReadonlyMap = new Map([ + ["stellar:testnet", Networks.TESTNET], + ["stellar:pubnet", Networks.PUBLIC], +]); + +/** The network a Stellar passphrase belongs to, for the message. */ +function stellarNetworkOf(passphrase: string): string { + for (const [network, known] of STELLAR_PASSPHRASES) if (known === passphrase) return network; + return `a network with the passphrase "${sanitizeText(passphrase).slice(0, 80)}"`; +} + +/** The method to ask, and how to read the answer into the CAIP-2 id it shows (or `undefined` when unreadable). */ +function ruleFor(network: string): { method: string; served: (result: unknown) => string | undefined } | undefined { + const [namespace, reference] = network.split(":", 2); + if (reference === undefined || reference === "") return undefined; + if (namespace === "stellar" && STELLAR_PASSPHRASES.has(network)) { + return { + method: "getNetwork", + served: (result) => { + const passphrase = (result as { passphrase?: unknown } | null)?.passphrase; + return typeof passphrase === "string" ? stellarNetworkOf(passphrase) : undefined; + }, + }; + } + if (namespace === "eip155" && /^[1-9][0-9]*$/.test(reference)) { + return { + method: "eth_chainId", + served: (result) => { + if (typeof result !== "string" || !/^0x[0-9a-fA-F]{1,16}$/.test(result)) return undefined; + return `eip155:${BigInt(result).toString()}`; + }, + }; + } + if (namespace === "solana" && /^[1-9A-HJ-NP-Za-km-z]{32}$/.test(reference)) { + return { + method: "getGenesisHash", + served: (result) => { + if (typeof result !== "string" || !/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(result)) return undefined; + return `solana:${result.slice(0, 32)}`; + }, + }; + } + return undefined; +} + +/** + * Refuses unless the RPC at `rpcUrl` says it serves `network`. + * + * @throws {RpcIdentityError} The RPC serves another network, did not answer, or + * answered something that does not name a network; or Wasit has no rule to + * tell which network an RPC for `network` serves. Nothing was sent to the + * target and nothing was signed. + */ +export async function assertRpcServesNetwork(network: string, rpcUrl: string): Promise { + const label = sanitizeText(network); + const at = sanitizeText(origin(rpcUrl)); + const rule = ruleFor(network); + if (rule === undefined) { + throw new RpcIdentityError( + `Wasit cannot tell which network an RPC for ${label} serves, so it does not pay or read ` + + `settlements through ${at}; nothing was signed.`, + ); + } + + let result: unknown; + try { + result = await transport(rpcUrl, rule.method); + } catch (error) { + const reason = sanitizeText(error instanceof Error ? error.message : String(error)).slice(0, 160); + throw new RpcIdentityError( + `The RPC at ${at} did not say which network it serves (${rule.method}: ${reason}), so Wasit ` + + `could not confirm it is ${label}. No payment was sent and nothing was signed.`, + ); + } + + const served = rule.served(result); + if (served === undefined) { + throw new RpcIdentityError( + `The RPC at ${at} answered ${rule.method} with something that does not name a network, so ` + + `Wasit could not confirm it is ${label}. No payment was sent and nothing was signed.`, + ); + } + if (served !== network) { + throw new RpcIdentityError( + `The RPC at ${at} serves ${served}, and this run is on ${label}. Wasit pays and reads ` + + `settlements only through an RPC of the run's own network, so no payment was sent and ` + + `nothing was signed. Point the run at an RPC for ${label}.`, + ); + } +} diff --git a/packages/core/src/guard/rpc-in-use.ts b/packages/core/src/guard/rpc-in-use.ts new file mode 100644 index 0000000..b2420e4 --- /dev/null +++ b/packages/core/src/guard/rpc-in-use.ts @@ -0,0 +1,98 @@ +/** + * Which RPC a run reads the chain through, as a result names it (D-023c, + * option C), and the start-up setting that fixes it for the MCP server. + * + * The RPC identity check (rpc-identity.ts) refuses an RPC of another network. + * What it cannot see is an RPC of the right network that lies about a + * settlement: that is a false PASS, not a payment on another chain. So a result + * says which RPC it read through, by origin only (a key often rides in the path + * or the query), where that RPC came from, and when it is not Wasit's default + * for the network: then every chain read of the run is that RPC's word. + * + * `WASIT_RPC_URL`, read once when the MCP server starts, fixes the RPC of every + * tool call; the server then refuses the `rpcUrl` argument, so an agent cannot + * point a run at another RPC. + */ + +import { urlOrigin } from "../config.js"; +import { resolveRpcUrl as resolveMppRpcUrl } from "../mpp/network.js"; +import { paymentChainFor } from "../x402/chains/index.js"; +import { networkClass } from "./networks.js"; + +/** Where the RPC of a run came from. */ +export type RpcSource = "default" | "argument" | "start-up"; + +export interface RpcInUse { + /** The origin only: scheme, host and port. */ + readonly origin: string; + readonly source: RpcSource; + /** True when it is Wasit's default RPC for the network. */ + readonly isDefault: boolean; +} + +/** The variable that fixes the MCP server's RPC at start-up. */ +export const RPC_LOCK_VARIABLE = "WASIT_RPC_URL"; + +function defaultRpc(protocol: "x402" | "mpp", network: string): string | undefined { + try { + return protocol === "x402" ? paymentChainFor(network)?.resolveRpcUrl(network) : resolveMppRpcUrl(network); + } catch { + return undefined; + } +} + +function sameUrl(a: string, b: string): boolean { + try { + return new URL(a).href === new URL(b).href; + } catch { + return false; + } +} + +/** + * The RPC a run on `network` reads through: `given` when there is one, else + * Wasit's default for the network. Undefined on a network that is not a test + * network (nothing is read there: the guard refuses first), and when there is + * neither. + */ +export function rpcInUse( + protocol: "x402" | "mpp", + network: string, + given?: { readonly url: string; readonly source: "argument" | "start-up" }, +): RpcInUse | undefined { + if (networkClass(network) !== "test") return undefined; + const fallback = defaultRpc(protocol, network); + if (fallback === undefined) return undefined; + if (given === undefined) return { origin: urlOrigin(fallback), source: "default", isDefault: true }; + return { origin: urlOrigin(given.url), source: given.source, isDefault: sameUrl(given.url, fallback) }; +} + +/** One line for a result: which RPC, from where, and a flag when it is not the default. */ +export function describeRpcInUse(network: string, rpc: RpcInUse): string { + if (rpc.source === "default") return `RPC: ${rpc.origin}, Wasit's default for ${network}.`; + const from = rpc.source === "argument" ? "from the rpcUrl argument" : `fixed when this server started (${RPC_LOCK_VARIABLE})`; + return rpc.isDefault + ? `RPC: ${rpc.origin}, ${from} (Wasit's default for ${network}).` + : `RPC: ${rpc.origin}, ${from}: not Wasit's default for ${network}, so every chain read of this run is this RPC's word.`; +} + +/** + * The MCP server's RPC lock: `WASIT_RPC_URL` when it holds a value. Off when it + * is unset or blank. A value that is not an http(s) URL is a problem the server + * refuses to start on; the message never quotes the value. + */ +export function readRpcLock( + env: Readonly>, +): { readonly url: string } | { readonly problem: string } | undefined { + const value = env[RPC_LOCK_VARIABLE]; + if (value === undefined || value.trim() === "") return undefined; + let url: URL; + try { + url = new URL(value.trim()); + } catch { + return { problem: `${RPC_LOCK_VARIABLE} is not a valid absolute URL; include the scheme, e.g. https://rpc.example.com` }; + } + if (url.protocol !== "http:" && url.protocol !== "https:") return { problem: `${RPC_LOCK_VARIABLE} must be an http or https URL` }; + if (url.hostname === "") return { problem: `${RPC_LOCK_VARIABLE} has no host` }; + return { url: value.trim() }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 259be58..a54e118 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -68,6 +68,7 @@ export { redactReport, redactValue, reportTotals, + paymentChecksSkipped, skippedPaymentChecks, toGradedRun, } from "./report.js"; @@ -112,7 +113,17 @@ export { runExitCode } from "./verdict.js"; export type { RunVerdict } from "./verdict.js"; // The pull request comment and the job summary. -export { COMMENT_MARKER, renderComment, renderNoReportComment, renderNoReportSummary, renderSummary } from "./ci-report.js"; +export { + COMMENT_MARKER, + renderCheckRun, + renderComment, + renderNoReportCheckRun, + renderNoReportComment, + renderNoReportSummary, + renderRunningComment, + renderSummary, +} from "./ci-report.js"; +export type { CheckRunOutput, RunningCommentInput } from "./ci-report.js"; export type { CiReportInput } from "./ci-report.js"; // Variables kept away from a service Wasit starts, and values kept out of output. @@ -132,6 +143,36 @@ export { } from "./guard/networks.js"; export type { NetworkClass, PaymentProtocol } from "./guard/networks.js"; +// The mainnet opt-in switches of this version: each one refuses (spec B12). +export { + MAINNET_OPT_IN_ABSENT, + MainnetOptInRefusedError, + mainnetStartupSwitches, + refuseMainnetSwitch, +} from "./guard/mainnet-optin.js"; +export type { MainnetSwitch } from "./guard/mainnet-optin.js"; + +// Which RPC a result read the chain through, and the MCP server's start-up RPC lock (D-023c). +export { RPC_LOCK_VARIABLE, describeRpcInUse, readRpcLock, rpcInUse } from "./guard/rpc-in-use.js"; +export { RpcIdentityError, assertRpcServesNetwork } from "./guard/rpc-identity.js"; +export type { RpcInUse, RpcSource } from "./guard/rpc-in-use.js"; + +// Which GitHub events may run the payment tier (D-022a), and which key variables are set. +export { inGithubActions, payerKeyVariables, paymentEventGate, readGithubEvent } from "./guard/ci-event.js"; +export type { PaymentEventGate } from "./guard/ci-event.js"; + +// L1 and L2: the plan, and the caps every signature is charged against. +export { + PER_PAYMENT_CAP_USD, + PER_RUN_CAP_USD, + PaymentGuardRefusedError, + RunBudget, + formatUsd, +} from "./guard/budget.js"; +export type { GuardRefusal, PinTerms, PlannedSignature } from "./guard/budget.js"; +export { describePlan, planX402Run } from "./x402/plan.js"; +export type { EndpointPlan, EndpointPlanStatus, PlannedOption, RunPlan, X402PlanOptions } from "./x402/plan.js"; + export * from "./x402/simulator.js"; export * from "./mpp/channel.js"; export * from "./mpp/charge.js"; diff --git a/packages/core/src/mpp/charge.ts b/packages/core/src/mpp/charge.ts index 5f85a6d..49221e3 100644 --- a/packages/core/src/mpp/charge.ts +++ b/packages/core/src/mpp/charge.ts @@ -28,9 +28,11 @@ import { MalformedResponseError, assertHttpUrl, fetchTarget, + fetchWithoutRedirects, } from "../errors.js"; import { type MppNetwork, assertMppNetwork, isMppNetwork, resolveRpcUrl } from "./network.js"; import { assertPaymentNetworkAllowed } from "../guard/networks.js"; +import { assertRpcServesNetwork } from "../guard/rpc-identity.js"; import { verifySettlement } from "../settlement.js"; const CHECK_ID = "MPP-01"; @@ -213,6 +215,9 @@ export async function payCharge( methods: [onNetwork(method, network)], polyfill: false, maxPaymentRetries: 1, + // Every request mppx makes here refuses a redirect (D-022c): it pays at the + // URL it read the challenge from, never at a URL the target sends it on to. + fetch: fetchWithoutRedirects, }); return mppx.fetch(target); } @@ -279,6 +284,10 @@ export async function runMppChargeChecks( ); } + // The payment is built and its settlement read through this endpoint: it + // must serve the run's network before the target is asked anything (D-023). + await assertRpcServesNetwork(runNetwork, endpoint); + const advertised = await fetchChargeChallenge(target); assertRunNetwork(advertised.network, runNetwork); diff --git a/packages/core/src/mpp/suite.ts b/packages/core/src/mpp/suite.ts index cbc77f9..d3b873c 100644 --- a/packages/core/src/mpp/suite.ts +++ b/packages/core/src/mpp/suite.ts @@ -16,8 +16,9 @@ import { runMppChannelReplayCheck, } from "./channel.js"; import { fetchChannelChallenge } from "./channel-credential.js"; -import { assertMppNetwork } from "./network.js"; +import { assertMppNetwork, resolveRpcUrl } from "./network.js"; import { assertPaymentNetworkAllowed } from "../guard/networks.js"; +import { assertRpcServesNetwork } from "../guard/rpc-identity.js"; const DEPLOY_ID = "MPP-10"; const DEPLOY_NAME = "Channel Deploy"; @@ -178,6 +179,9 @@ export async function runMppChannelSuite( assertHttpUrl(target); assertMppNetwork(network); assertPaymentNetworkAllowed("mpp-channel", network); + // Commitments are prepared and the channel read through this endpoint: it + // must serve the run's network before the target is asked anything (D-023). + await assertRpcServesNetwork(network, resolveRpcUrl(network, rpcUrl)); } catch (error) { const preflight = errored("PREFLIGHT", "Run Preflight", error); options.onResult?.(preflight); diff --git a/packages/core/src/report.ts b/packages/core/src/report.ts index f7ca8d1..f6b5cde 100644 --- a/packages/core/src/report.ts +++ b/packages/core/src/report.ts @@ -58,7 +58,7 @@ export function checkGroup(id: string, protocol: ProtocolId): CheckGroup { } /** - * True when an x402 payment check (X402-06..10) was skipped as `unsupported`: + * True when an x402 payment check (X402-06..11) was skipped as `unsupported`: * the run asked to pay and Wasit cannot pay on that network. A read-only or * no-payer skip is not this, and neither is a result of another protocol. An MPP * endpoint has no group besides its gating one, so for it this is always false. @@ -117,7 +117,7 @@ const KEY_LABEL: Readonly> = { /** The checks of a protocol that pay or sign. MPP-13 closes a channel for good and is never listed. */ const PAYMENT_CHECK_IDS: Readonly> = { - x402: ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"], + x402: ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"], "mpp-charge": ["MPP-01"], "mpp-channel": ["MPP-10", "MPP-11", "MPP-12", "MPP-14"], }; @@ -139,6 +139,15 @@ export function skippedPaymentChecks(protocol: ProtocolId, kind: "read-only" | " return PAYMENT_CHECK_IDS[protocol].map((id) => skipped(id, catalogueEntry(id)?.name ?? id, reason, kind)); } +/** + * The same checks, skipped with a reason the caller words: the run asked to pay + * and a rule of the run stopped it (the GitHub event, `operatedByMe`, a key + * variable that is not set), or the front end does not run them. + */ +export function paymentChecksSkipped(protocol: ProtocolId, kind: SkipKind, reason: string): CheckResult[] { + return PAYMENT_CHECK_IDS[protocol].map((id) => skipped(id, catalogueEntry(id)?.name ?? id, reason, kind)); +} + /** * The exit code of one endpoint's checks (spec A8 #3, D-021): 1 on any FAIL; 2 * when the endpoint was not graded (`unsupported` or `no-verdict`) or a check diff --git a/packages/core/src/settlement.ts b/packages/core/src/settlement.ts index dc14680..4c73175 100644 --- a/packages/core/src/settlement.ts +++ b/packages/core/src/settlement.ts @@ -55,7 +55,7 @@ function asRecord(value: unknown): Record | undefined { * form would drop every payment to a muxed address, and report a settlement * that happened as one that did not. */ -function readTransferData( +export function readTransferData( data: xdr.ScVal, ): { amount: bigint; toMuxedId?: string } | undefined { const native: unknown = scValToNative(data); diff --git a/packages/core/src/x402/chains/evm.ts b/packages/core/src/x402/chains/evm.ts index 94fa8a2..8c226fe 100644 --- a/packages/core/src/x402/chains/evm.ts +++ b/packages/core/src/x402/chains/evm.ts @@ -306,7 +306,10 @@ export const evmChain: PaymentChain = { client.register("eip155:*", new ExactEvmScheme(signer, { rpcUrl })); const allowed = NETWORKS[network]?.allowedAssets; if (allowed !== undefined) { + // Replaces the controls Wasit set before this call, so the $1 cap on the + // default assets is stated again rather than left to the SDK's default. client.setSpendControls({ + maxAmountPerPayment: "$1", allowedAssets: allowed.map((entry) => ({ network: network as `${string}:${string}`, ...entry })), }); } diff --git a/packages/core/src/x402/chains/index.ts b/packages/core/src/x402/chains/index.ts index 1cc3d0c..a7f1afa 100644 --- a/packages/core/src/x402/chains/index.ts +++ b/packages/core/src/x402/chains/index.ts @@ -13,12 +13,25 @@ export type { PaymentChain } from "./types.js"; // Stellar first: it is the default network, and the only chain with MPP. const CHAINS: readonly PaymentChain[] = [stellarChain, evmChain, svmChain]; +let chains: readonly PaymentChain[] = CHAINS; + +/** + * Tests only: replaces the adapters, so a recording chain can stand in for a + * real one (spec B11, the worst-case property test). `undefined` restores the + * real ones. Not exported from the package index, and reachable from no flag, + * setting or tool argument. The network guard still applies: a replacement + * pays only on a test network. + */ +export function setPaymentChainsForTesting(replacement: readonly PaymentChain[] | undefined): void { + chains = replacement ?? CHAINS; +} + /** The adapter that pays on `network`, if Wasit has one. */ export function paymentChainFor(network: string): PaymentChain | undefined { - return CHAINS.find((chain) => chain.networks.includes(network)); + return chains.find((chain) => chain.networks.includes(network)); } /** Every network the payment checks can pay on, in adapter order. */ export function paymentNetworks(): readonly string[] { - return CHAINS.flatMap((chain) => chain.networks); + return chains.flatMap((chain) => chain.networks); } diff --git a/packages/core/src/x402/chains/stellar.ts b/packages/core/src/x402/chains/stellar.ts index 4a48461..c356984 100644 --- a/packages/core/src/x402/chains/stellar.ts +++ b/packages/core/src/x402/chains/stellar.ts @@ -22,8 +22,8 @@ import { import { CheckSetupError } from "../../errors.js"; import { networkPassphrase, resolveRpcUrl } from "../../mpp/network.js"; -import { verifySettlement } from "../../settlement.js"; -import type { PaymentChain } from "./types.js"; +import { readTransferData, verifySettlement } from "../../settlement.js"; +import type { AuthorizationWatch, PaymentChain, RecordedTransfer, SignedAuthorization } from "./types.js"; /** A Stellar transaction hash: 64 hex characters. */ const TRANSACTION_HASH = /^[0-9a-f]{64}$/i; @@ -165,6 +165,129 @@ async function stellarTokenBalance( return entries.length === 0 ? 0n : undefined; } + +/** + * X402-11 reads (D-032, spec B16.4): the authorization a payment carries, as + * the payer signed it. Only an address credential is read; another form (the + * newer `AddressV2`, one with delegates) is not, and gives no reading rather + * than a guess, since its nonce handling was not read. + */ +export function decodeStellarAuthorization(payload: Record): SignedAuthorization { + const transaction = payload["transaction"]; + if (typeof transaction !== "string") { + throw new CheckSetupError("The payment payload carries no transaction to read its authorization from."); + } + let envelope: xdr.TransactionEnvelope; + try { + envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64"); + } catch { + throw new CheckSetupError("The payment payload's transaction does not decode, so its authorization cannot be read."); + } + const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : []; + const found: SignedAuthorization[] = []; + let otherForms = 0; + for (const operation of operations) { + if (operation.body().switch().name !== "invokeHostFunction") continue; + for (const entry of operation.body().invokeHostFunctionOp().auth()) { + const credentials = entry.credentials(); + const kind = credentials.switch().name; + if (kind === "sorobanCredentialsSourceAccount") continue; + if (kind !== "sorobanCredentialsAddress") { + otherForms += 1; + continue; + } + const address = credentials.address(); + found.push({ + payer: Address.fromScAddress(address.address()).toString(), + nonce: address.nonce().toString(), + expiresAt: address.signatureExpirationLedger(), + }); + } + } + if (otherForms > 0) { + throw new CheckSetupError( + "The payment's authorization uses a credential form this check does not read (it reads address credentials), " + + "so whether it was used cannot be read.", + ); + } + if (found.length !== 1) { + throw new CheckSetupError(`The payment carries ${found.length} address authorizations; this check reads exactly one.`); + } + return found[0]!; +} + +/** The ledger entry the host writes when it consumes the nonce: TEMPORARY contract data of the signer. */ +function nonceKey(authorization: SignedAuthorization): xdr.LedgerKey { + return xdr.LedgerKey.contractData( + new xdr.LedgerKeyContractData({ + contract: new Address(authorization.payer).toScAddress(), + key: xdr.ScVal.scvLedgerKeyNonce(new xdr.ScNonceKey({ nonce: xdr.Int64.fromString(authorization.nonce) })), + durability: xdr.ContractDataDurability.temporary(), + }), + ); +} + +function rpcServer(rpcUrl: string): rpc.Server { + return new rpc.Server(rpcUrl, { allowHttp: rpcUrl.startsWith("http://") }); +} + +/** The most events read for one X402-11 window: far more than one run makes. */ +const EVENTS_PAGE = 100; +const EVENTS_MAX_PAGES = 20; + +const stellarAuthorizations: AuthorizationWatch = { + unit: "ledger", + unitMs: 5_000, + // The x402 Stellar client's own default (DEFAULT_ESTIMATED_LEDGER_SECONDS in + // @x402/stellar 2.28.0); it estimates from recent ledgers when it can. + unitSeconds: 5, + decode: decodeStellarAuthorization, + async read(_network, rpcUrl, authorizations) { + const keys = authorizations.map(nonceKey); + const response = await rpcServer(rpcUrl).getLedgerEntries(...keys); + const byKey = new Map(response.entries.map((entry) => [entry.key.toXDR("base64"), entry])); + return { + latest: response.latestLedger, + used: keys.map((key) => { + const entry = byKey.get(key.toXDR("base64")); + return entry === undefined ? undefined : (entry.lastModifiedLedgerSeq ?? response.latestLedger); + }), + }; + }, + async transfers(_network, rpcUrl, query) { + const server = rpcServer(rpcUrl); + const name = xdr.ScVal.scvSymbol("transfer").toXDR("base64"); + const from = new Address(query.from).toScVal().toXDR("base64"); + const to = new Address(query.to).toScVal().toXDR("base64"); + // A Stellar Asset Contract adds the asset as a fourth topic (CAP-67); a SEP-41 token may not. + const filters: rpc.Api.EventFilter[] = [ + { type: "contract", contractIds: [query.asset], topics: [[name, from, to, "*"], [name, from, to]] }, + ]; + const transfers: RecordedTransfer[] = []; + let response = await server.getEvents({ startLedger: query.fromLedger, filters, limit: EVENTS_PAGE }); + for (let page = 1; ; page += 1) { + for (const event of response.events) { + // Only an event the RPC marks as from a failed call is left out. The testnet RPC no + // longer sends the field at all (observed 2026-11-16, run of slice 4's live check): + // reading its absence as "failed" dropped every transfer. + if (event.inSuccessfulContractCall === false) continue; + const [topic, sender, receiver] = event.topic; + if (topic?.switch().name !== "scvSymbol" || topic.sym().toString() !== "transfer") continue; + if (sender === undefined || receiver === undefined) continue; + if (Address.fromScVal(sender).toString() !== query.from || Address.fromScVal(receiver).toString() !== query.to) continue; + const data = readTransferData(event.value); + if (data === undefined) continue; + transfers.push({ amount: data.amount, reference: event.txHash, ledger: event.ledger }); + } + if (response.events.length < EVENTS_PAGE) break; + // Never a partial answer read as complete. + if (page >= EVENTS_MAX_PAGES) throw new Error("more transfer events than can be read in full"); + response = await server.getEvents({ cursor: response.cursor, filters, limit: EVENTS_PAGE }); + } + return { latest: response.latestLedger, transfers }; + }, +}; + export const stellarChain: PaymentChain = { name: "Stellar", networks: ["stellar:testnet", "stellar:pubnet"], @@ -187,4 +310,5 @@ export const stellarChain: PaymentChain = { ...payload, transaction: corruptAuthSignature(payload["transaction"] as string), }), + authorizations: stellarAuthorizations, }; diff --git a/packages/core/src/x402/chains/types.ts b/packages/core/src/x402/chains/types.ts index 1e13077..4bb9fc2 100644 --- a/packages/core/src/x402/chains/types.ts +++ b/packages/core/src/x402/chains/types.ts @@ -32,6 +32,72 @@ export interface ExpiredSigning { readonly holdMs: number; } +/** + * One signed authorization of a payment, as the chain records its use + * (X402-11, D-032). Decoded from what the payer signed, never computed. + */ +export interface SignedAuthorization { + /** The address that signed it. X402-11 holds it to the run's payer. */ + readonly payer: string; + /** Its single-use id on the chain (on Stellar the auth entry's nonce), as text. */ + readonly nonce: string; + /** The last ledger (or block) it can be used in, as signed. */ + readonly expiresAt: number; +} + +/** One read of the chain about some authorizations, all at the same state. */ +export interface AuthorizationRead { + /** The chain's latest closed ledger when it answered. */ + readonly latest: number; + /** + * Per authorization asked for, in order: the ledger its use was recorded in, + * or undefined when the chain holds no record of a use. + */ + readonly used: readonly (number | undefined)[]; +} + +/** A transfer the chain recorded, as X402-11's second reading counts it. */ +export interface RecordedTransfer { + readonly amount: bigint; + /** The transaction that made it (a hash), for the report. */ + readonly reference: string; + readonly ledger: number; +} + +/** + * How X402-11 reads whether an authorization was used, on chains where that + * can be read directly. A chain without one does not run X402-11. + */ +export interface AuthorizationWatch { + /** What the chain's unit of time is called in a report: "ledger". */ + readonly unit: string; + /** About how long one unit lasts, in milliseconds: the watch reads once per unit. */ + readonly unitMs: number; + /** + * The seconds one unit counts for when a client turns an advertised lifetime + * into an expiration (the lifetime divided by this, rounded up). X402-11 does + * not send an authorization that outlives its 300 s by more than that count. + */ + readonly unitSeconds: number; + /** + * The authorization a payment payload's inner `payload` carries. Throws + * `CheckSetupError` when it carries none that can be read, or more than one. + */ + decode(payload: Record): SignedAuthorization; + /** Whether each authorization was used, read in one call, so all at one state of the chain. */ + read(network: string, rpcUrl: string, authorizations: readonly SignedAuthorization[]): Promise; + /** + * Every successful transfer of `asset` from `from` to `to` recorded from + * ledger `fromLedger` on. Throws when the chain cannot serve that range in + * full: a partial answer is never read as "no transfer". + */ + transfers( + network: string, + rpcUrl: string, + query: { readonly asset: string; readonly from: string; readonly to: string; readonly fromLedger: number }, + ): Promise<{ readonly latest: number; readonly transfers: readonly RecordedTransfer[] }>; +} + export interface PaymentChain { /** The chain family's name, for reports. */ readonly name: string; @@ -96,4 +162,6 @@ export interface PaymentChain { * signature to corrupt. */ corruptPayload(payload: Record): Record; + /** X402-11's chain reads. Absent: X402-11 is skipped on this chain, nothing signed. */ + readonly authorizations?: AuthorizationWatch; } diff --git a/packages/core/src/x402/plan.ts b/packages/core/src/x402/plan.ts new file mode 100644 index 0000000..f2e27ba --- /dev/null +++ b/packages/core/src/x402/plan.ts @@ -0,0 +1,243 @@ +/** + * L1, the plan (spec B3, B4): before anything is signed, read each endpoint's + * unpaid challenge and work out what the run's payment checks would sign, and + * refuse what the caps or the pin do not allow. + * + * The plan is what `--dry-run` prints, and what a paying run hands to each + * endpoint's checks: L2 then refuses any signature the plan did not allow, so + * a service that raises its price or changes its payee between the plan and + * the payment gets a refusal, not a signature. + * + * It sends no payment, reads no key and signs nothing. + */ + +import { sanitizeText } from "../sanitize.js"; +import { assertPaymentNetworkAllowed } from "../guard/networks.js"; +import { + PER_PAYMENT_CAP_USD, + PER_RUN_CAP_USD, + PaymentGuardRefusedError, + RunBudget, + assertPinned, + formatUsd, + parseAmount, + plannedSignatures, + shown, + usdAsset, + usdFromDollars, + type PinTerms, + type PlannedSignature, +} from "../guard/budget.js"; +import { paymentChainFor } from "./chains/index.js"; +import { REJECTED_REQUEST_MAX_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_LIFETIME_SECONDS, type RejectCase } from "./rejected-request.js"; +import { readPaymentChallenge, type RequestShape } from "./simulator.js"; + +export interface PlanEndpointInput extends RequestShape { + readonly name: string; + readonly target: string; + /** The request the service must refuse: X402-11 signs once more, when it can run. */ + readonly reject?: RejectCase; +} + +export interface X402PlanOptions { + readonly network: string; + readonly pin?: PinTerms; + /** A lower per-run cap in dollars. */ + readonly maxRunUsd?: number; + readonly endpoints: readonly PlanEndpointInput[]; +} + +/** The option an endpoint's checks would pay, as its challenge stated it. */ +export interface PlannedOption { + readonly scheme: string; + readonly network: string; + readonly payTo: string; + readonly asset: string; + /** Base units. */ + readonly amount: bigint; + readonly maxTimeoutSeconds: number; +} + +export type EndpointPlanStatus = + /** Its payment checks would sign `signatures`. */ + | "planned" + /** Its payment checks would not pay at all (no option to pay, an unreadable challenge): `reason`. */ + | "not-paid" + /** The guard refuses to pay it: `reason`. */ + | "refused"; + +export interface EndpointPlan { + readonly name: string; + readonly status: EndpointPlanStatus; + readonly reason?: string; + readonly option?: PlannedOption; + readonly signatures: readonly PlannedSignature[]; + /** Base units of `option.asset`. */ + readonly worstCase: bigint; + /** Dollar units of `guard/budget.ts`; format with `formatUsd`. */ + readonly worstCaseUsd: bigint; +} + +export interface RunPlan { + readonly network: string; + readonly pin?: PinTerms; + readonly perPaymentCapUsd: bigint; + readonly capUsd: bigint; + /** Lowered by maxRunUsd. */ + readonly capLowered: boolean; + readonly endpoints: readonly EndpointPlan[]; + /** The sum over the planned endpoints. */ + readonly worstCaseUsd: bigint; + /** Set when the run must not start: its worst case is above its cap. Nothing was signed. */ + readonly refusal?: string; +} + +function message(error: unknown): string { + return sanitizeText(error instanceof Error ? error.message : String(error)).replace(/\s+/g, " "); +} + +const nothing = (name: string, status: EndpointPlanStatus, reason: string, option?: PlannedOption): EndpointPlan => ({ + name, + status, + reason, + ...(option === undefined ? {} : { option }), + signatures: [], + worstCase: 0n, + worstCaseUsd: 0n, +}); + +async function planEndpoint( + network: string, + pin: PinTerms | undefined, + endpoint: PlanEndpointInput, +): Promise { + let read; + try { + read = await readPaymentChallenge({ ...endpoint, network }); + } catch (error) { + // The same reasons the payment checks give when they would not pay. + return nothing(endpoint.name, "not-paid", message(error)); + } + const { paymentRequired, selected } = read; + try { + assertPinned(network, paymentRequired.accepts, pin); + const amount = parseAmount(selected.amount); + const option: PlannedOption = { + scheme: selected.scheme, + network: selected.network, + payTo: selected.payTo, + asset: selected.asset, + amount, + maxTimeoutSeconds: selected.maxTimeoutSeconds, + }; + const asset = usdAsset(network, selected.asset); + const price = RunBudget.valueOf(network, selected.asset, amount); + if (asset === undefined || price === undefined) { + return nothing( + endpoint.name, + "refused", + `it asks to be paid in an asset Wasit does not value in US dollars, so it cannot be held to the ` + + `$${PER_PAYMENT_CAP_USD}.00 cap. Nothing was signed.`, + option, + ); + } + const perPayment = usdFromDollars(PER_PAYMENT_CAP_USD); + if (price > perPayment) { + return nothing( + endpoint.name, + "refused", + `it is priced at ${amount} base units of ${asset.symbol} (${formatUsd(price)}), above the ` + + `${formatUsd(perPayment)} per payment fixed in Wasit. Nothing was signed. Test a route ` + + `priced at ${formatUsd(perPayment)} or less.`, + option, + ); + } + // X402-11 signs only when it can reach a verdict: a reject case, a chain whose + // authorizations can be read, a lifetime it waits out (D-032). + const rejectedRequest = + endpoint.reject !== undefined && + paymentChainFor(network)?.authorizations !== undefined && + selected.maxTimeoutSeconds >= REJECTED_REQUEST_MIN_LIFETIME_SECONDS && + selected.maxTimeoutSeconds <= REJECTED_REQUEST_MAX_LIFETIME_SECONDS; + const signatures = plannedSignatures(amount, { rejectedRequest }); + const worstCase = signatures.reduce((sum, entry) => sum + entry.amount, 0n); + return { + name: endpoint.name, + status: "planned", + option, + signatures, + worstCase, + worstCaseUsd: RunBudget.valueOf(network, selected.asset, worstCase) ?? 0n, + }; + } catch (error) { + if (error instanceof PaymentGuardRefusedError) return nothing(endpoint.name, "refused", message(error)); + throw error; + } +} + +/** + * The plan of a run's x402 payment checks. Throws the guard's refusal for a + * network that is not a test network (L0), before any request; the mainnet + * plan (the payer's balance, the token's decimals read on chain, the + * authorization lifetime) is part of the opt-in, not of this version. + */ +export async function planX402Run(options: X402PlanOptions): Promise { + assertPaymentNetworkAllowed("x402", options.network); + const budget = new RunBudget(options.maxRunUsd === undefined ? {} : { maxRunUsd: options.maxRunUsd }); + const capLowered = budget.capUsd < usdFromDollars(PER_RUN_CAP_USD); + + const endpoints: EndpointPlan[] = []; + for (const endpoint of options.endpoints) { + endpoints.push(await planEndpoint(options.network, options.pin, endpoint)); + } + const planned = endpoints.filter((endpoint) => endpoint.status === "planned"); + const worstCaseUsd = planned.reduce((sum, endpoint) => sum + endpoint.worstCaseUsd, 0n); + + const base = { + network: options.network, + ...(options.pin === undefined ? {} : { pin: options.pin }), + perPaymentCapUsd: usdFromDollars(PER_PAYMENT_CAP_USD), + capUsd: budget.capUsd, + capLowered, + endpoints, + worstCaseUsd, + }; + if (worstCaseUsd <= budget.capUsd) return base; + + const parts = planned.map((endpoint) => `${sanitizeText(endpoint.name)} ${formatUsd(endpoint.worstCaseUsd)}`); + return { + ...base, + refusal: + `This run could spend up to ${formatUsd(worstCaseUsd)} (${parts.join(", ")}), above the ` + + `${formatUsd(budget.capUsd)} per run${capLowered ? " set by maxRunUsd" : ""}. Nothing was signed. ` + + `Select fewer endpoints with --endpoint, or test a cheaper route.`, + }; +} + +/** + * The plan for a terminal or a log: the network, the caps, and per endpoint + * the destination, the asset, the amount of each signature and the worst case. + * Sanitised; no header value and no key (the plan holds neither). + */ +export function describePlan(plan: RunPlan): string[] { + const lines = [ + `Plan (dry run): x402 payment checks on ${plan.network}. Nothing is signed or sent.`, + `Caps: ${formatUsd(plan.perPaymentCapUsd)} a payment, ${formatUsd(plan.capUsd)} this run` + + `${plan.capLowered ? " (maxRunUsd)" : ""}.`, + ...(plan.pin === undefined ? [] : [`Pinned: payTo ${plan.pin.payTo}, asset ${plan.pin.asset}.`]), + ]; + for (const endpoint of plan.endpoints) { + if (endpoint.status !== "planned" || endpoint.option === undefined) { + lines.push(` ${endpoint.name}: ${endpoint.status === "refused" ? "refused" : "not paid"}: ${endpoint.reason ?? ""}`); + continue; + } + const { option } = endpoint; + lines.push( + ` ${endpoint.name}: pays ${shown(option.payTo)} in ${shown(option.asset)}, up to ${formatUsd(endpoint.worstCaseUsd)}`, + ` ${endpoint.signatures.map((entry) => `${entry.check} ${entry.amount}`).join(", ")} (base units)`, + ); + } + lines.push(`Worst case: ${formatUsd(plan.worstCaseUsd)} of ${formatUsd(plan.capUsd)}.`); + if (plan.refusal !== undefined) lines.push(`Refused: ${plan.refusal}`); + return lines.map((line) => sanitizeText(line)); +} diff --git a/packages/core/src/x402/rejected-request.ts b/packages/core/src/x402/rejected-request.ts new file mode 100644 index 0000000..b80cd8c --- /dev/null +++ b/packages/core/src/x402/rejected-request.ts @@ -0,0 +1,353 @@ +/** + * X402-11, "Rejected Request Not Settled" (spec B7 as D-032 changed it). + * + * Wasit sends a valid payment, for the advertised terms exactly, with a request + * the builder's config declares invalid (`endpoints[].reject`), then reads the + * chain: the nonce of that payment's authorization must still be unused once + * its expiration ledger has passed. The verdict comes from one read that asks + * for that nonce and for X402-06's, which was used and must be found: a read + * that cannot find X402-06's cannot show that ours is absent. The payer's + * balance and the transfer events are second readings; when they disagree with + * the nonce, there is no verdict. + * + * The wait (Najmi, 2026-11-16): a payment whose advertised lifetime + * (`maxTimeoutSeconds`) is at most 300 s is waited out, with a hard stop 360 s + * after it was sent; a longer one is not signed at all (it is read again on the + * challenge the payment is signed from), and an authorization the client signs + * to outlive it is not sent. A lifetime below 30 s is not signed either, and an + * authorization with fewer than 3 ledgers left is not sent (2026-11-17). + * + * This file holds the parts that need no network: the rules, the reject + * request's shape, the watch loop over a chain's reads, and the verdict. The + * check itself, which pays, is in `simulator.ts` with the other payment checks. + */ + +import { errored, skipped, type CheckResult } from "../check.js"; +import { CheckSetupError } from "../errors.js"; +import { sanitizeText } from "../sanitize.js"; +import type { AuthorizationWatch, SignedAuthorization } from "./chains/types.js"; + +export const REJECTED_REQUEST_ID = "X402-11"; +export const REJECTED_REQUEST_NAME = "Rejected Request Not Settled"; + +/** The longest advertised lifetime X402-11 waits out on a test network. */ +export const REJECTED_REQUEST_MAX_LIFETIME_SECONDS = 300; + +/** + * The shortest advertised lifetime X402-11 signs for (Najmi, 2026-11-17, + * screening S-1): a payment valid for a few seconds can expire before a service + * that settles it has it on chain, and its unused authorization would then show + * nothing about the service. + */ +export const REJECTED_REQUEST_MIN_LIFETIME_SECONDS = 30; + +/** The fewest units of validity a signed authorization must have left when X402-11 sends it. */ +export const REJECTED_REQUEST_MIN_UNITS_LEFT = 3; + +/** + * How long after the payment is sent the watch stops, whatever the lifetime: + * a 300 s lifetime is 60 ledgers of 5 s, and the verdict needs the ledger + * after it, so about 305 s; the rest is slack for a slow ledger or RPC. + */ +export const REJECTED_REQUEST_HARD_STOP_MS = 360_000; + +let hardStopForTesting: number | undefined; + +/** + * Tests only: a shorter hard stop, so "still valid when the watch stopped" can + * be shown without a six-minute test. It can only lower the stop. Not exported + * from the package index; no flag, setting or tool argument reaches it. + */ +export function setRejectedRequestHardStopForTesting(ms: number | undefined): void { + hardStopForTesting = ms; +} + +export function rejectedRequestHardStopMs(): number { + return hardStopForTesting === undefined + ? REJECTED_REQUEST_HARD_STOP_MS + : Math.min(hardStopForTesting, REJECTED_REQUEST_HARD_STOP_MS); +} + +/** The request the service must refuse, as the config gives it (`ResolvedReject`). */ +export interface RejectCase { + readonly method?: string; + readonly headers?: Readonly>; + /** Serialised, as `ResolvedReject` holds it. */ + readonly body?: string; + readonly note?: string; +} + +interface Shape { + readonly method?: string; + readonly body?: string; + readonly headers?: Readonly>; +} + +const BODYLESS = new Set(["GET", "HEAD"]); + +/** + * The endpoint's own request with the reject case over it: its method when it + * names one, its headers over the endpoint's (by name, ignoring case), and its + * body instead of the endpoint's. A method that carries no body drops the + * endpoint's body; the config already refuses a reject body on such a method. + */ +export function rejectRequestShape(shape: Shape, reject: RejectCase): Shape { + const method = (reject.method ?? shape.method ?? "GET").toUpperCase(); + const replaced = new Set(Object.keys(reject.headers ?? {}).map((name) => name.toLowerCase())); + const headers: Record = {}; + for (const [name, value] of Object.entries(shape.headers ?? {})) { + if (!replaced.has(name.toLowerCase())) headers[name] = value; + } + Object.assign(headers, reject.headers ?? {}); + const body = reject.body !== undefined ? reject.body : BODYLESS.has(method) ? undefined : shape.body; + return { + method, + ...(Object.keys(headers).length === 0 ? {} : { headers }), + ...(body === undefined ? {} : { body }), + }; +} + +/** What the watch found, from the chain's reads only. */ +export type WatchOutcome = + /** The chain records the authorization as used, in `ledger`. */ + | { readonly kind: "used"; readonly ledger: number; readonly latest: number } + /** A read at `latest`, past the expiration ledger, found it unused, and found the control. */ + | { readonly kind: "unused"; readonly latest: number } + /** The hard stop came first: at `latest` it was unused and could still be used. */ + | { readonly kind: "still-valid"; readonly latest: number } + /** The chain could not be read to the end, or its answer could not be trusted: `why`. */ + | { readonly kind: "unread"; readonly why: string }; + +function message(error: unknown): string { + return sanitizeText(error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").slice(0, 200); +} + +class ReadTimedOut extends Error {} + +/** `promise`, or `ReadTimedOut` once `ms` have passed (at once when `ms` is 0 or less). */ +function withinMs(promise: Promise, ms: number): Promise { + // A read that answers after the stop is ignored, and its failure too. + promise.catch(() => undefined); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new ReadTimedOut()), Math.max(0, ms)); + promise.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (error: unknown) => { + clearTimeout(timer); + reject(error); + }, + ); + }); +} + +export interface WatchInput { + readonly watch: AuthorizationWatch; + readonly network: string; + readonly rpcUrl: string; + readonly ours: SignedAuthorization; + /** X402-06's authorization, which was used: every read must find it. */ + readonly control: SignedAuthorization; + /** When the payment was sent (ms since the epoch): the hard stop counts from it. */ + readonly sentAt: number; + readonly now?: () => number; + readonly sleep?: (ms: number) => Promise; +} + +/** + * Reads the chain once a ledger until the authorization is used, or a read + * past its expiration ledger finds it unused, or the hard stop comes. Every + * read asks for the control too; one that does not return it ends the watch + * with no reading. Never throws: a failed read is an `unread` outcome. + */ +export async function watchAuthorization(input: WatchInput): Promise { + const now = input.now ?? Date.now; + const sleep = input.sleep ?? ((ms: number) => new Promise((done) => setTimeout(done, ms))); + const stop = input.sentAt + rejectedRequestHardStopMs(); + for (;;) { + let read; + try { + // A read that has not answered by the hard stop ends the watch there: the + // stop holds while a read is in flight, not only between reads. + read = await withinMs(input.watch.read(input.network, input.rpcUrl, [input.ours, input.control]), stop - now()); + } catch (error) { + if (error instanceof ReadTimedOut) { + return { + kind: "unread", + why: `the chain did not answer a read before the watch's hard stop, ${Math.round(rejectedRequestHardStopMs() / 1000)} s after the payment was sent`, + }; + } + return { kind: "unread", why: `the chain read failed: ${message(error)}` }; + } + if (read.used[1] === undefined) { + return { + kind: "unread", + why: "the chain's answer left out X402-06's authorization, which was used, so it cannot show that this one was not", + }; + } + const usedAt = read.used[0]; + if (usedAt !== undefined) return { kind: "used", ledger: usedAt, latest: read.latest }; + if (read.latest > input.ours.expiresAt) return { kind: "unused", latest: read.latest }; + const left = stop - now(); + if (left <= 0) return { kind: "still-valid", latest: read.latest }; + await sleep(Math.max(1, Math.min(input.watch.unitMs, left))); + } +} + +export interface RejectedRequestEvidence { + /** What the service answered the paid invalid request with. */ + readonly status: number; + readonly reason?: string; + /** Base units, as signed: the advertised amount. */ + readonly amount: bigint; + /** The expiration ledger, decoded from the signed authorization. */ + readonly expiresAt: number; + /** "ledger". */ + readonly unit: string; + readonly watch: WatchOutcome; + /** The payer's balance before signing and after the watch. Missing: not read. */ + readonly balance?: { readonly before: bigint; readonly after: bigint }; + /** Transfers of exactly `amount` from the payer to `payTo` recorded after the payment was sent. Missing: not read. */ + readonly transfers?: readonly { readonly reference: string; readonly ledger: number }[]; +} + +function refusal(status: number, reason: string | undefined): string { + return reason === undefined ? `HTTP ${status}` : `HTTP ${status}: ${reason}`; +} + +/** Why the second readings do not support "taken", or undefined when they do. */ +function notTaken(evidence: RejectedRequestEvidence): string | undefined { + const { balance, transfers, amount } = evidence; + if (balance === undefined || transfers === undefined) return "the payer's balance or the transfer events were not read"; + const fell = balance.before - balance.after; + if (transfers.length === 0) return `no transfer of ${amount} base units from the payer to payTo was recorded`; + if (fell < amount) return `the payer's balance fell by ${fell} base units, less than the ${amount} paid`; + return undefined; +} + +/** Why the second readings do not support "not taken", or undefined when they do. */ +function notUntaken(evidence: RejectedRequestEvidence): string | undefined { + const { balance, transfers, amount } = evidence; + if (balance === undefined || transfers === undefined) return "the payer's balance or the transfer events were not read"; + const fell = balance.before - balance.after; + if (transfers.length > 0) { + return `a transfer of ${amount} base units from the payer to payTo was recorded (${transfers.map((item) => item.reference).join(", ")})`; + } + if (fell >= amount) return `the payer's balance fell by ${fell} base units, at least the ${amount} paid`; + return undefined; +} + +const SERVED_HINT = + "Refuse an invalid request before its payment is settled. The official x402 Express middleware does not settle " + + "when the handler answers 400 or above; a route that serves every request it is paid for sells what it should refuse."; + +const TAKEN_HINT = + "A refused request must not cost the payer: settle a payment only after the request has been accepted. The " + + "official x402 Express middleware does not settle when the handler answers 400 or above; code that settles " + + "before validating the request, or settles on its own, takes the payment for a request it then refuses."; + +/** + * X402-11's verdict from what the service answered and what the chain shows. + * + * - served (2xx): FAIL, whatever the chain shows; the chain only adds whether it settled. + * - refused, used, the second readings agree: FAIL, the payment was taken. + * - refused, unused past the expiry, the second readings agree: PASS. + * - refused and still valid at the hard stop: SKIP, "not settled by ledger N; still valid until ledger M". + * - anything else (a reading that disagrees or is missing, a read that failed): no verdict, never PASS. + */ +export function rejectedRequestVerdict(evidence: RejectedRequestEvidence): CheckResult { + const id = REJECTED_REQUEST_ID; + const name = REJECTED_REQUEST_NAME; + const { watch, unit, expiresAt, amount, status } = evidence; + const served = status >= 200 && status < 300; + + if (served) { + let note: string; + if (watch.kind === "used") { + const why = notTaken(evidence); + note = + why === undefined + ? ` The payment was taken: ${evidence.transfers!.map((item) => `${item.reference} (${unit} ${item.ledger})`).join(", ")}.` + : ` The chain records its authorization as used (${unit} ${watch.ledger}), but ${why}, so whether it was taken is not stated.`; + } else if (watch.kind === "unused") { + const why = notUntaken(evidence); + note = + why === undefined + ? ` The payment did not settle: its authorization expired at ${unit} ${expiresAt} unused.` + : ` Whether the payment settled is not stated: the chain records its authorization as unused, but ${why}.`; + } else if (watch.kind === "still-valid") { + note = ` Whether the payment settled is not known: it was still valid at ${unit} ${watch.latest}, until ${unit} ${expiresAt}, when Wasit stopped waiting.`; + } else { + note = ` Whether the payment settled was not read: ${watch.why}.`; + } + return { + id, + name, + pass: false, + detail: `A request the config declares invalid was served (HTTP ${status}) with a valid payment for ${amount} base units.${note}`, + hint: SERVED_HINT, + expected: "the invalid request refused", + actual: `HTTP ${status}`, + }; + } + + const refused = `The request the config declares invalid was refused (${refusal(status, evidence.reason)})`; + const noVerdict = (text: string): CheckResult => errored(id, name, new CheckSetupError(text)); + + switch (watch.kind) { + case "used": { + const why = notTaken(evidence); + if (why !== undefined) { + return noVerdict( + `${refused}. The chain records this payment's authorization as used (${unit} ${watch.ledger}), but ${why}, ` + + `so the readings disagree and there is no verdict.`, + ); + } + const where = evidence.transfers!.map((item) => `${item.reference} (${unit} ${item.ledger})`).join(", "); + return { + id, + name, + pass: false, + detail: + `${refused} and the payment was taken: ${amount} base units moved from the payer to payTo in ${where}; ` + + `the chain records its authorization as used.`, + hint: TAKEN_HINT, + expected: "a refused request leaves its payment unsettled", + actual: `the payment settled (${unit} ${watch.ledger})`, + }; + } + case "unused": { + const why = notUntaken(evidence); + if (why !== undefined) { + return noVerdict( + `${refused}. The chain records this payment's authorization as unused past its expiry (${unit} ${expiresAt}), ` + + `but ${why}, so the readings disagree and there is no verdict.`, + ); + } + return { + id, + name, + pass: true, + detail: + `${refused}, and the payment was not taken: its authorization expired at ${unit} ${expiresAt} unused ` + + `(read at ${unit} ${watch.latest}, in the same read that found X402-06's used authorization); no transfer ` + + `of it to payTo was recorded, and the payer's balance did not fall by it.`, + }; + } + case "still-valid": + return skipped( + id, + name, + `the request was refused (${refusal(status, evidence.reason)}), and its payment was not settled by ${unit} ` + + `${watch.latest}; still valid until ${unit} ${expiresAt} when Wasit stopped waiting (at most ` + + `${REJECTED_REQUEST_HARD_STOP_MS / 1000} s on a test network), so whether it settles is not known.`, + ); + case "unread": + return noVerdict( + `${refused}, but the chain was not read to the end of the payment's validity (${watch.why}), so whether it ` + + `settled is not known.`, + ); + } +} diff --git a/packages/core/src/x402/simulator.ts b/packages/core/src/x402/simulator.ts index a5bc318..44fd864 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -4,9 +4,33 @@ import { ConfigurationError, MalformedResponseError, assertHttpUrl, + fetchPaymentChallenge, fetchTarget, } from "../errors.js"; +import { + PER_PAYMENT_CAP_USD, + PaymentGuardRefusedError, + RunBudget, + assertPinned, + sameAddress, + type PinTerms, +} from "../guard/budget.js"; import { assertPaymentNetworkAllowed } from "../guard/networks.js"; +import { assertRpcServesNetwork } from "../guard/rpc-identity.js"; +import type { EndpointPlan } from "./plan.js"; +import { + REJECTED_REQUEST_ID, + REJECTED_REQUEST_MAX_LIFETIME_SECONDS, + REJECTED_REQUEST_MIN_LIFETIME_SECONDS, + REJECTED_REQUEST_MIN_UNITS_LEFT, + REJECTED_REQUEST_NAME, + rejectRequestShape, + rejectedRequestHardStopMs, + rejectedRequestVerdict, + watchAuthorization, + type RejectCase, + type WatchOutcome, +} from "./rejected-request.js"; import { sanitizeText } from "../sanitize.js"; import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js"; @@ -201,14 +225,16 @@ async function readText(response: Response): Promise { /** * Why an x402 v1 challenge is not graded: the reason on X402-02..05 and on the - * endpoint. Kept under 300 characters, the longest a value goes into a pull - * request comment, so the way to get graded is not cut off. + * endpoint, on every chain (a v1 service on an EVM chain gets it too). Kept + * under 300 characters, the longest a value goes into a pull request comment, + * so the way to get graded is not cut off. It names no URL: the comment's + * sanitiser removes links from check text, so it points at docs/CHECKS.md, + * whose note on x402 v1 links the x402 specification. */ const V1_UNSUPPORTED_REASON = - "the service sent an x402 v1 challenge in its response body. Wasit grades x402 v2, and the " + - "`exact` scheme on Stellar exists for v2 only, so this endpoint is unsupported, not failed. " + - "To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED " + - "response header."; + "the service sent an x402 v1 challenge (x402Version 1, in the body). Wasit grades only x402 v2, on " + + "every chain: challenge in a PAYMENT-REQUIRED header, CAIP-2 networks, v2 `exact` scheme (Stellar is " + + "v2 only). Unsupported, not failed. Fix: move it to that header. Why: docs/CHECKS.md."; /** What a check found on a challenge Wasit does not grade, to be shown as a note. */ function noteOf(result: CheckResult): string { @@ -398,6 +424,23 @@ export interface X402PaymentCheckOptions extends RequestShape { readonly rpcUrl?: string; /** See {@link X402SimulatorOptions.onResult} — same contract. */ readonly onResult?: (result: CheckResult) => void; + /** + * The run's budget, shared by every endpoint of one run. Without one, these + * checks get their own: $5, of which they sign at most 3.5 times a $1 price. + */ + readonly budget?: RunBudget; + /** Every `exact` option on the run's network must pay this `payTo` in this asset. */ + readonly pin?: PinTerms; + /** This endpoint's entry of the run's plan (L1): no signature beyond it. */ + readonly plan?: EndpointPlan; + /** The request the service must refuse (`endpoints[].reject`), for X402-11. Absent: X402-11 is skipped. */ + readonly reject?: RejectCase; + /** + * Called with one line when a check starts a long wait on the chain (X402-11 + * waits up to six minutes), so a log does not look stuck. The line holds no + * text from the service. + */ + readonly onProgress?: (line: string) => void; } /** One check has nothing to test against this target; it is skipped with the reason. */ @@ -453,16 +496,27 @@ async function buildX402Client( network: string, payerSecretKey: string, rpcUrl: string, + pin: PinTerms | undefined, ) { const client = new x402Client(); + // L3 (spec B3): the SDK's own spend controls, set here rather than left to + // its default, as a second implementation of the $1 cap. An adapter that + // allows more assets replaces them and states the cap again (`evm.ts`). + client.setSpendControls({ maxAmountPerPayment: `$${PER_PAYMENT_CAP_USD}` }); await chain.registerPayer(client, network, payerSecretKey, rpcUrl); client // A challenge may offer several networks, including both Stellar ones. // The client's default pick is the first it supports, which would sign // for one network with a signer built for another; pay only on the - // network this run was asked to use. + // network this run was asked to use. With a pin, L3 also keeps only the + // pinned payee and asset, whatever else picked the option. .registerPolicy((_version, requirements) => - requirements.filter((requirement) => requirement.network === network), + requirements.filter( + (requirement) => + requirement.network === network && + (pin === undefined || + (sameAddress(network, requirement.payTo, pin.payTo) && sameAddress(network, requirement.asset, pin.asset))), + ), ); return { client, httpClient: new x402HTTPClient(client) }; } @@ -516,38 +570,27 @@ async function withinSpendControls( } /** - * Reads the challenge and produces a signed payment payload for it. + * What a payment check reads before it can pay: the challenge, the URL to pay + * at, and the one option it would pay. Shared by `preparePayment` and the plan + * (L1), so both judge the same option by the same rules. * - * Shared by every payment check so each one starts from a challenge the - * target issued just now, rather than reusing a stale one. With `altered`, - * the payment is signed for those terms instead, and its `accepted` is set - * back to what the target advertised. `beforeSigning` runs once the option - * to pay is known and before the client builds anything: the Stellar client - * simulates the transfer while building, so a check placed later would never - * see an unfunded payer. + * Throws `PaymentNotAttemptedError` when there is nothing to pay: an + * unreadable or v1 challenge, no option on the run's network, or none in the + * `exact` scheme. */ -async function preparePayment( - options: X402PaymentCheckOptions, - alter?: (selected: PaymentRequirements) => AlteredSigning | Promise, - beforeSigning?: (selected: PaymentRequirements) => Promise, -) { - // L0 again at the one function every x402 signature goes through, whoever - // reaches it: nothing is fetched or signed on a network that is not a test - // network. - assertPaymentNetworkAllowed("x402", options.network); - const chain = chainFor(options.network); - const { client, httpClient } = await buildX402Client( - chain, - options.network, - options.payerSecretKey, - chain.resolveRpcUrl(options.network, options.rpcUrl), - ); - - const challenge = await fetchTarget(options.target, buildInit(options)); +export async function readPaymentChallenge(options: RequestShape & { readonly target: string; readonly network: string }) { + // The payment goes where this challenge came from, never through a redirect + // (D-022c): `payUrl` is the target, or the URL one same-origin redirect led to. + const { response: challenge, url: payUrl } = await fetchPaymentChallenge(options.target, buildInit(options)); + return { ...(await paymentTerms(challenge, options.network)), payUrl }; +} +/** The terms of a challenge already fetched, by the rules of {@link readPaymentChallenge}. */ +async function paymentTerms(challenge: Response, network: string) { + const options = { network }; let paymentRequired; try { - paymentRequired = httpClient.getPaymentRequiredResponse((name) => + paymentRequired = new x402HTTPClient(new x402Client()).getPaymentRequiredResponse((name) => challenge.headers.get(name), ); } catch (error) { @@ -567,6 +610,7 @@ async function preparePayment( `(see X402-02–04).`, ); } + await challenge.body?.cancel().catch(() => undefined); // A target that offers no option Wasit can pay has not refused anything: // there is no payment to judge, so neither check gets a verdict. X402-05 @@ -593,24 +637,125 @@ async function preparePayment( // The payment-identifier extension lets a server answer a repeated payload // with its cached response (specs/extensions/payment_identifier.md). const idempotent = paymentRequired.extensions?.["payment-identifier"] !== undefined; + return { paymentRequired, selected, idempotent }; +} - await beforeSigning?.(selected); - if (alter === undefined) { - const paymentPayload = await withinSpendControls(options.network, selected, () => - client.createPaymentPayload(paymentRequired), +/** A stable text of a value, keys sorted, for a field-by-field comparison. */ +function canonical(value: unknown): string { + return JSON.stringify(value, (_key, item: unknown) => + item !== null && typeof item === "object" && !Array.isArray(item) + ? Object.fromEntries(Object.entries(item as Record).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) + : item, + ); +} + +/** + * L2 against the plan: the option a check is about to pay must be the one the + * plan read, and the amount at most what the plan allowed for that check. + * Returns that amount, or undefined when the run has no plan. + */ +function plannedAmount(plan: EndpointPlan | undefined, check: string, selected: PaymentRequirements): bigint | undefined { + if (plan === undefined) return undefined; + const option = plan.option; + if (plan.status !== "planned" || option === undefined) { + throw new PaymentGuardRefusedError( + "plan", + `The plan of this run did not plan a payment for ${plan.name} (${plan.status}), so ${check} does not pay it.` + + (plan.reason === undefined ? "" : ` The plan says: ${plan.reason}`), ); - return { httpClient, paymentPayload, selected, idempotent }; } + for (const field of ["scheme", "network", "payTo", "asset"] as const) { + const same = + field === "payTo" || field === "asset" + ? sameAddress(option.network, String(selected[field]), option[field]) + : selected[field] === option[field]; + if (!same) { + throw new PaymentGuardRefusedError( + "plan", + `${check}: the service changed its ${field} after the plan (the plan read ${option[field]}), ` + + `so the payment the plan allowed is not the one it now asks for.`, + ); + } + } + const entry = plan.signatures.find((signature) => signature.check === check); + if (entry === undefined) { + throw new PaymentGuardRefusedError("plan", `The plan of this run has no signature for ${check}.`); + } + return entry.amount; +} - const altered = await alter(selected); +/** + * Reads the challenge and produces a signed payment payload for it. + * + * Shared by every payment check so each one starts from a challenge the + * target issued just now, rather than reusing a stale one. With `altered`, + * the payment is signed for those terms instead, and its `accepted` is set + * back to what the target advertised. `beforeSigning` runs once the option + * to pay is known and before the client builds anything: the Stellar client + * simulates the transfer while building, so a check placed later would never + * see an unfunded payer. + * + * L2 (spec B3) is here, between the fresh challenge and the SDK: the pin over + * every `exact` option, the plan, the $1 cap and the run's cap, the run charged + * before the signature. The SDK is then handed exactly the one option checked, + * and a payload whose `accepted` is not that option is discarded unsent. + */ +async function preparePayment( + options: X402PaymentCheckOptions, + check: string, + alter?: (selected: PaymentRequirements) => AlteredSigning | Promise, + beforeSigning?: (selected: PaymentRequirements) => Promise, +) { + // L0 again at the one function every x402 signature goes through, whoever + // reaches it: nothing is fetched or signed on a network that is not a test + // network. + assertPaymentNetworkAllowed("x402", options.network); + const chain = chainFor(options.network); + const budget = options.budget ?? new RunBudget(); + const { client, httpClient } = await buildX402Client( + chain, + options.network, + options.payerSecretKey, + chain.resolveRpcUrl(options.network, options.rpcUrl), + options.pin, + ); + + const { paymentRequired, selected, idempotent, payUrl } = await readPaymentChallenge(options); + + // L2, before anything is built: the service may change its challenge between + // requests, so the plan alone is not enough. + assertPinned(options.network, paymentRequired.accepts, options.pin); + const planned = plannedAmount(options.plan, check, selected); + const signing: PaymentRequirements = alter === undefined ? selected : { ...selected, ...(await alter(selected)) }; + for (const field of ["scheme", "network", "payTo", "asset"] as const) { + if (signing[field] !== selected[field]) { + throw new PaymentGuardRefusedError("accepted", `${check} would sign different ${field} terms than the target's.`); + } + } + budget.charge({ + check, + network: options.network, + asset: signing.asset, + amount: signing.amount, + ...(planned === undefined ? {} : { planned }), + }); + + await beforeSigning?.(selected); const signed = await withinSpendControls(options.network, selected, () => - client.createPaymentPayload({ - ...paymentRequired, - accepts: [{ ...selected, ...altered }], - }), + client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }), ); - const paymentPayload = { ...signed, accepted: selected }; - return { httpClient, paymentPayload, selected, idempotent }; + // What the SDK says it signed must be the option checked, field by field; + // otherwise the payload is discarded here, unsent. It stays charged. + if (canonical(signed.accepted) !== canonical(signing)) { + throw new PaymentGuardRefusedError( + "accepted", + `The payment the x402 client built for ${check} names other terms in its accepted field than the ` + + `option Wasit checked.`, + { signed: true }, + ); + } + const paymentPayload = alter === undefined ? signed : { ...signed, accepted: selected }; + return { httpClient, paymentPayload, selected, idempotent, payUrl }; } /** @@ -679,8 +824,12 @@ interface HonestPayment { readonly accepted: boolean; /** The exact headers the honest payment was sent with. */ readonly headers: Record; + /** Where the honest payment was sent: the replay goes to the same URL. */ + readonly url: string; /** True when the challenge advertised the payment-identifier extension. */ readonly idempotent: boolean; + /** The honest payment's inner payload: X402-11 reads its authorization as the control. */ + readonly payload: Record; } /** @@ -733,19 +882,18 @@ async function checkSignatureAccepted(options: X402PaymentCheckOptions): Promise const name = "Signature Resubmit Accepted"; const fail = (detail: string, hint: string): CheckResult => ({ id, name, pass: false, detail, hint }); - const { httpClient, paymentPayload, idempotent } = await preparePayment(options, undefined, (selected) => + const { httpClient, paymentPayload, idempotent, payUrl } = await preparePayment(options, "X402-06", undefined, (selected) => assertPayerCanPay(options, selected), ); const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload); - const paid = await fetchTarget( - options.target, - withPaymentHeaders(options, paymentHeaders), - ); + const paid = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders)); const honest = (result: CheckResult, accepted: boolean): HonestPayment => ({ result, accepted, headers: paymentHeaders, + url: payUrl, idempotent, + payload: paymentPayload.payload, }); if (paid.status < 200 || paid.status >= 300) { @@ -808,6 +956,8 @@ async function checkSignatureAccepted(options: X402PaymentCheckOptions): Promise name, pass: true, detail: `Valid payment accepted (HTTP ${paid.status}) and ${verdict.detail}.`, + // Read back from the chain and found to be this payment: a report may link it. + reference, } : fail( verdict.detail, @@ -835,7 +985,7 @@ async function checkSignatureAccepted(options: X402PaymentCheckOptions): Promise async function checkInvalidSignatureRejected( options: X402PaymentCheckOptions, ): Promise { - const { httpClient, paymentPayload } = await preparePayment(options); + const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-07"); const corrupted = { ...paymentPayload, @@ -843,10 +993,7 @@ async function checkInvalidSignatureRejected( }; const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted); - const response = await fetchTarget( - options.target, - withPaymentHeaders(options, paymentHeaders), - ); + const response = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders)); return signatureRejectionVerdict(response.status, await refusalReason(response)); } @@ -949,7 +1096,7 @@ async function checkReplayRejected( "server may answer a repeated payment with its cached response.", ); } - const response = await fetchTarget(options.target, withPaymentHeaders(options, honest.headers)); + const response = await fetchTarget(honest.url, withPaymentHeaders(options, honest.headers)); return replayVerdict(response.status, await refusalReason(response)); } @@ -986,11 +1133,28 @@ export function replayVerdict(status: number, reason?: string): CheckResult { * accepts, the lower amount may settle. */ async function checkUnderpaymentRejected(options: X402PaymentCheckOptions): Promise { + // The plan of `wasit run` leaves X402-09 out at a price below 2 base units; + // the check is then skipped as it is without a plan, and nothing is fetched. + const plan = options.plan; + if ( + plan?.status === "planned" && + plan.option !== undefined && + plan.option.amount < 2n && + !plan.signatures.some((signature) => signature.check === "X402-09") + ) { + const price = plan.option.amount; + return skipped( + "X402-09", + "Underpayment Rejected", + `the advertised price is ${price} base unit${price === 1n ? "" : "s"} (as the plan read it before the run), so ` + + `there is no smaller payment to offer.`, + ); + } let advertised = 0n; let offered = 0n; let prepared; try { - prepared = await preparePayment(options, (selected) => { + prepared = await preparePayment(options, "X402-09", (selected) => { try { advertised = BigInt(selected.amount); } catch { @@ -1013,9 +1177,9 @@ async function checkUnderpaymentRejected(options: X402PaymentCheckOptions): Prom } throw error; } - const { httpClient, paymentPayload } = prepared; + const { httpClient, paymentPayload, payUrl } = prepared; const response = await fetchTarget( - options.target, + payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)), ); return underpaymentVerdict(response.status, offered, advertised, await refusalReason(response)); @@ -1065,14 +1229,14 @@ async function checkExpiredRejected(options: X402PaymentCheckOptions): Promise { + const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-10", async (selected) => { const expired = await chain.expiredSigning(selected, rpcUrl); holdMs = expired.holdMs; return expired.terms; }); await new Promise((done) => setTimeout(done, holdMs)); const response = await fetchTarget( - options.target, + payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)), ); return expiredVerdict(response.status, await refusalReason(response)); @@ -1100,6 +1264,257 @@ export function expiredVerdict(status: number, reason?: string): CheckResult { }; } +/** A signed authorization, decoded and held to the run's payer; `what` names it in a message. */ +function authorizationOf( + chain: PaymentChain, + payload: Record, + payer: string, + what: string, +): ReturnType["decode"]> { + const watch = chain.authorizations!; + let decoded; + try { + decoded = watch.decode(payload); + } catch (error) { + if (error instanceof CheckSetupError) throw error; + throw new CheckSetupError(`The authorization of ${what} could not be read from its payload (${(error as Error).message}).`); + } + if (decoded.payer !== payer) { + throw new CheckSetupError(`The authorization of ${what} is signed by another address than this run's payer.`); + } + return decoded; +} + +/** A lifetime X402-11 signs for: at least 30 s, and at most the 300 s it waits out. */ +function withinRejectLifetime(value: unknown): boolean { + const lifetime = Number(value); + return lifetime >= REJECTED_REQUEST_MIN_LIFETIME_SECONDS && lifetime <= REJECTED_REQUEST_MAX_LIFETIME_SECONDS; +} + +/** Thrown before signing when the challenge X402-11 is paid from advertises a lifetime it does not sign for. */ +class RejectLifetimeOutside extends Error { + public constructor(public readonly lifetime: unknown) { + super("the advertised lifetime is outside what X402-11 signs for"); + } +} + +/** + * X402-11 (negative, spec B7 as D-032 changed it): a valid payment sent with a + * request the service must refuse must not settle. See `rejected-request.ts` + * for the rules and the verdict. + * + * Nothing is signed when the check could not reach a verdict anyway: no + * reject case, X402-06 not shown settled (its nonce is the control), a chain + * whose authorizations Wasit cannot read, a service that refuses the request + * before asking for payment, an advertised lifetime above 300 s, or a control + * the chain does not return. The payment then goes through `preparePayment` + * like every other: the pin, the plan, the $1 and run caps, the advertised + * terms exactly. + */ +async function checkRejectedRequestNotSettled( + options: X402PaymentCheckOptions, + honest: HonestPayment, +): Promise { + const id = REJECTED_REQUEST_ID; + const name = REJECTED_REQUEST_NAME; + const reject = options.reject; + if (reject === undefined) { + return skipped( + id, + name, + "no request the service must refuse is configured (endpoints[].reject in wasit.config.json, read by " + + "wasit run), so there is nothing to send. Nothing was signed.", + "not-applicable", + ); + } + const chain = chainFor(options.network); + const watch = chain.authorizations; + if (watch === undefined) { + return skipped( + id, + name, + `Wasit cannot read on ${chain.name} whether a payment's authorization was used, which this check needs, ` + + `so nothing was signed.`, + "not-applicable", + ); + } + if (honest.result.pass !== true || honest.result.error !== undefined || honest.result.skipped === true) { + return skipped( + id, + name, + "X402-06's payment was not shown settled on chain, so its authorization cannot be the control that shows a " + + "chain read is complete. Nothing was signed.", + "dependency", + ); + } + + // The reject request is the endpoint's request with the reject case over it. + const { method: _method, headers: _headers, body: _body, ...rest } = options; + const shape = rejectRequestShape(options, reject); + const rejectOptions: X402PaymentCheckOptions = { ...rest, ...shape }; + + // Without payment first: a service that refuses it before asking for payment + // gives this check nothing to watch. + const { response: unpaid } = await fetchPaymentChallenge(options.target, buildInit(shape)); + if (unpaid.status !== 402) { + await unpaid.body?.cancel().catch(() => undefined); + const status = unpaid.status; + return skipped( + id, + name, + status >= 400 && status < 500 + ? `the service refuses this request before any payment is asked (HTTP ${status}), so there is no payment ` + + `to watch. Nothing was signed.` + : `the service answered this request with HTTP ${status} without asking for payment, so there is no ` + + `payment to watch. Nothing was signed.`, + "not-applicable", + ); + } + const { selected: advertised } = await paymentTerms(unpaid, options.network); + const outside = (value: unknown, again: boolean): CheckResult => + skipped( + id, + name, + `the service's payments stay valid for ${sanitizeText(String(value))} seconds (maxTimeoutSeconds)` + + (again ? ", as it said when asked for payment again" : "") + + (Number(value) > REJECTED_REQUEST_MAX_LIFETIME_SECONDS + ? `, longer than the ${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds Wasit waits for one to expire on a ` + + `test network, so this check could not show that the payment never settled.` + : `, shorter than the ${REJECTED_REQUEST_MIN_LIFETIME_SECONDS} seconds this check needs: such a payment can ` + + `expire before a service that settles it has it on chain, so its unused authorization would show nothing.`) + + ` Nothing was signed.`, + ); + if (!withinRejectLifetime(advertised.maxTimeoutSeconds)) return outside(advertised.maxTimeoutSeconds, false); + + const network = options.network; + const rpcUrl = chain.resolveRpcUrl(network, options.rpcUrl); + const payer = chain.payerAddress(options.payerSecretKey); + const control = authorizationOf(chain, honest.payload, payer, "X402-06's payment"); + + // Before signing: the chain must return X402-06's used authorization, and the + // payer's balance must be readable. Otherwise no verdict could be reached, and + // nothing is signed. + let balanceBefore = 0n; + let prepared; + try { + prepared = await preparePayment(rejectOptions, id, undefined, async (selected) => { + // The challenge is read again for the signature, and the service may + // answer it with another lifetime: the one signed is held to 300 s too. + if (!withinRejectLifetime(selected.maxTimeoutSeconds)) throw new RejectLifetimeOutside(selected.maxTimeoutSeconds); + let read; + try { + read = await watch.read(network, rpcUrl, [control]); + } catch (error) { + throw new CheckSetupError(`The chain could not be read before signing (${(error as Error).message}). Nothing was signed.`); + } + if (read.used[0] === undefined) { + throw new CheckSetupError( + "The chain's answer leaves out X402-06's authorization, which was used, so a later read could not show " + + "that this payment's was not. Nothing was signed.", + ); + } + let balance: bigint | undefined; + try { + balance = await chain.payerBalance(network, rpcUrl, payer, advertised.asset); + } catch { + balance = undefined; + } + if (balance === undefined) { + throw new CheckSetupError( + "The payer's balance could not be read, and this check needs it as a second reading. Nothing was signed.", + ); + } + balanceBefore = balance; + }); + } catch (error) { + if (error instanceof RejectLifetimeOutside) return outside(error.lifetime, true); + throw error; + } + const { httpClient, paymentPayload, selected, payUrl } = prepared; + const amount = BigInt(selected.amount); + const ours = authorizationOf(chain, paymentPayload.payload, payer, "this payment"); + if (ours.nonce === control.nonce) { + throw new CheckSetupError("This payment's authorization carries X402-06's nonce, so it could not be told apart. It was not sent."); + } + + // Right before sending: ours unused, the control found. This read's ledger + // starts the range the transfers are read over. + const before = await watch.read(network, rpcUrl, [ours, control]); + if (before.used[1] === undefined) { + throw new CheckSetupError("The chain's answer leaves out X402-06's authorization, so this payment was not sent."); + } + if (before.used[0] !== undefined) { + throw new CheckSetupError("The chain records this payment's authorization as used before it was sent, so it was not sent."); + } + // What the client signed, not what it was asked: an authorization that stays + // valid longer than the 300 s this check waits is not sent (2 units of slack + // for the ledgers that close while it is built). + const longest = Math.ceil(REJECTED_REQUEST_MAX_LIFETIME_SECONDS / watch.unitSeconds) + 2; + if (ours.expiresAt - before.latest > longest) { + throw new CheckSetupError( + `This payment's authorization stays valid until ${watch.unit} ${ours.expiresAt}, ` + + `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}), longer than the ` + + `${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds this check waits. It was signed and discarded; it was not sent.`, + ); + } + // And long enough that a service which settles it could still get it on chain. + if (ours.expiresAt - before.latest < REJECTED_REQUEST_MIN_UNITS_LEFT) { + throw new CheckSetupError( + `This payment's authorization expires at ${watch.unit} ${ours.expiresAt}, ` + + `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}): too soon for an unused ` + + `authorization to show anything. It was signed and discarded; it was not sent.`, + ); + } + + const sentAt = Date.now(); + const response = await fetchTarget(payUrl, withPaymentHeaders(shape, httpClient.encodePaymentSignatureHeader(paymentPayload))); + const status = response.status; + const reason = await refusalReason(response); + options.onProgress?.( + `X402-11: the payment was sent with the request the service must refuse (HTTP ${status}); reading the chain ` + + `once a ${watch.unit} until its authorization expires at ${watch.unit} ${ours.expiresAt}, for at most ` + + `${Math.round(rejectedRequestHardStopMs() / 1000)} s.`, + ); + + let outcome: WatchOutcome = await watchAuthorization({ watch, network, rpcUrl, ours, control, sentAt }); + let balance: { before: bigint; after: bigint } | undefined; + let transfers: { reference: string; ledger: number }[] | undefined; + if (outcome.kind === "used" || outcome.kind === "unused") { + try { + const after = await chain.payerBalance(network, rpcUrl, payer, selected.asset); + if (after === undefined) throw new Error("the payer's balance could not be read after the watch"); + balance = { before: balanceBefore, after }; + const recorded = await watch.transfers(network, rpcUrl, { + asset: selected.asset, + from: payer, + to: selected.payTo, + fromLedger: before.latest + 1, + }); + // Only what the watch covered: from the ledger after the pre-send read to the last ledger + // it read. A later transfer of the same amount (another run with this payer) is not this one. + const lastRead = outcome.latest; + transfers = recorded.transfers + .filter((transfer) => transfer.amount === amount && transfer.ledger <= lastRead) + .map((transfer) => ({ reference: transfer.reference, ledger: transfer.ledger })); + } catch (error) { + outcome = { kind: "unread", why: `the second readings failed: ${sanitizeText((error as Error).message).slice(0, 200)}` }; + balance = undefined; + transfers = undefined; + } + } + + return rejectedRequestVerdict({ + status, + ...(reason === undefined ? {} : { reason }), + amount, + expiresAt: ours.expiresAt, + unit: watch.unit, + watch: outcome, + ...(balance === undefined ? {} : { balance }), + ...(transfers === undefined ? {} : { transfers }), + }); +} + /** The negative checks, in catalogue order, each with how it runs. */ const NEGATIVE_CHECKS: ReadonlyArray< readonly [string, string, (options: X402PaymentCheckOptions, honest: HonestPayment) => Promise] @@ -1108,6 +1523,7 @@ const NEGATIVE_CHECKS: ReadonlyArray< ["X402-08", "Payment Replay Rejected", checkReplayRejected], ["X402-09", "Underpayment Rejected", (options) => checkUnderpaymentRejected(options)], ["X402-10", "Expired Authorization Rejected", (options) => checkExpiredRejected(options)], + [REJECTED_REQUEST_ID, REJECTED_REQUEST_NAME, checkRejectedRequestNotSettled], ]; /** @@ -1127,8 +1543,11 @@ export const X402_PAYMENT_CHECK_IDS: readonly string[] = [ * See docs/CHECKS.md. */ export async function runX402PaymentChecks( - options: X402PaymentCheckOptions, + input: X402PaymentCheckOptions, ): Promise { + // One budget for every signature these checks make: the run's, when the + // caller shares one across endpoints, or this call's own $5. + const options: X402PaymentCheckOptions = { ...input, budget: input.budget ?? new RunBudget() }; try { assertHttpUrl(options.target); buildInit(options); @@ -1141,7 +1560,7 @@ export async function runX402PaymentChecks( // test network passes; stellar:pubnet waits for the mainnet opt-in, which // this version does not have. assertPaymentNetworkAllowed("x402", options.network); - chain.resolveRpcUrl(options.network, options.rpcUrl); + const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl); // A key for another chain, or a malformed one, would otherwise surface // mid-payment as a harness error. Checked here, it is what it is: the // run's configuration. The message never echoes the key. @@ -1154,6 +1573,9 @@ export async function runX402PaymentChecks( `or --payer-key).`, ); } + // The RPC signs and settles nothing itself, but the payment is built and + // its settlement read through it: it must serve the run's network (D-023). + await assertRpcServesNetwork(options.network, rpcUrl); } catch (error) { // A network no adapter pays on is not a failure of the run: Wasit does not // grade it (spec A3). Every payment check is skipped as unsupported, and diff --git a/packages/core/test/fixtures/ci-report/failing-with-baseline.md b/packages/core/test/fixtures/ci-report/failing-with-baseline.md index 9b5f513..ff4e254 100644 --- a/packages/core/test/fixtures/ci-report/failing-with-baseline.md +++ b/packages/core/test/fixtures/ci-report/failing-with-baseline.md @@ -1,13 +1,56 @@ -**Wasit: non-conformant.** 3 graded (1 non-conformant) on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. +**Wasit: ❌ non-conformant.** 3 graded (1 non-conformant) on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. | Endpoint | Protocol | Outcome | Checks | | --- | --- | --- | --- | -| weather | x402 | non-conformant | challenge 4/5, 1 failed | -| summarize | x402 | conformant | challenge 5/5; payment not run: read-only tier | -| fresh | x402 | conformant | challenge 5/5; payment not run: read-only tier | +| weather | x402 | ❌ non-conformant | challenge 4/5, 1 failed | +| summarize | x402 | ✅ conformant | challenge 5/5; payment not run: read-only tier | +| fresh | x402 | ✅ conformant | challenge 5/5; payment not run: read-only tier | + +### ❌ weather · x402 · non-conformant + +| | Check | Result | +| --- | --- | --- | +| ✅ | X402-01 402 Response Status | PASS | +| ✅ | X402-02 Payment Header Present | PASS | +| ✅ | X402-03 Header Payload Decodable | PASS | +| ❌ | X402-04 Required Fields Present | FAIL | +| ✅ | X402-05 Network Identifier Valid | PASS | + +### ✅ summarize · x402 · conformant + +| | Check | Result | +| --- | --- | --- | +| ✅ | X402-01 402 Response Status | PASS | +| ✅ | X402-02 Payment Header Present | PASS | +| ✅ | X402-03 Header Payload Decodable | PASS | +| ✅ | X402-04 Required Fields Present | PASS | +| ✅ | X402-05 Network Identifier Valid | PASS | +| ⚪ | X402-06 Signature Resubmit Accepted | SKIP | +| ⚪ | X402-07 Invalid Signature Rejected | SKIP | +| ⚪ | X402-08 Payment Replay Rejected | SKIP | +| ⚪ | X402-09 Underpayment Rejected | SKIP | +| ⚪ | X402-10 Expired Authorization Rejected | SKIP | +| ⚪ | X402-11 Rejected Request Not Settled | SKIP | + +### ✅ fresh · x402 · conformant + +| | Check | Result | +| --- | --- | --- | +| ✅ | X402-01 402 Response Status | PASS | +| ✅ | X402-02 Payment Header Present | PASS | +| ✅ | X402-03 Header Payload Decodable | PASS | +| ✅ | X402-04 Required Fields Present | PASS | +| ✅ | X402-05 Network Identifier Valid | PASS | +| ⚪ | X402-06 Signature Resubmit Accepted | SKIP | +| ⚪ | X402-07 Invalid Signature Rejected | SKIP | +| ⚪ | X402-08 Payment Replay Rejected | SKIP | +| ⚪ | X402-09 Underpayment Rejected | SKIP | +| ⚪ | X402-10 Expired Authorization Rejected | SKIP | +| ⚪ | X402-11 Rejected Request Not Settled | SKIP | ### Changed since main +Compared with the last green run on main, started 2026-11-15 10:00 UTC. Runs on main that failed after it are counted under Recent failures on main, not here. - New FAIL: weather X402-04 (was PASS on main). - New endpoint: fresh. @@ -22,3 +65,43 @@ ### Recent failures on main - weather X402-04: failed in 1 of the last 3 runs on main + +
Details of each check + +**weather** + +- ✅ X402-01 402 Response Status: ok +- ✅ X402-02 Payment Header Present: ok +- ✅ X402-03 Header Payload Decodable: ok +- ❌ X402-04 Required Fields Present: Missing: payTo, asset. +- ✅ X402-05 Network Identifier Valid: ok + +**summarize** + +- ✅ X402-01 402 Response Status: ok +- ✅ X402-02 Payment Header Present: ok +- ✅ X402-03 Header Payload Decodable: ok +- ✅ X402-04 Required Fields Present: ok +- ✅ X402-05 Network Identifier Valid: ok +- ⚪ X402-06 Signature Resubmit Accepted: Skipped: the read-only tier makes no payment and signs nothing; this check needs a payer key and the payment tier +- ⚪ X402-07 Invalid Signature Rejected: the same reason as above. +- ⚪ X402-08 Payment Replay Rejected: the same reason as above. +- ⚪ X402-09 Underpayment Rejected: the same reason as above. +- ⚪ X402-10 Expired Authorization Rejected: the same reason as above. +- ⚪ X402-11 Rejected Request Not Settled: the same reason as above. + +**fresh** + +- ✅ X402-01 402 Response Status: ok +- ✅ X402-02 Payment Header Present: ok +- ✅ X402-03 Header Payload Decodable: ok +- ✅ X402-04 Required Fields Present: ok +- ✅ X402-05 Network Identifier Valid: ok +- ⚪ X402-06 Signature Resubmit Accepted: Skipped: the read-only tier makes no payment and signs nothing; this check needs a payer key and the payment tier +- ⚪ X402-07 Invalid Signature Rejected: the same reason as above. +- ⚪ X402-08 Payment Replay Rejected: the same reason as above. +- ⚪ X402-09 Underpayment Rejected: the same reason as above. +- ⚪ X402-10 Expired Authorization Rejected: the same reason as above. +- ⚪ X402-11 Rejected Request Not Settled: the same reason as above. + +
diff --git a/packages/core/test/fixtures/ci-report/green-read-only-no-baseline.md b/packages/core/test/fixtures/ci-report/green-read-only-no-baseline.md index cdb50f3..b59e04d 100644 --- a/packages/core/test/fixtures/ci-report/green-read-only-no-baseline.md +++ b/packages/core/test/fixtures/ci-report/green-read-only-no-baseline.md @@ -1,9 +1,43 @@ -**Wasit: conformant.** 1 graded on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. +**Wasit: ✅ conformant.** 1 graded on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. | Endpoint | Protocol | Outcome | Checks | | --- | --- | --- | --- | -| weather | x402 | conformant | challenge 5/5; payment not run: read-only tier | +| weather | x402 | ✅ conformant | challenge 5/5; payment not run: read-only tier | + +### ✅ weather · x402 · conformant + +| | Check | Result | +| --- | --- | --- | +| ✅ | X402-01 402 Response Status | PASS | +| ✅ | X402-02 Payment Header Present | PASS | +| ✅ | X402-03 Header Payload Decodable | PASS | +| ✅ | X402-04 Required Fields Present | PASS | +| ✅ | X402-05 Network Identifier Valid | PASS | +| ⚪ | X402-06 Signature Resubmit Accepted | SKIP | +| ⚪ | X402-07 Invalid Signature Rejected | SKIP | +| ⚪ | X402-08 Payment Replay Rejected | SKIP | +| ⚪ | X402-09 Underpayment Rejected | SKIP | +| ⚪ | X402-10 Expired Authorization Rejected | SKIP | +| ⚪ | X402-11 Rejected Request Not Settled | SKIP | ### Changed since main No baseline on main yet, so nothing is compared. The next run on main creates it. + +
Details of each check + +**weather** + +- ✅ X402-01 402 Response Status: ok +- ✅ X402-02 Payment Header Present: ok +- ✅ X402-03 Header Payload Decodable: ok +- ✅ X402-04 Required Fields Present: ok +- ✅ X402-05 Network Identifier Valid: ok +- ⚪ X402-06 Signature Resubmit Accepted: Skipped: the read-only tier makes no payment and signs nothing; this check needs a payer key and the payment tier +- ⚪ X402-07 Invalid Signature Rejected: the same reason as above. +- ⚪ X402-08 Payment Replay Rejected: the same reason as above. +- ⚪ X402-09 Underpayment Rejected: the same reason as above. +- ⚪ X402-10 Expired Authorization Rejected: the same reason as above. +- ⚪ X402-11 Rejected Request Not Settled: the same reason as above. + +
diff --git a/packages/core/test/fixtures/ci-report/regression-vs-baseline.md b/packages/core/test/fixtures/ci-report/regression-vs-baseline.md index 44764f4..a1b4c51 100644 --- a/packages/core/test/fixtures/ci-report/regression-vs-baseline.md +++ b/packages/core/test/fixtures/ci-report/regression-vs-baseline.md @@ -1,17 +1,82 @@ -**Wasit: regression.** 1 graded, 1 unsupported on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. +**Wasit: ❌ regression.** 1 graded, 1 unsupported on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. | Endpoint | Protocol | Outcome | Checks | | --- | --- | --- | --- | -| weather | x402 | conformant | challenge 5/5; payment not run: read-only tier | -| summarize | x402 | unsupported | challenge 1/5, 4 skipped; payment not run: read-only tier | +| weather | x402 | ✅ conformant | challenge 5/5; payment not run: read-only tier | +| summarize | x402 | ⚪ unsupported | challenge 1/5, 4 skipped; payment not run: read-only tier | + +### ✅ weather · x402 · conformant + +| | Check | Result | +| --- | --- | --- | +| ✅ | X402-01 402 Response Status | PASS | +| ✅ | X402-02 Payment Header Present | PASS | +| ✅ | X402-03 Header Payload Decodable | PASS | +| ✅ | X402-04 Required Fields Present | PASS | +| ✅ | X402-05 Network Identifier Valid | PASS | +| ⚪ | X402-06 Signature Resubmit Accepted | SKIP | +| ⚪ | X402-07 Invalid Signature Rejected | SKIP | +| ⚪ | X402-08 Payment Replay Rejected | SKIP | +| ⚪ | X402-09 Underpayment Rejected | SKIP | +| ⚪ | X402-10 Expired Authorization Rejected | SKIP | +| ⚪ | X402-11 Rejected Request Not Settled | SKIP | + +### ⚪ summarize · x402 · unsupported + +| | Check | Result | +| --- | --- | --- | +| ✅ | X402-01 402 Response Status | PASS | +| ⚪ | X402-02 X402-02 | SKIP | +| ⚪ | X402-03 X402-03 | SKIP | +| ⚪ | X402-04 X402-04 | SKIP | +| ⚪ | X402-05 X402-05 | SKIP | +| ⚪ | X402-06 Signature Resubmit Accepted | SKIP | +| ⚪ | X402-07 Invalid Signature Rejected | SKIP | +| ⚪ | X402-08 Payment Replay Rejected | SKIP | +| ⚪ | X402-09 Underpayment Rejected | SKIP | +| ⚪ | X402-10 Expired Authorization Rejected | SKIP | +| ⚪ | X402-11 Rejected Request Not Settled | SKIP | ### Not graded - **summarize**: unsupported. The service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. ### Changed since main +Compared with the last green run on main, started 2026-11-15 10:00 UTC. Runs on main that failed after it are counted under Recent failures on main, not here. - Regression: summarize was conformant on main and is now unsupported. - summarize X402-02: PASS on main, now SKIP. - summarize X402-03: PASS on main, now SKIP. - summarize X402-04: PASS on main, now SKIP. - summarize X402-05: PASS on main, now SKIP. + +
Details of each check + +**weather** + +- ✅ X402-01 402 Response Status: ok +- ✅ X402-02 Payment Header Present: ok +- ✅ X402-03 Header Payload Decodable: ok +- ✅ X402-04 Required Fields Present: ok +- ✅ X402-05 Network Identifier Valid: ok +- ⚪ X402-06 Signature Resubmit Accepted: Skipped: the read-only tier makes no payment and signs nothing; this check needs a payer key and the payment tier +- ⚪ X402-07 Invalid Signature Rejected: the same reason as above. +- ⚪ X402-08 Payment Replay Rejected: the same reason as above. +- ⚪ X402-09 Underpayment Rejected: the same reason as above. +- ⚪ X402-10 Expired Authorization Rejected: the same reason as above. +- ⚪ X402-11 Rejected Request Not Settled: the same reason as above. + +**summarize** + +- ✅ X402-01 402 Response Status: ok +- ⚪ X402-02 X402-02: Skipped: the service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. +- ⚪ X402-03 X402-03: the same reason as above. +- ⚪ X402-04 X402-04: the same reason as above. +- ⚪ X402-05 X402-05: the same reason as above. +- ⚪ X402-06 Signature Resubmit Accepted: Skipped: the read-only tier makes no payment and signs nothing; this check needs a payer key and the payment tier +- ⚪ X402-07 Invalid Signature Rejected: the same reason as above. +- ⚪ X402-08 Payment Replay Rejected: the same reason as above. +- ⚪ X402-09 Underpayment Rejected: the same reason as above. +- ⚪ X402-10 Expired Authorization Rejected: the same reason as above. +- ⚪ X402-11 Rejected Request Not Settled: the same reason as above. + +
diff --git a/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md b/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md index 91771da..346f651 100644 --- a/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md +++ b/packages/core/test/fixtures/ci-report/v1-only-no-baseline.md @@ -1,9 +1,25 @@ -**Wasit: nothing graded.** 0 graded, 1 unsupported on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. +**Wasit: ⚪ nothing graded.** 0 graded, 1 unsupported on local, stellar:testnet. Wasit 0.7.0 (core 0.7.0), x402 v2, @x402/core 2.28.0, @x402/stellar 2.28.0, @stellar/mpp 0.7.1, mppx 0.8.14, @stellar/stellar-sdk 16.1.0. | Endpoint | Protocol | Outcome | Checks | | --- | --- | --- | --- | -| old | x402 | unsupported | challenge 1/5, 4 skipped; payment not run: read-only tier | +| old | x402 | ⚪ unsupported | challenge 1/5, 4 skipped; payment not run: read-only tier | + +### ⚪ old · x402 · unsupported + +| | Check | Result | +| --- | --- | --- | +| ✅ | X402-01 402 Response Status | PASS | +| ⚪ | X402-02 X402-02 | SKIP | +| ⚪ | X402-03 X402-03 | SKIP | +| ⚪ | X402-04 X402-04 | SKIP | +| ⚪ | X402-05 X402-05 | SKIP | +| ⚪ | X402-06 Signature Resubmit Accepted | SKIP | +| ⚪ | X402-07 Invalid Signature Rejected | SKIP | +| ⚪ | X402-08 Payment Replay Rejected | SKIP | +| ⚪ | X402-09 Underpayment Rejected | SKIP | +| ⚪ | X402-10 Expired Authorization Rejected | SKIP | +| ⚪ | X402-11 Rejected Request Not Settled | SKIP | ### Not graded - **old**: unsupported. The service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. @@ -13,3 +29,21 @@ No baseline on main yet, so nothing is compared. The next run on main creates it ### Notes - Tier: read-only. Payment checks were not run. + +
Details of each check + +**old** + +- ✅ X402-01 402 Response Status: ok +- ⚪ X402-02 X402-02: Skipped: the service sent an x402 v1 challenge in its response body. To have it graded, move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header. +- ⚪ X402-03 X402-03: the same reason as above. +- ⚪ X402-04 X402-04: the same reason as above. +- ⚪ X402-05 X402-05: the same reason as above. +- ⚪ X402-06 Signature Resubmit Accepted: Skipped: the read-only tier makes no payment and signs nothing; this check needs a payer key and the payment tier +- ⚪ X402-07 Invalid Signature Rejected: the same reason as above. +- ⚪ X402-08 Payment Replay Rejected: the same reason as above. +- ⚪ X402-09 Underpayment Rejected: the same reason as above. +- ⚪ X402-10 Expired Authorization Rejected: the same reason as above. +- ⚪ X402-11 Rejected Request Not Settled: the same reason as above. + +
diff --git a/packages/core/test/fixtures/x402-reject-server.ts b/packages/core/test/fixtures/x402-reject-server.ts new file mode 100644 index 0000000..2a01b63 --- /dev/null +++ b/packages/core/test/fixtures/x402-reject-server.ts @@ -0,0 +1,71 @@ +/** + * X402-11's fixture on the Stellar test network (spec B7): three routes, each a + * conformant x402 paywall for a valid request, which differ only in what they + * do with a paid request that carries the `x-wasit-invalid` header, the request + * the config declares invalid. + * + * - /refuses: answers 400. The official middleware does not settle a response + * of 400 or above, so the payment is never taken. X402-11 passes. + * - /settles-then-refuses: settles the payment through the facilitator itself, + * then answers 400. X402-11 fails: the request was refused and the payment taken. + * - /serves: serves it with 200, and the middleware settles. X402-11 fails. + * + * The lifetime is 60 s, shorter than the x402 default of 300 s, so the passing + * route reaches its verdict in about a minute. Test funds only: the public + * testnet facilitator, as `x402-real-server.ts` uses. + */ + +import "dotenv/config"; +import express from "express"; +import { paymentMiddlewareFromConfig } from "@x402/express"; +import { HTTPFacilitatorClient } from "@x402/core/server"; +import { decodePaymentSignatureHeader } from "@x402/core/http"; +import { ExactStellarScheme } from "@x402/stellar/exact/server"; + +const PORT = 3009; +const PRICE = "$0.01"; +const NETWORK = "stellar:testnet"; +const FACILITATOR_URL = "https://www.x402.org/facilitator"; +const MAX_TIMEOUT_SECONDS = 60; +const PAY_TO = process.env.STELLAR_PAYEE_ADDRESS; +if (!PAY_TO) throw new Error("STELLAR_PAYEE_ADDRESS is not set in .env"); + +const facilitator = new HTTPFacilitatorClient({ url: FACILITATOR_URL }); +const accepts = { scheme: "exact", price: PRICE, network: NETWORK, payTo: PAY_TO, maxTimeoutSeconds: MAX_TIMEOUT_SECONDS } as const; +const ROUTES = ["/refuses", "/settles-then-refuses", "/serves"]; + +const app = express(); + +app.use( + paymentMiddlewareFromConfig( + Object.fromEntries(ROUTES.map((route) => [`GET ${route}`, { accepts }])), + facilitator, + [{ network: NETWORK, server: new ExactStellarScheme() }], + ), +); + +const invalid = (request: express.Request): boolean => request.get("x-wasit-invalid") !== undefined; + +app.get("/refuses", (request, response) => { + if (invalid(request)) return response.status(400).json({ error: "invalid request" }); + return response.json({ resource: "wasit test resource" }); +}); + +app.get("/settles-then-refuses", async (request, response) => { + if (!invalid(request)) return response.json({ resource: "wasit test resource" }); + // The defect X402-11 exists to find: the payment is taken before the request is judged. + const header = request.get("payment-signature") ?? request.get("x-payment") ?? ""; + try { + const payload = decodePaymentSignatureHeader(header); + await facilitator.settle(payload, payload.accepted); + } catch (error) { + console.error("settle failed:", (error as Error).message); + } + return response.status(400).json({ error: "invalid request" }); +}); + +app.get("/serves", (_request, response) => response.json({ resource: "wasit test resource" })); + +app.listen(PORT, () => { + console.log(`X402-11 fixture on http://localhost:${PORT}: ${ROUTES.join(", ")} (invalid = header x-wasit-invalid)`); +}); diff --git a/packages/core/test/support/authorization-ledger.ts b/packages/core/test/support/authorization-ledger.ts new file mode 100644 index 0000000..1dc784a --- /dev/null +++ b/packages/core/test/support/authorization-ledger.ts @@ -0,0 +1,302 @@ +/** + * Tests only: X402-11's stand-ins (spec B7, D-032). + * + * A ledger that holds what a chain would record (used nonces, transfers, the + * payer's balance) and advances one ledger on every read; a recording chain + * whose payloads carry a nonce and an expiration ledger, with an + * `authorizations` watch that reads that ledger; and a paywall with the three + * modes of B7 for a request the config declares invalid: it refuses without + * settling, it settles and then refuses, or it serves it. + * + * The paywall settles a valid payment the way a facilitator would: only when + * the signature is good, the amount is the price, the lifetime is not the + * one-second one of X402-10 and the nonce was not used before. So X402-06 + * passes and X402-07 to X402-10 are refused, as on a conformant service. + */ + +import http from "node:http"; + +import type { PaymentRequirements } from "@x402/core/types"; + +import type { AuthorizationWatch, PaymentChain, RecordedTransfer } from "../../src/x402/chains/types.js"; +import { NETWORK, PAYER, USDC, recordingChain, type Recorder } from "./recording-chain.js"; + +export interface LedgerTransfer extends RecordedTransfer { + readonly asset: string; + readonly from: string; + readonly to: string; +} + +export interface FakeLedger { + /** The latest closed ledger. Each read of the watch closes one more. */ + latest: number; + /** nonce -> the ledger its use was recorded in. */ + readonly used: Map; + readonly transfers: LedgerTransfer[]; + balance: bigint; + /** Reads of `read`, for "read before signing" assertions. */ + reads: number; + /** Nonces the chain will not return (an RPC that answers without them). */ + readonly hidden: Set; + /** When set, `read` throws this. */ + readError?: Error; + /** When set, `transfers` throws this. */ + transferError?: Error; + /** When set, the payer's balance cannot be read. */ + balanceUnreadable?: boolean; + /** Ledgers each read moves on by. Default 1. */ + step: number; + /** A settlement marks the nonce used and lowers the balance, but records no transfer event. */ + dropTransfers?: boolean; + /** Called on every read of the watch, with how many there have been. */ + onRead?: (reads: number) => void; +} + +export function fakeLedger(start = 1000): FakeLedger { + return { latest: start, used: new Map(), transfers: [], balance: 10_000_000n, reads: 0, hidden: new Set(), step: 1 }; +} + +/** What the recording chain's payload holds: enough for the paywall to judge it, and for the watch. */ +export interface FakePayload { + readonly signature: string; + readonly nonce: string; + readonly expiresAt: number; + readonly payer: string; + readonly amount: string; + readonly maxTimeoutSeconds: number; +} + +/** Records a use of `payload`'s nonce at the next ledger, and the transfer it makes. */ +export function settle(ledger: FakeLedger, payload: FakePayload, payTo: string): string { + const at = ledger.latest + 1; + const reference = `tx-${payload.nonce}`; + ledger.used.set(payload.nonce, at); + if (ledger.dropTransfers !== true) ledger.transfers.push({ amount: BigInt(payload.amount), reference, ledger: at, asset: USDC, from: payload.payer, to: payTo }); + ledger.balance -= BigInt(payload.amount); + return reference; +} + +export function watchOf(ledger: FakeLedger): AuthorizationWatch { + return { + unit: "ledger", + unitMs: 1, + unitSeconds: 5, + decode(payload) { + const nonce = payload["nonce"]; + const expiresAt = payload["expiresAt"]; + const payer = payload["payer"]; + if (typeof nonce !== "string" || typeof expiresAt !== "number" || typeof payer !== "string") { + throw new Error("the stand-in payload carries no authorization"); + } + return { nonce, expiresAt, payer }; + }, + async read(_network, _rpcUrl, authorizations) { + ledger.reads += 1; + ledger.onRead?.(ledger.reads); + if (ledger.readError !== undefined) throw ledger.readError; + ledger.latest += ledger.step; + return { + latest: ledger.latest, + used: authorizations.map((item) => (ledger.hidden.has(item.nonce) ? undefined : ledger.used.get(item.nonce))), + }; + }, + async transfers(_network, _rpcUrl, query) { + if (ledger.transferError !== undefined) throw ledger.transferError; + return { + latest: ledger.latest, + transfers: ledger.transfers.filter( + (item) => item.asset === query.asset && item.from === query.from && item.to === query.to && item.ledger >= query.fromLedger, + ), + }; + }, + }; +} + +export interface LedgerChainOptions { + /** Leave the watch out: a chain X402-11 cannot read. */ + readonly withoutWatch?: boolean; + /** X402-06's settlement does not hold up on chain: X402-06 fails. */ + readonly settlementFails?: boolean; + /** Ledgers added to every expiration the client signs: a client that signs longer than it was asked. */ + readonly extraExpiryLedgers?: number; + /** Fields over the payload of the `count`th signature (1 = X402-06's). */ + readonly alterPayload?: (count: number) => Partial | undefined; +} + +/** The recording chain, with payloads that carry a nonce and an expiration, and a watch on `ledger`. */ +export function ledgerChain(recorder: Recorder, ledger: FakeLedger, options: LedgerChainOptions = {}): PaymentChain { + const base = recordingChain(recorder); + let count = 0; + return { + ...base, + registerPayer(client) { + client.register(NETWORK, { + scheme: "exact", + findDefaultAsset: (asset, network) => + network === NETWORK && asset.toLowerCase() === USDC.toLowerCase() ? { asset: USDC, decimals: 6, symbol: "USDC" } : undefined, + async createPaymentPayload(version, requirements) { + recorder.signed.push(requirements); + count += 1; + // As the Stellar client does: the expiration ledger from maxTimeoutSeconds, 5 s a ledger. + const payload: FakePayload = { + signature: `sig-${count}`, + nonce: `nonce-${count}`, + expiresAt: ledger.latest + Math.ceil(requirements.maxTimeoutSeconds / 5) + (options.extraExpiryLedgers ?? 0), + payer: PAYER, + amount: requirements.amount, + maxTimeoutSeconds: requirements.maxTimeoutSeconds, + ...(options.alterPayload?.(count) ?? {}), + }; + return { x402Version: version, payload: { ...payload } }; + }, + }); + }, + payerBalance: async () => (ledger.balanceUnreadable === true ? undefined : ledger.balance), + ...(options.settlementFails === true + ? { verifySettlement: async () => ({ pass: false, detail: "the stand-in chain holds no such transfer" }) } + : {}), + corruptPayload: (payload) => ({ ...payload, signature: "corrupted" }), + ...(options.withoutWatch === true ? {} : { authorizations: watchOf(ledger) }), + }; +} + +/** What the paywall does with a paid request the config declares invalid. */ +export type InvalidMode = "refuse" | "settle-then-refuse" | "serve"; + +export interface RejectPaywallOptions { + readonly mode: InvalidMode; + /** The header that marks the invalid request. Default `x-invalid`. */ + readonly marker?: string; + /** Refuse the invalid request with 400 before asking for payment. */ + readonly refuseUnpaidInvalid?: boolean; + /** Answer the paid invalid request with this status instead of 400 (refusing modes). */ + readonly refusalStatus?: number; + /** + * The `maxTimeoutSeconds` of each unpaid invalid request in turn (the last + * one repeats): a service that changes the lifetime between two reads. + */ + readonly invalidUnpaidLifetimes?: readonly number[]; +} + +export interface RejectPaywall { + readonly url: string; + accepts: PaymentRequirements[]; + /** Paid invalid requests received, with what they carried. */ + readonly invalid: { method: string; headers: http.IncomingHttpHeaders; body: string }[]; + close(): Promise; +} + +function decodePayment(header: string): { payload: FakePayload; accepted?: PaymentRequirements } | undefined { + try { + return JSON.parse(Buffer.from(header, "base64").toString("utf-8")) as { payload: FakePayload }; + } catch { + return undefined; + } +} + +export async function rejectPaywall( + ledger: FakeLedger, + accepts: PaymentRequirements[], + options: RejectPaywallOptions, +): Promise { + const marker = options.marker ?? "x-invalid"; + const state = { accepts }; + const invalid: RejectPaywall["invalid"] = []; + let invalidUnpaidReads = 0; + + const challenge = (response: http.ServerResponse, error?: string): void => { + const body = { x402Version: 2, resource: { url: "http://127.0.0.1/paid" }, accepts: state.accepts, ...(error === undefined ? {} : { error }) }; + response.writeHead(402, { + "content-type": "application/json", + "payment-required": Buffer.from(JSON.stringify(body)).toString("base64"), + }); + response.end("{}"); + }; + + const server = http.createServer((request, response) => { + let body = ""; + request.on("data", (chunk: Buffer) => (body += chunk.toString("utf-8"))); + request.on("end", () => { + const isInvalid = request.headers[marker] !== undefined; + const header = request.headers["payment-signature"]; + if (typeof header !== "string") { + if (isInvalid && options.refuseUnpaidInvalid === true) { + response.writeHead(400, { "content-type": "application/json" }); + response.end(JSON.stringify({ error: "invalid request" })); + return; + } + const lifetimes = options.invalidUnpaidLifetimes; + if (isInvalid && lifetimes !== undefined && lifetimes.length > 0) { + const lifetime = lifetimes[Math.min(invalidUnpaidReads, lifetimes.length - 1)]!; + invalidUnpaidReads += 1; + const saved = state.accepts; + state.accepts = saved.map((requirement) => ({ ...requirement, maxTimeoutSeconds: lifetime })); + challenge(response); + state.accepts = saved; + return; + } + challenge(response); + return; + } + const decoded = decodePayment(header); + const payload = decoded?.payload; + const price = state.accepts[0]?.amount; + const payTo = state.accepts[0]?.payTo ?? ""; + const valid = + payload !== undefined && + payload.signature !== "corrupted" && + payload.amount === price && + payload.maxTimeoutSeconds !== 1 && + !ledger.used.has(payload.nonce); + + if (isInvalid) { + invalid.push({ method: request.method ?? "", headers: request.headers, body }); + if (!valid) return challenge(response, "invalid_payment"); + if (options.mode === "refuse") { + response.writeHead(options.refusalStatus ?? 400, { "content-type": "application/json" }); + response.end(JSON.stringify({ error: "invalid request" })); + return; + } + const reference = settle(ledger, payload, payTo); + const settled = { success: true, transaction: reference, network: NETWORK, payer: PAYER }; + if (options.mode === "settle-then-refuse") { + response.writeHead(options.refusalStatus ?? 400, { "content-type": "application/json" }); + response.end(JSON.stringify({ error: "invalid request" })); + return; + } + response.writeHead(200, { + "content-type": "application/json", + "payment-response": Buffer.from(JSON.stringify(settled)).toString("base64"), + }); + response.end("{}"); + return; + } + + if (!valid) return challenge(response, "invalid_payment"); + const reference = settle(ledger, payload, payTo); + const settled = { success: true, transaction: reference, network: NETWORK, payer: PAYER }; + response.writeHead(200, { + "content-type": "application/json", + "payment-response": Buffer.from(JSON.stringify(settled)).toString("base64"), + }); + response.end("{}"); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as { port: number }).port; + return { + url: `http://127.0.0.1:${port}/paid`, + get accepts() { + return state.accepts; + }, + set accepts(next: PaymentRequirements[]) { + state.accepts = next; + }, + invalid, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} diff --git a/packages/core/test/support/recording-chain.ts b/packages/core/test/support/recording-chain.ts new file mode 100644 index 0000000..f431842 --- /dev/null +++ b/packages/core/test/support/recording-chain.ts @@ -0,0 +1,177 @@ +/** + * Tests only: a payment chain that records every signature and holds nothing, + * and a paywall on loopback that settles everything it is sent (spec B11: "a + * recording signer and a facilitator that settles everything signed"). + * + * The chain stands in for Base Sepolia's adapter through + * `setPaymentChainsForTesting`, so the guard, the budget and the SDK client + * run as they do in a real run; only the signing and the chain reads are + * replaced. The RPC identity check answers through its own test seam. + */ + +import http from "node:http"; + +import type { PaymentRequirements } from "@x402/core/types"; + +import { setRpcIdentityTransportForTesting } from "../../src/guard/rpc-identity.js"; +import { setPaymentChainsForTesting } from "../../src/x402/chains/index.js"; +import type { PaymentChain } from "../../src/x402/chains/types.js"; + +export const NETWORK = "eip155:84532"; +/** Base Sepolia USDC, 6 decimals: $1 is 1,000,000 base units. */ +export const USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; +export const PAY_TO = "0x209693Bc6afc0C5328bA36FaF03C514EF312287C"; +export const OTHER_PAY_TO = "0x1111111111111111111111111111111111111111"; +export const PAYER = "0x2222222222222222222222222222222222222222"; + +export interface Recorder { + /** Every option the scheme was asked to sign, in order. */ + readonly signed: PaymentRequirements[]; +} + +export interface RecordingChainOptions { + /** A policy the "SDK" applies after Wasit's: it signs for another payee (B-A02). */ + readonly swapPayTo?: string; + /** What `expiredSigning` gives as X402-10's terms: an adapter that changes more than the lifetime. */ + readonly expiredTerms?: Partial; +} + +export function recordingChain(recorder: Recorder, options: RecordingChainOptions = {}): PaymentChain { + return { + name: "Recording", + networks: [NETWORK], + payerKeyEnv: "TEST_PAYER_KEY", + referenceKind: "a test reference", + resolveRpcUrl: (_network, override) => override || "http://127.0.0.1:9/rpc", + registerPayer(client) { + client.register(NETWORK, { + scheme: "exact", + // As the real EVM scheme does: the SDK's own $1 cap applies to USDC. + findDefaultAsset: (asset, network) => + network === NETWORK && asset.toLowerCase() === USDC.toLowerCase() + ? { asset: USDC, decimals: 6, symbol: "USDC" } + : undefined, + async createPaymentPayload(version, requirements) { + recorder.signed.push(requirements); + return { x402Version: version, payload: { signature: `sig-${recorder.signed.length}` } }; + }, + }); + const swap = options.swapPayTo; + if (swap !== undefined) { + client.registerPolicy((_version, requirements) => + requirements.map((requirement) => ({ ...requirement, payTo: swap })), + ); + } + }, + expiredSigning: async () => ({ terms: options.expiredTerms ?? { maxTimeoutSeconds: 1 }, holdMs: 0 }), + payerAddress: () => PAYER, + generatePayerKey: () => "test-payer-key", + payerBalance: async () => 10n ** 30n, + isSettlementReference: (reference) => reference.startsWith("tx-"), + verifySettlement: async () => ({ pass: true, detail: "settled (recording chain)" }), + corruptPayload: (payload) => ({ ...payload, signature: "corrupted" }), + }; +} + +/** Installs the recording chain and an RPC that serves Base Sepolia. Returns the undo. */ +export function installRecordingChain(recorder: Recorder, options: RecordingChainOptions = {}): () => void { + setPaymentChainsForTesting([recordingChain(recorder, options)]); + setRpcIdentityTransportForTesting(async (_url, method) => (method === "eth_chainId" ? "0x14a34" : undefined)); + return () => { + setPaymentChainsForTesting(undefined); + setRpcIdentityTransportForTesting(undefined); + }; +} + +export interface ChallengeOption { + readonly amount: string; + readonly payTo?: string; + readonly asset?: string; + readonly network?: string; + readonly scheme?: string; + readonly extra?: Record; +} + +export function option(spec: ChallengeOption): PaymentRequirements { + return { + scheme: spec.scheme ?? "exact", + network: (spec.network ?? NETWORK) as PaymentRequirements["network"], + amount: spec.amount, + asset: spec.asset ?? USDC, + payTo: spec.payTo ?? PAY_TO, + maxTimeoutSeconds: 60, + extra: spec.extra ?? { name: "USDC", version: "2" }, + }; +} + +export interface Paywall { + readonly url: string; + /** What the next unpaid request is answered with. */ + accepts: PaymentRequirements[]; + /** Paid requests received. */ + readonly paid: number; + /** Called on every unpaid request, before it is answered: lets a test change the terms mid-run. */ + onChallenge?: (count: number) => void; + close(): Promise; +} + +/** A paywall that answers 402 with `accepts`, and settles every paid request it gets. */ +export async function paywall(accepts: PaymentRequirements[], path = "/paid"): Promise { + let paid = 0; + let challenges = 0; + const state: { accepts: PaymentRequirements[]; onChallenge?: (count: number) => void } = { accepts }; + const server = http.createServer((request, response) => { + request.on("data", () => undefined); + request.on("end", () => { + if (typeof request.headers["payment-signature"] === "string") { + paid += 1; + const settled = { success: true, transaction: `tx-${paid}`, network: NETWORK, payer: PAYER }; + response.writeHead(200, { + "content-type": "application/json", + "payment-response": Buffer.from(JSON.stringify(settled)).toString("base64"), + }); + response.end("{}"); + return; + } + challenges += 1; + state.onChallenge?.(challenges); + const challenge = { x402Version: 2, resource: { url: `http://127.0.0.1${path}` }, accepts: state.accepts }; + response.writeHead(402, { + "content-type": "application/json", + "payment-required": Buffer.from(JSON.stringify(challenge)).toString("base64"), + }); + response.end("{}"); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as { port: number }).port; + return { + url: `http://127.0.0.1:${port}${path}`, + get accepts() { + return state.accepts; + }, + set accepts(next: PaymentRequirements[]) { + state.accepts = next; + }, + get paid() { + return paid; + }, + get onChallenge() { + return state.onChallenge; + }, + set onChallenge(next: ((count: number) => void) | undefined) { + if (next === undefined) delete state.onChallenge; + else state.onChallenge = next; + }, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +/** Sum of what was signed, in base units. */ +export function signedTotal(recorder: Recorder): bigint { + return recorder.signed.reduce((sum, requirement) => sum + BigInt(requirement.amount), 0n); +} diff --git a/packages/core/test/unit/baseline.test.ts b/packages/core/test/unit/baseline.test.ts index 2ecf5ae..6d6dd40 100644 --- a/packages/core/test/unit/baseline.test.ts +++ b/packages/core/test/unit/baseline.test.ts @@ -323,6 +323,46 @@ describe("diffReports", () => { assert.deepEqual(diffReports(now, report([endpoint("weather", conformant())])), []); }); + // main runs the payment tier, a pull request the read-only one (D-022a): a check + // the tier did not run says nothing about the service, in either direction. + const PAYMENT = ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]; + const paid = (): CheckResult[] => [...CHALLENGE.map(pass), ...PAYMENT.map(pass)]; + const tierSkip = (reason: string, kind: "read-only" | "needs-payer"): CheckResult[] => + [...CHALLENGE.map(pass), ...PAYMENT.map((id) => skipped(id, id, reason, kind))]; + + it("shows no change for payment checks a pull request did not run, against a main that paid", () => { + const main = report([endpoint("weather", paid())]); + for (const now of [ + report([endpoint("weather", conformant())]), + report([endpoint("weather", tierSkip("payment checks not run: pull request", "read-only"))]), + report([endpoint("weather", tierSkip("no payer key", "needs-payer"))]), + ]) { + assert.deepEqual(diffReports(now, main), []); + assert.equal(runExitCode(now, main).code, 0); + } + }); + + it("does not show a FAIL on main as fixed by a pull request that did not run that check", () => { + const main = report([endpoint("weather", [...CHALLENGE.map(pass), pass("X402-06"), fail("X402-07"), ...["X402-08", "X402-09", "X402-10"].map(pass)])]); + const now = report([endpoint("weather", conformant())]); + assert.deepEqual(diffReports(now, main), []); + }); + + it("still shows a payment check that changed between two runs that both ran it", () => { + const main = report([endpoint("weather", paid())]); + const now = report([endpoint("weather", [...CHALLENGE.map(pass), pass("X402-06"), fail("X402-07"), ...["X402-08", "X402-09", "X402-10"].map(pass)])]); + assert.deepEqual( + diffReports(now, main).filter((change) => change.check === "X402-07").map((change) => change.kind), + ["new-failure"], + ); + }); + + it("shows no change when main did not run a check that the run now passes", () => { + const main = report([endpoint("weather", conformant())]); + const now = report([endpoint("weather", paid())]); + assert.deepEqual(diffReports(now, main), []); + }); + it("names a new FAIL with the check and what it was", () => { const before = report([endpoint("weather", conformant())]); const now = report([endpoint("weather", [pass("X402-01"), fail("X402-02")])]); diff --git a/packages/core/test/unit/charge-network.test.ts b/packages/core/test/unit/charge-network.test.ts index 4732d92..1d9585f 100644 --- a/packages/core/test/unit/charge-network.test.ts +++ b/packages/core/test/unit/charge-network.test.ts @@ -13,13 +13,14 @@ import assert from "node:assert/strict"; import http from "node:http"; import net from "node:net"; -import { describe, it } from "node:test"; +import { afterEach, beforeEach, describe, it } from "node:test"; -import { Keypair } from "@stellar/stellar-sdk"; +import { Keypair, Networks } from "@stellar/stellar-sdk"; import { charge as chargeClient } from "@stellar/mpp/charge/client"; import { Mppx, Store, charge } from "@stellar/mpp/charge/server"; import { classifyCheckError } from "../../src/errors.js"; +import { setRpcIdentityTransportForTesting } from "../../src/guard/rpc-identity.js"; import { payCharge, runMppChargeChecks } from "../../src/mpp/charge.js"; import type { MppNetwork } from "../../src/mpp/network.js"; @@ -108,6 +109,13 @@ async function rejection(promise: Promise): Promise { } describe("MPP-01 and the challenge's network", () => { + // The run's RPC here is an https address nothing can answer (see + // countingRpc), so the RPC identity check (D-023, rpc-identity.test.ts) is + // given a stand-in that says testnet. The connections countingRpc sees are + // then the SDK's own, which is what these tests are about. + beforeEach(() => setRpcIdentityTransportForTesting(async () => ({ passphrase: Networks.TESTNET }))); + afterEach(() => setRpcIdentityTransportForTesting(undefined)); + // A stellar:pubnet run no longer reaches the challenge at all: L0 refuses it // first (network-guard.test.ts). The run-network rule below still guards a // testnet run against a challenge that asks for pubnet. diff --git a/packages/core/test/unit/ci-report.test.ts b/packages/core/test/unit/ci-report.test.ts index aa8f5be..269c4bd 100644 --- a/packages/core/test/unit/ci-report.test.ts +++ b/packages/core/test/unit/ci-report.test.ts @@ -16,8 +16,16 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { describe, it } from "node:test"; -import { type Baseline, updateHistory } from "../../src/baseline.js"; -import { COMMENT_MARKER, renderComment, renderNoReportComment, renderSummary } from "../../src/ci-report.js"; +import { type Baseline, parseRunReport, updateHistory } from "../../src/baseline.js"; +import { + COMMENT_MARKER, + renderCheckRun, + renderComment, + renderNoReportCheckRun, + renderNoReportComment, + renderRunningComment, + renderSummary, +} from "../../src/ci-report.js"; import { catalogueEntry } from "../../src/catalogue.js"; import { type CheckResult, errored, skipped } from "../../src/check.js"; import { ConfigurationError } from "../../src/errors.js"; @@ -122,7 +130,7 @@ describe("the shape of a comment", () => { const [first, second] = lines(comment); assert.equal(COMMENT_MARKER, ""); assert.equal(first, COMMENT_MARKER); - assert.match(second ?? "", /Wasit: conformant/); + assert.match(second ?? "", /Wasit: ✅ conformant/); assert.match(second ?? "", /Wasit 0\.7\.0/); assert.match(second ?? "", /x402 v2/); assert.match(second ?? "", /@x402\/core 2\.28\.0/); @@ -140,10 +148,10 @@ describe("the shape of a comment", () => { const comment = renderComment({ report: report([endpoint("old", v1())], { notes: ["Tier: read-only. Payment checks were not run."] }), }); - assert.match(comment, /Wasit: nothing graded/); + assert.match(comment, /Wasit: ⚪ nothing graded/); assert.match(comment, /0 graded, 1 unsupported/); assert.match(comment, /unsupported/); - assert.ok(!/Wasit: conformant/.test(comment)); + assert.ok(!/Wasit: ✅ conformant/.test(comment)); assert.match(comment, /PAYMENT-REQUIRED response header/, "the way to get graded is not cut off"); assert.match(comment, /Tier: read-only/); expectSnapshot("v1-only-no-baseline.md", comment); @@ -154,7 +162,7 @@ describe("the shape of a comment", () => { endpoint("weather", [pass("X402-01"), pass("X402-02"), pass("X402-03"), fail("X402-04", "Option 0 is missing payTo, asset.", undefined, { expected: "payTo, asset present", actual: "payTo, asset missing" }), pass("X402-05")]), ]); const comment = renderComment({ report: now }); - assert.match(comment, /Wasit: non-conformant/); + assert.match(comment, /Wasit: ❌ non-conformant/); assert.match(comment, /Option 0 is missing payTo, asset\./); assert.match(comment, /Send the challenge in the PAYMENT-REQUIRED header\./); assert.match(comment, /https:\/\/usewasit\.dev\/docs\/checks\/x402/); @@ -231,7 +239,7 @@ describe("the shape of a comment", () => { const main = report([endpoint("weather", conformant()), endpoint("summarize", conformant())]); const now = report([endpoint("weather", conformant()), endpoint("summarize", v1())]); const comment = renderComment({ report: now, baseline: baselineOf([main]) }); - assert.match(comment, /Wasit: regression/); + assert.match(comment, /Wasit: ❌ regression/); assert.match(comment, /Regression: summarize was conformant on main and is now unsupported/); expectSnapshot("regression-vs-baseline.md", comment); }); @@ -261,7 +269,7 @@ describe("the shape of a comment", () => { const comment = renderComment({ report: report([endpoint("weather", [pass("X402-01"), errored("X402-02", "x", new ConfigurationError("could not connect"))])]), }); - assert.match(comment, /Wasit: no verdict/); + assert.match(comment, /Wasit: ⚠️ no verdict/); assert.match(comment, /1 could not run/); }); @@ -385,6 +393,15 @@ describe("a hostile service", () => { assert.ok(!comment.includes("onerror=alert(1)>")); }); + it("holds no HTML tag but its own: the marker, one details block and its summary (2026-11-20)", () => { + const tags = comment.match(/<[^>]*>/g) ?? []; + assert.deepEqual([...new Set(tags)].sort(), ["", "", "", "
", ""]); + assert.equal(tags.filter((tag) => tag === "
").length, 1); + assert.equal(tags.filter((tag) => tag === "
").length, 1); + const summary = renderCheckRun({ report: hostileReport(), secrets: [CANARY] }).summary; + assert.deepEqual([...new Set(summary.match(/<[^>]*>/g) ?? [])].sort(), ["
", "", "
", ""]); + }); + it("lets no link, mention, issue reference or mailto of the service stand", () => { assert.ok(!comment.includes("evil.example")); assert.ok(!/@octocat|@github/.test(comment)); @@ -449,3 +466,170 @@ describe("a hostile service", () => { assert.match(big, /more failures? not shown/); }); }); + +// D-022b option 2 (Najmi, 2026-11-16): "Changed since main" compares with the last +// green run on main, the history comes from every completed run on main, and the +// comment names the run it compares with, so a red main does not read as the +// pull request's fault. Written before the code. +describe("the run compared with, and the history of every run (D-022b)", () => { + const green = report([endpoint("weather", conformant())]); + const failing = report([endpoint("weather", [...CHALLENGE.slice(0, 3).map((id) => pass(id)), fail("X402-04", "missing field"), pass("X402-05")])]); + + it("names the green run of main it compares with, by run id and its start time", () => { + const comment = renderComment({ report: green, baseline: baselineOf([green]), baselineRun: 43724229283 }); + assert.match( + comment, + /Compared with the last green run on main: run 43724229283, started 2026-11-15 10:00 UTC\. Runs on main that failed after it are counted under Recent failures on main, not here\./, + ); + }); + + it("names the start time alone when the run id is not known, and nothing when there is no baseline", () => { + assert.match(renderComment({ report: green, baseline: baselineOf([green]) }), /Compared with the last green run on main, started 2026-11-15 10:00 UTC\./); + assert.doesNotMatch(renderComment({ report: green }), /Compared with the last green run/); + }); + + it("counts recent failures from the history of every run when one is given, not only the green ones", () => { + const everyRun = baselineOf([green, failing, failing]).history; + const comment = renderComment({ report: green, baseline: baselineOf([green]), history: everyRun }); + assert.match(comment, /weather X402-04: failed in 2 of the last 3 runs on main/); + }); + + it("keeps the baseline's own history when no other is given", () => { + const comment = renderComment({ report: green, baseline: baselineOf([failing, green]) }); + assert.match(comment, /weather X402-04: failed in 1 of the last 2 runs on main/); + }); +}); + +// The detailed comment, the running comment and the check run (Najmi, 2026-11-20). +// Written before the code. What they add is laid out from the same sanitised +// report; links are built only from parts Wasit checked. +describe("the detailed comment", () => { + // An obviously made-up hash: no real transaction, nothing a secret scanner should flag. + const HASH = "0123456789abcdef".repeat(4); + const settled = (reference: string, pass = true): CheckResult => ({ + id: "X402-06", + name: "Signature Resubmit Accepted", + pass, + detail: pass ? "settled on chain" : "no settlement", + ...(pass ? { reference } : {}), + }); + const onNetwork = (network: string, endpoints: ReturnType[]): RunReport => + buildRunReport({ environment: "local", network, startedAt: "2026-11-15T10:00:00.000Z", versions: VERSIONS, endpoints, notes: [] }); + + it("shows each endpoint's checks in a table, each with its mark and its status", () => { + const comment = renderComment({ + report: report([endpoint("weather", [pass("X402-01"), fail("X402-02", "no header"), errored("X402-03", "Header Payload Decodable", new ConfigurationError("down"))])]), + }); + assert.match(comment, /^### ❌ weather · x402 · non-conformant$/m); + assert.match(comment, /^\| ✅ \| X402-01 402 Response Status \| PASS \|$/m); + assert.match(comment, /^\| ❌ \| X402-02 Payment Header Present \| FAIL \|$/m); + assert.match(comment, /^\| ⚠️ \| X402-03 Header Payload Decodable \| ERROR \|$/m); + assert.match(comment, /\| weather \| x402 \| ❌ non-conformant \|/); + }); + + it("folds every check's detail away at the end, and gives a skip's repeated reason once", () => { + const comment = renderComment({ report: report([endpoint("weather", conformant())]) }); + const at = comment.indexOf("
Details of each check"); + assert.ok(at > comment.indexOf("### Changed since main"), "the details come after the report's sections"); + assert.ok(comment.trimEnd().endsWith("
")); + assert.match(comment, /- ⚪ X402-07 Invalid Signature Rejected: the same reason as above\./); + assert.equal(comment.split("the read-only tier makes no payment").length - 1, 1, "the skip reason is given once"); + }); + + it("links the payment proof only for X402-06 passed on stellar:testnet with a 64-character hex reference", () => { + const proof = renderComment({ report: report([endpoint("weather", [pass("X402-01"), settled(HASH)])]) }); + assert.ok(proof.includes(`[tx 0123…cdef on Stellar Expert](https://stellar.expert/explorer/testnet/tx/${HASH})`)); + for (const [label, text] of [ + ["upper-case hash", renderComment({ report: report([endpoint("w", [settled(HASH.toUpperCase())])]) })], + ["not hex", renderComment({ report: report([endpoint("w", [settled("z".repeat(64))])]) })], + ["a link in the reference", renderComment({ report: report([endpoint("w", [settled(`${HASH.slice(0, 40)}](https://evil.example)`)])]) })], + ["a failed X402-06", renderComment({ report: report([endpoint("w", [settled(HASH, false)])]) })], + ["another network", renderComment({ report: onNetwork("eip155:84532", [endpoint("w", [settled(HASH)])]) })], + ] as const) { + assert.ok(!text.includes("Payment proof"), label); + assert.ok(!text.includes("stellar.expert"), label); + assert.ok(!text.includes("evil.example"), label); + } + }); + + it("keeps a reference in the report only for a PASS, and reads it back from a report file, cut short", () => { + const failedWithReference: CheckResult = { ...fail("X402-07", "accepted"), reference: HASH }; + const built = report([endpoint("weather", [settled(HASH), failedWithReference])]); + const results = built.endpoints[0]!.results; + assert.equal(results.find((result) => result.id === "X402-06")?.reference, HASH); + assert.equal(results.find((result) => result.id === "X402-07")?.reference, undefined, "a FAIL carries no reference"); + assert.equal(parseRunReport(JSON.parse(JSON.stringify(built))).endpoints[0]!.results[0]!.reference, HASH); + const forged = JSON.parse(JSON.stringify(built)); + forged.endpoints[0].results[0].reference = "a".repeat(500); + const read = parseRunReport(forged); + assert.equal(read.endpoints[0]!.results[0]!.reference?.length, 120, "a long reference is cut, as every text of a report file"); + assert.ok(!renderComment({ report: read }).includes("Payment proof"), "and a cut reference is not a hash, so it is never linked"); + }); + + it("shows at most 10 endpoints check by check, and says where the rest are", () => { + const many = Array.from({ length: 12 }, (_, index) => endpoint(`endpoint-${index}`, conformant())); + const comment = renderComment({ report: report(many) }); + assert.equal((comment.match(/^### ✅ endpoint-\d+ · x402 · conformant$/gm) ?? []).length, 10); + assert.match(comment, /2 more endpoints are not shown check by check here/); + assert.match(comment, /the log of the step Run Wasit/, "the pointer names a place a pull request run has"); + assert.ok(!comment.includes("wasit-report.json")); + }); +}); + +describe("the running comment", () => { + const RUN = "https://github.com/acme/shop/actions/runs/123456789"; + + it("starts with the marker, says Wasit is running, when it started, and links the run", () => { + const body = renderRunningComment({ startedAt: "2026-11-20T08:54:10.000Z", runUrl: RUN, environment: "staging" }); + const [first, second] = lines(body); + assert.equal(first, COMMENT_MARKER); + assert.equal(second, `⏳ **Wasit is running** on staging · started 2026-11-20 08:54 UTC · [follow the run](${RUN})`); + assert.match(body, /The result replaces this comment when the run ends\./); + }); + + it("links the run only when the URL has the shape of a GitHub run page", () => { + for (const runUrl of [ + "javascript:alert(1)", + "http://github.com/acme/shop/actions/runs/1", + "https://github.com/acme/shop/actions/runs/1?x=1", + "https://github.com/acme/shop/pull/1", + "https://evil.example/acme/shop/actions/runs/1](https://evil.example)", + "", + ]) { + const body = renderRunningComment({ startedAt: "2026-11-20T08:54:10.000Z", runUrl }); + assert.ok(!body.includes("follow the run"), runUrl); + } + }); + + it("passes the environment's name through the sanitiser, and leaves out a time that is not one", () => { + const body = renderRunningComment({ + startedAt: "not a time", + environment: "@octocat [x](https://evil.example) canary-secret", + secrets: ["canary-secret"], + }); + assert.ok(!/@octocat/.test(body)); + assert.ok(!body.includes("evil.example")); + assert.ok(!/ { + it("ends as success for a conformant run, failure for a failing one, neutral for no verdict", () => { + assert.equal(renderCheckRun({ report: report([endpoint("weather", conformant())]) }).conclusion, "success"); + assert.equal(renderCheckRun({ report: report([endpoint("weather", [pass("X402-01"), fail("X402-02", "no header")])]) }).conclusion, "failure"); + const noVerdict = report([endpoint("weather", [pass("X402-01"), errored("X402-02", "x", new ConfigurationError("down"))])]); + assert.equal(renderCheckRun({ report: noVerdict }).conclusion, "neutral"); + assert.equal(renderNoReportCheckRun(VERSIONS).conclusion, "neutral"); + }); + + it("has a title of the verdict and the counts only, within GitHub's 255 characters, and the job summary as its summary", () => { + const hostile = report([endpoint("@octocat https://evil.example", [pass("X402-01"), fail("X402-02", "x".repeat(4000))])]); + const output = renderCheckRun({ report: hostile, secrets: ["canary"] }); + assert.equal(output.title, "❌ non-conformant · 1 passed, 1 failed"); + assert.ok(output.title.length <= 255); + assert.equal(output.summary, renderSummary({ report: hostile, secrets: ["canary"] })); + assert.ok(!output.summary.includes("evil.example") && !/@octocat| { }); describe("fetchTarget by default (the calls that carry a payment)", () => { - it("still follows a redirect to another origin, as before this change", async () => { + it("refuses a redirect to another origin and never connects there (D-022c; paid-request-redirects.test.ts)", async () => { const b = await site((_request, response) => { response.writeHead(402); response.end("elsewhere"); }); const a = await site((_request, response) => { response.writeHead(302, { location: `${b.origin}/x` }); response.end(); }); - const response = await fetchTarget(`${a.origin}/paid`); - assert.equal(response.status, 402); - assert.equal(await response.text(), "elsewhere"); - assert.equal(b.seen.length, 1); + await refusal(fetchTarget(`${a.origin}/paid`)); + assert.equal(b.seen.length, 0); }); }); diff --git a/packages/core/test/unit/fix-hints.test.ts b/packages/core/test/unit/fix-hints.test.ts index 4cf6b24..b6125ae 100644 --- a/packages/core/test/unit/fix-hints.test.ts +++ b/packages/core/test/unit/fix-hints.test.ts @@ -206,7 +206,11 @@ describe("X402-01 to X402-03 hints", () => { try { const results = byId(await runX402ReadChecks({ target: target.url })); assert.equal(results["X402-02"]?.skipKind, "unsupported"); - assert.match(results["X402-02"]?.skipReason ?? "", /move to x402 v2: send the challenge base64-encoded in a PAYMENT-REQUIRED response header/); + const reason = results["X402-02"]?.skipReason ?? ""; + assert.match(reason, /Wasit grades only x402 v2, on every chain: challenge in a PAYMENT-REQUIRED header/); + assert.match(reason, /Fix: move it to that header\. Why: docs\/CHECKS\.md\.$/); + assert.doesNotMatch(reason, /https?:\/\//, "no URL: the comment's sanitiser would remove it"); + assert.ok(Array.from(`Skipped: ${reason}`).length <= 300, "fits a pull request comment uncut"); assert.equal(results["X402-02"]?.hint, undefined); } finally { await target.close(); diff --git a/packages/core/test/unit/mainnet-optin.test.ts b/packages/core/test/unit/mainnet-optin.test.ts new file mode 100644 index 0000000..5247e48 --- /dev/null +++ b/packages/core/test/unit/mainnet-optin.test.ts @@ -0,0 +1,117 @@ +/** + * The mainnet opt-in switches of this version (spec B5, B12): `--mainnet` of + * `wasit run`, and the MCP server's start-up variables `WASIT_MAINNET_OPT_IN` + * and `WASIT_MAINNET_CONFIG`. Each exists only to refuse, with the sentence of + * B12, so a run or a server that asks for mainnet is stopped and told why, + * never run on what else it was given. + * + * The module has no function that answers "allowed": every function either + * throws or only says which switches are set. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { ConfigurationError } from "../../src/errors.js"; +import * as optin from "../../src/guard/mainnet-optin.js"; +import { + MAINNET_OPT_IN_ABSENT, + MainnetOptInRefusedError, + mainnetStartupSwitches, + refuseMainnetSwitch, + type MainnetSwitch, +} from "../../src/guard/mainnet-optin.js"; +import { NETWORK_CLASSES } from "../../src/guard/networks.js"; + +const SWITCHES: readonly MainnetSwitch[] = ["--mainnet", "WASIT_MAINNET_OPT_IN", "WASIT_MAINNET_CONFIG"]; +const TEST_NETWORKS = [...NETWORK_CLASSES].filter(([, kind]) => kind === "test").map(([network]) => network); + +function refusal(name: MainnetSwitch, context?: { event?: string }): MainnetOptInRefusedError { + try { + refuseMainnetSwitch(name, context); + } catch (error) { + assert.ok(error instanceof MainnetOptInRefusedError, `${name}: a MainnetOptInRefusedError`); + return error; + } + assert.fail(`${name} was not refused`); +} + +describe("the mainnet opt-in switches of this version (B12)", () => { + it("says the sentence of B12", () => { + assert.equal(MAINNET_OPT_IN_ABSENT, "the mainnet opt-in is not part of this version"); + }); + + it("refuses --mainnet, names the test networks it pays on, and says nothing was done", () => { + const error = refusal("--mainnet"); + assert.ok(error instanceof ConfigurationError, "a ConfigurationError: the front ends exit 2 on it"); + assert.equal(error.switchName, "--mainnet"); + assert.match(error.message, /^--mainnet is refused: the mainnet opt-in is not part of this version\./); + for (const network of TEST_NETWORKS) assert.ok(error.message.includes(network), network); + assert.match(error.message, /The config was not read, and nothing was started, sent or signed\.$/); + assert.doesNotMatch(error.message, /workflow_dispatch/, "no event rule outside GitHub Actions"); + }); + + it("adds the event rule on a GitHub event that is not workflow_dispatch, and names the event", () => { + for (const event of ["push", "schedule", "pull_request", "pull_request_target", "merge_group"]) { + const error = refusal("--mainnet", { event }); + assert.ok( + error.message.includes(`--mainnet is also refused on every GitHub event but workflow_dispatch, and this run's event is ${event}.`), + error.message, + ); + assert.match(error.message, /The config was not read, and nothing was started, sent or signed\.$/); + } + }); + + it("still refuses on workflow_dispatch, without the event rule", () => { + const error = refusal("--mainnet", { event: "workflow_dispatch" }); + assert.match(error.message, /the mainnet opt-in is not part of this version/); + assert.doesNotMatch(error.message, /also refused/); + }); + + it("never echoes an event name it cannot read", () => { + for (const event of ["push; rm -rf /", "x".repeat(65), "Push", "pu\u001bsh", ""]) { + const error = refusal("--mainnet", { event }); + assert.ok(!error.message.includes(event) || event === "", JSON.stringify(event)); + if (event !== "") assert.match(error.message, /and this run's event is another event\./); + } + }); + + it("refuses each MCP start-up variable: the server does not start", () => { + for (const name of ["WASIT_MAINNET_OPT_IN", "WASIT_MAINNET_CONFIG"] as const) { + const error = refusal(name); + assert.equal(error.switchName, name); + assert.match(error.message, new RegExp(`^${name} is set: the mainnet opt-in is not part of this version, so this server does not start\\.`)); + for (const network of TEST_NETWORKS) assert.ok(error.message.includes(network), network); + assert.match(error.message, new RegExp(`Remove ${name} from the server's environment to start it\\.$`)); + } + }); + + it("finds the MCP start-up switches: any value that is not blank, in any letter case on the name, and --mainnet among the arguments", () => { + assert.deepEqual(mainnetStartupSwitches({}, []), []); + assert.deepEqual(mainnetStartupSwitches({ WASIT_MAINNET_OPT_IN: "", WASIT_MAINNET_CONFIG: " " }, []), []); + assert.deepEqual(mainnetStartupSwitches({ WASIT_MAINNET_OPT_IN: "1" }, []), ["WASIT_MAINNET_OPT_IN"]); + assert.deepEqual(mainnetStartupSwitches({ WASIT_MAINNET_OPT_IN: "0" }, []), ["WASIT_MAINNET_OPT_IN"], "0 is set: remove it"); + assert.deepEqual(mainnetStartupSwitches({ wasit_mainnet_config: "/tmp/x.json" }, []), ["WASIT_MAINNET_CONFIG"]); + assert.deepEqual( + mainnetStartupSwitches({ WASIT_MAINNET_OPT_IN: "1", WASIT_MAINNET_CONFIG: "/x" }, ["--mainnet"]), + ["--mainnet", "WASIT_MAINNET_OPT_IN", "WASIT_MAINNET_CONFIG"], + ); + assert.deepEqual(mainnetStartupSwitches({}, ["--mainnet=true"]), ["--mainnet"]); + assert.deepEqual(mainnetStartupSwitches({}, ["--allow-destructive"]), []); + }); + + it("has no function that answers allowed: each one throws, or only lists the switches that are set", () => { + const functions = Object.entries(optin).filter(([, value]) => typeof value === "function"); + const names = functions.map(([name]) => name).sort(); + assert.deepEqual(names, ["MainnetOptInRefusedError", "mainnetStartupSwitches", "refuseMainnetSwitch"]); + for (const name of SWITCHES) { + for (const context of [undefined, {}, { event: "workflow_dispatch" }, { event: "push" }]) { + assert.throws(() => refuseMainnetSwitch(name, context), MainnetOptInRefusedError); + } + } + for (const env of [{}, { WASIT_MAINNET_OPT_IN: "1" }]) { + const result = mainnetStartupSwitches(env, ["--mainnet"]); + assert.ok(Array.isArray(result) && result.every((entry) => SWITCHES.includes(entry)), "a list of switch names, nothing else"); + } + }); +}); diff --git a/packages/core/test/unit/no-allow-path.test.ts b/packages/core/test/unit/no-allow-path.test.ts new file mode 100644 index 0000000..abe75ff --- /dev/null +++ b/packages/core/test/unit/no-allow-path.test.ts @@ -0,0 +1,218 @@ +/** + * The "no allow path" property test of spec B11 and B12, in core: for random + * combinations of the options a caller can give, a payment on `stellar:pubnet` + * is refused before any request, and the signer is never called. + * + * The chain under test stands in for Stellar's adapter and makes every gate + * that is not Wasit's own permissive: it takes any key, its RPC answers the + * mainnet passphrase, its scheme signs whatever it is asked and records it, and + * the paywall settles every paid request. So the only thing between a caller + * and a mainnet signature is the guard. A control run on stellar:testnet with + * the same chain shows that the recorder does see a signature when one is made. + * + * Seeded, so a failure is reproducible: the seed is in the message. + */ + +import assert from "node:assert/strict"; +import { afterEach, beforeEach, describe, it } from "node:test"; + +import { Keypair, Networks } from "@stellar/stellar-sdk"; +import type { PaymentRequirements } from "@x402/core/types"; + +import { checkStatus } from "../../src/check.js"; +import { RunBudget } from "../../src/guard/budget.js"; +import { PaymentNetworkRefusedError } from "../../src/guard/networks.js"; +import { setRpcIdentityTransportForTesting } from "../../src/guard/rpc-identity.js"; +import { setPaymentChainsForTesting } from "../../src/x402/chains/index.js"; +import type { PaymentChain } from "../../src/x402/chains/types.js"; +import type { EndpointPlan } from "../../src/x402/plan.js"; +import { planX402Run } from "../../src/x402/plan.js"; +import { runX402PaymentChecks } from "../../src/x402/simulator.js"; +import { paywall, type Paywall } from "../support/recording-chain.js"; + +const PUBNET = "stellar:pubnet"; +const TESTNET = "stellar:testnet"; +/** Stellar mainnet USDC (Circle), as the MCP tests use it. */ +const PUBNET_USDC = "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75"; +/** Stellar testnet USDC, the asset of guard/budget.ts. */ +const TESTNET_USDC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; +const PAY_TO = Keypair.random().publicKey(); +const PAYER = Keypair.random().publicKey(); +const PASSPHRASES: Record = { [PUBNET]: Networks.PUBLIC, [TESTNET]: Networks.TESTNET }; + +/** mulberry32: small, seeded, good enough to pick test cases. */ +function random(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const signed: PaymentRequirements[] = []; + +/** Stellar's two networks, every gate but Wasit's own open. */ +function permissiveStellar(): PaymentChain { + const asset = (network: string): string => (network === PUBNET ? PUBNET_USDC : TESTNET_USDC); + return { + name: "Recording Stellar", + networks: [TESTNET, PUBNET], + payerKeyEnv: "STELLAR_PRIVATE_KEY", + referenceKind: "a test reference", + resolveRpcUrl: (network, override) => override || `http://127.0.0.1:9/${network}`, + registerPayer(client) { + for (const network of [TESTNET, PUBNET] as const) { + client.register(network, { + scheme: "exact", + findDefaultAsset: (wanted, on) => (on === network && wanted === asset(network) ? { asset: wanted, decimals: 7, symbol: "USDC" } : undefined), + async createPaymentPayload(version, requirements) { + signed.push(requirements); + return { x402Version: version, payload: { signature: `sig-${signed.length}` } }; + }, + }); + } + }, + expiredSigning: async () => ({ terms: { maxTimeoutSeconds: 1 }, holdMs: 0 }), + payerAddress: () => PAYER, + generatePayerKey: () => Keypair.random().secret(), + payerBalance: async () => 10n ** 30n, + isSettlementReference: (reference) => reference.startsWith("tx-"), + verifySettlement: async () => ({ pass: true, detail: "settled (recording chain)" }), + corruptPayload: (payload) => ({ ...payload, signature: "corrupted" }), + }; +} + +function challengeOption(network: string, amount: bigint): PaymentRequirements { + return { + scheme: "exact", + network: network as PaymentRequirements["network"], + amount: amount.toString(), + asset: network === PUBNET ? PUBNET_USDC : TESTNET_USDC, + payTo: PAY_TO, + maxTimeoutSeconds: 60, + extra: { areFeesSponsored: true }, + }; +} + +function pick(next: () => number, values: readonly T[]): T { + return values[Math.floor(next() * values.length)]!; +} + +/** A plan entry as a caller could hand one in, planned for pubnet: core must not take it as permission. */ +function forgedPlan(name: string, amount: bigint): EndpointPlan { + return { + name, + status: "planned", + option: { scheme: "exact", network: PUBNET, payTo: PAY_TO, asset: PUBNET_USDC, amount, maxTimeoutSeconds: 60 }, + signatures: ["X402-06", "X402-07", "X402-09", "X402-10", "X402-11"].map((check) => ({ check, amount })), + worstCase: amount * 5n, + worstCaseUsd: 0n, + }; +} + +let wall: Paywall | undefined; + +beforeEach(() => { + signed.length = 0; + setPaymentChainsForTesting([permissiveStellar()]); + setRpcIdentityTransportForTesting(async (url, method) => { + if (method !== "getNetwork") return undefined; + const network = new URL(url).pathname.slice(1); + return { passphrase: PASSPHRASES[network] ?? Networks.PUBLIC }; + }); +}); + +afterEach(async () => { + setPaymentChainsForTesting(undefined); + setRpcIdentityTransportForTesting(undefined); + await wall?.close(); + wall = undefined; +}); + +describe("no allow path for stellar:pubnet (B11, B12), in core", () => { + it("control: the same chain on stellar:testnet signs, so the recorder sees a signature when one is made", async () => { + wall = await paywall([challengeOption(TESTNET, 100_000n)]); + await runX402PaymentChecks({ target: wall.url, network: TESTNET, payerSecretKey: Keypair.random().secret() }); + assert.ok(signed.length > 0, "the control signed nothing: the test below would prove nothing"); + assert.ok(wall.paid > 0, "the control sent no payment"); + }); + + it("refuses every random combination of options: no signature, no paid request, no payment check passes", async () => { + const seed = Number(process.env.WASIT_PROPERTY_SEED ?? Date.now() % 2 ** 31); + const next = random(seed); + for (let round = 0; round < 60; round += 1) { + const amount = BigInt(1 + Math.floor(next() * 10_000_000)); + const accepts = pick(next, [ + [challengeOption(PUBNET, amount)], + [challengeOption(PUBNET, amount), challengeOption(TESTNET, amount)], + [challengeOption(TESTNET, amount), challengeOption(PUBNET, amount)], + ]); + wall = await paywall(accepts); + let challenges = 0; + wall.onChallenge = () => { + challenges += 1; + }; + const method = pick(next, ["GET", "POST"] as const); + const options = { + target: wall.url, + network: PUBNET, + payerSecretKey: pick(next, [Keypair.random().secret(), "SNOTAKEY", "x"]), + ...(next() < 0.5 ? { rpcUrl: pick(next, [`http://127.0.0.1:9/${PUBNET}`, `http://127.0.0.1:9/${TESTNET}`, "https://rpc.example.test/key"]) } : {}), + ...(next() < 0.5 ? { budget: new RunBudget({ maxRunUsd: pick(next, [0.01, 1, 5]) }) } : {}), + ...(next() < 0.5 ? { pin: { payTo: PAY_TO, asset: PUBNET_USDC } } : {}), + ...(next() < 0.5 ? { plan: forgedPlan("paid", amount) } : {}), + ...(next() < 0.5 ? { reject: { headers: { "x-wasit-invalid": "1" } } } : {}), + method, + ...(method === "POST" ? { body: "{}" } : {}), + }; + const results = await runX402PaymentChecks(options); + const { budget: _budget, plan: _plan, payerSecretKey: _key, ...shown } = options as typeof options & { budget?: unknown; plan?: unknown }; + const label = `seed ${seed}, round ${round}: ${JSON.stringify({ ...shown, budget: "budget" in options, plan: "plan" in options })}`; + assert.equal(signed.length, 0, `${label}: signed ${signed.length}`); + assert.equal(wall.paid, 0, `${label}: a paid request reached the paywall`); + assert.equal(challenges, 0, `${label}: the target was asked for its challenge before the refusal`); + assert.ok(!results.some((result) => result.id !== "PREFLIGHT" && checkStatus(result) === "PASS"), `${label}: a payment check passed`); + const preflight = results.find((result) => result.id === "PREFLIGHT"); + assert.ok(preflight !== undefined && checkStatus(preflight) === "ERROR", `${label}: no PREFLIGHT error`); + assert.match(preflight.detail, /stellar:pubnet is Stellar mainnet/, label); + await wall.close(); + wall = undefined; + } + }); + + it("refuses the plan of a pubnet run before any request, whatever its endpoints", async () => { + const seed = Number(process.env.WASIT_PROPERTY_SEED ?? Date.now() % 2 ** 31); + const next = random(seed); + for (let round = 0; round < 20; round += 1) { + wall = await paywall([challengeOption(PUBNET, BigInt(1 + Math.floor(next() * 10_000_000)))]); + let challenges = 0; + wall.onChallenge = () => { + challenges += 1; + }; + const count = 1 + Math.floor(next() * 4); + const endpoints = Array.from({ length: count }, (_, index) => ({ + name: `e${index}`, + target: wall!.url, + ...(next() < 0.5 ? { reject: { headers: { "x-wasit-invalid": "1" } } } : {}), + })); + await assert.rejects( + planX402Run({ + network: PUBNET, + ...(next() < 0.5 ? { pin: { payTo: PAY_TO, asset: PUBNET_USDC } } : {}), + ...(next() < 0.5 ? { maxRunUsd: pick(next, [0.5, 1, 5]) } : {}), + endpoints, + }), + PaymentNetworkRefusedError, + `seed ${seed}, round ${round}`, + ); + assert.equal(signed.length, 0); + assert.equal(wall.paid, 0); + assert.equal(challenges, 0, `seed ${seed}, round ${round}: a request was sent before the refusal`); + await wall.close(); + wall = undefined; + } + }); +}); diff --git a/packages/core/test/unit/paid-request-redirects.test.ts b/packages/core/test/unit/paid-request-redirects.test.ts new file mode 100644 index 0000000..5cba85b --- /dev/null +++ b/packages/core/test/unit/paid-request-redirects.test.ts @@ -0,0 +1,431 @@ +/** + * A request that carries a payment never follows a redirect (D-032, D-022c). + * + * `fetch` follows a redirect and keeps a custom header such as + * `PAYMENT-SIGNATURE` on the way, so a route that redirects a paid request + * would deliver the signed payment to a second URL: another host, or a second + * handler of the same service, which can settle it while the check grades the + * first. The rule: the unpaid challenge a payment check reads may follow one + * redirect inside the origin, when the request keeps its method; the payment + * then goes to the URL that challenge came from, with redirects refused. A + * redirect answer to a paid request is no verdict, and the payment is not sent + * again. MPP pays at the URL it reads, so every MPP request refuses a redirect. + * + * Offline: in-process servers on loopback, a throwaway EVM key (EIP-3009 + * signing needs no RPC), and a stand-in RPC for the balance X402-06 reads. + */ + +import assert from "node:assert/strict"; +import http from "node:http"; +import { afterEach, describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; +import { charge as chargeClient } from "@stellar/mpp/charge/client"; +import { Mppx, Store, charge } from "@stellar/mpp/charge/server"; +import { generatePrivateKey } from "viem/accounts"; + +import { + RedirectRefusedError, + classifyCheckError, + fetchPaymentChallenge, + fetchTarget, + fetchWithoutRedirects, +} from "../../src/errors.js"; +import { payCharge } from "../../src/mpp/charge.js"; +import { runX402PaymentChecks } from "../../src/x402/simulator.js"; + +const NETWORK = "eip155:84532"; + +interface Seen { + readonly method: string; + readonly path: string; + readonly paid: boolean; +} + +interface Site { + readonly origin: string; + readonly seen: Seen[]; + readonly close: () => Promise; +} + +const open: Site[] = []; + +async function site( + handle: (request: http.IncomingMessage, response: http.ServerResponse, origin: string) => void, +): Promise { + const seen: Seen[] = []; + let origin = ""; + const server = http.createServer((request, response) => { + request.on("data", () => undefined); + request.on("end", () => { + seen.push({ + method: request.method ?? "", + path: request.url ?? "", + paid: + typeof request.headers["payment-signature"] === "string" || + typeof request.headers["authorization"] === "string", + }); + handle(request, response, origin); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`; + const created: Site = { + origin, + seen, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; + open.push(created); + return created; +} + +afterEach(async () => { + await Promise.all(open.splice(0).map((created) => created.close())); +}); + +async function refusal(promise: Promise): Promise { + try { + await promise; + } catch (error) { + assert.ok(error instanceof RedirectRefusedError, `expected a RedirectRefusedError, got ${String(error)}`); + return error; + } + return assert.fail("expected the redirect to be refused"); +} + +const CHALLENGE = Buffer.from( + JSON.stringify({ + x402Version: 2, + resource: { url: "http://127.0.0.1/paid" }, + accepts: [ + { + scheme: "exact", + network: NETWORK, + amount: "10000", + asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + payTo: "0x209693Bc6afc0C5328bA36FaF03C514EF312287C", + maxTimeoutSeconds: 60, + extra: { name: "USDC", version: "2" }, + }, + ], + }), +).toString("base64"); + +function isPaid(request: http.IncomingMessage): boolean { + return typeof request.headers["payment-signature"] === "string"; +} + +/** A JSON-RPC stand-in: `eth_chainId` is Base Sepolia's, `eth_call` (the balance X402-06 reads) is plenty. */ +async function rpcStandIn(): Promise<{ url: string; close: () => Promise }> { + const server = http.createServer((request, response) => { + let body = ""; + request.on("data", (chunk) => (body += chunk)); + request.on("end", () => { + const { id, method } = JSON.parse(body) as { id: number; method: string }; + const result = + method === "eth_chainId" ? "0x14a34" : method === "eth_call" ? `0x${(10n ** 12n).toString(16).padStart(64, "0")}` : undefined; + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify( + result === undefined + ? { jsonrpc: "2.0", id, error: { code: -32601, message: "not in this stand-in" } } + : { jsonrpc: "2.0", id, result }, + ), + ); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + url: `http://127.0.0.1:${port}`, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +describe("fetchTarget by default: a redirect is never followed", () => { + it("refuses a redirect inside the origin and sends nothing to the Location", async () => { + const a = await site((request, response) => { + if (request.url === "/paid") { + response.writeHead(307, { location: "/elsewhere" }); + response.end(); + return; + } + response.writeHead(200); + response.end(); + }); + const error = await refusal(fetchTarget(`${a.origin}/paid`, { headers: { "payment-signature": "signed" } })); + assert.match(error.message, /307/); + assert.match(error.message, /does not follow a redirect/); + assert.deepEqual(a.seen.map((s) => s.path), ["/paid"]); + }); + + it("refuses a redirect to another origin, names only its origin, and never connects there", async () => { + const b = await site((_request, response) => { + response.writeHead(200); + response.end(); + }); + const a = await site((_request, response) => { + response.writeHead(302, { location: `${b.origin}/x?token=hunter2` }); + response.end(); + }); + const error = await refusal(fetchTarget(`${a.origin}/paid`)); + assert.match(error.message, new RegExp(b.origin.replace(/\./g, "\\."))); + assert.equal(error.message.includes("hunter2"), false); + assert.equal(b.seen.length, 0, "a request reached the other origin"); + }); + + it("returns an answer that is not a redirect untouched, a 3xx without Location included", async () => { + const a = await site((request, response) => { + response.writeHead(request.url === "/bare" ? 302 : 402); + response.end("body"); + }); + assert.equal((await fetchTarget(`${a.origin}/x`)).status, 402); + assert.equal((await fetchTarget(`${a.origin}/bare`)).status, 302); + }); + + it("is a configuration error: no verdict about the target", async () => { + const a = await site((_request, response) => { + response.writeHead(308, { location: "/y" }); + response.end(); + }); + const error = await refusal(fetchTarget(`${a.origin}/x`)); + assert.equal(classifyCheckError(error).kind, "configuration"); + }); +}); + +describe("fetchPaymentChallenge: the challenge a payment is signed for, and where to pay", () => { + it("returns the target itself when it answers directly", async () => { + const a = await site((_request, response) => { + response.writeHead(402); + response.end(); + }); + const { response, url } = await fetchPaymentChallenge(`${a.origin}/paid`, undefined); + assert.equal(response.status, 402); + assert.equal(url, `${a.origin}/paid`); + }); + + it("follows one redirect inside the origin and returns the URL it led to", async () => { + const a = await site((request, response) => { + if (request.url === "/old") { + response.writeHead(308, { location: "/paid?x=1" }); + response.end(); + return; + } + response.writeHead(402); + response.end(); + }); + const { response, url } = await fetchPaymentChallenge(`${a.origin}/old`, { method: "POST", body: "{}" }); + assert.equal(response.status, 402); + assert.equal(url, `${a.origin}/paid?x=1`); + assert.deepEqual(a.seen.map((s) => [s.method, s.path]), [["POST", "/old"], ["POST", "/paid?x=1"]]); + }); + + it("refuses a redirect that turns the request into a GET: the payment would go with another request", async () => { + for (const status of [301, 302, 303]) { + const a = await site((request, response) => { + if (request.url === "/old") { + response.writeHead(status, { location: "/paid" }); + response.end(); + return; + } + response.writeHead(402); + response.end(); + }); + const error = await refusal(fetchPaymentChallenge(`${a.origin}/old`, { method: "POST", body: "{}" })); + assert.match(error.message, /GET/, String(status)); + assert.deepEqual(a.seen.map((s) => s.path), ["/old"], String(status)); + } + }); + + it("refuses a redirect to another origin and a second redirect", async () => { + const b = await site((_request, response) => { + response.writeHead(402); + response.end(); + }); + const a = await site((request, response) => { + const to: Record = { "/away": `${b.origin}/paid`, "/one": "/two", "/two": "/three" }; + const location = to[request.url ?? ""]; + if (location !== undefined) { + response.writeHead(307, { location }); + response.end(); + return; + } + response.writeHead(402); + response.end(); + }); + await refusal(fetchPaymentChallenge(`${a.origin}/away`, undefined)); + assert.equal(b.seen.length, 0); + await refusal(fetchPaymentChallenge(`${a.origin}/one`, undefined)); + }); +}); + +describe("fetchWithoutRedirects (the fetch MPP pays through)", () => { + it("refuses a redirect for a string, a URL and a Request, and sends nothing to the Location", async () => { + const a = await site((request, response) => { + if (request.url === "/paid") { + response.writeHead(302, { location: "/elsewhere" }); + response.end(); + return; + } + response.writeHead(200); + response.end(); + }); + await refusal(fetchWithoutRedirects(`${a.origin}/paid`, { headers: { authorization: "Payment x" } })); + await refusal(fetchWithoutRedirects(new URL(`${a.origin}/paid`))); + await refusal(fetchWithoutRedirects(new Request(`${a.origin}/paid`))); + assert.deepEqual(a.seen.map((s) => s.path), ["/paid", "/paid", "/paid"]); + }); + + it("returns a direct answer", async () => { + const a = await site((_request, response) => { + response.writeHead(402); + response.end(); + }); + assert.equal((await fetchWithoutRedirects(`${a.origin}/paid`)).status, 402); + }); +}); + +describe("runX402PaymentChecks and a redirect", () => { + it("gives X402-06 no verdict when the paid request is redirected, and the payment reaches no second URL", async () => { + const b = await site((_request, response) => { + response.writeHead(200); + response.end(); + }); + const a = await site((request, response) => { + if (!isPaid(request)) { + response.writeHead(402, { "payment-required": CHALLENGE }); + response.end(); + return; + } + response.writeHead(307, { location: request.url === "/same" ? "/handler-two" : `${b.origin}/paid` }); + response.end(); + }); + const node = await rpcStandIn(); + try { + for (const path of ["/same", "/away"]) { + const results = await runX402PaymentChecks({ + target: `${a.origin}${path}`, + network: NETWORK, + payerSecretKey: generatePrivateKey(), + rpcUrl: node.url, + }); + const honest = results.find((result) => result.id === "X402-06"); + assert.equal(honest?.pass, false, path); + assert.equal(honest?.error?.kind, "configuration", path); + assert.match(honest?.detail ?? "", /redirect/, path); + for (const result of results.filter((r) => r.id !== "X402-06")) { + assert.notEqual(result.pass, true, `${path} ${result.id}`); + } + } + assert.equal(b.seen.length, 0, "the payment reached another origin"); + assert.equal( + a.seen.filter((s) => s.path === "/handler-two").length, + 0, + "the payment reached a second handler of the same service", + ); + } finally { + await node.close(); + } + }); + + it("pays at the URL a same-origin redirect of the challenge led to, never at the first URL", async () => { + const a = await site((request, response) => { + if (request.url === "/old") { + response.writeHead(307, { location: "/paid" }); + response.end(); + return; + } + if (!isPaid(request)) { + response.writeHead(402, { "payment-required": CHALLENGE }); + response.end(); + return; + } + response.writeHead(402); + response.end(); + }); + const node = await rpcStandIn(); + try { + await runX402PaymentChecks({ + target: `${a.origin}/old`, + network: NETWORK, + payerSecretKey: generatePrivateKey(), + rpcUrl: node.url, + }); + const paid = a.seen.filter((s) => s.paid); + assert.ok(paid.length > 0, "no payment was sent"); + assert.deepEqual([...new Set(paid.map((s) => s.path))], ["/paid"]); + } finally { + await node.close(); + } + }); +}); + +describe("payCharge (MPP-01) and a redirect", () => { + const USDC_SAC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; + + /** The official @stellar/mpp charge server for a 0.001 USDC resource on testnet. */ + function officialCharge(): http.RequestListener { + const recipient = Keypair.random().publicKey(); + const mppx = Mppx.create({ + secretKey: "wasit-unit-test-challenge-secret", + methods: [charge({ recipient, currency: USDC_SAC, network: "stellar:testnet", store: Store.memory() })], + }); + return async (req, res) => { + const result = await Mppx.toNodeListener(mppx.charge({ amount: "0.001", currency: USDC_SAC, recipient }))(req, res); + if (result.status !== 402) res.end("paid"); + }; + } + + function countingMethod(): { method: ReturnType; signed: () => number } { + let signed = 0; + const sdk = chargeClient({ secretKey: Keypair.random().secret() }); + const method = { + ...sdk, + createCredential: async () => { + signed += 1; + return "wasit-unit-test-credential"; + }, + } as typeof sdk; + return { method, signed: () => signed }; + } + + it("does not follow a redirect of the paid request, and the credential reaches no second URL", async () => { + const official = officialCharge(); + const a = await site((request, response) => { + if (request.url === "/elsewhere") { + response.writeHead(200); + response.end(); + return; + } + if (typeof request.headers.authorization === "string") { + response.writeHead(307, { location: "/elsewhere" }); + response.end(); + return; + } + void official(request, response); + }); + const { method, signed } = countingMethod(); + await refusal(payCharge(`${a.origin}/paid`, "stellar:testnet", method)); + assert.equal(signed(), 1); + assert.equal(a.seen.filter((s) => s.path === "/elsewhere").length, 0); + }); + + it("refuses a route that redirects before the challenge, and signs nothing", async () => { + const a = await site((_request, response) => { + response.writeHead(302, { location: "/paid-here" }); + response.end(); + }); + const { method, signed } = countingMethod(); + await refusal(payCharge(`${a.origin}/paid`, "stellar:testnet", method)); + assert.equal(signed(), 0); + assert.deepEqual(a.seen.map((s) => s.path), ["/paid"]); + }); +}); diff --git a/packages/core/test/unit/payment-budget.test.ts b/packages/core/test/unit/payment-budget.test.ts new file mode 100644 index 0000000..b5f4fa0 --- /dev/null +++ b/packages/core/test/unit/payment-budget.test.ts @@ -0,0 +1,226 @@ +/** + * The caps of spec B4, as code: $1 a payment, $5 a run (a config may only + * lower it), charged before the signature and never credited back; the US + * dollar assets Wasit can hold to those caps; the pin over every `exact` + * option; the signatures a run makes per endpoint (B0 fact 8). + * + * Pure: no network, no key. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { + PER_PAYMENT_CAP_USD, + PER_RUN_CAP_USD, + PaymentGuardRefusedError, + RunBudget, + USD_ASSETS, + assertPinned, + formatUsd, + plannedSignatures, + sameAddress, + usdAsset, + usdFromDollars, +} from "../../src/guard/budget.js"; +import { CheckSetupError } from "../../src/errors.js"; +import { NETWORK_CLASSES } from "../../src/guard/networks.js"; + +const STELLAR = "stellar:testnet"; +const STELLAR_USDC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; +const BASE = "eip155:84532"; +const BASE_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; +const PAY_TO = "GDPAPDZWAKBXUPCNMI4YHAZ7DS7UOUTPGXAFDSWZG4URRMWHFSQTDQBM"; + +function refusedWith(reason: PaymentGuardRefusedError["reason"], run: () => void): PaymentGuardRefusedError { + try { + run(); + } catch (error) { + assert.ok(error instanceof PaymentGuardRefusedError, `expected a refusal, got ${String(error)}`); + assert.equal(error.reason, reason); + assert.match(error.message, /Nothing was signed\.$/); + return error; + } + return assert.fail(`expected a "${reason}" refusal`); +} + +describe("the caps", () => { + it("are $1 a payment and $5 a run, fixed in code", () => { + assert.equal(PER_PAYMENT_CAP_USD, 1); + assert.equal(PER_RUN_CAP_USD, 5); + }); + + it("a refusal is a setup error: no verdict about the target", () => { + const error = refusedWith("price", () => + new RunBudget().charge({ check: "X402-06", network: STELLAR, asset: STELLAR_USDC, amount: "10000001" }), + ); + assert.ok(error instanceof CheckSetupError); + }); +}); + +describe("the US dollar assets", () => { + it("lists only test networks, each in the guard's table, and nothing on mainnet in this version", () => { + for (const entry of USD_ASSETS) { + assert.equal(NETWORK_CLASSES.get(entry.network), "test", entry.network); + } + }); + + it("knows USDC on every test network, with the decimals the SDK uses", () => { + assert.equal(usdAsset(STELLAR, STELLAR_USDC)?.decimals, 7); + assert.equal(usdAsset(BASE, BASE_USDC)?.decimals, 6); + assert.equal(usdAsset("eip155:11155111", "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238")?.decimals, 6); + assert.equal( + usdAsset("solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU")?.decimals, + 6, + ); + }); + + it("reads an EVM address in any case, and a Stellar or Solana one exactly", () => { + assert.ok(usdAsset(BASE, BASE_USDC.toLowerCase())); + assert.ok(sameAddress(BASE, BASE_USDC, BASE_USDC.toUpperCase().replace("0X", "0x"))); + assert.equal(usdAsset(STELLAR, STELLAR_USDC.toLowerCase()), undefined); + assert.equal(sameAddress(STELLAR, PAY_TO, PAY_TO.toLowerCase()), false); + }); + + it("does not value an asset on another network, or one it does not list", () => { + assert.equal(usdAsset(BASE, STELLAR_USDC), undefined); + assert.equal(usdAsset(STELLAR, BASE_USDC), undefined); + assert.equal(usdAsset("stellar:pubnet", "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75"), undefined); + }); + + it("formats a dollar amount exactly, with at least two decimals", () => { + assert.equal(formatUsd(usdFromDollars(4.5)), "$4.50"); + assert.equal(formatUsd(usdFromDollars(5)), "$5.00"); + assert.equal(formatUsd(0n), "$0.00"); + const budget = new RunBudget(); + budget.charge({ check: "X402-06", network: STELLAR, asset: STELLAR_USDC, amount: "1" }); + assert.equal(formatUsd(budget.spentUsd), "$0.0000001"); + }); +}); + +describe("a run's budget", () => { + const pay = (budget: RunBudget, amount: string, check = "X402-06"): void => + budget.charge({ check, network: STELLAR, asset: STELLAR_USDC, amount }); + + it("takes a payment of exactly $1, and refuses one base unit more", () => { + const budget = new RunBudget(); + pay(budget, "10000000"); + refusedWith("price", () => pay(new RunBudget(), "10000001")); + assert.equal(formatUsd(budget.spentUsd), "$1.00"); + }); + + it("refuses the payment that would take the run above $5, and keeps what was charged", () => { + const budget = new RunBudget(); + for (let index = 0; index < 5; index += 1) pay(budget, "10000000"); + const error = refusedWith("run-cap", () => pay(budget, "1")); + assert.match(error.message, /\$5\.00/); + assert.equal(formatUsd(budget.spentUsd), "$5.00"); + }); + + it("is lowered by maxRunUsd and never raised by it", () => { + const lowered = new RunBudget({ maxRunUsd: 1.5 }); + assert.equal(formatUsd(lowered.capUsd), "$1.50"); + pay(lowered, "10000000"); + refusedWith("run-cap", () => pay(lowered, "5000001")); + assert.equal(formatUsd(new RunBudget({ maxRunUsd: 50 }).capUsd), "$5.00"); + }); + + it("refuses a maxRunUsd that is not a positive number, rather than reading it as no cap", () => { + for (const bad of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) { + assert.throws(() => new RunBudget({ maxRunUsd: bad }), /maxRunUsd/); + } + }); + + it("charges before anything is signed: a failed signature is never credited back", () => { + const budget = new RunBudget({ maxRunUsd: 1 }); + pay(budget, "10000000"); + // Whatever happens to that payment afterwards, the run has spent its dollar. + refusedWith("run-cap", () => pay(budget, "1", "X402-07")); + assert.equal(budget.entries.length, 1); + assert.deepEqual(budget.entries[0], { check: "X402-06", network: STELLAR, asset: STELLAR_USDC, amount: 10000000n }); + }); + + it("refuses an asset it cannot value, a negative amount and one that is not a whole number", () => { + refusedWith("asset", () => new RunBudget().charge({ check: "X402-06", network: STELLAR, asset: "CAAAA", amount: "1" })); + for (const amount of ["-1", "1.5", "1e3", "", " 1", "0x10", "9".repeat(79)]) { + refusedWith("amount", () => pay(new RunBudget(), amount)); + } + }); + + it("refuses a payment above what the plan allowed for that check", () => { + const budget = new RunBudget(); + const error = refusedWith("plan", () => + budget.charge({ check: "X402-06", network: STELLAR, asset: STELLAR_USDC, amount: "100001", planned: 100000n }), + ); + assert.match(error.message, /X402-06/); + assert.equal(budget.spentUsd, 0n); + }); + + it("charges USDC with 6 decimals at the same dollar value", () => { + const budget = new RunBudget(); + budget.charge({ check: "X402-06", network: BASE, asset: BASE_USDC, amount: "1000000" }); + assert.equal(formatUsd(budget.spentUsd), "$1.00"); + refusedWith("price", () => + budget.charge({ check: "X402-07", network: BASE, asset: BASE_USDC, amount: "1000001" }), + ); + }); +}); + +describe("the pin", () => { + const option = (payTo: string, asset = STELLAR_USDC, network = STELLAR, scheme = "exact") => ({ + scheme, + network, + payTo, + asset, + amount: "100000", + maxTimeoutSeconds: 60, + extra: {}, + }); + const pin = { payTo: PAY_TO, asset: STELLAR_USDC }; + const OTHER = "GALVZ57VAY6BE33WYPJMUJ27PFAUDRQ6ATTVMIIF4STTGQTXDBEIBXUI"; + + it("passes a challenge whose every exact option on the network is the pinned one", () => { + assertPinned(STELLAR, [option(PAY_TO), option(PAY_TO)], pin); + }); + + it("refuses ANY exact option on the network that pays someone else, not only the first", () => { + const error = refusedWith("pin", () => assertPinned(STELLAR, [option(PAY_TO), option(OTHER)], pin)); + assert.match(error.message, /payTo/); + }); + + it("refuses an exact option in another asset", () => { + refusedWith("pin", () => assertPinned(STELLAR, [option(PAY_TO, "CAS3J7GYLGXMF6TDJBBYYSE3HQ6BBSMLNUQ34T6TZMYMW2EVH34XOWMA")], pin)); + }); + + it("ignores options on other networks and other schemes, which are never signed", () => { + assertPinned(STELLAR, [option(PAY_TO), option(OTHER, BASE_USDC, BASE), option(OTHER, STELLAR_USDC, STELLAR, "upto")], pin); + }); + + it("does nothing without a pin", () => { + assertPinned(STELLAR, [option(OTHER)], undefined); + }); + + it("never echoes a long or hostile value from the challenge", () => { + const error = refusedWith("pin", () => assertPinned(STELLAR, [option(`G${"A".repeat(500)}\u001b[31m`)], pin)); + assert.ok(error.message.length < 400, error.message); + assert.doesNotMatch(error.message, /\u001b/); + }); +}); + +describe("what a run signs per endpoint (B0 fact 8)", () => { + it("is 3.5 times the price: X402-06, 07 and 10 at the price, 09 at half", () => { + assert.deepEqual(plannedSignatures(100000n), [ + { check: "X402-06", amount: 100000n }, + { check: "X402-07", amount: 100000n }, + { check: "X402-09", amount: 50000n }, + { check: "X402-10", amount: 100000n }, + ]); + }); + + it("has no X402-09 when there is no smaller payment to offer", () => { + assert.deepEqual( + plannedSignatures(1n).map((entry) => entry.check), + ["X402-06", "X402-07", "X402-10"], + ); + }); +}); diff --git a/packages/core/test/unit/payment-event-gate.test.ts b/packages/core/test/unit/payment-event-gate.test.ts new file mode 100644 index 0000000..df37341 --- /dev/null +++ b/packages/core/test/unit/payment-event-gate.test.ts @@ -0,0 +1,184 @@ +/** + * Which GitHub events may run the payment tier (D-022a option 2, D-032; Najmi's + * answers of 2026-11-16 in s2-build-plan.md): push to the default branch, + * schedule, and workflow_dispatch on the default branch. Every pull request event + * is refused, and so is every other event. Outside GitHub Actions the gate is + * open: a laptop run is the builder's own choice. + * + * This stops a mistake in a workflow, not its author (B-A10): a step can hide + * the runner's variables from the CLI. Written before the code (CONTEXT rule 3). + */ + +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, describe, it } from "node:test"; + +import { payerKeyVariables, paymentEventGate, readGithubEvent } from "../../src/guard/ci-event.js"; + +const main = { repository: { default_branch: "main" } }; + +function gha(event: string, ref = "refs/heads/main"): Record { + return { GITHUB_ACTIONS: "true", GITHUB_EVENT_NAME: event, GITHUB_REF: ref }; +} + +describe("paymentEventGate", () => { + it("is open outside CI", () => { + assert.deepEqual(paymentEventGate({}, undefined), { allowed: true }); + assert.deepEqual(paymentEventGate({ CI: "" }, undefined), { allowed: true }); + }); + + it("is closed in a CI that is not GitHub Actions, and says so (review R9 a, Najmi 2026-11-17)", () => { + for (const value of ["true", "1", "yes"]) { + const gate = paymentEventGate({ CI: value }, undefined); + assert.equal(gate.allowed, false, value); + assert.equal(gate.ciOutsideGithub, true, value); + assert.equal(gate.reason, "payment checks not run: CI is set, and this is not GitHub Actions"); + } + // GitHub Actions sets CI too: its own rules apply, not this one. + assert.equal(paymentEventGate({ CI: "true", ...gha("push") }, main).allowed, true); + assert.equal(paymentEventGate({ CI: "true", ...gha("push") }, main).ciOutsideGithub, undefined); + }); + + it("allows a push to the default branch", () => { + assert.equal(paymentEventGate(gha("push"), main).allowed, true); + }); + + it("allows a schedule, with or without a repository in the event", () => { + assert.equal(paymentEventGate(gha("schedule"), { schedule: "0 6 * * *" }).allowed, true); + assert.equal(paymentEventGate(gha("schedule"), main).allowed, true); + assert.equal(paymentEventGate(gha("schedule"), undefined).allowed, true); + }); + + it("counts any non-empty GITHUB_ACTIONS as GitHub Actions, as the CLI's CI test does (review R9 b)", () => { + for (const value of ["1", "TRUE", "yes"]) { + const gate = paymentEventGate({ GITHUB_ACTIONS: value }, undefined); + assert.equal(gate.allowed, false, value); + } + assert.equal(paymentEventGate({ GITHUB_ACTIONS: "" }, undefined).allowed, true, "an empty value is not set"); + }); + + it("refuses a schedule whose payload names no repository unless its ref is a branch (review R9 c)", () => { + for (const ref of ["refs/pull/1/merge", "refs/tags/v1", "", "main"]) { + const gate = paymentEventGate(gha("schedule", ref), { schedule: "0 6 * * *" }); + assert.equal(gate.allowed, false, ref); + assert.match(gate.reason ?? "", /payment checks not run/); + } + assert.equal(paymentEventGate(gha("schedule", "refs/heads/main"), undefined).allowed, true); + }); + + it("allows workflow_dispatch on the default branch", () => { + assert.equal(paymentEventGate(gha("workflow_dispatch"), main).allowed, true); + }); + + for (const event of ["pull_request", "pull_request_target", "pull_request_review", "pull_request_review_comment"]) { + it(`refuses ${event} with "payment checks not run: pull request"`, () => { + const gate = paymentEventGate(gha(event, "refs/pull/7/merge"), main); + assert.equal(gate.allowed, false); + assert.equal(gate.reason, "payment checks not run: pull request"); + }); + } + + it("refuses a pull request even when GITHUB_ACTIONS is not set but the event name is", () => { + const gate = paymentEventGate({ GITHUB_EVENT_NAME: "pull_request", GITHUB_REF: "refs/pull/7/merge" }, main); + assert.equal(gate.allowed, false); + assert.equal(gate.reason, "payment checks not run: pull request"); + }); + + for (const event of ["merge_group", "workflow_run", "issue_comment", "release", "repository_dispatch", ""]) { + it(`refuses the ${event === "" ? "unnamed" : event} event`, () => { + const gate = paymentEventGate(gha(event), main); + assert.equal(gate.allowed, false); + assert.match(gate.reason ?? "", /^payment checks not run: /); + assert.match(gate.reason ?? "", /push to the default branch, schedule and workflow_dispatch/); + }); + } + + it("refuses a push to another branch, and to a tag", () => { + for (const ref of ["refs/heads/feature", "refs/tags/v1.0.0", "refs/heads/main-copy", ""]) { + const gate = paymentEventGate(gha("push", ref), main); + assert.equal(gate.allowed, false, ref); + assert.match(gate.reason ?? "", /not the default branch/); + } + }); + + it("refuses workflow_dispatch on another branch", () => { + const gate = paymentEventGate(gha("workflow_dispatch", "refs/heads/feature"), main); + assert.equal(gate.allowed, false); + assert.match(gate.reason ?? "", /not the default branch/); + }); + + it("refuses a push or a dispatch when the event does not name the default branch", () => { + for (const event of ["push", "workflow_dispatch"]) { + for (const payload of [undefined, {}, { repository: {} }, { repository: { default_branch: 7 } }, "text"]) { + const gate = paymentEventGate(gha(event), payload); + assert.equal(gate.allowed, false, `${event} ${JSON.stringify(payload)}`); + assert.match(gate.reason ?? "", /default branch/); + } + } + }); + + it("refuses a schedule whose ref is not the default branch the event names", () => { + assert.equal(paymentEventGate(gha("schedule", "refs/heads/other"), main).allowed, false); + }); + + it("never echoes an event name or a ref that carries control characters", () => { + const gate = paymentEventGate(gha("evil\u001b[31m\nname", "refs/heads/x\u0007"), main); + assert.equal(gate.allowed, false); + assert.doesNotMatch(gate.reason ?? "", /[\u0000-\u001f\u007f]/); + }); +}); + +describe("payerKeyVariables", () => { + it("names each key variable that has a value, in upper case", () => { + assert.deepEqual(payerKeyVariables({ STELLAR_PRIVATE_KEY: "S...", PATH: "/bin" }), ["STELLAR_PRIVATE_KEY"]); + assert.deepEqual( + payerKeyVariables({ + EVM_PRIVATE_KEY: "0x1", + SVM_PRIVATE_KEY: "x", + MPP_PAYER_SECRET: "S", + COMMITMENT_SECRET_HEX: "ab", + WASIT_MAINNET_PAYER_SECRET: "S", + }).sort(), + ["COMMITMENT_SECRET_HEX", "EVM_PRIVATE_KEY", "MPP_PAYER_SECRET", "SVM_PRIVATE_KEY", "WASIT_MAINNET_PAYER_SECRET"], + ); + // Windows spells variables in any case; it is the same variable there. + assert.deepEqual(payerKeyVariables({ Stellar_Private_Key: "S" }), ["STELLAR_PRIVATE_KEY"]); + }); + + it("does not count an empty or blank value: a fork's pull request gets empty secrets", () => { + assert.deepEqual(payerKeyVariables({ STELLAR_PRIVATE_KEY: "", EVM_PRIVATE_KEY: " ", SVM_PRIVATE_KEY: undefined }), []); + }); + + it("does not count header or RPC variables: they are not payer keys", () => { + assert.deepEqual(payerKeyVariables({ WASIT_HEADER_X_API_KEY: "k", WASIT_RPC_URL: "https://rpc" }), []); + }); +}); + +describe("readGithubEvent", () => { + let dir: string; + before(async () => { + dir = await mkdtemp(path.join(tmpdir(), "wasit-event-")); + }); + after(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + it("reads the event file GITHUB_EVENT_PATH names", async () => { + const file = path.join(dir, "event.json"); + await writeFile(file, JSON.stringify(main)); + assert.deepEqual(readGithubEvent({ GITHUB_EVENT_PATH: file }), main); + }); + + it("gives undefined for no path, a missing file, a file that is not JSON, or one above 1 MiB", async () => { + assert.equal(readGithubEvent({}), undefined); + assert.equal(readGithubEvent({ GITHUB_EVENT_PATH: path.join(dir, "missing.json") }), undefined); + const text = path.join(dir, "text.json"); + await writeFile(text, "not json"); + assert.equal(readGithubEvent({ GITHUB_EVENT_PATH: text }), undefined); + const big = path.join(dir, "big.json"); + await writeFile(big, JSON.stringify({ repository: { default_branch: "main" }, pad: "x".repeat(1024 * 1024) })); + assert.equal(readGithubEvent({ GITHUB_EVENT_PATH: big }), undefined); + }); +}); diff --git a/packages/core/test/unit/payment-guard-l2.test.ts b/packages/core/test/unit/payment-guard-l2.test.ts new file mode 100644 index 0000000..21f1107 --- /dev/null +++ b/packages/core/test/unit/payment-guard-l2.test.ts @@ -0,0 +1,286 @@ +/** + * L1 (the plan) and L2 (every signature) on a test network, spec B3 and B4, + * written before the code they test (B11). + * + * L2 sits in `preparePayment`, the one function every x402 signature goes + * through: after the fresh challenge is read and before the SDK signs. It + * refuses a payment above $1, in an asset Wasit cannot value, to anyone but the + * pin in ANY `exact` option, above what the plan allowed, or past the run's + * cap; it charges the run before the signature and never credits it back; it + * hands the SDK exactly the one option it checked; and it discards, unsent, a + * payload whose `accepted` is not that option. + * + * Offline: a recording chain (it holds nothing, it only records what it is + * asked to sign) and a loopback paywall that settles everything. + */ + +import assert from "node:assert/strict"; +import { afterEach, beforeEach, describe, it } from "node:test"; + +import { RunBudget, formatUsd } from "../../src/guard/budget.js"; +import { planX402Run } from "../../src/x402/plan.js"; +import { runX402PaymentChecks } from "../../src/x402/simulator.js"; +import type { CheckResult } from "../../src/check.js"; +import { + NETWORK, + OTHER_PAY_TO, + PAY_TO, + USDC, + installRecordingChain, + option, + paywall, + signedTotal, + type Paywall, + type Recorder, +} from "../support/recording-chain.js"; + +let recorder: Recorder; +let undo: (() => void) | undefined; +const walls: Paywall[] = []; + +beforeEach(() => { + recorder = { signed: [] }; + undo = installRecordingChain(recorder); +}); + +afterEach(async () => { + undo?.(); + undo = undefined; + await Promise.all(walls.splice(0).map((wall) => wall.close())); +}); + +async function wall(...accepts: Parameters[0][]): Promise { + const created = await paywall(accepts.map(option)); + walls.push(created); + return created; +} + +function byId(results: readonly CheckResult[], id: string): CheckResult { + const found = results.find((result) => result.id === id); + assert.ok(found, `no ${id} in ${results.map((result) => result.id).join(", ")}`); + return found; +} + +function refusedSetup(result: CheckResult, pattern: RegExp): void { + assert.equal(result.error?.kind, "setup", `${result.id}: ${result.detail}`); + assert.match(result.detail, pattern); + assert.match(result.detail, /Nothing was signed\./); +} + +const run = (target: string, extra: Partial[0]> = {}) => + runX402PaymentChecks({ target, network: NETWORK, payerSecretKey: "test-payer-key", ...extra }); + +describe("L2: $1 a payment", () => { + it("signs nothing for a price one base unit above $1, and sends nothing", async () => { + const target = await wall({ amount: "1000001" }); + const results = await run(target.url); + refusedSetup(byId(results, "X402-06"), /\$1\.00/); + assert.equal(recorder.signed.length, 0); + assert.equal(target.paid, 0); + }); + + it("signs a price of exactly $1: 3.5 times the price over the run, within $5", async () => { + const target = await wall({ amount: "1000000" }); + const budget = new RunBudget(); + const results = await run(target.url, { budget }); + assert.equal(byId(results, "X402-06").pass, true, byId(results, "X402-06").detail); + assert.deepEqual( + recorder.signed.map((requirement) => requirement.amount), + ["1000000", "1000000", "500000", "1000000"], + ); + assert.equal(formatUsd(budget.spentUsd), "$3.50"); + }); + + it("signs nothing in an asset Wasit cannot hold to a dollar cap", async () => { + const target = await wall({ amount: "1", asset: "0x3333333333333333333333333333333333333333" }); + const results = await run(target.url); + refusedSetup(byId(results, "X402-06"), /does not value|US dollar/); + assert.equal(recorder.signed.length, 0); + }); +}); + +describe("L2: the run's cap", () => { + it("is shared across endpoints: once reached, nothing more is signed in the run", async () => { + const first = await wall({ amount: "1000000" }); + const second = await wall({ amount: "1000000" }); + const budget = new RunBudget(); + await run(first.url, { budget }); + const results = await run(second.url, { budget }); + + assert.equal(byId(results, "X402-06").pass, true); + refusedSetup(byId(results, "X402-07"), /\$5\.00/); + for (const id of ["X402-09", "X402-10"]) refusedSetup(byId(results, id), /cap/); + assert.equal(signedTotal(recorder), 4_500_000n); + assert.equal(formatUsd(budget.spentUsd), "$4.50"); + }); + + it("maxRunUsd lowers it: $1.50 lets X402-06 sign and refuses X402-07", async () => { + const target = await wall({ amount: "1000000" }); + const results = await run(target.url, { budget: new RunBudget({ maxRunUsd: 1.5 }) }); + assert.equal(byId(results, "X402-06").pass, true); + refusedSetup(byId(results, "X402-07"), /\$1\.50/); + assert.equal(signedTotal(recorder), 1_000_000n); + }); +}); + +describe("L2: the pin", () => { + const pin = { payTo: PAY_TO, asset: USDC }; + + it("refuses a challenge with a second exact option that pays someone else, and signs nothing", async () => { + const target = await wall({ amount: "10000" }, { amount: "10000", payTo: OTHER_PAY_TO }); + const results = await run(target.url, { pin }); + refusedSetup(byId(results, "X402-06"), /payTo/); + assert.equal(recorder.signed.length, 0); + assert.equal(target.paid, 0); + }); + + it("accepts an EVM pin in another letter case, and options on other networks", async () => { + const target = await wall( + { amount: "10000", payTo: PAY_TO.toLowerCase() }, + { amount: "10000", payTo: "GDPAPDZWAKBXUPCNMI4YHAZ7DS7UOUTPGXAFDSWZG4URRMWHFSQTDQBM", network: "stellar:testnet", asset: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA" }, + ); + const results = await run(target.url, { pin }); + assert.equal(byId(results, "X402-06").pass, true, byId(results, "X402-06").detail); + }); + + it("is re-checked on every signature: a payee changed after X402-06 stops X402-07", async () => { + const target = await wall({ amount: "10000" }); + target.onChallenge = (count) => { + if (count >= 2) target.accepts = [option({ amount: "10000", payTo: OTHER_PAY_TO })]; + }; + const results = await run(target.url, { pin }); + assert.equal(byId(results, "X402-06").pass, true); + refusedSetup(byId(results, "X402-07"), /payTo/); + assert.ok(recorder.signed.every((requirement) => requirement.payTo === PAY_TO)); + }); +}); + +describe("L1 then L2: a challenge that changes after the plan", () => { + it("the plan reads the price without paying, and signs nothing", async () => { + const target = await wall({ amount: "100000" }); + const plan = await planX402Run({ network: NETWORK, endpoints: [{ name: "weather", target: target.url }] }); + assert.equal(plan.refusal, undefined); + assert.equal(plan.endpoints[0]?.status, "planned"); + assert.equal(formatUsd(plan.worstCaseUsd), "$0.35"); + assert.equal(recorder.signed.length, 0); + assert.equal(target.paid, 0); + }); + + it("a price raised after the plan is refused, not signed", async () => { + const target = await wall({ amount: "100000" }); + const plan = await planX402Run({ network: NETWORK, endpoints: [{ name: "weather", target: target.url }] }); + target.accepts = [option({ amount: "200000" })]; + const results = await run(target.url, { plan: plan.endpoints[0]! }); + refusedSetup(byId(results, "X402-06"), /plan/); + assert.equal(recorder.signed.length, 0); + }); + + it("a payee changed after the plan is refused even without a pin", async () => { + const target = await wall({ amount: "100000" }); + const plan = await planX402Run({ network: NETWORK, endpoints: [{ name: "weather", target: target.url }] }); + target.accepts = [option({ amount: "100000", payTo: OTHER_PAY_TO })]; + const results = await run(target.url, { plan: plan.endpoints[0]! }); + refusedSetup(byId(results, "X402-06"), /plan/); + assert.equal(recorder.signed.length, 0); + }); + + it("refuses the whole run before anything is signed when its worst case is above the cap", async () => { + const weather = await wall({ amount: "1000000" }); + const summarize = await wall({ amount: "1000000" }); + const plan = await planX402Run({ + network: NETWORK, + endpoints: [ + { name: "weather", target: weather.url }, + { name: "summarize", target: summarize.url }, + ], + }); + assert.equal(formatUsd(plan.worstCaseUsd), "$7.00"); + assert.match(plan.refusal ?? "", /\$7\.00 \(weather \$3\.50, summarize \$3\.50\), above the \$5\.00 per run\. Nothing was signed\./); + assert.equal(recorder.signed.length, 0); + }); + + it("on a test network, an endpoint above $1 is refused in the plan and the others are still planned", async () => { + const cheap = await wall({ amount: "10000" }); + const dear = await wall({ amount: "2000000" }); + const plan = await planX402Run({ + network: NETWORK, + endpoints: [ + { name: "cheap", target: cheap.url }, + { name: "dear", target: dear.url }, + ], + }); + assert.equal(plan.refusal, undefined); + assert.equal(plan.endpoints[0]?.status, "planned"); + assert.equal(plan.endpoints[1]?.status, "refused"); + assert.match(plan.endpoints[1]?.reason ?? "", /\$2\.00.*\$1\.00/); + }); + + it("refuses a pinned run whose challenge has any exact option off the pin", async () => { + const target = await wall({ amount: "10000" }, { amount: "10000", payTo: OTHER_PAY_TO }); + const plan = await planX402Run({ + network: NETWORK, + pin: { payTo: PAY_TO, asset: USDC }, + endpoints: [{ name: "weather", target: target.url }], + }); + assert.equal(plan.endpoints[0]?.status, "refused"); + assert.match(plan.endpoints[0]?.reason ?? "", /payTo/); + }); + + it("plans nothing on a network that is not a test network", async () => { + await assert.rejects( + planX402Run({ network: "stellar:pubnet", endpoints: [{ name: "weather", target: "http://127.0.0.1:9/x" }] }), + /mainnet opt-in is not part of this version/, + ); + }); +}); + +describe("L2: the SDK signs only the option Wasit checked", () => { + it("hands the SDK one option: a first option it would drop never lets it sign the second", async () => { + const target = await wall( + { amount: "10000", extra: { name: "USDC", version: "2", paymentFlow: "not-a-known-flow" } }, + { amount: "20000" }, + ); + await run(target.url); + assert.ok( + recorder.signed.every((requirement) => requirement.amount !== "20000"), + `signed: ${recorder.signed.map((requirement) => requirement.amount).join(", ")}`, + ); + }); + + it("refuses X402-10 before signing when the chain's expired terms change the payee (review R6, K2)", async () => { + undo?.(); + undo = installRecordingChain(recorder, { expiredTerms: { maxTimeoutSeconds: 1, payTo: OTHER_PAY_TO } }); + const target = await wall({ amount: "10000" }); + const expired = byId(await run(target.url), "X402-10"); + assert.equal(expired.error?.kind, "setup", expired.detail); + assert.match(expired.detail, /would sign different payTo terms than the target's/); + assert.ok(recorder.signed.every((requirement) => requirement.payTo !== OTHER_PAY_TO), "signed for another payee"); + }); + + it("discards, unsent, a payload whose accepted option is not the one checked", async () => { + undo?.(); + undo = installRecordingChain(recorder, { swapPayTo: OTHER_PAY_TO }); + const target = await wall({ amount: "10000" }); + const budget = new RunBudget(); + const results = await run(target.url, { budget }); + const honest = byId(results, "X402-06"); + assert.equal(honest.error?.kind, "setup", honest.detail); + assert.match(honest.detail, /accepted/); + // It was signed: the message must not say otherwise (review R2). + assert.doesNotMatch(honest.detail, /Nothing was signed/); + assert.match(honest.detail, /It was signed and discarded; it was not sent\./); + assert.equal(target.paid, 0, "the payload signed for another payee was sent"); + // It was signed, so it stays charged. + assert.equal(formatUsd(budget.spentUsd), "$0.01"); + }); + + it("L3: with a pin, the SDK's own policy drops another payee before it signs", async () => { + undo?.(); + undo = installRecordingChain(recorder, { swapPayTo: OTHER_PAY_TO }); + const target = await wall({ amount: "10000" }); + const results = await run(target.url, { pin: { payTo: PAY_TO, asset: USDC } }); + assert.equal(byId(results, "X402-06").pass, false); + assert.equal(recorder.signed.length, 0); + assert.equal(target.paid, 0); + }); +}); diff --git a/packages/core/test/unit/payment-negatives.test.ts b/packages/core/test/unit/payment-negatives.test.ts index 1df4c5d..4403a1d 100644 --- a/packages/core/test/unit/payment-negatives.test.ts +++ b/packages/core/test/unit/payment-negatives.test.ts @@ -24,6 +24,7 @@ import { runX402PaymentChecks, underpaymentVerdict, } from "../../src/x402/simulator.js"; +import { planX402Run } from "../../src/x402/plan.js"; const NETWORK = "eip155:84532"; @@ -113,24 +114,32 @@ async function standIn(options: { } /** - * A JSON-RPC endpoint that answers every `eth_call` (the ERC-20 `balanceOf` - * X402-06 reads) with `balance`, or fails every request with 500. + * A JSON-RPC endpoint that says it serves `chainId` (the RPC identity check, + * D-023) and answers every `eth_call` (the ERC-20 `balanceOf` X402-06 reads) + * with `balance`, or fails every balance read with 500. `calls` counts the + * balance reads only. */ async function rpcStandIn( balance: bigint | "unreadable", + chainId = 84532n, ): Promise<{ url: string; calls: () => number; close: () => Promise }> { let calls = 0; const server = http.createServer((request, response) => { let body = ""; request.on("data", (chunk) => (body += chunk)); request.on("end", () => { + const { id, method } = JSON.parse(body) as { id: number; method: string }; + if (method === "eth_chainId") { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ jsonrpc: "2.0", id, result: `0x${chainId.toString(16)}` })); + return; + } calls++; if (balance === "unreadable") { response.writeHead(500); response.end(); return; } - const { id, method } = JSON.parse(body) as { id: number; method: string }; response.writeHead(200, { "content-type": "application/json" }); response.end( JSON.stringify( @@ -175,10 +184,12 @@ describe("the negative checks against a target that takes anything", () => { }); assert.deepEqual( results.map((result) => result.id), - ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"], + ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"], ); const r = byId(results); assert.match(r["X402-06"]!.detail, /no PAYMENT-RESPONSE header/); + // X402-11 needs a reject case, which this run has none of: skipped, nothing signed for it. + assert.equal(r["X402-11"]?.skipKind, "not-applicable"); for (const id of ["X402-07", "X402-08", "X402-09", "X402-10"]) { assert.equal(r[id]?.pass, false, id); assert.equal(r[id]?.skipped, undefined, id); @@ -312,46 +323,56 @@ describe("a refused valid payment", () => { describe("on Ethereum Sepolia", () => { // Circle's Sepolia USDC is not an SDK default asset, and the SDK client's - // spend controls refuse non-default assets unless they are allowed. - it("pays in Circle's Sepolia USDC, up to the SDK's own $1 cap", async () => { - for (const [amount, paid] of [ - ["10000", true], - ["1000001", false], - ] as const) { - const target = await standIn({ - mode: "refuse", - amount, - network: "eip155:11155111", - asset: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", - }); - try { - const r = byId( - await runX402PaymentChecks({ - target: target.url, - network: "eip155:11155111", - payerSecretKey: generatePrivateKey(), - rpcUrl: funded.url, - }), - ); - assert.equal(target.received.length, paid ? 1 : 0, amount); - if (paid) assert.match(r["X402-06"]?.detail ?? "", /got 402/); - else { - assert.equal(r["X402-06"]?.error?.kind, "setup"); - assert.match(r["X402-06"]?.detail ?? "", /asks for 1000001 base units .* more than the \$1 a payment/); + // spend controls refuse non-default assets unless they are allowed. Wasit's + // own cap (L2) refuses above $1 first, before the SDK's (L3) is reached. + it("pays in Circle's Sepolia USDC, up to the $1 cap", async () => { + const sepolia = await rpcStandIn(10n ** 12n, 11155111n); + try { + for (const [amount, paid] of [ + ["10000", true], + ["1000001", false], + ] as const) { + const target = await standIn({ + mode: "refuse", + amount, + network: "eip155:11155111", + asset: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", + }); + try { + const r = byId( + await runX402PaymentChecks({ + target: target.url, + network: "eip155:11155111", + payerSecretKey: generatePrivateKey(), + rpcUrl: sepolia.url, + }), + ); + assert.equal(target.received.length, paid ? 1 : 0, amount); + if (paid) assert.match(r["X402-06"]?.detail ?? "", /got 402/); + else { + assert.equal(r["X402-06"]?.error?.kind, "setup"); + assert.match( + r["X402-06"]?.detail ?? "", + /X402-06 would sign 1000001 base units of USDC \(\$1\.000001\), above the \$1\.00 per payment fixed in Wasit\. .*Nothing was signed\./, + ); + } + } finally { + await target.close(); } - } finally { - await target.close(); } + } finally { + await sepolia.close(); } }); }); -describe("a target the SDK client's spend controls refuse", () => { - // Not the target's fault, and nothing is sent: no verdict, saying why. +describe("a target the guard refuses before the SDK client's spend controls", () => { + // Not the target's fault, and nothing is sent: no verdict, saying why. L2 + // refuses first; the SDK's own controls (L3) stay behind it. it("is a setup error on a price above $1, or on an asset the client does not pay in", async () => { for (const [label, options, reason] of [ - ["above $1", { amount: "1000001" }, /more than the \$1 a payment the official x402 client pays by default/], - ["other asset", { asset: "0x0000000000000000000000000000000000000Bad" }, /not an asset the official x402 client pays in by default/], + ["above $1", { amount: "1000001" }, /above the \$1\.00 per payment fixed in Wasit/], + ["other asset", { asset: "0x0000000000000000000000000000000000000Bad" }, /an asset Wasit does not value in US dollars/], ] as const) { const target = await standIn({ mode: "accept", ...options }); try { @@ -452,6 +473,34 @@ describe("when a negative check has nothing to test", () => { }); }); +describe("when a negative check has nothing to test, under the plan of wasit run", () => { + it("skips X402-09 at a 1-unit price, as without a plan, and fetches nothing for it (review R3)", async () => { + const target = await standIn({ mode: "accept", amount: "1" }); + try { + const plan = await planX402Run({ network: NETWORK, endpoints: [{ name: "paid", target: target.url }] }); + const entry = plan.endpoints[0]!; + assert.equal(entry.status, "planned", entry.reason ?? ""); + assert.ok(!entry.signatures.some((signature) => signature.check === "X402-09"), "the plan has no X402-09 signature"); + const r = byId( + await runX402PaymentChecks({ + target: target.url, + network: NETWORK, + payerSecretKey: generatePrivateKey(), + rpcUrl: funded.url, + plan: entry, + }), + ); + assert.equal(r["X402-09"]?.error, undefined, r["X402-09"]?.detail); + assert.equal(r["X402-09"]?.skipped, true, r["X402-09"]?.detail); + assert.match(r["X402-09"]?.skipReason ?? "", /1 base unit/); + // honest, replay, corrupted, expired: no underpayment was sent. + assert.equal(target.received.length, 4); + } finally { + await target.close(); + } + }); +}); + describe("the verdicts", () => { it("pass a refusal and fail a 2xx, with a fix only on the failure", () => { for (const verdict of [replayVerdict, expiredVerdict, (s: number) => underpaymentVerdict(s, 5000n, 10000n)]) { diff --git a/packages/core/test/unit/read-only-tier.test.ts b/packages/core/test/unit/read-only-tier.test.ts index 0a83405..0dd8ef0 100644 --- a/packages/core/test/unit/read-only-tier.test.ts +++ b/packages/core/test/unit/read-only-tier.test.ts @@ -31,16 +31,16 @@ function fail(id: string): CheckResult { return { id, name: id, pass: false, detail: "wrong", hint: "fix it" }; } const CHALLENGE = ["X402-01", "X402-02", "X402-03", "X402-04", "X402-05"]; -const PAYMENT = ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]; +const PAYMENT = ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"]; function v1Results(): CheckResult[] { return [pass("X402-01"), ...CHALLENGE.slice(1).map((id) => skipped(id, id, "x402 v1", "unsupported"))]; } describe("skippedPaymentChecks", () => { - it("lists X402-06..10 for x402, each a SKIP of the kind it was given, named from the catalogue", () => { + it("lists X402-06..11 for x402, each a SKIP of the kind it was given, named from the catalogue", () => { const checks = skippedPaymentChecks("x402", "read-only"); - assert.deepEqual(checks.map((check) => check.id), ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]); + assert.deepEqual(checks.map((check) => check.id), ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"]); for (const check of checks) { assert.equal(checkStatus(check), "SKIP", check.id); assert.equal(check.skipKind, "read-only", check.id); diff --git a/packages/core/test/unit/rejected-request.test.ts b/packages/core/test/unit/rejected-request.test.ts new file mode 100644 index 0000000..bd6f247 --- /dev/null +++ b/packages/core/test/unit/rejected-request.test.ts @@ -0,0 +1,729 @@ +/** + * X402-11, "Rejected Request Not Settled" (spec B7 as D-032 changed it, with + * Najmi's reading of the 300 s limit, 2026-11-16). Written before the code + * (CONTEXT rule 3). + * + * Wasit sends a valid payment with a request the config declares invalid, then + * reads the chain: the nonce of that payment's authorization must still be + * unused after its expiration ledger has passed, read in the same call as + * X402-06's nonce, which must be found (the control). The payer's balance and + * the transfer events are second readings; when they disagree with the nonce, + * there is no verdict. Nothing is signed when the check cannot reach a + * verdict anyway: no reject case, a service that refuses before asking for + * payment, a lifetime above 300 s, a chain it cannot read, a control it cannot + * find. + * + * Offline: a recording chain whose payloads carry a nonce and an expiration + * ledger, a ledger that advances one ledger a read, and a paywall with the + * three modes of B7. + */ + +import assert from "node:assert/strict"; +import { afterEach, beforeEach, describe, it } from "node:test"; + +import type { CheckResult } from "../../src/check.js"; +import { setRpcIdentityTransportForTesting } from "../../src/guard/rpc-identity.js"; +import { setPaymentChainsForTesting } from "../../src/x402/chains/index.js"; +import { planX402Run } from "../../src/x402/plan.js"; +import { + REJECTED_REQUEST_HARD_STOP_MS, + REJECTED_REQUEST_MAX_LIFETIME_SECONDS, + REJECTED_REQUEST_MIN_LIFETIME_SECONDS, + rejectRequestShape, + rejectedRequestHardStopMs, + rejectedRequestVerdict, + setRejectedRequestHardStopForTesting, + watchAuthorization, +} from "../../src/x402/rejected-request.js"; +import { X402_PAYMENT_CHECK_IDS, runX402PaymentChecks } from "../../src/x402/simulator.js"; +import { + fakeLedger, + ledgerChain, + rejectPaywall, + type FakeLedger, + type InvalidMode, + type LedgerChainOptions, + type RejectPaywall, + type RejectPaywallOptions, +} from "../support/authorization-ledger.js"; +import { NETWORK, PAY_TO, option, type Recorder } from "../support/recording-chain.js"; + +const REJECT = { headers: { "x-invalid": "1" }, note: "the marker header must be refused" }; + +let recorder: Recorder; +let ledger: FakeLedger; +const walls: RejectPaywall[] = []; + +function install(options: LedgerChainOptions = {}): void { + setPaymentChainsForTesting([ledgerChain(recorder, ledger, options)]); + setRpcIdentityTransportForTesting(async (_url, method) => (method === "eth_chainId" ? "0x14a34" : undefined)); +} + +beforeEach(() => { + recorder = { signed: [] }; + ledger = fakeLedger(); + install(); +}); + +afterEach(async () => { + setPaymentChainsForTesting(undefined); + setRpcIdentityTransportForTesting(undefined); + setRejectedRequestHardStopForTesting(undefined); + await Promise.all(walls.splice(0).map((wall) => wall.close())); +}); + +async function wall(mode: InvalidMode, extra: Partial = {}, maxTimeoutSeconds = 60): Promise { + const created = await rejectPaywall(ledger, [{ ...option({ amount: "10000" }), maxTimeoutSeconds }], { mode, ...extra }); + walls.push(created); + return created; +} + +function byId(results: readonly CheckResult[], id: string): CheckResult { + const found = results.find((result) => result.id === id); + assert.ok(found, `no ${id} in ${results.map((result) => result.id).join(", ")}`); + return found; +} + +const run = (target: string, extra: Partial[0]> = {}) => + runX402PaymentChecks({ target, network: NETWORK, payerSecretKey: "test-payer-key", reject: REJECT, ...extra }); + +/** The X402-06..10 signatures of a conformant service: four, X402-08 resends X402-06's. */ +const BEFORE_X402_11 = 4; + +describe("X402-11 in the payment checks", () => { + it("is the last payment check, after X402-10", () => { + assert.deepEqual(X402_PAYMENT_CHECK_IDS, ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"]); + }); + + it("PASS: the service refuses without settling; the nonce is unused past its expiry; the control is found", async () => { + const target = await wall("refuse"); + const results = await run(target.url); + const result = byId(results, "X402-11"); + assert.equal(result.pass, true, result.detail); + assert.equal(result.error, undefined); + assert.match(result.detail, /refused \(HTTP 400/); + assert.match(result.detail, /not taken/); + assert.match(result.detail, /expired at ledger \d+ unused/); + // It signed one payment, for the advertised terms exactly (no shortened lifetime). + assert.equal(recorder.signed.length, BEFORE_X402_11 + 1); + const signed = recorder.signed.at(-1)!; + assert.equal(signed.amount, "10000"); + assert.equal(signed.maxTimeoutSeconds, 60); + assert.equal(signed.payTo, PAY_TO); + // The invalid request was the one sent with it. + assert.equal(target.invalid.length, 1); + assert.equal(target.invalid[0]!.headers["x-invalid"], "1"); + for (const id of ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]) { + assert.equal(byId(results, id).pass, true, `${id}: ${byId(results, id).detail}`); + } + }); + + it("FAIL: the service settles the payment and then refuses the request; the transaction is named", async () => { + const target = await wall("settle-then-refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.pass, false); + assert.equal(result.error, undefined, result.detail); + assert.equal(result.skipped, undefined); + assert.match(result.detail, /refused .* and the payment was taken/); + assert.match(result.detail, /tx-nonce-5/); + assert.ok(result.hint !== undefined && /settle/i.test(result.hint)); + }); + + it("FAIL: the service serves the request the config declares invalid, and says whether it settled", async () => { + const target = await wall("serve"); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.pass, false); + assert.equal(result.error, undefined, result.detail); + assert.match(result.detail, /declares invalid was served \(HTTP 200\)/); + assert.match(result.detail, /taken/); + }); + + it("says in one line, before the wait, what it waits for and for how long, with no text from the service", async () => { + const target = await wall("refuse"); + const lines: string[] = []; + await run(target.url, { onProgress: (line) => lines.push(line) }); + assert.equal(lines.length, 1); + assert.match(lines[0]!, /^X402-11: the payment was sent with the request the service must refuse \(HTTP 400\); reading the chain once a ledger until its authorization expires at ledger \d+, for at most 360 s\.$/); + assert.doesNotMatch(lines[0]!, /invalid request/); + }); + + it("a refusal with another 4xx or a 5xx counts as a refusal", async () => { + for (const refusalStatus of [422, 500]) { + const target = await wall("refuse", { refusalStatus }); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.pass, true, `${refusalStatus}: ${result.detail}`); + assert.match(result.detail, new RegExp(`HTTP ${refusalStatus}`)); + } + }); +}); + +describe("X402-11 signs nothing when it cannot reach a verdict", () => { + it("SKIP without a reject case in the config", async () => { + const target = await wall("refuse"); + const result = byId(await run(target.url, { reject: undefined }), "X402-11"); + assert.equal(result.skipped, true); + assert.equal(result.skipKind, "not-applicable"); + assert.match(result.skipReason ?? "", /reject/); + assert.equal(recorder.signed.length, BEFORE_X402_11); + }); + + it("SKIP when the service refuses the invalid request before asking for payment", async () => { + const target = await wall("refuse", { refuseUnpaidInvalid: true }); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.skipped, true); + assert.equal(result.skipKind, "not-applicable"); + assert.match(result.skipReason ?? "", /before any payment is asked \(HTTP 400\)/); + assert.equal(recorder.signed.length, BEFORE_X402_11); + assert.equal(target.invalid.length, 0); + }); + + it(`SKIP before signing when the advertised lifetime is above ${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} s`, async () => { + assert.equal(REJECTED_REQUEST_MAX_LIFETIME_SECONDS, 300); + const target = await wall("refuse", {}, 301); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.skipped, true); + assert.match(result.skipReason ?? "", /301 seconds/); + assert.match(result.skipReason ?? "", /Nothing was signed/); + assert.equal(recorder.signed.length, BEFORE_X402_11); + assert.equal(target.invalid.length, 0); + }); + + it("SKIP before signing when the service raises the lifetime above 300 s on the read it is paid from (review R1)", async () => { + // The first unpaid read of the reject request says 60 s; the read the + // payment is signed from says 100000 s. + const target = await wall("refuse", { invalidUnpaidLifetimes: [60, 100_000] }); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.skipped, true, result.detail); + assert.match(result.skipReason ?? "", /100000 seconds/); + assert.match(result.skipReason ?? "", /Nothing was signed/); + assert.equal(recorder.signed.length, BEFORE_X402_11, "nothing signed for X402-11"); + assert.ok(recorder.signed.every((signed) => signed.maxTimeoutSeconds <= REJECTED_REQUEST_MAX_LIFETIME_SECONDS)); + assert.equal(target.invalid.length, 0, "nothing sent with the invalid request"); + }); + + it("not sent when the signed authorization outlives 300 s, whatever the client was asked (review R1)", async () => { + install({ extraExpiryLedgers: 100 }); + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.notEqual(result.pass, true); + assert.ok(result.error !== undefined, `no verdict expected: ${result.detail}`); + assert.match(result.error.message, /it was not sent/); + assert.doesNotMatch(result.error.message, /Nothing was signed/); + assert.equal(recorder.signed.length, BEFORE_X402_11 + 1, "signed once, then discarded"); + assert.equal(target.invalid.length, 0, "nothing sent with the invalid request"); + }); + + it(`SKIP before signing when the advertised lifetime is below ${REJECTED_REQUEST_MIN_LIFETIME_SECONDS} s (screening S-1)`, async () => { + assert.equal(REJECTED_REQUEST_MIN_LIFETIME_SECONDS, 30); + const target = await wall("refuse", {}, 29); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.skipped, true, result.detail); + assert.match(result.skipReason ?? "", /29 seconds/); + assert.match(result.skipReason ?? "", /shorter than the 30 seconds/); + assert.match(result.skipReason ?? "", /Nothing was signed/); + assert.equal(recorder.signed.length, BEFORE_X402_11); + assert.equal(target.invalid.length, 0); + }); + + it("a lifetime of exactly 30 s is waited out", async () => { + const target = await wall("refuse", {}, 30); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.pass, true, result.detail); + assert.equal(recorder.signed.at(-1)!.maxTimeoutSeconds, 30); + }); + + it("SKIP before signing when the service lowers the lifetime below 30 s on the read it is paid from (screening S-1)", async () => { + const target = await wall("refuse", { invalidUnpaidLifetimes: [60, 10] }); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.skipped, true, result.detail); + assert.match(result.skipReason ?? "", /10 seconds/); + assert.match(result.skipReason ?? "", /Nothing was signed/); + assert.equal(recorder.signed.length, BEFORE_X402_11); + assert.equal(target.invalid.length, 0); + }); + + it("not sent when fewer than 3 ledgers of validity are left right before sending (screening S-1)", async () => { + install({ extraExpiryLedgers: -10 }); + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.notEqual(result.pass, true); + assert.ok(result.error !== undefined, `no verdict expected: ${result.detail}`); + assert.match(result.error.message, /too soon/); + assert.match(result.error.message, /it was not sent/); + assert.equal(recorder.signed.length, BEFORE_X402_11 + 1, "signed once, then discarded"); + assert.equal(target.invalid.length, 0); + }); + + it("a lifetime of exactly 300 s is waited out", async () => { + const target = await wall("refuse", {}, 300); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.pass, true, result.detail); + assert.equal(recorder.signed.at(-1)!.maxTimeoutSeconds, 300); + }); + + it("SKIP on a chain X402-11 cannot read, without making the endpoint unsupported", async () => { + install({ withoutWatch: true }); + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.skipped, true); + assert.notEqual(result.skipKind, "unsupported"); + assert.equal(recorder.signed.length, BEFORE_X402_11); + }); + + it("SKIP when X402-06 did not pass: its nonce cannot be the control", async () => { + install({ settlementFails: true }); + const target = await wall("refuse"); + const results = await run(target.url); + assert.equal(byId(results, "X402-06").pass, false); + const result = byId(results, "X402-11"); + assert.equal(result.skipped, true); + assert.equal(result.skipKind, "dependency"); + assert.equal(recorder.signed.length, BEFORE_X402_11); + }); + + it("no verdict, nothing signed, when the chain does not return X402-06's used nonce before signing", async () => { + ledger.hidden.add("nonce-1"); + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.error?.kind, "setup", result.detail); + assert.match(result.detail, /X402-06/); + assert.match(result.detail, /Nothing was signed/); + assert.equal(recorder.signed.length, BEFORE_X402_11); + assert.equal(target.invalid.length, 0); + }); + + it("no verdict, nothing signed, when the payer's balance cannot be read before signing", async () => { + ledger.balanceUnreadable = true; + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.error?.kind, "setup", result.detail); + assert.match(result.detail, /balance/); + assert.equal(recorder.signed.length, BEFORE_X402_11); + }); + + it("refused by L2 when the plan has no signature for X402-11", async () => { + const target = await wall("refuse"); + const plan = await planX402Run({ network: NETWORK, endpoints: [{ name: "paid", target: target.url }] }); + const entry = plan.endpoints[0]!; + assert.ok(!entry.signatures.some((signature) => signature.check === "X402-11")); + const result = byId(await run(target.url, { plan: entry }), "X402-11"); + assert.equal(result.error?.kind, "setup", result.detail); + assert.match(result.detail, /plan/); + assert.equal(recorder.signed.length, BEFORE_X402_11); + }); +}); + +describe("X402-11 does not send a payment it cannot tell apart (review R6)", () => { + const X402_11 = BEFORE_X402_11 + 1; + + it("not sent when its authorization carries X402-06's nonce (K3)", async () => { + install({ alterPayload: (count) => (count === X402_11 ? { nonce: "nonce-1" } : undefined) }); + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.match(result.error?.message ?? "", /carries X402-06's nonce/, result.detail); + assert.equal(target.invalid.length, 0); + }); + + it("not sent when the chain records its authorization as used before it was sent (K4)", async () => { + install({ alterPayload: (count) => (count === X402_11 ? { nonce: "nonce-early" } : undefined) }); + ledger.used.set("nonce-early", 999); + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.match(result.error?.message ?? "", /used before it was sent/, result.detail); + assert.equal(target.invalid.length, 0); + }); + + it("not sent when the read right before sending leaves out X402-06's authorization (K5)", async () => { + // Read 1 is before signing and finds the control; read 2, right before sending, does not. + ledger.onRead = (reads) => { + if (reads === 2) ledger.hidden.add("nonce-1"); + }; + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.match(result.error?.message ?? "", /leaves out X402-06's authorization, so this payment was not sent/, result.detail); + assert.equal(target.invalid.length, 0); + }); + + it("not sent when its authorization is signed by another address than the run's payer (K15)", async () => { + install({ alterPayload: (count) => (count === X402_11 ? { payer: "GANOTHERPAYER" } : undefined) }); + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.match(result.error?.message ?? "", /signed by another address than this run's payer/, result.detail); + assert.equal(target.invalid.length, 0); + }); +}); + +describe("X402-11 gives no verdict when the chain readings disagree or stop", () => { + it("the nonce is used but no transfer of the price to payTo was recorded", async () => { + ledger.dropTransfers = true; + const target = await wall("settle-then-refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.error?.kind, "setup", result.detail); + assert.match(result.detail, /disagree/); + }); + + it("the nonce stays unused, but the payer's balance fell by the price during the watch", async () => { + const target = await wall("refuse"); + let dropped = false; + ledger.onRead = () => { + // After X402-11's payment is sent (its first watch read), money leaves the payer some other way. + if (target.invalid.length === 1 && !dropped) { + dropped = true; + ledger.balance -= 10000n; + } + }; + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.error?.kind, "setup", result.detail); + assert.match(result.detail, /disagree/); + }); + + it("the nonce stays unused, but a transfer of the price to payTo was recorded after the payment was sent", async () => { + const target = await wall("refuse"); + let pushed = false; + ledger.onRead = () => { + if (target.invalid.length === 1 && !pushed) { + pushed = true; + ledger.transfers.push({ amount: 10000n, reference: "tx-other", ledger: ledger.latest + 1, asset: option({ amount: "1" }).asset, from: "0x2222222222222222222222222222222222222222", to: PAY_TO }); + ledger.balance -= 10000n; + } + }; + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.error?.kind, "setup", result.detail); + assert.match(result.detail, /disagree/); + }); + + it("a late settlement of X402-09's half-price payment during the watch is not this payment: still a PASS", async () => { + const target = await wall("refuse"); + let pushed = false; + ledger.onRead = () => { + if (target.invalid.length === 1 && !pushed) { + pushed = true; + ledger.transfers.push({ amount: 5000n, reference: "tx-half", ledger: ledger.latest + 1, asset: option({ amount: "1" }).asset, from: "0x2222222222222222222222222222222222222222", to: PAY_TO }); + ledger.balance -= 5000n; + } + }; + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.pass, true, result.detail); + }); + + it("a transfer of the same amount after the last ledger the watch read is not this payment: still a PASS", async () => { + const target = await wall("refuse"); + let pushed = false; + ledger.onRead = () => { + if (target.invalid.length === 1 && !pushed) { + pushed = true; + // Another run with the same payer, recorded far past this watch. + ledger.transfers.push({ amount: 10000n, reference: "tx-later", ledger: 999_999, asset: option({ amount: "1" }).asset, from: "0x2222222222222222222222222222222222222222", to: PAY_TO }); + } + }; + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.pass, true, result.detail); + }); + + it("the chain's answer leaves out X402-06's nonce during the watch: no verdict, never PASS", async () => { + const target = await wall("refuse"); + ledger.onRead = () => { + if (target.invalid.length === 1) ledger.hidden.add("nonce-1"); + }; + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.error?.kind, "setup", result.detail); + assert.match(result.detail, /X402-06/); + }); + + it("the chain cannot be read during the watch: no verdict on a refused request", async () => { + const target = await wall("refuse"); + ledger.onRead = () => { + if (target.invalid.length === 1) ledger.readError = new Error("rpc down"); + }; + const result = byId(await run(target.url), "X402-11"); + assert.notEqual(result.error, undefined, result.detail); + assert.equal(result.pass, false); + }); + + it("the chain's transfers cannot be read: a served request is still a FAIL, and says the settlement was not read", async () => { + ledger.transferError = new Error("events not served"); + const target = await wall("serve"); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.pass, false); + assert.equal(result.error, undefined, result.detail); + assert.match(result.detail, /served/); + assert.match(result.detail, /not read/); + }); + + it("SKIP when the authorization is still valid at the hard stop", async () => { + setRejectedRequestHardStopForTesting(60); + ledger.step = 0; + const target = await wall("refuse"); + const result = byId(await run(target.url), "X402-11"); + assert.equal(result.skipped, true, result.detail); + assert.match(result.skipReason ?? "", /still valid until ledger \d+/); + }); + + it(`the hard stop is ${REJECTED_REQUEST_HARD_STOP_MS / 1000} s, and a test cannot raise it`, () => { + assert.equal(REJECTED_REQUEST_HARD_STOP_MS, 360_000); + assert.equal(rejectedRequestHardStopMs(), 360_000); + setRejectedRequestHardStopForTesting(10 * 60_000); + assert.equal(rejectedRequestHardStopMs(), 360_000); + setRejectedRequestHardStopForTesting(5); + assert.equal(rejectedRequestHardStopMs(), 5); + }); +}); + +describe("watchAuthorization", () => { + const ours = { payer: "P", nonce: "2", expiresAt: 1010 }; + const control = { payer: "P", nonce: "1", expiresAt: 990 }; + + /** A watch whose reads answer from `latests` in turn, ours never used, the control always found. */ + function scripted(latests: number[], used: (latest: number) => number | undefined = () => undefined) { + let index = 0; + const reads: number[] = []; + return { + reads, + watch: { + unit: "ledger", + unitMs: 1, + unitSeconds: 5, + decode: () => ours, + async read() { + const latest = latests[Math.min(index, latests.length - 1)]!; + index += 1; + reads.push(latest); + return { latest, used: [used(latest), 995] }; + }, + async transfers() { + return { latest: 0, transfers: [] }; + }, + }, + }; + } + + it("needs a read ABOVE the expiration ledger: at the expiration ledger it keeps reading", async () => { + const { watch, reads } = scripted([1009, 1010, 1011]); + const outcome = await watchAuthorization({ watch, network: NETWORK, rpcUrl: "x", ours, control, sentAt: Date.now() }); + assert.deepEqual(outcome, { kind: "unused", latest: 1011 }); + assert.deepEqual(reads, [1009, 1010, 1011]); + }); + + it("ends as unread at the hard stop when a read never answers (review R5)", { timeout: 5000 }, async () => { + setRejectedRequestHardStopForTesting(200); + const watch = { + unit: "ledger", + unitMs: 1, + unitSeconds: 5, + decode: () => ours, + read: () => new Promise(() => undefined), + async transfers() { + return { latest: 0, transfers: [] }; + }, + }; + const started = Date.now(); + const outcome = await watchAuthorization({ watch, network: NETWORK, rpcUrl: "x", ours, control, sentAt: started }); + assert.equal(outcome.kind, "unread"); + assert.match(outcome.kind === "unread" ? outcome.why : "", /did not answer/); + assert.ok(Date.now() - started < 2000, "the watch waited past its hard stop for a read"); + }); + + it("stops at once when the authorization is found used", async () => { + const { watch, reads } = scripted([1003, 1004], (latest) => (latest === 1004 ? 1004 : undefined)); + const outcome = await watchAuthorization({ watch, network: NETWORK, rpcUrl: "x", ours, control, sentAt: Date.now() }); + assert.deepEqual(outcome, { kind: "used", ledger: 1004, latest: 1004 }); + assert.equal(reads.length, 2); + }); + + it("counts the hard stop from when the payment was sent", async () => { + setRejectedRequestHardStopForTesting(1000); + const { watch } = scripted([1003]); + let now = 10_000; + const outcome = await watchAuthorization({ + watch, + network: NETWORK, + rpcUrl: "x", + ours, + control, + sentAt: 9_500, + now: () => now, + sleep: async (ms) => { + now += ms; + }, + }); + assert.deepEqual(outcome, { kind: "still-valid", latest: 1003 }); + assert.ok(now >= 10_500 && now <= 10_501, String(now)); + }); +}); + +describe("the reject request", () => { + it("is the endpoint's request with the reject case over it: method, headers merged, body replaced", () => { + const shape = rejectRequestShape( + { method: "POST", headers: { "x-tenant": "demo" }, body: '{"text":"hello"}' }, + { headers: { "x-lang": "xx" }, body: '{"text":""}' }, + ); + assert.deepEqual(shape, { method: "POST", headers: { "x-tenant": "demo", "x-lang": "xx" }, body: '{"text":""}' }); + }); + + it("keeps the endpoint's body when the reject case changes only a header", () => { + const shape = rejectRequestShape({ method: "POST", body: '{"text":"hello"}' }, { headers: { "x-lang": "xx" } }); + assert.equal(shape.body, '{"text":"hello"}'); + }); + + it("drops the endpoint's body when the reject case asks for a method without one", () => { + const shape = rejectRequestShape({ method: "POST", body: '{"text":"hello"}' }, { method: "GET", headers: {} }); + assert.equal(shape.method, "GET"); + assert.equal(shape.body, undefined); + }); + + it("is what reaches the service: the reject body and the endpoint's own headers", async () => { + const target = await wall("refuse"); + await run(target.url, { + method: "POST", + headers: { "x-tenant": "demo" }, + body: '{"text":"hello"}', + reject: { headers: { "x-invalid": "1" }, body: '{"text":""}' }, + }); + assert.equal(target.invalid.length, 1); + assert.equal(target.invalid[0]!.method, "POST"); + assert.equal(target.invalid[0]!.body, '{"text":""}'); + assert.equal(target.invalid[0]!.headers["x-tenant"], "demo"); + }); +}); + +describe("the plan (L1) counts X402-11", () => { + it("plans one more signature at the price when the endpoint has a reject case", async () => { + const target = await wall("refuse"); + const plan = await planX402Run({ + network: NETWORK, + endpoints: [ + { name: "with", target: target.url, reject: REJECT }, + { name: "without", target: target.url }, + ], + }); + const [withReject, without] = plan.endpoints; + assert.deepEqual( + withReject!.signatures.map((signature) => [signature.check, signature.amount]), + [["X402-06", 10000n], ["X402-07", 10000n], ["X402-09", 5000n], ["X402-10", 10000n], ["X402-11", 10000n]], + ); + assert.equal(withReject!.worstCase, 45000n); + assert.equal(without!.worstCase, 35000n); + }); + + it("does not plan it when the lifetime is above 300 s, or on a chain X402-11 cannot read", async () => { + const long = await wall("refuse", {}, 301); + const longPlan = await planX402Run({ network: NETWORK, endpoints: [{ name: "long", target: long.url, reject: REJECT }] }); + assert.ok(!longPlan.endpoints[0]!.signatures.some((signature) => signature.check === "X402-11")); + + const short = await wall("refuse", {}, 29); + const shortPlan = await planX402Run({ network: NETWORK, endpoints: [{ name: "short", target: short.url, reject: REJECT }] }); + assert.ok(!shortPlan.endpoints[0]!.signatures.some((signature) => signature.check === "X402-11"), "planned below 30 s"); + + install({ withoutWatch: true }); + const target = await wall("refuse"); + const plan = await planX402Run({ network: NETWORK, endpoints: [{ name: "paid", target: target.url, reject: REJECT }] }); + assert.ok(!plan.endpoints[0]!.signatures.some((signature) => signature.check === "X402-11")); + }); + + it("a $1 price with a reject case plans $4.50, within the $5 cap", async () => { + const target = await rejectPaywall(ledger, [option({ amount: "1000000" })], { mode: "refuse" }); + walls.push(target); + const plan = await planX402Run({ network: NETWORK, endpoints: [{ name: "paid", target: target.url, reject: REJECT }] }); + assert.equal(plan.endpoints[0]!.worstCase, 4_500_000n); + assert.equal(plan.refusal, undefined); + }); + + it("with the plan, a full run signs exactly what was planned", async () => { + const target = await wall("refuse"); + const plan = await planX402Run({ network: NETWORK, endpoints: [{ name: "paid", target: target.url, reject: REJECT }] }); + const entry = plan.endpoints[0]!; + const result = byId(await run(target.url, { plan: entry }), "X402-11"); + assert.equal(result.pass, true, result.detail); + const total = recorder.signed.reduce((sum, requirement) => sum + BigInt(requirement.amount), 0n); + assert.equal(total, entry.worstCase); + }); +}); + +describe("rejectedRequestVerdict", () => { + const base = { amount: 10000n, expiresAt: 1012, unit: "ledger" } as const; + const agreeNotTaken = { balance: { before: 50000n, after: 50000n }, transfers: [] }; + const agreeTaken = { balance: { before: 50000n, after: 40000n }, transfers: [{ reference: "tx-a", ledger: 1003 }] }; + + it("PASS: refused, unused past the expiry, readings agree", () => { + const result = rejectedRequestVerdict({ ...base, status: 400, watch: { kind: "unused", latest: 1013 }, ...agreeNotTaken }); + assert.equal(result.pass, true); + assert.equal(result.id, "X402-11"); + assert.equal(result.name, "Rejected Request Not Settled"); + }); + + it("FAIL: refused, used, readings agree; the transaction is named", () => { + const result = rejectedRequestVerdict({ ...base, status: 402, reason: "invalid", watch: { kind: "used", ledger: 1003, latest: 1004 }, ...agreeTaken }); + assert.equal(result.pass, false); + assert.equal(result.error, undefined); + assert.match(result.detail, /tx-a/); + assert.match(result.detail, /HTTP 402: invalid/); + }); + + it("no verdict: used, but the balance did not fall by the price", () => { + const result = rejectedRequestVerdict({ + ...base, + status: 400, + watch: { kind: "used", ledger: 1003, latest: 1004 }, + balance: { before: 50000n, after: 45000n }, + transfers: [{ reference: "tx-a", ledger: 1003 }], + }); + assert.equal(result.error?.kind, "setup"); + }); + + it("no verdict: unused, but a transfer of the price was recorded", () => { + const result = rejectedRequestVerdict({ + ...base, + status: 400, + watch: { kind: "unused", latest: 1013 }, + balance: { before: 50000n, after: 50000n }, + transfers: [{ reference: "tx-b", ledger: 1005 }], + }); + assert.equal(result.error?.kind, "setup"); + }); + + it("no verdict: a refused request whose chain read did not finish", () => { + const result = rejectedRequestVerdict({ ...base, status: 400, watch: { kind: "unread", why: "rpc down" } }); + assert.equal(result.error?.kind, "setup"); + assert.match(result.detail, /rpc down/); + }); + + it("no verdict: the second readings are missing", () => { + const result = rejectedRequestVerdict({ ...base, status: 400, watch: { kind: "unused", latest: 1013 } }); + assert.equal(result.error?.kind, "setup"); + }); + + it("SKIP: refused and still valid when the watch stopped", () => { + const result = rejectedRequestVerdict({ ...base, status: 400, watch: { kind: "still-valid", latest: 1005 } }); + assert.equal(result.skipped, true); + assert.match(result.skipReason ?? "", /not settled by ledger 1005; still valid until ledger 1012/); + }); + + it("FAIL whenever the invalid request was served, whatever the chain shows", () => { + for (const watch of [ + { kind: "used", ledger: 1003, latest: 1004 }, + { kind: "unused", latest: 1013 }, + { kind: "still-valid", latest: 1005 }, + { kind: "unread", why: "rpc down" }, + ] as const) { + const result = rejectedRequestVerdict({ ...base, status: 200, watch, ...(watch.kind === "used" ? agreeTaken : agreeNotTaken) }); + assert.equal(result.pass, false, watch.kind); + assert.equal(result.error, undefined, watch.kind); + assert.equal(result.skipped, undefined, watch.kind); + assert.match(result.detail, /served \(HTTP 200\)/); + } + }); +}); + +describe("X402-06's reference, for the payment proof of the PR comment (2026-11-20)", () => { + it("carries the settlement it read back from the chain on a PASS, and none on a FAIL", async () => { + const target = await wall("refuse"); + const honest = byId(await run(target.url), "X402-06"); + assert.equal(honest.pass, true, honest.detail); + assert.equal(honest.reference, "tx-nonce-1"); + install({ settlementFails: true }); + const other = await wall("refuse"); + const failed = byId(await run(other.url), "X402-06"); + assert.equal(failed.pass, false, failed.detail); + assert.equal(failed.reference, undefined); + }); +}); diff --git a/packages/core/test/unit/report.test.ts b/packages/core/test/unit/report.test.ts index 58241d1..5d979fc 100644 --- a/packages/core/test/unit/report.test.ts +++ b/packages/core/test/unit/report.test.ts @@ -30,14 +30,14 @@ function fail(id: string): CheckResult { return { id, name: id, pass: false, detail: "wrong", hint: "fix it" }; } const CHALLENGE = ["X402-01", "X402-02", "X402-03", "X402-04", "X402-05"]; -const PAYMENT = ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]; +const PAYMENT = ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"]; function v1Results(): CheckResult[] { return [pass("X402-01"), ...CHALLENGE.slice(1).map((id) => skipped(id, id, "x402 v1", "unsupported"))]; } describe("checkGroup", () => { - it("puts X402-01..05 in challenge and X402-06..10 in payment", () => { + it("puts X402-01..05 in challenge and X402-06..11 in payment", () => { for (const id of CHALLENGE) assert.equal(checkGroup(id, "x402"), "challenge", id); for (const id of PAYMENT) assert.equal(checkGroup(id, "x402"), "payment", id); }); @@ -114,9 +114,9 @@ describe("buildEndpointReport", () => { }); assert.equal(report.outcome, "conformant"); assert.deepEqual(report.groups["challenge"], { passed: 5, failed: 0, errored: 0, skipped: 0 }); - assert.deepEqual(report.groups["payment"], { passed: 0, failed: 0, errored: 0, skipped: 5 }); + assert.deepEqual(report.groups["payment"], { passed: 0, failed: 0, errored: 0, skipped: 6 }); assert.equal(report.groups["mppCharge"], undefined); - assert.equal(report.results.length, 10); + assert.equal(report.results.length, 11); assert.equal(report.results[5]?.skipKind, "read-only"); }); diff --git a/packages/core/test/unit/rpc-identity.test.ts b/packages/core/test/unit/rpc-identity.test.ts new file mode 100644 index 0000000..73b5138 --- /dev/null +++ b/packages/core/test/unit/rpc-identity.test.ts @@ -0,0 +1,253 @@ +/** + * The RPC identity check (D-032, D-023a+b): before a run signs anything or + * reads a settlement, the RPC it was given must say it serves the run's + * network. Stellar: `getNetwork`'s passphrase; EVM: `eth_chainId`; Solana: the + * genesis hash, whose first 32 characters are the CAIP-2 reference. A mismatch, + * no answer, or an answer that cannot be read refuses the run before any + * request reaches the target. + * + * Why: a run labelled `stellar:testnet` pointed at a mainnet RPC signed a + * mainnet-valid channel commitment in 0.7.0 (`689bdc0` fixed that case by + * decoding); a wrong RPC also makes every settlement read come from the wrong + * chain. Offline: JSON-RPC stand-ins on loopback. + */ + +import assert from "node:assert/strict"; +import http from "node:http"; +import { afterEach, describe, it } from "node:test"; + +import { Keypair, Networks } from "@stellar/stellar-sdk"; +import { generatePrivateKey } from "viem/accounts"; + +import { ConfigurationError, classifyCheckError } from "../../src/errors.js"; +import { + RpcIdentityError, + assertRpcServesNetwork, + setRpcIdentityTransportForTesting, +} from "../../src/guard/rpc-identity.js"; +import { runMppChargeChecks } from "../../src/mpp/charge.js"; +import { runMppChannelSuite } from "../../src/mpp/suite.js"; +import { runX402PaymentChecks } from "../../src/x402/simulator.js"; + +const SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"; +const DEVNET_GENESIS = "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG"; +const MAINNET_GENESIS = "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d"; + +interface Rpc { + readonly url: string; + readonly methods: string[]; + readonly close: () => Promise; +} + +const open: Array<{ close: () => Promise }> = []; + +afterEach(async () => { + setRpcIdentityTransportForTesting(undefined); + await Promise.all(open.splice(0).map((server) => server.close())); +}); + +/** A JSON-RPC stand-in: `answer(method)` gives the result, `undefined` gives a JSON-RPC error. */ +async function rpc(answer: (method: string) => unknown, raw?: (response: http.ServerResponse) => boolean): Promise { + const methods: string[] = []; + const server = http.createServer((request, response) => { + let body = ""; + request.on("data", (chunk) => (body += chunk)); + request.on("end", () => { + if (raw?.(response)) return; + const { id, method } = JSON.parse(body) as { id: number; method: string }; + methods.push(method); + const result = answer(method); + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify( + result === undefined + ? { jsonrpc: "2.0", id, error: { code: -32601, message: "method not found" } } + : { jsonrpc: "2.0", id, result }, + ), + ); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + const created = { + url: `http://127.0.0.1:${port}/v1/secret-api-key-123`, + methods, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; + open.push(created); + return created; +} + +/** A target that only counts requests: the check must stop the run before any reaches it. */ +async function countingTarget(): Promise<{ url: string; requests: () => number }> { + let requests = 0; + const server = http.createServer((_request, response) => { + requests += 1; + response.writeHead(402); + response.end(); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + open.push({ + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }); + return { url: `http://127.0.0.1:${port}/paid`, requests: () => requests }; +} + +async function refused(promise: Promise): Promise { + try { + await promise; + } catch (error) { + assert.ok(error instanceof RpcIdentityError, `expected an RpcIdentityError, got ${String(error)}`); + return error; + } + return assert.fail("expected the RPC to be refused"); +} + +describe("assertRpcServesNetwork", () => { + it("passes a Stellar RPC whose passphrase is the run's network", async () => { + const node = await rpc((method) => (method === "getNetwork" ? { passphrase: Networks.TESTNET, protocolVersion: 30 } : undefined)); + await assertRpcServesNetwork("stellar:testnet", node.url); + assert.deepEqual(node.methods, ["getNetwork"]); + }); + + it("refuses a mainnet Stellar RPC on a testnet run, naming both networks and only the RPC's origin", async () => { + const node = await rpc(() => ({ passphrase: Networks.PUBLIC, protocolVersion: 29 })); + const error = await refused(assertRpcServesNetwork("stellar:testnet", node.url)); + assert.match(error.message, /stellar:pubnet/); + assert.match(error.message, /stellar:testnet/); + assert.match(error.message, /nothing was signed/); + assert.equal(error.message.includes("secret-api-key-123"), false, "the RPC path can hold an API key"); + assert.ok(error instanceof ConfigurationError); + assert.equal(classifyCheckError(error).kind, "configuration"); + }); + + it("refuses a Stellar RPC that names a passphrase Wasit does not know, without echoing it raw", async () => { + const node = await rpc(() => ({ passphrase: "Private network\u001b[31m ; 2026" })); + const error = await refused(assertRpcServesNetwork("stellar:testnet", node.url)); + assert.equal(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(error.message), false); + }); + + it("passes an EVM RPC whose chain id is the run's, and refuses another chain", async () => { + const sepolia = await rpc((method) => (method === "eth_chainId" ? "0x14a34" : undefined)); + await assertRpcServesNetwork("eip155:84532", sepolia.url); + const mainnet = await rpc(() => "0x2105"); + const error = await refused(assertRpcServesNetwork("eip155:84532", mainnet.url)); + assert.match(error.message, /eip155:8453\b/); + }); + + it("passes a Solana RPC whose genesis hash starts with the CAIP-2 reference, and refuses mainnet", async () => { + const devnet = await rpc((method) => (method === "getGenesisHash" ? DEVNET_GENESIS : undefined)); + await assertRpcServesNetwork(SOLANA_DEVNET, devnet.url); + const mainnet = await rpc(() => MAINNET_GENESIS); + await refused(assertRpcServesNetwork(SOLANA_DEVNET, mainnet.url)); + }); + + it("refuses when the RPC does not answer the method, answers garbage, or answers an error status", async () => { + const missing = await rpc(() => undefined); + const garbage = await rpc(() => undefined, (response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end("not json"); + return true; + }); + const status = await rpc(() => undefined, (response) => { + response.writeHead(503); + response.end(); + return true; + }); + const wrongShape = await rpc(() => ({ passphrase: 42 })); + for (const node of [missing, garbage, status, wrongShape]) { + const error = await refused(assertRpcServesNetwork("stellar:testnet", node.url)); + assert.match(error.message, /could not confirm|did not say/); + } + }); + + it("refuses an RPC that cannot be reached", async () => { + await refused(assertRpcServesNetwork("stellar:testnet", "http://127.0.0.1:1")); + }); + + it("does not follow a redirect from the RPC", async () => { + let elsewhere = 0; + const other = http.createServer((_request, response) => { + elsewhere += 1; + response.end("{}"); + }); + await new Promise((resolve) => other.listen(0, "127.0.0.1", resolve)); + open.push({ close: () => new Promise((resolve) => { other.closeAllConnections(); other.close(() => resolve()); }) }); + const { port } = other.address() as { port: number }; + const node = await rpc(() => undefined, (response) => { + response.writeHead(307, { location: `http://127.0.0.1:${port}/` }); + response.end(); + return true; + }); + await refused(assertRpcServesNetwork("stellar:testnet", node.url)); + assert.equal(elsewhere, 0); + }); + + it("refuses a network it has no identity rule for: fail closed", async () => { + const node = await rpc(() => "0x1"); + await refused(assertRpcServesNetwork("cosmos:cosmoshub-4", node.url)); + assert.equal(node.methods.length, 0); + }); +}); + +describe("the entry points check the RPC before any request to the target", () => { + it("x402: a wrong EVM chain id is a PREFLIGHT error, and the target sees nothing", async () => { + const target = await countingTarget(); + const node = await rpc(() => "0x1"); + const results = await runX402PaymentChecks({ + target: target.url, + network: "eip155:84532", + payerSecretKey: generatePrivateKey(), + rpcUrl: node.url, + }); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "PREFLIGHT"); + assert.equal(results[0]?.error?.kind, "configuration"); + assert.match(results[0]?.detail ?? "", /eip155:1\b/); + assert.equal(target.requests(), 0); + }); + + it("MPP charge: an RPC that serves mainnet refuses the run before the challenge is read", async () => { + const target = await countingTarget(); + const asked: string[] = []; + setRpcIdentityTransportForTesting(async (url, method) => { + asked.push(`${new URL(url).host} ${method}`); + return { passphrase: Networks.PUBLIC }; + }); + const error = await refused( + runMppChargeChecks({ + target: target.url, + network: "stellar:testnet", + payerSecretKey: Keypair.random().secret(), + rpcUrl: "https://rpc.example.test", + }), + ); + assert.match(error.message, /stellar:pubnet/); + assert.deepEqual(asked, ["rpc.example.test getNetwork"]); + assert.equal(target.requests(), 0); + }); + + it("MPP channel: an RPC that serves mainnet is a PREFLIGHT error, and the target sees nothing", async () => { + const target = await countingTarget(); + setRpcIdentityTransportForTesting(async () => ({ passphrase: Networks.PUBLIC })); + const results = await runMppChannelSuite({ + target: target.url, + commitmentSecretHex: "11".repeat(32), + network: "stellar:testnet", + rpcUrl: "https://rpc.example.test", + }); + assert.equal(results.length, 1); + assert.equal(results[0]?.id, "PREFLIGHT"); + assert.equal(results[0]?.error?.kind, "configuration"); + assert.equal(target.requests(), 0); + }); +}); diff --git a/packages/core/test/unit/rpc-in-use.test.ts b/packages/core/test/unit/rpc-in-use.test.ts new file mode 100644 index 0000000..6d2452e --- /dev/null +++ b/packages/core/test/unit/rpc-in-use.test.ts @@ -0,0 +1,110 @@ +/** + * Which RPC a run reads the chain through, as a result names it (D-023c, + * option C): its origin only, where it came from (Wasit's default for the + * network, the `rpcUrl` argument of an MCP tool, or `WASIT_RPC_URL` fixed when + * the server started), and whether it is Wasit's default. A non-default RPC is + * flagged, because every settlement read of the run is its word. And the + * start-up lock itself: `WASIT_RPC_URL`, read once, must be an http(s) URL. + * + * No request is made: the defaults are read from the adapters' own tables. + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { describeRpcInUse, readRpcLock, rpcInUse } from "../../src/guard/rpc-in-use.js"; +import { stellarChain } from "../../src/x402/chains/stellar.js"; +import { setPaymentChainsForTesting } from "../../src/x402/chains/index.js"; + +const STELLAR_DEFAULT = "https://soroban-testnet.stellar.org"; +const SECRET_PATH = "/v1/rpc-key-0f0e0d0c0b0a"; + +describe("the RPC a run reads the chain through (D-023c)", () => { + it("is Wasit's default for the network when nothing was given", () => { + for (const protocol of ["x402", "mpp"] as const) { + const rpc = rpcInUse(protocol, "stellar:testnet"); + assert.deepEqual(rpc, { origin: STELLAR_DEFAULT, source: "default", isDefault: true }, protocol); + assert.equal(describeRpcInUse("stellar:testnet", rpc!), `RPC: ${STELLAR_DEFAULT}, Wasit's default for stellar:testnet.`); + } + for (const network of ["eip155:84532", "eip155:11155111", "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"]) { + const rpc = rpcInUse("x402", network); + assert.equal(rpc?.source, "default", network); + assert.equal(rpc?.isDefault, true, network); + assert.match(rpc!.origin, /^https:\/\//, network); + } + }); + + it("names a given RPC by its origin only, and flags it when it is not the default", () => { + const url = `https://rpc.example.test:8443${SECRET_PATH}?apikey=abc123#frag`; + const rpc = rpcInUse("x402", "stellar:testnet", { url, source: "argument" }); + assert.deepEqual(rpc, { origin: "https://rpc.example.test:8443", source: "argument", isDefault: false }); + const line = describeRpcInUse("stellar:testnet", rpc!); + assert.equal( + line, + "RPC: https://rpc.example.test:8443, from the rpcUrl argument: not Wasit's default for stellar:testnet, " + + "so every chain read of this run is this RPC's word.", + ); + for (const part of [SECRET_PATH, "apikey", "abc123", "frag"]) assert.ok(!line.includes(part), part); + }); + + it("says when the RPC was fixed at start-up, and names the variable", () => { + const rpc = rpcInUse("mpp", "stellar:testnet", { url: `http://127.0.0.1:8000${SECRET_PATH}`, source: "start-up" }); + assert.deepEqual(rpc, { origin: "http://127.0.0.1:8000", source: "start-up", isDefault: false }); + assert.equal( + describeRpcInUse("stellar:testnet", rpc!), + "RPC: http://127.0.0.1:8000, fixed when this server started (WASIT_RPC_URL): not Wasit's default for " + + "stellar:testnet, so every chain read of this run is this RPC's word.", + ); + }); + + it("is not flagged when the given RPC is the default itself", () => { + const rpc = rpcInUse("x402", "stellar:testnet", { url: `${STELLAR_DEFAULT}/`, source: "argument" }); + assert.deepEqual(rpc, { origin: STELLAR_DEFAULT, source: "argument", isDefault: true }); + assert.equal(describeRpcInUse("stellar:testnet", rpc!), `RPC: ${STELLAR_DEFAULT}, from the rpcUrl argument (Wasit's default for stellar:testnet).`); + }); + + it("is not named on a network that is not a test network: nothing is read there", () => { + for (const network of ["stellar:pubnet", "eip155:8453", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", "nope"]) { + for (const protocol of ["x402", "mpp"] as const) { + assert.equal(rpcInUse(protocol, network), undefined, `${protocol} ${network}`); + assert.equal(rpcInUse(protocol, network, { url: "https://rpc.example.test", source: "argument" }), undefined, `${protocol} ${network}`); + } + } + }); + + it("is not named on stellar:pubnet even when an adapter offers a default RPC there", () => { + setPaymentChainsForTesting([{ ...stellarChain, resolveRpcUrl: (_network, override) => override || "https://mainnet-rpc.example.test" }]); + try { + assert.equal(rpcInUse("x402", "stellar:pubnet"), undefined); + assert.equal(rpcInUse("x402", "stellar:pubnet", { url: "https://rpc.example.test", source: "start-up" }), undefined); + } finally { + setPaymentChainsForTesting(undefined); + } + }); + + it("is not named for MPP on a test network MPP does not pay on", () => { + assert.equal(rpcInUse("mpp", "eip155:84532"), undefined); + }); +}); + +describe("the start-up RPC lock, WASIT_RPC_URL (D-023c)", () => { + it("is off when the variable is unset or blank", () => { + assert.equal(readRpcLock({}), undefined); + assert.equal(readRpcLock({ WASIT_RPC_URL: "" }), undefined); + assert.equal(readRpcLock({ WASIT_RPC_URL: " " }), undefined); + }); + + it("holds an http or https URL", () => { + assert.deepEqual(readRpcLock({ WASIT_RPC_URL: `https://rpc.example.test${SECRET_PATH}` }), { url: `https://rpc.example.test${SECRET_PATH}` }); + assert.deepEqual(readRpcLock({ WASIT_RPC_URL: "http://127.0.0.1:8000" }), { url: "http://127.0.0.1:8000" }); + }); + + it("refuses anything else, without quoting the value", () => { + for (const value of ["rpc.example.test/key-123", "ftp://rpc.example.test/key-123", "file:///etc/key-123", "https://"]) { + const lock = readRpcLock({ WASIT_RPC_URL: value }); + assert.ok(lock !== undefined && "problem" in lock, value); + assert.match(lock.problem, /^WASIT_RPC_URL /); + assert.ok(!lock.problem.includes("key-123"), lock.problem); + } + }); +}); diff --git a/packages/core/test/unit/stellar-authorization.test.ts b/packages/core/test/unit/stellar-authorization.test.ts new file mode 100644 index 0000000..bcea296 --- /dev/null +++ b/packages/core/test/unit/stellar-authorization.test.ts @@ -0,0 +1,317 @@ +/** + * X402-11's reads on Stellar (D-032, spec B16.4), written before the code. + * + * - The authorization is decoded from the signed entry of the payload, never + * computed: the payer's address, the nonce, the expiration ledger. + * - Its use is read with `getLedgerEntries` on the TEMPORARY contract-data + * entry the host writes when it consumes a nonce: contract = the payer's + * address, key = `LedgerKeyNonce { nonce }` (rs-soroban-env `consume_nonce`). + * Several are asked for in one call, so they are read at one state. + * - The second reading is the token's `transfer` events from the payer to + * `payTo`, read with `getEvents` from a ledger on; only events of a + * successful call count, and a failed read throws rather than reading as + * "no transfer". + * + * Offline: a JSON-RPC stand-in on loopback answers as Stellar RPC would. + */ + +import assert from "node:assert/strict"; +import http from "node:http"; +import { after, before, describe, it } from "node:test"; + +import { + Account, + Address, + Keypair, + Networks, + Operation, + TransactionBuilder, + nativeToScVal, + xdr, +} from "@stellar/stellar-sdk"; + +import { CheckSetupError } from "../../src/errors.js"; +import { stellarChain } from "../../src/x402/chains/stellar.js"; + +const TOKEN = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA"; +const PAYER = Keypair.random().publicKey(); +const PAY_TO = Keypair.random().publicKey(); +const NETWORK = "stellar:testnet"; + +const watch = stellarChain.authorizations!; + +function addressEntry(address: string, nonce: string, expiration: number): xdr.SorobanAuthorizationEntry { + return new xdr.SorobanAuthorizationEntry({ + credentials: xdr.SorobanCredentials.sorobanCredentialsAddress( + new xdr.SorobanAddressCredentials({ + address: Address.fromString(address).toScAddress(), + nonce: xdr.Int64.fromString(nonce), + signatureExpirationLedger: expiration, + signature: xdr.ScVal.scvVec([]), + }), + ), + rootInvocation: new xdr.SorobanAuthorizedInvocation({ + function: xdr.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn( + new xdr.InvokeContractArgs({ contractAddress: Address.fromString(TOKEN).toScAddress(), functionName: "transfer", args: [] }), + ), + subInvocations: [], + }), + }); +} + +function sourceAccountEntry(): xdr.SorobanAuthorizationEntry { + return new xdr.SorobanAuthorizationEntry({ + credentials: xdr.SorobanCredentials.sorobanCredentialsSourceAccount(), + rootInvocation: addressEntry(PAYER, "1", 1).rootInvocation(), + }); +} + +function payload(...auth: xdr.SorobanAuthorizationEntry[]): Record { + const transaction = new TransactionBuilder(new Account(PAYER, "1"), { fee: "100", networkPassphrase: Networks.TESTNET }) + .addOperation(Operation.invokeContractFunction({ contract: TOKEN, function: "transfer", args: [], auth })) + .setTimeout(30) + .build(); + return { transaction: transaction.toEnvelope().toXDR("base64") }; +} + +describe("decode: the authorization as signed", () => { + it("reads the payer, the nonce and the expiration ledger from the address credential", () => { + const decoded = watch.decode(payload(addressEntry(PAYER, "1234567890123", 5000))); + assert.deepEqual(decoded, { payer: PAYER, nonce: "1234567890123", expiresAt: 5000 }); + }); + + it("keeps a negative 64-bit nonce exact", () => { + assert.equal(watch.decode(payload(addressEntry(PAYER, "-9223372036854775808", 7))).nonce, "-9223372036854775808"); + }); + + it("ignores a source-account entry next to the address one", () => { + assert.equal(watch.decode(payload(sourceAccountEntry(), addressEntry(PAYER, "5", 9))).nonce, "5"); + }); + + for (const [label, value] of [ + ["no transaction", {}], + ["a transaction that does not decode", { transaction: "not-xdr" }], + ["no address authorization", payload(sourceAccountEntry())], + ["two address authorizations", payload(addressEntry(PAYER, "1", 9), addressEntry(PAYER, "2", 9))], + ] as const) { + it(`gives no reading (CheckSetupError) for ${label}`, () => { + assert.throws(() => watch.decode(value as Record), CheckSetupError); + }); + } + + it("is the unit Stellar counts in: a ledger, about 5 s", () => { + assert.equal(watch.unit, "ledger"); + assert.equal(watch.unitMs, 5000); + assert.equal(watch.unitSeconds, 5, "the x402 Stellar client's default ledger estimate"); + }); +}); + +interface RpcCall { + readonly method: string; + readonly params: Record; +} + +/** A Stellar RPC stand-in: `answer` gets each call and returns its `result`, or throws for a JSON-RPC error. */ +async function rpcStandIn(answer: (call: RpcCall) => unknown) { + const calls: RpcCall[] = []; + const server = http.createServer((request, response) => { + let body = ""; + request.on("data", (chunk: Buffer) => (body += chunk.toString("utf-8"))); + request.on("end", () => { + const parsed = JSON.parse(body) as { id: number; method: string; params: Record }; + calls.push({ method: parsed.method, params: parsed.params }); + response.writeHead(200, { "content-type": "application/json" }); + try { + response.end(JSON.stringify({ jsonrpc: "2.0", id: parsed.id, result: answer(parsed) })); + } catch (error) { + response.end(JSON.stringify({ jsonrpc: "2.0", id: parsed.id, error: { code: -32600, message: (error as Error).message } })); + } + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const port = (server.address() as { port: number }).port; + return { + url: `http://127.0.0.1:${port}/rpc`, + calls, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +function nonceKey(address: string, nonce: string): xdr.LedgerKey { + return xdr.LedgerKey.contractData( + new xdr.LedgerKeyContractData({ + contract: Address.fromString(address).toScAddress(), + key: xdr.ScVal.scvLedgerKeyNonce(new xdr.ScNonceKey({ nonce: xdr.Int64.fromString(nonce) })), + durability: xdr.ContractDataDurability.temporary(), + }), + ); +} + +function nonceEntry(address: string, nonce: string): string { + return xdr.LedgerEntryData.contractData( + new xdr.ContractDataEntry({ + ext: new xdr.ExtensionPoint(0), + contract: Address.fromString(address).toScAddress(), + key: xdr.ScVal.scvLedgerKeyNonce(new xdr.ScNonceKey({ nonce: xdr.Int64.fromString(nonce) })), + durability: xdr.ContractDataDurability.temporary(), + val: xdr.ScVal.scvVoid(), + }), + ).toXDR("base64"); +} + +describe("read: the nonce entries, in one call", () => { + let rpc: Awaited>; + const used = nonceKey(PAYER, "11").toXDR("base64"); + + before(async () => { + rpc = await rpcStandIn((call) => { + if (call.method !== "getLedgerEntries") throw new Error(`unexpected ${call.method}`); + const keys = call.params["keys"] as string[]; + return { + latestLedger: 5100, + entries: keys + .filter((key) => key === used) + .map((key) => ({ key, xdr: nonceEntry(PAYER, "11"), lastModifiedLedgerSeq: 5003, liveUntilLedgerSeq: 5722 })), + }; + }); + }); + after(() => rpc.close()); + + it("asks for the temporary nonce entry of each authorization, and says which was used and when", async () => { + const read = await watch.read(NETWORK, rpc.url, [ + { payer: PAYER, nonce: "12", expiresAt: 5050 }, + { payer: PAYER, nonce: "11", expiresAt: 5010 }, + ]); + assert.equal(rpc.calls.length, 1, "both were read in one call"); + assert.deepEqual(rpc.calls[0]!.params["keys"], [nonceKey(PAYER, "12").toXDR("base64"), used]); + assert.deepEqual(read, { latest: 5100, used: [undefined, 5003] }); + }); +}); + +describe("read: an RPC that fails", () => { + it("throws, and is never read as unused", async () => { + const rpc = await rpcStandIn(() => { + throw new Error("start is before oldest ledger"); + }); + try { + await assert.rejects(watch.read(NETWORK, rpc.url, [{ payer: PAYER, nonce: "1", expiresAt: 9 }])); + } finally { + await rpc.close(); + } + }); +}); + +/** + * An event as the testnet RPC sent it on 2026-11-16: the keys type, ledger, + * ledgerClosedAt, contractId, id, operationIndex, transactionIndex, txHash, + * topic and value, and no `inSuccessfulContractCall`. + */ +function transferEvent(from: string, to: string, amount: bigint, extra: Record = {}) { + return { + type: "contract", + ledger: 5004, + ledgerClosedAt: "2026-11-16T10:00:00Z", + contractId: TOKEN, + id: `0000-${amount}`, + txHash: "ab".repeat(32), + transactionIndex: 1, + operationIndex: 0, + topic: [ + xdr.ScVal.scvSymbol("transfer").toXDR("base64"), + Address.fromString(from).toScVal().toXDR("base64"), + Address.fromString(to).toScVal().toXDR("base64"), + nativeToScVal("USDC:GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5", { type: "string" }).toXDR("base64"), + ], + value: nativeToScVal(amount, { type: "i128" }).toXDR("base64"), + ...extra, + }; +} + +describe("transfers: the second reading", () => { + it("reads the token's transfer events from the payer to payTo, from the ledger on, leaving out a failed call", async () => { + const rpc = await rpcStandIn((call) => { + if (call.method !== "getEvents") throw new Error(`unexpected ${call.method}`); + return { + latestLedger: 5100, + oldestLedger: 100, + latestLedgerCloseTime: "0", + oldestLedgerCloseTime: "0", + cursor: "c1", + events: [ + transferEvent(PAYER, PAY_TO, 10000n), + transferEvent(PAYER, PAY_TO, 777n, { inSuccessfulContractCall: false }), + transferEvent(PAYER, PAY_TO, 888n, { inSuccessfulContractCall: true, txHash: "cd".repeat(32) }), + ], + }; + }); + try { + const read = await watch.transfers(NETWORK, rpc.url, { asset: TOKEN, from: PAYER, to: PAY_TO, fromLedger: 5001 }); + // The first has no inSuccessfulContractCall, as the testnet RPC sends it; it counts. + assert.deepEqual(read, { + latest: 5100, + transfers: [ + { amount: 10000n, reference: "ab".repeat(32), ledger: 5004 }, + { amount: 888n, reference: "cd".repeat(32), ledger: 5004 }, + ], + }); + const params = rpc.calls[0]!.params; + assert.equal(params["startLedger"], 5001); + const filters = params["filters"] as { type: string; contractIds: string[]; topics: string[][] }[]; + assert.deepEqual(filters[0]!.contractIds, [TOKEN]); + assert.equal(filters[0]!.type, "contract"); + for (const topics of filters[0]!.topics) { + assert.equal(topics[0], xdr.ScVal.scvSymbol("transfer").toXDR("base64")); + assert.equal(topics[1], Address.fromString(PAYER).toScVal().toXDR("base64")); + assert.equal(topics[2], Address.fromString(PAY_TO).toScVal().toXDR("base64")); + } + } finally { + await rpc.close(); + } + }); + + it("follows the cursor when a page is full", async () => { + let page = 0; + const rpc = await rpcStandIn(() => { + page += 1; + const events = page === 1 ? Array.from({ length: 100 }, () => transferEvent(PAYER, PAY_TO, 1n)) : [transferEvent(PAYER, PAY_TO, 10000n)]; + return { latestLedger: 5100, oldestLedger: 100, latestLedgerCloseTime: "0", oldestLedgerCloseTime: "0", cursor: `c${page}`, events }; + }); + try { + const read = await watch.transfers(NETWORK, rpc.url, { asset: TOKEN, from: PAYER, to: PAY_TO, fromLedger: 5001 }); + assert.equal(read.transfers.length, 101); + assert.equal(rpc.calls.length, 2); + assert.equal(rpc.calls[1]!.params["pagination"] !== undefined || rpc.calls[1]!.params["cursor"] !== undefined, true); + } finally { + await rpc.close(); + } + }); + + it("throws after 20 full pages rather than read a cut list as complete (review R6, K27)", async () => { + let page = 0; + const rpc = await rpcStandIn(() => { + page += 1; + const events = Array.from({ length: 100 }, () => transferEvent(PAYER, PAY_TO, 1n)); + return { latestLedger: 5100, oldestLedger: 100, latestLedgerCloseTime: "0", oldestLedgerCloseTime: "0", cursor: `c${page}`, events }; + }); + try { + await assert.rejects( + watch.transfers(NETWORK, rpc.url, { asset: TOKEN, from: PAYER, to: PAY_TO, fromLedger: 5001 }), + /more transfer events than can be read in full/, + ); + assert.equal(rpc.calls.length, 20); + } finally { + await rpc.close(); + } + }); + + it("throws when the RPC cannot serve the range, rather than reading it as no transfer", async () => { + const rpc = await rpcStandIn(() => { + throw new Error("startLedger must be within the ledger range"); + }); + try { + await assert.rejects(watch.transfers(NETWORK, rpc.url, { asset: TOKEN, from: PAYER, to: PAY_TO, fromLedger: 1 })); + } finally { + await rpc.close(); + } + }); +}); diff --git a/packages/core/test/unit/worst-case.test.ts b/packages/core/test/unit/worst-case.test.ts new file mode 100644 index 0000000..3c4f903 --- /dev/null +++ b/packages/core/test/unit/worst-case.test.ts @@ -0,0 +1,144 @@ +/** + * The worst-case property test of spec B11: random endpoint sets and prices, + * run against a recording signer and a paywall that settles everything signed. + * Whatever the terms, and whatever the paywalls change after the plan: + * + * - the dollars signed never exceed the run's cap; + * - they never exceed the worst case the plan computed before anything was + * signed; + * - nothing is signed for a payee the plan did not see, or above what the plan + * allowed for that check; + * - a plan refused for its worst case is refused before any signature. + * + * Seeded, so a failure is reproducible: the seed is in the message. + */ + +import assert from "node:assert/strict"; +import { afterEach, beforeEach, describe, it } from "node:test"; + +import { PER_RUN_CAP_USD, RunBudget, formatUsd, usdFromDollars } from "../../src/guard/budget.js"; +import { planX402Run } from "../../src/x402/plan.js"; +import { runX402PaymentChecks } from "../../src/x402/simulator.js"; +import { + NETWORK, + installRecordingChain, + option, + paywall, + type Paywall, + type Recorder, +} from "../support/recording-chain.js"; + +/** mulberry32: small, seeded, good enough to pick test cases. */ +function random(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** 6 decimals: one base unit is a millionth of a dollar. */ +const usdOf = (baseUnits: bigint): bigint => usdFromDollars(1) * baseUnits / 1_000_000n; + +function payee(index: number): string { + return `0x${(0xa0 + index).toString(16).padStart(2, "0").repeat(20)}`; +} + +let recorder: Recorder; +let undo: (() => void) | undefined; +const walls: Paywall[] = []; + +beforeEach(() => { + recorder = { signed: [] }; + undo = installRecordingChain(recorder); +}); + +afterEach(async () => { + undo?.(); + undo = undefined; + await Promise.all(walls.splice(0).map((wall) => wall.close())); +}); + +const CASES = 40; + +describe("worst case (B11)", () => { + it(`holds for ${CASES} random runs`, { timeout: 120_000 }, async () => { + for (let seed = 1; seed <= CASES; seed += 1) { + const next = random(seed); + recorder.signed.length = 0; + await Promise.all(walls.splice(0).map((wall) => wall.close())); + + const count = 1 + Math.floor(next() * 3); + const caps = [undefined, 0.25, 1, 2.5, 5]; + const maxRunUsd = caps[Math.floor(next() * caps.length)]; + const endpoints = []; + for (let index = 0; index < count; index += 1) { + // From 1 base unit to $1.50: some above the $1 cap. + const amount = BigInt(1 + Math.floor(next() * 1_500_000)); + const created = await paywall([option({ amount: amount.toString(), payTo: payee(index) })]); + walls.push(created); + endpoints.push({ name: `endpoint-${index}`, target: created.url }); + } + + const plan = await planX402Run({ + network: NETWORK, + endpoints, + ...(maxRunUsd === undefined ? {} : { maxRunUsd }), + }); + const label = `seed ${seed}: plan ${formatUsd(plan.worstCaseUsd)}, cap ${formatUsd(plan.capUsd)}`; + assert.equal(recorder.signed.length, 0, `${label}: the plan signed`); + + // After the plan, a paywall may raise its price or change its payee. + const changed = new Set(); + for (const [index, created] of walls.entries()) { + const roll = next(); + const current = created.accepts[0]!; + if (roll < 0.2) { + created.accepts = [{ ...current, amount: (BigInt(current.amount) * 2n).toString() }]; + } else if (roll < 0.35) { + created.accepts = [{ ...current, payTo: payee(index + 10) }]; + changed.add(payee(index + 10)); + } + } + + // The caller of the plan: a refused plan is not run; one that passes is, + // endpoint by endpoint, on one budget. + const budget = new RunBudget(maxRunUsd === undefined ? {} : { maxRunUsd }); + if (plan.refusal === undefined) { + for (const [index, endpoint] of plan.endpoints.entries()) { + if (endpoint.status !== "planned") continue; + await runX402PaymentChecks({ + target: endpoints[index]!.target, + network: NETWORK, + payerSecretKey: "test-payer-key", + budget, + plan: endpoint, + }); + } + } + + const signedUsd = recorder.signed.reduce((sum, requirement) => sum + usdOf(BigInt(requirement.amount)), 0n); + const cap = usdFromDollars(Math.min(maxRunUsd ?? PER_RUN_CAP_USD, PER_RUN_CAP_USD)); + assert.ok(signedUsd <= cap, `${label}: signed ${formatUsd(signedUsd)}, above the cap`); + assert.ok(signedUsd <= plan.worstCaseUsd, `${label}: signed ${formatUsd(signedUsd)}, above the plan`); + assert.equal(signedUsd, budget.spentUsd, `${label}: the budget does not match what was signed`); + if (plan.refusal !== undefined) assert.equal(recorder.signed.length, 0, `${label}: a refused plan signed`); + + const planned = new Map( + plan.endpoints.flatMap((endpoint) => + endpoint.option === undefined ? [] : [[endpoint.option.payTo.toLowerCase(), endpoint] as const], + ), + ); + for (const requirement of recorder.signed) { + const endpoint = planned.get(requirement.payTo.toLowerCase()); + assert.ok(endpoint, `${label}: signed for ${requirement.payTo}, a payee the plan did not see`); + assert.ok(!changed.has(requirement.payTo), `${label}: signed for a payee changed after the plan`); + const most = endpoint.signatures.reduce((max, entry) => (entry.amount > max ? entry.amount : max), 0n); + assert.ok(BigInt(requirement.amount) <= most, `${label}: signed ${requirement.amount}, above the plan`); + } + } + }); +}); diff --git a/packages/core/test/unit/x402-networks.test.ts b/packages/core/test/unit/x402-networks.test.ts index 9ed2914..9e73701 100644 --- a/packages/core/test/unit/x402-networks.test.ts +++ b/packages/core/test/unit/x402-networks.test.ts @@ -289,7 +289,7 @@ describe("payment checks on a challenge Wasit cannot pay", () => { }); assert.deepEqual( results.map((result) => [result.id, result.skipped, result.skipKind]), - ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"].map((id) => [id, true, "unsupported"]), + ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"].map((id) => [id, true, "unsupported"]), ); assert.match(results[0]?.skipReason ?? "", /pay on .*stellar:testnet.*"eip155:97" is not one of them/); assert.equal(target.paymentHeadersSeen(), 0); diff --git a/packages/core/test/unit/x402-unsupported-network.test.ts b/packages/core/test/unit/x402-unsupported-network.test.ts index 7af6ef6..a1b2285 100644 --- a/packages/core/test/unit/x402-unsupported-network.test.ts +++ b/packages/core/test/unit/x402-unsupported-network.test.ts @@ -18,7 +18,7 @@ import { checkStatus } from "../../src/check.js"; import { ConfigurationError, classifyCheckError } from "../../src/errors.js"; import { runX402PaymentChecks } from "../../src/x402/simulator.js"; -const PAYMENT_IDS = ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10"]; +const PAYMENT_IDS = ["X402-06", "X402-07", "X402-08", "X402-09", "X402-10", "X402-11"]; /** A target that counts every request it gets, and answers 402 with an empty challenge. */ async function countingTarget(): Promise<{ url: string; requests: () => number; close: () => Promise }> { diff --git a/packages/core/test/unit/x402-v1-challenge.test.ts b/packages/core/test/unit/x402-v1-challenge.test.ts index 2120d66..01e90b7 100644 --- a/packages/core/test/unit/x402-v1-challenge.test.ts +++ b/packages/core/test/unit/x402-v1-challenge.test.ts @@ -185,6 +185,7 @@ describe("payment checks when no payment can be built", () => { ["X402-08", true], ["X402-09", true], ["X402-10", true], + ["X402-11", true], ], ); for (const result of results) assert.match(result.detail, reason); diff --git a/packages/server/README.md b/packages/server/README.md index eaab049..93b4c08 100644 --- a/packages/server/README.md +++ b/packages/server/README.md @@ -4,7 +4,7 @@ MCP server exposing [Wasit](https://github.com/wasit-dev/wasit)'s **x402** / **M The suite logic isn't reimplemented here — this is a thin adapter over [`@wasit-dev/core`](https://www.npmjs.com/package/@wasit-dev/core), the same package [`@wasit-dev/cli`](https://www.npmjs.com/package/@wasit-dev/cli) runs. An agent's run and a CLI run against the same target can never disagree. -**Testnet only.** Several tools settle real transactions. +**Testnet only.** Several tools settle real transactions. In 0.8.0-beta.1 (npm tag `beta`; `latest` is 0.7.0) the tools pay on test networks only: any other network, `stellar:pubnet` included, is refused before a key is read. `WASIT_MAINNET_OPT_IN`, `WASIT_MAINNET_CONFIG` and `--mainnet` stop the server at start: the mainnet opt-in is not part of this version. ## Install @@ -94,6 +94,10 @@ echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' \ Signing keys are read from the server process's own environment, never accepted as a tool parameter — so an agent handles a result, never a key, and a key can't end up in a transcript. A missing key returns an error result naming which variable to set. +## The RPC lock + +`WASIT_RPC_URL`, read when the server starts, fixes the RPC of every tool call, and a tool call that names another `rpcUrl` is then refused before anything is sent. A result that reads the chain names its RPC by origin, where it came from, and when it is not Wasit's default (in the text and in `structuredContent.rpc`). New in 0.8.0-beta.1. + ## Results Every tool returns both prose and `structuredContent`: diff --git a/packages/server/package.json b/packages/server/package.json index ff41ca3..dbc91a0 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -1,6 +1,6 @@ { "name": "@wasit-dev/server", - "version": "0.7.0", + "version": "0.8.0-beta.1", "description": "MCP server exposing Wasit's x402/MPP conformance checks as tools for Claude Code and other MCP-compatible agents.", "type": "module", "bin": { @@ -44,7 +44,7 @@ }, "dependencies": { "@modelcontextprotocol/sdk": "^1.29.0", - "@wasit-dev/core": "^0.7.0", + "@wasit-dev/core": "^0.8.0-beta.1", "zod": "^4.4.3" } } diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index ec5034c..2540549 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -11,6 +11,14 @@ * is only registered when a human starts this process with an explicit opt-in. * Without it the tool is absent from the tool list entirely — an agent cannot * call what it cannot see. + * + * Mainnet is never a tool argument (spec B5). The start-up settings a later + * version would read for its mainnet opt-in, `WASIT_MAINNET_OPT_IN`, + * `WASIT_MAINNET_CONFIG` and `--mainnet`, stop this server before it starts: + * this version has no opt-in (spec B12). `WASIT_RPC_URL`, read once at start-up, + * fixes the RPC of every tool call, and the `rpcUrl` argument is then refused, + * so an agent cannot point a run at another RPC (D-023c). A result that reads + * the chain names its RPC by origin, and flags one that is not the default. */ import { existsSync, readFileSync } from "node:fs"; @@ -21,11 +29,17 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { SERVER_VERSION } from "./version.js"; import { + RPC_LOCK_VARIABLE, checkStatus, deniedEnvValues, + describeRpcInUse, fixFor, + mainnetStartupSwitches, paymentChainFor, + readRpcLock, redactValue, + refuseMainnetSwitch, + rpcInUse, runMppChannelSuite, runMppChargeSuite, runX402PaymentChecks, @@ -34,8 +48,10 @@ import { summarize, toGradedRun, toStructuredRun, + urlOrigin, type CheckResult, type ProtocolId, + type RpcInUse, } from "@wasit-dev/core"; import { z } from "zod"; @@ -43,6 +59,29 @@ const DESTRUCTIVE_ENABLED = process.env.WASIT_ALLOW_DESTRUCTIVE === "1" || process.argv.includes("--allow-destructive"); +/** + * Start-up, read once: a setting that asks for mainnet, or an RPC lock that is + * not an http(s) URL, stops the server before it registers a tool. Each reason + * goes to stderr (stdout is the protocol channel), and the exit code is 2. + */ +const startupRefusals: string[] = []; +for (const name of mainnetStartupSwitches(process.env, process.argv.slice(2))) { + try { + refuseMainnetSwitch(name); + } catch (error) { + startupRefusals.push(error instanceof Error ? error.message : String(error)); + } +} +const rpcLock = readRpcLock(process.env); +if (rpcLock !== undefined && "problem" in rpcLock) startupRefusals.push(`${rpcLock.problem}, so this server does not start.`); +if (startupRefusals.length > 0) { + for (const reason of startupRefusals) process.stderr.write(`wasit MCP server: ${reason}\n`); + process.exit(2); +} + +/** The RPC every tool call uses when `WASIT_RPC_URL` was set at start-up; the `rpcUrl` argument is then refused. */ +const LOCKED_RPC: string | undefined = rpcLock !== undefined && "url" in rpcLock ? rpcLock.url : undefined; + /** Locates docs/CHECKS.md by walking up from this file. */ function locateChecksCatalogue(): string | undefined { const override = process.env.WASIT_CHECKS_PATH; @@ -74,6 +113,8 @@ const resultShape = { /** Present only on a FAIL whose check recorded them: what it expected, and what the service sent. */ expected: z.string().optional(), actual: z.string().optional(), + /** Present only on a PASS that read its settlement back from the chain (X402-06): the transaction. */ + reference: z.string().optional(), /** Present only on FAIL: what to change. */ fix: z.string().optional(), /** Present only on FAIL: the check's docs page. */ @@ -87,15 +128,73 @@ const runOutputShape = { errored: z.number(), skipped: z.number(), results: z.array(z.object(resultShape)), + /** + * Present only when the run read the chain: its RPC by origin, where it came + * from, and whether it is Wasit's default for the network (D-023c). The one + * field this server adds to the CLI's JSON shape. + */ + rpc: z + .object({ + origin: z.string(), + source: z.enum(["default", "argument", "start-up"]), + isDefault: z.boolean(), + }) + .optional(), }; +/** What a run reads the chain through, for {@link present}. */ +interface RunRpc { + readonly network: string; + readonly rpc: RpcInUse; +} + +/** + * The RPC a tool call reads through: the lock when the server has one, else the + * argument, else the network's default. Undefined when the run reads no chain. + */ +function rpcFor(protocol: "x402" | "mpp", network: string, argument: string | undefined): RunRpc | undefined { + const given = + LOCKED_RPC !== undefined + ? { url: LOCKED_RPC, source: "start-up" as const } + : argument !== undefined && argument !== "" + ? { url: argument, source: "argument" as const } + : undefined; + const rpc = rpcInUse(protocol, network, given); + return rpc === undefined ? undefined : { network, rpc }; +} + +/** The RPC the call passes on: the lock, else the argument. */ +function rpcOption(argument: string | undefined): { rpcUrl: string } | Record { + const url = LOCKED_RPC ?? argument; + return url !== undefined && url !== "" ? { rpcUrl: url } : {}; +} + +/** With a lock, a call that names an RPC is refused before anything is sent (D-023c). */ +function rpcArgumentRefused(argument: string | undefined): { + content: Array<{ type: "text"; text: string }>; + isError: true; +} | undefined { + if (LOCKED_RPC === undefined || argument === undefined) return undefined; + return { + content: [ + { + type: "text", + text: + `rpcUrl is not taken by this server: its RPC was fixed when it started (${RPC_LOCK_VARIABLE}, ` + + `${urlOrigin(LOCKED_RPC)}). Call the tool without rpcUrl. Nothing was sent.`, + }, + ], + isError: true, + }; +} + /** * Renders a run for both the agent's prose channel and its structured channel. * * `outcome` is deliberately named rather than numeric: an exit code means * nothing to an agent, and "no-verdict" must never be read as "compliant". */ -function present(results: CheckResult[], protocol?: ProtocolId): { +function present(results: CheckResult[], protocol?: ProtocolId, read?: RunRpc): { content: Array<{ type: "text"; text: string }>; structuredContent: Record; } { @@ -137,13 +236,19 @@ function present(results: CheckResult[], protocol?: ProtocolId): { // structuredContent is `toStructuredRun()` verbatim — the same reshape // the CLI's `--json` output calls — so the two front ends can never // report the same run two different ways. + // D-023c: every chain read of the run is this RPC's word; it is named, by origin only. + const rpcLine = read === undefined ? "" : `\n${describeRpcInUse(read.network, read.rpc)}`; + return { - content: [{ type: "text", text: `${lines.join("\n\n")}\n\n${summaryLine}${caveat}` }], + content: [{ type: "text", text: `${lines.join("\n\n")}\n\n${summaryLine}${rpcLine}${caveat}` }], // toStructuredRun() returns a precisely-typed StructuredRun, which has // no index signature and so is not directly assignable to the SDK's // looser Record. It is still a plain JSON-serializable // object — this cast widens the type, it does not change the value. - structuredContent: redactValue(structured, secrets) as unknown as Record, + structuredContent: redactValue( + read === undefined ? structured : { ...structured, rpc: { ...read.rpc } }, + secrets, + ) as unknown as Record, }; } @@ -193,7 +298,8 @@ server.registerTool( { title: "Test x402 compliance", description: - "Runs the x402 conformance checks (X402-01..10) against a running service. " + + "Runs the x402 conformance checks (X402-01..10) against a running service; " + + "X402-11 needs the reject case of a wasit.config.json endpoint and is skipped by this tool. " + "Payment checks are included only when the network's payer key is set in " + "this server's environment (STELLAR_PRIVATE_KEY on Stellar, EVM_PRIVATE_KEY " + "on Base and Ethereum Sepolia, SVM_PRIVATE_KEY on Solana devnet); otherwise they are " + @@ -219,12 +325,13 @@ server.registerTool( readOnly: z .boolean() .optional() - .describe("Skip the payment checks (X402-06..10) even if a payer key is set"), + .describe("Skip the payment checks (X402-06..11) even if a payer key is set"), rpcUrl: z .string() .optional() .describe( - "Override the RPC endpoint used to verify X402-06's settlement (Soroban RPC on Stellar, JSON-RPC on EVM and Solana)", + "Override the RPC endpoint used to verify X402-06's settlement (Soroban RPC on Stellar, JSON-RPC on EVM and Solana). " + + "Refused when the server was started with WASIT_RPC_URL, which fixes the RPC of every call.", ), method: z .string() @@ -258,6 +365,8 @@ server.registerTool( }, }, async ({ target, network, readOnly, rpcUrl, method, body, headers }) => { + const refused = rpcArgumentRefused(rpcUrl); + if (refused !== undefined) return refused; // Same request shape for every probe, exactly as the CLI's --method, // --body and --header build it, so a POST endpoint is tested as a POST. const shape = { @@ -269,19 +378,21 @@ server.registerTool( const payNetwork = network ?? "stellar:testnet"; const payerKey = process.env[paymentChainFor(payNetwork)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY"]; + let read: RunRpc | undefined; if (readOnly !== true && payerKey) { + read = rpcFor("x402", payNetwork, rpcUrl); results.push( ...(await runX402PaymentChecks({ target, network: payNetwork, payerSecretKey: payerKey, - ...(rpcUrl !== undefined ? { rpcUrl } : {}), + ...rpcOption(rpcUrl), ...shape, })), ); } - return present(results, "x402"); + return present(results, "x402", read); }, ); @@ -310,7 +421,10 @@ server.registerTool( rpcUrl: z .string() .optional() - .describe("Override the Soroban RPC endpoint (https), used for the payment and the settlement read"), + .describe( + "Override the Soroban RPC endpoint (https), used for the payment and the settlement read. " + + "Refused when the server was started with WASIT_RPC_URL, which fixes the RPC of every call.", + ), }, outputSchema: runOutputShape, annotations: { @@ -323,16 +437,21 @@ server.registerTool( }, }, async ({ target, network, rpcUrl }) => { + const refused = rpcArgumentRefused(rpcUrl); + if (refused !== undefined) return refused; const payerSecretKey = process.env.MPP_PAYER_SECRET; if (!payerSecretKey) return missingKey("MPP_PAYER_SECRET"); + const runNetwork = network ?? process.env.MPP_STELLAR_NETWORK ?? "stellar:testnet"; return present( await runMppChargeSuite({ target, - network: network ?? process.env.MPP_STELLAR_NETWORK ?? "stellar:testnet", + network: runNetwork, payerSecretKey, - ...(rpcUrl ? { rpcUrl } : {}), + ...rpcOption(rpcUrl), }), + undefined, + rpcFor("mpp", runNetwork, rpcUrl), ); }, ); @@ -346,7 +465,10 @@ const channelInputShape = { 'CAIP-2 network id, default "stellar:testnet". "stellar:testnet" only: ' + "any other network is refused before anything is sent.", ), - rpcUrl: z.string().optional().describe("Override the Soroban RPC endpoint"), + rpcUrl: z + .string() + .optional() + .describe("Override the Soroban RPC endpoint. Refused when the server was started with WASIT_RPC_URL, which fixes the RPC of every call."), channel: z .string() .optional() @@ -381,12 +503,13 @@ async function runChannel( allowDestructive: boolean, destructiveChannel?: string, ): Promise> { + const network = input.network ?? process.env.MPP_STELLAR_NETWORK ?? "stellar:testnet"; const results = await runMppChannelSuite({ target: input.target, commitmentSecretHex: process.env.COMMITMENT_SECRET_HEX ?? "", - network: input.network ?? process.env.MPP_STELLAR_NETWORK ?? "stellar:testnet", + network, allowDestructive, - ...(input.rpcUrl ? { rpcUrl: input.rpcUrl } : {}), + ...rpcOption(input.rpcUrl), ...(input.channel ? { channelOverride: input.channel } : {}), ...(destructiveChannel ? { destructiveChannel } : {}), expected: { @@ -399,7 +522,7 @@ async function runChannel( }, }); - return present(results); + return present(results, undefined, rpcFor("mpp", network, input.rpcUrl)); } server.registerTool( @@ -420,6 +543,8 @@ server.registerTool( }, }, async (input) => { + const refused = rpcArgumentRefused(input.rpcUrl); + if (refused !== undefined) return refused; if (!process.env.COMMITMENT_SECRET_HEX) return missingKey("COMMITMENT_SECRET_HEX"); return runChannel(input, false); }, @@ -452,6 +577,8 @@ if (DESTRUCTIVE_ENABLED) { }, }, async ({ destructiveChannel, ...input }) => { + const refused = rpcArgumentRefused(input.rpcUrl); + if (refused !== undefined) return refused; if (!process.env.COMMITMENT_SECRET_HEX) return missingKey("COMMITMENT_SECRET_HEX"); return runChannel(input, true, destructiveChannel); }, diff --git a/packages/server/test/unit/canary-output.test.ts b/packages/server/test/unit/canary-output.test.ts new file mode 100644 index 0000000..a4c9bce --- /dev/null +++ b/packages/server/test/unit/canary-output.test.ts @@ -0,0 +1,162 @@ +/** + * The canary test (spec B6) for the MCP server (review R7): a fresh random + * Stellar key, which holds nothing, in every key variable at once, and an RPC + * url that carries a made-up API key in its path and its query. The tools are + * then called on the paths where a key or a url is most likely to be echoed: + * an RPC that drops every connection, an RPC that answers another network, the + * lock refusing an `rpcUrl` argument, an agent's own `rpcUrl`, and + * `stellar:pubnet`. Every tool result and everything the server wrote to + * stderr is searched for the key, its raw seed in hex and in base64, and the + * RPC key. Any hit fails. + * + * Offline: the target and the RPCs are on 127.0.0.1. Nothing is signed: every + * call stops at the preflight, or is refused before it. + */ + +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import http from "node:http"; +import net from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, it } from "node:test"; + +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { Keypair } from "@stellar/stellar-sdk"; + +const SERVER = fileURLToPath(new URL("../../dist/index.js", import.meta.url)); + +const CANARY = Keypair.random(); +const KEY = CANARY.secret(); +const SEED = CANARY.rawSecretKey(); +const RPC_KEY = `rpckey${Math.random().toString(36).slice(2)}canary`; +const NEEDLES = [KEY, SEED.toString("hex"), SEED.toString("base64"), SEED.toString("base64url"), RPC_KEY]; + +/** Every key variable the server reads holds the canary, in the form it expects. */ +const KEYS = { + STELLAR_PRIVATE_KEY: KEY, + MPP_PAYER_SECRET: KEY, + COMMITMENT_SECRET_HEX: SEED.toString("hex"), + EVM_PRIVATE_KEY: `0x${SEED.toString("hex")}`, + SVM_PRIVATE_KEY: KEY, +}; + +function assertClean(label: string, text: string): void { + for (const needle of NEEDLES) assert.ok(!text.includes(needle), `${label} carries a key value`); +} + +async function listen(server: net.Server): Promise { + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return (server.address() as net.AddressInfo).port; +} + +describe("canary: no key and no RPC key in any MCP tool result or on the server's stderr", () => { + let cwd: string; + const drop = net.createServer((socket) => socket.destroy()); + const otherNetwork = http.createServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { passphrase: "Some Other Network ; 2026", protocolVersion: 23 } })); + }); + const target = http.createServer((_request, response) => { + const body = { + x402Version: 2, + resource: { url: "http://127.0.0.1/paid" }, + accepts: [ + { + scheme: "exact", + network: "stellar:testnet", + amount: "10000", + asset: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + payTo: Keypair.random().publicKey(), + maxTimeoutSeconds: 60, + extra: { areFeesSponsored: true }, + }, + ], + }; + response.writeHead(402, { "payment-required": Buffer.from(JSON.stringify(body)).toString("base64") }); + response.end("{}"); + }); + let ports: { drop: number; other: number; target: number }; + const scanned: string[] = []; + + before(async () => { + cwd = await mkdtemp(path.join(tmpdir(), "wasit-mcp-canary-")); + ports = { drop: await listen(drop), other: await listen(otherNetwork), target: await listen(target) }; + }); + after(async () => { + drop.close(); + otherNetwork.closeAllConnections(); + otherNetwork.close(); + target.closeAllConnections(); + target.close(); + await rm(cwd, { recursive: true, force: true }); + }); + + /** One server, started with `env`, called with each of `calls`; its results and stderr are kept for the scan. */ + async function session(env: Record, calls: Array<[string, Record]>): Promise { + const transport = new StdioClientTransport({ + command: process.execPath, + args: [SERVER], + cwd, + env: { PATH: process.env["PATH"] ?? "", HOME: cwd, ...env }, + stderr: "pipe", + }); + let stderr = ""; + transport.stderr?.on("data", (chunk: Buffer) => (stderr += chunk.toString("utf-8"))); + const client = new Client({ name: "wasit-mcp-canary", version: "0.0.0" }); + await client.connect(transport); + try { + for (const [name, args] of calls) { + try { + scanned.push(JSON.stringify(await client.callTool({ name, arguments: args }))); + } catch (error) { + scanned.push(String(error instanceof Error ? error.message : error)); + } + } + } finally { + await client.close(); + } + scanned.push(stderr); + } + + const paid = () => `http://127.0.0.1:${ports.target}/paid`; + const lockAt = (port: number) => `http://127.0.0.1:${port}/v1/${RPC_KEY}?apikey=${RPC_KEY}`; + + it("with the RPC locked at start-up to an RPC that drops every connection", async () => { + await session({ ...KEYS, WASIT_RPC_URL: lockAt(ports.drop) }, [ + ["wasit_x402_test", { target: paid() }], + ["wasit_mpp_charge_test", { target: paid() }], + ["wasit_mpp_channel_test", { target: paid() }], + ["wasit_x402_test", { target: paid(), rpcUrl: `http://127.0.0.1:${ports.other}/${RPC_KEY}` }], + ]); + }); + + it("with the RPC locked at start-up to an RPC of another network", async () => { + await session({ ...KEYS, WASIT_RPC_URL: lockAt(ports.other) }, [ + ["wasit_x402_test", { target: paid() }], + ["wasit_x402_test", { target: paid(), network: "eip155:84532" }], + ["wasit_mpp_charge_test", { target: paid() }], + ]); + }); + + it("without a lock: the agent's own rpcUrl, and stellar:pubnet", async () => { + await session({ ...KEYS }, [ + ["wasit_x402_test", { target: paid(), rpcUrl: `http://127.0.0.1:${ports.drop}/v1/${RPC_KEY}?k=${RPC_KEY}` }], + ["wasit_x402_test", { target: paid(), network: "stellar:pubnet", rpcUrl: `http://127.0.0.1:${ports.other}/${RPC_KEY}` }], + ]); + }); + + it("a server that does not start: a mainnet start-up switch and a lock that is not a url", async () => { + for (const env of [{ ...KEYS, WASIT_MAINNET_OPT_IN: KEY }, { ...KEYS, WASIT_RPC_URL: `ftp://127.0.0.1/${RPC_KEY}` }]) { + await session(env, []).catch((error: unknown) => scanned.push(String(error instanceof Error ? error.message : error))); + } + }); + + it("left no key and no RPC key in any result or on stderr", () => { + assert.ok(scanned.length >= 12, `too few outputs were searched (${scanned.length})`); + assert.ok(scanned.some((text) => text.includes("RPC")), "no output named an RPC: the paths were not reached"); + for (const [index, text] of scanned.entries()) assertClean(`output ${index + 1}`, text); + }); +}); diff --git a/packages/server/test/unit/mainnet-and-rpc-lock.test.ts b/packages/server/test/unit/mainnet-and-rpc-lock.test.ts new file mode 100644 index 0000000..7f74f35 --- /dev/null +++ b/packages/server/test/unit/mainnet-and-rpc-lock.test.ts @@ -0,0 +1,310 @@ +/** + * The MCP server's start-up switches and its RPC (spec B5, B12; D-023c option C). + * + * - `WASIT_MAINNET_OPT_IN`, `WASIT_MAINNET_CONFIG` and `--mainnet` ask for the + * mainnet opt-in, which this version does not have: the server does not + * start, exit 2, and says why. Without them the tool list has no mainnet tool. + * - `WASIT_RPC_URL`, read once at start-up, fixes the RPC of every tool call; + * the server then refuses the `rpcUrl` argument before anything is sent. A + * value that is not an http(s) URL stops the server, without being echoed. + * - A result that reads the chain names its RPC by origin, says where it came + * from, and flags one that is not Wasit's default. + * + * Starts the built server (`npm run build` first), as an MCP client does. Every + * key is generated here and holds nothing. Nothing leaves 127.0.0.1. + */ + +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import http from "node:http"; +import net from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, it } from "node:test"; + +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { Keypair } from "@stellar/stellar-sdk"; + +const SERVER = fileURLToPath(new URL("../../dist/index.js", import.meta.url)); +const SECRET_PATH = "/v1/rpc-key-5f4e3d2c1b0a"; + +/** Starts the server as a plain process and waits for it to end (or kills it after `ms`). */ +function startRaw(cwd: string, env: Record, args: string[] = [], ms = 10_000) { + return new Promise<{ code: number | null; stderr: string; stdout: string }>((resolve, reject) => { + const child = spawn(process.execPath, [SERVER, ...args], { + cwd, + env: { PATH: process.env["PATH"] ?? "", HOME: cwd, ...env }, + stdio: ["pipe", "pipe", "pipe"], + }); + let stderr = ""; + let stdout = ""; + child.stderr.on("data", (chunk) => (stderr += chunk)); + child.stdout.on("data", (chunk) => (stdout += chunk)); + const timer = setTimeout(() => child.kill("SIGKILL"), ms); + child.on("error", reject); + child.on("close", (code) => { + clearTimeout(timer); + resolve({ code, stderr, stdout }); + }); + }); +} + +/** Answers every request with an x402 v2 challenge on stellar:testnet, counting requests and paid ones. */ +async function target() { + let requests = 0; + let paid = 0; + const challenge = Buffer.from( + JSON.stringify({ + x402Version: 2, + resource: { url: "http://127.0.0.1/paid" }, + accepts: [ + { + scheme: "exact", + network: "stellar:testnet", + amount: "10000", + asset: "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA", + payTo: Keypair.random().publicKey(), + maxTimeoutSeconds: 60, + extra: { areFeesSponsored: true }, + }, + ], + }), + ).toString("base64"); + const server = http.createServer((req, res) => { + requests += 1; + if (req.headers["payment-signature"] || req.headers["x-payment"] || req.headers.authorization) paid += 1; + res.writeHead(402, { "payment-required": challenge, "content-type": "application/json" }); + res.end("{}"); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + url: `http://127.0.0.1:${port}/paid`, + requests: () => requests, + paid: () => paid, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +/** An RPC address on 127.0.0.1 that counts connections and drops each one. */ +async function countingRpc() { + let calls = 0; + const server = net.createServer((socket) => { + calls += 1; + socket.destroy(); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as net.AddressInfo; + return { + origin: `http://127.0.0.1:${port}`, + url: `http://127.0.0.1:${port}${SECRET_PATH}`, + calls: () => calls, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +interface ToolResult { + readonly isError?: boolean; + readonly text: string; + readonly structured?: { rpc?: { origin: string; source: string; isDefault: boolean }; results?: Array<{ id: string; status: string }> }; +} + +async function withClient(cwd: string, env: Record, use: (client: Client) => Promise): Promise { + const transport = new StdioClientTransport({ + command: process.execPath, + args: [SERVER], + cwd, + env: { HOME: cwd, ...env }, + stderr: "pipe", + }); + const client = new Client({ name: "wasit-rpc-lock-test", version: "0.0.0" }); + await client.connect(transport); + try { + return await use(client); + } finally { + await client.close(); + } +} + +async function call(cwd: string, env: Record, name: string, args: Record): Promise { + return withClient(cwd, env, async (client) => { + const result = await client.callTool({ name, arguments: args }); + const content = result.content as Array<{ type: string; text?: string }>; + return { + ...(result.isError === true ? { isError: true } : {}), + text: content.map((entry) => entry.text ?? "").join("\n"), + ...(result.structuredContent === undefined ? {} : { structured: result.structuredContent as ToolResult["structured"] }), + }; + }); +} + +describe("the MCP server's start-up switches (B12)", () => { + let cwd: string; + before(async () => { + cwd = await mkdtemp(path.join(tmpdir(), "wasit-mcp-switch-")); + }); + after(async () => { + await rm(cwd, { recursive: true, force: true }); + }); + + for (const [name, env, args] of [ + ["WASIT_MAINNET_OPT_IN", { WASIT_MAINNET_OPT_IN: "1" }, []], + ["WASIT_MAINNET_OPT_IN", { WASIT_MAINNET_OPT_IN: "0" }, []], + ["WASIT_MAINNET_CONFIG", { WASIT_MAINNET_CONFIG: "/srv/wasit/mainnet.config.json" }, []], + ["--mainnet", {}, ["--mainnet"]], + ] as const) { + it(`does not start with ${name}${"WASIT_MAINNET_OPT_IN" in env ? `=${env.WASIT_MAINNET_OPT_IN}` : ""}: exit 2, and says why on stderr`, async () => { + const result = await startRaw(cwd, { ...env }, [...args]); + assert.equal(result.code, 2, result.stderr); + assert.equal(result.stdout, "", "nothing on the protocol channel"); + assert.match(result.stderr, new RegExp(`^wasit MCP server: ${name.replace(/[-]/g, "\\-")} is (set|refused): the mainnet opt-in is not part of this version`)); + assert.match(result.stderr, /Wasit pays on test networks only \(stellar:testnet, /); + }); + } + + it("names every switch that is set", async () => { + const result = await startRaw(cwd, { WASIT_MAINNET_OPT_IN: "1", WASIT_MAINNET_CONFIG: "/x.json" }, ["--mainnet"]); + assert.equal(result.code, 2); + for (const name of ["--mainnet", "WASIT_MAINNET_OPT_IN", "WASIT_MAINNET_CONFIG"]) assert.ok(result.stderr.includes(`${name} is`), name); + }); + + it("starts without them, and its tool list has no mainnet tool", async () => { + const names = await withClient(cwd, {}, async (client) => (await client.listTools()).tools.map((tool) => tool.name)); + assert.deepEqual(names.sort(), ["wasit_mpp_channel_test", "wasit_mpp_charge_test", "wasit_x402_test"]); + assert.ok(!names.some((name) => /mainnet|pubnet/i.test(name))); + }); + + it("does not start when WASIT_RPC_URL is not an http(s) URL, and never echoes the value", async () => { + for (const value of ["rpc.example.test/key-77aa", "ftp://rpc.example.test/key-77aa"]) { + const result = await startRaw(cwd, { WASIT_RPC_URL: value }); + assert.equal(result.code, 2, result.stderr); + assert.match(result.stderr, /^wasit MCP server: WASIT_RPC_URL /); + assert.match(result.stderr, /so this server does not start\./); + assert.ok(!result.stderr.includes("key-77aa"), result.stderr); + } + }); +}); + +describe("the MCP server's RPC lock and the RPC in results (D-023c)", () => { + let cwd: string; + before(async () => { + cwd = await mkdtemp(path.join(tmpdir(), "wasit-mcp-rpc-")); + }); + after(async () => { + await rm(cwd, { recursive: true, force: true }); + }); + + const tools: Array<[string, Record, Record?]> = [ + ["wasit_x402_test", { STELLAR_PRIVATE_KEY: Keypair.random().secret() }], + ["wasit_mpp_charge_test", { MPP_PAYER_SECRET: Keypair.random().secret() }], + ["wasit_mpp_channel_test", { COMMITMENT_SECRET_HEX: randomBytes(32).toString("hex") }], + // The close tool exists only with WASIT_ALLOW_DESTRUCTIVE=1 (review R6, S1). + [ + "wasit_mpp_channel_test_with_close", + { COMMITMENT_SECRET_HEX: randomBytes(32).toString("hex"), WASIT_ALLOW_DESTRUCTIVE: "1" }, + { destructiveChannel: "CDESTROYCHANNEL" }, + ], + ]; + + for (const [tool, keys, extra = {}] of tools) { + it(`${tool}: with WASIT_RPC_URL set, the rpcUrl argument is refused before anything is sent`, async () => { + const paywall = await target(); + const locked = await countingRpc(); + const other = await countingRpc(); + try { + const result = await call(cwd, { ...keys, WASIT_RPC_URL: locked.url }, tool, { target: paywall.url, rpcUrl: other.url, ...extra }); + assert.equal(result.isError, true, result.text); + assert.match(result.text, /^rpcUrl is not taken by this server: its RPC was fixed when it started \(WASIT_RPC_URL, http:\/\/127\.0\.0\.1:\d+\)\./); + assert.match(result.text, /Nothing was sent\.$/); + assert.ok(!result.text.includes(SECRET_PATH), "the lock's path was printed"); + assert.equal(paywall.requests(), 0); + assert.equal(locked.calls(), 0); + assert.equal(other.calls(), 0); + } finally { + await paywall.close(); + await locked.close(); + await other.close(); + } + }); + } + + it("wasit_x402_test with WASIT_RPC_URL and no argument reads through the lock and names it by origin, flagged", async () => { + const paywall = await target(); + const locked = await countingRpc(); + try { + const result = await call(cwd, { STELLAR_PRIVATE_KEY: Keypair.random().secret(), WASIT_RPC_URL: locked.url }, "wasit_x402_test", { target: paywall.url }); + assert.ok( + result.text.includes( + `RPC: ${locked.origin}, fixed when this server started (WASIT_RPC_URL): not Wasit's default for stellar:testnet, so every chain read of this run is this RPC's word.`, + ), + result.text, + ); + assert.deepEqual(result.structured?.rpc, { origin: locked.origin, source: "start-up", isDefault: false }); + assert.ok(locked.calls() > 0, "the lock was not the RPC the run used"); + assert.ok(!JSON.stringify(result).includes(SECRET_PATH), "the lock's path was printed"); + assert.equal(paywall.paid(), 0); + } finally { + await paywall.close(); + await locked.close(); + } + }); + + it("wasit_x402_test without a lock names the rpcUrl argument by origin, flagged", async () => { + const paywall = await target(); + const rpc = await countingRpc(); + try { + const result = await call(cwd, { STELLAR_PRIVATE_KEY: Keypair.random().secret() }, "wasit_x402_test", { target: paywall.url, rpcUrl: rpc.url }); + assert.ok( + result.text.includes(`RPC: ${rpc.origin}, from the rpcUrl argument: not Wasit's default for stellar:testnet, so every chain read of this run is this RPC's word.`), + result.text, + ); + assert.deepEqual(result.structured?.rpc, { origin: rpc.origin, source: "argument", isDefault: false }); + assert.ok(!JSON.stringify(result).includes(SECRET_PATH)); + assert.equal(paywall.paid(), 0); + } finally { + await paywall.close(); + await rpc.close(); + } + }); + + it("wasit_x402_test that reads no chain (readOnly, or no payer key) names no RPC", async () => { + const paywall = await target(); + const rpc = await countingRpc(); + try { + for (const [env, args] of [ + [{ STELLAR_PRIVATE_KEY: Keypair.random().secret() }, { readOnly: true }], + [{}, {}], + ] as const) { + const result = await call(cwd, { ...env }, "wasit_x402_test", { target: paywall.url, rpcUrl: rpc.url, ...args }); + assert.doesNotMatch(result.text, /^RPC: /m, result.text); + assert.equal(result.structured?.rpc, undefined); + } + assert.equal(rpc.calls(), 0); + } finally { + await paywall.close(); + await rpc.close(); + } + }); + + it("wasit_mpp_charge_test with WASIT_RPC_URL names the lock too", async () => { + const paywall = await target(); + const locked = await countingRpc(); + try { + const result = await call(cwd, { MPP_PAYER_SECRET: Keypair.random().secret(), WASIT_RPC_URL: locked.url }, "wasit_mpp_charge_test", { target: paywall.url }); + assert.ok(result.text.includes(`RPC: ${locked.origin}, fixed when this server started (WASIT_RPC_URL)`), result.text); + assert.equal(result.structured?.rpc?.source, "start-up"); + assert.equal(paywall.paid(), 0); + } finally { + await paywall.close(); + await locked.close(); + } + }); +}); diff --git a/scripts/fixtures.sh b/scripts/fixtures.sh index f447881..e6fc2cd 100755 --- a/scripts/fixtures.sh +++ b/scripts/fixtures.sh @@ -30,6 +30,7 @@ FIXTURES=( "x402-permit2:3006:packages/core/test/fixtures/x402-evm-permit2-server.ts" "x402-svm:3007:packages/core/test/fixtures/x402-svm-server.ts" "x402-sepolia:3008:packages/core/test/fixtures/x402-evm-sepolia-server.ts" + "x402-reject:3009:packages/core/test/fixtures/x402-reject-server.ts" ) field() { echo "$1" | cut -d: -f"$2"; } @@ -118,6 +119,7 @@ cmd_start() { echo " x402-permit2 http://localhost:3006/protected (Base Sepolia, Permit2 with EIP-2612 sponsoring)" echo " x402-svm http://localhost:3007/protected (Solana devnet, needs SVM_PAYEE_ADDRESS)" echo " x402-sepolia http://localhost:3008/protected (Ethereum Sepolia, own facilitator, needs EVM_FACILITATOR_PRIVATE_KEY)" + echo " x402-reject http://localhost:3009/refuses, /settles-then-refuses, /serves (X402-11; invalid = header x-wasit-invalid)" } cmd_stop() {