mppx 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/Challenge.d.ts +59 -3
  3. package/dist/Challenge.js +162 -21
  4. package/dist/Errors.d.ts +35 -1
  5. package/dist/Errors.js +41 -3
  6. package/dist/Method.js +2 -2
  7. package/dist/Receipt.d.ts +2 -0
  8. package/dist/Receipt.js +5 -0
  9. package/dist/Store.d.ts +39 -10
  10. package/dist/Store.js +136 -29
  11. package/dist/cli/cli.d.ts +5 -0
  12. package/dist/cli/cli.js +135 -135
  13. package/dist/cli/plugins/index.js +12 -12
  14. package/dist/cli/sessions/commands.js +9 -0
  15. package/dist/cli/sessions/store.js +3 -2
  16. package/dist/cli/validate/challenge.js +15 -1
  17. package/dist/client/Mppx.d.ts +1 -1
  18. package/dist/client/Mppx.js +2 -1
  19. package/dist/client/internal/Fetch.d.ts +2 -1
  20. package/dist/client/internal/Fetch.js +43 -5
  21. package/dist/client/internal/PendingSettlement.d.ts +11 -0
  22. package/dist/client/internal/PendingSettlement.js +22 -0
  23. package/dist/client/internal/protocols/Mcp.js +8 -0
  24. package/dist/evm/client/Charge.js +7 -1
  25. package/dist/evm/server/Charge.d.ts +5 -0
  26. package/dist/evm/server/Charge.js +44 -0
  27. package/dist/evm/server/Methods.d.ts +8 -0
  28. package/dist/evm/server/Methods.js +8 -0
  29. package/dist/extensions/identity/attestation/Jwks.js +3 -3
  30. package/dist/extensions/identity/link/server/index.js +4 -4
  31. package/dist/extensions/identity/persona/server/index.js +3 -3
  32. package/dist/internal/CredentialExpiry.d.ts +30 -0
  33. package/dist/internal/CredentialExpiry.js +51 -0
  34. package/dist/internal/version.d.ts +2 -2
  35. package/dist/internal/version.js +1 -1
  36. package/dist/mcp/client/McpClient.js +29 -10
  37. package/dist/middlewares/express.d.ts +7 -2
  38. package/dist/middlewares/express.js +20 -23
  39. package/dist/middlewares/internal/express.d.ts +9 -1
  40. package/dist/middlewares/internal/express.js +348 -2
  41. package/dist/proxy/Proxy.js +15 -3
  42. package/dist/proxy/internal/Replay.d.ts +10 -0
  43. package/dist/proxy/internal/Replay.js +5 -0
  44. package/dist/server/Mppx.d.ts +1 -1
  45. package/dist/server/Mppx.js +19 -14
  46. package/dist/server/NodeListener.js +7 -0
  47. package/dist/server/Request.d.ts +6 -0
  48. package/dist/server/Request.js +43 -22
  49. package/dist/server/internal/challengeMeta.d.ts +10 -0
  50. package/dist/server/internal/challengeMeta.js +31 -1
  51. package/dist/server/internal/host.d.ts +4 -0
  52. package/dist/server/internal/host.js +41 -0
  53. package/dist/tempo/client/Charge.d.ts +5 -4
  54. package/dist/tempo/client/Charge.js +210 -38
  55. package/dist/tempo/client/Subscription.js +3 -0
  56. package/dist/tempo/internal/zone.d.ts +8 -0
  57. package/dist/tempo/internal/zone.js +15 -0
  58. package/dist/tempo/server/Charge.d.ts +19 -0
  59. package/dist/tempo/server/Charge.js +60 -15
  60. package/dist/tempo/server/internal/html.gen.js +1 -1
  61. package/dist/tempo/server/internal/transport.js +10 -54
  62. package/dist/tempo/session/client/ChannelOps.js +1 -1
  63. package/dist/tempo/session/client/SessionManager.d.ts +4 -1
  64. package/dist/tempo/session/client/SessionManager.js +8 -2
  65. package/dist/tempo/session/server/CredentialVerification.js +2 -3
  66. package/dist/viem/Client.d.ts +2 -0
  67. package/dist/viem/Client.js +4 -1
  68. package/dist/x402/Assets.d.ts +6 -0
  69. package/dist/x402/Assets.js +10 -0
  70. package/dist/x402/Types.d.ts +68 -8
  71. package/dist/x402/Types.js +17 -2
  72. package/dist/x402/client/Exact.js +4 -1
  73. package/dist/x402/middlewares/express.js +10 -1
  74. package/dist/x402/server/EvmCharge.d.ts +20 -3
  75. package/dist/x402/server/EvmCharge.js +13 -1
  76. package/dist/x402/server/Facilitator.d.ts +42 -3
  77. package/dist/x402/server/Facilitator.js +126 -16
  78. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # mppx
2
2
 
