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

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 (88) hide show
  1. package/README.md +13 -2
  2. package/dist/baseline.d.ts +109 -0
  3. package/dist/baseline.js +353 -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 +399 -0
  9. package/dist/config-writer.d.ts +96 -0
  10. package/dist/config-writer.js +281 -0
  11. package/dist/config.d.ts +205 -0
  12. package/dist/config.js +1011 -0
  13. package/dist/denied-env.d.ts +33 -0
  14. package/dist/denied-env.js +86 -0
  15. package/dist/errors.d.ts +44 -1
  16. package/dist/errors.js +151 -2
  17. package/dist/guard/budget.d.ts +138 -0
  18. package/dist/guard/budget.js +206 -0
  19. package/dist/guard/ci-event.d.ts +56 -0
  20. package/dist/guard/ci-event.js +129 -0
  21. package/dist/guard/ci-mainnet.d.ts +59 -0
  22. package/dist/guard/ci-mainnet.js +149 -0
  23. package/dist/guard/horizon.d.ts +30 -0
  24. package/dist/guard/horizon.js +107 -0
  25. package/dist/guard/mainnet-payer.d.ts +66 -0
  26. package/dist/guard/mainnet-payer.js +92 -0
  27. package/dist/guard/mainnet-plan.d.ts +133 -0
  28. package/dist/guard/mainnet-plan.js +208 -0
  29. package/dist/guard/mainnet-run.d.ts +87 -0
  30. package/dist/guard/mainnet-run.js +225 -0
  31. package/dist/guard/networks.d.ts +51 -0
  32. package/dist/guard/networks.js +91 -0
  33. package/dist/guard/optin.d.ts +106 -0
  34. package/dist/guard/optin.js +202 -0
  35. package/dist/guard/rpc-identity.d.ts +45 -0
  36. package/dist/guard/rpc-identity.js +156 -0
  37. package/dist/guard/rpc-in-use.d.ts +48 -0
  38. package/dist/guard/rpc-in-use.js +84 -0
  39. package/dist/guard/run-ledger.d.ts +212 -0
  40. package/dist/guard/run-ledger.js +426 -0
  41. package/dist/guard/run-lock.d.ts +62 -0
  42. package/dist/guard/run-lock.js +172 -0
  43. package/dist/guard/signed-terms.d.ts +96 -0
  44. package/dist/guard/signed-terms.js +207 -0
  45. package/dist/index.d.ts +44 -4
  46. package/dist/index.js +42 -2
  47. package/dist/mpp/channel-commitment.d.ts +48 -2
  48. package/dist/mpp/channel-commitment.js +80 -4
  49. package/dist/mpp/channel-credential.d.ts +13 -1
  50. package/dist/mpp/channel-credential.js +21 -2
  51. package/dist/mpp/channel.d.ts +6 -0
  52. package/dist/mpp/channel.js +36 -3
  53. package/dist/mpp/charge.d.ts +33 -1
  54. package/dist/mpp/charge.js +90 -20
  55. package/dist/mpp/network.js +4 -1
  56. package/dist/mpp/plan.d.ts +77 -0
  57. package/dist/mpp/plan.js +188 -0
  58. package/dist/mpp/suite.d.ts +6 -0
  59. package/dist/mpp/suite.js +12 -3
  60. package/dist/report.d.ts +163 -0
  61. package/dist/report.js +282 -0
  62. package/dist/route-reader.d.ts +124 -0
  63. package/dist/route-reader.js +349 -0
  64. package/dist/sanitize.d.ts +52 -0
  65. package/dist/sanitize.js +106 -0
  66. package/dist/settlement.d.ts +14 -0
  67. package/dist/settlement.js +1 -1
  68. package/dist/verdict.d.ts +24 -0
  69. package/dist/verdict.js +46 -0
  70. package/dist/versions.d.ts +50 -0
  71. package/dist/versions.js +123 -0
  72. package/dist/wallet.d.ts +58 -1
  73. package/dist/wallet.js +128 -0
  74. package/dist/x402/chains/evm.js +3 -0
  75. package/dist/x402/chains/index.d.ts +8 -0
  76. package/dist/x402/chains/index.js +13 -2
  77. package/dist/x402/chains/stellar.d.ts +8 -1
  78. package/dist/x402/chains/stellar.js +259 -4
  79. package/dist/x402/chains/types.d.ts +104 -2
  80. package/dist/x402/plan.d.ts +184 -0
  81. package/dist/x402/plan.js +520 -0
  82. package/dist/x402/rejected-request.d.ts +156 -0
  83. package/dist/x402/rejected-request.js +287 -0
  84. package/dist/x402/requirements.d.ts +1 -0
  85. package/dist/x402/requirements.js +37 -4
  86. package/dist/x402/simulator.d.ts +86 -1
  87. package/dist/x402/simulator.js +863 -87
  88. package/package.json +1 -1
@@ -1,5 +1,14 @@
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, shown, } from "../guard/budget.js";
4
+ import { MainnetPlanRefusedError, assertMainnetOption, paidUrlOf } from "../guard/mainnet-plan.js";
5
+ import { PaymentNetworkRefusedError, assertPaymentNetworkAllowed } from "../guard/networks.js";
6
+ import { MainnetRunRefusedError, anchorOfOptIn, isLiveOptIn } from "../guard/optin.js";
7
+ import { SigningAnchor, SigningGate, expirationOfSigned } from "../guard/signed-terms.js";
8
+ import { RunLedgerError } from "../guard/run-ledger.js";
9
+ import { RpcIdentityError, assertRpcServesNetwork } from "../guard/rpc-identity.js";
10
+ import { REJECTED_REQUEST_ID, REJECTED_REQUEST_MAX_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_UNITS_LEFT, REJECTED_REQUEST_NAME, rejectRequestShape, rejectedRequestHardStopMs, rejectedRequestSettlement, rejectedRequestVerdict, watchAuthorization, } from "./rejected-request.js";
11
+ import { sanitizeText } from "../sanitize.js";
3
12
  import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js";
4
13
  const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
