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
@@ -155,6 +155,25 @@ export declare namespace charge {
155
155
  * polling for a receipt.
156
156
  */
157
157
  waitForConfirmation?: boolean | undefined;
158
+ /**
159
+ * How long, in milliseconds, after its challenge expires a `zone` credential is still
160
+ * accepted, for a withdrawal that settled on Tempo before the challenge expired. Lets a
161
+ * payer whose withdrawal settled late in the challenge's lifetime redeem it on retry.
162
+ * At most 5 minutes (`300_000`).
163
+ *
164
+ * Only a Challenge issued while the grace is on gets it: issuance marks the Challenge in its
165
+ * HMAC-bound `opaque` metadata (`_mppx_expiry_grace`). A Challenge issued without the mark,
166
+ * by an earlier release or with no grace, is rejected at its expiry as before, since an
167
+ * earlier release records a redeemed withdrawal only until then.
168
+ *
169
+ * Enable it once no instance of an earlier release verifies credentials from the same store:
170
+ * such an instance could redeem a marked Challenge and record it only until its expiry.
171
+ *
172
+ * Not supported with `relay`, which verifies credentials without the settled-before-expiry check.
173
+ *
174
+ * @default 0
175
+ */
176
+ zoneCredentialGraceMs?: number | undefined;
158
177
  } & Client.getResolver.Parameters & Account.resolve.Parameters & Defaults & Method.ComposableHooks<typeof Methods.charge>;
159
178
  type DeriveDefaults<parameters extends Parameters> = types.DeriveDefaults<parameters, Defaults, {
160
179
  currency: string;
@@ -1,11 +1,14 @@
1
+ import { Secp256k1 } from 'ox';
1
2
  import * as SignatureEnvelope from 'ox/tempo/SignatureEnvelope';
2
3
  import { decodeFunctionData, formatUnits, keccak256, parseEventLogs, WaitForTransactionReceiptTimeoutError, } from 'viem';
3
- import { getTransaction, getTransactionReceipt, sendRawTransaction, sendRawTransactionSync, signTransaction, verifyTypedData, waitForTransactionReceipt, call as viem_call, } from 'viem/actions';
4
+ import { getTransaction, getBlock, getTransactionReceipt, sendRawTransaction, sendRawTransactionSync, signTransaction, verifyTypedData, waitForTransactionReceipt, call as viem_call, } from 'viem/actions';
4
5
  import { Abis, Actions, Transaction } from 'viem/tempo';
5
6
  import { tempo as tempo_chain } from 'viem/tempo/chains';
6
- import { BroadcastOutcomeUnknownError, CredentialReplayedError, PaymentError, VerificationFailedError, } from '../../Errors.js';
7
+ import { BroadcastOutcomeUnknownError, CredentialReplayedError, PaymentError, PaymentExpiredError, VerificationFailedError, } from '../../Errors.js';
7
8
  import * as Expires from '../../Expires.js';
9
+ import * as CredentialExpiry from '../../internal/CredentialExpiry.js';
8
10
  import * as Method from '../../Method.js';
11
+ import * as ChallengeMeta from '../../server/internal/challengeMeta.js';
9
12
  import * as Store from '../../Store.js';
10
13
  import * as Client from '../../viem/Client.js';
11
14
  import * as Attribution from '../Attribution.js';
@@ -34,7 +37,25 @@ import * as SponsorBudget from './SponsorBudget.js';
34
37
  * ```
35
38
  */
36
39
  export function charge(parameters = {}) {
37
- const { machineTokenEnabled, allowedFeeTokens: configuredAllowedFeeTokens, amount, confirmationTimeoutMs = 30_000, currency = defaults.resolveCurrency(parameters), decimals = defaults.decimals, description, externalId, feeToken: configuredFeeToken, feePayerPolicy, html, relay, sponsorBudget, splits, supportedModes, validateSender, waitForConfirmation = true, zones, } = parameters;
40
+ const { machineTokenEnabled, allowedFeeTokens: configuredAllowedFeeTokens, amount, confirmationTimeoutMs = 30_000, currency = defaults.resolveCurrency(parameters), decimals = defaults.decimals, description, externalId, feeToken: configuredFeeToken, feePayerPolicy, html, relay, sponsorBudget, splits, supportedModes, validateSender, waitForConfirmation = true, zoneCredentialGraceMs = 0, zones, } = parameters;
41
+ if (!Number.isFinite(zoneCredentialGraceMs) ||
42
+ zoneCredentialGraceMs < 0 ||
43
+ zoneCredentialGraceMs > Zone.redemptionGraceMs)
44
+ throw new Error(`\`zoneCredentialGraceMs\` must be between 0 and ${Zone.redemptionGraceMs} milliseconds.`);
45
+ // A relay verifies credentials itself, without the local check that a late `zone` credential
46
+ // settled before its challenge expired, so it can't honor the grace safely.
47
+ if (relay && zoneCredentialGraceMs > 0)
48
+ throw new Error('`zoneCredentialGraceMs` is not supported with `relay`.');
49
+ /**
50
+ * Grace for a credential presented after its challenge expired: only a `zone` credential gets
51
+ * one, and only for a challenge issued with the grace on. A challenge issued without it (by an
52
+ * earlier release, whose replay claims end at the expiry, or with no grace) gets none.
53
+ */
54
+ const graceMsFor = (credential) => zoneCredentialGraceMs > 0 &&
55
+ isZoneCredential(credential) &&
56
+ ChallengeMeta.hasExpiryGrace(credential.challenge)
57
+ ? zoneCredentialGraceMs
58
+ : undefined;
38
59
  if (configuredAllowedFeeTokens?.length === 0)
