@happyvertical/payments 0.107.0 → 0.109.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/AGENT.md CHANGED
@@ -43,3 +43,18 @@ parsing. Missing evidence throws; an empty array is valid. Unknown lifecycle
43
43
  statuses map to `unknown`, unknown dispute event types throw. Never infer money
44
44
  movement from lifecycle status; consumers own ledger postings, ownership,
45
45
  durable deduplication, ordering, and recovery. See README dispute documentation.
46
+
47
+
48
+ ## Checkout reverse reconciliation
49
+
50
+ `lookupCheckout({ paymentIntentId?, chargeId?, livemode, stripeAccount?, maxPages? })`
51
+ reads existing payment evidence and exhausts filtered Checkout Session pagination.
52
+ Root `PaymentCheckoutLookupInput` / `PaymentCheckoutLookupResult` are generic;
53
+ Stripe adds `StripeCheckoutLookupInput` account scope. Only `status: no_match`
54
+ proves complete absence. `matched` returns validated session/PI/quote identity,
55
+ `accountId` and environment, without raw payloads. `indeterminate` reasons are
56
+ `pagination_limit`, `ambiguous`, `missing_quote`; never acknowledge these as
57
+ unrelated. Provider/identity failures throw. The method is optional on
58
+ PaymentBackend, preserving other integrations. Bind quote/account to local owner
59
+ records and retain settlement-ordering retries; provider metadata is not
60
+ application authorization. See README for exact pagination and identity rules.
package/README.md CHANGED
@@ -475,3 +475,53 @@ options.
475
475
  `pollPaymentStatus` emits `event: 'timeout'` when polling times out. The
476
476
  associated `status` remains the last observed status, or `pending` if no status
477
477
  was observed, rather than being coerced to `failed`.
478
+
479
+
480
+ ### Reverse checkout reconciliation (Stripe)
481
+
482
+ `lookupCheckout` is an optional `PaymentBackend` method. Stripe implements it
483
+ without relying on a cached create response or PaymentIntent metadata, including
484
+ Checkout Sessions created by earlier SDK releases:
485
+
486
+ ```typescript
487
+ const result = await stripe.lookupCheckout({
488
+ chargeId: dispute.chargeId,
489
+ paymentIntentId: dispute.paymentIntentId, // optional; if supplied, must agree
490
+ stripeAccount: verifiedAccount, // omit for platform scope
491
+ livemode: dispute.livemode, // required expected environment
492
+ });
493
+ if (result.status === 'matched') {
494
+ // result.checkoutId, paymentIntentId, quoteId, optional clientReferenceId
495
+ // Bind quoteId to YOUR persisted owner/account before deciding what to do.
496
+ } else if (result.status === 'no_match') {
497
+ // Complete absence of a Checkout Session for this authenticated payment.
498
+ } else {
499
+ // indeterminate: pagination_limit, ambiguous, or missing_quote.
500
+ // Retry/investigate; do not treat this as unrelated or acknowledge ownership.
501
+ }
502
+ ```
503
+
504
+ Supply a PaymentIntent id, a Charge id, or both. Every Charge/PaymentIntent is
505
+ reread and validated for resource identity and environment; both supplied ids
506
+ must agree. A Charge explicitly lacking a PaymentIntent returns `no_match`.
507
+ Otherwise Stripe's [Checkout Session list PaymentIntent filter](https://docs.stripe.com/api/checkout/sessions/list)
508
+ is paginated to completion (100 per page). `maxPages` defaults to 10 and accepts
509
+ 1–100; reaching the cap returns `indeterminate`, even after finding a candidate.
510
+ Malformed pages, duplicate sessions/cursors, resource/linkage mismatch, wrong
511
+ account/environment, and provider failures throw, never `no_match`.
512
+
513
+ A unique Session in payment mode returns `matched` only with a nonempty quote
514
+ from `metadata.quoteId` or `client_reference_id`; when both exist they must
515
+ agree exactly. Missing both returns `indeterminate: missing_quote`; multiple
516
+ Sessions return `indeterminate: ambiguous`. The result includes `backendId`,
517
+ `livemode`, authenticated `accountId` (absent for platform), and available
518
+ payment references. It exposes no raw provider payload. Adapter account scope
519
+ cannot be overridden with another account. All reads use that same scope.
520
+
521
+ This proves provider correlation, not application authorization or settlement.
522
+ Connected account operators control their metadata: validate the quote against
523
+ your own owner/account records. A matched quote with no local settlement can
524
+ mean settlement is delayed or the create response was lost; retain a retry path.
525
+ Only complete `no_match` proves no hosted Checkout Session, and it says nothing
526
+ about payments created by another API (including manual authorization). A
527
+ backend without this optional method supplies no absence evidence.
@@ -1,5 +1,5 @@
1
1
  import { FetchLike } from '../shared.js';
2
- import { AuthorizationResult, AuthorizePaymentInput, CapturePaymentInput, CaptureResult, CreatePaymentOptionInput, CreateSetupSessionInput, GetSetupResultInput, PaymentBackend, PaymentBackendCapabilities, PaymentDispute, PaymentEvent, PaymentOption, PaymentStatus, PaymentStatusContext, PaymentStatusResult, PaymentWebhookEvent, PayoutResult, RefundPaymentInput, RefundResult, SavedPaymentMethod, SendPayoutInput, SetupSession, VoidPaymentInput, VoidResult, WatchPaymentInput } from '../types.js';
2
+ import { AuthorizationResult, AuthorizePaymentInput, CapturePaymentInput, CaptureResult, CreatePaymentOptionInput, CreateSetupSessionInput, GetSetupResultInput, PaymentBackend, PaymentBackendCapabilities, PaymentCheckoutLookupInput, PaymentCheckoutLookupResult, PaymentDispute, PaymentEvent, PaymentOption, PaymentStatus, PaymentStatusContext, PaymentStatusResult, PaymentWebhookEvent, PayoutResult, RefundPaymentInput, RefundResult, SavedPaymentMethod, SendPayoutInput, SetupSession, VoidPaymentInput, VoidResult, WatchPaymentInput } from '../types.js';
3
3
  export declare const STRIPE_BACKEND_ID = "stripe";