3
+ ## 0.21.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 7b47ff2: Fixed payment enforcement, stream handling, and excessive callback overhead in Express, and hardened subscription signing and CLI retries against chain mismatches and cleartext payment requests. Proxy replay now requires a stable, explicitly configured `replay.authority`, shared only by replicas with identical payment policies and upstream permissions.
8
+
9
+ ### Patch Changes
10
+
11
+ - 1cb1c24: Validated the authority actually used to construct adapter request URLs. Returned HTTP 400 for malformed request targets in the x402 Express adapter.
12
+ - a7e84b7: Added optional exact host allowlists to Express and Node adapters, rejecting unapproved requests before payment or identity verification.
13
+ - d2d3fba: Fixed payment retries creating credentials after cancellation during approval.
14
+ - 58513ac: Changed challenges to accept only `Payment-Authorization` (any case) as an explicit `header`, keeping the received spelling so credentials echo it unchanged; clients skip a challenge that names any other credential header. Servers now throw when configured with another header (`Authorization` still means the default).
15
+ - bf0bbcb: The CLI paid a new Challenge offered in a 402 after a Credential, such as the real charge after a zero-amount proof, instead of failing with `PAYMENT_REJECTED`, and resent the same Credential when the same Challenge was offered again, as the client's fetch does.
16
+ - c796e45: Preserved automatic-payment opt-outs through identity clients and session managers, and disabled payment during issuer key retrieval.
17
+ - 7300c80: Fixed stale payment cleanup removing a newer replay claim.
18
+ - b457436: Bound session credential sources to the funding payer while preserving delegated voucher signatures.
19
+ - c796e45: Prevented Persona issuer lookups from paying through identity wrappers and unpaid session requests from changing accounting or opening payment-driven streams.
20
+ - 6826a97: Added `headers` for x402 facilitators that need an API key: a flat record sent on every request, or an object keyed by `verify`, `settle` and `supported` (the shape `createAuthHeaders` returns in `@x402/core`), or a function returning either. `x402.facilitator` accepts `{ url, headers }`, and `x402.headers`, `Facilitator.http(url, { headers })` and `evm.facilitatorPayTo(url, { headers })` authenticate a URL facilitator. A non-2xx facilitator response now throws `Errors.FacilitatorResponseError` (status and truncated body) and reaches the client as a 500 instead of a schema error. Clients with `maxAmount` and no `currencies` allowlist now read decimals and EIP-3009 metadata for assets mppx ships (such as Base USDC) from its registry.
21
+ - c5c01a7: Added `x402.extra` to `evm.charge` for facilitators that read their own keys in a payment requirement's `extra`, an optional `supported()` on x402 facilitator clients (`GET /supported`, implemented by the HTTP client), and `evm.facilitatorPayTo()` to read the `payTo` a facilitator publishes there as the charge's `recipient`.
22
+ - fa0388c: Added `extensions` to `Receipt` and to the result of `evm.charge`'s `settle` so a server reads the `extensions` an x402 facilitator returns from `/settle`, and forwarded them unchanged in the x402 `PAYMENT-RESPONSE` header. Fixed the HTTP facilitator client rejecting `/verify` and `/settle` responses whose `extensions` values aren't `{ info, schema }` declarations.
23
+ - 6629814: Fixed `tempo.charge` clients so that `maxAmount` and `maxAtomicAmount` cover a Zone payment's withdrawal fee: the amount plus the fee must fit, checked before withdrawing.
24
+ - 132e1b5: Fixed Zone payments so that a retry under a new Challenge no longer starts a second withdrawal: `tempo.charge` resumes the outstanding withdrawal for the same terms while it can still pay, and the fetch and MCP clients retry the original Challenge while it settles. Added the `zoneCredentialGraceMs` server option, which accepts a `zone` Credential for up to 5 minutes after its Challenge expires when its withdrawal settled before the expiry; only Challenges issued with the option on get this grace.
25
+ - 88e8810: Fixed `tempo.charge` servers accepting a Zone withdrawal's settlement as a `hash` Credential as well as a `zone` Credential. A transfer sent by a Zone portal now counts only through its `zone` Credential, so one settlement pays once.
26
+
3
27
  ## 0.20.1
4
28
 
5
29
  ### Patch Changes
@@ -25,6 +25,26 @@ export declare const Schema: z.ZodMiniObject<{
25
25
  realm: z.ZodMiniString<string>;
26
26
  request: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
27
27
  }, z.core.$strip>;
