@wasit-dev/core 0.7.0 → 0.8.0-beta.1

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.
Files changed (61) hide show
  1. package/README.md +1 -1
  2. package/dist/baseline.d.ts +109 -0
  3. package/dist/baseline.js +351 -0
  4. package/dist/catalogue.js +10 -0
  5. package/dist/check.d.ts +57 -2
  6. package/dist/check.js +46 -6
  7. package/dist/ci-report.d.ts +74 -0
  8. package/dist/ci-report.js +391 -0
  9. package/dist/config.d.ts +205 -0
  10. package/dist/config.js +1011 -0
  11. package/dist/denied-env.d.ts +33 -0
  12. package/dist/denied-env.js +86 -0
  13. package/dist/errors.d.ts +44 -1
  14. package/dist/errors.js +151 -2
  15. package/dist/guard/budget.d.ts +135 -0
  16. package/dist/guard/budget.js +199 -0
  17. package/dist/guard/ci-event.d.ts +50 -0
  18. package/dist/guard/ci-event.js +125 -0
  19. package/dist/guard/mainnet-optin.d.ts +58 -0
  20. package/dist/guard/mainnet-optin.js +95 -0
  21. package/dist/guard/networks.d.ts +50 -0
  22. package/dist/guard/networks.js +80 -0
  23. package/dist/guard/rpc-identity.d.ts +45 -0
  24. package/dist/guard/rpc-identity.js +156 -0
  25. package/dist/guard/rpc-in-use.d.ts +48 -0
  26. package/dist/guard/rpc-in-use.js +84 -0
  27. package/dist/index.d.ts +31 -2
  28. package/dist/index.js +27 -1
  29. package/dist/mpp/channel-commitment.d.ts +48 -2
  30. package/dist/mpp/channel-commitment.js +80 -4
  31. package/dist/mpp/channel-credential.js +3 -0
  32. package/dist/mpp/channel.js +29 -0
  33. package/dist/mpp/charge.d.ts +2 -0
  34. package/dist/mpp/charge.js +17 -1
  35. package/dist/mpp/network.js +4 -1
  36. package/dist/mpp/suite.js +10 -2
  37. package/dist/report.d.ts +163 -0
  38. package/dist/report.js +282 -0
  39. package/dist/sanitize.d.ts +52 -0
  40. package/dist/sanitize.js +106 -0
  41. package/dist/settlement.d.ts +14 -0
  42. package/dist/settlement.js +1 -1
  43. package/dist/verdict.d.ts +24 -0
  44. package/dist/verdict.js +46 -0
  45. package/dist/versions.d.ts +50 -0
  46. package/dist/versions.js +123 -0
  47. package/dist/x402/chains/evm.js +3 -0
  48. package/dist/x402/chains/index.d.ts +8 -0
  49. package/dist/x402/chains/index.js +13 -2
  50. package/dist/x402/chains/stellar.d.ts +8 -1
  51. package/dist/x402/chains/stellar.js +125 -1
  52. package/dist/x402/chains/types.d.ts +68 -0
  53. package/dist/x402/plan.d.ts +82 -0
  54. package/dist/x402/plan.js +146 -0
  55. package/dist/x402/rejected-request.d.ts +146 -0
  56. package/dist/x402/rejected-request.js +269 -0
  57. package/dist/x402/requirements.d.ts +1 -0
  58. package/dist/x402/requirements.js +37 -4
  59. package/dist/x402/simulator.d.ts +52 -1
  60. package/dist/x402/simulator.js +452 -82
  61. package/package.json +1 -1
@@ -1,5 +1,10 @@
1
- import { errored, skipped } from "../check.js";
2
- import { CheckSetupError, ConfigurationError, MalformedResponseError, assertHttpUrl, fetchTarget, } from "../errors.js";
1
+ import { errored, quoteValue, skipped } from "../check.js";
2
+ import { CheckSetupError, ConfigurationError, MalformedResponseError, assertHttpUrl, fetchPaymentChallenge, fetchTarget, } from "../errors.js";
3
+ import { PER_PAYMENT_CAP_USD, PaymentGuardRefusedError, RunBudget, assertPinned, sameAddress, } from "../guard/budget.js";
4
+ import { assertPaymentNetworkAllowed } from "../guard/networks.js";
5
+ import { assertRpcServesNetwork } from "../guard/rpc-identity.js";
6
+ import { REJECTED_REQUEST_ID, REJECTED_REQUEST_MAX_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_UNITS_LEFT, REJECTED_REQUEST_NAME, rejectRequestShape, rejectedRequestHardStopMs, rejectedRequestVerdict, watchAuthorization, } from "./rejected-request.js";
7
+ import { sanitizeText } from "../sanitize.js";
3
8
  import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js";
4
9
  const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
