@aglyn/plugins-commerce 1.14.0 → 1.15.1

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 (214) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/account-subscriptions.d.ts +51 -0
  3. package/src/lib/components/account-subscriptions.js +168 -0
  4. package/src/lib/components/account-subscriptions.js.map +1 -0
  5. package/src/lib/components/account.js +12 -48
  6. package/src/lib/components/account.js.map +1 -1
  7. package/src/lib/components/cart.js +38 -9
  8. package/src/lib/components/cart.js.map +1 -1
  9. package/src/lib/components/commerce-console-page.js +6 -0
  10. package/src/lib/components/commerce-console-page.js.map +1 -1
  11. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  12. package/src/lib/components/commerce-console-sections.js +5 -0
  13. package/src/lib/components/commerce-console-sections.js.map +1 -1
  14. package/src/lib/components/console/paid-media.d.ts +1 -0
  15. package/src/lib/components/console/paid-media.js +15 -4
  16. package/src/lib/components/console/paid-media.js.map +1 -1
  17. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  18. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  19. package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
  20. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
  22. package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
  24. package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
  25. package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
  26. package/src/lib/components/console/pos-cellular-control.component.js +5 -5
  27. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  28. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  29. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  30. package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
  31. package/src/lib/components/console/pos-hardware-card.component.js +77 -8
  32. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  33. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
  34. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
  35. package/src/lib/components/console/pos-page.component.js +19 -2
  36. package/src/lib/components/console/pos-page.component.js.map +1 -1
  37. package/src/lib/components/console/product-editor-dialog.component.js +21 -2
  38. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  39. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
  40. package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
  41. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
  42. package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
  43. package/src/lib/components/console/subscriptions-card.component.js +282 -0
  44. package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
  45. package/src/lib/components/hardware-terms-consent.d.ts +22 -0
  46. package/src/lib/components/hardware-terms-consent.js +85 -0
  47. package/src/lib/components/hardware-terms-consent.js.map +1 -0
  48. package/src/lib/components/product-detail.js +32 -8
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/components/quote-page-body.js +7 -3
  51. package/src/lib/components/quote-page-body.js.map +1 -1
  52. package/src/lib/components/related-products.js +6 -3
  53. package/src/lib/components/related-products.js.map +1 -1
  54. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  55. package/src/lib/components/storefront-payment-element.js +11 -7
  56. package/src/lib/components/storefront-payment-element.js.map +1 -1
  57. package/src/lib/constants/operator-alerts.d.ts +1 -1
  58. package/src/lib/constants/operator-alerts.js +4 -4
  59. package/src/lib/constants/operator-alerts.js.map +1 -1
  60. package/src/lib/model/commerce-orders.d.ts +6 -2
  61. package/src/lib/model/commerce-orders.js.map +1 -1
  62. package/src/lib/model/commerce-payment-methods.d.ts +27 -16
  63. package/src/lib/model/commerce-payment-methods.js +11 -83
  64. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  65. package/src/lib/model/commerce.d.ts +6 -0
  66. package/src/lib/model/commerce.js.map +1 -1
  67. package/src/lib/model/index.d.ts +1 -0
  68. package/src/lib/model/index.js +1 -0
  69. package/src/lib/model/index.js.map +1 -1
  70. package/src/lib/model/paid-media.d.ts +8 -0
  71. package/src/lib/model/paid-media.js +13 -0
  72. package/src/lib/model/paid-media.js.map +1 -1
  73. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  74. package/src/lib/model/pos-hardware-in-person.js +52 -20
  75. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  76. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  77. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  78. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  79. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  80. package/src/lib/model/pos-hardware-terms.js +68 -3
  81. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  82. package/src/lib/model/pos-hardware.d.ts +101 -15
  83. package/src/lib/model/pos-hardware.js +128 -18
  84. package/src/lib/model/pos-hardware.js.map +1 -1
  85. package/src/lib/model/pos-reader-splash.js +2 -2
  86. package/src/lib/model/pos-reader-splash.js.map +1 -1
  87. package/src/lib/model/product-write.d.ts +3 -0
  88. package/src/lib/model/subscription-view.d.ts +90 -0
  89. package/src/lib/model/subscription-view.js +176 -0
  90. package/src/lib/model/subscription-view.js.map +1 -0
  91. package/src/lib/server/billing-webhook.d.ts +27 -6
  92. package/src/lib/server/billing-webhook.js +271 -81
  93. package/src/lib/server/billing-webhook.js.map +1 -1
  94. package/src/lib/server/cancel-order.js +4 -3
  95. package/src/lib/server/cancel-order.js.map +1 -1
  96. package/src/lib/server/cart-checkout.js +105 -23
  97. package/src/lib/server/cart-checkout.js.map +1 -1
  98. package/src/lib/server/cart.js +15 -3
  99. package/src/lib/server/cart.js.map +1 -1
  100. package/src/lib/server/catalog.js +58 -22
  101. package/src/lib/server/catalog.js.map +1 -1
  102. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  103. package/src/lib/server/checkout-session-expiry.js +19 -5
  104. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  105. package/src/lib/server/checkout-status.js +4 -3
  106. package/src/lib/server/checkout-status.js.map +1 -1
  107. package/src/lib/server/checkout.js +98 -26
  108. package/src/lib/server/checkout.js.map +1 -1
  109. package/src/lib/server/connect.js +42 -11
  110. package/src/lib/server/connect.js.map +1 -1
  111. package/src/lib/server/draft-order.js +36 -7
  112. package/src/lib/server/draft-order.js.map +1 -1
  113. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  114. package/src/lib/server/manual-tax-rate.js +10 -6
  115. package/src/lib/server/manual-tax-rate.js.map +1 -1
  116. package/src/lib/server/membership-account.d.ts +22 -0
  117. package/src/lib/server/membership-account.js +52 -8
  118. package/src/lib/server/membership-account.js.map +1 -1
  119. package/src/lib/server/native-checkout.d.ts +10 -3
  120. package/src/lib/server/native-checkout.js +8 -3
  121. package/src/lib/server/native-checkout.js.map +1 -1
  122. package/src/lib/server/payment-method-domains.d.ts +50 -9
  123. package/src/lib/server/payment-method-domains.js +150 -51
  124. package/src/lib/server/payment-method-domains.js.map +1 -1
  125. package/src/lib/server/payment-methods.js +3 -2
  126. package/src/lib/server/payment-methods.js.map +1 -1
  127. package/src/lib/server/pos-auth.d.ts +3 -3
  128. package/src/lib/server/pos-auth.js +3 -3
  129. package/src/lib/server/pos-auth.js.map +1 -1
  130. package/src/lib/server/pos-cellular-billing.js +1 -1
  131. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  132. package/src/lib/server/pos-cellular-notify.js +1 -1
  133. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  134. package/src/lib/server/pos-cellular.js +1 -1
  135. package/src/lib/server/pos-cellular.js.map +1 -1
  136. package/src/lib/server/pos-hardware-admin.js +86 -13
  137. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  138. package/src/lib/server/pos-hardware-attach.js +5 -5
  139. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  140. package/src/lib/server/pos-hardware-cancel.js +65 -0
  141. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  142. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  143. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  144. package/src/lib/server/pos-hardware-closure.js +5 -8
  145. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  146. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  147. package/src/lib/server/pos-hardware-in-person.js +72 -17
  148. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  149. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  150. package/src/lib/server/pos-hardware-notify.js +30 -5
  151. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  152. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  153. package/src/lib/server/pos-hardware-readers.js +206 -85
  154. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  155. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  156. package/src/lib/server/pos-hardware-returns.js +39 -7
  157. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  158. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  159. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  160. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  161. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  162. package/src/lib/server/pos-hardware-sale.js +1 -0
  163. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  164. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  165. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  166. package/src/lib/server/pos-hardware-webhook.js +16 -3
  167. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  168. package/src/lib/server/pos-hardware.d.ts +14 -3
  169. package/src/lib/server/pos-hardware.js +83 -18
  170. package/src/lib/server/pos-hardware.js.map +1 -1
  171. package/src/lib/server/pos-ops-routes.js +2 -10
  172. package/src/lib/server/pos-ops-routes.js.map +1 -1
  173. package/src/lib/server/pos-order.js +5 -1
  174. package/src/lib/server/pos-order.js.map +1 -1
  175. package/src/lib/server/pos-stripe.d.ts +7 -7
  176. package/src/lib/server/pos-stripe.js +15 -13
  177. package/src/lib/server/pos-stripe.js.map +1 -1
  178. package/src/lib/server/pos-terminal.js +11 -3
  179. package/src/lib/server/pos-terminal.js.map +1 -1
  180. package/src/lib/server/quote-pay.d.ts +23 -1
  181. package/src/lib/server/quote-pay.js +111 -27
  182. package/src/lib/server/quote-pay.js.map +1 -1
  183. package/src/lib/server/quote.d.ts +2 -1
  184. package/src/lib/server/quote.js +12 -11
  185. package/src/lib/server/quote.js.map +1 -1
  186. package/src/lib/server/refund.js +13 -6
  187. package/src/lib/server/refund.js.map +1 -1
  188. package/src/lib/server/related.js +10 -3
  189. package/src/lib/server/related.js.map +1 -1
  190. package/src/lib/server/reserve.js +19 -6
  191. package/src/lib/server/reserve.js.map +1 -1
  192. package/src/lib/server/revenue-source.d.ts +6 -0
  193. package/src/lib/server/revenue-source.js +25 -9
  194. package/src/lib/server/revenue-source.js.map +1 -1
  195. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  196. package/src/lib/server/seller-stripe-account.js +99 -0
  197. package/src/lib/server/seller-stripe-account.js.map +1 -0
  198. package/src/lib/server/storefront-tax-record.js +6 -1
  199. package/src/lib/server/storefront-tax-record.js.map +1 -1
  200. package/src/lib/server/storefront-tax.d.ts +33 -2
  201. package/src/lib/server/storefront-tax.js +39 -3
  202. package/src/lib/server/storefront-tax.js.map +1 -1
  203. package/src/lib/server/stream.d.ts +2 -0
  204. package/src/lib/server/stream.js +22 -2
  205. package/src/lib/server/stream.js.map +1 -1
  206. package/src/lib/server/stripe-refund.d.ts +15 -0
  207. package/src/lib/server/stripe-refund.js +54 -26
  208. package/src/lib/server/stripe-refund.js.map +1 -1
  209. package/src/lib/server/subscription-portal.js +8 -3
  210. package/src/lib/server/subscription-portal.js.map +1 -1
  211. package/src/lib/server/tax-return-source.js +5 -1
  212. package/src/lib/server/tax-return-source.js.map +1 -1
  213. package/src/lib/server.js +2 -2
  214. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/storefront-tax-record.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 { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { storefrontTaxRow, type StorefrontTaxRow } from './storefront-tax'\n\n/**\n * Writes `storefrontTaxCollected/{stripeId}` for every storefront sale that\n * carried tax (AGL-1904) — the row that makes tax collected under Aglyn's\n * registration visible to Aglyn's own quarterly return.\n *\n * ## The hole this closes\n *\n * AGL-1811 records one `platformRevenue` row per paid invoice and the Texas\n * return is their sum. That collection is deliberately scoped to AGLYN's own\n * charges: the console webhook only writes a row when the invoice's customer\n * resolves through the `stripeCustomers` index, which `writeOrgBilling` stamps\n * for Aglyn's billing customers and nothing else stamps. A storefront\n * shopper's customer is never in it.\n *\n * That scoping is correct for what it was built for and it left a gap: a\n * `mode: 'stripe'` storefront sale charges the shopper tax computed on\n * AGLYN's registrations (measured — see `storefront-tax.ts`), settles it into\n * Aglyn's platform balance, and NOTHING recorded it anywhere Aglyn's return\n * could see. The merchant's order document carries a `totals.taxCents`, but\n * that is the merchant's books, per host, and no return sums it.\n *\n * ## Why a SEPARATE collection rather than more `platformRevenue` rows\n *\n * Structural, and the reason must survive a future tidy-up: a\n * `platformRevenue` row's `netCents` is Aglyn's revenue, and a storefront\n * row's is mostly the MERCHANT's — it transfers straight out to the connected\n * account. Merging the two would make the return's \"total sales\" figure silently\n * include other companies' receipts. Keeping them in different collections\n * means no query, sum or future refactor can accidentally add them together;\n * the return reports the storefront figures as their own section, and what\n * belongs on which line of a filed return stays a question for the preparer\n * and for counsel rather than one this code answers.\n *\n * ## What is recorded, and what is not\n *\n * Recorded: cart, buy-now, reservation and draft-order sessions, plus every\n * storefront subscription INVOICE (opening cycle and renewals both — the\n * subscription's own `checkout.session.completed` is deliberately skipped so\n * the opening cycle is not counted twice, the same rule AGL-1811 applies).\n *\n * Manual-mode sales are recorded too, with `taxMode: 'manual'`, precisely so\n * the two modes can be told apart at read time instead of being invisible.\n * They are NOT Aglyn-collected and the return never sums them into the\n * Aglyn-liable figure.\n *\n * **Refunds are not yet reflected.** A refunded storefront sale keeps its full\n * tax on this record, so the Aglyn-liable figure is an OVER-statement of what\n * is owed rather than an under-statement. That direction is deliberate:\n * over-stating what is held for the state is correctable at filing time,\n * under-stating it is a shortfall discovered by an auditor. Stated here rather\n * than left to be discovered.\n *\n * Never throws. A recording failure logs and returns — a throw here propagates\n * through `runBillingWebhookHandlers` into a 500 that Stripe redelivers\n * forever, which is the AGL-1743 lesson.\n */\n\n/** The commerce session types that settle money on the platform account. */\nconst SESSION_TYPES = new Set([\n 'commerce-cart',\n 'commerce-order',\n 'commerce-reservation',\n 'commerce-draft',\n // A paid service booking (AGL-2000). It carries no tax by a stated\n // decision (`bookings/server.ts`), but it is a storefront sale and it was\n // absent from this set entirely — so it was not merely untaxed, it did not\n // appear in the record that would let anyone NOTICE it was untaxed or\n // reconcile it later. An untaxed sale that is recorded reads\n // `taxMode: 'none'`; an unrecorded one reads as nothing at all.\n 'booking-payment',\n])\n\n/**\n * Session types whose zero tax is a decision taken HERE, not by the merchant\n * (AGL-2000). Their rows are filed even at `taxMode: 'none'`, so an untaxed\n * service or stay is reconcilable instead of merely missing. See the note at\n * the `taxMode === 'none'` gate below.\n */\nconst PLATFORM_UNTAXED_TYPES = new Set(['booking-payment', 'commerce-reservation'])\n\nfunction stripeKey(): string {\n return String(process.env.STRIPE_SECRET_KEY ?? '')\n}\n\n/**\n * A Checkout Session's tax BREAKDOWN, which the webhook payload does not\n * carry: `total_details.breakdown` is an expandable field, so the delivered\n * object states `amount_tax` and nothing about the base it was applied to.\n *\n * Returns the expanded session, or null when the read cannot be made. Null is\n * not a failure that stops the recording — the row is written from the\n * delivered object with `taxLines: []`, and a taxed row with no stated base is\n * COUNTED in the return's `attention` rather than dropped or zeroed.\n */\nasync function expandedSession(sessionId: string): Promise<any | null> {\n const key = stripeKey()\n if (!key || !sessionId) return null\n try {\n const response = await fetch(\n `https://api.stripe.com/v1/checkout/sessions/${encodeURIComponent(\n sessionId,\n )}?expand[]=total_details.breakdown`,\n { headers: { Authorization: `Bearer ${key}` } },\n )\n if (!response.ok) return null\n const body = await response.json().catch(() => null)\n return body?.id ? body : null\n } catch {\n return null\n }\n}\n\n/** The host this Stripe object belongs to, from whichever metadata bag. */\nfunction hostIdOf(object: any): string {\n return String(\n object?.metadata?.hostId ??\n object?.subscription_details?.metadata?.hostId ??\n object?.parent?.subscription_details?.metadata?.hostId ??\n '',\n )\n}\n\nfunction metadataTypeOf(object: any): string {\n return String(\n object?.metadata?.type ??\n object?.subscription_details?.metadata?.type ??\n object?.parent?.subscription_details?.metadata?.type ??\n '',\n )\n}\n\n/**\n * Records one storefront sale's tax, or does nothing when this event is not\n * one. Returns the row written, for the specs — never for control flow.\n */\nexport async function recordStorefrontTax(\n type: string,\n object: any,\n): Promise<StorefrontTaxRow | null> {\n try {\n const metadataType = metadataTypeOf(object)\n const hostId = hostIdOf(object)\n if (!hostId) return null\n\n let kind: 'session' | 'invoice'\n let taxSource = object\n let manualTaxCents = 0\n if (\n type === 'checkout.session.completed' &&\n SESSION_TYPES.has(metadataType) &&\n object?.payment_status === 'paid'\n ) {\n kind = 'session'\n // The manual tax rides as an ordinary `line_items[1]` Stripe is never\n // told is tax (AGL-1711), so the session's own metadata snapshot is the\n // only witness to it. A cart session carries no such line at all.\n manualTaxCents = Math.max(0, Number(object?.metadata?.taxCents ?? 0)) || 0\n // Expanded whenever Stripe COMPUTED tax on this session — which since\n // AGL-1953 includes a `manual`-mode cart or draft order, where the tax\n // rides a real Tax Rate and Stripe therefore states a `taxable_amount`\n // for it. Gated on the delivered `amount_tax` rather than done\n // unconditionally so the buy-now and POS constructions, which report 0\n // there and answer from metadata, still cost no extra Stripe read.\n const stripeStatedTax = Number(\n object?.total_details?.amount_tax ?? 0,\n )\n if (\n object?.automatic_tax?.enabled === true ||\n (Number.isFinite(stripeStatedTax) && stripeStatedTax > 0)\n ) {\n taxSource = (await expandedSession(String(object?.id ?? ''))) ?? object\n }\n } else if (\n (type === 'invoice.paid' || type === 'invoice.payment_succeeded') &&\n metadataType === 'commerce-subscription'\n ) {\n // Every cycle including the opening one. The subscription's own\n // `checkout.session.completed` is NOT a second source — recording both\n // would count the opening sale twice (AGL-1811's rule, same reason).\n kind = 'invoice'\n } else {\n return null\n }\n\n const row = storefrontTaxRow(taxSource, { kind, hostId, manualTaxCents })\n if (!row) return null\n // Nothing to file and nothing to explain: no tax computed, no tax charged.\n // A `stripe-automatic` row is kept even at zero tax — that a Stripe Tax\n // sale answered \"not collecting\" is itself the audit answer to why a\n // jurisdiction is absent from the return.\n //\n // EXCEPT where the absence is AGLYN'S decision rather than the merchant's\n // (AGL-2000). A zero-tax commerce sale means the merchant configured no\n // tax — their call, their liability, nothing here to explain. A booking or\n // a reservation is untaxed because THIS CODEBASE decided not to compute a\n // goods rate on a service or a room (`bookings/server.ts`, `reserve.ts`),\n // and that is exactly the kind of absence somebody has to be able to find\n // later: it is the platform answering a tax question on a merchant's\n // revenue. Dropping those rows made the decision invisible in the one\n // place anyone would go looking for it.\n if (row.taxMode === 'none' && !PLATFORM_UNTAXED_TYPES.has(metadataType)) {\n return null\n }\n\n const documentId = String(object?.id ?? '')\n if (!documentId) return null\n const orgId = (await getOrgForHost(hostId).catch(() => null))?.orgId ?? null\n await firebaseAdmin\n .app()\n .firestore()\n .collection('storefrontTaxCollected')\n .doc(documentId)\n .set(\n {\n ...row,\n orgId,\n recordedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n // Keyed by the Stripe object id and merged, so a redelivery — and the\n // `invoice.paid` / `invoice.payment_succeeded` pair Stripe sends for\n // ONE payment — restamps a single document instead of duplicating a\n // taxable sale.\n { merge: true },\n )\n return row\n } catch (error) {\n console.error('[AGL-1904] storefront tax recording failed', error)\n return null\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","storefrontTaxRow","SESSION_TYPES","Set","PLATFORM_UNTAXED_TYPES","stripeKey","process","String","env","STRIPE_SECRET_KEY","expandedSession","sessionId","key","response","fetch","encodeURIComponent","headers","Authorization","ok","body","json","catch","id","hostIdOf","object","metadata","hostId","subscription_details","parent","metadataTypeOf","type","recordStorefrontTax","metadataType","kind","taxSource","manualTaxCents","has","payment_status","Math","max","Number","taxCents","stripeStatedTax","total_details","amount_tax","automatic_tax","enabled","isFinite","row","taxMode","documentId","orgId","app","firestore","collection","doc","set","recordedAt","FieldValue","serverTimestamp","merge","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,gBAAgB,QAA+B,sBAAkB;AAE1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GAED,0EAA0E,GAC1E,MAAMC,gBAAgB,IAAIC,IAAI;IAC5B;IACA;IACA;IACA;IACA,mEAAmE;IACnE,0EAA0E;IAC1E,2EAA2E;IAC3E,sEAAsE;IACtE,6DAA6D;IAC7D,gEAAgE;IAChE;CACD;AAED;;;;;CAKC,GACD,MAAMC,yBAAyB,IAAID,IAAI;IAAC;IAAmB;CAAuB;AAElF,SAASE;QACOC;IAAd,OAAOC,QAAOD,iCAAAA,QAAQE,GAAG,CAACC,iBAAiB,YAA7BH,iCAAiC;AACjD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;YACrEC,OAAO;QACT,OAAO;YACL,OAAO;QACT;QAEA,MAAMe,MAAM/C,iBAAiBiC,WAAW;YAAED;YAAMP;YAAQS;QAAe;QACvE,IAAI,CAACa,KAAK,OAAO;QACjB,2EAA2E;QAC3E,wEAAwE;QACxE,qEAAqE;QACrE,0CAA0C;QAC1C,EAAE;QACF,0EAA0E;QAC1E,wEAAwE;QACxE,2EAA2E;QAC3E,0EAA0E;QAC1E,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,sEAAsE;QACtE,wCAAwC;QACxC,IAAIA,IAAIC,OAAO,KAAK,UAAU,CAAC7C,uBAAuBgC,GAAG,CAACJ,eAAe;YACvE,OAAO;QACT;QAEA,MAAMkB,aAAa3C,eAAOiB,0BAAAA,OAAQF,EAAE,mBAAI;QACxC,IAAI,CAAC4B,YAAY,OAAO;QACxB,MAAMC,kBAAS,QAAA,MAAMnD,cAAc0B,QAAQL,KAAK,CAAC,IAAM,0BAAzC,AAAC,MAAgD8B,KAAK,oBAAI;QACxE,MAAMpD,cACHqD,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,0BACXC,GAAG,CAACL,YACJM,GAAG,CACF,aACKR;YACHG;YACAM,YAAY1D,cAAcsD,SAAS,CAACK,UAAU,CAACC,eAAe;YAEhE,sEAAsE;QACtE,qEAAqE;QACrE,oEAAoE;QACpE,gBAAgB;QAChB;YAAEC,OAAO;QAAK;QAElB,OAAOZ;IACT,EAAE,OAAOa,OAAO;QACdC,QAAQD,KAAK,CAAC,8CAA8CA;QAC5D,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/storefront-tax-record.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 { isDirectChargeObject } from './seller-stripe-account'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { storefrontTaxRow, type StorefrontTaxRow } from './storefront-tax'\n\n/**\n * Writes `storefrontTaxCollected/{stripeId}` for every storefront sale that\n * carried tax (AGL-1904) — the row that makes tax collected under Aglyn's\n * registration visible to Aglyn's own quarterly return.\n *\n * ## The hole this closes\n *\n * AGL-1811 records one `platformRevenue` row per paid invoice and the Texas\n * return is their sum. That collection is deliberately scoped to AGLYN's own\n * charges: the console webhook only writes a row when the invoice's customer\n * resolves through the `stripeCustomers` index, which `writeOrgBilling` stamps\n * for Aglyn's billing customers and nothing else stamps. A storefront\n * shopper's customer is never in it.\n *\n * That scoping is correct for what it was built for and it left a gap: a\n * `mode: 'stripe'` storefront sale charges the shopper tax computed on\n * AGLYN's registrations (measured — see `storefront-tax.ts`), settles it into\n * Aglyn's platform balance, and NOTHING recorded it anywhere Aglyn's return\n * could see. The merchant's order document carries a `totals.taxCents`, but\n * that is the merchant's books, per host, and no return sums it.\n *\n * ## Why a SEPARATE collection rather than more `platformRevenue` rows\n *\n * Structural, and the reason must survive a future tidy-up: a\n * `platformRevenue` row's `netCents` is Aglyn's revenue, and a storefront\n * row's is mostly the MERCHANT's — it transfers straight out to the connected\n * account. Merging the two would make the return's \"total sales\" figure silently\n * include other companies' receipts. Keeping them in different collections\n * means no query, sum or future refactor can accidentally add them together;\n * the return reports the storefront figures as their own section, and what\n * belongs on which line of a filed return stays a question for the preparer\n * and for counsel rather than one this code answers.\n *\n * ## What is recorded, and what is not\n *\n * Recorded: cart, buy-now, reservation and draft-order sessions, plus every\n * storefront subscription INVOICE (opening cycle and renewals both — the\n * subscription's own `checkout.session.completed` is deliberately skipped so\n * the opening cycle is not counted twice, the same rule AGL-1811 applies).\n *\n * Manual-mode sales are recorded too, with `taxMode: 'manual'`, precisely so\n * the two modes can be told apart at read time instead of being invisible.\n * They are NOT Aglyn-collected and the return never sums them into the\n * Aglyn-liable figure.\n *\n * **Refunds are not yet reflected.** A refunded storefront sale keeps its full\n * tax on this record, so the Aglyn-liable figure is an OVER-statement of what\n * is owed rather than an under-statement. That direction is deliberate:\n * over-stating what is held for the state is correctable at filing time,\n * under-stating it is a shortfall discovered by an auditor. Stated here rather\n * than left to be discovered.\n *\n * Never throws. A recording failure logs and returns — a throw here propagates\n * through `runBillingWebhookHandlers` into a 500 that Stripe redelivers\n * forever, which is the AGL-1743 lesson.\n */\n\n/** The commerce session types that settle money on the platform account. */\nconst SESSION_TYPES = new Set([\n 'commerce-cart',\n 'commerce-order',\n 'commerce-reservation',\n 'commerce-draft',\n // A paid service booking (AGL-2000). It carries no tax by a stated\n // decision (`bookings/server.ts`), but it is a storefront sale and it was\n // absent from this set entirely — so it was not merely untaxed, it did not\n // appear in the record that would let anyone NOTICE it was untaxed or\n // reconcile it later. An untaxed sale that is recorded reads\n // `taxMode: 'none'`; an unrecorded one reads as nothing at all.\n 'booking-payment',\n])\n\n/**\n * Session types whose zero tax is a decision taken HERE, not by the merchant\n * (AGL-2000). Their rows are filed even at `taxMode: 'none'`, so an untaxed\n * service or stay is reconcilable instead of merely missing. See the note at\n * the `taxMode === 'none'` gate below.\n */\nconst PLATFORM_UNTAXED_TYPES = new Set(['booking-payment', 'commerce-reservation'])\n\nfunction stripeKey(): string {\n return String(process.env.STRIPE_SECRET_KEY ?? '')\n}\n\n/**\n * A Checkout Session's tax BREAKDOWN, which the webhook payload does not\n * carry: `total_details.breakdown` is an expandable field, so the delivered\n * object states `amount_tax` and nothing about the base it was applied to.\n *\n * Returns the expanded session, or null when the read cannot be made. Null is\n * not a failure that stops the recording — the row is written from the\n * delivered object with `taxLines: []`, and a taxed row with no stated base is\n * COUNTED in the return's `attention` rather than dropped or zeroed.\n */\nasync function expandedSession(sessionId: string): Promise<any | null> {\n const key = stripeKey()\n if (!key || !sessionId) return null\n try {\n const response = await fetch(\n `https://api.stripe.com/v1/checkout/sessions/${encodeURIComponent(\n sessionId,\n )}?expand[]=total_details.breakdown`,\n { headers: { Authorization: `Bearer ${key}` } },\n )\n if (!response.ok) return null\n const body = await response.json().catch(() => null)\n return body?.id ? body : null\n } catch {\n return null\n }\n}\n\n/** The host this Stripe object belongs to, from whichever metadata bag. */\nfunction hostIdOf(object: any): string {\n return String(\n object?.metadata?.hostId ??\n object?.subscription_details?.metadata?.hostId ??\n object?.parent?.subscription_details?.metadata?.hostId ??\n '',\n )\n}\n\nfunction metadataTypeOf(object: any): string {\n return String(\n object?.metadata?.type ??\n object?.subscription_details?.metadata?.type ??\n object?.parent?.subscription_details?.metadata?.type ??\n '',\n )\n}\n\n/**\n * Records one storefront sale's tax, or does nothing when this event is not\n * one. Returns the row written, for the specs — never for control flow.\n */\nexport async function recordStorefrontTax(\n type: string,\n object: any,\n): Promise<StorefrontTaxRow | null> {\n try {\n // A DIRECT-charge sale is the seller's own: the seller collected the tax\n // against their own registrations and files it. It is not a facilitated\n // sale and has no place in Aglyn's return.\n if (isDirectChargeObject(object)) return null\n const metadataType = metadataTypeOf(object)\n const hostId = hostIdOf(object)\n if (!hostId) return null\n\n let kind: 'session' | 'invoice'\n let taxSource = object\n let manualTaxCents = 0\n if (\n type === 'checkout.session.completed' &&\n SESSION_TYPES.has(metadataType) &&\n object?.payment_status === 'paid'\n ) {\n kind = 'session'\n // The manual tax rides as an ordinary `line_items[1]` Stripe is never\n // told is tax (AGL-1711), so the session's own metadata snapshot is the\n // only witness to it. A cart session carries no such line at all.\n manualTaxCents = Math.max(0, Number(object?.metadata?.taxCents ?? 0)) || 0\n // Expanded whenever Stripe COMPUTED tax on this session — which since\n // AGL-1953 includes a `manual`-mode cart or draft order, where the tax\n // rides a real Tax Rate and Stripe therefore states a `taxable_amount`\n // for it. Gated on the delivered `amount_tax` rather than done\n // unconditionally so the buy-now and POS constructions, which report 0\n // there and answer from metadata, still cost no extra Stripe read.\n const stripeStatedTax = Number(\n object?.total_details?.amount_tax ?? 0,\n )\n if (\n object?.automatic_tax?.enabled === true ||\n (Number.isFinite(stripeStatedTax) && stripeStatedTax > 0)\n ) {\n taxSource = (await expandedSession(String(object?.id ?? ''))) ?? object\n }\n } else if (\n (type === 'invoice.paid' || type === 'invoice.payment_succeeded') &&\n metadataType === 'commerce-subscription'\n ) {\n // Every cycle including the opening one. The subscription's own\n // `checkout.session.completed` is NOT a second source — recording both\n // would count the opening sale twice (AGL-1811's rule, same reason).\n kind = 'invoice'\n } else {\n return null\n }\n\n const row = storefrontTaxRow(taxSource, { kind, hostId, manualTaxCents })\n if (!row) return null\n // Nothing to file and nothing to explain: no tax computed, no tax charged.\n // A `stripe-automatic` row is kept even at zero tax — that a Stripe Tax\n // sale answered \"not collecting\" is itself the audit answer to why a\n // jurisdiction is absent from the return.\n //\n // EXCEPT where the absence is AGLYN'S decision rather than the merchant's\n // (AGL-2000). A zero-tax commerce sale means the merchant configured no\n // tax — their call, their liability, nothing here to explain. A booking or\n // a reservation is untaxed because THIS CODEBASE decided not to compute a\n // goods rate on a service or a room (`bookings/server.ts`, `reserve.ts`),\n // and that is exactly the kind of absence somebody has to be able to find\n // later: it is the platform answering a tax question on a merchant's\n // revenue. Dropping those rows made the decision invisible in the one\n // place anyone would go looking for it.\n if (row.taxMode === 'none' && !PLATFORM_UNTAXED_TYPES.has(metadataType)) {\n return null\n }\n\n const documentId = String(object?.id ?? '')\n if (!documentId) return null\n const orgId = (await getOrgForHost(hostId).catch(() => null))?.orgId ?? null\n await firebaseAdmin\n .app()\n .firestore()\n .collection('storefrontTaxCollected')\n .doc(documentId)\n .set(\n {\n ...row,\n orgId,\n recordedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n // Keyed by the Stripe object id and merged, so a redelivery — and the\n // `invoice.paid` / `invoice.payment_succeeded` pair Stripe sends for\n // ONE payment — restamps a single document instead of duplicating a\n // taxable sale.\n { merge: true },\n )\n return row\n } catch (error) {\n console.error('[AGL-1904] storefront tax recording failed', error)\n return null\n }\n}\n"],"names":["isDirectChargeObject","firebaseAdmin","getOrgForHost","storefrontTaxRow","SESSION_TYPES","Set","PLATFORM_UNTAXED_TYPES","stripeKey","process","String","env","STRIPE_SECRET_KEY","expandedSession","sessionId","key","response","fetch","encodeURIComponent","headers","Authorization","ok","body","json","catch","id","hostIdOf","object","metadata","hostId","subscription_details","parent","metadataTypeOf","type","recordStorefrontTax","metadataType","kind","taxSource","manualTaxCents","has","payment_status","Math","max","Number","taxCents","stripeStatedTax","total_details","amount_tax","automatic_tax","enabled","isFinite","row","taxMode","documentId","orgId","app","firestore","collection","doc","set","recordedAt","FieldValue","serverTimestamp","merge","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,gBAAgB,QAA+B,sBAAkB;AAE1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GAED,0EAA0E,GAC1E,MAAMC,gBAAgB,IAAIC,IAAI;IAC5B;IACA;IACA;IACA;IACA,mEAAmE;IACnE,0EAA0E;IAC1E,2EAA2E;IAC3E,sEAAsE;IACtE,6DAA6D;IAC7D,gEAAgE;IAChE;CACD;AAED;;;;;CAKC,GACD,MAAMC,yBAAyB,IAAID,IAAI;IAAC;IAAmB;CAAuB;AAElF,SAASE;QACOC;IAAd,OAAOC,QAAOD,iCAAAA,QAAQE,GAAG,CAACC,iBAAiB,YAA7BH,iCAAiC;AACjD;AAEA;;;;;;;;;CASC,GACD,eAAeI,gBAAgBC,SAAiB;IAC9C,MAAMC,MAAMP;IACZ,IAAI,CAACO,OAAO,CAACD,WAAW,OAAO;IAC/B,IAAI;QACF,MAAME,WAAW,MAAMC,MACrB,CAAC,4CAA4C,EAAEC,mB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QAAe;QACvE,IAAI,CAACa,KAAK,OAAO;QACjB,2EAA2E;QAC3E,wEAAwE;QACxE,qEAAqE;QACrE,0CAA0C;QAC1C,EAAE;QACF,0EAA0E;QAC1E,wEAAwE;QACxE,2EAA2E;QAC3E,0EAA0E;QAC1E,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,sEAAsE;QACtE,wCAAwC;QACxC,IAAIA,IAAIC,OAAO,KAAK,UAAU,CAAC7C,uBAAuBgC,GAAG,CAACJ,eAAe;YACvE,OAAO;QACT;QAEA,MAAMkB,aAAa3C,eAAOiB,0BAAAA,OAAQF,EAAE,mBAAI;QACxC,IAAI,CAAC4B,YAAY,OAAO;QACxB,MAAMC,kBAAS,QAAA,MAAMnD,cAAc0B,QAAQL,KAAK,CAAC,IAAM,0BAAzC,AAAC,MAAgD8B,KAAK,oBAAI;QACxE,MAAMpD,cACHqD,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,0BACXC,GAAG,CAACL,YACJM,GAAG,CACF,aACKR;YACHG;YACAM,YAAY1D,cAAcsD,SAAS,CAACK,UAAU,CAACC,eAAe;YAEhE,sEAAsE;QACtE,qEAAqE;QACrE,oEAAoE;QACpE,gBAAgB;QAChB;YAAEC,OAAO;QAAK;QAElB,OAAOZ;IACT,EAAE,OAAOa,OAAO;QACdC,QAAQD,KAAK,CAAC,8CAA8CA;QAC5D,OAAO;IACT;AACF"}
@@ -89,6 +89,17 @@
89
89
  * and must be re-read with `expand[]=total_details.breakdown`; an invoice
90
90
  * carries `total_taxes[]` inline. Both land in the same `taxLines` shape.
91
91
  *
92
+ * ## A DIRECT charge is the seller's tax, never the platform's
93
+ *
94
+ * A seller on its own full Stripe account sells by DIRECT charge: the session
95
+ * is created ON the seller's account (`Stripe-Account` header) and stamped
96
+ * `metadata[chargeModel]=direct`. Stripe Tax on it computes against the
97
+ * SELLER's registrations, the tax settles into the seller's balance, and the
98
+ * seller remits it. Stripe still reports `liability: { type: "self" }`, but
99
+ * `self` is then the seller's account, so reading `self` as "the platform"
100
+ * would book the seller's tax as Aglyn's. A direct sale's Stripe Tax is
101
+ * therefore always `connected-account` here, whatever the field says.
102
+ *
92
103
  * Pure and total: unreadable input answers `null`, never throws — a recording
93
104
  * failure must never 500 a webhook into redelivery.
94
105
  */
@@ -105,8 +116,9 @@ export type { StorefrontTaxMode };
105
116
  /**
106
117
  * Whose registrations Stripe Tax computed against, from
107
118
  * `automatic_tax.liability.type`: `self` (the account the object lives on,
108
- * i.e. Aglyn's platform) or `account` (a named connected account).
109
- * Null whenever `taxMode` is not `stripe-automatic`.
119
+ * i.e. Aglyn's platform) or `account` (a named connected account). A DIRECT
120
+ * charge lives on the seller's account, so it is always `connected-account`
121
+ * (see the module note). Null whenever `taxMode` is not `stripe-automatic`.
110
122
  */
111
123
  export type StorefrontTaxLiability = 'platform' | 'connected-account';
112
124
  /** One entry of the stored tax breakdown. */
@@ -166,6 +178,11 @@ export declare function stripeTaxBreakdownLines(source: any): StorefrontTaxLine[
166
178
  export interface StorefrontTaxContext {
167
179
  kind: 'session' | 'invoice';
168
180
  hostId: string;
181
+ /**
182
+ * The seller's account for a DIRECT charge, which names no transfer
183
+ * destination: the event's `account`, when the caller has it.
184
+ */
185
+ connectedAccountId?: string | null;
169
186
  /**
170
187
  * The manual-mode tax `checkout.ts` puts over as an ordinary line item.
171
188
  * Stripe is never told it is tax, so no Stripe field carries it and the
@@ -200,6 +217,20 @@ export declare function resolveStorefrontTax(object: unknown, manualTaxCents?: n
200
217
  * is the same answer the filed tax record gives for the same object.
201
218
  */
202
219
  export declare function storefrontTaxModeOf(object: unknown, manualTaxCents?: number): StorefrontTaxMode;
220
+ /**
221
+ * Whether a session, subscription or invoice was sold as a DIRECT charge on
222
+ * the seller's own account, from the `chargeModel` stamp the session doors
223
+ * write (an invoice carries its subscription's under `subscription_details`).
224
+ */
225
+ export declare function storefrontSaleIsDirect(object: unknown): boolean;
226
+ /**
227
+ * Who owns, and remits, the tax a storefront sale carried: the SELLER for
228
+ * any merchant-configured rate and for every direct charge, and the PLATFORM
229
+ * only for Stripe Tax computed on Aglyn's own account. `none` when no tax was
230
+ * charged. The single answer a summary or a return should read rather than
231
+ * re-deriving it from the liability field.
232
+ */
233
+ export declare function storefrontTaxOwner(object: unknown, manualTaxCents?: number): 'platform' | 'seller' | 'none';
203
234
  /**
204
235
  * Decomposes a paid storefront session or invoice into the stored row, or
205
236
  * `null` when there is no host to attribute it to.
@@ -88,6 +88,17 @@
88
88
  * and must be re-read with `expand[]=total_details.breakdown`; an invoice
89
89
  * carries `total_taxes[]` inline. Both land in the same `taxLines` shape.
90
90
  *
91
+ * ## A DIRECT charge is the seller's tax, never the platform's
92
+ *
93
+ * A seller on its own full Stripe account sells by DIRECT charge: the session
94
+ * is created ON the seller's account (`Stripe-Account` header) and stamped
95
+ * `metadata[chargeModel]=direct`. Stripe Tax on it computes against the
96
+ * SELLER's registrations, the tax settles into the seller's balance, and the
97
+ * seller remits it. Stripe still reports `liability: { type: "self" }`, but
98
+ * `self` is then the seller's account, so reading `self` as "the platform"
99
+ * would book the seller's tax as Aglyn's. A direct sale's Stripe Tax is
100
+ * therefore always `connected-account` here, whatever the field says.
101
+ *
91
102
  * Pure and total: unreadable input answers `null`, never throws — a recording
92
103
  * failure must never 500 a webhook into redelivery.
93
104
  */ import { storefrontTaxMode } from "../model/commerce-tax-decision.js";
@@ -205,6 +216,30 @@ function taxLines(source) {
205
216
  */ export function storefrontTaxModeOf(object, manualTaxCents = 0) {
206
217
  return resolveStorefrontTax(object, manualTaxCents).taxMode;
207
218
  }
219
+ /**
220
+ * Whether a session, subscription or invoice was sold as a DIRECT charge on
221
+ * the seller's own account, from the `chargeModel` stamp the session doors
222
+ * write (an invoice carries its subscription's under `subscription_details`).
223
+ */ export function storefrontSaleIsDirect(object) {
224
+ var _ref, _ref1;
225
+ var _source_metadata, _source_subscription_details_metadata, _source_subscription_details, _source_parent_subscription_details_metadata, _source_parent_subscription_details, _source_parent;
226
+ const source = object;
227
+ return ((_ref = (_ref1 = source == null ? void 0 : (_source_metadata = source.metadata) == null ? void 0 : _source_metadata.chargeModel) != null ? _ref1 : source == null ? void 0 : (_source_subscription_details = source.subscription_details) == null ? void 0 : (_source_subscription_details_metadata = _source_subscription_details.metadata) == null ? void 0 : _source_subscription_details_metadata.chargeModel) != null ? _ref : source == null ? void 0 : (_source_parent = source.parent) == null ? void 0 : (_source_parent_subscription_details = _source_parent.subscription_details) == null ? void 0 : (_source_parent_subscription_details_metadata = _source_parent_subscription_details.metadata) == null ? void 0 : _source_parent_subscription_details_metadata.chargeModel) === 'direct';
228
+ }
229
+ /**
230
+ * Who owns, and remits, the tax a storefront sale carried: the SELLER for
231
+ * any merchant-configured rate and for every direct charge, and the PLATFORM
232
+ * only for Stripe Tax computed on Aglyn's own account. `none` when no tax was
233
+ * charged. The single answer a summary or a return should read rather than
234
+ * re-deriving it from the liability field.
235
+ */ export function storefrontTaxOwner(object, manualTaxCents = 0) {
236
+ var _object_automatic_tax_liability, _object_automatic_tax;
237
+ const { automatic, taxMode } = resolveStorefrontTax(object, manualTaxCents);
238
+ if (taxMode === 'none') return 'none';
239
+ if (!automatic || storefrontSaleIsDirect(object)) return 'seller';
240
+ const liabilityType = asStringOrNull(object == null ? void 0 : (_object_automatic_tax = object.automatic_tax) == null ? void 0 : (_object_automatic_tax_liability = _object_automatic_tax.liability) == null ? void 0 : _object_automatic_tax_liability.type);
241
+ return liabilityType === 'account' ? 'seller' : 'platform';
242
+ }
208
243
  /**
209
244
  * Decomposes a paid storefront session or invoice into the stored row, or
210
245
  * `null` when there is no host to attribute it to.
@@ -212,14 +247,15 @@ function taxLines(source) {
212
247
  * The caller decides WHICH objects reach this — the commerce webhook
213
248
  * self-selects on `metadata.type`, exactly as every other section does.
214
249
  */ export function storefrontTaxRow(object, context) {
215
- var _ref, _ref1, _ref2, _asStringOrNull, _asStringOrNull1, _asStringOrNull2, _address, _asDate;
250
+ var _ref, _ref1, _ref2, _asStringOrNull, _ref3, _asStringOrNull1, _asStringOrNull2, _address, _asDate;
216
251
  var _source_automatic_tax_liability, _source_automatic_tax, _source_payment_intent_data_transfer_data, _source_payment_intent_data, _source_transfer_data, _source_metadata, _source_subscription_details_metadata, _source_subscription_details, _source_parent_subscription_details_metadata, _source_parent_subscription_details, _source_parent, _source_customer_details, _source_status_transitions;
217
252
  const source = object;
218
253
  const hostId = String((_ref = context == null ? void 0 : context.hostId) != null ? _ref : '');
219
254
  if (!hostId) return null;
220
255
  const { automatic, lines, taxCents, taxMode } = resolveStorefrontTax(source, context == null ? void 0 : context.manualTaxCents);
221
256
  const liabilityType = asStringOrNull(source == null ? void 0 : (_source_automatic_tax = source.automatic_tax) == null ? void 0 : (_source_automatic_tax_liability = _source_automatic_tax.liability) == null ? void 0 : _source_automatic_tax_liability.type);
222
- const taxLiability = !automatic ? null : liabilityType === 'account' ? 'connected-account' : // older API versions, where the only account a session could be
257
+ const direct = storefrontSaleIsDirect(source);
258
+ const taxLiability = !automatic ? null : direct || liabilityType === 'account' ? 'connected-account' : // older API versions, where the only account a session could be
223
259
  // liable under is the one it was created on — the platform.
224
260
  'platform';
225
261
  const grossCents = asCents(context.kind === 'invoice' ? source == null ? void 0 : source.amount_paid : source == null ? void 0 : source.amount_total);
@@ -230,7 +266,7 @@ function taxLines(source) {
230
266
  metadataType: (_ref2 = (_asStringOrNull = asStringOrNull(source == null ? void 0 : (_source_metadata = source.metadata) == null ? void 0 : _source_metadata.type)) != null ? _asStringOrNull : asStringOrNull(source == null ? void 0 : (_source_subscription_details = source.subscription_details) == null ? void 0 : (_source_subscription_details_metadata = _source_subscription_details.metadata) == null ? void 0 : _source_subscription_details_metadata.type)) != null ? _ref2 : asStringOrNull(source == null ? void 0 : (_source_parent = source.parent) == null ? void 0 : (_source_parent_subscription_details = _source_parent.subscription_details) == null ? void 0 : (_source_parent_subscription_details_metadata = _source_parent_subscription_details.metadata) == null ? void 0 : _source_parent_subscription_details_metadata.type),
231
267
  taxMode,
232
268
  taxLiability,
233
- connectedAccountId: (_asStringOrNull1 = asStringOrNull(transferDestination)) != null ? _asStringOrNull1 : asStringOrNull(transferDestination == null ? void 0 : transferDestination.id),
269
+ connectedAccountId: (_ref3 = (_asStringOrNull1 = asStringOrNull(transferDestination)) != null ? _asStringOrNull1 : asStringOrNull(transferDestination == null ? void 0 : transferDestination.id)) != null ? _ref3 : direct ? asStringOrNull(context == null ? void 0 : context.connectedAccountId) : null,
234
270
  grossCents,
235
271
  taxCents,
236
272
  netCents: grossCents - taxCents,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/storefront-tax.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\n/**\n * What a storefront sale's TAX decomposes to (AGL-1904) — the record that\n * makes tax collected on a merchant's sale visible to Aglyn's own return.\n *\n * ## The observation this module exists to record\n *\n * Every storefront checkout — cart, buy-now, subscription — creates its\n * Checkout Session on the PLATFORM account: platform secret key, no\n * `Stripe-Account` header, no `on_behalf_of`, with\n * `payment_intent_data[transfer_data][destination]` pointing at the merchant's\n * connected account. `cart-checkout.ts` and `checkout.ts` then set\n * `automatic_tax[enabled]` when the store's tax mode is `stripe`.\n *\n * That was long suspected to mean Stripe Tax computes the shopper's tax\n * against AGLYN's registrations rather than the merchant's. It was MEASURED on\n * 2026-08-18, in test mode, as a two-arm experiment on exactly that session\n * shape (a $100 line, a Texas shopper address, `transfer_data[destination]`\n * set):\n *\n * - **Platform unregistered, destination connected account registered in\n * TX** → `amount_tax: 0`, one breakdown line with\n * `taxability_reason: \"not_collecting\"`, `taxable_amount: 0`.\n * - **Platform registered in TX, everything else byte-identical** →\n * `amount_tax: 825`, `taxability_reason: \"standard_rated\"`,\n * `taxable_amount: 10000`, rate 8.25% \"Texas\".\n *\n * Both sessions reported `automatic_tax.liability: { type: \"self\" }` — Stripe's\n * own word for \"the account this session was created on is the one liable\".\n * `transfer_data[destination]` had no effect on tax in either arm.\n *\n * So on a `mode: 'stripe'` store the tax charged to the shopper is computed on\n * Aglyn's registration footprint, lands in Aglyn's platform balance, and is\n * Aglyn's to remit. The live platform account has held an ACTIVE Texas state\n * sales tax registration since 2026-08-17, so this is not hypothetical.\n *\n * **This module describes that mechanism and records the money.** Aglyn IS a\n * marketplace facilitator for storefront sales, and the published Terms say so\n * at §10.7 (AGL-1956). Facilitator status still attaches by operation of\n * law rather than by our say-so, and §10.7 is deliberately narrow — Aglyn\n * collects and remits **where applicable law gives it an obligation**, not\n * universally — so this module still records the mechanism per sale and does\n * not stamp a per-merchant or per-jurisdiction verdict on any row.\n *\n * ## The two store modes are DIFFERENT FACTS and must never be summed\n *\n * `taxMode` is the whole point of this record, and it is derived from\n * `automatic_tax.enabled` — **never** from whether tax lines are present:\n *\n * - **`stripe-automatic`** — Stripe Tax computed it, against whichever\n * account `automatic_tax.liability` names. When that is `platform`, the\n * money is held under Aglyn's registration.\n * - **`manual`** — the merchant's own configured rate\n * (`checkout.ts` / `pos-order.ts`), applied to the merchant's own declared\n * origin. Aglyn's registrations never enter into it and the amount is not\n * Aglyn's to remit.\n *\n * The trap that makes the `automatic_tax.enabled` discriminator load-bearing:\n * a MANUAL-mode subscription renewal carries a real Stripe Tax Rate (AGL-1751\n * attaches one so the tax recurs), so its invoice arrives with a populated\n * `total_taxes[]` — indistinguishable from a Stripe Tax invoice if you look at\n * the tax lines. Summing tax lines would silently book merchant-configured tax\n * as Aglyn-collected. **Read the flag, not the lines.**\n *\n * ## The taxable base is kept, never inferred\n *\n * `taxable_amount` is what a return reports as \"taxable sales\". Deriving it as\n * `amount ÷ rate` needs a live read to resolve the rate id and rounds wrong at\n * the edges, so it is stored when Stripe states it and left `null` when it\n * does not — and a row whose base cannot be read is COUNTED OUT LOUD by the\n * return rather than treated as a zero-base sale.\n *\n * A Checkout Session's `total_details.breakdown` is not in the webhook payload\n * and must be re-read with `expand[]=total_details.breakdown`; an invoice\n * carries `total_taxes[]` inline. Both land in the same `taxLines` shape.\n *\n * Pure and total: unreadable input answers `null`, never throws — a recording\n * failure must never 500 a webhook into redelivery.\n */\n\nimport {\n storefrontTaxMode,\n type StorefrontTaxMode,\n} from '../model/commerce-tax-decision'\n\n/**\n * Which machinery produced the tax on this sale. See the module note.\n *\n * The union and its derivation live in the MODEL since AGL-2451, because the\n * merchant's order document now carries the same fact (`HostOrder.taxMode`)\n * and two copies of a rule that must agree are one copy too many. Re-exported\n * here so this module stays the place the mechanism is documented.\n */\nexport type { StorefrontTaxMode }\n\n/**\n * Whose registrations Stripe Tax computed against, from\n * `automatic_tax.liability.type`: `self` (the account the object lives on,\n * i.e. Aglyn's platform) or `account` (a named connected account).\n * Null whenever `taxMode` is not `stripe-automatic`.\n */\nexport type StorefrontTaxLiability = 'platform' | 'connected-account'\n\n/** One entry of the stored tax breakdown. */\nexport interface StorefrontTaxLine {\n amountCents: number\n /** Stripe's stated reason, e.g. `standard_rated`, `not_collecting`. */\n taxabilityReason: string | null\n taxRateId: string | null\n /** Stripe's `taxable_amount`; null when the shape did not carry it. */\n taxableAmountCents: number | null\n /** e.g. `Texas` — from the expanded rate, for the working papers. */\n jurisdiction: string | null\n /** The rate's own state code, which is not the shopper's address. */\n rateState: string | null\n percentage: number | null\n}\n\n/** The per-transaction record `storefrontTaxCollected/{stripeId}` stores. */\nexport interface StorefrontTaxRow {\n /** `session` for one-time sales, `invoice` for subscription cycles. */\n kind: 'session' | 'invoice'\n hostId: string\n /** The commerce path — `commerce-cart`, `commerce-order`, … */\n metadataType: string | null\n taxMode: StorefrontTaxMode\n taxLiability: StorefrontTaxLiability | null\n /** The merchant's connected account, when the object names one. */\n connectedAccountId: string | null\n /** What the shopper actually paid, tax included. */\n grossCents: number\n taxCents: number\n /** Gross minus tax. NOT Aglyn's revenue — most of it is the merchant's. */\n netCents: number\n currency: string\n /** The jurisdiction input — the shopper's address on the Stripe object. */\n customerAddress: {\n country: string | null\n state: string | null\n city: string | null\n postalCode: string | null\n } | null\n taxLines: StorefrontTaxLine[]\n paidAt: Date | null\n}\n\nfunction asCents(value: unknown): number {\n const cents = Number(value ?? 0)\n return Number.isFinite(cents) ? Math.round(cents) : 0\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n return typeof value === 'string' && value ? value : null\n}\n\nfunction asNumberOrNull(value: unknown): number | null {\n const parsed = Number(value ?? NaN)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/** Seconds-since-epoch to Date, or null for anything unreadable. */\nfunction asDate(value: unknown): Date | null {\n const seconds = Number(value ?? NaN)\n return Number.isFinite(seconds) && seconds > 0\n ? new Date(seconds * 1000)\n : null\n}\n\nfunction address(source: any): StorefrontTaxRow['customerAddress'] {\n if (!source || typeof source !== 'object') return null\n return {\n country: asStringOrNull(source.country),\n state: asStringOrNull(source.state),\n city: asStringOrNull(source.city),\n postalCode: asStringOrNull(source.postal_code),\n }\n}\n\n/**\n * The breakdown entries, from either shape.\n *\n * A Checkout Session expands them under `total_details.breakdown.taxes[]`\n * with the rate object inline; an invoice carries `total_taxes[]` (rate under\n * `tax_rate_details.tax_rate`) or the older `total_tax_amounts[]` (`tax_rate`,\n * an id or an expanded object). All three map onto one stored line.\n *\n * Exported for the POS hardware shop's own sales (AGL-4038), whose tax rows\n * keep the same lines: one reading of Stripe's breakdown for every half of\n * the return.\n */\nexport function stripeTaxBreakdownLines(source: any): StorefrontTaxLine[] {\n return taxLines(source)\n}\n\nfunction taxLines(source: any): StorefrontTaxLine[] {\n const entries: any[] = Array.isArray(source?.total_details?.breakdown?.taxes)\n ? source.total_details.breakdown.taxes\n : Array.isArray(source?.total_taxes)\n ? source.total_taxes\n : Array.isArray(source?.total_tax_amounts)\n ? source.total_tax_amounts\n : []\n return entries.map((entry: any) => {\n const rate = entry?.rate ?? entry?.tax_rate_details?.tax_rate ?? entry?.tax_rate\n const rateObject = rate && typeof rate === 'object' ? rate : null\n // Distinguish an absent `taxable_amount` from a genuine zero: a zero base\n // is a real fact (`not_collecting`), an absent one means the base is\n // UNKNOWN, and the return has to be able to tell those apart.\n const taxableAmount = Number(entry?.taxable_amount ?? NaN)\n return {\n amountCents: asCents(entry?.amount),\n taxabilityReason: asStringOrNull(entry?.taxability_reason),\n taxRateId: asStringOrNull(rate) ?? asStringOrNull(rateObject?.id),\n taxableAmountCents: Number.isFinite(taxableAmount)\n ? Math.round(taxableAmount)\n : null,\n jurisdiction: asStringOrNull(rateObject?.jurisdiction),\n rateState: asStringOrNull(rateObject?.state),\n percentage:\n asNumberOrNull(rateObject?.effective_percentage) ??\n asNumberOrNull(rateObject?.percentage),\n }\n })\n}\n\n/** Sum of the stored lines' amounts. */\nfunction sumLines(lines: readonly StorefrontTaxLine[]): number {\n return lines.reduce((sum, line) => sum + line.amountCents, 0)\n}\n\nexport interface StorefrontTaxContext {\n kind: 'session' | 'invoice'\n hostId: string\n /**\n * The manual-mode tax `checkout.ts` puts over as an ordinary line item.\n * Stripe is never told it is tax, so no Stripe field carries it and the\n * session's own `metadata[taxCents]` is the only witness (AGL-1711).\n */\n manualTaxCents?: number\n}\n\n/** What one Stripe object says about the tax it carried. */\nexport interface ResolvedStorefrontTax {\n /** `automatic_tax.enabled` — the discriminator, never the tax lines. */\n automatic: boolean\n /** Stripe's own breakdown, present only on a `stripe-automatic` sale. */\n lines: StorefrontTaxLine[]\n taxCents: number\n taxMode: StorefrontTaxMode\n}\n\n/**\n * Reads the tax off one paid session or invoice — the SINGLE derivation, and\n * the reason it is its own exported function (AGL-2451).\n *\n * `storefrontTaxRow` builds the `storefrontTaxCollected` record from it, and\n * the four order-writing doors in `billing-webhook.ts` stamp `HostOrder.taxMode`\n * from it, so an order and the row filed for the same Stripe id cannot state\n * different regimes. Re-deriving the mode beside a second reading of the same\n * object is exactly how the two would drift.\n *\n * Pure and total: unreadable input answers `taxMode: 'none'`, never throws.\n */\nexport function resolveStorefrontTax(\n object: unknown,\n manualTaxCents = 0,\n): ResolvedStorefrontTax {\n const source = object as any\n const automatic = source?.automatic_tax?.enabled === true\n const lines = automatic ? taxLines(source) : []\n const manualCents = Math.max(0, asCents(manualTaxCents))\n // The flag, never the lines — see the module note. A manual-mode\n // subscription renewal carries real Stripe tax rates in `total_taxes[]`,\n // and booking those as Aglyn-collected would be the whole defect restated.\n //\n // Read on SESSIONS as well as invoices since AGL-1953: the cart and\n // draft-order paths now carry their manual tax as a real Stripe Tax Rate on\n // the line (the construction that survives a session-level coupon), so a\n // manual session reports a genuine `total_details.amount_tax`. The scalar is\n // the fallback because `total_details.breakdown` is expandable and absent\n // unless the recorder re-read it. Buy-now's `line_items[1]` construction\n // reports 0 in both shapes and still answers from `manualTaxCents` below.\n const manualLineCents = !automatic\n ? sumLines(taxLines(source)) ||\n asCents(source?.total_details?.amount_tax ?? source?.tax)\n : 0\n const taxCents = automatic\n ? // `total_details.amount_tax` on a session, `total_taxes[]` on an\n // invoice. Prefer the summed lines when they exist (a computed invoice\n // can send a 0/null scalar beside a populated array — AGL-1811's\n // measurement), and fall back to the scalar shapes otherwise.\n lines.length > 0\n ? sumLines(lines)\n : asCents(source?.total_details?.amount_tax ?? source?.tax)\n : Math.max(manualCents, manualLineCents)\n return {\n automatic,\n lines,\n taxCents,\n taxMode: storefrontTaxMode({ automatic, taxCents }),\n }\n}\n\n/**\n * Just the regime, for the order-writing doors (AGL-2451). Delegates, so this\n * is the same answer the filed tax record gives for the same object.\n */\nexport function storefrontTaxModeOf(\n object: unknown,\n manualTaxCents = 0,\n): StorefrontTaxMode {\n return resolveStorefrontTax(object, manualTaxCents).taxMode\n}\n\n/**\n * Decomposes a paid storefront session or invoice into the stored row, or\n * `null` when there is no host to attribute it to.\n *\n * The caller decides WHICH objects reach this — the commerce webhook\n * self-selects on `metadata.type`, exactly as every other section does.\n */\nexport function storefrontTaxRow(\n object: unknown,\n context: StorefrontTaxContext,\n): StorefrontTaxRow | null {\n const source = object as any\n const hostId = String(context?.hostId ?? '')\n if (!hostId) return null\n\n const { automatic, lines, taxCents, taxMode } = resolveStorefrontTax(\n source,\n context?.manualTaxCents,\n )\n\n const liabilityType = asStringOrNull(source?.automatic_tax?.liability?.type)\n const taxLiability: StorefrontTaxLiability | null = !automatic\n ? null\n : liabilityType === 'account'\n ? 'connected-account'\n : // `self`, and also an absent liability: Stripe omits the field on\n // older API versions, where the only account a session could be\n // liable under is the one it was created on — the platform.\n 'platform'\n\n const grossCents = asCents(\n context.kind === 'invoice' ? source?.amount_paid : source?.amount_total,\n )\n const transferDestination =\n source?.payment_intent_data?.transfer_data?.destination ??\n source?.transfer_data?.destination\n return {\n kind: context.kind,\n hostId,\n metadataType:\n asStringOrNull(source?.metadata?.type) ??\n asStringOrNull(source?.subscription_details?.metadata?.type) ??\n asStringOrNull(source?.parent?.subscription_details?.metadata?.type),\n taxMode,\n taxLiability,\n connectedAccountId:\n asStringOrNull(transferDestination) ??\n asStringOrNull((transferDestination as any)?.id),\n grossCents,\n taxCents,\n netCents: grossCents - taxCents,\n currency: asStringOrNull(source?.currency) ?? 'usd',\n customerAddress:\n address(source?.customer_details?.address) ??\n address(source?.customer_address),\n // Stripe's OWN breakdown, whenever Stripe stated one — never an invented\n // base. Buy-now's manual construction states none (Stripe was never told\n // the line was tax) and answers `[]`, which is the honest answer. The\n // cart, draft-order and subscription-renewal manual paths carry a real\n // Tax Rate, so Stripe DOES state a `taxable_amount` for them, and keeping\n // it gives `merchantManual` a real taxable-sales figure instead of a\n // permanent zero (AGL-1953). It never reaches the Aglyn-liable bucket:\n // the classification above is the flag, not these lines.\n taxLines: automatic ? lines : taxLines(source),\n paidAt:\n asDate(source?.status_transitions?.paid_at) ?? asDate(source?.created),\n }\n}\n"],"names":["storefrontTaxMode","asCents","value","cents","Number","isFinite","Math","round","asStringOrNull","asNumberOrNull","parsed","NaN","asDate","seconds","Date","address","source","country","state","city","postalCode","postal_code","stripeTaxBreakdownLines","taxLines","entries","Array","isArray","total_details","breakdown","taxes","total_taxes","total_tax_amounts","map","entry","rate","tax_rate_details","tax_rate","rateObject","taxableAmount","taxable_amount","amountCents","amount","taxabilityReason","taxability_reason","taxRateId","id","taxableAmountCents","jurisdiction","rateState","percentage","effective_percentage","sumLines","lines","reduce","sum","line","resolveStorefrontTax","object","manualTaxCents","automatic","automatic_tax","enabled","manualCents","max","manualLineCents","amount_tax","tax","taxCents","length","taxMode","storefrontTaxModeOf","storefrontTaxRow","context","hostId","String","liabilityType","liability","type","taxLiability","grossCents","kind","amount_paid","amount_total","transferDestination","payment_intent_data","transfer_data","destination","metadataType","metadata","subscription_details","parent","connectedAccountId","netCents","currency","customerAddress","customer_details","customer_address","paidAt","status_transitions","paid_at","created"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6EC,GAED,SACEA,iBAAiB,QAEZ,oCAAgC;AA+DvC,SAASC,QAAQC,KAAc;IAC7B,MAAMC,QAAQC,OAAOF,gBAAAA,QAAS;IAC9B,OAAOE,OAAOC,QAAQ,CAACF,SAASG,KAAKC,KAAK,CAACJ,SAAS;AACtD;AAEA,SAASK,eAAeN,KAAc;IACpC,OAAO,OAAOA,UAAU,YAAYA,QAAQA,QAAQ;AACtD;AAEA,SAASO,eAAeP,KAAc;IACpC,MAAMQ,SAASN,OAAOF,gBAAAA,QAASS;IAC/B,OAAOP,OAAOC,QAAQ,CAACK,UAAUA,SAAS;AAC5C;AAEA,kEAAkE,GAClE,SAASE,OAAOV,KAAc;IAC5B,MAAMW,UAAUT,OAAOF,gBAAAA,QAASS;IAChC,OAAOP,OAAOC,QAAQ,CAACQ,YAAYA,UAAU,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AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/storefront-tax.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\n/**\n * What a storefront sale's TAX decomposes to (AGL-1904) — the record that\n * makes tax collected on a merchant's sale visible to Aglyn's own return.\n *\n * ## The observation this module exists to record\n *\n * Every storefront checkout — cart, buy-now, subscription — creates its\n * Checkout Session on the PLATFORM account: platform secret key, no\n * `Stripe-Account` header, no `on_behalf_of`, with\n * `payment_intent_data[transfer_data][destination]` pointing at the merchant's\n * connected account. `cart-checkout.ts` and `checkout.ts` then set\n * `automatic_tax[enabled]` when the store's tax mode is `stripe`.\n *\n * That was long suspected to mean Stripe Tax computes the shopper's tax\n * against AGLYN's registrations rather than the merchant's. It was MEASURED on\n * 2026-08-18, in test mode, as a two-arm experiment on exactly that session\n * shape (a $100 line, a Texas shopper address, `transfer_data[destination]`\n * set):\n *\n * - **Platform unregistered, destination connected account registered in\n * TX** → `amount_tax: 0`, one breakdown line with\n * `taxability_reason: \"not_collecting\"`, `taxable_amount: 0`.\n * - **Platform registered in TX, everything else byte-identical** →\n * `amount_tax: 825`, `taxability_reason: \"standard_rated\"`,\n * `taxable_amount: 10000`, rate 8.25% \"Texas\".\n *\n * Both sessions reported `automatic_tax.liability: { type: \"self\" }` — Stripe's\n * own word for \"the account this session was created on is the one liable\".\n * `transfer_data[destination]` had no effect on tax in either arm.\n *\n * So on a `mode: 'stripe'` store the tax charged to the shopper is computed on\n * Aglyn's registration footprint, lands in Aglyn's platform balance, and is\n * Aglyn's to remit. The live platform account has held an ACTIVE Texas state\n * sales tax registration since 2026-08-17, so this is not hypothetical.\n *\n * **This module describes that mechanism and records the money.** Aglyn IS a\n * marketplace facilitator for storefront sales, and the published Terms say so\n * at §10.7 (AGL-1956). Facilitator status still attaches by operation of\n * law rather than by our say-so, and §10.7 is deliberately narrow — Aglyn\n * collects and remits **where applicable law gives it an obligation**, not\n * universally — so this module still records the mechanism per sale and does\n * not stamp a per-merchant or per-jurisdiction verdict on any row.\n *\n * ## The two store modes are DIFFERENT FACTS and must never be summed\n *\n * `taxMode` is the whole point of this record, and it is derived from\n * `automatic_tax.enabled` — **never** from whether tax lines are present:\n *\n * - **`stripe-automatic`** — Stripe Tax computed it, against whichever\n * account `automatic_tax.liability` names. When that is `platform`, the\n * money is held under Aglyn's registration.\n * - **`manual`** — the merchant's own configured rate\n * (`checkout.ts` / `pos-order.ts`), applied to the merchant's own declared\n * origin. Aglyn's registrations never enter into it and the amount is not\n * Aglyn's to remit.\n *\n * The trap that makes the `automatic_tax.enabled` discriminator load-bearing:\n * a MANUAL-mode subscription renewal carries a real Stripe Tax Rate (AGL-1751\n * attaches one so the tax recurs), so its invoice arrives with a populated\n * `total_taxes[]` — indistinguishable from a Stripe Tax invoice if you look at\n * the tax lines. Summing tax lines would silently book merchant-configured tax\n * as Aglyn-collected. **Read the flag, not the lines.**\n *\n * ## The taxable base is kept, never inferred\n *\n * `taxable_amount` is what a return reports as \"taxable sales\". Deriving it as\n * `amount ÷ rate` needs a live read to resolve the rate id and rounds wrong at\n * the edges, so it is stored when Stripe states it and left `null` when it\n * does not — and a row whose base cannot be read is COUNTED OUT LOUD by the\n * return rather than treated as a zero-base sale.\n *\n * A Checkout Session's `total_details.breakdown` is not in the webhook payload\n * and must be re-read with `expand[]=total_details.breakdown`; an invoice\n * carries `total_taxes[]` inline. Both land in the same `taxLines` shape.\n *\n * ## A DIRECT charge is the seller's tax, never the platform's\n *\n * A seller on its own full Stripe account sells by DIRECT charge: the session\n * is created ON the seller's account (`Stripe-Account` header) and stamped\n * `metadata[chargeModel]=direct`. Stripe Tax on it computes against the\n * SELLER's registrations, the tax settles into the seller's balance, and the\n * seller remits it. Stripe still reports `liability: { type: \"self\" }`, but\n * `self` is then the seller's account, so reading `self` as \"the platform\"\n * would book the seller's tax as Aglyn's. A direct sale's Stripe Tax is\n * therefore always `connected-account` here, whatever the field says.\n *\n * Pure and total: unreadable input answers `null`, never throws — a recording\n * failure must never 500 a webhook into redelivery.\n */\n\nimport {\n storefrontTaxMode,\n type StorefrontTaxMode,\n} from '../model/commerce-tax-decision'\n\n/**\n * Which machinery produced the tax on this sale. See the module note.\n *\n * The union and its derivation live in the MODEL since AGL-2451, because the\n * merchant's order document now carries the same fact (`HostOrder.taxMode`)\n * and two copies of a rule that must agree are one copy too many. Re-exported\n * here so this module stays the place the mechanism is documented.\n */\nexport type { StorefrontTaxMode }\n\n/**\n * Whose registrations Stripe Tax computed against, from\n * `automatic_tax.liability.type`: `self` (the account the object lives on,\n * i.e. Aglyn's platform) or `account` (a named connected account). A DIRECT\n * charge lives on the seller's account, so it is always `connected-account`\n * (see the module note). Null whenever `taxMode` is not `stripe-automatic`.\n */\nexport type StorefrontTaxLiability = 'platform' | 'connected-account'\n\n/** One entry of the stored tax breakdown. */\nexport interface StorefrontTaxLine {\n amountCents: number\n /** Stripe's stated reason, e.g. `standard_rated`, `not_collecting`. */\n taxabilityReason: string | null\n taxRateId: string | null\n /** Stripe's `taxable_amount`; null when the shape did not carry it. */\n taxableAmountCents: number | null\n /** e.g. `Texas` — from the expanded rate, for the working papers. */\n jurisdiction: string | null\n /** The rate's own state code, which is not the shopper's address. */\n rateState: string | null\n percentage: number | null\n}\n\n/** The per-transaction record `storefrontTaxCollected/{stripeId}` stores. */\nexport interface StorefrontTaxRow {\n /** `session` for one-time sales, `invoice` for subscription cycles. */\n kind: 'session' | 'invoice'\n hostId: string\n /** The commerce path — `commerce-cart`, `commerce-order`, … */\n metadataType: string | null\n taxMode: StorefrontTaxMode\n taxLiability: StorefrontTaxLiability | null\n /** The merchant's connected account, when the object names one. */\n connectedAccountId: string | null\n /** What the shopper actually paid, tax included. */\n grossCents: number\n taxCents: number\n /** Gross minus tax. NOT Aglyn's revenue — most of it is the merchant's. */\n netCents: number\n currency: string\n /** The jurisdiction input — the shopper's address on the Stripe object. */\n customerAddress: {\n country: string | null\n state: string | null\n city: string | null\n postalCode: string | null\n } | null\n taxLines: StorefrontTaxLine[]\n paidAt: Date | null\n}\n\nfunction asCents(value: unknown): number {\n const cents = Number(value ?? 0)\n return Number.isFinite(cents) ? Math.round(cents) : 0\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n return typeof value === 'string' && value ? value : null\n}\n\nfunction asNumberOrNull(value: unknown): number | null {\n const parsed = Number(value ?? NaN)\n return Number.isFinite(parsed) ? parsed : null\n}\n\n/** Seconds-since-epoch to Date, or null for anything unreadable. */\nfunction asDate(value: unknown): Date | null {\n const seconds = Number(value ?? NaN)\n return Number.isFinite(seconds) && seconds > 0\n ? new Date(seconds * 1000)\n : null\n}\n\nfunction address(source: any): StorefrontTaxRow['customerAddress'] {\n if (!source || typeof source !== 'object') return null\n return {\n country: asStringOrNull(source.country),\n state: asStringOrNull(source.state),\n city: asStringOrNull(source.city),\n postalCode: asStringOrNull(source.postal_code),\n }\n}\n\n/**\n * The breakdown entries, from either shape.\n *\n * A Checkout Session expands them under `total_details.breakdown.taxes[]`\n * with the rate object inline; an invoice carries `total_taxes[]` (rate under\n * `tax_rate_details.tax_rate`) or the older `total_tax_amounts[]` (`tax_rate`,\n * an id or an expanded object). All three map onto one stored line.\n *\n * Exported for the POS hardware shop's own sales (AGL-4038), whose tax rows\n * keep the same lines: one reading of Stripe's breakdown for every half of\n * the return.\n */\nexport function stripeTaxBreakdownLines(source: any): StorefrontTaxLine[] {\n return taxLines(source)\n}\n\nfunction taxLines(source: any): StorefrontTaxLine[] {\n const entries: any[] = Array.isArray(source?.total_details?.breakdown?.taxes)\n ? source.total_details.breakdown.taxes\n : Array.isArray(source?.total_taxes)\n ? source.total_taxes\n : Array.isArray(source?.total_tax_amounts)\n ? source.total_tax_amounts\n : []\n return entries.map((entry: any) => {\n const rate = entry?.rate ?? entry?.tax_rate_details?.tax_rate ?? entry?.tax_rate\n const rateObject = rate && typeof rate === 'object' ? rate : null\n // Distinguish an absent `taxable_amount` from a genuine zero: a zero base\n // is a real fact (`not_collecting`), an absent one means the base is\n // UNKNOWN, and the return has to be able to tell those apart.\n const taxableAmount = Number(entry?.taxable_amount ?? NaN)\n return {\n amountCents: asCents(entry?.amount),\n taxabilityReason: asStringOrNull(entry?.taxability_reason),\n taxRateId: asStringOrNull(rate) ?? asStringOrNull(rateObject?.id),\n taxableAmountCents: Number.isFinite(taxableAmount)\n ? Math.round(taxableAmount)\n : null,\n jurisdiction: asStringOrNull(rateObject?.jurisdiction),\n rateState: asStringOrNull(rateObject?.state),\n percentage:\n asNumberOrNull(rateObject?.effective_percentage) ??\n asNumberOrNull(rateObject?.percentage),\n }\n })\n}\n\n/** Sum of the stored lines' amounts. */\nfunction sumLines(lines: readonly StorefrontTaxLine[]): number {\n return lines.reduce((sum, line) => sum + line.amountCents, 0)\n}\n\nexport interface StorefrontTaxContext {\n kind: 'session' | 'invoice'\n hostId: string\n /**\n * The seller's account for a DIRECT charge, which names no transfer\n * destination: the event's `account`, when the caller has it.\n */\n connectedAccountId?: string | null\n /**\n * The manual-mode tax `checkout.ts` puts over as an ordinary line item.\n * Stripe is never told it is tax, so no Stripe field carries it and the\n * session's own `metadata[taxCents]` is the only witness (AGL-1711).\n */\n manualTaxCents?: number\n}\n\n/** What one Stripe object says about the tax it carried. */\nexport interface ResolvedStorefrontTax {\n /** `automatic_tax.enabled` — the discriminator, never the tax lines. */\n automatic: boolean\n /** Stripe's own breakdown, present only on a `stripe-automatic` sale. */\n lines: StorefrontTaxLine[]\n taxCents: number\n taxMode: StorefrontTaxMode\n}\n\n/**\n * Reads the tax off one paid session or invoice — the SINGLE derivation, and\n * the reason it is its own exported function (AGL-2451).\n *\n * `storefrontTaxRow` builds the `storefrontTaxCollected` record from it, and\n * the four order-writing doors in `billing-webhook.ts` stamp `HostOrder.taxMode`\n * from it, so an order and the row filed for the same Stripe id cannot state\n * different regimes. Re-deriving the mode beside a second reading of the same\n * object is exactly how the two would drift.\n *\n * Pure and total: unreadable input answers `taxMode: 'none'`, never throws.\n */\nexport function resolveStorefrontTax(\n object: unknown,\n manualTaxCents = 0,\n): ResolvedStorefrontTax {\n const source = object as any\n const automatic = source?.automatic_tax?.enabled === true\n const lines = automatic ? taxLines(source) : []\n const manualCents = Math.max(0, asCents(manualTaxCents))\n // The flag, never the lines — see the module note. A manual-mode\n // subscription renewal carries real Stripe tax rates in `total_taxes[]`,\n // and booking those as Aglyn-collected would be the whole defect restated.\n //\n // Read on SESSIONS as well as invoices since AGL-1953: the cart and\n // draft-order paths now carry their manual tax as a real Stripe Tax Rate on\n // the line (the construction that survives a session-level coupon), so a\n // manual session reports a genuine `total_details.amount_tax`. The scalar is\n // the fallback because `total_details.breakdown` is expandable and absent\n // unless the recorder re-read it. Buy-now's `line_items[1]` construction\n // reports 0 in both shapes and still answers from `manualTaxCents` below.\n const manualLineCents = !automatic\n ? sumLines(taxLines(source)) ||\n asCents(source?.total_details?.amount_tax ?? source?.tax)\n : 0\n const taxCents = automatic\n ? // `total_details.amount_tax` on a session, `total_taxes[]` on an\n // invoice. Prefer the summed lines when they exist (a computed invoice\n // can send a 0/null scalar beside a populated array — AGL-1811's\n // measurement), and fall back to the scalar shapes otherwise.\n lines.length > 0\n ? sumLines(lines)\n : asCents(source?.total_details?.amount_tax ?? source?.tax)\n : Math.max(manualCents, manualLineCents)\n return {\n automatic,\n lines,\n taxCents,\n taxMode: storefrontTaxMode({ automatic, taxCents }),\n }\n}\n\n/**\n * Just the regime, for the order-writing doors (AGL-2451). Delegates, so this\n * is the same answer the filed tax record gives for the same object.\n */\nexport function storefrontTaxModeOf(\n object: unknown,\n manualTaxCents = 0,\n): StorefrontTaxMode {\n return resolveStorefrontTax(object, manualTaxCents).taxMode\n}\n\n/**\n * Whether a session, subscription or invoice was sold as a DIRECT charge on\n * the seller's own account, from the `chargeModel` stamp the session doors\n * write (an invoice carries its subscription's under `subscription_details`).\n */\nexport function storefrontSaleIsDirect(object: unknown): boolean {\n const source = object as any\n return (\n (source?.metadata?.chargeModel ??\n source?.subscription_details?.metadata?.chargeModel ??\n source?.parent?.subscription_details?.metadata?.chargeModel) === 'direct'\n )\n}\n\n/**\n * Who owns, and remits, the tax a storefront sale carried: the SELLER for\n * any merchant-configured rate and for every direct charge, and the PLATFORM\n * only for Stripe Tax computed on Aglyn's own account. `none` when no tax was\n * charged. The single answer a summary or a return should read rather than\n * re-deriving it from the liability field.\n */\nexport function storefrontTaxOwner(\n object: unknown,\n manualTaxCents = 0,\n): 'platform' | 'seller' | 'none' {\n const { automatic, taxMode } = resolveStorefrontTax(object, manualTaxCents)\n if (taxMode === 'none') return 'none'\n if (!automatic || storefrontSaleIsDirect(object)) return 'seller'\n const liabilityType = asStringOrNull((object as any)?.automatic_tax?.liability?.type)\n return liabilityType === 'account' ? 'seller' : 'platform'\n}\n\n/**\n * Decomposes a paid storefront session or invoice into the stored row, or\n * `null` when there is no host to attribute it to.\n *\n * The caller decides WHICH objects reach this — the commerce webhook\n * self-selects on `metadata.type`, exactly as every other section does.\n */\nexport function storefrontTaxRow(\n object: unknown,\n context: StorefrontTaxContext,\n): StorefrontTaxRow | null {\n const source = object as any\n const hostId = String(context?.hostId ?? '')\n if (!hostId) return null\n\n const { automatic, lines, taxCents, taxMode } = resolveStorefrontTax(\n source,\n context?.manualTaxCents,\n )\n\n const liabilityType = asStringOrNull(source?.automatic_tax?.liability?.type)\n const direct = storefrontSaleIsDirect(source)\n const taxLiability: StorefrontTaxLiability | null = !automatic\n ? null\n : // A direct charge's `self` is the seller's account (module note).\n direct || liabilityType === 'account'\n ? 'connected-account'\n : // `self`, and also an absent liability: Stripe omits the field on\n // older API versions, where the only account a session could be\n // liable under is the one it was created on — the platform.\n 'platform'\n\n const grossCents = asCents(\n context.kind === 'invoice' ? source?.amount_paid : source?.amount_total,\n )\n const transferDestination =\n source?.payment_intent_data?.transfer_data?.destination ??\n source?.transfer_data?.destination\n return {\n kind: context.kind,\n hostId,\n metadataType:\n asStringOrNull(source?.metadata?.type) ??\n asStringOrNull(source?.subscription_details?.metadata?.type) ??\n asStringOrNull(source?.parent?.subscription_details?.metadata?.type),\n taxMode,\n taxLiability,\n connectedAccountId:\n asStringOrNull(transferDestination) ??\n asStringOrNull((transferDestination as any)?.id) ??\n (direct ? asStringOrNull(context?.connectedAccountId) : null),\n grossCents,\n taxCents,\n netCents: grossCents - taxCents,\n currency: asStringOrNull(source?.currency) ?? 'usd',\n customerAddress:\n address(source?.customer_details?.address) ??\n address(source?.customer_address),\n // Stripe's OWN breakdown, whenever Stripe stated one — never an invented\n // base. Buy-now's manual construction states none (Stripe was never told\n // the line was tax) and answers `[]`, which is the honest answer. The\n // cart, draft-order and subscription-renewal manual paths carry a real\n // Tax Rate, so Stripe DOES state a `taxable_amount` for them, and keeping\n // it gives `merchantManual` a real taxable-sales figure instead of a\n // permanent zero (AGL-1953). It never reaches the Aglyn-liable bucket:\n // the classification above is the flag, not these lines.\n taxLines: automatic ? lines : taxLines(source),\n paidAt:\n asDate(source?.status_transitions?.paid_at) ?? asDate(source?.created),\n }\n}\n"],"names":["storefrontTaxMode","asCents","value","cents","Number","isFinite","Math","round","asStringOrNull","asNumberOrNull","parsed","NaN","asDate","seconds","Date","address","source","country","state","city","postalCode","postal_code","stripeTaxBreakdownLines","taxLines","entries","Array","isArray","total_details","breakdown","taxes","total_taxes","total_tax_amounts","map","entry","rate","tax_rate_details","tax_rate","rateObject","taxableAmount","taxable_amount","amountCents","amount","taxabilityReason","taxability_reason","taxRateId","id","taxableAmountCents","jurisdiction","rateState","percentage","effective_percentage","sumLines","lines","reduce","sum","line","resolveStorefrontTax","object","manualTaxCents","automatic","automatic_tax","enabled","manualCents","max","manualLineCents","amount_tax","tax","taxCents","length","taxMode","storefrontTaxModeOf","storefrontSaleIsDirect","metadata","chargeModel","subscription_details","parent","storefrontTaxOwner","liabilityType","liability","type","storefrontTaxRow","context","hostId","String","direct","taxLiability","grossCents","kind","amount_paid","amount_total","transferDestination","payment_intent_data","transfer_data","destination","metadataType","connectedAccountId","netCents","currency","customerAddress","customer_details","customer_address","paidAt","status_transitions","paid_at","created"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwFC,GAED,SACEA,iBAAiB,QAEZ,oCAAgC;AAgEvC,SAASC,QAAQC,KAAc;IAC7B,MAAMC,QAAQC,OAAOF,gBAAAA,QAAS;IAC9B,OAAOE,OAAOC,QAAQ,CAACF,SAASG,KAAKC,KAAK,CAACJ,SAAS;AACtD;AAEA,SAASK,eAAeN,KAAc;IACpC,OAAO,OAAOA,UAAU,YAAYA,QAAQA,QAAQ;AACtD;AAEA,SAASO,eAAeP,KAAc;IACpC,MAAMQ,SAASN,OAAOF,gBAAAA,QAASS;IAC/B,OAAOP,OAAOC,QAAQ,CAACK,UAAUA,SAAS;AAC5C;AAEA,kEAAkE,GAClE,SAASE,OAAOV,KAAc;IAC5B,MAAMW,UAAUT,OAAOF,gBAAAA,QAASS;IAChC,OAAOP,OAAOC,QAAQ,CAACQ,YAAYA,UAAU,IACzC,IAAIC,KAAKD,UAAU,QACnB;AACN;AAEA,SAASE,QAAQC,MAAW;IAC1B,IAAI,CAACA,UAAU,OAAOA,WAAW,UAAU,OAAO;IAClD,OAAO;QACLC,SAAST,eAAeQ,OAAOC,OAAO;QACtCC,OAAOV,eAAeQ,OAAOE,KAAK;QAClCC,MAAMX,eAAeQ,OAAOG,IAAI;QAChCC,YAAYZ,eAAeQ,OAAOK,WAAW;IAC/C;AACF;AAEA;;;;;;;;;;;CAWC,GACD,O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eAAekF,gCAAflF,mBACAA,eAAgBkF,uCAAD,AAACA,oBAA6B7C,EAAE,aAD/CrC,QAEC4E,SAAS5E,eAAeyE,2BAAAA,QAASc,kBAAkB,IAAI;QAC1DT;QACAnB;QACA6B,UAAUV,aAAanB;QACvB8B,QAAQ,GAAEzF,mBAAAA,eAAeQ,0BAAAA,OAAQiF,QAAQ,aAA/BzF,mBAAoC;QAC9C0F,eAAe,GACbnF,WAAAA,QAAQC,2BAAAA,2BAAAA,OAAQmF,gBAAgB,qBAAxBnF,yBAA0BD,OAAO,aAAzCA,WACAA,QAAQC,0BAAAA,OAAQoF,gBAAgB;QAClC,yEAAyE;QACzE,yEAAyE;QACzE,sEAAsE;QACtE,uEAAuE;QACvE,0EAA0E;QAC1E,qEAAqE;QACrE,uEAAuE;QACvE,yDAAyD;QACzD7E,UAAUoC,YAAYP,QAAQ7B,SAASP;QACvCqF,MAAM,GACJzF,UAAAA,OAAOI,2BAAAA,6BAAAA,OAAQsF,kBAAkB,qBAA1BtF,2BAA4BuF,OAAO,aAA1C3F,UAA+CA,OAAOI,0BAAAA,OAAQwF,OAAO;IACzE;AACF"}
@@ -22,4 +22,6 @@ import { type PluginApiHandler } from '@aglyn/aglyn/server';
22
22
  * the server-enforced gate, a shared stream link dies within 15 minutes, and
23
23
  * the media URL behind it dies with the viewing session.
24
24
  */
25
+ /** How many "also open to" products one video product may name (AGL-4188). */
26
+ export declare const MAX_VIDEO_ACCESS_PRODUCTS = 20;
25
27
  export declare const streamHandler: PluginApiHandler;
@@ -60,7 +60,27 @@ const TTL_MS = 15 * 60 * 1000;
60
60
  * redirects to a media URL that itself expires (AGL-2814). The mint step is
61
61
  * the server-enforced gate, a shared stream link dies within 15 minutes, and
62
62
  * the media URL behind it dies with the viewing session.
63
- */ export const streamHandler = async (req, res)=>{
63
+ */ /** How many "also open to" products one video product may name (AGL-4188). */ export const MAX_VIDEO_ACCESS_PRODUCTS = 20;
64
+ /**
65
+ * May this member watch `productId`'s gated videos? Yes when they are entitled
66
+ * to the product itself, or to one of the products its merchant opened the
67
+ * videos to (`videoAccessProductIds`, AGL-4188). The list is read from the
68
+ * product document, never from the request, so a visitor cannot widen it.
69
+ */ async function memberMayWatch(hostId, email, productId) {
70
+ var _productSnapshot_data;
71
+ if (await checkMemberEntitlement(hostId, email, productId)) return true;
72
+ const productSnapshot = await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('products').doc(productId).get();
73
+ const listed = (_productSnapshot_data = productSnapshot.data()) == null ? void 0 : _productSnapshot_data.videoAccessProductIds;
74
+ if (!Array.isArray(listed)) return false;
75
+ const others = [
76
+ ...new Set(listed.filter((id)=>typeof id === 'string' && id !== '' && id !== 'any' && id !== productId))
77
+ ].slice(0, MAX_VIDEO_ACCESS_PRODUCTS);
78
+ for (const other of others){
79
+ if (await checkMemberEntitlement(hostId, email, other)) return true;
80
+ }
81
+ return false;
82
+ }
83
+ export const streamHandler = async (req, res)=>{
64
84
  var _ref, _ref1, _ref2;
65
85
  var _req_body, _req_body1, _req_body2;
66
86
  const hostId = String((_ref = req.method === 'POST' ? (_req_body = req.body) == null ? void 0 : _req_body.hostId : req.query.hostId) != null ? _ref : '');
@@ -81,7 +101,7 @@ const TTL_MS = 15 * 60 * 1000;
81
101
  const auth = await requireActiveMember(req, res, hostId, 'Sign in first');
82
102
  if (!auth) return;
83
103
  const email = String((_auth_member_get = auth.member.get('email')) != null ? _auth_member_get : '');
84
- const entitled = email && await checkMemberEntitlement(hostId, email, productId);
104
+ const entitled = email && await memberMayWatch(hostId, email, productId);
85
105
  if (!entitled) {
86
106
  return res.status(403).json({
87
107
  error: 'Not entitled'
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/stream.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 { flagLookalikeDomain } from '@aglyn/tenant-data-admin/server/hosted-page-review'\nimport {\n MEDIA_CDN_RENDITION_AUTO,\n MEDIA_CDN_RENDITION_PARAM,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport {\n firebaseAdmin,\n GATED_VIDEO_SESSION_TTL_MS,\n} from '@aglyn/tenant-data-admin'\nimport {\n createPaidMediaDeliveryIo,\n resolvePaidMediaDelivery,\n} from './paid-media-delivery'\nimport { createHmac, timingSafeEqual } from 'crypto'\nimport { requireActiveMember } from './membership'\nimport { checkMemberEntitlement } from './gate'\nimport { tokenSigningSecret } from './download'\nimport { countOffRouteServe } from './paid-media-serve-count'\n\nconst TTL_MS = 15 * 60 * 1000\n\n/**\n * Signed with the dedicated, fail-closed `TOKEN_SIGNING_SECRET` (AGL-509).\n * AGL-509 converted the download and supplier tokens but missed this call\n * site (AGL-689): the old `STRIPE_SECRET_KEY ?? 'aglyn'` key left the whole\n * payload — `stream:${hostId}:${productId}:${video}:${exp}`, all public\n * identifiers — forgeable on any deploy without the Stripe key, and the\n * short TTL bought nothing because the forger chooses `exp`.\n */\nfunction sign(hostId: string, productId: string, video: number, exp: number) {\n return createHmac('sha256', tokenSigningSecret())\n .update(`stream:${hostId}:${productId}:${video}:${exp}`)\n .digest('hex')\n .slice(0, 32)\n}\n\n/**\n * Constant-time signature compare (AGL-512, closed here by AGL-1881).\n *\n * The presented signature was compared with `!==`, which short-circuits on\n * the first differing byte — the exact defect AGL-512 closed in `download.ts`\n * and `supplier-update.ts` and missed here, one directory over. It matters\n * more on this route than it reads: the signature is a truncated HMAC over\n * values the caller already knows (`hostId`, `productId`, `video`, `exp`), so\n * a byte-at-a-time oracle recovers a token for a video the caller was never\n * entitled to, and the 15-minute TTL does not bound the attempt rate.\n *\n * Length is checked first because `timingSafeEqual` THROWS on a length\n * mismatch rather than returning false, and the expected length here is a\n * public constant (32 hex chars) — leaking it costs nothing.\n */\nfunction signatureMatches(presented: string, expected: string): boolean {\n const a = Buffer.from(String(presented ?? ''), 'utf8')\n const b = Buffer.from(String(expected ?? ''), 'utf8')\n if (a.length !== b.length) return false\n return timingSafeEqual(new Uint8Array(a), new Uint8Array(b))\n}\n\n/**\n * Gated video streaming (AGL-315). POST (member session) checks the\n * entitlement and mints a short-TTL signed URL; GET with a valid signature\n * redirects to a media URL that itself expires (AGL-2814). The mint step is\n * the server-enforced gate, a shared stream link dies within 15 minutes, and\n * the media URL behind it dies with the viewing session.\n */\nexport const streamHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(\n (req.method === 'POST' ? req.body?.hostId : req.query.hostId) ?? '',\n )\n const productId = String(\n (req.method === 'POST' ? req.body?.productId : req.query.productId) ?? '',\n )\n const video = Math.max(\n 0,\n Number(\n (req.method === 'POST' ? req.body?.video : req.query.video) ?? 0,\n ),\n )\n if (!hostId || !productId) {\n return res.status(400).json({ error: 'Missing hostId or productId' })\n }\n\n try {\n if (req.method === 'POST') {\n // Suspension gate (AGL-550): suspended members (AGL-546) cannot\n // mint stream URLs — 403'd with the session cookie cleared.\n const auth = await requireActiveMember(req, res, hostId, 'Sign in first')\n if (!auth) return\n const email = String(auth.member.get('email') ?? '')\n const entitled =\n email && (await checkMemberEntitlement(hostId, email, productId))\n if (!entitled) {\n return res.status(403).json({ error: 'Not entitled' })\n }\n const exp = Date.now() + TTL_MS\n const url =\n `/api/commerce/stream?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(productId)}&video=${video}` +\n `&exp=${exp}&sig=${sign(hostId, productId, video, exp)}`\n res.setHeader('Cache-Control', 'private, no-store')\n return res.status(200).json({ url, expiresAtMs: exp })\n }\n\n // GET: signature + expiry gate, then redirect to the media.\n const exp = Number(req.query.exp ?? 0)\n const sig = String(req.query.sig ?? '')\n if (\n !exp ||\n exp < Date.now() ||\n !signatureMatches(sig, sign(hostId, productId, video, exp))\n ) {\n return res.status(403).send('Link expired — reload the page')\n }\n const app = firebaseAdmin.app()\n const productSnapshot = await app\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .doc(productId)\n .get()\n const product = CommerceModel.liftLegacyProduct(\n (productSnapshot.data() as any) ?? {},\n )\n const file = product.gatedVideos?.[video]\n if (!file?.url) return res.status(404).send('No video')\n /**\n * The redirect lands on a link that expires (AGL-2814).\n *\n * Everything above only guards the 302. What the 302 points at is what\n * the buyer, and anyone who copies the `Location` out of the buyer's\n * network panel, keeps. So `resolvePaidMediaDelivery` hands back one of\n * three things and never a permanent URL:\n *\n * - a CDN URL signed for {@link GATED_VIDEO_SESSION_TTL_MS}, when the video\n * is a PRIVATE asset in this site's library or its org's. The CDN refuses\n * a private asset on every path without an unexpired signature.\n * - a V4 signed Storage read with the same lifetime, for an object in those\n * libraries that no media document owns. A raw download URL's token lives\n * as long as the object, so it is never the redirect.\n * - an author-typed hotlink, unchanged, because nothing of ours runs there.\n *\n * A video whose asset is still PUBLIC is refused rather than delivered:\n * its URL already works for anyone, so redirecting a buyer to it is the\n * leak. The 409 is what the gated player reports to the viewer, and the\n * log line is what tells the operator which product needs its video made\n * private.\n *\n * `?r=auto` rides inside the signed URL (AGL-2766). The signature covers\n * `(scope, mediaId, exp)` and not the parameter, so it asks the CDN for the\n * best delivery copy of the one asset the signature names and can reach no\n * other. Nothing the caller sends reaches this `Location`: the GET half\n * reads `hostId`, `productId`, `video`, `exp` and `sig`, and builds the\n * target from the product document.\n *\n * With a delivery provider configured and its release flag on for the\n * owning org, a video with a current copy there is redirected straight to\n * the provider's short-lived URL instead (AGL-2824), for the same session\n * and the same rendition the CDN would pick. `Accept` is the one request\n * header that reaches that choice, and only to pick among the asset's own\n * encodings.\n */\n const delivery = await resolvePaidMediaDelivery({\n stored: file.url,\n hostId,\n ttlMs: GATED_VIDEO_SESSION_TTL_MS,\n cdnParams: [[MEDIA_CDN_RENDITION_PARAM, MEDIA_CDN_RENDITION_AUTO]],\n delivery: { accept: req.headers?.['accept'] },\n io: createPaidMediaDeliveryIo({\n firestore: app.firestore(),\n bucket: app\n .storage()\n .bucket(process.env['NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET']),\n }),\n })\n // Per-member and time-boxed, whichever way it goes: no cache may keep the\n // redirect past the session it opens, nor a refusal past the fix.\n res.setHeader('Cache-Control', 'private, no-store')\n if (delivery.ok === false) {\n console.error(\n '[commerce/stream] gated video not delivered',\n JSON.stringify({ hostId, productId, video, refusal: delivery.refusal }),\n )\n // A lookalike hotlink is filed for staff and the merchant (AGL-3363).\n if (delivery.refusal === 'lookalike' && delivery.host) {\n await flagLookalikeDomain({\n kind: 'link',\n hostId,\n orgId: null,\n domain: delivery.host,\n where: \"a product's video link\",\n })\n }\n return delivery.refusal === 'not-private'\n ? res.status(409).send('This video is not ready to play yet')\n : res.status(404).send('No video')\n }\n /*\n * `Vary: Accept` only when this response chose the rendition (AGL-2824).\n *\n * A signed CDN URL is the same for every client: the `Location` is a\n * function of the product document and the clock, not of the request's\n * `Accept`, and the negotiation happens on the SECOND response, where\n * `serveMediaCdn` declares `Vary` (AGL-2766). A delivery provider's URL is\n * minted after the rendition is picked, so there the `Accept` shaped this\n * `Location`, and saying so is correct even under `no-store`.\n */\n if (delivery.via === 'delivery') res.setHeader('Vary', 'Accept')\n res.redirect(302, delivery.location)\n await countOffRouteServe(app.firestore(), delivery)\n return\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Stream unavailable' })\n }\n}\n"],"names":["flagLookalikeDomain","MEDIA_CDN_RENDITION_AUTO","MEDIA_CDN_RENDITION_PARAM","CommerceModel","firebaseAdmin","GATED_VIDEO_SESSION_TTL_MS","createPaidMediaDeliveryIo","resolvePaidMediaDelivery","createHmac","timingSafeEqual","requireActiveMember","checkMemberEntitlement","tokenSigningSecret","countOffRouteServe","TTL_MS","sign","hostId","productId","video","exp","update","digest","slice","signatureMatches","presented","expected","a","Buffer","from","String","b","length","Uint8Array","streamHandler","req","res","method","body","query","Math","max","Number","status","json","error","productSnapshot","product","auth","email","member","get","entitled","Date","now","url","encodeURIComponent","setHeader","expiresAtMs","sig","send","app","firestore","collection","doc","liftLegacyProduct","data","file","gatedVideos","delivery","stored","ttlMs","cdnParams","accept","headers","io","bucket","storage","process","env","ok","console","JSON","stringify","refusal","host","kind","orgId","domain","where","via","redirect","location"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,qDAAoD;AACxF,SACEC,wBAAwB,EACxBC,yBAAyB,QAEpB,sBAAqB;AAC5B,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,aAAa,EACbC,0BAA0B,QACrB,2BAA0B;AACjC,SACEC,yBAAyB,EACzBC,wBAAwB,QACnB,2BAAuB;AAC9B,SAASC,UAAU,EAAEC,eAAe,QAAQ,SAAQ;AACpD,SAASC,mBAAmB,QAAQ,kBAAc;AAClD,SAASC,sBAAsB,QAAQ,YAAQ;AAC/C,SAASC,kBAAkB,QAAQ,gBAAY;AAC/C,SAASC,kBAAkB,QAAQ,8BAA0B;AAE7D,MAAMC,SAAS,KAAK,KAAK;AAEzB;;;;;;;CAOC,GACD,SAASC,KAAKC,MAAc,EAAEC,SAAiB,EAAEC,KAAa,EAAEC,GAAW;IACzE,OAAOX,WAAW,UAAUI,sBACzBQ,MAAM,CAAC,CAAC,OAAO,EAAEJ,OAAO,CAAC,EAAEC,UAAU,CAAC,EAAEC,MAAM,CAAC,EAAEC,KAAK,EACtDE,MAAM,CAAC,OACPC,KAAK,CAAC,GAAG;AACd;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAASC,iBAAiBC,SAAiB,EAAEC,QAAgB;IAC3D,MAAMC,IAAIC,OAAOC,IAAI,CAACC,OAAOL,oBAAAA,YAAa,KAAK;IAC/C,MAAMM,IAAIH,OAAOC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IACF,EAAE,OAAOxB,OAAO;QACdoC,QAAQpC,KAAK,CAACA;QACd,OAAOT,IAAIO,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/stream.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 { flagLookalikeDomain } from '@aglyn/tenant-data-admin/server/hosted-page-review'\nimport {\n MEDIA_CDN_RENDITION_AUTO,\n MEDIA_CDN_RENDITION_PARAM,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport {\n firebaseAdmin,\n GATED_VIDEO_SESSION_TTL_MS,\n} from '@aglyn/tenant-data-admin'\nimport {\n createPaidMediaDeliveryIo,\n resolvePaidMediaDelivery,\n} from './paid-media-delivery'\nimport { createHmac, timingSafeEqual } from 'crypto'\nimport { requireActiveMember } from './membership'\nimport { checkMemberEntitlement } from './gate'\nimport { tokenSigningSecret } from './download'\nimport { countOffRouteServe } from './paid-media-serve-count'\n\nconst TTL_MS = 15 * 60 * 1000\n\n/**\n * Signed with the dedicated, fail-closed `TOKEN_SIGNING_SECRET` (AGL-509).\n * AGL-509 converted the download and supplier tokens but missed this call\n * site (AGL-689): the old `STRIPE_SECRET_KEY ?? 'aglyn'` key left the whole\n * payload — `stream:${hostId}:${productId}:${video}:${exp}`, all public\n * identifiers — forgeable on any deploy without the Stripe key, and the\n * short TTL bought nothing because the forger chooses `exp`.\n */\nfunction sign(hostId: string, productId: string, video: number, exp: number) {\n return createHmac('sha256', tokenSigningSecret())\n .update(`stream:${hostId}:${productId}:${video}:${exp}`)\n .digest('hex')\n .slice(0, 32)\n}\n\n/**\n * Constant-time signature compare (AGL-512, closed here by AGL-1881).\n *\n * The presented signature was compared with `!==`, which short-circuits on\n * the first differing byte — the exact defect AGL-512 closed in `download.ts`\n * and `supplier-update.ts` and missed here, one directory over. It matters\n * more on this route than it reads: the signature is a truncated HMAC over\n * values the caller already knows (`hostId`, `productId`, `video`, `exp`), so\n * a byte-at-a-time oracle recovers a token for a video the caller was never\n * entitled to, and the 15-minute TTL does not bound the attempt rate.\n *\n * Length is checked first because `timingSafeEqual` THROWS on a length\n * mismatch rather than returning false, and the expected length here is a\n * public constant (32 hex chars) — leaking it costs nothing.\n */\nfunction signatureMatches(presented: string, expected: string): boolean {\n const a = Buffer.from(String(presented ?? ''), 'utf8')\n const b = Buffer.from(String(expected ?? ''), 'utf8')\n if (a.length !== b.length) return false\n return timingSafeEqual(new Uint8Array(a), new Uint8Array(b))\n}\n\n/**\n * Gated video streaming (AGL-315). POST (member session) checks the\n * entitlement and mints a short-TTL signed URL; GET with a valid signature\n * redirects to a media URL that itself expires (AGL-2814). The mint step is\n * the server-enforced gate, a shared stream link dies within 15 minutes, and\n * the media URL behind it dies with the viewing session.\n */\n/** How many \"also open to\" products one video product may name (AGL-4188). */\nexport const MAX_VIDEO_ACCESS_PRODUCTS = 20\n\n/**\n * May this member watch `productId`'s gated videos? Yes when they are entitled\n * to the product itself, or to one of the products its merchant opened the\n * videos to (`videoAccessProductIds`, AGL-4188). The list is read from the\n * product document, never from the request, so a visitor cannot widen it.\n */\nasync function memberMayWatch(\n hostId: string,\n email: string,\n productId: string,\n): Promise<boolean> {\n if (await checkMemberEntitlement(hostId, email, productId)) return true\n const productSnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .doc(productId)\n .get()\n const listed = (productSnapshot.data() as any)?.videoAccessProductIds\n if (!Array.isArray(listed)) return false\n const others = [\n ...new Set(\n listed.filter(\n (id): id is string =>\n typeof id === 'string' && id !== '' && id !== 'any' && id !== productId,\n ),\n ),\n ].slice(0, MAX_VIDEO_ACCESS_PRODUCTS)\n for (const other of others) {\n if (await checkMemberEntitlement(hostId, email, other)) return true\n }\n return false\n}\n\nexport const streamHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(\n (req.method === 'POST' ? req.body?.hostId : req.query.hostId) ?? '',\n )\n const productId = String(\n (req.method === 'POST' ? req.body?.productId : req.query.productId) ?? '',\n )\n const video = Math.max(\n 0,\n Number(\n (req.method === 'POST' ? req.body?.video : req.query.video) ?? 0,\n ),\n )\n if (!hostId || !productId) {\n return res.status(400).json({ error: 'Missing hostId or productId' })\n }\n\n try {\n if (req.method === 'POST') {\n // Suspension gate (AGL-550): suspended members (AGL-546) cannot\n // mint stream URLs — 403'd with the session cookie cleared.\n const auth = await requireActiveMember(req, res, hostId, 'Sign in first')\n if (!auth) return\n const email = String(auth.member.get('email') ?? '')\n const entitled =\n email && (await memberMayWatch(hostId, email, productId))\n if (!entitled) {\n return res.status(403).json({ error: 'Not entitled' })\n }\n const exp = Date.now() + TTL_MS\n const url =\n `/api/commerce/stream?hostId=${encodeURIComponent(hostId)}` +\n `&productId=${encodeURIComponent(productId)}&video=${video}` +\n `&exp=${exp}&sig=${sign(hostId, productId, video, exp)}`\n res.setHeader('Cache-Control', 'private, no-store')\n return res.status(200).json({ url, expiresAtMs: exp })\n }\n\n // GET: signature + expiry gate, then redirect to the media.\n const exp = Number(req.query.exp ?? 0)\n const sig = String(req.query.sig ?? '')\n if (\n !exp ||\n exp < Date.now() ||\n !signatureMatches(sig, sign(hostId, productId, video, exp))\n ) {\n return res.status(403).send('Link expired — reload the page')\n }\n const app = firebaseAdmin.app()\n const productSnapshot = await app\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .doc(productId)\n .get()\n const product = CommerceModel.liftLegacyProduct(\n (productSnapshot.data() as any) ?? {},\n )\n const file = product.gatedVideos?.[video]\n if (!file?.url) return res.status(404).send('No video')\n /**\n * The redirect lands on a link that expires (AGL-2814).\n *\n * Everything above only guards the 302. What the 302 points at is what\n * the buyer, and anyone who copies the `Location` out of the buyer's\n * network panel, keeps. So `resolvePaidMediaDelivery` hands back one of\n * three things and never a permanent URL:\n *\n * - a CDN URL signed for {@link GATED_VIDEO_SESSION_TTL_MS}, when the video\n * is a PRIVATE asset in this site's library or its org's. The CDN refuses\n * a private asset on every path without an unexpired signature.\n * - a V4 signed Storage read with the same lifetime, for an object in those\n * libraries that no media document owns. A raw download URL's token lives\n * as long as the object, so it is never the redirect.\n * - an author-typed hotlink, unchanged, because nothing of ours runs there.\n *\n * A video whose asset is still PUBLIC is refused rather than delivered:\n * its URL already works for anyone, so redirecting a buyer to it is the\n * leak. The 409 is what the gated player reports to the viewer, and the\n * log line is what tells the operator which product needs its video made\n * private.\n *\n * `?r=auto` rides inside the signed URL (AGL-2766). The signature covers\n * `(scope, mediaId, exp)` and not the parameter, so it asks the CDN for the\n * best delivery copy of the one asset the signature names and can reach no\n * other. Nothing the caller sends reaches this `Location`: the GET half\n * reads `hostId`, `productId`, `video`, `exp` and `sig`, and builds the\n * target from the product document.\n *\n * With a delivery provider configured and its release flag on for the\n * owning org, a video with a current copy there is redirected straight to\n * the provider's short-lived URL instead (AGL-2824), for the same session\n * and the same rendition the CDN would pick. `Accept` is the one request\n * header that reaches that choice, and only to pick among the asset's own\n * encodings.\n */\n const delivery = await resolvePaidMediaDelivery({\n stored: file.url,\n hostId,\n ttlMs: GATED_VIDEO_SESSION_TTL_MS,\n cdnParams: [[MEDIA_CDN_RENDITION_PARAM, MEDIA_CDN_RENDITION_AUTO]],\n delivery: { accept: req.headers?.['accept'] },\n io: createPaidMediaDeliveryIo({\n firestore: app.firestore(),\n bucket: app\n .storage()\n .bucket(process.env['NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET']),\n }),\n })\n // Per-member and time-boxed, whichever way it goes: no cache may keep the\n // redirect past the session it opens, nor a refusal past the fix.\n res.setHeader('Cache-Control', 'private, no-store')\n if (delivery.ok === false) {\n console.error(\n '[commerce/stream] gated video not delivered',\n JSON.stringify({ hostId, productId, video, refusal: delivery.refusal }),\n )\n // A lookalike hotlink is filed for staff and the merchant (AGL-3363).\n if (delivery.refusal === 'lookalike' && delivery.host) {\n await flagLookalikeDomain({\n kind: 'link',\n hostId,\n orgId: null,\n domain: delivery.host,\n where: \"a product's video link\",\n })\n }\n return delivery.refusal === 'not-private'\n ? res.status(409).send('This video is not ready to play yet')\n : res.status(404).send('No video')\n }\n /*\n * `Vary: Accept` only when this response chose the rendition (AGL-2824).\n *\n * A signed CDN URL is the same for every client: the `Location` is a\n * function of the product document and the clock, not of the request's\n * `Accept`, and the negotiation happens on the SECOND response, where\n * `serveMediaCdn` declares `Vary` (AGL-2766). A delivery provider's URL is\n * minted after the rendition is picked, so there the `Accept` shaped this\n * `Location`, and saying so is correct even under `no-store`.\n */\n if (delivery.via === 'delivery') res.setHeader('Vary', 'Accept')\n res.redirect(302, delivery.location)\n await countOffRouteServe(app.firestore(), delivery)\n return\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Stream unavailable' })\n }\n}\n"],"names":["flagLookalikeDomain","MEDIA_CDN_RENDITION_AUTO","MEDIA_CDN_RENDITION_PARAM","CommerceModel","firebaseAdmin","GATED_VIDEO_SESSION_TTL_MS","createPaidMediaDeliveryIo","resolvePaidMediaDelivery","createHmac","timingSafeEqual","requireActiveMember","checkMemberEntitlement","tokenSigningSecret","countOffRouteServe","TTL_MS","sign","hostId","productId","video","exp","update","digest","slice","signatureMatches","presented","expected","a","Buffer","from","String","b","length","Uint8Array","MAX_VIDEO_ACCESS_PRODUCTS","memberMayWatch","email","productSnapshot","app","firestore","collection","doc","get","listed","data","videoAccessProductIds","Array","isArray","others","Set","filter","id","other","streamHandler","req","res","method","body","query","Math","max","Number","status","json","error","product","auth","member","entitled","Date","now","url","encodeURIComponent","setHeader","expiresAtMs","sig","send","liftLegacyProduct","file","gatedVideos","delivery","stored","ttlMs","cdnParams","accept","headers","io","bucket","storage","process","env","ok","console","JSON","stringify","refusal","host","kind","orgId","domain","where","via","redirect","location"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,qDAAoD;AACxF,SACEC,wBAAwB,EACxBC,yBAAyB,QAEpB,sBAAqB;AAC5B,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,aAAa,EACbC,0BAA0B,QACrB,2BAA0B;AACjC,SACEC,yBAAyB,EACzBC,wBAAwB,QACnB,2BAAuB;AAC9B,SAASC,UAAU,EAAEC,eAAe,QAAQ,SAAQ;AACpD,SAASC,mBAAmB,QAAQ,kBAAc;AAClD,SAASC,sBAAsB,QAAQ,YAAQ;AAC/C,SAASC,kBAAkB,QAAQ,gBAAY;AAC/C,SAASC,kBAAkB,QAAQ,8BAA0B;AAE7D,MAAMC,SAAS,KAAK,KAAK;AAEzB;;;;;;;CAOC,GACD,SAASC,KAAKC,MAAc,EAAEC,SAAiB,EAAEC,KAAa,EAAEC,GAAW;IACzE,OAAOX,WAAW,UAAUI,sBACzBQ,MAAM,CAAC,CAAC,OAAO,EAAEJ,OAAO,CAAC,EAAEC,UAAU,CAAC,EAAEC,MAAM,CAAC,EAAEC,KAAK,EACtDE,MAAM,CAAC,OACPC,KAAK,CAAC,GAAG;AACd;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAASC,iBAAiBC,SAAiB,EAAEC,QAAgB;IAC3D,MAAMC,IAAIC,OAAOC,IAAI,CAACC,OAAOL,oBAAAA,YAAa,KAAK;IAC/C,MAAMM,IAAIH,OAAOC,IAAI,CAACC,OAAOJ,mBAAAA,WAAY,KAAK;IAC9C,IAAIC,EAAEK,MAAM,KAAKD,EAAEC,MAAM,EAAE,OAAO;IAClC,OAAOtB,gBAAgB,IAAIuB,WAAWN,IAAI,IAAIM,WAAWF;AAC3D;AAEA;;;;;;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E,SAASf,SAASe,OAAO;YAAC;YAEvE,sEAAsE;YACtE,IAAIf,SAASe,OAAO,KAAK,eAAef,SAASgB,IAAI,EAAE;gBACrD,MAAM/F,oBAAoB;oBACxBgG,MAAM;oBACNhF;oBACAiF,OAAO;oBACPC,QAAQnB,SAASgB,IAAI;oBACrBI,OAAO;gBACT;YACF;YACA,OAAOpB,SAASe,OAAO,KAAK,gBACxBxC,IAAIO,MAAM,CAAC,KAAKc,IAAI,CAAC,yCACrBrB,IAAIO,MAAM,CAAC,KAAKc,IAAI,CAAC;QAC3B;QACA;;;;;;;;;KASC,GACD,IAAII,SAASqB,GAAG,KAAK,YAAY9C,IAAIkB,SAAS,CAAC,QAAQ;QACvDlB,IAAI+C,QAAQ,CAAC,KAAKtB,SAASuB,QAAQ;QACnC,MAAMzF,mBAAmBwB,IAAIC,SAAS,IAAIyC;QAC1C;IACF,EAAE,OAAOhB,OAAO;QACd4B,QAAQ5B,KAAK,CAACA;QACd,OAAOT,IAAIO,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
@@ -27,6 +27,16 @@
27
27
  * refunded share, as it always has.
28
28
  * - the caller's IDEMPOTENCY KEY, so a retried request is the same refund
29
29
  * at Stripe and never a second one.
30
+ *
31
+ * A DIRECT charge (the seller's own Stripe account sold it) is refunded ON
32
+ * that account with the `Stripe-Account` header: the money comes out of the
33
+ * seller's balance, where the sale settled, so there is no transfer to
34
+ * reverse and `reverse_transfer` is never sent. `refund_application_fee` is
35
+ * kept, so Aglyn hands its fee back on the refunded share exactly as it does
36
+ * on a destination charge. A payment intent the seller's account does not
37
+ * know (a sale from before the seller switched, or Aglyn's own hardware) is
38
+ * refunded on the platform as a destination charge, so a caller may pass the
39
+ * site's direct-charge account without first asking which kind the sale was.
30
40
  */
31
41
  export type StripeRefundResult = {
32
42
  ok: true;
@@ -42,6 +52,11 @@ export declare function createStripeRefund(input: {
42
52
  amountCents: number;
43
53
  idempotencyKey?: string | null;
44
54
  metadata?: Record<string, string>;
55
+ /**
56
+ * The seller's connected account when the sale was (or may have been) a
57
+ * DIRECT charge. Absent for a destination sale.
58
+ */
59
+ stripeAccount?: string | null;
45
60
  fetch?: typeof fetch;
46
61
  secretKey?: string;
47
62
  }): Promise<StripeRefundResult>;