@aglyn/plugins-commerce 1.15.0 → 1.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +8 -3
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  6. package/src/lib/components/console/subscription-detail-dialog.component.js +2 -2
  7. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
  8. package/src/lib/components/console/subscriptions-card.component.js +4 -2
  9. package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
  10. package/src/lib/components/product-detail.js +7 -3
  11. package/src/lib/components/product-detail.js.map +1 -1
  12. package/src/lib/components/quote-page-body.js +7 -3
  13. package/src/lib/components/quote-page-body.js.map +1 -1
  14. package/src/lib/components/related-products.js +6 -3
  15. package/src/lib/components/related-products.js.map +1 -1
  16. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  17. package/src/lib/components/storefront-payment-element.js +11 -7
  18. package/src/lib/components/storefront-payment-element.js.map +1 -1
  19. package/src/lib/model/commerce-payment-methods.d.ts +26 -39
  20. package/src/lib/model/commerce-payment-methods.js +11 -118
  21. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  22. package/src/lib/server/billing-webhook.d.ts +23 -0
  23. package/src/lib/server/billing-webhook.js +162 -30
  24. package/src/lib/server/billing-webhook.js.map +1 -1
  25. package/src/lib/server/cancel-order.js +4 -3
  26. package/src/lib/server/cancel-order.js.map +1 -1
  27. package/src/lib/server/cart-checkout.js +61 -14
  28. package/src/lib/server/cart-checkout.js.map +1 -1
  29. package/src/lib/server/catalog.js +58 -22
  30. package/src/lib/server/catalog.js.map +1 -1
  31. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  32. package/src/lib/server/checkout-session-expiry.js +19 -5
  33. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  34. package/src/lib/server/checkout-status.js +4 -3
  35. package/src/lib/server/checkout-status.js.map +1 -1
  36. package/src/lib/server/checkout.js +42 -12
  37. package/src/lib/server/checkout.js.map +1 -1
  38. package/src/lib/server/connect.js +42 -11
  39. package/src/lib/server/connect.js.map +1 -1
  40. package/src/lib/server/draft-order.js +37 -12
  41. package/src/lib/server/draft-order.js.map +1 -1
  42. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  43. package/src/lib/server/manual-tax-rate.js +10 -6
  44. package/src/lib/server/manual-tax-rate.js.map +1 -1
  45. package/src/lib/server/native-checkout.d.ts +10 -3
  46. package/src/lib/server/native-checkout.js +8 -3
  47. package/src/lib/server/native-checkout.js.map +1 -1
  48. package/src/lib/server/payment-method-domains.d.ts +50 -9
  49. package/src/lib/server/payment-method-domains.js +150 -51
  50. package/src/lib/server/payment-method-domains.js.map +1 -1
  51. package/src/lib/server/payment-methods.js +3 -2
  52. package/src/lib/server/payment-methods.js.map +1 -1
  53. package/src/lib/server/pos-order.js +5 -1
  54. package/src/lib/server/pos-order.js.map +1 -1
  55. package/src/lib/server/pos-stripe.d.ts +7 -7
  56. package/src/lib/server/pos-stripe.js +15 -13
  57. package/src/lib/server/pos-stripe.js.map +1 -1
  58. package/src/lib/server/pos-terminal.js +11 -3
  59. package/src/lib/server/pos-terminal.js.map +1 -1
  60. package/src/lib/server/quote-pay.d.ts +23 -1
  61. package/src/lib/server/quote-pay.js +112 -32
  62. package/src/lib/server/quote-pay.js.map +1 -1
  63. package/src/lib/server/quote.d.ts +2 -1
  64. package/src/lib/server/quote.js +12 -11
  65. package/src/lib/server/quote.js.map +1 -1
  66. package/src/lib/server/refund.js +13 -6
  67. package/src/lib/server/refund.js.map +1 -1
  68. package/src/lib/server/related.js +10 -3
  69. package/src/lib/server/related.js.map +1 -1
  70. package/src/lib/server/reserve.js +19 -6
  71. package/src/lib/server/reserve.js.map +1 -1
  72. package/src/lib/server/revenue-source.d.ts +6 -0
  73. package/src/lib/server/revenue-source.js +25 -9
  74. package/src/lib/server/revenue-source.js.map +1 -1
  75. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  76. package/src/lib/server/seller-stripe-account.js +99 -0
  77. package/src/lib/server/seller-stripe-account.js.map +1 -0
  78. package/src/lib/server/storefront-tax-record.js +6 -1
  79. package/src/lib/server/storefront-tax-record.js.map +1 -1
  80. package/src/lib/server/storefront-tax.d.ts +33 -2
  81. package/src/lib/server/storefront-tax.js +39 -3
  82. package/src/lib/server/storefront-tax.js.map +1 -1
  83. package/src/lib/server/stripe-refund.d.ts +15 -0
  84. package/src/lib/server/stripe-refund.js +54 -26
  85. package/src/lib/server/stripe-refund.js.map +1 -1
  86. package/src/lib/server/subscription-portal.js +8 -3
  87. package/src/lib/server/subscription-portal.js.map +1 -1
@@ -14,12 +14,12 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { checkEntitlement, claimAttempt, deriveStripeObjectKey, PAY_LINK_PROCESSING_PERCENT, resolveTransactionFeeCents } from "@aglyn/aglyn/server";
17
+ */ import { checkEntitlement, claimAttempt, deriveStripeObjectKey, resolveTransactionFeeCents } from "@aglyn/aglyn/server";
18
18
  import { resolveHostToken } from "@aglyn/aglyn/app-utils/host-tokens";