39
60
  throw new Error('`allowedFeeTokens` must contain at least one token.');
40
61
  const storeKeyPrefix = parameters.storeKeyPrefix ?? '';
@@ -97,7 +118,7 @@ export function charge(parameters = {}) {
97
118
  ? MachineTokenCharge.getSettlementSender(chainId)
98
119
  : undefined;
99
120
  const isZeroAmount = BigInt(amount) === 0n;
100
- Expires.assert(challenge.expires, challenge.id);
121
+ CredentialExpiry.assert(credential, graceMsFor(credential));
101
122
  if (isZeroAmount && payload.type !== 'proof')
102
123
  throw new MismatchError('Zero-amount challenges require a proof credential.', {});
103
124
  // Request-level local sponsorship takes precedence over the hosted provider.
@@ -239,6 +260,14 @@ export function charge(parameters = {}) {
239
260
  });
240
261
  if (!isChallengeBound([withdrawal.memo], { challengeId: challenge.id, realm: challenge.realm }))
241
262
  throw new CredentialReplayedError({ reason: 'memo is not bound to this challenge' });
263
+ // A credential presented after its challenge expired is accepted only for a withdrawal
264
+ // that settled before then; see `zoneCredentialGraceMs`.
265
+ const expiresAt = Date.parse(challenge.expires);
266
+ if (expiresAt <= Date.now()) {
267
+ const block = await getBlock(client, { blockNumber: receipt.blockNumber });
268
+ if (Number(block.timestamp) * 1000 >= expiresAt)
269
+ throw new PaymentExpiredError({ expires: challenge.expires });
270
+ }
242
271
  return { hash, portal, receipt, senderTag };
243
272
  }
