@nevermined-io/payments 1.1.18 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/a2a/clientRegistry.d.ts.map +1 -1
  2. package/dist/a2a/clientRegistry.js +2 -2
  3. package/dist/a2a/clientRegistry.js.map +1 -1
  4. package/dist/a2a/paymentsClient.d.ts +2 -2
  5. package/dist/a2a/paymentsClient.d.ts.map +1 -1
  6. package/dist/a2a/paymentsClient.js +10 -6
  7. package/dist/a2a/paymentsClient.js.map +1 -1
  8. package/dist/a2a/server.d.ts.map +1 -1
  9. package/dist/a2a/server.js +3 -1
  10. package/dist/a2a/server.js.map +1 -1
  11. package/dist/a2a/types.d.ts +1 -0
  12. package/dist/a2a/types.d.ts.map +1 -1
  13. package/dist/a2a/types.js.map +1 -1
  14. package/dist/api/plans-api.d.ts +12 -2
  15. package/dist/api/plans-api.d.ts.map +1 -1
  16. package/dist/api/plans-api.js +16 -3
  17. package/dist/api/plans-api.js.map +1 -1
  18. package/dist/common/types.d.ts +70 -7
  19. package/dist/common/types.d.ts.map +1 -1
  20. package/dist/common/types.js +16 -0
  21. package/dist/common/types.js.map +1 -1
  22. package/dist/index.d.ts +2 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/plans.d.ts +13 -2
  27. package/dist/plans.d.ts.map +1 -1
  28. package/dist/plans.js +19 -2
  29. package/dist/plans.js.map +1 -1
  30. package/dist/x402/delegation-api.d.ts +92 -19
  31. package/dist/x402/delegation-api.d.ts.map +1 -1
  32. package/dist/x402/delegation-api.js +65 -23
  33. package/dist/x402/delegation-api.js.map +1 -1
  34. package/dist/x402/express/middleware.d.ts +4 -0
  35. package/dist/x402/express/middleware.d.ts.map +1 -1
  36. package/dist/x402/express/middleware.js +7 -4
  37. package/dist/x402/express/middleware.js.map +1 -1
  38. package/dist/x402/facilitator-api.d.ts +9 -0
  39. package/dist/x402/facilitator-api.d.ts.map +1 -1
  40. package/dist/x402/facilitator-api.js +24 -10
  41. package/dist/x402/facilitator-api.js.map +1 -1
  42. package/dist/x402/index.d.ts +3 -3
  43. package/dist/x402/index.d.ts.map +1 -1
  44. package/dist/x402/index.js +2 -2
  45. package/dist/x402/index.js.map +1 -1
  46. package/dist/x402/token.d.ts +17 -17
  47. package/dist/x402/token.d.ts.map +1 -1
  48. package/dist/x402/token.js +27 -37
  49. package/dist/x402/token.js.map +1 -1
  50. package/package.json +1 -1
