From 986ee516b8bdf1ae2f757aab964dd6e6e53732da Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Mon, 16 Nov 2026 07:34:58 +0800 Subject: [PATCH 01/27] fix(core): a request that carries a payment never follows a redirect fetch follows a redirect and keeps a custom header such as PAYMENT-SIGNATURE on the way, so a route that redirects a paid request delivered the signed payment to a second URL, another host or a second handler of the same service, which could settle it while the check graded the first. The verdict was then about the wrong URL. fetchTarget now refuses a redirect answer by default ("never"): nothing is sent to the Location and the check gets no verdict, naming the origin. The old "follow" mode is gone, so a call that forgets to choose cannot leak a payment. The read-only checks keep the same-origin rule. The payment checks read their fresh challenge with fetchPaymentChallenge: one redirect inside the origin is followed when it keeps the request (a POST turned into a GET is refused), and X402-06 to X402-10 pay at the URL that challenge came from; the replay goes to X402-06's URL. MPP charge gives mppx a fetch that refuses redirects, and the MPP reads and channel credentials use the default, since MPP pays at the URL it reads. --- packages/core/src/errors.ts | 105 ++++- packages/core/src/mpp/charge.ts | 4 + packages/core/src/x402/simulator.ts | 36 +- .../test/unit/fetch-target-redirects.test.ts | 8 +- .../test/unit/paid-request-redirects.test.ts | 431 ++++++++++++++++++ 5 files changed, 541 insertions(+), 43 deletions(-) create mode 100644 packages/core/test/unit/paid-request-redirects.test.ts 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/mpp/charge.ts b/packages/core/src/mpp/charge.ts index 5f85a6d..73fab66 100644 --- a/packages/core/src/mpp/charge.ts +++ b/packages/core/src/mpp/charge.ts @@ -28,6 +28,7 @@ import { MalformedResponseError, assertHttpUrl, fetchTarget, + fetchWithoutRedirects, } from "../errors.js"; import { type MppNetwork, assertMppNetwork, isMppNetwork, resolveRpcUrl } from "./network.js"; import { assertPaymentNetworkAllowed } from "../guard/networks.js"; @@ -213,6 +214,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); } diff --git a/packages/core/src/x402/simulator.ts b/packages/core/src/x402/simulator.ts index a5bc318..1a1fde2 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -4,6 +4,7 @@ import { ConfigurationError, MalformedResponseError, assertHttpUrl, + fetchPaymentChallenge, fetchTarget, } from "../errors.js"; import { assertPaymentNetworkAllowed } from "../guard/networks.js"; @@ -543,7 +544,9 @@ async function preparePayment( chain.resolveRpcUrl(options.network, options.rpcUrl), ); - const challenge = await fetchTarget(options.target, buildInit(options)); + // 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)); let paymentRequired; try { @@ -599,7 +602,7 @@ async function preparePayment( const paymentPayload = await withinSpendControls(options.network, selected, () => client.createPaymentPayload(paymentRequired), ); - return { httpClient, paymentPayload, selected, idempotent }; + return { httpClient, paymentPayload, selected, idempotent, payUrl }; } const altered = await alter(selected); @@ -610,7 +613,7 @@ async function preparePayment( }), ); const paymentPayload = { ...signed, accepted: selected }; - return { httpClient, paymentPayload, selected, idempotent }; + return { httpClient, paymentPayload, selected, idempotent, payUrl }; } /** @@ -679,6 +682,8 @@ 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; } @@ -733,18 +738,16 @@ 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, 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, }); @@ -835,7 +838,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); const corrupted = { ...paymentPayload, @@ -843,10 +846,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 +949,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)); } @@ -1013,9 +1013,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 +1065,14 @@ async function checkExpiredRejected(options: X402PaymentCheckOptions): Promise { + const { httpClient, paymentPayload, payUrl } = await preparePayment(options, 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)); diff --git a/packages/core/test/unit/fetch-target-redirects.test.ts b/packages/core/test/unit/fetch-target-redirects.test.ts index 552a1c9..b411fa7 100644 --- a/packages/core/test/unit/fetch-target-redirects.test.ts +++ b/packages/core/test/unit/fetch-target-redirects.test.ts @@ -243,13 +243,11 @@ describe("fetchTarget with redirects: same-origin", () => { }); 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/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"]); + }); +}); From 8d2b69180dc3c4d2a5184825e54d056b905084be Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Mon, 16 Nov 2026 07:35:28 +0800 Subject: [PATCH 02/27] feat(core): check that the RPC serves the run's network before paying The network a run is labelled with and the RPC it is given are separate inputs (--rpc-url, the MCP tool argument rpcUrl), and nothing tied them together: a run labelled stellar:testnet and pointed at a mainnet RPC builds its payment and reads its settlement on the wrong chain. Before any request to the target, the x402 payment checks, MPP charge and the MPP channel suite now ask the RPC which network it serves: Stellar getNetwork (the passphrase), EVM eth_chainId, Solana getGenesisHash (its first 32 characters are the CAIP-2 reference). A mismatch, no answer, a redirect or an unreadable answer refuses the run with nothing sent or signed; a network with no rule is refused too. The message names the RPC's origin only, since its path may hold an API key. The test stand-ins answer the identity method; the MPP charge tests, whose https RPC nothing can serve, use a test-only transport, so the connections they count are still the SDK's own. --- packages/core/src/guard/rpc-identity.ts | 174 ++++++++++++ packages/core/src/mpp/charge.ts | 5 + packages/core/src/mpp/suite.ts | 6 +- packages/core/src/x402/simulator.ts | 6 +- .../core/test/unit/charge-network.test.ts | 12 +- .../core/test/unit/payment-negatives.test.ts | 71 +++-- packages/core/test/unit/rpc-identity.test.ts | 253 ++++++++++++++++++ 7 files changed, 494 insertions(+), 33 deletions(-) create mode 100644 packages/core/src/guard/rpc-identity.ts create mode 100644 packages/core/test/unit/rpc-identity.test.ts diff --git a/packages/core/src/guard/rpc-identity.ts b/packages/core/src/guard/rpc-identity.ts new file mode 100644 index 0000000..ca4a705 --- /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}. Nothing was sent to the target 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}. Nothing was sent to the target 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 nothing was sent to the ` + + `target and nothing was signed. Point the run at an RPC for ${label}.`, + ); + } +} diff --git a/packages/core/src/mpp/charge.ts b/packages/core/src/mpp/charge.ts index 73fab66..49221e3 100644 --- a/packages/core/src/mpp/charge.ts +++ b/packages/core/src/mpp/charge.ts @@ -32,6 +32,7 @@ import { } 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"; @@ -283,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/x402/simulator.ts b/packages/core/src/x402/simulator.ts index 1a1fde2..ff08744 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -8,6 +8,7 @@ import { fetchTarget, } from "../errors.js"; import { assertPaymentNetworkAllowed } from "../guard/networks.js"; +import { assertRpcServesNetwork } from "../guard/rpc-identity.js"; import { sanitizeText } from "../sanitize.js"; import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js"; @@ -1141,7 +1142,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 +1155,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/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/payment-negatives.test.ts b/packages/core/test/unit/payment-negatives.test.ts index 1df4c5d..2fa34b7 100644 --- a/packages/core/test/unit/payment-negatives.test.ts +++ b/packages/core/test/unit/payment-negatives.test.ts @@ -113,24 +113,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( @@ -314,34 +322,39 @@ 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/); + 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 ?? "", /asks for 1000001 base units .* more than the \$1 a payment/); + } + } finally { + await target.close(); } - } finally { - await target.close(); } + } finally { + await sepolia.close(); } }); }); 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); + }); +}); From fcc8edb8cf2d88c756af26eaf78f258c39b5feee Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Mon, 16 Nov 2026 08:57:26 +0800 Subject: [PATCH 03/27] feat(core): hold every x402 signature to $1, the run's cap, the pin and the plan The payment checks paid whatever the SDK client allowed: its default $1 cap on its default assets, and its own pick among the challenge's options. That is an accident of the SDK, not a guard of Wasit's, and the mainnet opt-in needs caps of its own (spec B3, B4). - guard/budget.ts: $1 a payment and $5 a run, fixed; maxRunUsd only lowers the run cap. Each signature is charged before it is made and never credited back; once the cap refuses, the run signs nothing more. Only USDC on the four test networks is valued; any other asset is refused. - x402/plan.ts (L1): reads each endpoint's unpaid challenge, plans what the checks would sign (3.5 times the price), refuses a run whose worst case is above its cap before anything is signed. - preparePayment (L2): on every signature, the pin over every exact option, the plan, the caps; the SDK is handed the one option checked, and a payload whose accepted field differs is discarded unsent. - L3: the SDK's spend controls are set explicitly to $1, and its policy keeps only the pinned payee and asset. - setPaymentChainsForTesting: a recording chain for the worst-case property test; not in the package index. A price above $1 now gets Wasit's own refusal, as a setup error with nothing sent, where it got the SDK's before. Run live on testnet on all four chains, Permit2 included, before this commit. --- packages/core/src/guard/budget.ts | 280 ++++++++++++++++++ packages/core/src/index.ts | 12 + packages/core/src/x402/chains/evm.ts | 3 + packages/core/src/x402/chains/index.ts | 17 +- packages/core/src/x402/plan.ts | 232 +++++++++++++++ packages/core/src/x402/simulator.ts | 202 ++++++++++--- packages/core/test/support/recording-chain.ts | 175 +++++++++++ .../core/test/unit/payment-budget.test.ts | 226 ++++++++++++++ .../core/test/unit/payment-guard-l2.test.ts | 273 +++++++++++++++++ .../core/test/unit/payment-negatives.test.ts | 19 +- packages/core/test/unit/worst-case.test.ts | 144 +++++++++ 11 files changed, 1530 insertions(+), 53 deletions(-) create mode 100644 packages/core/src/guard/budget.ts create mode 100644 packages/core/src/x402/plan.ts create mode 100644 packages/core/test/support/recording-chain.ts create mode 100644 packages/core/test/unit/payment-budget.test.ts create mode 100644 packages/core/test/unit/payment-guard-l2.test.ts create mode 100644 packages/core/test/unit/worst-case.test.ts diff --git a/packages/core/src/guard/budget.ts b/packages/core/src/guard/budget.ts new file mode 100644 index 0000000..35d206a --- /dev/null +++ b/packages/core/src/guard/budget.ts @@ -0,0 +1,280 @@ +/** + * 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. 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) { + super(`${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. + */ +export function plannedSignatures(price: bigint): 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 }, + ]; +} + +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)} a payment that is 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/index.ts b/packages/core/src/index.ts index 259be58..9368f82 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -132,6 +132,18 @@ export { } from "./guard/networks.js"; export type { NetworkClass, PaymentProtocol } from "./guard/networks.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/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/plan.ts b/packages/core/src/x402/plan.ts new file mode 100644 index 0000000..d28d4e7 --- /dev/null +++ b/packages/core/src/x402/plan.ts @@ -0,0 +1,232 @@ +/** + * 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 { readPaymentChallenge, type RequestShape } from "./simulator.js"; + +export interface PlanEndpointInput extends RequestShape { + readonly name: string; + readonly target: string; +} + +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)} a payment that is fixed in Wasit. Nothing was signed. Test a route ` + + `priced at ${formatUsd(perPayment)} or less.`, + option, + ); + } + const signatures = plannedSignatures(amount); + 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/simulator.ts b/packages/core/src/x402/simulator.ts index ff08744..69fa840 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -7,8 +7,17 @@ import { 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 { sanitizeText } from "../sanitize.js"; import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js"; @@ -400,6 +409,15 @@ 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; } /** One check has nothing to test against this target; it is skipped with the reason. */ @@ -455,16 +473,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) }; } @@ -518,40 +547,22 @@ 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), - ); - +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)); let paymentRequired; try { - paymentRequired = httpClient.getPaymentRequiredResponse((name) => + paymentRequired = new x402HTTPClient(new x402Client()).getPaymentRequiredResponse((name) => challenge.headers.get(name), ); } catch (error) { @@ -571,6 +582,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 @@ -597,23 +609,122 @@ 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, payUrl }; +} - 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.`, ); - return { httpClient, paymentPayload, selected, idempotent, payUrl }; } + 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 }; + // 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, so it was discarded and not sent.`, + ); + } + const paymentPayload = alter === undefined ? signed : { ...signed, accepted: selected }; return { httpClient, paymentPayload, selected, idempotent, payUrl }; } @@ -739,7 +850,7 @@ 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, payUrl } = 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); @@ -839,7 +950,7 @@ async function checkSignatureAccepted(options: X402PaymentCheckOptions): Promise async function checkInvalidSignatureRejected( options: X402PaymentCheckOptions, ): Promise { - const { httpClient, paymentPayload, payUrl } = await preparePayment(options); + const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-07"); const corrupted = { ...paymentPayload, @@ -991,7 +1102,7 @@ async function checkUnderpaymentRejected(options: X402PaymentCheckOptions): Prom let offered = 0n; let prepared; try { - prepared = await preparePayment(options, (selected) => { + prepared = await preparePayment(options, "X402-09", (selected) => { try { advertised = BigInt(selected.amount); } catch { @@ -1066,7 +1177,7 @@ 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; @@ -1128,8 +1239,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); diff --git a/packages/core/test/support/recording-chain.ts b/packages/core/test/support/recording-chain.ts new file mode 100644 index 0000000..4f0e1e1 --- /dev/null +++ b/packages/core/test/support/recording-chain.ts @@ -0,0 +1,175 @@ +/** + * 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; +} + +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: { 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/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-guard-l2.test.ts b/packages/core/test/unit/payment-guard-l2.test.ts new file mode 100644 index 0000000..1fce63f --- /dev/null +++ b/packages/core/test/unit/payment-guard-l2.test.ts @@ -0,0 +1,273 @@ +/** + * 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("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/); + 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 2fa34b7..ddd9a33 100644 --- a/packages/core/test/unit/payment-negatives.test.ts +++ b/packages/core/test/unit/payment-negatives.test.ts @@ -320,8 +320,9 @@ 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 () => { + // 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 [ @@ -347,7 +348,10 @@ describe("on Ethereum Sepolia", () => { 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/); + assert.match( + r["X402-06"]?.detail ?? "", + /X402-06 would sign 1000001 base units of USDC \(\$1\.000001\), above the \$1\.00 a payment .* Nothing was signed\./, + ); } } finally { await target.close(); @@ -359,12 +363,13 @@ describe("on Ethereum Sepolia", () => { }); }); -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 a payment that is 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 { 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`); + } + } + }); +}); From 60f7097542dda3b40dbf5fdfb3079f28227d378c Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Mon, 16 Nov 2026 08:57:33 +0800 Subject: [PATCH 04/27] feat(cli): wasit run --dry-run prints what the payment checks would sign A builder should see what a paying run would sign before it signs anything (spec B5, safety rule 5). The dry run is L0 and L1 only: it reads each x402 endpoint's unpaid challenge and prints, 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), and the pin when the config sets one. It uses no key, sends no payment and signs nothing. It exits 2 when a paying run would be refused: a worst case above the cap, an endpoint the guard refuses, a network that is not a test network, or operatedByMe not set. MPP endpoints are named as not planned. It takes neither --read-only nor --json, --out or --baseline. --- packages/cli/src/index.ts | 13 +- packages/cli/src/run.ts | 90 ++++++++- packages/cli/test/unit/run-cli.test.ts | 13 +- packages/cli/test/unit/run-dry-run.test.ts | 202 +++++++++++++++++++++ 4 files changed, 305 insertions(+), 13 deletions(-) create mode 100644 packages/cli/test/unit/run-dry-run.test.ts diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 70e172d..f57d790 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -269,7 +269,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 (read-only or a dry run in this version)") .option("--config ", "The config file", "wasit.config.json") .option("--env ", "The environment to run (default: defaultEnvironment, else the only one)") .option( @@ -280,7 +280,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). They send no payment and sign nothing. The only tier in this version: it, or --dry-run, is required.", + 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) @@ -309,6 +316,7 @@ 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 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 @@ -325,6 +333,7 @@ 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, diff --git a/packages/cli/src/run.ts b/packages/cli/src/run.ts index 584f120..1bbb3c4 100644 --- a/packages/cli/src/run.ts +++ b/packages/cli/src/run.ts @@ -2,12 +2,16 @@ * `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. + * In this version a run is read-only, or a dry run. The payment tier is refused + * before a config is read or anything is sent; `--mainnet` and a key flag 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. + * + * `--dry-run` (spec B5) runs L0 and L1 only: it reads each x402 endpoint's + * unpaid challenge, prints what the payment checks would sign and the caps, + * and exits. It uses no key, sends no payment and signs nothing. * * `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,12 +21,16 @@ import { readFileSync, statSync, writeFileSync } from "node:fs"; import { ConfigError, + ConfigurationError, MAX_BASELINE_BYTES, buildEndpointReport, buildRunReport, deniedEnvValues, + describePlan, + describeRun, errored, isLoopbackUrl, + planX402Run, readBaseline, readConfigFile, readBuildCommit, @@ -50,6 +58,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; @@ -108,6 +118,54 @@ 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 { + const x402 = resolved.endpoints.filter((endpoint) => endpoint.protocol === "x402"); + let plan; + try { + plan = await planX402Run({ + network: resolved.network, + ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }), + ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }), + endpoints: 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 }), + })), + }); + } 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,10 +175,18 @@ export async function executeRun(options: RunCommandOptions, context: RunContext return 2; }; - if (!options.readOnly) { + 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.readOnly && !dryRun) { 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.", + "unpaid challenge checks, which send no payment and sign nothing, or --dry-run to see what " + + "the payment checks would sign.", ); } @@ -186,6 +252,14 @@ 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(); try { const endpoints = []; diff --git a/packages/cli/test/unit/run-cli.test.ts b/packages/cli/test/unit/run-cli.test.ts index 24e9c6d..1e576c7 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 [["--mainnet"], ["--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); @@ -101,11 +101,18 @@ describe("the wasit binary", () => { } }); - it("--help works and exits 0", async () => { + it("--help works and exits 0, and offers --dry-run but no mainnet or 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.ok(!/--mainnet|--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); + }); +}); From b83fa7825c697dd72426d6a6e0f68e69b0f54d72 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Mon, 16 Nov 2026 10:34:54 +0800 Subject: [PATCH 05/27] feat(core): say which GitHub events may pay, and show no change for checks a tier did not run The payment tier must run only where merged code runs (D-022a): a push to the default branch, a schedule, workflow_dispatch on the default branch. paymentEventGate refuses every pull request event and every other event, and a push or a dispatch whose event file does not name the default branch. payerKeyVariables names the key variables that hold a value, so a run can refuse a key given to a run that may not pay; a fork's empty secrets do not count. A pull request runs the read-only tier while main may pay, so diffReports no longer reports a check that either run skipped by tier (read-only, no payer key) as a change or as fixed. paymentChecksSkipped lets a front end word why the payment checks did not run, and an L2 refusal against the plan now ends with the plan's reason. --- packages/core/src/baseline.ts | 14 ++ packages/core/src/guard/ci-event.ts | 124 ++++++++++++++ packages/core/src/index.ts | 5 + packages/core/src/report.ts | 9 + packages/core/src/x402/simulator.ts | 3 +- packages/core/test/unit/baseline.test.ts | 40 +++++ .../core/test/unit/payment-event-gate.test.ts | 155 ++++++++++++++++++ 7 files changed, 349 insertions(+), 1 deletion(-) create mode 100644 packages/core/src/guard/ci-event.ts create mode 100644 packages/core/test/unit/payment-event-gate.test.ts diff --git a/packages/core/src/baseline.ts b/packages/core/src/baseline.ts index 8667b87..7629dfa 100644 --- a/packages/core/src/baseline.ts +++ b/packages/core/src/baseline.ts @@ -368,6 +368,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 +403,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/guard/ci-event.ts b/packages/core/src/guard/ci-event.ts new file mode 100644 index 0000000..83c879c --- /dev/null +++ b/packages/core/src/guard/ci-event.ts @@ -0,0 +1,124 @@ +/** + * 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; +} + +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. */ +export function inGithubActions(env: Readonly>): boolean { + return env["GITHUB_ACTIONS"] === "true" || 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)) 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. + if (name === "schedule") 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/index.ts b/packages/core/src/index.ts index 9368f82..69fd8b9 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"; @@ -132,6 +133,10 @@ export { } from "./guard/networks.js"; export type { NetworkClass, PaymentProtocol } from "./guard/networks.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, diff --git a/packages/core/src/report.ts b/packages/core/src/report.ts index f7ca8d1..1a371f2 100644 --- a/packages/core/src/report.ts +++ b/packages/core/src/report.ts @@ -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/x402/simulator.ts b/packages/core/src/x402/simulator.ts index 69fa840..40f6bdf 100644 --- a/packages/core/src/x402/simulator.ts +++ b/packages/core/src/x402/simulator.ts @@ -632,7 +632,8 @@ function plannedAmount(plan: EndpointPlan | undefined, check: string, selected: 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.`, + `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}`), ); } for (const field of ["scheme", "network", "payTo", "asset"] as const) { 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/payment-event-gate.test.ts b/packages/core/test/unit/payment-event-gate.test.ts new file mode 100644 index 0000000..428486a --- /dev/null +++ b/packages/core/test/unit/payment-event-gate.test.ts @@ -0,0 +1,155 @@ +/** + * 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 GitHub Actions", () => { + assert.deepEqual(paymentEventGate({}, undefined), { allowed: true }); + assert.deepEqual(paymentEventGate({ CI: "true" }, undefined), { allowed: true }); + }); + + 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("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); + }); +}); From 9a1b8094414b03af2b11c717a53ddf2e51871c09 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Mon, 16 Nov 2026 10:35:04 +0800 Subject: [PATCH 06/27] feat(cli): wasit run pays on test networks, and starts the service as its own user on hosted runners Without --read-only and --dry-run, wasit run is the payment tier. It pays only when the GitHub event may pay, the network is a test network (L0, checked before the service starts), the environment is operatedByMe, the chain's key variable is set and the plan (L1) fits the caps. Then one budget is shared by every endpoint, and each endpoint's checks get its entry of the plan, the pin and the RPC url, so L2 holds every signature to what was planned. The first line says it pays, on which network, from which payer and up to how much; the report's note says what was charged. On a pull request the run is the read-only tier and says why. A payer key set on a run that may not pay is refused before the service starts: the service of a pull request would run in the same job as the key (D-022a, Najmi 2026-11-16). The payment tier asked for and not paid (no key, or operatedByMe not true) exits 2 instead of green. On a GitHub-hosted runner, when a payer key is set, --start runs the service as the user wasit-service: made with passwordless sudo, given the working directory by ACL and nothing on .git, started with sudo -E so no value lands on a command line, and stopped by user. When sudo, useradd or setfacl fails the run stops; it never falls back to the runner's user. --- packages/cli/src/index.ts | 13 +- packages/cli/src/run-format.ts | 6 +- packages/cli/src/run.ts | 265 +++++++++++-- packages/cli/src/service.ts | 187 ++++++++- packages/cli/test/unit/payment-helpers.ts | 164 ++++++++ packages/cli/test/unit/run-cli.test.ts | 22 +- packages/cli/test/unit/run-payment.test.ts | 395 ++++++++++++++++++++ packages/cli/test/unit/run.test.ts | 9 +- packages/cli/test/unit/service-user.test.ts | 228 +++++++++++ 9 files changed, 1230 insertions(+), 59 deletions(-) create mode 100644 packages/cli/test/unit/payment-helpers.ts create mode 100644 packages/cli/test/unit/run-payment.test.ts create mode 100644 packages/cli/test/unit/service-user.test.ts diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index f57d790..91212a2 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -269,7 +269,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 or a dry run 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 +280,7 @@ 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: it, or --dry-run, 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( @@ -317,10 +317,17 @@ Examples: $ 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 CI (CI or GITHUB_ACTIONS set) a .env file in the working directory is not read.`, ) .exitOverride(exitTwoOnUsageError) 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 1bbb3c4..a3d9832 100644 --- a/packages/cli/src/run.ts +++ b/packages/cli/src/run.ts @@ -2,16 +2,22 @@ * `wasit run`: the endpoints of a `wasit.config.json`, one after another, with * one report (spec A2, A8). * - * In this version a run is read-only, or a dry run. The payment tier is refused - * before a config is read or anything is sent; `--mainnet` and a key flag 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. * - * `--dry-run` (spec B5) runs L0 and L1 only: it reads each x402 endpoint's - * unpaid challenge, prints what the payment checks would sign and the caps, - * and exits. It uses no key, sends no payment and signs nothing. + * 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). * * `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. @@ -23,21 +29,31 @@ import { ConfigError, ConfigurationError, MAX_BASELINE_BYTES, + PER_PAYMENT_CAP_USD, + RunBudget, + assertPaymentNetworkAllowed, buildEndpointReport, buildRunReport, deniedEnvValues, describePlan, describeRun, errored, + formatUsd, isLoopbackUrl, + payerKeyVariables, + paymentChainFor, + paymentChecksSkipped, + paymentEventGate, planX402Run, readBaseline, readConfigFile, readBuildCommit, + readGithubEvent, readToolVersions, redactReport, resolveRun, runExitCode, + runX402PaymentChecks, runX402ReadChecks, sanitizeText, selectBaseline, @@ -45,12 +61,18 @@ import { urlOrigin, type BaselineResult, type CheckResult, + type PaymentChain, + type PinTerms, type ResolvedEndpoint, type ResolvedRun, + type RunPlan, + type RunVerdict, + type SkipKind, + UnsupportedPaymentNetworkError, } 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 { @@ -81,30 +103,112 @@ 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; + }; + +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, }); - 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 }), + })); +} + +/** + * 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 || '' }}` + ); +} + +/** 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 { @@ -128,20 +232,13 @@ async function printPlan( clean: (text: string) => string, fail: (message: string) => number, ): Promise { - const x402 = resolved.endpoints.filter((endpoint) => endpoint.protocol === "x402"); let plan; try { plan = await planX402Run({ network: resolved.network, ...(resolved.pinned === undefined ? {} : { pin: resolved.pinned }), ...(resolved.maxRunUsd === undefined ? {} : { maxRunUsd: resolved.maxRunUsd }), - endpoints: 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 }), - })), + endpoints: planEndpoints(resolved), }); } catch (error) { // L0: a network that is not a test network, refused before any request. @@ -182,14 +279,6 @@ export async function executeRun(options: RunCommandOptions, context: RunContext 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.readOnly && !dryRun) { - 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, or --dry-run to see what " + - "the payment checks would sign.", - ); - } - if (options.start && options.startIfLocal === true) { return fail("wasit run: choose --start or --start-if-local, not both."); } @@ -209,6 +298,42 @@ 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.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; + // 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; @@ -227,6 +352,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) { @@ -245,6 +372,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); @@ -261,10 +389,61 @@ export async function executeRun(options: RunCommandOptions, context: RunContext } 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, + }; + 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, @@ -276,6 +455,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, @@ -283,7 +469,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), @@ -291,10 +477,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..41b5611 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,91 @@ 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 `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 +219,53 @@ 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 +341,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/test/unit/payment-helpers.ts b/packages/cli/test/unit/payment-helpers.ts new file mode 100644 index 0000000..a4fd079 --- /dev/null +++ b/packages/cli/test/unit/payment-helpers.ts @@ -0,0 +1,164 @@ +/** + * 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[]; +} + +function recordingChain(recorder: Recorder): PaymentChain { + return { + name: "Recording", + networks: [NETWORK], + payerKeyEnv: 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 (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" }), + }; +} + +/** Installs the recording chain and an RPC that serves Base Sepolia. Returns the undo. */ +export function installRecordingChain(recorder: Recorder): () => void { + setPaymentChainsForTesting([recordingChain(recorder)]); + 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 1e576c7..4fca666 100644 --- a/packages/cli/test/unit/run-cli.test.ts +++ b/packages/cli/test/unit/run-cli.test.ts @@ -88,13 +88,31 @@ describe("the wasit binary", () => { 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(); 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..0e0d0ce --- /dev/null +++ b/packages/cli/test/unit/run-payment.test.ts @@ -0,0 +1,395 @@ +/** + * 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 { 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("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("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..eb79db6 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", () => { 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..35236db --- /dev/null +++ b/packages/cli/test/unit/service-user.test.ts @@ -0,0 +1,228 @@ +/** + * 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 -E -u ` with the scrubbed + * environment, 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 { SERVICE_USER, ServiceError, serviceUserFor, startService, type StartedService } from "../../src/service.js"; + +const POSIX = process.platform !== "win32"; +const CANARY = "SCANARYKEYTHATHOLDSNOTHINGATALLXXXXXXXXXXXXXXXXXXXXXXXXXX"; + +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) shift; [ "$1" = "-u" ] || exit 65; 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")); + const launch = calls.find((call) => call.startsWith("-n -E -u wasit-service -- env ")); + assert.ok(launch, calls.join("\n")); + assert.match(launch, /HOME=\/home\/wasit-service/); + assert.match(launch, /USER=wasit-service/); + assert.ok(!launch.includes(CANARY) && !launch.includes("hdr-secret"), "a secret was put on the command line"); + assert.ok(!launch.includes("KEEP_ME"), "the environment is passed by sudo -E, 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["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 -E")), "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), + ); + }); +}); From 41f04c0b087cbfba064c31dbad474a54448c7b50 Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Mon, 16 Nov 2026 10:35:04 +0800 Subject: [PATCH 07/27] feat(action): accept tier payment, and take baselines from push, schedule and dispatch tier: payment reaches the CLI as wasit run without --read-only; whether the event may pay is the CLI's decision, so one workflow serves pull requests (read-only, with the reason) and main (payment). The baseline is uploaded on a schedule and on workflow_dispatch on the default branch as well as on a push, and baseline.mjs takes runs of those three events, never a pull request, merge_group or workflow_run run. The template workflow shows the payment tier in comments: a dedicated testnet payer, the key on the Wasit step only and only for events that may pay, and what the separate service user does and does not keep from the key. --- action/action.yml | 19 ++++++++++++------- action/examples/wasit.yml | 16 ++++++++++++++++ action/scripts/baseline.mjs | 19 ++++++++++++++----- action/scripts/inputs.mjs | 15 ++++++++------- action/test/action-yaml.test.mjs | 9 +++++++-- action/test/baseline.test.mjs | 15 +++++++++++---- action/test/inputs.test.mjs | 31 +++++++++++++++++++++++-------- action/test/wasit-script.test.mjs | 30 +++++++++++++++++++++--------- 8 files changed, 112 insertions(+), 42 deletions(-) diff --git a/action/action.yml b/action/action.yml index 1f86d84..869f7f0 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,8 +18,12 @@ 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-10) 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: @@ -117,7 +122,7 @@ runs: # 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 with: name: wasit-baseline diff --git a/action/examples/wasit.yml b/action/examples/wasit.yml index 123f675..4efb21a 100644 --- a/action/examples/wasit.yml +++ b/action/examples/wasit.yml @@ -45,6 +45,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/baseline.mjs b/action/scripts/baseline.mjs index 485d6b0..fdd57a5 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(); /** @@ -45,7 +53,7 @@ export function selectBaselineRun(runs, context) { 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) && @@ -82,13 +90,14 @@ export async function findBaseline({ gh, repository, runId, directory, defaultBr 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. + // The API takes one event at a time, so the events are filtered here. 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`, + `repos/${repository}/actions/workflows/${workflowId}/runs?branch=${encodeURIComponent(branch)}${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`); + if (chosen === undefined) return none(`no successful push, schedule or workflow_dispatch 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 : []) diff --git a/action/scripts/inputs.mjs b/action/scripts/inputs.mjs index 9373304..0242090 100644 --- a/action/scripts/inputs.mjs +++ b/action/scripts/inputs.mjs @@ -30,7 +30,7 @@ function trimmed(value) { * `INPUT_ENVIRONMENT`, `INPUT_TIER`, `INPUT_ENDPOINTS`, and the event name). * * @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 +40,10 @@ export function parseInputs(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 +68,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 +83,7 @@ export function buildRunArgs(inputs, paths) { return [ paths.cli, "run", - "--read-only", + ...(inputs.tier === "payment" ? [] : ["--read-only"]), "--start-if-local", "--json", "--out", diff --git a/action/test/action-yaml.test.mjs b/action/test/action-yaml.test.mjs index a658d93..93ab319 100644 --- a/action/test/action-yaml.test.mjs +++ b/action/test/action-yaml.test.mjs @@ -38,7 +38,9 @@ describe("action.yml", () => { 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", () => { @@ -179,10 +181,13 @@ 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"); }); diff --git a/action/test/baseline.test.mjs b/action/test/baseline.test.mjs index 68c2779..797bde6 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/); }); diff --git a/action/test/inputs.test.mjs b/action/test/inputs.test.mjs index 326966d..87fefc9 100644 --- a/action/test/inputs.test.mjs +++ b/action/test/inputs.test.mjs @@ -35,13 +35,20 @@ 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, 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 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, + ); } }); }); @@ -95,9 +102,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", () => { diff --git a/action/test/wasit-script.test.mjs b/action/test/wasit-script.test.mjs index dd70c42..f78dac9 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 () => { @@ -307,6 +308,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 +344,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", @@ -424,8 +435,9 @@ http.createServer((req, res) => { 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("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); }); }); From dc706f06a81c2ad97bed9ca371c04f3adbdc6efa Mon Sep 17 00:00:00 2001 From: Muhammad Dzakwan Najmi Date: Mon, 16 Nov 2026 13:06:48 +0800 Subject: [PATCH 08/27] feat(core): name the green run a comment compares with, and count failures from every run D-022b option 2: "Changed since main" compares with the last green run on main, and the recent-failures line counts every finished run there, failed ones included. The comment now says which run it compares with ("Compared with the last green run on main: run , started