244
273
  async function validateProofCredential(credential, payload, context) {
@@ -510,8 +539,8 @@ export function charge(parameters = {}) {
510
539
  ? request.feePayer
511
540
  : feePayer
512
541
  : undefined;
542
+ CredentialExpiry.assert(credential, graceMsFor(credential));
513
543
  const expires = challenge.expires;
514
- Expires.assert(expires, challenge.id);
515
544
  const replayExpires = Date.parse(expires);
516
545
  switch (validated.type) {
517
546
  case 'hash': {
@@ -537,7 +566,9 @@ export function charge(parameters = {}) {
537
566
  }
538
567
  case 'zone': {
539
568
  const { portal, receipt, senderTag } = validated;
540
- if (!(await tryClaimZoneWithdrawal(store, portal, senderTag, replayExpires))) {
569
+ // Held through the longest grace any server may grant, not only this one's, so an
570
+ // instance with a longer grace on the same store can't redeem the credential again.
571
+ if (!(await tryClaimZoneWithdrawal(store, portal, senderTag, replayExpires + Zone.redemptionGraceMs))) {
541
572
  throw new CredentialReplayedError({
542
573
  reason: 'Zone withdrawal has already been used',
543
574
  });
@@ -557,7 +588,8 @@ export function charge(parameters = {}) {
557
588
  const { fundingCurrency, isFeePayerTx, serializedTransaction, settlementSenders, transaction, transfers, } = validated;
558
589
  // Pre-broadcast dedup: catch exact byte-for-byte replays early.
559
590
  const hash = keccak256(serializedTransaction);
560
- if (!(await tryClaimHash(store, hash, replayExpires))) {
591
+ const owner = Secp256k1.randomPrivateKey();
592
+ if (!(await tryClaimHash(store, hash, replayExpires, owner))) {
561
593
  throw new CredentialReplayedError({
562
594
  reason: 'Transaction hash has already been used',
563
595
  });
@@ -642,7 +674,7 @@ export function charge(parameters = {}) {
642
674
  const serializedTransaction_final = await Transaction.serialize(Transaction.deserialize(completedTransaction.serializedTransaction));
643
675
  finalHash = keccak256(serializedTransaction_final);
644
676
  if (finalHash.toLowerCase() !== hash.toLowerCase()) {
645
- if (!(await tryClaimHash(store, finalHash, replayExpires)))
677
+ if (!(await tryClaimHash(store, finalHash, replayExpires, owner)))
646
678
  throw new CredentialReplayedError({
647
679
  reason: 'Transaction hash has already been used',
648
680
  });
@@ -804,9 +836,12 @@ export function charge(parameters = {}) {
804
836
  // Only a successful settlement consumes the credential. A signed
805
837
  // transaction can be mined at most once, so a retry re-broadcasts it
806
838
  // and recovers the receipt instead of being rejected as a replay.
807
- if (claimedFinalHash)
808
- await releaseHashUse(store, claimedFinalHash);
809
- await releaseHashUse(store, hash);
839
+ const cleanup = await Promise.allSettled([
840
+ ...(claimedFinalHash ? [releaseHashUse(store, claimedFinalHash, owner)] : []),
841
+ releaseHashUse(store, hash, owner),
842
+ ]);
843
+ if (cleanup.some((result) => result.status === 'rejected'))
844
+ console.error('mppx: replay claim cleanup failed; claims remain consumed until expiry');
810
845
  if (broadcastAttempted)
811
846
  throw error;
812
847
  throw await explainMachineTokenFailure(error, {
@@ -821,6 +856,7 @@ export function charge(parameters = {}) {
821
856
  }
822
857
  },
823
858
  });
859
+ CredentialExpiry.register(method, graceMsFor, { issue: zoneCredentialGraceMs > 0 });
824
860
  return relay ? Relay.configure(method, relay) : method;
825
861
  }
826
862
  /**
@@ -994,6 +1030,10 @@ async function assertTransferLogs(receipt, parameters) {
994
1030
  })();
995
1031
  if (!memoMatches)
996
1032
  continue;
1033
+ // A Zone portal's payout settles a Zone withdrawal, which pays only through its `zone`
1034
+ // credential, so the same settlement can't also be redeemed by transaction hash.
1035
+ if (Zone.isPortalAddress(log.args.from))
1036
+ continue;
997
1037
  if (!(await isValidTransferSender({
998
1038
  expectedSender: parameters.sender,
999
1039
  sender: log.args.from,
@@ -1097,11 +1137,16 @@ function getProofStoreKey(challengeId) {
1097
1137
  function getZoneWithdrawalStoreKey(portal, senderTag) {
1098
1138
  return `mppx:charge:zone:${portal.toLowerCase()}:${senderTag.toLowerCase()}`;
1099
1139
  }
1140
+ /** Whether a credential pays with a Zone withdrawal. */
1141
+ function isZoneCredential(credential) {
1142
+ const { payload } = credential;
1143
+ return (typeof payload === 'object' && payload !== null && 'type' in payload && payload.type === 'zone');
1144
+ }
1100
1145
  async function tryClaimZoneWithdrawal(store, portal, senderTag, expires) {
1101
1146
  return Store.tryClaim(store, getZoneWithdrawalStoreKey(portal, senderTag), expires);
1102
1147
  }
1103
- async function tryClaimHash(store, hash, expires) {
1104
- return Store.tryClaim(store, getHashStoreKey(hash), expires);
1148
+ async function tryClaimHash(store, hash, expires, owner) {
1149
+ return Store.tryClaim(store, getHashStoreKey(hash), expires, owner);
1105
1150
  }
1106
1151
  /** Whether a live replay marker holds `hash`, read without claiming it. */
1107
1152
  async function isHashUsed(store, hash) {
@@ -1112,8 +1157,8 @@ async function isHashUsed(store, hash) {
1112
1157
  return typeof expires !== 'number' || expires > Date.now();
1113
1158
  }
1114
1159
  /** @internal */
1115
- async function releaseHashUse(store, hash) {
1116
- await store.delete(getHashStoreKey(hash));
1160
+ async function releaseHashUse(store, hash, owner) {
1161
+ await Store.releaseClaim(store, getHashStoreKey(hash), owner);
1117
1162
  }
1118
1163
  function parseHashCredentialSource(parameters) {
1119
1164
  const { chainId, source } = parameters;