28
+ /**
29
+ * Schema for a payment challenge whose `header` may be any string. Use it to read challenges stored
30
+ * before `header` was limited to `Payment-Authorization`, or to check that a received challenge is
31
+ * well formed before skipping it for its credential header.
32
+ *
33
+ * @internal
34
+ */
35
+ export declare const LenientSchema: z.ZodMiniObject<{
36
+ description: z.ZodMiniOptional<z.ZodMiniString<string>>;
37
+ digest: z.ZodMiniOptional<z.ZodMiniString<string>>;
38
+ expires: z.ZodMiniOptional<z.ZodMiniString<string>>;
39
+ id: z.ZodMiniString<string>;
40
+ intent: z.ZodMiniString<string>;
41
+ method: z.ZodMiniString<string>;
42
+ meta: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniString<string>>>;
43
+ opaque: z.ZodMiniOptional<z.ZodMiniString<string>>;
44
+ realm: z.ZodMiniString<string>;
45
+ request: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
46
+ header: z.ZodMiniOptional<z.ZodMiniString<string>>;
47
+ }, z.core.$strip>;
28
48
  /**
29
49
  * A parsed payment challenge from a `WWW-Authenticate` header.
30
50
  *
@@ -107,7 +127,10 @@ export declare namespace from {
107
127
  digest?: string | undefined;
108
128
  /** Optional expiration timestamp (ISO 8601). */
109
129
  expires?: z.DatetimeInput | undefined;
110
- /** Optional HTTP field name to carry the payment credential. When omitted, uses Authorization. */
130
+ /**
131
+ * Optional HTTP field name to carry the payment credential: `Payment-Authorization`, or
132
+ * `Authorization` (the default, not advertised). Any other value throws.
133
+ */
111
134
  header?: string | undefined;
112
135
  /** Intent type (e.g., "charge", "session"). */
113
136
  intent: string;
@@ -171,7 +194,10 @@ export declare namespace fromMethod {
171
194
  digest?: string | undefined;
172
195
  /** Optional expiration timestamp (ISO 8601). */
173
196
  expires?: z.DatetimeInput | undefined;
174
- /** Optional HTTP field name to carry the payment credential. When omitted, uses Authorization. */
197
+ /**
198
+ * Optional HTTP field name to carry the payment credential: `Payment-Authorization`, or
199
+ * `Authorization` (the default, not advertised). Any other value throws.
200
+ */
175
201
  header?: string | undefined;
176
202
  /** Optional server-defined correlation data (serialized as `opaque` on the challenge). Flat string-to-string map; clients MUST NOT modify. */
177
203
  meta?: Record<string, string> | undefined;
@@ -292,11 +318,28 @@ export declare function fromHeadersList<const methods extends readonly Method.Me
292
318
  * Deserializes a `WWW-Authenticate` header value that may contain multiple
293
319
  * Payment challenges (comma-separated per RFC 9110 §11.6.1).
294
320
  *
321
+ * Challenges that select a credential header other than `Payment-Authorization`
322
+ * are skipped, so the result may be empty.
323
+ *
295
324
  * @param value - The raw WWW-Authenticate header value.
296
325
  * @param options - Optional settings to narrow the challenge type.
297
326
  * @returns An array of deserialized challenges.
298
327
  */
299
328
  export declare function deserializeList<const methods extends readonly Method.Method[] | undefined = undefined>(value: string, options?: from.Options<methods>): from.ReturnType<from.Parameters, methods>[];
329
+ /**
330
+ * Counts the Payment challenges in a `WWW-Authenticate` value that list parsing skips because they
331
+ * select a credential header other than `Payment-Authorization`.
332
+ *
333
+ * @internal
334
+ */
335
+ export declare function countUnsupportedCredentialHeaders(value: string | null | undefined): number;
336
+ /**
337
+ * Appends a note on skipped challenges to an error that reports no payable challenge. Returns the
338
+ * message unchanged when none were skipped.
339
+ *
340
+ * @internal
341
+ */
342
+ export declare function withSkippedChallenges(message: string, count: number): string;
300
343
  /**
301
344
  * Verifies that a challenge ID matches the expected HMAC for the given parameters.
302
345
  *
@@ -320,6 +363,19 @@ export declare namespace verify {
320
363
  }
321
364
  /** Extracts parsed server-defined correlation data from a challenge when available. */
322
365
  export declare function meta(challenge: Challenge): Record<string, string> | undefined;
323
- /** Returns the HTTP field name a client must use for a payment credential. */
366
+ /**
367
+ * Returns the HTTP field name a client must use for a payment credential: `Authorization` when the
368
+ * challenge omits `header`, and the canonical `Payment-Authorization` for any spelling of it.
369
+ */
324
370
  export declare function credentialHeader(challenge: Challenge): string;
371
+ /**
372
+ * Returns whether a challenge object selects a credential header a client must not send a Payment
373
+ * credential for: any `header` other than `Payment-Authorization` (matched case-insensitively).
374
+ *
375
+ * Use it on challenge objects received outside `WWW-Authenticate`, such as MCP payment-required
376
+ * data, to skip such a challenge while still paying another one.
377
+ *
378
+ * @internal
379
+ */
380
+ export declare function hasUnsupportedCredentialHeader(challenge: unknown): boolean;
325
381
  //# sourceMappingURL=Challenge.d.ts.map
package/dist/Challenge.js CHANGED
@@ -4,6 +4,19 @@ import { constantTimeEqual } from './internal/constantTimeEqual.js';
4
4
  import * as PaymentRequest from './PaymentRequest.js';
5
5
  import * as z from './zod.js';
6
6
  const maxRequestParameterLength = 16 * 1024;
7
+ const unsupportedCredentialHeaderMessage = 'Unsupported credential header: challenges may only select Payment-Authorization.';
8
+ /**
9
+ * Thrown when a challenge selects a credential header other than `Payment-Authorization`.
10
+ * List parsing skips such challenges so the client can still pay another one.
11
+ *
12
+ * @internal
13
+ */
14
+ class UnsupportedCredentialHeaderError extends Error {
15
+ name = 'UnsupportedCredentialHeaderError';
16
+ constructor() {
17
+ super(unsupportedCredentialHeaderMessage);
18
+ }
19
+ }
7
20
  /**
8
21
  * Schema for a payment challenge.
9
22
  *
@@ -21,8 +34,12 @@ export const Schema = z.object({
21
34
  digest: z.optional(z.string().check(z.regex(/^sha-256=/, 'Invalid digest format'))),
22
35
  /** Optional expiration timestamp (ISO 8601). */
23
36
  expires: z.optional(z.datetime()),
24
- /** Optional HTTP field name to carry the payment credential. When omitted, uses Authorization. */
25
- header: z.optional(z.string().check(z.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/, 'Invalid HTTP header name'))),
37
+ /**
38
+ * Optional HTTP field name to carry the payment credential. When omitted, uses Authorization.
39
+ * When present, it MUST be `Payment-Authorization`, matched case-insensitively. The spelling is
40
+ * kept as received, because clients echo it unchanged and the challenge ID binds it.
41
+ */
42
+ header: z.optional(z.string().check(z.refine(isPaymentAuthorizationHeader, unsupportedCredentialHeaderMessage))),
26
43
  /** Unique challenge identifier (HMAC-bound). */
