mppx 0.21.4 → 0.22.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 (59) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/BodyDigest.d.ts +3 -3
  3. package/dist/BodyDigest.js +5 -3
  4. package/dist/Challenge.js +12 -2
  5. package/dist/Credential.js +9 -1
  6. package/dist/Errors.d.ts +62 -8
  7. package/dist/Errors.js +57 -6
  8. package/dist/Store.d.ts +7 -4
  9. package/dist/Store.js +18 -8
  10. package/dist/cli/cli.js +135 -135
  11. package/dist/cli/internal.js +1 -1
  12. package/dist/cli/plugins/index.js +12 -12
  13. package/dist/client/Budget.d.ts +49 -0
  14. package/dist/client/Budget.js +101 -0
  15. package/dist/client/Mppx.d.ts +8 -3
  16. package/dist/client/Mppx.js +55 -13
  17. package/dist/client/Spend.d.ts +134 -0
  18. package/dist/client/Spend.js +58 -0
  19. package/dist/client/core.d.ts +2 -0
  20. package/dist/client/core.js +2 -0
  21. package/dist/client/internal/Fetch.d.ts +23 -3
  22. package/dist/client/internal/Fetch.js +155 -37
  23. package/dist/client/internal/FundsMoved.d.ts +9 -0
  24. package/dist/client/internal/FundsMoved.js +18 -0
  25. package/dist/client/internal/SpendGate.d.ts +136 -0
  26. package/dist/client/internal/SpendGate.js +608 -0
  27. package/dist/client/internal/SpendHooks.d.ts +42 -0
  28. package/dist/client/internal/SpendHooks.js +36 -0
  29. package/dist/client/internal/protocols/Mcp.d.ts +9 -0
  30. package/dist/client/internal/protocols/Mcp.js +27 -0
  31. package/dist/client/internal/protocols/Mpp.js +20 -3
  32. package/dist/client/internal/protocols/Shared.js +29 -3
  33. package/dist/evm/client/Charge.js +20 -8
  34. package/dist/extensions/identity/erc8004/server/index.d.ts +7 -1
  35. package/dist/extensions/identity/erc8004/server/index.js +13 -1
  36. package/dist/extensions/identity/link/client/index.js +57 -5
  37. package/dist/identity/Client.d.ts +7 -3
  38. package/dist/identity/Client.js +178 -13
  39. package/dist/identity/Types.d.ts +2 -1
  40. package/dist/integrations/x402/Negotiator.js +4 -1
  41. package/dist/integrations/x402/Solana.d.ts +75 -0
  42. package/dist/integrations/x402/Solana.js +143 -0
  43. package/dist/internal/challengeMeta.d.ts +17 -2
  44. package/dist/internal/challengeMeta.js +35 -7
  45. package/dist/internal/version.d.ts +2 -2
  46. package/dist/internal/version.js +1 -1
  47. package/dist/mcp/client/McpClient.d.ts +6 -1
  48. package/dist/mcp/client/McpClient.js +48 -10
  49. package/dist/server/Mppx.d.ts +12 -1
  50. package/dist/server/Mppx.js +58 -6
  51. package/dist/server/Transport.js +46 -2
  52. package/dist/stripe/server/internal/html.gen.js +1 -1
  53. package/dist/tempo/client/Charge.js +81 -17
  54. package/dist/tempo/server/Charge.d.ts +7 -1
  55. package/dist/tempo/server/Charge.js +98 -12
  56. package/dist/tempo/server/internal/html.gen.js +1 -1
  57. package/dist/tempo/session/client/SessionManager.js +3 -0
  58. package/dist/x402/server/EvmCharge.js +3 -0
  59. package/package.json +1 -1
