mppx 0.20.0 → 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 (97) hide show
  1. package/CHANGELOG.md +31 -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 +148 -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/Issuer.d.ts +91 -0
  30. package/dist/extensions/identity/attestation/Issuer.js +159 -0
  31. package/dist/extensions/identity/attestation/Jwks.js +3 -3
  32. package/dist/extensions/identity/attestation/Token.js +7 -0
  33. package/dist/extensions/identity/attestation/Types.d.ts +31 -3
  34. package/dist/extensions/identity/attestation/index.d.ts +3 -1
  35. package/dist/extensions/identity/attestation/index.js +3 -1
  36. package/dist/extensions/identity/link/server/index.js +4 -4
  37. package/dist/extensions/identity/persona/server/index.js +3 -3
  38. package/dist/extensions/identity/tempo/Constants.d.ts +4 -0
  39. package/dist/extensions/identity/tempo/Constants.js +4 -0
  40. package/dist/extensions/identity/tempo/client/index.d.ts +63 -0
  41. package/dist/extensions/identity/tempo/client/index.js +151 -0
  42. package/dist/extensions/identity/tempo/index.d.ts +1 -0
  43. package/dist/extensions/identity/tempo/index.js +1 -0
  44. package/dist/extensions/identity/tempo/issuer/index.d.ts +83 -0
  45. package/dist/extensions/identity/tempo/issuer/index.js +183 -0
  46. package/dist/internal/CredentialExpiry.d.ts +30 -0
  47. package/dist/internal/CredentialExpiry.js +51 -0
  48. package/dist/internal/version.d.ts +2 -2
  49. package/dist/internal/version.js +1 -1
  50. package/dist/mcp/client/McpClient.js +29 -10
  51. package/dist/middlewares/express.d.ts +7 -2
  52. package/dist/middlewares/express.js +20 -23
  53. package/dist/middlewares/internal/express.d.ts +9 -1
  54. package/dist/middlewares/internal/express.js +348 -2
  55. package/dist/proxy/Proxy.js +15 -3
  56. package/dist/proxy/internal/Headers.js +1 -0
  57. package/dist/proxy/internal/Replay.d.ts +10 -0
  58. package/dist/proxy/internal/Replay.js +5 -0
  59. package/dist/server/Mppx.d.ts +1 -1
  60. package/dist/server/Mppx.js +47 -15
  61. package/dist/server/NodeListener.js +7 -0
  62. package/dist/server/Request.d.ts +6 -0
  63. package/dist/server/Request.js +43 -22
  64. package/dist/server/internal/challengeMeta.d.ts +10 -0
  65. package/dist/server/internal/challengeMeta.js +31 -1
  66. package/dist/server/internal/host.d.ts +4 -0
  67. package/dist/server/internal/host.js +41 -0
  68. package/dist/tempo/client/Charge.d.ts +5 -4
  69. package/dist/tempo/client/Charge.js +210 -38
  70. package/dist/tempo/client/Subscription.js +3 -0
  71. package/dist/tempo/internal/zone.d.ts +8 -0
  72. package/dist/tempo/internal/zone.js +15 -0
  73. package/dist/tempo/server/Charge.d.ts +19 -0
  74. package/dist/tempo/server/Charge.js +60 -15
  75. package/dist/tempo/server/internal/html.gen.js +1 -1
  76. package/dist/tempo/server/internal/transport.js +10 -54
  77. package/dist/tempo/session/client/ChannelOps.js +1 -1
  78. package/dist/tempo/session/client/SessionManager.d.ts +4 -1
  79. package/dist/tempo/session/client/SessionManager.js +8 -2
  80. package/dist/tempo/session/server/CredentialVerification.js +2 -3
  81. package/dist/viem/Client.d.ts +2 -0
  82. package/dist/viem/Client.js +4 -1
  83. package/dist/x402/Assets.d.ts +6 -0
  84. package/dist/x402/Assets.js +10 -0
  85. package/dist/x402/Siwx.d.ts +270 -0
  86. package/dist/x402/Siwx.js +458 -0
  87. package/dist/x402/Types.d.ts +72 -12
  88. package/dist/x402/Types.js +18 -3
  89. package/dist/x402/client/Exact.js +4 -1
  90. package/dist/x402/index.d.ts +1 -0
  91. package/dist/x402/index.js +1 -0
  92. package/dist/x402/middlewares/express.js +10 -1
  93. package/dist/x402/server/EvmCharge.d.ts +27 -3
  94. package/dist/x402/server/EvmCharge.js +27 -2
  95. package/dist/x402/server/Facilitator.d.ts +42 -3
  96. package/dist/x402/server/Facilitator.js +126 -16
  97. package/package.json +1 -1
@@ -1,4 +1,9 @@
1
+ import * as Host from './internal/host.js';
1
2
  import * as NodeListener from './NodeListener.js';