19
19
  import { readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
20
20
  import { siteReturnOrigin } from "@aglyn/aglyn/app-utils/site-return-url";
21
21
  import { consumeRateLimit, firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
22
- import { merchantAccountIsReady } from "@aglyn/tenant-data-admin/server/payment-provider";
22
+ import { connectedAccountHeader, directChargeParams, merchantAccountIsReady, saleChargeModel } from "@aglyn/tenant-data-admin/server/payment-provider";
23
23
  import { checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admin/server/stripe-card-authentication";
24
24
  import { quotePageHref } from "../constants/quote-page.js";
25
25
  import * as CommerceModel from "../model/index.js";
@@ -29,6 +29,7 @@ import { applyNativeCheckoutParams, nativeCheckoutStripeHeaders, readCheckoutSes
29
29
  import { orderStatusUrl } from "./order-status-token.js";
30
30
  import { ensureCheckoutDomain } from "./payment-method-domains.js";
31
31
  import { verifyQuoteLinkToken } from "./quote-link-token.js";
32
+ import { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from "./seller-stripe-account.js";
32
33
  /*==========================================
33
34
  * THE CUSTOMER'S QUOTE PAGE AND ITS PAY BUTTON (AGL-4094), AND AN
34
35
  * INVOICE'S (AGL-4099).
@@ -101,11 +102,44 @@ export function defaultQuotePayDeps() {
101
102
  session: await response.json().catch(()=>({}))
102
103
  };
103
104
  },
104
- expireSession: (sessionId)=>expireCheckoutSession(sessionId),
105
+ expireSession: (sessionId, stripeAccount)=>stripeAccount ? expireConnectedCheckoutSession(sessionId, stripeAccount) : expireCheckoutSession(sessionId),
105
106
  ensureDomain: (input)=>ensureCheckoutDomain(input).catch(()=>null),
106
107
  now: ()=>Date.now()
107
108
  };
108
109
  }
110
+ /**
111
+ * `expireCheckoutSession` for a session on the seller's own account (a direct
112
+ * charge), where the platform's call answers 404. Same answers, same rule: a
113
+ * refused expiry reads the session back, so a paid one is never read as closed.
114
+ */ async function expireConnectedCheckoutSession(sessionId, stripeAccount) {
115
+ var _process_env_STRIPE_SECRET_KEY;
116
+ if (!/^cs_(test|live)_[A-Za-z0-9]{8,255}$/.test(String(sessionId != null ? sessionId : ''))) return 'missing';
117
+ const secretKey = String((_process_env_STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY) != null ? _process_env_STRIPE_SECRET_KEY : '').trim();
118
+ if (!secretKey) return 'open';
119
+ const headers = {
120
+ Authorization: `Bearer ${secretKey}`,
121
+ 'Content-Type': 'application/x-www-form-urlencoded',
122
+ 'Stripe-Account': stripeAccount
123
+ };
124
+ try {
125
+ const expired = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}/expire`, {
126
+ method: 'POST',
127
+ headers
128
+ });
129
+ if (expired.ok) return 'expired';
130
+ const read = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, {
131
+ headers
132
+ });
133
+ if (read.status === 404) return 'missing';
134
+ if (!read.ok) return 'open';
135
+ const session = await read.json().catch(()=>({}));
136
+ if (session.status === 'complete') return 'complete';
137
+ if (session.status === 'expired') return 'expired';
138
+ return 'open';
139
+ } catch (unused) {
140
+ return 'open';
141
+ }
142
+ }
109
143
  const DOC_ID = /^(?!__.*__$)[^/]{1,200}$/;
110
144
  const NOT_FOUND = {
111
145
  status: 404,
@@ -243,11 +277,14 @@ function headerOf(req, name) {
243
277
  */ export async function payLinkPayments(deps, input) {
244
278
  var _owner_org;
245
279
  const owner = await deps.orgForHost(input.hostId);
246
- if (!checkEntitlement(owner == null ? void 0 : owner.org, 'commerce')) return {
247
- ready: false,
248
- owner,
249
- accountId: ''
250
- };
280
+ if (!checkEntitlement(owner == null ? void 0 : owner.org, 'commerce')) {
281
+ return {
282
+ ready: false,
283
+ owner,
284
+ accountId: '',
285
+ chargeModel: 'destination'
286
+ };
287
+ }
251
288
  const ownerUid = owner == null ? void 0 : (_owner_org = owner.org) == null ? void 0 : _owner_org.ownerUid;
252
289
  const profile = ownerUid ? await deps.firestore().collection('profiles').doc(String(ownerUid)).get() : null;
253
290
  const accountId = profile == null ? void 0 : profile.get('stripeAccountId');
@@ -261,7 +298,8 @@ function headerOf(req, name) {
261
298
  return {
262
299
  ready,
263
300
  owner,
264
- accountId: ready ? String(accountId) : ''
301
+ accountId: ready ? String(accountId) : '',
302
+ chargeModel: saleChargeModel(profile == null ? void 0 : profile.get('stripeChargeModel'))
265
303
  };
266
304
  }
267
305
  /**
@@ -387,7 +425,10 @@ function headerOf(req, name) {
387
425
  ]);
388
426
  }
389
427
  const shippingFloorCents = rates.length > 0 ? CommerceModel.shippingFloorCents(rates) : charge.shippingCents;
390
- for (const [key, value] of Object.entries(CommerceModel.destinationChargeParams({
428
+ const direct = input.chargeModel === 'direct';
429
+ for (const [key, value] of Object.entries(// A direct charge is already the seller's money, Stripe Tax included
430
+ // (computed on THEIR registrations), so the take is the whole split.
431
+ direct ? directChargeParams(input.feeCents) : CommerceModel.destinationChargeParams({
391
432
  accountId: input.accountId,
392
433
  feeCents: input.feeCents,
393
434
  taxOwner: charge.taxAtPayment ? 'platform' : 'merchant',
@@ -421,12 +462,17 @@ function headerOf(req, name) {
421
462
  if (input.chargedTax) params.set('metadata[quoteTax]', CommerceModel.quoteTaxBasisKey(input.chargedTax));
422
463
  }
423
464
  params.set('metadata[feeCents]', String(input.feeCents));
465
+ // What the webhook, refunds and reports read to find the payment on the
466
+ // seller's account rather than the platform's.
467
+ if (direct) params.set('metadata[chargeModel]', 'direct');
424
468
  // A tax charged as its own line is invisible to Stripe's tax total; this
425
469
  // witness is what records it as the business's tax.
426
470
  if (charge.taxCents > 0 && charge.taxPct === null) {
427
471
  params.set('metadata[taxCents]', String(charge.taxCents));
428
472
  }
429
- if (charge.taxAtPayment) {
473
+ // The fixed transfer Aglyn keeps its Stripe Tax back from; a direct charge
474
+ // transfers nothing and its tax is the seller's.
475
+ if (charge.taxAtPayment && !direct) {
430
476
  params.set('metadata[transferCents]', String(CommerceModel.platformLiableTransferCents({
431
477
  feeCents: input.feeCents,
432
478
  merchantGoodsCents: charge.goodsCents,
@@ -434,10 +480,9 @@ function headerOf(req, name) {
434
480
  })));
435
481
  params.set('metadata[transferShippingCents]', String(shippingFloorCents));
436
482
  }
437
- // A quote or an invoice pays by card or a card-rate wallet, never by
438
- // buy-now-pay-later, whatever the store offers on its storefront: its fee is
439
- // priced at the card rate (`PAY_LINK_PROCESSING_PERCENT`).
440
- CommerceModel.appendStorefrontPaymentMethodParams(params, CommerceModel.payLinkPaymentMethodControls(input.paymentMethods));
483
+ // The store's choices, and never buy-now-pay-later (AGL-4198), so the fee
484
+ // above is priced at the card rate.
485
+ CommerceModel.appendStorefrontPaymentMethodParams(params, input.paymentMethods);
441
486
  return params;
442
487
  }
443
488
  const QUOTE_UPDATED_MESSAGE = 'This quote was updated since you opened it. Reload the page to see it before you pay.';
@@ -449,7 +494,7 @@ const refusal = (status, reason, error, extra = {})=>({
449
494
  }, extra)
450
495
  });
451
496
  /** `POST /api/commerce/quote-pay`: a fresh Checkout Session for the quote. */ export async function handleQuotePay(deps, req) {
452
- var _ref, _order_checkoutSessionId, _ref1;
497
+ var _onAccount_StripeAccount, _ref, _order_checkoutSessionId, _ref1;
453
498
  var _order_quote, _order_quote1;
454
499
  if (req.method !== 'POST') return {
455
500
  status: 405,
@@ -518,13 +563,30 @@ const refusal = (status, reason, error, extra = {})=>({
518
563
  return refusal(409, blocked, CommerceModel.payLinkPaymentsUnavailableMessage(storeName, kind));
519
564
  }
520
565
  if (blocked) return refusal(409, blocked, CommerceModel.invoicePayRefusalMessage(blocked, storeName, kind));
521
- const { owner, accountId } = payments;
566
+ const { owner, accountId, chargeModel } = payments;
567
+ const direct = chargeModel === 'direct';
568
+ // Every Stripe object for a direct sale lives on the seller's account.
569
+ const onAccount = connectedAccountHeader(chargeModel, accountId);
570
+ const sessionAccount = (_onAccount_StripeAccount = onAccount['Stripe-Account']) != null ? _onAccount_StripeAccount : '';
522
571
  const charge = CommerceModel.invoiceCheckoutCharge(order, quoteId, payStore);
523
572
  // The fee is sized on the most the buyer can pay, as a draft's first link
524
573
  // sized it on its dearest rate, and its processing half at the card rate:
525
- // the session below excludes every buy-now-pay-later method.
574
+ // the session below excludes every buy-now-pay-later method. A direct
575
+ // charge's fee is the take alone: Stripe bills the seller its card fee.
526
576
  const dearestRateCents = charge.shippingOptions.reduce((most, rate)=>Math.max(most, rate.amountCents), 0);
527
- const feeCents = resolveTransactionFeeCents(owner == null ? void 0 : owner.org, charge.feeProductType, charge.goodsCents, charge.totalCents + dearestRateCents, PAY_LINK_PROCESSING_PERCENT);
577
+ const feeCents = resolveTransactionFeeCents(owner == null ? void 0 : owner.org, charge.feeProductType, charge.goodsCents, charge.totalCents + dearestRateCents, direct ? {
578
+ direct: true
579
+ } : {
580
+ stripeTax: charge.taxAtPayment
581
+ });
582
+ // Stripe refuses `automatic_tax` on a seller's account whose Stripe Tax is
583
+ // not set up, and a store that chose it must not sell untaxed. Above the
584
+ // claim, so the refusal spends no press.
585
+ if (direct && charge.taxAtPayment) {
586
+ var _deps_sellerTaxActive;
587
+ const taxActive = await ((_deps_sellerTaxActive = deps.sellerTaxActive) != null ? _deps_sellerTaxActive : sellerStripeTaxActive)(String(accountId));
588
+ if (!taxActive) return refusal(409, 'seller-tax', SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE);
589
+ }
528
590
  const nativeMode = await deps.nativeMode(String((_ref = owner == null ? void 0 : owner.id) != null ? _ref : ''));
529
591
  const site = host;
530
592
  const origin = siteReturnOrigin({
@@ -541,6 +603,15 @@ const refusal = (status, reason, error, extra = {})=>({
541
603
  const openedFor = (_order_checkoutSessionId = order.checkoutSessionId) != null ? _order_checkoutSessionId : '';
542
604
  const openedAtEdit = Number((_order_quote1 = order.quote) == null ? void 0 : _order_quote1.updatedAtMs) || 0;
543
605
  const openedAtVersion = CommerceModel.orderPayLinkVersion(order);
606
+ // Closes a session this quote opened, on the account it was opened on. A
607
+ // seller's earlier session may be the platform's (opened before the seller
608
+ // moved to direct charges), so one the seller's account does not know is
609
+ // closed there too: leaving it open would be a second way to pay.
610
+ const expire = async (sessionId)=>{
611
+ if (!sessionAccount) return deps.expireSession(sessionId);
612
+ const result = await deps.expireSession(sessionId, sessionAccount);
613
+ return result === 'missing' ? deps.expireSession(sessionId) : result;
614
+ };
544
615
  const claimed = await claimAttempt(deps.firestore(), {
545
616
  kind: 'commerce-quote-pay',
546
617
  scopeId: `${hostId}:${quoteId}`,
@@ -567,7 +638,7 @@ const refusal = (status, reason, error, extra = {})=>({
567
638
  // that was paid a moment ago means the quote is paid; one that cannot be
568
639
  // closed means a second session would be a second way to pay.
569
640
  if (openedFor) {
570
- const previous = await deps.expireSession(openedFor);
641
+ const previous = await expire(openedFor);
571
642
  if (previous === 'complete') {
572
643
  await claim.release();
573
644
  return refusal(409, 'paid', `This ${noun} has just been paid. Your receipt is on its way.`, {
@@ -588,12 +659,14 @@ const refusal = (status, reason, error, extra = {})=>({
588
659
  if (charge.taxPct !== null && charge.taxableCents > 0) {
589
660
  var _ref2;
590
661
  const basis = kind === 'quote' ? payTax.basis : null;
591
- taxRateId = (_ref2 = await deps.taxRateId({
662
+ taxRateId = (_ref2 = await deps.taxRateId(_extends({
592
663
  hostRef,
593
664
  taxPct: charge.taxPct,
594
665
  taxLabel: (basis == null ? void 0 : basis.kind) === 'rate' ? basis.label || `Tax (${charge.taxPct}%)` : 'Sales tax',
595
666
  headers: stripeKey(`tax-rate-${Math.round(charge.taxPct * 10000)}`)
596
- })) != null ? _ref2 : '';
667
+ }, sessionAccount ? {
668
+ stripeAccount: sessionAccount
669
+ } : {}))) != null ? _ref2 : '';
597
670
  if (!taxRateId) {
598
671
  // Never an untaxed session for a taxed quote.
599
672
  await claim.release();
@@ -606,30 +679,37 @@ const refusal = (status, reason, error, extra = {})=>({
606
679
  }
607
680
  }
608
681
  const paymentMethods = CommerceModel.resolveStorefrontPaymentMethodControls(CommerceModel.normalizeStorefrontPaymentMethodSettings(store.get('paymentMethods')));
609
- const params = buildQuoteSessionParams({
682
+ const params = buildQuoteSessionParams(_extends({
610
683
  hostId,
611
684
  quoteId,
612
685
  order,
613
686
  charge,
614
- accountId: String(accountId),
687
+ accountId: String(accountId)
688
+ }, direct ? {
689
+ chargeModel
690
+ } : {}, {
615
691
  feeCents,
616
692
  taxRateId,
617
693
  returnUrl,
618
694
  paymentMethods,
619
695
  chargedTax: kind === 'quote' && payTax.source === 'current' ? payTax.basis : null
620
- });
696
+ }));
621
697
  if (nativeMode.native) {
622
698
  var _params_get;
623
699
  applyNativeCheckoutParams(params, (_params_get = params.get('success_url')) != null ? _params_get : returnUrl);
624
700
  }
625
- const domain = nativeMode.native ? deps.ensureDomain({
701
+ // Apple Pay's domain is registered on the account the session lives on.
702
+ const domainInput = _extends({
626
703
  pageUrl: returnUrl,
627
704
  site,
628
705
  hostId
629
- }) : Promise.resolve(null);
630
- const created = await deps.createSession(params, _extends({}, stripeKey('session'), nativeCheckoutStripeHeaders(nativeMode)));
706
+ }, sessionAccount ? {
707
+ stripeAccount: sessionAccount
708
+ } : {});
709
+ const domain = nativeMode.native ? deps.ensureDomain(domainInput) : Promise.resolve(null);
710
+ const created = await deps.createSession(params, _extends({}, stripeKey('session'), nativeCheckoutStripeHeaders(nativeMode), onAccount));
631
711
  await domain;
632
- const payload = created.ok ? readCheckoutSessionPayload(created.session, nativeMode, paymentMethods.wallets) : null;
712
+ const payload = created.ok ? readCheckoutSessionPayload(created.session, nativeMode, paymentMethods.wallets, sessionAccount) : null;
633
713
  if (!payload || !created.session.id) {
634
714
  var _created_session;
635
715
  console.error('Stripe quote checkout error', (_created_session = created.session) == null ? void 0 : _created_session.error);
@@ -692,11 +772,11 @@ const refusal = (status, reason, error, extra = {})=>({
692
772
  };
693
773
  });
694
774
  if (settled.outcome) {
695
- await deps.expireSession(minted);
775
+ await expire(minted);
696
776
  await claim.release();
697
777
  return settled.outcome;
698
778
  }
699
- if (settled.displaced && settled.displaced !== minted) await deps.expireSession(settled.displaced);
779
+ if (settled.displaced && settled.displaced !== minted) await expire(settled.displaced);
700
780
  await claim.record(200, payload);
701
781
  return {
702
782
  status: 200,
@@ -704,7 +784,7 @@ const refusal = (status, reason, error, extra = {})=>({
704
784
  };
705
785
  } catch (error) {
706
786
  console.error('quote pay failed', error);
707
- if (minted) await deps.expireSession(minted).catch(()=>'open');
787
+ if (minted) await expire(minted).catch(()=>'open');
708
788
  await claim.release();
709
789
  return {
710
790
  status: 500,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-pay.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 {\n checkEntitlement,\n claimAttempt,\n deriveStripeObjectKey,\n PAY_LINK_PROCESSING_PERCENT,\n resolveTransactionFeeCents,\n type PluginApiHandler,\n type PluginApiRequest,\n} from '@aglyn/aglyn/server'\nimport { resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { type SiteReturnHost, siteReturnOrigin } from '@aglyn/aglyn/app-utils/site-return-url'\nimport { consumeRateLimit, firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { merchantAccountIsReady } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport { quotePageHref } from '../constants/quote-page'\nimport * as CommerceModel from '../model'\nimport { expireCheckoutSession, type CheckoutSessionExpiry } from './checkout-session-expiry'\nimport { resolveManualTaxRateId } from './manual-tax-rate'\nimport {\n applyNativeCheckoutParams,\n nativeCheckoutStripeHeaders,\n readCheckoutSessionPayload,\n resolveNativeCheckoutMode,\n type NativeCheckoutMode,\n} from './native-checkout'\nimport { orderStatusUrl } from './order-status-token'\nimport { ensureCheckoutDomain } from './payment-method-domains'\nimport { verifyQuoteLinkToken } from './quote-link-token'\n\n/*==========================================\n * THE CUSTOMER'S QUOTE PAGE AND ITS PAY BUTTON (AGL-4094), AND AN\n * INVOICE'S (AGL-4099).\n *\n * GET /api/commerce/quote-view?hostId=&q=<quoteId>&t=<token>\n * → 200 QuotePageView | 200 { state: 'replaced', storeName } | 404\n * POST /api/commerce/quote-pay { hostId, q, t, v } + Idempotency-Key\n * → 200 { url } (Stripe's page) | 200 { clientSecret, publishableKey, sessionId, wallets? }\n * (the in-page form) | 409 { error, reason } | 410 { error, replaced: true } | 404\n *\n * The signed link (`quote-link-token.ts`) is the whole credential. A wrong\n * token answers exactly as a missing quote does, so neither route tells\n * anyone which quote ids exist; both are rate-limited per address per site\n * BEFORE the token check, so guessing costs what looking does. A link signed\n * for an older version of the quote opens the replaced page and nothing else.\n *\n * Pay opens a FRESH Checkout Session from the stored quote on every press:\n * the prices are the stored lines', never anything the page sends, and the\n * session the previous press opened is expired first, so two sessions for one\n * quote can never both be open. The quote keeps the open one in\n * `checkoutSessionId`. A Stripe session lapses after a day; the quote and its\n * link do not, because the next press opens another.\n *\n * The payment completes in `billing-webhook.ts`, which turns this same\n * document into the order (`paidQuoteOrder`); nothing here marks it paid.\n *\n * THE PAGE OFFERS ONLY A PAY THAT WORKS (AGL-4162). The view asks the same\n * payments check Pay refuses on ({@link payLinkPayments}) and prices the tax\n * the same way (`quotePayTax`): a quote saved before the store chose its\n * sales tax is shown and charged under the store's choice now, and Pay\n * refuses when that choice is not the one the page showed (`tax`). The\n * session carries that basis (`quoteTax`) so the paid order records it.\n *\n * AN INVOICE'S LINK IS THIS ONE (AGL-4099). A draft order the business sent\n * an invoice for opens on the same page from the same kind of link (its\n * version on `payLink.version`, `commerce-invoices.ts`), as \"Invoice #N\" with\n * no proofs or approval, and Pay opens the same kind of fresh session from\n * its stored lines, discount, tax and the shipping rates it was made with.\n * Its webhook is the draft branch it always completed through, which flips\n * the draft to paid without restamping its list fields. The proof and answer\n * routes stay a quote's alone: `loadLinkedQuote` opens an invoice only for\n * the routes that ask (`{ invoices: true }`).\n *=========================================*/\n\n/** Lookups and presses one address may make per site, per ten minutes. */\nexport const QUOTE_VIEW_LOOKUPS_PER_WINDOW = 60\nexport const QUOTE_PAY_PRESSES_PER_WINDOW = 20\nexport const QUOTE_WINDOW_MS = 10 * 60_000\n\nexport interface QuotePayDeps {\n firestore(): FirebaseFirestore.Firestore\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean; resetMs: number }>\n orgForHost(hostId: string): Promise<{ id?: string; org?: any } | null>\n nativeMode(orgId: string): Promise<NativeCheckoutMode>\n /** The store's manual tax rate as a Stripe tax rate, or null when one cannot be had. */\n taxRateId(input: Parameters<typeof resolveManualTaxRateId>[0]): Promise<string | null>\n createSession(\n params: URLSearchParams,\n headers: Record<string, string>,\n ): Promise<{ ok: boolean; session: { id?: string; url?: string; client_secret?: string; error?: unknown } }>\n expireSession(sessionId: string): Promise<CheckoutSessionExpiry>\n /** Registers the page's domain for Apple Pay; never throws. */\n ensureDomain(input: Parameters<typeof ensureCheckoutDomain>[0]): Promise<unknown>\n now(): number\n}\n\nexport function defaultQuotePayDeps(): QuotePayDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore(),\n consumeRateLimit: (key, options) => consumeRateLimit(key, options),\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n nativeMode: (orgId) => resolveNativeCheckoutMode(orgId),\n taxRateId: (input) => resolveManualTaxRateId(input),\n createSession: async (params, headers) => {\n const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...headers,\n },\n body: params.toString(),\n })\n return { ok: response.ok, session: (await response.json().catch(() => ({}))) as never }\n },\n expireSession: (sessionId) => expireCheckoutSession(sessionId),\n ensureDomain: (input) => ensureCheckoutDomain(input).catch(() => null),\n now: () => Date.now(),\n }\n}\n\n/** A link route's answer: a status, a JSON body and any extra headers. */\nexport type QuoteLinkOutcome = { status: number; body: Record<string, unknown>; headers?: Record<string, string> }\n\nconst DOC_ID = /^(?!__.*__$)[^/]{1,200}$/\n\nconst NOT_FOUND: QuoteLinkOutcome = {\n status: 404,\n body: { error: 'We could not find that quote. Check the link you were sent.' },\n}\n\n/** The not-found answer of a route an invoice's link reaches too: it names neither. */\nconst NOT_FOUND_ANY: QuoteLinkOutcome = {\n status: 404,\n body: { error: 'We could not find that quote or invoice. Check the link you were sent.' },\n}\n\n/** `quote` or `invoice`, as the customer reads it. */\nconst nounOf = (kind: CommerceModel.OrderPayLinkKind) => (kind === 'invoice' ? 'invoice' : 'quote')\n\nfunction bodyOf(req: PluginApiRequest): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}\n}\n\nfunction headerOf(req: PluginApiRequest, name: string): string {\n const headers = (req.headers ?? {}) as Record<string, unknown>\n const value = headers[name.toLowerCase()] ?? headers[name]\n return String(Array.isArray(value) ? (value[0] ?? '') : (value ?? '')).trim()\n}\n\n/** The rate limit a link route spends per address per site, BEFORE the token is checked. */\nexport async function limitedQuoteLink(\n deps: QuotePayDeps,\n req: PluginApiRequest,\n key: string,\n limit: number,\n): Promise<QuoteLinkOutcome | null> {\n const ip = readClientIp(req.headers as never, { remoteAddress: req.socket?.remoteAddress }) ?? 'no-address'\n const rate = await deps.consumeRateLimit(`${key}:${ip}`, { limit, windowMs: QUOTE_WINDOW_MS })\n if (rate.allowed) return null\n return {\n status: 429,\n body: { error: 'Too many tries. Try again in a few minutes.' },\n headers: { 'Retry-After': String(Math.max(1, Math.ceil((rate.resetMs - deps.now()) / 1000))) },\n }\n}\n\nexport interface LoadedQuote {\n hostRef: FirebaseFirestore.DocumentReference\n host: Record<string, unknown>\n order: CommerceModel.HostOrder\n storeName: string\n store: FirebaseFirestore.DocumentSnapshot\n /** A quote, or an order's invoice (only for a route that opens invoices). */\n kind: CommerceModel.OrderPayLinkKind\n}\n\n/**\n * The quote a link names, after its token: the quote, the replaced answer for\n * a link to an older version, or the one not-found answer for everything else.\n * With `invoices`, a draft order's invoice too (AGL-4099). With `history`, a\n * link to an older version opens the quote as well: only for a route that\n * serves the quote's record and acts on nothing (its proofs, which an earlier\n * email draws, AGL-4097); pay, answers and uploads keep the current version.\n */\nexport async function loadLinkedQuote(\n deps: QuotePayDeps,\n hostId: string,\n quoteId: string,\n token: string,\n options: { invoices?: boolean; history?: boolean } = {},\n): Promise<{ loaded: LoadedQuote } | { outcome: QuoteLinkOutcome }> {\n const notFound = options.invoices ? NOT_FOUND_ANY : NOT_FOUND\n const version = verifyQuoteLinkToken(hostId, quoteId, token)\n if (version === null) return { outcome: notFound }\n const hostRef = deps.firestore().collection('hosts').doc(hostId)\n const [hostSnapshot, store, orderSnapshot] = await Promise.all([\n hostRef.get(),\n hostRef.collection('settings').doc('store').get(),\n hostRef.collection('orders').doc(quoteId).get(),\n ])\n if (!hostSnapshot.exists || !orderSnapshot.exists) return { outcome: notFound }\n const order = orderSnapshot.data() as CommerceModel.HostOrder\n const kind = CommerceModel.orderPayLinkKind(order)\n if (kind === null || (kind === 'invoice' && !options.invoices)) return { outcome: notFound }\n const host = (hostSnapshot.data() ?? {}) as Record<string, unknown>\n const storeName = String(resolveHostToken('businessName', host as HostTokenSource) ?? '')\n const current = CommerceModel.orderPayLinkVersion(order)\n if (version > current) return { outcome: notFound }\n if (version < current && !options.history) {\n // What the customer was sent, in their words: a proof with no price says proof (AGL-4184).\n const noun = kind === 'quote' && CommerceModel.quoteIsProofOnly(order) ? 'proof' : nounOf(kind)\n return {\n outcome: {\n status: 410,\n body: {\n state: 'replaced',\n kind,\n noun,\n storeName,\n replaced: true,\n error: `This ${noun} was updated, and ${storeName || 'the business'} sent you a newer link.`,\n },\n },\n }\n }\n return { loaded: { hostRef, host, order, storeName, store, kind } }\n}\n\n/** The link's site, quote and token from a query or a body, and whether all three are there. */\nexport function quoteLinkParams(source: Record<string, unknown>) {\n const hostId = String(source['hostId'] ?? '')\n const quoteId = String(source['q'] ?? '').slice(0, 200)\n const token = String(source['t'] ?? '').slice(0, 200)\n const complete = DOC_ID.test(hostId) && DOC_ID.test(quoteId) && Boolean(token)\n return { hostId, quoteId, token, complete }\n}\n\n/** Whether the business behind a pay link can take a card payment now, and with what. */\nexport interface PayLinkPayments {\n ready: boolean\n /** The site's workspace, for the platform fee and the attempt's record. */\n owner: { id?: string; org?: any } | null\n /** The owner's payment account; empty unless `ready`. */\n accountId: string\n}\n\n/**\n * The one payments check a pay link answers on: the workspace's plan\n * includes commerce, and the workspace OWNER's payment account can take\n * charges (`merchantAccountIsReady`, the check every money route makes). The\n * page asks it before offering Pay and Pay asks it before charging, so the\n * two never disagree.\n */\nexport async function payLinkPayments(\n deps: QuotePayDeps,\n input: { hostId: string; orderId: string; kind: CommerceModel.OrderPayLinkKind },\n): Promise<PayLinkPayments> {\n const owner = await deps.orgForHost(input.hostId)\n if (!checkEntitlement(owner?.org as never, 'commerce')) return { ready: false, owner, accountId: '' }\n const ownerUid = owner?.org?.ownerUid\n const profile = ownerUid ? await deps.firestore().collection('profiles').doc(String(ownerUid)).get() : null\n const accountId = profile?.get('stripeAccountId')\n const ready = merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: profile?.get('stripeChargesEnabled'),\n accountLivemode: profile?.get('stripeAccountLivemode'),\n },\n { subject: `${nounOf(input.kind)} ${input.orderId} on host ${input.hostId}` },\n )\n return { ready, owner, accountId: ready ? String(accountId) : '' }\n}\n\n/**\n * The page's view of a linked quote or invoice: the allow-listed projection,\n * priced under the store's tax choice and with Pay only where the business\n * can take it. A paid one asks nothing about payments.\n */\nexport async function payLinkPageView(\n deps: QuotePayDeps,\n input: { hostId: string; orderId: string; loaded: Pick<LoadedQuote, 'host' | 'order' | 'storeName' | 'store' | 'kind'> },\n): Promise<CommerceModel.QuotePageView> {\n const { hostId, orderId } = input\n const { host, order, storeName, store, kind } = input.loaded\n const currency = String(store.get('currency') ?? 'USD')\n const unpaid = order.status === 'pending'\n const receiptUrl = unpaid ? null : orderStatusUrl(host, hostId, orderId)\n const paymentsReady = unpaid ? (await payLinkPayments(deps, { hostId, orderId, kind })).ready : undefined\n const view = {\n order,\n orderId,\n storeName,\n currency,\n receiptUrl,\n store: CommerceModel.payLinkStoreOf({ tax: store.get('tax') }),\n paymentsReady,\n }\n return kind === 'quote' ? CommerceModel.buildQuotePageView(view) : CommerceModel.buildInvoicePageView(view)\n}\n\n/** `GET /api/commerce/quote-view`: the quote page's data. */\nexport async function handleQuoteView(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-view:${hostId}`, QUOTE_VIEW_LOOKUPS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) {\n // The replaced page is a page, not a failure: answered as data.\n if (linked.outcome.status === 410) {\n const { storeName, kind, noun } = linked.outcome.body as {\n storeName: string\n kind: CommerceModel.OrderPayLinkKind\n noun: string\n }\n return { status: 200, body: { state: 'replaced', kind, noun, storeName } }\n }\n return linked.outcome\n }\n const view = await payLinkPageView(deps, { hostId, orderId: quoteId, loaded: linked.loaded })\n return { status: 200, body: view as unknown as Record<string, unknown> }\n}\n\n/** The Checkout Session a quote's (or an invoice's) Pay opens, as form params. Pure over its inputs. */\nexport function buildQuoteSessionParams(input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n charge: CommerceModel.QuoteCheckoutCharge & Partial<Pick<CommerceModel.InvoiceCheckoutCharge, 'shippingOptions' | 'shippingCountries'>>\n accountId: string\n feeCents: number\n taxRateId: string\n returnUrl: string\n paymentMethods: CommerceModel.StorefrontPaymentMethodControls\n /**\n * The tax basis charged when it is not the quote's stored one: a quote\n * saved before the store chose its sales tax, priced under the choice now\n * (`quotePayTax`, AGL-4162). The webhook records it on the paid order.\n */\n chargedTax?: CommerceModel.QuoteTaxBasis | null\n}): URLSearchParams {\n const { charge, order } = input\n const invoice = CommerceModel.orderPayLinkKind(order) === 'invoice'\n const quote = (order.quote ?? {}) as CommerceModel.OrderQuote\n const params = new URLSearchParams({\n mode: 'payment',\n ...checkoutSessionCardAuthenticationParams('payment'),\n ...(charge.taxAtPayment ? { 'automatic_tax[enabled]': 'true' } : {}),\n })\n charge.lines.forEach((line, index) => {\n const at = `line_items[${index}]`\n params.set(`${at}[quantity]`, '1')\n params.set(`${at}[price_data][currency]`, 'usd')\n params.set(`${at}[price_data][unit_amount]`, String(line.amountCents))\n params.set(`${at}[price_data][product_data][name]`, line.name.slice(0, 120))\n if (line.description) params.set(`${at}[price_data][product_data][description]`, line.description)\n // Stripe Tax's nontaxable code, for tax-exempt products and a tax charged as its own line.\n if (!line.taxable) params.set(`${at}[price_data][product_data][tax_code]`, 'txcd_00000000')\n if (line.taxable && input.taxRateId) params.set(`${at}[tax_rates][0]`, input.taxRateId)\n })\n // Shipping the business priced for the quote's ship-to, charged as the one\n // option, with the address asked for where it ships (and where Stripe Tax\n // reads the tax from). The quote's own address stands when it asks nothing.\n // An invoiced draft offers the rates it was made with, and the buyer picks\n // one, as on the draft's first link (AGL-4099).\n const rates = charge.shippingOptions ?? []\n if (rates.length > 0) {\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n charge.shippingCountries?.length ? charge.shippingCountries : CommerceModel.CHECKOUT_SHIPPING_COUNTRIES,\n )\n CommerceModel.appendCheckoutShippingParams(params, rates)\n } else if (charge.shippingCents > 0) {\n const country = String(quote.shipTo?.country ?? '').toUpperCase()\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n /^[A-Z]{2}$/.test(country) ? [country] : CommerceModel.CHECKOUT_SHIPPING_COUNTRIES,\n )\n CommerceModel.appendCheckoutShippingParams(params, [\n { rateId: 'quote', name: 'Shipping', amountCents: charge.shippingCents },\n ])\n }\n const shippingFloorCents = rates.length > 0 ? CommerceModel.shippingFloorCents(rates) : charge.shippingCents\n for (const [key, value] of Object.entries(\n CommerceModel.destinationChargeParams({\n accountId: input.accountId,\n feeCents: input.feeCents,\n taxOwner: charge.taxAtPayment ? 'platform' : 'merchant',\n merchantGoodsCents: charge.goodsCents,\n shippingFloorCents,\n }),\n )) {\n params.set(key, value)\n }\n const email = String((invoice ? order.customerEmail : quote.customer?.email) ?? '').trim()\n if (email) params.set('customer_email', email)\n const separator = input.returnUrl.includes('?') ? '&' : '?'\n params.set('success_url', `${input.returnUrl}${separator}session_id={CHECKOUT_SESSION_ID}`)\n params.set('cancel_url', input.returnUrl)\n // What the `commerce-draft` webhook branch reads to turn this quote into\n // its order, and to tell a payment for the quote as it stands from one for\n // a replaced link or an earlier edit.\n params.set('metadata[type]', 'commerce-draft')\n params.set('metadata[hostId]', input.hostId)\n params.set('metadata[orderId]', input.quoteId)\n if (invoice) {\n // An invoice's link version, which the draft branch compares as a\n // quote's (AGL-4099), and the promotion the draft was priced with, which\n // it counts once the draft is paid (no hold: the draft's lapsed with its\n // first session).\n params.set('metadata[payLinkVersion]', String(CommerceModel.orderPayLinkVersion(order)))\n if (order.discountId) params.set('metadata[discountId]', String(order.discountId))\n } else {\n params.set('metadata[quoteId]', input.quoteId)\n params.set('metadata[quoteLinkVersion]', String(CommerceModel.quoteLinkVersion(quote)))\n params.set('metadata[quoteUpdatedAtMs]', String(Number(quote.updatedAtMs) || 0))\n if (input.chargedTax) params.set('metadata[quoteTax]', CommerceModel.quoteTaxBasisKey(input.chargedTax))\n }\n params.set('metadata[feeCents]', String(input.feeCents))\n // A tax charged as its own line is invisible to Stripe's tax total; this\n // witness is what records it as the business's tax.\n if (charge.taxCents > 0 && charge.taxPct === null) {\n params.set('metadata[taxCents]', String(charge.taxCents))\n }\n if (charge.taxAtPayment) {\n params.set(\n 'metadata[transferCents]',\n String(\n CommerceModel.platformLiableTransferCents({\n feeCents: input.feeCents,\n merchantGoodsCents: charge.goodsCents,\n shippingFloorCents,\n }),\n ),\n )\n params.set('metadata[transferShippingCents]', String(shippingFloorCents))\n }\n // A quote or an invoice pays by card or a card-rate wallet, never by\n // buy-now-pay-later, whatever the store offers on its storefront: its fee is\n // priced at the card rate (`PAY_LINK_PROCESSING_PERCENT`).\n CommerceModel.appendStorefrontPaymentMethodParams(\n params,\n CommerceModel.payLinkPaymentMethodControls(input.paymentMethods),\n )\n return params\n}\n\nconst QUOTE_UPDATED_MESSAGE = 'This quote was updated since you opened it. Reload the page to see it before you pay.'\n\nconst refusal = (status: number, reason: string, error: string, extra: Record<string, unknown> = {}): QuoteLinkOutcome => ({\n status,\n body: { error, reason, ...extra },\n})\n\n/** `POST /api/commerce/quote-pay`: a fresh Checkout Session for the quote. */\nexport async function handleQuotePay(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n if (!process.env.STRIPE_SECRET_KEY) return { status: 501, body: { error: 'Payments are not configured.' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams(bodyOf(req))\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return { status: 400, body: { error: 'Paying needs an Idempotency-Key header.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pay:${hostId}`, QUOTE_PAY_PRESSES_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { hostRef, host, order, storeName, store, kind } = linked.loaded\n const noun = nounOf(kind)\n\n // Every refusal the customer can be given is above the claim, so none of\n // them spends the press. `v` is the edit of the quote the page showed: a\n // quote changed since is shown again before it is paid, never charged unseen.\n // An invoice is not edited, so it sends none. `tax` is the tax the page\n // priced it under: a quote saved before the store chose its sales tax is\n // priced under the choice as it stands, so one the store changed since, or\n // a page that did not say, is shown again too.\n const body = bodyOf(req)\n const seen = Number(body['v'])\n if (kind === 'quote' && Number.isFinite(seen) && seen > 0 && seen !== (Number(order.quote?.updatedAtMs) || 0)) {\n return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE)\n }\n const payStore = CommerceModel.payLinkStoreOf({ tax: store.get('tax') })\n const payTax = CommerceModel.quotePayTax(order.quote, payStore)\n if (kind === 'quote') {\n const shownTax = typeof body['tax'] === 'string' ? body['tax'] : null\n const taxKey = CommerceModel.quoteTaxBasisKey(payTax.basis)\n if (shownTax !== null ? shownTax !== taxKey : payTax.source === 'current') {\n return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE)\n }\n }\n const payments = await payLinkPayments(deps, { hostId, orderId: quoteId, kind })\n const blocked = CommerceModel.payLinkRefusalWithPayments(\n CommerceModel.invoicePayRefusal(order, quoteId, payStore),\n payments.ready,\n )\n if (blocked === 'payments-unavailable') {\n return refusal(409, blocked, CommerceModel.payLinkPaymentsUnavailableMessage(storeName, kind))\n }\n if (blocked) return refusal(409, blocked, CommerceModel.invoicePayRefusalMessage(blocked, storeName, kind))\n const { owner, accountId } = payments\n\n const charge = CommerceModel.invoiceCheckoutCharge(order, quoteId, payStore)\n // The fee is sized on the most the buyer can pay, as a draft's first link\n // sized it on its dearest rate, and its processing half at the card rate:\n // the session below excludes every buy-now-pay-later method.\n const dearestRateCents = charge.shippingOptions.reduce((most, rate) => Math.max(most, rate.amountCents), 0)\n const feeCents = resolveTransactionFeeCents(\n owner?.org as never,\n charge.feeProductType,\n charge.goodsCents,\n charge.totalCents + dearestRateCents,\n PAY_LINK_PROCESSING_PERCENT,\n )\n const nativeMode = await deps.nativeMode(String(owner?.id ?? ''))\n const site = host as SiteReturnHost\n const origin = siteReturnOrigin({\n candidates: [headerOf(req, 'referer'), `https://${headerOf(req, 'host')}`],\n site,\n requestHost: headerOf(req, 'host'),\n })\n const returnUrl = `${origin}${quotePageHref(quoteId, token)}`\n // A draft's first session (the one its paymentLinkUrl opens) is closed\n // here too, so the draft has one way to pay from the first press on.\n const openedFor = order.checkoutSessionId ?? ''\n const openedAtEdit = Number(order.quote?.updatedAtMs) || 0\n const openedAtVersion = CommerceModel.orderPayLinkVersion(order)\n\n const claimed = await claimAttempt(deps.firestore(), {\n kind: 'commerce-quote-pay',\n scopeId: `${hostId}:${quoteId}`,\n orgId: String(owner?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'Your payment is already being set up',\n })\n if ('replay' in claimed) {\n return { status: claimed.replay.status, body: claimed.replay.body as Record<string, unknown> }\n }\n const claim = claimed.claim\n const stripeKey = (object: string): Record<string, string> => {\n const derived = deriveStripeObjectKey(claim.stripeKey, object)\n return derived ? { 'Idempotency-Key': derived } : {}\n }\n let minted = ''\n try {\n // The session the last press opened is closed before another opens. One\n // that was paid a moment ago means the quote is paid; one that cannot be\n // closed means a second session would be a second way to pay.\n if (openedFor) {\n const previous = await deps.expireSession(openedFor)\n if (previous === 'complete') {\n await claim.release()\n return refusal(409, 'paid', `This ${noun} has just been paid. Your receipt is on its way.`, { confirming: true })\n }\n if (previous === 'open') {\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n }\n\n let taxRateId = ''\n if (charge.taxPct !== null && charge.taxableCents > 0) {\n const basis = kind === 'quote' ? payTax.basis : null\n taxRateId =\n (await deps.taxRateId({\n hostRef,\n taxPct: charge.taxPct,\n taxLabel:\n basis?.kind === 'rate'\n ? basis.label || `Tax (${charge.taxPct}%)`\n : 'Sales tax',\n headers: stripeKey(`tax-rate-${Math.round(charge.taxPct * 10_000)}`),\n })) ?? ''\n if (!taxRateId) {\n // Never an untaxed session for a taxed quote.\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n }\n\n const paymentMethods = CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(store.get('paymentMethods')),\n )\n const params = buildQuoteSessionParams({\n hostId,\n quoteId,\n order,\n charge,\n accountId: String(accountId),\n feeCents,\n taxRateId,\n returnUrl,\n paymentMethods,\n chargedTax: kind === 'quote' && payTax.source === 'current' ? payTax.basis : null,\n })\n if (nativeMode.native) {\n applyNativeCheckoutParams(params, params.get('success_url') ?? returnUrl)\n }\n const domain = nativeMode.native\n ? deps.ensureDomain({ pageUrl: returnUrl, site, hostId })\n : Promise.resolve(null)\n const created = await deps.createSession(params, {\n ...stripeKey('session'),\n ...nativeCheckoutStripeHeaders(nativeMode),\n })\n await domain\n const payload = created.ok\n ? readCheckoutSessionPayload(created.session, nativeMode, paymentMethods.wallets)\n : null\n if (!payload || !created.session.id) {\n console.error('Stripe quote checkout error', created.session?.error)\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n minted = String(created.session.id)\n\n // The quote keeps the session it now has open. Whatever another press\n // stored meanwhile is closed after, so the last press is the one open\n // session; a quote that was paid, replaced or edited meanwhile closes\n // this one instead.\n const orderRef = hostRef.collection('orders').doc(quoteId)\n const settled = await deps.firestore().runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n const current = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n if (!current || CommerceModel.orderPayLinkKind(current) !== kind) return { outcome: NOT_FOUND_ANY, displaced: '' }\n if (current.status !== 'pending') {\n const closed = current.status === 'cancelled' || current.status === 'refunded'\n return {\n outcome: refusal(\n 409,\n closed ? 'closed' : 'paid',\n CommerceModel.invoicePayRefusalMessage(closed ? 'closed' : 'paid', storeName, kind),\n ),\n displaced: '',\n }\n }\n if (CommerceModel.orderPayLinkVersion(current) !== openedAtVersion) {\n return {\n outcome: {\n status: 410,\n body: { replaced: true, error: `This ${noun} was updated, and ${storeName || 'the business'} sent you a newer link.` },\n },\n displaced: '',\n }\n }\n if (kind === 'quote' && (Number(current.quote?.updatedAtMs) || 0) !== openedAtEdit) {\n return { outcome: refusal(409, 'updated', QUOTE_UPDATED_MESSAGE), displaced: '' }\n }\n transaction.set(orderRef, { checkoutSessionId: minted }, { merge: true })\n const displaced = current.checkoutSessionId && current.checkoutSessionId !== openedFor ? current.checkoutSessionId : ''\n return { outcome: null, displaced }\n })\n if (settled.outcome) {\n await deps.expireSession(minted)\n await claim.release()\n return settled.outcome\n }\n if (settled.displaced && settled.displaced !== minted) await deps.expireSession(settled.displaced)\n await claim.record(200, payload)\n return { status: 200, body: payload as unknown as Record<string, unknown> }\n } catch (error) {\n console.error('quote pay failed', error)\n if (minted) await deps.expireSession(minted).catch(() => 'open')\n await claim.release()\n return { status: 500, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n}\n\n/** Sends a link route's answer, never cached or indexed. */\nexport function sendQuoteLinkOutcome(res: Parameters<PluginApiHandler>[1], outcome: QuoteLinkOutcome) {\n res.setHeader('Cache-Control', 'private, no-store')\n res.setHeader('X-Robots-Tag', 'noindex, nofollow')\n for (const [name, value] of Object.entries(outcome.headers ?? {})) res.setHeader(name, value)\n return res.status(outcome.status).json(outcome.body)\n}\n\n/** `GET /api/commerce/quote-view`. */\nexport const quoteViewHandler: PluginApiHandler = async (req, res) => {\n try {\n return sendQuoteLinkOutcome(res, await handleQuoteView(defaultQuotePayDeps(), req))\n } catch (error) {\n console.error('quote view failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be loaded. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-pay`. */\nexport const quotePayHandler: PluginApiHandler = async (req, res) =>\n sendQuoteLinkOutcome(res, await handleQuotePay(defaultQuotePayDeps(), req))\n"],"names":["checkEntitlement","claimAttempt","deriveStripeObjectKey","PAY_LINK_PROCESSING_PERCENT","resolveTransactionFeeCents","resolveHostToken","readClientIp","siteReturnOrigin","consumeRateLimit","firebaseAdmin","getOrgForHost","merchantAccountIsReady","checkoutSessionCardAuthenticationParams","quotePageHref","CommerceModel","expireCheckoutSession","resolveManualTaxRateId","applyNativeCheckoutParams","nativeCheckoutStripeHeaders","readCheckoutSessionPayload","resolveNativeCheckoutMode","orderStatusUrl","ensureCheckoutDomain","verifyQuoteLinkToken","QUOTE_VIEW_LOOKUPS_PER_WINDOW","QUOTE_PAY_PRESSES_PER_WINDOW","QUOTE_WINDOW_MS","defaultQuotePayDeps","firestore","app","key","options","orgForHost","hostId","found","id","orgId","org","nativeMode","taxRateId","input","createSession","params","headers","response","fetch","method","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","ok","session","json","catch","expireSession","sessionId","ensureDomain","now","Date","DOC_ID","NOT_FOUND","status","error","NOT_FOUND_ANY","nounOf","kind","bodyOf","req","raw","parsed","JSON","parse","headerOf","name","value","toLowerCase","String","Array","isArray","trim","limitedQuoteLink","deps","limit","ip","remoteAddress","socket","rate","windowMs","allowed","Math","max","ceil","resetMs","loadLinkedQuote","quoteId","token","hostSnapshot","notFound","invoices","version","outcome","hostRef","collection","doc","store","orderSnapshot","Promise","all","get","exists","order","data","orderPayLinkKind","host","storeName","current","orderPayLinkVersion","history","noun","quoteIsProofOnly","state","replaced","loaded","quoteLinkParams","source","slice","complete","test","Boolean","payLinkPayments","owner","ready","accountId","ownerUid","profile","chargesEnabled","accountLivemode","subject","orderId","payLinkPageView","currency","unpaid","receiptUrl","paymentsReady","undefined","view","payLinkStoreOf","tax","buildQuotePageView","buildInvoicePageView","handleQuoteView","query","refused","linked","buildQuoteSessionParams","charge","invoice","quote","URLSearchParams","mode","taxAtPayment","lines","forEach","line","index","at","set","amountCents","description","taxable","rates","shippingOptions","length","appendShippingAddressCollectionParams","shippingCountries","CHECKOUT_SHIPPING_COUNTRIES","appendCheckoutShippingParams","shippingCents","country","shipTo","toUpperCase","rateId","shippingFloorCents","Object","entries","destinationChargeParams","feeCents","taxOwner","merchantGoodsCents","goodsCents","email","customerEmail","customer","separator","returnUrl","includes","discountId","quoteLinkVersion","Number","updatedAtMs","chargedTax","quoteTaxBasisKey","taxCents","taxPct","platformLiableTransferCents","appendStorefrontPaymentMethodParams","payLinkPaymentMethodControls","paymentMethods","QUOTE_UPDATED_MESSAGE","refusal","reason","extra","handleQuotePay","idempotencyKey","seen","isFinite","payStore","payTax","quotePayTax","shownTax","taxKey","basis","payments","blocked","payLinkRefusalWithPayments","invoicePayRefusal","payLinkPaymentsUnavailableMessage","invoicePayRefusalMessage","invoiceCheckoutCharge","dearestRateCents","reduce","most","feeProductType","totalCents","site","origin","candidates","requestHost","openedFor","checkoutSessionId","openedAtEdit","openedAtVersion","claimed","scopeId","busyMessage","replay","claim","stripeKey","object","derived","minted","previous","release","confirming","taxableCents","taxLabel","label","round","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","native","domain","pageUrl","resolve","created","payload","wallets","console","orderRef","settled","runTransaction","transaction","snapshot","displaced","closed","merge","record","sendQuoteLinkOutcome","res","setHeader","quoteViewHandler","quotePayHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,YAAY,EACZC,qBAAqB,EACrBC,2BAA2B,EAC3BC,0BAA0B,QAGrB,sBAAqB;AAC5B,SAASC,gBAAgB,QAA8B,qCAAoC;AAC3F,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAA8BC,gBAAgB,QAAQ,yCAAwC;AAC9F,SAASC,gBAAgB,EAAEC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACzF,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SAASC,aAAa,QAAQ,6BAAyB;AACvD,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,qBAAqB,QAAoC,+BAA2B;AAC7F,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SACEC,yBAAyB,EACzBC,2BAA2B,EAC3BC,0BAA0B,EAC1BC,yBAAyB,QAEpB,uBAAmB;AAC1B,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,oBAAoB,QAAQ,8BAA0B;AAC/D,SAASC,oBAAoB,QAAQ,wBAAoB;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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MAAM,CAAC9M,MAAMC,MAAM,IAAI6G,OAAOC,OAAO,EAACpF,mBAAAA,QAAQ5D,OAAO,YAAf4D,mBAAmB,CAAC,GAAIkL,IAAIC,SAAS,CAAC9M,MAAMC;IACvF,OAAO4M,IAAIzN,MAAM,CAACuC,QAAQvC,MAAM,EAAET,IAAI,CAACgD,QAAQpD,IAAI;AACrD;AAEA,oCAAoC,GACpC,OAAO,MAAMwO,mBAAqC,OAAOrN,KAAKmN;IAC5D,IAAI;QACF,OAAOD,qBAAqBC,KAAK,MAAMhI,gBAAgB9H,uBAAuB2C;IAChF,EAAE,OAAOL,OAAO;QACd6M,QAAQ7M,KAAK,CAAC,qBAAqBA;QACnC,OAAOuN,qBAAqBC,KAAK;YAAEzN,QAAQ;YAAKb,MAAM;gBAAEc,OAAO;YAA6C;QAAE;IAChH;AACF,EAAC;AAED,oCAAoC,GACpC,OAAO,MAAM2N,kBAAoC,OAAOtN,KAAKmN,MAC3DD,qBAAqBC,KAAK,MAAMlE,eAAe5L,uBAAuB2C,MAAK"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-pay.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 {\n checkEntitlement,\n claimAttempt,\n deriveStripeObjectKey,\n resolveTransactionFeeCents,\n type PluginApiHandler,\n type PluginApiRequest,\n} from '@aglyn/aglyn/server'\nimport { resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { type SiteReturnHost, siteReturnOrigin } from '@aglyn/aglyn/app-utils/site-return-url'\nimport { consumeRateLimit, firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n connectedAccountHeader,\n directChargeParams,\n merchantAccountIsReady,\n saleChargeModel,\n type SaleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport { quotePageHref } from '../constants/quote-page'\nimport * as CommerceModel from '../model'\nimport { expireCheckoutSession, type CheckoutSessionExpiry } from './checkout-session-expiry'\nimport { resolveManualTaxRateId } from './manual-tax-rate'\nimport {\n applyNativeCheckoutParams,\n nativeCheckoutStripeHeaders,\n readCheckoutSessionPayload,\n resolveNativeCheckoutMode,\n type NativeCheckoutMode,\n} from './native-checkout'\nimport { orderStatusUrl } from './order-status-token'\nimport { ensureCheckoutDomain } from './payment-method-domains'\nimport { verifyQuoteLinkToken } from './quote-link-token'\nimport { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from './seller-stripe-account'\n\n/*==========================================\n * THE CUSTOMER'S QUOTE PAGE AND ITS PAY BUTTON (AGL-4094), AND AN\n * INVOICE'S (AGL-4099).\n *\n * GET /api/commerce/quote-view?hostId=&q=<quoteId>&t=<token>\n * → 200 QuotePageView | 200 { state: 'replaced', storeName } | 404\n * POST /api/commerce/quote-pay { hostId, q, t, v } + Idempotency-Key\n * → 200 { url } (Stripe's page) | 200 { clientSecret, publishableKey, sessionId, wallets? }\n * (the in-page form) | 409 { error, reason } | 410 { error, replaced: true } | 404\n *\n * The signed link (`quote-link-token.ts`) is the whole credential. A wrong\n * token answers exactly as a missing quote does, so neither route tells\n * anyone which quote ids exist; both are rate-limited per address per site\n * BEFORE the token check, so guessing costs what looking does. A link signed\n * for an older version of the quote opens the replaced page and nothing else.\n *\n * Pay opens a FRESH Checkout Session from the stored quote on every press:\n * the prices are the stored lines', never anything the page sends, and the\n * session the previous press opened is expired first, so two sessions for one\n * quote can never both be open. The quote keeps the open one in\n * `checkoutSessionId`. A Stripe session lapses after a day; the quote and its\n * link do not, because the next press opens another.\n *\n * The payment completes in `billing-webhook.ts`, which turns this same\n * document into the order (`paidQuoteOrder`); nothing here marks it paid.\n *\n * THE PAGE OFFERS ONLY A PAY THAT WORKS (AGL-4162). The view asks the same\n * payments check Pay refuses on ({@link payLinkPayments}) and prices the tax\n * the same way (`quotePayTax`): a quote saved before the store chose its\n * sales tax is shown and charged under the store's choice now, and Pay\n * refuses when that choice is not the one the page showed (`tax`). The\n * session carries that basis (`quoteTax`) so the paid order records it.\n *\n * AN INVOICE'S LINK IS THIS ONE (AGL-4099). A draft order the business sent\n * an invoice for opens on the same page from the same kind of link (its\n * version on `payLink.version`, `commerce-invoices.ts`), as \"Invoice #N\" with\n * no proofs or approval, and Pay opens the same kind of fresh session from\n * its stored lines, discount, tax and the shipping rates it was made with.\n * Its webhook is the draft branch it always completed through, which flips\n * the draft to paid without restamping its list fields. The proof and answer\n * routes stay a quote's alone: `loadLinkedQuote` opens an invoice only for\n * the routes that ask (`{ invoices: true }`).\n *=========================================*/\n\n/** Lookups and presses one address may make per site, per ten minutes. */\nexport const QUOTE_VIEW_LOOKUPS_PER_WINDOW = 60\nexport const QUOTE_PAY_PRESSES_PER_WINDOW = 20\nexport const QUOTE_WINDOW_MS = 10 * 60_000\n\nexport interface QuotePayDeps {\n firestore(): FirebaseFirestore.Firestore\n consumeRateLimit(key: string, options: { limit: number; windowMs: number }): Promise<{ allowed: boolean; resetMs: number }>\n orgForHost(hostId: string): Promise<{ id?: string; org?: any } | null>\n nativeMode(orgId: string): Promise<NativeCheckoutMode>\n /** The store's manual tax rate as a Stripe tax rate, or null when one cannot be had. */\n taxRateId(input: Parameters<typeof resolveManualTaxRateId>[0]): Promise<string | null>\n createSession(\n params: URLSearchParams,\n headers: Record<string, string>,\n ): Promise<{ ok: boolean; session: { id?: string; url?: string; client_secret?: string; error?: unknown } }>\n /**\n * Closes a session so it can no longer be paid. `stripeAccount` names the\n * seller's account for a session opened there (a direct charge); absent, the\n * session is the platform's.\n */\n expireSession(sessionId: string, stripeAccount?: string): Promise<CheckoutSessionExpiry>\n /**\n * Whether the seller's own Stripe Tax is set up, for a direct charge that\n * asks Stripe Tax. Absent, `sellerStripeTaxActive` answers.\n */\n sellerTaxActive?(accountId: string): Promise<boolean>\n /** Registers the page's domain for Apple Pay; never throws. */\n ensureDomain(input: Parameters<typeof ensureCheckoutDomain>[0]): Promise<unknown>\n now(): number\n}\n\nexport function defaultQuotePayDeps(): QuotePayDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore(),\n consumeRateLimit: (key, options) => consumeRateLimit(key, options),\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n nativeMode: (orgId) => resolveNativeCheckoutMode(orgId),\n taxRateId: (input) => resolveManualTaxRateId(input),\n createSession: async (params, headers) => {\n const response = await fetch('https://api.stripe.com/v1/checkout/sessions', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...headers,\n },\n body: params.toString(),\n })\n return { ok: response.ok, session: (await response.json().catch(() => ({}))) as never }\n },\n expireSession: (sessionId, stripeAccount) =>\n stripeAccount ? expireConnectedCheckoutSession(sessionId, stripeAccount) : expireCheckoutSession(sessionId),\n ensureDomain: (input) => ensureCheckoutDomain(input).catch(() => null),\n now: () => Date.now(),\n }\n}\n\n/**\n * `expireCheckoutSession` for a session on the seller's own account (a direct\n * charge), where the platform's call answers 404. Same answers, same rule: a\n * refused expiry reads the session back, so a paid one is never read as closed.\n */\nasync function expireConnectedCheckoutSession(\n sessionId: string,\n stripeAccount: string,\n): Promise<CheckoutSessionExpiry> {\n if (!/^cs_(test|live)_[A-Za-z0-9]{8,255}$/.test(String(sessionId ?? ''))) return 'missing'\n const secretKey = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!secretKey) return 'open'\n const headers = {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Stripe-Account': stripeAccount,\n }\n try {\n const expired = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}/expire`, {\n method: 'POST',\n headers,\n })\n if (expired.ok) return 'expired'\n const read = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, { headers })\n if (read.status === 404) return 'missing'\n if (!read.ok) return 'open'\n const session = (await read.json().catch(() => ({}))) as { status?: string }\n if (session.status === 'complete') return 'complete'\n if (session.status === 'expired') return 'expired'\n return 'open'\n } catch {\n return 'open'\n }\n}\n\n/** A link route's answer: a status, a JSON body and any extra headers. */\nexport type QuoteLinkOutcome = { status: number; body: Record<string, unknown>; headers?: Record<string, string> }\n\nconst DOC_ID = /^(?!__.*__$)[^/]{1,200}$/\n\nconst NOT_FOUND: QuoteLinkOutcome = {\n status: 404,\n body: { error: 'We could not find that quote. Check the link you were sent.' },\n}\n\n/** The not-found answer of a route an invoice's link reaches too: it names neither. */\nconst NOT_FOUND_ANY: QuoteLinkOutcome = {\n status: 404,\n body: { error: 'We could not find that quote or invoice. Check the link you were sent.' },\n}\n\n/** `quote` or `invoice`, as the customer reads it. */\nconst nounOf = (kind: CommerceModel.OrderPayLinkKind) => (kind === 'invoice' ? 'invoice' : 'quote')\n\nfunction bodyOf(req: PluginApiRequest): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}\n}\n\nfunction headerOf(req: PluginApiRequest, name: string): string {\n const headers = (req.headers ?? {}) as Record<string, unknown>\n const value = headers[name.toLowerCase()] ?? headers[name]\n return String(Array.isArray(value) ? (value[0] ?? '') : (value ?? '')).trim()\n}\n\n/** The rate limit a link route spends per address per site, BEFORE the token is checked. */\nexport async function limitedQuoteLink(\n deps: QuotePayDeps,\n req: PluginApiRequest,\n key: string,\n limit: number,\n): Promise<QuoteLinkOutcome | null> {\n const ip = readClientIp(req.headers as never, { remoteAddress: req.socket?.remoteAddress }) ?? 'no-address'\n const rate = await deps.consumeRateLimit(`${key}:${ip}`, { limit, windowMs: QUOTE_WINDOW_MS })\n if (rate.allowed) return null\n return {\n status: 429,\n body: { error: 'Too many tries. Try again in a few minutes.' },\n headers: { 'Retry-After': String(Math.max(1, Math.ceil((rate.resetMs - deps.now()) / 1000))) },\n }\n}\n\nexport interface LoadedQuote {\n hostRef: FirebaseFirestore.DocumentReference\n host: Record<string, unknown>\n order: CommerceModel.HostOrder\n storeName: string\n store: FirebaseFirestore.DocumentSnapshot\n /** A quote, or an order's invoice (only for a route that opens invoices). */\n kind: CommerceModel.OrderPayLinkKind\n}\n\n/**\n * The quote a link names, after its token: the quote, the replaced answer for\n * a link to an older version, or the one not-found answer for everything else.\n * With `invoices`, a draft order's invoice too (AGL-4099). With `history`, a\n * link to an older version opens the quote as well: only for a route that\n * serves the quote's record and acts on nothing (its proofs, which an earlier\n * email draws, AGL-4097); pay, answers and uploads keep the current version.\n */\nexport async function loadLinkedQuote(\n deps: QuotePayDeps,\n hostId: string,\n quoteId: string,\n token: string,\n options: { invoices?: boolean; history?: boolean } = {},\n): Promise<{ loaded: LoadedQuote } | { outcome: QuoteLinkOutcome }> {\n const notFound = options.invoices ? NOT_FOUND_ANY : NOT_FOUND\n const version = verifyQuoteLinkToken(hostId, quoteId, token)\n if (version === null) return { outcome: notFound }\n const hostRef = deps.firestore().collection('hosts').doc(hostId)\n const [hostSnapshot, store, orderSnapshot] = await Promise.all([\n hostRef.get(),\n hostRef.collection('settings').doc('store').get(),\n hostRef.collection('orders').doc(quoteId).get(),\n ])\n if (!hostSnapshot.exists || !orderSnapshot.exists) return { outcome: notFound }\n const order = orderSnapshot.data() as CommerceModel.HostOrder\n const kind = CommerceModel.orderPayLinkKind(order)\n if (kind === null || (kind === 'invoice' && !options.invoices)) return { outcome: notFound }\n const host = (hostSnapshot.data() ?? {}) as Record<string, unknown>\n const storeName = String(resolveHostToken('businessName', host as HostTokenSource) ?? '')\n const current = CommerceModel.orderPayLinkVersion(order)\n if (version > current) return { outcome: notFound }\n if (version < current && !options.history) {\n // What the customer was sent, in their words: a proof with no price says proof (AGL-4184).\n const noun = kind === 'quote' && CommerceModel.quoteIsProofOnly(order) ? 'proof' : nounOf(kind)\n return {\n outcome: {\n status: 410,\n body: {\n state: 'replaced',\n kind,\n noun,\n storeName,\n replaced: true,\n error: `This ${noun} was updated, and ${storeName || 'the business'} sent you a newer link.`,\n },\n },\n }\n }\n return { loaded: { hostRef, host, order, storeName, store, kind } }\n}\n\n/** The link's site, quote and token from a query or a body, and whether all three are there. */\nexport function quoteLinkParams(source: Record<string, unknown>) {\n const hostId = String(source['hostId'] ?? '')\n const quoteId = String(source['q'] ?? '').slice(0, 200)\n const token = String(source['t'] ?? '').slice(0, 200)\n const complete = DOC_ID.test(hostId) && DOC_ID.test(quoteId) && Boolean(token)\n return { hostId, quoteId, token, complete }\n}\n\n/** Whether the business behind a pay link can take a card payment now, and with what. */\nexport interface PayLinkPayments {\n ready: boolean\n /** The site's workspace, for the platform fee and the attempt's record. */\n owner: { id?: string; org?: any } | null\n /** The owner's payment account; empty unless `ready`. */\n accountId: string\n /**\n * Whether a sale is a direct charge on that account or a destination charge\n * from the platform's, as the connect route recorded it on the profile.\n */\n chargeModel: SaleChargeModel\n}\n\n/**\n * The one payments check a pay link answers on: the workspace's plan\n * includes commerce, and the workspace OWNER's payment account can take\n * charges (`merchantAccountIsReady`, the check every money route makes). The\n * page asks it before offering Pay and Pay asks it before charging, so the\n * two never disagree.\n */\nexport async function payLinkPayments(\n deps: QuotePayDeps,\n input: { hostId: string; orderId: string; kind: CommerceModel.OrderPayLinkKind },\n): Promise<PayLinkPayments> {\n const owner = await deps.orgForHost(input.hostId)\n if (!checkEntitlement(owner?.org as never, 'commerce')) {\n return { ready: false, owner, accountId: '', chargeModel: 'destination' }\n }\n const ownerUid = owner?.org?.ownerUid\n const profile = ownerUid ? await deps.firestore().collection('profiles').doc(String(ownerUid)).get() : null\n const accountId = profile?.get('stripeAccountId')\n const ready = merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: profile?.get('stripeChargesEnabled'),\n accountLivemode: profile?.get('stripeAccountLivemode'),\n },\n { subject: `${nounOf(input.kind)} ${input.orderId} on host ${input.hostId}` },\n )\n return {\n ready,\n owner,\n accountId: ready ? String(accountId) : '',\n chargeModel: saleChargeModel(profile?.get('stripeChargeModel')),\n }\n}\n\n/**\n * The page's view of a linked quote or invoice: the allow-listed projection,\n * priced under the store's tax choice and with Pay only where the business\n * can take it. A paid one asks nothing about payments.\n */\nexport async function payLinkPageView(\n deps: QuotePayDeps,\n input: { hostId: string; orderId: string; loaded: Pick<LoadedQuote, 'host' | 'order' | 'storeName' | 'store' | 'kind'> },\n): Promise<CommerceModel.QuotePageView> {\n const { hostId, orderId } = input\n const { host, order, storeName, store, kind } = input.loaded\n const currency = String(store.get('currency') ?? 'USD')\n const unpaid = order.status === 'pending'\n const receiptUrl = unpaid ? null : orderStatusUrl(host, hostId, orderId)\n const paymentsReady = unpaid ? (await payLinkPayments(deps, { hostId, orderId, kind })).ready : undefined\n const view = {\n order,\n orderId,\n storeName,\n currency,\n receiptUrl,\n store: CommerceModel.payLinkStoreOf({ tax: store.get('tax') }),\n paymentsReady,\n }\n return kind === 'quote' ? CommerceModel.buildQuotePageView(view) : CommerceModel.buildInvoicePageView(view)\n}\n\n/** `GET /api/commerce/quote-view`: the quote page's data. */\nexport async function handleQuoteView(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-view:${hostId}`, QUOTE_VIEW_LOOKUPS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) {\n // The replaced page is a page, not a failure: answered as data.\n if (linked.outcome.status === 410) {\n const { storeName, kind, noun } = linked.outcome.body as {\n storeName: string\n kind: CommerceModel.OrderPayLinkKind\n noun: string\n }\n return { status: 200, body: { state: 'replaced', kind, noun, storeName } }\n }\n return linked.outcome\n }\n const view = await payLinkPageView(deps, { hostId, orderId: quoteId, loaded: linked.loaded })\n return { status: 200, body: view as unknown as Record<string, unknown> }\n}\n\n/** The Checkout Session a quote's (or an invoice's) Pay opens, as form params. Pure over its inputs. */\nexport function buildQuoteSessionParams(input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n charge: CommerceModel.QuoteCheckoutCharge & Partial<Pick<CommerceModel.InvoiceCheckoutCharge, 'shippingOptions' | 'shippingCountries'>>\n accountId: string\n /**\n * `direct` opens the session ON the seller's account (the caller sends the\n * `Stripe-Account` header): Aglyn's take is the application fee, the seller\n * owns any Stripe Tax, and nothing is transferred. Absent is `destination`.\n */\n chargeModel?: SaleChargeModel\n feeCents: number\n taxRateId: string\n returnUrl: string\n paymentMethods: CommerceModel.StorefrontPaymentMethodControls\n /**\n * The tax basis charged when it is not the quote's stored one: a quote\n * saved before the store chose its sales tax, priced under the choice now\n * (`quotePayTax`, AGL-4162). The webhook records it on the paid order.\n */\n chargedTax?: CommerceModel.QuoteTaxBasis | null\n}): URLSearchParams {\n const { charge, order } = input\n const invoice = CommerceModel.orderPayLinkKind(order) === 'invoice'\n const quote = (order.quote ?? {}) as CommerceModel.OrderQuote\n const params = new URLSearchParams({\n mode: 'payment',\n ...checkoutSessionCardAuthenticationParams('payment'),\n ...(charge.taxAtPayment ? { 'automatic_tax[enabled]': 'true' } : {}),\n })\n charge.lines.forEach((line, index) => {\n const at = `line_items[${index}]`\n params.set(`${at}[quantity]`, '1')\n params.set(`${at}[price_data][currency]`, 'usd')\n params.set(`${at}[price_data][unit_amount]`, String(line.amountCents))\n params.set(`${at}[price_data][product_data][name]`, line.name.slice(0, 120))\n if (line.description) params.set(`${at}[price_data][product_data][description]`, line.description)\n // Stripe Tax's nontaxable code, for tax-exempt products and a tax charged as its own line.\n if (!line.taxable) params.set(`${at}[price_data][product_data][tax_code]`, 'txcd_00000000')\n if (line.taxable && input.taxRateId) params.set(`${at}[tax_rates][0]`, input.taxRateId)\n })\n // Shipping the business priced for the quote's ship-to, charged as the one\n // option, with the address asked for where it ships (and where Stripe Tax\n // reads the tax from). The quote's own address stands when it asks nothing.\n // An invoiced draft offers the rates it was made with, and the buyer picks\n // one, as on the draft's first link (AGL-4099).\n const rates = charge.shippingOptions ?? []\n if (rates.length > 0) {\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n charge.shippingCountries?.length ? charge.shippingCountries : CommerceModel.CHECKOUT_SHIPPING_COUNTRIES,\n )\n CommerceModel.appendCheckoutShippingParams(params, rates)\n } else if (charge.shippingCents > 0) {\n const country = String(quote.shipTo?.country ?? '').toUpperCase()\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n /^[A-Z]{2}$/.test(country) ? [country] : CommerceModel.CHECKOUT_SHIPPING_COUNTRIES,\n )\n CommerceModel.appendCheckoutShippingParams(params, [\n { rateId: 'quote', name: 'Shipping', amountCents: charge.shippingCents },\n ])\n }\n const shippingFloorCents = rates.length > 0 ? CommerceModel.shippingFloorCents(rates) : charge.shippingCents\n const direct = input.chargeModel === 'direct'\n for (const [key, value] of Object.entries(\n // A direct charge is already the seller's money, Stripe Tax included\n // (computed on THEIR registrations), so the take is the whole split.\n direct\n ? directChargeParams(input.feeCents)\n : CommerceModel.destinationChargeParams({\n accountId: input.accountId,\n feeCents: input.feeCents,\n taxOwner: charge.taxAtPayment ? 'platform' : 'merchant',\n merchantGoodsCents: charge.goodsCents,\n shippingFloorCents,\n }),\n )) {\n params.set(key, value)\n }\n const email = String((invoice ? order.customerEmail : quote.customer?.email) ?? '').trim()\n if (email) params.set('customer_email', email)\n const separator = input.returnUrl.includes('?') ? '&' : '?'\n params.set('success_url', `${input.returnUrl}${separator}session_id={CHECKOUT_SESSION_ID}`)\n params.set('cancel_url', input.returnUrl)\n // What the `commerce-draft` webhook branch reads to turn this quote into\n // its order, and to tell a payment for the quote as it stands from one for\n // a replaced link or an earlier edit.\n params.set('metadata[type]', 'commerce-draft')\n params.set('metadata[hostId]', input.hostId)\n params.set('metadata[orderId]', input.quoteId)\n if (invoice) {\n // An invoice's link version, which the draft branch compares as a\n // quote's (AGL-4099), and the promotion the draft was priced with, which\n // it counts once the draft is paid (no hold: the draft's lapsed with its\n // first session).\n params.set('metadata[payLinkVersion]', String(CommerceModel.orderPayLinkVersion(order)))\n if (order.discountId) params.set('metadata[discountId]', String(order.discountId))\n } else {\n params.set('metadata[quoteId]', input.quoteId)\n params.set('metadata[quoteLinkVersion]', String(CommerceModel.quoteLinkVersion(quote)))\n params.set('metadata[quoteUpdatedAtMs]', String(Number(quote.updatedAtMs) || 0))\n if (input.chargedTax) params.set('metadata[quoteTax]', CommerceModel.quoteTaxBasisKey(input.chargedTax))\n }\n params.set('metadata[feeCents]', String(input.feeCents))\n // What the webhook, refunds and reports read to find the payment on the\n // seller's account rather than the platform's.\n if (direct) params.set('metadata[chargeModel]', 'direct')\n // A tax charged as its own line is invisible to Stripe's tax total; this\n // witness is what records it as the business's tax.\n if (charge.taxCents > 0 && charge.taxPct === null) {\n params.set('metadata[taxCents]', String(charge.taxCents))\n }\n // The fixed transfer Aglyn keeps its Stripe Tax back from; a direct charge\n // transfers nothing and its tax is the seller's.\n if (charge.taxAtPayment && !direct) {\n params.set(\n 'metadata[transferCents]',\n String(\n CommerceModel.platformLiableTransferCents({\n feeCents: input.feeCents,\n merchantGoodsCents: charge.goodsCents,\n shippingFloorCents,\n }),\n ),\n )\n params.set('metadata[transferShippingCents]', String(shippingFloorCents))\n }\n // The store's choices, and never buy-now-pay-later (AGL-4198), so the fee\n // above is priced at the card rate.\n CommerceModel.appendStorefrontPaymentMethodParams(params, input.paymentMethods)\n return params\n}\n\nconst QUOTE_UPDATED_MESSAGE = 'This quote was updated since you opened it. Reload the page to see it before you pay.'\n\nconst refusal = (status: number, reason: string, error: string, extra: Record<string, unknown> = {}): QuoteLinkOutcome => ({\n status,\n body: { error, reason, ...extra },\n})\n\n/** `POST /api/commerce/quote-pay`: a fresh Checkout Session for the quote. */\nexport async function handleQuotePay(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n if (!process.env.STRIPE_SECRET_KEY) return { status: 501, body: { error: 'Payments are not configured.' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams(bodyOf(req))\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return { status: 400, body: { error: 'Paying needs an Idempotency-Key header.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pay:${hostId}`, QUOTE_PAY_PRESSES_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { hostRef, host, order, storeName, store, kind } = linked.loaded\n const noun = nounOf(kind)\n\n // Every refusal the customer can be given is above the claim, so none of\n // them spends the press. `v` is the edit of the quote the page showed: a\n // quote changed since is shown again before it is paid, never charged unseen.\n // An invoice is not edited, so it sends none. `tax` is the tax the page\n // priced it under: a quote saved before the store chose its sales tax is\n // priced under the choice as it stands, so one the store changed since, or\n // a page that did not say, is shown again too.\n const body = bodyOf(req)\n const seen = Number(body['v'])\n if (kind === 'quote' && Number.isFinite(seen) && seen > 0 && seen !== (Number(order.quote?.updatedAtMs) || 0)) {\n return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE)\n }\n const payStore = CommerceModel.payLinkStoreOf({ tax: store.get('tax') })\n const payTax = CommerceModel.quotePayTax(order.quote, payStore)\n if (kind === 'quote') {\n const shownTax = typeof body['tax'] === 'string' ? body['tax'] : null\n const taxKey = CommerceModel.quoteTaxBasisKey(payTax.basis)\n if (shownTax !== null ? shownTax !== taxKey : payTax.source === 'current') {\n return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE)\n }\n }\n const payments = await payLinkPayments(deps, { hostId, orderId: quoteId, kind })\n const blocked = CommerceModel.payLinkRefusalWithPayments(\n CommerceModel.invoicePayRefusal(order, quoteId, payStore),\n payments.ready,\n )\n if (blocked === 'payments-unavailable') {\n return refusal(409, blocked, CommerceModel.payLinkPaymentsUnavailableMessage(storeName, kind))\n }\n if (blocked) return refusal(409, blocked, CommerceModel.invoicePayRefusalMessage(blocked, storeName, kind))\n const { owner, accountId, chargeModel } = payments\n const direct = chargeModel === 'direct'\n // Every Stripe object for a direct sale lives on the seller's account.\n const onAccount = connectedAccountHeader(chargeModel, accountId)\n const sessionAccount = onAccount['Stripe-Account'] ?? ''\n\n const charge = CommerceModel.invoiceCheckoutCharge(order, quoteId, payStore)\n // The fee is sized on the most the buyer can pay, as a draft's first link\n // sized it on its dearest rate, and its processing half at the card rate:\n // the session below excludes every buy-now-pay-later method. A direct\n // charge's fee is the take alone: Stripe bills the seller its card fee.\n const dearestRateCents = charge.shippingOptions.reduce((most, rate) => Math.max(most, rate.amountCents), 0)\n const feeCents = resolveTransactionFeeCents(\n owner?.org as never,\n charge.feeProductType,\n charge.goodsCents,\n charge.totalCents + dearestRateCents,\n direct ? { direct: true } : { stripeTax: charge.taxAtPayment },\n )\n // Stripe refuses `automatic_tax` on a seller's account whose Stripe Tax is\n // not set up, and a store that chose it must not sell untaxed. Above the\n // claim, so the refusal spends no press.\n if (direct && charge.taxAtPayment) {\n const taxActive = await (deps.sellerTaxActive ?? sellerStripeTaxActive)(String(accountId))\n if (!taxActive) return refusal(409, 'seller-tax', SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE)\n }\n const nativeMode = await deps.nativeMode(String(owner?.id ?? ''))\n const site = host as SiteReturnHost\n const origin = siteReturnOrigin({\n candidates: [headerOf(req, 'referer'), `https://${headerOf(req, 'host')}`],\n site,\n requestHost: headerOf(req, 'host'),\n })\n const returnUrl = `${origin}${quotePageHref(quoteId, token)}`\n // A draft's first session (the one its paymentLinkUrl opens) is closed\n // here too, so the draft has one way to pay from the first press on.\n const openedFor = order.checkoutSessionId ?? ''\n const openedAtEdit = Number(order.quote?.updatedAtMs) || 0\n const openedAtVersion = CommerceModel.orderPayLinkVersion(order)\n // Closes a session this quote opened, on the account it was opened on. A\n // seller's earlier session may be the platform's (opened before the seller\n // moved to direct charges), so one the seller's account does not know is\n // closed there too: leaving it open would be a second way to pay.\n const expire = async (sessionId: string): Promise<CheckoutSessionExpiry> => {\n if (!sessionAccount) return deps.expireSession(sessionId)\n const result = await deps.expireSession(sessionId, sessionAccount)\n return result === 'missing' ? deps.expireSession(sessionId) : result\n }\n\n const claimed = await claimAttempt(deps.firestore(), {\n kind: 'commerce-quote-pay',\n scopeId: `${hostId}:${quoteId}`,\n orgId: String(owner?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'Your payment is already being set up',\n })\n if ('replay' in claimed) {\n return { status: claimed.replay.status, body: claimed.replay.body as Record<string, unknown> }\n }\n const claim = claimed.claim\n const stripeKey = (object: string): Record<string, string> => {\n const derived = deriveStripeObjectKey(claim.stripeKey, object)\n return derived ? { 'Idempotency-Key': derived } : {}\n }\n let minted = ''\n try {\n // The session the last press opened is closed before another opens. One\n // that was paid a moment ago means the quote is paid; one that cannot be\n // closed means a second session would be a second way to pay.\n if (openedFor) {\n const previous = await expire(openedFor)\n if (previous === 'complete') {\n await claim.release()\n return refusal(409, 'paid', `This ${noun} has just been paid. Your receipt is on its way.`, { confirming: true })\n }\n if (previous === 'open') {\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n }\n\n let taxRateId = ''\n if (charge.taxPct !== null && charge.taxableCents > 0) {\n const basis = kind === 'quote' ? payTax.basis : null\n taxRateId =\n (await deps.taxRateId({\n hostRef,\n taxPct: charge.taxPct,\n taxLabel:\n basis?.kind === 'rate'\n ? basis.label || `Tax (${charge.taxPct}%)`\n : 'Sales tax',\n headers: stripeKey(`tax-rate-${Math.round(charge.taxPct * 10_000)}`),\n // A platform rate id does not resolve on the seller's account.\n ...(sessionAccount ? { stripeAccount: sessionAccount } : {}),\n })) ?? ''\n if (!taxRateId) {\n // Never an untaxed session for a taxed quote.\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n }\n\n const paymentMethods = CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(store.get('paymentMethods')),\n )\n const params = buildQuoteSessionParams({\n hostId,\n quoteId,\n order,\n charge,\n accountId: String(accountId),\n ...(direct ? { chargeModel } : {}),\n feeCents,\n taxRateId,\n returnUrl,\n paymentMethods,\n chargedTax: kind === 'quote' && payTax.source === 'current' ? payTax.basis : null,\n })\n if (nativeMode.native) {\n applyNativeCheckoutParams(params, params.get('success_url') ?? returnUrl)\n }\n // Apple Pay's domain is registered on the account the session lives on.\n const domainInput = {\n pageUrl: returnUrl,\n site,\n hostId,\n ...(sessionAccount ? { stripeAccount: sessionAccount } : {}),\n }\n const domain = nativeMode.native ? deps.ensureDomain(domainInput) : Promise.resolve(null)\n const created = await deps.createSession(params, {\n ...stripeKey('session'),\n ...nativeCheckoutStripeHeaders(nativeMode),\n ...onAccount,\n })\n await domain\n const payload = created.ok\n ? // A direct sale's in-page form opens Stripe.js on the seller's account, where the session is.\n readCheckoutSessionPayload(created.session, nativeMode, paymentMethods.wallets, sessionAccount)\n : null\n if (!payload || !created.session.id) {\n console.error('Stripe quote checkout error', created.session?.error)\n await claim.release()\n return { status: 502, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n minted = String(created.session.id)\n\n // The quote keeps the session it now has open. Whatever another press\n // stored meanwhile is closed after, so the last press is the one open\n // session; a quote that was paid, replaced or edited meanwhile closes\n // this one instead.\n const orderRef = hostRef.collection('orders').doc(quoteId)\n const settled = await deps.firestore().runTransaction(async (transaction) => {\n const snapshot = await transaction.get(orderRef)\n const current = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n if (!current || CommerceModel.orderPayLinkKind(current) !== kind) return { outcome: NOT_FOUND_ANY, displaced: '' }\n if (current.status !== 'pending') {\n const closed = current.status === 'cancelled' || current.status === 'refunded'\n return {\n outcome: refusal(\n 409,\n closed ? 'closed' : 'paid',\n CommerceModel.invoicePayRefusalMessage(closed ? 'closed' : 'paid', storeName, kind),\n ),\n displaced: '',\n }\n }\n if (CommerceModel.orderPayLinkVersion(current) !== openedAtVersion) {\n return {\n outcome: {\n status: 410,\n body: { replaced: true, error: `This ${noun} was updated, and ${storeName || 'the business'} sent you a newer link.` },\n },\n displaced: '',\n }\n }\n if (kind === 'quote' && (Number(current.quote?.updatedAtMs) || 0) !== openedAtEdit) {\n return { outcome: refusal(409, 'updated', QUOTE_UPDATED_MESSAGE), displaced: '' }\n }\n transaction.set(orderRef, { checkoutSessionId: minted }, { merge: true })\n const displaced = current.checkoutSessionId && current.checkoutSessionId !== openedFor ? current.checkoutSessionId : ''\n return { outcome: null, displaced }\n })\n if (settled.outcome) {\n await expire(minted)\n await claim.release()\n return settled.outcome\n }\n if (settled.displaced && settled.displaced !== minted) await expire(settled.displaced)\n await claim.record(200, payload)\n return { status: 200, body: payload as unknown as Record<string, unknown> }\n } catch (error) {\n console.error('quote pay failed', error)\n if (minted) await expire(minted).catch(() => 'open')\n await claim.release()\n return { status: 500, body: { error: 'Your payment could not be set up. Try again.' } }\n }\n}\n\n/** Sends a link route's answer, never cached or indexed. */\nexport function sendQuoteLinkOutcome(res: Parameters<PluginApiHandler>[1], outcome: QuoteLinkOutcome) {\n res.setHeader('Cache-Control', 'private, no-store')\n res.setHeader('X-Robots-Tag', 'noindex, nofollow')\n for (const [name, value] of Object.entries(outcome.headers ?? {})) res.setHeader(name, value)\n return res.status(outcome.status).json(outcome.body)\n}\n\n/** `GET /api/commerce/quote-view`. */\nexport const quoteViewHandler: PluginApiHandler = async (req, res) => {\n try {\n return sendQuoteLinkOutcome(res, await handleQuoteView(defaultQuotePayDeps(), req))\n } catch (error) {\n console.error('quote view failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be loaded. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-pay`. */\nexport const quotePayHandler: PluginApiHandler = async (req, res) =>\n sendQuoteLinkOutcome(res, await handleQuotePay(defaultQuotePayDeps(), req))\n"],"names":["checkEntitlement","claimAttempt","deriveStripeObjectKey","resolveTransactionFeeCents","resolveHostToken","readClientIp","siteReturnOrigin","consumeRateLimit","firebaseAdmin","getOrgForHost","connectedAccountHeader","directChargeParams","merchantAccountIsReady","saleChargeModel","checkoutSessionCardAuthenticationParams","quotePageHref","CommerceModel","expireCheckoutSession","resolveManualTaxRateId","applyNativeCheckoutParams","nativeCheckoutStripeHeaders","readCheckoutSessionPayload","resolveNativeCheckoutMode","orderStatusUrl","ensureCheckoutDomain","verifyQuoteLinkToken","SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE","sellerStripeTaxActive","QUOTE_VIEW_LOOKUPS_PER_WINDOW","QUOTE_PAY_PRESSES_PER_WINDOW","QUOTE_WINDOW_MS","defaultQuotePayDeps","firestore","app","key","options","orgForHost","hostId","found","id","orgId","org","nativeMode","taxRateId","input","createSession","params","headers","response","fetch","method","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","ok","session","json","catch","expireSession","sessionId","stripeAccount","expireConnectedCheckoutSession","ensureDomain","now","Date","test","String","secretKey","trim","expired","read","status","DOC_ID","NOT_FOUND","error","NOT_FOUND_ANY","nounOf","kind","bodyOf","req","raw","parsed","JSON","parse","headerOf","name","value","toLowerCase","Array","isArray","limitedQuoteLink","deps","limit","ip","remoteAddress","socket","rate","windowMs","allowed","Math","max","ceil","resetMs","loadLinkedQuote","quoteId","token","hostSnapshot","notFound","invoices","version","outcome","hostRef","collection","doc","store","orderSnapshot","Promise","all","get","exists","order","data","orderPayLinkKind","host","storeName","current","orderPayLinkVersion","history","noun","quoteIsProofOnly","state","replaced","loaded","quoteLinkParams","source","slice","complete","Boolean","payLinkPayments","owner","ready","accountId","chargeModel","ownerUid","profile","chargesEnabled","accountLivemode","subject","orderId","payLinkPageView","currency","unpaid","receiptUrl","paymentsReady","undefined","view","payLinkStoreOf","tax","buildQuotePageView","buildInvoicePageView","handleQuoteView","query","refused","linked","buildQuoteSessionParams","charge","invoice","quote","URLSearchParams","mode","taxAtPayment","lines","forEach","line","index","at","set","amountCents","description","taxable","rates","shippingOptions","length","appendShippingAddressCollectionParams","shippingCountries","CHECKOUT_SHIPPING_COUNTRIES","appendCheckoutShippingParams","shippingCents","country","shipTo","toUpperCase","rateId","shippingFloorCents","direct","Object","entries","feeCents","destinationChargeParams","taxOwner","merchantGoodsCents","goodsCents","email","customerEmail","customer","separator","returnUrl","includes","discountId","quoteLinkVersion","Number","updatedAtMs","chargedTax","quoteTaxBasisKey","taxCents","taxPct","platformLiableTransferCents","appendStorefrontPaymentMethodParams","paymentMethods","QUOTE_UPDATED_MESSAGE","refusal","reason","extra","handleQuotePay","onAccount","idempotencyKey","seen","isFinite","payStore","payTax","quotePayTax","shownTax","taxKey","basis","payments","blocked","payLinkRefusalWithPayments","invoicePayRefusal","payLinkPaymentsUnavailableMessage","invoicePayRefusalMessage","sessionAccount","invoiceCheckoutCharge","dearestRateCents","reduce","most","feeProductType","totalCents","stripeTax","taxActive","sellerTaxActive","site","origin","candidates","requestHost","openedFor","checkoutSessionId","openedAtEdit","openedAtVersion","expire","result","claimed","scopeId","busyMessage","replay","claim","stripeKey","object","derived","minted","previous","release","confirming","taxableCents","taxLabel","label","round","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","native","domainInput","pageUrl","domain","resolve","created","payload","wallets","console","orderRef","settled","runTransaction","transaction","snapshot","displaced","closed","merge","record","sendQuoteLinkOutcome","res","setHeader","quoteViewHandler","quotePayHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,YAAY,EACZC,qBAAqB,EACrBC,0BAA0B,QAGrB,sBAAqB;AAC5B,SAASC,gBAAgB,QAA8B,qCAAoC;AAC3F,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAA8BC,gBAAgB,QAAQ,yCAAwC;AAC9F,SAASC,gBAAgB,EAAEC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACzF,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,sBAAsB,EACtBC,eAAe,QAEV,mDAAkD;AACzD,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SAASC,aAAa,QAAQ,6BAAyB;AACvD,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,qBAAqB,QAAoC,+BAA2B;AAC7F,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SACEC,yBAAyB,EACzBC,2BAA2B,EAC3BC,0BAA0B,EAC1BC,yBAAyB,QAEpB,uBAAmB;AAC1B,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,oBAAoB,QAAQ,8BAA0B;AAC/D,SAASC,oBAAoB,QAAQ,wBAAoB;AACzD,SAASC,oCAAoC,EAAEC,qBAAqB,QAAQ,6BAAyB;AAErG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA0C2C,GAE3C,wEAAwE,GACxE,OAAO,MAAMC,gCAAgC,GAAE;AAC/C,OAAO,MAAMC,+BAA+B,GAAE;AAC9C,OAAO,MAAMC,kBAAkB,KAAK,MAAM;AA6B1C,OAAO,SAASC;IACd,OAAO;QACLC,WAAW,IAAMxB,cAAcyB,GAAG,GAAGD,SAAS;QAC9CzB,kBAAkB,CAAC2B,KAAKC,UAAY5B,iBAAiB2B,KAAKC;QAC1DC,YAAY,OAAOC;YACjB,MAA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KyN,MAC3DD,qBAAqBC,KAAK,MAAM1E,eAAelM,uBAAuBmD,MAAK"}
@@ -39,7 +39,8 @@ export interface QuoteDeps {
39
39
  /** The site's tax service, where one is connected; `{ quote: null }` otherwise. */
40
40
  quoteTax(request: SaleTaxEngineRequest): Promise<SaleTaxEngineResult>;
41
41
  /** Closes a Checkout Session the pay page opened for the quote. */
42
- expireSession(sessionId: string): Promise<CheckoutSessionExpiry>;
42
+ /** `hostId` lets a direct-charge store's session be closed on its own account. */
43
+ expireSession(sessionId: string, hostId?: string): Promise<CheckoutSessionExpiry>;
43
44
  /** The quote's pay link at a link version, or null when the site has no address or no signing secret. */
44
45
  payLinkUrl(host: Record<string, unknown>, hostId: string, quoteId: string, version: number): string | null;
45
46
  /** One of the current revision's proofs behind that link, for the email's pictures. */