5
10
  const KNOWN_METHODS = new Set([
@@ -89,7 +94,7 @@ function statusHint(status) {
89
94
  /** Skips every check after `id`, naming the one cause they all depend on. */
90
95
  function skipAfter(id, reason) {
91
96
  const index = READ_CHECKS.findIndex(([candidate]) => candidate === id);
92
- return READ_CHECKS.slice(index + 1).map(([checkId, name]) => skipped(checkId, name, reason));
97
+ return READ_CHECKS.slice(index + 1).map(([checkId, name]) => skipped(checkId, name, reason, "dependency"));
93
98
  }
94
99
  function asRecord(value) {
95
100
  return typeof value === "object" && value !== null
@@ -115,6 +120,11 @@ export function readV1BodyChallenge(body) {
115
120
  const record = asRecord(parsed);
116
121
  return record?.["x402Version"] === 1 && Array.isArray(record["accepts"]) ? record : undefined;
117
122
  }
123
+ /** What a header that did not decode to JSON held, quoted. The service chose it; the sinks cut it. */
124
+ function decodedStart(headerValue) {
125
+ const decoded = Buffer.from(headerValue, "base64").toString("utf-8");
126
+ return decoded === "" ? "an empty value" : `a value that starts with ${quoteValue(decoded)}`;
127
+ }
118
128
  /** A body that cannot be read is simply not a v1 challenge. */
119
129
  async function readText(response) {
120
130
  try {
@@ -124,6 +134,21 @@ async function readText(response) {
124
134
  return "";
125
135
  }
126
136
  }
137
+ /**
138
+ * Why an x402 v1 challenge is not graded: the reason on X402-02..05 and on the
139
+ * endpoint, on every chain (a v1 service on an EVM chain gets it too). Kept
140
+ * under 300 characters, the longest a value goes into a pull request comment,
141
+ * so the way to get graded is not cut off. It names no URL: the comment's
142
+ * sanitiser removes links from check text, so it points at docs/CHECKS.md,
143
+ * whose note on x402 v1 links the x402 specification.
144
+ */
145
+ const V1_UNSUPPORTED_REASON = "the service sent an x402 v1 challenge (x402Version 1, in the body). Wasit grades only x402 v2, on " +
146
+ "every chain: challenge in a PAYMENT-REQUIRED header, CAIP-2 networks, v2 `exact` scheme (Stellar is " +
147
+ "v2 only). Unsupported, not failed. Fix: move it to that header. Why: docs/CHECKS.md.";
148
+ /** What a check found on a challenge Wasit does not grade, to be shown as a note. */
149
+ function noteOf(result) {
150
+ return result.skipped === true ? (result.skipReason ?? result.detail) : result.detail;
151
+ }
127
152
  /**
128
153
  * Runs X402-01 through X402-05 against a target.
129
154
  *
@@ -151,7 +176,9 @@ export async function runX402ReadChecks(options) {
151
176
  }
152
177
  let response;
153
178
  try {
154
- response = await fetchTarget(target, init);
179
+ // The unpaid request of the read-only tier: a redirect to another origin
180
+ // is reported and gives no verdict, never followed (spec A8 #5).
181
+ response = await fetchTarget(target, init, { redirects: "same-origin" });
155
182
  }
156
183
  catch (error) {
157
184
  return emit([
@@ -167,7 +194,9 @@ export async function runX402ReadChecks(options) {
167
194
  detail: statusPass
168
195
  ? "Server responded with 402 as required."
169
196
  : `Expected status 402, got ${response.status}.`,
170
- ...(statusPass ? {} : { hint: statusHint(response.status) }),
197
+ ...(statusPass
198
+ ? {}
199
+ : { hint: statusHint(response.status), expected: "status 402", actual: `status ${response.status}` }),
171
200
  };
172
201
  if (!statusPass) {
173
202
  return emit([
@@ -179,49 +208,42 @@ export async function runX402ReadChecks(options) {
179
208
  // Both names are checked because Stellar's own documentation is not yet
180
209
  // internally consistent — see docs/CHECKS.md.
181
210
  const headerValue = response.headers.get("PAYMENT-REQUIRED") ?? response.headers.get("X-Payment");
182
- // x402 v1 signals payment in the response body rather than a header. The
183
- // `exact` scheme on Stellar is defined for v2 only, so a missing header is
184
- // still X402-02's failure — but a v1 challenge in the body still has terms
185
- // worth checking, and skipping them would hide which ones diverge.
211
+ // x402 v1 signals payment in the response body rather than a header, and the
212
+ // `exact` scheme on Stellar is defined for v2 only. Wasit grades v2, so a v1
213
+ // service is unsupported, not failed (spec A3): X402-02..05 are skipped with
214
+ // that reason. The v1 terms are still read and reported as notes, so an
215
+ // operator sees which of them diverge without being handed a verdict.
186
216
  const v1Payload = headerValue === null ? readV1BodyChallenge(await readText(response)) : undefined;
217
+ if (headerValue === null && v1Payload !== undefined) {
218
+ const notes = new Map([
219
+ ["X402-04", noteOf(checkRequiredFields(v1Payload))],
220
+ ["X402-05", noteOf(checkNetworkIdentifier(v1Payload))],
221
+ ]);
222
+ return emit([
223
+ r1,
224
+ ...READ_CHECKS.slice(1).map(([id, name]) => {
225
+ const skip = skipped(id, name, V1_UNSUPPORTED_REASON, "unsupported");
226
+ const note = notes.get(id);
227
+ return note === undefined ? skip : { ...skip, detail: `${skip.detail} Note, not a verdict: ${note}` };
228
+ }),
229
+ ]);
230
+ }
187
231
  const r2 = {
188
232
  id: "X402-02",
189
233
  name: "Payment Header Present",
190
234
  pass: headerValue !== null,
191
235
  detail: headerValue !== null
192
236
  ? "Payment header found."
193
- : v1Payload !== undefined
194
- ? `Neither PAYMENT-REQUIRED nor X-Payment header was present. The ` +
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.`
198
- : "Neither PAYMENT-REQUIRED nor X-Payment header was present.",
237
+ : "Neither PAYMENT-REQUIRED nor X-Payment header was present.",
199
238
  ...(headerValue !== null
200
239
  ? {}
201
240
  : {
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.",
241
+ hint: "Send the challenge as base64-encoded JSON in a PAYMENT-REQUIRED " +
242
+ "response header, as the x402 v2 HTTP transport defines.",
243
+ expected: "a PAYMENT-REQUIRED header",
244
+ actual: "no PAYMENT-REQUIRED or X-Payment header",
208
245
  }),
209
246
  };
210
- if (headerValue === null && v1Payload !== undefined) {
211
- return emit([
212
- r1,
213
- r2,
214
- {
215
- id: "X402-03",
216
- name: "Header Payload Decodable",
217
- pass: true,
218
- detail: "No header to decode; the x402 v1 challenge in the response body " +
219
- "decoded to valid JSON.",
220
- },
221
- checkRequiredFields(v1Payload),
222
- checkNetworkIdentifier(v1Payload),
223
- ]);
224
- }
225
247
  if (headerValue === null) {
226
248
  return emit([
227
249
  r1,
@@ -245,6 +267,8 @@ export async function runX402ReadChecks(options) {
245
267
  detail: `Failed to decode/parse: ${error.message}`,
246
268
  hint: "Base64-encode the JSON PaymentRequired object for the header; raw " +
247
269
  "JSON or a truncated value does not decode.",
270
+ expected: "a base64 value that decodes to JSON",
271
+ actual: decodedStart(headerValue),
248
272
  },
249
273
  ...skipAfter("X402-03", "the payment header did not decode to JSON, so no payload was " +
250
274
  "available to inspect."),
@@ -280,28 +304,49 @@ class PaymentNotAttemptedError extends Error {
280
304
  }
281
305
  }
282
306
  /**
283
- * The adapter for the run's network. Throws `ConfigurationError` for a
284
- * network the payment checks cannot pay on; preflight calls this before
307
+ * No payment adapter pays on this network, so the payment checks cannot be
308
+ * graded here. A `ConfigurationError`, so a caller that does not know the class
309
+ * still reads it as no verdict; preflight turns it into a skip of kind
310
+ * `unsupported` (spec A3). It is not the guard's refusal: `stellar:pubnet` has
311
+ * an adapter and is refused by `assertPaymentNetworkAllowed`, as an error.
312
+ */
313
+ export class UnsupportedPaymentNetworkError extends ConfigurationError {
314
+ network;
315
+ constructor(network) {
316
+ super(`Wasit's payment checks pay on ${paymentNetworks().join(", ")}; ` +
317
+ `${sanitizeText(JSON.stringify(String(network)))} is not one of them, so no payment ` +
318
+ `was attempted. X402-01..05 still apply to a challenge on any chain.`);
319
+ this.name = "UnsupportedPaymentNetworkError";
320
+ this.network = String(network);
321
+ }
322
+ }
323
+ /**
324
+ * The adapter for the run's network. Throws `UnsupportedPaymentNetworkError`
325
+ * for a network the payment checks cannot pay on; preflight calls this before
285
326
  * anything is sent.
286
327
  */
287
328
  function chainFor(network) {
288
329
  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
- }
330
+ if (chain === undefined)
331
+ throw new UnsupportedPaymentNetworkError(network);
294
332
  return chain;
295
333
  }
296
- async function buildX402Client(chain, network, payerSecretKey, rpcUrl) {
334
+ async function buildX402Client(chain, network, payerSecretKey, rpcUrl, pin) {
297
335
  const client = new x402Client();
336
+ // L3 (spec B3): the SDK's own spend controls, set here rather than left to
337
+ // its default, as a second implementation of the $1 cap. An adapter that
338
+ // allows more assets replaces them and states the cap again (`evm.ts`).
339
+ client.setSpendControls({ maxAmountPerPayment: `$${PER_PAYMENT_CAP_USD}` });
298
340
  await chain.registerPayer(client, network, payerSecretKey, rpcUrl);
299
341
  client
300
342
  // A challenge may offer several networks, including both Stellar ones.
301
343
  // The client's default pick is the first it supports, which would sign
302
344
  // 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));
345
+ // network this run was asked to use. With a pin, L3 also keeps only the
346
+ // pinned payee and asset, whatever else picked the option.
347
+ .registerPolicy((_version, requirements) => requirements.filter((requirement) => requirement.network === network &&
348
+ (pin === undefined ||
349
+ (sameAddress(network, requirement.payTo, pin.payTo) && sameAddress(network, requirement.asset, pin.asset)))));
305
350
  return { client, httpClient: new x402HTTPClient(client) };
306
351
  }
307
352
  /** The networks a challenge offers, for a report. */
@@ -344,23 +389,26 @@ async function withinSpendControls(network, selected, build) {
344
389
  }
345
390
  }
346
391
  /**
347
- * Reads the challenge and produces a signed payment payload for it.
392
+ * What a payment check reads before it can pay: the challenge, the URL to pay
393
+ * at, and the one option it would pay. Shared by `preparePayment` and the plan
394
+ * (L1), so both judge the same option by the same rules.
348
395
  *
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.
396
+ * Throws `PaymentNotAttemptedError` when there is nothing to pay: an
397
+ * unreadable or v1 challenge, no option on the run's network, or none in the
398
+ * `exact` scheme.
356
399
  */
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));
360
- const challenge = await fetchTarget(options.target, buildInit(options));
400
+ export async function readPaymentChallenge(options) {
401
+ // The payment goes where this challenge came from, never through a redirect
402
+ // (D-022c): `payUrl` is the target, or the URL one same-origin redirect led to.
403
+ const { response: challenge, url: payUrl } = await fetchPaymentChallenge(options.target, buildInit(options));
404
+ return { ...(await paymentTerms(challenge, options.network)), payUrl };
405
+ }
406
+ /** The terms of a challenge already fetched, by the rules of {@link readPaymentChallenge}. */
407
+ async function paymentTerms(challenge, network) {
408
+ const options = { network };
361
409
  let paymentRequired;
362
410
  try {
363
- paymentRequired = httpClient.getPaymentRequiredResponse((name) => challenge.headers.get(name));
411
+ paymentRequired = new x402HTTPClient(new x402Client()).getPaymentRequiredResponse((name) => challenge.headers.get(name));
364
412
  }
365
413
  catch (error) {
366
414
  // The read checks already report what is wrong with the challenge. Failing
@@ -377,6 +425,7 @@ async function preparePayment(options, alter, beforeSigning) {
377
425
  `(${error.message}), so no payment was attempted ` +
378
426
  `(see X402-02–04).`);
379
427
  }
428
+ await challenge.body?.cancel().catch(() => undefined);
380
429
  // A target that offers no option Wasit can pay has not refused anything:
381
430
  // there is no payment to judge, so neither check gets a verdict. X402-05
382
431
  // already reports which networks it advertises.
@@ -395,18 +444,94 @@ async function preparePayment(options, alter, beforeSigning) {
395
444
  // The payment-identifier extension lets a server answer a repeated payload
396
445
  // with its cached response (specs/extensions/payment_identifier.md).
397
446
  const idempotent = paymentRequired.extensions?.["payment-identifier"] !== undefined;
447
+ return { paymentRequired, selected, idempotent };
448
+ }
449
+ /** A stable text of a value, keys sorted, for a field-by-field comparison. */
450
+ function canonical(value) {
451
+ return JSON.stringify(value, (_key, item) => item !== null && typeof item === "object" && !Array.isArray(item)
452
+ ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
453
+ : item);
454
+ }
455
+ /**
456
+ * L2 against the plan: the option a check is about to pay must be the one the
457
+ * plan read, and the amount at most what the plan allowed for that check.
458
+ * Returns that amount, or undefined when the run has no plan.
459
+ */
460
+ function plannedAmount(plan, check, selected) {
461
+ if (plan === undefined)
462
+ return undefined;
463
+ const option = plan.option;
464
+ if (plan.status !== "planned" || option === undefined) {
465
+ 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.` +
466
+ (plan.reason === undefined ? "" : ` The plan says: ${plan.reason}`));
467
+ }
468
+ for (const field of ["scheme", "network", "payTo", "asset"]) {
469
+ const same = field === "payTo" || field === "asset"
470
+ ? sameAddress(option.network, String(selected[field]), option[field])
471
+ : selected[field] === option[field];
472
+ if (!same) {
473
+ throw new PaymentGuardRefusedError("plan", `${check}: the service changed its ${field} after the plan (the plan read ${option[field]}), ` +
474
+ `so the payment the plan allowed is not the one it now asks for.`);
475
+ }
476
+ }
477
+ const entry = plan.signatures.find((signature) => signature.check === check);
478
+ if (entry === undefined) {
479
+ throw new PaymentGuardRefusedError("plan", `The plan of this run has no signature for ${check}.`);
480
+ }
481
+ return entry.amount;
482
+ }
483
+ /**
484
+ * Reads the challenge and produces a signed payment payload for it.
485
+ *
486
+ * Shared by every payment check so each one starts from a challenge the
487
+ * target issued just now, rather than reusing a stale one. With `altered`,
488
+ * the payment is signed for those terms instead, and its `accepted` is set
489
+ * back to what the target advertised. `beforeSigning` runs once the option
490
+ * to pay is known and before the client builds anything: the Stellar client
491
+ * simulates the transfer while building, so a check placed later would never
492
+ * see an unfunded payer.
493
+ *
494
+ * L2 (spec B3) is here, between the fresh challenge and the SDK: the pin over
495
+ * every `exact` option, the plan, the $1 cap and the run's cap, the run charged
496
+ * before the signature. The SDK is then handed exactly the one option checked,
497
+ * and a payload whose `accepted` is not that option is discarded unsent.
498
+ */
499
+ async function preparePayment(options, check, alter, beforeSigning) {
500
+ // L0 again at the one function every x402 signature goes through, whoever
501
+ // reaches it: nothing is fetched or signed on a network that is not a test
502
+ // network.
503
+ assertPaymentNetworkAllowed("x402", options.network);
504
+ const chain = chainFor(options.network);
505
+ const budget = options.budget ?? new RunBudget();
506
+ const { client, httpClient } = await buildX402Client(chain, options.network, options.payerSecretKey, chain.resolveRpcUrl(options.network, options.rpcUrl), options.pin);
507
+ const { paymentRequired, selected, idempotent, payUrl } = await readPaymentChallenge(options);
508
+ // L2, before anything is built: the service may change its challenge between
509
+ // requests, so the plan alone is not enough.
510
+ assertPinned(options.network, paymentRequired.accepts, options.pin);
511
+ const planned = plannedAmount(options.plan, check, selected);
512
+ const signing = alter === undefined ? selected : { ...selected, ...(await alter(selected)) };
513
+ for (const field of ["scheme", "network", "payTo", "asset"]) {
514
+ if (signing[field] !== selected[field]) {
515
+ throw new PaymentGuardRefusedError("accepted", `${check} would sign different ${field} terms than the target's.`);
516
+ }
517
+ }
518
+ budget.charge({
519
+ check,
520
+ network: options.network,
521
+ asset: signing.asset,
522
+ amount: signing.amount,
523
+ ...(planned === undefined ? {} : { planned }),
524
+ });
398
525
  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 };
526
+ const signed = await withinSpendControls(options.network, selected, () => client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }));
527
+ // What the SDK says it signed must be the option checked, field by field;
528
+ // otherwise the payload is discarded here, unsent. It stays charged.
529
+ if (canonical(signed.accepted) !== canonical(signing)) {
530
+ throw new PaymentGuardRefusedError("accepted", `The payment the x402 client built for ${check} names other terms in its accepted field than the ` +
531
+ `option Wasit checked.`, { signed: true });
532
+ }
533
+ const paymentPayload = alter === undefined ? signed : { ...signed, accepted: selected };
534
+ return { httpClient, paymentPayload, selected, idempotent, payUrl };
410
535
  }