3
+ /** Raised when the incoming Host is outside the configured allowlist. */
4
+ export class UntrustedHostError extends Error {
5
+ name = 'UntrustedHostError';
6
+ }
2
7
  const defaultMaxBodySize = 10 * 1024 * 1024;
3
8
  const bodyCompletions = new WeakMap();
4
9
  /** Raised when a Node request body exceeds the configured byte limit. */
@@ -13,19 +18,23 @@ export class RequestBodyTooLargeError extends Error {
13
18
  * @returns A Node.js `(req, res)` listener.
14
19
  */
15
20
  export function toNodeListener(handler, options) {
16
- const onError = options?.onError ??
17
- ((error) => {
18
- if (error instanceof RequestBodyTooLargeError)
19
- return new Response('Payload Too Large', {
20
- status: 413,
21
- headers: { 'Content-Type': 'text/plain' },
22
- });
23
- console.error(error);
24
- return new Response('Internal Server Error', {
25
- status: 500,
21
+ const customOnError = options?.onError;
22
+ const defaultError = (error) => {
23
+ if (error instanceof UntrustedHostError)
24
+ return new Response('Misdirected Request', { status: 421 });
25
+ if (error instanceof RequestBodyTooLargeError)
26
+ return new Response('Payload Too Large', {
27
+ status: 413,
26
28
  headers: { 'Content-Type': 'text/plain' },
27
29
  });
30
+ if (!customOnError)
31
+ console.error(error);
32
+ return new Response('Internal Server Error', {
33
+ status: 500,
34
+ headers: { 'Content-Type': 'text/plain' },
28
35
  });
36
+ };
37
+ const onError = customOnError ?? defaultError;
29
38
  return (async (req, res) => {
30
39
  let response;
31
40
  try {
@@ -35,12 +44,7 @@ export function toNodeListener(handler, options) {
35
44
  }
36
45
  catch (error) {
37
46
  try {
38
- response =
39
- (await onError(error)) ??
40
- new Response('Internal Server Error', {
41
- status: 500,
42
- headers: { 'Content-Type': 'text/plain' },
43
- });
47
+ response = (await onError(error)) ?? defaultError(error);
44
48
  }
45
49
  catch (innerError) {
46
50
  console.error(`There was an error in the error handler: ${innerError}`);
@@ -50,7 +54,22 @@ export function toNodeListener(handler, options) {
50
54
  });
51
55
  }
52
56
  }
53
- await NodeListener.sendResponse(res, response);
57
+ try {
58
+ await NodeListener.sendResponse(res, response);
59
+ }
60
+ catch (error) {
61
+ try {
62
+ await onError(error);
63
+ }
64
+ catch (innerError) {
65
+ console.error(`There was an error in the error handler: ${innerError}`);
66
+ }
67
+ finally {
68
+ // Transmission may already have sent headers; never send a second response.
69
+ if (!res.destroyed)
70
+ res.destroy();
71
+ }
72
+ }
54
73
  });
55
74
  }
56
75
  /**
@@ -61,21 +80,23 @@ export function toNodeListener(handler, options) {
61
80
  * @returns A Fetch API Request.
62
81
  */
63
82
  export function fromNodeListener(req, res, options) {
83
+ const headers = createHeaders(req);
84
+ const incomingHost = headers.get('Host') ?? req.headers[':authority'] ?? 'localhost';
85
+ const fixedHost = options?.host !== undefined;
86
+ const checkedHost = fixedHost ? (req.headers.host ?? incomingHost) : incomingHost;
87
+ if (!Host.isAllowed(req, options?.allowedHosts, checkedHost, fixedHost))
88
+ throw new UntrustedHostError('Incoming host is not allowed.');
64
89
  let controller = new AbortController();
65
90
  res.once('close', () => controller?.abort());
66
91
  res.once('finish', () => {
67
92
  controller = null;
68
93
  });
69
94
  const method = req.method ?? 'GET';
70
- const headers = createHeaders(req);
71
95
  const protocol = options?.protocol ??
72
96
  ('encrypted' in req.socket && req.socket.encrypted
73
97
  ? 'https:'
74
98
  : 'http:');
75
- const host = options?.host ??
76
- headers.get('Host') ??
77
- req.headers[':authority'] ??
78
- 'localhost';
99
+ const host = options?.host ?? incomingHost;
79
100
  const url = createRequestUrl(req.url, `${protocol}//${host}`);
80
101
  const init = {
81
102
  method,
@@ -1,5 +1,15 @@
1
1
  /** Adds fresh issuance randomness while preserving application and route metadata. */
2
2
  export declare function withNonce(meta: Record<string, string> | undefined): Record<string, string>;
3
+ /** Sets the expiry grace marker when `grace` is true and removes any copy of it otherwise. */
4
+ export declare function withExpiryGrace(meta: Record<string, string> | undefined, grace: boolean): Record<string, string> | undefined;
5
+ /**
6
+ * Whether the challenge carries the expiry grace marker. Reads `opaque` when present, the
7
+ * value the challenge HMAC covers, and `meta` only otherwise.
8
+ */
9
+ export declare function hasExpiryGrace(challenge: {
10
+ meta?: Record<string, string> | undefined;
11
+ opaque?: string | undefined;
12
+ }): boolean;
3
13
  /** Removes issuance-only metadata when comparing stable route requirements. */
4
14
  export declare function routeMeta(meta: Record<string, string> | undefined): Record<string, string> | undefined;
5
15
  //# sourceMappingURL=challengeMeta.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { Secp256k1 } from 'ox';
2
+ import * as PaymentRequest from '../../PaymentRequest.js';
2
3
  /** Reserved metadata key for HMAC-bound, per-issuance challenge randomness. */
3
4
  const nonceKey = '_mppx_nonce';
4
5
  /** Adds fresh issuance randomness while preserving application and route metadata. */
@@ -6,11 +7,40 @@ export function withNonce(meta) {
6
7
  // Ox uses runtime-specific secure randomness, including Node without global Web Crypto.
7
8
  return { ...meta, [nonceKey]: Secp256k1.randomPrivateKey() };
8
9
  }
10
+ /**
11
+ * Reserved metadata key marking a challenge whose method accepts some of its credentials for a
12
+ * while after it expires. Bound by the challenge HMAC, so a challenge issued without it, by an
13
+ * earlier release or with no grace configured, never gets that grace.
14
+ */
15
+ const expiryGraceKey = '_mppx_expiry_grace';
16
+ /** Sets the expiry grace marker when `grace` is true and removes any copy of it otherwise. */
17
+ export function withExpiryGrace(meta, grace) {
18
+ const { [expiryGraceKey]: _, ...rest } = meta ?? {};
19
+ if (grace)
20
+ return { ...rest, [expiryGraceKey]: '1' };
21
+ return meta === undefined || !(expiryGraceKey in meta) ? meta : rest;
22
+ }
23
+ /**
24
+ * Whether the challenge carries the expiry grace marker. Reads `opaque` when present, the
25
+ * value the challenge HMAC covers, and `meta` only otherwise.
26
+ */
27
+ export function hasExpiryGrace(challenge) {
28
+ const { meta, opaque } = challenge;
29
+ if (opaque === undefined)
30
+ return meta?.[expiryGraceKey] === '1';
31
+ try {
32
+ const decoded = PaymentRequest.deserialize(opaque);
33
+ return decoded?.[expiryGraceKey] === '1';
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
9
39
  /** Issuance-only identity nonce of earlier mppx releases with payment-stage verifiers; still ignored. */
10
40
  const legacyIdentityKey = '_mppx_identity';
11
41
  /** Removes issuance-only metadata when comparing stable route requirements. */
12
42
  export function routeMeta(meta) {
13
- const { [nonceKey]: _, [legacyIdentityKey]: __, ...rest } = meta ?? {};
43
+ const { [nonceKey]: _, [legacyIdentityKey]: __, [expiryGraceKey]: ___, ...rest } = meta ?? {};
14
44
  return Object.keys(rest).length ? rest : undefined;
15
45
  }
16
46
  //# sourceMappingURL=challengeMeta.js.map
@@ -0,0 +1,4 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ /** Validates every incoming authority before Node or Express normalizes duplicate headers. */
3
+ export declare function isAllowed(request: Pick<IncomingMessage, 'headers' | 'rawHeaders'>, allowedHosts: readonly string[] | undefined, urlAuthority: string | undefined, allowNormalizedOnly?: boolean): boolean;
4
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1,41 @@
1
+ const normalizedHosts = new WeakMap();
2
+ /** Validates every incoming authority before Node or Express normalizes duplicate headers. */
3
+ export function isAllowed(request, allowedHosts, urlAuthority, allowNormalizedOnly = false) {
4
+ if (allowedHosts === undefined)
5
+ return true;
6
+ if (typeof urlAuthority !== 'string' || urlAuthority.length === 0)
7
+ return false;
8
+ const authorities = [urlAuthority];
9
+ const names = new Set();
10
+ for (let i = 0; i < request.rawHeaders.length; i += 2) {
11
+ const name = request.rawHeaders[i]?.toLowerCase();
12
+ if (name !== 'host' && name !== ':authority')
13
+ continue;
14
+ if (names.has(name))
15
+ return false;
16
+ names.add(name);
17
+ authorities.push(request.rawHeaders[i + 1] ?? '');
18
+ }
19
+ const host = request.headers.host;
20
+ const authority = request.headers[':authority'];
21
+ if (host !== undefined)
22
+ authorities.push(host);
23
+ if (authority !== undefined) {
24
+ if (typeof authority !== 'string')
25
+ return false;
26
+ authorities.push(authority);
27
+ }
28
+ if (names.size === 0 &&
29
+ (!allowNormalizedOnly || (typeof host !== 'string' && typeof authority !== 'string')))
30
+ return false;
31
+ const expected = authorities[0]?.toLowerCase();
32
+ if (expected === undefined || !authorities.every((value) => value.toLowerCase() === expected))
33
+ return false;
34
+ let allowed = normalizedHosts.get(allowedHosts);
35
+ if (!allowed) {
36
+ allowed = new Set(allowedHosts.map((value) => value.toLowerCase()));
37
+ normalizedHosts.set(allowedHosts, allowed);
38
+ }
39
+ return allowed.has(expected);
40
+ }
41
+ //# sourceMappingURL=host.js.map
@@ -281,14 +281,15 @@ export declare namespace charge {
281
281
  * charge, parsed with the matched currency's decimals. Values with more fractional digits than
282
282
  * `decimals` are rejected rather than rounded. Compared against the challenge
283
283
  * amount, which includes splits; larger offers are skipped during selection and
284
- * rejected before signing. Applies per credential, not cumulatively across
285
- * payment retries. Requires `currencies`.
284
+ * rejected before signing. A payment from a Zone balance also pays the Zone's
285
+ * withdrawal fee, so the amount plus that fee must fit, checked before withdrawing.
286
+ * Applies per credential, not cumulatively across payment retries. Requires `currencies`.
286
287
  */
287
288
  maxAmount?: string | undefined;
288
289
  /**
289
290
  * Maximum amount the client is willing to pay per charge, in raw base units of
290
- * the challenge currency (compared directly with the challenge `amount`).
291
- * Checked like `maxAmount`. Requires `currencies`.
291
+ * the challenge currency (compared directly with the challenge `amount`, plus the
292
+ * withdrawal fee for a Zone payment). Checked like `maxAmount`. Requires `currencies`.
292
293
  */
293
294
  maxAtomicAmount?: string | undefined;
294
295
  /**
@@ -7,7 +7,10 @@ import * as MethodResponse from '../../client/internal/MethodResponse.js';
7
7
  import * as Credential from '../../Credential.js';
8
8
  import * as Currency from '../../Currency.js';
9
9
  import * as Errors from '../../Errors.js';
10
+ import * as Expires from '../../Expires.js';
10
11
  import * as Method from '../../Method.js';
12
+ import * as PaymentRequest from '../../PaymentRequest.js';
13
+ import * as ChallengeMeta from '../../server/internal/challengeMeta.js';
11
14
  import * as Account from '../../viem/Account.js';
12
15
  import * as Client from '../../viem/Client.js';
13
16
  import * as z from '../../zod.js';
@@ -71,7 +74,7 @@ export function charge(parameters = {}) {
71
74
  });
72
75
  const getAccount = Account.getResolver({ account: parameters.account });
73
76
  assertZone(parameters.zone);
74
- // Zone withdrawals still settling, by challenge ID, so a retry resumes waiting instead of paying again.
77
+ // Zone withdrawals still settling, by challenge, so a retry resumes waiting instead of paying again.
75
78
  const pendingZoneWithdrawals = new Map();
76
79
  const method = Method.toClient(Methods.charge, {
77
80
  // Skip offers that violate client policy so an acceptable offer can be chosen.
@@ -85,7 +88,8 @@ export function charge(parameters = {}) {
85
88
  }
86
89
  },
87
90
  context: chargeContextSchema,
88
- async createCredential({ challenge, context }) {
91
+ async createCredential(credentialParameters) {
92
+ const { challenge, context } = credentialParameters;
89
93
  assertChallengePolicy(parameters, caps, challenge.request);
90
94
  // Sign on the pinned chain when the challenge omits a chain ID.
91
95
  const challengeChainId = challenge.request.methodDetails?.chainId;
@@ -121,19 +125,31 @@ export function charge(parameters = {}) {
121
125
  supportedModes.includes('push') &&
122
126
  (explicitMode === undefined || explicitMode === 'push') &&
123
127
  Zone.isAccepted(methodDetails?.zones, zoneId) &&
124
- !methodDetails?.splits &&
125
- // A withdrawal can't be undone, so start one only when it can settle before the
126
- // challenge expires; an expired challenge would invite another payment.
127
- (pendingZoneWithdrawals.has(zoneWithdrawalKey(challenge)) ||
128
- settlesBeforeExpiry(challenge.expires, parameters.zone.settlementTimeoutMs)))
129
- return createZoneCredential({
128
+ !methodDetails?.splits) {
129
+ const options = {
130
+ // The withdrawal fee is paid on top of the amount, so both must fit the caps.
131
+ assertFee: (fee) => assertChallengePolicy(parameters, caps, request, chainId, fee),
130
132
  challenge,
131
133
  clientId,
132
134
  client,
135
+ origin: httpOrigin(MethodResponse.getOrigin(credentialParameters)),
133
136
  pending: pendingZoneWithdrawals,
134
137
  zone: parameters.zone,
135
138
  zoneId,
136
- });
139
+ };
140
+ // A withdrawal can't be undone, so one still outstanding for these terms is resumed,
141
+ // even under a new challenge, and a new one starts only when it can settle before the
142
+ // challenge expires; an expired challenge would invite another payment.
143
+ const outstanding = findZoneWithdrawal(options);
144
+ if (outstanding)
145
+ return resumeZoneCredential(options, outstanding);
146
+ // With nothing outstanding, an expired challenge can't be paid: its server refuses any
147
+ // credential for it, so a payment on Tempo would be lost.
148
+ if (challenge.expires)
149
+ Expires.assert(challenge.expires, challenge.id);
150
+ if (settlesBeforeExpiry(challenge.expires, parameters.zone.settlementTimeoutMs))
151
+ return createZoneCredential(options);
152
+ }
137
153
  const defaultAccount = getAccount(client, context);
138
154
  const resolveAccount = async (operation) => (await parameters.resolveAccount?.({
139
155
  account: defaultAccount,
@@ -415,27 +431,100 @@ function transactionHash(credential) {
415
431
  * with the challenge-bound memo, and returns a `zone` credential that names it
416
432
  * by sender tag and the Tempo transaction hash that settled it.
417
433
  */
418
- async function createZoneCredential(options) {
419
- const { challenge, client, pending, zone, zoneId } = options;
420
- const request = challenge.request;
421
- const recipient = request.recipient;
422
- // The whole challenge, so a challenge from another realm or request with the same ID never matches.
434
+ function createZoneCredential(options) {
435
+ const { challenge, origin, pending, zoneId } = options;
436
+ // Stored before it is sent, so concurrent and later calls for one challenge or its terms share it.
437
+ const state = { sent: false };
438
+ const entry = {
439
+ challenge,
440
+ origin,
441
+ terms: zoneTermsKey(challenge, zoneId),
442
+ waiters: 0,
443
+ withdrawal: requestZoneWithdrawal(options, state),
444
+ };
423
445
  const key = zoneWithdrawalKey(challenge);
424
- // A withdrawal can't be undone, so a retry after a failed wait resumes it instead of paying again.
425
- // Concurrent calls for one challenge share the request, which is stored before it is sent.
426
- let withdrawalRequest = pending.get(key);
427
- if (!withdrawalRequest) {
428
- const state = { sent: false };
429
- withdrawalRequest = requestZoneWithdrawal(options, state);
430
- pending.set(key, withdrawalRequest);
431
- // Only a failure before the transaction was sent is safe to retry. After that, the
432
- // withdrawal may have gone through, so retries of this challenge keep failing.
433
- withdrawalRequest.catch(() => {
434
- if (!state.sent)
435
- pending.delete(key);
436
- });
446
+ pending.set(key, entry);
447
+ // Only a failure before the transaction was sent is safe to retry. After that, the
448
+ // withdrawal may have gone through, so retries of this challenge keep failing.
449
+ entry.withdrawal.catch(() => {
450
+ if (!state.sent && pending.get(key) === entry)
451
+ pending.delete(key);
452
+ });
453
+ return resumeZoneCredential(options, entry);
454
+ }
455
+ /**
456
+ * Returns the outstanding withdrawal that pays this challenge: its own, or, for a new
457
+ * challenge with the same terms, one an earlier challenge started and no call is still
458
+ * waiting on. A withdrawal stays outstanding until it produces a credential, even after its
459
+ * challenge expires: it may have settled, so paying its terms again could pay twice. It
460
+ * stops paying other challenges once its own can no longer be redeemed.
461
+ */
462
+ function findZoneWithdrawal(options) {
463
+ const { challenge, pending, zoneId } = options;
464
+ const own = pending.get(zoneWithdrawalKey(challenge));
465
+ if (own)
466
+ return own;
467
+ const terms = zoneTermsKey(challenge, zoneId);
468
+ if (terms === undefined)
469
+ return undefined;
470
+ for (const [key, entry] of pending) {
471
+ if (entry.terms !== terms)
472
+ continue;
473
+ // No server accepts its credential any more, so it can't pay this challenge.
474
+ if (!isRedeemable(entry.challenge.expires)) {
475
+ pending.delete(key);
476
+ continue;
477
+ }
478
+ // Its credential was sent after its challenge expired, and its server may still accept or
479
+ // refuse it. Sending it again for this challenge could redeem it twice, and a new payment
480
+ // could pay twice if it was refused, so fail closed until its redemption window ends.
481
+ // The error names the challenge the withdrawal paid, whose retry gets its credential.
482
+ if (entry.redeemedLate)
483
+ throw new Errors.ZoneSettlementPendingError({
484
+ challengeId: entry.challenge.id,
485
+ senderTags: entry.senderTags,
486
+ zoneId,
487
+ });
488
+ // A call still waiting on it is another payment in flight, not one this challenge retries:
489
+ // sharing its credential would leave one of the two payments unpaid.
490
+ if (entry.waiters > 0)
491
+ continue;
492
+ return entry;
437
493
  }
438
- const withdrawal = await withdrawalRequest;
494
+ return undefined;
495
+ }
496
+ /**
497
+ * Waits for an outstanding withdrawal to settle and returns a `zone` credential for the
498
+ * challenge it pays. A withdrawal started for an earlier challenge pays only that challenge,
499
+ * so its credential is sent only back to the origin that issued it; under any other origin,
500
+ * or one the caller did not verify, this throws the settlement-pending error instead.
501
+ */
502
+ async function resumeZoneCredential(options, entry) {
503
+ // Counted from the call itself, before any await, so a concurrent call sees it.
504
+ entry.waiters++;
505
+ try {
506
+ return await waitForZoneCredential(options, entry);
507
+ }
508
+ finally {
509
+ entry.waiters--;
510
+ }
511
+ }
512
+ /** Waits for {@link resumeZoneCredential}'s withdrawal to settle and serializes its credential. */
513
+ async function waitForZoneCredential(options, entry) {
514
+ const { client, origin, pending, zone, zoneId } = options;
515
+ const { challenge } = entry;
516
+ const recipient = challenge.request.recipient;
517
+ const key = zoneWithdrawalKey(challenge);
518
+ const foreign = key !== zoneWithdrawalKey(options.challenge);
519
+ if (foreign
520
+ ? !origin || origin !== entry.origin
521
+ : origin !== undefined && entry.origin !== undefined && origin !== entry.origin)
522
+ throw new Errors.ZoneSettlementPendingError({ challengeId: challenge.id, zoneId });
523
+ // Past its redemption window, the server refuses the challenge's credential, but the
524
+ // withdrawal may still have paid it: fail closed rather than withdraw again.
525
+ if (!isRedeemable(challenge.expires))
526
+ throw new Errors.ZoneSettlementPendingError({ challengeId: challenge.id, zoneId });
527
+ const withdrawal = await entry.withdrawal;
439
528
  // Derived on every attempt, so a failed read on the Zone is retried without withdrawing again.
440
529
  const senderTags = withdrawal.senderTags ??
441
530
  (await Zone.senderTagCandidates(zone.client, withdrawal).catch((cause) => {
@@ -461,13 +550,42 @@ async function createZoneCredential(options) {
461
550
  zoneId,
462
551
  });
463
552
  }
464
- pending.delete(key);
553
+ // The credential pays once: a later challenge with the same terms is a new payment. One
554
+ // made after its challenge expired is accepted only by a server that grants a grace period
555
+ // (`zoneCredentialGraceMs`), so it stays for a retry of its own challenge, which would
556
+ // otherwise pay again on Tempo, and blocks other challenges until its window ends.
557
+ if (pending.get(key) === entry) {
558
+ if (isExpired(challenge.expires)) {
559
+ entry.redeemedLate = true;
560
+ entry.senderTags = [settled.senderTag];
561
+ }
562
+ else
563
+ pending.delete(key);
564
+ }
465
565
  const { hash, senderTag } = settled;
466
566
  return Credential.serialize({
467
567
  challenge,
468
568
  payload: { hash, senderTag, type: 'zone', zoneId },
469
569
  });
470
570
  }
571
+ /**
572
+ * Returns the origin of an HTTP(S) URL, or `undefined` for anything else. Every other scheme
573
+ * has the opaque origin `"null"`, which can't tell two servers apart, so it never counts as
574
+ * a verified origin.
575
+ */
576
+ function httpOrigin(origin) {
577
+ if (!origin)
578
+ return undefined;
579
+ try {
580
+ const url = new URL(origin);
581
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
582
+ return undefined;
583
+ return url.origin;
584
+ }
585
+ catch {
586
+ return undefined;
587
+ }
588
+ }
471
589
  /**
472
590
  * Throws on Zone options that would fail only after an irreversible withdrawal:
473
591
  * a `settlementTimeoutMs` that is not a finite, non-negative number, or a
@@ -499,7 +617,10 @@ function settlesBeforeExpiry(expires, settlementTimeoutMs) {
499
617
  const timeoutMs = settlementTimeoutMs ?? Zone.defaultSettlementTimeoutMs;
500
618
  return new Date(expires).getTime() - Date.now() > timeoutMs + zoneSubmissionMarginMs;
501
619
  }
502
- /** Returns how long to wait for settlement: `settlementTimeoutMs`, cut short at `expires`. */
620
+ /**
621
+ * Returns how long to wait for settlement: `settlementTimeoutMs`, cut short at `expires`. After
622
+ * `expires`, it looks once: only a settlement from before then can still be redeemed.
623
+ */
503
624
  function settlementTimeoutMs(expires, settlementTimeoutMs) {
504
625
  const timeoutMs = settlementTimeoutMs ?? Zone.defaultSettlementTimeoutMs;
505
626
  if (!expires)
@@ -510,6 +631,50 @@ function settlementTimeoutMs(expires, settlementTimeoutMs) {
510
631
  function zoneWithdrawalKey(challenge) {
511
632
  return JSON.stringify(challenge);
512
633
  }
634
+ /**
635
+ * Keys what a challenge asks a Zone withdrawal to pay: its realm, request, digest and route
636
+ * metadata, everything a server compares when it accepts another challenge's credential,
637
+ * but not its ID, expiry or issuance nonce. `undefined` when its metadata can't be read.
638
+ */
639
+ function zoneTermsKey(challenge, zoneId) {
640
+ let meta;
641
+ try {
642
+ meta =
643
+ challenge.opaque !== undefined
644
+ ? PaymentRequest.deserialize(challenge.opaque)
645
+ : challenge.meta;
646
+ }
647
+ catch {
648
+ return undefined;
649
+ }
650
+ const { digest, intent, method, realm, request } = challenge;
651
+ return PaymentRequest.serialize({
652
+ digest,
653
+ intent,
654
+ meta: ChallengeMeta.routeMeta(meta),
655
+ method,
656
+ realm,
657
+ request,
658
+ zoneId,
659
+ });
660
+ }
661
+ /** Whether a challenge expiring at `expires` has expired. */
662
+ function isExpired(expires) {
663
+ if (!expires)
664
+ return false;
665
+ const expiresAt = new Date(expires).getTime();
666
+ return !Number.isNaN(expiresAt) && Date.now() >= expiresAt;
667
+ }
668
+ /**
669
+ * Whether a credential for a challenge expiring at `expires` may still be redeemed: until
670
+ * `Zone.redemptionGraceMs`, the longest server grace, after it expires.
671
+ */
672
+ function isRedeemable(expires) {
673
+ if (!expires)
674
+ return true;
675
+ const expiresAt = new Date(expires).getTime();
676
+ return Number.isNaN(expiresAt) || Date.now() < expiresAt + Zone.redemptionGraceMs;
677
+ }
513
678
  /** How long to look for a withdrawal's receipt on the Zone after its send response fails. */
514
679
  const zoneReceiptRecoveryTimeoutMs = 15_000;
515
680
  /**
@@ -517,7 +682,7 @@ const zoneReceiptRecoveryTimeoutMs = 15_000;
517
682
  * Returns its sender tag, or leaves it to be derived when the Zone RPC hides it from the receipt.
518
683
  */
519
684
  async function requestZoneWithdrawal(options, state) {
520
- const { challenge, clientId, zone } = options;
685
+ const { assertFee, challenge, clientId, zone } = options;
521
686
  const request = challenge.request;
522
687
  const account = zone.client.account;
523
688
  if (!account)
@@ -532,6 +697,7 @@ async function requestZoneWithdrawal(options, state) {
532
697
  });
533
698
  // The outbox pulls the amount plus its withdrawal fee.
534
699
  const fee = await Actions.zone.getWithdrawalFee(zone.client);
700
+ assertFee(fee);
535
701
  const [, withdrawal] = Actions.zone.requestWithdrawal.calls({
536
702
  amount,
537
703
  // A bounced payout refunds the payer, not the payee's Zone address.
@@ -609,8 +775,10 @@ function parseMaxAmount(maxAmount, decimals) {
609
775
  */
610
776
  function assertChallengePolicy(parameters, caps, request,
611
777
  /** Chain the client signs on, once resolved, for a challenge that names none. */
612
- signingChainId) {
613
- const { amount, methodDetails, recipient } = request;
778
+ signingChainId,
779
+ /** Zone withdrawal fee paid on top of the amount, which the caps cover too. */
780
+ fee) {
781
+ const { methodDetails, recipient } = request;
614
782
  // Chain pinning: reject a challenge whose chain ID conflicts with the pinned one.
615
783
  const challengeChainId = methodDetails?.chainId;
616
784
  if (parameters.expectedChainId !== undefined &&
@@ -645,10 +813,14 @@ signingChainId) {
645
813
  }
646
814
  }
647
815
  }
648
- if (caps.maxAtomicAmount !== undefined && BigInt(amount) > caps.maxAtomicAmount)
649
- throw new Error('Tempo charge amount exceeds maxAtomicAmount.');
650
- if (caps.maxAmount !== undefined &&
651
- BigInt(amount) > parseMaxAmount(caps.maxAmount, currency?.decimals))
652
- throw new Error('Tempo charge amount exceeds maxAmount.');
816
+ if (caps.maxAtomicAmount === undefined && caps.maxAmount === undefined)
817
+ return;
818
+ // Parsed only after the checks above pass, and only when a cap needs it.
819
+ const amount = BigInt(request.amount) + (fee ?? 0n);
820
+ const exceeds = fee === undefined ? 'amount exceeds' : 'amount plus Zone withdrawal fee exceeds';
821
+ if (caps.maxAtomicAmount !== undefined && amount > caps.maxAtomicAmount)
822
+ throw new Error(`Tempo charge ${exceeds} maxAtomicAmount.`);
823
+ if (caps.maxAmount !== undefined && amount > parseMaxAmount(caps.maxAmount, currency?.decimals))
824
+ throw new Error(`Tempo charge ${exceeds} maxAmount.`);
653
825
  }
654
826
  //# sourceMappingURL=Charge.js.map
@@ -19,6 +19,7 @@ export const subscriptionContextSchema = z.object({
19
19
  export function subscription(parameters = {}) {
20
20
  const getClient = Client.getResolver({
21
21
  chain: tempo_chain,
22
+ requireChain: true,
22
23
  getClient: parameters.getClient,
23
24
  rpcUrl: defaults.rpcUrl,
24
25
  });
@@ -28,6 +29,8 @@ export function subscription(parameters = {}) {
28
29
  async createCredential({ challenge, context }) {
29
30
  const chainId = challenge.request.methodDetails?.chainId ?? defaults.chainId.testnet;
30
31
  const client = await getClient({ chainId });
32
+ if (client.chain?.id !== chainId)
33
+ throw new Error(`Subscription chain mismatch: expected ${chainId}, got ${client.chain?.id ?? 'unknown'}.`);
31
34
  const account = getAccount(client, context);
32
35
  const accessKey = context?.accessKey ?? parameters.accessKey ?? challenge.request.methodDetails?.accessKey;
33
36
  if (!accessKey) {
@@ -1,6 +1,12 @@
1
1
  import { type Address, type Client, type Hex, type TransactionReceipt } from 'viem';
2
2
  /** Default time a payer waits for a Zone withdrawal to settle on Tempo. */
3
3
  export declare const defaultSettlementTimeoutMs = 60000;
4
+ /**
5
+ * The longest a server accepts a `zone` credential after its challenge expires (its
6
+ * `zoneCredentialGraceMs`), for a withdrawal that settled before then. A payer keeps resuming
7
+ * a withdrawal it has not redeemed for as long.
8
+ */
9
+ export declare const redemptionGraceMs: number;
4
10
  /** A withdrawal as `ZonePortal.processWithdrawals` receives it on Tempo. */
5
11
  export type Withdrawal = {
6
12
  token: Address;
@@ -29,6 +35,8 @@ export declare function isId(zoneId: number): boolean;
29
35
  export declare function isAccepted(zones: Accepted | undefined, zoneId: number): boolean;
30
36
  /** Returns the Tempo portal address of a Zone. */
31
37
  export declare function portalAddress(zoneId: number): Address;
38
+ /** Whether `address` is the Tempo portal of some Zone. */
39
+ export declare function isPortalAddress(address: Address): boolean;
32
40
  /**
33
41
  * Derives a Zone ID from a Zone chain ID.
34
42
  *
@@ -5,6 +5,12 @@ import { Abis, Addresses } from 'viem/tempo';
5
5
  import * as TempoAddress from './address.js';
6
6
  /** Default time a payer waits for a Zone withdrawal to settle on Tempo. */
7
7
  export const defaultSettlementTimeoutMs = 60_000;
8
+ /**
9
+ * The longest a server accepts a `zone` credential after its challenge expires (its
10
+ * `zoneCredentialGraceMs`), for a withdrawal that settled before then. A payer keeps resuming
11
+ * a withdrawal it has not redeemed for as long.
12
+ */
13
+ export const redemptionGraceMs = 5 * 60_000;
8
14
  /** Number of Tempo blocks searched back for a settled Zone withdrawal. */
9
15
  const lookbackBlocks = 7200n;
10
16
  /**
@@ -34,6 +40,15 @@ export function isAccepted(zones, zoneId) {
34
40
  export function portalAddress(zoneId) {
35
41
  return Addresses.zonePortal(zoneId);
36
42
  }
43
+ /** Prefix of every Zone portal address but the legacy ones: the Zone ID fills the last 8 bytes. */
44
+ const portalAddressPrefix = portalAddress(0).slice(0, -16).toLowerCase();
45
+ /** Zone IDs whose portals predate the prefixed addresses. */
46
+ const legacyPortalZoneIds = [6, 7];
47
+ /** Whether `address` is the Tempo portal of some Zone. */
48
+ export function isPortalAddress(address) {
49
+ return (address.toLowerCase().startsWith(portalAddressPrefix) ||
50
+ legacyPortalZoneIds.some((zoneId) => TempoAddress.isEqual(address, portalAddress(zoneId))));
51
+ }
37
52
  /**
38
53
  * Derives a Zone ID from a Zone chain ID.
39
54
  *