4
4
  export interface StripeAdapterOptions {
5
5
  secretKey: string;
@@ -99,6 +99,8 @@ export interface StripeGetDisputeOptions extends StripeAccountScope {
99
99
  /** Reject an authoritative reread from a different environment. */
100
100
  expectedLivemode?: boolean;
101
101
  }
102
+ export interface StripeCheckoutLookupInput extends PaymentCheckoutLookupInput, StripeAccountScope {
103
+ }
102
104
  /** Connected account onboarding and capability state. */
103
105
  export interface StripeConnectAccountStatus {
104
106
  accountId: string;
@@ -258,6 +260,12 @@ export declare class StripeAdapter implements PaymentBackend {
258
260
  getAccountCapabilities(accountId: string): Promise<StripeConnectAccountStatus>;
259
261
  /** Authoritative read. No request or adapter account scope means platform. */
260
262
  getDispute(disputeId: string, options?: StripeGetDisputeOptions): Promise<StripeDispute>;
263
+ /**
264
+ * Resolve existing PI/Charge evidence to a Checkout Session in the authenticated
265
+ * account and required environment. No local cache or new PI metadata needed.
266
+ * A quote is correlation evidence, not authorization: bind it to your owner.
267
+ */
268
+ lookupCheckout(input: StripeCheckoutLookupInput): Promise<PaymentCheckoutLookupResult>;
261
269
  private verifyWebhookEvent;
262
270
  private recordWebhookEvent;
263
271
  private assertAdapterAccount;
@@ -1 +1 @@
1
- {"version":3,"file":"stripe.d.ts","sourceRoot":"","sources":["../../src/adapters/stripe.ts"],"names":[],"mappings":"AAOA,OAAO,EAEL,KAAK,SAAS,EAaf,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EACV,mBAAmB,EACnB,qBAAqB,EACrB,mBAAmB,EACnB,aAAa,EACb,wBAAwB,EACxB,uBAAuB,EACvB,mBAAmB,EACnB,cAAc,EACd,0BAA0B,EAC1B,cAAc,EAEd,YAAY,EACZ,aAAa,EACb,aAAa,EACb,oBAAoB,EACpB,mBAAmB,EACnB,mBAAmB,EACnB,YAAY,EACZ,kBAAkB,EAClB,YAAY,EACZ,kBAAkB,EAClB,eAAe,EACf,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,iBAAiB,EAClB,MAAM,aAAa,CAAC;AAErB,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAM1C,MAAM,WAAW,oBAAoB;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC/B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,2EAA2E;IAC3E,aAAa,CAAC,EAAE,MAAM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OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,aAAa,CAAC;IAoCzB;;;;OAIG;IACG,cAAc,CAClB,KAAK,EAAE,yBAAyB,GAC/B,OAAO,CAAC,2BAA2B,CAAC;IAyLvC,OAAO,CAAC,kBAAkB;IAqH1B,OAAO,CAAC,kBAAkB;IAmB1B,OAAO,CAAC,oBAAoB;YAQd,aAAa;IAsC3B,OAAO,CAAC,uBAAuB;YAQjB,iCAAiC;IAyB/C,OAAO,CAAC,oBAAoB;IAS5B,OAAO,CAAC,2BAA2B;CAQpC;AA6fD,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,MAAM,EACf,eAAe,EAAE,MAAM,EACvB,MAAM,EAAE,MAAM,EACd,gBAAgB,SAAM,GACrB,IAAI,CA2FN"}
@@ -507,6 +507,118 @@ var StripeAdapter = class {
507
507
  if (dispute.id !== id || options.expectedLivemode !== void 0 && dispute.livemode !== options.expectedLivemode) throw new PaymentVerificationError("Stripe dispute response identity or environment did not match the request.");
508
508
  return dispute;
509
509
  }
510
+ /**
511
+ * Resolve existing PI/Charge evidence to a Checkout Session in the authenticated
512
+ * account and required environment. No local cache or new PI metadata needed.
513
+ * A quote is correlation evidence, not authorization: bind it to your owner.
514
+ */
515
+ async lookupCheckout(input) {
516
+ if (!input || typeof input.livemode !== "boolean") throw new PaymentConfigurationError("Stripe lookup requires livemode.");
517
+ const maxPages = input.maxPages ?? 10;
518
+ if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > 100) throw new PaymentConfigurationError("Stripe lookup maxPages must be 1–100.");
519
+ const scope = this.resolveStripeAccount(input.stripeAccount);
520
+ const account = scope === void 0 ? void 0 : normalizeStripeConnectedAccountId(scope);
521
+ if (account !== void 0) this.assertAdapterAccount(account);
522
+ const inputId = (value, prefix) => {
523
+ if (value === void 0) return void 0;
524
+ if (typeof value !== "string" || !new RegExp(`^${prefix}_[A-Za-z0-9_]+$`).test(value)) throw new PaymentConfigurationError("Stripe lookup payment reference is invalid.");
525
+ return value;
526
+ };
527
+ let paymentIntentId = inputId(input.paymentIntentId, "pi");
528
+ const chargeId = inputId(input.chargeId, "(?:ch|py)");
529
+ if (paymentIntentId === void 0 && chargeId === void 0) throw new PaymentConfigurationError("Stripe lookup requires paymentIntentId or chargeId.");
530
+ const read = async (path) => {
531
+ try {
532
+ return await this.stripeRequest(path, { stripeAccount: account });
533
+ } catch (error) {
534
+ throw new PaymentProviderError("Stripe checkout lookup request failed.", { retryable: error instanceof PaymentProviderError ? error.retryable : true });
535
+ }
536
+ };
537
+ if (chargeId !== void 0) {
538
+ const charge = lookupRecord(await read(`/charges/${encodeURIComponent(chargeId)}`));
539
+ assertLookupObject(charge, "charge", chargeId, input.livemode, account);
540
+ if (charge.payment_intent === null) {
541
+ if (paymentIntentId !== void 0) lookupIdentityError();
542
+ } else {
543
+ const chargeIntentId = lookupReference(charge.payment_intent, "payment_intent", "pi", input.livemode, account);
544
+ if (paymentIntentId !== void 0 && paymentIntentId !== chargeIntentId) lookupIdentityError();
545
+ paymentIntentId = chargeIntentId;
546
+ }
547
+ }
548
+ const context = {
549
+ backendId: STRIPE_BACKEND_ID,
550
+ ...account === void 0 ? {} : { accountId: account },
551
+ livemode: input.livemode,
552
+ ...paymentIntentId === void 0 ? {} : { paymentIntentId },
553
+ ...chargeId === void 0 ? {} : { chargeId }
554
+ };
555
+ if (paymentIntentId === void 0) return {
556
+ ...context,
557
+ status: "no_match"
558
+ };
559
+ assertLookupObject(lookupRecord(await read(`/payment_intents/${encodeURIComponent(paymentIntentId)}`)), "payment_intent", paymentIntentId, input.livemode, account);
560
+ const seen = /* @__PURE__ */ new Set();
561
+ const matches = [];
562
+ let cursor;
563
+ for (let page = 0; page < maxPages; page++) {
564
+ const params = new URLSearchParams({
565
+ payment_intent: paymentIntentId,
566
+ limit: "100"
567
+ });
568
+ if (cursor !== void 0) params.set("starting_after", cursor);
569
+ const list = lookupRecord(await read(`/checkout/sessions?${params}`));
570
+ if (list.object !== "list" || !Array.isArray(list.data) || typeof list.has_more !== "boolean" || list.data.length > 100) lookupDataError();
571
+ for (const value of list.data) {
572
+ const session = lookupRecord(value);
573
+ const id = lookupReference(session.id, "checkout.session", "cs", input.livemode, account);
574
+ assertLookupObject(session, "checkout.session", id, input.livemode, account);
575
+ if (session.mode !== "payment") lookupDataError();
576
+ if (lookupReference(session.payment_intent, "payment_intent", "pi", input.livemode, account) !== paymentIntentId) lookupIdentityError();
577
+ if (seen.has(id)) lookupDataError();
578
+ seen.add(id);
579
+ const quote = lookupQuote((session.metadata == null ? {} : lookupRecord(session.metadata)).quoteId);
580
+ const clientReferenceId = lookupQuote(session.client_reference_id);
581
+ if (quote !== void 0 && clientReferenceId !== void 0 && quote !== clientReferenceId) lookupIdentityError();
582
+ matches.push({
583
+ checkoutId: id,
584
+ quoteId: quote ?? clientReferenceId,
585
+ ...clientReferenceId === void 0 ? {} : { clientReferenceId }
586
+ });
587
+ cursor = id;
588
+ }
589
+ if (!list.has_more) {
590
+ if (matches.length === 0) return {
591
+ ...context,
592
+ status: "no_match"
593
+ };
594
+ if (matches.length !== 1) return {
595
+ ...context,
596
+ status: "indeterminate",
597
+ reason: "ambiguous"
598
+ };
599
+ const match = matches[0];
600
+ if (match.quoteId === void 0) return {
601
+ ...context,
602
+ status: "indeterminate",
603
+ reason: "missing_quote"
604
+ };
605
+ return {
606
+ ...context,
607
+ status: "matched",
608
+ checkoutId: match.checkoutId,
609
+ paymentIntentId,
610
+ quoteId: match.quoteId,
611
+ ...match.clientReferenceId === void 0 ? {} : { clientReferenceId: match.clientReferenceId }
612
+ };
613
+ }
614
+ if (list.data.length === 0) lookupDataError();
615
+ }
616
+ return {
617
+ ...context,
618
+ status: "indeterminate",
619
+ reason: "pagination_limit"
620
+ };
621
+ }
510
622
  verifyWebhookEvent(payload, signature, endpoint) {
511
623
  const secret = endpoint === "connect" ? this.connectWebhookSecret : this.webhookSecret;
512
624
  if (!secret) throw new PaymentConfigurationError(endpoint === "connect" ? "StripeAdapter parseConnectWebhookEvent requires connectWebhookSecret." : "StripeAdapter parseWebhookEvent requires webhookSecret.");
@@ -715,6 +827,32 @@ function disputeCurrency(value) {
715
827
  if (typeof value !== "string" || !/^[a-z]{3}$/.test(value)) return disputeError("currency");
716
828
  return value.toUpperCase();
717
829
  }
830
+ function lookupDataError() {
831
+ throw new PaymentProviderError("Stripe checkout lookup returned malformed data.");
832
+ }
833
+ function lookupIdentityError() {
834
+ throw new PaymentVerificationError("Stripe checkout lookup identity or environment mismatch.");
835
+ }
836
+ function lookupRecord(value) {
837
+ if (!value || typeof value !== "object" || Array.isArray(value)) return lookupDataError();
838
+ return value;
839
+ }
840
+ function assertLookupObject(value, object, id, livemode, account) {
841
+ if (value.object !== object || typeof value.livemode !== "boolean") lookupDataError();
842
+ if (value.id !== id || value.livemode !== livemode || value.account !== void 0 && value.account !== account) lookupIdentityError();
843
+ }
844
+ function lookupReference(value, object, prefix, livemode, account) {
845
+ const expanded = typeof value === "object" && value !== null ? lookupRecord(value) : void 0;
846
+ const id = expanded === void 0 ? value : expanded.id;
847
+ if (typeof id !== "string" || !new RegExp(`^${prefix}_[A-Za-z0-9_]+$`).test(id)) return lookupDataError();
848
+ if (expanded !== void 0) assertLookupObject(expanded, object, id, livemode, account);
849
+ return id;
850
+ }
851
+ function lookupQuote(value) {
852
+ if (value === void 0 || value === null) return void 0;
853
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value) return lookupDataError();
854
+ return value;
855
+ }
718
856
  function mapStripeDispute(value, account) {
719
857
  const object = disputeRecord(value, "object");
720
858
  if (object.object !== "dispute") return disputeError("object");
@@ -1 +1 @@
1
- {"version":3,"file":"stripe.js","names":[],"sources":["../../src/adapters/stripe.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\nimport {\n PaymentConfigurationError,\n PaymentNotOwnedError,\n PaymentProviderError,\n PaymentVerificationError,\n} from '../errors.js';\nimport {\n applyExpiryToPendingStatus,\n type FetchLike,\n formEncode,\n getFetch,\n normalizeDate,\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 AuthorizationResult,\n AuthorizePaymentInput,\n CapturePaymentInput,\n CaptureResult,\n CreatePaymentOptionInput,\n CreateSetupSessionInput,\n GetSetupResultInput,\n PaymentBackend,\n PaymentBackendCapabilities,\n PaymentDispute,\n PaymentDisputeStatus,\n PaymentEvent,\n PaymentOption,\n PaymentStatus,\n PaymentStatusContext,\n PaymentStatusResult,\n PaymentWebhookEvent,\n PayoutResult,\n RefundPaymentInput,\n RefundResult,\n SavedPaymentMethod,\n SendPayoutInput,\n SetupSession,\n VoidPaymentInput,\n VoidResult,\n WatchPaymentInput,\n} from '../types.js';\n\nexport const STRIPE_BACKEND_ID = 'stripe';\nconst STRIPE_CHECKOUT_MIN_EXPIRY_MS = 30 * 60 * 1_000;\nconst STRIPE_CHECKOUT_MAX_EXPIRY_MS = 24 * 60 * 60 * 1_000;\nconst DEFAULT_STRIPE_API_VERSION = '2024-06-20';\nconst DEFAULT_MAX_STORED_WEBHOOK_EVENT_IDS = 50_000;\n\nexport interface StripeAdapterOptions {\n secretKey: string;\n fetch?: FetchLike;\n apiBaseUrl?: string;\n apiVersion?: string;\n defaultCurrency?: string;\n supportedCurrencies?: string[];\n successUrl?: string;\n cancelUrl?: string;\n checkoutMode?: string;\n webhookSecret?: string;\n /**\n * Signing secret of the Stripe Connect webhook endpoint. Stripe signs\n * connected-account events with a different secret from the platform\n * endpoint; see {@link StripeAdapter.parseConnectWebhookEvent}.\n */\n connectWebhookSecret?: string;\n pollIntervalMs?: number;\n maxStoredPaymentOptions?: number;\n maxStoredWebhookEventIds?: number;\n /** Default Stripe Connect account for this adapter's provider requests. */\n stripeAccount?: string;\n}\n\n/** Stripe Connect account scope for a request; omit it for the platform. */\nexport interface StripeAccountScope {\n stripeAccount?: string;\n}\n\nexport interface StripeCreatePaymentOptionInput\n extends CreatePaymentOptionInput,\n StripeAccountScope {\n /** Stripe application fee in integer minor units for this direct charge. */\n applicationFeeAmount?: number;\n}\n\nexport interface StripePaymentStatusContext\n extends PaymentStatusContext,\n StripeAccountScope {}\n\nexport interface StripeRefundPaymentInput\n extends RefundPaymentInput,\n StripeAccountScope {\n /** Refund a Stripe application fee collected with the charge. */\n refundApplicationFee?: boolean;\n /** Reverse a destination transfer when the provider supports one. */\n reverseTransfer?: boolean;\n}\n\nexport interface StripeAuthorizePaymentInput\n extends AuthorizePaymentInput,\n StripeAccountScope {\n /** Stripe application fee in integer minor units for this PaymentIntent. */\n applicationFeeAmount?: number;\n}\n\nexport interface StripeCapturePaymentInput\n extends CapturePaymentInput,\n StripeAccountScope {}\n\nexport interface StripeVoidPaymentInput\n extends VoidPaymentInput,\n StripeAccountScope {}\n\nexport interface StripeCreateSetupSessionInput\n extends CreateSetupSessionInput,\n StripeAccountScope {}\n\nexport interface StripeGetSetupResultInput\n extends GetSetupResultInput,\n StripeAccountScope {}\n\nexport interface StripeWatchPaymentInput\n extends Omit<WatchPaymentInput, 'statusContext'> {\n statusContext?: StripePaymentStatusContext;\n}\n\nexport interface StripeWebhookEvent extends PaymentWebhookEvent {\n id: string;\n type: string;\n status: PaymentStatus;\n quoteId?: string;\n providerPaymentId?: string;\n /**\n * Connected account (`acct_...`) the event originated from. Set only on\n * events verified through {@link StripeAdapter.parseConnectWebhookEvent};\n * platform-endpoint events never carry it.\n */\n account?: string;\n /** Verified event environment and timestamp (required for dispute events). */\n livemode?: boolean;\n createdAt?: Date;\n dispute?: StripeDispute;\n /** Typed Connect account, application-fee, and dispute payloads. */\n connect?: StripeConnectEventDetail;\n raw: unknown;\n}\n\n/** A Connect endpoint event: always scoped to a connected account. */\nexport interface StripeConnectWebhookEvent extends StripeWebhookEvent {\n account: string;\n}\n\nexport type StripeConnectEventDetail =\n | {\n type: 'account.updated';\n account: StripeConnectAccountStatus;\n }\n | {\n type: 'application_fee.created' | 'application_fee.refunded';\n applicationFee: StripeApplicationFee;\n }\n | { type: StripeDisputeEventType; dispute: StripeDispute };\n\nexport type StripeDisputeEventType =\n | 'charge.dispute.created'\n | 'charge.dispute.updated'\n | 'charge.dispute.closed'\n | 'charge.dispute.funds_withdrawn'\n | 'charge.dispute.funds_reinstated';\n\nexport interface StripeDispute extends PaymentDispute {\n /** Verified webhook origin or authenticated request scope; absent for platform. */\n account?: string;\n raw: unknown;\n}\n\nexport interface StripeGetDisputeOptions extends StripeAccountScope {\n /** Reject an authoritative reread from a different environment. */\n expectedLivemode?: boolean;\n}\n\n/** Connected account onboarding and capability state. */\nexport interface StripeConnectAccountStatus {\n accountId: string;\n /** Stripe account type (`standard`, `express`, `custom`) when reported. */\n type?: string;\n /** Stripe `charges_enabled`. */\n chargesEnabled: boolean;\n /** Stripe `details_submitted`. */\n detailsSubmitted: boolean;\n /** Stripe `payouts_enabled`. */\n payoutsEnabled: boolean;\n /** Per-capability state, e.g. `{ card_payments: 'active' }`. */\n capabilities: Record<string, string>;\n requirements: {\n currentlyDue: string[];\n eventuallyDue: string[];\n pastDue: string[];\n disabledReason?: string;\n };\n country?: string;\n defaultCurrency?: string;\n raw: unknown;\n}\n\nexport interface StripeApplicationFee {\n id: string;\n /** Connected account the fee was collected from. */\n account?: string;\n /** Fee amount in integer minor units. */\n amount?: number;\n /** Refunded portion in integer minor units. */\n amountRefunded?: number;\n currency?: string;\n refunded: boolean;\n charge?: string;\n livemode?: boolean;\n raw: unknown;\n}\n\nexport interface StripeCreateStandardAccountInput {\n /** Two-letter ISO country code of the account holder. */\n country?: string;\n /** Prefills the account holder's email in Stripe onboarding. */\n email?: string;\n businessType?: 'individual' | 'company' | 'non_profit' | 'government_entity';\n metadata?: Record<string, string | number | boolean | null | undefined>;\n idempotencyKey?: string;\n}\n\nexport interface StripeOnboardingLink {\n /** Single-use Stripe-hosted onboarding URL; treat it as a bearer secret. */\n url: string;\n expiresAt?: Date;\n raw: unknown;\n}\n\nexport interface StripeCreateOnboardingLinkOptions {\n /** Which requirements to collect up front; Stripe defaults to `currently_due`. */\n collect?: 'currently_due' | 'eventually_due';\n idempotencyKey?: string;\n}\n\n/**\n * Host mapping from a connected account to its owner. Return `undefined` or\n * `null` for an account the host does not recognize; the event is then\n * rejected with {@link PaymentNotOwnedError}.\n */\nexport type StripeConnectAccountResolver<TOwner> = (\n account: string,\n event: StripeWebhookEvent,\n) => TOwner | null | undefined | Promise<TOwner | null | undefined>;\n\nexport interface StripeResolveConnectWebhookOptions<TOwner> {\n resolveAccount: StripeConnectAccountResolver<TOwner>;\n /**\n * Endpoint the delivery arrived on. `connect` (default) verifies with\n * `connectWebhookSecret` and routes by the event's `account`. `platform`\n * verifies with `webhookSecret` and routes `application_fee.*` events by the\n * fee's connected account; other platform events are rejected.\n */\n endpoint?: 'connect' | 'platform';\n}\n\nexport interface StripeResolvedConnectWebhookEvent<TOwner> {\n event: StripeWebhookEvent;\n /** Connected account the event was routed by. */\n account: string;\n owner: TOwner;\n}\n\nexport class StripeAdapter implements PaymentBackend {\n readonly capabilities: PaymentBackendCapabilities;\n\n private readonly fetch: FetchLike;\n private readonly secretKey: string;\n private readonly apiBaseUrl: string;\n private readonly apiVersion: string;\n private readonly defaultCurrency: string;\n private readonly supportedCurrencies: Set<string>;\n private readonly checkoutMode: string;\n private readonly webhookSecret: string | undefined;\n private readonly connectWebhookSecret: string | undefined;\n private readonly stripeAccount: string | undefined;\n private readonly maxStoredPaymentOptions: number;\n private readonly maxStoredWebhookEventIds: number;\n private readonly optionsByQuote = new Map<string, PaymentOption>();\n private readonly seenWebhookEventIds = new Set<string>();\n\n constructor(private readonly options: StripeAdapterOptions) {\n if (typeof options.secretKey !== 'string' || !options.secretKey.trim()) {\n throw new PaymentConfigurationError('StripeAdapter requires secretKey.');\n }\n\n assertOptionalSecret(options.webhookSecret, 'webhookSecret');\n assertOptionalSecret(options.connectWebhookSecret, 'connectWebhookSecret');\n\n if (options.apiBaseUrl !== undefined) {\n if (typeof options.apiBaseUrl !== 'string') {\n throw new PaymentConfigurationError(\n 'StripeAdapter apiBaseUrl must be a string when configured.',\n );\n }\n\n if (!options.apiBaseUrl.trim()) {\n throw new PaymentConfigurationError(\n 'StripeAdapter apiBaseUrl must not be empty when configured.',\n );\n }\n }\n\n this.fetch = getFetch(options.fetch);\n this.maxStoredPaymentOptions = normalizeMaxStoredPaymentOptions(\n options.maxStoredPaymentOptions,\n 'StripeAdapter maxStoredPaymentOptions',\n );\n this.maxStoredWebhookEventIds = normalizeMaxStoredPaymentOptions(\n options.maxStoredWebhookEventIds ?? DEFAULT_MAX_STORED_WEBHOOK_EVENT_IDS,\n 'StripeAdapter maxStoredWebhookEventIds',\n );\n this.secretKey = options.secretKey.trim();\n this.apiBaseUrl = normalizeUrlString(\n options.apiBaseUrl ?? 'https://api.stripe.com/v1',\n 'StripeAdapter apiBaseUrl',\n ).replace(/\\/$/, '');\n this.apiVersion = normalizeNonEmptyString(\n options.apiVersion ?? DEFAULT_STRIPE_API_VERSION,\n 'StripeAdapter apiVersion',\n );\n this.defaultCurrency = normalizeStripeCurrency(\n options.defaultCurrency ?? 'usd',\n );\n this.supportedCurrencies = normalizeSupportedStripeCurrencies(\n options.supportedCurrencies,\n this.defaultCurrency,\n );\n this.checkoutMode = options.checkoutMode ?? 'payment';\n\n if (this.checkoutMode !== 'payment') {\n throw new PaymentConfigurationError(\n 'StripeAdapter only supports payment Checkout mode.',\n );\n }\n\n this.webhookSecret = options.webhookSecret?.trim();\n this.connectWebhookSecret = options.connectWebhookSecret?.trim();\n this.stripeAccount = normalizeOptionalStripeAccount(\n options.stripeAccount,\n 'StripeAdapter stripeAccount',\n );\n this.capabilities = {\n id: STRIPE_BACKEND_ID,\n displayName: 'Stripe Checkout',\n settlementCurrency: this.defaultCurrency.toUpperCase(),\n supportedSettlementCurrencies: [...this.supportedCurrencies].map(\n (currency) => currency.toUpperCase(),\n ),\n chain: 'stripe',\n settlementShape: 'url',\n x402Capable: false,\n confirmationLatency: {\n expectedSeconds: 5,\n maxExpectedSeconds: 600,\n description:\n 'Card payments usually confirm in seconds; bank debits can remain processing while Stripe settles them.',\n },\n supportsRefunds: true,\n supportsPayouts: true,\n supportsWebhooks: true,\n supportsManualCapture: true,\n supportsSavedPaymentMethods: true,\n metadata: {\n provider: 'stripe',\n },\n };\n }\n\n async createPaymentOption(\n input: StripeCreatePaymentOptionInput,\n ): Promise<PaymentOption> {\n const quoteId = normalizeNonEmptyString(input.quoteId, 'Stripe quoteId');\n const rawSuccessUrl = input.successUrl ?? this.options.successUrl;\n const rawCancelUrl = input.cancelUrl ?? this.options.cancelUrl;\n\n if (rawSuccessUrl === undefined || rawCancelUrl === undefined) {\n throw new PaymentConfigurationError(\n 'StripeAdapter createPaymentOption requires successUrl and cancelUrl.',\n );\n }\n\n const successUrl = normalizeUrlString(rawSuccessUrl, 'Stripe successUrl');\n const cancelUrl = normalizeUrlString(rawCancelUrl, 'Stripe cancelUrl');\n const currency = normalizeStripeCurrency(input.currency);\n this.assertSupportedCurrency(currency);\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe Checkout amount',\n );\n const applicationFeeAmount = normalizeApplicationFeeAmount(\n input.applicationFeeAmount,\n amount,\n 'Stripe Checkout applicationFeeAmount',\n );\n const expiresAt = normalizeDate(input.expiresAt);\n const stripeExpiresAt = normalizeStripeCheckoutExpiresAt(expiresAt);\n const params: Record<string, unknown> = {\n mode: this.checkoutMode,\n ...Object.fromEntries([\n ['success_url', successUrl],\n ['cancel_url', cancelUrl],\n ['client_reference_id', quoteId],\n ['customer_email', input.buyerEmail],\n ['expires_at', Math.floor(stripeExpiresAt.getTime() / 1_000)],\n ]),\n 'line_items[0][quantity]': 1,\n 'line_items[0][price_data][currency]': currency,\n 'line_items[0][price_data][unit_amount]': amount,\n 'line_items[0][price_data][product_data][name]':\n input.description ?? `Quote ${quoteId}`,\n ...(applicationFeeAmount === undefined\n ? {}\n : {\n 'payment_intent_data[application_fee_amount]': applicationFeeAmount,\n }),\n ...flattenStripeMetadata(input.metadata),\n 'metadata[quoteId]': quoteId,\n };\n\n const stripeAccount = this.resolveStripeAccount(input.stripeAccount);\n const session = await this.stripeRequest<Record<string, unknown>>(\n '/checkout/sessions',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount,\n body: formEncode(params),\n },\n );\n const sessionId = normalizeOptionalProviderString(\n readProviderString(session, 'id'),\n );\n const checkoutUrl = normalizeOptionalProviderString(\n readProviderString(session, 'url'),\n );\n\n if (!sessionId || !checkoutUrl) {\n throw new PaymentProviderError(\n 'Stripe Checkout Session response did not include id and url.',\n );\n }\n\n const option: PaymentOption = {\n backendId: this.capabilities.id,\n quoteId,\n payTo: checkoutUrl,\n settlementShape: 'url',\n settlementCurrency: currency.toUpperCase(),\n settlementAmount: amount,\n amount,\n currency: currency.toUpperCase(),\n expiresAt: stripeExpiresAt,\n providerPaymentId: sessionId,\n paymentUri: checkoutUrl,\n metadata: {\n sessionId,\n stripeAccount,\n paymentIntent: normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n ),\n },\n };\n\n rememberPaymentOption(\n this.optionsByQuote,\n stripePaymentOptionKey(quoteId, stripeAccount),\n option,\n this.maxStoredPaymentOptions,\n );\n\n return option;\n }\n\n watchPayment(input: StripeWatchPaymentInput): AsyncIterable<PaymentEvent> {\n return pollPaymentStatus(\n {\n ...input,\n pollIntervalMs:\n input.pollIntervalMs ?? this.options.pollIntervalMs ?? 5_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: StripePaymentStatusContext = {},\n ): Promise<PaymentStatusResult> {\n const normalizedQuoteId = normalizeNonEmptyString(\n quoteId,\n 'Stripe quoteId',\n );\n const normalizedPayTo = normalizeNonEmptyString(payTo, 'Stripe payTo');\n const contextProviderPaymentId =\n context.providerPaymentId === undefined\n ? undefined\n : normalizeNonEmptyString(\n context.providerPaymentId,\n 'Stripe providerPaymentId',\n );\n const contextStripeAccount = normalizeOptionalStripeAccount(\n context.stripeAccount,\n 'Stripe stripeAccount',\n );\n const scopedOption = this.optionsByQuote.get(\n stripePaymentOptionKey(\n normalizedQuoteId,\n contextStripeAccount ?? this.stripeAccount,\n ),\n );\n const sessionId =\n contextProviderPaymentId ??\n extractStripeSessionId(normalizedPayTo) ??\n scopedOption?.providerPaymentId;\n\n if (!sessionId) {\n throw new PaymentConfigurationError(\n 'Stripe getStatus requires a Checkout Session id or URL.',\n );\n }\n\n const storedOption = this.findStoredOptionBySessionId(sessionId);\n const stripeAccount =\n contextStripeAccount ??\n readStripeOptionAccount(storedOption) ??\n this.stripeAccount;\n const cachedOption = this.optionsByQuote.get(\n stripePaymentOptionKey(normalizedQuoteId, stripeAccount),\n );\n\n // A caller-supplied session id can deliberately select a later checkout\n // for the same quote. Cache-derived amount, currency, and expiry describe\n // only the session we created, never an explicitly selected replacement.\n const option =\n cachedOption?.providerPaymentId === sessionId ? cachedOption : undefined;\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(sessionId)}`,\n { stripeAccount },\n );\n const sessionQuoteId = readStripeSessionQuoteId(session);\n\n if (sessionQuoteId !== undefined && sessionQuoteId !== normalizedQuoteId) {\n throw new PaymentVerificationError(\n `Stripe Checkout Session quoteId ${sessionQuoteId} did not match ${normalizedQuoteId}.`,\n );\n }\n\n const paymentStatus = readString(session, 'payment_status');\n const status = mapStripeStatus(\n readString(session, 'status'),\n paymentStatus,\n );\n\n const contextAmount =\n context.amount === undefined\n ? undefined\n : normalizeMinorUnitAmount(context.amount, 'Stripe status');\n const contextCurrency =\n context.currency === undefined\n ? undefined\n : normalizeStripeCurrency(context.currency).toUpperCase();\n const sessionCurrency =\n readString(session, 'currency') === undefined\n ? undefined\n : normalizeStripeCurrency(\n readString(session, 'currency') ?? '',\n ).toUpperCase();\n const sessionAmount = readSafeInteger(session, 'amount_total');\n const expiresAt =\n option?.expiresAt ??\n (context.expiresAt === undefined\n ? undefined\n : normalizeDate(context.expiresAt));\n const effectiveStatus = applyExpiryToPendingStatus(status, expiresAt);\n\n return {\n backendId: this.capabilities.id,\n quoteId: normalizedQuoteId,\n payTo: normalizedPayTo,\n status: effectiveStatus,\n settlementCurrency:\n sessionCurrency ??\n option?.settlementCurrency ??\n contextCurrency ??\n this.defaultCurrency.toUpperCase(),\n settlementAmount:\n sessionAmount ?? option?.settlementAmount ?? contextAmount,\n receivedAmount:\n paymentStatus === 'paid' || paymentStatus === 'no_payment_required'\n ? (sessionAmount ?? option?.settlementAmount ?? contextAmount)\n : undefined,\n amount: option?.amount ?? contextAmount,\n currency: option?.currency ?? contextCurrency,\n providerPaymentId: sessionId,\n transactionId: normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n ),\n updatedAt: new Date(),\n raw: session,\n };\n }\n\n async sendPayout(input: SendPayoutInput): Promise<PayoutResult> {\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const destination = normalizeNonEmptyString(\n input.destination,\n 'Stripe payout destination',\n );\n const quoteId =\n input.quoteId === undefined\n ? undefined\n : normalizeNonEmptyString(input.quoteId, 'Stripe payout quoteId');\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe payout amount',\n );\n const transfer = await this.stripeRequest<Record<string, unknown>>(\n '/transfers',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n body: formEncode({\n amount,\n currency,\n destination,\n description: input.memo,\n ...flattenStripeMetadata(input.metadata),\n ...(quoteId === undefined ? {} : { 'metadata[quoteId]': quoteId }),\n }),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: 'submitted',\n payoutId: normalizeOptionalProviderString(\n readProviderString(transfer, 'id'),\n ),\n destination,\n amount,\n currency: currency.toUpperCase(),\n raw: transfer,\n };\n }\n\n async refundPayment(input: StripeRefundPaymentInput): Promise<RefundResult> {\n const rawPaymentReference = input.paymentId ?? input.transactionId;\n\n if (!rawPaymentReference) {\n throw new PaymentConfigurationError(\n 'Stripe refunds require paymentId or transactionId.',\n );\n }\n\n const paymentReference = normalizeNonEmptyString(\n rawPaymentReference,\n 'Stripe refund payment reference',\n );\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const amount =\n input.amount === undefined\n ? undefined\n : normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe refund amount',\n );\n const stripeAccount = this.resolveStripeAccount(input.stripeAccount);\n const refundReferenceParam = await this.resolveStripeRefundReferenceParam(\n paymentReference,\n stripeAccount,\n );\n const refundParams: Record<string, unknown> = {\n ...refundReferenceParam,\n amount: amount === undefined ? undefined : amount,\n reason: input.reason,\n refund_application_fee: input.refundApplicationFee,\n reverse_transfer: input.reverseTransfer,\n ...flattenStripeMetadata(input.metadata),\n };\n\n const refund = await this.stripeRequest<Record<string, unknown>>(\n '/refunds',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount,\n body: formEncode(refundParams),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeRefundStatus(readString(refund, 'status')),\n refundId: normalizeOptionalProviderString(\n readProviderString(refund, 'id'),\n ),\n transactionId: paymentReference,\n // Read the settled amount and currency back from the refund object\n // (mirrors capturePayment) so a full refund — no `input.amount` supplied,\n // and possibly a currency differing from the adapter default when\n // `input.currency` is omitted — surfaces what Stripe actually refunded\n // instead of the request defaults.\n amount: readSafeInteger(refund, 'amount') ?? amount,\n currency: readStripeResultCurrency(refund) ?? currency.toUpperCase(),\n raw: refund,\n };\n }\n\n async authorizePayment(\n input: StripeAuthorizePaymentInput,\n ): Promise<AuthorizationResult> {\n const currency = normalizeStripeCurrency(input.currency);\n this.assertSupportedCurrency(currency);\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe authorize amount',\n );\n const paymentMethod = normalizeNonEmptyString(\n input.providerPaymentMethodId,\n 'Stripe authorize providerPaymentMethodId',\n );\n const providerCustomerId =\n input.providerCustomerId === undefined\n ? undefined\n : normalizeNonEmptyString(\n input.providerCustomerId,\n 'Stripe authorize providerCustomerId',\n );\n const quoteId =\n input.quoteId === undefined\n ? undefined\n : normalizeNonEmptyString(input.quoteId, 'Stripe authorize quoteId');\n const applicationFeeAmount = normalizeApplicationFeeAmount(\n input.applicationFeeAmount,\n amount,\n 'Stripe PaymentIntent applicationFeeAmount',\n );\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n '/payment_intents',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode({\n amount,\n currency,\n confirm: true,\n 'payment_method_types[]': 'card',\n description: input.description,\n application_fee_amount: applicationFeeAmount,\n ...Object.fromEntries([\n ['payment_method', paymentMethod],\n ['capture_method', 'manual'],\n // Off-session (merchant-initiated) by default — the primary use is\n // charging a saved card while the buyer is absent. Without this,\n // Stripe treats it as on-session and may raise an SCA challenge the\n // absent buyer can't complete, so the hold is never placed.\n ['off_session', input.offSession ?? true],\n ]),\n ...(providerCustomerId === undefined\n ? {}\n : { customer: providerCustomerId }),\n ...flattenStripeMetadata(input.metadata),\n ...(quoteId === undefined ? {} : { 'metadata[quoteId]': quoteId }),\n }),\n },\n );\n\n const providerPaymentId = normalizeOptionalProviderString(\n readProviderString(intent, 'id'),\n );\n\n if (!providerPaymentId) {\n throw new PaymentProviderError(\n 'Stripe PaymentIntent response did not include an id.',\n );\n }\n\n const status = mapStripeAuthorizationStatus(readString(intent, 'status'));\n // Only surface the SCA fields when authentication is actually required — the\n // documented contract — even though Stripe returns client_secret regardless.\n // (Authorization progress is observed via `parseWebhookEvent`, which surfaces\n // the ready-to-capture transition as `processing` — there is no distinct\n // `requires_capture` webhook status; `getStatus` handles Checkout sessions,\n // not PaymentIntents.)\n const actionRequired = status === 'requires_action';\n\n return {\n backendId: this.capabilities.id,\n status,\n providerPaymentId,\n amount: readSafeInteger(intent, 'amount') ?? amount,\n currency: (readString(intent, 'currency') ?? currency).toUpperCase(),\n clientSecret: actionRequired\n ? normalizeOptionalProviderString(\n readProviderString(intent, 'client_secret'),\n )\n : undefined,\n nextAction: actionRequired\n ? (intent.next_action ?? undefined)\n : undefined,\n raw: intent,\n };\n }\n\n async capturePayment(\n input: StripeCapturePaymentInput,\n ): Promise<CaptureResult> {\n const providerPaymentId = normalizeNonEmptyString(\n input.providerPaymentId,\n 'Stripe capture providerPaymentId',\n );\n const amount =\n input.amount === undefined\n ? undefined\n : normalizePositiveMinorUnitAmount(\n input.amount,\n 'Stripe capture amount',\n );\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n `/payment_intents/${encodeURIComponent(providerPaymentId)}/capture`,\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode({\n ...Object.fromEntries([['amount_to_capture', amount]]),\n ...flattenStripeMetadata(input.metadata),\n }),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeCaptureStatus(readString(intent, 'status')),\n providerPaymentId:\n normalizeOptionalProviderString(readProviderString(intent, 'id')) ??\n providerPaymentId,\n amount:\n readSafeInteger(intent, 'amount_received') ??\n readSafeInteger(intent, 'amount') ??\n amount,\n currency: readStripeResultCurrency(intent),\n raw: intent,\n };\n }\n\n async voidPayment(input: StripeVoidPaymentInput): Promise<VoidResult> {\n const providerPaymentId = normalizeNonEmptyString(\n input.providerPaymentId,\n 'Stripe void providerPaymentId',\n );\n const reason =\n input.reason === undefined\n ? undefined\n : normalizeNonEmptyString(input.reason, 'Stripe void reason');\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n `/payment_intents/${encodeURIComponent(providerPaymentId)}/cancel`,\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode(Object.fromEntries([['cancellation_reason', reason]])),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeVoidStatus(readString(intent, 'status')),\n providerPaymentId:\n normalizeOptionalProviderString(readProviderString(intent, 'id')) ??\n providerPaymentId,\n amount: readSafeInteger(intent, 'amount'),\n currency: readStripeResultCurrency(intent),\n raw: intent,\n };\n }\n\n async createSetupSession(\n input: StripeCreateSetupSessionInput,\n ): Promise<SetupSession> {\n const rawSuccessUrl = input.successUrl ?? this.options.successUrl;\n const rawCancelUrl = input.cancelUrl ?? this.options.cancelUrl;\n\n if (rawSuccessUrl === undefined || rawCancelUrl === undefined) {\n throw new PaymentConfigurationError(\n 'StripeAdapter createSetupSession requires successUrl and cancelUrl.',\n );\n }\n\n const successUrl = normalizeUrlString(rawSuccessUrl, 'Stripe successUrl');\n const cancelUrl = normalizeUrlString(rawCancelUrl, 'Stripe cancelUrl');\n // Currency for the setup-mode session (defaults to the backend currency).\n // Redundant now that payment_method_types is always set, but harmless and\n // kept so the session is well-formed if that restriction is ever relaxed.\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const providerCustomerId =\n input.providerCustomerId === undefined\n ? undefined\n : normalizeNonEmptyString(\n input.providerCustomerId,\n 'Stripe setup customer',\n );\n\n // Either attach to an existing customer, or force Stripe to create one so\n // the saved method comes back with a reusable `cus_` reference. Setup-mode\n // sessions do NOT create a customer on their own — `customer_creation` must\n // be `always`. All snake_case keys go through Object.fromEntries.\n const customerParams: [string, unknown][] = [];\n if (providerCustomerId !== undefined) {\n customerParams.push(['customer', providerCustomerId]);\n } else {\n customerParams.push(['customer_creation', 'always']);\n if (input.customerEmail !== undefined) {\n customerParams.push([\n 'customer_email',\n normalizeNonEmptyString(\n input.customerEmail,\n 'Stripe setup customerEmail',\n ),\n ]);\n }\n }\n\n const params: Record<string, unknown> = {\n mode: 'setup',\n currency,\n // Restrict to cards: SavedPaymentMethod exposes card display fields\n // (brand/last4/expiry), so allowing SEPA/Bacs/etc. would yield saved\n // methods with no usable display detail.\n 'payment_method_types[]': 'card',\n ...Object.fromEntries([\n ['success_url', successUrl],\n ['cancel_url', cancelUrl],\n ...customerParams,\n ]),\n ...flattenStripeMetadata(input.metadata),\n };\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n '/checkout/sessions',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode(params),\n },\n );\n\n const sessionId = normalizeOptionalProviderString(\n readProviderString(session, 'id'),\n );\n const url = normalizeOptionalProviderString(\n readProviderString(session, 'url'),\n );\n\n if (!sessionId || !url) {\n throw new PaymentProviderError(\n 'Stripe setup Checkout Session response did not include id and url.',\n );\n }\n\n return {\n backendId: this.capabilities.id,\n sessionId,\n url,\n providerCustomerId:\n providerCustomerId ??\n normalizeOptionalProviderString(\n readProviderString(session, 'customer'),\n ),\n raw: session,\n };\n }\n\n async getSetupResult(\n input: StripeGetSetupResultInput,\n ): Promise<SavedPaymentMethod> {\n const sessionId = normalizeNonEmptyString(\n input.sessionId,\n 'Stripe setup sessionId',\n );\n\n const query = new URLSearchParams();\n query.append('expand[]', 'setup_intent.payment_method');\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(sessionId)}?${query.toString()}`,\n { stripeAccount: this.resolveStripeAccount(input.stripeAccount) },\n );\n\n const setupIntent = readObject(session, 'setup_intent');\n const paymentMethod = readObject(setupIntent, 'payment_method');\n const card = readObject(paymentMethod, 'card');\n\n // `customer` is a bare `cus_` string on the request path (only\n // setup_intent.payment_method is expanded), but read tolerantly of an\n // expanded object so a future `expand[]=customer` can't wrongly downgrade a\n // completed setup to a permanent `pending`.\n const providerCustomerId = normalizeOptionalProviderString(\n readProviderString(session, 'customer') ??\n readProviderString(readObject(session, 'customer'), 'id'),\n );\n const providerPaymentMethodId = normalizeOptionalProviderString(\n readProviderString(paymentMethod, 'id'),\n );\n\n let status = mapStripeSetupStatus(\n readString(session, 'status'),\n readString(setupIntent, 'status'),\n );\n // Never report `complete` without the reusable references a caller needs to\n // charge the method later — a `pm_` with no `cus_` can't be charged\n // off-session, so treat that as not-yet-ready rather than a false success.\n if (\n status === 'complete' &&\n (!providerCustomerId || !providerPaymentMethodId)\n ) {\n status = 'pending';\n }\n\n return {\n backendId: this.capabilities.id,\n status,\n providerCustomerId,\n providerPaymentMethodId,\n type: readString(paymentMethod, 'type'),\n brand: readString(card, 'brand'),\n last4: readString(card, 'last4'),\n expMonth: readSafeInteger(card, 'exp_month'),\n expYear: readSafeInteger(card, 'exp_year'),\n raw: session,\n };\n }\n\n /**\n * Verify and parse a delivery to the platform webhook endpoint. Events that\n * carry a connected `account` are rejected: they belong to the Connect\n * endpoint and must never be processed as platform-account events.\n */\n parseWebhookEvent(payload: string, signature?: string): StripeWebhookEvent {\n const event = this.verifyWebhookEvent(payload, signature, 'platform');\n this.recordWebhookEvent(event);\n return event;\n }\n\n /**\n * Verify a Stripe Connect endpoint delivery with `connectWebhookSecret`,\n * then parse it. The signature is checked before the payload is parsed, and\n * an event without a connected `account` is rejected. When this adapter is\n * scoped to a `stripeAccount`, events for any other account are rejected.\n * The payload, including `quoteId`, is controlled by the connected account:\n * bind `quoteId` to `account` before acting on it.\n */\n parseConnectWebhookEvent(\n payload: string,\n signature?: string,\n ): StripeConnectWebhookEvent {\n const event = this.verifyWebhookEvent(payload, signature, 'connect');\n this.recordWebhookEvent(event);\n return event as StripeConnectWebhookEvent;\n }\n\n /**\n * Verify a webhook delivery, then map its connected account to an owner\n * (for example a tenant) with the host's resolver. An account the resolver\n * does not recognize is rejected with {@link PaymentNotOwnedError}; there is\n * no fallback to the platform account. The event is recorded for duplicate\n * detection only after it resolves, so a retried delivery that failed to\n * resolve is not reported as a duplicate.\n *\n * Security: a connected account controls the objects it creates, so a\n * Connect event's `quoteId` (and every other payload field) is chosen by\n * that account. Resolving the account proves only who sent the event. The\n * host must check that `event.quoteId` belongs to the resolved owner (for\n * example inside `resolveAccount`, which receives the event, or before\n * settling) and must never settle another owner's quote from it.\n */\n async resolveConnectWebhookEvent<TOwner>(\n payload: string,\n signature: string | undefined,\n options: StripeResolveConnectWebhookOptions<TOwner>,\n ): Promise<StripeResolvedConnectWebhookEvent<TOwner>> {\n if (typeof options?.resolveAccount !== 'function') {\n throw new PaymentConfigurationError(\n 'Stripe resolveConnectWebhookEvent requires a resolveAccount function.',\n );\n }\n\n const endpoint = options.endpoint ?? 'connect';\n\n if (endpoint !== 'connect' && endpoint !== 'platform') {\n throw new PaymentConfigurationError(\n 'Stripe resolveConnectWebhookEvent endpoint must be connect or platform.',\n );\n }\n\n const event = this.verifyWebhookEvent(payload, signature, endpoint);\n const account =\n endpoint === 'connect'\n ? event.account\n : event.connect?.type === 'application_fee.created' ||\n event.connect?.type === 'application_fee.refunded'\n ? event.connect.applicationFee.account\n : undefined;\n\n if (account === undefined) {\n throw new PaymentNotOwnedError(\n `Stripe webhook event ${event.id} (${event.type}) has no connected account to route by.`,\n );\n }\n\n this.assertAdapterAccount(account);\n const owner = await options.resolveAccount(account, event);\n\n if (owner === undefined || owner === null) {\n throw new PaymentNotOwnedError(\n `Stripe connected account ${account} is not mapped to an owner.`,\n );\n }\n\n this.recordWebhookEvent(event);\n return { event, account, owner };\n }\n\n /**\n * Create a Stripe Connect **Standard** account. The account holder owns the\n * Stripe relationship and dashboard; the platform only connects to it.\n * Always issued on the platform account, never on a connected account.\n */\n async createStandardAccount(\n input: StripeCreateStandardAccountInput = {},\n ): Promise<StripeConnectAccountStatus> {\n const country =\n input.country === undefined\n ? undefined\n : normalizeStripeCountry(input.country);\n const email =\n input.email === undefined\n ? undefined\n : normalizeNonEmptyString(input.email, 'Stripe account email');\n const account = await this.stripeRequest<Record<string, unknown>>(\n '/accounts',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n body: formEncode({\n type: 'standard',\n country,\n email,\n ...Object.fromEntries([['business_type', input.businessType]]),\n ...flattenStripeMetadata(input.metadata),\n }),\n },\n );\n\n return mapStripeConnectAccount(account, 'Stripe account response');\n }\n\n /**\n * Create a single-use Account Link that sends the account holder through\n * Stripe-hosted onboarding. `refreshUrl` is visited when the link expires or\n * is reused, and should mint a new link; `returnUrl` does not mean\n * onboarding finished, so read {@link getAccountCapabilities} afterwards.\n */\n async createOnboardingLink(\n accountId: string,\n returnUrl: string,\n refreshUrl: string,\n options: StripeCreateOnboardingLinkOptions = {},\n ): Promise<StripeOnboardingLink> {\n const account = normalizeStripeConnectedAccountId(accountId);\n const link = await this.stripeRequest<Record<string, unknown>>(\n '/account_links',\n {\n method: 'POST',\n idempotencyKey: options.idempotencyKey,\n body: formEncode({\n account,\n type: 'account_onboarding',\n collect: options.collect,\n ...Object.fromEntries([\n ['return_url', normalizeUrlString(returnUrl, 'Stripe returnUrl')],\n [\n 'refresh_url',\n normalizeUrlString(refreshUrl, 'Stripe refreshUrl'),\n ],\n ]),\n }),\n },\n );\n const url = normalizeOptionalProviderString(\n readProviderString(link, 'url'),\n );\n\n if (!url) {\n throw new PaymentProviderError(\n 'Stripe Account Link response did not include a url.',\n );\n }\n\n const expiresAtSeconds = readSafeInteger(link, 'expires_at');\n\n return {\n url,\n expiresAt:\n expiresAtSeconds === undefined\n ? undefined\n : new Date(expiresAtSeconds * 1_000),\n raw: link,\n };\n }\n\n /**\n * Read a connected account's onboarding and capability state\n * (`charges_enabled`, `details_submitted`, `payouts_enabled`, per-capability\n * status, and outstanding requirements).\n */\n async getAccountCapabilities(\n accountId: string,\n ): Promise<StripeConnectAccountStatus> {\n const account = normalizeStripeConnectedAccountId(accountId);\n const response = await this.stripeRequest<Record<string, unknown>>(\n `/accounts/${encodeURIComponent(account)}`,\n );\n const status = mapStripeConnectAccount(response, 'Stripe account response');\n\n if (status.accountId !== account) {\n throw new PaymentVerificationError(\n `Stripe account response ${status.accountId} did not match ${account}.`,\n );\n }\n\n return status;\n }\n\n /** Authoritative read. No request or adapter account scope means platform. */\n async getDispute(\n disputeId: string,\n options: StripeGetDisputeOptions = {},\n ): Promise<StripeDispute> {\n const id = normalizeNonEmptyString(disputeId, 'Stripe dispute id');\n if (!/^(?:du|dp)_[A-Za-z0-9_]+$/.test(id)) {\n throw new PaymentConfigurationError('Stripe dispute id is invalid.');\n }\n const scope = this.resolveStripeAccount(options.stripeAccount);\n const account =\n scope === undefined\n ? undefined\n : normalizeStripeConnectedAccountId(scope);\n if (account !== undefined) this.assertAdapterAccount(account);\n if (\n options.expectedLivemode !== undefined &&\n typeof options.expectedLivemode !== 'boolean'\n ) {\n throw new PaymentConfigurationError(\n 'Stripe expectedLivemode must be boolean.',\n );\n }\n const response = await this.stripeRequest<Record<string, unknown>>(\n `/disputes/${encodeURIComponent(id)}?expand[]=charge`,\n { stripeAccount: account },\n );\n const dispute = mapStripeDispute(response, account);\n if (\n dispute.id !== id ||\n (options.expectedLivemode !== undefined &&\n dispute.livemode !== options.expectedLivemode)\n ) {\n throw new PaymentVerificationError(\n 'Stripe dispute response identity or environment did not match the request.',\n );\n }\n return dispute;\n }\n\n private verifyWebhookEvent(\n payload: string,\n signature: string | undefined,\n endpoint: 'connect' | 'platform',\n ): StripeWebhookEvent {\n const secret =\n endpoint === 'connect' ? this.connectWebhookSecret : this.webhookSecret;\n\n if (!secret) {\n throw new PaymentConfigurationError(\n endpoint === 'connect'\n ? 'StripeAdapter parseConnectWebhookEvent requires connectWebhookSecret.'\n : 'StripeAdapter parseWebhookEvent requires webhookSecret.',\n );\n }\n\n if (!signature) {\n throw new PaymentProviderError('Missing Stripe webhook signature.');\n }\n\n // Authenticate the raw bytes before anything reads the payload.\n verifyStripeWebhookSignature(payload, signature, secret);\n\n const event = parseStripeWebhookPayload(payload);\n const id = readRequiredWebhookString(\n event,\n 'id',\n 'Stripe webhook event id',\n );\n const type = readRequiredWebhookString(\n event,\n 'type',\n 'Stripe webhook event type',\n );\n const rawAccount = event.account;\n let account: string | undefined;\n\n if (endpoint === 'connect') {\n account = typeof rawAccount === 'string' ? rawAccount.trim() : undefined;\n\n if (!account || !STRIPE_CONNECTED_ACCOUNT_ID.test(account)) {\n throw new PaymentVerificationError(\n 'Stripe Connect webhook event did not include a valid connected account.',\n );\n }\n\n this.assertAdapterAccount(account);\n } else if (rawAccount !== undefined && rawAccount !== null) {\n throw new PaymentVerificationError(\n 'Stripe connected-account event received on the platform webhook endpoint; verify it with parseConnectWebhookEvent.',\n );\n }\n\n const data = (\n event.data as { object?: Record<string, unknown> } | undefined\n )?.object;\n const dispute = type.startsWith('charge.dispute.')\n ? mapStripeDispute(data, account)\n : undefined;\n let disputeType: StripeDisputeEventType | undefined;\n if (dispute !== undefined) {\n disputeType = readStripeDisputeEventType(type);\n if (\n typeof event.livemode !== 'boolean' ||\n event.livemode !== dispute.livemode\n ) {\n throw new PaymentVerificationError(\n 'Stripe dispute event environment is missing or inconsistent.',\n );\n }\n }\n const createdAt =\n dispute === undefined ? undefined : disputeDate(event.created);\n const connect: StripeConnectEventDetail | undefined =\n disputeType && dispute\n ? { type: disputeType, dispute }\n : mapStripeConnectEventDetail(type, data);\n\n if (\n account !== undefined &&\n connect?.type === 'account.updated' &&\n connect.account.accountId !== account\n ) {\n throw new PaymentVerificationError(\n 'Stripe account.updated webhook object did not match the event account.',\n );\n }\n\n return {\n id,\n type,\n status: mapStripeWebhookStatus(type, data),\n quoteId: normalizeOptionalWebhookString(\n // `client_reference_id` is a Checkout Session-only field; honor it only\n // for session events so a non-session object (a PaymentIntent / Charge /\n // Transfer, possibly from a malicious Connect account) can't spoof\n // correlation to another quote's id. Non-session events correlate only\n // via our own `metadata.quoteId`.\n (type.startsWith('checkout.session.')\n ? readString(data, 'client_reference_id')\n : undefined) ??\n readString(\n (data?.metadata as Record<string, unknown>) ?? {},\n 'quoteId',\n ),\n ),\n providerPaymentId: normalizeOptionalWebhookString(readString(data, 'id')),\n duplicate: this.seenWebhookEventIds.has(id),\n ...(account === undefined ? {} : { account }),\n ...(connect === undefined ? {} : { connect }),\n ...(dispute === undefined\n ? {}\n : { dispute, livemode: dispute.livemode, createdAt }),\n raw: event,\n };\n }\n\n private recordWebhookEvent(event: StripeWebhookEvent): void {\n if (this.seenWebhookEventIds.has(event.id)) {\n event.duplicate = true;\n return;\n }\n\n event.duplicate = false;\n this.seenWebhookEventIds.add(event.id);\n while (this.seenWebhookEventIds.size > this.maxStoredWebhookEventIds) {\n const oldest = this.seenWebhookEventIds.values().next().value;\n\n if (oldest === undefined) {\n break;\n }\n\n this.seenWebhookEventIds.delete(oldest);\n }\n }\n\n private assertAdapterAccount(account: string): void {\n if (this.stripeAccount !== undefined && account !== this.stripeAccount) {\n throw new PaymentNotOwnedError(\n `Stripe connected account ${account} does not match this adapter's account scope.`,\n );\n }\n }\n\n private async stripeRequest<T>(\n path: string,\n init: RequestInit & {\n idempotencyKey?: string;\n stripeAccount?: string;\n } = {},\n ): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${this.secretKey}`);\n headers.set('Content-Type', 'application/x-www-form-urlencoded');\n headers.set('Accept', 'application/json');\n headers.set('Stripe-Version', this.apiVersion);\n\n if (init.stripeAccount !== undefined) {\n headers.set('Stripe-Account', init.stripeAccount);\n }\n\n if (init.idempotencyKey !== undefined) {\n headers.set(\n 'Idempotency-Key',\n normalizeNonEmptyString(init.idempotencyKey, 'Stripe idempotencyKey'),\n );\n }\n\n const {\n idempotencyKey: _idempotencyKey,\n stripeAccount: _stripeAccount,\n ...requestInit\n } = init;\n const response = await this.fetch(`${this.apiBaseUrl}${path}`, {\n ...requestInit,\n method: init.method ?? 'GET',\n headers,\n });\n\n return readJsonResponse<T>(response, `Stripe ${path}`);\n }\n\n private assertSupportedCurrency(currency: string): void {\n if (!this.supportedCurrencies.has(currency)) {\n throw new PaymentConfigurationError(\n `StripeAdapter currency ${currency.toUpperCase()} is not configured as supported.`,\n );\n }\n }\n\n private async resolveStripeRefundReferenceParam(\n paymentReference: string,\n stripeAccount: string | undefined,\n ): Promise<Record<string, string>> {\n if (paymentReference.startsWith('cs_')) {\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(paymentReference)}`,\n { stripeAccount },\n );\n const paymentIntent = normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n );\n\n if (!paymentIntent) {\n throw new PaymentProviderError(\n 'Stripe Checkout Session did not include payment_intent for refund.',\n );\n }\n\n return Object.fromEntries([['payment_intent', paymentIntent]]);\n }\n\n return stripeRefundReferenceParam(paymentReference);\n }\n\n private resolveStripeAccount(\n override: string | undefined,\n ): string | undefined {\n return (\n normalizeOptionalStripeAccount(override, 'Stripe stripeAccount') ??\n this.stripeAccount\n );\n }\n\n private findStoredOptionBySessionId(\n sessionId: string,\n ): PaymentOption | undefined {\n for (const option of this.optionsByQuote.values()) {\n if (option.providerPaymentId === sessionId) return option;\n }\n return undefined;\n }\n}\n\nfunction assertOptionalSecret(value: unknown, name: string): void {\n if (value === undefined) return;\n\n if (typeof value !== 'string') {\n throw new PaymentConfigurationError(\n `StripeAdapter ${name} must be a string when configured.`,\n );\n }\n\n if (!value.trim()) {\n throw new PaymentConfigurationError(\n `StripeAdapter ${name} must not be empty when configured.`,\n );\n }\n}\n\nconst STRIPE_CONNECTED_ACCOUNT_ID = /^acct_[A-Za-z0-9]+$/;\n\nfunction normalizeStripeConnectedAccountId(value: unknown): string {\n const account = typeof value === 'string' ? value.trim() : undefined;\n\n if (!account || !STRIPE_CONNECTED_ACCOUNT_ID.test(account)) {\n throw new PaymentConfigurationError(\n 'Stripe connected account id must look like acct_...',\n );\n }\n\n return account;\n}\n\nfunction normalizeStripeCountry(value: string): string {\n const country = typeof value === 'string' ? value.trim().toUpperCase() : '';\n\n if (!/^[A-Z]{2}$/.test(country)) {\n throw new PaymentConfigurationError(\n 'Stripe account country must be a two-letter ISO country code.',\n );\n }\n\n return country;\n}\n\nfunction readStringArray(\n value: Record<string, unknown> | undefined,\n key: string,\n): string[] {\n const item = value?.[key];\n\n return Array.isArray(item)\n ? item.filter((entry): entry is string => typeof entry === 'string')\n : [];\n}\n\nfunction mapStripeConnectAccount(\n account: Record<string, unknown> | undefined,\n context: string,\n): StripeConnectAccountStatus {\n const accountId = readProviderString(account, 'id')?.trim();\n\n if (!account || !accountId || !STRIPE_CONNECTED_ACCOUNT_ID.test(accountId)) {\n throw new PaymentProviderError(`${context} did not include an account id.`);\n }\n\n const capabilities: Record<string, string> = {};\n\n for (const [name, state] of Object.entries(\n readObject(account, 'capabilities') ?? {},\n )) {\n if (typeof state === 'string') {\n capabilities[name] = state;\n }\n }\n\n const requirements = readObject(account, 'requirements');\n const disabledReason = normalizeOptionalProviderString(\n readProviderString(requirements, 'disabled_reason'),\n );\n const defaultCurrency = readProviderString(account, 'default_currency');\n\n return {\n accountId,\n type: normalizeOptionalProviderString(readProviderString(account, 'type')),\n chargesEnabled: account.charges_enabled === true,\n detailsSubmitted: account.details_submitted === true,\n payoutsEnabled: account.payouts_enabled === true,\n capabilities,\n requirements: {\n currentlyDue: readStringArray(requirements, 'currently_due'),\n eventuallyDue: readStringArray(requirements, 'eventually_due'),\n pastDue: readStringArray(requirements, 'past_due'),\n ...(disabledReason === undefined ? {} : { disabledReason }),\n },\n country: normalizeOptionalProviderString(\n readProviderString(account, 'country'),\n ),\n defaultCurrency: defaultCurrency?.toUpperCase(),\n raw: account,\n };\n}\n\nfunction mapStripeApplicationFee(\n fee: Record<string, unknown> | undefined,\n): StripeApplicationFee {\n const id = normalizeOptionalProviderString(readProviderString(fee, 'id'));\n\n if (!fee || !id) {\n throw new PaymentProviderError(\n 'Stripe application_fee webhook object did not include an id.',\n );\n }\n\n const account = normalizeOptionalProviderString(\n readProviderString(fee, 'account'),\n );\n\n if (account !== undefined && !STRIPE_CONNECTED_ACCOUNT_ID.test(account)) {\n throw new PaymentProviderError(\n 'Stripe application_fee webhook object has an invalid account id.',\n );\n }\n const livemode = fee.livemode;\n\n return {\n id,\n account,\n amount: readSafeInteger(fee, 'amount'),\n amountRefunded: readSafeInteger(fee, 'amount_refunded'),\n currency: readStripeResultCurrency(fee),\n refunded: fee.refunded === true,\n charge: normalizeOptionalProviderString(\n readProviderString(fee, 'charge') ??\n readProviderString(readObject(fee, 'charge'), 'id'),\n ),\n livemode: typeof livemode === 'boolean' ? livemode : undefined,\n raw: fee,\n };\n}\n\nconst STRIPE_DISPUTE_STATUSES: ReadonlySet<string> = new Set([\n 'warning_needs_response',\n 'warning_under_review',\n 'warning_closed',\n 'needs_response',\n 'under_review',\n 'won',\n 'lost',\n 'prevented',\n]);\n\nfunction readStripeDisputeEventType(type: string): StripeDisputeEventType {\n switch (type) {\n case 'charge.dispute.created':\n case 'charge.dispute.updated':\n case 'charge.dispute.closed':\n case 'charge.dispute.funds_withdrawn':\n case 'charge.dispute.funds_reinstated':\n return type;\n default:\n throw new PaymentProviderError('Unsupported Stripe dispute event type.');\n }\n}\n\nfunction disputeError(field: string): never {\n throw new PaymentProviderError(\n `Stripe dispute has invalid or missing ${field}.`,\n );\n}\n\nfunction disputeRecord(value: unknown, field: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return disputeError(field);\n return value as Record<string, unknown>;\n}\n\nfunction disputeString(value: unknown, field: string): string {\n if (typeof value !== 'string' || !value.trim() || value !== value.trim())\n return disputeError(field);\n return value;\n}\n\nfunction disputeId(value: unknown, prefix: string): string {\n const id = disputeString(\n typeof value === 'object' && value !== null\n ? disputeRecord(value, prefix).id\n : value,\n prefix,\n );\n // Charge IDs include non-card py_ identities; legacy disputes can use dp_.\n const prefixes =\n prefix === 'ch' ? '(?:ch|py)' : prefix === 'du' ? '(?:du|dp)' : prefix;\n if (!new RegExp(`^${prefixes}_[A-Za-z0-9_]+$`).test(id))\n return disputeError(prefix);\n return id;\n}\n\nfunction disputeInteger(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value))\n return disputeError(field);\n return value;\n}\n\nfunction disputeDate(value: unknown): Date {\n const seconds = disputeInteger(value, 'created');\n const date = new Date(seconds * 1000);\n if (\n seconds < 0 ||\n !Number.isSafeInteger(seconds * 1000) ||\n !Number.isFinite(date.getTime())\n )\n return disputeError('created');\n return date;\n}\n\nfunction disputeCurrency(value: unknown): string {\n if (typeof value !== 'string' || !/^[a-z]{3}$/.test(value))\n return disputeError('currency');\n return value.toUpperCase();\n}\n\nfunction mapStripeDispute(value: unknown, account?: string): StripeDispute {\n const object = disputeRecord(value, 'object');\n if (object.object !== 'dispute') return disputeError('object');\n const id = disputeId(object.id, 'du');\n const chargeId = disputeId(object.charge, 'ch');\n const expandedCharge =\n typeof object.charge === 'object'\n ? disputeRecord(object.charge, 'charge')\n : undefined;\n const paymentIntent = object.payment_intent ?? expandedCharge?.payment_intent;\n const paymentIntentId =\n paymentIntent == null ? undefined : disputeId(paymentIntent, 'pi');\n if (\n object.payment_intent != null &&\n expandedCharge?.payment_intent != null &&\n paymentIntentId !== disputeId(expandedCharge.payment_intent, 'pi')\n )\n return disputeError('payment_intent');\n const amount = disputeInteger(object.amount, 'amount');\n if (amount < 0) return disputeError('amount');\n const currency = disputeCurrency(object.currency);\n const providerStatus = disputeString(object.status, 'status');\n const status: PaymentDisputeStatus = STRIPE_DISPUTE_STATUSES.has(\n providerStatus,\n )\n ? (providerStatus as PaymentDisputeStatus)\n : 'unknown';\n if (typeof object.livemode !== 'boolean') return disputeError('livemode');\n // Stripe objects normally omit account; when supplied it must agree with the\n // authenticated scope, never replace it with a payload-provided account.\n if (object.account !== undefined && object.account !== account)\n return disputeError('account');\n if (\n expandedCharge?.livemode !== undefined &&\n expandedCharge.livemode !== object.livemode\n )\n return disputeError('charge.livemode');\n if (!Array.isArray(object.balance_transactions))\n return disputeError('balance_transactions');\n const ids = new Set<string>();\n const balanceTransactions = object.balance_transactions.map(\n (value: unknown) => {\n const transaction = disputeRecord(value, 'balance_transaction');\n if (transaction.object !== 'balance_transaction')\n return disputeError('balance_transaction.object');\n const id = disputeId(transaction.id, 'txn');\n if (ids.has(id)) return disputeError('duplicate balance_transaction');\n ids.add(id);\n const amount = disputeInteger(\n transaction.amount,\n 'balance_transaction.amount',\n );\n const fee = disputeInteger(transaction.fee, 'balance_transaction.fee');\n const net = disputeInteger(transaction.net, 'balance_transaction.net');\n if (!Number.isSafeInteger(amount - fee) || amount - fee !== net)\n return disputeError('balance_transaction.net');\n return {\n id,\n amount,\n fee,\n net,\n currency: disputeCurrency(transaction.currency),\n createdAt: disputeDate(transaction.created),\n type: disputeString(transaction.type, 'balance_transaction.type'),\n reportingCategory:\n transaction.reporting_category === undefined\n ? undefined\n : disputeString(\n transaction.reporting_category,\n 'balance_transaction.reporting_category',\n ),\n };\n },\n );\n return {\n id,\n chargeId,\n paymentIntentId,\n amount,\n currency,\n status,\n providerStatus,\n livemode: object.livemode,\n createdAt: disputeDate(object.created),\n balanceTransactions,\n ...(account === undefined ? {} : { account }),\n raw: object,\n };\n}\n\nfunction mapStripeConnectEventDetail(\n type: string,\n object: Record<string, unknown> | undefined,\n): StripeConnectEventDetail | undefined {\n if (type === 'account.updated') {\n return {\n type,\n account: mapStripeConnectAccount(\n object,\n 'Stripe account.updated webhook object',\n ),\n };\n }\n\n if (\n type === 'application_fee.created' ||\n type === 'application_fee.refunded'\n ) {\n return { type, applicationFee: mapStripeApplicationFee(object) };\n }\n\n return undefined;\n}\n\nfunction readStripeOptionAccount(\n option: PaymentOption | undefined,\n): string | undefined {\n const value = option?.metadata?.stripeAccount;\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction normalizeOptionalStripeAccount(\n value: string | undefined,\n context: string,\n): string | undefined {\n return value === undefined\n ? undefined\n : normalizeNonEmptyString(value, context);\n}\n\nfunction normalizeApplicationFeeAmount(\n value: number | undefined,\n chargeAmount: number,\n context: string,\n): number | undefined {\n if (value === undefined) return undefined;\n\n const fee = normalizePositiveMinorUnitAmount(value, context);\n if (fee > chargeAmount) {\n throw new PaymentConfigurationError(\n `${context} must not exceed the charge amount.`,\n );\n }\n return fee;\n}\n\nfunction stripePaymentOptionKey(\n quoteId: string,\n stripeAccount: string | undefined,\n): string {\n // Platform entries retain their old quote-only keys. Connected-account ids\n // cannot contain NUL in an HTTP header, so it safely separates account scope\n // from the caller's quote id without collapsing tenant-local quote ids.\n return stripeAccount === undefined ? quoteId : `${stripeAccount}\\0${quoteId}`;\n}\n\nfunction stripeRefundReferenceParam(\n paymentReference: string,\n): Record<string, string> {\n if (paymentReference.startsWith('pi_')) {\n return Object.fromEntries([['payment_intent', paymentReference]]);\n }\n\n if (paymentReference.startsWith('ch_')) {\n return { charge: paymentReference };\n }\n\n throw new PaymentConfigurationError(\n 'Stripe refunds require a Checkout Session (cs_), payment_intent (pi_), or charge (ch_) reference.',\n );\n}\n\nfunction normalizeStripeCurrency(value: string): string {\n if (typeof value !== 'string') {\n throw new PaymentConfigurationError(\n `StripeAdapter currency must be a three-letter ISO currency code, received ${String(value)}.`,\n );\n }\n\n const normalized = value.trim().toLowerCase();\n\n if (!/^[a-z]{3}$/.test(normalized)) {\n throw new PaymentConfigurationError(\n `StripeAdapter currency must be a three-letter ISO currency code, received ${String(value)}.`,\n );\n }\n\n return normalized;\n}\n\nfunction normalizeSupportedStripeCurrencies(\n configuredCurrencies: string[] | undefined,\n defaultCurrency: string,\n): Set<string> {\n const normalized = new Set(\n (configuredCurrencies ?? ['usd', 'eur', 'gbp', 'cad']).map(\n normalizeStripeCurrency,\n ),\n );\n normalized.add(defaultCurrency);\n\n return normalized;\n}\n\nfunction normalizeStripeCheckoutExpiresAt(\n expiresAt: Date,\n now = Date.now(),\n): Date {\n if (expiresAt.getTime() <= now) {\n throw new PaymentProviderError('Stripe Checkout expiry is in the past.');\n }\n\n const min = now + STRIPE_CHECKOUT_MIN_EXPIRY_MS;\n const max = now + STRIPE_CHECKOUT_MAX_EXPIRY_MS;\n\n if (expiresAt.getTime() < min || expiresAt.getTime() > max) {\n throw new PaymentConfigurationError(\n 'Stripe Checkout expiry must be at least 30 minutes and no more than 24 hours from now.',\n );\n }\n\n return expiresAt;\n}\n\nexport function verifyStripeWebhookSignature(\n payload: string,\n signatureHeader: string,\n secret: string,\n toleranceSeconds = 300,\n): void {\n if (typeof payload !== 'string') {\n throw new PaymentProviderError('Stripe webhook payload must be a string.');\n }\n\n const normalizedSignatureHeader = normalizeNonEmptyString(\n signatureHeader,\n 'Stripe signature header',\n );\n const normalizedSecret = normalizeNonEmptyString(\n secret,\n 'Stripe webhook secret',\n );\n\n if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) {\n throw new PaymentConfigurationError(\n `Stripe webhook toleranceSeconds must be a non-negative finite number, received ${String(toleranceSeconds)}.`,\n );\n }\n\n const timestampCandidates: string[] = [];\n const signatures: string[] = [];\n\n for (const part of normalizedSignatureHeader.split(',')) {\n const [rawKey, ...rawValue] = part.split('=');\n const key = rawKey?.trim();\n const value = rawValue.join('=').trim();\n\n if (!key || !value) {\n continue;\n }\n\n if (key === 't') {\n timestampCandidates.push(value);\n }\n\n if (key === 'v1') {\n signatures.push(value);\n }\n }\n\n if (timestampCandidates.length !== 1 || signatures.length === 0) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const timestamp = timestampCandidates[0] ?? '';\n\n if (!/^\\d+$/.test(timestamp)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const timestampSeconds = Number(timestamp);\n\n if (!Number.isSafeInteger(timestampSeconds)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const nowSeconds = Date.now() / 1_000;\n const ageSeconds = nowSeconds - timestampSeconds;\n\n if (ageSeconds < -5) {\n throw new PaymentProviderError(\n 'Stripe webhook signature timestamp is in the future.',\n );\n }\n\n if (ageSeconds > toleranceSeconds) {\n throw new PaymentProviderError('Stripe webhook signature is too old.');\n }\n\n const expected = createHmac('sha256', normalizedSecret)\n .update(`${timestamp}.${payload}`)\n .digest('hex');\n const expectedBuffer = Buffer.from(expected, 'hex');\n\n for (const signature of signatures) {\n if (!/^[0-9a-f]+$/i.test(signature)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const actualBuffer = Buffer.from(signature, 'hex');\n\n if (\n expectedBuffer.length === actualBuffer.length &&\n timingSafeEqual(expectedBuffer, actualBuffer)\n ) {\n return;\n }\n }\n\n throw new PaymentProviderError('Invalid Stripe webhook signature.');\n}\n\nfunction parseStripeWebhookPayload(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 Stripe 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 Stripe 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 readProviderString(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n return typeof item === 'string' ? item : undefined;\n}\n\nfunction readRequiredWebhookString(\n value: Record<string, unknown>,\n key: string,\n context: string,\n): string {\n const item = value[key];\n\n if (typeof item !== 'string') {\n throw new PaymentProviderError(`${context} must be a string.`);\n }\n\n return normalizeNonEmptyString(item, context);\n}\n\nfunction readStripeSessionQuoteId(\n session: Record<string, unknown>,\n): string | undefined {\n return normalizeOptionalWebhookString(\n readString(session, 'client_reference_id') ??\n readString(\n (session.metadata as Record<string, unknown>) ?? {},\n 'quoteId',\n ),\n );\n}\n\nfunction mapStripeStatus(\n checkoutStatus: string | undefined,\n paymentStatus: string | undefined,\n): PaymentStatus {\n if (paymentStatus === 'paid' || paymentStatus === 'no_payment_required') {\n return 'confirmed';\n }\n\n if (checkoutStatus === 'expired') {\n return 'expired';\n }\n\n if (paymentStatus === 'unpaid' || checkoutStatus === 'open') {\n return 'pending';\n }\n\n if (checkoutStatus === 'complete') {\n return 'processing';\n }\n\n return 'pending';\n}\n\nfunction mapStripeWebhookStatus(\n type: string | undefined,\n object: Record<string, unknown> | undefined,\n): PaymentStatus {\n if (type === 'checkout.session.completed') {\n return mapStripeStatus(\n readString(object, 'status'),\n readString(object, 'payment_status'),\n );\n }\n\n if (type === 'checkout.session.async_payment_succeeded') {\n return 'confirmed';\n }\n\n if (type === 'checkout.session.async_payment_failed') {\n return 'failed';\n }\n\n if (type === 'checkout.session.expired') {\n return 'expired';\n }\n\n // Manual-capture PaymentIntent lifecycle (authorize → capture / void). Only\n // treat these as terminal for intents WE created and can correlate — i.e.\n // ones carrying our `quoteId` in metadata. Checkout Sessions create their own\n // PaymentIntents (which fire these same events with no quoteId on the intent);\n // those are handled via the `checkout.session.*` events above, so here they\n // stay non-terminal (`processing`) rather than emitting a spurious,\n // uncorrelatable terminal event. Handled before the generic `failed` catch\n // below so an un-owned `payment_intent.payment_failed` isn't reclassified.\n if (\n type === 'payment_intent.succeeded' ||\n type === 'payment_intent.canceled' ||\n type === 'payment_intent.payment_failed'\n ) {\n const metadata = (object?.metadata as Record<string, unknown>) ?? {};\n // Match parseWebhookEvent's normalization so an empty/blank quoteId is\n // treated as un-owned by both — gate and reporter must agree on ownership.\n const owned =\n normalizeOptionalWebhookString(readString(metadata, 'quoteId')) !==\n undefined;\n if (owned) {\n if (type === 'payment_intent.succeeded') {\n return 'confirmed';\n }\n // A manual-capture hold Stripe released automatically (it lapsed) is\n // `expired`, distinct from a deliberate void or hard decline (`failed`);\n // the shared PaymentStatus union has no `canceled`.\n if (\n type === 'payment_intent.canceled' &&\n readString(object, 'cancellation_reason') === 'automatic'\n ) {\n return 'expired';\n }\n return 'failed';\n }\n return 'processing';\n }\n\n // Terminal failure/refund only for payment-in objects (Checkout Session,\n // PaymentIntent, Charge). Money-out / unrelated events (transfer.failed,\n // payout.failed, refund.failed, application_fee.refunded, …) also match a\n // naive substring scan — and a failed Transfer even carries our quoteId\n // (sendPayout stamps it), which would miscorrelate a payout failure as a\n // payment failure — so they must not surface as a terminal payment status.\n const isPaymentInEvent =\n type?.startsWith('checkout.session.') === true ||\n type?.startsWith('payment_intent.') === true ||\n type?.startsWith('charge.') === true;\n\n if (isPaymentInEvent && type?.includes('refunded')) {\n return 'refunded';\n }\n\n if (isPaymentInEvent && type?.includes('failed')) {\n return 'failed';\n }\n\n return 'processing';\n}\n\nfunction mapStripeRefundStatus(\n status: string | undefined,\n): RefundResult['status'] {\n switch (status) {\n case 'succeeded':\n return 'succeeded';\n case 'failed':\n case 'canceled':\n return 'failed';\n case 'requires_action':\n return 'requires_action';\n default:\n return 'submitted';\n }\n}\n\nfunction mapStripeAuthorizationStatus(\n status: string | undefined,\n): AuthorizationResult['status'] {\n switch (status) {\n case 'requires_capture':\n return 'requires_capture';\n case 'succeeded':\n return 'succeeded';\n case 'requires_action':\n return 'requires_action';\n case 'processing':\n return 'processing';\n default:\n return 'failed';\n }\n}\n\nfunction mapStripeCaptureStatus(\n status: string | undefined,\n): CaptureResult['status'] {\n switch (status) {\n case 'succeeded':\n return 'succeeded';\n // Capturing an authorized intent shouldn't re-enter authentication; treat\n // any in-flight/action state as still processing rather than a failure.\n case 'processing':\n case 'requires_action':\n return 'processing';\n default:\n return 'failed';\n }\n}\n\nfunction mapStripeVoidStatus(status: string | undefined): VoidResult['status'] {\n return status === 'canceled' ? 'canceled' : 'failed';\n}\n\nfunction readStripeResultCurrency(\n value: Record<string, unknown>,\n): string | undefined {\n const currency = readString(value, 'currency');\n\n return currency === undefined ? undefined : currency.toUpperCase();\n}\n\nfunction mapStripeSetupStatus(\n sessionStatus: string | undefined,\n setupIntentStatus: string | undefined,\n): SavedPaymentMethod['status'] {\n if (sessionStatus === 'expired') {\n return 'expired';\n }\n\n if (sessionStatus === 'complete') {\n // The method is reusable only once the SetupIntent itself has succeeded —\n // the Session can be `complete` while the intent is still `processing`\n // (async setup methods via dynamic payment methods).\n if (setupIntentStatus === 'succeeded') {\n return 'complete';\n }\n // A finished session whose SetupIntent didn't succeed is a terminal\n // failure (card declined → `requires_payment_method`, or `canceled`), so\n // callers can stop polling instead of waiting on a `pending` that will\n // never resolve. Still-in-flight states (`processing`, `requires_action`)\n // remain `pending`.\n if (\n setupIntentStatus === 'canceled' ||\n setupIntentStatus === 'requires_payment_method'\n ) {\n return 'failed';\n }\n }\n\n return 'pending';\n}\n\nfunction readObject(\n value: Record<string, unknown> | undefined,\n key: string,\n): Record<string, unknown> | undefined {\n const item = value?.[key];\n\n return item && typeof item === 'object' && !Array.isArray(item)\n ? (item as Record<string, unknown>)\n : undefined;\n}\n\nfunction extractStripeSessionId(payTo: string): string | undefined {\n if (/^cs_(test_|live_)?[A-Za-z0-9_]+$/.test(payTo)) {\n return payTo;\n }\n\n try {\n const url = new URL(payTo);\n const match = url.pathname.match(/\\/pay\\/([^/?#]+)/);\n\n const sessionId = match?.[1];\n\n return sessionId && /^cs_(test_|live_)?[A-Za-z0-9_]+$/.test(sessionId)\n ? sessionId\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction flattenStripeMetadata(\n metadata:\n | Record<string, string | number | boolean | null | undefined>\n | undefined,\n): Record<string, string | number | boolean> {\n const result: Record<string, string | number | boolean> = {};\n\n for (const [key, value] of Object.entries(metadata ?? {})) {\n if (value !== undefined && value !== null) {\n result[`metadata[${key}]`] = value;\n }\n }\n\n return result;\n}\n\nfunction readString(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[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 readSafeInteger(\n value: Record<string, unknown> | undefined,\n key: string,\n): number | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n return typeof item === 'number' && Number.isSafeInteger(item) && item >= 0\n ? item\n : undefined;\n}\n"],"mappings":";;;;AAoDA,IAAa,oBAAoB;AACjC,IAAM,gCAAgC,OA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AAmC,KAAK,KAAK,GAC/C,OAAO;CAGT,IAAI;EAIF,MAAM,YAFQ,IADE,IAAI,KACN,CAAA,CAAI,SAAS,MAAM,kBAEf,CAAA,GAAQ;EAE1B,OAAO,aAAa,mCAAmC,KAAK,SAAS,IACjE,YACA,KAAA;CACN,QAAQ;EACN;CACF;AACF;AAEA,SAAS,sBACP,UAG2C;CAC3C,MAAM,SAAoD,CAAC;CAE3D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,YAAY,CAAC,CAAC,GACtD,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,YAAY,IAAI,MAAM;CAIjC,OAAO;AACT;AAEA,SAAS,WACP,OACA,KACoB;CACpB,IAAI,CAAC,OACH;CAGF,MAAM,OAAO,MAAM;CAEnB,IAAI,OAAO,SAAS,UAClB,OAAO;CAGT,IAAI,OAAO,SAAS,UAClB,OAAO,OAAO,IAAI;AAItB;AAEA,SAAS,gBACP,OACA,KACoB;CACpB,IAAI,CAAC,OACH;CAGF,MAAM,OAAO,MAAM;CAEnB,OAAO,OAAO,SAAS,YAAY,OAAO,cAAc,IAAI,KAAK,QAAQ,IACrE,OACA,KAAA;AACN"}
1
+ {"version":3,"file":"stripe.js","names":[],"sources":["../../src/adapters/stripe.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\nimport {\n PaymentConfigurationError,\n PaymentNotOwnedError,\n PaymentProviderError,\n PaymentVerificationError,\n} from '../errors.js';\nimport {\n applyExpiryToPendingStatus,\n type FetchLike,\n formEncode,\n getFetch,\n normalizeDate,\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 AuthorizationResult,\n AuthorizePaymentInput,\n CapturePaymentInput,\n CaptureResult,\n CreatePaymentOptionInput,\n CreateSetupSessionInput,\n GetSetupResultInput,\n PaymentBackend,\n PaymentBackendCapabilities,\n PaymentCheckoutLookupInput,\n PaymentCheckoutLookupResult,\n PaymentDispute,\n PaymentDisputeStatus,\n PaymentEvent,\n PaymentOption,\n PaymentStatus,\n PaymentStatusContext,\n PaymentStatusResult,\n PaymentWebhookEvent,\n PayoutResult,\n RefundPaymentInput,\n RefundResult,\n SavedPaymentMethod,\n SendPayoutInput,\n SetupSession,\n VoidPaymentInput,\n VoidResult,\n WatchPaymentInput,\n} from '../types.js';\n\nexport const STRIPE_BACKEND_ID = 'stripe';\nconst STRIPE_CHECKOUT_MIN_EXPIRY_MS = 30 * 60 * 1_000;\nconst STRIPE_CHECKOUT_MAX_EXPIRY_MS = 24 * 60 * 60 * 1_000;\nconst DEFAULT_STRIPE_API_VERSION = '2024-06-20';\nconst DEFAULT_MAX_STORED_WEBHOOK_EVENT_IDS = 50_000;\n\nexport interface StripeAdapterOptions {\n secretKey: string;\n fetch?: FetchLike;\n apiBaseUrl?: string;\n apiVersion?: string;\n defaultCurrency?: string;\n supportedCurrencies?: string[];\n successUrl?: string;\n cancelUrl?: string;\n checkoutMode?: string;\n webhookSecret?: string;\n /**\n * Signing secret of the Stripe Connect webhook endpoint. Stripe signs\n * connected-account events with a different secret from the platform\n * endpoint; see {@link StripeAdapter.parseConnectWebhookEvent}.\n */\n connectWebhookSecret?: string;\n pollIntervalMs?: number;\n maxStoredPaymentOptions?: number;\n maxStoredWebhookEventIds?: number;\n /** Default Stripe Connect account for this adapter's provider requests. */\n stripeAccount?: string;\n}\n\n/** Stripe Connect account scope for a request; omit it for the platform. */\nexport interface StripeAccountScope {\n stripeAccount?: string;\n}\n\nexport interface StripeCreatePaymentOptionInput\n extends CreatePaymentOptionInput,\n StripeAccountScope {\n /** Stripe application fee in integer minor units for this direct charge. */\n applicationFeeAmount?: number;\n}\n\nexport interface StripePaymentStatusContext\n extends PaymentStatusContext,\n StripeAccountScope {}\n\nexport interface StripeRefundPaymentInput\n extends RefundPaymentInput,\n StripeAccountScope {\n /** Refund a Stripe application fee collected with the charge. */\n refundApplicationFee?: boolean;\n /** Reverse a destination transfer when the provider supports one. */\n reverseTransfer?: boolean;\n}\n\nexport interface StripeAuthorizePaymentInput\n extends AuthorizePaymentInput,\n StripeAccountScope {\n /** Stripe application fee in integer minor units for this PaymentIntent. */\n applicationFeeAmount?: number;\n}\n\nexport interface StripeCapturePaymentInput\n extends CapturePaymentInput,\n StripeAccountScope {}\n\nexport interface StripeVoidPaymentInput\n extends VoidPaymentInput,\n StripeAccountScope {}\n\nexport interface StripeCreateSetupSessionInput\n extends CreateSetupSessionInput,\n StripeAccountScope {}\n\nexport interface StripeGetSetupResultInput\n extends GetSetupResultInput,\n StripeAccountScope {}\n\nexport interface StripeWatchPaymentInput\n extends Omit<WatchPaymentInput, 'statusContext'> {\n statusContext?: StripePaymentStatusContext;\n}\n\nexport interface StripeWebhookEvent extends PaymentWebhookEvent {\n id: string;\n type: string;\n status: PaymentStatus;\n quoteId?: string;\n providerPaymentId?: string;\n /**\n * Connected account (`acct_...`) the event originated from. Set only on\n * events verified through {@link StripeAdapter.parseConnectWebhookEvent};\n * platform-endpoint events never carry it.\n */\n account?: string;\n /** Verified event environment and timestamp (required for dispute events). */\n livemode?: boolean;\n createdAt?: Date;\n dispute?: StripeDispute;\n /** Typed Connect account, application-fee, and dispute payloads. */\n connect?: StripeConnectEventDetail;\n raw: unknown;\n}\n\n/** A Connect endpoint event: always scoped to a connected account. */\nexport interface StripeConnectWebhookEvent extends StripeWebhookEvent {\n account: string;\n}\n\nexport type StripeConnectEventDetail =\n | {\n type: 'account.updated';\n account: StripeConnectAccountStatus;\n }\n | {\n type: 'application_fee.created' | 'application_fee.refunded';\n applicationFee: StripeApplicationFee;\n }\n | { type: StripeDisputeEventType; dispute: StripeDispute };\n\nexport type StripeDisputeEventType =\n | 'charge.dispute.created'\n | 'charge.dispute.updated'\n | 'charge.dispute.closed'\n | 'charge.dispute.funds_withdrawn'\n | 'charge.dispute.funds_reinstated';\n\nexport interface StripeDispute extends PaymentDispute {\n /** Verified webhook origin or authenticated request scope; absent for platform. */\n account?: string;\n raw: unknown;\n}\n\nexport interface StripeGetDisputeOptions extends StripeAccountScope {\n /** Reject an authoritative reread from a different environment. */\n expectedLivemode?: boolean;\n}\n\nexport interface StripeCheckoutLookupInput\n extends PaymentCheckoutLookupInput,\n StripeAccountScope {}\n\n/** Connected account onboarding and capability state. */\nexport interface StripeConnectAccountStatus {\n accountId: string;\n /** Stripe account type (`standard`, `express`, `custom`) when reported. */\n type?: string;\n /** Stripe `charges_enabled`. */\n chargesEnabled: boolean;\n /** Stripe `details_submitted`. */\n detailsSubmitted: boolean;\n /** Stripe `payouts_enabled`. */\n payoutsEnabled: boolean;\n /** Per-capability state, e.g. `{ card_payments: 'active' }`. */\n capabilities: Record<string, string>;\n requirements: {\n currentlyDue: string[];\n eventuallyDue: string[];\n pastDue: string[];\n disabledReason?: string;\n };\n country?: string;\n defaultCurrency?: string;\n raw: unknown;\n}\n\nexport interface StripeApplicationFee {\n id: string;\n /** Connected account the fee was collected from. */\n account?: string;\n /** Fee amount in integer minor units. */\n amount?: number;\n /** Refunded portion in integer minor units. */\n amountRefunded?: number;\n currency?: string;\n refunded: boolean;\n charge?: string;\n livemode?: boolean;\n raw: unknown;\n}\n\nexport interface StripeCreateStandardAccountInput {\n /** Two-letter ISO country code of the account holder. */\n country?: string;\n /** Prefills the account holder's email in Stripe onboarding. */\n email?: string;\n businessType?: 'individual' | 'company' | 'non_profit' | 'government_entity';\n metadata?: Record<string, string | number | boolean | null | undefined>;\n idempotencyKey?: string;\n}\n\nexport interface StripeOnboardingLink {\n /** Single-use Stripe-hosted onboarding URL; treat it as a bearer secret. */\n url: string;\n expiresAt?: Date;\n raw: unknown;\n}\n\nexport interface StripeCreateOnboardingLinkOptions {\n /** Which requirements to collect up front; Stripe defaults to `currently_due`. */\n collect?: 'currently_due' | 'eventually_due';\n idempotencyKey?: string;\n}\n\n/**\n * Host mapping from a connected account to its owner. Return `undefined` or\n * `null` for an account the host does not recognize; the event is then\n * rejected with {@link PaymentNotOwnedError}.\n */\nexport type StripeConnectAccountResolver<TOwner> = (\n account: string,\n event: StripeWebhookEvent,\n) => TOwner | null | undefined | Promise<TOwner | null | undefined>;\n\nexport interface StripeResolveConnectWebhookOptions<TOwner> {\n resolveAccount: StripeConnectAccountResolver<TOwner>;\n /**\n * Endpoint the delivery arrived on. `connect` (default) verifies with\n * `connectWebhookSecret` and routes by the event's `account`. `platform`\n * verifies with `webhookSecret` and routes `application_fee.*` events by the\n * fee's connected account; other platform events are rejected.\n */\n endpoint?: 'connect' | 'platform';\n}\n\nexport interface StripeResolvedConnectWebhookEvent<TOwner> {\n event: StripeWebhookEvent;\n /** Connected account the event was routed by. */\n account: string;\n owner: TOwner;\n}\n\nexport class StripeAdapter implements PaymentBackend {\n readonly capabilities: PaymentBackendCapabilities;\n\n private readonly fetch: FetchLike;\n private readonly secretKey: string;\n private readonly apiBaseUrl: string;\n private readonly apiVersion: string;\n private readonly defaultCurrency: string;\n private readonly supportedCurrencies: Set<string>;\n private readonly checkoutMode: string;\n private readonly webhookSecret: string | undefined;\n private readonly connectWebhookSecret: string | undefined;\n private readonly stripeAccount: string | undefined;\n private readonly maxStoredPaymentOptions: number;\n private readonly maxStoredWebhookEventIds: number;\n private readonly optionsByQuote = new Map<string, PaymentOption>();\n private readonly seenWebhookEventIds = new Set<string>();\n\n constructor(private readonly options: StripeAdapterOptions) {\n if (typeof options.secretKey !== 'string' || !options.secretKey.trim()) {\n throw new PaymentConfigurationError('StripeAdapter requires secretKey.');\n }\n\n assertOptionalSecret(options.webhookSecret, 'webhookSecret');\n assertOptionalSecret(options.connectWebhookSecret, 'connectWebhookSecret');\n\n if (options.apiBaseUrl !== undefined) {\n if (typeof options.apiBaseUrl !== 'string') {\n throw new PaymentConfigurationError(\n 'StripeAdapter apiBaseUrl must be a string when configured.',\n );\n }\n\n if (!options.apiBaseUrl.trim()) {\n throw new PaymentConfigurationError(\n 'StripeAdapter apiBaseUrl must not be empty when configured.',\n );\n }\n }\n\n this.fetch = getFetch(options.fetch);\n this.maxStoredPaymentOptions = normalizeMaxStoredPaymentOptions(\n options.maxStoredPaymentOptions,\n 'StripeAdapter maxStoredPaymentOptions',\n );\n this.maxStoredWebhookEventIds = normalizeMaxStoredPaymentOptions(\n options.maxStoredWebhookEventIds ?? DEFAULT_MAX_STORED_WEBHOOK_EVENT_IDS,\n 'StripeAdapter maxStoredWebhookEventIds',\n );\n this.secretKey = options.secretKey.trim();\n this.apiBaseUrl = normalizeUrlString(\n options.apiBaseUrl ?? 'https://api.stripe.com/v1',\n 'StripeAdapter apiBaseUrl',\n ).replace(/\\/$/, '');\n this.apiVersion = normalizeNonEmptyString(\n options.apiVersion ?? DEFAULT_STRIPE_API_VERSION,\n 'StripeAdapter apiVersion',\n );\n this.defaultCurrency = normalizeStripeCurrency(\n options.defaultCurrency ?? 'usd',\n );\n this.supportedCurrencies = normalizeSupportedStripeCurrencies(\n options.supportedCurrencies,\n this.defaultCurrency,\n );\n this.checkoutMode = options.checkoutMode ?? 'payment';\n\n if (this.checkoutMode !== 'payment') {\n throw new PaymentConfigurationError(\n 'StripeAdapter only supports payment Checkout mode.',\n );\n }\n\n this.webhookSecret = options.webhookSecret?.trim();\n this.connectWebhookSecret = options.connectWebhookSecret?.trim();\n this.stripeAccount = normalizeOptionalStripeAccount(\n options.stripeAccount,\n 'StripeAdapter stripeAccount',\n );\n this.capabilities = {\n id: STRIPE_BACKEND_ID,\n displayName: 'Stripe Checkout',\n settlementCurrency: this.defaultCurrency.toUpperCase(),\n supportedSettlementCurrencies: [...this.supportedCurrencies].map(\n (currency) => currency.toUpperCase(),\n ),\n chain: 'stripe',\n settlementShape: 'url',\n x402Capable: false,\n confirmationLatency: {\n expectedSeconds: 5,\n maxExpectedSeconds: 600,\n description:\n 'Card payments usually confirm in seconds; bank debits can remain processing while Stripe settles them.',\n },\n supportsRefunds: true,\n supportsPayouts: true,\n supportsWebhooks: true,\n supportsManualCapture: true,\n supportsSavedPaymentMethods: true,\n metadata: {\n provider: 'stripe',\n },\n };\n }\n\n async createPaymentOption(\n input: StripeCreatePaymentOptionInput,\n ): Promise<PaymentOption> {\n const quoteId = normalizeNonEmptyString(input.quoteId, 'Stripe quoteId');\n const rawSuccessUrl = input.successUrl ?? this.options.successUrl;\n const rawCancelUrl = input.cancelUrl ?? this.options.cancelUrl;\n\n if (rawSuccessUrl === undefined || rawCancelUrl === undefined) {\n throw new PaymentConfigurationError(\n 'StripeAdapter createPaymentOption requires successUrl and cancelUrl.',\n );\n }\n\n const successUrl = normalizeUrlString(rawSuccessUrl, 'Stripe successUrl');\n const cancelUrl = normalizeUrlString(rawCancelUrl, 'Stripe cancelUrl');\n const currency = normalizeStripeCurrency(input.currency);\n this.assertSupportedCurrency(currency);\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe Checkout amount',\n );\n const applicationFeeAmount = normalizeApplicationFeeAmount(\n input.applicationFeeAmount,\n amount,\n 'Stripe Checkout applicationFeeAmount',\n );\n const expiresAt = normalizeDate(input.expiresAt);\n const stripeExpiresAt = normalizeStripeCheckoutExpiresAt(expiresAt);\n const params: Record<string, unknown> = {\n mode: this.checkoutMode,\n ...Object.fromEntries([\n ['success_url', successUrl],\n ['cancel_url', cancelUrl],\n ['client_reference_id', quoteId],\n ['customer_email', input.buyerEmail],\n ['expires_at', Math.floor(stripeExpiresAt.getTime() / 1_000)],\n ]),\n 'line_items[0][quantity]': 1,\n 'line_items[0][price_data][currency]': currency,\n 'line_items[0][price_data][unit_amount]': amount,\n 'line_items[0][price_data][product_data][name]':\n input.description ?? `Quote ${quoteId}`,\n ...(applicationFeeAmount === undefined\n ? {}\n : {\n 'payment_intent_data[application_fee_amount]': applicationFeeAmount,\n }),\n ...flattenStripeMetadata(input.metadata),\n 'metadata[quoteId]': quoteId,\n };\n\n const stripeAccount = this.resolveStripeAccount(input.stripeAccount);\n const session = await this.stripeRequest<Record<string, unknown>>(\n '/checkout/sessions',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount,\n body: formEncode(params),\n },\n );\n const sessionId = normalizeOptionalProviderString(\n readProviderString(session, 'id'),\n );\n const checkoutUrl = normalizeOptionalProviderString(\n readProviderString(session, 'url'),\n );\n\n if (!sessionId || !checkoutUrl) {\n throw new PaymentProviderError(\n 'Stripe Checkout Session response did not include id and url.',\n );\n }\n\n const option: PaymentOption = {\n backendId: this.capabilities.id,\n quoteId,\n payTo: checkoutUrl,\n settlementShape: 'url',\n settlementCurrency: currency.toUpperCase(),\n settlementAmount: amount,\n amount,\n currency: currency.toUpperCase(),\n expiresAt: stripeExpiresAt,\n providerPaymentId: sessionId,\n paymentUri: checkoutUrl,\n metadata: {\n sessionId,\n stripeAccount,\n paymentIntent: normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n ),\n },\n };\n\n rememberPaymentOption(\n this.optionsByQuote,\n stripePaymentOptionKey(quoteId, stripeAccount),\n option,\n this.maxStoredPaymentOptions,\n );\n\n return option;\n }\n\n watchPayment(input: StripeWatchPaymentInput): AsyncIterable<PaymentEvent> {\n return pollPaymentStatus(\n {\n ...input,\n pollIntervalMs:\n input.pollIntervalMs ?? this.options.pollIntervalMs ?? 5_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: StripePaymentStatusContext = {},\n ): Promise<PaymentStatusResult> {\n const normalizedQuoteId = normalizeNonEmptyString(\n quoteId,\n 'Stripe quoteId',\n );\n const normalizedPayTo = normalizeNonEmptyString(payTo, 'Stripe payTo');\n const contextProviderPaymentId =\n context.providerPaymentId === undefined\n ? undefined\n : normalizeNonEmptyString(\n context.providerPaymentId,\n 'Stripe providerPaymentId',\n );\n const contextStripeAccount = normalizeOptionalStripeAccount(\n context.stripeAccount,\n 'Stripe stripeAccount',\n );\n const scopedOption = this.optionsByQuote.get(\n stripePaymentOptionKey(\n normalizedQuoteId,\n contextStripeAccount ?? this.stripeAccount,\n ),\n );\n const sessionId =\n contextProviderPaymentId ??\n extractStripeSessionId(normalizedPayTo) ??\n scopedOption?.providerPaymentId;\n\n if (!sessionId) {\n throw new PaymentConfigurationError(\n 'Stripe getStatus requires a Checkout Session id or URL.',\n );\n }\n\n const storedOption = this.findStoredOptionBySessionId(sessionId);\n const stripeAccount =\n contextStripeAccount ??\n readStripeOptionAccount(storedOption) ??\n this.stripeAccount;\n const cachedOption = this.optionsByQuote.get(\n stripePaymentOptionKey(normalizedQuoteId, stripeAccount),\n );\n\n // A caller-supplied session id can deliberately select a later checkout\n // for the same quote. Cache-derived amount, currency, and expiry describe\n // only the session we created, never an explicitly selected replacement.\n const option =\n cachedOption?.providerPaymentId === sessionId ? cachedOption : undefined;\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(sessionId)}`,\n { stripeAccount },\n );\n const sessionQuoteId = readStripeSessionQuoteId(session);\n\n if (sessionQuoteId !== undefined && sessionQuoteId !== normalizedQuoteId) {\n throw new PaymentVerificationError(\n `Stripe Checkout Session quoteId ${sessionQuoteId} did not match ${normalizedQuoteId}.`,\n );\n }\n\n const paymentStatus = readString(session, 'payment_status');\n const status = mapStripeStatus(\n readString(session, 'status'),\n paymentStatus,\n );\n\n const contextAmount =\n context.amount === undefined\n ? undefined\n : normalizeMinorUnitAmount(context.amount, 'Stripe status');\n const contextCurrency =\n context.currency === undefined\n ? undefined\n : normalizeStripeCurrency(context.currency).toUpperCase();\n const sessionCurrency =\n readString(session, 'currency') === undefined\n ? undefined\n : normalizeStripeCurrency(\n readString(session, 'currency') ?? '',\n ).toUpperCase();\n const sessionAmount = readSafeInteger(session, 'amount_total');\n const expiresAt =\n option?.expiresAt ??\n (context.expiresAt === undefined\n ? undefined\n : normalizeDate(context.expiresAt));\n const effectiveStatus = applyExpiryToPendingStatus(status, expiresAt);\n\n return {\n backendId: this.capabilities.id,\n quoteId: normalizedQuoteId,\n payTo: normalizedPayTo,\n status: effectiveStatus,\n settlementCurrency:\n sessionCurrency ??\n option?.settlementCurrency ??\n contextCurrency ??\n this.defaultCurrency.toUpperCase(),\n settlementAmount:\n sessionAmount ?? option?.settlementAmount ?? contextAmount,\n receivedAmount:\n paymentStatus === 'paid' || paymentStatus === 'no_payment_required'\n ? (sessionAmount ?? option?.settlementAmount ?? contextAmount)\n : undefined,\n amount: option?.amount ?? contextAmount,\n currency: option?.currency ?? contextCurrency,\n providerPaymentId: sessionId,\n transactionId: normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n ),\n updatedAt: new Date(),\n raw: session,\n };\n }\n\n async sendPayout(input: SendPayoutInput): Promise<PayoutResult> {\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const destination = normalizeNonEmptyString(\n input.destination,\n 'Stripe payout destination',\n );\n const quoteId =\n input.quoteId === undefined\n ? undefined\n : normalizeNonEmptyString(input.quoteId, 'Stripe payout quoteId');\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe payout amount',\n );\n const transfer = await this.stripeRequest<Record<string, unknown>>(\n '/transfers',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n body: formEncode({\n amount,\n currency,\n destination,\n description: input.memo,\n ...flattenStripeMetadata(input.metadata),\n ...(quoteId === undefined ? {} : { 'metadata[quoteId]': quoteId }),\n }),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: 'submitted',\n payoutId: normalizeOptionalProviderString(\n readProviderString(transfer, 'id'),\n ),\n destination,\n amount,\n currency: currency.toUpperCase(),\n raw: transfer,\n };\n }\n\n async refundPayment(input: StripeRefundPaymentInput): Promise<RefundResult> {\n const rawPaymentReference = input.paymentId ?? input.transactionId;\n\n if (!rawPaymentReference) {\n throw new PaymentConfigurationError(\n 'Stripe refunds require paymentId or transactionId.',\n );\n }\n\n const paymentReference = normalizeNonEmptyString(\n rawPaymentReference,\n 'Stripe refund payment reference',\n );\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const amount =\n input.amount === undefined\n ? undefined\n : normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe refund amount',\n );\n const stripeAccount = this.resolveStripeAccount(input.stripeAccount);\n const refundReferenceParam = await this.resolveStripeRefundReferenceParam(\n paymentReference,\n stripeAccount,\n );\n const refundParams: Record<string, unknown> = {\n ...refundReferenceParam,\n amount: amount === undefined ? undefined : amount,\n reason: input.reason,\n refund_application_fee: input.refundApplicationFee,\n reverse_transfer: input.reverseTransfer,\n ...flattenStripeMetadata(input.metadata),\n };\n\n const refund = await this.stripeRequest<Record<string, unknown>>(\n '/refunds',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount,\n body: formEncode(refundParams),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeRefundStatus(readString(refund, 'status')),\n refundId: normalizeOptionalProviderString(\n readProviderString(refund, 'id'),\n ),\n transactionId: paymentReference,\n // Read the settled amount and currency back from the refund object\n // (mirrors capturePayment) so a full refund — no `input.amount` supplied,\n // and possibly a currency differing from the adapter default when\n // `input.currency` is omitted — surfaces what Stripe actually refunded\n // instead of the request defaults.\n amount: readSafeInteger(refund, 'amount') ?? amount,\n currency: readStripeResultCurrency(refund) ?? currency.toUpperCase(),\n raw: refund,\n };\n }\n\n async authorizePayment(\n input: StripeAuthorizePaymentInput,\n ): Promise<AuthorizationResult> {\n const currency = normalizeStripeCurrency(input.currency);\n this.assertSupportedCurrency(currency);\n const amount = normalizePositivePaymentAmount(\n input.amount,\n currency,\n 'Stripe authorize amount',\n );\n const paymentMethod = normalizeNonEmptyString(\n input.providerPaymentMethodId,\n 'Stripe authorize providerPaymentMethodId',\n );\n const providerCustomerId =\n input.providerCustomerId === undefined\n ? undefined\n : normalizeNonEmptyString(\n input.providerCustomerId,\n 'Stripe authorize providerCustomerId',\n );\n const quoteId =\n input.quoteId === undefined\n ? undefined\n : normalizeNonEmptyString(input.quoteId, 'Stripe authorize quoteId');\n const applicationFeeAmount = normalizeApplicationFeeAmount(\n input.applicationFeeAmount,\n amount,\n 'Stripe PaymentIntent applicationFeeAmount',\n );\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n '/payment_intents',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode({\n amount,\n currency,\n confirm: true,\n 'payment_method_types[]': 'card',\n description: input.description,\n application_fee_amount: applicationFeeAmount,\n ...Object.fromEntries([\n ['payment_method', paymentMethod],\n ['capture_method', 'manual'],\n // Off-session (merchant-initiated) by default — the primary use is\n // charging a saved card while the buyer is absent. Without this,\n // Stripe treats it as on-session and may raise an SCA challenge the\n // absent buyer can't complete, so the hold is never placed.\n ['off_session', input.offSession ?? true],\n ]),\n ...(providerCustomerId === undefined\n ? {}\n : { customer: providerCustomerId }),\n ...flattenStripeMetadata(input.metadata),\n ...(quoteId === undefined ? {} : { 'metadata[quoteId]': quoteId }),\n }),\n },\n );\n\n const providerPaymentId = normalizeOptionalProviderString(\n readProviderString(intent, 'id'),\n );\n\n if (!providerPaymentId) {\n throw new PaymentProviderError(\n 'Stripe PaymentIntent response did not include an id.',\n );\n }\n\n const status = mapStripeAuthorizationStatus(readString(intent, 'status'));\n // Only surface the SCA fields when authentication is actually required — the\n // documented contract — even though Stripe returns client_secret regardless.\n // (Authorization progress is observed via `parseWebhookEvent`, which surfaces\n // the ready-to-capture transition as `processing` — there is no distinct\n // `requires_capture` webhook status; `getStatus` handles Checkout sessions,\n // not PaymentIntents.)\n const actionRequired = status === 'requires_action';\n\n return {\n backendId: this.capabilities.id,\n status,\n providerPaymentId,\n amount: readSafeInteger(intent, 'amount') ?? amount,\n currency: (readString(intent, 'currency') ?? currency).toUpperCase(),\n clientSecret: actionRequired\n ? normalizeOptionalProviderString(\n readProviderString(intent, 'client_secret'),\n )\n : undefined,\n nextAction: actionRequired\n ? (intent.next_action ?? undefined)\n : undefined,\n raw: intent,\n };\n }\n\n async capturePayment(\n input: StripeCapturePaymentInput,\n ): Promise<CaptureResult> {\n const providerPaymentId = normalizeNonEmptyString(\n input.providerPaymentId,\n 'Stripe capture providerPaymentId',\n );\n const amount =\n input.amount === undefined\n ? undefined\n : normalizePositiveMinorUnitAmount(\n input.amount,\n 'Stripe capture amount',\n );\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n `/payment_intents/${encodeURIComponent(providerPaymentId)}/capture`,\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode({\n ...Object.fromEntries([['amount_to_capture', amount]]),\n ...flattenStripeMetadata(input.metadata),\n }),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeCaptureStatus(readString(intent, 'status')),\n providerPaymentId:\n normalizeOptionalProviderString(readProviderString(intent, 'id')) ??\n providerPaymentId,\n amount:\n readSafeInteger(intent, 'amount_received') ??\n readSafeInteger(intent, 'amount') ??\n amount,\n currency: readStripeResultCurrency(intent),\n raw: intent,\n };\n }\n\n async voidPayment(input: StripeVoidPaymentInput): Promise<VoidResult> {\n const providerPaymentId = normalizeNonEmptyString(\n input.providerPaymentId,\n 'Stripe void providerPaymentId',\n );\n const reason =\n input.reason === undefined\n ? undefined\n : normalizeNonEmptyString(input.reason, 'Stripe void reason');\n\n const intent = await this.stripeRequest<Record<string, unknown>>(\n `/payment_intents/${encodeURIComponent(providerPaymentId)}/cancel`,\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode(Object.fromEntries([['cancellation_reason', reason]])),\n },\n );\n\n return {\n backendId: this.capabilities.id,\n status: mapStripeVoidStatus(readString(intent, 'status')),\n providerPaymentId:\n normalizeOptionalProviderString(readProviderString(intent, 'id')) ??\n providerPaymentId,\n amount: readSafeInteger(intent, 'amount'),\n currency: readStripeResultCurrency(intent),\n raw: intent,\n };\n }\n\n async createSetupSession(\n input: StripeCreateSetupSessionInput,\n ): Promise<SetupSession> {\n const rawSuccessUrl = input.successUrl ?? this.options.successUrl;\n const rawCancelUrl = input.cancelUrl ?? this.options.cancelUrl;\n\n if (rawSuccessUrl === undefined || rawCancelUrl === undefined) {\n throw new PaymentConfigurationError(\n 'StripeAdapter createSetupSession requires successUrl and cancelUrl.',\n );\n }\n\n const successUrl = normalizeUrlString(rawSuccessUrl, 'Stripe successUrl');\n const cancelUrl = normalizeUrlString(rawCancelUrl, 'Stripe cancelUrl');\n // Currency for the setup-mode session (defaults to the backend currency).\n // Redundant now that payment_method_types is always set, but harmless and\n // kept so the session is well-formed if that restriction is ever relaxed.\n const currency = normalizeStripeCurrency(\n input.currency ?? this.defaultCurrency,\n );\n this.assertSupportedCurrency(currency);\n const providerCustomerId =\n input.providerCustomerId === undefined\n ? undefined\n : normalizeNonEmptyString(\n input.providerCustomerId,\n 'Stripe setup customer',\n );\n\n // Either attach to an existing customer, or force Stripe to create one so\n // the saved method comes back with a reusable `cus_` reference. Setup-mode\n // sessions do NOT create a customer on their own — `customer_creation` must\n // be `always`. All snake_case keys go through Object.fromEntries.\n const customerParams: [string, unknown][] = [];\n if (providerCustomerId !== undefined) {\n customerParams.push(['customer', providerCustomerId]);\n } else {\n customerParams.push(['customer_creation', 'always']);\n if (input.customerEmail !== undefined) {\n customerParams.push([\n 'customer_email',\n normalizeNonEmptyString(\n input.customerEmail,\n 'Stripe setup customerEmail',\n ),\n ]);\n }\n }\n\n const params: Record<string, unknown> = {\n mode: 'setup',\n currency,\n // Restrict to cards: SavedPaymentMethod exposes card display fields\n // (brand/last4/expiry), so allowing SEPA/Bacs/etc. would yield saved\n // methods with no usable display detail.\n 'payment_method_types[]': 'card',\n ...Object.fromEntries([\n ['success_url', successUrl],\n ['cancel_url', cancelUrl],\n ...customerParams,\n ]),\n ...flattenStripeMetadata(input.metadata),\n };\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n '/checkout/sessions',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n stripeAccount: this.resolveStripeAccount(input.stripeAccount),\n body: formEncode(params),\n },\n );\n\n const sessionId = normalizeOptionalProviderString(\n readProviderString(session, 'id'),\n );\n const url = normalizeOptionalProviderString(\n readProviderString(session, 'url'),\n );\n\n if (!sessionId || !url) {\n throw new PaymentProviderError(\n 'Stripe setup Checkout Session response did not include id and url.',\n );\n }\n\n return {\n backendId: this.capabilities.id,\n sessionId,\n url,\n providerCustomerId:\n providerCustomerId ??\n normalizeOptionalProviderString(\n readProviderString(session, 'customer'),\n ),\n raw: session,\n };\n }\n\n async getSetupResult(\n input: StripeGetSetupResultInput,\n ): Promise<SavedPaymentMethod> {\n const sessionId = normalizeNonEmptyString(\n input.sessionId,\n 'Stripe setup sessionId',\n );\n\n const query = new URLSearchParams();\n query.append('expand[]', 'setup_intent.payment_method');\n\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(sessionId)}?${query.toString()}`,\n { stripeAccount: this.resolveStripeAccount(input.stripeAccount) },\n );\n\n const setupIntent = readObject(session, 'setup_intent');\n const paymentMethod = readObject(setupIntent, 'payment_method');\n const card = readObject(paymentMethod, 'card');\n\n // `customer` is a bare `cus_` string on the request path (only\n // setup_intent.payment_method is expanded), but read tolerantly of an\n // expanded object so a future `expand[]=customer` can't wrongly downgrade a\n // completed setup to a permanent `pending`.\n const providerCustomerId = normalizeOptionalProviderString(\n readProviderString(session, 'customer') ??\n readProviderString(readObject(session, 'customer'), 'id'),\n );\n const providerPaymentMethodId = normalizeOptionalProviderString(\n readProviderString(paymentMethod, 'id'),\n );\n\n let status = mapStripeSetupStatus(\n readString(session, 'status'),\n readString(setupIntent, 'status'),\n );\n // Never report `complete` without the reusable references a caller needs to\n // charge the method later — a `pm_` with no `cus_` can't be charged\n // off-session, so treat that as not-yet-ready rather than a false success.\n if (\n status === 'complete' &&\n (!providerCustomerId || !providerPaymentMethodId)\n ) {\n status = 'pending';\n }\n\n return {\n backendId: this.capabilities.id,\n status,\n providerCustomerId,\n providerPaymentMethodId,\n type: readString(paymentMethod, 'type'),\n brand: readString(card, 'brand'),\n last4: readString(card, 'last4'),\n expMonth: readSafeInteger(card, 'exp_month'),\n expYear: readSafeInteger(card, 'exp_year'),\n raw: session,\n };\n }\n\n /**\n * Verify and parse a delivery to the platform webhook endpoint. Events that\n * carry a connected `account` are rejected: they belong to the Connect\n * endpoint and must never be processed as platform-account events.\n */\n parseWebhookEvent(payload: string, signature?: string): StripeWebhookEvent {\n const event = this.verifyWebhookEvent(payload, signature, 'platform');\n this.recordWebhookEvent(event);\n return event;\n }\n\n /**\n * Verify a Stripe Connect endpoint delivery with `connectWebhookSecret`,\n * then parse it. The signature is checked before the payload is parsed, and\n * an event without a connected `account` is rejected. When this adapter is\n * scoped to a `stripeAccount`, events for any other account are rejected.\n * The payload, including `quoteId`, is controlled by the connected account:\n * bind `quoteId` to `account` before acting on it.\n */\n parseConnectWebhookEvent(\n payload: string,\n signature?: string,\n ): StripeConnectWebhookEvent {\n const event = this.verifyWebhookEvent(payload, signature, 'connect');\n this.recordWebhookEvent(event);\n return event as StripeConnectWebhookEvent;\n }\n\n /**\n * Verify a webhook delivery, then map its connected account to an owner\n * (for example a tenant) with the host's resolver. An account the resolver\n * does not recognize is rejected with {@link PaymentNotOwnedError}; there is\n * no fallback to the platform account. The event is recorded for duplicate\n * detection only after it resolves, so a retried delivery that failed to\n * resolve is not reported as a duplicate.\n *\n * Security: a connected account controls the objects it creates, so a\n * Connect event's `quoteId` (and every other payload field) is chosen by\n * that account. Resolving the account proves only who sent the event. The\n * host must check that `event.quoteId` belongs to the resolved owner (for\n * example inside `resolveAccount`, which receives the event, or before\n * settling) and must never settle another owner's quote from it.\n */\n async resolveConnectWebhookEvent<TOwner>(\n payload: string,\n signature: string | undefined,\n options: StripeResolveConnectWebhookOptions<TOwner>,\n ): Promise<StripeResolvedConnectWebhookEvent<TOwner>> {\n if (typeof options?.resolveAccount !== 'function') {\n throw new PaymentConfigurationError(\n 'Stripe resolveConnectWebhookEvent requires a resolveAccount function.',\n );\n }\n\n const endpoint = options.endpoint ?? 'connect';\n\n if (endpoint !== 'connect' && endpoint !== 'platform') {\n throw new PaymentConfigurationError(\n 'Stripe resolveConnectWebhookEvent endpoint must be connect or platform.',\n );\n }\n\n const event = this.verifyWebhookEvent(payload, signature, endpoint);\n const account =\n endpoint === 'connect'\n ? event.account\n : event.connect?.type === 'application_fee.created' ||\n event.connect?.type === 'application_fee.refunded'\n ? event.connect.applicationFee.account\n : undefined;\n\n if (account === undefined) {\n throw new PaymentNotOwnedError(\n `Stripe webhook event ${event.id} (${event.type}) has no connected account to route by.`,\n );\n }\n\n this.assertAdapterAccount(account);\n const owner = await options.resolveAccount(account, event);\n\n if (owner === undefined || owner === null) {\n throw new PaymentNotOwnedError(\n `Stripe connected account ${account} is not mapped to an owner.`,\n );\n }\n\n this.recordWebhookEvent(event);\n return { event, account, owner };\n }\n\n /**\n * Create a Stripe Connect **Standard** account. The account holder owns the\n * Stripe relationship and dashboard; the platform only connects to it.\n * Always issued on the platform account, never on a connected account.\n */\n async createStandardAccount(\n input: StripeCreateStandardAccountInput = {},\n ): Promise<StripeConnectAccountStatus> {\n const country =\n input.country === undefined\n ? undefined\n : normalizeStripeCountry(input.country);\n const email =\n input.email === undefined\n ? undefined\n : normalizeNonEmptyString(input.email, 'Stripe account email');\n const account = await this.stripeRequest<Record<string, unknown>>(\n '/accounts',\n {\n method: 'POST',\n idempotencyKey: input.idempotencyKey,\n body: formEncode({\n type: 'standard',\n country,\n email,\n ...Object.fromEntries([['business_type', input.businessType]]),\n ...flattenStripeMetadata(input.metadata),\n }),\n },\n );\n\n return mapStripeConnectAccount(account, 'Stripe account response');\n }\n\n /**\n * Create a single-use Account Link that sends the account holder through\n * Stripe-hosted onboarding. `refreshUrl` is visited when the link expires or\n * is reused, and should mint a new link; `returnUrl` does not mean\n * onboarding finished, so read {@link getAccountCapabilities} afterwards.\n */\n async createOnboardingLink(\n accountId: string,\n returnUrl: string,\n refreshUrl: string,\n options: StripeCreateOnboardingLinkOptions = {},\n ): Promise<StripeOnboardingLink> {\n const account = normalizeStripeConnectedAccountId(accountId);\n const link = await this.stripeRequest<Record<string, unknown>>(\n '/account_links',\n {\n method: 'POST',\n idempotencyKey: options.idempotencyKey,\n body: formEncode({\n account,\n type: 'account_onboarding',\n collect: options.collect,\n ...Object.fromEntries([\n ['return_url', normalizeUrlString(returnUrl, 'Stripe returnUrl')],\n [\n 'refresh_url',\n normalizeUrlString(refreshUrl, 'Stripe refreshUrl'),\n ],\n ]),\n }),\n },\n );\n const url = normalizeOptionalProviderString(\n readProviderString(link, 'url'),\n );\n\n if (!url) {\n throw new PaymentProviderError(\n 'Stripe Account Link response did not include a url.',\n );\n }\n\n const expiresAtSeconds = readSafeInteger(link, 'expires_at');\n\n return {\n url,\n expiresAt:\n expiresAtSeconds === undefined\n ? undefined\n : new Date(expiresAtSeconds * 1_000),\n raw: link,\n };\n }\n\n /**\n * Read a connected account's onboarding and capability state\n * (`charges_enabled`, `details_submitted`, `payouts_enabled`, per-capability\n * status, and outstanding requirements).\n */\n async getAccountCapabilities(\n accountId: string,\n ): Promise<StripeConnectAccountStatus> {\n const account = normalizeStripeConnectedAccountId(accountId);\n const response = await this.stripeRequest<Record<string, unknown>>(\n `/accounts/${encodeURIComponent(account)}`,\n );\n const status = mapStripeConnectAccount(response, 'Stripe account response');\n\n if (status.accountId !== account) {\n throw new PaymentVerificationError(\n `Stripe account response ${status.accountId} did not match ${account}.`,\n );\n }\n\n return status;\n }\n\n /** Authoritative read. No request or adapter account scope means platform. */\n async getDispute(\n disputeId: string,\n options: StripeGetDisputeOptions = {},\n ): Promise<StripeDispute> {\n const id = normalizeNonEmptyString(disputeId, 'Stripe dispute id');\n if (!/^(?:du|dp)_[A-Za-z0-9_]+$/.test(id)) {\n throw new PaymentConfigurationError('Stripe dispute id is invalid.');\n }\n const scope = this.resolveStripeAccount(options.stripeAccount);\n const account =\n scope === undefined\n ? undefined\n : normalizeStripeConnectedAccountId(scope);\n if (account !== undefined) this.assertAdapterAccount(account);\n if (\n options.expectedLivemode !== undefined &&\n typeof options.expectedLivemode !== 'boolean'\n ) {\n throw new PaymentConfigurationError(\n 'Stripe expectedLivemode must be boolean.',\n );\n }\n const response = await this.stripeRequest<Record<string, unknown>>(\n `/disputes/${encodeURIComponent(id)}?expand[]=charge`,\n { stripeAccount: account },\n );\n const dispute = mapStripeDispute(response, account);\n if (\n dispute.id !== id ||\n (options.expectedLivemode !== undefined &&\n dispute.livemode !== options.expectedLivemode)\n ) {\n throw new PaymentVerificationError(\n 'Stripe dispute response identity or environment did not match the request.',\n );\n }\n return dispute;\n }\n\n /**\n * Resolve existing PI/Charge evidence to a Checkout Session in the authenticated\n * account and required environment. No local cache or new PI metadata needed.\n * A quote is correlation evidence, not authorization: bind it to your owner.\n */\n async lookupCheckout(\n input: StripeCheckoutLookupInput,\n ): Promise<PaymentCheckoutLookupResult> {\n if (!input || typeof input.livemode !== 'boolean') {\n throw new PaymentConfigurationError('Stripe lookup requires livemode.');\n }\n const maxPages = input.maxPages ?? 10;\n if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > 100) {\n throw new PaymentConfigurationError(\n 'Stripe lookup maxPages must be 1–100.',\n );\n }\n const scope = this.resolveStripeAccount(input.stripeAccount);\n const account =\n scope === undefined\n ? undefined\n : normalizeStripeConnectedAccountId(scope);\n if (account !== undefined) this.assertAdapterAccount(account);\n const inputId = (value: string | undefined, prefix: string) => {\n if (value === undefined) return undefined;\n if (\n typeof value !== 'string' ||\n !new RegExp(`^${prefix}_[A-Za-z0-9_]+$`).test(value)\n ) {\n throw new PaymentConfigurationError(\n 'Stripe lookup payment reference is invalid.',\n );\n }\n return value;\n };\n let paymentIntentId = inputId(input.paymentIntentId, 'pi');\n const chargeId = inputId(input.chargeId, '(?:ch|py)');\n if (paymentIntentId === undefined && chargeId === undefined) {\n throw new PaymentConfigurationError(\n 'Stripe lookup requires paymentIntentId or chargeId.',\n );\n }\n const read = async (path: string): Promise<unknown> => {\n // Do not expose private provider payloads through errors from this API.\n try {\n return await this.stripeRequest<unknown>(path, {\n stripeAccount: account,\n });\n } catch (error) {\n throw new PaymentProviderError(\n 'Stripe checkout lookup request failed.',\n {\n retryable:\n error instanceof PaymentProviderError ? error.retryable : true,\n },\n );\n }\n };\n if (chargeId !== undefined) {\n const charge = lookupRecord(\n await read(`/charges/${encodeURIComponent(chargeId)}`),\n );\n assertLookupObject(charge, 'charge', chargeId, input.livemode, account);\n // Stripe explicitly returns null for Charges made without a PaymentIntent.\n if (charge.payment_intent === null) {\n if (paymentIntentId !== undefined) lookupIdentityError();\n } else {\n const chargeIntentId = lookupReference(\n charge.payment_intent,\n 'payment_intent',\n 'pi',\n input.livemode,\n account,\n );\n if (paymentIntentId !== undefined && paymentIntentId !== chargeIntentId)\n lookupIdentityError();\n paymentIntentId = chargeIntentId;\n }\n }\n const context = {\n backendId: STRIPE_BACKEND_ID,\n ...(account === undefined ? {} : { accountId: account }),\n livemode: input.livemode,\n ...(paymentIntentId === undefined ? {} : { paymentIntentId }),\n ...(chargeId === undefined ? {} : { chargeId }),\n };\n if (paymentIntentId === undefined)\n return { ...context, status: 'no_match' };\n const intent = lookupRecord(\n await read(`/payment_intents/${encodeURIComponent(paymentIntentId)}`),\n );\n assertLookupObject(\n intent,\n 'payment_intent',\n paymentIntentId,\n input.livemode,\n account,\n );\n const seen = new Set<string>();\n const matches: {\n checkoutId: string;\n quoteId?: string;\n clientReferenceId?: string;\n }[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < maxPages; page++) {\n const params = new URLSearchParams({\n payment_intent: paymentIntentId,\n limit: '100',\n });\n if (cursor !== undefined) params.set('starting_after', cursor);\n const list = lookupRecord(await read(`/checkout/sessions?${params}`));\n if (\n list.object !== 'list' ||\n !Array.isArray(list.data) ||\n typeof list.has_more !== 'boolean' ||\n list.data.length > 100\n )\n lookupDataError();\n for (const value of list.data) {\n const session = lookupRecord(value);\n const id = lookupReference(\n session.id,\n 'checkout.session',\n 'cs',\n input.livemode,\n account,\n );\n assertLookupObject(\n session,\n 'checkout.session',\n id,\n input.livemode,\n account,\n );\n if (session.mode !== 'payment') lookupDataError();\n if (\n lookupReference(\n session.payment_intent,\n 'payment_intent',\n 'pi',\n input.livemode,\n account,\n ) !== paymentIntentId\n )\n lookupIdentityError();\n if (seen.has(id)) lookupDataError();\n seen.add(id);\n const metadata =\n session.metadata == null ? {} : lookupRecord(session.metadata);\n const quote = lookupQuote(metadata.quoteId);\n const clientReferenceId = lookupQuote(session.client_reference_id);\n if (\n quote !== undefined &&\n clientReferenceId !== undefined &&\n quote !== clientReferenceId\n )\n lookupIdentityError();\n matches.push({\n checkoutId: id,\n quoteId: quote ?? clientReferenceId,\n ...(clientReferenceId === undefined ? {} : { clientReferenceId }),\n });\n cursor = id;\n }\n if (!list.has_more) {\n if (matches.length === 0) return { ...context, status: 'no_match' };\n if (matches.length !== 1)\n return { ...context, status: 'indeterminate', reason: 'ambiguous' };\n const match = matches[0]!;\n if (match.quoteId === undefined)\n return {\n ...context,\n status: 'indeterminate',\n reason: 'missing_quote',\n };\n return {\n ...context,\n status: 'matched',\n checkoutId: match.checkoutId,\n paymentIntentId,\n quoteId: match.quoteId,\n ...(match.clientReferenceId === undefined\n ? {}\n : { clientReferenceId: match.clientReferenceId }),\n };\n }\n if (list.data.length === 0) lookupDataError();\n }\n return { ...context, status: 'indeterminate', reason: 'pagination_limit' };\n }\n\n private verifyWebhookEvent(\n payload: string,\n signature: string | undefined,\n endpoint: 'connect' | 'platform',\n ): StripeWebhookEvent {\n const secret =\n endpoint === 'connect' ? this.connectWebhookSecret : this.webhookSecret;\n\n if (!secret) {\n throw new PaymentConfigurationError(\n endpoint === 'connect'\n ? 'StripeAdapter parseConnectWebhookEvent requires connectWebhookSecret.'\n : 'StripeAdapter parseWebhookEvent requires webhookSecret.',\n );\n }\n\n if (!signature) {\n throw new PaymentProviderError('Missing Stripe webhook signature.');\n }\n\n // Authenticate the raw bytes before anything reads the payload.\n verifyStripeWebhookSignature(payload, signature, secret);\n\n const event = parseStripeWebhookPayload(payload);\n const id = readRequiredWebhookString(\n event,\n 'id',\n 'Stripe webhook event id',\n );\n const type = readRequiredWebhookString(\n event,\n 'type',\n 'Stripe webhook event type',\n );\n const rawAccount = event.account;\n let account: string | undefined;\n\n if (endpoint === 'connect') {\n account = typeof rawAccount === 'string' ? rawAccount.trim() : undefined;\n\n if (!account || !STRIPE_CONNECTED_ACCOUNT_ID.test(account)) {\n throw new PaymentVerificationError(\n 'Stripe Connect webhook event did not include a valid connected account.',\n );\n }\n\n this.assertAdapterAccount(account);\n } else if (rawAccount !== undefined && rawAccount !== null) {\n throw new PaymentVerificationError(\n 'Stripe connected-account event received on the platform webhook endpoint; verify it with parseConnectWebhookEvent.',\n );\n }\n\n const data = (\n event.data as { object?: Record<string, unknown> } | undefined\n )?.object;\n const dispute = type.startsWith('charge.dispute.')\n ? mapStripeDispute(data, account)\n : undefined;\n let disputeType: StripeDisputeEventType | undefined;\n if (dispute !== undefined) {\n disputeType = readStripeDisputeEventType(type);\n if (\n typeof event.livemode !== 'boolean' ||\n event.livemode !== dispute.livemode\n ) {\n throw new PaymentVerificationError(\n 'Stripe dispute event environment is missing or inconsistent.',\n );\n }\n }\n const createdAt =\n dispute === undefined ? undefined : disputeDate(event.created);\n const connect: StripeConnectEventDetail | undefined =\n disputeType && dispute\n ? { type: disputeType, dispute }\n : mapStripeConnectEventDetail(type, data);\n\n if (\n account !== undefined &&\n connect?.type === 'account.updated' &&\n connect.account.accountId !== account\n ) {\n throw new PaymentVerificationError(\n 'Stripe account.updated webhook object did not match the event account.',\n );\n }\n\n return {\n id,\n type,\n status: mapStripeWebhookStatus(type, data),\n quoteId: normalizeOptionalWebhookString(\n // `client_reference_id` is a Checkout Session-only field; honor it only\n // for session events so a non-session object (a PaymentIntent / Charge /\n // Transfer, possibly from a malicious Connect account) can't spoof\n // correlation to another quote's id. Non-session events correlate only\n // via our own `metadata.quoteId`.\n (type.startsWith('checkout.session.')\n ? readString(data, 'client_reference_id')\n : undefined) ??\n readString(\n (data?.metadata as Record<string, unknown>) ?? {},\n 'quoteId',\n ),\n ),\n providerPaymentId: normalizeOptionalWebhookString(readString(data, 'id')),\n duplicate: this.seenWebhookEventIds.has(id),\n ...(account === undefined ? {} : { account }),\n ...(connect === undefined ? {} : { connect }),\n ...(dispute === undefined\n ? {}\n : { dispute, livemode: dispute.livemode, createdAt }),\n raw: event,\n };\n }\n\n private recordWebhookEvent(event: StripeWebhookEvent): void {\n if (this.seenWebhookEventIds.has(event.id)) {\n event.duplicate = true;\n return;\n }\n\n event.duplicate = false;\n this.seenWebhookEventIds.add(event.id);\n while (this.seenWebhookEventIds.size > this.maxStoredWebhookEventIds) {\n const oldest = this.seenWebhookEventIds.values().next().value;\n\n if (oldest === undefined) {\n break;\n }\n\n this.seenWebhookEventIds.delete(oldest);\n }\n }\n\n private assertAdapterAccount(account: string): void {\n if (this.stripeAccount !== undefined && account !== this.stripeAccount) {\n throw new PaymentNotOwnedError(\n `Stripe connected account ${account} does not match this adapter's account scope.`,\n );\n }\n }\n\n private async stripeRequest<T>(\n path: string,\n init: RequestInit & {\n idempotencyKey?: string;\n stripeAccount?: string;\n } = {},\n ): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${this.secretKey}`);\n headers.set('Content-Type', 'application/x-www-form-urlencoded');\n headers.set('Accept', 'application/json');\n headers.set('Stripe-Version', this.apiVersion);\n\n if (init.stripeAccount !== undefined) {\n headers.set('Stripe-Account', init.stripeAccount);\n }\n\n if (init.idempotencyKey !== undefined) {\n headers.set(\n 'Idempotency-Key',\n normalizeNonEmptyString(init.idempotencyKey, 'Stripe idempotencyKey'),\n );\n }\n\n const {\n idempotencyKey: _idempotencyKey,\n stripeAccount: _stripeAccount,\n ...requestInit\n } = init;\n const response = await this.fetch(`${this.apiBaseUrl}${path}`, {\n ...requestInit,\n method: init.method ?? 'GET',\n headers,\n });\n\n return readJsonResponse<T>(response, `Stripe ${path}`);\n }\n\n private assertSupportedCurrency(currency: string): void {\n if (!this.supportedCurrencies.has(currency)) {\n throw new PaymentConfigurationError(\n `StripeAdapter currency ${currency.toUpperCase()} is not configured as supported.`,\n );\n }\n }\n\n private async resolveStripeRefundReferenceParam(\n paymentReference: string,\n stripeAccount: string | undefined,\n ): Promise<Record<string, string>> {\n if (paymentReference.startsWith('cs_')) {\n const session = await this.stripeRequest<Record<string, unknown>>(\n `/checkout/sessions/${encodeURIComponent(paymentReference)}`,\n { stripeAccount },\n );\n const paymentIntent = normalizeOptionalProviderString(\n readProviderString(session, 'payment_intent'),\n );\n\n if (!paymentIntent) {\n throw new PaymentProviderError(\n 'Stripe Checkout Session did not include payment_intent for refund.',\n );\n }\n\n return Object.fromEntries([['payment_intent', paymentIntent]]);\n }\n\n return stripeRefundReferenceParam(paymentReference);\n }\n\n private resolveStripeAccount(\n override: string | undefined,\n ): string | undefined {\n return (\n normalizeOptionalStripeAccount(override, 'Stripe stripeAccount') ??\n this.stripeAccount\n );\n }\n\n private findStoredOptionBySessionId(\n sessionId: string,\n ): PaymentOption | undefined {\n for (const option of this.optionsByQuote.values()) {\n if (option.providerPaymentId === sessionId) return option;\n }\n return undefined;\n }\n}\n\nfunction assertOptionalSecret(value: unknown, name: string): void {\n if (value === undefined) return;\n\n if (typeof value !== 'string') {\n throw new PaymentConfigurationError(\n `StripeAdapter ${name} must be a string when configured.`,\n );\n }\n\n if (!value.trim()) {\n throw new PaymentConfigurationError(\n `StripeAdapter ${name} must not be empty when configured.`,\n );\n }\n}\n\nconst STRIPE_CONNECTED_ACCOUNT_ID = /^acct_[A-Za-z0-9]+$/;\n\nfunction normalizeStripeConnectedAccountId(value: unknown): string {\n const account = typeof value === 'string' ? value.trim() : undefined;\n\n if (!account || !STRIPE_CONNECTED_ACCOUNT_ID.test(account)) {\n throw new PaymentConfigurationError(\n 'Stripe connected account id must look like acct_...',\n );\n }\n\n return account;\n}\n\nfunction normalizeStripeCountry(value: string): string {\n const country = typeof value === 'string' ? value.trim().toUpperCase() : '';\n\n if (!/^[A-Z]{2}$/.test(country)) {\n throw new PaymentConfigurationError(\n 'Stripe account country must be a two-letter ISO country code.',\n );\n }\n\n return country;\n}\n\nfunction readStringArray(\n value: Record<string, unknown> | undefined,\n key: string,\n): string[] {\n const item = value?.[key];\n\n return Array.isArray(item)\n ? item.filter((entry): entry is string => typeof entry === 'string')\n : [];\n}\n\nfunction mapStripeConnectAccount(\n account: Record<string, unknown> | undefined,\n context: string,\n): StripeConnectAccountStatus {\n const accountId = readProviderString(account, 'id')?.trim();\n\n if (!account || !accountId || !STRIPE_CONNECTED_ACCOUNT_ID.test(accountId)) {\n throw new PaymentProviderError(`${context} did not include an account id.`);\n }\n\n const capabilities: Record<string, string> = {};\n\n for (const [name, state] of Object.entries(\n readObject(account, 'capabilities') ?? {},\n )) {\n if (typeof state === 'string') {\n capabilities[name] = state;\n }\n }\n\n const requirements = readObject(account, 'requirements');\n const disabledReason = normalizeOptionalProviderString(\n readProviderString(requirements, 'disabled_reason'),\n );\n const defaultCurrency = readProviderString(account, 'default_currency');\n\n return {\n accountId,\n type: normalizeOptionalProviderString(readProviderString(account, 'type')),\n chargesEnabled: account.charges_enabled === true,\n detailsSubmitted: account.details_submitted === true,\n payoutsEnabled: account.payouts_enabled === true,\n capabilities,\n requirements: {\n currentlyDue: readStringArray(requirements, 'currently_due'),\n eventuallyDue: readStringArray(requirements, 'eventually_due'),\n pastDue: readStringArray(requirements, 'past_due'),\n ...(disabledReason === undefined ? {} : { disabledReason }),\n },\n country: normalizeOptionalProviderString(\n readProviderString(account, 'country'),\n ),\n defaultCurrency: defaultCurrency?.toUpperCase(),\n raw: account,\n };\n}\n\nfunction mapStripeApplicationFee(\n fee: Record<string, unknown> | undefined,\n): StripeApplicationFee {\n const id = normalizeOptionalProviderString(readProviderString(fee, 'id'));\n\n if (!fee || !id) {\n throw new PaymentProviderError(\n 'Stripe application_fee webhook object did not include an id.',\n );\n }\n\n const account = normalizeOptionalProviderString(\n readProviderString(fee, 'account'),\n );\n\n if (account !== undefined && !STRIPE_CONNECTED_ACCOUNT_ID.test(account)) {\n throw new PaymentProviderError(\n 'Stripe application_fee webhook object has an invalid account id.',\n );\n }\n const livemode = fee.livemode;\n\n return {\n id,\n account,\n amount: readSafeInteger(fee, 'amount'),\n amountRefunded: readSafeInteger(fee, 'amount_refunded'),\n currency: readStripeResultCurrency(fee),\n refunded: fee.refunded === true,\n charge: normalizeOptionalProviderString(\n readProviderString(fee, 'charge') ??\n readProviderString(readObject(fee, 'charge'), 'id'),\n ),\n livemode: typeof livemode === 'boolean' ? livemode : undefined,\n raw: fee,\n };\n}\n\nconst STRIPE_DISPUTE_STATUSES: ReadonlySet<string> = new Set([\n 'warning_needs_response',\n 'warning_under_review',\n 'warning_closed',\n 'needs_response',\n 'under_review',\n 'won',\n 'lost',\n 'prevented',\n]);\n\nfunction readStripeDisputeEventType(type: string): StripeDisputeEventType {\n switch (type) {\n case 'charge.dispute.created':\n case 'charge.dispute.updated':\n case 'charge.dispute.closed':\n case 'charge.dispute.funds_withdrawn':\n case 'charge.dispute.funds_reinstated':\n return type;\n default:\n throw new PaymentProviderError('Unsupported Stripe dispute event type.');\n }\n}\n\nfunction disputeError(field: string): never {\n throw new PaymentProviderError(\n `Stripe dispute has invalid or missing ${field}.`,\n );\n}\n\nfunction disputeRecord(value: unknown, field: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return disputeError(field);\n return value as Record<string, unknown>;\n}\n\nfunction disputeString(value: unknown, field: string): string {\n if (typeof value !== 'string' || !value.trim() || value !== value.trim())\n return disputeError(field);\n return value;\n}\n\nfunction disputeId(value: unknown, prefix: string): string {\n const id = disputeString(\n typeof value === 'object' && value !== null\n ? disputeRecord(value, prefix).id\n : value,\n prefix,\n );\n // Charge IDs include non-card py_ identities; legacy disputes can use dp_.\n const prefixes =\n prefix === 'ch' ? '(?:ch|py)' : prefix === 'du' ? '(?:du|dp)' : prefix;\n if (!new RegExp(`^${prefixes}_[A-Za-z0-9_]+$`).test(id))\n return disputeError(prefix);\n return id;\n}\n\nfunction disputeInteger(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value))\n return disputeError(field);\n return value;\n}\n\nfunction disputeDate(value: unknown): Date {\n const seconds = disputeInteger(value, 'created');\n const date = new Date(seconds * 1000);\n if (\n seconds < 0 ||\n !Number.isSafeInteger(seconds * 1000) ||\n !Number.isFinite(date.getTime())\n )\n return disputeError('created');\n return date;\n}\n\nfunction disputeCurrency(value: unknown): string {\n if (typeof value !== 'string' || !/^[a-z]{3}$/.test(value))\n return disputeError('currency');\n return value.toUpperCase();\n}\n\nfunction lookupDataError(): never {\n throw new PaymentProviderError(\n 'Stripe checkout lookup returned malformed data.',\n );\n}\n\nfunction lookupIdentityError(): never {\n throw new PaymentVerificationError(\n 'Stripe checkout lookup identity or environment mismatch.',\n );\n}\n\nfunction lookupRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return lookupDataError();\n return value as Record<string, unknown>;\n}\n\nfunction assertLookupObject(\n value: Record<string, unknown>,\n object: string,\n id: string,\n livemode: boolean,\n account: string | undefined,\n): void {\n if (value.object !== object || typeof value.livemode !== 'boolean')\n lookupDataError();\n if (\n value.id !== id ||\n value.livemode !== livemode ||\n (value.account !== undefined && value.account !== account)\n )\n lookupIdentityError();\n}\n\nfunction lookupReference(\n value: unknown,\n object: string,\n prefix: string,\n livemode: boolean,\n account: string | undefined,\n): string {\n const expanded =\n typeof value === 'object' && value !== null\n ? lookupRecord(value)\n : undefined;\n const id = expanded === undefined ? value : expanded.id;\n if (\n typeof id !== 'string' ||\n !new RegExp(`^${prefix}_[A-Za-z0-9_]+$`).test(id)\n )\n return lookupDataError();\n if (expanded !== undefined)\n assertLookupObject(expanded, object, id, livemode, account);\n return id;\n}\n\nfunction lookupQuote(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'string' || value.length === 0 || value.trim() !== value)\n return lookupDataError();\n return value;\n}\n\nfunction mapStripeDispute(value: unknown, account?: string): StripeDispute {\n const object = disputeRecord(value, 'object');\n if (object.object !== 'dispute') return disputeError('object');\n const id = disputeId(object.id, 'du');\n const chargeId = disputeId(object.charge, 'ch');\n const expandedCharge =\n typeof object.charge === 'object'\n ? disputeRecord(object.charge, 'charge')\n : undefined;\n const paymentIntent = object.payment_intent ?? expandedCharge?.payment_intent;\n const paymentIntentId =\n paymentIntent == null ? undefined : disputeId(paymentIntent, 'pi');\n if (\n object.payment_intent != null &&\n expandedCharge?.payment_intent != null &&\n paymentIntentId !== disputeId(expandedCharge.payment_intent, 'pi')\n )\n return disputeError('payment_intent');\n const amount = disputeInteger(object.amount, 'amount');\n if (amount < 0) return disputeError('amount');\n const currency = disputeCurrency(object.currency);\n const providerStatus = disputeString(object.status, 'status');\n const status: PaymentDisputeStatus = STRIPE_DISPUTE_STATUSES.has(\n providerStatus,\n )\n ? (providerStatus as PaymentDisputeStatus)\n : 'unknown';\n if (typeof object.livemode !== 'boolean') return disputeError('livemode');\n // Stripe objects normally omit account; when supplied it must agree with the\n // authenticated scope, never replace it with a payload-provided account.\n if (object.account !== undefined && object.account !== account)\n return disputeError('account');\n if (\n expandedCharge?.livemode !== undefined &&\n expandedCharge.livemode !== object.livemode\n )\n return disputeError('charge.livemode');\n if (!Array.isArray(object.balance_transactions))\n return disputeError('balance_transactions');\n const ids = new Set<string>();\n const balanceTransactions = object.balance_transactions.map(\n (value: unknown) => {\n const transaction = disputeRecord(value, 'balance_transaction');\n if (transaction.object !== 'balance_transaction')\n return disputeError('balance_transaction.object');\n const id = disputeId(transaction.id, 'txn');\n if (ids.has(id)) return disputeError('duplicate balance_transaction');\n ids.add(id);\n const amount = disputeInteger(\n transaction.amount,\n 'balance_transaction.amount',\n );\n const fee = disputeInteger(transaction.fee, 'balance_transaction.fee');\n const net = disputeInteger(transaction.net, 'balance_transaction.net');\n if (!Number.isSafeInteger(amount - fee) || amount - fee !== net)\n return disputeError('balance_transaction.net');\n return {\n id,\n amount,\n fee,\n net,\n currency: disputeCurrency(transaction.currency),\n createdAt: disputeDate(transaction.created),\n type: disputeString(transaction.type, 'balance_transaction.type'),\n reportingCategory:\n transaction.reporting_category === undefined\n ? undefined\n : disputeString(\n transaction.reporting_category,\n 'balance_transaction.reporting_category',\n ),\n };\n },\n );\n return {\n id,\n chargeId,\n paymentIntentId,\n amount,\n currency,\n status,\n providerStatus,\n livemode: object.livemode,\n createdAt: disputeDate(object.created),\n balanceTransactions,\n ...(account === undefined ? {} : { account }),\n raw: object,\n };\n}\n\nfunction mapStripeConnectEventDetail(\n type: string,\n object: Record<string, unknown> | undefined,\n): StripeConnectEventDetail | undefined {\n if (type === 'account.updated') {\n return {\n type,\n account: mapStripeConnectAccount(\n object,\n 'Stripe account.updated webhook object',\n ),\n };\n }\n\n if (\n type === 'application_fee.created' ||\n type === 'application_fee.refunded'\n ) {\n return { type, applicationFee: mapStripeApplicationFee(object) };\n }\n\n return undefined;\n}\n\nfunction readStripeOptionAccount(\n option: PaymentOption | undefined,\n): string | undefined {\n const value = option?.metadata?.stripeAccount;\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction normalizeOptionalStripeAccount(\n value: string | undefined,\n context: string,\n): string | undefined {\n return value === undefined\n ? undefined\n : normalizeNonEmptyString(value, context);\n}\n\nfunction normalizeApplicationFeeAmount(\n value: number | undefined,\n chargeAmount: number,\n context: string,\n): number | undefined {\n if (value === undefined) return undefined;\n\n const fee = normalizePositiveMinorUnitAmount(value, context);\n if (fee > chargeAmount) {\n throw new PaymentConfigurationError(\n `${context} must not exceed the charge amount.`,\n );\n }\n return fee;\n}\n\nfunction stripePaymentOptionKey(\n quoteId: string,\n stripeAccount: string | undefined,\n): string {\n // Platform entries retain their old quote-only keys. Connected-account ids\n // cannot contain NUL in an HTTP header, so it safely separates account scope\n // from the caller's quote id without collapsing tenant-local quote ids.\n return stripeAccount === undefined ? quoteId : `${stripeAccount}\\0${quoteId}`;\n}\n\nfunction stripeRefundReferenceParam(\n paymentReference: string,\n): Record<string, string> {\n if (paymentReference.startsWith('pi_')) {\n return Object.fromEntries([['payment_intent', paymentReference]]);\n }\n\n if (paymentReference.startsWith('ch_')) {\n return { charge: paymentReference };\n }\n\n throw new PaymentConfigurationError(\n 'Stripe refunds require a Checkout Session (cs_), payment_intent (pi_), or charge (ch_) reference.',\n );\n}\n\nfunction normalizeStripeCurrency(value: string): string {\n if (typeof value !== 'string') {\n throw new PaymentConfigurationError(\n `StripeAdapter currency must be a three-letter ISO currency code, received ${String(value)}.`,\n );\n }\n\n const normalized = value.trim().toLowerCase();\n\n if (!/^[a-z]{3}$/.test(normalized)) {\n throw new PaymentConfigurationError(\n `StripeAdapter currency must be a three-letter ISO currency code, received ${String(value)}.`,\n );\n }\n\n return normalized;\n}\n\nfunction normalizeSupportedStripeCurrencies(\n configuredCurrencies: string[] | undefined,\n defaultCurrency: string,\n): Set<string> {\n const normalized = new Set(\n (configuredCurrencies ?? ['usd', 'eur', 'gbp', 'cad']).map(\n normalizeStripeCurrency,\n ),\n );\n normalized.add(defaultCurrency);\n\n return normalized;\n}\n\nfunction normalizeStripeCheckoutExpiresAt(\n expiresAt: Date,\n now = Date.now(),\n): Date {\n if (expiresAt.getTime() <= now) {\n throw new PaymentProviderError('Stripe Checkout expiry is in the past.');\n }\n\n const min = now + STRIPE_CHECKOUT_MIN_EXPIRY_MS;\n const max = now + STRIPE_CHECKOUT_MAX_EXPIRY_MS;\n\n if (expiresAt.getTime() < min || expiresAt.getTime() > max) {\n throw new PaymentConfigurationError(\n 'Stripe Checkout expiry must be at least 30 minutes and no more than 24 hours from now.',\n );\n }\n\n return expiresAt;\n}\n\nexport function verifyStripeWebhookSignature(\n payload: string,\n signatureHeader: string,\n secret: string,\n toleranceSeconds = 300,\n): void {\n if (typeof payload !== 'string') {\n throw new PaymentProviderError('Stripe webhook payload must be a string.');\n }\n\n const normalizedSignatureHeader = normalizeNonEmptyString(\n signatureHeader,\n 'Stripe signature header',\n );\n const normalizedSecret = normalizeNonEmptyString(\n secret,\n 'Stripe webhook secret',\n );\n\n if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) {\n throw new PaymentConfigurationError(\n `Stripe webhook toleranceSeconds must be a non-negative finite number, received ${String(toleranceSeconds)}.`,\n );\n }\n\n const timestampCandidates: string[] = [];\n const signatures: string[] = [];\n\n for (const part of normalizedSignatureHeader.split(',')) {\n const [rawKey, ...rawValue] = part.split('=');\n const key = rawKey?.trim();\n const value = rawValue.join('=').trim();\n\n if (!key || !value) {\n continue;\n }\n\n if (key === 't') {\n timestampCandidates.push(value);\n }\n\n if (key === 'v1') {\n signatures.push(value);\n }\n }\n\n if (timestampCandidates.length !== 1 || signatures.length === 0) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const timestamp = timestampCandidates[0] ?? '';\n\n if (!/^\\d+$/.test(timestamp)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const timestampSeconds = Number(timestamp);\n\n if (!Number.isSafeInteger(timestampSeconds)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const nowSeconds = Date.now() / 1_000;\n const ageSeconds = nowSeconds - timestampSeconds;\n\n if (ageSeconds < -5) {\n throw new PaymentProviderError(\n 'Stripe webhook signature timestamp is in the future.',\n );\n }\n\n if (ageSeconds > toleranceSeconds) {\n throw new PaymentProviderError('Stripe webhook signature is too old.');\n }\n\n const expected = createHmac('sha256', normalizedSecret)\n .update(`${timestamp}.${payload}`)\n .digest('hex');\n const expectedBuffer = Buffer.from(expected, 'hex');\n\n for (const signature of signatures) {\n if (!/^[0-9a-f]+$/i.test(signature)) {\n throw new PaymentProviderError('Invalid Stripe signature header.');\n }\n\n const actualBuffer = Buffer.from(signature, 'hex');\n\n if (\n expectedBuffer.length === actualBuffer.length &&\n timingSafeEqual(expectedBuffer, actualBuffer)\n ) {\n return;\n }\n }\n\n throw new PaymentProviderError('Invalid Stripe webhook signature.');\n}\n\nfunction parseStripeWebhookPayload(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 Stripe 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 Stripe 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 readProviderString(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n return typeof item === 'string' ? item : undefined;\n}\n\nfunction readRequiredWebhookString(\n value: Record<string, unknown>,\n key: string,\n context: string,\n): string {\n const item = value[key];\n\n if (typeof item !== 'string') {\n throw new PaymentProviderError(`${context} must be a string.`);\n }\n\n return normalizeNonEmptyString(item, context);\n}\n\nfunction readStripeSessionQuoteId(\n session: Record<string, unknown>,\n): string | undefined {\n return normalizeOptionalWebhookString(\n readString(session, 'client_reference_id') ??\n readString(\n (session.metadata as Record<string, unknown>) ?? {},\n 'quoteId',\n ),\n );\n}\n\nfunction mapStripeStatus(\n checkoutStatus: string | undefined,\n paymentStatus: string | undefined,\n): PaymentStatus {\n if (paymentStatus === 'paid' || paymentStatus === 'no_payment_required') {\n return 'confirmed';\n }\n\n if (checkoutStatus === 'expired') {\n return 'expired';\n }\n\n if (paymentStatus === 'unpaid' || checkoutStatus === 'open') {\n return 'pending';\n }\n\n if (checkoutStatus === 'complete') {\n return 'processing';\n }\n\n return 'pending';\n}\n\nfunction mapStripeWebhookStatus(\n type: string | undefined,\n object: Record<string, unknown> | undefined,\n): PaymentStatus {\n if (type === 'checkout.session.completed') {\n return mapStripeStatus(\n readString(object, 'status'),\n readString(object, 'payment_status'),\n );\n }\n\n if (type === 'checkout.session.async_payment_succeeded') {\n return 'confirmed';\n }\n\n if (type === 'checkout.session.async_payment_failed') {\n return 'failed';\n }\n\n if (type === 'checkout.session.expired') {\n return 'expired';\n }\n\n // Manual-capture PaymentIntent lifecycle (authorize → capture / void). Only\n // treat these as terminal for intents WE created and can correlate — i.e.\n // ones carrying our `quoteId` in metadata. Checkout Sessions create their own\n // PaymentIntents (which fire these same events with no quoteId on the intent);\n // those are handled via the `checkout.session.*` events above, so here they\n // stay non-terminal (`processing`) rather than emitting a spurious,\n // uncorrelatable terminal event. Handled before the generic `failed` catch\n // below so an un-owned `payment_intent.payment_failed` isn't reclassified.\n if (\n type === 'payment_intent.succeeded' ||\n type === 'payment_intent.canceled' ||\n type === 'payment_intent.payment_failed'\n ) {\n const metadata = (object?.metadata as Record<string, unknown>) ?? {};\n // Match parseWebhookEvent's normalization so an empty/blank quoteId is\n // treated as un-owned by both — gate and reporter must agree on ownership.\n const owned =\n normalizeOptionalWebhookString(readString(metadata, 'quoteId')) !==\n undefined;\n if (owned) {\n if (type === 'payment_intent.succeeded') {\n return 'confirmed';\n }\n // A manual-capture hold Stripe released automatically (it lapsed) is\n // `expired`, distinct from a deliberate void or hard decline (`failed`);\n // the shared PaymentStatus union has no `canceled`.\n if (\n type === 'payment_intent.canceled' &&\n readString(object, 'cancellation_reason') === 'automatic'\n ) {\n return 'expired';\n }\n return 'failed';\n }\n return 'processing';\n }\n\n // Terminal failure/refund only for payment-in objects (Checkout Session,\n // PaymentIntent, Charge). Money-out / unrelated events (transfer.failed,\n // payout.failed, refund.failed, application_fee.refunded, …) also match a\n // naive substring scan — and a failed Transfer even carries our quoteId\n // (sendPayout stamps it), which would miscorrelate a payout failure as a\n // payment failure — so they must not surface as a terminal payment status.\n const isPaymentInEvent =\n type?.startsWith('checkout.session.') === true ||\n type?.startsWith('payment_intent.') === true ||\n type?.startsWith('charge.') === true;\n\n if (isPaymentInEvent && type?.includes('refunded')) {\n return 'refunded';\n }\n\n if (isPaymentInEvent && type?.includes('failed')) {\n return 'failed';\n }\n\n return 'processing';\n}\n\nfunction mapStripeRefundStatus(\n status: string | undefined,\n): RefundResult['status'] {\n switch (status) {\n case 'succeeded':\n return 'succeeded';\n case 'failed':\n case 'canceled':\n return 'failed';\n case 'requires_action':\n return 'requires_action';\n default:\n return 'submitted';\n }\n}\n\nfunction mapStripeAuthorizationStatus(\n status: string | undefined,\n): AuthorizationResult['status'] {\n switch (status) {\n case 'requires_capture':\n return 'requires_capture';\n case 'succeeded':\n return 'succeeded';\n case 'requires_action':\n return 'requires_action';\n case 'processing':\n return 'processing';\n default:\n return 'failed';\n }\n}\n\nfunction mapStripeCaptureStatus(\n status: string | undefined,\n): CaptureResult['status'] {\n switch (status) {\n case 'succeeded':\n return 'succeeded';\n // Capturing an authorized intent shouldn't re-enter authentication; treat\n // any in-flight/action state as still processing rather than a failure.\n case 'processing':\n case 'requires_action':\n return 'processing';\n default:\n return 'failed';\n }\n}\n\nfunction mapStripeVoidStatus(status: string | undefined): VoidResult['status'] {\n return status === 'canceled' ? 'canceled' : 'failed';\n}\n\nfunction readStripeResultCurrency(\n value: Record<string, unknown>,\n): string | undefined {\n const currency = readString(value, 'currency');\n\n return currency === undefined ? undefined : currency.toUpperCase();\n}\n\nfunction mapStripeSetupStatus(\n sessionStatus: string | undefined,\n setupIntentStatus: string | undefined,\n): SavedPaymentMethod['status'] {\n if (sessionStatus === 'expired') {\n return 'expired';\n }\n\n if (sessionStatus === 'complete') {\n // The method is reusable only once the SetupIntent itself has succeeded —\n // the Session can be `complete` while the intent is still `processing`\n // (async setup methods via dynamic payment methods).\n if (setupIntentStatus === 'succeeded') {\n return 'complete';\n }\n // A finished session whose SetupIntent didn't succeed is a terminal\n // failure (card declined → `requires_payment_method`, or `canceled`), so\n // callers can stop polling instead of waiting on a `pending` that will\n // never resolve. Still-in-flight states (`processing`, `requires_action`)\n // remain `pending`.\n if (\n setupIntentStatus === 'canceled' ||\n setupIntentStatus === 'requires_payment_method'\n ) {\n return 'failed';\n }\n }\n\n return 'pending';\n}\n\nfunction readObject(\n value: Record<string, unknown> | undefined,\n key: string,\n): Record<string, unknown> | undefined {\n const item = value?.[key];\n\n return item && typeof item === 'object' && !Array.isArray(item)\n ? (item as Record<string, unknown>)\n : undefined;\n}\n\nfunction extractStripeSessionId(payTo: string): string | undefined {\n if (/^cs_(test_|live_)?[A-Za-z0-9_]+$/.test(payTo)) {\n return payTo;\n }\n\n try {\n const url = new URL(payTo);\n const match = url.pathname.match(/\\/pay\\/([^/?#]+)/);\n\n const sessionId = match?.[1];\n\n return sessionId && /^cs_(test_|live_)?[A-Za-z0-9_]+$/.test(sessionId)\n ? sessionId\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction flattenStripeMetadata(\n metadata:\n | Record<string, string | number | boolean | null | undefined>\n | undefined,\n): Record<string, string | number | boolean> {\n const result: Record<string, string | number | boolean> = {};\n\n for (const [key, value] of Object.entries(metadata ?? {})) {\n if (value !== undefined && value !== null) {\n result[`metadata[${key}]`] = value;\n }\n }\n\n return result;\n}\n\nfunction readString(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[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 readSafeInteger(\n value: Record<string, unknown> | undefined,\n key: string,\n): number | undefined {\n if (!value) {\n return undefined;\n }\n\n const item = value[key];\n\n return typeof item === 'number' && Number.isSafeInteger(item) && item >= 0\n ? item\n : undefined;\n}\n"],"mappings":";;;;AAsDA,IAAa,oBAAoB;AACjC,IAAM,gCAAgC,OAAU;AAChD,IAAM,gCAAgC,OAAU,KAAK;AACrD,IAAM,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,OAAO,OAAO,IAAI;AAItB;AAEA,SAAS,gBACP,OACA,KACoB;CACpB,IAAI,CAAC,OACH;CAGF,MAAM,OAAO,MAAM;CAEnB,OAAO,OAAO,SAAS,YAAY,OAAO,cAAc,IAAI,KAAK,QAAQ,IACrE,OACA,KAAA;AACN"}
package/dist/types.d.ts CHANGED
@@ -376,6 +376,37 @@ export interface SavedPaymentMethod {
376
376
  */
377
377
  raw?: unknown;
378
378
  }
379
+ /** Evidence for a read-only reverse lookup of a hosted checkout. */
380
+ export interface PaymentCheckoutLookupInput {
381
+ /** Supply at least one payment reference; when both exist they must agree. */
382
+ paymentIntentId?: string;
383
+ chargeId?: string;
384
+ /** Required expected environment, normally from a verified provider event. */
385
+ livemode: boolean;
386
+ /** Maximum provider pages to read (1–100, default 10). */
387
+ maxPages?: number;
388
+ }
389
+ export interface PaymentCheckoutLookupContext {
390
+ backendId: string;
391
+ /** Authenticated provider account; absent means the platform account. */
392
+ accountId?: string;
393
+ livemode: boolean;
394
+ paymentIntentId?: string;
395
+ chargeId?: string;
396
+ }
397
+ /** Only `no_match` proves complete absence. All other failures must be retried or investigated. */
398
+ export type PaymentCheckoutLookupResult = PaymentCheckoutLookupContext & ({
399
+ status: 'matched';
400
+ checkoutId: string;
401
+ paymentIntentId: string;
402
+ quoteId: string;
403
+ clientReferenceId?: string;
404
+ } | {
405
+ status: 'no_match';
406
+ } | {
407
+ status: 'indeterminate';
408
+ reason: 'pagination_limit' | 'ambiguous' | 'missing_quote';
409
+ });
379
410
  export interface PaymentBackend {
380
411
  readonly capabilities: PaymentBackendCapabilities;
381
412
  createPaymentOption(input: CreatePaymentOptionInput): Promise<PaymentOption>;
@@ -411,6 +442,12 @@ export interface PaymentBackend {
411
442
  * fields (brand / last4 / expiry). Never returns raw card data.
412
443
  */
413
444
  getSetupResult?(input: GetSetupResultInput): Promise<SavedPaymentMethod>;
445
+ /**
446
+ * Resolve existing payment evidence to a hosted checkout without a local cache.
447
+ * Provider/identity failures throw; indeterminate is never proof of absence.
448
+ * Callers must bind the returned quote to their own owner/account records.
449
+ */
450
+ lookupCheckout?(input: PaymentCheckoutLookupInput): Promise<PaymentCheckoutLookupResult>;
414
451
  parseWebhookEvent?(payload: string, signature?: string): PaymentWebhookEvent;
415
452
  }
416
453
  export type PaymentBackendFactory<TOptions> = (options: TOptions) => PaymentBackend | Promise<PaymentBackend>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,sBAAsB,GAAG,SAAS,GAAG,KAAK,GAAG,MAAM,CAAC;AAEhE,MAAM,MAAM,aAAa,GACrB,SAAS,GACT,YAAY,GACZ,WAAW,GACX,QAAQ,GACR,SAAS,GACT,UAAU,GACV,iBAAiB,CAAC;AAEtB,MAAM,WAAW,0BAA0B;IACzC,eAAe,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,0BAA0B;IACzC,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,6BAA6B,CAAC,EAAE,MAAM,EAAE,CAAC;IACzC,KAAK,EAAE,MAAM,CAAC;IACd,eAAe,EAAE,sBAAsB,CAAC;IACxC,WAAW,EAAE,OAAO,CAAC;IACrB,mBAAmB,EAAE,0BAA0B,CAAC;IAChD,eAAe,EAAE,OAAO,CAAC;IACzB,eAAe,EAAE,OAAO,CAAC;IACzB,gBAAgB,EAAE,OAAO,CAAC;IAC1B;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC;;;;OAIG;IACH,2BAA2B,CAAC,EAAE,OAAO,CAAC;IACtC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC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IG;IACH,cAAc,CAAC,CACb,KAAK,EAAE,0BAA0B,GAChC,OAAO,CAAC,2BAA2B,CAAC,CAAC;IAExC,iBAAiB,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,mBAAmB,CAAC;CAC9E;AAED,MAAM,MAAM,qBAAqB,CAAC,QAAQ,IAAI,CAC5C,OAAO,EAAE,QAAQ,KACd,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/payments",
3
- "version": "0.107.0",
3
+ "version": "0.109.0",
4
4
  "description": "Payment backend abstraction with adapters for Base USDC, BTCPay Server, and Stripe",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",