411
536
  /**
412
537
  * Reads the settlement a paid response reports, before anything is looked up.
@@ -484,14 +609,16 @@ async function checkSignatureAccepted(options) {
484
609
  const id = "X402-06";
485
610
  const name = "Signature Resubmit Accepted";
486
611
  const fail = (detail, hint) => ({ id, name, pass: false, detail, hint });
487
- const { httpClient, paymentPayload, idempotent } = await preparePayment(options, undefined, (selected) => assertPayerCanPay(options, selected));
612
+ const { httpClient, paymentPayload, idempotent, payUrl } = await preparePayment(options, "X402-06", undefined, (selected) => assertPayerCanPay(options, selected));
488
613
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
489
- const paid = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
614
+ const paid = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders));
490
615
  const honest = (result, accepted) => ({
491
616
  result,
492
617
  accepted,
493
618
  headers: paymentHeaders,
619
+ url: payUrl,
494
620
  idempotent,
621
+ payload: paymentPayload.payload,
495
622
  });
496
623
  if (paid.status < 200 || paid.status >= 300) {
497
624
  const reason = await refusalReason(paid);
@@ -539,6 +666,8 @@ async function checkSignatureAccepted(options) {
539
666
  name,
540
667
  pass: true,
541
668
  detail: `Valid payment accepted (HTTP ${paid.status}) and ${verdict.detail}.`,
669
+ // Read back from the chain and found to be this payment: a report may link it.
670
+ reference,
542
671
  }
543
672
  : fail(verdict.detail, "PAYMENT-RESPONSE must name the transaction that settled this payment, " +
544
673
  "and that transaction must move exactly `amount` of `asset` from the " +
@@ -558,13 +687,13 @@ async function checkSignatureAccepted(options) {
558
687
  * answer: anything that prevents one produces no verdict.
559
688
  */
