@wasit-dev/core 0.5.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
- import { ConfigurationError, assertHttpUrl, fetchTarget, } from "../errors.js";
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,8 +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";
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
+ }
321
275
  /** The payment flow was never started, so neither payment check has a verdict. */
322
276
  class PaymentNotAttemptedError extends Error {
323
277
  constructor(reason) {
@@ -325,19 +279,84 @@ class PaymentNotAttemptedError extends Error {
325
279
  this.name = "PaymentNotAttemptedError";
326
280
  }
327
281
  }
328
- function buildX402Client(network, payerSecretKey) {
329
- const signer = createEd25519Signer(payerSecretKey, network);
330
- 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));
331
305
  return { client, httpClient: new x402HTTPClient(client) };
332
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
+ }
333
346
  /**
334
347
  * Reads the challenge and produces a signed payment payload for it.
335
348
  *
336
- * Shared by both payment checks so each one starts from a challenge the
337
- * 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.
338
356
  */
339
- async function preparePayment(options) {
340
- 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));
341
360
  const challenge = await fetchTarget(options.target, buildInit(options));
342
361
  let paymentRequired;
343
362
  try {
@@ -345,83 +364,470 @@ async function preparePayment(options) {
345
364
  }
346
365
  catch (error) {
347
366
  // The read checks already report what is wrong with the challenge. Failing
348
- // 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
349
368
  // would make X402-07 read as a signature that was not rejected when no
350
369
  // payment was ever sent. docs/CHECKS.md: an unreadable challenge produces
351
370
  // no verdict.
352
371
  const v1 = readV1BodyChallenge(await readText(challenge)) !== undefined;
353
372
  throw new PaymentNotAttemptedError(v1
354
- ? `the target issued an x402 v1 challenge, and Wasit pays through the ` +
355
- `v2 \`exact\` scheme on Stellar, the only version the spec defines, ` +
356
- `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).`
357
376
  : `the challenge could not be read as x402 payment requirements ` +
358
377
  `(${error.message}), so no payment was attempted ` +
359
378
  `(see X402-02–04).`);
360
379
  }
361
- const paymentPayload = await client.createPaymentPayload(paymentRequired);
362
- 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 };
410
+ }
411
+ /**
412
+ * Reads the settlement a paid response reports, before anything is looked up.
413
+ *
414
+ * Takes the header decoder rather than the response so the rules can be
415
+ * exercised without a network. `readSettlement` throws when the response
416
+ * carries no `PAYMENT-RESPONSE` header, as `x402HTTPClient` does.
417
+ */
418
+ export function readSettlementReference(status, readSettlement, chain = stellarChain) {
419
+ let settlement;
420
+ try {
421
+ settlement = readSettlement();
422
+ }
423
+ catch {
424
+ return {
425
+ failure: `Valid payment accepted (HTTP ${status}), but the response carried no ` +
426
+ `PAYMENT-RESPONSE header, which the x402 v2 HTTP transport uses to ` +
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.",
430
+ };
431
+ }
432
+ const reference = settlement.transaction ?? "";
433
+ // `settlement_pending` means broadcast but unconfirmed; the x402 spec has the
434
+ // caller reconcile on chain, which is exactly what X402-06 goes on to do.
435
+ const pending = !settlement.success && settlement.errorReason === "settlement_pending";
436
+ if ((!settlement.success && !pending) || !chain.isSettlementReference(reference)) {
437
+ return {
438
+ failure: `Valid payment accepted (HTTP ${status}), but its PAYMENT-RESPONSE ` +
439
+ `reports ${settlement.success ? "success" : "failure"} with transaction ` +
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`.",
443
+ };
444
+ }
445
+ return { reference };
446
+ }
447
+ /**
448
+ * Stops X402-06 before it pays when the payer certainly cannot cover the
449
+ * price.
450
+ *
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.
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
+ }
363
482
  }
364
- /** X402-06: a valid payment must be accepted. Settles on-chain. */
365
483
  async function checkSignatureAccepted(options) {
366
- const { httpClient, paymentPayload } = await preparePayment(options);
484
+ const id = "X402-06";
485
+ const name = "Signature Resubmit Accepted";
486
+ const fail = (detail, hint) => ({ id, name, pass: false, detail, hint });
487
+ const { httpClient, paymentPayload, idempotent } = await preparePayment(options, undefined, (selected) => assertPayerCanPay(options, selected));
367
488
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
368
489
  const paid = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
369
- const pass = paid.status >= 200 && paid.status < 300;
370
- return {
371
- id: "X402-06",
372
- name: "Signature Resubmit Accepted",
373
- pass,
374
- detail: pass
375
- ? `Valid payment accepted (HTTP ${paid.status}).`
376
- : `Expected 2xx after a valid payment, got ${paid.status}.`,
377
- };
490
+ const honest = (result, accepted) => ({
491
+ result,
492
+ accepted,
493
+ headers: paymentHeaders,
494
+ idempotent,
495
+ });
496
+ if (paid.status < 200 || paid.status >= 300) {
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);
517
+ if ("failure" in read)
518
+ return honest(fail(read.failure, read.hint), true);
519
+ const reference = read.reference;
520
+ const accepted = paymentPayload.accepted;
521
+ let amount;
522
+ try {
523
+ amount = BigInt(accepted.amount);
524
+ }
525
+ catch {
526
+ throw new MalformedResponseError(`The accepted payment requirements carry a non-numeric amount ` +
527
+ `(${JSON.stringify(accepted.amount)}).`);
528
+ }
529
+ const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
530
+ const verdict = await chain.verifySettlement(options.network, rpcUrl, reference, {
531
+ amount,
532
+ token: accepted.asset,
533
+ recipient: accepted.payTo,
534
+ payer: chain.payerAddress(options.payerSecretKey),
535
+ });
536
+ return honest(verdict.pass
537
+ ? {
538
+ id,
539
+ name,
540
+ pass: true,
541
+ detail: `Valid payment accepted (HTTP ${paid.status}) and ${verdict.detail}.`,
542
+ }
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);
378
546
  }
379
547
  /**
380
548
  * X402-07 (negative): a corrupted signature must be rejected.
381
549
  *
382
- * This check previously treated *any* thrown error as proof of rejection,
383
- * which meant an unreachable target made a security check pass. A rejection
384
- * is only established by the target answering non-200; anything that prevents
385
- * an answer produces no verdict and is reported as such.
550
+ * The payment is built exactly as for X402-06, then only the client's
551
+ * authorization signature is corrupted (see {@link corruptAuthSignature}), so
552
+ * the envelope still decodes and a target can refuse it only by verifying the
553
+ * signature. Before 0.6.0 the base64 envelope's tail was overwritten instead,
554
+ * which broke XDR decoding: a target that parsed the envelope and skipped
555
+ * signature verification entirely still passed.
556
+ *
557
+ * A rejection is any non-2xx answer. A rejection is only established by an
558
+ * answer: anything that prevents one produces no verdict.
386
559
  */
387
560
  async function checkInvalidSignatureRejected(options) {
388
561
  const { httpClient, paymentPayload } = await preparePayment(options);
389
- // Corrupt the signed transaction after signing. This overwrites the tail of
390
- // the base64 envelope, which also drops its padding — so the decoded envelope
391
- // gains two bytes and stops parsing as XDR. Against the reference facilitator
392
- // in stellar/x402-stellar the rejection therefore happens at decoding, not at
393
- // signature verification, which is weaker than this check should be: a target
394
- // that parsed the envelope and skipped verification entirely would still pass.
395
- // Corrupting only the signature bytes, preserving a decodable envelope, is a
396
- // tracked for 0.6.0. See docs/CHECKS.md's X402-07 row.
397
562
  const corrupted = {
398
563
  ...paymentPayload,
399
- payload: {
400
- ...paymentPayload.payload,
401
- transaction: paymentPayload.payload.transaction.slice(0, -8) + "AAAAAAAA",
402
- },
564
+ payload: chainFor(options.network).corruptPayload(paymentPayload.payload),
403
565
  };
404
566
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted);
405
567
  const response = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
406
- const pass = response.status !== 200;
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;
407
576
  return {
408
577
  id: "X402-07",
409
578
  name: "Invalid Signature Rejected",
410
- pass,
411
- detail: pass
412
- ? `Corrupted payment correctly rejected (HTTP ${response.status}).`
413
- : `Corrupted payment was accepted with HTTP 200 — security-relevant failure.`,
579
+ pass: !accepted,
580
+ detail: accepted
581
+ ? `A payment with a corrupted authorization signature was accepted with ` +
582
+ `HTTP ${status} — security-relevant failure.`
583
+ : `Payment with a corrupted authorization signature correctly rejected ` +
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
+ }
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}`;
643
+ }
644
+ /**
645
+ * X402-08 (negative): a payment already accepted must not be accepted again.
646
+ *
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
+ : {}),
414
741
  };
415
742
  }
416
743
  /**
417
- * Runs X402-06 and X402-07 against a target.
744
+ * X402-10 (negative): a payment whose authorization has expired must be
745
+ * rejected.
418
746
  *
419
- * Both settle real payments when the target accepts them; see docs/CHECKS.md.
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.
420
808
  */
421
809
  export async function runX402PaymentChecks(options) {
422
810
  try {
423
811
  assertHttpUrl(options.target);
424
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
+ }
425
831
  }
426
832
  catch (error) {
427
833
  const preflight = errored("PREFLIGHT", "Run Preflight", error);
@@ -429,41 +835,46 @@ export async function runX402PaymentChecks(options) {
429
835
  return [preflight];
430
836
  }
431
837
  const results = [];
432
- 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;
433
848
  try {
434
- accepted = await checkSignatureAccepted(options);
849
+ honest = await checkSignatureAccepted(options);
435
850
  }
436
851
  catch (error) {
437
852
  if (error instanceof PaymentNotAttemptedError) {
438
- const notAttempted = [
439
- skipped("X402-06", "Signature Resubmit Accepted", error.message),
440
- skipped("X402-07", "Invalid Signature Rejected", error.message),
441
- ];
442
- for (const result of notAttempted)
443
- options.onResult?.(result);
444
- return notAttempted;
853
+ emit(skipped("X402-06", "Signature Resubmit Accepted", error.message));
854
+ return skipNegatives(error.message);
445
855
  }
446
- accepted = errored("X402-06", "Signature Resubmit Accepted", error);
447
- }
448
- results.push(accepted);
449
- options.onResult?.(accepted);
450
- // If the payment flow could not be exercised at all, a corrupted variant of
451
- // it cannot be either — and must not be reported as a passing rejection.
452
- if (accepted.error !== undefined) {
453
- const notExercised = skipped("X402-07", "Invalid Signature Rejected", `the payment flow could not be exercised (${accepted.error.kind}), so ` +
454
- `a corrupted signature cannot be tested against it.`);
455
- results.push(notExercised);
456
- options.onResult?.(notExercised);
457
- return results;
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.`);
458
862
  }
459
- let rejected;
460
- try {
461
- rejected = await checkInvalidSignatureRejected(options);
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.");
462
870
  }
463
- catch (error) {
464
- rejected = errored("X402-07", "Invalid Signature Rejected", error);
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));
877
+ }
465
878
  }
466
- results.push(rejected);
467
- options.onResult?.(rejected);
468
879
  return results;
469
880
  }