27
44
  id: z.string().check(z.minLength(1)),
28
45
  /** Intent type (e.g., "charge", "session"). */
@@ -38,6 +55,17 @@ export const Schema = z.object({
38
55
  /** Method-specific request data. */
39
56
  request: z.record(z.string(), z.unknown()),
40
57
  });
58
+ /**
59
+ * Schema for a payment challenge whose `header` may be any string. Use it to read challenges stored
60
+ * before `header` was limited to `Payment-Authorization`, or to check that a received challenge is
61
+ * well formed before skipping it for its credential header.
62
+ *
63
+ * @internal
64
+ */
65
+ export const LenientSchema = z.extend(Schema, {
66
+ /** Optional HTTP field name to carry the payment credential, unchecked. */
67
+ header: z.optional(z.string()),
68
+ });
41
69
  /**
42
70
  * Creates a challenge from the given parameters.
43
71
  *
@@ -80,12 +108,12 @@ export function from(parameters, options) {
80
108
  const { description, digest, meta, method: methodName, header: suppliedHeader, intent, realm, request, secretKey, } = parameters;
81
109
  // `Authorization` is the implicit protocol default and is intentionally not
82
110
  // advertised on the wire. This preserves the legacy challenge binding and
83
- // lets servers opt into an alternate credential field explicitly.
84
- const header = isDefaultCredentialHeader(suppliedHeader) ? undefined : suppliedHeader;
111
+ // lets servers opt into `Payment-Authorization` explicitly.
112
+ const header = normalizeCredentialHeader(suppliedHeader);
85
113
  const expires = parameters.expires ? z.toDatetimeString(parameters.expires) : undefined;
86
114
  const opaque = parameters.opaque ?? (meta !== undefined ? PaymentRequest.serialize(meta) : undefined);
87
115
  const id = secretKey
88
- ? computeId({ ...parameters, expires, ...(meta !== undefined && { meta }), opaque }, { secretKey })
116
+ ? computeId({ ...parameters, expires, header, ...(meta !== undefined && { meta }), opaque }, { secretKey })
89
117
  : parameters.id;
90
118
  return Schema.parse({
91
119
  id,
@@ -178,8 +206,8 @@ export function serialize(challenge) {
178
206
  parts.push(authParam('digest', challenge.digest));
179
207
  if (challenge.expires !== undefined)
180
208
  parts.push(authParam('expires', challenge.expires));
181
- const credentialHeader = challenge.header;
182
- if (credentialHeader !== undefined && !isDefaultCredentialHeader(credentialHeader))
209
+ const credentialHeader = advertisedCredentialHeader(challenge.header);
210
+ if (credentialHeader !== undefined)
183
211
  parts.push(authParam('header', credentialHeader));
184
212
  if (challenge.opaque !== undefined)
185
213
  parts.push(authParam('opaque', challenge.opaque));
@@ -223,18 +251,27 @@ export function deserialize(value, options) {
223
251
  if (!params)
224
252
  throw new Error('Missing Payment scheme.');
225
253
  const result = parseAuthParams(params);
226
- const { request, opaque, ...rest } = result;
254
+ const { request, opaque, header, ...rest } = result;
227
255
  if (!request)
228
256
  throw new Error('Missing request parameter.');
229
257
  if (request.length > maxRequestParameterLength)
230
258
  throw new Error('Request parameter too large.');
231
259
  if (rest.method && !/^[a-z][a-z0-9:_-]*$/.test(rest.method))
232
260
  throw new Error(`Invalid method: "${rest.method}". Must be lowercase per spec.`);
233
- return from({
261
+ // Validate the raw value before `from` treats `Authorization` as the omitted default: a
262
+ // received challenge may only select `Payment-Authorization`.
263
+ if (header !== undefined && !isPaymentAuthorizationHeader(header))
264
+ throw new UnsupportedCredentialHeaderError();
265
+ const challenge = from({
234
266
  ...rest,
235
267
  request: PaymentRequest.deserialize(request),
236
268
  ...(opaque && { opaque }),
237
269
  }, options);
270
+ // Keep the spelling the server sent: the client echoes it unchanged, and the server's challenge
271
+ // ID may bind that exact spelling.
272
+ if (header === undefined)
273
+ return challenge;
274
+ return { ...challenge, header };
238
275
  }
239
276
  /** @internal Extracts the `Payment` scheme from a WWW-Authenticate value that may contain multiple schemes. */
