From 98f472419213a4a38258c8596d78d1e5c88a77bc Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sat, 21 Nov 2026 05:53:40 +0800 Subject: [PATCH 1/5] fix(action): run on the supported events only, and blank what changes how a step starts The action refused pull_request_target because it hands a pull request's code the base repository's token. issue_comment, workflow_run and other events can do the same when a workflow checks out the pull request, and the service Wasit starts would then be that code, in a job whose later steps hold the token. The step that checks the inputs now allows pull_request, push, schedule, workflow_dispatch and merge_group, and stops any other event with exit 2. Every step also sets BASH_ENV, ENV, LD_PRELOAD, LD_LIBRARY_PATH and LD_AUDIT empty, as it already did NODE_OPTIONS: a file the shell runs before a step, or a library loaded into bash, node or gh, no longer reaches the steps that hold the token or the payer key from the workflow's env. The comments and the example workflow say what this does not cover: code that ran earlier in the job as the runner's user, which can change PATH or files or leave a process running, and which is kept from neither the key nor the token. The YAML test now also pins that "Finish the check run" runs only when a check run was started and uses only what the report step wrote. --- action/action.yml | 64 +++++++++++++++++++++++++++++++- action/examples/wasit.yml | 9 +++-- action/scripts/inputs.mjs | 20 ++++++++++ action/test/action-yaml.test.mjs | 23 ++++++++++++ action/test/inputs.test.mjs | 31 +++++++++++++++- 5 files changed, 140 insertions(+), 7 deletions(-) diff --git a/action/action.yml b/action/action.yml index 43bcadf..ab23195 100644 --- a/action/action.yml +++ b/action/action.yml @@ -3,8 +3,9 @@ description: >- 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). + workflow_dispatch. Runs on pull_request, push, schedule, workflow_dispatch + and merge_group, and refuses any other event. Linux runners. Needs Node 22 + or later (add actions/setup-node before this step). inputs: config: @@ -57,6 +58,15 @@ runs: # 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. + # For the same reason BASH_ENV and ENV (a file the shell runs before the + # step) and LD_PRELOAD, LD_LIBRARY_PATH and LD_AUDIT (libraries loaded into + # bash, node and gh) are set empty in every step, so the workflow's env does + # not reach them. That a step's env also wins over an earlier step's + # GITHUB_ENV for these names is not yet seen on a runner. A service that + # needs one sets it in its service.start command. None of this keeps the steps apart from code + # that ran earlier in the job as the runner's user: such code can also put a + # program of its own first on PATH (GITHUB_PATH), change files on disk, or + # leave a process running; the example workflow states that limit. - name: Check the runner shell: bash @@ -68,6 +78,11 @@ runs: COMMITMENT_SECRET_HEX: "" WASIT_MAINNET_PAYER_SECRET: "" NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" run: | if [ "$RUNNER_OS" != "Linux" ]; then echo "Wasit: this action runs on Linux runners in this version." >&2 @@ -94,6 +109,11 @@ runs: COMMITMENT_SECRET_HEX: "" WASIT_MAINNET_PAYER_SECRET: "" NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" INPUT_CONFIG: ${{ inputs.config }} INPUT_ENVIRONMENT: ${{ inputs.environment }} INPUT_TIER: ${{ inputs.tier }} @@ -114,6 +134,11 @@ runs: COMMITMENT_SECRET_HEX: "" WASIT_MAINNET_PAYER_SECRET: "" NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" run: | cd "$ACTION_PATH/.." npm ci --ignore-scripts --no-audit --no-fund @@ -138,6 +163,11 @@ runs: COMMITMENT_SECRET_HEX: "" WASIT_MAINNET_PAYER_SECRET: "" NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" GH_TOKEN: ${{ github.token }} INPUT_ENVIRONMENT: ${{ inputs.environment }} run: node "$ACTION_PATH/scripts/announce.mjs" start @@ -154,6 +184,11 @@ runs: COMMITMENT_SECRET_HEX: "" WASIT_MAINNET_PAYER_SECRET: "" NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" GH_TOKEN: ${{ github.token }} run: node "$ACTION_PATH/scripts/baseline.mjs" @@ -165,6 +200,11 @@ runs: env: ACTION_PATH: ${{ github.action_path }} NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" INPUT_CONFIG: ${{ inputs.config }} INPUT_ENVIRONMENT: ${{ inputs.environment }} INPUT_TIER: ${{ inputs.tier }} @@ -189,6 +229,11 @@ runs: COMMITMENT_SECRET_HEX: "" WASIT_MAINNET_PAYER_SECRET: "" NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" BASELINE_PATH: ${{ steps.baseline.outputs.path }} HISTORY_PATH: ${{ steps.baseline.outputs.history }} BASELINE_RUN: ${{ steps.baseline.outputs.run }} @@ -207,6 +252,11 @@ runs: COMMITMENT_SECRET_HEX: "" WASIT_MAINNET_PAYER_SECRET: "" NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" GH_TOKEN: ${{ github.token }} WASIT_COMMENT_FILE: ${{ runner.temp }}/wasit/comment.md run: node "$ACTION_PATH/scripts/comment.mjs" @@ -225,6 +275,11 @@ runs: COMMITMENT_SECRET_HEX: "" WASIT_MAINNET_PAYER_SECRET: "" NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" GH_TOKEN: ${{ github.token }} CHECK_RUN_ID: ${{ steps.announce.outputs.check_run_id }} REPORT_OUTCOME: ${{ steps.report.outcome }} @@ -244,6 +299,11 @@ runs: COMMITMENT_SECRET_HEX: "" WASIT_MAINNET_PAYER_SECRET: "" NODE_OPTIONS: "" + BASH_ENV: "" + ENV: "" + LD_PRELOAD: "" + LD_LIBRARY_PATH: "" + LD_AUDIT: "" with: name: wasit-baseline path: ${{ runner.temp }}/wasit/baseline-next.json diff --git a/action/examples/wasit.yml b/action/examples/wasit.yml index 0d765cf..dcb5c95 100644 --- a/action/examples/wasit.yml +++ b/action/examples/wasit.yml @@ -17,8 +17,10 @@ # The service Wasit starts is not given that variable, and neither is it given # the key variables or WASIT_RPC_URL. Never put a key in wasit.config.json. # -# Do not use pull_request_target. It would give the code of a pull request the -# token and the secrets of your repository. +# The action runs on pull_request, push, schedule, workflow_dispatch and +# merge_group, and refuses any other event: pull_request_target, issue_comment, +# workflow_run and the like can give the code of a pull request the token and +# the secrets of your repository. name: Wasit @@ -71,7 +73,8 @@ jobs: # 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. + # as the runner's user is not kept from it, nor from the job's token, which + # the action gives to the steps that call gh. - uses: wasit-dev/wasit/action@ with: config: wasit.config.json diff --git a/action/scripts/inputs.mjs b/action/scripts/inputs.mjs index 591d3d0..6009c45 100644 --- a/action/scripts/inputs.mjs +++ b/action/scripts/inputs.mjs @@ -36,6 +36,14 @@ export class MainnetRefusedError extends InputError { /** An event name as GitHub writes them; anything else is never echoed. */ const EVENT_NAME = /^[a-z_]{1,64}$/; +/** + * The events the action runs on. A pull request runs the read-only checks; the + * payment tier pays only on push to the default branch, schedule and + * workflow_dispatch (the CLI decides, D-022a); merge_group runs the read-only + * checks on the merge queue's commit. + */ +export const SUPPORTED_EVENTS = Object.freeze(["pull_request", "push", "schedule", "workflow_dispatch", "merge_group"]); + function trimmed(value) { return typeof value === "string" ? value.trim() : ""; } @@ -75,6 +83,18 @@ export function parseInputs(env) { // B12: no mainnet opt-in in this version. Refused before anything else is read. checkMainnet(env); + // The events this action is built for. Others (issue_comment, workflow_run, ...) run with the + // base repository's write token, and a workflow on them often checks out a pull request's code: + // the service Wasit starts would be that code, in the job that holds the token. + const event = typeof env["GITHUB_EVENT_NAME"] === "string" ? env["GITHUB_EVENT_NAME"] : ""; + if (!SUPPORTED_EVENTS.includes(event)) { + throw new InputError( + `this action runs on ${SUPPORTED_EVENTS.join(", ")} only, and this run's event is ` + + `${EVENT_NAME.test(event) ? event : "another event"}. On other events a workflow can hand a pull request's code ` + + "the base repository's token, and the service Wasit starts would be that code.", + ); + } + // 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"; diff --git a/action/test/action-yaml.test.mjs b/action/test/action-yaml.test.mjs index ee43d64..bd8d2f9 100644 --- a/action/test/action-yaml.test.mjs +++ b/action/test/action-yaml.test.mjs @@ -144,6 +144,29 @@ describe("action.yml", () => { }); }); + describe("what changes how a step's shell or programs start (2026-11-21)", () => { + it("sets BASH_ENV, ENV, LD_PRELOAD, LD_LIBRARY_PATH and LD_AUDIT empty in every step, the run step and the upload step included", () => { + for (const step of steps) { + for (const name of ["BASH_ENV", "ENV", "LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT"]) assert.equal(step.env?.[name], "", `${step.name}: ${name}`); + } + }); + }); + + describe("the check run is completed only from what the report step wrote (2026-11-20)", () => { + it("runs Finish whenever the announcement started a check run, and only then", () => { + assert.equal(stepByName("Finish the check run").if, "${{ always() && steps.announce.outputs.check_run_id != '' }}"); + }); + + it("hands Finish the report step's outcome and the announcement's id, so a file the report step did not write is not used", () => { + const env = stepByName("Finish the check run").env; + assert.equal(env.REPORT_OUTCOME, "${{ steps.report.outcome }}"); + assert.equal(env.CHECK_RUN_ID, "${{ steps.announce.outputs.check_run_id }}"); + assert.equal(env.WASIT_CHECK_RUN_FILE, "${{ runner.temp }}/wasit/check-run.json"); + assert.equal(stepByName("Write the report").id, "report"); + assert.equal(stepByName("Announce the run").id, "announce"); + }); + }); + 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"]) { diff --git a/action/test/inputs.test.mjs b/action/test/inputs.test.mjs index 3ee8a25..8be3c41 100644 --- a/action/test/inputs.test.mjs +++ b/action/test/inputs.test.mjs @@ -116,8 +116,35 @@ describe("parseInputs", () => { ); }); - it("allows push, pull_request, workflow_dispatch and schedule", () => { - for (const name of ["push", "pull_request", "workflow_dispatch", "schedule"]) assert.doesNotThrow(() => parseInputs(env({ GITHUB_EVENT_NAME: name })), name); + it("allows push, pull_request, workflow_dispatch, schedule and merge_group", () => { + for (const name of ["push", "pull_request", "workflow_dispatch", "schedule", "merge_group"]) { + assert.doesNotThrow(() => parseInputs(env({ GITHUB_EVENT_NAME: name })), name); + } + }); + + it("refuses every other event, as pull_request_target: they hand a pull request's code the base repository's token", () => { + for (const name of ["issue_comment", "workflow_run", "pull_request_review", "pull_request_review_comment", "repository_dispatch", "release"]) { + assert.throws( + () => parseInputs(env({ GITHUB_EVENT_NAME: name })), + (error) => + error instanceof InputError && + /^this action runs on pull_request, push, schedule, workflow_dispatch, merge_group only/.test(error.message) && + error.message.includes(`this run's event is ${name}.`), + name, + ); + } + }); + + it("refuses a run with no event name, and never quotes one that is not an event name", () => { + const unset = env(); + delete unset.GITHUB_EVENT_NAME; + for (const given of [unset, env({ GITHUB_EVENT_NAME: "" }), env({ GITHUB_EVENT_NAME: "push; id" })]) { + assert.throws( + () => parseInputs(given), + (error) => error instanceof InputError && /this run's event is another event\./.test(error.message) && !error.message.includes("; id"), + JSON.stringify(given.GITHUB_EVENT_NAME), + ); + } }); describe("names that would be shell text", () => { From 29b1e357f41e1db1f5147fe00a05cfd3541f369e Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sat, 21 Nov 2026 05:53:49 +0800 Subject: [PATCH 2/5] fix(cli): no wrapped line of the coloured output starts with a workflow command The sanitiser breaks "::" and "##[" at the start of a text, but the coloured output of wasit test wraps text after that, so a word in the middle of a fix could start a line that a GitHub job log reads as a workflow command (colour is on in CI with FORCE_COLOR). wrap() now breaks every wrapped line the same way. The live wasit test moves from index.ts to its own module, test-live.ts, with the stream, the environment and the checks passed in, so a test can hold it to what the plain output promises: only Wasit's own colour codes, no secret of the environment, no line that starts with a command, the same exit code. The comment before the RPC check in wasit run no longer says the payment is built through that RPC on Stellar: there the x402 client builds it through its own default RPC for the network. --- packages/cli/src/index.ts | 87 +--------------- packages/cli/src/run.ts | 6 +- packages/cli/src/style.ts | 15 ++- packages/cli/src/test-live.ts | 112 +++++++++++++++++++++ packages/cli/test/unit/test-live.test.ts | 121 +++++++++++++++++++++++ 5 files changed, 254 insertions(+), 87 deletions(-) create mode 100644 packages/cli/src/test-live.ts create mode 100644 packages/cli/test/unit/test-live.test.ts diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index db71aa3..c465f0f 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -16,18 +16,14 @@ import { type ServeMode, } from "./serve.js"; import { executeCiReport } from "./ci-report-command.js"; -import { exitCodeFor, note, report, verdictNotes } from "./output.js"; -import { LiveReport } from "./live.js"; -import { colorDepth, colorEnabled, lineWidth, liveEnabled, styler } from "./style.js"; +import { note, report } from "./output.js"; +import { liveX402Test } from "./test-live.js"; +import { colorDepth, colorEnabled, lineWidth, 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, @@ -249,7 +245,7 @@ or NO_COLOR gives the plain text; FORCE_COLOR=1 colours a pipe.`, // 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)); + process.exit(await liveX402Test(opts, shape, { stream: process.stdout, env: process.env })); } const results = await runX402ReadChecks({ target: opts.target, ...shape }); @@ -599,81 +595,6 @@ function terminalStyle(jsonMode: boolean): { style: ReturnType; w }; } -/** - * `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") .description("Run the MPP charge-mode check (MPP-01) against a target service") diff --git a/packages/cli/src/run.ts b/packages/cli/src/run.ts index 3e57914..9955259 100644 --- a/packages/cli/src/run.ts +++ b/packages/cli/src/run.ts @@ -384,8 +384,10 @@ export async function executeRun(options: RunCommandOptions, context: RunContext : 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. + // anything is sent to it: the settlements are read through it (and, on EVM + // and Solana, the payments are built through it), so it must serve the run's + // own network. On Stellar the x402 client builds the payment through its own + // default RPC for the network; that is changed before the mainnet opt-in. if (paying && notPaid === undefined && chain !== undefined && key !== undefined && hasX402) { try { await assertRpcServesNetwork(resolved.network, chain.resolveRpcUrl(resolved.network, resolved.rpcUrl)); diff --git a/packages/cli/src/style.ts b/packages/cli/src/style.ts index 41eed2f..cb2a8c8 100644 --- a/packages/cli/src/style.ts +++ b/packages/cli/src/style.ts @@ -190,9 +190,20 @@ export function truncate(text: string, max: number): string { return `${chars.slice(0, max - 1).join("")}…`; } +/** + * A wrapped line that would start with a workflow command once the runner trims + * its indent (`::name::`, `##[name]`), broken the way the sanitiser breaks one + * at the start of a text. Wrapping makes new line starts out of words in the + * middle of a text, after the sanitiser ran, so each one is checked here. + */ +function breakCommandStart(line: string): string { + return line.replace(/^(::|##\[)/, (command: string) => (command === "::" ? ": :" : "# #[")); +} + /** * 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. + * longer than a line (a URL, a hash) is kept whole and runs over. No line + * starts with a workflow command (`breakCommandStart`). */ export function wrap(text: string, width: number, indent: string): string[] { const room = Math.max(20, width - [...indent].length); @@ -207,7 +218,7 @@ export function wrap(text: string, width: number, indent: string): string[] { } } if (current !== "") lines.push(current); - return lines.map((line) => `${indent}${line}`); + return lines.map((line) => `${indent}${breakCommandStart(line)}`); } /** diff --git a/packages/cli/src/test-live.ts b/packages/cli/src/test-live.ts new file mode 100644 index 0000000..96d7d31 --- /dev/null +++ b/packages/cli/src/test-live.ts @@ -0,0 +1,112 @@ +/** + * `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). + * + * Its own module so that a test can drive it with a stream, an environment and + * stand-in checks, and hold it to what the plain output promises: every text a + * service chose is sanitised, and no secret of the environment is printed. + */ + +import { + X402_PAYMENT_CHECK_IDS, + catalogueEntry, + deniedEnvValues, + endpointOutcome, + networkClass, + paymentChainFor, + runX402PaymentChecks, + runX402ReadChecks, + sanitizeText, +} from "@wasit-dev/core"; + +import { LiveReport, type LiveStream } from "./live.js"; +import { exitCodeFor, verdictNotes } from "./output.js"; +import { colorDepth, liveEnabled } from "./style.js"; +import { CLI_VERSION } from "./version.js"; + +export interface LiveTestShape { + method?: string; + body?: string; + headers?: Record; +} + +export interface LiveTestDeps { + /** Where the output goes: `process.stdout` in the CLI. */ + readonly stream: LiveStream; + /** The environment the payer key and the secrets are read from: `process.env` in the CLI. */ + readonly env: Readonly>; + /** The checks, replaceable in tests. */ + readonly readChecks?: typeof runX402ReadChecks; + readonly paymentChecks?: typeof runX402PaymentChecks; +} + +export async function liveX402Test(opts: Record, shape: LiveTestShape, deps: LiveTestDeps): Promise { + const { stream, env } = deps; + const readChecks = deps.readChecks ?? runX402ReadChecks; + const paymentChecks = deps.paymentChecks ?? runX402PaymentChecks; + const secrets = deniedEnvValues(env); + const live = new LiveReport({ + stream, + live: liveEnabled(stream, env), + depth: colorDepth(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 readChecks({ target, ...shape, onResult: (result) => live.result(result) }); + live.gap(); + + const keyEnv = paymentChainFor(network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY"; + const payerKey = (opts["payerKey"] as string | undefined) ?? 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 paymentChecks({ + 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"); +} diff --git a/packages/cli/test/unit/test-live.test.ts b/packages/cli/test/unit/test-live.test.ts new file mode 100644 index 0000000..730aa7a --- /dev/null +++ b/packages/cli/test/unit/test-live.test.ts @@ -0,0 +1,121 @@ +/** + * `wasit test` drawn live, for a person at a terminal (`liveX402Test`), driven + * with a stream, an environment and stand-in checks. + * + * What it is held to: every text a service + * chose reaches the screen only through the sanitiser, so the only escape + * sequences are Wasit's own colours; no secret of the environment is printed; + * and no line starts with a GitHub workflow command, also where the output is + * wrapped in the middle of a service's text (colour is on in CI with + * FORCE_COLOR). + */ + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { Keypair } from "@stellar/stellar-sdk"; +import type { CheckResult, runX402PaymentChecks, runX402ReadChecks } from "@wasit-dev/core"; + +import { liveX402Test } from "../../src/test-live.js"; + +const SGR = /\u001b\[[0-9;]*m/g; + +/** A stream that keeps what is written; not a TTY, 80 columns. */ +function stream(): { isTTY: boolean; columns: number; text: string; write(chunk: string): boolean } { + return { + isTTY: false, + columns: 80, + text: "", + write(chunk: string) { + this.text += chunk; + return true; + }, + }; +} + +type ReadChecks = typeof runX402ReadChecks; +type PaymentChecks = typeof runX402PaymentChecks; + +/** Stand-in checks that report `results` through `onResult`, as the real ones do. */ +function emitting(results: CheckResult[]): ReadChecks & PaymentChecks { + return (async (options: { onResult?: (result: CheckResult) => void }) => { + for (const result of results) options.onResult?.(result); + return [...results]; + }) as unknown as ReadChecks & PaymentChecks; +} + +/** The lines as the runner reads them: colours out, the indent trimmed. */ +function runnerLines(text: string): string[] { + return text.split("\n").map((line) => line.replace(SGR, "").trimStart()); +} + +describe("wasit test, live (liveX402Test)", () => { + const payerKey = Keypair.random().secret(); + const headerSecret = "header-secret-value-5f1e"; + const env = { STELLAR_PRIVATE_KEY: payerKey, WASIT_HEADER_X_API_KEY: headerSecret }; + + // Text a service chose, with escape sequences, a bell, both secrets, and a + // workflow command placed at every point where a line may wrap. + const hostile = (n: number): string => + `\u001b]0;title\u0007\u001b[2J\u001b[31mred ${headerSecret} ${payerKey} ${"w ".repeat(n).trim()} ::add-mask::visible ##[group]planted`; + const readResults: CheckResult[] = [ + { id: "X402-01", name: "402 Response Status\u001b[2Kx", pass: true, detail: hostile(1) }, + ]; + const paymentResults: CheckResult[] = Array.from({ length: 40 }, (_, n) => ({ + id: "X402-06", + name: "Signature Resubmit Accepted", + pass: false, + detail: hostile(n + 1), + hint: hostile(n + 2), + })); + + async function run(opts: Record): Promise<{ text: string; code: number; paid: boolean }> { + const out = stream(); + let paid = false; + const payment = emitting(paymentResults); + const code = await liveX402Test( + { network: "stellar:testnet", target: "http://127.0.0.1:9/paid\u001b[2J\u0007", ...opts }, + { method: "post" }, + { + stream: out, + env, + readChecks: emitting(readResults), + paymentChecks: ((options: Parameters[0]) => { + paid = true; + return payment(options); + }) as PaymentChecks, + }, + ); + return { text: out.text, code, paid }; + } + + it("prints only Wasit's own colour codes: the target, a check's name and every detail and fix are sanitised", async () => { + const { text, paid } = await run({}); + assert.equal(paid, true, "the payment checks ran"); + assert.ok(text.includes("\u001b["), "the output is coloured"); + assert.ok(!text.replace(SGR, "").includes("\u001b"), "an escape sequence that is not a colour reached the output"); + assert.ok(!text.includes("\u0007"), "a bell reached the output"); + }); + + it("prints no secret of the environment", async () => { + const { text } = await run({}); + assert.ok(!text.includes(payerKey), "the payer key was printed"); + assert.ok(!text.includes(headerSecret), "a header value was printed"); + assert.match(text, /\[redacted\]/); + }); + + it("starts no line with a workflow command, where the output wraps in the middle of a service's text too", async () => { + const { text } = await run({}); + assert.ok(text.includes("::add-mask::visible"), "the probe text is in the output, in the middle of a line or broken"); + for (const line of runnerLines(text)) { + assert.ok(!line.startsWith("::") && !line.startsWith("##["), `a line starts with a workflow command: ${JSON.stringify(line)}`); + } + }); + + it("keeps the exit code of the plain output, and runs no payment check with --read-only", async () => { + assert.equal((await run({})).code, 1); + const readOnly = await run({ readOnly: true }); + assert.equal(readOnly.paid, false); + assert.match(readOnly.text, /--read-only set: the payment checks were not run\./); + }); +}); From bf3841a1820874c4db7d011b41e664a4b8c22b71 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sat, 21 Nov 2026 05:54:02 +0800 Subject: [PATCH 3/5] fix(core): a report file keeps a settlement reference only on a PASS wasit run writes a reference only on an X402-06 PASS whose settlement was read back from the chain, and the payment proof links one only there. A report file read back could still carry one on another status; it is now dropped when the file is read, so the renderer's own PASS rule is not the only one. A test holds both, for FAIL, ERROR and SKIP. X402-11 gains a test at the exact limit of the authorization it sends: valid for 300 s plus 2 ledgers it is sent, one ledger more and it is discarded unsent. The comment before the RPC check in the payment checks no longer says the payment is built through that RPC on Stellar. --- packages/core/src/baseline.ts | 4 +++- packages/core/src/x402/simulator.ts | 6 +++-- packages/core/test/unit/ci-report.test.ts | 14 +++++++++++ .../core/test/unit/rejected-request.test.ts | 23 +++++++++++++++++++ 4 files changed, 44 insertions(+), 3 deletions(-) diff --git a/packages/core/src/baseline.ts b/packages/core/src/baseline.ts index 9767079..ae5531b 100644 --- a/packages/core/src/baseline.ts +++ b/packages/core/src/baseline.ts @@ -100,7 +100,9 @@ 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) }), + // Wasit writes a reference only on a PASS that read its settlement back (`toStructuredRun`); a file that + // carries one on another status is not taken at its word. + ...(entry["reference"] === undefined || status !== "PASS" ? {} : { 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) }), }; diff --git a/packages/core/src/x402/simulator.ts b/packages/core/src/x402/simulator.ts index 44fd864..f54e35e 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -1573,8 +1573,10 @@ 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). + // The RPC signs and settles nothing itself, but the settlement is read + // through it (and, on EVM and Solana, the payment is built through it): it + // must serve the run's network (D-023). On Stellar the x402 client builds + // the payment through its own default RPC. await assertRpcServesNetwork(options.network, rpcUrl); } catch (error) { // A network no adapter pays on is not a failure of the run: Wasit does not diff --git a/packages/core/test/unit/ci-report.test.ts b/packages/core/test/unit/ci-report.test.ts index 269c4bd..2b89888 100644 --- a/packages/core/test/unit/ci-report.test.ts +++ b/packages/core/test/unit/ci-report.test.ts @@ -566,6 +566,20 @@ describe("the detailed comment", () => { assert.ok(!renderComment({ report: read }).includes("Payment proof"), "and a cut reference is not a hash, so it is never linked"); }); + it("links no payment proof for an X402-06 that did not pass, even when a report or a report file carries a hash for it", () => { + for (const status of ["FAIL", "ERROR", "SKIP"] as const) { + const forged = JSON.parse(JSON.stringify(report([endpoint("weather", [settled(HASH)])]))) as RunReport; + (forged.endpoints[0]!.results[0] as { status: string }).status = status; + // The renderer holds to a PASS by itself, on a report built in memory... + const text = renderComment({ report: forged }); + assert.ok(!text.includes("Payment proof"), status); + assert.ok(!text.includes("stellar.expert"), status); + // ...and a report file read back keeps no reference on another status. + const read = parseRunReport(JSON.parse(JSON.stringify(forged))); + assert.equal(read.endpoints[0]!.results[0]!.reference, undefined, status); + } + }); + 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) }); diff --git a/packages/core/test/unit/rejected-request.test.ts b/packages/core/test/unit/rejected-request.test.ts index bd6f247..6e39497 100644 --- a/packages/core/test/unit/rejected-request.test.ts +++ b/packages/core/test/unit/rejected-request.test.ts @@ -213,6 +213,29 @@ describe("X402-11 signs nothing when it cannot reach a verdict", () => { assert.equal(target.invalid.length, 0, "nothing sent with the invalid request"); }); + it("sends an authorization valid exactly 300 s plus the 2 ledgers of slack, and not one ledger more", async () => { + // The stand-in client signs `latest + ceil(60 / 5) + extra`; the read right before + // sending closes one more ledger. So `extra` puts the expiration that many ledgers + // past the 12 a 60 s lifetime is, less one, after the latest read. + const longest = Math.ceil(REJECTED_REQUEST_MAX_LIFETIME_SECONDS / 5) + 2; + const atLimit = longest - (Math.ceil(60 / 5) - 1); + + install({ extraExpiryLedgers: atLimit }); + const sent = await wall("refuse"); + const inside = byId(await run(sent.url), "X402-11"); + assert.equal(inside.pass, true, inside.detail); + assert.equal(sent.invalid.length, 1, "sent at the limit"); + + recorder.signed.length = 0; + ledger = fakeLedger(); + install({ extraExpiryLedgers: atLimit + 1 }); + const held = await wall("refuse"); + const over = byId(await run(held.url), "X402-11"); + assert.ok(over.error !== undefined, `no verdict expected one ledger over: ${over.detail}`); + assert.match(over.error.message, /longer than the 300 seconds this check waits\. It was signed and discarded; it was not sent\./); + assert.equal(held.invalid.length, 0, "not sent one ledger over the limit"); + }); + 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); From d14ea9e4036c255fc02ac0c1321263bec154019a Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sat, 21 Nov 2026 05:54:02 +0800 Subject: [PATCH 4/5] docs: the unreleased fixes of the action, the CLI and core What changes on upgrade: the events the action runs on and the variables every step sets empty. Fixed: the wrapped lines of the coloured output, and the settlement reference in a report file. --- CHANGELOG.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dd73ac..4bd1108 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ 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. +## [Unreleased] + +**Results can change on upgrade.** +- The GitHub Action runs on `pull_request`, `push`, `schedule`, + `workflow_dispatch` and `merge_group` only. Any other event + (`pull_request_target` as before, now also `issue_comment`, `workflow_run` + and the rest) stops the job with exit 2 in the step that checks the inputs: + on those events a workflow can hand a pull request's code the base + repository's token, and the service Wasit starts would be that code. +- Every step of the Action sets `BASH_ENV`, `ENV`, `LD_PRELOAD`, + `LD_LIBRARY_PATH` and `LD_AUDIT` empty, as it does `NODE_OPTIONS`: a file the + shell runs before a step, or a library loaded into `bash`, `node` or `gh`, + no longer comes from the workflow's env into the steps that hold the token or + the payer key. A service Wasit starts no longer inherits them from the + workflow's env either; set what it needs in `service.start`. + +**Fixed.** +- In the coloured output of `wasit test` (at a terminal, or with + `FORCE_COLOR`), a wrapped line of a fix could start with `::name::` or + `##[name]` from the middle of the text, which a GitHub job log reads as a + workflow command. Every wrapped line is now broken the way the sanitiser + breaks the start of a text. +- `wasit ci-report` keeps a settlement reference from a report file only on a + PASS, as `wasit run` writes it; on any other status it is dropped. + ## [0.8.0-beta.1] - 2026-11-20 A pre-release for beta testers, on npm under the `beta` tag From 2333bad01884e26899b4db77c2d62735f9bcd0d2 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Sat, 21 Nov 2026 06:39:51 +0800 Subject: [PATCH 5/5] docs(action): the step env beats an earlier step's GITHUB_ENV, as seen on a runner The comment said that a step's env winning over an earlier step's GITHUB_ENV for BASH_ENV and the other names was not yet seen on a runner. It was seen on a GitHub-hosted runner on 2026-11-21: an earlier step set BASH_ENV through GITHUB_ENV, a plain step after it ran the file, and each step of this action showed BASH_ENV empty and did not run it. --- action/action.yml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/action/action.yml b/action/action.yml index ab23195..e74f606 100644 --- a/action/action.yml +++ b/action/action.yml @@ -61,12 +61,14 @@ runs: # For the same reason BASH_ENV and ENV (a file the shell runs before the # step) and LD_PRELOAD, LD_LIBRARY_PATH and LD_AUDIT (libraries loaded into # bash, node and gh) are set empty in every step, so the workflow's env does - # not reach them. That a step's env also wins over an earlier step's - # GITHUB_ENV for these names is not yet seen on a runner. A service that - # needs one sets it in its service.start command. None of this keeps the steps apart from code - # that ran earlier in the job as the runner's user: such code can also put a - # program of its own first on PATH (GITHUB_PATH), change files on disk, or - # leave a process running; the example workflow states that limit. + # not reach them, and neither does an earlier step's GITHUB_ENV: seen for + # BASH_ENV on a GitHub-hosted runner, 2026-11-21 (each step of this action + # showed it empty, a plain step after the earlier one ran the file). A + # service that needs one sets it in its service.start command. None of this + # keeps the steps apart from code that ran earlier in the job as the + # runner's user: such code can also put a program of its own first on PATH + # (GITHUB_PATH), change files on disk, or leave a process running; the + # example workflow states that limit. - name: Check the runner shell: bash