@happyvertical/payments 0.74.8

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"btc.js","sources":["../../src/adapters/btc.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\nimport { PaymentConfigurationError, PaymentProviderError } from '../errors.js';\nimport {\n applyExpiryToPendingStatus,\n currencyMinorUnitDecimals,\n decimalToMinorUnitAmount,\n type FetchLike,\n getFetch,\n minorUnitsToDecimal,\n normalizeAmount,\n normalizeDate,\n normalizeFutureDate,\n normalizeMaxStoredPaymentOptions,\n normalizeMinorUnitAmount,\n normalizeNonEmptyString,\n normalizePositiveMinorUnitAmount,\n normalizePositivePaymentAmount,\n normalizeUrlString,\n pollPaymentStatus,\n readJsonResponse,\n rememberPaymentOption,\n} from '../shared.js';\nimport type {\n CreatePaymentOptionInput,\n PaymentBackend,\n PaymentBackendCapabilities,\n PaymentEvent,\n PaymentOption,\n PaymentStatus,\n PaymentStatusContext,\n PaymentStatusResult,\n PaymentWebhookEvent,\n PayoutResult,\n RefundPaymentInput,\n RefundResult,\n SendPayoutInput,\n WatchPaymentInput,\n} from '../types.js';\n\nexport const BTC_BACKEND_ID = 'btc';\nconst DEFAULT_MAX_STORED_WEBHOOK_DELIVERY_IDS = 50_000;\n\nexport type BtcConfirmationPolicy = (input: {\n amount: number;\n currency: string;\n quoteId?: string;\n}) => number;\n\nexport interface BtcAdapterOptions {\n baseUrl: string;\n apiKey: string;\n storeId: string;\n fetch?: FetchLike;\n currency?: string;\n paymentMethod?: string;\n pollIntervalMs?: number;\n confirmationPolicy?: BtcConfirmationPolicy;\n webhookSecret?: string;\n managedProviderName?: string;\n maxStoredPaymentOptions?: number;\n maxStoredWebhookDeliveryIds?: number;\n}\n\ninterface StoredBtcOption extends PaymentOption {\n requiredConfirmations: number;\n}\n\ninterface BtcpayPaymentMethod {\n decimalAmount?: string;\n destination?: string;\n paymentLink?: string;\n paymentMethod?: string;\n paymentMethodId?: string;\n cryptoCode?: string;\n rate?: string;\n networkFee?: string;\n confirmations?: number;\n}\n\nexport interface BtcpayWebhookEvent extends PaymentWebhookEvent {\n deliveryId: string;\n invoiceId?: string;\n quoteId?: string;\n type?: string;\n status: PaymentStatus;\n raw: unknown;\n}\n\nexport class BtcAdapter implements PaymentBackend {\n readonly capabilities: PaymentBackendCapabilities;\n\n private readonly fetch: FetchLike;\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly storeId: string;\n private readonly currency: string;\n private readonly paymentMethod: string;\n private readonly webhookSecret: string | undefined;\n private readonly maxStoredPaymentOptions: number;\n private readonly maxStoredWebhookDeliveryIds: number;\n private readonly optionsByQuote = new Map<string, StoredBtcOption>();\n private readonly seenWebhookDeliveryIds = new Set<string>();\n\n constructor(private readonly options: BtcAdapterOptions) {\n if (typeof options.baseUrl !== 'string' || !options.baseUrl.trim()) {\n throw new PaymentConfigurationError('BtcAdapter requires baseUrl.');\n }\n\n if (typeof options.apiKey !== 'string' || !options.apiKey.trim()) {\n throw new PaymentConfigurationError('BtcAdapter requires apiKey.');\n }\n\n if (typeof options.storeId !== 'string' || !options.storeId.trim()) {\n throw new PaymentConfigurationError('BtcAdapter requires storeId.');\n }\n\n if (options.webhookSecret !== undefined) {\n if (typeof options.webhookSecret !== 'string') {\n throw new PaymentConfigurationError(\n 'BtcAdapter webhookSecret must be a string when configured.',\n );\n }\n\n if (!options.webhookSecret.trim()) {\n throw new PaymentConfigurationError(\n 'BtcAdapter webhookSecret must not be empty when configured.',\n );\n }\n }\n\n this.fetch = getFetch(options.fetch);\n this.maxStoredPaymentOptions = normalizeMaxStoredPaymentOptions(\n options.maxStoredPaymentOptions,\n 'BtcAdapter maxStoredPaymentOptions',\n );\n this.maxStoredWebhookDeliveryIds = normalizeMaxStoredPaymentOptions(\n options.maxStoredWebhookDeliveryIds ??\n DEFAULT_MAX_STORED_WEBHOOK_DELIVERY_IDS,\n 'BtcAdapter maxStoredWebhookDeliveryIds',\n );\n this.baseUrl = normalizeBtcpayBaseUrl(options.baseUrl);\n this.apiKey = options.apiKey.trim();\n this.storeId = options.storeId.trim();\n this.currency = normalizeCurrencyCode(options.currency ?? 'USD');\n this.paymentMethod = normalizePaymentMethod(\n options.paymentMethod ?? 'BTC-CHAIN',\n );\n this.webhookSecret = options.webhookSecret?.trim();\n const managedProviderName = normalizeOptionalProviderString(\n options.managedProviderName,\n );\n this.capabilities = {\n id: BTC_BACKEND_ID,\n displayName: 'Bitcoin via BTCPay Server',\n settlementCurrency: 'BTC',\n supportedSettlementCurrencies: ['BTC'],\n chain: 'bitcoin',\n settlementShape: 'address',\n x402Capable: false,\n confirmationLatency: {\n expectedSeconds: 600,\n maxExpectedSeconds: 1_800,\n minConfirmations: 1,\n description:\n 'Tiered Bitcoin confirmation policy: 1 confirmation below $100, 2 below $1,000, 3 at $1,000 and above.',\n },\n supportsRefunds: true,\n supportsPayouts: true,\n supportsWebhooks: true,\n metadata: {\n provider: 'btcpay-server',\n managedProviderName,\n },\n };\n }\n\n async createPaymentOption(\n input: CreatePaymentOptionInput,\n ): Promise<PaymentOption> {\n const quoteId = normalizeNonEmptyString(input.quoteId, 'BTC quoteId');\n const expiresAt = normalizeFutureDate(\n input.expiresAt,\n 'BTCPay invoice expiry',\n );\n const currency = normalizeCurrencyCode(input.currency);\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'BTCPay invoice amount',\n );\n const invoiceAmount = minorUnitsToDecimal(\n amount,\n currencyMinorUnitDecimals(currency),\n );\n const invoice = await this.request<Record<string, unknown>>(\n `/api/v1/stores/${encodeURIComponent(this.storeId)}/invoices`,\n {\n method: 'POST',\n body: JSON.stringify({\n amount: invoiceAmount,\n currency,\n metadata: {\n ...input.metadata,\n quoteId,\n buyerEmail: input.buyerEmail,\n description: input.description,\n },\n checkout: {\n expirationMinutes: Math.max(\n 1,\n Math.ceil((expiresAt.getTime() - Date.now()) / 60_000),\n ),\n },\n additionalSearchTerms: [quoteId],\n }),\n },\n );\n const invoiceId = normalizeOptionalProviderString(\n readProviderString(invoice, 'id'),\n );\n const methods =\n extractPaymentMethods(invoice) ??\n (invoiceId\n ? await this.getPaymentMethods(invoiceId)\n : ([] as BtcpayPaymentMethod[]));\n const method = selectBtcPaymentMethod(methods, this.paymentMethod);\n const settlementAmountDecimal =\n method?.decimalAmount === undefined\n ? undefined\n : normalizeAmount(method.decimalAmount);\n const settlementAmount =\n settlementAmountDecimal === undefined\n ? undefined\n : decimalToMinorUnitAmount(\n settlementAmountDecimal,\n currencyMinorUnitDecimals('BTC'),\n 'BTC settlement',\n );\n const payTo = method?.destination?.trim();\n\n if (!invoiceId) {\n throw new PaymentProviderError(\n 'BTCPay invoice response did not include an invoice id.',\n );\n }\n\n if (\n !method ||\n !payTo ||\n settlementAmount === undefined ||\n settlementAmount === 0\n ) {\n throw new PaymentProviderError(\n `BTCPay invoice response did not include a ${this.paymentMethod} payment address and amount.`,\n );\n }\n\n const requiredConfirmations = this.getRequiredConfirmations({\n quoteId,\n amount,\n currency,\n });\n const option: StoredBtcOption = {\n backendId: this.capabilities.id,\n quoteId,\n payTo,\n settlementShape: 'address',\n settlementCurrency: 'BTC',\n settlementAmount,\n amount,\n currency,\n expiresAt,\n providerPaymentId: invoiceId,\n paymentUri: normalizeOptionalProviderString(method?.paymentLink),\n metadata: {\n invoiceId,\n checkoutLink: normalizeOptionalProviderString(\n readString(invoice, 'checkoutLink'),\n ),\n requiredConfirmations,\n rate: method?.rate,\n networkFee: method?.networkFee,\n },\n requiredConfirmations,\n };\n\n rememberPaymentOption(\n this.optionsByQuote,\n quoteId,\n option,\n this.maxStoredPaymentOptions,\n );\n\n return option;\n }\n\n watchPayment(input: WatchPaymentInput): AsyncIterable<PaymentEvent> {\n return pollPaymentStatus(\n {\n ...input,\n pollIntervalMs:\n input.pollIntervalMs ?? this.options.pollIntervalMs ?? 30_000,\n },\n () => this.getStatus(input.quoteId, input.payTo, input.statusContext),\n );\n }\n\n async getStatus(\n quoteId: string,\n payTo: string,\n context: PaymentStatusContext = {},\n ): Promise<PaymentStatusResult> {\n const normalizedQuoteId = normalizeNonEmptyString(quoteId, 'BTC quoteId');\n const normalizedPayTo = normalizeNonEmptyString(payTo, 'BTC payTo');\n const contextProviderPaymentId =\n context.providerPaymentId === undefined\n ? undefined\n : normalizeNonEmptyString(\n context.providerPaymentId,\n 'BTC providerPaymentId',\n );\n const option = this.optionsByQuote.get(normalizedQuoteId);\n const contextAmount =\n context.amount === undefined\n ? undefined\n : normalizeMinorUnitAmount(context.amount, 'BTC status');\n const contextCurrency =\n context.currency === undefined\n ? undefined\n : normalizeCurrencyCode(context.currency);\n const contextSettlementAmount =\n context.settlementAmount === undefined\n ? undefined\n : normalizeMinorUnitAmount(\n context.settlementAmount,\n 'BTC settlement status',\n );\n const invoice =\n option?.providerPaymentId !== undefined ||\n contextProviderPaymentId !== undefined\n ? await this.getInvoice(\n option?.providerPaymentId ?? contextProviderPaymentId ?? '',\n )\n : await this.findInvoice(normalizedQuoteId);\n const invoiceId =\n normalizeOptionalProviderString(readProviderString(invoice, 'id')) ??\n option?.providerPaymentId;\n const status = mapBtcpayStatus(\n readString(invoice, 'status'),\n readString(invoice, 'additionalStatus'),\n );\n const expiresAt =\n option?.expiresAt ??\n (context.expiresAt === undefined\n ? undefined\n : normalizeDate(context.expiresAt));\n const statusWithExpiry = applyExpiryToPendingStatus(status, expiresAt);\n let confirmations = findNestedNonNegativeInteger(invoice, [\n 'confirmations',\n 'confirmationCount',\n ]);\n const contextRequiredConfirmations =\n context.requiredConfirmations === undefined\n ? undefined\n : normalizeConfirmationCount(\n context.requiredConfirmations,\n 'BTC requiredConfirmations',\n );\n const requiredConfirmations =\n option?.requiredConfirmations ??\n contextRequiredConfirmations ??\n this.getRequiredConfirmations({\n quoteId: normalizedQuoteId,\n amount:\n option?.amount ??\n contextAmount ??\n decimalToMinorUnitAmount(\n readDecimalString(invoice, 'amount') ?? '0',\n currencyMinorUnitDecimals(\n option?.currency ?? contextCurrency ?? this.currency,\n ),\n 'BTCPay invoice',\n ),\n currency: option?.currency ?? contextCurrency ?? this.currency,\n });\n\n if (\n statusWithExpiry === 'confirmed' &&\n confirmations === undefined &&\n invoiceId\n ) {\n try {\n confirmations = maxConfirmationCount(\n await this.getPaymentMethods(invoiceId, { requireUsable: false }),\n );\n } catch (error) {\n if (!(error instanceof PaymentProviderError)) {\n throw error;\n }\n }\n }\n\n const effectiveStatus = enforceBtcConfirmations(\n statusWithExpiry,\n confirmations,\n requiredConfirmations,\n );\n const invoiceSettlementAmount = findNestedDecimalString(invoice, [\n 'btcDue',\n 'amountDue',\n ]);\n const receivedSettlementAmount =\n readDecimalString(invoice, 'amountPaid') ??\n findNestedDecimalString(invoice, ['paid']);\n\n return {\n backendId: this.capabilities.id,\n quoteId: normalizedQuoteId,\n payTo: normalizedPayTo,\n status: effectiveStatus,\n settlementCurrency: 'BTC',\n settlementAmount:\n option?.settlementAmount ??\n contextSettlementAmount ??\n (invoiceSettlementAmount === undefined\n ? undefined\n : decimalToMinorUnitAmount(\n invoiceSettlementAmount,\n currencyMinorUnitDecimals('BTC'),\n 'BTC settlement',\n )),\n receivedAmount:\n receivedSettlementAmount === undefined\n ? undefined\n : decimalToMinorUnitAmount(\n receivedSettlementAmount,\n currencyMinorUnitDecimals('BTC'),\n 'BTC received',\n ),\n amount: option?.amount ?? contextAmount,\n currency: option?.currency ?? contextCurrency,\n requiredConfirmations,\n confirmations,\n providerPaymentId: invoiceId,\n transactionId: normalizeOptionalProviderString(\n findNestedProviderString(invoice, ['transactionId', 'txid']),\n ),\n updatedAt: new Date(),\n raw: invoice,\n };\n }\n\n async sendPayout(input: SendPayoutInput): Promise<PayoutResult> {\n if (input.currency !== undefined) {\n const currency = normalizeNonEmptyString(\n input.currency,\n 'BTC payout currency',\n );\n\n if (currency.toUpperCase() !== 'BTC') {\n throw new PaymentConfigurationError(\n `BtcAdapter can only send BTC payouts, received ${input.currency}.`,\n );\n }\n }\n\n const destination = normalizeNonEmptyString(\n input.destination,\n 'BTC payout destination',\n );\n const quoteId =\n input.quoteId === undefined\n ? undefined\n : normalizeNonEmptyString(input.quoteId, 'BTC payout quoteId');\n const idempotencyKey =\n input.idempotencyKey === undefined\n ? quoteId\n : normalizeNonEmptyString(\n input.idempotencyKey,\n 'BTC payout idempotencyKey',\n );\n const amount = normalizePositiveMinorUnitAmount(\n input.amount,\n 'BTC payout amount',\n );\n const payoutAmount = minorUnitsToDecimal(\n amount,\n currencyMinorUnitDecimals('BTC'),\n );\n const result = await this.request<Record<string, unknown>>(\n `/api/v1/stores/${encodeURIComponent(\n this.storeId,\n )}/payment-methods/onchain/${encodeURIComponent(\n this.paymentMethod,\n )}/wallet/transactions`,\n {\n method: 'POST',\n body: JSON.stringify({\n destinations: [\n {\n destination,\n amount: payoutAmount,\n },\n ],\n subtractFromAmount: false,\n metadata: {\n ...input.metadata,\n ...(quoteId === undefined ? {} : { quoteId }),\n ...(idempotencyKey === undefined ? {} : { idempotencyKey }),\n ...(input.memo === undefined ? {} : { memo: input.memo }),\n },\n }),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: 'pending_signature',\n payoutId: normalizeOptionalProviderString(\n readProviderString(result, 'id'),\n ),\n psbt:\n normalizeOptionalProviderString(readProviderString(result, 'psbt')) ??\n normalizeOptionalProviderString(\n readProviderString(result, 'psbtBase64'),\n ) ??\n normalizeOptionalProviderString(\n readProviderString(result, 'unsignedPsbt'),\n ),\n transactionId: normalizeOptionalProviderString(\n readProviderString(result, 'transactionId'),\n ),\n destination,\n amount,\n currency: 'BTC',\n raw: result,\n };\n }\n\n async refundPayment(input: RefundPaymentInput): Promise<RefundResult> {\n if (\n input.currency !== undefined &&\n normalizeCurrencyCode(input.currency) !== 'BTC'\n ) {\n throw new PaymentConfigurationError(\n `BTC refunds require BTC currency when specified, received ${input.currency}.`,\n );\n }\n\n if (!input.destination) {\n throw new PaymentConfigurationError(\n 'BTC refunds require a destination address.',\n );\n }\n\n if (input.amount === undefined) {\n throw new PaymentConfigurationError('BTC refunds require an amount.');\n }\n\n const payout = await this.sendPayout({\n destination: input.destination,\n amount: input.amount,\n currency: 'BTC',\n idempotencyKey: input.idempotencyKey,\n memo: input.reason,\n metadata: input.metadata,\n });\n\n return {\n backendId: this.capabilities.id,\n status: 'requires_action',\n refundId: payout.payoutId,\n transactionId: payout.transactionId,\n amount: payout.amount,\n currency: payout.currency,\n raw: payout.raw,\n };\n }\n\n parseWebhookEvent(payload: string, signature?: string): BtcpayWebhookEvent {\n if (!this.webhookSecret) {\n throw new PaymentConfigurationError(\n 'BtcAdapter parseWebhookEvent requires webhookSecret.',\n );\n }\n\n if (!signature) {\n throw new PaymentProviderError('Missing BTCPay webhook signature.');\n }\n\n verifyBtcpayWebhookSignature(payload, signature, this.webhookSecret);\n\n const event = parseBtcpayWebhookPayload(payload);\n const type = normalizeOptionalWebhookString(\n readProviderString(event, 'type'),\n );\n const deliveryId = normalizeOptionalWebhookString(\n readProviderString(event, 'deliveryId'),\n );\n\n if (!deliveryId) {\n throw new PaymentProviderError('BTCPay webhook deliveryId is required.');\n }\n\n const duplicate = this.seenWebhookDeliveryIds.has(deliveryId);\n\n if (!duplicate) {\n this.seenWebhookDeliveryIds.add(deliveryId);\n while (\n this.seenWebhookDeliveryIds.size > this.maxStoredWebhookDeliveryIds\n ) {\n const oldest = this.seenWebhookDeliveryIds.values().next().value;\n\n if (oldest === undefined) {\n break;\n }\n\n this.seenWebhookDeliveryIds.delete(oldest);\n }\n }\n\n const invoiceId =\n readProviderString(event, 'invoiceId') ??\n findNestedProviderString(event, ['invoiceId', 'id']);\n\n return {\n deliveryId,\n invoiceId: normalizeOptionalWebhookString(invoiceId),\n quoteId: normalizeOptionalWebhookString(\n findNestedProviderString(event, ['quoteId']),\n ),\n duplicate,\n type,\n status: mapBtcpayStatus(\n readString(event, 'status'),\n readString(event, 'additionalStatus'),\n type,\n ),\n raw: event,\n };\n }\n\n private getRequiredConfirmations(input: {\n amount: number;\n currency: string;\n quoteId?: string;\n }): number {\n return normalizeConfirmationCount(\n (this.options.confirmationPolicy ?? defaultBtcConfirmationPolicy)(input),\n 'BTC confirmationPolicy result',\n );\n }\n\n private async getInvoice(\n invoiceId: string,\n ): Promise<Record<string, unknown>> {\n return this.request<Record<string, unknown>>(\n `/api/v1/stores/${encodeURIComponent(\n this.storeId,\n )}/invoices/${encodeURIComponent(invoiceId)}`,\n );\n }\n\n private async findInvoice(quoteId: string): Promise<Record<string, unknown>> {\n const invoices = await this.request<unknown>(\n `/api/v1/stores/${encodeURIComponent(\n this.storeId,\n )}/invoices?textSearch=${encodeURIComponent(quoteId)}`,\n );\n const list = Array.isArray(invoices)\n ? invoices\n : Array.isArray((invoices as { items?: unknown[] }).items)\n ? (invoices as { items: unknown[] }).items\n : [];\n const matches = list.filter((invoice) =>\n invoiceMatchesQuote(invoice, quoteId),\n );\n\n if (matches.length > 1) {\n throw new PaymentProviderError(\n `BTCPay invoice lookup for quote ${quoteId} returned multiple matches.`,\n );\n }\n\n const [match] = matches;\n\n if (!match || typeof match !== 'object') {\n throw new PaymentProviderError(\n `BTCPay invoice for quote ${quoteId} was not found.`,\n );\n }\n\n return match as Record<string, unknown>;\n }\n\n private async getPaymentMethods(\n invoiceId: string,\n options: { requireUsable?: boolean } = {},\n ): Promise<BtcpayPaymentMethod[]> {\n const response = await this.request<unknown>(\n `/api/v1/stores/${encodeURIComponent(\n this.storeId,\n )}/invoices/${encodeURIComponent(invoiceId)}/payment-methods`,\n );\n\n return extractPaymentMethods(response, options.requireUsable) ?? [];\n }\n\n private async request<T>(path: string, init: RequestInit = {}): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set('Authorization', `token ${this.apiKey}`);\n headers.set('Content-Type', 'application/json');\n headers.set('Accept', 'application/json');\n\n const response = await this.fetch(`${this.baseUrl}${path}`, {\n ...init,\n headers,\n });\n\n return readJsonResponse<T>(response, `BTCPay ${path}`);\n }\n}\n\nfunction invoiceMatchesQuote(invoice: unknown, quoteId: string): boolean {\n if (!invoice || typeof invoice !== 'object') {\n return false;\n }\n\n const record = invoice as Record<string, unknown>;\n const metadata =\n record.metadata && typeof record.metadata === 'object'\n ? (record.metadata as Record<string, unknown>)\n : undefined;\n\n if (readProviderString(metadata, 'quoteId')?.trim() === quoteId) {\n return true;\n }\n\n return false;\n}\n\nexport function defaultBtcConfirmationPolicy(input: {\n amount: number;\n currency: string;\n}): number {\n const decimals = currencyMinorUnitDecimals(input.currency);\n const highValueThreshold = decimalToMinorUnitAmount(\n '1000',\n decimals,\n 'BTC confirmation threshold',\n );\n const mediumValueThreshold = decimalToMinorUnitAmount(\n '100',\n decimals,\n 'BTC confirmation threshold',\n );\n\n if (input.amount >= highValueThreshold) {\n return 3;\n }\n\n if (input.amount >= mediumValueThreshold) {\n return 2;\n }\n\n return 1;\n}\n\nexport function verifyBtcpayWebhookSignature(\n payload: string,\n signature: string,\n secret: string,\n): void {\n if (typeof payload !== 'string') {\n throw new PaymentProviderError('BTCPay webhook payload must be a string.');\n }\n\n const normalizedSignature = normalizeNonEmptyString(\n signature,\n 'BTCPay webhook signature',\n );\n const normalizedSecret = normalizeNonEmptyString(\n secret,\n 'BTCPay webhook secret',\n );\n const expected = createHmac('sha256', normalizedSecret)\n .update(payload)\n .digest('hex');\n const actual = normalizedSignature.replace(/^sha256=/, '');\n\n if (!/^[a-f0-9]{64}$/i.test(actual)) {\n throw new PaymentProviderError('Invalid BTCPay webhook signature.');\n }\n\n const expectedBuffer = Buffer.from(expected, 'hex');\n const actualBuffer = Buffer.from(actual, 'hex');\n\n if (\n expectedBuffer.length !== actualBuffer.length ||\n !timingSafeEqual(expectedBuffer, actualBuffer)\n ) {\n throw new PaymentProviderError('Invalid BTCPay webhook signature.');\n }\n}\n\nfunction parseBtcpayWebhookPayload(payload: string): Record<string, unknown> {\n try {\n const event = JSON.parse(payload);\n\n if (!event || typeof event !== 'object' || Array.isArray(event)) {\n throw new PaymentProviderError('Invalid BTCPay webhook JSON payload.');\n }\n\n return event as Record<string, unknown>;\n } catch (error) {\n if (error instanceof PaymentProviderError) {\n throw error;\n }\n\n throw new PaymentProviderError('Invalid BTCPay webhook JSON payload.', {\n cause: error,\n });\n }\n}\n\nfunction normalizeOptionalWebhookString(\n value: string | undefined,\n): string | undefined {\n const normalized = value?.trim();\n\n return normalized ? normalized : undefined;\n}\n\nfunction normalizeOptionalProviderString(\n value: string | undefined,\n): string | undefined {\n const normalized = value?.trim();\n\n return normalized ? normalized : undefined;\n}\n\nfunction mapBtcpayStatus(\n status: string | undefined,\n additionalStatus?: string,\n type?: string,\n): PaymentStatus {\n const statusToken = normalizeBtcpayToken(status);\n const additionalStatusToken = normalizeBtcpayToken(additionalStatus);\n const typeToken = normalizeBtcpayToken(type);\n const tokens = [statusToken, additionalStatusToken, typeToken];\n\n if (\n tokens.some((token) =>\n ['incomplete', 'invoiceincomplete', 'new', 'unpaid'].includes(token),\n )\n ) {\n return 'pending';\n }\n\n if (\n tokens.some((token) =>\n [\n 'settled',\n 'complete',\n 'confirmed',\n 'invoicesettled',\n 'invoicepaymentsettled',\n ].includes(token),\n )\n ) {\n return 'confirmed';\n }\n\n if (tokens.some((token) => ['expired', 'invoiceexpired'].includes(token))) {\n return 'expired';\n }\n\n if (\n tokens.some((token) =>\n ['invalid', 'failed', 'invoiceinvalid'].includes(token),\n )\n ) {\n return 'failed';\n }\n\n if (\n tokens.some((token) =>\n [\n 'processing',\n 'paid',\n 'paidlate',\n 'paidpartial',\n 'invoiceprocessing',\n 'invoicereceivedpayment',\n 'invoicepaymentsettling',\n ].includes(token),\n )\n ) {\n return 'processing';\n }\n\n return 'pending';\n}\n\nfunction normalizeBtcpayToken(value: string | undefined): string {\n return (\n value\n ?.trim()\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '') ?? ''\n );\n}\n\nfunction enforceBtcConfirmations(\n status: PaymentStatus,\n confirmations: number | undefined,\n requiredConfirmations: number,\n): PaymentStatus {\n if (status !== 'confirmed') {\n return status;\n }\n\n if (requiredConfirmations <= 0) {\n return status;\n }\n\n if (confirmations === undefined) {\n return 'processing';\n }\n\n return confirmations >= requiredConfirmations ? 'confirmed' : 'processing';\n}\n\nfunction normalizeConfirmationCount(value: number, label: string): number {\n if (!Number.isInteger(value) || value < 0) {\n throw new PaymentConfigurationError(\n `${label} must be a non-negative integer, received ${String(value)}.`,\n );\n }\n\n return value;\n}\n\nfunction normalizeCurrencyCode(value: string): string {\n if (typeof value !== 'string') {\n throw new PaymentConfigurationError(\n `BtcAdapter currency must be a three-letter currency code, received ${String(value)}.`,\n );\n }\n\n const normalized = value.trim().toUpperCase();\n\n if (!/^[A-Z]{3}$/.test(normalized)) {\n throw new PaymentConfigurationError(\n `BtcAdapter currency must be a three-letter currency code, received ${String(value)}.`,\n );\n }\n\n return normalized;\n}\n\nfunction normalizePaymentMethod(value: string): string {\n if (typeof value !== 'string') {\n throw new PaymentConfigurationError(\n 'BtcAdapter paymentMethod must be a string.',\n );\n }\n\n const normalized = value.trim();\n\n if (!normalized) {\n throw new PaymentConfigurationError(\n 'BtcAdapter paymentMethod must not be empty when configured.',\n );\n }\n\n return normalized;\n}\n\nfunction normalizeBtcpayBaseUrl(value: string): string {\n const normalized = normalizeUrlString(value, 'BtcAdapter baseUrl')\n .trim()\n .replace(/\\/$/, '');\n const parsed = new URL(normalized);\n\n if (parsed.search || parsed.hash || !['', '/'].includes(parsed.pathname)) {\n throw new PaymentConfigurationError(\n 'BtcAdapter baseUrl must be an origin URL without path, query, or fragment.',\n );\n }\n\n return parsed.origin;\n}\n\nfunction extractPaymentMethods(\n value: unknown,\n requireUsable = true,\n): BtcpayPaymentMethod[] | undefined {\n if (!value) {\n return undefined;\n }\n\n if (Array.isArray(value)) {\n const methods = value\n .filter(\n (item): item is Record<string, unknown> =>\n Boolean(item) && typeof item === 'object' && !Array.isArray(item),\n )\n .map(readPaymentMethod);\n\n return requireUsable ? methods.filter(isUsablePaymentMethod) : methods;\n }\n\n if (typeof value !== 'object') {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n\n for (const key of ['paymentMethods', 'paymentMethodDetails', 'methods']) {\n const nested = extractPaymentMethods(record[key], requireUsable);\n\n if (nested?.length) {\n return nested;\n }\n }\n\n const methods = Object.entries(record)\n .filter(([key, item]) => key.toUpperCase().includes('BTC') && item)\n .map(([key, item]) => {\n const method = readPaymentMethod(item as Record<string, unknown>);\n\n return {\n ...method,\n paymentMethod: method.paymentMethod ?? key,\n };\n });\n\n return requireUsable ? methods.filter(isUsablePaymentMethod) : methods;\n}\n\nfunction selectBtcPaymentMethod(\n methods: BtcpayPaymentMethod[],\n paymentMethod: string,\n): BtcpayPaymentMethod | undefined {\n const target = paymentMethod.toUpperCase();\n const aliases =\n target === 'BTC' || target === 'BTC-CHAIN'\n ? ['BTC-CHAIN', 'BTC', 'BITCOIN']\n : [target];\n\n return methods.find((method) => paymentMethodMatchesAlias(method, aliases));\n}\n\nfunction paymentMethodMatchesAlias(\n method: BtcpayPaymentMethod,\n aliases: string[],\n): boolean {\n const methodIdentifiers = [method.paymentMethod, method.paymentMethodId]\n .map((value) => value?.trim().toUpperCase())\n .filter((value): value is string => Boolean(value));\n\n if (methodIdentifiers.length > 0) {\n return methodIdentifiers.some((value) => aliases.includes(value));\n }\n\n const cryptoCode = method.cryptoCode?.trim().toUpperCase();\n\n return cryptoCode !== undefined && aliases.includes(cryptoCode);\n}\n\nfunction readPaymentMethod(\n value: Record<string, unknown>,\n): BtcpayPaymentMethod {\n return {\n decimalAmount:\n readDecimalString(value, 'amount') ?? readDecimalString(value, 'due'),\n destination:\n readProviderString(value, 'destination') ??\n readProviderString(value, 'address') ??\n readProviderString(value, 'paymentAddress'),\n paymentLink:\n readProviderString(value, 'paymentLink') ??\n readProviderString(value, 'paymentUrl'),\n paymentMethod:\n readProviderString(value, 'paymentMethod') ??\n readProviderString(value, 'paymentMethodId'),\n paymentMethodId: readProviderString(value, 'paymentMethodId'),\n cryptoCode: readProviderString(value, 'cryptoCode'),\n rate: readDecimalString(value, 'rate'),\n networkFee: readDecimalString(value, 'networkFee'),\n confirmations: findNestedNonNegativeInteger(value, [\n 'confirmations',\n 'confirmationCount',\n ]),\n };\n}\n\nfunction isUsablePaymentMethod(method: BtcpayPaymentMethod): boolean {\n return Boolean(method.destination && method.decimalAmount);\n}\n\nfunction maxConfirmationCount(\n methods: BtcpayPaymentMethod[],\n): number | undefined {\n const confirmations = methods\n .map((method) => method.confirmations)\n .filter((value): value is number => value !== undefined);\n\n return confirmations.length === 0 ? undefined : Math.max(...confirmations);\n}\n\nfunction readString(\n value: Record<string, unknown> | unknown,\n key: string,\n): string | undefined {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n\n const item = (value as Record<string, unknown>)[key];\n\n if (typeof item === 'string') {\n return item;\n }\n\n if (typeof item === 'number') {\n return String(item);\n }\n\n return undefined;\n}\n\nfunction readProviderString(\n value: Record<string, unknown> | unknown,\n key: string,\n): string | undefined {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n\n const item = (value as Record<string, unknown>)[key];\n\n return typeof item === 'string' ? item : undefined;\n}\n\nfunction findNestedString(\n value: unknown,\n keys: string[],\n depth = 0,\n): string | undefined {\n if (!value || typeof value !== 'object' || depth > 16) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n\n for (const key of keys) {\n const direct = readString(record, key);\n if (direct) {\n return direct;\n }\n }\n\n for (const child of Object.values(record)) {\n const match = findNestedString(child, keys, depth + 1);\n\n if (match) {\n return match;\n }\n }\n\n return undefined;\n}\n\nfunction findNestedProviderString(\n value: unknown,\n keys: string[],\n depth = 0,\n): string | undefined {\n if (!value || typeof value !== 'object' || depth > 16) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n\n for (const key of keys) {\n const direct = readProviderString(record, key);\n if (direct) {\n return direct;\n }\n }\n\n for (const child of Object.values(record)) {\n const match = findNestedProviderString(child, keys, depth + 1);\n\n if (match) {\n return match;\n }\n }\n\n return undefined;\n}\n\nfunction findNestedNonNegativeInteger(\n value: unknown,\n keys: string[],\n): number | undefined {\n const raw = findNestedString(value, keys);\n\n if (raw === undefined || !/^\\d+$/.test(raw)) {\n return undefined;\n }\n\n const parsed = Number(raw);\n\n return Number.isSafeInteger(parsed) ? parsed : undefined;\n}\n\nfunction findNestedDecimalString(\n value: unknown,\n keys: string[],\n depth = 0,\n): string | undefined {\n if (!value || typeof value !== 'object' || depth > 16) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n\n for (const key of keys) {\n const direct = readDecimalString(record, key);\n if (direct) {\n return direct;\n }\n }\n\n for (const child of Object.values(record)) {\n const match = findNestedDecimalString(child, keys, depth + 1);\n\n if (match) {\n return match;\n }\n }\n\n return undefined;\n}\n\nfunction readDecimalString(\n value: Record<string, unknown>,\n key: string,\n): string | undefined {\n const item = value[key];\n\n if (typeof item !== 'string') {\n return undefined;\n }\n\n try {\n return normalizeAmount(item);\n } catch {\n return undefined;\n }\n}\n"],"names":["methods"],"mappings":";;;AAuCO,MAAM,iBAAiB;AAC9B,MAAM,0CAA0C;AAgDzC,MAAM,WAAqC;AAAA,EAehD,YAA6B,SAA4B;AAA5B,SAAA,UAAA;AAC3B,QAAI,OAAO,QAAQ,YAAY,YAAY,CAAC,QAAQ,QAAQ,QAAQ;AAClE,YAAM,IAAI,0BAA0B,8BAA8B;AAAA,IACpE;AAEA,QAAI,OAAO,QAAQ,WAAW,YAAY,CAAC,QAAQ,OAAO,QAAQ;AAChE,YAAM,IAAI,0BAA0B,6BAA6B;AAAA,IACnE;AAEA,QAAI,OAAO,QAAQ,YAAY,YAAY,CAAC,QAAQ,QAAQ,QAAQ;AAClE,YAAM,IAAI,0BAA0B,8BAA8B;AAAA,IACpE;AAEA,QAAI,QAAQ,kBAAkB,QAAW;AACvC,UAAI,OAAO,QAAQ,kBAAkB,UAAU;AAC7C,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAAA,MAEJ;AAEA,UAAI,CAAC,QAAQ,cAAc,QAAQ;AACjC,cAAM,IAAI;AAAA,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KAAK,GAAG,GAAG;AAC3C,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,OAAO,GAAG;AAEzB,SAAO,OAAO,cAAc,MAAM,IAAI,SAAS;AACjD;AAEA,SAAS,wBACP,OACA,MACA,QAAQ,GACY;AACpB,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,QAAQ,IAAI;AACrD,WAAO;AAAA,EACT;AAEA,QAAM,SAAS;AAEf,aAAW,OAAO,MAAM;AACtB,UAAM,SAAS,kBAAkB,QAAQ,GAAG;AAC5C,QAAI,QAAQ;AACV,aAAO;AAAA,IACT;AAAA,EACF;AAEA,aAAW,SAAS,OAAO,OAAO,MAAM,GAAG;AACzC,UAAM,QAAQ,wBAAwB,OAAO,MAAM,QAAQ,CAAC;AAE5D,QAAI,OAAO;AACT,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,kBACP,OACA,KACoB;AACpB,QAAM,OAAO,MAAM,GAAG;AAEtB,MAAI,OAAO,SAAS,UAAU;AAC5B,WAAO;AAAA,EACT;AAEA,MAAI;AACF,WAAO,gBAAgB,IAAI;AAAA,EAC7B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;"}
@@ -0,0 +1,54 @@
1
+ import { FetchLike } from '../shared.js';
2
+ import { CreatePaymentOptionInput, PaymentBackend, PaymentBackendCapabilities, PaymentEvent, PaymentOption, PaymentStatus, PaymentStatusContext, PaymentStatusResult, PaymentWebhookEvent, PayoutResult, RefundPaymentInput, RefundResult, SendPayoutInput, WatchPaymentInput } from '../types.js';
3
+ export declare const STRIPE_BACKEND_ID = "stripe";
4
+ export interface StripeAdapterOptions {
5
+ secretKey: string;
6
+ fetch?: FetchLike;
7
+ apiBaseUrl?: string;
8
+ apiVersion?: string;
9
+ defaultCurrency?: string;
10
+ supportedCurrencies?: string[];
11
+ successUrl?: string;
12
+ cancelUrl?: string;
13
+ checkoutMode?: string;
14
+ webhookSecret?: string;
15
+ pollIntervalMs?: number;
16
+ maxStoredPaymentOptions?: number;
17
+ maxStoredWebhookEventIds?: number;
18
+ }
19
+ export interface StripeWebhookEvent extends PaymentWebhookEvent {
20
+ id: string;
21
+ type: string;
22
+ status: PaymentStatus;
23
+ quoteId?: string;
24
+ providerPaymentId?: string;
25
+ raw: unknown;
26
+ }
27
+ export declare class StripeAdapter implements PaymentBackend {
28
+ private readonly options;
29
+ readonly capabilities: PaymentBackendCapabilities;
30
+ private readonly fetch;
31
+ private readonly secretKey;
32
+ private readonly apiBaseUrl;
33
+ private readonly apiVersion;
34
+ private readonly defaultCurrency;
35
+ private readonly supportedCurrencies;
36
+ private readonly checkoutMode;
37
+ private readonly webhookSecret;
38
+ private readonly maxStoredPaymentOptions;
39
+ private readonly maxStoredWebhookEventIds;
40
+ private readonly optionsByQuote;
41
+ private readonly seenWebhookEventIds;
42
+ constructor(options: StripeAdapterOptions);
43
+ createPaymentOption(input: CreatePaymentOptionInput): Promise<PaymentOption>;
44
+ watchPayment(input: WatchPaymentInput): AsyncIterable<PaymentEvent>;
45
+ getStatus(quoteId: string, payTo: string, context?: PaymentStatusContext): Promise<PaymentStatusResult>;
46
+ sendPayout(input: SendPayoutInput): Promise<PayoutResult>;
47
+ refundPayment(input: RefundPaymentInput): Promise<RefundResult>;
48
+ parseWebhookEvent(payload: string, signature?: string): StripeWebhookEvent;
49
+ private stripeRequest;
50
+ private assertSupportedCurrency;
51
+ private resolveStripeRefundReferenceParam;
52
+ }
53
+ export declare function verifyStripeWebhookSignature(payload: string, signatureHeader: string, secret: string, toleranceSeconds?: number): void;
54
+ //# sourceMappingURL=stripe.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stripe.d.ts","sourceRoot":"","sources":["../../src/adapters/stripe.ts"],"names":[],"mappings":"AAMA,OAAO,EAEL,KAAK,SAAS,EAYf,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EACV,wBAAwB,EACxB,cAAc,EACd,0BAA0B,EAC1B,YAAY,EACZ,aAAa,EACb,aAAa,EACb,o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