@@ -4,7 +4,7 @@ import { decodeFunctionData, formatUnits, keccak256, parseEventLogs, WaitForTran
4
4
  import { getTransaction, getBlock, getTransactionReceipt, sendRawTransaction, sendRawTransactionSync, signTransaction, verifyTypedData, waitForTransactionReceipt, call as viem_call, } from 'viem/actions';
5
5
  import { Abis, Actions, Transaction } from 'viem/tempo';
6
6
  import { tempo as tempo_chain } from 'viem/tempo/chains';
7
- import { BroadcastOutcomeUnknownError, CredentialReplayedError, PaymentError, PaymentExpiredError, VerificationFailedError, } from '../../Errors.js';
7
+ import { BroadcastOutcomeUnknownError, CredentialReplayedError, InvalidChallengeError, PaymentError, PaymentExpiredError, VerificationFailedError, } from '../../Errors.js';
8
8
  import * as Expires from '../../Expires.js';
9
9
  import * as ChallengeMeta from '../../internal/challengeMeta.js';
10
10
  import * as CredentialExpiry from '../../internal/CredentialExpiry.js';
@@ -65,6 +65,8 @@ export function charge(parameters = {}) {
65
65
  (relay
66
66
  ? Store.memory()
67
67
  : fallbackStore('tempo.charge')));
68
+ if (!relay && rawStore.tryClaim && !rawStore.releaseClaim)
69
+ throw new Error('Tempo charge requires a custom store with atomic releaseClaim support. Migrate the store before use.');
68
70
  const store = Store.from(rawStore, { keyPrefix: storeKeyPrefix });
69
71
  const { maxInFlightReservations: legacyMaxInFlightReservations, maxInFlightTotalFee: legacyMaxInFlightTotalFee, ...transactionFeePayerPolicy } = feePayerPolicy ?? {};
70
72
  const sponsorBudgetConfig = sponsorBudget === false ? undefined : (sponsorBudget ?? {});
@@ -201,9 +203,11 @@ export function charge(parameters = {}) {
201
203
  transfers,
202
204
  validateSender,
203
205
  });
206
+ // A push payment (hash credential) must carry the challenge-bound attribution memo.
204
207
  assertChallengeBoundMemo(matchedLogs, {
205
208
  challengeId: challenge.id,
206
209
  realm: challenge.realm,
210
+ required: true,
207
211
  });
208
212
  // The payer is the account the matched transfers debited, not the submitter.
209
213
  // Settlement-contract transfers are funded by the transaction sender.
@@ -258,8 +262,13 @@ export function charge(parameters = {}) {
258
262
  throw new MismatchError('Payment verification failed: Zone withdrawal not found.', {
259
263
  senderTag,
260
264
  });
261
- if (!isChallengeBound([withdrawal.memo], { challengeId: challenge.id, realm: challenge.realm }))
262
- throw new CredentialReplayedError({ reason: 'memo is not bound to this challenge' });
265
+ // A push payment (Zone withdrawal) must carry the challenge-bound attribution memo.
266
+ if (!isChallengeBound([withdrawal.memo], {
267
+ challengeId: challenge.id,
268
+ realm: challenge.realm,
269
+ required: true,
270
+ }))
271
+ throw new MismatchError('Payment verification failed: memo is not bound to this challenge.', {});
263
272
  // A credential presented after its challenge expired is accepted only for a withdrawal
264
273
  // that settled before then; see `zoneCredentialGraceMs`.
265
274
  const expiresAt = Date.parse(challenge.expires);
@@ -364,6 +373,13 @@ export function charge(parameters = {}) {
364
373
  };
365
374
  }