560
689
  async function checkInvalidSignatureRejected(options) {
561
- const { httpClient, paymentPayload } = await preparePayment(options);
690
+ const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-07");
562
691
  const corrupted = {
563
692
  ...paymentPayload,
564
693
  payload: chainFor(options.network).corruptPayload(paymentPayload.payload),
565
694
  };
566
695
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted);
567
- const response = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
696
+ const response = await fetchTarget(payUrl, withPaymentHeaders(options, paymentHeaders));
568
697
  return signatureRejectionVerdict(response.status, await refusalReason(response));
569
698
  }
570
699
  /**
@@ -655,7 +784,7 @@ async function checkReplayRejected(options, honest) {
655
784
  return skipped("X402-08", "Payment Replay Rejected", "the challenge advertises the payment-identifier extension, under which a " +
656
785
  "server may answer a repeated payment with its cached response.");
657
786
  }
658
- const response = await fetchTarget(options.target, withPaymentHeaders(options, honest.headers));
787
+ const response = await fetchTarget(honest.url, withPaymentHeaders(options, honest.headers));
659
788
  return replayVerdict(response.status, await refusalReason(response));
660
789
  }
661
790
  /** X402-08's verdict from the status the replayed payment drew. */
@@ -689,11 +818,22 @@ export function replayVerdict(status, reason) {
689
818
  * accepts, the lower amount may settle.
690
819
  */
691
820
  async function checkUnderpaymentRejected(options) {
821
+ // The plan of `wasit run` leaves X402-09 out at a price below 2 base units;
822
+ // the check is then skipped as it is without a plan, and nothing is fetched.
823
+ const plan = options.plan;
824
+ if (plan?.status === "planned" &&
825
+ plan.option !== undefined &&
826
+ plan.option.amount < 2n &&
827
+ !plan.signatures.some((signature) => signature.check === "X402-09")) {
828
+ const price = plan.option.amount;
829
+ return skipped("X402-09", "Underpayment Rejected", `the advertised price is ${price} base unit${price === 1n ? "" : "s"} (as the plan read it before the run), so ` +
830
+ `there is no smaller payment to offer.`);
831
+ }
692
832
  let advertised = 0n;
693
833
  let offered = 0n;
694
834
  let prepared;
695
835
  try {
696
- prepared = await preparePayment(options, (selected) => {
836
+ prepared = await preparePayment(options, "X402-09", (selected) => {
697
837
  try {
698
838
  advertised = BigInt(selected.amount);
699
839
  }
@@ -714,8 +854,8 @@ async function checkUnderpaymentRejected(options) {
714
854
  }
715
855
  throw error;
716
856
  }
717
- const { httpClient, paymentPayload } = prepared;
718
- const response = await fetchTarget(options.target, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
857
+ const { httpClient, paymentPayload, payUrl } = prepared;
858
+ const response = await fetchTarget(payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
719
859
  return underpaymentVerdict(response.status, offered, advertised, await refusalReason(response));
720
860
  }
721
861
  /** X402-09's verdict from the status the underpaid payment drew. */
@@ -755,13 +895,13 @@ async function checkExpiredRejected(options) {
755
895
  const chain = chainFor(options.network);
756
896
  const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
757
897
  let holdMs = 0;
758
- const { httpClient, paymentPayload } = await preparePayment(options, async (selected) => {
898
+ const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-10", async (selected) => {
759
899
  const expired = await chain.expiredSigning(selected, rpcUrl);
760
900
  holdMs = expired.holdMs;
761
901
  return expired.terms;
762
902
  });
763
903
  await new Promise((done) => setTimeout(done, holdMs));
764
- const response = await fetchTarget(options.target, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
904
+ const response = await fetchTarget(payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
765
905
  return expiredVerdict(response.status, await refusalReason(response));
766
906
  }
767
907
  /** X402-10's verdict from the status the expired payment drew. */
@@ -784,12 +924,221 @@ export function expiredVerdict(status, reason) {
784
924
  : {}),
785
925
  };
786
926
  }
927
+ /** A signed authorization, decoded and held to the run's payer; `what` names it in a message. */
928
+ function authorizationOf(chain, payload, payer, what) {
929
+ const watch = chain.authorizations;
930
+ let decoded;
931
+ try {
932
+ decoded = watch.decode(payload);
933
+ }
934
+ catch (error) {
935
+ if (error instanceof CheckSetupError)
936
+ throw error;
937
+ throw new CheckSetupError(`The authorization of ${what} could not be read from its payload (${error.message}).`);
938
+ }
939
+ if (decoded.payer !== payer) {
940
+ throw new CheckSetupError(`The authorization of ${what} is signed by another address than this run's payer.`);
941
+ }
942
+ return decoded;
943
+ }
944
+ /** A lifetime X402-11 signs for: at least 30 s, and at most the 300 s it waits out. */
945
+ function withinRejectLifetime(value) {
946
+ const lifetime = Number(value);
947
+ return lifetime >= REJECTED_REQUEST_MIN_LIFETIME_SECONDS && lifetime <= REJECTED_REQUEST_MAX_LIFETIME_SECONDS;
948
+ }
949
+ /** Thrown before signing when the challenge X402-11 is paid from advertises a lifetime it does not sign for. */
950
+ class RejectLifetimeOutside extends Error {
951
+ lifetime;
952
+ constructor(lifetime) {
953
+ super("the advertised lifetime is outside what X402-11 signs for");
954
+ this.lifetime = lifetime;
955
+ }
956
+ }
957
+ /**
958
+ * X402-11 (negative, spec B7 as D-032 changed it): a valid payment sent with a
959
+ * request the service must refuse must not settle. See `rejected-request.ts`
960
+ * for the rules and the verdict.
961
+ *
962
+ * Nothing is signed when the check could not reach a verdict anyway: no
963
+ * reject case, X402-06 not shown settled (its nonce is the control), a chain
964
+ * whose authorizations Wasit cannot read, a service that refuses the request
965
+ * before asking for payment, an advertised lifetime above 300 s, or a control
966
+ * the chain does not return. The payment then goes through `preparePayment`
967
+ * like every other: the pin, the plan, the $1 and run caps, the advertised
968
+ * terms exactly.
969
+ */
970
+ async function checkRejectedRequestNotSettled(options, honest) {
971
+ const id = REJECTED_REQUEST_ID;
972
+ const name = REJECTED_REQUEST_NAME;
973
+ const reject = options.reject;
974
+ if (reject === undefined) {
975
+ return skipped(id, name, "no request the service must refuse is configured (endpoints[].reject in wasit.config.json, read by " +
976
+ "wasit run), so there is nothing to send. Nothing was signed.", "not-applicable");
977
+ }
978
+ const chain = chainFor(options.network);
979
+ const watch = chain.authorizations;
980
+ if (watch === undefined) {
981
+ return skipped(id, name, `Wasit cannot read on ${chain.name} whether a payment's authorization was used, which this check needs, ` +
982
+ `so nothing was signed.`, "not-applicable");
983
+ }
984
+ if (honest.result.pass !== true || honest.result.error !== undefined || honest.result.skipped === true) {
985
+ return skipped(id, name, "X402-06's payment was not shown settled on chain, so its authorization cannot be the control that shows a " +
986
+ "chain read is complete. Nothing was signed.", "dependency");
987
+ }
988
+ // The reject request is the endpoint's request with the reject case over it.
989
+ const { method: _method, headers: _headers, body: _body, ...rest } = options;
990
+ const shape = rejectRequestShape(options, reject);
991
+ const rejectOptions = { ...rest, ...shape };
992
+ // Without payment first: a service that refuses it before asking for payment
993
+ // gives this check nothing to watch.
994
+ const { response: unpaid } = await fetchPaymentChallenge(options.target, buildInit(shape));
995
+ if (unpaid.status !== 402) {
996
+ await unpaid.body?.cancel().catch(() => undefined);
997
+ const status = unpaid.status;
998
+ return skipped(id, name, status >= 400 && status < 500
999
+ ? `the service refuses this request before any payment is asked (HTTP ${status}), so there is no payment ` +
1000
+ `to watch. Nothing was signed.`
1001
+ : `the service answered this request with HTTP ${status} without asking for payment, so there is no ` +
1002
+ `payment to watch. Nothing was signed.`, "not-applicable");
1003
+ }
1004
+ const { selected: advertised } = await paymentTerms(unpaid, options.network);
1005
+ const outside = (value, again) => skipped(id, name, `the service's payments stay valid for ${sanitizeText(String(value))} seconds (maxTimeoutSeconds)` +
1006
+ (again ? ", as it said when asked for payment again" : "") +
1007
+ (Number(value) > REJECTED_REQUEST_MAX_LIFETIME_SECONDS
1008
+ ? `, longer than the ${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds Wasit waits for one to expire on a ` +
1009
+ `test network, so this check could not show that the payment never settled.`
1010
+ : `, shorter than the ${REJECTED_REQUEST_MIN_LIFETIME_SECONDS} seconds this check needs: such a payment can ` +
1011
+ `expire before a service that settles it has it on chain, so its unused authorization would show nothing.`) +
1012
+ ` Nothing was signed.`);
1013
+ if (!withinRejectLifetime(advertised.maxTimeoutSeconds))
1014
+ return outside(advertised.maxTimeoutSeconds, false);
1015
+ const network = options.network;
1016
+ const rpcUrl = chain.resolveRpcUrl(network, options.rpcUrl);
1017
+ const payer = chain.payerAddress(options.payerSecretKey);
1018
+ const control = authorizationOf(chain, honest.payload, payer, "X402-06's payment");
1019
+ // Before signing: the chain must return X402-06's used authorization, and the
1020
+ // payer's balance must be readable. Otherwise no verdict could be reached, and
1021
+ // nothing is signed.
1022
+ let balanceBefore = 0n;
1023
+ let prepared;
1024
+ try {
1025
+ prepared = await preparePayment(rejectOptions, id, undefined, async (selected) => {
1026
+ // The challenge is read again for the signature, and the service may
1027
+ // answer it with another lifetime: the one signed is held to 300 s too.
1028
+ if (!withinRejectLifetime(selected.maxTimeoutSeconds))
1029
+ throw new RejectLifetimeOutside(selected.maxTimeoutSeconds);
1030
+ let read;
1031
+ try {
1032
+ read = await watch.read(network, rpcUrl, [control]);
1033
+ }
1034
+ catch (error) {
1035
+ throw new CheckSetupError(`The chain could not be read before signing (${error.message}). Nothing was signed.`);
1036
+ }
1037
+ if (read.used[0] === undefined) {
1038
+ throw new CheckSetupError("The chain's answer leaves out X402-06's authorization, which was used, so a later read could not show " +
1039
+ "that this payment's was not. Nothing was signed.");
1040
+ }
1041
+ let balance;
1042
+ try {
1043
+ balance = await chain.payerBalance(network, rpcUrl, payer, advertised.asset);
1044
+ }
1045
+ catch {
1046
+ balance = undefined;
1047
+ }
1048
+ if (balance === undefined) {
1049
+ throw new CheckSetupError("The payer's balance could not be read, and this check needs it as a second reading. Nothing was signed.");
1050
+ }
1051
+ balanceBefore = balance;
1052
+ });
1053
+ }
1054
+ catch (error) {
1055
+ if (error instanceof RejectLifetimeOutside)
1056
+ return outside(error.lifetime, true);
1057
+ throw error;
1058
+ }
1059
+ const { httpClient, paymentPayload, selected, payUrl } = prepared;
1060
+ const amount = BigInt(selected.amount);
1061
+ const ours = authorizationOf(chain, paymentPayload.payload, payer, "this payment");
1062
+ if (ours.nonce === control.nonce) {
1063
+ throw new CheckSetupError("This payment's authorization carries X402-06's nonce, so it could not be told apart. It was not sent.");
1064
+ }
1065
+ // Right before sending: ours unused, the control found. This read's ledger
1066
+ // starts the range the transfers are read over.
1067
+ const before = await watch.read(network, rpcUrl, [ours, control]);
1068
+ if (before.used[1] === undefined) {
1069
+ throw new CheckSetupError("The chain's answer leaves out X402-06's authorization, so this payment was not sent.");
1070
+ }
1071
+ if (before.used[0] !== undefined) {
1072
+ throw new CheckSetupError("The chain records this payment's authorization as used before it was sent, so it was not sent.");
1073
+ }
1074
+ // What the client signed, not what it was asked: an authorization that stays
1075
+ // valid longer than the 300 s this check waits is not sent (2 units of slack
1076
+ // for the ledgers that close while it is built).
1077
+ const longest = Math.ceil(REJECTED_REQUEST_MAX_LIFETIME_SECONDS / watch.unitSeconds) + 2;
1078
+ if (ours.expiresAt - before.latest > longest) {
1079
+ throw new CheckSetupError(`This payment's authorization stays valid until ${watch.unit} ${ours.expiresAt}, ` +
1080
+ `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}), longer than the ` +
1081
+ `${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds this check waits. It was signed and discarded; it was not sent.`);
1082
+ }
1083
+ // And long enough that a service which settles it could still get it on chain.
1084
+ if (ours.expiresAt - before.latest < REJECTED_REQUEST_MIN_UNITS_LEFT) {
1085
+ throw new CheckSetupError(`This payment's authorization expires at ${watch.unit} ${ours.expiresAt}, ` +
1086
+ `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}): too soon for an unused ` +
1087
+ `authorization to show anything. It was signed and discarded; it was not sent.`);
1088
+ }
1089
+ const sentAt = Date.now();
1090
+ const response = await fetchTarget(payUrl, withPaymentHeaders(shape, httpClient.encodePaymentSignatureHeader(paymentPayload)));
1091
+ const status = response.status;
1092
+ const reason = await refusalReason(response);
1093
+ options.onProgress?.(`X402-11: the payment was sent with the request the service must refuse (HTTP ${status}); reading the chain ` +
1094
+ `once a ${watch.unit} until its authorization expires at ${watch.unit} ${ours.expiresAt}, for at most ` +
1095
+ `${Math.round(rejectedRequestHardStopMs() / 1000)} s.`);
1096
+ let outcome = await watchAuthorization({ watch, network, rpcUrl, ours, control, sentAt });
1097
+ let balance;
1098
+ let transfers;
1099
+ if (outcome.kind === "used" || outcome.kind === "unused") {
1100
+ try {
1101
+ const after = await chain.payerBalance(network, rpcUrl, payer, selected.asset);
1102
+ if (after === undefined)
1103
+ throw new Error("the payer's balance could not be read after the watch");
1104
+ balance = { before: balanceBefore, after };
1105
+ const recorded = await watch.transfers(network, rpcUrl, {
1106
+ asset: selected.asset,
1107
+ from: payer,
1108
+ to: selected.payTo,
1109
+ fromLedger: before.latest + 1,
1110
+ });
1111
+ // Only what the watch covered: from the ledger after the pre-send read to the last ledger
1112
+ // it read. A later transfer of the same amount (another run with this payer) is not this one.
1113
+ const lastRead = outcome.latest;
1114
+ transfers = recorded.transfers
1115
+ .filter((transfer) => transfer.amount === amount && transfer.ledger <= lastRead)
1116
+ .map((transfer) => ({ reference: transfer.reference, ledger: transfer.ledger }));
1117
+ }
1118
+ catch (error) {
1119
+ outcome = { kind: "unread", why: `the second readings failed: ${sanitizeText(error.message).slice(0, 200)}` };
1120
+ balance = undefined;
1121
+ transfers = undefined;
1122
+ }
1123
+ }
1124
+ return rejectedRequestVerdict({
1125
+ status,
1126
+ ...(reason === undefined ? {} : { reason }),
1127
+ amount,
1128
+ expiresAt: ours.expiresAt,
1129
+ unit: watch.unit,
1130
+ watch: outcome,
1131
+ ...(balance === undefined ? {} : { balance }),
1132
+ ...(transfers === undefined ? {} : { transfers }),
1133
+ });
1134
+ }
787
1135
  /** The negative checks, in catalogue order, each with how it runs. */
788
1136
  const NEGATIVE_CHECKS = [
789
1137
  ["X402-07", "Invalid Signature Rejected", (options) => checkInvalidSignatureRejected(options)],
790
1138
  ["X402-08", "Payment Replay Rejected", checkReplayRejected],
791
1139
  ["X402-09", "Underpayment Rejected", (options) => checkUnderpaymentRejected(options)],
792
1140
  ["X402-10", "Expired Authorization Rejected", (options) => checkExpiredRejected(options)],
1141
+ [REJECTED_REQUEST_ID, REJECTED_REQUEST_NAME, checkRejectedRequestNotSettled],
793
1142
  ];
794
1143
  /**
795
1144
  * Every check `runX402PaymentChecks` reports, in order. Front ends that list
@@ -806,7 +1155,10 @@ export const X402_PAYMENT_CHECK_IDS = [
806
1155
  * target must refuse; a target that accepts the underpaid one may settle it.
807
1156
  * See docs/CHECKS.md.
808
1157
  */
809
- export async function runX402PaymentChecks(options) {
1158
+ export async function runX402PaymentChecks(input) {
1159
+ // One budget for every signature these checks make: the run's, when the
1160
+ // caller shares one across endpoints, or this call's own $5.
1161
+ const options = { ...input, budget: input.budget ?? new RunBudget() };
810
1162
  try {
811
1163
  assertHttpUrl(options.target);
812
1164
  buildInit(options);
@@ -815,7 +1167,11 @@ export async function runX402PaymentChecks(options) {
815
1167
  // money moves, so a run that could not finish is stopped here rather than
816
1168
  // after paying.
817
1169
  const chain = chainFor(options.network);
818
- chain.resolveRpcUrl(options.network, options.rpcUrl);
1170
+ // L0: an adapter for the network is not permission to pay on it. Only a
1171
+ // test network passes; stellar:pubnet waits for the mainnet opt-in, which
1172
+ // this version does not have.
1173
+ assertPaymentNetworkAllowed("x402", options.network);
1174
+ const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
819
1175
  // A key for another chain, or a malformed one, would otherwise surface
820
1176
  // mid-payment as a harness error. Checked here, it is what it is: the
821
1177
  // run's configuration. The message never echoes the key.
@@ -828,8 +1184,22 @@ export async function runX402PaymentChecks(options) {
828
1184
  throw new ConfigurationError(`The payer key is not a valid ${chain.name} key (read from ${chain.payerKeyEnv} ` +
829
1185
  `or --payer-key).`);
830
1186
  }
1187
+ // The RPC signs and settles nothing itself, but the payment is built and
1188
+ // its settlement read through it: it must serve the run's network (D-023).
1189
+ await assertRpcServesNetwork(options.network, rpcUrl);
831
1190
  }
832
1191
  catch (error) {
1192
+ // A network no adapter pays on is not a failure of the run: Wasit does not
1193
+ // grade it (spec A3). Every payment check is skipped as unsupported, and
1194
+ // nothing was fetched or signed. The guard's refusals are not this: they
1195
+ // are other errors, and stay a PREFLIGHT error below.
1196
+ if (error instanceof UnsupportedPaymentNetworkError) {
1197
+ const unsupported = [["X402-06", "Signature Resubmit Accepted"], ...NEGATIVE_CHECKS.map(([id, name]) => [id, name])]
1198
+ .map(([id, name]) => skipped(id, name, error.message, "unsupported"));
1199
+ for (const result of unsupported)
1200
+ options.onResult?.(result);
1201
+ return unsupported;
1202
+ }
833
1203
  const preflight = errored("PREFLIGHT", "Run Preflight", error);
834
1204
  options.onResult?.(preflight);
835
1205
  return [preflight];