@mixrpay/merchant-sdk 0.1.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 +293 -0
- package/dist/index.d.mts +291 -0
- package/dist/index.d.ts +291 -0
- package/dist/index.js +901 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +843 -0
- package/dist/index.mjs.map +1 -0
- package/dist/middleware/express.d.mts +57 -0
- package/dist/middleware/express.d.ts +57 -0
- package/dist/middleware/express.js +326 -0
- package/dist/middleware/express.js.map +1 -0
- package/dist/middleware/express.mjs +299 -0
- package/dist/middleware/express.mjs.map +1 -0
- package/dist/middleware/fastify.d.mts +56 -0
- package/dist/middleware/fastify.d.ts +56 -0
- package/dist/middleware/fastify.js +328 -0
- package/dist/middleware/fastify.js.map +1 -0
- package/dist/middleware/fastify.mjs +300 -0
- package/dist/middleware/fastify.mjs.map +1 -0
- package/dist/middleware/nextjs.d.mts +78 -0
- package/dist/middleware/nextjs.d.ts +78 -0
- package/dist/middleware/nextjs.js +346 -0
- package/dist/middleware/nextjs.js.map +1 -0
- package/dist/middleware/nextjs.mjs +320 -0
- package/dist/middleware/nextjs.mjs.map +1 -0
- package/dist/types-BJNy6Hhb.d.mts +166 -0
- package/dist/types-BJNy6Hhb.d.ts +166 -0
- package/package.json +91 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/middleware/express.ts","../../src/verify.ts","../../src/utils.ts","../../src/receipt-fetcher.ts"],"sourcesContent":["/**\n * MixrPay Merchant SDK - Express Middleware\n * \n * Add x402 payment requirement to Express routes with a single line of code.\n * \n * @example\n * ```typescript\n * import express from 'express';\n * import { x402 } from '@mixrpay/merchant-sdk/express';\n * \n * const app = express();\n * \n * // Fixed price\n * app.post('/api/query', x402({ price: 0.05 }), (req, res) => {\n * // This handler only runs after payment is verified\n * res.json({ result: 'success', payer: req.x402Payment?.payer });\n * });\n * \n * // Dynamic pricing\n * app.post('/api/generate', x402({ \n * getPrice: (ctx) => ctx.body?.premium ? 0.10 : 0.05 \n * }), handler);\n * \n * // With JWT receipts\n * app.post('/api/premium', x402({ price: 0.10, receiptMode: 'jwt' }), (req, res) => {\n * // Receipt is set in X-Payment-Receipt header\n * res.json({ receipt: req.x402Payment?.receipt });\n * });\n * ```\n */\n\nimport type { Request, Response, NextFunction } from 'express';\nimport { verifyX402Payment } from '../verify';\nimport { usdToMinor, generateNonce, DEFAULT_FACILITATOR } from '../utils';\nimport { fetchPaymentReceipt } from '../receipt-fetcher';\nimport type { X402Options, X402PaymentResult, X402PaymentRequired, PriceContext } from '../types';\n\n// Extend Express Request type\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n /** Payment result after x402 verification */\n x402Payment?: X402PaymentResult;\n }\n }\n}\n\n/**\n * Express middleware that adds x402 payment requirement to a route.\n * \n * When a request comes in without a valid X-PAYMENT header, it returns\n * a 402 Payment Required response with the payment details.\n * \n * When a valid X-PAYMENT header is provided, it verifies the payment\n * and calls the next handler with `req.x402Payment` containing the result.\n * \n * @param options - x402 configuration options\n * @returns Express middleware function\n */\nexport function x402(options: X402Options) {\n return async (req: Request, res: Response, next: NextFunction) => {\n try {\n // Build context for callbacks\n const context: PriceContext = {\n path: req.path,\n method: req.method,\n headers: req.headers as Record<string, string | string[] | undefined>,\n body: req.body,\n };\n\n // Check if we should skip payment\n if (options.skip) {\n const shouldSkip = await options.skip(context);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Get recipient address\n const recipient = options.recipient || process.env.MIXRPAY_MERCHANT_ADDRESS;\n if (!recipient) {\n console.error('[x402] No recipient address configured. Set MIXRPAY_MERCHANT_ADDRESS env var or pass recipient option.');\n return res.status(500).json({ \n error: 'Payment configuration error',\n message: 'Merchant wallet address not configured',\n });\n }\n\n // Determine price\n const price = options.getPrice \n ? await options.getPrice(context) \n : options.price;\n \n const priceMinor = usdToMinor(price);\n const chainId = options.chainId || 8453;\n const facilitator = options.facilitator || DEFAULT_FACILITATOR;\n\n // Check for X-PAYMENT header\n const paymentHeader = req.headers['x-payment'] as string | undefined;\n\n if (!paymentHeader) {\n // Return 402 with payment requirements\n const nonce = generateNonce();\n const expiresAt = Math.floor(Date.now() / 1000) + 300; // 5 minutes\n\n const paymentRequired: X402PaymentRequired = {\n recipient,\n amount: priceMinor.toString(),\n currency: 'USDC',\n chainId,\n facilitator,\n nonce,\n expiresAt,\n description: options.description,\n };\n\n // Set headers per x402 spec\n res.setHeader('X-Payment-Required', JSON.stringify(paymentRequired));\n res.setHeader('WWW-Authenticate', `X-402 ${Buffer.from(JSON.stringify(paymentRequired)).toString('base64')}`);\n\n return res.status(402).json({\n error: 'Payment required',\n payment: paymentRequired,\n });\n }\n\n // Verify the payment\n const result = await verifyX402Payment(paymentHeader, {\n expectedAmount: priceMinor,\n expectedRecipient: recipient,\n chainId,\n facilitator,\n skipSettlement: options.testMode,\n });\n\n if (!result.valid) {\n return res.status(402).json({\n error: 'Invalid payment',\n reason: result.error,\n });\n }\n\n // Payment verified! Attach to request\n req.x402Payment = result;\n\n // Set response header with tx hash\n if (result.txHash) {\n res.setHeader('X-Payment-TxHash', result.txHash);\n }\n\n // Handle receipt mode\n const receiptMode = options.receiptMode || 'webhook';\n \n if ((receiptMode === 'jwt' || receiptMode === 'both') && result.txHash && result.payer) {\n try {\n const receipt = await fetchPaymentReceipt({\n txHash: result.txHash,\n payer: result.payer,\n recipient,\n amount: priceMinor,\n chainId,\n apiUrl: options.mixrpayApiUrl,\n });\n \n if (receipt) {\n result.receipt = receipt;\n res.setHeader('X-Payment-Receipt', receipt);\n }\n } catch (receiptError) {\n console.warn('[x402] Failed to fetch JWT receipt:', receiptError);\n // Continue without receipt - payment was still successful\n }\n }\n\n // Call onPayment callback\n if (options.onPayment) {\n await options.onPayment(result);\n }\n\n next();\n } catch (error) {\n console.error('[x402] Middleware error:', error);\n return res.status(500).json({\n error: 'Payment processing error',\n message: (error as Error).message,\n });\n }\n };\n}\n\n// Re-export for convenience\nexport { x402 as default };\nexport type { X402Options, X402PaymentResult };\n\n","/**\n * MixrPay Merchant SDK - Payment Verification\n */\n\nimport { recoverTypedDataAddress } from 'viem';\nimport type { \n X402PaymentResult, \n X402PaymentPayload, \n VerifyOptions,\n TransferWithAuthorizationMessage,\n} from './types';\nimport { \n getUSDCDomain, \n TRANSFER_WITH_AUTHORIZATION_TYPES, \n base64Decode,\n minorToUsd,\n DEFAULT_FACILITATOR,\n} from './utils';\n\n// =============================================================================\n// Payment Verification\n// =============================================================================\n\n/**\n * Verify an X-PAYMENT header and optionally settle the payment.\n * \n * @param paymentHeader - The X-PAYMENT header value (base64 encoded JSON)\n * @param options - Verification options\n * @returns Payment verification result\n * \n * @example\n * ```typescript\n * const result = await verifyX402Payment(req.headers['x-payment'], {\n * expectedAmount: 50000n, // 0.05 USDC\n * expectedRecipient: '0x...',\n * });\n * \n * if (result.valid) {\n * console.log(`Payment from ${result.payer}: $${result.amount}`);\n * }\n * ```\n */\nexport async function verifyX402Payment(\n paymentHeader: string,\n options: VerifyOptions\n): Promise<X402PaymentResult> {\n try {\n // 1. Decode the X-PAYMENT header\n let decoded: X402PaymentPayload;\n try {\n const jsonStr = base64Decode(paymentHeader);\n decoded = JSON.parse(jsonStr);\n } catch (e) {\n return { valid: false, error: 'Invalid payment header encoding' };\n }\n\n // 2. Validate payload structure\n if (!decoded.payload?.authorization || !decoded.payload?.signature) {\n return { valid: false, error: 'Missing authorization or signature in payment' };\n }\n\n const { authorization, signature } = decoded.payload;\n const chainId = options.chainId || 8453;\n\n // 3. Build EIP-712 message for verification\n const message: TransferWithAuthorizationMessage = {\n from: authorization.from as `0x${string}`,\n to: authorization.to as `0x${string}`,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as `0x${string}`,\n };\n\n // 4. Recover signer address\n const domain = getUSDCDomain(chainId);\n let signerAddress: string;\n \n try {\n signerAddress = await recoverTypedDataAddress({\n domain,\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message,\n signature: signature as `0x${string}`,\n });\n } catch (e) {\n return { valid: false, error: 'Failed to recover signer from signature' };\n }\n\n // 5. Verify signer matches the 'from' address\n if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {\n return { \n valid: false, \n error: `Signature mismatch: expected ${authorization.from}, got ${signerAddress}` \n };\n }\n\n // 6. Verify payment amount\n const paymentAmount = BigInt(authorization.value);\n if (paymentAmount < options.expectedAmount) {\n return { \n valid: false, \n error: `Insufficient payment: expected ${options.expectedAmount}, got ${paymentAmount}` \n };\n }\n\n // 7. Verify recipient\n if (authorization.to.toLowerCase() !== options.expectedRecipient.toLowerCase()) {\n return { \n valid: false, \n error: `Wrong recipient: expected ${options.expectedRecipient}, got ${authorization.to}` \n };\n }\n\n // 8. Check expiration\n const now = Math.floor(Date.now() / 1000);\n if (Number(authorization.validBefore) < now) {\n return { valid: false, error: 'Payment authorization has expired' };\n }\n\n // 9. Check validAfter\n if (Number(authorization.validAfter) > now) {\n return { valid: false, error: 'Payment authorization is not yet valid' };\n }\n\n // 10. Submit to facilitator for settlement (unless skipped)\n let txHash: string | undefined;\n let settledAt: Date | undefined;\n\n if (!options.skipSettlement) {\n const facilitatorUrl = options.facilitator || DEFAULT_FACILITATOR;\n \n try {\n const settlementResponse = await fetch(`${facilitatorUrl}/settle`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ \n authorization, \n signature,\n chainId,\n }),\n });\n\n if (!settlementResponse.ok) {\n const errorBody = await settlementResponse.text();\n let errorMessage = 'Settlement failed';\n try {\n const errorJson = JSON.parse(errorBody);\n errorMessage = errorJson.message || errorJson.error || errorMessage;\n } catch {\n errorMessage = errorBody || errorMessage;\n }\n return { valid: false, error: `Settlement failed: ${errorMessage}` };\n }\n\n const settlement = await settlementResponse.json() as { txHash?: string; tx_hash?: string };\n txHash = settlement.txHash || settlement.tx_hash;\n settledAt = new Date();\n } catch (e) {\n return { \n valid: false, \n error: `Settlement request failed: ${(e as Error).message}` \n };\n }\n }\n\n // Success!\n return {\n valid: true,\n payer: authorization.from,\n amount: minorToUsd(paymentAmount),\n amountMinor: paymentAmount,\n txHash,\n settledAt: settledAt || new Date(),\n nonce: authorization.nonce,\n };\n\n } catch (error) {\n return { \n valid: false, \n error: `Verification error: ${(error as Error).message}` \n };\n }\n}\n\n/**\n * Parse and validate an X-PAYMENT header without settlement.\n * Useful for checking if a payment is structurally valid before processing.\n */\nexport async function parseX402Payment(\n paymentHeader: string,\n chainId: number = 8453\n): Promise<{\n valid: boolean;\n error?: string;\n payer?: string;\n recipient?: string;\n amount?: number;\n amountMinor?: bigint;\n expiresAt?: Date;\n}> {\n try {\n const jsonStr = base64Decode(paymentHeader);\n const decoded: X402PaymentPayload = JSON.parse(jsonStr);\n\n if (!decoded.payload?.authorization) {\n return { valid: false, error: 'Missing authorization in payment' };\n }\n\n const { authorization, signature } = decoded.payload;\n\n // Verify signature\n const domain = getUSDCDomain(chainId);\n const message: TransferWithAuthorizationMessage = {\n from: authorization.from as `0x${string}`,\n to: authorization.to as `0x${string}`,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as `0x${string}`,\n };\n\n const signerAddress = await recoverTypedDataAddress({\n domain,\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message,\n signature: signature as `0x${string}`,\n });\n\n if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {\n return { valid: false, error: 'Signature mismatch' };\n }\n\n const amountMinor = BigInt(authorization.value);\n \n return {\n valid: true,\n payer: authorization.from,\n recipient: authorization.to,\n amount: minorToUsd(amountMinor),\n amountMinor,\n expiresAt: new Date(Number(authorization.validBefore) * 1000),\n };\n } catch (error) {\n return { valid: false, error: `Parse error: ${(error as Error).message}` };\n }\n}\n\n","/**\n * MixrPay Merchant SDK - Utilities\n */\n\nimport type { EIP712Domain } from './types';\n\n// =============================================================================\n// USDC Constants by Chain\n// =============================================================================\n\nexport const USDC_CONTRACTS: Record<number, `0x${string}`> = {\n 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base Mainnet\n 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia\n};\n\nexport const DEFAULT_FACILITATOR = 'https://x402.org/facilitator';\n\n// =============================================================================\n// EIP-712 Domain\n// =============================================================================\n\nexport function getUSDCDomain(chainId: number): EIP712Domain {\n const verifyingContract = USDC_CONTRACTS[chainId];\n if (!verifyingContract) {\n throw new Error(`Unsupported chain ID: ${chainId}. Supported: ${Object.keys(USDC_CONTRACTS).join(', ')}`);\n }\n\n return {\n name: 'USD Coin',\n version: '2',\n chainId,\n verifyingContract,\n };\n}\n\n// EIP-712 types for TransferWithAuthorization\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'validAfter', type: 'uint256' },\n { name: 'validBefore', type: 'uint256' },\n { name: 'nonce', type: 'bytes32' },\n ],\n} as const;\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Convert USD dollars to USDC minor units (6 decimals)\n */\nexport function usdToMinor(usd: number): bigint {\n return BigInt(Math.round(usd * 1_000_000));\n}\n\n/**\n * Convert USDC minor units to USD dollars\n */\nexport function minorToUsd(minor: bigint): number {\n return Number(minor) / 1_000_000;\n}\n\n/**\n * Generate a random nonce for x402 payments\n */\nexport function generateNonce(): `0x${string}` {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return `0x${Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('')}` as `0x${string}`;\n}\n\n/**\n * Check if an address is valid\n */\nexport function isValidAddress(address: string): address is `0x${string}` {\n return /^0x[a-fA-F0-9]{40}$/.test(address);\n}\n\n/**\n * Normalize an address to lowercase checksum format\n */\nexport function normalizeAddress(address: string): `0x${string}` {\n if (!isValidAddress(address)) {\n throw new Error(`Invalid address: ${address}`);\n }\n return address.toLowerCase() as `0x${string}`;\n}\n\n/**\n * Safe base64 decode that works in both Node.js and browsers\n */\nexport function base64Decode(str: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf-8');\n }\n return atob(str);\n}\n\n/**\n * Safe base64 encode that works in both Node.js and browsers\n */\nexport function base64Encode(str: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf-8').toString('base64');\n }\n return btoa(str);\n}\n\n","/**\n * MixrPay Merchant SDK - Receipt Fetcher\n * \n * Internal utility to fetch JWT receipts from MixrPay API after settlement.\n * Used by x402 middleware to get receipts for the X-Payment-Receipt header.\n */\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst DEFAULT_MIXRPAY_API_URL = process.env.MIXRPAY_BASE_URL || 'http://localhost:3000';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface FetchReceiptParams {\n /** Settlement transaction hash */\n txHash: string;\n /** Payer address */\n payer: string;\n /** Recipient address */\n recipient: string;\n /** Amount in USDC minor units */\n amount: bigint;\n /** Chain ID */\n chainId: number;\n /** Custom MixrPay API URL (optional) */\n apiUrl?: string;\n}\n\ninterface ReceiptResponse {\n receipt: string;\n expiresAt: string;\n}\n\n// =============================================================================\n// Receipt Fetching\n// =============================================================================\n\n/**\n * Fetch a JWT payment receipt from MixrPay API.\n * \n * This is called by the x402 middleware after successful payment verification\n * when receiptMode is 'jwt' or 'both'.\n * \n * @param params - Receipt request parameters\n * @returns JWT receipt string, or null if not available\n */\nexport async function fetchPaymentReceipt(params: FetchReceiptParams): Promise<string | null> {\n const apiUrl = params.apiUrl || DEFAULT_MIXRPAY_API_URL;\n const endpoint = `${apiUrl}/api/v1/receipts`;\n\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n tx_hash: params.txHash,\n payer: params.payer,\n recipient: params.recipient,\n amount: params.amount.toString(),\n chain_id: params.chainId,\n }),\n });\n\n if (!response.ok) {\n // Log but don't throw - receipt is optional\n console.warn(`[x402] Receipt fetch failed: ${response.status} ${response.statusText}`);\n return null;\n }\n\n const data = await response.json() as ReceiptResponse;\n return data.receipt || null;\n } catch (error) {\n // Log but don't throw - payment was successful, receipt is optional\n console.warn('[x402] Receipt fetch error:', (error as Error).message);\n return null;\n }\n}\n\n/**\n * Generate a local receipt for testing purposes.\n * \n * WARNING: This generates an unsigned receipt that will NOT verify.\n * Use only for local development and testing.\n * \n * @param params - Receipt parameters\n * @returns Mock JWT-like string (not cryptographically signed)\n */\nexport function generateMockReceipt(params: FetchReceiptParams): string {\n const header = {\n alg: 'none',\n typ: 'JWT',\n };\n\n const payload = {\n paymentId: `mock_${Date.now()}`,\n amount: params.amount.toString(),\n amountUsd: Number(params.amount) / 1_000_000,\n payer: params.payer,\n recipient: params.recipient,\n chainId: params.chainId,\n txHash: params.txHash,\n settledAt: new Date().toISOString(),\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + 3600,\n _mock: true,\n };\n\n const base64Header = Buffer.from(JSON.stringify(header)).toString('base64url');\n const base64Payload = Buffer.from(JSON.stringify(payload)).toString('base64url');\n\n // Mock signature (not cryptographically valid)\n return `${base64Header}.${base64Payload}.mock_signature_for_testing_only`;\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,kBAAwC;;;ACMjC,IAAM,iBAAgD;AAAA,EAC3D,MAAM;AAAA;AAAA,EACN,OAAO;AAAA;AACT;AAEO,IAAM,sBAAsB;AAM5B,SAAS,cAAc,SAA+B;AAC3D,QAAM,oBAAoB,eAAe,OAAO;AAChD,MAAI,CAAC,mBAAmB;AACtB,UAAM,IAAI,MAAM,yBAAyB,OAAO,gBAAgB,OA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AAK,gBAAgB,SAAS,gBAAgB,WAAW,OAAO,UAAU,OAAO,OAAO;AACtF,YAAI;AACF,gBAAM,UAAU,MAAM,oBAAoB;AAAA,YACxC,QAAQ,OAAO;AAAA,YACf,OAAO,OAAO;AAAA,YACd;AAAA,YACA,QAAQ;AAAA,YACR;AAAA,YACA,QAAQ,QAAQ;AAAA,UAClB,CAAC;AAED,cAAI,SAAS;AACX,mBAAO,UAAU;AACjB,gBAAI,UAAU,qBAAqB,OAAO;AAAA,UAC5C;AAAA,QACF,SAAS,cAAc;AACrB,kBAAQ,KAAK,uCAAuC,YAAY;AAAA,QAElE;AAAA,MACF;AAGA,UAAI,QAAQ,WAAW;AACrB,cAAM,QAAQ,UAAU,MAAM;AAAA,MAChC;AAEA,WAAK;AAAA,IACP,SAAS,OAAO;AACd,cAAQ,MAAM,4BAA4B,KAAK;AAC/C,aAAO,IAAI,OAAO,GAAG,EAAE,KAAK;AAAA,QAC1B,OAAO;AAAA,QACP,SAAU,MAAgB;AAAA,MAC5B,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
// src/verify.ts
|
|
2
|
+
import { recoverTypedDataAddress } from "viem";
|
|
3
|
+
|
|
4
|
+
// src/utils.ts
|
|
5
|
+
var USDC_CONTRACTS = {
|
|
6
|
+
8453: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
7
|
+
// Base Mainnet
|
|
8
|
+
84532: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
|
|
9
|
+
// Base Sepolia
|
|
10
|
+
};
|
|
11
|
+
var DEFAULT_FACILITATOR = "https://x402.org/facilitator";
|
|
12
|
+
function getUSDCDomain(chainId) {
|
|
13
|
+
const verifyingContract = USDC_CONTRACTS[chainId];
|
|
14
|
+
if (!verifyingContract) {
|
|
15
|
+
throw new Error(`Unsupported chain ID: ${chainId}. Supported: ${Object.keys(USDC_CONTRACTS).join(", ")}`);
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
name: "USD Coin",
|
|
19
|
+
version: "2",
|
|
20
|
+
chainId,
|
|
21
|
+
verifyingContract
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
var TRANSFER_WITH_AUTHORIZATION_TYPES = {
|
|
25
|
+
TransferWithAuthorization: [
|
|
26
|
+
{ name: "from", type: "address" },
|
|
27
|
+
{ name: "to", type: "address" },
|
|
28
|
+
{ name: "value", type: "uint256" },
|
|
29
|
+
{ name: "validAfter", type: "uint256" },
|
|
30
|
+
{ name: "validBefore", type: "uint256" },
|
|
31
|
+
{ name: "nonce", type: "bytes32" }
|
|
32
|
+
]
|
|
33
|
+
};
|
|
34
|
+
function usdToMinor(usd) {
|
|
35
|
+
return BigInt(Math.round(usd * 1e6));
|
|
36
|
+
}
|
|
37
|
+
function minorToUsd(minor) {
|
|
38
|
+
return Number(minor) / 1e6;
|
|
39
|
+
}
|
|
40
|
+
function generateNonce() {
|
|
41
|
+
const bytes = new Uint8Array(32);
|
|
42
|
+
crypto.getRandomValues(bytes);
|
|
43
|
+
return `0x${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
44
|
+
}
|
|
45
|
+
function base64Decode(str) {
|
|
46
|
+
if (typeof Buffer !== "undefined") {
|
|
47
|
+
return Buffer.from(str, "base64").toString("utf-8");
|
|
48
|
+
}
|
|
49
|
+
return atob(str);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/verify.ts
|
|
53
|
+
async function verifyX402Payment(paymentHeader, options) {
|
|
54
|
+
try {
|
|
55
|
+
let decoded;
|
|
56
|
+
try {
|
|
57
|
+
const jsonStr = base64Decode(paymentHeader);
|
|
58
|
+
decoded = JSON.parse(jsonStr);
|
|
59
|
+
} catch (e) {
|
|
60
|
+
return { valid: false, error: "Invalid payment header encoding" };
|
|
61
|
+
}
|
|
62
|
+
if (!decoded.payload?.authorization || !decoded.payload?.signature) {
|
|
63
|
+
return { valid: false, error: "Missing authorization or signature in payment" };
|
|
64
|
+
}
|
|
65
|
+
const { authorization, signature } = decoded.payload;
|
|
66
|
+
const chainId = options.chainId || 8453;
|
|
67
|
+
const message = {
|
|
68
|
+
from: authorization.from,
|
|
69
|
+
to: authorization.to,
|
|
70
|
+
value: BigInt(authorization.value),
|
|
71
|
+
validAfter: BigInt(authorization.validAfter),
|
|
72
|
+
validBefore: BigInt(authorization.validBefore),
|
|
73
|
+
nonce: authorization.nonce
|
|
74
|
+
};
|
|
75
|
+
const domain = getUSDCDomain(chainId);
|
|
76
|
+
let signerAddress;
|
|
77
|
+
try {
|
|
78
|
+
signerAddress = await recoverTypedDataAddress({
|
|
79
|
+
domain,
|
|
80
|
+
types: TRANSFER_WITH_AUTHORIZATION_TYPES,
|
|
81
|
+
primaryType: "TransferWithAuthorization",
|
|
82
|
+
message,
|
|
83
|
+
signature
|
|
84
|
+
});
|
|
85
|
+
} catch (e) {
|
|
86
|
+
return { valid: false, error: "Failed to recover signer from signature" };
|
|
87
|
+
}
|
|
88
|
+
if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {
|
|
89
|
+
return {
|
|
90
|
+
valid: false,
|
|
91
|
+
error: `Signature mismatch: expected ${authorization.from}, got ${signerAddress}`
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const paymentAmount = BigInt(authorization.value);
|
|
95
|
+
if (paymentAmount < options.expectedAmount) {
|
|
96
|
+
return {
|
|
97
|
+
valid: false,
|
|
98
|
+
error: `Insufficient payment: expected ${options.expectedAmount}, got ${paymentAmount}`
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
if (authorization.to.toLowerCase() !== options.expectedRecipient.toLowerCase()) {
|
|
102
|
+
return {
|
|
103
|
+
valid: false,
|
|
104
|
+
error: `Wrong recipient: expected ${options.expectedRecipient}, got ${authorization.to}`
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
108
|
+
if (Number(authorization.validBefore) < now) {
|
|
109
|
+
return { valid: false, error: "Payment authorization has expired" };
|
|
110
|
+
}
|
|
111
|
+
if (Number(authorization.validAfter) > now) {
|
|
112
|
+
return { valid: false, error: "Payment authorization is not yet valid" };
|
|
113
|
+
}
|
|
114
|
+
let txHash;
|
|
115
|
+
let settledAt;
|
|
116
|
+
if (!options.skipSettlement) {
|
|
117
|
+
const facilitatorUrl = options.facilitator || DEFAULT_FACILITATOR;
|
|
118
|
+
try {
|
|
119
|
+
const settlementResponse = await fetch(`${facilitatorUrl}/settle`, {
|
|
120
|
+
method: "POST",
|
|
121
|
+
headers: { "Content-Type": "application/json" },
|
|
122
|
+
body: JSON.stringify({
|
|
123
|
+
authorization,
|
|
124
|
+
signature,
|
|
125
|
+
chainId
|
|
126
|
+
})
|
|
127
|
+
});
|
|
128
|
+
if (!settlementResponse.ok) {
|
|
129
|
+
const errorBody = await settlementResponse.text();
|
|
130
|
+
let errorMessage = "Settlement failed";
|
|
131
|
+
try {
|
|
132
|
+
const errorJson = JSON.parse(errorBody);
|
|
133
|
+
errorMessage = errorJson.message || errorJson.error || errorMessage;
|
|
134
|
+
} catch {
|
|
135
|
+
errorMessage = errorBody || errorMessage;
|
|
136
|
+
}
|
|
137
|
+
return { valid: false, error: `Settlement failed: ${errorMessage}` };
|
|
138
|
+
}
|
|
139
|
+
const settlement = await settlementResponse.json();
|
|
140
|
+
txHash = settlement.txHash || settlement.tx_hash;
|
|
141
|
+
settledAt = /* @__PURE__ */ new Date();
|
|
142
|
+
} catch (e) {
|
|
143
|
+
return {
|
|
144
|
+
valid: false,
|
|
145
|
+
error: `Settlement request failed: ${e.message}`
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return {
|
|
150
|
+
valid: true,
|
|
151
|
+
payer: authorization.from,
|
|
152
|
+
amount: minorToUsd(paymentAmount),
|
|
153
|
+
amountMinor: paymentAmount,
|
|
154
|
+
txHash,
|
|
155
|
+
settledAt: settledAt || /* @__PURE__ */ new Date(),
|
|
156
|
+
nonce: authorization.nonce
|
|
157
|
+
};
|
|
158
|
+
} catch (error) {
|
|
159
|
+
return {
|
|
160
|
+
valid: false,
|
|
161
|
+
error: `Verification error: ${error.message}`
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/receipt-fetcher.ts
|
|
167
|
+
var DEFAULT_MIXRPAY_API_URL = process.env.MIXRPAY_BASE_URL || "http://localhost:3000";
|
|
168
|
+
async function fetchPaymentReceipt(params) {
|
|
169
|
+
const apiUrl = params.apiUrl || DEFAULT_MIXRPAY_API_URL;
|
|
170
|
+
const endpoint = `${apiUrl}/api/v1/receipts`;
|
|
171
|
+
try {
|
|
172
|
+
const response = await fetch(endpoint, {
|
|
173
|
+
method: "POST",
|
|
174
|
+
headers: {
|
|
175
|
+
"Content-Type": "application/json"
|
|
176
|
+
},
|
|
177
|
+
body: JSON.stringify({
|
|
178
|
+
tx_hash: params.txHash,
|
|
179
|
+
payer: params.payer,
|
|
180
|
+
recipient: params.recipient,
|
|
181
|
+
amount: params.amount.toString(),
|
|
182
|
+
chain_id: params.chainId
|
|
183
|
+
})
|
|
184
|
+
});
|
|
185
|
+
if (!response.ok) {
|
|
186
|
+
console.warn(`[x402] Receipt fetch failed: ${response.status} ${response.statusText}`);
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
const data = await response.json();
|
|
190
|
+
return data.receipt || null;
|
|
191
|
+
} catch (error) {
|
|
192
|
+
console.warn("[x402] Receipt fetch error:", error.message);
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// src/middleware/express.ts
|
|
198
|
+
function x402(options) {
|
|
199
|
+
return async (req, res, next) => {
|
|
200
|
+
try {
|
|
201
|
+
const context = {
|
|
202
|
+
path: req.path,
|
|
203
|
+
method: req.method,
|
|
204
|
+
headers: req.headers,
|
|
205
|
+
body: req.body
|
|
206
|
+
};
|
|
207
|
+
if (options.skip) {
|
|
208
|
+
const shouldSkip = await options.skip(context);
|
|
209
|
+
if (shouldSkip) {
|
|
210
|
+
return next();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const recipient = options.recipient || process.env.MIXRPAY_MERCHANT_ADDRESS;
|
|
214
|
+
if (!recipient) {
|
|
215
|
+
console.error("[x402] No recipient address configured. Set MIXRPAY_MERCHANT_ADDRESS env var or pass recipient option.");
|
|
216
|
+
return res.status(500).json({
|
|
217
|
+
error: "Payment configuration error",
|
|
218
|
+
message: "Merchant wallet address not configured"
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
const price = options.getPrice ? await options.getPrice(context) : options.price;
|
|
222
|
+
const priceMinor = usdToMinor(price);
|
|
223
|
+
const chainId = options.chainId || 8453;
|
|
224
|
+
const facilitator = options.facilitator || DEFAULT_FACILITATOR;
|
|
225
|
+
const paymentHeader = req.headers["x-payment"];
|
|
226
|
+
if (!paymentHeader) {
|
|
227
|
+
const nonce = generateNonce();
|
|
228
|
+
const expiresAt = Math.floor(Date.now() / 1e3) + 300;
|
|
229
|
+
const paymentRequired = {
|
|
230
|
+
recipient,
|
|
231
|
+
amount: priceMinor.toString(),
|
|
232
|
+
currency: "USDC",
|
|
233
|
+
chainId,
|
|
234
|
+
facilitator,
|
|
235
|
+
nonce,
|
|
236
|
+
expiresAt,
|
|
237
|
+
description: options.description
|
|
238
|
+
};
|
|
239
|
+
res.setHeader("X-Payment-Required", JSON.stringify(paymentRequired));
|
|
240
|
+
res.setHeader("WWW-Authenticate", `X-402 ${Buffer.from(JSON.stringify(paymentRequired)).toString("base64")}`);
|
|
241
|
+
return res.status(402).json({
|
|
242
|
+
error: "Payment required",
|
|
243
|
+
payment: paymentRequired
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
const result = await verifyX402Payment(paymentHeader, {
|
|
247
|
+
expectedAmount: priceMinor,
|
|
248
|
+
expectedRecipient: recipient,
|
|
249
|
+
chainId,
|
|
250
|
+
facilitator,
|
|
251
|
+
skipSettlement: options.testMode
|
|
252
|
+
});
|
|
253
|
+
if (!result.valid) {
|
|
254
|
+
return res.status(402).json({
|
|
255
|
+
error: "Invalid payment",
|
|
256
|
+
reason: result.error
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
req.x402Payment = result;
|
|
260
|
+
if (result.txHash) {
|
|
261
|
+
res.setHeader("X-Payment-TxHash", result.txHash);
|
|
262
|
+
}
|
|
263
|
+
const receiptMode = options.receiptMode || "webhook";
|
|
264
|
+
if ((receiptMode === "jwt" || receiptMode === "both") && result.txHash && result.payer) {
|
|
265
|
+
try {
|
|
266
|
+
const receipt = await fetchPaymentReceipt({
|
|
267
|
+
txHash: result.txHash,
|
|
268
|
+
payer: result.payer,
|
|
269
|
+
recipient,
|
|
270
|
+
amount: priceMinor,
|
|
271
|
+
chainId,
|
|
272
|
+
apiUrl: options.mixrpayApiUrl
|
|
273
|
+
});
|
|
274
|
+
if (receipt) {
|
|
275
|
+
result.receipt = receipt;
|
|
276
|
+
res.setHeader("X-Payment-Receipt", receipt);
|
|
277
|
+
}
|
|
278
|
+
} catch (receiptError) {
|
|
279
|
+
console.warn("[x402] Failed to fetch JWT receipt:", receiptError);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (options.onPayment) {
|
|
283
|
+
await options.onPayment(result);
|
|
284
|
+
}
|
|
285
|
+
next();
|
|
286
|
+
} catch (error) {
|
|
287
|
+
console.error("[x402] Middleware error:", error);
|
|
288
|
+
return res.status(500).json({
|
|
289
|
+
error: "Payment processing error",
|
|
290
|
+
message: error.message
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
export {
|
|
296
|
+
x402 as default,
|
|
297
|
+
x402
|
|
298
|
+
};
|
|
299
|
+
//# sourceMappingURL=express.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/verify.ts","../../src/utils.ts","../../src/receipt-fetcher.ts","../../src/middleware/express.ts"],"sourcesContent":["/**\n * MixrPay Merchant SDK - Payment Verification\n */\n\nimport { recoverTypedDataAddress } from 'viem';\nimport type { \n X402PaymentResult, \n X402PaymentPayload, \n VerifyOptions,\n TransferWithAuthorizationMessage,\n} from './types';\nimport { \n getUSDCDomain, \n TRANSFER_WITH_AUTHORIZATION_TYPES, \n base64Decode,\n minorToUsd,\n DEFAULT_FACILITATOR,\n} from './utils';\n\n// =============================================================================\n// Payment Verification\n// =============================================================================\n\n/**\n * Verify an X-PAYMENT header and optionally settle the payment.\n * \n * @param paymentHeader - The X-PAYMENT header value (base64 encoded JSON)\n * @param options - Verification options\n * @returns Payment verification result\n * \n * @example\n * ```typescript\n * const result = await verifyX402Payment(req.headers['x-payment'], {\n * expectedAmount: 50000n, // 0.05 USDC\n * expectedRecipient: '0x...',\n * });\n * \n * if (result.valid) {\n * console.log(`Payment from ${result.payer}: $${result.amount}`);\n * }\n * ```\n */\nexport async function verifyX402Payment(\n paymentHeader: string,\n options: VerifyOptions\n): Promise<X402PaymentResult> {\n try {\n // 1. Decode the X-PAYMENT header\n let decoded: X402PaymentPayload;\n try {\n const jsonStr = base64Decode(paymentHeader);\n decoded = JSON.parse(jsonStr);\n } catch (e) {\n return { valid: false, error: 'Invalid payment header encoding' };\n }\n\n // 2. Validate payload structure\n if (!decoded.payload?.authorization || !decoded.payload?.signature) {\n return { valid: false, error: 'Missing authorization or signature in payment' };\n }\n\n const { authorization, signature } = decoded.payload;\n const chainId = options.chainId || 8453;\n\n // 3. Build EIP-712 message for verification\n const message: TransferWithAuthorizationMessage = {\n from: authorization.from as `0x${string}`,\n to: authorization.to as `0x${string}`,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as `0x${string}`,\n };\n\n // 4. Recover signer address\n const domain = getUSDCDomain(chainId);\n let signerAddress: string;\n \n try {\n signerAddress = await recoverTypedDataAddress({\n domain,\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message,\n signature: signature as `0x${string}`,\n });\n } catch (e) {\n return { valid: false, error: 'Failed to recover signer from signature' };\n }\n\n // 5. Verify signer matches the 'from' address\n if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {\n return { \n valid: false, \n error: `Signature mismatch: expected ${authorization.from}, got ${signerAddress}` \n };\n }\n\n // 6. Verify payment amount\n const paymentAmount = BigInt(authorization.value);\n if (paymentAmount < options.expectedAmount) {\n return { \n valid: false, \n error: `Insufficient payment: expected ${options.expectedAmount}, got ${paymentAmount}` \n };\n }\n\n // 7. Verify recipient\n if (authorization.to.toLowerCase() !== options.expectedRecipient.toLowerCase()) {\n return { \n valid: false, \n error: `Wrong recipient: expected ${options.expectedRecipient}, got ${authorization.to}` \n };\n }\n\n // 8. Check expiration\n const now = Math.floor(Date.now() / 1000);\n if (Number(authorization.validBefore) < now) {\n return { valid: false, error: 'Payment authorization has expired' };\n }\n\n // 9. Check validAfter\n if (Number(authorization.validAfter) > now) {\n return { valid: false, error: 'Payment authorization is not yet valid' };\n }\n\n // 10. Submit to facilitator for settlement (unless skipped)\n let txHash: string | undefined;\n let settledAt: Date | undefined;\n\n if (!options.skipSettlement) {\n const facilitatorUrl = options.facilitator || DEFAULT_FACILITATOR;\n \n try {\n const settlementResponse = await fetch(`${facilitatorUrl}/settle`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ \n authorization, \n signature,\n chainId,\n }),\n });\n\n if (!settlementResponse.ok) {\n const errorBody = await settlementResponse.text();\n let errorMessage = 'Settlement failed';\n try {\n const errorJson = JSON.parse(errorBody);\n errorMessage = errorJson.message || errorJson.error || errorMessage;\n } catch {\n errorMessage = errorBody || errorMessage;\n }\n return { valid: false, error: `Settlement failed: ${errorMessage}` };\n }\n\n const settlement = await settlementResponse.json() as { txHash?: string; tx_hash?: string };\n txHash = settlement.txHash || settlement.tx_hash;\n settledAt = new Date();\n } catch (e) {\n return { \n valid: false, \n error: `Settlement request failed: ${(e as Error).message}` \n };\n }\n }\n\n // Success!\n return {\n valid: true,\n payer: authorization.from,\n amount: minorToUsd(paymentAmount),\n amountMinor: paymentAmount,\n txHash,\n settledAt: settledAt || new Date(),\n nonce: authorization.nonce,\n };\n\n } catch (error) {\n return { \n valid: false, \n error: `Verification error: ${(error as Error).message}` \n };\n }\n}\n\n/**\n * Parse and validate an X-PAYMENT header without settlement.\n * Useful for checking if a payment is structurally valid before processing.\n */\nexport async function parseX402Payment(\n paymentHeader: string,\n chainId: number = 8453\n): Promise<{\n valid: boolean;\n error?: string;\n payer?: string;\n recipient?: string;\n amount?: number;\n amountMinor?: bigint;\n expiresAt?: Date;\n}> {\n try {\n const jsonStr = base64Decode(paymentHeader);\n const decoded: X402PaymentPayload = JSON.parse(jsonStr);\n\n if (!decoded.payload?.authorization) {\n return { valid: false, error: 'Missing authorization in payment' };\n }\n\n const { authorization, signature } = decoded.payload;\n\n // Verify signature\n const domain = getUSDCDomain(chainId);\n const message: TransferWithAuthorizationMessage = {\n from: authorization.from as `0x${string}`,\n to: authorization.to as `0x${string}`,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce as `0x${string}`,\n };\n\n const signerAddress = await recoverTypedDataAddress({\n domain,\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message,\n signature: signature as `0x${string}`,\n });\n\n if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {\n return { valid: false, error: 'Signature mismatch' };\n }\n\n const amountMinor = BigInt(authorization.value);\n \n return {\n valid: true,\n payer: authorization.from,\n recipient: authorization.to,\n amount: minorToUsd(amountMinor),\n amountMinor,\n expiresAt: new Date(Number(authorization.validBefore) * 1000),\n };\n } catch (error) {\n return { valid: false, error: `Parse error: ${(error as Error).message}` };\n }\n}\n\n","/**\n * MixrPay Merchant SDK - Utilities\n */\n\nimport type { EIP712Domain } from './types';\n\n// =============================================================================\n// USDC Constants by Chain\n// =============================================================================\n\nexport const USDC_CONTRACTS: Record<number, `0x${string}`> = {\n 8453: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base Mainnet\n 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia\n};\n\nexport const DEFAULT_FACILITATOR = 'https://x402.org/facilitator';\n\n// =============================================================================\n// EIP-712 Domain\n// =============================================================================\n\nexport function getUSDCDomain(chainId: number): EIP712Domain {\n const verifyingContract = USDC_CONTRACTS[chainId];\n if (!verifyingContract) {\n throw new Error(`Unsupported chain ID: ${chainId}. Supported: ${Object.keys(USDC_CONTRACTS).join(', ')}`);\n }\n\n return {\n name: 'USD Coin',\n version: '2',\n chainId,\n verifyingContract,\n };\n}\n\n// EIP-712 types for TransferWithAuthorization\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'validAfter', type: 'uint256' },\n { name: 'validBefore', type: 'uint256' },\n { name: 'nonce', type: 'bytes32' },\n ],\n} as const;\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Convert USD dollars to USDC minor units (6 decimals)\n */\nexport function usdToMinor(usd: number): bigint {\n return BigInt(Math.round(usd * 1_000_000));\n}\n\n/**\n * Convert USDC minor units to USD dollars\n */\nexport function minorToUsd(minor: bigint): number {\n return Number(minor) / 1_000_000;\n}\n\n/**\n * Generate a random nonce for x402 payments\n */\nexport function generateNonce(): `0x${string}` {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return `0x${Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('')}` as `0x${string}`;\n}\n\n/**\n * Check if an address is valid\n */\nexport function isValidAddress(address: string): address is `0x${string}` {\n return /^0x[a-fA-F0-9]{40}$/.test(address);\n}\n\n/**\n * Normalize an address to lowercase checksum format\n */\nexport function normalizeAddress(address: string): `0x${string}` {\n if (!isValidAddress(address)) {\n throw new Error(`Invalid address: ${address}`);\n }\n return address.toLowerCase() as `0x${string}`;\n}\n\n/**\n * Safe base64 decode that works in both Node.js and browsers\n */\nexport function base64Decode(str: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'base64').toString('utf-8');\n }\n return atob(str);\n}\n\n/**\n * Safe base64 encode that works in both Node.js and browsers\n */\nexport function base64Encode(str: string): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str, 'utf-8').toString('base64');\n }\n return btoa(str);\n}\n\n","/**\n * MixrPay Merchant SDK - Receipt Fetcher\n * \n * Internal utility to fetch JWT receipts from MixrPay API after settlement.\n * Used by x402 middleware to get receipts for the X-Payment-Receipt header.\n */\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst DEFAULT_MIXRPAY_API_URL = process.env.MIXRPAY_BASE_URL || 'http://localhost:3000';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface FetchReceiptParams {\n /** Settlement transaction hash */\n txHash: string;\n /** Payer address */\n payer: string;\n /** Recipient address */\n recipient: string;\n /** Amount in USDC minor units */\n amount: bigint;\n /** Chain ID */\n chainId: number;\n /** Custom MixrPay API URL (optional) */\n apiUrl?: string;\n}\n\ninterface ReceiptResponse {\n receipt: string;\n expiresAt: string;\n}\n\n// =============================================================================\n// Receipt Fetching\n// =============================================================================\n\n/**\n * Fetch a JWT payment receipt from MixrPay API.\n * \n * This is called by the x402 middleware after successful payment verification\n * when receiptMode is 'jwt' or 'both'.\n * \n * @param params - Receipt request parameters\n * @returns JWT receipt string, or null if not available\n */\nexport async function fetchPaymentReceipt(params: FetchReceiptParams): Promise<string | null> {\n const apiUrl = params.apiUrl || DEFAULT_MIXRPAY_API_URL;\n const endpoint = `${apiUrl}/api/v1/receipts`;\n\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n tx_hash: params.txHash,\n payer: params.payer,\n recipient: params.recipient,\n amount: params.amount.toString(),\n chain_id: params.chainId,\n }),\n });\n\n if (!response.ok) {\n // Log but don't throw - receipt is optional\n console.warn(`[x402] Receipt fetch failed: ${response.status} ${response.statusText}`);\n return null;\n }\n\n const data = await response.json() as ReceiptResponse;\n return data.receipt || null;\n } catch (error) {\n // Log but don't throw - payment was successful, receipt is optional\n console.warn('[x402] Receipt fetch error:', (error as Error).message);\n return null;\n }\n}\n\n/**\n * Generate a local receipt for testing purposes.\n * \n * WARNING: This generates an unsigned receipt that will NOT verify.\n * Use only for local development and testing.\n * \n * @param params - Receipt parameters\n * @returns Mock JWT-like string (not cryptographically signed)\n */\nexport function generateMockReceipt(params: FetchReceiptParams): string {\n const header = {\n alg: 'none',\n typ: 'JWT',\n };\n\n const payload = {\n paymentId: `mock_${Date.now()}`,\n amount: params.amount.toString(),\n amountUsd: Number(params.amount) / 1_000_000,\n payer: params.payer,\n recipient: params.recipient,\n chainId: params.chainId,\n txHash: params.txHash,\n settledAt: new Date().toISOString(),\n iat: Math.floor(Date.now() / 1000),\n exp: Math.floor(Date.now() / 1000) + 3600,\n _mock: true,\n };\n\n const base64Header = Buffer.from(JSON.stringify(header)).toString('base64url');\n const base64Payload = Buffer.from(JSON.stringify(payload)).toString('base64url');\n\n // Mock signature (not cryptographically valid)\n return `${base64Header}.${base64Payload}.mock_signature_for_testing_only`;\n}\n\n","/**\n * MixrPay Merchant SDK - Express Middleware\n * \n * Add x402 payment requirement to Express routes with a single line of code.\n * \n * @example\n * ```typescript\n * import express from 'express';\n * import { x402 } from '@mixrpay/merchant-sdk/express';\n * \n * const app = express();\n * \n * // Fixed price\n * app.post('/api/query', x402({ price: 0.05 }), (req, res) => {\n * // This handler only runs after payment is verified\n * res.json({ result: 'success', payer: req.x402Payment?.payer });\n * });\n * \n * // Dynamic pricing\n * app.post('/api/generate', x402({ \n * getPrice: (ctx) => ctx.body?.premium ? 0.10 : 0.05 \n * }), handler);\n * \n * // With JWT receipts\n * app.post('/api/premium', x402({ price: 0.10, receiptMode: 'jwt' }), (req, res) => {\n * // Receipt is set in X-Payment-Receipt header\n * res.json({ receipt: req.x402Payment?.receipt });\n * });\n * ```\n */\n\nimport type { Request, Response, NextFunction } from 'express';\nimport { verifyX402Payment } from '../verify';\nimport { usdToMinor, generateNonce, DEFAULT_FACILITATOR } from '../utils';\nimport { fetchPaymentReceipt } from '../receipt-fetcher';\nimport type { X402Options, X402PaymentResult, X402PaymentRequired, PriceContext } from '../types';\n\n// Extend Express Request type\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n /** Payment result after x402 verification */\n x402Payment?: X402PaymentResult;\n }\n }\n}\n\n/**\n * Express middleware that adds x402 payment requirement to a route.\n * \n * When a request comes in without a valid X-PAYMENT header, it returns\n * a 402 Payment Required response with the payment details.\n * \n * When a valid X-PAYMENT header is provided, it verifies the payment\n * and calls the next handler with `req.x402Payment` containing the result.\n * \n * @param options - x402 configuration options\n * @returns Express middleware function\n */\nexport function x402(options: X402Options) {\n return async (req: Request, res: Response, next: NextFunction) => {\n try {\n // Build context for callbacks\n const context: PriceContext = {\n path: req.path,\n method: req.method,\n headers: req.headers as Record<string, string | string[] | undefined>,\n body: req.body,\n };\n\n // Check if we should skip payment\n if (options.skip) {\n const shouldSkip = await options.skip(context);\n if (shouldSkip) {\n return next();\n }\n }\n\n // Get recipient address\n const recipient = options.recipient || process.env.MIXRPAY_MERCHANT_ADDRESS;\n if (!recipient) {\n console.error('[x402] No recipient address configured. Set MIXRPAY_MERCHANT_ADDRESS env var or pass recipient option.');\n return res.status(500).json({ \n error: 'Payment configuration error',\n message: 'Merchant wallet address not configured',\n });\n }\n\n // Determine price\n const price = options.getPrice \n ? await options.getPrice(context) \n : options.price;\n \n const priceMinor = usdToMinor(price);\n const chainId = options.chainId || 8453;\n const facilitator = options.facilitator || DEFAULT_FACILITATOR;\n\n // Check for X-PAYMENT header\n const paymentHeader = req.headers['x-payment'] as string | undefined;\n\n if (!paymentHeader) {\n // Return 402 with payment requirements\n const nonce = generateNonce();\n const expiresAt = Math.floor(Date.now() / 1000) + 300; // 5 minutes\n\n const paymentRequired: X402PaymentRequired = {\n recipient,\n amount: priceMinor.toString(),\n currency: 'USDC',\n chainId,\n facilitator,\n nonce,\n expiresAt,\n description: options.description,\n };\n\n // Set headers per x402 spec\n res.setHeader('X-Payment-Required', JSON.stringify(paymentRequired));\n res.setHeader('WWW-Authenticate', `X-402 ${Buffer.from(JSON.stringify(paymentRequired)).toString('base64')}`);\n\n return res.status(402).json({\n error: 'Payment required',\n payment: paymentRequired,\n });\n }\n\n // Verify the payment\n const result = await verifyX402Payment(paymentHeader, {\n expectedAmount: priceMinor,\n expectedRecipient: recipient,\n chainId,\n facilitator,\n skipSettlement: options.testMode,\n });\n\n if (!result.valid) {\n return res.status(402).json({\n error: 'Invalid payment',\n reason: result.error,\n });\n }\n\n // Payment verified! Attach to request\n req.x402Payment = result;\n\n // Set response header with tx hash\n if (result.txHash) {\n res.setHeader('X-Payment-TxHash', result.txHash);\n }\n\n // Handle receipt mode\n const receiptMode = options.receiptMode || 'webhook';\n \n if ((receiptMode === 'jwt' || receiptMode === 'both') && result.txHash && result.payer) {\n try {\n const receipt = await fetchPaymentReceipt({\n txHash: result.txHash,\n payer: result.payer,\n recipient,\n amount: priceMinor,\n chainId,\n apiUrl: options.mixrpayApiUrl,\n });\n \n if (receipt) {\n result.receipt = receipt;\n res.setHeader('X-Payment-Receipt', receipt);\n }\n } catch (receiptError) {\n console.warn('[x402] Failed to fetch JWT receipt:', receiptError);\n // Continue without receipt - payment was still successful\n }\n }\n\n // Call onPayment callback\n if (options.onPayment) {\n await options.onPayment(result);\n }\n\n next();\n } catch (error) {\n console.error('[x402] Middleware error:', error);\n return res.status(500).json({\n error: 'Payment processing error',\n message: (error as Error).message,\n });\n }\n };\n}\n\n// Re-export for convenience\nexport { x402 as default };\nexport type { X402Options, X402PaymentResult };\n\n"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,OAAO,OAAO;AACjB,eAAO,IAAI,OAAO,GAAG,EAAE,KAAK;AAAA,UAC1B,OAAO;AAAA,UACP,QAAQ,OAAO;AAAA,QACjB,CAAC;AAAA,MACH;AAGA,UAAI,cAAc;AAGlB,UAAI,OAAO,QAAQ;AACjB,YAAI,UAAU,oBAAoB,OAAO,MAAM;AAAA,MACjD;AAGA,YAAM,cAAc,QAAQ,eAAe;AAE3C,WAAK,gBAAgB,SAAS,gBAAgB,WAAW,OAAO,UAAU,OAAO,OAAO;AACtF,YAAI;AACF,gBAAM,UAAU,MAAM,oBAAoB;AAAA,YACxC,QAAQ,OAAO;AAAA,YACf,OAAO,OAAO;AAAA,YACd;AAAA,YACA,QAAQ;AAAA,YACR;AAAA,YACA,QAAQ,QAAQ;AAAA,UAClB,CAAC;AAED,cAAI,SAAS;AACX,mBAAO,UAAU;AACjB,gBAAI,UAAU,qBAAqB,OAAO;AAAA,UAC5C;AAAA,QACF,SAAS,cAAc;AACrB,kBAAQ,KAAK,uCAAuC,YAAY;AAAA,QAElE;AAAA,MACF;AAGA,UAAI,QAAQ,WAAW;AACrB,cAAM,QAAQ,UAAU,MAAM;AAAA,MAChC;AAEA,WAAK;AAAA,IACP,SAAS,OAAO;AACd,cAAQ,MAAM,4BAA4B,KAAK;AAC/C,aAAO,IAAI,OAAO,GAAG,EAAE,KAAK;AAAA,QAC1B,OAAO;AAAA,QACP,SAAU,MAAgB;AAAA,MAC5B,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { FastifyPluginCallback, FastifyRequest, FastifyReply } from 'fastify';
|
|
2
|
+
import { X as X402PaymentResult, b as X402Options } from '../types-BJNy6Hhb.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* MixrPay Merchant SDK - Fastify Plugin
|
|
6
|
+
*
|
|
7
|
+
* Add x402 payment requirement to Fastify routes.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import Fastify from 'fastify';
|
|
12
|
+
* import { x402Plugin, x402 } from '@mixrpay/merchant-sdk/fastify';
|
|
13
|
+
*
|
|
14
|
+
* const app = Fastify();
|
|
15
|
+
*
|
|
16
|
+
* // Register the plugin
|
|
17
|
+
* app.register(x402Plugin, {
|
|
18
|
+
* recipient: '0x...', // or use MIXRPAY_MERCHANT_ADDRESS env var
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* // Use on routes
|
|
22
|
+
* app.post('/api/query', { preHandler: x402({ price: 0.05 }) }, async (req, reply) => {
|
|
23
|
+
* return { result: 'success', payer: req.x402Payment?.payer };
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* // With JWT receipts
|
|
27
|
+
* app.post('/api/premium', { preHandler: x402({ price: 0.10, receiptMode: 'jwt' }) }, handler);
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
declare module 'fastify' {
|
|
32
|
+
interface FastifyRequest {
|
|
33
|
+
x402Payment?: X402PaymentResult;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
interface X402PluginOptions {
|
|
37
|
+
/** Default recipient address (can be overridden per route) */
|
|
38
|
+
recipient?: string;
|
|
39
|
+
/** Default chain ID */
|
|
40
|
+
chainId?: number;
|
|
41
|
+
/** Default facilitator URL */
|
|
42
|
+
facilitator?: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Fastify plugin that adds x402 payment support.
|
|
46
|
+
*/
|
|
47
|
+
declare const x402Plugin: FastifyPluginCallback<X402PluginOptions>;
|
|
48
|
+
/**
|
|
49
|
+
* Create a preHandler hook that requires x402 payment.
|
|
50
|
+
*
|
|
51
|
+
* @param options - x402 configuration options
|
|
52
|
+
* @returns Fastify preHandler function
|
|
53
|
+
*/
|
|
54
|
+
declare function x402(options: X402Options): (request: FastifyRequest, reply: FastifyReply) => Promise<undefined>;
|
|
55
|
+
|
|
56
|
+
export { X402Options, X402PaymentResult, type X402PluginOptions, x402, x402Plugin };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { FastifyPluginCallback, FastifyRequest, FastifyReply } from 'fastify';
|
|
2
|
+
import { X as X402PaymentResult, b as X402Options } from '../types-BJNy6Hhb.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* MixrPay Merchant SDK - Fastify Plugin
|
|
6
|
+
*
|
|
7
|
+
* Add x402 payment requirement to Fastify routes.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import Fastify from 'fastify';
|
|
12
|
+
* import { x402Plugin, x402 } from '@mixrpay/merchant-sdk/fastify';
|
|
13
|
+
*
|
|
14
|
+
* const app = Fastify();
|
|
15
|
+
*
|
|
16
|
+
* // Register the plugin
|
|
17
|
+
* app.register(x402Plugin, {
|
|
18
|
+
* recipient: '0x...', // or use MIXRPAY_MERCHANT_ADDRESS env var
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* // Use on routes
|
|
22
|
+
* app.post('/api/query', { preHandler: x402({ price: 0.05 }) }, async (req, reply) => {
|
|
23
|
+
* return { result: 'success', payer: req.x402Payment?.payer };
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* // With JWT receipts
|
|
27
|
+
* app.post('/api/premium', { preHandler: x402({ price: 0.10, receiptMode: 'jwt' }) }, handler);
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
declare module 'fastify' {
|
|
32
|
+
interface FastifyRequest {
|
|
33
|
+
x402Payment?: X402PaymentResult;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
interface X402PluginOptions {
|
|
37
|
+
/** Default recipient address (can be overridden per route) */
|
|
38
|
+
recipient?: string;
|
|
39
|
+
/** Default chain ID */
|
|
40
|
+
chainId?: number;
|
|
41
|
+
/** Default facilitator URL */
|
|
42
|
+
facilitator?: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Fastify plugin that adds x402 payment support.
|
|
46
|
+
*/
|
|
47
|
+
declare const x402Plugin: FastifyPluginCallback<X402PluginOptions>;
|
|
48
|
+
/**
|
|
49
|
+
* Create a preHandler hook that requires x402 payment.
|
|
50
|
+
*
|
|
51
|
+
* @param options - x402 configuration options
|
|
52
|
+
* @returns Fastify preHandler function
|
|
53
|
+
*/
|
|
54
|
+
declare function x402(options: X402Options): (request: FastifyRequest, reply: FastifyReply) => Promise<undefined>;
|
|
55
|
+
|
|
56
|
+
export { X402Options, X402PaymentResult, type X402PluginOptions, x402, x402Plugin };
|