366
375
  async function validateCredential(credential, request, context) {
376
+ // Push and proof credentials are bound only to the Challenge ID. Without a per-issuance
377
+ // nonce, every requester of the route can hold that ID and redeem someone else's payment.
378
+ if (context.payload.type !== 'transaction' && !ChallengeMeta.hasNonce(credential.challenge))
379
+ throw new InvalidChallengeError({
380
+ id: credential.challenge.id,
381
+ reason: `${context.payload.type} credentials need a challenge with a nonce`,
382
+ });
367
383
  switch (context.payload.type) {
368
384
  case 'hash': {
369
385
  const { payer, receipt, sender, transfers } = await validateHashCredential(credential, context.payload, context);
@@ -595,6 +611,9 @@ export function charge(parameters = {}) {
595
611
  });
596
612
  }
597
613
  let broadcastAttempted = false;
614
+ // Set when the node already held the transaction from someone else,
615
+ // so an unknown outcome is not remembered as this server's own.
616
+ let duplicateElsewhere = false;
598
617
  let finalHash;
599
618
  // Set only after this request claims the final hash, so cleanup never
600
619
  // releases a marker that another request holds.
@@ -742,6 +761,11 @@ export function charge(parameters = {}) {
742
761
  ? Number.POSITIVE_INFINITY
743
762
  : transaction.validBefore * 1_000 + 2_000;
744
763
  let receipt;
764
+ // Set when the node already held the transaction this server
765
+ // sent: someone else (another server, or anyone who saw it
766
+ // pending) may have submitted it, so its receipt pays this
767
+ // challenge only with an attribution memo bound to it.
768
+ let submittedElsewhere = false;
745
769
  try {
746
770
  receipt = await withDeadline(sendRawTransactionSync(client, {
747
771
  serializedTransaction: serializedTransaction_final,
@@ -751,6 +775,12 @@ export function charge(parameters = {}) {
751
775
  catch (broadcastError) {
752
776
  if (!isAmbiguousBroadcastError(broadcastError))
753
777
  throw broadcastError;
778
+ // A duplicate of this server's own earlier broadcast for this
779
+ // challenge, whose outcome was unknown, is not someone else's.
780
+ submittedElsewhere =
781
+ isDuplicateBroadcastError(broadcastError) &&
782
+ !(await isOwnBroadcast(store, finalHash, challenge.id));
783
+ duplicateElsewhere = submittedElsewhere;
754
784
  // The node may have accepted the transaction, so poll for its receipt.
755
785
  const timeout = Math.min(deadline, validUntil) - Date.now();
756
786
  let recovered;
@@ -771,6 +801,10 @@ export function charge(parameters = {}) {
771
801
  validBefore: transaction.validBefore,
772
802
  });
773
803
  receipt = recovered;
804
+ // The record of this server's own broadcast may have landed while
805
+ // polling, written by the request whose outcome was unknown.
806
+ if (submittedElsewhere && (await isOwnBroadcast(store, finalHash, challenge.id)))
807
+ submittedElsewhere = duplicateElsewhere = false;
774
808
  }
775
809
  if (reservation)
776
810
  await SponsorBudget.release(sponsorBudgetStore, reservation);
@@ -783,11 +817,15 @@ export function charge(parameters = {}) {
783
817
  assertChallengeBoundMemo(matchedLogs, {
784
818
  challengeId: challenge.id,
785
819
  realm: challenge.realm,
820
+ required: submittedElsewhere && !isFeePayerTx,
786
821
  });
787
822
  if (receipt.transactionHash.toLowerCase() !== finalHash.toLowerCase())
788
823
  throw new VerificationFailedError({
789
824
  reason: 'Broadcast transaction hash does not match the signed transaction',
790
825
  });
826
+ // The transfer has settled: a marker left behind expires on its own and
827
+ // must not fail the payment.
828
+ await store.delete(getBroadcastStoreKey(finalHash)).catch(() => { });
791
829
  return toReceipt(receipt.transactionHash, fundingCurrency);
792
830
  }
793
831
  // Optimistic path: broadcast without waiting for confirmation
@@ -833,6 +871,21 @@ export function charge(parameters = {}) {
833
871
  console.error('mppx: sponsor budget cleanup error', budgetError);
834
872
  }
835
873
  }
874
+ // Remember a broadcast of this server's own whose outcome is
875
+ // unknown, for this challenge only, so a retry that finds the node
876
+ // already holding it recovers it as this server's own. It is written
877
+ // before the claims are released, so a concurrent retry that takes a
878
+ // released claim already sees it.
879
+ // A duplicate of someone else's submission leaves no record: this
880
+ // server has no evidence it sent the transaction.
881
+ if (error instanceof BroadcastOutcomeUnknownError && finalHash && !duplicateElsewhere)
882
+ await store
883
+ .put(getBroadcastStoreKey(finalHash), {
884
+ challengeId: challenge.id,
885
+ expires: Math.max(expires ? Date.parse(expires) : Date.now() + 3_600_000, (transaction.validBefore ?? 0) * 1_000) + 60_000,
886
+ type: 'mppx:broadcast',
887
+ })
888
+ .catch(() => { });
836
889
  // Only a successful settlement consumes the credential. A signed
837
890
  // transaction can be mined at most once, so a retry re-broadcasts it
838
891
  // and recovers the receipt instead of being rejected as a replay.
@@ -1148,6 +1201,20 @@ async function tryClaimZoneWithdrawal(store, portal, senderTag, expires) {
1148
1201
  async function tryClaimHash(store, hash, expires, owner) {
1149
1202
  return Store.tryClaim(store, getHashStoreKey(hash), expires, owner);
1150
1203
  }
1204
+ function getBroadcastStoreKey(hash) {
1205
+ return `mppx:charge:broadcast:${hash.toLowerCase()}`;
1206
+ }
1207
+ /** Whether this server broadcast `hash` for `challengeId` on an earlier attempt. */
1208
+ async function isOwnBroadcast(store, hash, challengeId) {
1209
+ const marker = await store.get(getBroadcastStoreKey(hash)).catch(() => null);
1210
+ if (typeof marker !== 'object' || marker === null)
1211
+ return false;
1212
+ const { challengeId: recorded, expires, type } = marker;
1213
+ return (type === 'mppx:broadcast' &&
1214
+ recorded === challengeId &&
1215
+ typeof expires === 'number' &&
1216
+ expires > Date.now());
1217
+ }
1151
1218
  /** Whether a live replay marker holds `hash`, read without claiming it. */
1152
1219
  async function isHashUsed(store, hash) {
1153
1220
  const current = await store.get(getHashStoreKey(hash));
@@ -1262,6 +1329,22 @@ function isAmbiguousBroadcastError(error) {
1262
1329
  }
1263
1330
  return false;
1264
1331
  }
1332
+ /**
1333
+ * Whether a failed synchronous broadcast says the node already holds the
1334
+ * transaction ("already known", "known transaction" or Tempo's
1335
+ * `ExpiringNonceReplay`), matched anywhere in the `cause` chain.
1336
+ */
1337
+ function isDuplicateBroadcastError(error) {
1338
+ for (let cause = error; cause; cause = cause.cause) {
1339
+ if (typeof cause !== 'object')
1340
+ return false;
1341
+ const { message } = cause;
1342
+ if (typeof message === 'string' &&
1343
+ /\balready ?known\b|\bknown transaction\b|\bExpiringNonceReplay\b/i.test(message))
1344
+ return true;
1345
+ }
1346
+ return false;
1347
+ }
1265
1348
  /** Rejects with `error` if `promise` has not settled by `deadline` (epoch ms). */
1266
1349
  async function withDeadline(promise, deadline, error) {
1267
1350
  let timer;
@@ -1289,9 +1372,8 @@ function toReceipt(reference, fundingCurrency) {
1289
1372
  }
1290
1373
  function assertChallengeBoundMemo(matchedLogs, parameters) {
1291
1374
  const memos = matchedLogs.map((log) => (log.kind === 'memo' ? log.args.memo : undefined));
1292
- // The transfer already settled to the recipient, so another payment would not help.
1293
1375
  if (!isChallengeBound(memos, parameters))
1294
- throw new CredentialReplayedError({ reason: 'memo is not bound to this challenge' });
1376
+ throw new MismatchError('Payment verification failed: memo is not bound to this challenge.', {});
1295
1377
  }
1296
1378
  function assertChallengeBoundCallMemo(matchedCalls, parameters) {
1297
1379
  const memos = matchedCalls.map((call) => call.memo);
@@ -1299,10 +1381,13 @@ function assertChallengeBoundCallMemo(matchedCalls, parameters) {
1299
1381
  throw new MismatchError('Payment verification failed: memo is not bound to this challenge.', {});
1300
1382
  }
1301
1383
  /**
1302
- * Whether matched payment transfers carry a challenge-bound attribution memo and
1303
- * no conflicting attribution. Otherwise, a split payment could authorize another
1304
- * challenge after the first challenge's replay marker expires. Unmatched transfers
1305
- * cannot establish the binding; plain transfers and non-MPP memos remain allowed.
1384
+ * Whether the matched payment transfers are bound to this challenge. Any attribution memo
1385
+ * that is not for this challenge's realm and ID is rejected, whatever the credential type:
1386
+ * a pull payment carrying another realm's attribution memo could later be presented to that
1387
+ * realm as a push payment, and that realm keeps no record of it. With required (push
1388
+ * payments), at least one matched transfer must also carry an attribution memo bound to this
1389
+ * challenge. Otherwise (pull payments) plain transfers and memos not in attribution format
1390
+ * are accepted.
1306
1391
  * @internal
1307
1392
  */
1308
1393
  function isChallengeBound(memos, parameters) {
@@ -1310,12 +1395,13 @@ function isChallengeBound(memos, parameters) {
1310
1395
  for (const memo of memos) {
1311
1396
  if (!memo || !Attribution.isMppMemo(memo))
1312
1397
  continue;
1313
- if (!Attribution.verifyServer(memo, parameters.realm) ||
1314
- !Attribution.verifyChallengeBinding(memo, parameters.challengeId))
1398
+ if (!Attribution.verifyServer(memo, parameters.realm))
1399
+ return false;
1400
+ if (!Attribution.verifyChallengeBinding(memo, parameters.challengeId))
1315
1401
  return false;
1316
1402
  bound = true;
1317
1403
  }
1318
- return bound;
1404
+ return bound || !parameters.required;
1319
1405
  }
1320
1406
  /** @internal */
1321
1407
  class MismatchError extends PaymentError {