@wasit-dev/core 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  import { errored, skipped } from "../check.js";
2
2
  import { CheckSetupError, ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
3
+ import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js";
3
4
  const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
4
5
  const KNOWN_METHODS = new Set([
5
6
  "GET",
@@ -69,6 +70,22 @@ const READ_CHECKS = [
69
70
  ["X402-04", "Required Fields Present"],
70
71
  ["X402-05", "Network Identifier Valid"],
71
72
  ];
73
+ /** What a wrong status on an unpaid request usually means, and what to do. */
74
+ function statusHint(status) {
75
+ if (status >= 200 && status < 300) {
76
+ return (`The route served HTTP ${status} without payment: put the x402 payment ` +
77
+ `middleware in front of it, so unpaid requests get 402 and a challenge.`);
78
+ }
79
+ if (status === 401 || status === 403) {
80
+ return (`Answer an unpaid request with 402, not ${status}: authentication errors ` +
81
+ `and payment challenges are different signals, and x402 clients act only on 402.`);
82
+ }
83
+ if (status === 404 || status === 405) {
84
+ return (`A ${status} usually means the wrong path or method. Check the URL, and ` +
85
+ `pass the method the endpoint uses (--method POST, MCP \`method\`).`);
86
+ }
87
+ return "Answer an unpaid request with 402 Payment Required and the challenge in a PAYMENT-REQUIRED header.";
88
+ }
72
89
  /** Skips every check after `id`, naming the one cause they all depend on. */
73
90
  function skipAfter(id, reason) {
74
91
  const index = READ_CHECKS.findIndex(([candidate]) => candidate === id);
@@ -79,72 +96,6 @@ function asRecord(value) {
79
96
  ? value
80
97
  : undefined;
81
98
  }
82
- /** x402 v2 nests the payment terms inside `accepts[]`, not at the top level. */
83
- function firstAccept(payload) {
84
- const accepts = asRecord(payload)?.["accepts"];
85
- return Array.isArray(accepts) ? asRecord(accepts[0]) : undefined;
86
- }
87
- /**
88
- * The field carrying the price, per protocol version.
89
- *
90
- * x402 v2 renamed `maxAmountRequired` to `amount` and dropped the embedded
91
- * resource object. Checking for whichever name happens to be present would
92
- * hide a real conformance failure: a service advertising `x402Version: 2`
93
- * while emitting the v1 field name is not conformant to the version it claims.
94
- */
95
- const PRICE_FIELD = {
96
- 1: "maxAmountRequired",
97
- 2: "amount",
98
- };
99
- function isSupportedVersion(value) {
100
- return value === 1 || value === 2;
101
- }
102
- function nonEmptyString(value) {
103
- return typeof value === "string" && value.length > 0;
104
- }
105
- /** X402-04: the challenge must carry price, network, and payTo. */
106
- function checkRequiredFields(payload) {
107
- const version = asRecord(payload)?.["x402Version"];
108
- const accept = firstAccept(payload);
109
- if (!isSupportedVersion(version)) {
110
- return {
111
- id: "X402-04",
112
- name: "Required Fields Present",
113
- pass: false,
114
- detail: `Challenge advertises x402Version ${JSON.stringify(version)}, which is ` +
115
- `neither 1 nor 2. The payment terms use different field names per ` +
116
- `version, so they cannot be checked against an unknown one.`,
117
- };
118
- }
119
- const expected = PRICE_FIELD[version];
120
- const wrongVersionField = version === 2 ? "maxAmountRequired" : "amount";
121
- // A v2 challenge carrying the v1 field name is a specific, actionable
122
- // failure — say which name was found and which one the version requires,
123
- // rather than reporting the price as simply absent.
124
- if (!nonEmptyString(accept?.[expected]) && accept?.[wrongVersionField] !== undefined) {
125
- return {
126
- id: "X402-04",
127
- name: "Required Fields Present",
128
- pass: false,
129
- detail: `Challenge advertises x402Version ${version} but carries ` +
130
- `\`${wrongVersionField}\`, which is the v${version === 2 ? 1 : 2} field ` +
131
- `name. v${version} requires \`${expected}\`.`,
132
- };
133
- }
134
- const missing = [
135
- nonEmptyString(accept?.[expected]) ? null : expected,
136
- nonEmptyString(accept?.["network"]) ? null : "network",
137
- nonEmptyString(accept?.["payTo"]) ? null : "payTo",
138
- ].filter((entry) => entry !== null);
139
- return {
140
- id: "X402-04",
141
- name: "Required Fields Present",
142
- pass: missing.length === 0,
143
- detail: missing.length === 0
144
- ? `All required v${version} fields present.`
145
- : `Missing: ${missing.join(", ")}.`,
146
- };
147
- }
148
99
  /**
149
100
  * Reads an x402 v1 challenge from a 402 response body, if that is what it is.
150
101
  *
@@ -173,24 +124,6 @@ async function readText(response) {
173
124
  return "";
174
125
  }
175
126
  }
176
- /** X402-05: the network identifier must be CAIP-2. */
177
- function checkNetworkIdentifier(payload) {
178
- const network = firstAccept(payload)?.["network"];
179
- // Absent is X402-04's finding, not a second one: report it there only.
180
- if (typeof network !== "string" || network.length === 0) {
181
- return skipped("X402-05", "Network Identifier Valid", "the challenge carries no network field to validate (see X402-04).");
182
- }
183
- const pass = /^stellar:(testnet|pubnet)$/.test(network);
184
- return {
185
- id: "X402-05",
186
- name: "Network Identifier Valid",
187
- pass,
188
- detail: pass
189
- ? `Network identifier "${network}" is valid.`
190
- : `"${network}" does not match stellar:testnet or stellar:pubnet, the CAIP-2 ` +
191
- `identifiers the \`exact\` scheme on Stellar defines.`,
192
- };
193
- }
194
127
  /**
195
128
  * Runs X402-01 through X402-05 against a target.
196
129
  *
@@ -234,6 +167,7 @@ export async function runX402ReadChecks(options) {
234
167
  detail: statusPass
235
168
  ? "Server responded with 402 as required."
236
169
  : `Expected status 402, got ${response.status}.`,
170
+ ...(statusPass ? {} : { hint: statusHint(response.status) }),
237
171
  };
238
172
  if (!statusPass) {
239
173
  return emit([
@@ -258,10 +192,20 @@ export async function runX402ReadChecks(options) {
258
192
  ? "Payment header found."
259
193
  : v1Payload !== undefined
260
194
  ? `Neither PAYMENT-REQUIRED nor X-Payment header was present. The ` +
261
- `response body carries an x402 v1 challenge instead; the \`exact\` ` +
262
- `scheme on Stellar is defined for v2 only, which signals payment in ` +
263
- `the PAYMENT-REQUIRED header.`
195
+ `response body carries an x402 v1 challenge instead; x402 v2 signals ` +
196
+ `payment in the PAYMENT-REQUIRED header, and the \`exact\` scheme on ` +
197
+ `Stellar is defined for v2 only.`
264
198
  : "Neither PAYMENT-REQUIRED nor X-Payment header was present.",
199
+ ...(headerValue !== null
200
+ ? {}
201
+ : {
202
+ hint: v1Payload !== undefined
203
+ ? "Move to x402 v2: send the challenge base64-encoded in a " +
204
+ "PAYMENT-REQUIRED response header instead of the body, with " +
205
+ "x402Version 2 and v2 field names."
206
+ : "Send the challenge as base64-encoded JSON in a PAYMENT-REQUIRED " +
207
+ "response header, as the x402 v2 HTTP transport defines.",
208
+ }),
265
209
  };
266
210
  if (headerValue === null && v1Payload !== undefined) {
267
211
  return emit([
@@ -299,6 +243,8 @@ export async function runX402ReadChecks(options) {
299
243
  name: "Header Payload Decodable",
300
244
  pass: false,
301
245
  detail: `Failed to decode/parse: ${error.message}`,
246
+ hint: "Base64-encode the JSON PaymentRequired object for the header; raw " +
247
+ "JSON or a truncated value does not decode.",
302
248
  },
303
249
  ...skipAfter("X402-03", "the payment header did not decode to JSON, so no payload was " +
304
250
  "available to inspect."),
@@ -316,11 +262,16 @@ export async function runX402ReadChecks(options) {
316
262
  ]));
317
263
  }
318
264
  import { x402Client, x402HTTPClient } from "@x402/fetch";
319
- import { createEd25519Signer } from "@x402/stellar";
320
- import { ExactStellarScheme as ExactStellarClientScheme } from "@x402/stellar/exact/client";
321
- import { Keypair, xdr } from "@stellar/stellar-sdk";
322
- import { resolveRpcUrl } from "../mpp/network.js";
323
- import { verifySettlement } from "../settlement.js";
265
+ import { paymentChainFor, paymentNetworks } from "./chains/index.js";
266
+ import { stellarChain } from "./chains/stellar.js";
267
+ export { corruptAuthSignature } from "./chains/stellar.js";
268
+ /** One check has nothing to test against this target; it is skipped with the reason. */
269
+ class CheckNotApplicable extends Error {
270
+ constructor(reason) {
271
+ super(reason);
272
+ this.name = "CheckNotApplicable";
273
+ }
274
+ }
324
275
  /** The payment flow was never started, so neither payment check has a verdict. */
325
276
  class PaymentNotAttemptedError extends Error {
326
277
  constructor(reason) {
@@ -328,19 +279,84 @@ class PaymentNotAttemptedError extends Error {
328
279
  this.name = "PaymentNotAttemptedError";
329
280
  }
330
281
  }
331
- function buildX402Client(network, payerSecretKey) {
332
- const signer = createEd25519Signer(payerSecretKey, network);
333
- const client = new x402Client().register("stellar:*", new ExactStellarClientScheme(signer));
282
+ /**
283
+ * The adapter for the run's network. Throws `ConfigurationError` for a
284
+ * network the payment checks cannot pay on; preflight calls this before
285
+ * anything is sent.
286
+ */
287
+ function chainFor(network) {
288
+ const chain = paymentChainFor(network);
289
+ if (chain === undefined) {
290
+ throw new ConfigurationError(`The payment checks pay on ${paymentNetworks().join(", ")}; "${network}" is ` +
291
+ `not one of them. X402-01..05 still apply to a challenge on any chain ` +
292
+ `(--read-only, MCP readOnly).`);
293
+ }
294
+ return chain;
295
+ }
296
+ async function buildX402Client(chain, network, payerSecretKey, rpcUrl) {
297
+ const client = new x402Client();
298
+ await chain.registerPayer(client, network, payerSecretKey, rpcUrl);
299
+ client
300
+ // A challenge may offer several networks, including both Stellar ones.
301
+ // The client's default pick is the first it supports, which would sign
302
+ // for one network with a signer built for another; pay only on the
303
+ // network this run was asked to use.
304
+ .registerPolicy((_version, requirements) => requirements.filter((requirement) => requirement.network === network));
334
305
  return { client, httpClient: new x402HTTPClient(client) };
335
306
  }
307
+ /** The networks a challenge offers, for a report. */
308
+ function describeOffered(accepts) {
309
+ const networks = [...new Set(accepts.map((requirement) => requirement.network))];
310
+ return networks.length === 0 ? "none" : networks.join(", ");
311
+ }
312
+ /** What the SDK client's spend controls say when they refuse a payment. */
313
+ const SPEND_CONTROLS_REFUSAL = "All payment requirements were rejected by spendControls";
314
+ /**
315
+ * Builds a payment, turning a refusal by the SDK client's spend controls into
316
+ * no verdict that says why.
317
+ *
318
+ * The official client pays only its default assets (plus the ones an adapter
319
+ * allows, such as Circle's USDC on Ethereum Sepolia) and at most $1 a
320
+ * payment, so that a paywall cannot charge a payer more than it meant to.
321
+ * Wasit keeps those limits: it pays automatically, and on `stellar:pubnet`
322
+ * with real money. A target above them is not at fault, and nothing was
323
+ * sent, so this is `ERROR (setup)`, not a harness error. Matched on the SDK's
324
+ * message (`@x402/core` 2.28 `client/index.mjs`); a message it does not
325
+ * recognise passes through as before.
326
+ */
327
+ async function withinSpendControls(network, selected, build) {
328
+ try {
329
+ return await build();
330
+ }
331
+ catch (error) {
332
+ const message = error instanceof Error ? error.message : "";
333
+ if (!message.startsWith(SPEND_CONTROLS_REFUSAL))
334
+ throw error;
335
+ if (message.includes("only default assets")) {
336
+ throw new CheckSetupError(`The target asks to be paid in ${selected.asset} on ${network}, which is not ` +
337
+ `an asset the official x402 client pays in by default, nor one Wasit allows, ` +
338
+ `so nothing was sent.`);
339
+ }
340
+ throw new CheckSetupError(`The target asks for ${selected.amount} base units of ${selected.asset}, more ` +
341
+ `than the $1 a payment the official x402 client pays by default, so nothing ` +
342
+ `was sent. The cap keeps a paywall from charging a payer more than it meant ` +
343
+ `to; a target priced at $1 or less is checked as usual.`);
344
+ }
345
+ }
336
346
  /**
337
347
  * Reads the challenge and produces a signed payment payload for it.
338
348
  *
339
- * Shared by both payment checks so each one starts from a challenge the
340
- * target issued just now, rather than reusing a stale one.
349
+ * Shared by every payment check so each one starts from a challenge the
350
+ * target issued just now, rather than reusing a stale one. With `altered`,
351
+ * the payment is signed for those terms instead, and its `accepted` is set
352
+ * back to what the target advertised. `beforeSigning` runs once the option
353
+ * to pay is known and before the client builds anything: the Stellar client
354
+ * simulates the transfer while building, so a check placed later would never
355
+ * see an unfunded payer.
341
356
  */
342
- async function preparePayment(options) {
343
- const { client, httpClient } = buildX402Client(options.network, options.payerSecretKey);
357
+ async function preparePayment(options, alter, beforeSigning) {
358
+ const chain = chainFor(options.network);
359
+ const { client, httpClient } = await buildX402Client(chain, options.network, options.payerSecretKey, chain.resolveRpcUrl(options.network, options.rpcUrl));
344
360
  const challenge = await fetchTarget(options.target, buildInit(options));
345
361
  let paymentRequired;
346
362
  try {
@@ -348,24 +364,50 @@ async function preparePayment(options) {
348
364
  }
349
365
  catch (error) {
350
366
  // The read checks already report what is wrong with the challenge. Failing
351
- // X402-06/07 here too would count one broken challenge three times, and
367
+ // the payment checks here too would count one broken challenge many times, and
352
368
  // would make X402-07 read as a signature that was not rejected when no
353
369
  // payment was ever sent. docs/CHECKS.md: an unreadable challenge produces
354
370
  // no verdict.
355
371
  const v1 = readV1BodyChallenge(await readText(challenge)) !== undefined;
356
372
  throw new PaymentNotAttemptedError(v1
357
- ? `the target issued an x402 v1 challenge, and Wasit pays through the ` +
358
- `v2 \`exact\` scheme on Stellar, the only version the spec defines, ` +
359
- `so no payment was attempted (see X402-02).`
373
+ ? `the target issued an x402 v1 challenge, and Wasit's payment checks ` +
374
+ `pay through x402 v2 only (on Stellar, the only version the \`exact\` ` +
375
+ `scheme defines), so no payment was attempted (see X402-02).`
360
376
  : `the challenge could not be read as x402 payment requirements ` +
361
377
  `(${error.message}), so no payment was attempted ` +
362
378
  `(see X402-02–04).`);
363
379
  }
364
- const paymentPayload = await client.createPaymentPayload(paymentRequired);
365
- return { httpClient, paymentPayload };
380
+ // A target that offers no option Wasit can pay has not refused anything:
381
+ // there is no payment to judge, so neither check gets a verdict. X402-05
382
+ // already reports which networks it advertises.
383
+ const onNetwork = paymentRequired.accepts.filter((requirement) => requirement.network === options.network);
384
+ if (onNetwork.length === 0) {
385
+ throw new PaymentNotAttemptedError(`the target offers no payment option on ${options.network} (it offers ` +
386
+ `${describeOffered(paymentRequired.accepts)}), so no payment was ` +
387
+ `attempted (see X402-05).`);
388
+ }
389
+ if (!onNetwork.some((requirement) => requirement.scheme === "exact")) {
390
+ throw new PaymentNotAttemptedError(`the target's ${options.network} option uses the ` +
391
+ `"${onNetwork[0].scheme}" scheme, and Wasit pays through the \`exact\` ` +
392
+ `scheme only, so no payment was attempted.`);
393
+ }
394
+ const selected = onNetwork.find((requirement) => requirement.scheme === "exact");
395
+ // The payment-identifier extension lets a server answer a repeated payload
396
+ // with its cached response (specs/extensions/payment_identifier.md).
397
+ const idempotent = paymentRequired.extensions?.["payment-identifier"] !== undefined;
398
+ await beforeSigning?.(selected);
399
+ if (alter === undefined) {
400
+ const paymentPayload = await withinSpendControls(options.network, selected, () => client.createPaymentPayload(paymentRequired));
401
+ return { httpClient, paymentPayload, selected, idempotent };
402
+ }
403
+ const altered = await alter(selected);
404
+ const signed = await withinSpendControls(options.network, selected, () => client.createPaymentPayload({
405
+ ...paymentRequired,
406
+ accepts: [{ ...selected, ...altered }],
407
+ }));
408
+ const paymentPayload = { ...signed, accepted: selected };
409
+ return { httpClient, paymentPayload, selected, idempotent };
366
410
  }
367
- /** A Stellar transaction hash: 64 hex characters. */
368
- const TRANSACTION_HASH = /^[0-9a-f]{64}$/i;
369
411
  /**
370
412
  * Reads the settlement a paid response reports, before anything is looked up.
371
413
  *
@@ -373,7 +415,7 @@ const TRANSACTION_HASH = /^[0-9a-f]{64}$/i;
373
415
  * exercised without a network. `readSettlement` throws when the response
374
416
  * carries no `PAYMENT-RESPONSE` header, as `x402HTTPClient` does.
375
417
  */
376
- export function readSettlementReference(status, readSettlement) {
418
+ export function readSettlementReference(status, readSettlement, chain = stellarChain) {
377
419
  let settlement;
378
420
  try {
379
421
  settlement = readSettlement();
@@ -383,44 +425,97 @@ export function readSettlementReference(status, readSettlement) {
383
425
  failure: `Valid payment accepted (HTTP ${status}), but the response carried no ` +
384
426
  `PAYMENT-RESPONSE header, which the x402 v2 HTTP transport uses to ` +
385
427
  `report settlement. Whether the payment settled cannot be verified.`,
428
+ hint: "After settling, return the facilitator's settle result base64-encoded " +
429
+ "in a PAYMENT-RESPONSE header; the official x402 middleware does this.",
386
430
  };
387
431
  }
388
432
  const reference = settlement.transaction ?? "";
389
433
  // `settlement_pending` means broadcast but unconfirmed; the x402 spec has the
390
434
  // caller reconcile on chain, which is exactly what X402-06 goes on to do.
391
435
  const pending = !settlement.success && settlement.errorReason === "settlement_pending";
392
- if ((!settlement.success && !pending) || !TRANSACTION_HASH.test(reference)) {
436
+ if ((!settlement.success && !pending) || !chain.isSettlementReference(reference)) {
393
437
  return {
394
438
  failure: `Valid payment accepted (HTTP ${status}), but its PAYMENT-RESPONSE ` +
395
439
  `reports ${settlement.success ? "success" : "failure"} with transaction ` +
396
- `${JSON.stringify(reference)}, not a settled Stellar transaction hash.`,
440
+ `${JSON.stringify(reference)}, not ${chain.referenceKind}.`,
441
+ hint: "PAYMENT-RESPONSE must report `success: true` and carry the settlement " +
442
+ "transaction's hash in `transaction`.",
397
443
  };
398
444
  }
399
445
  return { reference };
400
446
  }
401
447
  /**
402
- * X402-06: a valid payment must be accepted, and must settle on-chain.
448
+ * Stops X402-06 before it pays when the payer certainly cannot cover the
449
+ * price.
403
450
  *
404
- * A 2xx proves only that the target served the resource. The x402 v2 HTTP
405
- * transport reports settlement in the `PAYMENT-RESPONSE` header, whose
406
- * `transaction` is, for the `exact` scheme on Stellar, the settlement's hash.
407
- * That hash is looked up on RPC and the token contract's own transfer event is
408
- * held to what the target advertised, as MPP-01 does: a target that serves
409
- * the resource without settling, or settles something else, fails here.
451
+ * A payment the payer cannot fund is refused, and the refusal reads as the
452
+ * target's: on Solana devnet the facilitator answers
453
+ * `invalid_exact_svm_transaction_simulation_failed`, the reason a real defect
454
+ * gives too, so it cannot be told apart afterwards; the Stellar client fails
455
+ * earlier, simulating the transfer while it builds, with only the token's
456
+ * error code. Read before signing, so a target that settles and then refuses
457
+ * still shows as one. Only a balance the
458
+ * chain reported counts: when it cannot be read, the run pays as before, and
459
+ * a failed read never becomes a verdict either way.
410
460
  */
461
+ async function assertPayerCanPay(options, selected) {
462
+ let price;
463
+ try {
464
+ price = BigInt(selected.amount);
465
+ }
466
+ catch {
467
+ return;
468
+ }
469
+ const chain = chainFor(options.network);
470
+ let balance;
471
+ try {
472
+ balance = await chain.payerBalance(options.network, chain.resolveRpcUrl(options.network, options.rpcUrl), chain.payerAddress(options.payerSecretKey), selected.asset);
473
+ }
474
+ catch {
475
+ balance = undefined;
476
+ }
477
+ if (balance !== undefined && balance < price) {
478
+ throw new CheckSetupError(`This run's payer holds less of ${selected.asset} than the advertised ${price} ` +
479
+ `base units, so its payment cannot settle, and a refusal would say nothing ` +
480
+ `about the target. Fund the payer (${chain.payerKeyEnv}), then re-run.`);
481
+ }
482
+ }
411
483
  async function checkSignatureAccepted(options) {
412
484
  const id = "X402-06";
413
485
  const name = "Signature Resubmit Accepted";
414
- const fail = (detail) => ({ id, name, pass: false, detail });
415
- const { httpClient, paymentPayload } = await preparePayment(options);
486
+ const fail = (detail, hint) => ({ id, name, pass: false, detail, hint });
487
+ const { httpClient, paymentPayload, idempotent } = await preparePayment(options, undefined, (selected) => assertPayerCanPay(options, selected));
416
488
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
417
489
  const paid = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
490
+ const honest = (result, accepted) => ({
491
+ result,
492
+ accepted,
493
+ headers: paymentHeaders,
494
+ idempotent,
495
+ });
418
496
  if (paid.status < 200 || paid.status >= 300) {
419
- return fail(`Expected 2xx after a valid payment, got ${paid.status}.`);
420
- }
421
- const read = readSettlementReference(paid.status, () => httpClient.getPaymentSettleResponse((header) => paid.headers.get(header)));
497
+ const reason = await refusalReason(paid);
498
+ // Permit2 needs the payer to have approved the Permit2 contract once. A
499
+ // target that offers no gas-sponsored approval leaves that to the payer,
500
+ // so this refusal is about Wasit's payer, not the target: no verdict.
501
+ if (reason === "permit2_allowance_required") {
502
+ throw new CheckSetupError("The target pays through Permit2 without a gas-sponsored approval, and this " +
503
+ "run's payer has not approved the Permit2 contract for the token. Approve it " +
504
+ "once (an on-chain transaction that needs gas), then re-run.");
505
+ }
506
+ return honest(fail(`Expected 2xx after a valid payment, got ${paid.status}` +
507
+ `${reason === undefined ? "" : ` (${reason})`}.`, reason?.startsWith("settlement failed:")
508
+ ? "The payment verified, but the facilitator did not settle it, and said why. " +
509
+ "That is the facilitator's failure, or its RPC's, yet a valid payment was " +
510
+ "refused; check the facilitator's account and endpoint, then re-run."
511
+ : "A valid payment was refused. Your server's log of the facilitator's " +
512
+ "verify or settle response says why; serve the resource with a 2xx once " +
513
+ "the payment settles."), false);
514
+ }
515
+ const chain = chainFor(options.network);
516
+ const read = readSettlementReference(paid.status, () => httpClient.getPaymentSettleResponse((header) => paid.headers.get(header)), chain);
422
517
  if ("failure" in read)
423
- return fail(read.failure);
518
+ return honest(fail(read.failure, read.hint), true);
424
519
  const reference = read.reference;
425
520
  const accepted = paymentPayload.accepted;
426
521
  let amount;
@@ -431,71 +526,23 @@ async function checkSignatureAccepted(options) {
431
526
  throw new MalformedResponseError(`The accepted payment requirements carry a non-numeric amount ` +
432
527
  `(${JSON.stringify(accepted.amount)}).`);
433
528
  }
434
- const rpcUrl = resolveRpcUrl(options.network, options.rpcUrl);
435
- const verdict = await verifySettlement(rpcUrl, reference, {
529
+ const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
530
+ const verdict = await chain.verifySettlement(options.network, rpcUrl, reference, {
436
531
  amount,
437
532
  token: accepted.asset,
438
533
  recipient: accepted.payTo,
439
- payer: Keypair.fromSecret(options.payerSecretKey).publicKey(),
534
+ payer: chain.payerAddress(options.payerSecretKey),
440
535
  });
441
- return verdict.pass
536
+ return honest(verdict.pass
442
537
  ? {
443
538
  id,
444
539
  name,
445
540
  pass: true,
446
541
  detail: `Valid payment accepted (HTTP ${paid.status}) and ${verdict.detail}.`,
447
542
  }
448
- : fail(verdict.detail);
449
- }
450
- /**
451
- * Corrupts the client's authorization signature, and nothing else.
452
- *
453
- * In the `exact` scheme on Stellar the client signs a Soroban authorization
454
- * entry, not the envelope: the facilitator signs the envelope later. So the
455
- * signature that proves the payer consented is the address credential's
456
- * `signature`, a `Vec<{ public_key, signature }>`. Flipping one byte of it
457
- * leaves a transaction that still decodes, carries the same amount, payer and
458
- * recipient, and fails only signature verification. A target can refuse it
459
- * only by verifying the signature.
460
- *
461
- * Throws {@link CheckSetupError} if the payload carries no such signature, so
462
- * the check reports no verdict rather than one it did not establish.
463
- */
464
- export function corruptAuthSignature(transaction) {
465
- const envelope = xdr.TransactionEnvelope.fromXDR(transaction, "base64");
466
- const operations = envelope.switch().name === "envelopeTypeTx" ? envelope.v1().tx().operations() : [];
467
- let corrupted = false;
468
- for (const operation of operations) {
469
- if (operation.body().switch().name !== "invokeHostFunction")
470
- continue;
471
- for (const entry of operation.body().invokeHostFunctionOp().auth()) {
472
- const credentials = entry.credentials();
473
- if (credentials.switch().name !== "sorobanCredentialsAddress")
474
- continue;
475
- const signature = credentials.address().signature();
476
- if (signature.switch().name !== "scvVec")
477
- continue;
478
- for (const item of signature.vec() ?? []) {
479
- if (item.switch().name !== "scvMap")
480
- continue;
481
- for (const field of item.map() ?? []) {
482
- if (field.key().switch().name !== "scvSymbol")
483
- continue;
484
- if (field.key().sym().toString() !== "signature")
485
- continue;
486
- const bytes = Buffer.from(field.val().bytes());
487
- bytes[0] = bytes[0] ^ 0xff;
488
- field.val(xdr.ScVal.scvBytes(bytes));
489
- corrupted = true;
490
- }
491
- }
492
- }
493
- }
494
- if (!corrupted) {
495
- throw new CheckSetupError("The payment payload carries no authorization-entry signature to " +
496
- "corrupt, so a corrupted signature cannot be tested.");
497
- }
498
- return envelope.toXDR("base64");
543
+ : fail(verdict.detail, "PAYMENT-RESPONSE must name the transaction that settled this payment, " +
544
+ "and that transaction must move exactly `amount` of `asset` from the " +
545
+ "payer to `payTo`, in a single transfer."), true);
499
546
  }
500
547
  /**
501
548
  * X402-07 (negative): a corrupted signature must be rejected.
@@ -514,34 +561,273 @@ async function checkInvalidSignatureRejected(options) {
514
561
  const { httpClient, paymentPayload } = await preparePayment(options);
515
562
  const corrupted = {
516
563
  ...paymentPayload,
517
- payload: {
518
- ...paymentPayload.payload,
519
- transaction: corruptAuthSignature(paymentPayload.payload.transaction),
520
- },
564
+ payload: chainFor(options.network).corruptPayload(paymentPayload.payload),
521
565
  };
522
566
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted);
523
567
  const response = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
524
- const accepted = response.status >= 200 && response.status < 300;
568
+ return signatureRejectionVerdict(response.status, await refusalReason(response));
569
+ }
570
+ /**
571
+ * X402-07's verdict from the status a corrupted payment drew. Split out so
572
+ * the verdict can be tested without building a payment.
573
+ */
574
+ export function signatureRejectionVerdict(status, reason) {
575
+ const accepted = status >= 200 && status < 300;
525
576
  return {
526
577
  id: "X402-07",
527
578
  name: "Invalid Signature Rejected",
528
579
  pass: !accepted,
529
580
  detail: accepted
530
581
  ? `A payment with a corrupted authorization signature was accepted with ` +
531
- `HTTP ${response.status} — security-relevant failure.`
582
+ `HTTP ${status} — security-relevant failure.`
532
583
  : `Payment with a corrupted authorization signature correctly rejected ` +
533
- `(HTTP ${response.status}).`,
584
+ `(${statusWithReason(status, reason)}).`,
585
+ ...(accepted
586
+ ? {
587
+ hint: "Verify every payment before serving: pass it to the facilitator's " +
588
+ "verify step and refuse it when verification fails. Never serve on a " +
589
+ "payload that was only decoded.",
590
+ }
591
+ : {}),
592
+ };
593
+ }
594
+ /** Any 2xx is the target serving the resource. */
595
+ function served(status) {
596
+ return status >= 200 && status < 300;
597
+ }
598
+ /**
599
+ * Why the target refused a payment, when it says. A payment refused at
600
+ * verify comes back with a fresh challenge whose `error` names the reason
601
+ * (often the facilitator's, e.g. `invalid_exact_evm_payload_signature`). One
602
+ * that verified but did not settle comes back with a `PAYMENT-RESPONSE` whose
603
+ * `success` is false and whose `errorReason` says why, as the official SDK
604
+ * server sends it; that is read first, and named as a settlement failure, so
605
+ * an operator can tell their facilitator's failure from a refusal. Shown with
606
+ * a PASS so a reader can tell the refusal came from the rule the check is
607
+ * about, not from something else that also answers 402.
608
+ */
609
+ async function refusalReason(response) {
610
+ const decode = (header) => {
611
+ try {
612
+ return asRecord(JSON.parse(Buffer.from(header, "base64").toString("utf-8")));
613
+ }
614
+ catch {
615
+ return undefined;
616
+ }
534
617
  };
618
+ const settlement = response.headers.get("PAYMENT-RESPONSE");
619
+ if (settlement !== null) {
620
+ const parsed = decode(settlement);
621
+ const reason = parsed?.["errorReason"];
622
+ if (parsed?.["success"] === false && typeof reason === "string" && reason.length > 0) {
623
+ // The reason is a code; some facilitators append a long RPC message.
624
+ return `settlement failed: ${/^[\w.-]+/.exec(reason)?.[0] ?? reason}`;
625
+ }
626
+ }
627
+ const errorOf = (record) => {
628
+ const error = record?.["error"];
629
+ return typeof error === "string" && error.length > 0 ? error : undefined;
630
+ };
631
+ const header = response.headers.get("PAYMENT-REQUIRED");
632
+ if (header !== null)
633
+ return errorOf(decode(header));
634
+ try {
635
+ return errorOf(asRecord(JSON.parse(await readText(response))));
636
+ }
637
+ catch {
638
+ return undefined;
639
+ }
640
+ }
641
+ function statusWithReason(status, reason) {
642
+ return reason === undefined ? `HTTP ${status}` : `HTTP ${status}: ${reason}`;
535
643
  }
536
644
  /**
537
- * Runs X402-06 and X402-07 against a target.
645
+ * X402-08 (negative): a payment already accepted must not be accepted again.
538
646
  *
539
- * Both settle real payments when the target accepts them; see docs/CHECKS.md.
647
+ * The headers X402-06's honest payment was sent with are sent once more,
648
+ * byte for byte. Each authorization is single-use: an EIP-3009 nonce, or a
649
+ * Soroban auth entry's nonce, is spent once the payment settles, so the
650
+ * facilitator's verify refuses it (spec §10.1). A target that serves it again
651
+ * has sold the resource twice for one payment. Nothing can settle twice.
652
+ */
653
+ async function checkReplayRejected(options, honest) {
654
+ if (honest.idempotent) {
655
+ return skipped("X402-08", "Payment Replay Rejected", "the challenge advertises the payment-identifier extension, under which a " +
656
+ "server may answer a repeated payment with its cached response.");
657
+ }
658
+ const response = await fetchTarget(options.target, withPaymentHeaders(options, honest.headers));
659
+ return replayVerdict(response.status, await refusalReason(response));
660
+ }
661
+ /** X402-08's verdict from the status the replayed payment drew. */
662
+ export function replayVerdict(status, reason) {
663
+ const accepted = served(status);
664
+ return {
665
+ id: "X402-08",
666
+ name: "Payment Replay Rejected",
667
+ pass: !accepted,
668
+ detail: accepted
669
+ ? `The payment X402-06 had already been accepted for was accepted again ` +
670
+ `(HTTP ${status}): one payment bought the resource twice.`
671
+ : `The same payment, sent again, was refused (${statusWithReason(status, reason)}).`,
672
+ ...(accepted
673
+ ? {
674
+ hint: "Treat every payment as single-use: verify it with the facilitator " +
675
+ "before serving, which refuses an authorization whose nonce is already " +
676
+ "spent, and never serve the same payload twice.",
677
+ }
678
+ : {}),
679
+ };
680
+ }
681
+ /**
682
+ * X402-09 (negative): a validly signed payment for less than the price must
683
+ * be rejected.
684
+ *
685
+ * The payment is signed for half the advertised amount, while its `accepted`
686
+ * still claims the advertised terms, so the signature is good and only the
687
+ * amount is wrong. The facilitator must hold the signed amount to the
688
+ * requirement (Stellar: exactly; EVM: verification step 3). If the target
689
+ * accepts, the lower amount may settle.
690
+ */
691
+ async function checkUnderpaymentRejected(options) {
692
+ let advertised = 0n;
693
+ let offered = 0n;
694
+ let prepared;
695
+ try {
696
+ prepared = await preparePayment(options, (selected) => {
697
+ try {
698
+ advertised = BigInt(selected.amount);
699
+ }
700
+ catch {
701
+ throw new MalformedResponseError(`The payment requirements carry a non-numeric amount (${JSON.stringify(selected.amount)}).`);
702
+ }
703
+ if (advertised < 2n) {
704
+ throw new CheckNotApplicable(`the advertised price is ${advertised} base unit${advertised === 1n ? "" : "s"}, so ` +
705
+ `there is no smaller payment to offer.`);
706
+ }
707
+ offered = advertised / 2n;
708
+ return { amount: offered.toString() };
709
+ });
710
+ }
711
+ catch (error) {
712
+ if (error instanceof CheckNotApplicable) {
713
+ return skipped("X402-09", "Underpayment Rejected", error.message);
714
+ }
715
+ throw error;
716
+ }
717
+ const { httpClient, paymentPayload } = prepared;
718
+ const response = await fetchTarget(options.target, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
719
+ return underpaymentVerdict(response.status, offered, advertised, await refusalReason(response));
720
+ }
721
+ /** X402-09's verdict from the status the underpaid payment drew. */
722
+ export function underpaymentVerdict(status, offered, advertised, reason) {
723
+ const accepted = served(status);
724
+ return {
725
+ id: "X402-09",
726
+ name: "Underpayment Rejected",
727
+ pass: !accepted,
728
+ detail: accepted
729
+ ? `A validly signed payment for ${offered} of the advertised ${advertised} base ` +
730
+ `units was accepted (HTTP ${status}) — security-relevant failure: the target ` +
731
+ `served for less than its price.`
732
+ : `A validly signed payment for ${offered} of the advertised ${advertised} base ` +
733
+ `units was refused (${statusWithReason(status, reason)}).`,
734
+ ...(accepted
735
+ ? {
736
+ hint: "Hold the signed payment to the advertised amount before serving. The " +
737
+ "facilitator's verify does; a server that skips it, or checks only the " +
738
+ "signature, sells for less than its price.",
739
+ }
740
+ : {}),
741
+ };
742
+ }
743
+ /**
744
+ * X402-10 (negative): a payment whose authorization has expired must be
745
+ * rejected.
746
+ *
747
+ * Each chain says how the payment is made to expire (`expiredSigning`): on
748
+ * Stellar and EVM it is signed with a one-second lifetime (the auth entry's
749
+ * expiration ledger, or `validBefore`, both derived from `maxTimeoutSeconds`)
750
+ * and held until that has passed; on Solana it is built on a blockhash already
751
+ * past its lifetime. It is sent claiming the advertised terms. An expired
752
+ * authorization cannot settle, so a target that serves it serves for nothing.
753
+ */
754
+ async function checkExpiredRejected(options) {
755
+ const chain = chainFor(options.network);
756
+ const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
757
+ let holdMs = 0;
758
+ const { httpClient, paymentPayload } = await preparePayment(options, async (selected) => {
759
+ const expired = await chain.expiredSigning(selected, rpcUrl);
760
+ holdMs = expired.holdMs;
761
+ return expired.terms;
762
+ });
763
+ await new Promise((done) => setTimeout(done, holdMs));
764
+ const response = await fetchTarget(options.target, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
765
+ return expiredVerdict(response.status, await refusalReason(response));
766
+ }
767
+ /** X402-10's verdict from the status the expired payment drew. */
768
+ export function expiredVerdict(status, reason) {
769
+ const accepted = served(status);
770
+ return {
771
+ id: "X402-10",
772
+ name: "Expired Authorization Rejected",
773
+ pass: !accepted,
774
+ detail: accepted
775
+ ? `A payment whose authorization had already expired was accepted (HTTP ` +
776
+ `${status}). It cannot settle, so the target served for nothing.`
777
+ : `A payment whose authorization had expired was refused (${statusWithReason(status, reason)}).`,
778
+ ...(accepted
779
+ ? {
780
+ hint: "Verify each payment with the facilitator before serving: it refuses an " +
781
+ "authorization past its window (validBefore on EVM, the auth entry's " +
782
+ "expiration ledger on Stellar, the recent blockhash on Solana).",
783
+ }
784
+ : {}),
785
+ };
786
+ }
787
+ /** The negative checks, in catalogue order, each with how it runs. */
788
+ const NEGATIVE_CHECKS = [
789
+ ["X402-07", "Invalid Signature Rejected", (options) => checkInvalidSignatureRejected(options)],
790
+ ["X402-08", "Payment Replay Rejected", checkReplayRejected],
791
+ ["X402-09", "Underpayment Rejected", (options) => checkUnderpaymentRejected(options)],
792
+ ["X402-10", "Expired Authorization Rejected", (options) => checkExpiredRejected(options)],
793
+ ];
794
+ /**
795
+ * Every check `runX402PaymentChecks` reports, in order. Front ends that list
796
+ * checks before a run use it, so a read-only run never shows these as pending.
797
+ */
798
+ export const X402_PAYMENT_CHECK_IDS = [
799
+ "X402-06",
800
+ ...NEGATIVE_CHECKS.map(([id]) => id),
801
+ ];
802
+ /**
803
+ * Runs X402-06 through X402-10 against a target.
804
+ *
805
+ * X402-06 settles a real payment. The negative checks send payments the
806
+ * target must refuse; a target that accepts the underpaid one may settle it.
807
+ * See docs/CHECKS.md.
540
808
  */
541
809
  export async function runX402PaymentChecks(options) {
542
810
  try {
543
811
  assertHttpUrl(options.target);
544
812
  buildInit(options);
813
+ // The payment checks pay only where Wasit has an adapter, and X402-06 can
814
+ // only verify a settlement it can look up. Both are known before any
815
+ // money moves, so a run that could not finish is stopped here rather than
816
+ // after paying.
817
+ const chain = chainFor(options.network);
818
+ chain.resolveRpcUrl(options.network, options.rpcUrl);
819
+ // A key for another chain, or a malformed one, would otherwise surface
820
+ // mid-payment as a harness error. Checked here, it is what it is: the
821
+ // run's configuration. The message never echoes the key.
822
+ try {
823
+ chain.payerAddress(options.payerSecretKey);
824
+ }
825
+ catch (error) {
826
+ if (error instanceof ConfigurationError)
827
+ throw error;
828
+ throw new ConfigurationError(`The payer key is not a valid ${chain.name} key (read from ${chain.payerKeyEnv} ` +
829
+ `or --payer-key).`);
830
+ }
545
831
  }
546
832
  catch (error) {
547
833
  const preflight = errored("PREFLIGHT", "Run Preflight", error);
@@ -549,41 +835,46 @@ export async function runX402PaymentChecks(options) {
549
835
  return [preflight];
550
836
  }
551
837
  const results = [];
552
- let accepted;
838
+ const emit = (result) => {
839
+ results.push(result);
840
+ options.onResult?.(result);
841
+ };
842
+ const skipNegatives = (reason) => {
843
+ for (const [id, name] of NEGATIVE_CHECKS)
844
+ emit(skipped(id, name, reason));
845
+ return results;
846
+ };
847
+ let honest;
553
848
  try {
554
- accepted = await checkSignatureAccepted(options);
849
+ honest = await checkSignatureAccepted(options);
555
850
  }
556
851
  catch (error) {
557
852
  if (error instanceof PaymentNotAttemptedError) {
558
- const notAttempted = [
559
- skipped("X402-06", "Signature Resubmit Accepted", error.message),
560
- skipped("X402-07", "Invalid Signature Rejected", error.message),
561
- ];
562
- for (const result of notAttempted)
563
- options.onResult?.(result);
564
- return notAttempted;
853
+ emit(skipped("X402-06", "Signature Resubmit Accepted", error.message));
854
+ return skipNegatives(error.message);
855
+ }
856
+ const failed = errored("X402-06", "Signature Resubmit Accepted", error);
857
+ emit(failed);
858
+ // If the payment flow could not be exercised at all, no altered variant of
859
+ // it can be either, and none may be reported as a passing rejection.
860
+ return skipNegatives(`the payment flow could not be exercised (${failed.error?.kind ?? "harness"}), ` +
861
+ `so no altered payment can be tested against it.`);
862
+ }
863
+ emit(honest.result);
864
+ // A negative check passes when the target refuses. A target that refused
865
+ // the honest payment too proves nothing by refusing a bad one, so without an
866
+ // accepted baseline none of them has a verdict.
867
+ if (!honest.accepted) {
868
+ return skipNegatives("the target refused X402-06's valid payment, so refusing an altered one " +
869
+ "says nothing about what it checks.");
870
+ }
871
+ for (const [id, name, run] of NEGATIVE_CHECKS) {
872
+ try {
873
+ emit(await run(options, honest));
874
+ }
875
+ catch (error) {
876
+ emit(errored(id, name, error));
565
877
  }
566
- accepted = errored("X402-06", "Signature Resubmit Accepted", error);
567
- }
568
- results.push(accepted);
569
- options.onResult?.(accepted);
570
- // If the payment flow could not be exercised at all, a corrupted variant of
571
- // it cannot be either — and must not be reported as a passing rejection.
572
- if (accepted.error !== undefined) {
573
- const notExercised = skipped("X402-07", "Invalid Signature Rejected", `the payment flow could not be exercised (${accepted.error.kind}), so ` +
574
- `a corrupted signature cannot be tested against it.`);
575
- results.push(notExercised);
576
- options.onResult?.(notExercised);
577
- return results;
578
- }
579
- let rejected;
580
- try {
581
- rejected = await checkInvalidSignatureRejected(options);
582
- }
583
- catch (error) {
584
- rejected = errored("X402-07", "Invalid Signature Rejected", error);
585
878
  }
586
- results.push(rejected);
587
- options.onResult?.(rejected);
588
879
  return results;
589
880
  }