@nevermined-io/payments 1.12.0 → 1.14.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.
- package/README.md +33 -0
- package/dist/a2a/clientRegistry.d.ts +10 -1
- package/dist/a2a/clientRegistry.d.ts.map +1 -1
- package/dist/a2a/clientRegistry.js +13 -4
- package/dist/a2a/clientRegistry.js.map +1 -1
- package/dist/a2a/paymentsClient.d.ts +60 -3
- package/dist/a2a/paymentsClient.d.ts.map +1 -1
- package/dist/a2a/paymentsClient.js +129 -8
- package/dist/a2a/paymentsClient.js.map +1 -1
- package/dist/a2a/paymentsRequestHandler.d.ts +5 -1
- package/dist/a2a/paymentsRequestHandler.d.ts.map +1 -1
- package/dist/a2a/paymentsRequestHandler.js +156 -13
- package/dist/a2a/paymentsRequestHandler.js.map +1 -1
- package/dist/a2a/types.d.ts +30 -0
- package/dist/a2a/types.d.ts.map +1 -1
- package/dist/a2a/types.js.map +1 -1
- package/dist/api/agents-api.d.ts +4 -3
- package/dist/api/agents-api.d.ts.map +1 -1
- package/dist/api/agents-api.js +7 -4
- package/dist/api/agents-api.js.map +1 -1
- package/dist/api/base-payments.d.ts +7 -2
- package/dist/api/base-payments.d.ts.map +1 -1
- package/dist/api/base-payments.js +15 -8
- package/dist/api/base-payments.js.map +1 -1
- package/dist/api/nvm-api.d.ts +5 -5
- package/dist/api/observability-api/types.d.ts +34 -6
- package/dist/api/observability-api/types.d.ts.map +1 -1
- package/dist/api/observability-api/types.js.map +1 -1
- package/dist/api/plans-api.d.ts +15 -12
- package/dist/api/plans-api.d.ts.map +1 -1
- package/dist/api/plans-api.js +17 -14
- package/dist/api/plans-api.js.map +1 -1
- package/dist/api/query-api.d.ts +1 -1
- package/dist/common/types.d.ts +175 -18
- package/dist/common/types.d.ts.map +1 -1
- package/dist/common/types.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/mcp/core/paywall.d.ts.map +1 -1
- package/dist/mcp/core/paywall.js +69 -8
- package/dist/mcp/core/paywall.js.map +1 -1
- package/dist/mcp/http/index.d.ts +1 -1
- package/dist/mcp/http/index.d.ts.map +1 -1
- package/dist/mcp/http/index.js +1 -1
- package/dist/mcp/http/index.js.map +1 -1
- package/dist/mcp/http/oauth-metadata.d.ts +32 -0
- package/dist/mcp/http/oauth-metadata.d.ts.map +1 -1
- package/dist/mcp/http/oauth-metadata.js +329 -34
- package/dist/mcp/http/oauth-metadata.js.map +1 -1
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/types/http.types.d.ts +38 -3
- package/dist/mcp/types/http.types.d.ts.map +1 -1
- package/dist/mcp/types/http.types.js.map +1 -1
- package/dist/mcp/types/paywall.types.d.ts +19 -3
- package/dist/mcp/types/paywall.types.d.ts.map +1 -1
- package/dist/mcp/types/paywall.types.js.map +1 -1
- package/dist/mpp/fetch.d.ts +8 -3
- package/dist/mpp/fetch.d.ts.map +1 -1
- package/dist/mpp/fetch.js +6 -0
- package/dist/mpp/fetch.js.map +1 -1
- package/dist/mpp/mpp-api.d.ts +11 -5
- package/dist/mpp/mpp-api.d.ts.map +1 -1
- package/dist/mpp/mpp-api.js +10 -3
- package/dist/mpp/mpp-api.js.map +1 -1
- package/dist/payments.d.ts.map +1 -1
- package/dist/x402/delegation-api.d.ts +5 -17
- package/dist/x402/delegation-api.d.ts.map +1 -1
- package/dist/x402/delegation-api.js +2 -2
- package/dist/x402/delegation-api.js.map +1 -1
- package/dist/x402/express/middleware.d.ts.map +1 -1
- package/dist/x402/express/middleware.js +98 -1
- package/dist/x402/express/middleware.js.map +1 -1
- package/dist/x402/facilitator-api.d.ts +90 -7
- package/dist/x402/facilitator-api.d.ts.map +1 -1
- package/dist/x402/facilitator-api.js +64 -3
- package/dist/x402/facilitator-api.js.map +1 -1
- package/dist/x402/index.d.ts +3 -2
- package/dist/x402/index.d.ts.map +1 -1
- package/dist/x402/index.js +1 -0
- package/dist/x402/index.js.map +1 -1
- package/dist/x402/token-request.d.ts +8 -0
- package/dist/x402/token-request.d.ts.map +1 -1
- package/dist/x402/token-request.js +101 -1
- package/dist/x402/token-request.js.map +1 -1
- package/dist/x402/token-version.d.ts +97 -0
- package/dist/x402/token-version.d.ts.map +1 -0
- package/dist/x402/token-version.js +127 -0
- package/dist/x402/token-version.js.map +1 -0
- package/dist/x402/token.d.ts +33 -2
- package/dist/x402/token.d.ts.map +1 -1
- package/dist/x402/token.js +47 -2
- package/dist/x402/token.js.map +1 -1
- package/package.json +22 -13
package/dist/common/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"AA2KA;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,aAIX;AAJD,WAAY,aAAa;IACvB,+DAAW,CAAA;IACX,yEAAgB,CAAA;IAChB,iFAAoB,CAAA;AACtB,CAAC,EAJW,aAAa,KAAb,aAAa,QAIxB;AAED;;;;GAIG;AACH,MAAM,CAAN,IAAY,QAKX;AALD,WAAY,QAAQ;IAClB,uBAAW,CAAA;IACX,uBAAW,CAAA;IACX,yBAAa,CAAA;IACb,yBAAa,CAAA;AACf,CAAC,EALW,QAAQ,KAAR,QAAQ,QAKnB;AAED,sDAAsD;AACtD,MAAM,CAAC,MAAM,kBAAkB,GAAY,4CAA4C,CAAA;AACvF,+DAA+D;AAC/D,MAAM,CAAC,MAAM,0BAA0B,GAAY,4CAA4C,CAAA;AAE/F;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,+DAAS,CAAA;IACT,uDAAK,CAAA;IACL,2DAAO,CAAA;AACT,CAAC,EAJW,eAAe,KAAf,eAAe,QAI1B;AAED;;;;;;;GAOG;AACH,MAAM,CAA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AA;IACjB,sCAAmB,CAAA;AACrB,CAAC,EAJW,eAAe,KAAf,eAAe,QAI1B;AA+CD;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAmC;IAClE,aAAa,EAAE,cAAc;IAC7B,qBAAqB,EAAE,QAAQ;CAChC,CAAA;AAED;;GAEG;AACH,MAAM,sBAAsB,GAA2B;IACrD,OAAO,EAAE,cAAc,EAAE,eAAe;IACxC,eAAe,EAAE,cAAc,EAAE,eAAe;IAChD,IAAI,EAAE,aAAa,EAAE,eAAe;IACpC,YAAY,EAAE,aAAa,EAAE,eAAe;CAC7C,CAAA;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAsB,EAAE,WAA6B;IACrF,IAAI,MAAM,KAAK,aAAa,IAAI,WAAW,EAAE,CAAC;QAC5C,OAAO,sBAAsB,CAAC,WAAW,CAAC,IAAI,cAAc,CAAA;IAC9D,CAAC;IACD,OAAO,oBAAoB,CAAC,MAAM,CAAC,CAAA;AACrC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,CAAU;IACtC,OAAO,CAAC,KAAK,aAAa,IAAI,CAAC,KAAK,qBAAqB,CAAA;AAC3D,CAAC","sourcesContent":["import { EnvironmentName } from '../environments.js'\n\n/**\n * The payment scheme to use.\n * - 'nvm' (default): Nevermined-issued x402 access tokens covering both\n * credit-based ERC-4337 payments and fiat card delegations (Stripe,\n * Braintree, Visa).\n */\nexport type PaymentScheme = 'nvm'\n\nexport interface PaymentOptions {\n /**\n * The Nevermined environment to connect to.\n *\n * @deprecated The environment is now derived from the NVM API key prefix\n * (`<prefix>:<jwt>`), so this option is no longer required. It is still\n * accepted for backward compatibility and as a fallback when the key prefix\n * is unrecognized (e.g. local/custom development), but when the prefix maps\n * to a known environment the key wins and this option is ignored (a one-time\n * deprecation warning is emitted). It will be removed in a future release.\n */\n environment?: EnvironmentName\n\n /**\n * The Nevermined API Key. This key identify your user and is required to interact with the Nevermined API.\n * You can get your API key by logging in to the Nevermined App.\n * @see https://nevermined.ai/docs/tutorials/integration/nvm-api-keys\n */\n nvmApiKey: string\n\n /**\n * The payment scheme to use. Defaults to 'nvm'.\n */\n scheme?: PaymentScheme\n\n /**\n * The URL to return to the app after a successful login.\n */\n returnUrl?: string\n\n /**\n * The app id. This attribute is optional and helps to associate assets registered into Nevermined with a common identifier.\n */\n appId?: string\n\n /**\n * Pins the Nevermined backend API version (MAJOR.MINOR) sent with every\n * request via the `Nevermined-Version` header. Defaults to\n * {@link LOCKED_API_VERSION} — the backend contract this SDK release is\n * built and tested against. Override only to deliberately target a\n * different backend contract.\n *\n * @see https://nevermined.ai/docs/development-guide/api-versioning\n */\n version?: string\n\n /**\n * Optional organization ID to use as the active workspace for every\n * authenticated backend request. When set, the SDK sends an\n * `X-Current-Org-Id` header so the backend scopes published agents,\n * plans, and other resources to this organization.\n *\n * If omitted the backend falls back to the API key's org tag or to the\n * caller's most-recent active membership (see `CurrentOrgContextGuard`\n * in nvm-monorepo).\n *\n * Override per-call via the `organizationId` option on create methods.\n *\n * @see Payments.setOrganizationId\n */\n organizationId?: string\n}\n\nexport interface Endpoint {\n [verb: string]: string\n}\n\nexport interface ApiResponse<T> {\n success: boolean\n data?: T\n error?: string\n}\n\nexport type Address = `0x${string}`\n\n/**\n * Definition of the price configuration for a Payment Plan\n */\nexport interface PlanPriceConfig {\n /**\n * The address of the token (ERC20 or Native if zero address) for paying the plan\n */\n tokenAddress?: Address\n /**\n * The amounts to be paid for the plan\n */\n amounts: bigint[]\n /**\n * The receivers of the payments of the plan\n */\n receivers: string[]\n /**\n * The address of the smart contract that calculates the price\n */\n contractAddress?: Address\n /**\n * The address of the fee controller contract, if any\n * @remarks if not given, the fee controller is the default one\n */\n feeController?: Address\n /**\n * The address of the external price contract, if any\n */\n externalPriceAddress?: Address\n /**\n * The address of the template contract, if any\n */\n templateAddress?: Address\n /**\n * Whether this is a crypto payment (true) or fiat payment (false)\n */\n isCrypto: boolean\n /**\n * Optional currency for the plan (e.g., 'USD', 'EUR', 'USDC', 'EURC').\n * When omitted, the backend determines the default based on the payment type.\n */\n currency?: Currency | string\n}\n\n/**\n * Definition of the credits configuration for a payment plan\n */\nexport interface PlanCreditsConfig {\n /**\n * Whether the redemption amount is fixed (true) or dynamic (false)\n */\n isRedemptionAmountFixed: boolean\n /**\n * How the credits can be redeemed\n */\n redemptionType: PlanRedemptionType\n /**\n * Whether burns of these credits are mirrored on-chain. When `false`\n * (default) the credits ledger lives in the API's Postgres and burns\n * are recorded off-chain only. When `true` an `OnchainMirrorWorker`\n * replays each off-chain burn to `NFT1155Credits` for audit.\n */\n onchainMirror: boolean\n /**\n * The duration of the credits in seconds\n * @remarks 0 means non-expirable\n */\n durationSecs: bigint\n /**\n * The amount of credits that are granted when purchasing the plan (as string for API)\n */\n amount: bigint\n /**\n * The minimum number of credits redeemed when using the plan\n */\n minAmount: bigint\n /**\n * The maximum number of credits redeemed when using the plan\n */\n maxAmount: bigint\n /**\n * The address of the NFT contract that represents the plan's credits\n */\n nftAddress?: Address\n}\n\n/**\n * Different types of prices that can be configured for a plan\n * @remarks 0 - FIXED_PRICE, 1 - FIXED_FIAT_PRICE, 2 - SMART_CONTRACT_PRICE\n * If FIXED_PRICE it means the plan can be paid in crypto by a fixed amount of a ERC20 or Native token\n * If FIXED_FIAT_PRICE it means the plan can be paid in fiat by a fixed amount (typically USD)\n * If SMART_CONTRACT_PRICE it means the plan can be paid in crypto and the amount to be paid is calculated by a smart contract\n */\nexport enum PlanPriceType {\n FIXED_PRICE,\n FIXED_FIAT_PRICE,\n SMART_CONTRACT_PRICE,\n}\n\n/**\n * Supported currencies for payment plans.\n * - Fiat: USD, EUR (processed via Stripe)\n * - Crypto: USDC, EURC (ERC20 stablecoins on Base)\n */\nexport enum Currency {\n USD = 'USD',\n EUR = 'EUR',\n USDC = 'USDC',\n EURC = 'EURC',\n}\n\n/** EURC token address on Base Mainnet (chain 8453) */\nexport const EURC_TOKEN_ADDRESS: Address = '0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42'\n/** EURC token address on Base Sepolia testnet (chain 84532) */\nexport const EURC_TOKEN_ADDRESS_TESTNET: Address = '0x808456652fdb597867f38412077A9182bf77359F'\n\n/**\n * Different types of credits that can be obtained when purchasing a plan\n * @remarks 0 - EXPIRABLE, 1 - FIXED, 2 - DYNAMIC\n * If EXPIRABLE it means the credits can be used for a fixed amount of time (calculated in seconds)\n * If FIXED it means the credits can be used for a fixed amount of times\n * If DYNAMIC it means the credits can be used but the redemption amount is dynamic\n */\nexport enum PlanCreditsType {\n EXPIRABLE,\n FIXED,\n DYNAMIC,\n}\n\n/**\n * Different types of redemptions criterias that can be used when redeeming credits\n * @remarks 0 - ONLY_GLOBAL_ROLE, 1 - ONLY_OWNER, 2 - ROLE_AND_OWNER\n * If ONLY_GLOBAL_ROLE it means the credits can be redeemed only by an account with the `CREDITS_BURNER_ROLE`\n * If ONLY_OWNER it means the credits can be redeemed only by the owner of the Plan\n * If ONLY_PLAN_ROLE it means the credits can be redeemed by an account with specifics grants for the plan\n * If ONLY_SUBSCRIBER means only the subscriber (the one who holds the credits NFT) can redeem\n */\nexport enum PlanRedemptionType {\n ONLY_GLOBAL_ROLE = 0, // NVM Proxy can burn\n ONLY_OWNER = 1, // Agent can burn\n ONLY_PLAN_ROLE = 2,\n ONLY_SUBSCRIBER = 4, // Subscriber who ordered the plan can redeem\n}\n\nexport interface PlanBalance {\n planId: string\n planName: string\n planType: string\n holderAddress: Address\n balance: bigint\n creditsContract: Address\n isSubscriber: boolean\n pricePerCredit: number\n}\n\nexport interface StartAgentRequest {\n agentRequestId: string\n agentName: string\n agentId: string\n balance: PlanBalance\n urlMatching: string\n verbMatching: string\n batch: boolean\n}\n\nexport interface ValidationAgentRequest {\n balance: PlanBalance\n urlMatching: string\n verbMatching: string\n}\n\nexport interface AgentAccessCredentials {\n accessToken: string\n proxies?: string[]\n}\n\nexport interface SubscriberRequestStatus {\n planId: string\n agentId: string\n isValid: boolean\n code: number\n message?: string\n}\n\nexport interface NvmAPIResult {\n success: boolean\n message?: string\n txHash?: string\n httpStatus?: number\n data?: APIOutputData\n when?: Date\n}\n\nexport interface APIOutputData {\n [key: string]: any\n}\n\nexport interface StripeCheckoutResult {\n stripeCheckoutSessionId: string\n checkoutLink: string\n clientReferenceId: string\n paymentStatus?: string\n linkCreatedAt: number\n linkExpiresAt: number\n}\n\n/**\n * Metadata attributes describing the AI Agent.\n */\nexport interface AgentMetadata {\n /**\n * Name of the Agent\n */\n name: string\n /**\n * Description of the Agent\n */\n description?: string\n /**\n * The author of the Agent (organization or person) that own the Agent.\n */\n author?: string\n /**\n * The author of the Agent (organization or person) that own the Agent.\n */\n license?: string\n /**\n * Tags describing the AI Agent\n */\n tags?: string[]\n /**\n * Some description or instructions about how to integrate the Agent.\n */\n integration?: string\n /**\n * A link to some same usage of the Agent.\n */\n sampleLink?: string\n /**\n * Text describing the API of the Agent.\n */\n apiDescription?: string\n /**\n * The date when the Agent was created.\n */\n dateCreated?: Date\n\n // internalAttributes?: any\n}\n\n/**\n * Metadata attributes describing the Payment Plan.\n */\nexport interface PlanMetadata extends AgentMetadata {\n /**\n * Indicates if a payment plan is a Trial plan.\n * A Trial plan is a plan that allows users to test the AI Agents associated with it typically without any cost.\n * @remarks A Trial plan only can be purchased once by a user.\n */\n isTrialPlan?: boolean\n /**\n * Indicates if a payment plan is limited by credits.\n * If 'time', the plan will be limited by time.\n * If 'credits', the plan will be limited by credits.\n */\n accessLimit?: 'credits' | 'time'\n}\n\n/**\n * It describes the API exposed by an AI Agent.\n * This information is necessary to query the AI Agent and to know which endpoints are available.\n */\nexport interface AgentAPIAttributes {\n /**\n * Optional allowlist of upstream endpoints that require a valid Payment Plan\n * subscription. When provided, the Nevermined platform enforces this list as\n * **Additional Security** (defense-in-depth) on top of any per-route gating\n * the Payments library middleware applies in your agent. When omitted, no\n * route-level allowlist is enforced — your library middleware remains the\n * sole gate.\n */\n endpoints?: Endpoint[]\n /**\n * The list of endpoints of the upstream service that publicly available. The access to these endpoints don't require subscription to the Payment Plan. They are useful to expose documentation, etc.\n */\n openEndpoints?: string[]\n /**\n * Optional URL to a discoverable agent definition (OpenAPI spec, MCP\n * Manifest, or A2A agent card). Stored as metadata for documentation /\n * discovery — not consumed at runtime by the Nevermined platform.\n */\n agentDefinitionUrl?: string\n\n /////// AUTHORIZATION ///////\n\n /**\n * The upstream agent/service authentication type ('none', 'basic', 'bearer' or 'oauth').\n */\n authType?: 'none' | 'basic' | 'oauth' | 'bearer'\n /**\n * The upstream agent/service username for authentication. Only if `authType` is 'basic'.\n */\n username?: string\n /**\n * The upstream agent/service password for authentication. Only if `authType` is 'basic'.\n */\n password?: string\n /**\n * The upstream agent/service bearer token for authentication. Only if `authType` is 'bearer' or 'oauth'.\n */\n token?: string\n}\n\n/**\n * Options for pagination in API requests to the Nevermined API.\n */\nexport class PaginationOptions {\n /**\n * The field to sort the results by.\n * If not provided, the default sorting defined by the API will be applied.\n */\n sortBy?: string\n /**\n * The order in which to sort the results.\n * Default is 'desc' (descending).\n */\n sortOrder: 'asc' | 'desc' = 'desc'\n /**\n * The page number to retrieve.\n * Default is 1.\n */\n page = 1\n /**\n * The number of items per page.\n * Default is 10.\n */\n offset = 10\n\n /**\n * Constructs a new PaginationOptions instance.\n * @param options - Optional initial values for the pagination options.\n */\n constructor(options?: Partial<PaginationOptions>) {\n if (options) {\n this.sortBy = options.sortBy\n this.sortOrder = options.sortOrder || 'desc'\n this.page = options.page || 1\n this.offset = options.offset || 10\n }\n }\n\n /**\n * It returns a string representation of the pagination options\n * @returns A string representation of the pagination options as URL query parameters.\n * This can be used to append to API requests for pagination.\n */\n asQueryParams(): string {\n const params: Record<string, string> = {}\n if (this.sortBy) {\n params.sortBy = this.sortBy\n }\n params.sortOrder = this.sortOrder\n params.page = this.page.toString()\n params.pageSize = this.offset.toString()\n\n return new URLSearchParams(params).toString()\n }\n}\n\n/**\n * Status of an agent task\n */\nexport enum AgentTaskStatus {\n SUCCESS = 'SUCCESS',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n}\n\n/**\n * Data transfer object for tracking agent sub tasks\n */\nexport interface TrackAgentSubTaskDto {\n /**\n * The unique identifier of the agent task\n */\n agentRequestId: string\n\n /**\n * The number of credits burned in this agent sub task (optional)\n * @defaultValue 0\n */\n creditsToRedeem?: number\n\n /**\n * A tag to categorize this agent sub task (optional)\n */\n tag?: string\n\n /**\n * A description of this agent sub task (optional)\n */\n description?: string\n\n /**\n * The status of the agent sub task (optional)\n */\n status?: AgentTaskStatus\n}\n\nexport type SimulationRequestOptions = {\n agentName?: string\n planName?: string\n batch?: boolean\n pricePerCredit?: number\n}\n\n/**\n * x402 payment scheme type.\n * - 'nvm:erc4337': Crypto payments via ERC-4337 smart accounts\n * - 'nvm:card-delegation': Fiat/Stripe card delegation payments\n */\nexport type X402SchemeType = 'nvm:erc4337' | 'nvm:card-delegation'\n\n/**\n * Default network for each x402 scheme (backward-compat: defaults to Base Sepolia).\n */\nexport const X402_SCHEME_NETWORKS: Record<X402SchemeType, string> = {\n 'nvm:erc4337': 'eip155:84532',\n 'nvm:card-delegation': 'stripe',\n}\n\n/**\n * Environment-specific network for the erc4337 scheme.\n */\nconst ERC4337_NETWORK_BY_ENV: Record<string, string> = {\n sandbox: 'eip155:84532', // Base Sepolia\n staging_sandbox: 'eip155:84532', // Base Sepolia\n live: 'eip155:8453', // Base Mainnet\n staging_live: 'eip155:8453', // Base Mainnet\n}\n\n/**\n * Return the default network for a scheme, accounting for the environment.\n *\n * For `nvm:erc4337`, the network depends on the environment:\n * - sandbox / staging_sandbox → `eip155:84532` (Base Sepolia)\n * - live / staging_live → `eip155:8453` (Base Mainnet)\n *\n * Falls back to `X402_SCHEME_NETWORKS` when no environment is given.\n */\nexport function getDefaultNetwork(scheme: X402SchemeType, environment?: EnvironmentName): string {\n if (scheme === 'nvm:erc4337' && environment) {\n return ERC4337_NETWORK_BY_ENV[environment] ?? 'eip155:84532'\n }\n return X402_SCHEME_NETWORKS[scheme]\n}\n\n/**\n * Type guard to check if a value is a valid x402 scheme type.\n */\nexport function isValidScheme(s: unknown): s is X402SchemeType {\n return s === 'nvm:erc4337' || s === 'nvm:card-delegation'\n}\n\n/**\n * Currency codes accepted for a delegation. Lowercase, mirroring the\n * backend's `@IsIn(['usd','eur','usdc','eurc'])` constraint on\n * `POST /api/v1/delegation/create` and the Python SDK's `DelegationCurrency`.\n * Card providers use `'usd'`/`'eur'`; erc4337 uses `'usdc'`/`'eurc'`.\n */\nexport type DelegationCurrency = 'usd' | 'eur' | 'usdc' | 'eurc'\n\n/**\n * Configuration for delegation-based payments (both crypto and card schemes).\n *\n * The supported flow is **create-first**: create a delegation with\n * {@link DelegationAPI.createDelegation}, then request the access token with\n * `delegationConfig: { delegationId }`.\n *\n * @remarks\n * The inline create-on-the-fly fields (`providerPaymentMethodId`,\n * `spendingLimitCents`, `durationSecs`, `currency`, `merchantAccountId`,\n * `maxTransactions`, `cardId`) are individually deprecated. Calling\n * {@link X402TokenAPI.getX402AccessToken} with a `delegationConfig` that lacks\n * `delegationId` but carries one of those fields emits a runtime deprecation\n * warning; create the delegation first and pass only `delegationId` (optionally\n * `apiKeyId`) here. The interface itself is NOT deprecated — the\n * `{ delegationId }` reuse path is the supported way to configure a token request.\n */\nexport interface DelegationConfig {\n /**\n * PaymentMethod entity UUID — references an enrolled card.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n cardId?: string\n /** Existing delegation UUID to reuse instead of creating a new one. The supported (non-deprecated) path. */\n delegationId?: string\n /**\n * Stripe payment method ID (e.g., 'pm_...'). Required only for new delegations.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n providerPaymentMethodId?: string\n /**\n * Maximum spending limit in cents. Required only for new delegations.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n spendingLimitCents?: number\n /**\n * Duration of the delegation in seconds. Required only for new delegations.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n durationSecs?: number\n /**\n * Currency code (e.g., 'usd' for card providers, 'usdc' for erc4337).\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n currency?: DelegationCurrency\n /**\n * Merchant account ID (Stripe Connect acct_xxx or Braintree merchantId).\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n merchantAccountId?: string\n /**\n * Maximum number of transactions allowed.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n maxTransactions?: number\n /**\n * Plan ID to scope a newly-created delegation to. Optional and additive:\n * delegations are plan-agnostic by default; supplying `planId` opts into a\n * plan-bound delegation. (Visa delegations are always plan-specific and\n * require it server-side.)\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n planId?: string\n /** NVM API Key ID to scope the delegation to. Active (non-deprecated). */\n apiKeyId?: string\n}\n\n/**\n * Payload for creating a new delegation via POST /api/v1/delegation/create.\n */\nexport interface CreateDelegationPayload {\n /** Delegation provider: 'stripe' | 'braintree' | 'visa' for card, 'erc4337' for crypto */\n provider: 'stripe' | 'braintree' | 'visa' | 'erc4337'\n /** Payment method ID from the provider (Stripe 'pm_...', Braintree vault token, or Visa Agentic token id). Required for card providers. */\n providerPaymentMethodId?: string\n /** Maximum spending limit in cents */\n spendingLimitCents: number\n /** Duration of the delegation in seconds */\n durationSecs: number\n /** Currency code (e.g., 'usd' for card providers, 'usdc' for erc4337). Required by the backend — no silent default. */\n currency: DelegationCurrency\n /**\n * Plan ID to scope the delegation to. Optional and additive: delegations are\n * plan-agnostic by default; supplying `planId` opts into a plan-bound\n * delegation. (Visa delegations are always plan-specific and require it.)\n */\n planId?: string\n /** Merchant account ID (Stripe Connect acct_xxx or Braintree merchantId) */\n merchantAccountId?: string\n /** Maximum number of transactions allowed */\n maxTransactions?: number\n /** NVM API Key ID to scope the delegation to */\n apiKeyId?: string\n}\n\n/**\n * Response from creating a delegation.\n */\nexport interface CreateDelegationResponse {\n /** Delegation token (for card delegations) */\n delegationToken?: string\n /** Delegation UUID */\n delegationId: string\n}\n\n/**\n * Options for x402 token generation that control scheme and delegation behavior.\n */\nexport interface X402TokenOptions {\n /** The x402 scheme to use (defaults to 'nvm:erc4337') */\n scheme?: X402SchemeType\n /** Network identifier (auto-derived from scheme if omitted) */\n network?: string\n /** Delegation configuration for both erc4337 and card-delegation schemes */\n delegationConfig?: DelegationConfig\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"AA2KA;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,aAIX;AAJD,WAAY,aAAa;IACvB,+DAAW,CAAA;IACX,yEAAgB,CAAA;IAChB,iFAAoB,CAAA;AACtB,CAAC,EAJW,aAAa,KAAb,aAAa,QAIxB;AAED;;;;GAIG;AACH,MAAM,CAAN,IAAY,QAKX;AALD,WAAY,QAAQ;IAClB,uBAAW,CAAA;IACX,uBAAW,CAAA;IACX,yBAAa,CAAA;IACb,yBAAa,CAAA;AACf,CAAC,EALW,QAAQ,KAAR,QAAQ,QAKnB;AAED,sDAAsD;AACtD,MAAM,CAAC,MAAM,kBAAkB,GAAY,4CAA4C,CAAA;AACvF,+DAA+D;AAC/D,MAAM,CAAC,MAAM,0BAA0B,GAAY,4CAA4C,CAAA;AAE/F;;;;;;GAMG;AACH,MAAM,CAAN,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,+DAAS,CAAA;IACT,uDAAK,CAAA;IACL,2DAAO,CAAA;AACT,CAAC,EAJW,eAAe,KAAf,eAAe,QAI1B;AAED;;;;;;;GAOG;AACH,MAAM,CAAN,IAAY,kBAKX;AALD,WAAY,kBAAkB;IAC5B,mFAAoB,CAAA;IACpB,uEAAc,CAAA;IACd,+EAAkB,CAAA;IAClB,iFAAmB,CAAA;AACrB,CAAC,EALW,kBAAkB,KAAlB,kBAAkB,QAK7B;AAmOD;;GAEG;AACH,MAAM,OAAO,iBA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ACH,MAAM,sBAAsB,GAA2B;IACrD,OAAO,EAAE,cAAc,EAAE,eAAe;IACxC,eAAe,EAAE,cAAc,EAAE,eAAe;IAChD,IAAI,EAAE,aAAa,EAAE,eAAe;IACpC,YAAY,EAAE,aAAa,EAAE,eAAe;CAC7C,CAAA;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAsB,EAAE,WAA6B;IACrF,IAAI,MAAM,KAAK,aAAa,IAAI,WAAW,EAAE,CAAC;QAC5C,OAAO,sBAAsB,CAAC,WAAW,CAAC,IAAI,cAAc,CAAA;IAC9D,CAAC;IACD,OAAO,oBAAoB,CAAC,MAAM,CAAC,CAAA;AACrC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,CAAU;IACtC,OAAO,CAAC,KAAK,aAAa,IAAI,CAAC,KAAK,qBAAqB,CAAA;AAC3D,CAAC","sourcesContent":["import { EnvironmentName } from '../environments.js'\n\n/**\n * The payment scheme to use.\n * - 'nvm' (default): Nevermined-issued x402 access tokens covering both\n * credit-based ERC-4337 payments and fiat card delegations (Stripe,\n * Braintree, Visa).\n */\nexport type PaymentScheme = 'nvm'\n\nexport interface PaymentOptions {\n /**\n * The Nevermined environment to connect to.\n *\n * @deprecated The environment is now derived from the NVM API key prefix\n * (`<prefix>:<jwt>`), so this option is no longer required. It is still\n * accepted for backward compatibility and as a fallback when the key prefix\n * is unrecognized (e.g. local/custom development), but when the prefix maps\n * to a known environment the key wins and this option is ignored (a one-time\n * deprecation warning is emitted). It will be removed in a future release.\n */\n environment?: EnvironmentName\n\n /**\n * The Nevermined API Key. This key identify your user and is required to interact with the Nevermined API.\n * You can get your API key by logging in to the Nevermined App.\n * @see https://nevermined.ai/docs/tutorials/integration/nvm-api-keys\n */\n nvmApiKey: string\n\n /**\n * The payment scheme to use. Defaults to 'nvm'.\n */\n scheme?: PaymentScheme\n\n /**\n * The URL to return to the app after a successful login.\n */\n returnUrl?: string\n\n /**\n * The app id. This attribute is optional and helps to associate assets registered into Nevermined with a common identifier.\n */\n appId?: string\n\n /**\n * Pins the Nevermined backend API version (MAJOR.MINOR) sent with every\n * request via the `Nevermined-Version` header. Defaults to\n * {@link LOCKED_API_VERSION} — the backend contract this SDK release is\n * built and tested against. Override only to deliberately target a\n * different backend contract.\n *\n * @see https://nevermined.ai/docs/development-guide/api-versioning\n */\n version?: string\n\n /**\n * Optional organization ID to use as the active workspace for every\n * authenticated backend request. When set, the SDK sends an\n * `X-Current-Org-Id` header so the backend scopes published agents,\n * plans, and other resources to this organization.\n *\n * If omitted the backend falls back to the API key's org tag or to the\n * caller's most-recent active membership (see `CurrentOrgContextGuard`\n * in nvm-monorepo).\n *\n * Override per-call via the `organizationId` option on create methods.\n *\n * @see Payments.setOrganizationId\n */\n organizationId?: string\n}\n\nexport interface Endpoint {\n [verb: string]: string\n}\n\nexport interface ApiResponse<T> {\n success: boolean\n data?: T\n error?: string\n}\n\nexport type Address = `0x${string}`\n\n/**\n * Definition of the price configuration for a Payment Plan\n */\nexport interface PlanPriceConfig {\n /**\n * The address of the token (ERC20 or Native if zero address) for paying the plan\n */\n tokenAddress?: Address\n /**\n * The amounts to be paid for the plan\n */\n amounts: bigint[]\n /**\n * The receivers of the payments of the plan\n */\n receivers: string[]\n /**\n * The address of the smart contract that calculates the price\n */\n contractAddress?: Address\n /**\n * The address of the fee controller contract, if any\n * @remarks if not given, the fee controller is the default one\n */\n feeController?: Address\n /**\n * The address of the external price contract, if any\n */\n externalPriceAddress?: Address\n /**\n * The address of the template contract, if any\n */\n templateAddress?: Address\n /**\n * Whether this is a crypto payment (true) or fiat payment (false)\n */\n isCrypto: boolean\n /**\n * Optional currency for the plan (e.g., 'USD', 'EUR', 'USDC', 'EURC').\n * When omitted, the backend determines the default based on the payment type.\n */\n currency?: Currency | string\n}\n\n/**\n * Definition of the credits configuration for a payment plan\n */\nexport interface PlanCreditsConfig {\n /**\n * Whether the redemption amount is fixed (true) or dynamic (false)\n */\n isRedemptionAmountFixed: boolean\n /**\n * How the credits can be redeemed\n */\n redemptionType: PlanRedemptionType\n /**\n * Whether burns of these credits are mirrored on-chain. When `false`\n * (default) the credits ledger lives in the API's Postgres and burns\n * are recorded off-chain only. When `true` an `OnchainMirrorWorker`\n * replays each off-chain burn to `NFT1155Credits` for audit.\n */\n onchainMirror: boolean\n /**\n * The duration of the credits in seconds\n * @remarks 0 means non-expirable\n */\n durationSecs: bigint\n /**\n * The amount of credits that are granted when purchasing the plan (as string for API)\n */\n amount: bigint\n /**\n * The minimum number of credits redeemed when using the plan\n */\n minAmount: bigint\n /**\n * The maximum number of credits redeemed when using the plan\n */\n maxAmount: bigint\n /**\n * The address of the NFT contract that represents the plan's credits\n */\n nftAddress?: Address\n}\n\n/**\n * Different types of prices that can be configured for a plan\n * @remarks 0 - FIXED_PRICE, 1 - FIXED_FIAT_PRICE, 2 - SMART_CONTRACT_PRICE\n * If FIXED_PRICE it means the plan can be paid in crypto by a fixed amount of a ERC20 or Native token\n * If FIXED_FIAT_PRICE it means the plan can be paid in fiat by a fixed amount (typically USD)\n * If SMART_CONTRACT_PRICE it means the plan can be paid in crypto and the amount to be paid is calculated by a smart contract\n */\nexport enum PlanPriceType {\n FIXED_PRICE,\n FIXED_FIAT_PRICE,\n SMART_CONTRACT_PRICE,\n}\n\n/**\n * Supported currencies for payment plans.\n * - Fiat: USD, EUR (processed via Stripe)\n * - Crypto: USDC, EURC (ERC20 stablecoins on Base)\n */\nexport enum Currency {\n USD = 'USD',\n EUR = 'EUR',\n USDC = 'USDC',\n EURC = 'EURC',\n}\n\n/** EURC token address on Base Mainnet (chain 8453) */\nexport const EURC_TOKEN_ADDRESS: Address = '0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42'\n/** EURC token address on Base Sepolia testnet (chain 84532) */\nexport const EURC_TOKEN_ADDRESS_TESTNET: Address = '0x808456652fdb597867f38412077A9182bf77359F'\n\n/**\n * Different types of credits that can be obtained when purchasing a plan\n * @remarks 0 - EXPIRABLE, 1 - FIXED, 2 - DYNAMIC\n * If EXPIRABLE it means the credits can be used for a fixed amount of time (calculated in seconds)\n * If FIXED it means the credits can be used for a fixed amount of times\n * If DYNAMIC it means the credits can be used but the redemption amount is dynamic\n */\nexport enum PlanCreditsType {\n EXPIRABLE,\n FIXED,\n DYNAMIC,\n}\n\n/**\n * Different types of redemptions criterias that can be used when redeeming credits\n * @remarks 0 - ONLY_GLOBAL_ROLE, 1 - ONLY_OWNER, 2 - ROLE_AND_OWNER\n * If ONLY_GLOBAL_ROLE it means the credits can be redeemed only by an account with the `CREDITS_BURNER_ROLE`\n * If ONLY_OWNER it means the credits can be redeemed only by the owner of the Plan\n * If ONLY_PLAN_ROLE it means the credits can be redeemed by an account with specifics grants for the plan\n * If ONLY_SUBSCRIBER means only the subscriber (the one who holds the credits NFT) can redeem\n */\nexport enum PlanRedemptionType {\n ONLY_GLOBAL_ROLE = 0, // NVM Proxy can burn\n ONLY_OWNER = 1, // Agent can burn\n ONLY_PLAN_ROLE = 2,\n ONLY_SUBSCRIBER = 4, // Subscriber who ordered the plan can redeem\n}\n\nexport interface PlanBalance {\n planId: string\n planName: string\n planType: string\n holderAddress: Address\n /**\n * Credit balance as a DECIMAL STRING, e.g. `'950'` — not a `bigint`.\n *\n * ⚠️ It is a string because that is what the deserializer produces, not as a\n * preference. `PlanBalance` is constructed nowhere in `src/`: it only ever\n * arrives from `getPlanBalance`, which ends in a bare `return response.json()`,\n * and JSON has no bigint. It had been declared `bigint` since 2025-05-26 while the API sent a\n * quoted string, so `balance > 100n` threw `Cannot mix BigInt and other types`\n * in code that typechecked clean, and `typeof balance === 'bigint'` silently\n * took the wrong branch. This reaches sellers as public API — `PlanBalance` is\n * on `req.paymentContext.agentRequest.balance`.\n *\n * The value can exceed `Number.MAX_SAFE_INTEGER`, so do NOT route it through\n * `Number`. For arithmetic, convert explicitly:\n *\n * ```ts\n * BigInt(ctx.agentRequest.balance.balance) > 100n\n * ```\n *\n * The outbound direction already has its counterpart: `jsonReplacer`\n * (`common/helper.ts`) narrows bigints to strings on request bodies. This is\n * the inbound side of the same boundary.\n */\n balance: string\n creditsContract: Address\n isSubscriber: boolean\n pricePerCredit: number\n}\n\nexport interface StartAgentRequest {\n agentRequestId: string\n agentName: string\n agentId: string\n balance: PlanBalance\n urlMatching: string\n verbMatching: string\n batch: boolean\n}\n\nexport interface ValidationAgentRequest {\n balance: PlanBalance\n urlMatching: string\n verbMatching: string\n}\n\nexport interface AgentAccessCredentials {\n accessToken: string\n proxies?: string[]\n}\n\nexport interface SubscriberRequestStatus {\n planId: string\n agentId: string\n isValid: boolean\n code: number\n message?: string\n}\n\nexport interface NvmAPIResult {\n success: boolean\n message?: string\n txHash?: string\n httpStatus?: number\n data?: APIOutputData\n when?: Date\n}\n\nexport interface APIOutputData {\n [key: string]: any\n}\n\n/** Status of a Stripe PaymentIntent. */\nexport type StripePaymentIntentStatus =\n | 'requires_payment_method'\n | 'requires_confirmation'\n | 'requires_action'\n | 'processing'\n | 'requires_capture'\n | 'canceled'\n | 'succeeded'\n\n/**\n * The Stripe PaymentIntent `POST /api/v1/fiat/stripe/payment` creates for a fiat plan,\n * returned by `PlansAPI.orderFiatPlan`. Confirm it client-side with Stripe.js and\n * its `client_secret`. These fields are what callers can rely on; do not depend on\n * any other field of the response.\n */\nexport interface StripePaymentIntent {\n /** PaymentIntent id (`pi_…`) */\n id: string\n /** Secret Stripe.js confirms the payment with. Pass it to Stripe.js only; never log or store it. */\n client_secret: string | null\n /** PaymentIntent status */\n status: StripePaymentIntentStatus\n /** Amount in the currency's smallest unit (e.g. cents) */\n amount: number\n /** Three-letter ISO currency code, lowercase */\n currency: string\n}\n\n/**\n * @deprecated Not returned by any SDK method: `PlansAPI.orderFiatPlan` returns a\n * {@link StripePaymentIntent}.\n */\nexport interface StripeCheckoutResult {\n stripeCheckoutSessionId: string\n checkoutLink: string\n clientReferenceId: string\n paymentStatus?: string\n linkCreatedAt: number\n linkExpiresAt: number\n}\n\n/**\n * Metadata attributes describing the AI Agent.\n */\nexport interface AgentMetadata {\n /**\n * Name of the Agent\n */\n name: string\n /**\n * Description of the Agent\n */\n description?: string\n /**\n * The author of the Agent (organization or person) that own the Agent.\n */\n author?: string\n /**\n * The author of the Agent (organization or person) that own the Agent.\n */\n license?: string\n /**\n * Tags describing the AI Agent\n */\n tags?: string[]\n /**\n * Some description or instructions about how to integrate the Agent.\n */\n integration?: string\n /**\n * A link to some same usage of the Agent.\n */\n sampleLink?: string\n /**\n * Text describing the API of the Agent.\n */\n apiDescription?: string\n /**\n * The date when the Agent was created.\n */\n dateCreated?: Date\n\n // internalAttributes?: any\n}\n\n/**\n * Metadata attributes describing the Payment Plan.\n */\nexport interface PlanMetadata extends AgentMetadata {\n /**\n * Indicates if a payment plan is a Trial plan.\n * A Trial plan is a plan that allows users to test the AI Agents associated with it typically without any cost.\n * @remarks A Trial plan only can be purchased once by a user.\n */\n isTrialPlan?: boolean\n /**\n * Indicates if a payment plan is limited by credits.\n * If 'time', the plan will be limited by time.\n * If 'credits', the plan will be limited by credits.\n */\n accessLimit?: 'credits' | 'time'\n}\n\n/**\n * It describes the API exposed by an AI Agent.\n * This information is necessary to query the AI Agent and to know which endpoints are available.\n */\nexport interface AgentAPIAttributes {\n /**\n * Optional allowlist of upstream endpoints that require a valid Payment Plan\n * subscription. When provided, the Nevermined platform enforces this list as\n * **Additional Security** (defense-in-depth) on top of any per-route gating\n * the Payments library middleware applies in your agent. When omitted, no\n * route-level allowlist is enforced — your library middleware remains the\n * sole gate.\n */\n endpoints?: Endpoint[]\n /**\n * The list of endpoints of the upstream service that publicly available. The access to these endpoints don't require subscription to the Payment Plan. They are useful to expose documentation, etc.\n */\n openEndpoints?: string[]\n /**\n * Optional URL to a discoverable agent definition (OpenAPI spec, MCP\n * Manifest, or A2A agent card). Stored as metadata for documentation /\n * discovery — not consumed at runtime by the Nevermined platform.\n */\n agentDefinitionUrl?: string\n\n /////// AUTHORIZATION ///////\n\n /**\n * The upstream agent/service authentication type ('none', 'basic', 'bearer' or 'oauth').\n */\n authType?: 'none' | 'basic' | 'oauth' | 'bearer'\n /**\n * The upstream agent/service username for authentication. Only if `authType` is 'basic'.\n */\n username?: string\n /**\n * The upstream agent/service password for authentication. Only if `authType` is 'basic'.\n */\n password?: string\n /**\n * The upstream agent/service bearer token for authentication. Only if `authType` is 'bearer' or 'oauth'.\n */\n token?: string\n}\n\n/**\n * Options for pagination in API requests to the Nevermined API.\n */\nexport class PaginationOptions {\n /**\n * The field to sort the results by.\n * If not provided, the default sorting defined by the API will be applied.\n */\n sortBy?: string\n /**\n * The order in which to sort the results.\n * Default is 'desc' (descending).\n */\n sortOrder: 'asc' | 'desc' = 'desc'\n /**\n * The page number to retrieve.\n * Default is 1.\n */\n page = 1\n /**\n * The number of items per page.\n * Default is 10.\n */\n offset = 10\n\n /**\n * Constructs a new PaginationOptions instance.\n * @param options - Optional initial values for the pagination options.\n */\n constructor(options?: Partial<PaginationOptions>) {\n if (options) {\n this.sortBy = options.sortBy\n this.sortOrder = options.sortOrder || 'desc'\n this.page = options.page || 1\n this.offset = options.offset || 10\n }\n }\n\n /**\n * It returns a string representation of the pagination options\n * @returns A string representation of the pagination options as URL query parameters.\n * This can be used to append to API requests for pagination.\n */\n asQueryParams(): string {\n const params: Record<string, string> = {}\n if (this.sortBy) {\n params.sortBy = this.sortBy\n }\n params.sortOrder = this.sortOrder\n params.page = this.page.toString()\n params.pageSize = this.offset.toString()\n\n return new URLSearchParams(params).toString()\n }\n}\n\n/**\n * Status of an agent task\n */\nexport enum AgentTaskStatus {\n SUCCESS = 'SUCCESS',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n}\n\n/**\n * Data transfer object for tracking agent sub tasks\n */\nexport interface TrackAgentSubTaskDto {\n /**\n * The unique identifier of the agent task\n */\n agentRequestId: string\n\n /**\n * The number of credits burned in this agent sub task (optional)\n * @defaultValue 0\n */\n creditsToRedeem?: number\n\n /**\n * A tag to categorize this agent sub task (optional)\n */\n tag?: string\n\n /**\n * A description of this agent sub task (optional)\n */\n description?: string\n\n /**\n * The status of the agent sub task (optional)\n */\n status?: AgentTaskStatus\n}\n\nexport type SimulationRequestOptions = {\n agentName?: string\n planName?: string\n batch?: boolean\n pricePerCredit?: number\n}\n\n/**\n * x402 payment scheme type.\n * - 'nvm:erc4337': Crypto payments via ERC-4337 smart accounts\n * - 'nvm:card-delegation': Fiat/Stripe card delegation payments\n */\nexport type X402SchemeType = 'nvm:erc4337' | 'nvm:card-delegation'\n\n/**\n * Default network for each x402 scheme (backward-compat: defaults to Base Sepolia).\n */\nexport const X402_SCHEME_NETWORKS: Record<X402SchemeType, string> = {\n 'nvm:erc4337': 'eip155:84532',\n 'nvm:card-delegation': 'stripe',\n}\n\n/**\n * Environment-specific network for the erc4337 scheme.\n */\nconst ERC4337_NETWORK_BY_ENV: Record<string, string> = {\n sandbox: 'eip155:84532', // Base Sepolia\n staging_sandbox: 'eip155:84532', // Base Sepolia\n live: 'eip155:8453', // Base Mainnet\n staging_live: 'eip155:8453', // Base Mainnet\n}\n\n/**\n * Return the default network for a scheme, accounting for the environment.\n *\n * For `nvm:erc4337`, the network depends on the environment:\n * - sandbox / staging_sandbox → `eip155:84532` (Base Sepolia)\n * - live / staging_live → `eip155:8453` (Base Mainnet)\n *\n * Falls back to `X402_SCHEME_NETWORKS` when no environment is given.\n */\nexport function getDefaultNetwork(scheme: X402SchemeType, environment?: EnvironmentName): string {\n if (scheme === 'nvm:erc4337' && environment) {\n return ERC4337_NETWORK_BY_ENV[environment] ?? 'eip155:84532'\n }\n return X402_SCHEME_NETWORKS[scheme]\n}\n\n/**\n * Type guard to check if a value is a valid x402 scheme type.\n */\nexport function isValidScheme(s: unknown): s is X402SchemeType {\n return s === 'nvm:erc4337' || s === 'nvm:card-delegation'\n}\n\n/**\n * Currency codes accepted for a delegation. Lowercase, mirroring the\n * backend's `@IsIn(['usd','eur','usdc','eurc'])` constraint on\n * `POST /api/v1/delegation/create` and the Python SDK's `DelegationCurrency`.\n * Card providers use `'usd'`/`'eur'`; erc4337 uses `'usdc'`/`'eurc'`.\n */\nexport type DelegationCurrency = 'usd' | 'eur' | 'usdc' | 'eurc'\n\n/**\n * Configuration for delegation-based payments (both crypto and card schemes).\n *\n * The supported flow is **create-first**: create a delegation with\n * {@link DelegationAPI.createDelegation}, then request the access token with\n * `delegationConfig: { delegationId }`.\n *\n * @remarks\n * The inline create-on-the-fly fields (`providerPaymentMethodId`,\n * `spendingLimitCents`, `durationSecs`, `currency`, `maxTransactions`,\n * `cardId`) are individually deprecated. Calling\n * {@link X402TokenAPI.getX402AccessToken} with a `delegationConfig` that lacks\n * `delegationId` but carries `cardId`, `providerPaymentMethodId`,\n * `spendingLimitCents` or `durationSecs` emits a runtime deprecation warning;\n * create the delegation first and pass only `delegationId` (optionally\n * `apiKeyId`) here. The interface itself is NOT deprecated — the\n * `{ delegationId }` reuse path is the supported way to configure a token request.\n */\nexport interface DelegationConfig {\n /**\n * PaymentMethod entity UUID — references an enrolled card.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n cardId?: string\n /** Existing delegation UUID to reuse instead of creating a new one. The supported (non-deprecated) path. */\n delegationId?: string\n /**\n * Stripe payment method ID (e.g., 'pm_...'). Required only for new delegations.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n providerPaymentMethodId?: string\n /**\n * Maximum spending limit in cents. Required only for new delegations.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n spendingLimitCents?: number\n /**\n * Duration of the delegation in seconds. Required only for new delegations.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n durationSecs?: number\n /**\n * Currency code (e.g., 'usd' for card providers, 'usdc' for erc4337).\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n currency?: DelegationCurrency\n /**\n * Merchant account ID (Stripe Connect acct_…).\n * @deprecated Ignored by the backend (the seller's Connect account is\n * resolved at settle time); drop it.\n */\n merchantAccountId?: string\n /**\n * Maximum number of transactions allowed.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n maxTransactions?: number\n /**\n * Ignored by the backend: an inline-created delegation is always\n * plan-agnostic. To bind a delegation to one plan, create it with\n * `createDelegation({ planId })` and pass its `delegationId`.\n * @deprecated Inline create-on-the-fly. Create the delegation first and pass `delegationId`.\n */\n planId?: string\n /** NVM API Key ID to scope the delegation to. Active (non-deprecated). */\n apiKeyId?: string\n}\n\n/**\n * Card-delegation providers exposed by the SDK. Use this when you want to\n * restrict to card-shape entries only (e.g., filtering the heterogeneous\n * list returned by `DelegationAPI.listPaymentMethods`).\n */\nexport type CardProvider = 'stripe' | 'braintree' | 'visa'\n\n/**\n * All delegation providers, including the crypto path. Matches the\n * server-side union and types {@link CreateDelegationPayload.provider}.\n * `vgs` = a card enrolled through the credit/debit card form: vaulted at VGS\n * and charged through the PSP the paid plan selects. (Visa Agentic cards are\n * `visa`.)\n */\nexport type DelegationProvider = CardProvider | 'vgs' | 'erc4337'\n\n/**\n * Payload for creating a new delegation via POST /api/v1/delegation/create.\n */\nexport interface CreateDelegationPayload {\n /**\n * Delegation provider: 'vgs' for a card enrolled through the credit/debit card form,\n * 'stripe' | 'visa' for the other card rails, 'erc4337' for crypto. 'braintree' is\n * refused at create.\n */\n provider: DelegationProvider\n /** Payment method ID from the provider (the card's 'CRD…' id for 'vgs', Stripe 'pm_...', or Visa Agentic token id). Required for card providers. */\n providerPaymentMethodId?: string\n /** Maximum spending limit in cents */\n spendingLimitCents: number\n /** Duration of the delegation in seconds */\n durationSecs: number\n /** Currency code (e.g., 'usd' for card providers, 'usdc' for erc4337). Required by the backend — no silent default. */\n currency: DelegationCurrency\n /**\n * Plan ID to scope the delegation to. Optional for every provider, and\n * additive: delegations are plan-agnostic by default; supplying `planId` opts\n * into a plan-bound delegation.\n */\n planId?: string\n /**\n * Merchant account ID (Stripe Connect acct_…).\n * @deprecated Ignored by the backend: the seller's Connect account is\n * resolved at settle time, never taken from the caller.\n */\n merchantAccountId?: string\n /** Maximum number of transactions allowed */\n maxTransactions?: number\n /** NVM API Key ID to scope the delegation to */\n apiKeyId?: string\n}\n\n/**\n * Response from creating a delegation.\n */\nexport interface CreateDelegationResponse {\n /** Delegation token (for card delegations) */\n delegationToken?: string\n /** Delegation UUID */\n delegationId: string\n}\n\n/**\n * The protected resource a token is minted for.\n *\n * Load-bearing from token v3 on: `url` is inside the EIP-712 signature, so a\n * v3 token only settles against the seller endpoint it names.\n *\n * Outside the v1/v2 signature, which covers `from` / `sessionKeysProvider` /\n * `sessionKeys` / `planId` only — but **not** inert there: the backend compares\n * this URL against the one the seller advertises in its `paymentRequired`\n * (origin + path; an exact string comparison when either side is not a\n * parseable URL) for **any** token that carries a resource. Binding a token to\n * a URL the seller does not advertise verbatim therefore fails verification\n * with `BCK.X402.0013`. Sellers built on this SDK's `paymentMiddleware`\n * advertise `req.originalUrl` — a **relative** path — so for such a seller bind\n * to that string, not to the absolute URL you fetch. See {@link\n * X402TokenResource.url} for a seller that advertises the absolute form, which\n * this SDK's own A2A server does.\n */\nexport interface X402TokenResource {\n /**\n * The protected resource URL, **as the seller advertises it** — e.g.\n * `/api/v1/tasks` from a `paymentMiddleware` seller, or the absolute\n * `https://seller.example/api/v1/tasks` from one that advertises it that way\n * (this SDK's A2A server does).\n */\n url: string\n /** Human-readable description. */\n description?: string\n /** Expected response MIME type (e.g. `application/json`). */\n mimeType?: string\n}\n\n/**\n * EIP-712 struct version the backend signs the access token under.\n *\n * - `2` — today's default: reusable bearer token, signature covers\n * `[from, sessionKeysProvider, sessionKeys, planId]`.\n * - `3` — appends `agentId`, `resourceUrl`, `httpVerb` and a one-time `nonce`\n * to the signed struct, making the token seller/resource-bound and\n * **single-use**: it is consumed on the first `POST /x402/settle`.\n *\n * Opt-in. Never assume the token you got back is the version you asked for —\n * a backend that predates the v3 struct silently drops the field (its\n * `ValidationPipe` whitelists without `forbidNonWhitelisted`) and mints v2.\n * Read the version off the token with {@link detectAccessTokenVersion}.\n */\nexport type X402TokenVersion = 2 | 3\n\n/**\n * Options accepted by the MPP token mint: everything {@link X402TokenOptions}\n * takes except `tokenVersion`.\n *\n * MPP and x402 stopped sharing a token version ladder (nvm-monorepo#3266). MPP\n * signs one struct and names no version for it, because its single-use unit is\n * the **challenge**, not the token — one MPP access token is presented across\n * many challenges by design, so an x402 v3 per-token nonce would reject every\n * buyer's second challenge. The backend refuses ANY `tokenVersion` on an MPP\n * mint with `BCK.MPP.0007`, `2` included, so the field is omitted from the type\n * rather than accepted and ignored.\n */\nexport type MppTokenOptions = Omit<X402TokenOptions, 'tokenVersion'>\n\n/**\n * Options for x402 token generation that control scheme and delegation behavior.\n */\nexport interface X402TokenOptions {\n /** The x402 scheme to use (defaults to 'nvm:erc4337') */\n scheme?: X402SchemeType\n /** Network identifier (auto-derived from scheme if omitted) */\n network?: string\n /** Delegation configuration for both erc4337 and card-delegation schemes */\n delegationConfig?: DelegationConfig\n /**\n * The protected resource the token is minted for. Signed into a v3 token,\n * which then only settles against this URL. Without it the backend has\n * nothing to bind to and skips endpoint validation, so `tokenVersion: 3`\n * alone yields a single-use token bound to nothing — a supported mode, but\n * not the seller binding.\n *\n * Must be the **exact string the seller advertises**; see\n * {@link X402TokenResource}. Supplying it without `tokenVersion: 3` is\n * **refused**: only a v3 signature covers the binding, while the resource\n * still arms the backend's endpoint allowlist and is compared against what\n * the seller advertises — so it can only cost you a `BCK.PROTOCOL.0031` or a\n * `BCK.X402.0013`.\n */\n resource?: X402TokenResource\n /**\n * HTTP verb of the protected resource (e.g. `POST`). Signed into a v3 token\n * alongside {@link X402TokenOptions.resource}, and compared against the verb\n * the seller advertises. Upper-cased by the SDK before it is sent, so\n * `'post'` and `'POST'` are equivalent.\n */\n httpVerb?: string\n /**\n * Request a specific EIP-712 token version. Omitted means the backend\n * default (currently `2`). Requesting `3` is a request, not a guarantee —\n * always read the version back off the minted token.\n */\n tokenVersion?: X402TokenVersion\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -17,9 +17,10 @@ export type { CreateOrderOptions, CreateOrderResult, Order, OrderStatus } from '
|
|
|
17
17
|
export { OrganizationMemberRole, OrganizationType, OrganizationActivityEventType, } from './api/organizations-api/types.js';
|
|
18
18
|
export type { MyMembership, OrganizationActivityEvent, OrganizationActivityFilters, OrganizationActivityPage, } from './api/organizations-api/types.js';
|
|
19
19
|
export { buildPaymentRequired, resolveNetwork, resolveScheme } from './x402/facilitator-api.js';
|
|
20
|
+
export { detectAccessTokenVersion, isSingleUseAccessToken, isAccessTokenAlreadyUsed, X402_TOKEN_ALREADY_USED_CODE, } from './x402/token-version.js';
|
|
20
21
|
export { DelegationAPI } from './x402/delegation-api.js';
|
|
21
22
|
export type { PaymentMethodSummary, UpdatePaymentMethodDto, DelegationSummary, DelegationListResponse, PurchasingPower, ListOptions, } from './x402/delegation-api.js';
|
|
22
|
-
export type { X402PaymentRequired, X402PaymentAccepted, X402Resource, X402Scheme, X402SchemeExtra, VerifyPermissionsParams, VerifyPermissionsResult, SettlePermissionsParams, SettlePermissionsResult, } from './x402/facilitator-api.js';
|
|
23
|
+
export type { X402PaymentRequired, X402PaymentAccepted, X402Resource, X402Scheme, X402SchemeExtra, VerifyPermissionsParams, VerifyPermissionsResult, SettlePermissionsParams, SettlePermissionsResult, X402BillingModel, } from './x402/facilitator-api.js';
|
|
23
24
|
export * from './mpp/index.js';
|
|
24
25
|
export type { CreditsContext, CreditsOption, PaywallOptions, McpConfig, PaywallContext, AuthResult, } from './mcp/types/paywall.types.js';
|
|
25
26
|
export type { OAuthUrls, OAuthConfig, HttpRouterConfig, HttpServerConfig, HttpServerResult, } from './mcp/types/http.types.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAA;AACjC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CA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AAuB,EACvB,uBAAuB,EACvB,uBAAuB,EACvB,gBAAgB,GACjB,MAAM,2BAA2B,CAAA;AAGlC,cAAc,gBAAgB,CAAA;AAG9B,YAAY,EACV,cAAc,EACd,aAAa,EACb,cAAc,EACd,SAAS,EACT,cAAc,EACd,UAAU,GACX,MAAM,8BAA8B,CAAA;AAGrC,YAAY,EACV,SAAS,EACT,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,2BAA2B,CAAA;AAGlC,YAAY,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAGvD,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAA;AAExE,YAAY,EACV,SAAS,EACT,iBAAiB,EACjB,qBAAqB,EACrB,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,sBAAsB,EACtB,IAAI,EACJ,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,qCAAqC,EACrC,YAAY,EACZ,qCAAqC,GACtC,MAAM,gBAAgB,CAAA;AAGvB,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,eAAe,EACf,4BAA4B,EAC5B,aAAa,IAAI,gBAAgB,GAClC,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,0BAA0B,EAC1B,iCAAiC,GAClC,MAAM,qBAAqB,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -14,6 +14,7 @@ export { OrdersAPI } from './api/orders-api.js';
|
|
|
14
14
|
export { OrganizationMemberRole, OrganizationType, OrganizationActivityEventType, } from './api/organizations-api/types.js';
|
|
15
15
|
// x402 utilities and types
|
|
16
16
|
export { buildPaymentRequired, resolveNetwork, resolveScheme } from './x402/facilitator-api.js';
|
|
17
|
+
export { detectAccessTokenVersion, isSingleUseAccessToken, isAccessTokenAlreadyUsed, X402_TOKEN_ALREADY_USED_CODE, } from './x402/token-version.js';
|
|
17
18
|
export { DelegationAPI } from './x402/delegation-api.js';
|
|
18
19
|
// MPP (Machine Payments Protocol) public surface
|
|
19
20
|
export * from './mpp/index.js';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAA;AACjC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,yBAAyB,CAAA;AACvC,cAAc,mBAAmB,CAAA;AACjC,cAAc,4BAA4B,CAAA;AAC1C,cAAc,oBAAoB,CAAA;AAClC,cAAc,oBAAoB,CAAA;AAClC,cAAc,8CAA8C,CAAA;AAE5D,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AACrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAA;AAE9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,8CAA8C,CAAA;AAC/E,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAE/C,OAAO,EACL,sBAAsB,EACtB,gBAAgB,EAChB,6BAA6B,GAC9B,MAAM,kCAAkC,CAAA;AAQzC,2BAA2B;AAC3B,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAA;AAC/F,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAA;AACjC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,yBAAyB,CAAA;AACvC,cAAc,mBAAmB,CAAA;AACjC,cAAc,4BAA4B,CAAA;AAC1C,cAAc,oBAAoB,CAAA;AAClC,cAAc,oBAAoB,CAAA;AAClC,cAAc,8CAA8C,CAAA;AAE5D,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AACrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAA;AAE9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,8CAA8C,CAAA;AAC/E,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAE/C,OAAO,EACL,sBAAsB,EACtB,gBAAgB,EAChB,6BAA6B,GAC9B,MAAM,kCAAkC,CAAA;AAQzC,2BAA2B;AAC3B,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAA;AAC/F,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACtB,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,yBAAyB,CAAA;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AAsBxD,iDAAiD;AACjD,cAAc,gBAAgB,CAAA;AAwB9B,qBAAqB;AACrB,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAA;AAqBxE,4EAA4E;AAC5E,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,eAAe,EACf,4BAA4B,EAC5B,aAAa,IAAI,gBAAgB,GAClC,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,0BAA0B,EAC1B,iCAAiC,GAClC,MAAM,qBAAqB,CAAA","sourcesContent":["export * from './environments.js'\nexport * from './payments.js'\nexport * from './utils.js'\nexport * from './common/api-version.js'\nexport * from './common/types.js'\nexport * from './common/payments.error.js'\nexport * from './common/helper.js'\nexport * from './api/query-api.js'\nexport * from './api/observability-api/observability-api.js'\nexport type { BackendApiOptions } from './api/nvm-api.js'\nexport { ContractsAPI } from './api/contracts-api.js'\nexport { CURRENT_ORG_ID_HEADER } from './api/base-payments.js'\nexport type { PublicationOptions } from './api/base-payments.js'\nexport { OrganizationsAPI } from './api/organizations-api/organizations-api.js'\nexport { OrdersAPI } from './api/orders-api.js'\nexport type { CreateOrderOptions, CreateOrderResult, Order, OrderStatus } from './api/orders-api.js'\nexport {\n OrganizationMemberRole,\n OrganizationType,\n OrganizationActivityEventType,\n} from './api/organizations-api/types.js'\nexport type {\n MyMembership,\n OrganizationActivityEvent,\n OrganizationActivityFilters,\n OrganizationActivityPage,\n} from './api/organizations-api/types.js'\n\n// x402 utilities and types\nexport { buildPaymentRequired, resolveNetwork, resolveScheme } from './x402/facilitator-api.js'\nexport {\n detectAccessTokenVersion,\n isSingleUseAccessToken,\n isAccessTokenAlreadyUsed,\n X402_TOKEN_ALREADY_USED_CODE,\n} from './x402/token-version.js'\nexport { DelegationAPI } from './x402/delegation-api.js'\nexport type {\n PaymentMethodSummary,\n UpdatePaymentMethodDto,\n DelegationSummary,\n DelegationListResponse,\n PurchasingPower,\n ListOptions,\n} from './x402/delegation-api.js'\nexport type {\n X402PaymentRequired,\n X402PaymentAccepted,\n X402Resource,\n X402Scheme,\n X402SchemeExtra,\n VerifyPermissionsParams,\n VerifyPermissionsResult,\n SettlePermissionsParams,\n SettlePermissionsResult,\n X402BillingModel,\n} from './x402/facilitator-api.js'\n\n// MPP (Machine Payments Protocol) public surface\nexport * from './mpp/index.js'\n\n// MCP public types\nexport type {\n CreditsContext,\n CreditsOption,\n PaywallOptions,\n McpConfig,\n PaywallContext,\n AuthResult,\n} from './mcp/types/paywall.types.js'\n\n// MCP HTTP types\nexport type {\n OAuthUrls,\n OAuthConfig,\n HttpRouterConfig,\n HttpServerConfig,\n HttpServerResult,\n} from './mcp/types/http.types.js'\n\n// MCP extended config type\nexport type { ExtendedMcpConfig } from './mcp/index.js'\n\n// MCP HTTP utilities\nexport { createRequireAuthMiddleware } from './mcp/http/oauth-router.js'\n\nexport type {\n AgentCard,\n TaskHandlerResult,\n TaskStatusUpdateEvent,\n ExecutionEventBus,\n AgentExecutor,\n RequestContext,\n PushNotificationConfig,\n Task,\n MessageSendParams,\n SendMessageResponse,\n TaskQueryParams,\n GetTaskResponse,\n TaskPushNotificationConfig,\n SetTaskPushNotificationConfigResponse,\n TaskIdParams,\n GetTaskPushNotificationConfigResponse,\n} from './a2a/types.js'\n\n// x402 v2 A2A in-band transport utilities (mirrors the Python X402A2AUtils)\nexport {\n X402A2AUtils,\n x402A2AUtils,\n X402A2AMetadata,\n X402_SETTLEMENT_DEFERRED_KEY,\n PaymentStatus as A2APaymentStatus,\n} from './a2a/x402-a2a.js'\nexport {\n A2A_X402_EXTENSION_URI,\n NVM_PAYMENT_EXTENSION_URI,\n AGENT_CARD_WELL_KNOWN_PATH,\n LEGACY_AGENT_CARD_WELL_KNOWN_PATH,\n} from './a2a/agent-card.js'\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paywall.d.ts","sourceRoot":"","sources":["../../../src/mcp/core/paywall.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAQjD,OAAO,EAEL,SAAS,EAET,aAAa,EACb,eAAe,EACf,WAAW,EACZ,MAAM,2BAA2B,CAAA;AAalC,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAA;
|
|
1
|
+
{"version":3,"file":"paywall.d.ts","sourceRoot":"","sources":["../../../src/mcp/core/paywall.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAQjD,OAAO,EAEL,SAAS,EAET,aAAa,EACb,eAAe,EACf,WAAW,EACZ,MAAM,2BAA2B,CAAA;AAalC,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAA;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAA;AA4C7D;;GAEG;AACH,qBAAa,gBAAgB;IAQzB,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,cAAc;IARxB,OAAO,CAAC,MAAM,CAGb;gBAGS,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,oBAAoB,EACnC,cAAc,EAAE,sBAAsB;IAGhD;;OAEG;IACH,SAAS,CAAC,OAAO,EAAE,SAAS,GAAG,IAAI;IAQnC;;OAEG;IAEH,OAAO,CAAC,KAAK,GAAG,GAAG,EACjB,OAAO,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,EACzD,OAAO,EAAE,WAAW,GAAG,aAAa,GACnC,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC;IAC7C,OAAO,CACL,OAAO,EAAE,CACP,GAAG,EAAE,GAAG,EACR,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,EAC5C,KAAK,CAAC,EAAE,GAAG,KACR,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,EACvB,OAAO,EAAE,eAAe,GACvB,CAAC,GAAG,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC;IAKxF;;OAEG;IACH,OAAO,CAAC,oBAAoB;IA8L5B;;;;OAIG;IACH,OAAO,CAAC,4BAA4B;IAYpC;;OAEG;YACW,aAAa;CAyE5B"}
|
package/dist/mcp/core/paywall.js
CHANGED
|
@@ -9,6 +9,42 @@ import { NEVERMINED_CREDITS_META_KEY, X402_PAYMENT_RESPONSE_META_KEY, paymentReq
|
|
|
9
9
|
// Emit the Authorization-header deprecation notice at most once per process to
|
|
10
10
|
// avoid log spam on high-traffic servers still using the legacy header path.
|
|
11
11
|
let authHeaderDeprecationWarned = false;
|
|
12
|
+
/**
|
|
13
|
+
* The `creditsRedeemed` value for `_meta['nevermined/credits']`, or `undefined`
|
|
14
|
+
* to OMIT the key.
|
|
15
|
+
*
|
|
16
|
+
* ⚠️ Exists so the two `_meta` builders cannot drift. They are separate code —
|
|
17
|
+
* the non-streaming tool result and `wrapAsyncIterable`'s final chunk — and a
|
|
18
|
+
* test on one proves nothing about the other, which is why each has its own
|
|
19
|
+
* regression test below this file.
|
|
20
|
+
*
|
|
21
|
+
* ⚠️ The two protocols deliberately DIVERGE here, and it is a settled decision
|
|
22
|
+
* (repo owner, on the #443 review) rather than an oversight — do not "fix" one
|
|
23
|
+
* to match the other:
|
|
24
|
+
*
|
|
25
|
+
* | surface | pay-as-you-go | why |
|
|
26
|
+
* | --- | --- | --- |
|
|
27
|
+
* | MCP `creditsRedeemed` (here) | reports `'0'` | it is the WIRE field name, and
|
|
28
|
+
* `billingModel` is emitted beside it, so a consumer can read the `'0'` |
|
|
29
|
+
* | A2A `creditsCharged` (#439) | OMITS | it is a DERIVED summary with no
|
|
30
|
+
* discriminator beside it, so a bare `0` would read as "you were charged
|
|
31
|
+
* nothing" on a charge that succeeded |
|
|
32
|
+
*
|
|
33
|
+
* The rule, which is deliberately NOT the A2A handler's:
|
|
34
|
+
* - a successful settle publishes whatever the facilitator reported, including
|
|
35
|
+
* the `'0'` a pay-as-you-go plan returns — because this key also carries
|
|
36
|
+
* `billingModel`, so a consumer can tell that `'0'` from a credits settle that
|
|
37
|
+
* burned nothing. A2A's `creditsCharged` omits instead, having no
|
|
38
|
+
* discriminator beside it. See the PR discussion on #443.
|
|
39
|
+
* - a successful settle that reported no figure omits, rather than substituting
|
|
40
|
+
* the credits the request ASKED to burn (the defect this helper replaced).
|
|
41
|
+
* - a failed settle, and a free / no-credit call, report `'0'`.
|
|
42
|
+
*/
|
|
43
|
+
function resolveCreditsRedeemed(settlement) {
|
|
44
|
+
if (!settlement?.success)
|
|
45
|
+
return '0';
|
|
46
|
+
return settlement.creditsRedeemed;
|
|
47
|
+
}
|
|
12
48
|
/**
|
|
13
49
|
* Main class for creating paywall-protected MCP handlers
|
|
14
50
|
*/
|
|
@@ -108,7 +144,7 @@ export class PaywallDecorator {
|
|
|
108
144
|
const onFinally = async () => {
|
|
109
145
|
return await this.redeemCredits(effectivePlanId, authResult.token, authResult.subscriberAddress, credits, options, authResult.agentId, authResult.logicalUrl, authResult.httpUrl, 'POST');
|
|
110
146
|
};
|
|
111
|
-
return wrapAsyncIterable(result, onFinally, effectivePlanId, authResult.subscriberAddress
|
|
147
|
+
return wrapAsyncIterable(result, onFinally, effectivePlanId, authResult.subscriberAddress);
|
|
112
148
|
}
|
|
113
149
|
// 7. Non-streaming: redeem immediately
|
|
114
150
|
const creditsResult = await this.redeemCredits(effectivePlanId, authResult.token, authResult.subscriberAddress, credits, options, authResult.agentId, authResult.logicalUrl,
|
|
@@ -133,10 +169,28 @@ export class PaywallDecorator {
|
|
|
133
169
|
...(creditsResult && { [X402_PAYMENT_RESPONSE_META_KEY]: creditsResult }),
|
|
134
170
|
[NEVERMINED_CREDITS_META_KEY]: {
|
|
135
171
|
...(creditsResult?.transaction && { txHash: creditsResult.transaction }),
|
|
136
|
-
creditsRedeemed:
|
|
137
|
-
|
|
138
|
-
|
|
172
|
+
// `creditsRedeemed` is meaningless without this: a pay-as-you-go plan
|
|
173
|
+
// holds no balance, so it reads '0' on a settle that DID charge the
|
|
174
|
+
// buyer. Omitted (not '') when the settle carried no discriminator,
|
|
175
|
+
// so a consumer can tell "absent" from "present and empty".
|
|
176
|
+
...(creditsResult?.billingModel && { billingModel: creditsResult.billingModel }),
|
|
177
|
+
// ⚠️ NO `?? credits.toString()` FALLBACK. That substituted the credits
|
|
178
|
+
// this request ASKED to burn and published them under the name
|
|
179
|
+
// `creditsRedeemed` — a figure the settle never reported, labelled as
|
|
180
|
+
// one it did. The A2A handler was corrected the same way in #438/#439;
|
|
181
|
+
// the two protocols must not tell a buyer different things about the
|
|
182
|
+
// same money.
|
|
183
|
+
//
|
|
184
|
+
// A successful settle that reports no figure now OMITS the key rather
|
|
185
|
+
// than inventing one. Omission is the honest answer and it is
|
|
186
|
+
// distinguishable: `remainingBalance`, `orderTx` and the full spec
|
|
187
|
+
// receipt under X402_PAYMENT_RESPONSE_META_KEY are all still here.
|
|
188
|
+
...(() => {
|
|
189
|
+
const r = resolveCreditsRedeemed(creditsResult);
|
|
190
|
+
return r !== undefined ? { creditsRedeemed: r } : {};
|
|
191
|
+
})(),
|
|
139
192
|
remainingBalance: creditsResult?.remainingBalance,
|
|
193
|
+
...(creditsResult?.orderTx && { orderTx: creditsResult.orderTx }),
|
|
140
194
|
planId: authResult.planId,
|
|
141
195
|
subscriberAddress: authResult.subscriberAddress,
|
|
142
196
|
success: creditsResult ? creditsResult.success : true,
|
|
@@ -243,7 +297,7 @@ function isAsyncIterable(value) {
|
|
|
243
297
|
/**
|
|
244
298
|
* Wrap an AsyncIterable with metadata injection at the end of the stream
|
|
245
299
|
*/
|
|
246
|
-
function wrapAsyncIterable(iterable, onFinally, planId, subscriberAddress
|
|
300
|
+
function wrapAsyncIterable(iterable, onFinally, planId, subscriberAddress) {
|
|
247
301
|
async function* generator() {
|
|
248
302
|
let creditsResult = null;
|
|
249
303
|
try {
|
|
@@ -268,10 +322,17 @@ function wrapAsyncIterable(iterable, onFinally, planId, subscriberAddress, credi
|
|
|
268
322
|
// Nevermined-namespaced observability (NOT part of the x402 spec).
|
|
269
323
|
[NEVERMINED_CREDITS_META_KEY]: {
|
|
270
324
|
...(settlement?.transaction && { txHash: settlement.transaction }),
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
325
|
+
// See the non-streaming site: without `billingModel`, `creditsRedeemed`
|
|
326
|
+
// cannot be read — it is '0' on a pay-as-you-go settle that charged.
|
|
327
|
+
...(settlement?.billingModel && { billingModel: settlement.billingModel }),
|
|
328
|
+
// See the non-streaming site: no `?? credits.toString()` substitution.
|
|
329
|
+
// A successful settle that reported no figure omits the key.
|
|
330
|
+
...(() => {
|
|
331
|
+
const r = resolveCreditsRedeemed(settlement);
|
|
332
|
+
return r !== undefined ? { creditsRedeemed: r } : {};
|
|
333
|
+
})(),
|
|
274
334
|
remainingBalance: settlement?.remainingBalance,
|
|
335
|
+
...(settlement?.orderTx && { orderTx: settlement.orderTx }),
|
|
275
336
|
planId,
|
|
276
337
|
subscriberAddress,
|
|
277
338
|
success: settlement ? settlement.success : true,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paywall.js","sourceRoot":"","sources":["../../../src/mcp/core/paywall.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAW,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAE9D,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AACrE,OAAO,EACL,oBAAoB,EACpB,4BAA4B,GAG7B,MAAM,+BAA+B,CAAA;AAStC,OAAO,EACL,WAAW,EACX,oBAAoB,EACpB,qBAAqB,EACrB,cAAc,GACf,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,EAC9B,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,kBAAkB,CAAA;AAIzB,+EAA+E;AAC/E,6EAA6E;AAC7E,IAAI,2BAA2B,GAAG,KAAK,CAAA;AAEvC;;GAEG;AACH,MAAM,OAAO,gBAAgB;IAO3B,YACU,QAAkB,EAClB,aAAmC,EACnC,cAAsC;QAFtC,aAAQ,GAAR,QAAQ,CAAU;QAClB,kBAAa,GAAb,aAAa,CAAsB;QACnC,mBAAc,GAAd,cAAc,CAAwB;QAThD,iEAAiE;QACzD,WAAM,GAA6D;YACzE,MAAM,EAAE,EAAE;YACV,UAAU,EAAE,YAAY;SACzB,CAAA;IAME,CAAC;IAEJ;;OAEG;IACH,SAAS,CAAC,OAAkB;QAC1B,IAAI,CAAC,MAAM,GAAG;YACZ,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM;YAC5C,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO;YAC/C,UAAU,EAA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,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;wBACpD,CAAC,CAAC,GAAG;oBACP,gBAAgB,EAAE,UAAU,EAAE,gBAAgB;oBAC9C,MAAM;oBACN,iBAAiB;oBACjB,OAAO,EAAE,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI;oBAC/C,GAAG,CAAC,UAAU,EAAE,WAAW,IAAI,EAAE,WAAW,EAAE,UAAU,CAAC,WAAW,EAAE,CAAC;iBACxE;aACF;SACF,CAAA;QACD,MAAM,aAAkB,CAAA;IAC1B,CAAC;IACD,OAAO,SAAS,EAAE,CAAA;AACpB,CAAC","sourcesContent":["/**\n * Main paywall decorator for MCP handlers (tools, resources, prompts)\n */\nimport { Address, isValidScheme } from '../../common/types.js'\nimport type { Payments } from '../../payments.js'\nimport { decodeAccessToken, encodeAccessToken } from '../../utils.js'\nimport {\n buildPaymentRequired,\n buildPaymentRequiredForPlans,\n type SettlePermissionsResult,\n type X402PaymentRequired,\n} from '../../x402/facilitator-api.js'\nimport {\n AuthResult,\n McpConfig,\n PaywallOptions,\n PromptOptions,\n ResourceOptions,\n ToolOptions,\n} from '../types/paywall.types.js'\nimport {\n ERROR_CODES,\n PaymentRequiredError,\n SettlementFailedError,\n createRpcError,\n} from '../utils/errors.js'\nimport {\n NEVERMINED_CREDITS_META_KEY,\n X402_PAYMENT_RESPONSE_META_KEY,\n paymentRequiredResult,\n readPaymentPayload,\n} from '../utils/meta.js'\nimport { PaywallAuthenticator } from './auth.js'\nimport { CreditsContextProvider } from './credits-context.js'\n\n// Emit the Authorization-header deprecation notice at most once per process to\n// avoid log spam on high-traffic servers still using the legacy header path.\nlet authHeaderDeprecationWarned = false\n\n/**\n * Main class for creating paywall-protected MCP handlers\n */\nexport class PaywallDecorator {\n // Internal config ensures serverName is always a concrete string\n private config: { planId: string; agentId?: string; serverName: string } = {\n planId: '',\n serverName: 'mcp-server',\n }\n\n constructor(\n private payments: Payments,\n private authenticator: PaywallAuthenticator,\n private creditsContext: CreditsContextProvider,\n ) {}\n\n /**\n * Configure the paywall with agent and server information\n */\n configure(options: McpConfig): void {\n this.config = {\n planId: options.planId || this.config.planId,\n agentId: options.agentId ?? this.config.agentId,\n serverName: options.serverName ?? this.config.serverName,\n }\n }\n\n /**\n * Create a paywall-protected handler (uncurried version only)\n */\n // Overloads per kind for stronger typing\n protect<TArgs = any>(\n handler: (args: TArgs, extra?: any) => Promise<any> | any,\n options: ToolOptions | PromptOptions,\n ): (args: TArgs, extra?: any) => Promise<any>\n protect(\n handler: (\n uri: URL,\n variables: Record<string, string | string[]>,\n extra?: any,\n ) => Promise<any> | any,\n options: ResourceOptions,\n ): (uri: URL, variables: Record<string, string | string[]>, extra?: any) => Promise<any>\n protect(handler: any, options: PaywallOptions): any {\n return this.createWrappedHandler(handler, options)\n }\n\n /**\n * Internal method to create the wrapped handler\n */\n private createWrappedHandler<TArgs = any>(\n handler: (args: TArgs, extra?: any) => Promise<any> | any,\n options: PaywallOptions,\n ): (...allArgs: any[]) => Promise<any> {\n return async (...allArgs: any[]): Promise<any> => {\n // Validate configuration: a planId must be resolvable (per-tool option or\n // server-level config). agentId is optional under the plan-centric model\n // (the facilitator resolves everything from planId + token).\n const configuredPlanId = options?.planId ?? this.config.planId\n if (!configuredPlanId) {\n throw createRpcError(\n ERROR_CODES.Misconfiguration,\n 'Server misconfiguration: missing planId',\n )\n }\n\n const kind = options?.kind ?? 'tool'\n const name = options?.name ?? 'unnamed'\n\n // Detect resource signature: (url, variables, extra)\n const isResource = allArgs.length >= 2 && allArgs[0] instanceof URL\n const extra = isResource ? allArgs[2] : allArgs[1]\n const argsOrVars = isResource ? allArgs[1] : allArgs[0]\n\n try {\n // x402 v2 MCP transport: prefer the in-band payment payload from\n // params._meta[\"x402/payment\"]. Re-encode it into the access token\n // string the verify/settle path expects and present it via the same\n // extra/headers shape the auth flow reads, so the in-band payload takes\n // precedence over the Authorization header (kept as a deprecated\n // fallback when the in-band payload is absent). The RAW extra is still\n // forwarded to the user handler below.\n const paymentPayload = readPaymentPayload(extra)\n let authExtra = extra\n if (paymentPayload) {\n const token = encodeAccessToken(paymentPayload)\n // Synthesize an auth-only extra carrying the in-band token. This\n // intentionally drops the rest of `extra` for the AUTH call only; the\n // RAW `extra` (with `_meta`) is still forwarded to the user handler below.\n authExtra = { requestInfo: { headers: { authorization: `Bearer ${token}` } } }\n } else if (!authHeaderDeprecationWarned) {\n authHeaderDeprecationWarned = true\n console.warn(\n '[x402] No _meta[\"x402/payment\"] on the MCP request; falling back to the ' +\n 'Authorization header (deprecated under the x402 v2 MCP transport).',\n )\n }\n\n // 1. Authenticate request\n const authResult = await this.authenticator.authenticate(\n authExtra,\n { planId: configuredPlanId, maxAmount: options?.maxAmount },\n this.config.agentId,\n this.config.serverName,\n name,\n kind,\n argsOrVars,\n )\n\n // 2. Pre-calculate credits if they are fixed (not a function)\n // This allows handlers to access credits during execution\n const creditsOption = options?.credits\n const isFixedCredits = typeof creditsOption === 'bigint' || creditsOption === undefined\n const preCalculatedCredits = isFixedCredits\n ? this.creditsContext.resolve(creditsOption, argsOrVars, null, authResult)\n : undefined\n\n // Determine effective planId: explicit option overrides token-derived value\n const effectivePlanId = options?.planId ?? authResult.planId\n\n // 3. Build PaywallContext for handler (with extra wrapper for backward compatibility)\n const paywallContext = {\n authResult,\n credits: preCalculatedCredits,\n planId: authResult.planId,\n subscriberAddress: authResult.subscriberAddress,\n agentRequest: authResult.agentRequest,\n }\n\n // 4. Execute original handler with context\n const result = await (handler as any)(...allArgs, paywallContext)\n\n // 5. Resolve final credits to burn (may be different if credits are dynamic)\n const credits = isFixedCredits\n ? (preCalculatedCredits ?? 1n)\n : this.creditsContext.resolve(creditsOption, argsOrVars, result, authResult)\n\n // Update context with final resolved credits\n paywallContext.credits = credits\n\n // 6. If the result is an AsyncIterable (stream), redeem on completion\n if (isAsyncIterable(result)) {\n const onFinally = async () => {\n return await this.redeemCredits(\n effectivePlanId,\n authResult.token,\n authResult.subscriberAddress,\n credits,\n options,\n authResult.agentId,\n authResult.logicalUrl,\n authResult.httpUrl,\n 'POST',\n )\n }\n return wrapAsyncIterable(\n result,\n onFinally,\n effectivePlanId,\n authResult.subscriberAddress,\n credits,\n )\n }\n\n // 7. Non-streaming: redeem immediately\n const creditsResult = await this.redeemCredits(\n effectivePlanId,\n authResult.token,\n authResult.subscriberAddress,\n credits,\n options,\n authResult.agentId,\n authResult.logicalUrl,\n // fix: pre-existing arg order — fallbackEndpoint=httpUrl, httpVerb='POST'\n // (matches the streaming site above)\n authResult.httpUrl,\n 'POST',\n )\n\n // Settlement failed AFTER the tool executed: per the x402 v2 MCP\n // transport spec, do NOT return the tool's content — surface only the\n // payment error so a paid result is never delivered without payment\n // landing. (onRedeemError \"ignore\" therefore no longer delivers paid\n // content; \"propagate\" already threw a Misconfiguration in redeemCredits.)\n if (creditsResult && !creditsResult.success) {\n console.error(\n `[x402] settlement failed after tool execution; suppressing tool content. reason=${creditsResult.errorReason}`,\n )\n throw new SettlementFailedError(this.buildPaymentRequiredFromAuth(authResult))\n }\n\n // creditsResult is undefined for free / no-credit calls (no settlement\n // performed) — in that case the spec receipt is omitted. On success the\n // full receipt goes under the spec key; Nevermined observability is kept\n // under a namespaced key so it never collides with the spec shape.\n result._meta = {\n ...result._meta,\n ...(creditsResult && { [X402_PAYMENT_RESPONSE_META_KEY]: creditsResult }),\n [NEVERMINED_CREDITS_META_KEY]: {\n ...(creditsResult?.transaction && { txHash: creditsResult.transaction }),\n creditsRedeemed: creditsResult?.success\n ? (creditsResult.creditsRedeemed ?? credits.toString())\n : '0',\n remainingBalance: creditsResult?.remainingBalance,\n planId: authResult.planId,\n subscriberAddress: authResult.subscriberAddress,\n success: creditsResult ? creditsResult.success : true,\n },\n }\n return result\n } catch (error) {\n // Payment-required (pre-execution, from auth) and settlement-failure\n // (post-execution) are surfaced in band as an error tool result for\n // tools. Resources/prompts have no tool-result error channel, so the\n // error propagates as a JSON-RPC error instead.\n if (error instanceof PaymentRequiredError && kind === 'tool') {\n return paymentRequiredResult(error.paymentRequired)\n }\n throw error\n }\n }\n }\n\n /**\n * Build a spec-shaped `PaymentRequired` dict for a settlement failure, from\n * the authenticated request context. Surfaced (with tool content suppressed)\n * when settlement fails after the tool has executed.\n */\n private buildPaymentRequiredFromAuth(authResult: AuthResult): Record<string, any> {\n const planId = authResult.planId || ''\n const paymentRequired = buildPaymentRequiredForPlans(planId ? [planId] : [''], {\n endpoint: authResult.logicalUrl || authResult.httpUrl,\n agentId: authResult.agentId,\n httpVerb: 'POST',\n environment: this.payments.getEnvironmentName(),\n }) as X402PaymentRequired & { error?: string }\n paymentRequired.error = 'settlement failed'\n return paymentRequired\n }\n\n /**\n * Redeem credits after successful request\n */\n private async redeemCredits(\n planId: string,\n token: string,\n subscriberAddress: Address,\n credits: bigint,\n options: PaywallOptions,\n agentId?: string,\n endpoint?: string,\n fallbackEndpoint?: string,\n httpVerb?: string,\n ): Promise<SettlePermissionsResult | undefined> {\n // No settlement for free / no-credit calls — signalled to the caller as\n // `undefined` so the spec receipt (_meta[\"x402/payment-response\"]) is omitted.\n if (!(credits && credits > 0n && subscriberAddress && planId)) {\n return undefined\n }\n\n const decoded = decodeAccessToken(token)\n const scheme = isValidScheme(decoded?.accepted?.scheme)\n ? decoded.accepted.scheme\n : 'nvm:erc4337'\n try {\n const paymentRequired: X402PaymentRequired = buildPaymentRequired(planId, {\n endpoint: endpoint || '',\n agentId,\n httpVerb,\n scheme,\n environment: this.payments.getEnvironmentName(),\n })\n\n return await this.payments.facilitator.settlePermissions({\n paymentRequired,\n x402AccessToken: token,\n maxAmount: credits,\n })\n } catch (primaryError) {\n // If logical URL fails and we have an HTTP URL fallback, retry with it\n let lastError: unknown = primaryError\n if (fallbackEndpoint) {\n try {\n const paymentRequired: X402PaymentRequired = buildPaymentRequired(planId, {\n endpoint: fallbackEndpoint,\n agentId,\n httpVerb,\n scheme,\n environment: this.payments.getEnvironmentName(),\n })\n\n return await this.payments.facilitator.settlePermissions({\n paymentRequired,\n x402AccessToken: token,\n maxAmount: credits,\n })\n } catch (fallbackError) {\n // Fallback also failed, use fallback error as the reported error\n lastError = fallbackError\n }\n }\n\n const errorReason = lastError instanceof Error ? lastError.message : String(lastError)\n console.error(`[x402] settle failed: ${errorReason}`)\n if (options.onRedeemError === 'propagate') {\n throw createRpcError(\n ERROR_CODES.Misconfiguration,\n `Failed to redeem credits: ${errorReason}`,\n )\n }\n // Default (\"ignore\"): return a failed result so the caller suppresses the\n // tool content and surfaces the in-band payment error (always-suppress\n // under the x402 v2 MCP transport).\n return { success: false, transaction: '', network: '', errorReason }\n }\n }\n}\n\n/**\n * Type guard to detect AsyncIterable values.\n */\nfunction isAsyncIterable<T = unknown>(value: any): value is AsyncIterable<T> {\n return value != null && typeof value[Symbol.asyncIterator] === 'function'\n}\n\n/**\n * Wrap an AsyncIterable with metadata injection at the end of the stream\n */\nfunction wrapAsyncIterable<T>(\n iterable: AsyncIterable<T>,\n onFinally: () => Promise<any>,\n planId: string,\n subscriberAddress: Address,\n credits: bigint,\n) {\n async function* generator() {\n let creditsResult: any = null\n try {\n for await (const chunk of iterable) {\n yield chunk as T\n }\n } finally {\n creditsResult = await onFinally()\n }\n\n // Yield a _meta chunk at the end with the redemption result.\n // NOTE: a stream cannot retroactively suppress already-yielded chunks, so a\n // post-execution settlement failure on a stream is only reported here in the\n // final _meta chunk (under nevermined/credits) — it cannot withhold content\n // the way a non-streaming tool result does. `creditsResult` is undefined for\n // free / no-credit calls.\n const settlement = creditsResult || undefined\n const metadataChunk = {\n _meta: {\n // Spec receipt only on a successful settlement.\n ...(settlement?.success && { [X402_PAYMENT_RESPONSE_META_KEY]: settlement }),\n // Nevermined-namespaced observability (NOT part of the x402 spec).\n [NEVERMINED_CREDITS_META_KEY]: {\n ...(settlement?.transaction && { txHash: settlement.transaction }),\n creditsRedeemed: settlement?.success\n ? (settlement.creditsRedeemed ?? credits.toString())\n : '0',\n remainingBalance: settlement?.remainingBalance,\n planId,\n subscriberAddress,\n success: settlement ? settlement.success : true,\n ...(settlement?.errorReason && { errorReason: settlement.errorReason }),\n },\n },\n }\n yield metadataChunk as T\n }\n return generator()\n}\n"]}
|
|
1
|
+
{"version":3,"file":"paywall.js","sourceRoot":"","sources":["../../../src/mcp/core/paywall.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAW,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAE9D,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AACrE,OAAO,EACL,oBAAoB,EACpB,4BAA4B,GAG7B,MAAM,+BAA+B,CAAA;AAStC,OAAO,EACL,WAAW,EACX,oBAAoB,EACpB,qBAAqB,EACrB,cAAc,GACf,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,EAC9B,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,kBAAkB,CAAA;AAIzB,+EAA+E;AAC/E,6EAA6E;AAC7E,IAAI,2BAA2B,GAAG,KAAK,CAAA;AAEvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,SAAS,sBAAsB,CAC7B,UAAuE;IAEvE,IAAI,CAAC,UAAU,EAAE,OAAO;QAAE,OAAO,GAAG,CAAA;IACpC,OAAO,UAAU,CAAC,eAAe,CAAA;AACnC,CAAC;AAED;;GAEG;AACH,MAAM,OAAO,gBAAgB;IAO3B,YACU,QAAkB,EAClB,aAAmC,EACnC,cAAsC;QAFtC,aAAQ,GAAR,QAAQ,CAAU;QAClB,kBAAa,GAAb,aAAa,CAAsB;QACnC,mBAAc,GAAd,cAAc,CAAwB;QAThD,iEAAiE;QACzD,WAAM,GAA6D;YACzE,MAAM,EAAE,EAAE;YACV,UAAU,EAAE,YAAY;SACzB,CAAA;IAME,CAAC;IAEJ;;OAEG;IACH,SAAS,CAAC,OAAkB;QAC1B,IAAI,CAAC,MAAM,GAAG;YACZ,MAAM,EAAE,OAAO,CAAC,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AW,EAAE,CAAC;iBACxE;aACF;SACF,CAAA;QACD,MAAM,aAAkB,CAAA;IAC1B,CAAC;IACD,OAAO,SAAS,EAAE,CAAA;AACpB,CAAC","sourcesContent":["/**\n * Main paywall decorator for MCP handlers (tools, resources, prompts)\n */\nimport { Address, isValidScheme } from '../../common/types.js'\nimport type { Payments } from '../../payments.js'\nimport { decodeAccessToken, encodeAccessToken } from '../../utils.js'\nimport {\n buildPaymentRequired,\n buildPaymentRequiredForPlans,\n type SettlePermissionsResult,\n type X402PaymentRequired,\n} from '../../x402/facilitator-api.js'\nimport {\n AuthResult,\n McpConfig,\n PaywallOptions,\n PromptOptions,\n ResourceOptions,\n ToolOptions,\n} from '../types/paywall.types.js'\nimport {\n ERROR_CODES,\n PaymentRequiredError,\n SettlementFailedError,\n createRpcError,\n} from '../utils/errors.js'\nimport {\n NEVERMINED_CREDITS_META_KEY,\n X402_PAYMENT_RESPONSE_META_KEY,\n paymentRequiredResult,\n readPaymentPayload,\n} from '../utils/meta.js'\nimport { PaywallAuthenticator } from './auth.js'\nimport { CreditsContextProvider } from './credits-context.js'\n\n// Emit the Authorization-header deprecation notice at most once per process to\n// avoid log spam on high-traffic servers still using the legacy header path.\nlet authHeaderDeprecationWarned = false\n\n/**\n * The `creditsRedeemed` value for `_meta['nevermined/credits']`, or `undefined`\n * to OMIT the key.\n *\n * ⚠️ Exists so the two `_meta` builders cannot drift. They are separate code —\n * the non-streaming tool result and `wrapAsyncIterable`'s final chunk — and a\n * test on one proves nothing about the other, which is why each has its own\n * regression test below this file.\n *\n * ⚠️ The two protocols deliberately DIVERGE here, and it is a settled decision\n * (repo owner, on the #443 review) rather than an oversight — do not \"fix\" one\n * to match the other:\n *\n * | surface | pay-as-you-go | why |\n * | --- | --- | --- |\n * | MCP `creditsRedeemed` (here) | reports `'0'` | it is the WIRE field name, and\n * `billingModel` is emitted beside it, so a consumer can read the `'0'` |\n * | A2A `creditsCharged` (#439) | OMITS | it is a DERIVED summary with no\n * discriminator beside it, so a bare `0` would read as \"you were charged\n * nothing\" on a charge that succeeded |\n *\n * The rule, which is deliberately NOT the A2A handler's:\n * - a successful settle publishes whatever the facilitator reported, including\n * the `'0'` a pay-as-you-go plan returns — because this key also carries\n * `billingModel`, so a consumer can tell that `'0'` from a credits settle that\n * burned nothing. A2A's `creditsCharged` omits instead, having no\n * discriminator beside it. See the PR discussion on #443.\n * - a successful settle that reported no figure omits, rather than substituting\n * the credits the request ASKED to burn (the defect this helper replaced).\n * - a failed settle, and a free / no-credit call, report `'0'`.\n */\nfunction resolveCreditsRedeemed(\n settlement: { success?: boolean; creditsRedeemed?: string } | undefined,\n): string | undefined {\n if (!settlement?.success) return '0'\n return settlement.creditsRedeemed\n}\n\n/**\n * Main class for creating paywall-protected MCP handlers\n */\nexport class PaywallDecorator {\n // Internal config ensures serverName is always a concrete string\n private config: { planId: string; agentId?: string; serverName: string } = {\n planId: '',\n serverName: 'mcp-server',\n }\n\n constructor(\n private payments: Payments,\n private authenticator: PaywallAuthenticator,\n private creditsContext: CreditsContextProvider,\n ) {}\n\n /**\n * Configure the paywall with agent and server information\n */\n configure(options: McpConfig): void {\n this.config = {\n planId: options.planId || this.config.planId,\n agentId: options.agentId ?? this.config.agentId,\n serverName: options.serverName ?? this.config.serverName,\n }\n }\n\n /**\n * Create a paywall-protected handler (uncurried version only)\n */\n // Overloads per kind for stronger typing\n protect<TArgs = any>(\n handler: (args: TArgs, extra?: any) => Promise<any> | any,\n options: ToolOptions | PromptOptions,\n ): (args: TArgs, extra?: any) => Promise<any>\n protect(\n handler: (\n uri: URL,\n variables: Record<string, string | string[]>,\n extra?: any,\n ) => Promise<any> | any,\n options: ResourceOptions,\n ): (uri: URL, variables: Record<string, string | string[]>, extra?: any) => Promise<any>\n protect(handler: any, options: PaywallOptions): any {\n return this.createWrappedHandler(handler, options)\n }\n\n /**\n * Internal method to create the wrapped handler\n */\n private createWrappedHandler<TArgs = any>(\n handler: (args: TArgs, extra?: any) => Promise<any> | any,\n options: PaywallOptions,\n ): (...allArgs: any[]) => Promise<any> {\n return async (...allArgs: any[]): Promise<any> => {\n // Validate configuration: a planId must be resolvable (per-tool option or\n // server-level config). agentId is optional under the plan-centric model\n // (the facilitator resolves everything from planId + token).\n const configuredPlanId = options?.planId ?? this.config.planId\n if (!configuredPlanId) {\n throw createRpcError(\n ERROR_CODES.Misconfiguration,\n 'Server misconfiguration: missing planId',\n )\n }\n\n const kind = options?.kind ?? 'tool'\n const name = options?.name ?? 'unnamed'\n\n // Detect resource signature: (url, variables, extra)\n const isResource = allArgs.length >= 2 && allArgs[0] instanceof URL\n const extra = isResource ? allArgs[2] : allArgs[1]\n const argsOrVars = isResource ? allArgs[1] : allArgs[0]\n\n try {\n // x402 v2 MCP transport: prefer the in-band payment payload from\n // params._meta[\"x402/payment\"]. Re-encode it into the access token\n // string the verify/settle path expects and present it via the same\n // extra/headers shape the auth flow reads, so the in-band payload takes\n // precedence over the Authorization header (kept as a deprecated\n // fallback when the in-band payload is absent). The RAW extra is still\n // forwarded to the user handler below.\n const paymentPayload = readPaymentPayload(extra)\n let authExtra = extra\n if (paymentPayload) {\n const token = encodeAccessToken(paymentPayload)\n // Synthesize an auth-only extra carrying the in-band token. This\n // intentionally drops the rest of `extra` for the AUTH call only; the\n // RAW `extra` (with `_meta`) is still forwarded to the user handler below.\n authExtra = { requestInfo: { headers: { authorization: `Bearer ${token}` } } }\n } else if (!authHeaderDeprecationWarned) {\n authHeaderDeprecationWarned = true\n console.warn(\n '[x402] No _meta[\"x402/payment\"] on the MCP request; falling back to the ' +\n 'Authorization header (deprecated under the x402 v2 MCP transport).',\n )\n }\n\n // 1. Authenticate request\n const authResult = await this.authenticator.authenticate(\n authExtra,\n { planId: configuredPlanId, maxAmount: options?.maxAmount },\n this.config.agentId,\n this.config.serverName,\n name,\n kind,\n argsOrVars,\n )\n\n // 2. Pre-calculate credits if they are fixed (not a function)\n // This allows handlers to access credits during execution\n const creditsOption = options?.credits\n const isFixedCredits = typeof creditsOption === 'bigint' || creditsOption === undefined\n const preCalculatedCredits = isFixedCredits\n ? this.creditsContext.resolve(creditsOption, argsOrVars, null, authResult)\n : undefined\n\n // Determine effective planId: explicit option overrides token-derived value\n const effectivePlanId = options?.planId ?? authResult.planId\n\n // 3. Build PaywallContext for handler (with extra wrapper for backward compatibility)\n const paywallContext = {\n authResult,\n credits: preCalculatedCredits,\n planId: authResult.planId,\n subscriberAddress: authResult.subscriberAddress,\n agentRequest: authResult.agentRequest,\n }\n\n // 4. Execute original handler with context\n const result = await (handler as any)(...allArgs, paywallContext)\n\n // 5. Resolve final credits to burn (may be different if credits are dynamic)\n const credits = isFixedCredits\n ? (preCalculatedCredits ?? 1n)\n : this.creditsContext.resolve(creditsOption, argsOrVars, result, authResult)\n\n // Update context with final resolved credits\n paywallContext.credits = credits\n\n // 6. If the result is an AsyncIterable (stream), redeem on completion\n if (isAsyncIterable(result)) {\n const onFinally = async () => {\n return await this.redeemCredits(\n effectivePlanId,\n authResult.token,\n authResult.subscriberAddress,\n credits,\n options,\n authResult.agentId,\n authResult.logicalUrl,\n authResult.httpUrl,\n 'POST',\n )\n }\n return wrapAsyncIterable(\n result,\n onFinally,\n effectivePlanId,\n authResult.subscriberAddress,\n )\n }\n\n // 7. Non-streaming: redeem immediately\n const creditsResult = await this.redeemCredits(\n effectivePlanId,\n authResult.token,\n authResult.subscriberAddress,\n credits,\n options,\n authResult.agentId,\n authResult.logicalUrl,\n // fix: pre-existing arg order — fallbackEndpoint=httpUrl, httpVerb='POST'\n // (matches the streaming site above)\n authResult.httpUrl,\n 'POST',\n )\n\n // Settlement failed AFTER the tool executed: per the x402 v2 MCP\n // transport spec, do NOT return the tool's content — surface only the\n // payment error so a paid result is never delivered without payment\n // landing. (onRedeemError \"ignore\" therefore no longer delivers paid\n // content; \"propagate\" already threw a Misconfiguration in redeemCredits.)\n if (creditsResult && !creditsResult.success) {\n console.error(\n `[x402] settlement failed after tool execution; suppressing tool content. reason=${creditsResult.errorReason}`,\n )\n throw new SettlementFailedError(this.buildPaymentRequiredFromAuth(authResult))\n }\n\n // creditsResult is undefined for free / no-credit calls (no settlement\n // performed) — in that case the spec receipt is omitted. On success the\n // full receipt goes under the spec key; Nevermined observability is kept\n // under a namespaced key so it never collides with the spec shape.\n result._meta = {\n ...result._meta,\n ...(creditsResult && { [X402_PAYMENT_RESPONSE_META_KEY]: creditsResult }),\n [NEVERMINED_CREDITS_META_KEY]: {\n ...(creditsResult?.transaction && { txHash: creditsResult.transaction }),\n // `creditsRedeemed` is meaningless without this: a pay-as-you-go plan\n // holds no balance, so it reads '0' on a settle that DID charge the\n // buyer. Omitted (not '') when the settle carried no discriminator,\n // so a consumer can tell \"absent\" from \"present and empty\".\n ...(creditsResult?.billingModel && { billingModel: creditsResult.billingModel }),\n // ⚠️ NO `?? credits.toString()` FALLBACK. That substituted the credits\n // this request ASKED to burn and published them under the name\n // `creditsRedeemed` — a figure the settle never reported, labelled as\n // one it did. The A2A handler was corrected the same way in #438/#439;\n // the two protocols must not tell a buyer different things about the\n // same money.\n //\n // A successful settle that reports no figure now OMITS the key rather\n // than inventing one. Omission is the honest answer and it is\n // distinguishable: `remainingBalance`, `orderTx` and the full spec\n // receipt under X402_PAYMENT_RESPONSE_META_KEY are all still here.\n ...(() => {\n const r = resolveCreditsRedeemed(creditsResult)\n return r !== undefined ? { creditsRedeemed: r } : {}\n })(),\n remainingBalance: creditsResult?.remainingBalance,\n ...(creditsResult?.orderTx && { orderTx: creditsResult.orderTx }),\n planId: authResult.planId,\n subscriberAddress: authResult.subscriberAddress,\n success: creditsResult ? creditsResult.success : true,\n },\n }\n return result\n } catch (error) {\n // Payment-required (pre-execution, from auth) and settlement-failure\n // (post-execution) are surfaced in band as an error tool result for\n // tools. Resources/prompts have no tool-result error channel, so the\n // error propagates as a JSON-RPC error instead.\n if (error instanceof PaymentRequiredError && kind === 'tool') {\n return paymentRequiredResult(error.paymentRequired)\n }\n throw error\n }\n }\n }\n\n /**\n * Build a spec-shaped `PaymentRequired` dict for a settlement failure, from\n * the authenticated request context. Surfaced (with tool content suppressed)\n * when settlement fails after the tool has executed.\n */\n private buildPaymentRequiredFromAuth(authResult: AuthResult): Record<string, any> {\n const planId = authResult.planId || ''\n const paymentRequired = buildPaymentRequiredForPlans(planId ? [planId] : [''], {\n endpoint: authResult.logicalUrl || authResult.httpUrl,\n agentId: authResult.agentId,\n httpVerb: 'POST',\n environment: this.payments.getEnvironmentName(),\n }) as X402PaymentRequired & { error?: string }\n paymentRequired.error = 'settlement failed'\n return paymentRequired\n }\n\n /**\n * Redeem credits after successful request\n */\n private async redeemCredits(\n planId: string,\n token: string,\n subscriberAddress: Address,\n credits: bigint,\n options: PaywallOptions,\n agentId?: string,\n endpoint?: string,\n fallbackEndpoint?: string,\n httpVerb?: string,\n ): Promise<SettlePermissionsResult | undefined> {\n // No settlement for free / no-credit calls — signalled to the caller as\n // `undefined` so the spec receipt (_meta[\"x402/payment-response\"]) is omitted.\n if (!(credits && credits > 0n && subscriberAddress && planId)) {\n return undefined\n }\n\n const decoded = decodeAccessToken(token)\n const scheme = isValidScheme(decoded?.accepted?.scheme)\n ? decoded.accepted.scheme\n : 'nvm:erc4337'\n try {\n const paymentRequired: X402PaymentRequired = buildPaymentRequired(planId, {\n endpoint: endpoint || '',\n agentId,\n httpVerb,\n scheme,\n environment: this.payments.getEnvironmentName(),\n })\n\n return await this.payments.facilitator.settlePermissions({\n paymentRequired,\n x402AccessToken: token,\n maxAmount: credits,\n })\n } catch (primaryError) {\n // If logical URL fails and we have an HTTP URL fallback, retry with it\n let lastError: unknown = primaryError\n if (fallbackEndpoint) {\n try {\n const paymentRequired: X402PaymentRequired = buildPaymentRequired(planId, {\n endpoint: fallbackEndpoint,\n agentId,\n httpVerb,\n scheme,\n environment: this.payments.getEnvironmentName(),\n })\n\n return await this.payments.facilitator.settlePermissions({\n paymentRequired,\n x402AccessToken: token,\n maxAmount: credits,\n })\n } catch (fallbackError) {\n // Fallback also failed, use fallback error as the reported error\n lastError = fallbackError\n }\n }\n\n const errorReason = lastError instanceof Error ? lastError.message : String(lastError)\n console.error(`[x402] settle failed: ${errorReason}`)\n if (options.onRedeemError === 'propagate') {\n throw createRpcError(\n ERROR_CODES.Misconfiguration,\n `Failed to redeem credits: ${errorReason}`,\n )\n }\n // Default (\"ignore\"): return a failed result so the caller suppresses the\n // tool content and surfaces the in-band payment error (always-suppress\n // under the x402 v2 MCP transport).\n return { success: false, transaction: '', network: '', errorReason }\n }\n }\n}\n\n/**\n * Type guard to detect AsyncIterable values.\n */\nfunction isAsyncIterable<T = unknown>(value: any): value is AsyncIterable<T> {\n return value != null && typeof value[Symbol.asyncIterator] === 'function'\n}\n\n/**\n * Wrap an AsyncIterable with metadata injection at the end of the stream\n */\nfunction wrapAsyncIterable<T>(\n iterable: AsyncIterable<T>,\n onFinally: () => Promise<any>,\n planId: string,\n subscriberAddress: Address,\n) {\n async function* generator() {\n let creditsResult: any = null\n try {\n for await (const chunk of iterable) {\n yield chunk as T\n }\n } finally {\n creditsResult = await onFinally()\n }\n\n // Yield a _meta chunk at the end with the redemption result.\n // NOTE: a stream cannot retroactively suppress already-yielded chunks, so a\n // post-execution settlement failure on a stream is only reported here in the\n // final _meta chunk (under nevermined/credits) — it cannot withhold content\n // the way a non-streaming tool result does. `creditsResult` is undefined for\n // free / no-credit calls.\n const settlement = creditsResult || undefined\n const metadataChunk = {\n _meta: {\n // Spec receipt only on a successful settlement.\n ...(settlement?.success && { [X402_PAYMENT_RESPONSE_META_KEY]: settlement }),\n // Nevermined-namespaced observability (NOT part of the x402 spec).\n [NEVERMINED_CREDITS_META_KEY]: {\n ...(settlement?.transaction && { txHash: settlement.transaction }),\n // See the non-streaming site: without `billingModel`, `creditsRedeemed`\n // cannot be read — it is '0' on a pay-as-you-go settle that charged.\n ...(settlement?.billingModel && { billingModel: settlement.billingModel }),\n // See the non-streaming site: no `?? credits.toString()` substitution.\n // A successful settle that reported no figure omits the key.\n ...(() => {\n const r = resolveCreditsRedeemed(settlement)\n return r !== undefined ? { creditsRedeemed: r } : {}\n })(),\n remainingBalance: settlement?.remainingBalance,\n ...(settlement?.orderTx && { orderTx: settlement.orderTx }),\n planId,\n subscriberAddress,\n success: settlement ? settlement.success : true,\n ...(settlement?.errorReason && { errorReason: settlement.errorReason }),\n },\n },\n }\n yield metadataChunk as T\n }\n return generator()\n}\n"]}
|
package/dist/mcp/http/index.d.ts
CHANGED
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
* app.listen(5001)
|
|
40
40
|
* ```
|
|
41
41
|
*/
|
|
42
|
-
export { getOAuthUrls, buildProtectedResourceMetadata, buildMcpProtectedResourceMetadata, buildAuthorizationServerMetadata, buildOidcConfiguration, buildServerInfoResponse, } from './oauth-metadata.js';
|
|
42
|
+
export { getOAuthUrls, resolveOAuthTier, OAUTH_TIER_PARAM, OAUTH_TIERS, type OAuthTier, buildProtectedResourceMetadata, buildMcpProtectedResourceMetadata, buildAuthorizationServerMetadata, buildOidcConfiguration, buildServerInfoResponse, } from './oauth-metadata.js';
|
|
43
43
|
export { isClientRegistrationRequest, validateClientRegistrationRequest, processClientRegistration, ClientRegistrationError, } from './client-registration.js';
|
|
44
44
|
export { createOAuthRouter, createCorsMiddleware, createJsonMiddleware, createRequireAuthMiddleware, createHttpLoggingMiddleware, type OAuthRouterOptions, } from './oauth-router.js';
|
|
45
45
|
export { startManagedServer, createMcpApp, type ManagedServerConfig } from './managed-server.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/mcp/http/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAGH,OAAO,EACL,YAAY,EACZ,8BAA8B,EAC9B,iCAAiC,EACjC,gCAAgC,EAChC,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,qBAAqB,CAAA;AAG5B,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,EACjC,yBAAyB,EACzB,uBAA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B,EACpB,mBAAmB,EACnB,sBAAsB,EACtB,gBAAgB,EAChB,wBAAwB,EACxB,qBAAqB,EACrB,KAAK,gBAAgB,GACtB,MAAM,kBAAkB,CAAA"}
|
package/dist/mcp/http/index.js
CHANGED
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
* ```
|
|
41
41
|
*/
|
|
42
42
|
// OAuth metadata generators (pure functions)
|
|
43
|
-
export { getOAuthUrls, buildProtectedResourceMetadata, buildMcpProtectedResourceMetadata, buildAuthorizationServerMetadata, buildOidcConfiguration, buildServerInfoResponse, } from './oauth-metadata.js';
|
|
43
|
+
export { getOAuthUrls, resolveOAuthTier, OAUTH_TIER_PARAM, OAUTH_TIERS, buildProtectedResourceMetadata, buildMcpProtectedResourceMetadata, buildAuthorizationServerMetadata, buildOidcConfiguration, buildServerInfoResponse, } from './oauth-metadata.js';
|
|
44
44
|
// Client registration
|
|
45
45
|
export { isClientRegistrationRequest, validateClientRegistrationRequest, processClientRegistration, ClientRegistrationError, } from './client-registration.js';
|
|
46
46
|
// OAuth router and middleware
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/mcp/http/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,6CAA6C;AAC7C,OAAO,EACL,YAAY,EACZ,8BAA8B,EAC9B,iCAAiC,EACjC,gCAAgC,EAChC,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,qBAAqB,CAAA;AAE5B,sBAAsB;AACtB,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,EACjC,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,0BAA0B,CAAA;AAEjC,8BAA8B;AAC9B,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,2BAA2B,EAC3B,2BAA2B,GAE5B,MAAM,mBAAmB,CAAA;AAE1B,iBAAiB;AACjB,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAA4B,MAAM,qBAAqB,CAAA;AAEhG,qBAAqB;AACrB,OAAO,EACL,cAAc,EACd,oBAAoB,GAErB,MAAM,sBAAsB,CAAA;AAE7B,eAAe;AACf,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,sBAAsB,EACtB,gBAAgB,EAChB,wBAAwB,EACxB,qBAAqB,GAEtB,MAAM,kBAAkB,CAAA","sourcesContent":["/**\n * HTTP module for MCP OAuth 2.1 integration.\n *\n * This module provides all the building blocks for adding OAuth 2.1 support\n * to MCP servers, from low-level metadata generators to high-level managed servers.\n *\n * @example Quick start with managed server\n * ```typescript\n * import { Payments } from '@nevermined-io/payments'\n *\n * const payments = Payments.getInstance({\n * nvmApiKey: process.env.NVM_API_KEY!,\n * environment: 'staging_sandbox'\n * })\n *\n * // Start a complete MCP server with OAuth\n * const { baseUrl, stop } = await payments.mcp.startServer({\n * port: 5001,\n * agentId: process.env.NVM_AGENT_ID!,\n * serverName: 'my-mcp-server',\n * tools: ['hello_world']\n * })\n * ```\n *\n * @example Using the router with existing Express app\n * ```typescript\n * import express from 'express'\n *\n * const app = express()\n *\n * // Mount OAuth router on existing app\n * const router = payments.mcp.createRouter({\n * baseUrl: 'http://localhost:5001',\n * agentId: 'agent_123',\n * serverName: 'my-mcp-server'\n * })\n *\n * app.use(router)\n * app.listen(5001)\n * ```\n */\n\n// OAuth metadata generators (pure functions)\nexport {\n getOAuthUrls,\n buildProtectedResourceMetadata,\n buildMcpProtectedResourceMetadata,\n buildAuthorizationServerMetadata,\n buildOidcConfiguration,\n buildServerInfoResponse,\n} from './oauth-metadata.js'\n\n// Client registration\nexport {\n isClientRegistrationRequest,\n validateClientRegistrationRequest,\n processClientRegistration,\n ClientRegistrationError,\n} from './client-registration.js'\n\n// OAuth router and middleware\nexport {\n createOAuthRouter,\n createCorsMiddleware,\n createJsonMiddleware,\n createRequireAuthMiddleware,\n createHttpLoggingMiddleware,\n type OAuthRouterOptions,\n} from './oauth-router.js'\n\n// Managed server\nexport { startManagedServer, createMcpApp, type ManagedServerConfig } from './managed-server.js'\n\n// Session management\nexport {\n SessionManager,\n createSessionManager,\n type SessionManagerConfig,\n} from './session-manager.js'\n\n// MCP handlers\nexport {\n createPostMcpHandler,\n createGetMcpHandler,\n createDeleteMcpHandler,\n mountMcpHandlers,\n getCurrentRequestContext,\n requestContextStorage,\n type McpHandlerConfig,\n} from './mcp-handler.js'\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/mcp/http/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,6CAA6C;AAC7C,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,gBAAgB,EAChB,WAAW,EAEX,8BAA8B,EAC9B,iCAAiC,EACjC,gCAAgC,EAChC,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,qBAAqB,CAAA;AAE5B,sBAAsB;AACtB,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,EACjC,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,0BAA0B,CAAA;AAEjC,8BAA8B;AAC9B,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,2BAA2B,EAC3B,2BAA2B,GAE5B,MAAM,mBAAmB,CAAA;AAE1B,iBAAiB;AACjB,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAA4B,MAAM,qBAAqB,CAAA;AAEhG,qBAAqB;AACrB,OAAO,EACL,cAAc,EACd,oBAAoB,GAErB,MAAM,sBAAsB,CAAA;AAE7B,eAAe;AACf,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,sBAAsB,EACtB,gBAAgB,EAChB,wBAAwB,EACxB,qBAAqB,GAEtB,MAAM,kBAAkB,CAAA","sourcesContent":["/**\n * HTTP module for MCP OAuth 2.1 integration.\n *\n * This module provides all the building blocks for adding OAuth 2.1 support\n * to MCP servers, from low-level metadata generators to high-level managed servers.\n *\n * @example Quick start with managed server\n * ```typescript\n * import { Payments } from '@nevermined-io/payments'\n *\n * const payments = Payments.getInstance({\n * nvmApiKey: process.env.NVM_API_KEY!,\n * environment: 'staging_sandbox'\n * })\n *\n * // Start a complete MCP server with OAuth\n * const { baseUrl, stop } = await payments.mcp.startServer({\n * port: 5001,\n * agentId: process.env.NVM_AGENT_ID!,\n * serverName: 'my-mcp-server',\n * tools: ['hello_world']\n * })\n * ```\n *\n * @example Using the router with existing Express app\n * ```typescript\n * import express from 'express'\n *\n * const app = express()\n *\n * // Mount OAuth router on existing app\n * const router = payments.mcp.createRouter({\n * baseUrl: 'http://localhost:5001',\n * agentId: 'agent_123',\n * serverName: 'my-mcp-server'\n * })\n *\n * app.use(router)\n * app.listen(5001)\n * ```\n */\n\n// OAuth metadata generators (pure functions)\nexport {\n getOAuthUrls,\n resolveOAuthTier,\n OAUTH_TIER_PARAM,\n OAUTH_TIERS,\n type OAuthTier,\n buildProtectedResourceMetadata,\n buildMcpProtectedResourceMetadata,\n buildAuthorizationServerMetadata,\n buildOidcConfiguration,\n buildServerInfoResponse,\n} from './oauth-metadata.js'\n\n// Client registration\nexport {\n isClientRegistrationRequest,\n validateClientRegistrationRequest,\n processClientRegistration,\n ClientRegistrationError,\n} from './client-registration.js'\n\n// OAuth router and middleware\nexport {\n createOAuthRouter,\n createCorsMiddleware,\n createJsonMiddleware,\n createRequireAuthMiddleware,\n createHttpLoggingMiddleware,\n type OAuthRouterOptions,\n} from './oauth-router.js'\n\n// Managed server\nexport { startManagedServer, createMcpApp, type ManagedServerConfig } from './managed-server.js'\n\n// Session management\nexport {\n SessionManager,\n createSessionManager,\n type SessionManagerConfig,\n} from './session-manager.js'\n\n// MCP handlers\nexport {\n createPostMcpHandler,\n createGetMcpHandler,\n createDeleteMcpHandler,\n mountMcpHandlers,\n getCurrentRequestContext,\n requestContextStorage,\n type McpHandlerConfig,\n} from './mcp-handler.js'\n"]}
|
|
@@ -5,6 +5,38 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { type EnvironmentName } from '../../environments.js';
|
|
7
7
|
import type { OAuthUrls, OAuthConfig, ProtectedResourceMetadata, McpProtectedResourceMetadata, AuthorizationServerMetadata, OidcConfiguration } from '../types/http.types.js';
|
|
8
|
+
/**
|
|
9
|
+
* The query parameter that tells the Nevermined web app WHICH API tier an OAuth ceremony belongs
|
|
10
|
+
* to, and its two values. Each tier (sandbox / live) is its own authorization server, but ONE web
|
|
11
|
+
* app serves the consent screens for both and boots on whatever tier the user's browser last chose
|
|
12
|
+
* — Live by default. A bare `https://nevermined.app/oauth/authorize` therefore sends a sandbox MCP
|
|
13
|
+
* server's users to the LIVE consent screen, where the connector is not registered ("Connector not
|
|
14
|
+
* authorized"). The tier is stated on the URL instead; RFC 6749 §3.1 obliges clients to retain the
|
|
15
|
+
* query component when they add their own parameters. Same name and values as the Nevermined API's
|
|
16
|
+
* own RFC 8414 document and the embed widget (nvm-monorepo#3430 / #1787).
|
|
17
|
+
*/
|
|
18
|
+
export declare const OAUTH_TIER_PARAM = "network";
|
|
19
|
+
export declare const OAUTH_TIERS: readonly ["sandbox", "live"];
|
|
20
|
+
export type OAuthTier = (typeof OAUTH_TIERS)[number];
|
|
21
|
+
/**
|
|
22
|
+
* The API tier an environment belongs to. The four named environments map directly. `custom` is
|
|
23
|
+
* derived from the host of the backend it will publish as `token_endpoint`: a Nevermined API host has
|
|
24
|
+
* an `api` label immediately followed by the tier label — `api.sandbox.nevermined.app`,
|
|
25
|
+
* `<slug>.api.live.nevermined.app` (branded per-org subdomains), `mcp.api.sandbox.nevermined.dev` —
|
|
26
|
+
* so that label pair is what is matched, never a bare `sandbox` anywhere in the host. When the host
|
|
27
|
+
* cannot be classified (a `localhost` stack, a proxy/CNAME in front of the API) the tier is
|
|
28
|
+
* **omitted**, not guessed: the URL stays the pre-#3430 bare one, and the operator sets
|
|
29
|
+
* `oauthUrls.authorizationUri` (with `?network=` on it) to say which tier that deployment is —
|
|
30
|
+
* `getOAuthUrlsForEnvironment` warns once when that happens, so the degradation is never silent.
|
|
31
|
+
*
|
|
32
|
+
* ⚠️ This is not the only classifier of a `custom` backend for the `network` value — the CLI's
|
|
33
|
+
* `resolveEmbedNetwork` (`cli/src/utils/widget-redirect-flow.ts`) and nvm-monorepo's
|
|
34
|
+
* `deriveEmbedNetwork` (`apps/mcp/src/config.ts`) classify the same input. All three now apply THIS
|
|
35
|
+
* rule — the `api.<tier>` label pair, never guessing (the CLI ports it verbatim, payments#456; the
|
|
36
|
+
* monorepo via the shared `oauthTierFromHostname`, nvm-monorepo#3638). Keep them in sync; do not
|
|
37
|
+
* derive a fourth rule here.
|
|
38
|
+
*/
|
|
39
|
+
export declare function resolveOAuthTier(environment: EnvironmentName, backendUrl: string): OAuthTier | undefined;
|
|
8
40
|
/**
|
|
9
41
|
* Get OAuth URLs for a given environment with optional overrides.
|
|
10
42
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth-metadata.d.ts","sourceRoot":"","sources":["../../../src/mcp/http/oauth-metadata.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAgB,KAAK,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAC1E,OAAO,KAAK,EACV,SAAS,EACT,WAAW,EACX,yBAAyB,EACzB,4BAA4B,EAC5B,2BAA2B,EAC3B,iBAAiB,EAClB,MAAM,wBAAwB,CAAA;
|
|
1
|
+
{"version":3,"file":"oauth-metadata.d.ts","sourceRoot":"","sources":["../../../src/mcp/http/oauth-metadata.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAgB,KAAK,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAC1E,OAAO,KAAK,EACV,SAAS,EACT,WAAW,EACX,yBAAyB,EACzB,4BAA4B,EAC5B,2BAA2B,EAC3B,iBAAiB,EAClB,MAAM,wBAAwB,CAAA;AAE/B;;;;;;;;;GASG;AACH,eAAO,MAAM,gBAAgB,YAAY,CAAA;AACzC,e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