package/dist/plans.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"plans.js","sourceRoot":"","sources":["../src/plans.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+C,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AACnG,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAE9C,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAO,CAAA,CAAC,uBAAuB;AAC/D,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAQ,CAAA,CAAC,2BAA2B;AACrE,MAAM,CAAC,MAAM,kBAAkB,GAAG,QAAU,CAAA,CAAC,yEAAyE;AACtH,MAAM,CAAC,MAAM,iBAAiB,GAAG,SAAW,CAAA,CAAC,gCAAgC;AAE7E,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,MAAc,EAAE,QAAiB,EAAmB,EAAE;IACvF,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,kCAAkC,CAAC,CAAA;IACjF,OAAO;QACL,YAAY,EAAE,WAAW;QACzB,OAAO,EAAE,CAAC,MAAM,CAAC;QACjB,SAAS,EAAE,CAAC,QAAQ,CAAC;QACrB,eAAe,EAAE,WAAW;QAC5B,aAAa,EAAE,WAAW;QAC1B,oBAAoB,EAAE,WAA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;IACrB,OAAO;QACL,GAAG,aAAa;QAChB,aAAa;KACd,CAAA;AACH,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CACtC,MAAc,EACd,QAAiB,EACjB,eAAwB,WAAW,EACnC,eAAyB,EACR,EAAE;IACnB,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,kCAAkC,CAAC,CAAA;IAEjF,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CACb,2HAA2H,CAC5H,CAAA;IACH,CAAC;IAED,OAAO;QACL,YAAY;QACZ,OAAO,EAAE,CAAC,MAAM,CAAC;QACjB,SAAS,EAAE,CAAC,QAAQ,CAAC;QACrB,eAAe,EAAE,WAAW;QAC5B,aAAa,EAAE,WAAW;QAC1B,oBAAoB,EAAE,WAAW;QACjC,eAAe;QACf,QAAQ,EAAE,IAAI;KACf,CAAA;AACH,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,GAAsB,EAAE;IAChE,OAAO;QACL,uBAAuB,EAAE,KAAK;QAC9B,cAAc,EAAE,kBAAkB,CAAC,eAAe;QAClD,aAAa,EAAE,KAAK;QACpB,YAAY,EAAE,EAAE;QAChB,MAAM,EAAE,EAAE;QACV,SAAS,EAAE,EAAE;QACb,SAAS,EAAE,EAAE;KACd,CAAA;AACH,CAAC,CAAA","sourcesContent":["import { Address, PlanCreditsConfig, PlanPriceConfig, PlanRedemptionType } from './common/types.js'\nimport { ZeroAddress } from './environments.js'\nimport { isEthereumAddress } from './utils.js'\n\nexport const ONE_DAY_DURATION = 86_400n // 24 * 60 * 60 seconds\nexport const ONE_WEEK_DURATION = 604_800n // 7 * 24 * 60 * 60 seconds\nexport const ONE_MONTH_DURATION = 2_629_746n // (365.25 days/year ÷ 12 months/year) × 24 × 60 × 60 ≈ 2,629,746 seconds\nexport const ONE_YEAR_DURATION = 31_557_600n // 365.25 * 24 * 60 * 60 seconds\n\nexport const getFiatPriceConfig = (amount: bigint, receiver: Address): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n return {\n tokenAddress: ZeroAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: false,\n }\n}\n\nexport const getCryptoPriceConfig = (\n amount: bigint,\n receiver: Address,\n tokenAddress: Address = ZeroAddress,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n return {\n tokenAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: true,\n }\n}\n\nexport const getERC20PriceConfig = (\n amount: bigint,\n tokenAddress: Address,\n receiver: Address,\n): PlanPriceConfig => {\n return getCryptoPriceConfig(amount, receiver, tokenAddress)\n}\n\nexport const getFreePriceConfig = (): PlanPriceConfig => {\n return {\n tokenAddress: ZeroAddress,\n amounts: [],\n receivers: [],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: true,\n }\n}\n\nexport const getNativeTokenPriceConfig = (amount: bigint, receiver: Address): PlanPriceConfig => {\n return getCryptoPriceConfig(amount, receiver, ZeroAddress)\n}\n\nexport const getExpirableDurationConfig = (durationOfPlan: bigint): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: durationOfPlan,\n amount: 1n,\n minAmount: 1n,\n maxAmount: 1n,\n }\n}\n\nexport const getNonExpirableDurationConfig = (): PlanCreditsConfig => {\n return getExpirableDurationConfig(0n)\n}\n\nexport const getFixedCreditsConfig = (\n creditsGranted: bigint,\n creditsPerRequest = 1n,\n): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: true,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: 0n,\n amount: creditsGranted,\n minAmount: creditsPerRequest,\n maxAmount: creditsPerRequest,\n }\n}\n\nexport const getDynamicCreditsConfig = (\n creditsGranted: bigint,\n minCreditsPerRequest = 1n,\n maxCreditsPerRequest = 1n,\n): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: 0n,\n amount: creditsGranted,\n minAmount: minCreditsPerRequest,\n maxAmount: maxCreditsPerRequest,\n }\n}\n\nexport const setRedemptionType = (\n creditsConfig: PlanCreditsConfig,\n redemptionType: PlanRedemptionType,\n): PlanCreditsConfig => {\n return {\n ...creditsConfig,\n redemptionType,\n }\n}\n\nexport const setProofRequired = (\n creditsConfig: PlanCreditsConfig,\n proofRequired = true,\n): PlanCreditsConfig => {\n return {\n ...creditsConfig,\n proofRequired,\n }\n}\n\n/**\n * Build a pay-as-you-go price configuration.\n *\n * For pay-as-you-go plans, the template address must come from the API deployment info.\n */\nexport const getPayAsYouGoPriceConfig = (\n amount: bigint,\n receiver: Address,\n tokenAddress: Address = ZeroAddress,\n templateAddress?: Address,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n\n if (!templateAddress) {\n throw new Error(\n 'templateAddress is required. Use ContractsAPI.getPayAsYouGoTemplateAddress() or Payments.plans.getPayAsYouGoPriceConfig()',\n )\n }\n\n return {\n tokenAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress,\n isCrypto: true,\n }\n}\n\n/**\n * Build a pay-as-you-go credits configuration.\n *\n * Credits are not minted upfront; these values are required for validation only.\n */\nexport const getPayAsYouGoCreditsConfig = (): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: 0n,\n amount: 1n,\n minAmount: 1n,\n maxAmount: 1n,\n }\n}\n"]}
1
+ {"version":3,"file":"plans.js","sourceRoot":"","sources":["../src/plans.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,QAAQ,EACR,kBAAkB,EAGlB,kBAAkB,GACnB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAE9C,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAO,CAAA,CAAC,uBAAuB;AAC/D,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAQ,CAAA,CAAC,2BAA2B;AACrE,MAAM,CAAC,MAAM,kBAAkB,GAAG,QAAU,CAAA,CAAC,yEAAyE;AACtH,MAAM,CAAC,MAAM,iBAAiB,GAAG,SAAW,CAAA,CAAC,gCAAgC;AAE7E,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAChC,MAAc,EACd,QAAiB,EACjB,WAA8B,QAAQ,CAAC,GAAG,EACzB,EAAE;IACnB,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,kCAAkC,CAAC,CAAA;IACjF,OAAO;QACL,YAAY,EAAE,WAAW;QACzB,OAAO,EAAE,CAAC,MAAM,CAAC;QACjB,SAAS,EAAE,CAAC,QAAQ,CAAC;QACrB,eAAe,EAAE,WAAW;QAC5B,aAAa,EAAE,WAAW;QAC1B,oBAAoB,EAAE,WAAW;QACjC,eAAe,EAAE,WAAW;QAC5B,QAAQ,EAAE,KAAK;QACf,QAAQ;KACT,CAAA;AACH,CAAC,CA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EAChC,cAAkC,EACf,EAAE;IACrB,OAAO;QACL,GAAG,aAAa;QAChB,cAAc;KACf,CAAA;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,aAAgC,EAChC,aAAa,GAAG,IAAI,EACD,EAAE;IACrB,OAAO;QACL,GAAG,aAAa;QAChB,aAAa;KACd,CAAA;AACH,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CACtC,MAAc,EACd,QAAiB,EACjB,eAAwB,WAAW,EACnC,eAAyB,EACR,EAAE;IACnB,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,kCAAkC,CAAC,CAAA;IAEjF,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CACb,2HAA2H,CAC5H,CAAA;IACH,CAAC;IAED,OAAO;QACL,YAAY;QACZ,OAAO,EAAE,CAAC,MAAM,CAAC;QACjB,SAAS,EAAE,CAAC,QAAQ,CAAC;QACrB,eAAe,EAAE,WAAW;QAC5B,aAAa,EAAE,WAAW;QAC1B,oBAAoB,EAAE,WAAW;QACjC,eAAe;QACf,QAAQ,EAAE,IAAI;KACf,CAAA;AACH,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,GAAsB,EAAE;IAChE,OAAO;QACL,uBAAuB,EAAE,KAAK;QAC9B,cAAc,EAAE,kBAAkB,CAAC,eAAe;QAClD,aAAa,EAAE,KAAK;QACpB,YAAY,EAAE,EAAE;QAChB,MAAM,EAAE,EAAE;QACV,SAAS,EAAE,EAAE;QACb,SAAS,EAAE,EAAE;KACd,CAAA;AACH,CAAC,CAAA","sourcesContent":["import {\n Address,\n Currency,\n EURC_TOKEN_ADDRESS,\n PlanCreditsConfig,\n PlanPriceConfig,\n PlanRedemptionType,\n} from './common/types.js'\nimport { ZeroAddress } from './environments.js'\nimport { isEthereumAddress } from './utils.js'\n\nexport const ONE_DAY_DURATION = 86_400n // 24 * 60 * 60 seconds\nexport const ONE_WEEK_DURATION = 604_800n // 7 * 24 * 60 * 60 seconds\nexport const ONE_MONTH_DURATION = 2_629_746n // (365.25 days/year ÷ 12 months/year) × 24 × 60 × 60 ≈ 2,629,746 seconds\nexport const ONE_YEAR_DURATION = 31_557_600n // 365.25 * 24 * 60 * 60 seconds\n\nexport const getFiatPriceConfig = (\n amount: bigint,\n receiver: Address,\n currency: Currency | string = Currency.USD,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n return {\n tokenAddress: ZeroAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: false,\n currency,\n }\n}\n\nexport const getCryptoPriceConfig = (\n amount: bigint,\n receiver: Address,\n tokenAddress: Address = ZeroAddress,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n return {\n tokenAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: true,\n }\n}\n\nexport const getERC20PriceConfig = (\n amount: bigint,\n tokenAddress: Address,\n receiver: Address,\n): PlanPriceConfig => {\n return getCryptoPriceConfig(amount, receiver, tokenAddress)\n}\n\n/**\n * Builds a price configuration for EURC (Euro stablecoin) payments.\n *\n * EURC uses 6 decimal places. To charge €29.00, pass `29_000_000n`.\n *\n * @param amount - Amount in the token's smallest unit (6 decimals for EURC).\n * @param receiver - Wallet address that will receive the payment.\n * @param eurcAddress - Optional EURC token address. Defaults to Base Mainnet EURC.\n * @returns The PlanPriceConfig representing an EURC price.\n */\nexport const getEURCPriceConfig = (\n amount: bigint,\n receiver: Address,\n eurcAddress: Address = EURC_TOKEN_ADDRESS,\n): PlanPriceConfig => {\n return {\n ...getERC20PriceConfig(amount, eurcAddress, receiver),\n currency: Currency.EURC,\n }\n}\n\nexport const getFreePriceConfig = (): PlanPriceConfig => {\n return {\n tokenAddress: ZeroAddress,\n amounts: [],\n receivers: [],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: true,\n }\n}\n\nexport const getNativeTokenPriceConfig = (amount: bigint, receiver: Address): PlanPriceConfig => {\n return getCryptoPriceConfig(amount, receiver, ZeroAddress)\n}\n\nexport const getExpirableDurationConfig = (durationOfPlan: bigint): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: durationOfPlan,\n amount: 1n,\n minAmount: 1n,\n maxAmount: 1n,\n }\n}\n\nexport const getNonExpirableDurationConfig = (): PlanCreditsConfig => {\n return getExpirableDurationConfig(0n)\n}\n\nexport const getFixedCreditsConfig = (\n creditsGranted: bigint,\n creditsPerRequest = 1n,\n): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: true,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: 0n,\n amount: creditsGranted,\n minAmount: creditsPerRequest,\n maxAmount: creditsPerRequest,\n }\n}\n\nexport const getDynamicCreditsConfig = (\n creditsGranted: bigint,\n minCreditsPerRequest = 1n,\n maxCreditsPerRequest = 1n,\n): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: 0n,\n amount: creditsGranted,\n minAmount: minCreditsPerRequest,\n maxAmount: maxCreditsPerRequest,\n }\n}\n\nexport const setRedemptionType = (\n creditsConfig: PlanCreditsConfig,\n redemptionType: PlanRedemptionType,\n): PlanCreditsConfig => {\n return {\n ...creditsConfig,\n redemptionType,\n }\n}\n\nexport const setProofRequired = (\n creditsConfig: PlanCreditsConfig,\n proofRequired = true,\n): PlanCreditsConfig => {\n return {\n ...creditsConfig,\n proofRequired,\n }\n}\n\n/**\n * Build a pay-as-you-go price configuration.\n *\n * For pay-as-you-go plans, the template address must come from the API deployment info.\n */\nexport const getPayAsYouGoPriceConfig = (\n amount: bigint,\n receiver: Address,\n tokenAddress: Address = ZeroAddress,\n templateAddress?: Address,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n\n if (!templateAddress) {\n throw new Error(\n 'templateAddress is required. Use ContractsAPI.getPayAsYouGoTemplateAddress() or Payments.plans.getPayAsYouGoPriceConfig()',\n )\n }\n\n return {\n tokenAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress,\n isCrypto: true,\n }\n}\n\n/**\n * Build a pay-as-you-go credits configuration.\n *\n * Credits are not minted upfront; these values are required for validation only.\n */\nexport const getPayAsYouGoCreditsConfig = (): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: 0n,\n amount: 1n,\n minAmount: 1n,\n maxAmount: 1n,\n }\n}\n"]}
@@ -1,43 +1,116 @@
1
1
  /**
2
- * Delegation API for managing card-delegation payment methods.
2
+ * Delegation API for managing payment delegations (crypto and card schemes).
3
3
  *
4
- * Provides access to the user's enrolled Stripe payment methods
5
- * for use with the nvm:card-delegation x402 scheme.
4
+ * Provides access to the user's enrolled payment methods and delegations
5
+ * for use with the nvm:erc4337 and nvm:card-delegation x402 schemes.
6
6
  */
7
7
  import { BasePaymentsAPI } from '../api/base-payments.js';
8
- import { PaymentOptions } from '../common/types.js';
8
+ import { CreateDelegationPayload, CreateDelegationResponse, PaymentOptions } from '../common/types.js';
9
9
  /**
10
10
  * Summary of a user's enrolled payment method.
11
11
  */
12
12
  export interface PaymentMethodSummary {
13
- /** Payment method ID (e.g., 'pm_...') */
13
+ /** Payment method ID (Stripe 'pm_...' or Braintree vault token) */
14
14
  id: string;
15
- /** Card brand (e.g., 'visa', 'mastercard') */
15
+ /** Payment method type (e.g., 'card', 'paypal') */
16
+ type: string;
17
+ /** Card brand (e.g., 'visa', 'mastercard') or payment method type ('paypal', 'venmo') */
16
18
  brand: string;
17
- /** Last 4 digits of the card number */
19
+ /** Last 4 digits (cards) or email/username (PayPal/Venmo) */
18
20
  last4: string;
19
- /** Card expiration month */
21
+ /** Expiration month (0 for non-card methods) */
20
22
  expMonth: number;
21
- /** Card expiration year */
23
+ /** Expiration year (0 for non-card methods) */
22
24
  expYear: number;
25
+ /** Human-readable alias, if set */
26
+ alias?: string | null;
27
+ /** Payment provider: 'stripe' or 'braintree' */
28
+ provider?: string;
29
+ /** Current status ('Active' or 'Revoked') */
30
+ status?: string;
31
+ /** NVM API Key IDs allowed to use this payment method, or null if unrestricted */
32
+ allowedApiKeyIds?: string[] | null;
23
33
  }
24
34
  /**
25
- * API for listing enrolled payment methods for card delegation.
35
+ * Summary of a delegation (card or crypto spending).
36
+ */
37
+ export interface DelegationSummary {
38
+ delegationId: string;
39
+ provider: string;
40
+ providerPaymentMethodId: string;
41
+ status: string;
42
+ spendingLimitCents: string;
43
+ amountSpentCents: string;
44
+ remainingBudgetCents: string;
45
+ currency: string;
46
+ transactionCount: number;
47
+ expiresAt: string;
48
+ createdAt: string;
49
+ apiKeyId: string | null;
50
+ }
51
+ /**
52
+ * Paginated list of delegations returned by the API.
53
+ */
54
+ export interface DelegationListResponse {
55
+ delegations: DelegationSummary[];
56
+ totalResults: number;
57
+ page: number;
58
+ offset: number;
59
+ }
60
+ /**
61
+ * Summary of an agent's purchasing power via card delegations.
62
+ */
63
+ export interface PurchasingPower {
64
+ cards: PaymentMethodSummary[];
65
+ delegations: DelegationSummary[];
66
+ totalRemainingBudgetCents: number;
67
+ currency: string;
68
+ }
69
+ /**
70
+ * DTO for updating a payment method's alias and allowed API keys.
71
+ */
72
+ export interface UpdatePaymentMethodDto {
73
+ alias?: string;
74
+ allowedApiKeyIds?: string[] | null;
75
+ }
76
+ /**
77
+ * Options for listing payment methods or delegations.
78
+ */
79
+ export interface ListOptions {
80
+ /** When true, return only items accessible to the requesting API key */
81
+ accessible?: boolean;
82
+ }
83
+ /**
84
+ * API for managing payment methods and delegations (card and crypto).
26
85
  */
27
86
  export declare class DelegationAPI extends BasePaymentsAPI {
28
- /**
29
- * Get an instance of the DelegationAPI class.
30
- *
31
- * @param options - The options to initialize the API
32
- * @returns The instance of the DelegationAPI class
33
- */
34
87
  static getInstance(options: PaymentOptions): DelegationAPI;
35
88
  /**
36
89
  * List the user's enrolled payment methods for card delegation.
90
+ * When `accessible: true`, only cards accessible to the requesting API key are returned.
91
+ */
92
+ listPaymentMethods(options?: ListOptions): Promise<PaymentMethodSummary[]>;
93
+ /**
94
+ * List the user's existing delegations.
95
+ * When `accessible: true`, only usable delegations (Active, non-expired, with budget) are returned.
96
+ */
97
+ listDelegations(options?: ListOptions): Promise<DelegationListResponse>;
98
+ /**
99
+ * Get the agent's purchasing power — accessible cards, active delegations,
100
+ * and combined remaining budget.
101
+ */
102
+ getPurchasingPower(): Promise<PurchasingPower>;
103
+ /**
104
+ * Create a new delegation for either stripe or erc4337 provider.
37
105
  *
38
- * @returns A promise that resolves to an array of payment method summaries
39
- * @throws PaymentsError if the request fails
106
+ * @param payload - The delegation creation parameters
107
+ * @returns The created delegation ID (and token for card delegations)
108
+ */
109
+ createDelegation(payload: CreateDelegationPayload): Promise<CreateDelegationResponse>;
110
+ /**
111
+ * Update a payment method's alias and/or allowed API keys.
40
112
  */
41
- listPaymentMethods(): Promise<PaymentMethodSummary[]>;
113
+ updatePaymentMethod(paymentMethodId: string, dto: UpdatePaymentMethodDto): Promise<PaymentMethodSummary>;
114
+ private fetchJSON;
42
115
  }
43
116
  //# sourceMappingURL=delegation-api.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"delegation-api.d.ts","sourceRoot":"","sources":["../../src/x402/delegation-api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAEnD;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,yCAAyC;IACzC,EAAE,EAAE,MAAM,CAAA;IACV,8CAA8C;IAC9C,KAAK,EAAE,MAAM,CAAA;IACb,uCAAuC;IACvC,KAAK,EAAE,MAAM,CAAA;IACb,4BAA4B;IAC5B,QAAQ,EAAE,MAAM,CAAA;IAChB,2BAA2B;IAC3B,OAAO,EAAE,MAAM,CAAA;CAChB;AAED;;GAEG;AACH,qBAAa,aAAc,SAAQ,eAAe;IAChD;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,cAAc,GAAG,aAAa;IAI1D;;;;;OAKG;IACG,kBAAkB,IAAI,OAAO,CAAC,oBAAoB,EAAE,CAAC;CA0B5D"}
1
+ {"version":3,"file":"delegation-api.d.ts","sourceRoot":"","sources":["../../src/x402/delegation-api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAEzD,OAAO,EAAE,uBAAuB,EAAE,wBAAwB,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAEtG;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,mEAAmE;IACnE,EAAE,EAAE,MAAM,CAAA;IACV,mDAAmD;IACnD,IAAI,EAAE,MAAM,CAAA;IACZ,yFAAyF;IACzF,KAAK,EAAE,MAAM,CAAA;IACb,6DAA6D;IAC7D,KAAK,EAAE,MAAM,CAAA;IACb,gDAAgD;IAChD,QAAQ,EAAE,MAAM,CAAA;IAChB,+CAA+C;IAC/C,OAAO,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;IACxE,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;AAED;;GAEG;AACH,qBAAa,aAAc,SAAQ,eAAe;IAChD,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,cAAc,GAAG,aAAa;IAI1D;;;OAGG;IACG,kBAAkB,CAAC,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,oBAAoB,EAAE,CAAC;IAMhF;;;OAGG;IACG,eAAe,CAAC,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,sBAAsB,CAAC;IAM7E;;;OAGG;IACG,kBAAkB,IAAI,OAAO,CAAC,eAAe,CAAC;IAoBpD;;;;;OAKG;IACG,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,wBAAwB,CAAC;IAK3F;;OAEG;IACG,mBAAmB,CACvB,eAAe,EAAE,MAAM,EACvB,GAAG,EAAE,sBAAsB,GAC1B,OAAO,CAAC,oBAAoB,CAAC;YAOlB,SAAS;CA2BxB"}
@@ -1,53 +1,95 @@
1
1
  /**
2
- * Delegation API for managing card-delegation payment methods.
2
+ * Delegation API for managing payment delegations (crypto and card schemes).
3
3
  *
4
- * Provides access to the user's enrolled Stripe payment methods
5
- * for use with the nvm:card-delegation x402 scheme.
4
+ * Provides access to the user's enrolled payment methods and delegations
5
+ * for use with the nvm:erc4337 and nvm:card-delegation x402 schemes.
6
6
  */
7
7
  import { BasePaymentsAPI } from '../api/base-payments.js';
8
8
  import { PaymentsError } from '../common/payments.error.js';
9
9
  /**
10
- * API for listing enrolled payment methods for card delegation.
10
+ * API for managing payment methods and delegations (card and crypto).
11
11
  */
12
12
  export class DelegationAPI extends BasePaymentsAPI {
13
- /**
14
- * Get an instance of the DelegationAPI class.
15
- *
16
- * @param options - The options to initialize the API
17
- * @returns The instance of the DelegationAPI class
18
- */
19
13
  static getInstance(options) {
20
14
  return new DelegationAPI(options);
21
15
  }
22
16
  /**
23
17
  * List the user's enrolled payment methods for card delegation.
18
+ * When `accessible: true`, only cards accessible to the requesting API key are returned.
19
+ */
20
+ async listPaymentMethods(options) {
21
+ const url = new URL('/api/v1/payment-methods', this.environment.backend);
22
+ if (options?.accessible)
23
+ url.searchParams.set('accessible', 'true');
24
+ return this.fetchJSON(url, 'GET', 'list payment methods');
25
+ }
26
+ /**
27
+ * List the user's existing delegations.
28
+ * When `accessible: true`, only usable delegations (Active, non-expired, with budget) are returned.
29
+ */
30
+ async listDelegations(options) {
31
+ const url = new URL('/api/v1/delegation', this.environment.backend);
32
+ if (options?.accessible)
33
+ url.searchParams.set('accessible', 'true');
34
+ return this.fetchJSON(url, 'GET', 'list delegations');
35
+ }
36
+ /**
37
+ * Get the agent's purchasing power — accessible cards, active delegations,
38
+ * and combined remaining budget.
39
+ */
40
+ async getPurchasingPower() {
41
+ const accessible = { accessible: true };
42
+ const [cards, { delegations }] = await Promise.all([
43
+ this.listPaymentMethods(accessible),
44
+ this.listDelegations(accessible),
45
+ ]);
46
+ const totalRemainingBudgetCents = delegations.reduce((sum, d) => sum + (parseInt(d.remainingBudgetCents, 10) || 0), 0);
47
+ return {
48
+ cards,
49
+ delegations,
50
+ totalRemainingBudgetCents,
51
+ currency: delegations[0]?.currency ?? 'usd',
52
+ };
53
+ }
54
+ /**
55
+ * Create a new delegation for either stripe or erc4337 provider.
24
56
  *
25
- * @returns A promise that resolves to an array of payment method summaries
26
- * @throws PaymentsError if the request fails
57
+ * @param payload - The delegation creation parameters
58
+ * @returns The created delegation ID (and token for card delegations)
59
+ */
60
+ async createDelegation(payload) {
61
+ const url = new URL('/api/v1/delegation/create', this.environment.backend);
62
+ return this.fetchJSON(url, 'POST', 'create delegation', payload);
63
+ }
64
+ /**
65
+ * Update a payment method's alias and/or allowed API keys.
27
66
  */
28
- async listPaymentMethods() {
29
- const url = new URL('/api/v1/delegation/payment-methods', this.environment.backend);
30
- const options = this.getBackendHTTPOptions('GET');
67
+ async updatePaymentMethod(paymentMethodId, dto) {
68
+ const url = new URL(`/api/v1/payment-methods/${paymentMethodId}`, this.environment.backend);
69
+ return this.fetchJSON(url, 'PATCH', 'update payment method', dto);
70
+ }
71
+ // --- Private helpers ---
72
+ async fetchJSON(url, method, action, body) {
73
+ const options = this.getBackendHTTPOptions(method, body);
31
74
  try {
32
75
  const response = await fetch(url, options);
33
76
  if (!response.ok) {
34
- let errorMessage = 'Failed to list payment methods';
77
+ let msg = `Failed to ${action}`;
35
78
  try {
36
- const errorData = await response.json();
37
- errorMessage = errorData.message || errorMessage;
79
+ const err = await response.json();
80
+ msg = err.message || msg;
38
81
  }
39
82
  catch {
40
- // Use default error message
83
+ // use default
41
84
  }
42
- throw PaymentsError.internal(`${errorMessage} (HTTP ${response.status})`);
85
+ throw PaymentsError.internal(`${msg} (HTTP ${response.status})`);
43
86
  }
44
87
  return await response.json();
45
88
  }
46
89
  catch (error) {
47
- if (error instanceof PaymentsError) {
90
+ if (error instanceof PaymentsError)
48
91
  throw error;
49
- }
50
- throw PaymentsError.internal(`Network error while listing payment methods: ${error instanceof Error ? error.message : String(error)}`);
92
+ throw PaymentsError.internal(`Network error while ${action}: ${error instanceof Error ? error.message : String(error)}`);
51
93
  }
52
94
  }
53
95
  }
@@ -1 +1 @@
1
- {"version":3,"file":"delegation-api.js","sourceRoot":"","sources":["../../src/x402/delegation-api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAmB3D;;GAEG;AACH,MAAM,OAAO,aAAc,SAAQ,eAAe;IAChD;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,OAAuB;QACxC,OAAO,IAAI,aAAa,CAAC,OAAO,CAAC,CAAA;IACnC,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,kBAAkB;QACtB,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,oCAAoC,EAAE,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;QACnF,MAAM,OAAO,GAAG,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,CAAA;QAEjD,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;YAC1C,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;gBACjB,IAAI,YAAY,GAAG,gCAAgC,CAAA;gBACnD,IAAI,CAAC;oBACH,MAAM,SAAS,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;oBACvC,YAAY,GAAG,SAAS,CAAC,OAAO,IAAI,YAAY,CAAA;gBAClD,CAAC;gBAAC,MAAM,CAAC;oBACP,4BAA4B;gBAC9B,CAAC;gBACD,MAAM,aAAa,CAAC,QAAQ,CAAC,GAAG,YAAY,UAAU,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAA;YAC3E,CAAC;YACD,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,aAAa,EAAE,CAAC;gBACnC,MAAM,KAAK,CAAA;YACb,CAAC;YACD,MAAM,aAAa,CAAC,QAAQ,CAC1B,gDAAgD,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CACzG,CAAA;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Delegation API for managing card-delegation payment methods.\n *\n * Provides access to the user's enrolled Stripe payment methods\n * for use with the nvm:card-delegation x402 scheme.\n */\n\nimport { BasePaymentsAPI } from '../api/base-payments.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { PaymentOptions } from '../common/types.js'\n\n/**\n * Summary of a user's enrolled payment method.\n */\nexport interface PaymentMethodSummary {\n /** Payment method ID (e.g., 'pm_...') */\n id: string\n /** Card brand (e.g., 'visa', 'mastercard') */\n brand: string\n /** Last 4 digits of the card number */\n last4: string\n /** Card expiration month */\n expMonth: number\n /** Card expiration year */\n expYear: number\n}\n\n/**\n * API for listing enrolled payment methods for card delegation.\n */\nexport class DelegationAPI extends BasePaymentsAPI {\n /**\n * Get an instance of the DelegationAPI class.\n *\n * @param options - The options to initialize the API\n * @returns The instance of the DelegationAPI class\n */\n static getInstance(options: PaymentOptions): DelegationAPI {\n return new DelegationAPI(options)\n }\n\n /**\n * List the user's enrolled payment methods for card delegation.\n *\n * @returns A promise that resolves to an array of payment method summaries\n * @throws PaymentsError if the request fails\n */\n async listPaymentMethods(): Promise<PaymentMethodSummary[]> {\n const url = new URL('/api/v1/delegation/payment-methods', this.environment.backend)\n const options = this.getBackendHTTPOptions('GET')\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Failed to list payment methods'\n try {\n const errorData = await response.json()\n errorMessage = errorData.message || errorMessage\n } catch {\n // Use default error message\n }\n throw PaymentsError.internal(`${errorMessage} (HTTP ${response.status})`)\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) {\n throw error\n }\n throw PaymentsError.internal(\n `Network error while listing payment methods: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n}\n"]}
1
+ {"version":3,"file":"delegation-api.js","sourceRoot":"","sources":["../../src/x402/delegation-api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAmF3D;;GAEG;AACH,MAAM,OAAO,aAAc,SAAQ,eAAe;IAChD,MAAM,CAAC,WAAW,CAAC,OAAuB;QACxC,OAAO,IAAI,aAAa,CAAC,OAAO,CAAC,CAAA;IACnC,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,kBAAkB,CAAC,OAAqB;QAC5C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,yBAAyB,EAAE,IAAI,CAAC,WAAW,CA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AO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,aAAa;gBAAE,MAAM,KAAK,CAAA;YAC/C,MAAM,aAAa,CAAC,QAAQ,CAC1B,uBAAuB,MAAM,KAAK,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAC3F,CAAA;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Delegation API for managing payment delegations (crypto and card schemes).\n *\n * Provides access to the user's enrolled payment methods and delegations\n * for use with the nvm:erc4337 and nvm:card-delegation x402 schemes.\n */\n\nimport { BasePaymentsAPI } from '../api/base-payments.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { CreateDelegationPayload, CreateDelegationResponse, PaymentOptions } from '../common/types.js'\n\n/**\n * Summary of a user's enrolled payment method.\n */\nexport interface PaymentMethodSummary {\n /** Payment method ID (Stripe 'pm_...' or Braintree vault token) */\n id: string\n /** Payment method type (e.g., 'card', 'paypal') */\n type: string\n /** Card brand (e.g., 'visa', 'mastercard') or payment method type ('paypal', 'venmo') */\n brand: string\n /** Last 4 digits (cards) or email/username (PayPal/Venmo) */\n last4: string\n /** Expiration month (0 for non-card methods) */\n expMonth: number\n /** Expiration year (0 for non-card methods) */\n expYear: number\n /** Human-readable alias, if set */\n alias?: string | null\n /** Payment provider: 'stripe' or 'braintree' */\n provider?: string\n /** Current status ('Active' or 'Revoked') */\n status?: string\n /** NVM API Key IDs allowed to use this payment method, or null if unrestricted */\n allowedApiKeyIds?: string[] | null\n}\n\n/**\n * Summary of a delegation (card or crypto spending).\n */\nexport interface DelegationSummary {\n delegationId: string\n provider: string\n providerPaymentMethodId: string\n status: string\n spendingLimitCents: string\n amountSpentCents: string\n remainingBudgetCents: string\n currency: string\n transactionCount: number\n expiresAt: string\n createdAt: string\n apiKeyId: string | null\n}\n\n/**\n * Paginated list of delegations returned by the API.\n */\nexport interface DelegationListResponse {\n delegations: DelegationSummary[]\n totalResults: number\n page: number\n offset: number\n}\n\n/**\n * Summary of an agent's purchasing power via card delegations.\n */\nexport interface PurchasingPower {\n cards: PaymentMethodSummary[]\n delegations: DelegationSummary[]\n totalRemainingBudgetCents: number\n currency: string\n}\n\n/**\n * DTO for updating a payment method's alias and allowed API keys.\n */\nexport interface UpdatePaymentMethodDto {\n alias?: string\n allowedApiKeyIds?: string[] | null\n}\n\n/**\n * Options for listing payment methods or delegations.\n */\nexport interface ListOptions {\n /** When true, return only items accessible to the requesting API key */\n accessible?: boolean\n}\n\n/**\n * API for managing payment methods and delegations (card and crypto).\n */\nexport class DelegationAPI extends BasePaymentsAPI {\n static getInstance(options: PaymentOptions): DelegationAPI {\n return new DelegationAPI(options)\n }\n\n /**\n * List the user's enrolled payment methods for card delegation.\n * When `accessible: true`, only cards accessible to the requesting API key are returned.\n */\n async listPaymentMethods(options?: ListOptions): Promise<PaymentMethodSummary[]> {\n const url = new URL('/api/v1/payment-methods', this.environment.backend)\n if (options?.accessible) url.searchParams.set('accessible', 'true')\n return this.fetchJSON(url, 'GET', 'list payment methods')\n }\n\n /**\n * List the user's existing delegations.\n * When `accessible: true`, only usable delegations (Active, non-expired, with budget) are returned.\n */\n async listDelegations(options?: ListOptions): Promise<DelegationListResponse> {\n const url = new URL('/api/v1/delegation', this.environment.backend)\n if (options?.accessible) url.searchParams.set('accessible', 'true')\n return this.fetchJSON(url, 'GET', 'list delegations')\n }\n\n /**\n * Get the agent's purchasing power — accessible cards, active delegations,\n * and combined remaining budget.\n */\n async getPurchasingPower(): Promise<PurchasingPower> {\n const accessible = { accessible: true } satisfies ListOptions\n const [cards, { delegations }] = await Promise.all([\n this.listPaymentMethods(accessible),\n this.listDelegations(accessible),\n ])\n\n const totalRemainingBudgetCents = delegations.reduce(\n (sum, d) => sum + (parseInt(d.remainingBudgetCents, 10) || 0),\n 0,\n )\n\n return {\n cards,\n delegations,\n totalRemainingBudgetCents,\n currency: delegations[0]?.currency ?? 'usd',\n }\n }\n\n /**\n * Create a new delegation for either stripe or erc4337 provider.\n *\n * @param payload - The delegation creation parameters\n * @returns The created delegation ID (and token for card delegations)\n */\n async createDelegation(payload: CreateDelegationPayload): Promise<CreateDelegationResponse> {\n const url = new URL('/api/v1/delegation/create', this.environment.backend)\n return this.fetchJSON(url, 'POST', 'create delegation', payload)\n }\n\n /**\n * Update a payment method's alias and/or allowed API keys.\n */\n async updatePaymentMethod(\n paymentMethodId: string,\n dto: UpdatePaymentMethodDto,\n ): Promise<PaymentMethodSummary> {\n const url = new URL(`/api/v1/payment-methods/${paymentMethodId}`, this.environment.backend)\n return this.fetchJSON(url, 'PATCH', 'update payment method', dto)\n }\n\n // --- Private helpers ---\n\n private async fetchJSON<T>(\n url: URL,\n method: string,\n action: string,\n body?: unknown,\n ): Promise<T> {\n const options = this.getBackendHTTPOptions(method, body)\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let msg = `Failed to ${action}`\n try {\n const err = await response.json()\n msg = err.message || msg\n } catch {\n // use default\n }\n throw PaymentsError.internal(`${msg} (HTTP ${response.status})`)\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) throw error\n throw PaymentsError.internal(\n `Network error while ${action}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n}\n"]}
@@ -69,6 +69,10 @@ export interface RouteConfig {
69
69
  network?: string;
70
70
  /** x402 scheme override (auto-detected from plan metadata if omitted) */
71
71
  scheme?: X402SchemeType;
72
+ /** Human-readable description of the protected resource */
73
+ description?: string;
74
+ /** Expected response MIME type (e.g., "application/json") */
75
+ mimeType?: string;
72
76
  }
73
77
  /**
74
78
  * Route configuration map: "METHOD \/path" -> RouteConfig
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../../src/x402/express/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAEH,OAAO,KAAK,EAAE,OAAO,EA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AAkD;IAClD,cAAc,CAAC,EAAE,MAAM,CAAA;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IAC/B,gDAAgD;IAChD,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,KAAK,IAAI,CAAA;IACpE,sCAAsC;IACtC,cAAc,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,eAAe,EAAE,mBAAmB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7F;;;OAGG;IACH,aAAa,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,YAAY,EAAE,uBAAuB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7F,8CAA8C;IAC9C,aAAa,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC7F;AAyGD,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,cAAc,EACtB,OAAO,GAAE,wBAA6B,GACrC,iBAAiB,CAoLnB;AAED,eAAe,iBAAiB,CAAA"}
@@ -45,7 +45,7 @@
45
45
  * })
46
46
  * ```
47
47
  */
48
- import { buildPaymentRequired, resolveScheme, } from '../facilitator-api.js';
48
+ import { buildPaymentRequired, resolveNetwork, resolveScheme, } from '../facilitator-api.js';
49
49
  /**
50
50
  * x402 HTTP Transport header names (v2 spec)
51
51
  * @see https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md
@@ -159,15 +159,18 @@ export function paymentMiddleware(payments, routes, options = {}) {
159
159
  next();
160
160
  return;
161
161
  }
162
- const { planId, credits = 1, agentId, network, scheme: explicitScheme } = routeConfig;
163
- // Resolve scheme from plan metadata (cached) or explicit override
162
+ const { planId, credits = 1, agentId, network, scheme: explicitScheme, description, mimeType, } = routeConfig;
163
+ // Resolve scheme and network from plan metadata (cached) or explicit overrides
164
164
  const scheme = await resolveScheme(payments, planId, explicitScheme);
165
+ const resolvedNetwork = await resolveNetwork(payments, planId, network);
165
166
  // Build payment required object (needed for both error responses and verification)
166
167
  const paymentRequired = buildPaymentRequired(planId, {
167
168
  endpoint: req.originalUrl || req.url,
168
169
  agentId,
169
170
  httpVerb: req.method,
170
- network,
171
+ network: resolvedNetwork,
172
+ description,
173
+ mimeType,
171
174
  scheme,
172
175
  environment: payments.getEnvironmentName(),
173
176
  });
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/x402/express/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAYH,OAAO,EACL,oBAAoB,EACpB,aAAa,GAGd,MAAM,uBAAuB,CAAA;AAuB9B;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,gDAAgD;IAChD,iBAAiB,EAAE,mBAAmB;IACtC,mEAAmE;IACnE,gBAAgB,EAAE,kBAAkB;IACpC,sEAAsE;IACtE,gBAAgB,EAAE,kBAAkB;CAC5B,CAAA;AA2CV;;GAEG;AACH,MAAM,qBAAqB,GAAG,CAAC,YAAY,CAAC,iBAAiB,CAAC,CAAA;AAE9D;;;GAGG;AACH,SAAS,YAAY,CAAC,GAAY,EAAE,WAA8B;IAChE,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAA;IAExE,KAAK,MAAM,UAAU,IAAI,OAAO,EAAE,CAAC;QACjC,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,C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,CAAC;gBACf,IAAI,cAAc,EAAE,CAAC;oBACnB,cAAc,CAAC,KAAc,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;oBACxC,OAAM;gBACR,CAAC;gBACD,mBAAmB,CACjB,GAAG,EACH,eAAe,EACf,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,6BAA6B,CACvE,CAAA;YACH,CAAC;QACH,CAAC,CAAA;QAED,4CAA4C;QAC5C,aAAa,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IAC7B,CAAC,CAAA;AACH,CAAC;AAED,eAAe,iBAAiB,CAAA","sourcesContent":["/**\n * Express middleware for Nevermined payment protection using the x402 protocol.\n *\n * This middleware provides a simple way to protect Express routes with\n * Nevermined payment verification and settlement.\n *\n * ## x402 HTTP Transport Headers\n *\n * Following the x402 spec (https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md):\n *\n * - **Client → Server**: `payment-signature` header with base64-encoded token\n * - **Server → Client (402)**: `payment-required` header with base64-encoded PaymentRequired\n * - **Server → Client (success)**: `payment-response` header with settlement receipt\n *\n * @example\n * ```typescript\n * import express from 'express'\n * import { Payments } from '@nevermined-io/payments'\n * import { paymentMiddleware } from '@nevermined-io/payments/express'\n *\n * const app = express()\n * const payments = Payments.getInstance({ nvmApiKey: '...', environment: 'testing' })\n *\n * // Protect routes with payment middleware\n * app.use(paymentMiddleware(payments, {\n * 'POST /ask': { planId: '123', credits: 1 },\n * 'POST /generate': { planId: '123', credits: 5 },\n * }))\n *\n * // Route handlers - no payment logic needed!\n * app.post('/ask', (req, res) => res.json({ answer: '...' }))\n * ```\n *\n * @example Client usage\n * ```typescript\n * const token = await payments.x402.getX402AccessToken(planId)\n *\n * const response = await fetch('/ask', {\n * method: 'POST',\n * headers: {\n * 'Content-Type': 'application/json',\n * 'payment-signature': token.accessToken, // x402 header\n * },\n * body: JSON.stringify({ query: 'Hello!' }),\n * })\n * ```\n */\n\nimport type { Request, Response, NextFunction } from 'express'\n\n/**\n * Express middleware function type.\n * Using explicit signature instead of RequestHandler to avoid type resolution issues\n * when SDK's \\@types/express version differs from consumer's.\n */\nexport type ExpressMiddleware = (req: Request, res: Response, next: NextFunction) => void\nimport type { Payments } from '../../payments.js'\nimport type { StartAgentRequest, X402SchemeType } from '../../common/types.js'\nimport {\n buildPaymentRequired,\n resolveScheme,\n type X402PaymentRequired,\n type VerifyPermissionsResult,\n} from '../facilitator-api.js'\n\n/**\n * Configuration for a protected route\n */\nexport interface RouteConfig {\n /** The Nevermined plan ID that protects this route */\n planId: string\n /** Number of credits to charge for this route (default: 1) */\n credits?: number | ((req: Request, res: Response) => number | Promise<number>)\n /** Optional agent ID */\n agentId?: string\n /** Network identifier (default: auto-derived from scheme) */\n network?: string\n /** x402 scheme override (auto-detected from plan metadata if omitted) */\n scheme?: X402SchemeType\n}\n\n/**\n * Route configuration map: \"METHOD \\/path\" -> RouteConfig\n */\nexport type RouteConfigMap = Record<string, RouteConfig>\n\n/**\n * x402 HTTP Transport header names (v2 spec)\n * @see https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md\n */\nexport const X402_HEADERS = {\n /** Client sends payment token in this header */\n PAYMENT_SIGNATURE: 'payment-signature',\n /** Server sends PaymentRequired in this header (base64-encoded) */\n PAYMENT_REQUIRED: 'payment-required',\n /** Server sends settlement receipt in this header (base64-encoded) */\n PAYMENT_RESPONSE: 'payment-response',\n} as const\n\n/**\n * Payment context attached to the request after verification.\n * Available as `req.paymentContext` in route handlers.\n */\nexport interface PaymentContext {\n /** The x402 access token */\n token: string\n /** The payment required object */\n paymentRequired: X402PaymentRequired\n /** Number of credits to settle */\n creditsToSettle: number\n /** Whether verification was successful */\n verified: boolean\n /** Agent request context for observability (from verification response) */\n agentRequest?: StartAgentRequest\n /** Agent request ID for observability tracking */\n agentRequestId?: string\n}\n\n/**\n * Options for the payment middleware\n */\nexport interface PaymentMiddlewareOptions {\n /**\n * Header name(s) to check for the x402 access token.\n * Default: 'payment-signature' (x402 v2 compliant)\n */\n tokenHeader?: string | string[]\n /** Custom error handler for payment failures */\n onPaymentError?: (error: Error, req: Request, res: Response) => void\n /** Hook called before verification */\n onBeforeVerify?: (req: Request, paymentRequired: X402PaymentRequired) => void | Promise<void>\n /**\n * Hook called after successful verification.\n * Use this to access agentRequest for observability configuration.\n */\n onAfterVerify?: (req: Request, verification: VerifyPermissionsResult) => void | Promise<void>\n /** Hook called after successful settlement */\n onAfterSettle?: (req: Request, creditsUsed: number, result: unknown) => void | Promise<void>\n}\n\n/**\n * Default header for token extraction (x402 v2 compliant)\n */\nconst DEFAULT_TOKEN_HEADERS = [X402_HEADERS.PAYMENT_SIGNATURE]\n\n/**\n * Extract the x402 access token from the request headers.\n * Checks multiple headers in priority order.\n */\nfunction extractToken(req: Request, headerNames: string | string[]): string | null {\n const headers = Array.isArray(headerNames) ? headerNames : [headerNames]\n\n for (const headerName of headers) {\n const header = req.headers[headerName.toLowerCase()]\n if (header && typeof header === 'string') {\n return header\n }\n }\n\n return null\n}\n\n/**\n * Match a request to a route config.\n * Returns the config if found, null otherwise.\n */\nfunction matchRoute(req: Request, routes: RouteConfigMap): RouteConfig | null {\n const method = req.method.toUpperCase()\n const path = req.path\n\n // Try exact match first: \"POST /ask\"\n const exactKey = `${method} ${path}`\n if (routes[exactKey]) {\n return routes[exactKey]\n }\n\n // Try pattern matching with path parameters\n for (const [routeKey, config] of Object.entries(routes)) {\n const [routeMethod, routePath] = routeKey.split(' ')\n if (routeMethod !== method) continue\n\n // Simple pattern matching: /users/:id -> /users/123\n const routeParts = routePath.split('/')\n const pathParts = path.split('/')\n\n if (routeParts.length !== pathParts.length) continue\n\n let match = true\n for (let i = 0; i < routeParts.length; i++) {\n if (routeParts[i].startsWith(':')) continue // Parameter - always matches\n if (routeParts[i] !== pathParts[i]) {\n match = false\n break\n }\n }\n\n if (match) return config\n }\n\n return null\n}\n\n/**\n * Create an Express middleware that protects routes with Nevermined payments.\n *\n * The middleware:\n * 1. Checks if the request matches a protected route\n * 2. Extracts the x402 token from headers\n * 3. Verifies the subscriber has sufficient credits\n * 4. Lets the route handler execute\n * 5. Settles (burns) the credits after successful response\n *\n * @param payments - The Payments instance\n * @param routes - Map of routes to protect: \\{ \"METHOD \\/path\": \\{ planId, credits \\} \\}\n * @param options - Optional middleware configuration\n * @returns Express middleware function\n *\n * @example\n * ```typescript\n * app.use(paymentMiddleware(payments, {\n * 'POST /ask': { planId: PLAN_ID, credits: 1 },\n * 'POST /generate': { planId: PLAN_ID, credits: 5 },\n * 'GET /status/:id': { planId: PLAN_ID, credits: 0 }, // Free but requires auth\n * }))\n * ```\n */\n/**\n * Helper to send a 402 Payment Required response with proper x402 headers.\n */\nfunction sendPaymentRequired(\n res: Response,\n paymentRequired: X402PaymentRequired,\n message: string,\n): void {\n // Base64 encode the PaymentRequired object for the header (per x402 spec)\n const paymentRequiredBase64 = Buffer.from(JSON.stringify(paymentRequired)).toString('base64')\n\n res.status(402).setHeader(X402_HEADERS.PAYMENT_REQUIRED, paymentRequiredBase64).json({\n error: 'Payment Required',\n message,\n })\n}\n\nexport function paymentMiddleware(\n payments: Payments,\n routes: RouteConfigMap,\n options: PaymentMiddlewareOptions = {},\n): ExpressMiddleware {\n const {\n tokenHeader = DEFAULT_TOKEN_HEADERS,\n onPaymentError,\n onBeforeVerify,\n onAfterVerify,\n onAfterSettle,\n } = options\n\n return (req: Request, res: Response, next: NextFunction): void => {\n // Wrap async logic to handle promises properly\n const handleRequest = async (): Promise<void> => {\n // Check if this route requires payment\n const routeConfig = matchRoute(req, routes)\n if (!routeConfig) {\n // Route not protected - pass through\n next()\n return\n }\n\n const { planId, credits = 1, agentId, network, scheme: explicitScheme } = routeConfig\n\n // Resolve scheme from plan metadata (cached) or explicit override\n const scheme = await resolveScheme(payments, planId, explicitScheme)\n\n // Build payment required object (needed for both error responses and verification)\n const paymentRequired = buildPaymentRequired(planId, {\n endpoint: req.originalUrl || req.url,\n agentId,\n httpVerb: req.method,\n network,\n scheme,\n environment: payments.getEnvironmentName(),\n })\n\n // Extract token from headers (x402 v2: payment-signature)\n const token = extractToken(req, tokenHeader)\n if (!token) {\n const error = new Error('Payment required: missing x402 access token')\n if (onPaymentError) {\n onPaymentError(error, req, res)\n return\n }\n sendPaymentRequired(\n res,\n paymentRequired,\n `Missing x402 payment token. Send token in ${X402_HEADERS.PAYMENT_SIGNATURE} header.`,\n )\n return\n }\n\n // Calculate credits to verify\n const creditsToVerify = typeof credits === 'function' ? await credits(req, res) : credits\n\n try {\n // Hook: before verification\n if (onBeforeVerify) {\n await onBeforeVerify(req, paymentRequired)\n }\n\n // Verify permissions\n const verification = await payments.facilitator.verifyPermissions({\n paymentRequired,\n x402AccessToken: token,\n maxAmount: BigInt(creditsToVerify),\n })\n\n if (!verification.isValid) {\n const error = new Error(verification.invalidReason || 'Payment verification failed')\n if (onPaymentError) {\n onPaymentError(error, req, res)\n return\n }\n sendPaymentRequired(\n res,\n paymentRequired,\n verification.invalidReason || 'Insufficient credits or invalid token',\n )\n return\n }\n\n // Hook: after verification (use for observability setup)\n if (onAfterVerify) {\n await onAfterVerify(req, verification)\n }\n\n // Store payment context for settlement and route handler access\n const paymentContext: PaymentContext = {\n token,\n paymentRequired,\n creditsToSettle: creditsToVerify,\n verified: true,\n agentRequest: verification.agentRequest,\n agentRequestId: verification.agentRequest?.agentRequestId || verification.agentRequestId,\n }\n\n // Attach to request for potential use by route handler\n ;(req as Request & { paymentContext?: PaymentContext }).paymentContext = paymentContext\n\n // Override res.json to settle BEFORE sending response\n // This ensures credits are burned and payment-response header is included\n const originalJson = res.json.bind(res)\n res.json = function (body: unknown) {\n // Re-evaluate dynamic credits now that the handler has run and\n // res.locals is populated. For fixed (numeric) credits this is a no-op.\n const settlePromise = (\n typeof credits === 'function'\n ? Promise.resolve(credits(req, res))\n : Promise.resolve(creditsToVerify)\n ).then((creditsToSettle) => {\n // Update payment context so downstream consumers see the actual value\n paymentContext.creditsToSettle = creditsToSettle\n\n // Settle credits before sending response\n // Pass agentRequestId to enable observability updates\n return payments.facilitator\n .settlePermissions({\n paymentRequired,\n x402AccessToken: token,\n maxAmount: BigInt(creditsToSettle),\n agentRequestId: paymentContext.agentRequestId,\n })\n .then((settlement) => {\n // Add settlement response header (base64-encoded per x402 spec)\n const settlementBase64 = Buffer.from(JSON.stringify(settlement)).toString('base64')\n res.setHeader(X402_HEADERS.PAYMENT_RESPONSE, settlementBase64)\n\n // Hook: after settlement\n if (onAfterSettle) {\n return Promise.resolve(onAfterSettle(req, creditsToSettle, settlement)).then(\n () => settlement,\n )\n }\n return settlement\n })\n })\n\n settlePromise\n .catch((settleError) => {\n console.error('Payment settlement failed:', settleError)\n // Still send response even if settlement fails\n })\n .finally(() => {\n // Send the actual response after settlement completes\n originalJson(body)\n })\n\n // Return res for chaining (Express pattern)\n return res\n }\n\n // Continue to route handler\n next()\n } catch (error) {\n if (onPaymentError) {\n onPaymentError(error as Error, req, res)\n return\n }\n sendPaymentRequired(\n res,\n paymentRequired,\n error instanceof Error ? error.message : 'Payment verification failed',\n )\n }\n }\n\n // Execute async handler with error handling\n handleRequest().catch(next)\n }\n}\n\nexport default paymentMiddleware\n"]}
1
+ {"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/x402/express/middleware.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAYH,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,aAAa,GAGd,MAAM,uBAAuB,CAAA;AA2B9B;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,gDAAgD;IAChD,iBAAiB,EAAE,mBAAmB;IACtC,mEAAmE;IACnE,gBAAgB,EAAE,kBAAkB;IACpC,sEAAsE;IACtE,gBAAgB,EAAE,kBAAkB;CAC5B,CAAA;AA2CV;;GAEG;AACH,MAAM,qBAAqB,GAAG,CAAC,YAAY,CAAC,iBAAiB,CAAC,CAAA;AAE9D;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BACnB,CAAC,CAAC,CAAA;oBACN,CAAC,CAAC,CAAA;oBAEF,aAAa;yBACV,KAAK,CAAC,CAAC,WAAW,EAAE,EAAE;wBACrB,OAAO,CAAC,KAAK,CAAC,4BAA4B,EAAE,WAAW,CAAC,CAAA;wBACxD,+CAA+C;oBACjD,CAAC,CAAC;yBACD,OAAO,CAAC,GAAG,EAAE;wBACZ,sDAAsD;wBACtD,YAAY,CAAC,IAAI,CAAC,CAAA;oBACpB,CAAC,CAAC,CAAA;oBAEJ,4CAA4C;oBAC5C,OAAO,GAAG,CAAA;gBACZ,CAAC,CAAA;gBAED,4BAA4B;gBAC5B,IAAI,EAAE,CAAA;YACR,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,cAAc,EAAE,CAAC;oBACnB,cAAc,CAAC,KAAc,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;oBACxC,OAAM;gBACR,CAAC;gBACD,mBAAmB,CACjB,GAAG,EACH,eAAe,EACf,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,6BAA6B,CACvE,CAAA;YACH,CAAC;QACH,CAAC,CAAA;QAED,4CAA4C;QAC5C,aAAa,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IAC7B,CAAC,CAAA;AACH,CAAC;AAED,eAAe,iBAAiB,CAAA","sourcesContent":["/**\n * Express middleware for Nevermined payment protection using the x402 protocol.\n *\n * This middleware provides a simple way to protect Express routes with\n * Nevermined payment verification and settlement.\n *\n * ## x402 HTTP Transport Headers\n *\n * Following the x402 spec (https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md):\n *\n * - **Client → Server**: `payment-signature` header with base64-encoded token\n * - **Server → Client (402)**: `payment-required` header with base64-encoded PaymentRequired\n * - **Server → Client (success)**: `payment-response` header with settlement receipt\n *\n * @example\n * ```typescript\n * import express from 'express'\n * import { Payments } from '@nevermined-io/payments'\n * import { paymentMiddleware } from '@nevermined-io/payments/express'\n *\n * const app = express()\n * const payments = Payments.getInstance({ nvmApiKey: '...', environment: 'testing' })\n *\n * // Protect routes with payment middleware\n * app.use(paymentMiddleware(payments, {\n * 'POST /ask': { planId: '123', credits: 1 },\n * 'POST /generate': { planId: '123', credits: 5 },\n * }))\n *\n * // Route handlers - no payment logic needed!\n * app.post('/ask', (req, res) => res.json({ answer: '...' }))\n * ```\n *\n * @example Client usage\n * ```typescript\n * const token = await payments.x402.getX402AccessToken(planId)\n *\n * const response = await fetch('/ask', {\n * method: 'POST',\n * headers: {\n * 'Content-Type': 'application/json',\n * 'payment-signature': token.accessToken, // x402 header\n * },\n * body: JSON.stringify({ query: 'Hello!' }),\n * })\n * ```\n */\n\nimport type { Request, Response, NextFunction } from 'express'\n\n/**\n * Express middleware function type.\n * Using explicit signature instead of RequestHandler to avoid type resolution issues\n * when SDK's \\@types/express version differs from consumer's.\n */\nexport type ExpressMiddleware = (req: Request, res: Response, next: NextFunction) => void\nimport type { Payments } from '../../payments.js'\nimport type { StartAgentRequest, X402SchemeType } from '../../common/types.js'\nimport {\n buildPaymentRequired,\n resolveNetwork,\n resolveScheme,\n type X402PaymentRequired,\n type VerifyPermissionsResult,\n} from '../facilitator-api.js'\n\n/**\n * Configuration for a protected route\n */\nexport interface RouteConfig {\n /** The Nevermined plan ID that protects this route */\n planId: string\n /** Number of credits to charge for this route (default: 1) */\n credits?: number | ((req: Request, res: Response) => number | Promise<number>)\n /** Optional agent ID */\n agentId?: string\n /** Network identifier (default: auto-derived from scheme) */\n network?: string\n /** x402 scheme override (auto-detected from plan metadata if omitted) */\n scheme?: X402SchemeType\n /** Human-readable description of the protected resource */\n description?: string\n /** Expected response MIME type (e.g., \"application/json\") */\n mimeType?: string\n}\n\n/**\n * Route configuration map: \"METHOD \\/path\" -> RouteConfig\n */\nexport type RouteConfigMap = Record<string, RouteConfig>\n\n/**\n * x402 HTTP Transport header names (v2 spec)\n * @see https://github.com/coinbase/x402/blob/main/specs/transports-v2/http.md\n */\nexport const X402_HEADERS = {\n /** Client sends payment token in this header */\n PAYMENT_SIGNATURE: 'payment-signature',\n /** Server sends PaymentRequired in this header (base64-encoded) */\n PAYMENT_REQUIRED: 'payment-required',\n /** Server sends settlement receipt in this header (base64-encoded) */\n PAYMENT_RESPONSE: 'payment-response',\n} as const\n\n/**\n * Payment context attached to the request after verification.\n * Available as `req.paymentContext` in route handlers.\n */\nexport interface PaymentContext {\n /** The x402 access token */\n token: string\n /** The payment required object */\n paymentRequired: X402PaymentRequired\n /** Number of credits to settle */\n creditsToSettle: number\n /** Whether verification was successful */\n verified: boolean\n /** Agent request context for observability (from verification response) */\n agentRequest?: StartAgentRequest\n /** Agent request ID for observability tracking */\n agentRequestId?: string\n}\n\n/**\n * Options for the payment middleware\n */\nexport interface PaymentMiddlewareOptions {\n /**\n * Header name(s) to check for the x402 access token.\n * Default: 'payment-signature' (x402 v2 compliant)\n */\n tokenHeader?: string | string[]\n /** Custom error handler for payment failures */\n onPaymentError?: (error: Error, req: Request, res: Response) => void\n /** Hook called before verification */\n onBeforeVerify?: (req: Request, paymentRequired: X402PaymentRequired) => void | Promise<void>\n /**\n * Hook called after successful verification.\n * Use this to access agentRequest for observability configuration.\n */\n onAfterVerify?: (req: Request, verification: VerifyPermissionsResult) => void | Promise<void>\n /** Hook called after successful settlement */\n onAfterSettle?: (req: Request, creditsUsed: number, result: unknown) => void | Promise<void>\n}\n\n/**\n * Default header for token extraction (x402 v2 compliant)\n */\nconst DEFAULT_TOKEN_HEADERS = [X402_HEADERS.PAYMENT_SIGNATURE]\n\n/**\n * Extract the x402 access token from the request headers.\n * Checks multiple headers in priority order.\n */\nfunction extractToken(req: Request, headerNames: string | string[]): string | null {\n const headers = Array.isArray(headerNames) ? headerNames : [headerNames]\n\n for (const headerName of headers) {\n const header = req.headers[headerName.toLowerCase()]\n if (header && typeof header === 'string') {\n return header\n }\n }\n\n return null\n}\n\n/**\n * Match a request to a route config.\n * Returns the config if found, null otherwise.\n */\nfunction matchRoute(req: Request, routes: RouteConfigMap): RouteConfig | null {\n const method = req.method.toUpperCase()\n const path = req.path\n\n // Try exact match first: \"POST /ask\"\n const exactKey = `${method} ${path}`\n if (routes[exactKey]) {\n return routes[exactKey]\n }\n\n // Try pattern matching with path parameters\n for (const [routeKey, config] of Object.entries(routes)) {\n const [routeMethod, routePath] = routeKey.split(' ')\n if (routeMethod !== method) continue\n\n // Simple pattern matching: /users/:id -> /users/123\n const routeParts = routePath.split('/')\n const pathParts = path.split('/')\n\n if (routeParts.length !== pathParts.length) continue\n\n let match = true\n for (let i = 0; i < routeParts.length; i++) {\n if (routeParts[i].startsWith(':')) continue // Parameter - always matches\n if (routeParts[i] !== pathParts[i]) {\n match = false\n break\n }\n }\n\n if (match) return config\n }\n\n return null\n}\n\n/**\n * Create an Express middleware that protects routes with Nevermined payments.\n *\n * The middleware:\n * 1. Checks if the request matches a protected route\n * 2. Extracts the x402 token from headers\n * 3. Verifies the subscriber has sufficient credits\n * 4. Lets the route handler execute\n * 5. Settles (burns) the credits after successful response\n *\n * @param payments - The Payments instance\n * @param routes - Map of routes to protect: \\{ \"METHOD \\/path\": \\{ planId, credits \\} \\}\n * @param options - Optional middleware configuration\n * @returns Express middleware function\n *\n * @example\n * ```typescript\n * app.use(paymentMiddleware(payments, {\n * 'POST /ask': { planId: PLAN_ID, credits: 1 },\n * 'POST /generate': { planId: PLAN_ID, credits: 5 },\n * 'GET /status/:id': { planId: PLAN_ID, credits: 0 }, // Free but requires auth\n * }))\n * ```\n */\n/**\n * Helper to send a 402 Payment Required response with proper x402 headers.\n */\nfunction sendPaymentRequired(\n res: Response,\n paymentRequired: X402PaymentRequired,\n message: string,\n): void {\n // Base64 encode the PaymentRequired object for the header (per x402 spec)\n const paymentRequiredBase64 = Buffer.from(JSON.stringify(paymentRequired)).toString('base64')\n\n res.status(402).setHeader(X402_HEADERS.PAYMENT_REQUIRED, paymentRequiredBase64).json({\n error: 'Payment Required',\n message,\n })\n}\n\nexport function paymentMiddleware(\n payments: Payments,\n routes: RouteConfigMap,\n options: PaymentMiddlewareOptions = {},\n): ExpressMiddleware {\n const {\n tokenHeader = DEFAULT_TOKEN_HEADERS,\n onPaymentError,\n onBeforeVerify,\n onAfterVerify,\n onAfterSettle,\n } = options\n\n return (req: Request, res: Response, next: NextFunction): void => {\n // Wrap async logic to handle promises properly\n const handleRequest = async (): Promise<void> => {\n // Check if this route requires payment\n const routeConfig = matchRoute(req, routes)\n if (!routeConfig) {\n // Route not protected - pass through\n next()\n return\n }\n\n const {\n planId,\n credits = 1,\n agentId,\n network,\n scheme: explicitScheme,\n description,\n mimeType,\n } = routeConfig\n\n // Resolve scheme and network from plan metadata (cached) or explicit overrides\n const scheme = await resolveScheme(payments, planId, explicitScheme)\n const resolvedNetwork = await resolveNetwork(payments, planId, network)\n\n // Build payment required object (needed for both error responses and verification)\n const paymentRequired = buildPaymentRequired(planId, {\n endpoint: req.originalUrl || req.url,\n agentId,\n httpVerb: req.method,\n network: resolvedNetwork,\n description,\n mimeType,\n scheme,\n environment: payments.getEnvironmentName(),\n })\n\n // Extract token from headers (x402 v2: payment-signature)\n const token = extractToken(req, tokenHeader)\n if (!token) {\n const error = new Error('Payment required: missing x402 access token')\n if (onPaymentError) {\n onPaymentError(error, req, res)\n return\n }\n sendPaymentRequired(\n res,\n paymentRequired,\n `Missing x402 payment token. Send token in ${X402_HEADERS.PAYMENT_SIGNATURE} header.`,\n )\n return\n }\n\n // Calculate credits to verify\n const creditsToVerify = typeof credits === 'function' ? await credits(req, res) : credits\n\n try {\n // Hook: before verification\n if (onBeforeVerify) {\n await onBeforeVerify(req, paymentRequired)\n }\n\n // Verify permissions\n const verification = await payments.facilitator.verifyPermissions({\n paymentRequired,\n x402AccessToken: token,\n maxAmount: BigInt(creditsToVerify),\n })\n\n if (!verification.isValid) {\n const error = new Error(verification.invalidReason || 'Payment verification failed')\n if (onPaymentError) {\n onPaymentError(error, req, res)\n return\n }\n sendPaymentRequired(\n res,\n paymentRequired,\n verification.invalidReason || 'Insufficient credits or invalid token',\n )\n return\n }\n\n // Hook: after verification (use for observability setup)\n if (onAfterVerify) {\n await onAfterVerify(req, verification)\n }\n\n // Store payment context for settlement and route handler access\n const paymentContext: PaymentContext = {\n token,\n paymentRequired,\n creditsToSettle: creditsToVerify,\n verified: true,\n agentRequest: verification.agentRequest,\n agentRequestId: verification.agentRequest?.agentRequestId || verification.agentRequestId,\n }\n\n // Attach to request for potential use by route handler\n ;(req as Request & { paymentContext?: PaymentContext }).paymentContext = paymentContext\n\n // Override res.json to settle BEFORE sending response\n // This ensures credits are burned and payment-response header is included\n const originalJson = res.json.bind(res)\n res.json = function (body: unknown) {\n // Re-evaluate dynamic credits now that the handler has run and\n // res.locals is populated. For fixed (numeric) credits this is a no-op.\n const settlePromise = (\n typeof credits === 'function'\n ? Promise.resolve(credits(req, res))\n : Promise.resolve(creditsToVerify)\n ).then((creditsToSettle) => {\n // Update payment context so downstream consumers see the actual value\n paymentContext.creditsToSettle = creditsToSettle\n\n // Settle credits before sending response\n // Pass agentRequestId to enable observability updates\n return payments.facilitator\n .settlePermissions({\n paymentRequired,\n x402AccessToken: token,\n maxAmount: BigInt(creditsToSettle),\n agentRequestId: paymentContext.agentRequestId,\n })\n .then((settlement) => {\n // Add settlement response header (base64-encoded per x402 spec)\n const settlementBase64 = Buffer.from(JSON.stringify(settlement)).toString('base64')\n res.setHeader(X402_HEADERS.PAYMENT_RESPONSE, settlementBase64)\n\n // Hook: after settlement\n if (onAfterSettle) {\n return Promise.resolve(onAfterSettle(req, creditsToSettle, settlement)).then(\n () => settlement,\n )\n }\n return settlement\n })\n })\n\n settlePromise\n .catch((settleError) => {\n console.error('Payment settlement failed:', settleError)\n // Still send response even if settlement fails\n })\n .finally(() => {\n // Send the actual response after settlement completes\n originalJson(body)\n })\n\n // Return res for chaining (Express pattern)\n return res\n }\n\n // Continue to route handler\n next()\n } catch (error) {\n if (onPaymentError) {\n onPaymentError(error as Error, req, res)\n return\n }\n sendPaymentRequired(\n res,\n paymentRequired,\n error instanceof Error ? error.message : 'Payment verification failed',\n )\n }\n }\n\n // Execute async handler with error handling\n handleRequest().catch(next)\n }\n}\n\nexport default paymentMiddleware\n"]}
@@ -136,6 +136,8 @@ export interface VerifyPermissionsResult {
136
136
  invalidReason?: string;
137
137
  /** Address of the payer's wallet */
138
138
  payer?: string;
139
+ /** Network identifier (e.g., 'stripe', 'braintree', 'eip155:84532') */
140
+ network?: string;
139
141
  /** Agent request ID for observability tracking (Nevermined extension) */
140
142
  agentRequestId?: string;
141
143
  /** URL pattern that matched the endpoint (Nevermined extension) */
@@ -215,9 +217,16 @@ export declare function buildPaymentRequired(planId: string, options?: {
215
217
  httpVerb?: string;
216
218
  network?: string;
217
219
  description?: string;
220
+ mimeType?: string;
218
221
  scheme?: X402SchemeType;
219
222
  environment?: EnvironmentName;
220
223
  }): X402PaymentRequired;
224
+ /**
225
+ * Resolve the network for a plan from its fiatPaymentProvider metadata.
226
+ * For card-delegation plans, returns the provider ('stripe' or 'braintree').
227
+ * Returns undefined for crypto plans.
228
+ */
229
+ export declare function resolveNetwork(payments: Payments, planId: string, explicitNetwork?: string): Promise<string | undefined>;
221
230
  /**
222
231
  * Resolve the x402 scheme for a plan by fetching plan metadata (cached).
223
232
  * Used in callsites that don't have a token to extract scheme from
@@ -1 +1 @@
1
- {"version":3,"file":"facilitator-api.d.ts","sourceRoot":"","sources":["../../src/x402/facilitator-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAGzD,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,cAAc,EAAqB,MAAM,oBAAoB,CAAA;AACzG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAC9C,OAAO,KAAK,EAAE,mB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