5
14
  const KNOWN_METHODS = new Set([
@@ -16,8 +25,10 @@ const KNOWN_METHODS = new Set([
16
25
  *
17
26
  * A bad method, or a body on a verb that cannot carry one, is a configuration
18
27
  * error rather than a finding: nothing has been learned about the target.
28
+ * Exported for `wasit init`'s unpaid request (route-reader.ts), which sends
29
+ * the route what the read checks send it.
19
30
  */
20
- function buildInit(shape) {
31
+ export function buildInit(shape) {
21
32
  const method = (shape.method ?? "GET").toUpperCase();
22
33
  if (!KNOWN_METHODS.has(method)) {
23
34
  throw new ConfigurationError(`"${shape.method}" is not an HTTP method. Expected one of ` +
@@ -89,7 +100,7 @@ function statusHint(status) {
89
100
  /** Skips every check after `id`, naming the one cause they all depend on. */
90
101
  function skipAfter(id, reason) {
91
102
  const index = READ_CHECKS.findIndex(([candidate]) => candidate === id);
92
- return READ_CHECKS.slice(index + 1).map(([checkId, name]) => skipped(checkId, name, reason));
103
+ return READ_CHECKS.slice(index + 1).map(([checkId, name]) => skipped(checkId, name, reason, "dependency"));
93
104
  }
94
105
  function asRecord(value) {
95
106
  return typeof value === "object" && value !== null
@@ -115,6 +126,11 @@ export function readV1BodyChallenge(body) {
115
126
  const record = asRecord(parsed);
116
127
  return record?.["x402Version"] === 1 && Array.isArray(record["accepts"]) ? record : undefined;
117
128
  }
129
+ /** What a header that did not decode to JSON held, quoted. The service chose it; the sinks cut it. */
130
+ function decodedStart(headerValue) {
131
+ const decoded = Buffer.from(headerValue, "base64").toString("utf-8");
132
+ return decoded === "" ? "an empty value" : `a value that starts with ${quoteValue(decoded)}`;
133
+ }
118
134
  /** A body that cannot be read is simply not a v1 challenge. */
119
135
  async function readText(response) {
120
136
  try {
@@ -124,6 +140,21 @@ async function readText(response) {
124
140
  return "";
125
141
  }
126
142
  }
143
+ /**
144
+ * Why an x402 v1 challenge is not graded: the reason on X402-02..05 and on the
145
+ * endpoint, on every chain (a v1 service on an EVM chain gets it too). Kept
146
+ * under 300 characters, the longest a value goes into a pull request comment,
147
+ * so the way to get graded is not cut off. It names no URL: the comment's
148
+ * sanitiser removes links from check text, so it points at docs/CHECKS.md,
149
+ * whose note on x402 v1 links the x402 specification.
150
+ */
151
+ const V1_UNSUPPORTED_REASON = "the service sent an x402 v1 challenge (x402Version 1, in the body). Wasit grades only x402 v2, on " +
152
+ "every chain: challenge in a PAYMENT-REQUIRED header, CAIP-2 networks, v2 `exact` scheme (Stellar is " +
153
+ "v2 only). Unsupported, not failed. Fix: move it to that header. Why: docs/CHECKS.md.";
154
+ /** What a check found on a challenge Wasit does not grade, to be shown as a note. */
155
+ function noteOf(result) {
156
+ return result.skipped === true ? (result.skipReason ?? result.detail) : result.detail;
157
+ }
127
158
  /**
128
159
  * Runs X402-01 through X402-05 against a target.
129
160
  *
@@ -151,7 +182,9 @@ export async function runX402ReadChecks(options) {
151
182
  }
152
183
  let response;
153
184
  try {
154
- response = await fetchTarget(target, init);
185
+ // The unpaid request of the read-only tier: a redirect to another origin
186
+ // is reported and gives no verdict, never followed (spec A8 #5).
187
+ response = await fetchTarget(target, init, { redirects: "same-origin" });
155
188
  }
156
189
  catch (error) {
157
190
  return emit([
@@ -167,7 +200,9 @@ export async function runX402ReadChecks(options) {
167
200
  detail: statusPass
168
201
  ? "Server responded with 402 as required."
169
202
  : `Expected status 402, got ${response.status}.`,
170
- ...(statusPass ? {} : { hint: statusHint(response.status) }),
203
+ ...(statusPass
204
+ ? {}
205
+ : { hint: statusHint(response.status), expected: "status 402", actual: `status ${response.status}` }),
171
206
  };
172
207
  if (!statusPass) {
173
208
  return emit([
@@ -179,49 +214,42 @@ export async function runX402ReadChecks(options) {
179
214
  // Both names are checked because Stellar's own documentation is not yet
180
215
  // internally consistent — see docs/CHECKS.md.
181
216
  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.
217
+ // x402 v1 signals payment in the response body rather than a header, and the
218
+ // `exact` scheme on Stellar is defined for v2 only. Wasit grades v2, so a v1
219
+ // service is unsupported, not failed (spec A3): X402-02..05 are skipped with
220
+ // that reason. The v1 terms are still read and reported as notes, so an
221
+ // operator sees which of them diverge without being handed a verdict.
186
222
  const v1Payload = headerValue === null ? readV1BodyChallenge(await readText(response)) : undefined;
223
+ if (headerValue === null && v1Payload !== undefined) {
224
+ const notes = new Map([
225
+ ["X402-04", noteOf(checkRequiredFields(v1Payload))],
226
+ ["X402-05", noteOf(checkNetworkIdentifier(v1Payload))],
227
+ ]);
228
+ return emit([
229
+ r1,
230
+ ...READ_CHECKS.slice(1).map(([id, name]) => {
231
+ const skip = skipped(id, name, V1_UNSUPPORTED_REASON, "unsupported");
232
+ const note = notes.get(id);
233
+ return note === undefined ? skip : { ...skip, detail: `${skip.detail} Note, not a verdict: ${note}` };
234
+ }),
235
+ ]);
236
+ }
187
237
  const r2 = {
188
238
  id: "X402-02",
189
239
  name: "Payment Header Present",
190
240
  pass: headerValue !== null,
191
241
  detail: headerValue !== null
192
242
  ? "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.",
243
+ : "Neither PAYMENT-REQUIRED nor X-Payment header was present.",
199
244
  ...(headerValue !== null
200
245
  ? {}
201
246
  : {
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.",
247
+ hint: "Send the challenge as base64-encoded JSON in a PAYMENT-REQUIRED " +
248
+ "response header, as the x402 v2 HTTP transport defines.",
249
+ expected: "a PAYMENT-REQUIRED header",
250
+ actual: "no PAYMENT-REQUIRED or X-Payment header",
208
251
  }),
209
252
  };
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
253
  if (headerValue === null) {
226
254
  return emit([
227
255
  r1,
@@ -245,6 +273,8 @@ export async function runX402ReadChecks(options) {
245
273
  detail: `Failed to decode/parse: ${error.message}`,
246
274
  hint: "Base64-encode the JSON PaymentRequired object for the header; raw " +
247
275
  "JSON or a truncated value does not decode.",
276
+ expected: "a base64 value that decodes to JSON",
277
+ actual: decodedStart(headerValue),
248
278
  },
249
279
  ...skipAfter("X402-03", "the payment header did not decode to JSON, so no payload was " +
250
280
  "available to inspect."),
@@ -280,28 +310,71 @@ class PaymentNotAttemptedError extends Error {
280
310
  }
281
311
  }
282
312
  /**
283
- * The adapter for the run's network. Throws `ConfigurationError` for a
284
- * network the payment checks cannot pay on; preflight calls this before
313
+ * The route answered 409 where a 402 challenge was asked for: a single-use
314
+ * resource that a payment has used up (spec B8). Nothing is paid for it.
315
+ * Before any payment of the run it is one more reason no payment was attempted
316
+ * (X402-06 and the plan read it so); after X402-06's payment was accepted the
317
+ * negative checks that need a new challenge are skipped as "resource consumed".
318
+ */
319
+ class ResourceConsumedError extends PaymentNotAttemptedError {
320
+ constructor() {
321
+ super("the target answered 409 instead of a 402 challenge: a single-use resource that is already used up, so no " +
322
+ "payment was attempted (see X402-01).");
323
+ this.name = "ResourceConsumedError";
324
+ }
325
+ }
326
+ /** The status a single-use resource answers once it is used up (spec B8). */
327
+ const RESOURCE_CONSUMED_STATUS = 409;
328
+ /** The one negative check that needs no new challenge: it sends X402-06's payment again. */
329
+ const REPLAY_CHECK = "X402-08";
330
+ /** Why a negative check is skipped once a new challenge drew a 409 after X402-06's payment was accepted. */
331
+ const RESOURCE_CONSUMED_REASON = "resource consumed: the route answered 409 to a new request after X402-06's payment was accepted, a single-use resource that the " +
332
+ "payment used up, so this check has no new challenge to pay, and nothing was signed for it. X402-08, the replay, " +
333
+ "needs no new challenge and still runs.";
334
+ /**
335
+ * No payment adapter pays on this network, so the payment checks cannot be
336
+ * graded here. A `ConfigurationError`, so a caller that does not know the class
337
+ * still reads it as no verdict; preflight turns it into a skip of kind
338
+ * `unsupported` (spec A3). It is not the guard's refusal: `stellar:pubnet` has
339
+ * an adapter and is refused by `assertPaymentNetworkAllowed`, as an error.
340
+ */
341
+ export class UnsupportedPaymentNetworkError extends ConfigurationError {
342
+ network;
343
+ constructor(network) {
344
+ super(`Wasit's payment checks pay on ${paymentNetworks().join(", ")}; ` +
345
+ `${sanitizeText(JSON.stringify(String(network)))} is not one of them, so no payment ` +
346
+ `was attempted. X402-01..05 still apply to a challenge on any chain.`);
347
+ this.name = "UnsupportedPaymentNetworkError";
348
+ this.network = String(network);
349
+ }
350
+ }
351
+ /**
352
+ * The adapter for the run's network. Throws `UnsupportedPaymentNetworkError`
353
+ * for a network the payment checks cannot pay on; preflight calls this before
285
354
  * anything is sent.
286
355
  */
287
356
  function chainFor(network) {
288
357
  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
- }
358
+ if (chain === undefined)
359
+ throw new UnsupportedPaymentNetworkError(network);
294
360
  return chain;
295
361
  }
296
- async function buildX402Client(chain, network, payerSecretKey, rpcUrl) {
362
+ async function buildX402Client(chain, network, payerSecretKey, rpcUrl, pin, gate, mainnet) {
297
363
  const client = new x402Client();
298
- await chain.registerPayer(client, network, payerSecretKey, rpcUrl);
364
+ // L3 (spec B3): the SDK's own spend controls, set here rather than left to
365
+ // its default, as a second implementation of the $1 cap. An adapter that
366
+ // allows more assets replaces them and states the cap again (`evm.ts`).
367
+ client.setSpendControls({ maxAmountPerPayment: `$${PER_PAYMENT_CAP_USD}` });
368
+ await chain.registerPayer(client, network, payerSecretKey, rpcUrl, gate, mainnet);
299
369
  client
300
370
  // A challenge may offer several networks, including both Stellar ones.
301
371
  // The client's default pick is the first it supports, which would sign
302
372
  // 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));
373
+ // network this run was asked to use. With a pin, L3 also keeps only the
374
+ // pinned payee and asset, whatever else picked the option.
375
+ .registerPolicy((_version, requirements) => requirements.filter((requirement) => requirement.network === network &&
376
+ (pin === undefined ||
377
+ (sameAddress(network, requirement.payTo, pin.payTo) && sameAddress(network, requirement.asset, pin.asset)))));
305
378
  return { client, httpClient: new x402HTTPClient(client) };
306
379
  }
307
380
  /** The networks a challenge offers, for a report. */
@@ -344,23 +417,31 @@ async function withinSpendControls(network, selected, build) {
344
417
  }
345
418
  }
346
419
  /**
347
- * Reads the challenge and produces a signed payment payload for it.
420
+ * What a payment check reads before it can pay: the challenge, the URL to pay
421
+ * at, and the one option it would pay. Shared by `preparePayment` and the plan
422
+ * (L1), so both judge the same option by the same rules.
348
423
  *
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.
424
+ * Throws `PaymentNotAttemptedError` when there is nothing to pay: an
425
+ * unreadable or v1 challenge, no option on the run's network, or none in the
426
+ * `exact` scheme.
356
427
  */
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));
428
+ export async function readPaymentChallenge(options) {
429
+ // The payment goes where this challenge came from, never through a redirect
430
+ // (D-022c): `payUrl` is the target, or the URL one same-origin redirect led to.
431
+ const { response: challenge, url: payUrl } = await fetchPaymentChallenge(options.target, buildInit(options));
432
+ return { ...(await paymentTerms(challenge, options.network)), payUrl };
433
+ }
434
+ /** The terms of a challenge already fetched, by the rules of {@link readPaymentChallenge}. */
435
+ async function paymentTerms(challenge, network) {
436
+ const options = { network };
437
+ // B8: a single-use resource answers 409 once it is used up. Said as that, before its headers are read as a challenge.
438
+ if (challenge.status === RESOURCE_CONSUMED_STATUS) {
439
+ await challenge.body?.cancel().catch(() => undefined);
440
+ throw new ResourceConsumedError();
441
+ }
361
442
  let paymentRequired;
362
443
  try {
363
- paymentRequired = httpClient.getPaymentRequiredResponse((name) => challenge.headers.get(name));
444
+ paymentRequired = new x402HTTPClient(new x402Client()).getPaymentRequiredResponse((name) => challenge.headers.get(name));
364
445
  }
365
446
  catch (error) {
366
447
  // The read checks already report what is wrong with the challenge. Failing
@@ -377,6 +458,7 @@ async function preparePayment(options, alter, beforeSigning) {
377
458
  `(${error.message}), so no payment was attempted ` +
378
459
  `(see X402-02–04).`);
379
460
  }
461
+ await challenge.body?.cancel().catch(() => undefined);
380
462
  // A target that offers no option Wasit can pay has not refused anything:
381
463
  // there is no payment to judge, so neither check gets a verdict. X402-05
382
464
  // already reports which networks it advertises.
@@ -395,18 +477,293 @@ async function preparePayment(options, alter, beforeSigning) {
395
477
  // The payment-identifier extension lets a server answer a repeated payload
396
478
  // with its cached response (specs/extensions/payment_identifier.md).
397
479
  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 };
480
+ return { paymentRequired, selected, idempotent };
481
+ }
482
+ /** A stable text of a value, keys sorted, for a field-by-field comparison. */
483
+ function canonical(value) {
484
+ return JSON.stringify(value, (_key, item) => item !== null && typeof item === "object" && !Array.isArray(item)
485
+ ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
486
+ : item);
487
+ }
488
+ /**
489
+ * L2 against the plan: the option a check is about to pay must be the one the
490
+ * plan read, and the amount at most what the plan allowed for that check.
491
+ * Returns that amount, or undefined when the run has no plan.
492
+ */
493
+ function plannedAmount(plan, check, selected) {
494
+ if (plan === undefined)
495
+ return undefined;
496
+ const option = plan.option;
497
+ if (plan.status !== "planned" || option === undefined) {
498
+ 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.` +
499
+ (plan.reason === undefined ? "" : ` The plan says: ${plan.reason}`));
500
+ }
501
+ for (const field of ["scheme", "network", "payTo", "asset"]) {
502
+ const same = field === "payTo" || field === "asset"
503
+ ? sameAddress(option.network, String(selected[field]), option[field])
504
+ : selected[field] === option[field];
505
+ if (!same) {
506
+ throw new PaymentGuardRefusedError("plan", `${check}: the service changed its ${field} after the plan (the plan read ${option[field]}), ` +
507
+ `so the payment the plan allowed is not the one it now asks for.`);
508
+ }
509
+ }
510
+ const entry = plan.signatures.find((signature) => signature.check === check);
511
+ if (entry === undefined) {
512
+ throw new PaymentGuardRefusedError("plan", `The plan of this run has no signature for ${check}.`);
513
+ }
514
+ return entry.amount;
515
+ }
516
+ /**
517
+ * Refuses an RPC an x402 payment on `network` cannot be built through, then
518
+ * checks that it serves `network` (D-023). On Stellar the client accepts only
519
+ * an https RPC. Throws `RpcIdentityError` (a configuration error) before the
520
+ * target is sent anything; the RPC's address is never echoed (it may carry a
521
+ * key). The CLI calls it before it starts a service.
522
+ */
523
+ export async function assertX402PaymentRpc(network, rpcUrl) {
524
+ const chain = paymentChainFor(network);
525
+ if (chain?.httpsRpcOnly === true) {
526
+ let protocol = "";
527
+ try {
528
+ protocol = new URL(rpcUrl).protocol;
529
+ }
530
+ catch {
531
+ protocol = "";
532
+ }
533
+ if (protocol !== "https:") {
534
+ throw new RpcIdentityError(`The x402 ${chain.name} client builds the payment through the run's RPC and accepts only an https RPC, ` +
535
+ `and this run's RPC is not https. No payment was sent and nothing was signed.`);
536
+ }
537
+ }
538
+ await assertRpcServesNetwork(network, rpcUrl);
539
+ }
540
+ /** The run's anchor for expiration bounds, one per run budget (a run shares one budget across endpoints). */
541
+ const anchors = new WeakMap();
542
+ function anchorOf(budget) {
543
+ let anchor = anchors.get(budget);
544
+ if (anchor === undefined) {
545
+ anchor = new SigningAnchor();
546
+ anchors.set(budget, anchor);
547
+ }
548
+ return anchor;
549
+ }
550
+ /**
551
+ * The terms the gate is armed with: those L2 checked and charged, and the
552
+ * latest ledger the signature may expire at. The run's first signature reads
553
+ * the chain's latest ledger as the anchor; nothing is signed when it cannot.
554
+ */
555
+ async function signingTerms(binding, network, rpcUrl, anchor, payer, signing, readIfMissing) {
556
+ if (anchor.reading === undefined) {
557
+ // A mainnet run's anchor is read in its plan, beside public Horizon's latest ledger (B17.2), never here.
558
+ if (!readIfMissing) {
559
+ throw new PaymentGuardRefusedError("plan", "The mainnet run's latest ledger was not read in its plan, so no expiration can be bounded.");
560
+ }
561
+ let latest;
562
+ try {
563
+ latest = await binding.latestUnit(network, rpcUrl);
564
+ }
565
+ catch (error) {
566
+ throw new CheckSetupError(`The chain's latest ledger could not be read before signing (${error.message}). Nothing was signed.`);
567
+ }
568
+ if (!Number.isSafeInteger(latest) || latest <= 0) {
569
+ throw new CheckSetupError("The chain's latest ledger could not be read before signing. Nothing was signed.");
570
+ }
571
+ anchor.set(latest);
572
+ }
573
+ return {
574
+ network,
575
+ payer,
576
+ asset: signing.asset,
577
+ payTo: signing.payTo,
578
+ amount: signing.amount,
579
+ maxExpiration: anchor.maxExpiration(binding.unitSeconds, signing.maxTimeoutSeconds),
580
+ };
581
+ }
582
+ /**
583
+ * Reads the challenge and produces a signed payment payload for it.
584
+ *
585
+ * Shared by every payment check so each one starts from a challenge the
586
+ * target issued just now, rather than reusing a stale one. With `altered`,
587
+ * the payment is signed for those terms instead, and its `accepted` is set
588
+ * back to what the target advertised. `beforeSigning` runs once the option
589
+ * to pay is known and before the client builds anything: the Stellar client
590
+ * simulates the transfer while building, so a check placed later would never
591
+ * see an unfunded payer.
592
+ *
593
+ * L2 (spec B3) is here, between the fresh challenge and the SDK: the pin over
594
+ * every `exact` option, the plan, the $1 cap and the run's cap, the run charged
595
+ * before the signature. The SDK is then handed exactly the one option checked,
596
+ * and a payload whose `accepted` is not that option is discarded unsent. On a
597
+ * chain with a signed-terms gate (Stellar), the key signs only an
598
+ * authorization for those same terms, and a payload that carries anything
599
+ * else is discarded unsent.
600
+ *
601
+ * On mainnet (a live opt-in, spec B5) the fresh terms are also held to the
602
+ * mainnet rules (exact, USDC, a lifetime of at most 300 s), the ledger is the
603
+ * opt-in's, the anchor is the one its plan read, and a refusal here stops the
604
+ * whole run (B3): nothing more is signed in it.
605
+ */
606
+ async function preparePayment(options, check, alter, beforeSigning) {
607
+ // L0 again at the one function every x402 signature goes through, whoever
608
+ // reaches it: nothing is fetched or signed on a network that is not a test
609
+ // network, but stellar:pubnet with a live mainnet opt-in.
610
+ assertPaymentNetworkAllowed("x402", options.network, options.mainnet);
611
+ const mainnet = isLiveOptIn(options.mainnet, options.network) ? options.mainnet : undefined;
612
+ if (mainnet === undefined)
613
+ return signPayment(options, check, undefined, alter, beforeSigning);
614
+ try {
615
+ return await signPayment(options, check, mainnet, alter, beforeSigning);
616
+ }
617
+ catch (error) {
618
+ if (isGuardRefusal(error))
619
+ mainnet.stop(error.message);
620
+ throw error;
621
+ }
622
+ }
623
+ /** A refusal of Wasit's own guard, the ledger's included: on mainnet it stops the whole run (B3). */
624
+ function isGuardRefusal(error) {
625
+ return (error instanceof PaymentGuardRefusedError ||
626
+ error instanceof PaymentNetworkRefusedError ||
627
+ error instanceof MainnetPlanRefusedError ||
628
+ error instanceof MainnetRunRefusedError ||
629
+ error instanceof RunLedgerError);
630
+ }
631
+ async function signPayment(options, check, mainnet, alter, beforeSigning) {
632
+ const chain = chainFor(options.network);
633
+ const budget = options.budget ?? new RunBudget();
634
+ if (mainnet !== undefined && (budget !== mainnet.budget || options.ledger === undefined || chain.signedTerms === undefined)) {
635
+ throw new MainnetRunRefusedError("run", `${check} on mainnet pays only through the run's own budget and ledger, with a signer that signs only the checked terms.`, { during: true });
636
+ }
637
+ const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
638
+ const gate = new SigningGate();
639
+ const { client, httpClient } = await buildX402Client(chain, options.network, options.payerSecretKey, rpcUrl, options.pin, gate, mainnet);
640
+ const { paymentRequired, selected, idempotent, payUrl } = await readPaymentChallenge(options);
641
+ // On mainnet a payment goes to the one URL the plan recorded, never to one the service sends it to later.
642
+ if (mainnet !== undefined && (options.plan?.url === undefined || paidUrlOf(payUrl) !== options.plan.url)) {
643
+ throw new PaymentGuardRefusedError("plan", `${check} would pay ${shown(paidUrlOf(payUrl))}, not the URL the plan recorded for this endpoint: the service ` +
644
+ `sent the request elsewhere after the plan.`);
645
+ }
646
+ // L2, before anything is built: the service may change its challenge between
647
+ // requests, so the plan alone is not enough.
648
+ assertPinned(options.network, paymentRequired.accepts, options.pin);
649
+ const planned = plannedAmount(options.plan, check, selected);
650
+ const signing = alter === undefined ? selected : { ...selected, ...(await alter(selected)) };
651
+ for (const field of ["scheme", "network", "payTo", "asset"]) {
652
+ if (signing[field] !== selected[field]) {
653
+ throw new PaymentGuardRefusedError("accepted", `${check} would sign different ${field} terms than the target's.`);
654
+ }
655
+ }
656
+ // The mainnet rules on the terms about to be signed, not only on the plan's:
657
+ // a lifetime raised after the plan is refused here (B3, L2).
658
+ if (mainnet !== undefined)
659
+ assertMainnetOption(signing);
660
+ budget.charge({
661
+ check,
662
+ network: options.network,
663
+ asset: signing.asset,
664
+ amount: signing.amount,
665
+ ...(planned === undefined ? {} : { planned }),
666
+ });
667
+ // The run ledger (spec B5): the intent is on disk before the key can be asked
668
+ // to sign. A ledger that cannot take it throws here, and nothing is signed.
669
+ const entry = options.ledger?.intent({
670
+ check,
671
+ network: options.network,
672
+ asset: signing.asset,
673
+ payTo: signing.payTo,
674
+ amount: signing.amount,
675
+ });
676
+ let asked = false;
677
+ let signed;
678
+ try {
679
+ await beforeSigning?.(selected);
680
+ // The signed-terms gate (spec B17.2): the key signs only what was checked and
681
+ // charged above, once, within this payment's lifetime.
682
+ if (chain.signedTerms !== undefined) {
683
+ gate.arm(await signingTerms(chain.signedTerms, options.network, rpcUrl, mainnet === undefined ? anchorOf(budget) : anchorOfOptIn(mainnet), chain.payerAddress(options.payerSecretKey), signing, mainnet === undefined));
684
+ }
685
+ asked = true;
686
+ signed = await withinSpendControls(options.network, selected, () => client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }));
687
+ }
688
+ catch (error) {
689
+ recordUnsigned(entry, chain, gate, asked, error);
690
+ throw error;
691
+ }
692
+ // Recorded before the payload can be used: a signature the ledger cannot
693
+ // take is never sent.
694
+ entry?.signed(gate.signed === undefined ? undefined : expirationOfSigned(gate.signed));
695
+ try {
696
+ // What the SDK says it signed must be the option checked, field by field;
697
+ // otherwise the payload is discarded here, unsent. It stays charged.
698
+ if (canonical(signed.accepted) !== canonical(signing)) {
699
+ throw new PaymentGuardRefusedError("accepted", `The payment the x402 client built for ${check} names other terms in its accepted field than the ` +
700
+ `option Wasit checked.`, { signed: true });
701
+ }
702
+ // And what it carries must be the one authorization the gate let the key sign.
703
+ chain.signedTerms?.bind(signed.payload, gate);
704
+ }
705
+ catch (error) {
706
+ recordDiscarded(entry, error);
707
+ throw error;
708
+ }
709
+ const paymentPayload = alter === undefined ? signed : { ...signed, accepted: selected };
710
+ return { httpClient, paymentPayload, selected, idempotent, payUrl, entry };
711
+ }
712
+ function reasonOf(error) {
713
+ return error instanceof Error ? error.message : String(error);
714
+ }
715
+ /**
716
+ * What became of a payment that failed before its payload was built. With
717
+ * the gate armed, only a signature the gate recorded was made: the gate is the
718
+ * only way to the key. Without a gate (EVM and Solana, test networks only),
719
+ * a client that failed once it was asked may have signed. A ledger that cannot
720
+ * take the outcome leaves the intent, which reads as signed.
721
+ */
722
+ function recordUnsigned(entry, chain, gate, asked, error) {
723
+ if (entry === undefined)
724
+ return;
725
+ try {
726
+ if (gate.signed !== undefined)
727
+ entry.signed(expirationOfSigned(gate.signed));
728
+ else if (!asked || chain.signedTerms !== undefined)
729
+ entry.notSigned(reasonOf(error));
730
+ else
731
+ entry.unknown(reasonOf(error));
732
+ }
733
+ catch {
734
+ // The payment's own error is what the check reports; the intent stays.
735
+ }
736
+ }
737
+ /** A signed payload discarded unsent. A ledger that cannot take it leaves "signed", which reads as sent. */
738
+ function recordDiscarded(entry, error) {
739
+ try {
740
+ entry?.discarded(reasonOf(error));
741
+ }
742
+ catch {
743
+ // The payment's own error is what the check reports.
744
+ }
745
+ }
746
+ /**
747
+ * Sends a signed payment and records it in the run ledger: the answer's
748
+ * status, or that no answer came (the payment may still have reached the
749
+ * service). The ledger's own text, never the service's.
750
+ */
751
+ async function sendPayment(entry, url, init) {
752
+ let response;
753
+ try {
754
+ response = await fetchTarget(url, init);
755
+ }
756
+ catch (error) {
757
+ try {
758
+ entry?.sent({ error: "no answer: the payment may have reached the service" });
759
+ }
760
+ catch {
761
+ // The send's own error is what the check reports.
762
+ }
763
+ throw error;
764
+ }
765
+ entry?.sent({ status: response.status });
766
+ return response;
410
767
  }
411
768
  /**
412
769
  * Reads the settlement a paid response reports, before anything is looked up.
@@ -484,14 +841,16 @@ async function checkSignatureAccepted(options) {
484
841
  const id = "X402-06";
485
842
  const name = "Signature Resubmit Accepted";
486
843
  const fail = (detail, hint) => ({ id, name, pass: false, detail, hint });
487
- const { httpClient, paymentPayload, idempotent } = await preparePayment(options, undefined, (selected) => assertPayerCanPay(options, selected));
844
+ const { httpClient, paymentPayload, idempotent, payUrl, entry } = await preparePayment(options, "X402-06", undefined, (selected) => assertPayerCanPay(options, selected));
488
845
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
489
- const paid = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
846
+ const paid = await sendPayment(entry, payUrl, withPaymentHeaders(options, paymentHeaders));
490
847
  const honest = (result, accepted) => ({
491
848
  result,
492
849
  accepted,
493
850
  headers: paymentHeaders,
851
+ url: payUrl,
494
852
  idempotent,
853
+ payload: paymentPayload.payload,
495
854
  });
496
855
  if (paid.status < 200 || paid.status >= 300) {
497
856
  const reason = await refusalReason(paid);
@@ -533,12 +892,15 @@ async function checkSignatureAccepted(options) {
533
892
  recipient: accepted.payTo,
534
893
  payer: chain.payerAddress(options.payerSecretKey),
535
894
  });
895
+ entry?.settled(reference, verdict.pass);
536
896
  return honest(verdict.pass
537
897
  ? {
538
898
  id,
539
899
  name,
540
900
  pass: true,
541
901
  detail: `Valid payment accepted (HTTP ${paid.status}) and ${verdict.detail}.`,
902
+ // Read back from the chain and found to be this payment: a report may link it.
903
+ reference,
542
904
  }
543
905
  : fail(verdict.detail, "PAYMENT-RESPONSE must name the transaction that settled this payment, " +
544
906
  "and that transaction must move exactly `amount` of `asset` from the " +
@@ -558,13 +920,13 @@ async function checkSignatureAccepted(options) {
558
920
  * answer: anything that prevents one produces no verdict.
559
921
  */
560
922
  async function checkInvalidSignatureRejected(options) {
561
- const { httpClient, paymentPayload } = await preparePayment(options);
923
+ const { httpClient, paymentPayload, payUrl, entry } = await preparePayment(options, "X402-07");
562
924
  const corrupted = {
563
925
  ...paymentPayload,
564
926
  payload: chainFor(options.network).corruptPayload(paymentPayload.payload),
565
927
  };
566
928
  const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted);
567
- const response = await fetchTarget(options.target, withPaymentHeaders(options, paymentHeaders));
929
+ const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, paymentHeaders));
568
930
  return signatureRejectionVerdict(response.status, await refusalReason(response));
569
931
  }
570
932
  /**
@@ -655,7 +1017,7 @@ async function checkReplayRejected(options, honest) {
655
1017
  return skipped("X402-08", "Payment Replay Rejected", "the challenge advertises the payment-identifier extension, under which a " +
656
1018
  "server may answer a repeated payment with its cached response.");
657
1019
  }
658
- const response = await fetchTarget(options.target, withPaymentHeaders(options, honest.headers));
1020
+ const response = await fetchTarget(honest.url, withPaymentHeaders(options, honest.headers));
659
1021
  return replayVerdict(response.status, await refusalReason(response));
660
1022
  }
661
1023
  /** X402-08's verdict from the status the replayed payment drew. */
@@ -689,11 +1051,22 @@ export function replayVerdict(status, reason) {
689
1051
  * accepts, the lower amount may settle.
690
1052
  */
691
1053
  async function checkUnderpaymentRejected(options) {
1054
+ // The plan of `wasit run` leaves X402-09 out at a price below 2 base units;
1055
+ // the check is then skipped as it is without a plan, and nothing is fetched.
1056
+ const plan = options.plan;
1057
+ if (plan?.status === "planned" &&
1058
+ plan.option !== undefined &&
1059
+ plan.option.amount < 2n &&
1060
+ !plan.signatures.some((signature) => signature.check === "X402-09")) {
1061
+ const price = plan.option.amount;
1062
+ 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 ` +
1063
+ `there is no smaller payment to offer.`);
1064
+ }
692
1065
  let advertised = 0n;
693
1066
  let offered = 0n;
694
1067
  let prepared;
695
1068
  try {
696
- prepared = await preparePayment(options, (selected) => {
1069
+ prepared = await preparePayment(options, "X402-09", (selected) => {
697
1070
  try {
698
1071
  advertised = BigInt(selected.amount);
699
1072
  }
@@ -714,9 +1087,57 @@ async function checkUnderpaymentRejected(options) {
714
1087
  }
715
1088
  throw error;
716
1089
  }
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));
1090
+ const { httpClient, paymentPayload, selected, payUrl, entry } = prepared;
1091
+ const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
1092
+ const reason = await refusalReason(response);
1093
+ const verdict = underpaymentVerdict(response.status, offered, advertised, reason);
1094
+ if (verdict.pass)
1095
+ return verdict;
1096
+ // Accepted: the lower amount may have settled. What the chain shows is
1097
+ // added to the FAIL, and recorded in the run ledger, as X402-06 records its own.
1098
+ const settlement = await underpaymentSettlement(options, httpClient, response, entry, offered, selected);
1099
+ return settlement === "" ? verdict : { ...verdict, detail: `${verdict.detail}${settlement}` };
1100
+ }
1101
+ /**
1102
+ * Whether the underpaid payment a target accepted settled, as X402-06 reads
1103
+ * its own: the `PAYMENT-RESPONSE` names a transaction, which is looked up and
1104
+ * held to the payment signed (the offered amount, the asset, payTo, the
1105
+ * payer). Recorded in the run ledger, verified or not. Returns the sentence
1106
+ * the FAIL adds; empty when the response names no settlement. A chain that
1107
+ * gives no answer changes nothing in the FAIL: the target served for less.
1108
+ */
1109
+ async function underpaymentSettlement(options, httpClient, response, entry, offered, selected) {
1110
+ const chain = chainFor(options.network);
1111
+ const read = readSettlementReference(response.status, () => httpClient.getPaymentSettleResponse((header) => response.headers.get(header)), chain);
1112
+ if ("failure" in read)
1113
+ return "";
1114
+ const reference = read.reference;
1115
+ let verdict;
1116
+ try {
1117
+ verdict = await chain.verifySettlement(options.network, chain.resolveRpcUrl(options.network, options.rpcUrl), reference, {
1118
+ amount: offered,
1119
+ token: selected.asset,
1120
+ recipient: selected.payTo,
1121
+ payer: chain.payerAddress(options.payerSecretKey),
1122
+ });
1123
+ }
1124
+ catch (error) {
1125
+ recordSettlement(entry, reference, false);
1126
+ return ` Its PAYMENT-RESPONSE names ${reference}, which could not be read on chain (${sanitizeText(error.message).slice(0, 200)}).`;
1127
+ }
1128
+ recordSettlement(entry, reference, verdict.pass);
1129
+ return verdict.pass
1130
+ ? ` It settled on chain: ${offered} base units moved from the payer to payTo in ${reference}, read back from the transfer event.`
1131
+ : ` Its PAYMENT-RESPONSE names ${reference}, which the chain does not show as this payment: ${verdict.detail}`;
1132
+ }
1133
+ /** A settlement for the run ledger. A ledger that cannot take it leaves it unverified, which explains nothing. */
1134
+ function recordSettlement(entry, reference, verified) {
1135
+ try {
1136
+ entry?.settled(reference, verified);
1137
+ }
1138
+ catch {
1139
+ // The check's own verdict stands; the next intent finds the ledger broken and stops the run.
1140
+ }
720
1141
  }
721
1142
  /** X402-09's verdict from the status the underpaid payment drew. */
722
1143
  export function underpaymentVerdict(status, offered, advertised, reason) {
@@ -755,13 +1176,13 @@ async function checkExpiredRejected(options) {
755
1176
  const chain = chainFor(options.network);
756
1177
  const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
757
1178
  let holdMs = 0;
758
- const { httpClient, paymentPayload } = await preparePayment(options, async (selected) => {
1179
+ const { httpClient, paymentPayload, payUrl, entry } = await preparePayment(options, "X402-10", async (selected) => {
759
1180
  const expired = await chain.expiredSigning(selected, rpcUrl);
760
1181
  holdMs = expired.holdMs;
761
1182
  return expired.terms;
762
1183
  });
763
1184
  await new Promise((done) => setTimeout(done, holdMs));
764
- const response = await fetchTarget(options.target, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
1185
+ const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
765
1186
  return expiredVerdict(response.status, await refusalReason(response));
766
1187
  }
767
1188
  /** X402-10's verdict from the status the expired payment drew. */
@@ -784,12 +1205,232 @@ export function expiredVerdict(status, reason) {
784
1205
  : {}),
785
1206
  };
786
1207
  }
1208
+ /** A signed authorization, decoded and held to the run's payer; `what` names it in a message. */
1209
+ function authorizationOf(chain, payload, payer, what) {
1210
+ const watch = chain.authorizations;
1211
+ let decoded;
1212
+ try {
1213
+ decoded = watch.decode(payload);
1214
+ }
1215
+ catch (error) {
1216
+ if (error instanceof CheckSetupError)
1217
+ throw error;
1218
+ throw new CheckSetupError(`The authorization of ${what} could not be read from its payload (${error.message}).`);
1219
+ }
1220
+ if (decoded.payer !== payer) {
1221
+ throw new CheckSetupError(`The authorization of ${what} is signed by another address than this run's payer.`);
1222
+ }
1223
+ return decoded;
1224
+ }
1225
+ /** A lifetime X402-11 signs for: at least 30 s, and at most the 300 s it waits out. */
1226
+ function withinRejectLifetime(value) {
1227
+ const lifetime = Number(value);
1228
+ return lifetime >= REJECTED_REQUEST_MIN_LIFETIME_SECONDS && lifetime <= REJECTED_REQUEST_MAX_LIFETIME_SECONDS;
1229
+ }
1230
+ /** Thrown before signing when the challenge X402-11 is paid from advertises a lifetime it does not sign for. */
1231
+ class RejectLifetimeOutside extends Error {
1232
+ lifetime;
1233
+ constructor(lifetime) {
1234
+ super("the advertised lifetime is outside what X402-11 signs for");
1235
+ this.lifetime = lifetime;
1236
+ }
1237
+ }
1238
+ /**
1239
+ * X402-11 (negative, spec B7 as D-032 changed it): a valid payment sent with a
1240
+ * request the service must refuse must not settle. See `rejected-request.ts`
1241
+ * for the rules and the verdict.
1242
+ *
1243
+ * Nothing is signed when the check could not reach a verdict anyway: no
1244
+ * reject case, X402-06 not shown settled (its nonce is the control), a chain
1245
+ * whose authorizations Wasit cannot read, a service that refuses the request
1246
+ * before asking for payment, an advertised lifetime above 300 s, or a control
1247
+ * the chain does not return. The payment then goes through `preparePayment`
1248
+ * like every other: the pin, the plan, the $1 and run caps, the advertised
1249
+ * terms exactly.
1250
+ */
1251
+ async function checkRejectedRequestNotSettled(options, honest) {
1252
+ const id = REJECTED_REQUEST_ID;
1253
+ const name = REJECTED_REQUEST_NAME;
1254
+ const reject = options.reject;
1255
+ if (reject === undefined) {
1256
+ return skipped(id, name, "no request the service must refuse is configured (endpoints[].reject in wasit.config.json, read by " +
1257
+ "wasit run), so there is nothing to send. Nothing was signed.", "not-applicable");
1258
+ }
1259
+ const chain = chainFor(options.network);
1260
+ const watch = chain.authorizations;
1261
+ if (watch === undefined) {
1262
+ return skipped(id, name, `Wasit cannot read on ${chain.name} whether a payment's authorization was used, which this check needs, ` +
1263
+ `so nothing was signed.`, "not-applicable");
1264
+ }
1265
+ if (honest.result.pass !== true || honest.result.error !== undefined || honest.result.skipped === true) {
1266
+ return skipped(id, name, "X402-06's payment was not shown settled on chain, so its authorization cannot be the control that shows a " +
1267
+ "chain read is complete. Nothing was signed.", "dependency");
1268
+ }
1269
+ // The reject request is the endpoint's request with the reject case over it.
1270
+ const { method: _method, headers: _headers, body: _body, ...rest } = options;
1271
+ const shape = rejectRequestShape(options, reject);
1272
+ const rejectOptions = { ...rest, ...shape };
1273
+ // Without payment first: a service that refuses it before asking for payment
1274
+ // gives this check nothing to watch.
1275
+ const { response: unpaid } = await fetchPaymentChallenge(options.target, buildInit(shape));
1276
+ if (unpaid.status !== 402) {
1277
+ await unpaid.body?.cancel().catch(() => undefined);
1278
+ const status = unpaid.status;
1279
+ return skipped(id, name, status >= 400 && status < 500
1280
+ ? `the service refuses this request before any payment is asked (HTTP ${status}), so there is no payment ` +
1281
+ `to watch. Nothing was signed.`
1282
+ : `the service answered this request with HTTP ${status} without asking for payment, so there is no ` +
1283
+ `payment to watch. Nothing was signed.`, "not-applicable");
1284
+ }
1285
+ const { selected: advertised } = await paymentTerms(unpaid, options.network);
1286
+ const outside = (value, again) => skipped(id, name, `the service's payments stay valid for ${sanitizeText(String(value))} seconds (maxTimeoutSeconds)` +
1287
+ (again ? ", as it said when asked for payment again" : "") +
1288
+ (Number(value) > REJECTED_REQUEST_MAX_LIFETIME_SECONDS
1289
+ ? `, longer than the ${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds Wasit waits for one to expire on a ` +
1290
+ `test network, so this check could not show that the payment never settled.`
1291
+ : `, shorter than the ${REJECTED_REQUEST_MIN_LIFETIME_SECONDS} seconds this check needs: such a payment can ` +
1292
+ `expire before a service that settles it has it on chain, so its unused authorization would show nothing.`) +
1293
+ ` Nothing was signed.`);
1294
+ if (!withinRejectLifetime(advertised.maxTimeoutSeconds))
1295
+ return outside(advertised.maxTimeoutSeconds, false);
1296
+ const network = options.network;
1297
+ const rpcUrl = chain.resolveRpcUrl(network, options.rpcUrl);
1298
+ const payer = chain.payerAddress(options.payerSecretKey);
1299
+ const control = authorizationOf(chain, honest.payload, payer, "X402-06's payment");
1300
+ // Before signing: the chain must return X402-06's used authorization, and the
1301
+ // payer's balance must be readable. Otherwise no verdict could be reached, and
1302
+ // nothing is signed.
1303
+ let balanceBefore = 0n;
1304
+ let prepared;
1305
+ try {
1306
+ prepared = await preparePayment(rejectOptions, id, undefined, async (selected) => {
1307
+ // The challenge is read again for the signature, and the service may
1308
+ // answer it with another lifetime: the one signed is held to 300 s too.
1309
+ if (!withinRejectLifetime(selected.maxTimeoutSeconds))
1310
+ throw new RejectLifetimeOutside(selected.maxTimeoutSeconds);
1311
+ let read;
1312
+ try {
1313
+ read = await watch.read(network, rpcUrl, [control]);
1314
+ }
1315
+ catch (error) {
1316
+ throw new CheckSetupError(`The chain could not be read before signing (${error.message}). Nothing was signed.`);
1317
+ }
1318
+ if (read.used[0] === undefined) {
1319
+ throw new CheckSetupError("The chain's answer leaves out X402-06's authorization, which was used, so a later read could not show " +
1320
+ "that this payment's was not. Nothing was signed.");
1321
+ }
1322
+ let balance;
1323
+ try {
1324
+ balance = await chain.payerBalance(network, rpcUrl, payer, advertised.asset);
1325
+ }
1326
+ catch {
1327
+ balance = undefined;
1328
+ }
1329
+ if (balance === undefined) {
1330
+ throw new CheckSetupError("The payer's balance could not be read, and this check needs it as a second reading. Nothing was signed.");
1331
+ }
1332
+ balanceBefore = balance;
1333
+ });
1334
+ }
1335
+ catch (error) {
1336
+ if (error instanceof RejectLifetimeOutside)
1337
+ return outside(error.lifetime, true);
1338
+ throw error;
1339
+ }
1340
+ const { httpClient, paymentPayload, selected, payUrl, entry } = prepared;
1341
+ // A signed payment this check does not send: recorded as discarded, then the check stops.
1342
+ const discard = (message) => {
1343
+ recordDiscarded(entry, new Error(message));
1344
+ throw new CheckSetupError(message);
1345
+ };
1346
+ const amount = BigInt(selected.amount);
1347
+ const ours = authorizationOf(chain, paymentPayload.payload, payer, "this payment");
1348
+ if (ours.nonce === control.nonce) {
1349
+ discard("This payment's authorization carries X402-06's nonce, so it could not be told apart. It was not sent.");
1350
+ }
1351
+ // Right before sending: ours unused, the control found. This read's ledger
1352
+ // starts the range the transfers are read over.
1353
+ const before = await watch.read(network, rpcUrl, [ours, control]);
1354
+ if (before.used[1] === undefined) {
1355
+ discard("The chain's answer leaves out X402-06's authorization, so this payment was not sent.");
1356
+ }
1357
+ if (before.used[0] !== undefined) {
1358
+ discard("The chain records this payment's authorization as used before it was sent, so it was not sent.");
1359
+ }
1360
+ // What the client signed, not what it was asked: an authorization that stays
1361
+ // valid longer than the 300 s this check waits is not sent (2 units of slack
1362
+ // for the ledgers that close while it is built).
1363
+ const longest = Math.ceil(REJECTED_REQUEST_MAX_LIFETIME_SECONDS / watch.unitSeconds) + 2;
1364
+ if (ours.expiresAt - before.latest > longest) {
1365
+ discard(`This payment's authorization stays valid until ${watch.unit} ${ours.expiresAt}, ` +
1366
+ `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}), longer than the ` +
1367
+ `${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds this check waits. It was signed and discarded; it was not sent.`);
1368
+ }
1369
+ // And long enough that a service which settles it could still get it on chain.
1370
+ if (ours.expiresAt - before.latest < REJECTED_REQUEST_MIN_UNITS_LEFT) {
1371
+ discard(`This payment's authorization expires at ${watch.unit} ${ours.expiresAt}, ` +
1372
+ `${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}): too soon for an unused ` +
1373
+ `authorization to show anything. It was signed and discarded; it was not sent.`);
1374
+ }
1375
+ const sentAt = Date.now();
1376
+ const response = await sendPayment(entry, payUrl, withPaymentHeaders(shape, httpClient.encodePaymentSignatureHeader(paymentPayload)));
1377
+ const status = response.status;
1378
+ const reason = await refusalReason(response);
1379
+ options.onProgress?.(`X402-11: the payment was sent with the request the service must refuse (HTTP ${status}); reading the chain ` +
1380
+ `once a ${watch.unit} until its authorization expires at ${watch.unit} ${ours.expiresAt}, for at most ` +
1381
+ `${Math.round(rejectedRequestHardStopMs() / 1000)} s.`);
1382
+ let outcome = await watchAuthorization({ watch, network, rpcUrl, ours, control, sentAt });
1383
+ let balance;
1384
+ let transfers;
1385
+ if (outcome.kind === "used" || outcome.kind === "unused") {
1386
+ try {
1387
+ const after = await chain.payerBalance(network, rpcUrl, payer, selected.asset);
1388
+ if (after === undefined)
1389
+ throw new Error("the payer's balance could not be read after the watch");
1390
+ balance = { before: balanceBefore, after };
1391
+ const recorded = await watch.transfers(network, rpcUrl, {
1392
+ asset: selected.asset,
1393
+ from: payer,
1394
+ to: selected.payTo,
1395
+ fromLedger: before.latest + 1,
1396
+ });
1397
+ // Only what the watch covered: from the ledger after the pre-send read to the last ledger
1398
+ // it read. A later transfer of the same amount (another run with this payer) is not this one.
1399
+ const lastRead = outcome.latest;
1400
+ transfers = recorded.transfers
1401
+ .filter((transfer) => transfer.amount === amount && transfer.ledger <= lastRead)
1402
+ .map((transfer) => ({ reference: transfer.reference, ledger: transfer.ledger }));
1403
+ }
1404
+ catch (error) {
1405
+ outcome = { kind: "unread", why: `the second readings failed: ${sanitizeText(error.message).slice(0, 200)}` };
1406
+ balance = undefined;
1407
+ transfers = undefined;
1408
+ }
1409
+ }
1410
+ const evidence = {
1411
+ status,
1412
+ ...(reason === undefined ? {} : { reason }),
1413
+ amount,
1414
+ expiresAt: ours.expiresAt,
1415
+ unit: watch.unit,
1416
+ watch: outcome,
1417
+ ...(balance === undefined ? {} : { balance }),
1418
+ ...(transfers === undefined ? {} : { transfers }),
1419
+ };
1420
+ // What the chain shows of this payment goes into the run ledger: a payment
1421
+ // the service took for a request it must refuse is a settlement the chain verified.
1422
+ const settlement = rejectedRequestSettlement(evidence);
1423
+ if (settlement !== undefined)
1424
+ recordSettlement(entry, settlement, true);
1425
+ return rejectedRequestVerdict(evidence);
1426
+ }
787
1427
  /** The negative checks, in catalogue order, each with how it runs. */
788
1428
  const NEGATIVE_CHECKS = [
789
1429
  ["X402-07", "Invalid Signature Rejected", (options) => checkInvalidSignatureRejected(options)],
790
1430
  ["X402-08", "Payment Replay Rejected", checkReplayRejected],
791
1431
  ["X402-09", "Underpayment Rejected", (options) => checkUnderpaymentRejected(options)],
792
1432
  ["X402-10", "Expired Authorization Rejected", (options) => checkExpiredRejected(options)],
1433
+ [REJECTED_REQUEST_ID, REJECTED_REQUEST_NAME, checkRejectedRequestNotSettled],
793
1434
  ];
794
1435
  /**
795
1436
  * Every check `runX402PaymentChecks` reports, in order. Front ends that list
@@ -806,8 +1447,26 @@ export const X402_PAYMENT_CHECK_IDS = [
806
1447
  * target must refuse; a target that accepts the underpaid one may settle it.
807
1448
  * See docs/CHECKS.md.
808
1449
  */
809
- export async function runX402PaymentChecks(options) {
1450
+ export async function runX402PaymentChecks(input) {
1451
+ const allChecks = [
1452
+ ["X402-06", "Signature Resubmit Accepted"],
1453
+ ...NEGATIVE_CHECKS.map(([id, name]) => [id, name]),
1454
+ ];
1455
+ // A mainnet run stopped by an earlier refusal (B3): every check of this
1456
+ // endpoint is skipped with the reason, and nothing is fetched or signed.
1457
+ const stoppedBefore = stopReason(input.mainnet);
1458
+ if (stoppedBefore !== undefined) {
1459
+ const results = allChecks.map(([id, name]) => skipped(id, name, stoppedBefore));
1460
+ for (const result of results)
1461
+ input.onResult?.(result);
1462
+ return results;
1463
+ }
1464
+ let options = input;
810
1465
  try {
1466
+ // One budget for every signature these checks make: the run's, when the
1467
+ // caller shares one across endpoints, or this call's own $5. On mainnet,
1468
+ // the opt-in's budget, pin, plan, ledger and RPC, and nothing else.
1469
+ options = input.mainnet === undefined ? { ...input, budget: input.budget ?? new RunBudget() } : mainnetOptions(input);
811
1470
  assertHttpUrl(options.target);
812
1471
  buildInit(options);
813
1472
  // The payment checks pay only where Wasit has an adapter, and X402-06 can
@@ -815,12 +1474,16 @@ export async function runX402PaymentChecks(options) {
815
1474
  // money moves, so a run that could not finish is stopped here rather than
816
1475
  // after paying.
817
1476
  const chain = chainFor(options.network);
818
- chain.resolveRpcUrl(options.network, options.rpcUrl);
1477
+ // L0: an adapter for the network is not permission to pay on it. Only a
1478
+ // test network passes, and stellar:pubnet with a live mainnet opt-in.
1479
+ assertPaymentNetworkAllowed("x402", options.network, options.mainnet);
1480
+ const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
819
1481
  // A key for another chain, or a malformed one, would otherwise surface
820
1482
  // mid-payment as a harness error. Checked here, it is what it is: the
821
1483
  // run's configuration. The message never echoes the key.
1484
+ let payer;
822
1485
  try {
823
- chain.payerAddress(options.payerSecretKey);
1486
+ payer = chain.payerAddress(options.payerSecretKey);
824
1487
  }
825
1488
  catch (error) {
826
1489
  if (error instanceof ConfigurationError)
@@ -828,8 +1491,26 @@ export async function runX402PaymentChecks(options) {
828
1491
  throw new ConfigurationError(`The payer key is not a valid ${chain.name} key (read from ${chain.payerKeyEnv} ` +
829
1492
  `or --payer-key).`);
830
1493
  }
1494
+ if (options.mainnet !== undefined && payer !== options.mainnet.payer) {
1495
+ throw stopMainnet(options.mainnet, "These checks were handed the key of another account than the mainnet run's payer.");
1496
+ }
1497
+ // The RPC signs and settles nothing itself, but the payment is built and
1498
+ // the settlement read through it: it must be one the client accepts and
1499
+ // serve the run's network (D-023).
1500
+ await assertX402PaymentRpc(options.network, rpcUrl);
831
1501
  }
832
1502
  catch (error) {
1503
+ // A network no adapter pays on is not a failure of the run: Wasit does not
1504
+ // grade it (spec A3). Every payment check is skipped as unsupported, and
1505
+ // nothing was fetched or signed. The guard's refusals are not this: they
1506
+ // are other errors, and stay a PREFLIGHT error below.
1507
+ if (error instanceof UnsupportedPaymentNetworkError) {
1508
+ const unsupported = [["X402-06", "Signature Resubmit Accepted"], ...NEGATIVE_CHECKS.map(([id, name]) => [id, name])]
1509
+ .map(([id, name]) => skipped(id, name, error.message, "unsupported"));
1510
+ for (const result of unsupported)
1511
+ options.onResult?.(result);
1512
+ return unsupported;
1513
+ }
833
1514
  const preflight = errored("PREFLIGHT", "Run Preflight", error);
834
1515
  options.onResult?.(preflight);
835
1516
  return [preflight];
@@ -837,6 +1518,7 @@ export async function runX402PaymentChecks(options) {
837
1518
  const results = [];
838
1519
  const emit = (result) => {
839
1520
  results.push(result);
1521
+ recordVerdict(options.ledger, result);
840
1522
  options.onResult?.(result);
841
1523
  };
842
1524
  const skipNegatives = (reason) => {
@@ -855,6 +1537,9 @@ export async function runX402PaymentChecks(options) {
855
1537
  }
856
1538
  const failed = errored("X402-06", "Signature Resubmit Accepted", error);
857
1539
  emit(failed);
1540
+ const stopped = stopReason(options.mainnet);
1541
+ if (stopped !== undefined)
1542
+ return skipNegatives(stopped);
858
1543
  // If the payment flow could not be exercised at all, no altered variant of
859
1544
  // it can be either, and none may be reported as a passing rejection.
860
1545
  return skipNegatives(`the payment flow could not be exercised (${failed.error?.kind ?? "harness"}), ` +
@@ -868,13 +1553,104 @@ export async function runX402PaymentChecks(options) {
868
1553
  return skipNegatives("the target refused X402-06's valid payment, so refusing an altered one " +
869
1554
  "says nothing about what it checks.");
870
1555
  }
1556
+ // B8: once a new challenge drew a 409, the resource is used up: every later
1557
+ // check that needs one is skipped as "resource consumed" without asking again,
1558
+ // and the replay, which needs none, still runs.
1559
+ let consumed = false;
871
1560
  for (const [id, name, run] of NEGATIVE_CHECKS) {
1561
+ // B3: once a mainnet run is stopped, nothing more is signed in it.
1562
+ const stopped = stopReason(options.mainnet);
1563
+ if (stopped !== undefined) {
1564
+ emit(skipped(id, name, stopped));
1565
+ continue;
1566
+ }
1567
+ if (consumed && id !== REPLAY_CHECK) {
1568
+ emit(skipped(id, name, RESOURCE_CONSUMED_REASON, "resource-consumed"));
1569
+ continue;
1570
+ }
872
1571
  try {
873
1572
  emit(await run(options, honest));
874
1573
  }
875
1574
  catch (error) {
1575
+ if (error instanceof ResourceConsumedError) {
1576
+ consumed = true;
1577
+ emit(skipped(id, name, RESOURCE_CONSUMED_REASON, "resource-consumed"));
1578
+ continue;
1579
+ }
876
1580
  emit(errored(id, name, error));
877
1581
  }
878
1582
  }
879
1583
  return results;
880
1584
  }
1585
+ /** What a result says about the target, as the run ledger records it. */
1586
+ function verdictOf(result) {
1587
+ if (result.skipped === true)
1588
+ return "skipped";
1589
+ if (result.error !== undefined)
1590
+ return "no-verdict";
1591
+ return result.pass ? "pass" : "fail";
1592
+ }
1593
+ /**
1594
+ * Records a check's verdict on its entries in the run ledger. A ledger that
1595
+ * cannot take it keeps none, and a payment of that check then explains
1596
+ * nothing when the balances are compared: the safe side.
1597
+ */
1598
+ function recordVerdict(ledger, result) {
1599
+ try {
1600
+ ledger?.verdict?.(result.id, verdictOf(result));
1601
+ }
1602
+ catch {
1603
+ // The result stands; see above.
1604
+ }
1605
+ }
1606
+ /** Why a check of a stopped mainnet run is skipped; undefined while the run goes on, or with no opt-in. */
1607
+ function stopReason(mainnet) {
1608
+ const reason = mainnet?.stopped;
1609
+ if (reason === undefined)
1610
+ return undefined;
1611
+ return `the mainnet run stopped, and nothing more is signed in it: ${sanitizeText(String(reason)).slice(0, 400)}`;
1612
+ }
1613
+ /** Stops `mainnet` with `message` and returns the error to throw. */
1614
+ function stopMainnet(mainnet, message) {
1615
+ const error = new MainnetRunRefusedError("run", message, { during: true });
1616
+ mainnet.stop(error.message);
1617
+ return error;
1618
+ }
1619
+ /**
1620
+ * The options a mainnet run's checks pay by (spec B5): the opt-in's own
1621
+ * budget, pin, plan entry, ledger and RPC. A value handed in beside it that is
1622
+ * not the opt-in's is refused and the run stopped: on mainnet nothing is paid
1623
+ * by terms core did not plan.
1624
+ */
1625
+ function mainnetOptions(input) {
1626
+ const optIn = input.mainnet;
1627
+ if (input.network !== optIn.network) {
1628
+ throw stopMainnet(optIn, `A mainnet opt-in was handed to checks on another network than ${optIn.network}.`);
1629
+ }
1630
+ // L0 first: a stopped, closed or forged opt-in is refused here, and says why.
1631
+ assertPaymentNetworkAllowed("x402", input.network, optIn);
1632
+ const plan = optIn.plan;
1633
+ if (plan === undefined)
1634
+ throw stopMainnet(optIn, "The mainnet run has no plan that passed: its plan comes before any payment.");
1635
+ const entry = input.plan;
1636
+ if (entry === undefined || !plan.endpoints.includes(entry)) {
1637
+ throw stopMainnet(optIn, "These checks were not handed an entry of the mainnet run's own plan.");
1638
+ }
1639
+ if (input.budget !== undefined && input.budget !== optIn.budget) {
1640
+ throw stopMainnet(optIn, "These checks were handed another budget than the mainnet run's.");
1641
+ }
1642
+ if (input.pin !== undefined && (input.pin.payTo !== optIn.pin.payTo || input.pin.asset !== optIn.pin.asset)) {
1643
+ throw stopMainnet(optIn, "These checks were handed another pin than the mainnet run's.");
1644
+ }
1645
+ if (input.rpcUrl !== undefined && input.rpcUrl !== optIn.rpcUrl) {
1646
+ throw stopMainnet(optIn, "These checks were handed another RPC than the mainnet run's.");
1647
+ }
1648
+ if (input.ledger !== undefined) {
1649
+ throw stopMainnet(optIn, "These checks were handed a ledger of their own: a mainnet run writes every signature to its own.");
1650
+ }
1651
+ const ledger = optIn.ledger;
1652
+ if (ledger === undefined) {
1653
+ throw stopMainnet(optIn, "The mainnet run's ledger is not open: on mainnet every signature is written to it first.");
1654
+ }
1655
+ return { ...input, budget: optIn.budget, pin: optIn.pin, rpcUrl: optIn.rpcUrl, ledger: ledger.forEndpoint(entry.name) };
1656
+ }