@aglyn/plugins-commerce 1.15.0 → 1.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +8 -3
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  6. package/src/lib/components/console/subscription-detail-dialog.component.js +2 -2
  7. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
  8. package/src/lib/components/console/subscriptions-card.component.js +4 -2
  9. package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
  10. package/src/lib/components/product-detail.js +7 -3
  11. package/src/lib/components/product-detail.js.map +1 -1
  12. package/src/lib/components/quote-page-body.js +7 -3
  13. package/src/lib/components/quote-page-body.js.map +1 -1
  14. package/src/lib/components/related-products.js +6 -3
  15. package/src/lib/components/related-products.js.map +1 -1
  16. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  17. package/src/lib/components/storefront-payment-element.js +11 -7
  18. package/src/lib/components/storefront-payment-element.js.map +1 -1
  19. package/src/lib/model/commerce-payment-methods.d.ts +26 -39
  20. package/src/lib/model/commerce-payment-methods.js +11 -118
  21. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  22. package/src/lib/server/billing-webhook.d.ts +23 -0
  23. package/src/lib/server/billing-webhook.js +162 -30
  24. package/src/lib/server/billing-webhook.js.map +1 -1
  25. package/src/lib/server/cancel-order.js +4 -3
  26. package/src/lib/server/cancel-order.js.map +1 -1
  27. package/src/lib/server/cart-checkout.js +61 -14
  28. package/src/lib/server/cart-checkout.js.map +1 -1
  29. package/src/lib/server/catalog.js +58 -22
  30. package/src/lib/server/catalog.js.map +1 -1
  31. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  32. package/src/lib/server/checkout-session-expiry.js +19 -5
  33. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  34. package/src/lib/server/checkout-status.js +4 -3
  35. package/src/lib/server/checkout-status.js.map +1 -1
  36. package/src/lib/server/checkout.js +42 -12
  37. package/src/lib/server/checkout.js.map +1 -1
  38. package/src/lib/server/connect.js +42 -11
  39. package/src/lib/server/connect.js.map +1 -1
  40. package/src/lib/server/draft-order.js +37 -12
  41. package/src/lib/server/draft-order.js.map +1 -1
  42. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  43. package/src/lib/server/manual-tax-rate.js +10 -6
  44. package/src/lib/server/manual-tax-rate.js.map +1 -1
  45. package/src/lib/server/native-checkout.d.ts +10 -3
  46. package/src/lib/server/native-checkout.js +8 -3
  47. package/src/lib/server/native-checkout.js.map +1 -1
  48. package/src/lib/server/payment-method-domains.d.ts +50 -9
  49. package/src/lib/server/payment-method-domains.js +150 -51
  50. package/src/lib/server/payment-method-domains.js.map +1 -1
  51. package/src/lib/server/payment-methods.js +3 -2
  52. package/src/lib/server/payment-methods.js.map +1 -1
  53. package/src/lib/server/pos-order.js +5 -1
  54. package/src/lib/server/pos-order.js.map +1 -1
  55. package/src/lib/server/pos-stripe.d.ts +7 -7
  56. package/src/lib/server/pos-stripe.js +15 -13
  57. package/src/lib/server/pos-stripe.js.map +1 -1
  58. package/src/lib/server/pos-terminal.js +11 -3
  59. package/src/lib/server/pos-terminal.js.map +1 -1
  60. package/src/lib/server/quote-pay.d.ts +23 -1
  61. package/src/lib/server/quote-pay.js +112 -32
  62. package/src/lib/server/quote-pay.js.map +1 -1
  63. package/src/lib/server/quote.d.ts +2 -1
  64. package/src/lib/server/quote.js +12 -11
  65. package/src/lib/server/quote.js.map +1 -1
  66. package/src/lib/server/refund.js +13 -6
  67. package/src/lib/server/refund.js.map +1 -1
  68. package/src/lib/server/related.js +10 -3
  69. package/src/lib/server/related.js.map +1 -1
  70. package/src/lib/server/reserve.js +19 -6
  71. package/src/lib/server/reserve.js.map +1 -1
  72. package/src/lib/server/revenue-source.d.ts +6 -0
  73. package/src/lib/server/revenue-source.js +25 -9
  74. package/src/lib/server/revenue-source.js.map +1 -1
  75. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  76. package/src/lib/server/seller-stripe-account.js +99 -0
  77. package/src/lib/server/seller-stripe-account.js.map +1 -0
  78. package/src/lib/server/storefront-tax-record.js +6 -1
  79. package/src/lib/server/storefront-tax-record.js.map +1 -1
  80. package/src/lib/server/storefront-tax.d.ts +33 -2
  81. package/src/lib/server/storefront-tax.js +39 -3
  82. package/src/lib/server/storefront-tax.js.map +1 -1
  83. package/src/lib/server/stripe-refund.d.ts +15 -0
  84. package/src/lib/server/stripe-refund.js +54 -26
  85. package/src/lib/server/stripe-refund.js.map +1 -1
  86. package/src/lib/server/subscription-portal.js +8 -3
  87. package/src/lib/server/subscription-portal.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-method-domains.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type SiteReturnHost, siteOwnHosts } from '@aglyn/aglyn/app-utils/site-return-url'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\n\n/**\n * Stripe payment method domains for storefronts (AGL-3629).\n *\n * The in-page checkout mounts Stripe's Payment Element on the merchant's own\n * domain, and Stripe shows Apple Pay there only on a REGISTERED domain (Google\n * Pay, Link, Amazon Pay and Klarna's express button use the same registration).\n * Nothing registered one, so a shopper on `shop.example.com` with a card in\n * Apple Wallet never saw the button.\n *\n * ## Which account the domain is registered on\n *\n * Stripe's rule: \"The domain where the charge is being run needs to be\n * registered for the user running the charge.\" Storefront charges are\n * DESTINATION charges created by the platform with no `Stripe-Account` header\n * and no `on_behalf_of`, so the platform runs them and the platform's key\n * registers the domain, with no `Stripe-Account` header. A direct-charge flow\n * would register on the connected account instead; there is none today, and\n * `registerOnPlatform` is named for that reason.\n *\n * ## When\n *\n * - On connect: core raises `host.domain.attached`, and commerce registers\n * the custom domain and its `www.` twin.\n * - On first checkout: the session handlers call `ensureCheckoutDomain` for\n * the page the shopper is on, which covers every `{site}.aglyn.app`\n * subdomain without registering thousands of sites that never sell.\n * - Daily: `reconcileCustomDomains` registers any connected custom domain the\n * first two missed (domains connected before AGL-3629 included) — the\n * backfill is a job rather than a one-off script, so it also repairs a\n * missed event later.\n * - On release: `host.domain.released` DISABLES the domain. Stripe has no\n * delete; a disabled domain stops showing the methods and can be enabled\n * again if the name comes back.\n *\n * ## The cache\n *\n * `paymentMethodDomains/{mode}~{domain}` records what Stripe last said, so a\n * checkout costs one document read rather than a Stripe round trip. The mode is\n * in the id because a test key and a live key register in different worlds and\n * a domain registered in one is not registered in the other. Server-only: the\n * rules deny every client.\n */\n\nexport const PAYMENT_METHOD_DOMAINS_COLLECTION = 'paymentMethodDomains'\n\n/** How long a recorded registration is trusted before Stripe is asked again. */\nexport const PAYMENT_METHOD_DOMAIN_RECHECK_MS = 7 * 24 * 60 * 60 * 1000\n\n/** The most a checkout waits on Stripe before selling without the domain. */\nexport const CHECKOUT_DOMAIN_BUDGET_MS = 2500\n\nexport type StripeMode = 'live' | 'test'\n\n/** Stripe's per-method verdict on a domain. */\nexport interface PaymentMethodDomainStatus {\n applePay: string | null\n googlePay: string | null\n link: string | null\n amazonPay: string | null\n klarna: string | null\n}\n\nexport interface PaymentMethodDomainRecord {\n domain: string\n mode: StripeMode\n stripeId: string | null\n enabled: boolean\n status: PaymentMethodDomainStatus\n hostId: string | null\n checkedAtMs: number\n lastError: string | null\n}\n\ninterface StripeDomainObject {\n id: string\n domain_name: string\n enabled: boolean\n apple_pay?: { status?: string }\n google_pay?: { status?: string }\n link?: { status?: string }\n amazon_pay?: { status?: string }\n klarna?: { status?: string }\n}\n\n/** Which Stripe world the platform key is in, from its prefix. */\nexport function stripeModeOfKey(key: string | undefined): StripeMode | null {\n const value = String(key ?? '')\n if (/^(sk|rk)_live_/.test(value)) return 'live'\n if (/^(sk|rk)_test_/.test(value)) return 'test'\n return null\n}\n\n/**\n * A hostname Stripe can register: lowercased, no trailing dot, at least two\n * labels, and never a local or IP host — a checkout opened on `localhost`\n * must not try to register it.\n */\nexport function registrableDomain(input: unknown): string | null {\n const value = String(input ?? '')\n .trim()\n .toLowerCase()\n .replace(/\\.+$/, '')\n if (!value || value.length > 253) return null\n if (value === 'localhost' || value.endsWith('.localhost')) return null\n if (/^[0-9.]+$/.test(value) || value.includes(':')) return null\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(value)) return null\n return value\n}\n\n/** The cache document id for a domain in a mode. */\nexport function paymentMethodDomainDocId(mode: StripeMode, domain: string): string {\n return `${mode}~${domain}`\n}\n\n/**\n * The domains a site's custom domain needs: the domain and its `www.` twin,\n * since the platform answers on both (`siteOwnHosts`).\n */\nexport function customDomainNames(cname: unknown): string[] {\n const domain = registrableDomain(cname)\n if (!domain) return []\n const twin = domain.startsWith('www.') ? domain.slice(4) : `www.${domain}`\n return [domain, ...(registrableDomain(twin) ? [twin] : [])]\n}\n\nfunction statusOf(object: StripeDomainObject): PaymentMethodDomainStatus {\n return {\n applePay: object.apple_pay?.status ?? null,\n googlePay: object.google_pay?.status ?? null,\n link: object.link?.status ?? null,\n amazonPay: object.amazon_pay?.status ?? null,\n klarna: object.klarna?.status ?? null,\n }\n}\n\nasync function stripeRequest<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: Record<string, string>,\n options: { idempotencyKey?: string; signal?: AbortSignal } = {},\n): Promise<T> {\n const query = method === 'GET' && params ? `?${new URLSearchParams(params)}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n // The platform's own key and NO `Stripe-Account`: destination charges\n // are run by the platform, so the platform holds the registration.\n ...(options.idempotencyKey && { 'Idempotency-Key': options.idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: new URLSearchParams(params).toString() }),\n ...(options.signal && { signal: options.signal }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\nasync function findOnStripe(\n domain: string,\n signal?: AbortSignal,\n): Promise<StripeDomainObject | null> {\n const list = await stripeRequest<{ data?: StripeDomainObject[] }>(\n 'GET',\n 'payment_method_domains',\n { domain_name: domain, limit: '1' },\n { signal },\n )\n return list.data?.find((entry) => entry.domain_name === domain) ?? null\n}\n\n/**\n * Register (or re-enable) one domain on the platform account. Idempotent end\n * to end: an existing registration is found first and reused, a disabled one\n * is enabled rather than duplicated, and the create carries an idempotency key\n * so two checkouts racing on a fresh subdomain open one registration.\n */\nexport async function registerOnPlatform(\n domain: string,\n signal?: AbortSignal,\n): Promise<StripeDomainObject> {\n const existing = await findOnStripe(domain, signal)\n if (existing) {\n if (existing.enabled) return existing\n return stripeRequest<StripeDomainObject>(\n 'POST',\n `payment_method_domains/${encodeURIComponent(existing.id)}`,\n { enabled: 'true' },\n { signal },\n )\n }\n try {\n return await stripeRequest<StripeDomainObject>(\n 'POST',\n 'payment_method_domains',\n { domain_name: domain, enabled: 'true' },\n { idempotencyKey: `aglyn-pmd-register:${domain}`, signal },\n )\n } catch (error) {\n // Lost a race to a create that landed between the lookup and this call:\n // the registration exists, which is what was wanted.\n const raced = await findOnStripe(domain, signal).catch(() => null)\n if (raced) return raced\n throw error\n }\n}\n\nfunction docRef(mode: StripeMode, domain: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection(PAYMENT_METHOD_DOMAINS_COLLECTION)\n .doc(paymentMethodDomainDocId(mode, domain))\n}\n\nasync function record(\n mode: StripeMode,\n domain: string,\n patch: Partial<PaymentMethodDomainRecord>,\n): Promise<void> {\n await docRef(mode, domain).set(\n { domain, mode, checkedAtMs: Date.now(), ...patch },\n { merge: true },\n )\n}\n\nexport interface EnsureDomainResult {\n domain: string\n outcome: 'registered' | 'cached' | 'skipped' | 'failed'\n record?: PaymentMethodDomainRecord\n error?: string\n}\n\n/**\n * Make sure one domain is registered and enabled, reading the cache first.\n *\n * Never throws: every caller is on its way to something more important (a\n * sale, a domain connect), and a domain Stripe would not take today is\n * recorded with its error and retried by the daily reconcile.\n */\nexport async function ensurePaymentMethodDomain(\n rawDomain: string,\n options: { hostId?: string | null; signal?: AbortSignal; force?: boolean } = {},\n): Promise<EnsureDomainResult> {\n const domain = registrableDomain(rawDomain)\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!domain || !mode) {\n return { domain: String(rawDomain ?? ''), outcome: 'skipped' }\n }\n try {\n if (!options.force) {\n const cached = await docRef(mode, domain).get()\n const data = cached.data?.() as PaymentMethodDomainRecord | undefined\n if (\n cached.exists &&\n data?.enabled === true &&\n data.stripeId &&\n Date.now() - Number(data.checkedAtMs ?? 0) < PAYMENT_METHOD_DOMAIN_RECHECK_MS\n ) {\n return { domain, outcome: 'cached', record: data }\n }\n }\n const object = await registerOnPlatform(domain, options.signal)\n const next: PaymentMethodDomainRecord = {\n domain,\n mode,\n stripeId: object.id,\n enabled: object.enabled !== false,\n status: statusOf(object),\n hostId: options.hostId ?? null,\n checkedAtMs: Date.now(),\n lastError: null,\n }\n await record(mode, domain, next)\n return { domain, outcome: 'registered', record: next }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n await record(mode, domain, {\n enabled: false,\n hostId: options.hostId ?? null,\n lastError: message.slice(0, 500),\n }).catch(() => undefined)\n return { domain, outcome: 'failed', error: message }\n }\n}\n\n/**\n * Disable a domain the platform no longer serves for a site. Stripe has no\n * delete for a payment method domain; disabling stops every method on it, and\n * `ensurePaymentMethodDomain` re-enables the same registration if the name is\n * connected again.\n */\nexport async function disablePaymentMethodDomain(\n rawDomain: string,\n): Promise<{ domain: string; outcome: 'disabled' | 'absent' | 'skipped' | 'failed'; error?: string }> {\n const domain = registrableDomain(rawDomain)\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!domain || !mode) return { domain: String(rawDomain ?? ''), outcome: 'skipped' }\n try {\n const existing = await findOnStripe(domain)\n if (!existing) {\n await record(mode, domain, { enabled: false, stripeId: null, lastError: null })\n return { domain, outcome: 'absent' }\n }\n const object = existing.enabled\n ? await stripeRequest<StripeDomainObject>(\n 'POST',\n `payment_method_domains/${encodeURIComponent(existing.id)}`,\n { enabled: 'false' },\n )\n : existing\n await record(mode, domain, {\n stripeId: object.id,\n enabled: false,\n status: statusOf(object),\n lastError: null,\n })\n return { domain, outcome: 'disabled' }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return { domain, outcome: 'failed', error: message }\n }\n}\n\n/**\n * Is a name still served for some OTHER site? A custom domain's `www.` twin\n * can be another site's own `cname`, and an aglyn subdomain released by a\n * deleted site can already belong to a new one. Disabling either would take\n * Apple Pay away from a store that did nothing.\n */\nexport async function domainStillClaimed(domain: string, exceptHostId: string): Promise<boolean> {\n const firestore = firebaseAdmin.app().firestore()\n const hosts = firestore.collection('hosts')\n const names = customDomainNames(domain)\n const byCname = await hosts\n .where('cname', 'in', names.length ? names : [domain])\n .limit(3)\n .get()\n if (byCname.docs.some((doc) => doc.id !== exceptHostId)) return true\n const suffix = `.${TENANT_APEX}`\n if (domain.endsWith(suffix)) {\n const subdomain = domain.slice(0, -suffix.length)\n const bySubdomain = await hosts.where('subdomain', '==', subdomain).limit(3).get()\n if (bySubdomain.docs.some((doc) => doc.id !== exceptHostId)) return true\n }\n return false\n}\n\n/**\n * The checkout's hook: register the domain the shopper is paying on, within a\n * budget, before the client secret goes back to the browser. Only a name the\n * SITE answers on is ever registered — the return URL has already been judged\n * against `siteOwnHosts` by `siteReturnUrl`, and it is judged again here so a\n * forged `Host` can never make the platform register a stranger's domain.\n */\nexport async function ensureCheckoutDomain(input: {\n pageUrl: string\n site: SiteReturnHost | null | undefined\n hostId: string\n budgetMs?: number\n}): Promise<EnsureDomainResult | null> {\n let hostname: string\n try {\n hostname = new URL(input.pageUrl).hostname.toLowerCase()\n } catch {\n return null\n }\n if (!siteOwnHosts(input.site).includes(hostname)) return null\n if (!registrableDomain(hostname)) return null\n const controller = new AbortController()\n const budget = input.budgetMs ?? CHECKOUT_DOMAIN_BUDGET_MS\n const timer = setTimeout(() => controller.abort(), budget)\n try {\n return await ensurePaymentMethodDomain(hostname, {\n hostId: input.hostId,\n signal: controller.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** One page of the daily reconcile. */\nexport const RECONCILE_PAGE_SIZE = 200\n\n/**\n * The backfill and the safety net in one pass: every site with a connected\n * custom domain gets its domain and `www.` twin registered. A cached, enabled\n * registration costs one read and no Stripe call, so the steady state is cheap;\n * a domain connected before AGL-3629, or whose connect event was lost, is\n * registered on the first pass after it.\n *\n * Paged by `cname` with a cursor so it reads every site once and stops; the\n * `cname > ''` range uses Firestore's automatic single-field index.\n */\nexport async function reconcileCustomDomains(\n gate: { isLocked(hostId: string): Promise<boolean> },\n options: { maxPages?: number } = {},\n): Promise<{ hosts: number; registered: number; failed: number; skippedLocked: number }> {\n const result = { hosts: 0, registered: 0, failed: 0, skippedLocked: 0 }\n if (!stripeModeOfKey(process.env.STRIPE_SECRET_KEY)) return result\n const firestore = firebaseAdmin.app().firestore()\n let cursor: string | null = null\n const maxPages = options.maxPages ?? 50\n for (let page = 0; page < maxPages; page += 1) {\n let query = firestore\n .collection('hosts')\n .where('cname', '>', '')\n .orderBy('cname')\n .limit(RECONCILE_PAGE_SIZE)\n if (cursor) query = query.startAfter(cursor)\n const snapshot = await query.get()\n if (snapshot.empty) break\n for (const hostDoc of snapshot.docs) {\n result.hosts += 1\n // Skipped, not dropped: a locked site is left as it is and picked up on\n // the first pass after the lift.\n if (await gate.isLocked(hostDoc.id)) {\n result.skippedLocked += 1\n continue\n }\n for (const domain of customDomainNames(hostDoc.get('cname'))) {\n const outcome = await ensurePaymentMethodDomain(domain, { hostId: hostDoc.id })\n if (outcome.outcome === 'registered') result.registered += 1\n if (outcome.outcome === 'failed') result.failed += 1\n }\n }\n cursor = String(snapshot.docs[snapshot.docs.length - 1]?.get('cname') ?? '')\n if (snapshot.size < RECONCILE_PAGE_SIZE || !cursor) break\n }\n return result\n}\n\n/** Core's `host.domain.attached`: register the custom domain and its twin. */\nexport async function onHostDomainAttached(payload: {\n hostId: string\n domain: string\n}): Promise<void> {\n for (const domain of customDomainNames(payload.domain)) {\n const outcome = await ensurePaymentMethodDomain(domain, {\n hostId: payload.hostId,\n force: true,\n })\n if (outcome.outcome === 'failed') {\n console.warn(`[commerce] payment method domain ${domain} not registered: ${outcome.error}`)\n }\n }\n}\n\n/** Core's `host.domain.released`: disable what no other site still serves. */\nexport async function onHostDomainReleased(payload: {\n hostId: string\n domain: string\n}): Promise<void> {\n const names = payload.domain.endsWith(`.${TENANT_APEX}`)\n ? [registrableDomain(payload.domain)].filter((name): name is string => Boolean(name))\n : customDomainNames(payload.domain)\n for (const domain of names) {\n if (await domainStillClaimed(domain, payload.hostId)) continue\n const outcome = await disablePaymentMethodDomain(domain)\n if (outcome.outcome === 'failed') {\n console.warn(`[commerce] payment method domain ${domain} not disabled: ${outcome.error}`)\n }\n }\n}\n\n/** The registrations a settings card shows for one site. */\nexport async function readSiteDomainRecords(\n site: SiteReturnHost | null | undefined,\n): Promise<PaymentMethodDomainRecord[]> {\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!mode) return []\n const names = siteOwnHosts(site).filter((name) => registrableDomain(name))\n const snapshots = await Promise.all(names.map((name) => docRef(mode, name).get()))\n return snapshots.map((snapshot, index) => {\n const data = (snapshot.exists ? snapshot.data?.() : null) as PaymentMethodDomainRecord | null\n return (\n data ?? {\n domain: names[index],\n mode,\n stripeId: null,\n enabled: false,\n status: { applePay: null, googlePay: null, link: null, amazonPay: null, klarna: null },\n hostId: null,\n checkedAtMs: 0,\n lastError: null,\n }\n )\n })\n}\n"],"names":["siteOwnHosts","TENANT_APEX","firebaseAdmin","PAYMENT_METHOD_DOMAINS_COLLECTION","PAYMENT_METHOD_DOMAIN_RECHECK_MS","CHECKOUT_DOMAIN_BUDGET_MS","stripeModeOfKey","key","value","String","test","registrableDomain","input","trim","toLowerCase","replace","length","endsWith","includes","paymentMethodDomainDocId","mode","domain","customDomainNames","cname","twin","startsWith","slice","statusOf","object","applePay","apple_pay","status","googlePay","google_pay","link","amazonPay","amazon_pay","klarna","stripeRequest","method","path","params","options","query","URLSearchParams","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","idempotencyKey","body","toString","signal","payload","json","catch","ok","Error","error","message","findOnStripe","list","domain_name","limit","data","find","entry","registerOnPlatform","existing","enabled","encodeURIComponent","id","raced","docRef","app","firestore","collection","doc","record","patch","set","checkedAtMs","Date","now","merge","ensurePaymentMethodDomain","rawDomain","outcome","force","cached","get","exists","stripeId","Number","next","hostId","lastError","undefined","disablePaymentMethodDomain","domainStillClaimed","exceptHostId","hosts","names","byCname","where","docs","some","suffix","subdomain","bySubdomain","ensureCheckoutDomain","hostname","URL","pageUrl","site","controller","AbortController","budget","budgetMs","timer","setTimeout","abort","clearTimeout","RECONCILE_PAGE_SIZE","reconcileCustomDomains","gate","result","registered","failed","skippedLocked","cursor","maxPages","page","snapshot","orderBy","startAfter","empty","hostDoc","isLocked","size","onHostDomainAttached","console","warn","onHostDomainReleased","filter","name","Boolean","readSiteDomainRecords","snapshots","Promise","all","map","index"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAA8BA,YAAY,QAAQ,yCAAwC;AAC1F,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AM,GAAG;QACtD,MAAMR,UAAU,MAAMW,2BAA2BhF;QACjD,IAAIqE,QAAQA,OAAO,KAAK,UAAU;YAChCsD,QAAQC,IAAI,CAAC,CAAC,iCAAiC,EAAE5H,OAAO,eAAe,EAAEqE,QAAQ7B,KAAK,EAAE;QAC1F;IACF;AACF;AAEA,0DAA0D,GAC1D,OAAO,eAAeyF,sBACpBjC,IAAuC;IAEvC,MAAMjG,OAAOd,gBAAgB2C,QAAQC,GAAG,CAACC,iBAAiB;IAC1D,IAAI,CAAC/B,MAAM,OAAO,EAAE;IACpB,MAAMqF,QAAQzG,aAAaqH,MAAM8B,MAAM,CAAC,CAACC,OAASzI,kBAAkByI;IACpE,MAAMG,YAAY,MAAMC,QAAQC,GAAG,CAAChD,MAAMiD,GAAG,CAAC,CAACN,OAASxE,OAAOxD,MAAMgI,MAAMvD,GAAG;IAC9E,OAAO0D,UAAUG,GAAG,CAAC,CAAClB,UAAUmB;QAC9B,MAAMxF,OAAQqE,SAAS1C,MAAM,GAAG0C,SAASrE,IAAI,oBAAbqE,SAASrE,IAAI,MAAbqE,YAAoB;QACpD,OACErE,eAAAA,OAAQ;YACN9C,QAAQoF,KAAK,CAACkD,MAAM;YACpBvI;YACA2E,UAAU;YACVvB,SAAS;YACTzC,QAAQ;gBAAEF,UAAU;gBAAMG,WAAW;gBAAME,MAAM;gBAAMC,WAAW;gBAAME,QAAQ;YAAK;YACrF6D,QAAQ;YACRd,aAAa;YACbe,WAAW;QACb;IAEJ;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-method-domains.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type SiteReturnHost, siteOwnHosts } from '@aglyn/aglyn/app-utils/site-return-url'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { directSellerAccountForHost } from './seller-stripe-account'\n\n/**\n * Stripe payment method domains for storefronts (AGL-3629).\n *\n * The in-page checkout mounts Stripe's Payment Element on the merchant's own\n * domain, and Stripe shows Apple Pay there only on a REGISTERED domain (Google\n * Pay, Link, Amazon Pay and Klarna's express button use the same registration).\n * Nothing registered one, so a shopper on `shop.example.com` with a card in\n * Apple Wallet never saw the button.\n *\n * ## Which account the domain is registered on\n *\n * Stripe's rule: \"The domain where the charge is being run needs to be\n * registered for the user running the charge.\" Storefront charges are\n * DESTINATION charges created by the platform with no `Stripe-Account` header\n * and no `on_behalf_of`, so the platform runs them and the platform's key\n * registers the domain, with no `Stripe-Account` header.\n *\n * A DIRECT-charge seller runs its own charges: the session is created on the\n * seller's connected account, so Apple Pay and Google Pay show only on a\n * domain registered ON THAT ACCOUNT (`Stripe-Account` header). Every entry\n * point below takes the seller's account for that case, and the platform's\n * registration is left as it is, because the seller's hardware purchases and\n * any sale from before the switch still run on the platform.\n *\n * ## When\n *\n * - On connect: core raises `host.domain.attached`, and commerce registers\n * the custom domain and its `www.` twin.\n * - On first checkout: the session handlers call `ensureCheckoutDomain` for\n * the page the shopper is on, which covers every `{site}.aglyn.app`\n * subdomain without registering thousands of sites that never sell.\n * - Daily: `reconcileCustomDomains` registers any connected custom domain the\n * first two missed (domains connected before AGL-3629 included) — the\n * backfill is a job rather than a one-off script, so it also repairs a\n * missed event later.\n * - On release: `host.domain.released` DISABLES the domain. Stripe has no\n * delete; a disabled domain stops showing the methods and can be enabled\n * again if the name comes back.\n *\n * ## The cache\n *\n * `paymentMethodDomains/{mode}~{domain}` records what Stripe last said, so a\n * checkout costs one document read rather than a Stripe round trip. The mode is\n * in the id because a test key and a live key register in different worlds and\n * a domain registered in one is not registered in the other. A seller's\n * registration is cached under its own id, `{mode}~{account}~{domain}`,\n * because it is a different Stripe object from the platform's for the same\n * name. Server-only: the rules deny every client.\n */\n\nexport const PAYMENT_METHOD_DOMAINS_COLLECTION = 'paymentMethodDomains'\n\n/** How long a recorded registration is trusted before Stripe is asked again. */\nexport const PAYMENT_METHOD_DOMAIN_RECHECK_MS = 7 * 24 * 60 * 60 * 1000\n\n/** The most a checkout waits on Stripe before selling without the domain. */\nexport const CHECKOUT_DOMAIN_BUDGET_MS = 2500\n\nexport type StripeMode = 'live' | 'test'\n\n/** Stripe's per-method verdict on a domain. */\nexport interface PaymentMethodDomainStatus {\n applePay: string | null\n googlePay: string | null\n link: string | null\n amazonPay: string | null\n klarna: string | null\n}\n\nexport interface PaymentMethodDomainRecord {\n domain: string\n mode: StripeMode\n /**\n * The connected account the domain is registered on, for a direct-charge\n * seller; absent or null for the platform's own registration.\n */\n stripeAccount?: string | null\n stripeId: string | null\n enabled: boolean\n status: PaymentMethodDomainStatus\n hostId: string | null\n checkedAtMs: number\n lastError: string | null\n}\n\ninterface StripeDomainObject {\n id: string\n domain_name: string\n enabled: boolean\n apple_pay?: { status?: string }\n google_pay?: { status?: string }\n link?: { status?: string }\n amazon_pay?: { status?: string }\n klarna?: { status?: string }\n}\n\n/** Which Stripe world the platform key is in, from its prefix. */\nexport function stripeModeOfKey(key: string | undefined): StripeMode | null {\n const value = String(key ?? '')\n if (/^(sk|rk)_live_/.test(value)) return 'live'\n if (/^(sk|rk)_test_/.test(value)) return 'test'\n return null\n}\n\n/**\n * A hostname Stripe can register: lowercased, no trailing dot, at least two\n * labels, and never a local or IP host — a checkout opened on `localhost`\n * must not try to register it.\n */\nexport function registrableDomain(input: unknown): string | null {\n const value = String(input ?? '')\n .trim()\n .toLowerCase()\n .replace(/\\.+$/, '')\n if (!value || value.length > 253) return null\n if (value === 'localhost' || value.endsWith('.localhost')) return null\n if (/^[0-9.]+$/.test(value) || value.includes(':')) return null\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(value)) return null\n return value\n}\n\n/**\n * The cache document id for a domain in a mode, on the platform or on one\n * seller's connected account.\n */\nexport function paymentMethodDomainDocId(\n mode: StripeMode,\n domain: string,\n stripeAccount?: string | null,\n): string {\n const account = accountOrNull(stripeAccount)\n return account ? `${mode}~${account}~${domain}` : `${mode}~${domain}`\n}\n\n/** A usable connected-account id, or null for \"the platform\". */\nfunction accountOrNull(value: unknown): string | null {\n const id = typeof value === 'string' ? value.trim() : ''\n return /^acct_[A-Za-z0-9]+$/.test(id) ? id : null\n}\n\n/**\n * The domains a site's custom domain needs: the domain and its `www.` twin,\n * since the platform answers on both (`siteOwnHosts`).\n */\nexport function customDomainNames(cname: unknown): string[] {\n const domain = registrableDomain(cname)\n if (!domain) return []\n const twin = domain.startsWith('www.') ? domain.slice(4) : `www.${domain}`\n return [domain, ...(registrableDomain(twin) ? [twin] : [])]\n}\n\nfunction statusOf(object: StripeDomainObject): PaymentMethodDomainStatus {\n return {\n applePay: object.apple_pay?.status ?? null,\n googlePay: object.google_pay?.status ?? null,\n link: object.link?.status ?? null,\n amazonPay: object.amazon_pay?.status ?? null,\n klarna: object.klarna?.status ?? null,\n }\n}\n\nasync function stripeRequest<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: Record<string, string>,\n options: {\n idempotencyKey?: string\n signal?: AbortSignal\n stripeAccount?: string | null\n } = {},\n): Promise<T> {\n const query = method === 'GET' && params ? `?${new URLSearchParams(params)}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n // The platform's own key and NO `Stripe-Account` for the platform's\n // registration (destination charges are run by the platform); the\n // seller's account for a direct-charge seller, who runs its own.\n ...(options.stripeAccount && { 'Stripe-Account': options.stripeAccount }),\n ...(options.idempotencyKey && { 'Idempotency-Key': options.idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: new URLSearchParams(params).toString() }),\n ...(options.signal && { signal: options.signal }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\nasync function findOnStripe(\n domain: string,\n signal?: AbortSignal,\n stripeAccount?: string | null,\n): Promise<StripeDomainObject | null> {\n const list = await stripeRequest<{ data?: StripeDomainObject[] }>(\n 'GET',\n 'payment_method_domains',\n { domain_name: domain, limit: '1' },\n { signal, stripeAccount },\n )\n return list.data?.find((entry) => entry.domain_name === domain) ?? null\n}\n\n/**\n * Register (or re-enable) one domain on the platform account. Idempotent end\n * to end: an existing registration is found first and reused, a disabled one\n * is enabled rather than duplicated, and the create carries an idempotency key\n * so two checkouts racing on a fresh subdomain open one registration.\n */\nexport async function registerOnPlatform(\n domain: string,\n signal?: AbortSignal,\n): Promise<StripeDomainObject> {\n return registerDomain(domain, { signal })\n}\n\n/**\n * Register (or re-enable) one domain on a direct-charge seller's connected\n * account: the same steps as {@link registerOnPlatform}, each sent with the\n * seller's `Stripe-Account`.\n */\nexport async function registerOnAccount(\n domain: string,\n stripeAccount: string,\n signal?: AbortSignal,\n): Promise<StripeDomainObject> {\n return registerDomain(domain, { signal, stripeAccount })\n}\n\nasync function registerDomain(\n domain: string,\n options: { signal?: AbortSignal; stripeAccount?: string | null },\n): Promise<StripeDomainObject> {\n const { signal } = options\n const stripeAccount = accountOrNull(options.stripeAccount)\n const existing = await findOnStripe(domain, signal, stripeAccount)\n if (existing) {\n if (existing.enabled) return existing\n return stripeRequest<StripeDomainObject>(\n 'POST',\n `payment_method_domains/${encodeURIComponent(existing.id)}`,\n { enabled: 'true' },\n { signal, stripeAccount },\n )\n }\n try {\n return await stripeRequest<StripeDomainObject>(\n 'POST',\n 'payment_method_domains',\n { domain_name: domain, enabled: 'true' },\n {\n // Stripe scopes the key per account; the account is in it anyway so\n // a log line names which registration it was.\n idempotencyKey: stripeAccount\n ? `aglyn-pmd-register:${stripeAccount}:${domain}`\n : `aglyn-pmd-register:${domain}`,\n signal,\n stripeAccount,\n },\n )\n } catch (error) {\n // Lost a race to a create that landed between the lookup and this call:\n // the registration exists, which is what was wanted.\n const raced = await findOnStripe(domain, signal, stripeAccount).catch(() => null)\n if (raced) return raced\n throw error\n }\n}\n\nfunction docRef(mode: StripeMode, domain: string, stripeAccount?: string | null) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection(PAYMENT_METHOD_DOMAINS_COLLECTION)\n .doc(paymentMethodDomainDocId(mode, domain, stripeAccount))\n}\n\nasync function record(\n mode: StripeMode,\n domain: string,\n patch: Partial<PaymentMethodDomainRecord>,\n stripeAccount?: string | null,\n): Promise<void> {\n const account = accountOrNull(stripeAccount)\n await docRef(mode, domain, account).set(\n {\n domain,\n mode,\n // Only a seller's registration names an account, so the platform's\n // documents are written exactly as before.\n ...(account ? { stripeAccount: account } : {}),\n checkedAtMs: Date.now(),\n ...patch,\n },\n { merge: true },\n )\n}\n\nexport interface EnsureDomainResult {\n domain: string\n outcome: 'registered' | 'cached' | 'skipped' | 'failed'\n record?: PaymentMethodDomainRecord\n error?: string\n}\n\n/**\n * Make sure one domain is registered and enabled, reading the cache first.\n *\n * Never throws: every caller is on its way to something more important (a\n * sale, a domain connect), and a domain Stripe would not take today is\n * recorded with its error and retried by the daily reconcile.\n */\nexport async function ensurePaymentMethodDomain(\n rawDomain: string,\n options: {\n hostId?: string | null\n signal?: AbortSignal\n force?: boolean\n /** Register on this direct-charge seller's account, not the platform. */\n stripeAccount?: string | null\n } = {},\n): Promise<EnsureDomainResult> {\n const domain = registrableDomain(rawDomain)\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!domain || !mode) {\n return { domain: String(rawDomain ?? ''), outcome: 'skipped' }\n }\n const account = accountOrNull(options.stripeAccount)\n try {\n if (!options.force) {\n const cached = await docRef(mode, domain, account).get()\n const data = cached.data?.() as PaymentMethodDomainRecord | undefined\n if (\n cached.exists &&\n data?.enabled === true &&\n data.stripeId &&\n Date.now() - Number(data.checkedAtMs ?? 0) < PAYMENT_METHOD_DOMAIN_RECHECK_MS\n ) {\n return { domain, outcome: 'cached', record: data }\n }\n }\n const object = account\n ? await registerOnAccount(domain, account, options.signal)\n : await registerOnPlatform(domain, options.signal)\n const next: PaymentMethodDomainRecord = {\n domain,\n mode,\n ...(account ? { stripeAccount: account } : {}),\n stripeId: object.id,\n enabled: object.enabled !== false,\n status: statusOf(object),\n hostId: options.hostId ?? null,\n checkedAtMs: Date.now(),\n lastError: null,\n }\n await record(mode, domain, next, account)\n return { domain, outcome: 'registered', record: next }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n await record(\n mode,\n domain,\n {\n enabled: false,\n hostId: options.hostId ?? null,\n lastError: message.slice(0, 500),\n },\n account,\n ).catch(() => undefined)\n return { domain, outcome: 'failed', error: message }\n }\n}\n\n/**\n * Disable a domain the platform no longer serves for a site. Stripe has no\n * delete for a payment method domain; disabling stops every method on it, and\n * `ensurePaymentMethodDomain` re-enables the same registration if the name is\n * connected again.\n */\nexport async function disablePaymentMethodDomain(\n rawDomain: string,\n options: { stripeAccount?: string | null } = {},\n): Promise<{ domain: string; outcome: 'disabled' | 'absent' | 'skipped' | 'failed'; error?: string }> {\n const domain = registrableDomain(rawDomain)\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!domain || !mode) return { domain: String(rawDomain ?? ''), outcome: 'skipped' }\n const account = accountOrNull(options.stripeAccount)\n try {\n const existing = await findOnStripe(domain, undefined, account)\n if (!existing) {\n await record(mode, domain, { enabled: false, stripeId: null, lastError: null }, account)\n return { domain, outcome: 'absent' }\n }\n const object = existing.enabled\n ? await stripeRequest<StripeDomainObject>(\n 'POST',\n `payment_method_domains/${encodeURIComponent(existing.id)}`,\n { enabled: 'false' },\n { stripeAccount: account },\n )\n : existing\n await record(\n mode,\n domain,\n {\n stripeId: object.id,\n enabled: false,\n status: statusOf(object),\n lastError: null,\n },\n account,\n )\n return { domain, outcome: 'disabled' }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return { domain, outcome: 'failed', error: message }\n }\n}\n\n/**\n * Is a name still served for some OTHER site? A custom domain's `www.` twin\n * can be another site's own `cname`, and an aglyn subdomain released by a\n * deleted site can already belong to a new one. Disabling either would take\n * Apple Pay away from a store that did nothing.\n */\nexport async function domainStillClaimed(domain: string, exceptHostId: string): Promise<boolean> {\n const firestore = firebaseAdmin.app().firestore()\n const hosts = firestore.collection('hosts')\n const names = customDomainNames(domain)\n const byCname = await hosts\n .where('cname', 'in', names.length ? names : [domain])\n .limit(3)\n .get()\n if (byCname.docs.some((doc) => doc.id !== exceptHostId)) return true\n const suffix = `.${TENANT_APEX}`\n if (domain.endsWith(suffix)) {\n const subdomain = domain.slice(0, -suffix.length)\n const bySubdomain = await hosts.where('subdomain', '==', subdomain).limit(3).get()\n if (bySubdomain.docs.some((doc) => doc.id !== exceptHostId)) return true\n }\n return false\n}\n\n/**\n * The checkout's hook: register the domain the shopper is paying on, within a\n * budget, before the client secret goes back to the browser. Only a name the\n * SITE answers on is ever registered — the return URL has already been judged\n * against `siteOwnHosts` by `siteReturnUrl`, and it is judged again here so a\n * forged `Host` can never make the platform register a stranger's domain.\n */\nexport async function ensureCheckoutDomain(input: {\n pageUrl: string\n site: SiteReturnHost | null | undefined\n hostId: string\n budgetMs?: number\n /**\n * The seller's connected account when this checkout is a DIRECT charge:\n * the session runs there, so the domain must be registered there.\n */\n stripeAccount?: string\n}): Promise<EnsureDomainResult | null> {\n let hostname: string\n try {\n hostname = new URL(input.pageUrl).hostname.toLowerCase()\n } catch {\n return null\n }\n if (!siteOwnHosts(input.site).includes(hostname)) return null\n if (!registrableDomain(hostname)) return null\n const controller = new AbortController()\n const budget = input.budgetMs ?? CHECKOUT_DOMAIN_BUDGET_MS\n const timer = setTimeout(() => controller.abort(), budget)\n try {\n return await ensurePaymentMethodDomain(hostname, {\n hostId: input.hostId,\n signal: controller.signal,\n ...(input.stripeAccount ? { stripeAccount: input.stripeAccount } : {}),\n })\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** One page of the daily reconcile. */\nexport const RECONCILE_PAGE_SIZE = 200\n\n/**\n * The backfill and the safety net in one pass: every site with a connected\n * custom domain gets its domain and `www.` twin registered. A cached, enabled\n * registration costs one read and no Stripe call, so the steady state is cheap;\n * a domain connected before AGL-3629, or whose connect event was lost, is\n * registered on the first pass after it.\n *\n * Paged by `cname` with a cursor so it reads every site once and stops; the\n * `cname > ''` range uses Firestore's automatic single-field index.\n */\nexport async function reconcileCustomDomains(\n gate: { isLocked(hostId: string): Promise<boolean> },\n options: {\n maxPages?: number\n /** The site's direct-charge seller account, or null (tests inject it). */\n sellerAccount?: (hostId: string) => Promise<string | null>\n } = {},\n): Promise<{ hosts: number; registered: number; failed: number; skippedLocked: number }> {\n const sellerAccount = options.sellerAccount ?? directSellerAccountForHost\n const result = { hosts: 0, registered: 0, failed: 0, skippedLocked: 0 }\n if (!stripeModeOfKey(process.env.STRIPE_SECRET_KEY)) return result\n const firestore = firebaseAdmin.app().firestore()\n let cursor: string | null = null\n const maxPages = options.maxPages ?? 50\n for (let page = 0; page < maxPages; page += 1) {\n let query = firestore\n .collection('hosts')\n .where('cname', '>', '')\n .orderBy('cname')\n .limit(RECONCILE_PAGE_SIZE)\n if (cursor) query = query.startAfter(cursor)\n const snapshot = await query.get()\n if (snapshot.empty) break\n for (const hostDoc of snapshot.docs) {\n result.hosts += 1\n // Skipped, not dropped: a locked site is left as it is and picked up on\n // the first pass after the lift.\n if (await gate.isLocked(hostDoc.id)) {\n result.skippedLocked += 1\n continue\n }\n // A direct-charge seller runs its own charges, so its domains are\n // registered on its account as well as the platform's.\n const account = await sellerAccount(hostDoc.id).catch(() => null)\n for (const domain of customDomainNames(hostDoc.get('cname'))) {\n for (const stripeAccount of account ? [null, account] : [null]) {\n const outcome = await ensurePaymentMethodDomain(domain, {\n hostId: hostDoc.id,\n ...(stripeAccount ? { stripeAccount } : {}),\n })\n if (outcome.outcome === 'registered') result.registered += 1\n if (outcome.outcome === 'failed') result.failed += 1\n }\n }\n }\n cursor = String(snapshot.docs[snapshot.docs.length - 1]?.get('cname') ?? '')\n if (snapshot.size < RECONCILE_PAGE_SIZE || !cursor) break\n }\n return result\n}\n\n/** Core's `host.domain.attached`: register the custom domain and its twin. */\nexport async function onHostDomainAttached(\n payload: {\n hostId: string\n domain: string\n },\n options: { sellerAccount?: (hostId: string) => Promise<string | null> } = {},\n): Promise<void> {\n // The platform's registration as before, and the seller's own as well when\n // the site sells by direct charges, since those sessions run on its account.\n const account = await (options.sellerAccount ?? directSellerAccountForHost)(\n payload.hostId,\n ).catch(() => null)\n for (const domain of customDomainNames(payload.domain)) {\n for (const stripeAccount of account ? [null, account] : [null]) {\n const outcome = await ensurePaymentMethodDomain(domain, {\n hostId: payload.hostId,\n force: true,\n ...(stripeAccount ? { stripeAccount } : {}),\n })\n if (outcome.outcome === 'failed') {\n console.warn(\n `[commerce] payment method domain ${domain}${\n stripeAccount ? ` on ${stripeAccount}` : ''\n } not registered: ${outcome.error}`,\n )\n }\n }\n }\n}\n\n/** Core's `host.domain.released`: disable what no other site still serves. */\nexport async function onHostDomainReleased(\n payload: {\n hostId: string\n domain: string\n },\n options: { sellerAccount?: (hostId: string) => Promise<string | null> } = {},\n): Promise<void> {\n const names = payload.domain.endsWith(`.${TENANT_APEX}`)\n ? [registrableDomain(payload.domain)].filter((name): name is string => Boolean(name))\n : customDomainNames(payload.domain)\n const account = await (options.sellerAccount ?? directSellerAccountForHost)(\n payload.hostId,\n ).catch(() => null)\n for (const domain of names) {\n // The PLATFORM's registration is shared by every site that answers on\n // the name, so it waits until no other site does. The seller's own is\n // that seller's alone, and goes with this site's release.\n if (account) {\n const onSeller = await disablePaymentMethodDomain(domain, { stripeAccount: account })\n if (onSeller.outcome === 'failed') {\n console.warn(\n `[commerce] payment method domain ${domain} on ${account} not disabled: ${onSeller.error}`,\n )\n }\n }\n if (await domainStillClaimed(domain, payload.hostId)) continue\n const outcome = await disablePaymentMethodDomain(domain)\n if (outcome.outcome === 'failed') {\n console.warn(`[commerce] payment method domain ${domain} not disabled: ${outcome.error}`)\n }\n }\n}\n\n/** The registrations a settings card shows for one site. */\nexport async function readSiteDomainRecords(\n site: SiteReturnHost | null | undefined,\n /**\n * The site's direct-charge seller account: its registrations are the ones\n * the site's checkout uses, so they are the ones to show.\n */\n stripeAccount?: string | null,\n): Promise<PaymentMethodDomainRecord[]> {\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!mode) return []\n const account = accountOrNull(stripeAccount)\n const names = siteOwnHosts(site).filter((name) => registrableDomain(name))\n const snapshots = await Promise.all(\n names.map((name) => docRef(mode, name, account).get()),\n )\n return snapshots.map((snapshot, index) => {\n const data = (snapshot.exists ? snapshot.data?.() : null) as PaymentMethodDomainRecord | null\n return (\n data ?? {\n domain: names[index],\n mode,\n ...(account ? { stripeAccount: account } : {}),\n stripeId: null,\n enabled: false,\n status: { applePay: null, googlePay: null, link: null, amazonPay: null, klarna: null },\n hostId: null,\n checkedAtMs: 0,\n lastError: null,\n }\n )\n })\n}\n"],"names":["siteOwnHosts","TENANT_APEX","firebaseAdmin","directSellerAccountForHost","PAYMENT_METHOD_DOMAINS_COLLECTION","PAYMENT_METHOD_DOMAIN_RECHECK_MS","CHECKOUT_DOMAIN_BUDGET_MS","stripeModeOfKey","key","value","String","test","registrableDomain","input","trim","toLowerCase","replace","length","endsWith","includes","paymentMethodDomainDocId","mode","domain","stripeAccount","account","accountOrNull","id","customDomainNames","cname","twin","startsWith","slice","statusOf","object","applePay","apple_pay","status","googlePay","google_pay","link","amazonPay","amazon_pay","klarna","stripeRequest","method","path","params","options","query","URLSearchParams","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","idempotencyKey","body","toString","signal","payload","json","catch","ok","Error","error","message","findOnStripe","list","domain_name","limit","data","find","entry","registerOnPlatform","registerDomain","registerOnAccount","existing","enabled","encodeURIComponent","raced","docRef","app","firestore","collection","doc","record","patch","set","checkedAtMs","Date","now","merge","ensurePaymentMethodDomain","rawDomain","outcome","force","cached","get","exists","stripeId","Number","next","hostId","lastError","undefined","disablePaymentMethodDomain","domainStillClaimed","exceptHostId","hosts","names","byCname","where","docs","some","suffix","subdomain","bySubdomain","ensureCheckoutDomain","hostname","URL","pageUrl","site","controller","AbortController","budget","budgetMs","timer","setTimeout","abort","clearTimeout","RECONCILE_PAGE_SIZE","reconcileCustomDomains","gate","sellerAccount","result","registered","failed","skippedLocked","cursor","maxPages","page","snapshot","orderBy","startAfter","empty","hostDoc","isLocked","size","onHostDomainAttached","console","warn","onHostDomainReleased","filter","name","Boolean","onSeller","readSiteDomainRecords","snapshots","Promise","all","map","index"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAA8BA,YAAY,QAAQ,yCAAwC;AAC1F,SAASC,WAAW,QAAQ,qCAAoC;AAChE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,0BAA0B,QAAQ,6BAAyB;AAEpE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDC,GAED,OAAO,MAAMC,oCAAoC,uBAAsB;AAEvE,8EAA8E,GAC9E,OAAO,MAAMC,mCAAmC,IAAI,KAAK,KAAK,KAAK,KAAI;AAEvE,2EAA2E,GAC3E,OAAO,MAAMC,4BAA4B,KAAI;AAwC7C,gEAAgE,GAChE,OAAO,SAASC,gBAAgBC,GAAuB;IACrD,MAAMC,QAAQC,OAAOF,cAAAA,MAAO;IAC5B,IAAI,iBAAiBG,IAAI,CAACF,QAAQ,OAAO;IACzC,IAAI,iBAAiBE,IAAI,CAACF,QAAQ,OAAO;IACzC,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASG,kBAAkBC,KAAc;IAC9C,MA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UG,GAAG,CAAC,CAACnB,UAAUoB;QAC9B,MAAM3F,OAAQuE,SAAS3C,MAAM,GAAG2C,SAASvE,IAAI,oBAAbuE,SAASvE,IAAI,MAAbuE,YAAoB;QACpD,OACEvE,eAAAA,OAAQ;YACNlD,QAAQyF,KAAK,CAACoD,MAAM;YACpB9I;WACIG,UAAU;YAAED,eAAeC;QAAQ,IAAI,CAAC;YAC5C6E,UAAU;YACVtB,SAAS;YACT3C,QAAQ;gBAAEF,UAAU;gBAAMG,WAAW;gBAAME,MAAM;gBAAMC,WAAW;gBAAME,QAAQ;YAAK;YACrF8D,QAAQ;YACRd,aAAa;YACbe,WAAW;;IAGjB;AACF"}
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { checkEntitlement, pluginRequestFromWeb } from "@aglyn/aglyn/server";
17
+ */ import { directSellerAccountForHost } from "./seller-stripe-account.js";
18
+ import { checkEntitlement, pluginRequestFromWeb } from "@aglyn/aglyn/server";
18
19
  import { emailUnverifiedResponse, firebaseAdmin, getOrgForHost, isImpersonationSession, lockdownRefusal } from "@aglyn/tenant-data-admin";
19
20
  import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
20
21
  import { isStorefrontPaymentMethodOn, normalizeStorefrontPaymentMethodSettings, STOREFRONT_PAYMENT_METHODS } from "../model/commerce-payment-methods.js";
@@ -268,7 +269,7 @@ export async function paymentMethodsHandler(request) {
268
269
  }
269
270
  const answer = {
270
271
  methods: buildPaymentMethodRows(settings, platform, capabilities),
271
- domains: await readSiteDomainRecords(hostSnapshot.data()),
272
+ domains: await readSiteDomainRecords(hostSnapshot.data(), await directSellerAccountForHost(hostId)),
272
273
  accountConnected: Boolean(accountId),
273
274
  canEdit: mayEdit,
274
275
  canFinish: Boolean(accountId) && decoded.uid === ownerUid,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-methods.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { checkEntitlement, pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport type { SiteReturnHost } from '@aglyn/aglyn/app-utils/site-return-url'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n getOrgForHost,\n isImpersonationSession,\n lockdownRefusal,\n} from '@aglyn/tenant-data-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n isStorefrontPaymentMethodOn,\n normalizeStorefrontPaymentMethodSettings,\n STOREFRONT_PAYMENT_METHODS,\n type StorefrontPaymentMethodId,\n type StorefrontPaymentMethodSettings,\n} from '../model/commerce-payment-methods'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport {\n type PaymentMethodDomainRecord,\n readSiteDomainRecords,\n} from './payment-method-domains'\n\n/**\n * The merchant's payment methods card (AGL-3629):\n * `GET|POST /api/commerce/payment-methods?hostId=…`, served by the console.\n *\n * GET answers, per method, three facts the card needs and no client can read:\n *\n * - whether the PLATFORM offers it (its default payment method configuration\n * — storefront charges are destination charges with the platform as\n * merchant of record, so that configuration is the ceiling). A method the\n * platform has not turned on, or that Stripe has not made available to it,\n * is reported `unavailable` and the card does not show it at all;\n * - the connected account's capability for it, which Stripe asks platforms to\n * request before an account accepts BNPL, Cash App, Amazon Pay or crypto;\n * - the site's domain registrations, which Apple Pay depends on.\n *\n * POST saves the toggles to `hosts/{hostId}/settings/store.paymentMethods` and\n * requests the capability of each method turned on, in one account update with\n * an idempotency key. Server-side, because the toggle and the capability are\n * one decision: a toggle saved by the browser with no capability behind it\n * would read as on and never appear.\n */\n\nexport type PlatformAvailability = 'on' | 'unavailable' | null\n\nexport type CapabilityStatus = 'active' | 'pending' | 'inactive' | 'unrequested' | null\n\nexport interface PaymentMethodRow {\n id: StorefrontPaymentMethodId\n on: boolean\n platform: PlatformAvailability\n capability: CapabilityStatus\n}\n\nexport interface PaymentMethodsAnswer {\n methods: PaymentMethodRow[]\n domains: PaymentMethodDomainRecord[]\n accountConnected: boolean\n /** The caller may save toggles: a site admin. */\n canEdit: boolean\n /** The caller may open Stripe to finish a method: the organization owner. */\n canFinish: boolean\n warnings: string[]\n}\n\n/** How long the platform's configuration is trusted in memory. */\nconst PLATFORM_CONFIGURATION_TTL_MS = 10 * 60 * 1000\n\nlet platformCache: { at: number; value: Record<string, PlatformAvailability> } | null = null\n\n/** Test seam: forget the cached platform configuration. */\nexport function resetPlatformPaymentMethodCacheForTests(): void {\n platformCache = null\n}\n\nasync function stripe<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: URLSearchParams,\n idempotencyKey?: string,\n): Promise<T> {\n const query = method === 'GET' && params ? `?${params}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && { 'Content-Type': 'application/x-www-form-urlencoded' }),\n ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: params.toString() }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\ninterface StripeConfiguration {\n is_default?: boolean\n application?: string | null\n active?: boolean\n [key: string]: unknown\n}\n\n/**\n * Which methods the platform's own default configuration offers. The list\n * also returns configurations OTHER Connect applications made for this\n * account (`application` set); those do not govern our sessions and are\n * skipped. `null` per method when Stripe could not be asked — the card then\n * shows the toggle without a verdict rather than hiding a method that may work.\n */\nexport async function platformPaymentMethodAvailability(): Promise<\n Record<string, PlatformAvailability>\n> {\n if (platformCache && Date.now() - platformCache.at < PLATFORM_CONFIGURATION_TTL_MS) {\n return platformCache.value\n }\n const value: Record<string, PlatformAvailability> = {}\n try {\n const list = await stripe<{ data?: StripeConfiguration[] }>(\n 'GET',\n 'payment_method_configurations',\n new URLSearchParams({ limit: '20' }),\n )\n const own =\n list.data?.find((entry) => entry.is_default && !entry.application) ??\n list.data?.find((entry) => !entry.application) ??\n null\n for (const method of STOREFRONT_PAYMENT_METHODS) {\n if (!own) {\n value[method.id] = null\n continue\n }\n const entry = own[method.configurationKey] as\n | { available?: boolean; display_preference?: { value?: string } }\n | undefined\n value[method.id] =\n entry?.available === true && entry?.display_preference?.value === 'on'\n ? 'on'\n : 'unavailable'\n }\n platformCache = { at: Date.now(), value }\n } catch (error) {\n console.warn('[commerce] payment method configuration unreadable', error)\n for (const method of STOREFRONT_PAYMENT_METHODS) value[method.id] = null\n }\n return value\n}\n\nfunction capabilityStatus(\n capabilities: Record<string, string> | undefined,\n key: string | undefined,\n): CapabilityStatus {\n if (!key) return null\n const status = capabilities?.[key]\n if (status === 'active' || status === 'pending' || status === 'inactive') return status\n return 'unrequested'\n}\n\nasync function readAccountCapabilities(\n accountId: string | null,\n): Promise<Record<string, string> | undefined> {\n if (!accountId) return undefined\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'GET',\n `accounts/${encodeURIComponent(accountId)}`,\n )\n return account.capabilities ?? {}\n } catch (error) {\n console.warn('[commerce] connected account unreadable', error)\n return undefined\n }\n}\n\n/** The capabilities a save asks Stripe for: on, offered, not yet requested. */\nexport function capabilitiesToRequest(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): string[] {\n return STOREFRONT_PAYMENT_METHODS.filter(\n (method) =>\n method.capability &&\n isStorefrontPaymentMethodOn(settings, method.id) &&\n platform[method.id] !== 'unavailable' &&\n capabilityStatus(capabilities, method.capability) === 'unrequested',\n ).map((method) => method.capability as string)\n}\n\nexport function buildPaymentMethodRows(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): PaymentMethodRow[] {\n return STOREFRONT_PAYMENT_METHODS.map((method) => ({\n id: method.id,\n on: isStorefrontPaymentMethodOn(settings, method.id),\n platform: platform[method.id] ?? null,\n capability: capabilities ? capabilityStatus(capabilities, method.capability) : null,\n }))\n}\n\nconst json = (body: unknown, status = 200) => Response.json(body, { status })\n\n/**\n * Where Stripe sends the owner back: the console page they pressed the button\n * on, judged against the request's own origin so a forged `Referer` cannot\n * turn the link into a redirect to somewhere else.\n */\nexport function consoleReturnUrl(headers: Partial<Record<string, string>>): string {\n const origin = headers.origin || (headers.host ? `https://${headers.host}` : '')\n const referer = headers.referer ?? ''\n try {\n if (origin && referer && new URL(referer).origin === new URL(origin).origin) {\n return referer\n }\n } catch {\n // Unparseable: fall through to the origin.\n }\n return origin || 'https://localhost/'\n}\n\nexport async function paymentMethodsHandler(request: Request): Promise<Response> {\n const { method, headers: rawHeaders, query, body } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET' && method !== 'POST') {\n return json({ error: 'Method not allowed' }, 405)\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' }, 501)\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n\n const parsed =\n typeof body === 'string' ? (JSON.parse(body || '{}') as Record<string, unknown>) : (body ?? {})\n const hostId = String(\n (method === 'GET' ? query?.['hostId'] : (parsed as Record<string, unknown>)['hostId']) ?? '',\n )\n if (!hostId) return json({ error: 'Missing hostId' }, 400)\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) return json({ error: 'Not found' }, 404)\n\n // An allowlist. Reading the card is for whoever works the store's orders\n // or changes its methods; a change asks Stripe for capabilities on the\n // owner's payout account, so it is \"Manage payment methods\" (AGL-4047),\n // whose preset is the site Admin who alone made it before, as the\n // reader's is the Admin and Editor.\n const mayEdit = holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.paymentMethods')\n const mayRead = mayEdit || holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')\n if (!mayRead) return json({ error: 'Not found' }, 404)\n if (method === 'POST' && !mayEdit) {\n return json({ error: commerceSitePermissionRefusal('commerce.paymentMethods') }, 403)\n }\n\n const owner = await getOrgForHost(hostId)\n const locked = await lockdownRefusal({\n request,\n staff: decoded['staff'] === true,\n uid: decoded.uid,\n org: owner?.org,\n host: hostSnapshot.data(),\n })\n if (locked) return locked\n if (!checkEntitlement((owner?.org ?? {}) as never, 'commerce')) {\n return json({ error: 'Selling is not included on this plan' }, 402)\n }\n\n const ownerUid = String(owner?.org?.ownerUid ?? '')\n const accountId = ownerUid\n ? (((await firestore.collection('profiles').doc(ownerUid).get()).get(\n 'stripeAccountId',\n ) as string | undefined) ?? null)\n : null\n\n const storeRef = hostRef.collection('settings').doc('store')\n let settings = normalizeStorefrontPaymentMethodSettings(\n (await storeRef.get()).get('paymentMethods'),\n )\n const platform = await platformPaymentMethodAvailability()\n let capabilities = await readAccountCapabilities(accountId)\n const warnings: string[] = []\n\n // FINISH IN STRIPE: a capability Stripe holds `inactive` needs details\n // only the account holder can give, and an Express account has no login of\n // its own, so a link minted here is the only way in. The owner's alone,\n // as connecting the account is (`connect.ts`): the link opens the owner's\n // identity and bank details.\n if (method === 'POST' && (parsed as Record<string, unknown>)['action'] === 'finish') {\n if (!accountId || decoded.uid !== ownerUid) {\n return json({ error: 'Only the organization owner can finish this in Stripe' }, 403)\n }\n const back = consoleReturnUrl(headers)\n const link = await stripe<{ url?: string }>(\n 'POST',\n 'account_links',\n new URLSearchParams({\n account: accountId,\n type: 'account_onboarding',\n 'collection_options[fields]': 'currently_due',\n refresh_url: back,\n return_url: back,\n }),\n )\n return json({ url: link.url ?? null })\n }\n\n if (method === 'POST') {\n const requested = normalizeStorefrontPaymentMethodSettings(\n (parsed as Record<string, unknown>)['methods'],\n )\n if (!Object.keys(requested).length) {\n return json({ error: 'Nothing to save' }, 400)\n }\n settings = { ...settings, ...requested }\n await storeRef.set(\n { paymentMethods: settings, paymentMethodsUpdatedAtMs: Date.now(), paymentMethodsUpdatedBy: decoded.uid },\n { merge: true },\n )\n const wanted = accountId ? capabilitiesToRequest(settings, platform, capabilities) : []\n if (accountId && wanted.length) {\n const params = new URLSearchParams()\n for (const capability of wanted) {\n params.set(`capabilities[${capability}][requested]`, 'true')\n }\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'POST',\n `accounts/${encodeURIComponent(accountId)}`,\n params,\n `aglyn-pm-capabilities:${accountId}:${[...wanted].sort().join(',')}`,\n )\n capabilities = account.capabilities ?? capabilities\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n warnings.push(\n `Stripe did not accept the request to enable ${wanted.join(', ')} on your payout account: ${message}`,\n )\n }\n }\n }\n\n const answer: PaymentMethodsAnswer = {\n methods: buildPaymentMethodRows(settings, platform, capabilities),\n domains: await readSiteDomainRecords(hostSnapshot.data() as SiteReturnHost | undefined),\n accountConnected: Boolean(accountId),\n canEdit: mayEdit,\n canFinish: Boolean(accountId) && decoded.uid === ownerUid,\n warnings,\n }\n return json(answer)\n } catch (error) {\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error(error)\n return json({ error: 'Payment methods could not be loaded' }, 500)\n }\n}\n"],"names":["checkEntitlement","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","getOrgForHost","isImpersonationSession","lockdownRefusal","invalidIdTokenResponse","isStorefrontPaymentMethodOn","normalizeStorefrontPaymentMethodSettings","STOREFRONT_PAYMENT_METHODS","commerceSitePermissionRefusal","holdsCommerceSiteKey","readSiteDomainRecords","PLATFORM_CONFIGURATION_TTL_MS","platformCache","resetPlatformPaymentMethodCacheForTests","stripe","method","path","params","idempotencyKey","query","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","catch","ok","Error","error","message","status","platformPaymentMethodAvailability","Date","now","at","value","list","URLSearchParams","limit","own","data","find","entry","is_default","application","id","configurationKey","available","display_preference","console","warn","capabilityStatus","capabilities","key","readAccountCapabilities","accountId","undefined","account","encodeURIComponent","capabilitiesToRequest","settings","platform","filter","capability","map","buildPaymentMethodRows","on","Response","consoleReturnUrl","origin","host","referer","URL","paymentMethodsHandler","request","rawHeaders","authorization","idToken","startsWith","slice","length","parsed","JSON","parse","hostId","String","owner","decoded","app","auth","verifyIdToken","email_verified","firestore","hostRef","collection","doc","hostSnapshot","get","exists","mayEdit","uid","mayRead","locked","staff","org","ownerUid","storeRef","warnings","link","back","type","refresh_url","return_url","url","requested","Object","keys","set","paymentMethods","paymentMethodsUpdatedAtMs","paymentMethodsUpdatedBy","merge","wanted","sort","join","push","answer","methods","domains","accountConnected","Boolean","canEdit","canFinish","unauthenticated"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,oBAAoB,QAAQ,sBAAqB;AAE5E,SACEC,uBAAuB,EACvBC,aAAa,EACbC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,QACV,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,2BAA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AAUT,gBAAgB,EAAE;YACvF,IAAIG,aAAamE,OAAO1C,MAAM,EAAE;gBAC9B,MAAMrE,SAAS,IAAI0B;gBACnB,KAAK,MAAM0B,cAAc2D,OAAQ;oBAC/B/G,OAAO0G,GAAG,CAAC,CAAC,aAAa,EAAEtD,WAAW,YAAY,CAAC,EAAE;gBACvD;gBACA,IAAI;wBAOaN;oBANf,MAAMA,UAAU,MAAMjD,OACpB,QACA,CAAC,SAAS,EAAEkD,mBAAmBH,YAAY,EAC3C5C,QACA,CAAC,sBAAsB,EAAE4C,UAAU,CAAC,EAAE;2BAAImE;qBAAO,CAACC,IAAI,GAAGC,IAAI,CAAC,MAAM;oBAEtExE,gBAAeK,wBAAAA,QAAQL,YAAY,YAApBK,wBAAwBL;gBACzC,EAAE,OAAOxB,OAAO;oBACd,MAAMC,UAAUD,iBAAiBD,QAAQC,MAAMC,OAAO,GAAGwD,OAAOzD;oBAChE+E,SAASkB,IAAI,CACX,CAAC,4CAA4C,EAAEH,OAAOE,IAAI,CAAC,MAAM,yBAAyB,EAAE/F,SAAS;gBAEzG;YACF;QACF;QAEA,MAAMiG,SAA+B;YACnCC,SAAS9D,uBAAuBL,UAAUC,UAAUT;YACpD4E,SAAS,MAAM5H,sBAAsB4F,aAAaxD,IAAI;YACtDyF,kBAAkBC,QAAQ3E;YAC1B4E,SAAShC;YACTiC,WAAWF,QAAQ3E,cAAcgC,QAAQa,GAAG,KAAKK;YACjDE;QACF;QACA,OAAOnF,KAAKsG;IACd,EAAE,OAAOlG,OAAO;QACd,MAAMyG,kBAAkBvI,uBAAuB8B;QAC/C,IAAIyG,iBAAiB,OAAOA;QAC5BpF,QAAQrB,KAAK,CAACA;QACd,OAAOJ,KAAK;YAAEI,OAAO;QAAsC,GAAG;IAChE;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-methods.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { directSellerAccountForHost } from './seller-stripe-account'\nimport { checkEntitlement, pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport type { SiteReturnHost } from '@aglyn/aglyn/app-utils/site-return-url'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n getOrgForHost,\n isImpersonationSession,\n lockdownRefusal,\n} from '@aglyn/tenant-data-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n isStorefrontPaymentMethodOn,\n normalizeStorefrontPaymentMethodSettings,\n STOREFRONT_PAYMENT_METHODS,\n type StorefrontPaymentMethodId,\n type StorefrontPaymentMethodSettings,\n} from '../model/commerce-payment-methods'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport {\n type PaymentMethodDomainRecord,\n readSiteDomainRecords,\n} from './payment-method-domains'\n\n/**\n * The merchant's payment methods card (AGL-3629):\n * `GET|POST /api/commerce/payment-methods?hostId=…`, served by the console.\n *\n * GET answers, per method, three facts the card needs and no client can read:\n *\n * - whether the PLATFORM offers it (its default payment method configuration\n * — storefront charges are destination charges with the platform as\n * merchant of record, so that configuration is the ceiling). A method the\n * platform has not turned on, or that Stripe has not made available to it,\n * is reported `unavailable` and the card does not show it at all;\n * - the connected account's capability for it, which Stripe asks platforms to\n * request before an account accepts BNPL, Cash App, Amazon Pay or crypto;\n * - the site's domain registrations, which Apple Pay depends on.\n *\n * POST saves the toggles to `hosts/{hostId}/settings/store.paymentMethods` and\n * requests the capability of each method turned on, in one account update with\n * an idempotency key. Server-side, because the toggle and the capability are\n * one decision: a toggle saved by the browser with no capability behind it\n * would read as on and never appear.\n */\n\nexport type PlatformAvailability = 'on' | 'unavailable' | null\n\nexport type CapabilityStatus = 'active' | 'pending' | 'inactive' | 'unrequested' | null\n\nexport interface PaymentMethodRow {\n id: StorefrontPaymentMethodId\n on: boolean\n platform: PlatformAvailability\n capability: CapabilityStatus\n}\n\nexport interface PaymentMethodsAnswer {\n methods: PaymentMethodRow[]\n domains: PaymentMethodDomainRecord[]\n accountConnected: boolean\n /** The caller may save toggles: a site admin. */\n canEdit: boolean\n /** The caller may open Stripe to finish a method: the organization owner. */\n canFinish: boolean\n warnings: string[]\n}\n\n/** How long the platform's configuration is trusted in memory. */\nconst PLATFORM_CONFIGURATION_TTL_MS = 10 * 60 * 1000\n\nlet platformCache: { at: number; value: Record<string, PlatformAvailability> } | null = null\n\n/** Test seam: forget the cached platform configuration. */\nexport function resetPlatformPaymentMethodCacheForTests(): void {\n platformCache = null\n}\n\nasync function stripe<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: URLSearchParams,\n idempotencyKey?: string,\n): Promise<T> {\n const query = method === 'GET' && params ? `?${params}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && { 'Content-Type': 'application/x-www-form-urlencoded' }),\n ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: params.toString() }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\ninterface StripeConfiguration {\n is_default?: boolean\n application?: string | null\n active?: boolean\n [key: string]: unknown\n}\n\n/**\n * Which methods the platform's own default configuration offers. The list\n * also returns configurations OTHER Connect applications made for this\n * account (`application` set); those do not govern our sessions and are\n * skipped. `null` per method when Stripe could not be asked — the card then\n * shows the toggle without a verdict rather than hiding a method that may work.\n */\nexport async function platformPaymentMethodAvailability(): Promise<\n Record<string, PlatformAvailability>\n> {\n if (platformCache && Date.now() - platformCache.at < PLATFORM_CONFIGURATION_TTL_MS) {\n return platformCache.value\n }\n const value: Record<string, PlatformAvailability> = {}\n try {\n const list = await stripe<{ data?: StripeConfiguration[] }>(\n 'GET',\n 'payment_method_configurations',\n new URLSearchParams({ limit: '20' }),\n )\n const own =\n list.data?.find((entry) => entry.is_default && !entry.application) ??\n list.data?.find((entry) => !entry.application) ??\n null\n for (const method of STOREFRONT_PAYMENT_METHODS) {\n if (!own) {\n value[method.id] = null\n continue\n }\n const entry = own[method.configurationKey] as\n | { available?: boolean; display_preference?: { value?: string } }\n | undefined\n value[method.id] =\n entry?.available === true && entry?.display_preference?.value === 'on'\n ? 'on'\n : 'unavailable'\n }\n platformCache = { at: Date.now(), value }\n } catch (error) {\n console.warn('[commerce] payment method configuration unreadable', error)\n for (const method of STOREFRONT_PAYMENT_METHODS) value[method.id] = null\n }\n return value\n}\n\nfunction capabilityStatus(\n capabilities: Record<string, string> | undefined,\n key: string | undefined,\n): CapabilityStatus {\n if (!key) return null\n const status = capabilities?.[key]\n if (status === 'active' || status === 'pending' || status === 'inactive') return status\n return 'unrequested'\n}\n\nasync function readAccountCapabilities(\n accountId: string | null,\n): Promise<Record<string, string> | undefined> {\n if (!accountId) return undefined\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'GET',\n `accounts/${encodeURIComponent(accountId)}`,\n )\n return account.capabilities ?? {}\n } catch (error) {\n console.warn('[commerce] connected account unreadable', error)\n return undefined\n }\n}\n\n/** The capabilities a save asks Stripe for: on, offered, not yet requested. */\nexport function capabilitiesToRequest(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): string[] {\n return STOREFRONT_PAYMENT_METHODS.filter(\n (method) =>\n method.capability &&\n isStorefrontPaymentMethodOn(settings, method.id) &&\n platform[method.id] !== 'unavailable' &&\n capabilityStatus(capabilities, method.capability) === 'unrequested',\n ).map((method) => method.capability as string)\n}\n\nexport function buildPaymentMethodRows(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): PaymentMethodRow[] {\n return STOREFRONT_PAYMENT_METHODS.map((method) => ({\n id: method.id,\n on: isStorefrontPaymentMethodOn(settings, method.id),\n platform: platform[method.id] ?? null,\n capability: capabilities ? capabilityStatus(capabilities, method.capability) : null,\n }))\n}\n\nconst json = (body: unknown, status = 200) => Response.json(body, { status })\n\n/**\n * Where Stripe sends the owner back: the console page they pressed the button\n * on, judged against the request's own origin so a forged `Referer` cannot\n * turn the link into a redirect to somewhere else.\n */\nexport function consoleReturnUrl(headers: Partial<Record<string, string>>): string {\n const origin = headers.origin || (headers.host ? `https://${headers.host}` : '')\n const referer = headers.referer ?? ''\n try {\n if (origin && referer && new URL(referer).origin === new URL(origin).origin) {\n return referer\n }\n } catch {\n // Unparseable: fall through to the origin.\n }\n return origin || 'https://localhost/'\n}\n\nexport async function paymentMethodsHandler(request: Request): Promise<Response> {\n const { method, headers: rawHeaders, query, body } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET' && method !== 'POST') {\n return json({ error: 'Method not allowed' }, 405)\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' }, 501)\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n\n const parsed =\n typeof body === 'string' ? (JSON.parse(body || '{}') as Record<string, unknown>) : (body ?? {})\n const hostId = String(\n (method === 'GET' ? query?.['hostId'] : (parsed as Record<string, unknown>)['hostId']) ?? '',\n )\n if (!hostId) return json({ error: 'Missing hostId' }, 400)\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) return json({ error: 'Not found' }, 404)\n\n // An allowlist. Reading the card is for whoever works the store's orders\n // or changes its methods; a change asks Stripe for capabilities on the\n // owner's payout account, so it is \"Manage payment methods\" (AGL-4047),\n // whose preset is the site Admin who alone made it before, as the\n // reader's is the Admin and Editor.\n const mayEdit = holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.paymentMethods')\n const mayRead = mayEdit || holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')\n if (!mayRead) return json({ error: 'Not found' }, 404)\n if (method === 'POST' && !mayEdit) {\n return json({ error: commerceSitePermissionRefusal('commerce.paymentMethods') }, 403)\n }\n\n const owner = await getOrgForHost(hostId)\n const locked = await lockdownRefusal({\n request,\n staff: decoded['staff'] === true,\n uid: decoded.uid,\n org: owner?.org,\n host: hostSnapshot.data(),\n })\n if (locked) return locked\n if (!checkEntitlement((owner?.org ?? {}) as never, 'commerce')) {\n return json({ error: 'Selling is not included on this plan' }, 402)\n }\n\n const ownerUid = String(owner?.org?.ownerUid ?? '')\n const accountId = ownerUid\n ? (((await firestore.collection('profiles').doc(ownerUid).get()).get(\n 'stripeAccountId',\n ) as string | undefined) ?? null)\n : null\n\n const storeRef = hostRef.collection('settings').doc('store')\n let settings = normalizeStorefrontPaymentMethodSettings(\n (await storeRef.get()).get('paymentMethods'),\n )\n const platform = await platformPaymentMethodAvailability()\n let capabilities = await readAccountCapabilities(accountId)\n const warnings: string[] = []\n\n // FINISH IN STRIPE: a capability Stripe holds `inactive` needs details\n // only the account holder can give, and an Express account has no login of\n // its own, so a link minted here is the only way in. The owner's alone,\n // as connecting the account is (`connect.ts`): the link opens the owner's\n // identity and bank details.\n if (method === 'POST' && (parsed as Record<string, unknown>)['action'] === 'finish') {\n if (!accountId || decoded.uid !== ownerUid) {\n return json({ error: 'Only the organization owner can finish this in Stripe' }, 403)\n }\n const back = consoleReturnUrl(headers)\n const link = await stripe<{ url?: string }>(\n 'POST',\n 'account_links',\n new URLSearchParams({\n account: accountId,\n type: 'account_onboarding',\n 'collection_options[fields]': 'currently_due',\n refresh_url: back,\n return_url: back,\n }),\n )\n return json({ url: link.url ?? null })\n }\n\n if (method === 'POST') {\n const requested = normalizeStorefrontPaymentMethodSettings(\n (parsed as Record<string, unknown>)['methods'],\n )\n if (!Object.keys(requested).length) {\n return json({ error: 'Nothing to save' }, 400)\n }\n settings = { ...settings, ...requested }\n await storeRef.set(\n { paymentMethods: settings, paymentMethodsUpdatedAtMs: Date.now(), paymentMethodsUpdatedBy: decoded.uid },\n { merge: true },\n )\n const wanted = accountId ? capabilitiesToRequest(settings, platform, capabilities) : []\n if (accountId && wanted.length) {\n const params = new URLSearchParams()\n for (const capability of wanted) {\n params.set(`capabilities[${capability}][requested]`, 'true')\n }\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'POST',\n `accounts/${encodeURIComponent(accountId)}`,\n params,\n `aglyn-pm-capabilities:${accountId}:${[...wanted].sort().join(',')}`,\n )\n capabilities = account.capabilities ?? capabilities\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n warnings.push(\n `Stripe did not accept the request to enable ${wanted.join(', ')} on your payout account: ${message}`,\n )\n }\n }\n }\n\n const answer: PaymentMethodsAnswer = {\n methods: buildPaymentMethodRows(settings, platform, capabilities),\n domains: await readSiteDomainRecords(\n hostSnapshot.data() as SiteReturnHost | undefined,\n await directSellerAccountForHost(hostId),\n ),\n accountConnected: Boolean(accountId),\n canEdit: mayEdit,\n canFinish: Boolean(accountId) && decoded.uid === ownerUid,\n warnings,\n }\n return json(answer)\n } catch (error) {\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error(error)\n return json({ error: 'Payment methods could not be loaded' }, 500)\n }\n}\n"],"names":["directSellerAccountForHost","checkEntitlement","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","getOrgForHost","isImpersonationSession","lockdownRefusal","invalidIdTokenResponse","isStorefrontPaymentMethodOn","normalizeStorefrontPaymentMethodSettings","STOREFRONT_PAYMENT_METHODS","commerceSitePermissionRefusal","holdsCommerceSiteKey","readSiteDomainRecords","PLATFORM_CONFIGURATION_TTL_MS","platformCache","resetPlatformPaymentMethodCacheForTests","stripe","method","path","params","idempotencyKey","query","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","catch","ok","Error","error","message","status","platformPaymentMethodAvailability","Date","now","at","value","list","URLSearchParams","limit","own","data","find","entry","is_default","application","id","configurationKey","available","display_preference","console","warn","capabilityStatus","capabilities","key","readAccountCapabilities","accountId","undefined","account","encodeURIComponent","capabilitiesToRequest","settings","platform","filter","capability","map","buildPaymentMethodRows","on","Response","consoleReturnUrl","origin","host","referer","URL","paymentMethodsHandler","request","rawHeaders","authorization","idToken","startsWith","slice","length","parsed","JSON","parse","hostId","String","owner","decoded","app","auth","verifyIdToken","email_verified","firestore","hostRef","collection","doc","hostSnapshot","get","exists","mayEdit","uid","mayRead","locked","staff","org","ownerUid","storeRef","warnings","link","back","type","refresh_url","return_url","url","requested","Object","keys","set","paymentMethods","paymentMethodsUpdatedAtMs","paymentMethodsUpdatedBy","merge","wanted","sort","join","push","answer","methods","domains","accountConnected","Boolean","canEdit","canFinish","unauthenticated"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,gBAAgB,EAAEC,oBAAoB,QAAQ,sBAAqB;AAE5E,SACEC,uBAAuB,EACvBC,aAAa,EACbC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,QACV,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,2BAA2B,EAC3BC,wCAAwC,EACxCC,0B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IG,aAAamE,OAAO1C,MAAM,EAAE;gBAC9B,MAAMrE,SAAS,IAAI0B;gBACnB,KAAK,MAAM0B,cAAc2D,OAAQ;oBAC/B/G,OAAO0G,GAAG,CAAC,CAAC,aAAa,EAAEtD,WAAW,YAAY,CAAC,EAAE;gBACvD;gBACA,IAAI;wBAOaN;oBANf,MAAMA,UAAU,MAAMjD,OACpB,QACA,CAAC,SAAS,EAAEkD,mBAAmBH,YAAY,EAC3C5C,QACA,CAAC,sBAAsB,EAAE4C,UAAU,CAAC,EAAE;2BAAImE;qBAAO,CAACC,IAAI,GAAGC,IAAI,CAAC,MAAM;oBAEtExE,gBAAeK,wBAAAA,QAAQL,YAAY,YAApBK,wBAAwBL;gBACzC,EAAE,OAAOxB,OAAO;oBACd,MAAMC,UAAUD,iBAAiBD,QAAQC,MAAMC,OAAO,GAAGwD,OAAOzD;oBAChE+E,SAASkB,IAAI,CACX,CAAC,4CAA4C,EAAEH,OAAOE,IAAI,CAAC,MAAM,yBAAyB,EAAE/F,SAAS;gBAEzG;YACF;QACF;QAEA,MAAMiG,SAA+B;YACnCC,SAAS9D,uBAAuBL,UAAUC,UAAUT;YACpD4E,SAAS,MAAM5H,sBACb4F,aAAaxD,IAAI,IACjB,MAAMlD,2BAA2B8F;YAEnC6C,kBAAkBC,QAAQ3E;YAC1B4E,SAAShC;YACTiC,WAAWF,QAAQ3E,cAAcgC,QAAQa,GAAG,KAAKK;YACjDE;QACF;QACA,OAAOnF,KAAKsG;IACd,EAAE,OAAOlG,OAAO;QACd,MAAMyG,kBAAkBvI,uBAAuB8B;QAC/C,IAAIyG,iBAAiB,OAAOA;QAC5BpF,QAAQrB,KAAK,CAACA;QACd,OAAOJ,KAAK;YAAEI,OAAO;QAAsC,GAAG;IAChE;AACF"}
@@ -15,6 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import * as Aglyn from "@aglyn/aglyn/server";
18
+ import { excludeBuyNowPayLater } from "@aglyn/aglyn/app-utils/buy-now-pay-later";
18
19
  import * as CommerceModel from "../model/index.js";
19
20
  import { firebaseAdmin, getOrgForHost, getPluginConfig } from "@aglyn/tenant-data-admin";
20
21
  import recordCapturedContact from "@aglyn/aglyn/plugin-manager/record-captured-contact";
@@ -604,7 +605,7 @@ import { posKioskPrincipal } from "./pos-kiosk-principal.js";
604
605
  // cashier's discount, plus the origin tax. A till knows both — there is no
605
606
  // shopper-chosen shipping and no Stripe Tax to wait on — so unlike the
606
607
  // online doors this one recovers the cost exactly.
607
- const feeCents = payment === 'link' ? tenderTakeFeeCents + Aglyn.saleProcessingCostCents(chargedItemsCents + taxCents) : tenderTakeFeeCents;
608
+ const feeCents = payment === 'link' ? Aglyn.saleApplicationFeeCents(tenderTakeFeeCents, chargedItemsCents + taxCents) : tenderTakeFeeCents;
608
609
  const totals = CommerceModel.computeOrderTotals(lineItems, {
609
610
  discountCents,
610
611
  taxCents,
@@ -938,6 +939,9 @@ import { posKioskPrincipal } from "./pos-kiosk-principal.js";
938
939
  } : {}, discountHoldKey ? {
939
940
  'metadata[discountHoldKey]': discountHoldKey
940
941
  } : {}));
942
+ // The register's card link offers no buy-now-pay-later (AGL-4198), so
943
+ // its fee, at the card rate, covers whatever the customer pays with.
944
+ excludeBuyNowPayLater(params);
941
945
  const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {
942
946
  method: 'POST',
943
947
  headers: _extends({