240
277
  function extractPaymentAuthParams(header) {
@@ -467,20 +504,70 @@ export function fromHeadersList(headers, options) {
467
504
  * Deserializes a `WWW-Authenticate` header value that may contain multiple
468
505
  * Payment challenges (comma-separated per RFC 9110 §11.6.1).
469
506
  *
507
+ * Challenges that select a credential header other than `Payment-Authorization`
508
+ * are skipped, so the result may be empty.
509
+ *
470
510
  * @param value - The raw WWW-Authenticate header value.
471
511
  * @param options - Optional settings to narrow the challenge type.
472
512
  * @returns An array of deserialized challenges.
473
513
  */
474
514
  export function deserializeList(value, options) {
475
- const starts = findSchemeStarts(value, Constants.Schemes.payment);
476
- if (starts.length === 0)
515
+ const chunks = paymentChunks(value);
516
+ if (chunks.length === 0)
477
517
  throw new Error('No Payment schemes found.');
518
+ return chunks.flatMap((chunk) => {
519
+ try {
520
+ return [deserialize(chunk, options)];
521
+ }
522
+ catch (error) {
523
+ // A challenge with an unsupported credential header gets no credential,
524
+ // but must not stop the client from paying another challenge.
525
+ if (error instanceof UnsupportedCredentialHeaderError)
526
+ return [];
527
+ throw error;
528
+ }
529
+ });
530
+ }
531
+ /**
532
+ * Counts the Payment challenges in a `WWW-Authenticate` value that list parsing skips because they
533
+ * select a credential header other than `Payment-Authorization`.
534
+ *
535
+ * @internal
536
+ */
537
+ export function countUnsupportedCredentialHeaders(value) {
538
+ if (!value)
539
+ return 0;
540
+ return paymentChunks(value).filter((chunk) => {
541
+ try {
542
+ deserialize(chunk);
543
+ return false;
544
+ }
545
+ catch (error) {
546
+ return error instanceof UnsupportedCredentialHeaderError;
547
+ }
548
+ }).length;
549
+ }
550
+ /**
551
+ * Appends a note on skipped challenges to an error that reports no payable challenge. Returns the
552
+ * message unchanged when none were skipped.
553
+ *
554
+ * @internal
555
+ */
556
+ export function withSkippedChallenges(message, count) {
557
+ if (count <= 0)
558
+ return message;
559
+ return count === 1
560
+ ? `${message}. Skipped 1 challenge that selects a credential header other than Payment-Authorization`
561
+ : `${message}. Skipped ${count} challenges that select a credential header other than Payment-Authorization`;
562
+ }
563
+ /** Splits a `WWW-Authenticate` value into its `Payment` challenges. */
564
+ function paymentChunks(value) {
565
+ const starts = findSchemeStarts(value, Constants.Schemes.payment);
478
566
  // Slice each scheme from its `Payment ` prefix up to the next scheme boundary,
479
567
  // trimming any trailing comma/whitespace between schemes.
480
568
  return starts.map((start, i) => {
481
569
  const end = i + 1 < starts.length ? starts[i + 1] : value.length;
482
- const chunk = value.slice(start, end).replace(/,\s*$/, '');
483
- return deserialize(chunk, options);
570
+ return value.slice(start, end).replace(/,\s*$/, '');
484
571
  });
485
572
  }
486
573
  /**
@@ -498,7 +585,16 @@ export function deserializeList(value, options) {
498
585
  * ```
499
586
  */
500
587
  export function verify(challenge, options) {
501
- const expectedId = computeId(challenge, options);
588
+ let expectedId;
589
+ try {
590
+ expectedId = computeId(challenge, options);
591
+ }
592
+ catch (error) {
593
+ // A challenge that selects an unsupported credential header was never issued by this server.
594
+ if (error instanceof UnsupportedCredentialHeaderError)
595
+ return false;
596
+ throw error;
597
+ }
502
598
  return constantTimeEqual(challenge.id, expectedId);
503
599
  }
504
600
  /** Extracts parsed server-defined correlation data from a challenge when available. */
@@ -531,19 +627,64 @@ function idBindingInput(challenge) {
531
627
  challenge.digest ?? '',
532
628
  ];
533
629
  // Keep opaque in the final optional slot required by the Payment auth scheme.
534
- const credentialHeader = challenge.header;
535
- if (credentialHeader !== undefined && !isDefaultCredentialHeader(credentialHeader))
630
+ const credentialHeader = advertisedCredentialHeader(challenge.header);
631
+ if (credentialHeader !== undefined)
536
632
  values.push(credentialHeader);
537
633
  values.push(challenge.opaque ?? (challenge.meta ? PaymentRequest.serialize(challenge.meta) : ''));
538
634
  return values.join('|');
539
635
  }
540
- /** Returns the HTTP field name a client must use for a payment credential. */
636
+ /**
637
+ * Returns the HTTP field name a client must use for a payment credential: `Authorization` when the
638
+ * challenge omits `header`, and the canonical `Payment-Authorization` for any spelling of it.
639
+ */
541
640
  export function credentialHeader(challenge) {
542
- return challenge.header ?? Constants.Headers.authorization;
641
+ const { header } = challenge;
642
+ if (header === undefined)
643
+ return Constants.Headers.authorization;
644
+ return isPaymentAuthorizationHeader(header) ? Constants.Headers.paymentAuthorization : header;
645
+ }
646
+ /**
647
+ * Returns whether a challenge object selects a credential header a client must not send a Payment
648
+ * credential for: any `header` other than `Payment-Authorization` (matched case-insensitively).
649
+ *
650
+ * Use it on challenge objects received outside `WWW-Authenticate`, such as MCP payment-required
651
+ * data, to skip such a challenge while still paying another one.
652
+ *
653
+ * @internal
654
+ */
655
+ export function hasUnsupportedCredentialHeader(challenge) {
656
+ if (typeof challenge !== 'object' || challenge === null || !('header' in challenge))
657
+ return false;
658
+ const { header } = challenge;
659
+ return (header !== undefined && !(typeof header === 'string' && isPaymentAuthorizationHeader(header)));
543
660
  }
544
- /** Returns whether a credential header is the implicit HTTP authentication default. */
545
- function isDefaultCredentialHeader(header) {
546
- return header?.toLowerCase() === Constants.Headers.authorization.toLowerCase();
661
+ /** Returns whether a header name is `Payment-Authorization`, ignoring ASCII case. */
662
+ function isPaymentAuthorizationHeader(header) {
663
+ // Without the `u` flag, `i` folds ASCII letters only.
664
+ return /^payment-authorization$/i.test(header);
665
+ }
666
+ /**
667
+ * Normalizes a locally configured credential header: `Authorization` (any case) is the
668
+ * implicit default and is not advertised, `Payment-Authorization` is canonicalized, and any
669
+ * other value throws because servers MUST NOT emit it.
670
+ */
671
+ function normalizeCredentialHeader(header) {
672
+ const advertised = advertisedCredentialHeader(header);
673
+ return advertised === undefined ? undefined : Constants.Headers.paymentAuthorization;
674
+ }
675
+ /**
676
+ * Returns a challenge's `header` as it is advertised and bound into the challenge ID:
677
+ * `Authorization` (any case) is the implicit default and is omitted, a `Payment-Authorization`
678
+ * spelling is kept exactly as given, and any other value throws because servers MUST NOT emit it.
679
+ */
680
+ function advertisedCredentialHeader(header) {
681
+ if (header === undefined)
682
+ return undefined;
683
+ if (/^authorization$/i.test(header))
684
+ return undefined;
685
+ if (isPaymentAuthorizationHeader(header))
686
+ return header;
687
+ throw new UnsupportedCredentialHeaderError();
547
688
  }
548
689
  /** @internal Computes HMAC-SHA256 challenge ID from parameters. */
549
690
  function computeId(challenge, options) {
package/dist/Errors.d.ts CHANGED
@@ -235,6 +235,37 @@ export declare namespace BroadcastOutcomeUnknownError {
235
235
  validBefore?: number | undefined;
236
236
  };
237
237
  }
238
+ /**
239
+ * An x402 facilitator answered with a non-2xx status (such as a 401 for a missing or wrong API
240
+ * key, or a 5xx outage) or with a body that is not a facilitator result.
241
+ *
242
+ * It says nothing about the payment itself, so it is not a `PaymentError`: HTTP handlers answer
243
+ * with a generic 500 `InternalPaymentError`, whose `cause` is this error, rather than a 402 that
244
+ * would tell the client its payment was invalid. A `/verify` or `/settle` error response whose
245
+ * body is a failed result (`isValid: false`, `success: false`) is read as that result instead.
246
+ */
247
+ export declare class FacilitatorResponseError extends Error {
248
+ readonly name = "FacilitatorResponseError";
249
+ /** First 200 characters of the response body, for server-side logs. Never sent to clients. */
250
+ readonly body: string;
251
+ /** Facilitator path that failed. */
252
+ readonly path: 'settle' | 'supported' | 'verify';
253
+ /** HTTP status of the facilitator response. */
254
+ readonly status: number;
255
+ constructor(options: FacilitatorResponseError.Options);
256
+ }
257
+ export declare namespace FacilitatorResponseError {
258
+ type Options = {
259
+ /** Response body. Truncated to 200 characters. */
260
+ body: string;
261
+ /** Parse error, when the body is not a facilitator result. */
262
+ cause?: unknown;
263
+ /** Facilitator path that failed. */
264
+ path: 'settle' | 'supported' | 'verify';
265
+ /** HTTP status of the facilitator response. */
266
+ status: number;
267
+ };
268
+ }
238
269
  /**
239
270
  * A pre-broadcast simulation of a fee-sponsored payment failed, so the payment was not broadcast.
240
271
  *
@@ -305,6 +336,9 @@ export declare namespace SpendingLimitExceededError {
305
336
  *
306
337
  * Retry the same challenge with the same `tempo.charge` client to resume waiting without
307
338
  * withdrawing again, or find the settlement with `senderTag` (or one of `senderTags`) on the Zone's portal.
339
+ * A new challenge for the same payment never starts a second withdrawal: from the origin that
340
+ * issued `challengeId`, it resumes this withdrawal and returns a credential for that challenge;
341
+ * otherwise it throws this error again.
308
342
  */
309
343
  export declare class ZoneSettlementPendingError extends Error {
310
344
  readonly name = "ZoneSettlementPendingError";
@@ -315,7 +349,7 @@ export declare class ZoneSettlementPendingError extends Error {
315
349
  * `undefined` when a Zone RPC hid it and more than one candidate remains: see `senderTags`.
316
350
  */
317
351
  readonly senderTag: `0x${string}` | undefined;
318
- /** Sender tags the withdrawal may carry: its tag alone when known, else every candidate. */
352
+ /** Sender tags the withdrawal may carry: its tag alone when known, else every candidate. Empty when not yet read. */
319
353
  readonly senderTags: readonly `0x${string}`[];
320
354
  /** ID of the Zone the withdrawal left. */
321
355
  readonly zoneId: number;
package/dist/Errors.js CHANGED
@@ -195,6 +195,41 @@ export class BroadcastOutcomeUnknownError extends Error {
195
195
  Object.defineProperty(this, 'cause', { configurable: true, value: cause, writable: true });
196
196
  }
197
197
  }
198
+ /**
199
+ * An x402 facilitator answered with a non-2xx status (such as a 401 for a missing or wrong API
200
+ * key, or a 5xx outage) or with a body that is not a facilitator result.
201
+ *
202
+ * It says nothing about the payment itself, so it is not a `PaymentError`: HTTP handlers answer
203
+ * with a generic 500 `InternalPaymentError`, whose `cause` is this error, rather than a 402 that
204
+ * would tell the client its payment was invalid. A `/verify` or `/settle` error response whose
205
+ * body is a failed result (`isValid: false`, `success: false`) is read as that result instead.
206
+ */
207
+ export class FacilitatorResponseError extends Error {
208
+ name = 'FacilitatorResponseError';
209
+ /** First 200 characters of the response body, for server-side logs. Never sent to clients. */
210
+ body;
211
+ /** Facilitator path that failed. */
212
+ path;
213
+ /** HTTP status of the facilitator response. */
214
+ status;
215
+ constructor(options) {
216
+ const { cause, path, status } = options;
217
+ const body = excerpt(options.body);
218
+ super(`x402 facilitator /${path} failed (${status}): ${body}`);
219
+ this.body = body;
220
+ this.path = path;
221
+ this.status = status;
222
+ // Defined manually (non-enumerable, like native `cause`) so consumers on pre-ES2022 libs still typecheck.
223
+ if (cause !== undefined)
224
+ Object.defineProperty(this, 'cause', { configurable: true, value: cause, writable: true });
225
+ }
226
+ }
227
+ function excerpt(text, limit = 200) {
228
+ const compact = text.trim().replace(/\s+/g, ' ');
229
+ if (!compact)
230
+ return '<empty response>';
231
+ return compact.length <= limit ? compact : `${compact.slice(0, limit - 3)}...`;
232
+ }
198
233
  /**
199
234
  * A pre-broadcast simulation of a fee-sponsored payment failed, so the payment was not broadcast.
200
235
  *
@@ -257,6 +292,9 @@ export class SpendingLimitExceededError extends Error {
257
292
  *
258
293
  * Retry the same challenge with the same `tempo.charge` client to resume waiting without
259
294
  * withdrawing again, or find the settlement with `senderTag` (or one of `senderTags`) on the Zone's portal.
295
+ * A new challenge for the same payment never starts a second withdrawal: from the origin that
296
+ * issued `challengeId`, it resumes this withdrawal and returns a credential for that challenge;
297
+ * otherwise it throws this error again.
260
298
  */
261
299
  export class ZoneSettlementPendingError extends Error {
262
300
  name = 'ZoneSettlementPendingError';
@@ -267,7 +305,7 @@ export class ZoneSettlementPendingError extends Error {
267
305
  * `undefined` when a Zone RPC hid it and more than one candidate remains: see `senderTags`.
268
306
  */
269
307
  senderTag;
270
- /** Sender tags the withdrawal may carry: its tag alone when known, else every candidate. */
308
+ /** Sender tags the withdrawal may carry: its tag alone when known, else every candidate. Empty when not yet read. */
271
309
  senderTags;
272
310
  /** ID of the Zone the withdrawal left. */
273
311
  zoneId;
@@ -275,8 +313,8 @@ export class ZoneSettlementPendingError extends Error {
275
313
  const { cause, challengeId, zoneId } = options;
276
314
  const senderTags = options.senderTags ?? (options.senderTag ? [options.senderTag] : []);
277
315
  const senderTag = senderTags.length === 1 ? senderTags[0] : undefined;
278
- const withdrawal = senderTag ?? `with sender tag ${senderTags.join(' or ')}`;
279
- super(`Zone ${zoneId} withdrawal ${withdrawal} for challenge "${challengeId}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`);
316
+ const withdrawal = senderTag ?? (senderTags.length ? `with sender tag ${senderTags.join(' or ')}` : undefined);
317
+ super(`Zone ${zoneId} withdrawal ${withdrawal ? `${withdrawal} ` : ''}for challenge "${challengeId}" has not settled on Tempo yet. Retry the challenge to resume waiting instead of paying again.`);
280
318
  this.challengeId = challengeId;
281
319
  this.senderTag = senderTag;
282
320
  this.senderTags = senderTags;
package/dist/Method.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as Credential from './Credential.js';
2
2
  import * as Errors from './Errors.js';
3
- import * as Expires from './Expires.js';
3
+ import * as CredentialExpiry from './internal/CredentialExpiry.js';
4
4
  /**
5
5
  * Creates a payment method.
6
6
  *
@@ -90,7 +90,7 @@ function prepareCredential(methods, input) {
90
90
  id: credential.challenge.id,
91
91
  reason: `no registered method for ${credential.challenge.method}/${credential.challenge.intent}`,
92
92
  });
93
- Expires.assert(credential.challenge.expires, credential.challenge.id);
93
+ CredentialExpiry.assertFor(method, credential);
94
94
  let payload;
95
95
  try {
96
96
  payload = method.schema.credential.payload.parse(credential.payload);
package/dist/Receipt.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as z from './zod.js';
2
2
  /** Base-field schema used only to derive the {@link Receipt} type without an index signature. */
3
3
  declare const BaseSchema: z.ZodMiniObject<{
4
+ extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
4
5
  fundingCurrency: z.ZodMiniOptional<z.ZodMiniString<string>>;
5
6
  method: z.ZodMiniString<string>;
6
7
  reference: z.ZodMiniString<string>;
@@ -24,6 +25,7 @@ declare const BaseSchema: z.ZodMiniObject<{
24
25
  * ```
25
26
  */
26
27
  export declare const Schema: z.ZodMiniObject<{
28
+ extensions: z.ZodMiniOptional<z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>>;
27
29
  fundingCurrency: z.ZodMiniOptional<z.ZodMiniString<string>>;
28
30
  method: z.ZodMiniString<string>;
29
31
  reference: z.ZodMiniString<string>;
package/dist/Receipt.js CHANGED
@@ -2,6 +2,11 @@ import { Base64 } from 'ox';
2
2
  import * as Constants from './Constants.js';
3
3
  import * as z from './zod.js';
4
4
  const shape = {
5
+ /**
6
+ * Settlement data the settler reported, keyed by extension name, such as an x402
7
+ * facilitator's `SettleResponse.extensions`. Passed through unchanged.
8
+ */
9
+ extensions: z.optional(z.record(z.string(), z.unknown())),
5
10
  /** Currency actually debited to fund the payment, when known. */
6
11
  fundingCurrency: z.optional(z.string()),
7
12
  /** Payment method used (e.g., "tempo", "stripe"). */