@aglyn/plugins-commerce 1.14.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/account-subscriptions.d.ts +51 -0
- package/src/lib/components/account-subscriptions.js +168 -0
- package/src/lib/components/account-subscriptions.js.map +1 -0
- package/src/lib/components/account.js +12 -48
- package/src/lib/components/account.js.map +1 -1
- package/src/lib/components/cart.js +38 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/commerce-console-sections.d.ts +1 -1
- package/src/lib/components/commerce-console-sections.js +5 -0
- package/src/lib/components/commerce-console-sections.js.map +1 -1
- package/src/lib/components/console/paid-media.d.ts +1 -0
- package/src/lib/components/console/paid-media.js +15 -4
- package/src/lib/components/console/paid-media.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
- package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
- package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
- package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
- package/src/lib/components/console/pos-cellular-control.component.js +5 -5
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
- package/src/lib/components/console/pos-hardware-card.component.js +77 -8
- package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.js +19 -2
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +21 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
- package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
- package/src/lib/components/console/subscriptions-card.component.js +282 -0
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
- package/src/lib/components/hardware-terms-consent.d.ts +22 -0
- package/src/lib/components/hardware-terms-consent.js +85 -0
- package/src/lib/components/hardware-terms-consent.js.map +1 -0
- package/src/lib/components/product-detail.js +32 -8
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/quote-page-body.js +7 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +6 -3
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +11 -7
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +1 -1
- package/src/lib/constants/operator-alerts.js +4 -4
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/model/commerce-orders.d.ts +6 -2
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +27 -16
- package/src/lib/model/commerce-payment-methods.js +11 -83
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/paid-media.d.ts +8 -0
- package/src/lib/model/paid-media.js +13 -0
- package/src/lib/model/paid-media.js.map +1 -1
- package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
- package/src/lib/model/pos-hardware-in-person.js +52 -20
- package/src/lib/model/pos-hardware-in-person.js.map +1 -1
- package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
- package/src/lib/model/pos-hardware-tax-summary.js +2 -1
- package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
- package/src/lib/model/pos-hardware-terms.d.ts +37 -2
- package/src/lib/model/pos-hardware-terms.js +68 -3
- package/src/lib/model/pos-hardware-terms.js.map +1 -1
- package/src/lib/model/pos-hardware.d.ts +101 -15
- package/src/lib/model/pos-hardware.js +128 -18
- package/src/lib/model/pos-hardware.js.map +1 -1
- package/src/lib/model/pos-reader-splash.js +2 -2
- package/src/lib/model/pos-reader-splash.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/model/subscription-view.d.ts +90 -0
- package/src/lib/model/subscription-view.js +176 -0
- package/src/lib/model/subscription-view.js.map +1 -0
- package/src/lib/server/billing-webhook.d.ts +27 -6
- package/src/lib/server/billing-webhook.js +271 -81
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +4 -3
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +105 -23
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +15 -3
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.js +58 -22
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +1 -1
- package/src/lib/server/checkout-session-expiry.js +19 -5
- package/src/lib/server/checkout-session-expiry.js.map +1 -1
- package/src/lib/server/checkout-status.js +4 -3
- package/src/lib/server/checkout-status.js.map +1 -1
- package/src/lib/server/checkout.js +98 -26
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect.js +42 -11
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +36 -7
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/manual-tax-rate.d.ts +11 -3
- package/src/lib/server/manual-tax-rate.js +10 -6
- package/src/lib/server/manual-tax-rate.js.map +1 -1
- package/src/lib/server/membership-account.d.ts +22 -0
- package/src/lib/server/membership-account.js +52 -8
- package/src/lib/server/membership-account.js.map +1 -1
- package/src/lib/server/native-checkout.d.ts +10 -3
- package/src/lib/server/native-checkout.js +8 -3
- package/src/lib/server/native-checkout.js.map +1 -1
- package/src/lib/server/payment-method-domains.d.ts +50 -9
- package/src/lib/server/payment-method-domains.js +150 -51
- package/src/lib/server/payment-method-domains.js.map +1 -1
- package/src/lib/server/payment-methods.js +3 -2
- package/src/lib/server/payment-methods.js.map +1 -1
- package/src/lib/server/pos-auth.d.ts +3 -3
- package/src/lib/server/pos-auth.js +3 -3
- package/src/lib/server/pos-auth.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.js +1 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular-notify.js +1 -1
- package/src/lib/server/pos-cellular-notify.js.map +1 -1
- package/src/lib/server/pos-cellular.js +1 -1
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-hardware-admin.js +86 -13
- package/src/lib/server/pos-hardware-admin.js.map +1 -1
- package/src/lib/server/pos-hardware-attach.js +5 -5
- package/src/lib/server/pos-hardware-attach.js.map +1 -1
- package/src/lib/server/pos-hardware-cancel.js +65 -0
- package/src/lib/server/pos-hardware-cancel.js.map +1 -1
- package/src/lib/server/pos-hardware-closure-notices.js +2 -5
- package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
- package/src/lib/server/pos-hardware-closure.js +5 -8
- package/src/lib/server/pos-hardware-closure.js.map +1 -1
- package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
- package/src/lib/server/pos-hardware-in-person.js +72 -17
- package/src/lib/server/pos-hardware-in-person.js.map +1 -1
- package/src/lib/server/pos-hardware-notify.d.ts +2 -0
- package/src/lib/server/pos-hardware-notify.js +30 -5
- package/src/lib/server/pos-hardware-notify.js.map +1 -1
- package/src/lib/server/pos-hardware-readers.d.ts +25 -0
- package/src/lib/server/pos-hardware-readers.js +206 -85
- package/src/lib/server/pos-hardware-readers.js.map +1 -1
- package/src/lib/server/pos-hardware-returns.d.ts +8 -3
- package/src/lib/server/pos-hardware-returns.js +39 -7
- package/src/lib/server/pos-hardware-returns.js.map +1 -1
- package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
- package/src/lib/server/pos-hardware-sale-fields.js +114 -1
- package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
- package/src/lib/server/pos-hardware-sale.d.ts +2 -0
- package/src/lib/server/pos-hardware-sale.js +1 -0
- package/src/lib/server/pos-hardware-sale.js.map +1 -1
- package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
- package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
- package/src/lib/server/pos-hardware-webhook.js +16 -3
- package/src/lib/server/pos-hardware-webhook.js.map +1 -1
- package/src/lib/server/pos-hardware.d.ts +14 -3
- package/src/lib/server/pos-hardware.js +83 -18
- package/src/lib/server/pos-hardware.js.map +1 -1
- package/src/lib/server/pos-ops-routes.js +2 -10
- package/src/lib/server/pos-ops-routes.js.map +1 -1
- package/src/lib/server/pos-order.js +5 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +7 -7
- package/src/lib/server/pos-stripe.js +15 -13
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.js +11 -3
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +23 -1
- package/src/lib/server/quote-pay.js +111 -27
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +2 -1
- package/src/lib/server/quote.js +12 -11
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +13 -6
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/related.js +10 -3
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/reserve.js +19 -6
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/revenue-source.d.ts +6 -0
- package/src/lib/server/revenue-source.js +25 -9
- package/src/lib/server/revenue-source.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +45 -0
- package/src/lib/server/seller-stripe-account.js +99 -0
- package/src/lib/server/seller-stripe-account.js.map +1 -0
- package/src/lib/server/storefront-tax-record.js +6 -1
- package/src/lib/server/storefront-tax-record.js.map +1 -1
- package/src/lib/server/storefront-tax.d.ts +33 -2
- package/src/lib/server/storefront-tax.js +39 -3
- package/src/lib/server/storefront-tax.js.map +1 -1
- package/src/lib/server/stream.d.ts +2 -0
- package/src/lib/server/stream.js +22 -2
- package/src/lib/server/stream.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +15 -0
- package/src/lib/server/stripe-refund.js +54 -26
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server/subscription-portal.js +8 -3
- package/src/lib/server/subscription-portal.js.map +1 -1
- package/src/lib/server/tax-return-source.js +5 -1
- package/src/lib/server/tax-return-source.js.map +1 -1
- package/src/lib/server.js +2 -2
- package/src/lib/server.js.map +1 -1
|
@@ -17,6 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
17
17
|
*/ import { siteOwnHosts } from "@aglyn/aglyn/app-utils/site-return-url";
|
|
18
18
|
import { TENANT_APEX } from "@aglyn/aglyn/app-utils/tenant-apex";
|
|
19
19
|
import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
20
|
+
import { directSellerAccountForHost } from "./seller-stripe-account.js";
|
|
20
21
|
/**
|
|
21
22
|
* Stripe payment method domains for storefronts (AGL-3629).
|
|
22
23
|
*
|
|
@@ -32,9 +33,14 @@ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
|
32
33
|
* registered for the user running the charge." Storefront charges are
|
|
33
34
|
* DESTINATION charges created by the platform with no `Stripe-Account` header
|
|
34
35
|
* and no `on_behalf_of`, so the platform runs them and the platform's key
|
|
35
|
-
* registers the domain, with no `Stripe-Account` header.
|
|
36
|
-
*
|
|
37
|
-
*
|
|
36
|
+
* registers the domain, with no `Stripe-Account` header.
|
|
37
|
+
*
|
|
38
|
+
* A DIRECT-charge seller runs its own charges: the session is created on the
|
|
39
|
+
* seller's connected account, so Apple Pay and Google Pay show only on a
|
|
40
|
+
* domain registered ON THAT ACCOUNT (`Stripe-Account` header). Every entry
|
|
41
|
+
* point below takes the seller's account for that case, and the platform's
|
|
42
|
+
* registration is left as it is, because the seller's hardware purchases and
|
|
43
|
+
* any sale from before the switch still run on the platform.
|
|
38
44
|
*
|
|
39
45
|
* ## When
|
|
40
46
|
*
|
|
@@ -56,8 +62,10 @@ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
|
56
62
|
* `paymentMethodDomains/{mode}~{domain}` records what Stripe last said, so a
|
|
57
63
|
* checkout costs one document read rather than a Stripe round trip. The mode is
|
|
58
64
|
* in the id because a test key and a live key register in different worlds and
|
|
59
|
-
* a domain registered in one is not registered in the other.
|
|
60
|
-
*
|
|
65
|
+
* a domain registered in one is not registered in the other. A seller's
|
|
66
|
+
* registration is cached under its own id, `{mode}~{account}~{domain}`,
|
|
67
|
+
* because it is a different Stripe object from the platform's for the same
|
|
68
|
+
* name. Server-only: the rules deny every client.
|
|
61
69
|
*/ export const PAYMENT_METHOD_DOMAINS_COLLECTION = 'paymentMethodDomains';
|
|
62
70
|
/** How long a recorded registration is trusted before Stripe is asked again. */ export const PAYMENT_METHOD_DOMAIN_RECHECK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
63
71
|
/** The most a checkout waits on Stripe before selling without the domain. */ export const CHECKOUT_DOMAIN_BUDGET_MS = 2500;
|
|
@@ -79,8 +87,16 @@ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
|
79
87
|
if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(value)) return null;
|
|
80
88
|
return value;
|
|
81
89
|
}
|
|
82
|
-
/**
|
|
83
|
-
|
|
90
|
+
/**
|
|
91
|
+
* The cache document id for a domain in a mode, on the platform or on one
|
|
92
|
+
* seller's connected account.
|
|
93
|
+
*/ export function paymentMethodDomainDocId(mode, domain, stripeAccount) {
|
|
94
|
+
const account = accountOrNull(stripeAccount);
|
|
95
|
+
return account ? `${mode}~${account}~${domain}` : `${mode}~${domain}`;
|
|
96
|
+
}
|
|
97
|
+
/** A usable connected-account id, or null for "the platform". */ function accountOrNull(value) {
|
|
98
|
+
const id = typeof value === 'string' ? value.trim() : '';
|
|
99
|
+
return /^acct_[A-Za-z0-9]+$/.test(id) ? id : null;
|
|
84
100
|
}
|
|
85
101
|
/**
|
|
86
102
|
* The domains a site's custom domain needs: the domain and its `www.` twin,
|
|
@@ -115,6 +131,8 @@ async function stripeRequest(method, path, params, options = {}) {
|
|
|
115
131
|
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`
|
|
116
132
|
}, method === 'POST' && {
|
|
117
133
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
134
|
+
}, options.stripeAccount && {
|
|
135
|
+
'Stripe-Account': options.stripeAccount
|
|
118
136
|
}, options.idempotencyKey && {
|
|
119
137
|
'Idempotency-Key': options.idempotencyKey
|
|
120
138
|
})
|
|
@@ -131,14 +149,15 @@ async function stripeRequest(method, path, params, options = {}) {
|
|
|
131
149
|
}
|
|
132
150
|
return payload;
|
|
133
151
|
}
|
|
134
|
-
async function findOnStripe(domain, signal) {
|
|
152
|
+
async function findOnStripe(domain, signal, stripeAccount) {
|
|
135
153
|
var _ref;
|
|
136
154
|
var _list_data;
|
|
137
155
|
const list = await stripeRequest('GET', 'payment_method_domains', {
|
|
138
156
|
domain_name: domain,
|
|
139
157
|
limit: '1'
|
|
140
158
|
}, {
|
|
141
|
-
signal
|
|
159
|
+
signal,
|
|
160
|
+
stripeAccount
|
|
142
161
|
});
|
|
143
162
|
return (_ref = (_list_data = list.data) == null ? void 0 : _list_data.find((entry)=>entry.domain_name === domain)) != null ? _ref : null;
|
|
144
163
|
}
|
|
@@ -148,13 +167,31 @@ async function findOnStripe(domain, signal) {
|
|
|
148
167
|
* is enabled rather than duplicated, and the create carries an idempotency key
|
|
149
168
|
* so two checkouts racing on a fresh subdomain open one registration.
|
|
150
169
|
*/ export async function registerOnPlatform(domain, signal) {
|
|
151
|
-
|
|
170
|
+
return registerDomain(domain, {
|
|
171
|
+
signal
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Register (or re-enable) one domain on a direct-charge seller's connected
|
|
176
|
+
* account: the same steps as {@link registerOnPlatform}, each sent with the
|
|
177
|
+
* seller's `Stripe-Account`.
|
|
178
|
+
*/ export async function registerOnAccount(domain, stripeAccount, signal) {
|
|
179
|
+
return registerDomain(domain, {
|
|
180
|
+
signal,
|
|
181
|
+
stripeAccount
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
async function registerDomain(domain, options) {
|
|
185
|
+
const { signal } = options;
|
|
186
|
+
const stripeAccount = accountOrNull(options.stripeAccount);
|
|
187
|
+
const existing = await findOnStripe(domain, signal, stripeAccount);
|
|
152
188
|
if (existing) {
|
|
153
189
|
if (existing.enabled) return existing;
|
|
154
190
|
return stripeRequest('POST', `payment_method_domains/${encodeURIComponent(existing.id)}`, {
|
|
155
191
|
enabled: 'true'
|
|
156
192
|
}, {
|
|
157
|
-
signal
|
|
193
|
+
signal,
|
|
194
|
+
stripeAccount
|
|
158
195
|
});
|
|
159
196
|
}
|
|
160
197
|
try {
|
|
@@ -162,24 +199,31 @@ async function findOnStripe(domain, signal) {
|
|
|
162
199
|
domain_name: domain,
|
|
163
200
|
enabled: 'true'
|
|
164
201
|
}, {
|
|
165
|
-
|
|
166
|
-
|
|
202
|
+
// Stripe scopes the key per account; the account is in it anyway so
|
|
203
|
+
// a log line names which registration it was.
|
|
204
|
+
idempotencyKey: stripeAccount ? `aglyn-pmd-register:${stripeAccount}:${domain}` : `aglyn-pmd-register:${domain}`,
|
|
205
|
+
signal,
|
|
206
|
+
stripeAccount
|
|
167
207
|
});
|
|
168
208
|
} catch (error) {
|
|
169
209
|
// Lost a race to a create that landed between the lookup and this call:
|
|
170
210
|
// the registration exists, which is what was wanted.
|
|
171
|
-
const raced = await findOnStripe(domain, signal).catch(()=>null);
|
|
211
|
+
const raced = await findOnStripe(domain, signal, stripeAccount).catch(()=>null);
|
|
172
212
|
if (raced) return raced;
|
|
173
213
|
throw error;
|
|
174
214
|
}
|
|
175
215
|
}
|
|
176
|
-
function docRef(mode, domain) {
|
|
177
|
-
return firebaseAdmin.app().firestore().collection(PAYMENT_METHOD_DOMAINS_COLLECTION).doc(paymentMethodDomainDocId(mode, domain));
|
|
216
|
+
function docRef(mode, domain, stripeAccount) {
|
|
217
|
+
return firebaseAdmin.app().firestore().collection(PAYMENT_METHOD_DOMAINS_COLLECTION).doc(paymentMethodDomainDocId(mode, domain, stripeAccount));
|
|
178
218
|
}
|
|
179
|
-
async function record(mode, domain, patch) {
|
|
180
|
-
|
|
219
|
+
async function record(mode, domain, patch, stripeAccount) {
|
|
220
|
+
const account = accountOrNull(stripeAccount);
|
|
221
|
+
await docRef(mode, domain, account).set(_extends({
|
|
181
222
|
domain,
|
|
182
|
-
mode
|
|
223
|
+
mode
|
|
224
|
+
}, account ? {
|
|
225
|
+
stripeAccount: account
|
|
226
|
+
} : {}, {
|
|
183
227
|
checkedAtMs: Date.now()
|
|
184
228
|
}, patch), {
|
|
185
229
|
merge: true
|
|
@@ -200,11 +244,12 @@ async function record(mode, domain, patch) {
|
|
|
200
244
|
outcome: 'skipped'
|
|
201
245
|
};
|
|
202
246
|
}
|
|
247
|
+
const account = accountOrNull(options.stripeAccount);
|
|
203
248
|
try {
|
|
204
249
|
var _options_hostId;
|
|
205
250
|
if (!options.force) {
|
|
206
251
|
var _data_checkedAtMs;
|
|
207
|
-
const cached = await docRef(mode, domain).get();
|
|
252
|
+
const cached = await docRef(mode, domain, account).get();
|
|
208
253
|
const data = cached.data == null ? void 0 : cached.data.call(cached);
|
|
209
254
|
if (cached.exists && (data == null ? void 0 : data.enabled) === true && data.stripeId && Date.now() - Number((_data_checkedAtMs = data.checkedAtMs) != null ? _data_checkedAtMs : 0) < PAYMENT_METHOD_DOMAIN_RECHECK_MS) {
|
|
210
255
|
return {
|
|
@@ -214,18 +259,21 @@ async function record(mode, domain, patch) {
|
|
|
214
259
|
};
|
|
215
260
|
}
|
|
216
261
|
}
|
|
217
|
-
const object = await registerOnPlatform(domain, options.signal);
|
|
218
|
-
const next = {
|
|
262
|
+
const object = account ? await registerOnAccount(domain, account, options.signal) : await registerOnPlatform(domain, options.signal);
|
|
263
|
+
const next = _extends({
|
|
219
264
|
domain,
|
|
220
|
-
mode
|
|
265
|
+
mode
|
|
266
|
+
}, account ? {
|
|
267
|
+
stripeAccount: account
|
|
268
|
+
} : {}, {
|
|
221
269
|
stripeId: object.id,
|
|
222
270
|
enabled: object.enabled !== false,
|
|
223
271
|
status: statusOf(object),
|
|
224
272
|
hostId: (_options_hostId = options.hostId) != null ? _options_hostId : null,
|
|
225
273
|
checkedAtMs: Date.now(),
|
|
226
274
|
lastError: null
|
|
227
|
-
};
|
|
228
|
-
await record(mode, domain, next);
|
|
275
|
+
});
|
|
276
|
+
await record(mode, domain, next, account);
|
|
229
277
|
return {
|
|
230
278
|
domain,
|
|
231
279
|
outcome: 'registered',
|
|
@@ -238,7 +286,7 @@ async function record(mode, domain, patch) {
|
|
|
238
286
|
enabled: false,
|
|
239
287
|
hostId: (_options_hostId1 = options.hostId) != null ? _options_hostId1 : null,
|
|
240
288
|
lastError: message.slice(0, 500)
|
|
241
|
-
}).catch(()=>undefined);
|
|
289
|
+
}, account).catch(()=>undefined);
|
|
242
290
|
return {
|
|
243
291
|
domain,
|
|
244
292
|
outcome: 'failed',
|
|
@@ -251,21 +299,22 @@ async function record(mode, domain, patch) {
|
|
|
251
299
|
* delete for a payment method domain; disabling stops every method on it, and
|
|
252
300
|
* `ensurePaymentMethodDomain` re-enables the same registration if the name is
|
|
253
301
|
* connected again.
|
|
254
|
-
*/ export async function disablePaymentMethodDomain(rawDomain) {
|
|
302
|
+
*/ export async function disablePaymentMethodDomain(rawDomain, options = {}) {
|
|
255
303
|
const domain = registrableDomain(rawDomain);
|
|
256
304
|
const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY);
|
|
257
305
|
if (!domain || !mode) return {
|
|
258
306
|
domain: String(rawDomain != null ? rawDomain : ''),
|
|
259
307
|
outcome: 'skipped'
|
|
260
308
|
};
|
|
309
|
+
const account = accountOrNull(options.stripeAccount);
|
|
261
310
|
try {
|
|
262
|
-
const existing = await findOnStripe(domain);
|
|
311
|
+
const existing = await findOnStripe(domain, undefined, account);
|
|
263
312
|
if (!existing) {
|
|
264
313
|
await record(mode, domain, {
|
|
265
314
|
enabled: false,
|
|
266
315
|
stripeId: null,
|
|
267
316
|
lastError: null
|
|
268
|
-
});
|
|
317
|
+
}, account);
|
|
269
318
|
return {
|
|
270
319
|
domain,
|
|
271
320
|
outcome: 'absent'
|
|
@@ -273,13 +322,15 @@ async function record(mode, domain, patch) {
|
|
|
273
322
|
}
|
|
274
323
|
const object = existing.enabled ? await stripeRequest('POST', `payment_method_domains/${encodeURIComponent(existing.id)}`, {
|
|
275
324
|
enabled: 'false'
|
|
325
|
+
}, {
|
|
326
|
+
stripeAccount: account
|
|
276
327
|
}) : existing;
|
|
277
328
|
await record(mode, domain, {
|
|
278
329
|
stripeId: object.id,
|
|
279
330
|
enabled: false,
|
|
280
331
|
status: statusOf(object),
|
|
281
332
|
lastError: null
|
|
282
|
-
});
|
|
333
|
+
}, account);
|
|
283
334
|
return {
|
|
284
335
|
domain,
|
|
285
336
|
outcome: 'disabled'
|
|
@@ -334,10 +385,12 @@ async function record(mode, domain, patch) {
|
|
|
334
385
|
const budget = (_input_budgetMs = input.budgetMs) != null ? _input_budgetMs : CHECKOUT_DOMAIN_BUDGET_MS;
|
|
335
386
|
const timer = setTimeout(()=>controller.abort(), budget);
|
|
336
387
|
try {
|
|
337
|
-
return await ensurePaymentMethodDomain(hostname, {
|
|
388
|
+
return await ensurePaymentMethodDomain(hostname, _extends({
|
|
338
389
|
hostId: input.hostId,
|
|
339
390
|
signal: controller.signal
|
|
340
|
-
}
|
|
391
|
+
}, input.stripeAccount ? {
|
|
392
|
+
stripeAccount: input.stripeAccount
|
|
393
|
+
} : {}));
|
|
341
394
|
} finally{
|
|
342
395
|
clearTimeout(timer);
|
|
343
396
|
}
|
|
@@ -353,7 +406,8 @@ async function record(mode, domain, patch) {
|
|
|
353
406
|
* Paged by `cname` with a cursor so it reads every site once and stops; the
|
|
354
407
|
* `cname > ''` range uses Firestore's automatic single-field index.
|
|
355
408
|
*/ export async function reconcileCustomDomains(gate, options = {}) {
|
|
356
|
-
var _options_maxPages;
|
|
409
|
+
var _options_sellerAccount, _options_maxPages;
|
|
410
|
+
const sellerAccount = (_options_sellerAccount = options.sellerAccount) != null ? _options_sellerAccount : directSellerAccountForHost;
|
|
357
411
|
const result = {
|
|
358
412
|
hosts: 0,
|
|
359
413
|
registered: 0,
|
|
@@ -379,12 +433,24 @@ async function record(mode, domain, patch) {
|
|
|
379
433
|
result.skippedLocked += 1;
|
|
380
434
|
continue;
|
|
381
435
|
}
|
|
436
|
+
// A direct-charge seller runs its own charges, so its domains are
|
|
437
|
+
// registered on its account as well as the platform's.
|
|
438
|
+
const account = await sellerAccount(hostDoc.id).catch(()=>null);
|
|
382
439
|
for (const domain of customDomainNames(hostDoc.get('cname'))){
|
|
383
|
-
const
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
440
|
+
for (const stripeAccount of account ? [
|
|
441
|
+
null,
|
|
442
|
+
account
|
|
443
|
+
] : [
|
|
444
|
+
null
|
|
445
|
+
]){
|
|
446
|
+
const outcome = await ensurePaymentMethodDomain(domain, _extends({
|
|
447
|
+
hostId: hostDoc.id
|
|
448
|
+
}, stripeAccount ? {
|
|
449
|
+
stripeAccount
|
|
450
|
+
} : {}));
|
|
451
|
+
if (outcome.outcome === 'registered') result.registered += 1;
|
|
452
|
+
if (outcome.outcome === 'failed') result.failed += 1;
|
|
453
|
+
}
|
|
388
454
|
}
|
|
389
455
|
}
|
|
390
456
|
cursor = String((_ref = (_snapshot_docs_ = snapshot.docs[snapshot.docs.length - 1]) == null ? void 0 : _snapshot_docs_.get('cname')) != null ? _ref : '');
|
|
@@ -392,22 +458,48 @@ async function record(mode, domain, patch) {
|
|
|
392
458
|
}
|
|
393
459
|
return result;
|
|
394
460
|
}
|
|
395
|
-
/** Core's `host.domain.attached`: register the custom domain and its twin. */ export async function onHostDomainAttached(payload) {
|
|
461
|
+
/** Core's `host.domain.attached`: register the custom domain and its twin. */ export async function onHostDomainAttached(payload, options = {}) {
|
|
462
|
+
var _options_sellerAccount;
|
|
463
|
+
// The platform's registration as before, and the seller's own as well when
|
|
464
|
+
// the site sells by direct charges, since those sessions run on its account.
|
|
465
|
+
const account = await ((_options_sellerAccount = options.sellerAccount) != null ? _options_sellerAccount : directSellerAccountForHost)(payload.hostId).catch(()=>null);
|
|
396
466
|
for (const domain of customDomainNames(payload.domain)){
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
467
|
+
for (const stripeAccount of account ? [
|
|
468
|
+
null,
|
|
469
|
+
account
|
|
470
|
+
] : [
|
|
471
|
+
null
|
|
472
|
+
]){
|
|
473
|
+
const outcome = await ensurePaymentMethodDomain(domain, _extends({
|
|
474
|
+
hostId: payload.hostId,
|
|
475
|
+
force: true
|
|
476
|
+
}, stripeAccount ? {
|
|
477
|
+
stripeAccount
|
|
478
|
+
} : {}));
|
|
479
|
+
if (outcome.outcome === 'failed') {
|
|
480
|
+
console.warn(`[commerce] payment method domain ${domain}${stripeAccount ? ` on ${stripeAccount}` : ''} not registered: ${outcome.error}`);
|
|
481
|
+
}
|
|
403
482
|
}
|
|
404
483
|
}
|
|
405
484
|
}
|
|
406
|
-
/** Core's `host.domain.released`: disable what no other site still serves. */ export async function onHostDomainReleased(payload) {
|
|
485
|
+
/** Core's `host.domain.released`: disable what no other site still serves. */ export async function onHostDomainReleased(payload, options = {}) {
|
|
486
|
+
var _options_sellerAccount;
|
|
407
487
|
const names = payload.domain.endsWith(`.${TENANT_APEX}`) ? [
|
|
408
488
|
registrableDomain(payload.domain)
|
|
409
489
|
].filter((name)=>Boolean(name)) : customDomainNames(payload.domain);
|
|
490
|
+
const account = await ((_options_sellerAccount = options.sellerAccount) != null ? _options_sellerAccount : directSellerAccountForHost)(payload.hostId).catch(()=>null);
|
|
410
491
|
for (const domain of names){
|
|
492
|
+
// The PLATFORM's registration is shared by every site that answers on
|
|
493
|
+
// the name, so it waits until no other site does. The seller's own is
|
|
494
|
+
// that seller's alone, and goes with this site's release.
|
|
495
|
+
if (account) {
|
|
496
|
+
const onSeller = await disablePaymentMethodDomain(domain, {
|
|
497
|
+
stripeAccount: account
|
|
498
|
+
});
|
|
499
|
+
if (onSeller.outcome === 'failed') {
|
|
500
|
+
console.warn(`[commerce] payment method domain ${domain} on ${account} not disabled: ${onSeller.error}`);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
411
503
|
if (await domainStillClaimed(domain, payload.hostId)) continue;
|
|
412
504
|
const outcome = await disablePaymentMethodDomain(domain);
|
|
413
505
|
if (outcome.outcome === 'failed') {
|
|
@@ -415,16 +507,23 @@ async function record(mode, domain, patch) {
|
|
|
415
507
|
}
|
|
416
508
|
}
|
|
417
509
|
}
|
|
418
|
-
/** The registrations a settings card shows for one site. */ export async function readSiteDomainRecords(site
|
|
510
|
+
/** The registrations a settings card shows for one site. */ export async function readSiteDomainRecords(site, /**
|
|
511
|
+
* The site's direct-charge seller account: its registrations are the ones
|
|
512
|
+
* the site's checkout uses, so they are the ones to show.
|
|
513
|
+
*/ stripeAccount) {
|
|
419
514
|
const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY);
|
|
420
515
|
if (!mode) return [];
|
|
516
|
+
const account = accountOrNull(stripeAccount);
|
|
421
517
|
const names = siteOwnHosts(site).filter((name)=>registrableDomain(name));
|
|
422
|
-
const snapshots = await Promise.all(names.map((name)=>docRef(mode, name).get()));
|
|
518
|
+
const snapshots = await Promise.all(names.map((name)=>docRef(mode, name, account).get()));
|
|
423
519
|
return snapshots.map((snapshot, index)=>{
|
|
424
520
|
const data = snapshot.exists ? snapshot.data == null ? void 0 : snapshot.data.call(snapshot) : null;
|
|
425
|
-
return data != null ? data : {
|
|
521
|
+
return data != null ? data : _extends({
|
|
426
522
|
domain: names[index],
|
|
427
|
-
mode
|
|
523
|
+
mode
|
|
524
|
+
}, account ? {
|
|
525
|
+
stripeAccount: account
|
|
526
|
+
} : {}, {
|
|
428
527
|
stripeId: null,
|
|
429
528
|
enabled: false,
|
|
430
529
|
status: {
|
|
@@ -437,7 +536,7 @@ async function record(mode, domain, patch) {
|
|
|
437
536
|
hostId: null,
|
|
438
537
|
checkedAtMs: 0,
|
|
439
538
|
lastError: null
|
|
440
|
-
};
|
|
539
|
+
});
|
|
441
540
|
});
|
|
442
541
|
}
|
|
443
542
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-method-domains.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type SiteReturnHost, siteOwnHosts } from '@aglyn/aglyn/app-utils/site-return-url'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\n\n/**\n * Stripe payment method domains for storefronts (AGL-3629).\n *\n * The in-page checkout mounts Stripe's Payment Element on the merchant's own\n * domain, and Stripe shows Apple Pay there only on a REGISTERED domain (Google\n * Pay, Link, Amazon Pay and Klarna's express button use the same registration).\n * Nothing registered one, so a shopper on `shop.example.com` with a card in\n * Apple Wallet never saw the button.\n *\n * ## Which account the domain is registered on\n *\n * Stripe's rule: \"The domain where the charge is being run needs to be\n * registered for the user running the charge.\" Storefront charges are\n * DESTINATION charges created by the platform with no `Stripe-Account` header\n * and no `on_behalf_of`, so the platform runs them and the platform's key\n * registers the domain, with no `Stripe-Account` header. A direct-charge flow\n * would register on the connected account instead; there is none today, and\n * `registerOnPlatform` is named for that reason.\n *\n * ## When\n *\n * - On connect: core raises `host.domain.attached`, and commerce registers\n * the custom domain and its `www.` twin.\n * - On first checkout: the session handlers call `ensureCheckoutDomain` for\n * the page the shopper is on, which covers every `{site}.aglyn.app`\n * subdomain without registering thousands of sites that never sell.\n * - Daily: `reconcileCustomDomains` registers any connected custom domain the\n * first two missed (domains connected before AGL-3629 included) — the\n * backfill is a job rather than a one-off script, so it also repairs a\n * missed event later.\n * - On release: `host.domain.released` DISABLES the domain. Stripe has no\n * delete; a disabled domain stops showing the methods and can be enabled\n * again if the name comes back.\n *\n * ## The cache\n *\n * `paymentMethodDomains/{mode}~{domain}` records what Stripe last said, so a\n * checkout costs one document read rather than a Stripe round trip. The mode is\n * in the id because a test key and a live key register in different worlds and\n * a domain registered in one is not registered in the other. Server-only: the\n * rules deny every client.\n */\n\nexport const PAYMENT_METHOD_DOMAINS_COLLECTION = 'paymentMethodDomains'\n\n/** How long a recorded registration is trusted before Stripe is asked again. */\nexport const PAYMENT_METHOD_DOMAIN_RECHECK_MS = 7 * 24 * 60 * 60 * 1000\n\n/** The most a checkout waits on Stripe before selling without the domain. */\nexport const CHECKOUT_DOMAIN_BUDGET_MS = 2500\n\nexport type StripeMode = 'live' | 'test'\n\n/** Stripe's per-method verdict on a domain. */\nexport interface PaymentMethodDomainStatus {\n applePay: string | null\n googlePay: string | null\n link: string | null\n amazonPay: string | null\n klarna: string | null\n}\n\nexport interface PaymentMethodDomainRecord {\n domain: string\n mode: StripeMode\n stripeId: string | null\n enabled: boolean\n status: PaymentMethodDomainStatus\n hostId: string | null\n checkedAtMs: number\n lastError: string | null\n}\n\ninterface StripeDomainObject {\n id: string\n domain_name: string\n enabled: boolean\n apple_pay?: { status?: string }\n google_pay?: { status?: string }\n link?: { status?: string }\n amazon_pay?: { status?: string }\n klarna?: { status?: string }\n}\n\n/** Which Stripe world the platform key is in, from its prefix. */\nexport function stripeModeOfKey(key: string | undefined): StripeMode | null {\n const value = String(key ?? '')\n if (/^(sk|rk)_live_/.test(value)) return 'live'\n if (/^(sk|rk)_test_/.test(value)) return 'test'\n return null\n}\n\n/**\n * A hostname Stripe can register: lowercased, no trailing dot, at least two\n * labels, and never a local or IP host — a checkout opened on `localhost`\n * must not try to register it.\n */\nexport function registrableDomain(input: unknown): string | null {\n const value = String(input ?? '')\n .trim()\n .toLowerCase()\n .replace(/\\.+$/, '')\n if (!value || value.length > 253) return null\n if (value === 'localhost' || value.endsWith('.localhost')) return null\n if (/^[0-9.]+$/.test(value) || value.includes(':')) return null\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(value)) return null\n return value\n}\n\n/** The cache document id for a domain in a mode. */\nexport function paymentMethodDomainDocId(mode: StripeMode, domain: string): string {\n return `${mode}~${domain}`\n}\n\n/**\n * The domains a site's custom domain needs: the domain and its `www.` twin,\n * since the platform answers on both (`siteOwnHosts`).\n */\nexport function customDomainNames(cname: unknown): string[] {\n const domain = registrableDomain(cname)\n if (!domain) return []\n const twin = domain.startsWith('www.') ? domain.slice(4) : `www.${domain}`\n return [domain, ...(registrableDomain(twin) ? [twin] : [])]\n}\n\nfunction statusOf(object: StripeDomainObject): PaymentMethodDomainStatus {\n return {\n applePay: object.apple_pay?.status ?? null,\n googlePay: object.google_pay?.status ?? null,\n link: object.link?.status ?? null,\n amazonPay: object.amazon_pay?.status ?? null,\n klarna: object.klarna?.status ?? null,\n }\n}\n\nasync function stripeRequest<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: Record<string, string>,\n options: { idempotencyKey?: string; signal?: AbortSignal } = {},\n): Promise<T> {\n const query = method === 'GET' && params ? `?${new URLSearchParams(params)}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n // The platform's own key and NO `Stripe-Account`: destination charges\n // are run by the platform, so the platform holds the registration.\n ...(options.idempotencyKey && { 'Idempotency-Key': options.idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: new URLSearchParams(params).toString() }),\n ...(options.signal && { signal: options.signal }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\nasync function findOnStripe(\n domain: string,\n signal?: AbortSignal,\n): Promise<StripeDomainObject | null> {\n const list = await stripeRequest<{ data?: StripeDomainObject[] }>(\n 'GET',\n 'payment_method_domains',\n { domain_name: domain, limit: '1' },\n { signal },\n )\n return list.data?.find((entry) => entry.domain_name === domain) ?? null\n}\n\n/**\n * Register (or re-enable) one domain on the platform account. Idempotent end\n * to end: an existing registration is found first and reused, a disabled one\n * is enabled rather than duplicated, and the create carries an idempotency key\n * so two checkouts racing on a fresh subdomain open one registration.\n */\nexport async function registerOnPlatform(\n domain: string,\n signal?: AbortSignal,\n): Promise<StripeDomainObject> {\n const existing = await findOnStripe(domain, signal)\n if (existing) {\n if (existing.enabled) return existing\n return stripeRequest<StripeDomainObject>(\n 'POST',\n `payment_method_domains/${encodeURIComponent(existing.id)}`,\n { enabled: 'true' },\n { signal },\n )\n }\n try {\n return await stripeRequest<StripeDomainObject>(\n 'POST',\n 'payment_method_domains',\n { domain_name: domain, enabled: 'true' },\n { idempotencyKey: `aglyn-pmd-register:${domain}`, signal },\n )\n } catch (error) {\n // Lost a race to a create that landed between the lookup and this call:\n // the registration exists, which is what was wanted.\n const raced = await findOnStripe(domain, signal).catch(() => null)\n if (raced) return raced\n throw error\n }\n}\n\nfunction docRef(mode: StripeMode, domain: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection(PAYMENT_METHOD_DOMAINS_COLLECTION)\n .doc(paymentMethodDomainDocId(mode, domain))\n}\n\nasync function record(\n mode: StripeMode,\n domain: string,\n patch: Partial<PaymentMethodDomainRecord>,\n): Promise<void> {\n await docRef(mode, domain).set(\n { domain, mode, checkedAtMs: Date.now(), ...patch },\n { merge: true },\n )\n}\n\nexport interface EnsureDomainResult {\n domain: string\n outcome: 'registered' | 'cached' | 'skipped' | 'failed'\n record?: PaymentMethodDomainRecord\n error?: string\n}\n\n/**\n * Make sure one domain is registered and enabled, reading the cache first.\n *\n * Never throws: every caller is on its way to something more important (a\n * sale, a domain connect), and a domain Stripe would not take today is\n * recorded with its error and retried by the daily reconcile.\n */\nexport async function ensurePaymentMethodDomain(\n rawDomain: string,\n options: { hostId?: string | null; signal?: AbortSignal; force?: boolean } = {},\n): Promise<EnsureDomainResult> {\n const domain = registrableDomain(rawDomain)\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!domain || !mode) {\n return { domain: String(rawDomain ?? ''), outcome: 'skipped' }\n }\n try {\n if (!options.force) {\n const cached = await docRef(mode, domain).get()\n const data = cached.data?.() as PaymentMethodDomainRecord | undefined\n if (\n cached.exists &&\n data?.enabled === true &&\n data.stripeId &&\n Date.now() - Number(data.checkedAtMs ?? 0) < PAYMENT_METHOD_DOMAIN_RECHECK_MS\n ) {\n return { domain, outcome: 'cached', record: data }\n }\n }\n const object = await registerOnPlatform(domain, options.signal)\n const next: PaymentMethodDomainRecord = {\n domain,\n mode,\n stripeId: object.id,\n enabled: object.enabled !== false,\n status: statusOf(object),\n hostId: options.hostId ?? null,\n checkedAtMs: Date.now(),\n lastError: null,\n }\n await record(mode, domain, next)\n return { domain, outcome: 'registered', record: next }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n await record(mode, domain, {\n enabled: false,\n hostId: options.hostId ?? null,\n lastError: message.slice(0, 500),\n }).catch(() => undefined)\n return { domain, outcome: 'failed', error: message }\n }\n}\n\n/**\n * Disable a domain the platform no longer serves for a site. Stripe has no\n * delete for a payment method domain; disabling stops every method on it, and\n * `ensurePaymentMethodDomain` re-enables the same registration if the name is\n * connected again.\n */\nexport async function disablePaymentMethodDomain(\n rawDomain: string,\n): Promise<{ domain: string; outcome: 'disabled' | 'absent' | 'skipped' | 'failed'; error?: string }> {\n const domain = registrableDomain(rawDomain)\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!domain || !mode) return { domain: String(rawDomain ?? ''), outcome: 'skipped' }\n try {\n const existing = await findOnStripe(domain)\n if (!existing) {\n await record(mode, domain, { enabled: false, stripeId: null, lastError: null })\n return { domain, outcome: 'absent' }\n }\n const object = existing.enabled\n ? await stripeRequest<StripeDomainObject>(\n 'POST',\n `payment_method_domains/${encodeURIComponent(existing.id)}`,\n { enabled: 'false' },\n )\n : existing\n await record(mode, domain, {\n stripeId: object.id,\n enabled: false,\n status: statusOf(object),\n lastError: null,\n })\n return { domain, outcome: 'disabled' }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return { domain, outcome: 'failed', error: message }\n }\n}\n\n/**\n * Is a name still served for some OTHER site? A custom domain's `www.` twin\n * can be another site's own `cname`, and an aglyn subdomain released by a\n * deleted site can already belong to a new one. Disabling either would take\n * Apple Pay away from a store that did nothing.\n */\nexport async function domainStillClaimed(domain: string, exceptHostId: string): Promise<boolean> {\n const firestore = firebaseAdmin.app().firestore()\n const hosts = firestore.collection('hosts')\n const names = customDomainNames(domain)\n const byCname = await hosts\n .where('cname', 'in', names.length ? names : [domain])\n .limit(3)\n .get()\n if (byCname.docs.some((doc) => doc.id !== exceptHostId)) return true\n const suffix = `.${TENANT_APEX}`\n if (domain.endsWith(suffix)) {\n const subdomain = domain.slice(0, -suffix.length)\n const bySubdomain = await hosts.where('subdomain', '==', subdomain).limit(3).get()\n if (bySubdomain.docs.some((doc) => doc.id !== exceptHostId)) return true\n }\n return false\n}\n\n/**\n * The checkout's hook: register the domain the shopper is paying on, within a\n * budget, before the client secret goes back to the browser. Only a name the\n * SITE answers on is ever registered — the return URL has already been judged\n * against `siteOwnHosts` by `siteReturnUrl`, and it is judged again here so a\n * forged `Host` can never make the platform register a stranger's domain.\n */\nexport async function ensureCheckoutDomain(input: {\n pageUrl: string\n site: SiteReturnHost | null | undefined\n hostId: string\n budgetMs?: number\n}): Promise<EnsureDomainResult | null> {\n let hostname: string\n try {\n hostname = new URL(input.pageUrl).hostname.toLowerCase()\n } catch {\n return null\n }\n if (!siteOwnHosts(input.site).includes(hostname)) return null\n if (!registrableDomain(hostname)) return null\n const controller = new AbortController()\n const budget = input.budgetMs ?? CHECKOUT_DOMAIN_BUDGET_MS\n const timer = setTimeout(() => controller.abort(), budget)\n try {\n return await ensurePaymentMethodDomain(hostname, {\n hostId: input.hostId,\n signal: controller.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** One page of the daily reconcile. */\nexport const RECONCILE_PAGE_SIZE = 200\n\n/**\n * The backfill and the safety net in one pass: every site with a connected\n * custom domain gets its domain and `www.` twin registered. A cached, enabled\n * registration costs one read and no Stripe call, so the steady state is cheap;\n * a domain connected before AGL-3629, or whose connect event was lost, is\n * registered on the first pass after it.\n *\n * Paged by `cname` with a cursor so it reads every site once and stops; the\n * `cname > ''` range uses Firestore's automatic single-field index.\n */\nexport async function reconcileCustomDomains(\n gate: { isLocked(hostId: string): Promise<boolean> },\n options: { maxPages?: number } = {},\n): Promise<{ hosts: number; registered: number; failed: number; skippedLocked: number }> {\n const result = { hosts: 0, registered: 0, failed: 0, skippedLocked: 0 }\n if (!stripeModeOfKey(process.env.STRIPE_SECRET_KEY)) return result\n const firestore = firebaseAdmin.app().firestore()\n let cursor: string | null = null\n const maxPages = options.maxPages ?? 50\n for (let page = 0; page < maxPages; page += 1) {\n let query = firestore\n .collection('hosts')\n .where('cname', '>', '')\n .orderBy('cname')\n .limit(RECONCILE_PAGE_SIZE)\n if (cursor) query = query.startAfter(cursor)\n const snapshot = await query.get()\n if (snapshot.empty) break\n for (const hostDoc of snapshot.docs) {\n result.hosts += 1\n // Skipped, not dropped: a locked site is left as it is and picked up on\n // the first pass after the lift.\n if (await gate.isLocked(hostDoc.id)) {\n result.skippedLocked += 1\n continue\n }\n for (const domain of customDomainNames(hostDoc.get('cname'))) {\n const outcome = await ensurePaymentMethodDomain(domain, { hostId: hostDoc.id })\n if (outcome.outcome === 'registered') result.registered += 1\n if (outcome.outcome === 'failed') result.failed += 1\n }\n }\n cursor = String(snapshot.docs[snapshot.docs.length - 1]?.get('cname') ?? '')\n if (snapshot.size < RECONCILE_PAGE_SIZE || !cursor) break\n }\n return result\n}\n\n/** Core's `host.domain.attached`: register the custom domain and its twin. */\nexport async function onHostDomainAttached(payload: {\n hostId: string\n domain: string\n}): Promise<void> {\n for (const domain of customDomainNames(payload.domain)) {\n const outcome = await ensurePaymentMethodDomain(domain, {\n hostId: payload.hostId,\n force: true,\n })\n if (outcome.outcome === 'failed') {\n console.warn(`[commerce] payment method domain ${domain} not registered: ${outcome.error}`)\n }\n }\n}\n\n/** Core's `host.domain.released`: disable what no other site still serves. */\nexport async function onHostDomainReleased(payload: {\n hostId: string\n domain: string\n}): Promise<void> {\n const names = payload.domain.endsWith(`.${TENANT_APEX}`)\n ? [registrableDomain(payload.domain)].filter((name): name is string => Boolean(name))\n : customDomainNames(payload.domain)\n for (const domain of names) {\n if (await domainStillClaimed(domain, payload.hostId)) continue\n const outcome = await disablePaymentMethodDomain(domain)\n if (outcome.outcome === 'failed') {\n console.warn(`[commerce] payment method domain ${domain} not disabled: ${outcome.error}`)\n }\n }\n}\n\n/** The registrations a settings card shows for one site. */\nexport async function readSiteDomainRecords(\n site: SiteReturnHost | null | undefined,\n): Promise<PaymentMethodDomainRecord[]> {\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!mode) return []\n const names = siteOwnHosts(site).filter((name) => registrableDomain(name))\n const snapshots = await Promise.all(names.map((name) => docRef(mode, name).get()))\n return snapshots.map((snapshot, index) => {\n const data = (snapshot.exists ? snapshot.data?.() : null) as PaymentMethodDomainRecord | null\n return (\n data ?? {\n domain: names[index],\n mode,\n stripeId: null,\n enabled: false,\n status: { applePay: null, googlePay: null, link: null, amazonPay: null, klarna: null },\n hostId: null,\n checkedAtMs: 0,\n lastError: null,\n }\n )\n })\n}\n"],"names":["siteOwnHosts","TENANT_APEX","firebaseAdmin","PAYMENT_METHOD_DOMAINS_COLLECTION","PAYMENT_METHOD_DOMAIN_RECHECK_MS","CHECKOUT_DOMAIN_BUDGET_MS","stripeModeOfKey","key","value","String","test","registrableDomain","input","trim","toLowerCase","replace","length","endsWith","includes","paymentMethodDomainDocId","mode","domain","customDomainNames","cname","twin","startsWith","slice","statusOf","object","applePay","apple_pay","status","googlePay","google_pay","link","amazonPay","amazon_pay","klarna","stripeRequest","method","path","params","options","query","URLSearchParams","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","idempotencyKey","body","toString","signal","payload","json","catch","ok","Error","error","message","findOnStripe","list","domain_name","limit","data","find","entry","registerOnPlatform","existing","enabled","encodeURIComponent","id","raced","docRef","app","firestore","collection","doc","record","patch","set","checkedAtMs","Date","now","merge","ensurePaymentMethodDomain","rawDomain","outcome","force","cached","get","exists","stripeId","Number","next","hostId","lastError","undefined","disablePaymentMethodDomain","domainStillClaimed","exceptHostId","hosts","names","byCname","where","docs","some","suffix","subdomain","bySubdomain","ensureCheckoutDomain","hostname","URL","pageUrl","site","controller","AbortController","budget","budgetMs","timer","setTimeout","abort","clearTimeout","RECONCILE_PAGE_SIZE","reconcileCustomDomains","gate","result","registered","failed","skippedLocked","cursor","maxPages","page","snapshot","orderBy","startAfter","empty","hostDoc","isLocked","size","onHostDomainAttached","console","warn","onHostDomainReleased","filter","name","Boolean","readSiteDomainRecords","snapshots","Promise","all","map","index"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAA8BA,YAAY,QAAQ,yCAAwC;AAC1F,SAASC,WAAW,QAAQ,qCAAoC;AAChE,SAASC,aAAa,QAAQ,2BAA0B;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GAED,OAAO,MAAMC,oCAAoC,uBAAsB;AAEvE,8EAA8E,GAC9E,OAAO,MAAMC,mCAAmC,IAAI,KAAK,KAAK,KAAK,KAAI;AAEvE,2EAA2E,GAC3E,OAAO,MAAMC,4BAA4B,KAAI;AAmC7C,gEAAgE,GAChE,OAAO,SAASC,gBAAgBC,GAAuB;IACrD,MAAMC,QAAQC,OAAOF,cAAAA,MAAO;IAC5B,IAAI,iBAAiBG,IAAI,CAACF,QAAQ,OAAO;IACzC,IAAI,iBAAiBE,IAAI,CAACF,QAAQ,OAAO;IACzC,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASG,kBAAkBC,KAAc;IAC9C,MAAMJ,QAAQC,OAAOG,gBAAAA,QAAS,IAC3BC,IAAI,GACJC,WAAW,GACXC,OAAO,CAAC,QAAQ;IACnB,IAAI,CAACP,SAASA,MAAMQ,MAAM,GAAG,KAAK,OAAO;IACzC,IAAIR,UAAU,eAAeA,MAAMS,QAAQ,CAAC,eAAe,OAAO;IAClE,IAAI,YAAYP,IAAI,CAACF,UAAUA,MAAMU,QAAQ,CAAC,MAAM,OAAO;IAC3D,IAAI,CAAC,8BAA8BR,IAAI,CAACF,QAAQ,OAAO;IACvD,OAAOA;AACT;AAEA,kDAAkD,GAClD,OAAO,SAASW,yBAAyBC,IAAgB,EAAEC,MAAc;I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ources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-method-domains.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type SiteReturnHost, siteOwnHosts } from '@aglyn/aglyn/app-utils/site-return-url'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { directSellerAccountForHost } from './seller-stripe-account'\n\n/**\n * Stripe payment method domains for storefronts (AGL-3629).\n *\n * The in-page checkout mounts Stripe's Payment Element on the merchant's own\n * domain, and Stripe shows Apple Pay there only on a REGISTERED domain (Google\n * Pay, Link, Amazon Pay and Klarna's express button use the same registration).\n * Nothing registered one, so a shopper on `shop.example.com` with a card in\n * Apple Wallet never saw the button.\n *\n * ## Which account the domain is registered on\n *\n * Stripe's rule: \"The domain where the charge is being run needs to be\n * registered for the user running the charge.\" Storefront charges are\n * DESTINATION charges created by the platform with no `Stripe-Account` header\n * and no `on_behalf_of`, so the platform runs them and the platform's key\n * registers the domain, with no `Stripe-Account` header.\n *\n * A DIRECT-charge seller runs its own charges: the session is created on the\n * seller's connected account, so Apple Pay and Google Pay show only on a\n * domain registered ON THAT ACCOUNT (`Stripe-Account` header). Every entry\n * point below takes the seller's account for that case, and the platform's\n * registration is left as it is, because the seller's hardware purchases and\n * any sale from before the switch still run on the platform.\n *\n * ## When\n *\n * - On connect: core raises `host.domain.attached`, and commerce registers\n * the custom domain and its `www.` twin.\n * - On first checkout: the session handlers call `ensureCheckoutDomain` for\n * the page the shopper is on, which covers every `{site}.aglyn.app`\n * subdomain without registering thousands of sites that never sell.\n * - Daily: `reconcileCustomDomains` registers any connected custom domain the\n * first two missed (domains connected before AGL-3629 included) — the\n * backfill is a job rather than a one-off script, so it also repairs a\n * missed event later.\n * - On release: `host.domain.released` DISABLES the domain. Stripe has no\n * delete; a disabled domain stops showing the methods and can be enabled\n * again if the name comes back.\n *\n * ## The cache\n *\n * `paymentMethodDomains/{mode}~{domain}` records what Stripe last said, so a\n * checkout costs one document read rather than a Stripe round trip. The mode is\n * in the id because a test key and a live key register in different worlds and\n * a domain registered in one is not registered in the other. A seller's\n * registration is cached under its own id, `{mode}~{account}~{domain}`,\n * because it is a different Stripe object from the platform's for the same\n * name. Server-only: the rules deny every client.\n */\n\nexport const PAYMENT_METHOD_DOMAINS_COLLECTION = 'paymentMethodDomains'\n\n/** How long a recorded registration is trusted before Stripe is asked again. */\nexport const PAYMENT_METHOD_DOMAIN_RECHECK_MS = 7 * 24 * 60 * 60 * 1000\n\n/** The most a checkout waits on Stripe before selling without the domain. */\nexport const CHECKOUT_DOMAIN_BUDGET_MS = 2500\n\nexport type StripeMode = 'live' | 'test'\n\n/** Stripe's per-method verdict on a domain. */\nexport interface PaymentMethodDomainStatus {\n applePay: string | null\n googlePay: string | null\n link: string | null\n amazonPay: string | null\n klarna: string | null\n}\n\nexport interface PaymentMethodDomainRecord {\n domain: string\n mode: StripeMode\n /**\n * The connected account the domain is registered on, for a direct-charge\n * seller; absent or null for the platform's own registration.\n */\n stripeAccount?: string | null\n stripeId: string | null\n enabled: boolean\n status: PaymentMethodDomainStatus\n hostId: string | null\n checkedAtMs: number\n lastError: string | null\n}\n\ninterface StripeDomainObject {\n id: string\n domain_name: string\n enabled: boolean\n apple_pay?: { status?: string }\n google_pay?: { status?: string }\n link?: { status?: string }\n amazon_pay?: { status?: string }\n klarna?: { status?: string }\n}\n\n/** Which Stripe world the platform key is in, from its prefix. */\nexport function stripeModeOfKey(key: string | undefined): StripeMode | null {\n const value = String(key ?? '')\n if (/^(sk|rk)_live_/.test(value)) return 'live'\n if (/^(sk|rk)_test_/.test(value)) return 'test'\n return null\n}\n\n/**\n * A hostname Stripe can register: lowercased, no trailing dot, at least two\n * labels, and never a local or IP host — a checkout opened on `localhost`\n * must not try to register it.\n */\nexport function registrableDomain(input: unknown): string | null {\n const value = String(input ?? '')\n .trim()\n .toLowerCase()\n .replace(/\\.+$/, '')\n if (!value || value.length > 253) return null\n if (value === 'localhost' || value.endsWith('.localhost')) return null\n if (/^[0-9.]+$/.test(value) || value.includes(':')) return null\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(value)) return null\n return value\n}\n\n/**\n * The cache document id for a domain in a mode, on the platform or on one\n * seller's connected account.\n */\nexport function paymentMethodDomainDocId(\n mode: StripeMode,\n domain: string,\n stripeAccount?: string | null,\n): string {\n const account = accountOrNull(stripeAccount)\n return account ? `${mode}~${account}~${domain}` : `${mode}~${domain}`\n}\n\n/** A usable connected-account id, or null for \"the platform\". */\nfunction accountOrNull(value: unknown): string | null {\n const id = typeof value === 'string' ? value.trim() : ''\n return /^acct_[A-Za-z0-9]+$/.test(id) ? id : null\n}\n\n/**\n * The domains a site's custom domain needs: the domain and its `www.` twin,\n * since the platform answers on both (`siteOwnHosts`).\n */\nexport function customDomainNames(cname: unknown): string[] {\n const domain = registrableDomain(cname)\n if (!domain) return []\n const twin = domain.startsWith('www.') ? domain.slice(4) : `www.${domain}`\n return [domain, ...(registrableDomain(twin) ? [twin] : [])]\n}\n\nfunction statusOf(object: StripeDomainObject): PaymentMethodDomainStatus {\n return {\n applePay: object.apple_pay?.status ?? null,\n googlePay: object.google_pay?.status ?? null,\n link: object.link?.status ?? null,\n amazonPay: object.amazon_pay?.status ?? null,\n klarna: object.klarna?.status ?? null,\n }\n}\n\nasync function stripeRequest<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: Record<string, string>,\n options: {\n idempotencyKey?: string\n signal?: AbortSignal\n stripeAccount?: string | null\n } = {},\n): Promise<T> {\n const query = method === 'GET' && params ? `?${new URLSearchParams(params)}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n // The platform's own key and NO `Stripe-Account` for the platform's\n // registration (destination charges are run by the platform); the\n // seller's account for a direct-charge seller, who runs its own.\n ...(options.stripeAccount && { 'Stripe-Account': options.stripeAccount }),\n ...(options.idempotencyKey && { 'Idempotency-Key': options.idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: new URLSearchParams(params).toString() }),\n ...(options.signal && { signal: options.signal }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\nasync function findOnStripe(\n domain: string,\n signal?: AbortSignal,\n stripeAccount?: string | null,\n): Promise<StripeDomainObject | null> {\n const list = await stripeRequest<{ data?: StripeDomainObject[] }>(\n 'GET',\n 'payment_method_domains',\n { domain_name: domain, limit: '1' },\n { signal, stripeAccount },\n )\n return list.data?.find((entry) => entry.domain_name === domain) ?? null\n}\n\n/**\n * Register (or re-enable) one domain on the platform account. Idempotent end\n * to end: an existing registration is found first and reused, a disabled one\n * is enabled rather than duplicated, and the create carries an idempotency key\n * so two checkouts racing on a fresh subdomain open one registration.\n */\nexport async function registerOnPlatform(\n domain: string,\n signal?: AbortSignal,\n): Promise<StripeDomainObject> {\n return registerDomain(domain, { signal })\n}\n\n/**\n * Register (or re-enable) one domain on a direct-charge seller's connected\n * account: the same steps as {@link registerOnPlatform}, each sent with the\n * seller's `Stripe-Account`.\n */\nexport async function registerOnAccount(\n domain: string,\n stripeAccount: string,\n signal?: AbortSignal,\n): Promise<StripeDomainObject> {\n return registerDomain(domain, { signal, stripeAccount })\n}\n\nasync function registerDomain(\n domain: string,\n options: { signal?: AbortSignal; stripeAccount?: string | null },\n): Promise<StripeDomainObject> {\n const { signal } = options\n const stripeAccount = accountOrNull(options.stripeAccount)\n const existing = await findOnStripe(domain, signal, stripeAccount)\n if (existing) {\n if (existing.enabled) return existing\n return stripeRequest<StripeDomainObject>(\n 'POST',\n `payment_method_domains/${encodeURIComponent(existing.id)}`,\n { enabled: 'true' },\n { signal, stripeAccount },\n )\n }\n try {\n return await stripeRequest<StripeDomainObject>(\n 'POST',\n 'payment_method_domains',\n { domain_name: domain, enabled: 'true' },\n {\n // Stripe scopes the key per account; the account is in it anyway so\n // a log line names which registration it was.\n idempotencyKey: stripeAccount\n ? `aglyn-pmd-register:${stripeAccount}:${domain}`\n : `aglyn-pmd-register:${domain}`,\n signal,\n stripeAccount,\n },\n )\n } catch (error) {\n // Lost a race to a create that landed between the lookup and this call:\n // the registration exists, which is what was wanted.\n const raced = await findOnStripe(domain, signal, stripeAccount).catch(() => null)\n if (raced) return raced\n throw error\n }\n}\n\nfunction docRef(mode: StripeMode, domain: string, stripeAccount?: string | null) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection(PAYMENT_METHOD_DOMAINS_COLLECTION)\n .doc(paymentMethodDomainDocId(mode, domain, stripeAccount))\n}\n\nasync function record(\n mode: StripeMode,\n domain: string,\n patch: Partial<PaymentMethodDomainRecord>,\n stripeAccount?: string | null,\n): Promise<void> {\n const account = accountOrNull(stripeAccount)\n await docRef(mode, domain, account).set(\n {\n domain,\n mode,\n // Only a seller's registration names an account, so the platform's\n // documents are written exactly as before.\n ...(account ? { stripeAccount: account } : {}),\n checkedAtMs: Date.now(),\n ...patch,\n },\n { merge: true },\n )\n}\n\nexport interface EnsureDomainResult {\n domain: string\n outcome: 'registered' | 'cached' | 'skipped' | 'failed'\n record?: PaymentMethodDomainRecord\n error?: string\n}\n\n/**\n * Make sure one domain is registered and enabled, reading the cache first.\n *\n * Never throws: every caller is on its way to something more important (a\n * sale, a domain connect), and a domain Stripe would not take today is\n * recorded with its error and retried by the daily reconcile.\n */\nexport async function ensurePaymentMethodDomain(\n rawDomain: string,\n options: {\n hostId?: string | null\n signal?: AbortSignal\n force?: boolean\n /** Register on this direct-charge seller's account, not the platform. */\n stripeAccount?: string | null\n } = {},\n): Promise<EnsureDomainResult> {\n const domain = registrableDomain(rawDomain)\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!domain || !mode) {\n return { domain: String(rawDomain ?? ''), outcome: 'skipped' }\n }\n const account = accountOrNull(options.stripeAccount)\n try {\n if (!options.force) {\n const cached = await docRef(mode, domain, account).get()\n const data = cached.data?.() as PaymentMethodDomainRecord | undefined\n if (\n cached.exists &&\n data?.enabled === true &&\n data.stripeId &&\n Date.now() - Number(data.checkedAtMs ?? 0) < PAYMENT_METHOD_DOMAIN_RECHECK_MS\n ) {\n return { domain, outcome: 'cached', record: data }\n }\n }\n const object = account\n ? await registerOnAccount(domain, account, options.signal)\n : await registerOnPlatform(domain, options.signal)\n const next: PaymentMethodDomainRecord = {\n domain,\n mode,\n ...(account ? { stripeAccount: account } : {}),\n stripeId: object.id,\n enabled: object.enabled !== false,\n status: statusOf(object),\n hostId: options.hostId ?? null,\n checkedAtMs: Date.now(),\n lastError: null,\n }\n await record(mode, domain, next, account)\n return { domain, outcome: 'registered', record: next }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n await record(\n mode,\n domain,\n {\n enabled: false,\n hostId: options.hostId ?? null,\n lastError: message.slice(0, 500),\n },\n account,\n ).catch(() => undefined)\n return { domain, outcome: 'failed', error: message }\n }\n}\n\n/**\n * Disable a domain the platform no longer serves for a site. Stripe has no\n * delete for a payment method domain; disabling stops every method on it, and\n * `ensurePaymentMethodDomain` re-enables the same registration if the name is\n * connected again.\n */\nexport async function disablePaymentMethodDomain(\n rawDomain: string,\n options: { stripeAccount?: string | null } = {},\n): Promise<{ domain: string; outcome: 'disabled' | 'absent' | 'skipped' | 'failed'; error?: string }> {\n const domain = registrableDomain(rawDomain)\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!domain || !mode) return { domain: String(rawDomain ?? ''), outcome: 'skipped' }\n const account = accountOrNull(options.stripeAccount)\n try {\n const existing = await findOnStripe(domain, undefined, account)\n if (!existing) {\n await record(mode, domain, { enabled: false, stripeId: null, lastError: null }, account)\n return { domain, outcome: 'absent' }\n }\n const object = existing.enabled\n ? await stripeRequest<StripeDomainObject>(\n 'POST',\n `payment_method_domains/${encodeURIComponent(existing.id)}`,\n { enabled: 'false' },\n { stripeAccount: account },\n )\n : existing\n await record(\n mode,\n domain,\n {\n stripeId: object.id,\n enabled: false,\n status: statusOf(object),\n lastError: null,\n },\n account,\n )\n return { domain, outcome: 'disabled' }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return { domain, outcome: 'failed', error: message }\n }\n}\n\n/**\n * Is a name still served for some OTHER site? A custom domain's `www.` twin\n * can be another site's own `cname`, and an aglyn subdomain released by a\n * deleted site can already belong to a new one. Disabling either would take\n * Apple Pay away from a store that did nothing.\n */\nexport async function domainStillClaimed(domain: string, exceptHostId: string): Promise<boolean> {\n const firestore = firebaseAdmin.app().firestore()\n const hosts = firestore.collection('hosts')\n const names = customDomainNames(domain)\n const byCname = await hosts\n .where('cname', 'in', names.length ? names : [domain])\n .limit(3)\n .get()\n if (byCname.docs.some((doc) => doc.id !== exceptHostId)) return true\n const suffix = `.${TENANT_APEX}`\n if (domain.endsWith(suffix)) {\n const subdomain = domain.slice(0, -suffix.length)\n const bySubdomain = await hosts.where('subdomain', '==', subdomain).limit(3).get()\n if (bySubdomain.docs.some((doc) => doc.id !== exceptHostId)) return true\n }\n return false\n}\n\n/**\n * The checkout's hook: register the domain the shopper is paying on, within a\n * budget, before the client secret goes back to the browser. Only a name the\n * SITE answers on is ever registered — the return URL has already been judged\n * against `siteOwnHosts` by `siteReturnUrl`, and it is judged again here so a\n * forged `Host` can never make the platform register a stranger's domain.\n */\nexport async function ensureCheckoutDomain(input: {\n pageUrl: string\n site: SiteReturnHost | null | undefined\n hostId: string\n budgetMs?: number\n /**\n * The seller's connected account when this checkout is a DIRECT charge:\n * the session runs there, so the domain must be registered there.\n */\n stripeAccount?: string\n}): Promise<EnsureDomainResult | null> {\n let hostname: string\n try {\n hostname = new URL(input.pageUrl).hostname.toLowerCase()\n } catch {\n return null\n }\n if (!siteOwnHosts(input.site).includes(hostname)) return null\n if (!registrableDomain(hostname)) return null\n const controller = new AbortController()\n const budget = input.budgetMs ?? CHECKOUT_DOMAIN_BUDGET_MS\n const timer = setTimeout(() => controller.abort(), budget)\n try {\n return await ensurePaymentMethodDomain(hostname, {\n hostId: input.hostId,\n signal: controller.signal,\n ...(input.stripeAccount ? { stripeAccount: input.stripeAccount } : {}),\n })\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** One page of the daily reconcile. */\nexport const RECONCILE_PAGE_SIZE = 200\n\n/**\n * The backfill and the safety net in one pass: every site with a connected\n * custom domain gets its domain and `www.` twin registered. A cached, enabled\n * registration costs one read and no Stripe call, so the steady state is cheap;\n * a domain connected before AGL-3629, or whose connect event was lost, is\n * registered on the first pass after it.\n *\n * Paged by `cname` with a cursor so it reads every site once and stops; the\n * `cname > ''` range uses Firestore's automatic single-field index.\n */\nexport async function reconcileCustomDomains(\n gate: { isLocked(hostId: string): Promise<boolean> },\n options: {\n maxPages?: number\n /** The site's direct-charge seller account, or null (tests inject it). */\n sellerAccount?: (hostId: string) => Promise<string | null>\n } = {},\n): Promise<{ hosts: number; registered: number; failed: number; skippedLocked: number }> {\n const sellerAccount = options.sellerAccount ?? directSellerAccountForHost\n const result = { hosts: 0, registered: 0, failed: 0, skippedLocked: 0 }\n if (!stripeModeOfKey(process.env.STRIPE_SECRET_KEY)) return result\n const firestore = firebaseAdmin.app().firestore()\n let cursor: string | null = null\n const maxPages = options.maxPages ?? 50\n for (let page = 0; page < maxPages; page += 1) {\n let query = firestore\n .collection('hosts')\n .where('cname', '>', '')\n .orderBy('cname')\n .limit(RECONCILE_PAGE_SIZE)\n if (cursor) query = query.startAfter(cursor)\n const snapshot = await query.get()\n if (snapshot.empty) break\n for (const hostDoc of snapshot.docs) {\n result.hosts += 1\n // Skipped, not dropped: a locked site is left as it is and picked up on\n // the first pass after the lift.\n if (await gate.isLocked(hostDoc.id)) {\n result.skippedLocked += 1\n continue\n }\n // A direct-charge seller runs its own charges, so its domains are\n // registered on its account as well as the platform's.\n const account = await sellerAccount(hostDoc.id).catch(() => null)\n for (const domain of customDomainNames(hostDoc.get('cname'))) {\n for (const stripeAccount of account ? [null, account] : [null]) {\n const outcome = await ensurePaymentMethodDomain(domain, {\n hostId: hostDoc.id,\n ...(stripeAccount ? { stripeAccount } : {}),\n })\n if (outcome.outcome === 'registered') result.registered += 1\n if (outcome.outcome === 'failed') result.failed += 1\n }\n }\n }\n cursor = String(snapshot.docs[snapshot.docs.length - 1]?.get('cname') ?? '')\n if (snapshot.size < RECONCILE_PAGE_SIZE || !cursor) break\n }\n return result\n}\n\n/** Core's `host.domain.attached`: register the custom domain and its twin. */\nexport async function onHostDomainAttached(\n payload: {\n hostId: string\n domain: string\n },\n options: { sellerAccount?: (hostId: string) => Promise<string | null> } = {},\n): Promise<void> {\n // The platform's registration as before, and the seller's own as well when\n // the site sells by direct charges, since those sessions run on its account.\n const account = await (options.sellerAccount ?? directSellerAccountForHost)(\n payload.hostId,\n ).catch(() => null)\n for (const domain of customDomainNames(payload.domain)) {\n for (const stripeAccount of account ? [null, account] : [null]) {\n const outcome = await ensurePaymentMethodDomain(domain, {\n hostId: payload.hostId,\n force: true,\n ...(stripeAccount ? { stripeAccount } : {}),\n })\n if (outcome.outcome === 'failed') {\n console.warn(\n `[commerce] payment method domain ${domain}${\n stripeAccount ? ` on ${stripeAccount}` : ''\n } not registered: ${outcome.error}`,\n )\n }\n }\n }\n}\n\n/** Core's `host.domain.released`: disable what no other site still serves. */\nexport async function onHostDomainReleased(\n payload: {\n hostId: string\n domain: string\n },\n options: { sellerAccount?: (hostId: string) => Promise<string | null> } = {},\n): Promise<void> {\n const names = payload.domain.endsWith(`.${TENANT_APEX}`)\n ? [registrableDomain(payload.domain)].filter((name): name is string => Boolean(name))\n : customDomainNames(payload.domain)\n const account = await (options.sellerAccount ?? directSellerAccountForHost)(\n payload.hostId,\n ).catch(() => null)\n for (const domain of names) {\n // The PLATFORM's registration is shared by every site that answers on\n // the name, so it waits until no other site does. The seller's own is\n // that seller's alone, and goes with this site's release.\n if (account) {\n const onSeller = await disablePaymentMethodDomain(domain, { stripeAccount: account })\n if (onSeller.outcome === 'failed') {\n console.warn(\n `[commerce] payment method domain ${domain} on ${account} not disabled: ${onSeller.error}`,\n )\n }\n }\n if (await domainStillClaimed(domain, payload.hostId)) continue\n const outcome = await disablePaymentMethodDomain(domain)\n if (outcome.outcome === 'failed') {\n console.warn(`[commerce] payment method domain ${domain} not disabled: ${outcome.error}`)\n }\n }\n}\n\n/** The registrations a settings card shows for one site. */\nexport async function readSiteDomainRecords(\n site: SiteReturnHost | null | undefined,\n /**\n * The site's direct-charge seller account: its registrations are the ones\n * the site's checkout uses, so they are the ones to show.\n */\n stripeAccount?: string | null,\n): Promise<PaymentMethodDomainRecord[]> {\n const mode = stripeModeOfKey(process.env.STRIPE_SECRET_KEY)\n if (!mode) return []\n const account = accountOrNull(stripeAccount)\n const names = siteOwnHosts(site).filter((name) => registrableDomain(name))\n const snapshots = await Promise.all(\n names.map((name) => docRef(mode, name, account).get()),\n )\n return snapshots.map((snapshot, index) => {\n const data = (snapshot.exists ? snapshot.data?.() : null) as PaymentMethodDomainRecord | null\n return (\n data ?? {\n domain: names[index],\n mode,\n ...(account ? { stripeAccount: account } : {}),\n stripeId: null,\n enabled: false,\n status: { applePay: null, googlePay: null, link: null, amazonPay: null, klarna: null },\n hostId: null,\n checkedAtMs: 0,\n lastError: null,\n }\n )\n })\n}\n"],"names":["siteOwnHosts","TENANT_APEX","firebaseAdmin","directSellerAccountForHost","PAYMENT_METHOD_DOMAINS_COLLECTION","PAYMENT_METHOD_DOMAIN_RECHECK_MS","CHECKOUT_DOMAIN_BUDGET_MS","stripeModeOfKey","key","value","String","test","registrableDomain","input","trim","toLowerCase","replace","length","endsWith","includes","paymentMethodDomainDocId","mode","domain","stripeAccount","account","accountOrNull","id","customDomainNames","cname","twin","startsWith","slice","statusOf","object","applePay","apple_pay","status","googlePay","google_pay","link","amazonPay","amazon_pay","klarna","stripeRequest","method","path","params","options","query","URLSearchParams","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","idempotencyKey","body","toString","signal","payload","json","catch","ok","Error","error","message","findOnStripe","list","domain_name","limit","data","find","entry","registerOnPlatform","registerDomain","registerOnAccount","existing","enabled","encodeURIComponent","raced","docRef","app","firestore","collection","doc","record","patch","set","checkedAtMs","Date","now","merge","ensurePaymentMethodDomain","rawDomain","outcome","force","cached","get","exists","stripeId","Number","next","hostId","lastError","undefined","disablePaymentMethodDomain","domainStillClaimed","exceptHostId","hosts","names","byCname","where","docs","some","suffix","subdomain","bySubdomain","ensureCheckoutDomain","hostname","URL","pageUrl","site","controller","AbortController","budget","budgetMs","timer","setTimeout","abort","clearTimeout","RECONCILE_PAGE_SIZE","reconcileCustomDomains","gate","sellerAccount","result","registered","failed","skippedLocked","cursor","maxPages","page","snapshot","orderBy","startAfter","empty","hostDoc","isLocked","size","onHostDomainAttached","console","warn","onHostDomainReleased","filter","name","Boolean","onSeller","readSiteDomainRecords","snapshots","Promise","all","map","index"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAA8BA,YAAY,QAAQ,yCAAwC;AAC1F,SAASC,WAAW,QAAQ,qCAAoC;AAChE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,0BAA0B,QAAQ,6BAAyB;AAEpE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDC,GAED,OAAO,MAAMC,oCAAoC,uBAAsB;AAEvE,8EAA8E,GAC9E,OAAO,MAAMC,mCAAmC,IAAI,KAAK,KAAK,KAAK,KAAI;AAEvE,2EAA2E,GAC3E,OAAO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;IAC1D,IAAI,CAACnC,MAAM,OAAO,EAAE;IACpB,MAAMG,UAAUC,cAAcF;IAC9B,MAAMwF,QAAQ/G,aAAa2H,MAAM+B,MAAM,CAAC,CAACC,OAAS/I,kBAAkB+I;IACpE,MAAMI,YAAY,MAAMC,QAAQC,GAAG,CACjClD,MAAMmD,GAAG,CAAC,CAACP,OAASzE,OAAO7D,MAAMsI,MAAMnI,SAAS2E,GAAG;IAErD,OAAO4D,UAAUG,GAAG,CAAC,CAACnB,UAAUoB;QAC9B,MAAM3F,OAAQuE,SAAS3C,MAAM,GAAG2C,SAASvE,IAAI,oBAAbuE,SAASvE,IAAI,MAAbuE,YAAoB;QACpD,OACEvE,eAAAA,OAAQ;YACNlD,QAAQyF,KAAK,CAACoD,MAAM;YACpB9I;WACIG,UAAU;YAAED,eAAeC;QAAQ,IAAI,CAAC;YAC5C6E,UAAU;YACVtB,SAAS;YACT3C,QAAQ;gBAAEF,UAAU;gBAAMG,WAAW;gBAAME,MAAM;gBAAMC,WAAW;gBAAME,QAAQ;YAAK;YACrF8D,QAAQ;YACRd,aAAa;YACbe,WAAW;;IAGjB;AACF"}
|
|
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import {
|
|
17
|
+
*/ import { directSellerAccountForHost } from "./seller-stripe-account.js";
|
|
18
|
+
import { checkEntitlement, pluginRequestFromWeb } from "@aglyn/aglyn/server";
|
|
18
19
|
import { emailUnverifiedResponse, firebaseAdmin, getOrgForHost, isImpersonationSession, lockdownRefusal } from "@aglyn/tenant-data-admin";
|
|
19
20
|
import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
20
21
|
import { isStorefrontPaymentMethodOn, normalizeStorefrontPaymentMethodSettings, STOREFRONT_PAYMENT_METHODS } from "../model/commerce-payment-methods.js";
|
|
@@ -268,7 +269,7 @@ export async function paymentMethodsHandler(request) {
|
|
|
268
269
|
}
|
|
269
270
|
const answer = {
|
|
270
271
|
methods: buildPaymentMethodRows(settings, platform, capabilities),
|
|
271
|
-
domains: await readSiteDomainRecords(hostSnapshot.data()),
|
|
272
|
+
domains: await readSiteDomainRecords(hostSnapshot.data(), await directSellerAccountForHost(hostId)),
|
|
272
273
|
accountConnected: Boolean(accountId),
|
|
273
274
|
canEdit: mayEdit,
|
|
274
275
|
canFinish: Boolean(accountId) && decoded.uid === ownerUid,
|