@aglyn/tenant-data-admin 1.20.1 → 1.20.3
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 +7 -7
- package/src/lib/server/erase.js +33 -1
- package/src/lib/server/erase.js.map +1 -1
- package/src/lib/server/firestore-transient.d.ts +37 -0
- package/src/lib/server/firestore-transient.js +68 -0
- package/src/lib/server/firestore-transient.js.map +1 -0
- package/src/lib/server/payment-provider-stripe-connect.d.ts +12 -0
- package/src/lib/server/payment-provider-stripe-connect.js +14 -0
- package/src/lib/server/payment-provider-stripe-connect.js.map +1 -1
- package/src/lib/server/payment-provider.d.ts +36 -0
- package/src/lib/server/payment-provider.js +44 -0
- package/src/lib/server/payment-provider.js.map +1 -1
- package/src/lib/server/tenant-dns-check.d.ts +33 -0
- package/src/lib/server/tenant-dns-check.js +141 -4
- package/src/lib/server/tenant-dns-check.js.map +1 -1
- package/src/tenancy.d.ts +1 -1
- package/src/tenancy.js +1 -1
- package/src/tenancy.js.map +1 -1
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
export declare function isTransientFirestoreError(error: unknown): boolean;
|
|
18
|
+
export interface TransientFirestoreRetryOptions {
|
|
19
|
+
/**
|
|
20
|
+
* The wait before each retry, in order. Its length is the number of
|
|
21
|
+
* retries, so the total attempts are `delaysMs.length + 1`.
|
|
22
|
+
*/
|
|
23
|
+
delaysMs?: readonly number[];
|
|
24
|
+
/** Called before each retry with the failure it follows. */
|
|
25
|
+
onRetry?: (error: unknown, attempt: number) => void;
|
|
26
|
+
}
|
|
27
|
+
/** 250 ms, 1 s, 2.5 s: past a burst without holding a request for long. */
|
|
28
|
+
export declare const DEFAULT_TRANSIENT_RETRY_DELAYS_MS: readonly number[];
|
|
29
|
+
/**
|
|
30
|
+
* Run `operation`, and run it again after a pause when it fails with a
|
|
31
|
+
* {@link isTransientFirestoreError | transient} code. Anything else, and the
|
|
32
|
+
* last transient failure once the delays are spent, is thrown as it came.
|
|
33
|
+
*
|
|
34
|
+
* Only for an operation that is safe to repeat: a delete, a merge set, an
|
|
35
|
+
* idempotent sweep. A retried `add` writes twice.
|
|
36
|
+
*/
|
|
37
|
+
export declare function retryTransientFirestore<T>(operation: () => Promise<T>, options?: TransientFirestoreRetryOptions): Promise<T>;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ /**
|
|
17
|
+
* Firestore failures that a second attempt can succeed past: contention
|
|
18
|
+
* (`ABORTED`, which the admin SDK has already retried inside a transaction),
|
|
19
|
+
* an unreachable backend, a deadline, or a quota burst. The admin SDK reports
|
|
20
|
+
* gRPC codes as numbers. The string forms are kept for anything that
|
|
21
|
+
* normalises them.
|
|
22
|
+
*
|
|
23
|
+
* `recursiveDelete` reports a failed bulk delete with the LAST failed write's
|
|
24
|
+
* code copied onto its own error, so the same test classifies it.
|
|
25
|
+
*/ const TRANSIENT_FIRESTORE_CODES = new Set([
|
|
26
|
+
4,
|
|
27
|
+
8,
|
|
28
|
+
10,
|
|
29
|
+
14,
|
|
30
|
+
'deadline-exceeded',
|
|
31
|
+
'resource-exhausted',
|
|
32
|
+
'aborted',
|
|
33
|
+
'unavailable'
|
|
34
|
+
]);
|
|
35
|
+
export function isTransientFirestoreError(error) {
|
|
36
|
+
try {
|
|
37
|
+
return TRANSIENT_FIRESTORE_CODES.has(error == null ? void 0 : error.code);
|
|
38
|
+
} catch (unused) {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** 250 ms, 1 s, 2.5 s: past a burst without holding a request for long. */ export const DEFAULT_TRANSIENT_RETRY_DELAYS_MS = [
|
|
43
|
+
250,
|
|
44
|
+
1000,
|
|
45
|
+
2500
|
|
46
|
+
];
|
|
47
|
+
/**
|
|
48
|
+
* Run `operation`, and run it again after a pause when it fails with a
|
|
49
|
+
* {@link isTransientFirestoreError | transient} code. Anything else, and the
|
|
50
|
+
* last transient failure once the delays are spent, is thrown as it came.
|
|
51
|
+
*
|
|
52
|
+
* Only for an operation that is safe to repeat: a delete, a merge set, an
|
|
53
|
+
* idempotent sweep. A retried `add` writes twice.
|
|
54
|
+
*/ export async function retryTransientFirestore(operation, options = {}) {
|
|
55
|
+
var _options_delaysMs;
|
|
56
|
+
const delaysMs = (_options_delaysMs = options.delaysMs) != null ? _options_delaysMs : DEFAULT_TRANSIENT_RETRY_DELAYS_MS;
|
|
57
|
+
for(let attempt = 0;; attempt += 1){
|
|
58
|
+
try {
|
|
59
|
+
return await operation();
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (attempt >= delaysMs.length || !isTransientFirestoreError(error)) throw error;
|
|
62
|
+
options.onRetry == null ? void 0 : options.onRetry.call(options, error, attempt + 1);
|
|
63
|
+
await new Promise((resolve)=>setTimeout(resolve, delaysMs[attempt]));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=firestore-transient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/firestore-transient.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Firestore failures that a second attempt can succeed past: contention\n * (`ABORTED`, which the admin SDK has already retried inside a transaction),\n * an unreachable backend, a deadline, or a quota burst. The admin SDK reports\n * gRPC codes as numbers. The string forms are kept for anything that\n * normalises them.\n *\n * `recursiveDelete` reports a failed bulk delete with the LAST failed write's\n * code copied onto its own error, so the same test classifies it.\n */\nconst TRANSIENT_FIRESTORE_CODES = new Set<unknown>([\n 4, // DEADLINE_EXCEEDED\n 8, // RESOURCE_EXHAUSTED\n 10, // ABORTED\n 14, // UNAVAILABLE\n 'deadline-exceeded',\n 'resource-exhausted',\n 'aborted',\n 'unavailable',\n])\n\nexport function isTransientFirestoreError(error: unknown): boolean {\n try {\n return TRANSIENT_FIRESTORE_CODES.has((error as { code?: unknown } | null)?.code)\n } catch {\n return false\n }\n}\n\nexport interface TransientFirestoreRetryOptions {\n /**\n * The wait before each retry, in order. Its length is the number of\n * retries, so the total attempts are `delaysMs.length + 1`.\n */\n delaysMs?: readonly number[]\n /** Called before each retry with the failure it follows. */\n onRetry?: (error: unknown, attempt: number) => void\n}\n\n/** 250 ms, 1 s, 2.5 s: past a burst without holding a request for long. */\nexport const DEFAULT_TRANSIENT_RETRY_DELAYS_MS: readonly number[] = [250, 1000, 2500]\n\n/**\n * Run `operation`, and run it again after a pause when it fails with a\n * {@link isTransientFirestoreError | transient} code. Anything else, and the\n * last transient failure once the delays are spent, is thrown as it came.\n *\n * Only for an operation that is safe to repeat: a delete, a merge set, an\n * idempotent sweep. A retried `add` writes twice.\n */\nexport async function retryTransientFirestore<T>(\n operation: () => Promise<T>,\n options: TransientFirestoreRetryOptions = {},\n): Promise<T> {\n const delaysMs = options.delaysMs ?? DEFAULT_TRANSIENT_RETRY_DELAYS_MS\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await operation()\n } catch (error) {\n if (attempt >= delaysMs.length || !isTransientFirestoreError(error)) throw error\n options.onRetry?.(error, attempt + 1)\n await new Promise((resolve) => setTimeout(resolve, delaysMs[attempt]))\n }\n }\n}\n"],"names":["TRANSIENT_FIRESTORE_CODES","Set","isTransientFirestoreError","error","has","code","DEFAULT_TRANSIENT_RETRY_DELAYS_MS","retryTransientFirestore","operation","options","delaysMs","attempt","length","onRetry","Promise","resolve","setTimeout"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;CASC,GACD,MAAMA,4BAA4B,IAAIC,IAAa;IACjD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,OAAO,SAASC,0BAA0BC,KAAc;IACtD,IAAI;QACF,OAAOH,0BAA0BI,GAAG,CAAED,yBAAD,AAACA,MAAqCE,IAAI;IACjF,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAYA,yEAAyE,GACzE,OAAO,MAAMC,oCAAuD;IAAC;IAAK;IAAM;CAAK,CAAA;AAErF;;;;;;;CAOC,GACD,OAAO,eAAeC,wBACpBC,SAA2B,EAC3BC,UAA0C,CAAC,CAAC;QAE3BA;IAAjB,MAAMC,YAAWD,oBAAAA,QAAQC,QAAQ,YAAhBD,oBAAoBH;IACrC,IAAK,IAAIK,UAAU,IAAKA,WAAW,EAAG;QACpC,IAAI;YACF,OAAO,MAAMH;QACf,EAAE,OAAOL,OAAO;YACd,IAAIQ,WAAWD,SAASE,MAAM,IAAI,CAACV,0BAA0BC,QAAQ,MAAMA;YAC3EM,QAAQI,OAAO,oBAAfJ,QAAQI,OAAO,MAAfJ,SAAkBN,OAAOQ,UAAU;YACnC,MAAM,IAAIG,QAAQ,CAACC,UAAYC,WAAWD,SAASL,QAAQ,CAACC,QAAQ;QACtE;IACF;AACF"}
|
|
@@ -100,6 +100,18 @@ export declare function platformStripeMode(key?: string | undefined): PaymentMod
|
|
|
100
100
|
* finish onboarding at all.
|
|
101
101
|
*/
|
|
102
102
|
export declare function resolvePlatformStripeMode(key?: string | undefined, fetchImpl?: typeof fetch): Promise<PaymentMode | undefined>;
|
|
103
|
+
/**
|
|
104
|
+
* Whether Stripe's refusal to read an account says it lives in the other
|
|
105
|
+
* mode — the contract's `refusedAsOtherMode`.
|
|
106
|
+
*
|
|
107
|
+
* Retrieving a test account with a live key answers 400 "The account acct_…
|
|
108
|
+
* was a test account created with a testmode key, and therefore can only be
|
|
109
|
+
* used with testmode keys" (measured, see the note above), and the live twin
|
|
110
|
+
* names a "livemode key". Matched on that wording and nothing wider: a
|
|
111
|
+
* refusal for any other reason (a network fault, an outage, a revoked
|
|
112
|
+
* platform) must never retire an account that may be working.
|
|
113
|
+
*/
|
|
114
|
+
export declare function stripeRefusedAsOtherMode(message: unknown): boolean;
|
|
103
115
|
/**
|
|
104
116
|
* A Stripe webhook event about a connected account, applied to the profiles in
|
|
105
117
|
* `collection` that store it — the contract's `applyAccountEvent`.
|
|
@@ -119,6 +119,19 @@
|
|
|
119
119
|
}
|
|
120
120
|
return fromKey;
|
|
121
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* Whether Stripe's refusal to read an account says it lives in the other
|
|
124
|
+
* mode — the contract's `refusedAsOtherMode`.
|
|
125
|
+
*
|
|
126
|
+
* Retrieving a test account with a live key answers 400 "The account acct_…
|
|
127
|
+
* was a test account created with a testmode key, and therefore can only be
|
|
128
|
+
* used with testmode keys" (measured, see the note above), and the live twin
|
|
129
|
+
* names a "livemode key". Matched on that wording and nothing wider: a
|
|
130
|
+
* refusal for any other reason (a network fault, an outage, a revoked
|
|
131
|
+
* platform) must never retire an account that may be working.
|
|
132
|
+
*/ export function stripeRefusedAsOtherMode(message) {
|
|
133
|
+
return /\b(test|live)\s?mode keys?\b/i.test(String(message != null ? message : ''));
|
|
134
|
+
}
|
|
122
135
|
/**
|
|
123
136
|
* A Stripe webhook event about a connected account, applied to the profiles in
|
|
124
137
|
* `collection` that store it — the contract's `applyAccountEvent`.
|
|
@@ -182,6 +195,7 @@
|
|
|
182
195
|
// module was first evaluated.
|
|
183
196
|
platformMode: ()=>platformStripeMode(),
|
|
184
197
|
resolvePlatformMode: ()=>resolvePlatformStripeMode(),
|
|
198
|
+
refusedAsOtherMode: stripeRefusedAsOtherMode,
|
|
185
199
|
applyAccountEvent: applyStripeConnectAccountEvent
|
|
186
200
|
};
|
|
187
201
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/payment-provider-stripe-connect.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 { PaymentMode, PaymentProvider, PaymentProviderEvent } from './payment-provider'\n\n/**\n * The Stripe Connect adapter behind the payment-provider contract\n * (`payment-provider.ts`): a tenant's merchant account is a Stripe Connect\n * account, charged and paid out through the platform's Stripe key.\n *\n * This module is the part that is Stripe's — which mode a key states, how the\n * API is asked, which webhook events describe a connected account and where\n * each one keeps the account id. What an event WRITES lives in the two modules\n * it dispatches to, loaded only when such an event arrives, so the money doors\n * that import the contract for its readiness rule load no Firebase.\n *\n * ## Whether a stored Connect linkage can actually take money HERE (AGL-2471)\n *\n * THE DEFECT. Production Firestore held three Connect linkages and all three\n * named TEST-mode accounts. One — `profiles/7AVEMtDa…`, `stripeAccountId:\n * acct_1TulDeRbL3B9Ioqz` — also carried `stripeChargesEnabled: true`, which\n * was the entire payments-readiness test every money door made:\n *\n * if (!accountId || !ownerProfile.get('stripeChargesEnabled')) …\n *\n * So three storefronts presented as payments-ready, minted a LIVE Checkout\n * session with a TEST-mode `payment_intent_data[transfer_data][destination]`,\n * and were refused by Stripe as a generic 502 at the shopper's checkout. A\n * merchant told they are ready to take money, who silently cannot.\n *\n * WHY THE ACCOUNT ID IS NOT THE EVIDENCE. `acct_1TulDeRbL3B9Ioqz` is a real\n * production value naming a TEST account. Stripe's account ids carry no mode\n * marker — live and test ids are the same shape — so no amount of reading the\n * string can tell them apart. What DOES tell them apart is Stripe itself:\n * retrieving that id with the live key answers\n *\n * 400 The account acct_1TulDeRbL3B9Ioqz was a test account created with a\n * testmode key, and therefore can only be used with testmode keys.\n *\n * The Account object, notably, has NO `livemode` field of its own (verified\n * against the live API: the payload carries `charges_enabled`,\n * `payouts_enabled`, `capabilities` and no `livemode`). So the mode is\n * recorded at the two moments Stripe does state it:\n *\n * 1. `account.updated` — the EVENT carries `livemode`, and it is Stripe's\n * own statement about the account the event is describing;\n * 2. onboarding — the account was just created or retrieved successfully\n * with the platform key, and Stripe hard-refuses cross-mode retrieval\n * (above), so the account's mode IS the key's mode; the key's mode is\n * then confirmed against the API via `resolvePlatformStripeMode`.\n *\n * The profile field is `stripeAccountLivemode`, and the rule that reads it —\n * refused on a live deployment when absent, refused in both directions when\n * it disagrees — is the contract's `merchantAccountReadiness`, which says why\n * it is asymmetric.\n *\n * WHAT IS SNIFFED, AND WHY THAT ONE IS FAIR. The SECRET KEY states its own\n * mode — `sk_live_`, `sk_test_`, `rk_live_`, `rk_test_` — and that is a\n * documented, stable Stripe invariant, unlike the account id. It is used only\n * to answer \"which mode is this deployment\", never \"which mode is this\n * account\", and even there `resolvePlatformStripeMode` prefers the API.\n *\n * HOW IT GOT THERE. A developer machine runs against PRODUCTION Firestore\n * (`FIREBASE_PROJECT_ID=aglyn-main` in every dev env file) while\n * `apps/console/.env.development.local` sets `STRIPE_SECRET_KEY` to the\n * `sk_test_` key by deliberate policy (AGL-1137: localhost must never touch\n * live Stripe). The connect route then creates a test-mode Express account\n * and writes it into the production database. Nothing about that is going to\n * change — the split key is the right call — so the gate has to be the thing\n * that notices.\n */\n\n/**\n * The mode a Stripe secret key states about itself, or `undefined` when the\n * string is not a Stripe secret key.\n *\n * Deliberately narrow: it matches `sk_`/`rk_` followed by `live`/`test`, and\n * refuses everything else rather than guessing. Handing it an `acct_…` id\n * returns `undefined` — the whole point is that account ids say nothing.\n */\nexport function platformStripeMode(\n key: string | undefined = process.env.STRIPE_SECRET_KEY,\n): PaymentMode | undefined {\n const match = /^[sr]k_(live|test)_/.exec(String(key ?? '').trim())\n return match ? (match[1] as PaymentMode) : undefined\n}\n\n/**\n * The platform's mode, asked of Stripe and only then of the key.\n *\n * `GET /v1/balance` is a singleton that carries `livemode`, so it states the\n * mode of whatever key made the call — no object has to be created to find\n * out. The key prefix is the fallback for a restricted key that cannot read\n * balance; without it, a self-hosted install with a scoped key could not\n * finish onboarding at all.\n */\nexport async function resolvePlatformStripeMode(\n key: string | undefined = process.env.STRIPE_SECRET_KEY,\n fetchImpl: typeof fetch = fetch,\n): Promise<PaymentMode | undefined> {\n const fromKey = platformStripeMode(key)\n if (!key) return fromKey\n try {\n const response = await fetchImpl('https://api.stripe.com/v1/balance', {\n method: 'GET',\n headers: { Authorization: `Bearer ${key}` },\n })\n if (response.ok) {\n const payload = await response.json()\n if (typeof payload?.livemode === 'boolean') {\n return payload.livemode ? 'live' : 'test'\n }\n }\n } catch {\n // Network or transport failure — fall through to the key, which is the\n // same answer we would have recorded before this existed.\n }\n return fromKey\n}\n\n/**\n * A Stripe webhook event about a connected account, applied to the profiles in\n * `collection` that store it — the contract's `applyAccountEvent`.\n *\n * Three events describe a connected account, and each keeps the account id\n * somewhere different:\n *\n * - `account.updated` — its readiness changed (AGL-1997). The object IS the\n * Account, and the EVENT carries `livemode` (AGL-2471): the Account object\n * has no such field, and the event's is what lets a linkage whose mode was\n * never recorded heal itself instead of staying refused forever.\n * - `payout.failed` / `transfer.failed` — money headed for the account never\n * landed. A payout is the connected account's balance failing to reach its\n * bank, so its account id is `event.account`: the Payout's own\n * `destination` names the BANK. A transfer is the platform's balance\n * failing to reach the connected account, a platform event whose\n * `destination` IS the account. Recorded and surfaced, never retried:\n * Stripe runs its own retry schedule, and a second transfer against an\n * account that has just refused one is how a duplicate lands.\n * - `payout.paid` — a later payout landed, which retires the warning the\n * failure left on the profile. The history is kept.\n *\n * Every other event answers `false` without loading anything. A write that\n * fails throws, and the webhook's 500 earns the redelivery; every write\n * mirrors current state or is keyed by Stripe's id, so a redelivery converges.\n */\nexport async function applyStripeConnectAccountEvent(\n collection: string,\n delivered: PaymentProviderEvent,\n): Promise<boolean> {\n const type = delivered?.type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const object = delivered?.object as any\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const event = delivered?.event as any\n if (type === 'account.updated') {\n const { syncConnectAccountStatus } = await import(\n './payment-provider-stripe-connect-status'\n )\n await syncConnectAccountStatus(collection, object, event?.livemode)\n return true\n }\n if (type === 'payout.failed' || type === 'transfer.failed') {\n const failedAccountId =\n type === 'payout.failed'\n ? String(event?.account ?? '')\n : String(object?.destination?.id ?? object?.destination ?? '')\n const { recordConnectPayoutFailure } = await import(\n './payment-provider-stripe-connect-payouts'\n )\n await recordConnectPayoutFailure(collection, {\n kind: type === 'payout.failed' ? 'payout' : 'transfer',\n object,\n accountId: failedAccountId,\n livemode: event?.livemode,\n })\n return true\n }\n if (type === 'payout.paid') {\n const { clearConnectPayoutFailure } = await import(\n './payment-provider-stripe-connect-payouts'\n )\n await clearConnectPayoutFailure(collection, String(event?.account ?? ''))\n return true\n }\n return false\n}\n\n/** The adapter the contract returns. */\nexport const STRIPE_CONNECT_PAYMENT_PROVIDER: PaymentProvider = {\n id: 'stripe-connect',\n // Called with no argument, so the key is read when asked — not when this\n // module was first evaluated.\n platformMode: () => platformStripeMode(),\n resolvePlatformMode: () => resolvePlatformStripeMode(),\n applyAccountEvent: applyStripeConnectAccountEvent,\n}\n"],"names":["platformStripeMode","key","process","env","STRIPE_SECRET_KEY","match","exec","String","trim","undefined","resolvePlatformStripeMode","fetchImpl","fetch","fromKey","response","method","headers","Authorization","ok","payload","json","livemode","applyStripeConnectAccountEvent","collection","delivered","type","object","event","syncConnectAccountStatus","failedAccountId","account","destination","id","recordConnectPayoutFailure","kind","accountId","clearConnectPayoutFailure","STRIPE_CONNECT_PAYMENT_PROVIDER","platformMode","resolvePlatformMode","applyAccountEvent"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAID;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiEC,GAED;;;;;;;CAOC,GACD,OAAO,SAASA,mBACdC,MAA0BC,QAAQC,GAAG,CAACC,iBAAiB;IAEvD,MAAMC,QAAQ,sBAAsBC,IAAI,CAACC,OAAON,cAAAA,MAAO,IAAIO,IAAI;IAC/D,OAAOH,QAASA,KAAK,CAAC,EAAE,GAAmBI;AAC7C;AAEA;;;;;;;;CAQC,GACD,OAAO,eAAeC,0BACpBT,MAA0BC,QAAQC,GAAG,CAACC,iBAAiB,EACvDO,YAA0BC,KAAK;IAE/B,MAAMC,UAAUb,mBAAmBC;IACnC,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EM,yBAAAA,MAAON,QAAQ;QAC3B;QACA,OAAO;IACT;IACA,IAAII,SAAS,eAAe;;QAC1B,MAAM,EAAEW,yBAAyB,EAAE,GAAG,MAAM,MAAM,CAChD;QAEF,MAAMA,0BAA0Bb,YAAYhB,gBAAOoB,yBAAAA,MAAOG,OAAO,oBAAI;QACrE,OAAO;IACT;IACA,OAAO;AACT;AAEA,sCAAsC,GACtC,OAAO,MAAMO,kCAAmD;IAC9DL,IAAI;IACJ,yEAAyE;IACzE,8BAA8B;IAC9BM,cAAc,IAAMtC;IACpBuC,qBAAqB,IAAM7B;IAC3B8B,mBAAmBlB;AACrB,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/payment-provider-stripe-connect.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 { PaymentMode, PaymentProvider, PaymentProviderEvent } from './payment-provider'\n\n/**\n * The Stripe Connect adapter behind the payment-provider contract\n * (`payment-provider.ts`): a tenant's merchant account is a Stripe Connect\n * account, charged and paid out through the platform's Stripe key.\n *\n * This module is the part that is Stripe's — which mode a key states, how the\n * API is asked, which webhook events describe a connected account and where\n * each one keeps the account id. What an event WRITES lives in the two modules\n * it dispatches to, loaded only when such an event arrives, so the money doors\n * that import the contract for its readiness rule load no Firebase.\n *\n * ## Whether a stored Connect linkage can actually take money HERE (AGL-2471)\n *\n * THE DEFECT. Production Firestore held three Connect linkages and all three\n * named TEST-mode accounts. One — `profiles/7AVEMtDa…`, `stripeAccountId:\n * acct_1TulDeRbL3B9Ioqz` — also carried `stripeChargesEnabled: true`, which\n * was the entire payments-readiness test every money door made:\n *\n * if (!accountId || !ownerProfile.get('stripeChargesEnabled')) …\n *\n * So three storefronts presented as payments-ready, minted a LIVE Checkout\n * session with a TEST-mode `payment_intent_data[transfer_data][destination]`,\n * and were refused by Stripe as a generic 502 at the shopper's checkout. A\n * merchant told they are ready to take money, who silently cannot.\n *\n * WHY THE ACCOUNT ID IS NOT THE EVIDENCE. `acct_1TulDeRbL3B9Ioqz` is a real\n * production value naming a TEST account. Stripe's account ids carry no mode\n * marker — live and test ids are the same shape — so no amount of reading the\n * string can tell them apart. What DOES tell them apart is Stripe itself:\n * retrieving that id with the live key answers\n *\n * 400 The account acct_1TulDeRbL3B9Ioqz was a test account created with a\n * testmode key, and therefore can only be used with testmode keys.\n *\n * The Account object, notably, has NO `livemode` field of its own (verified\n * against the live API: the payload carries `charges_enabled`,\n * `payouts_enabled`, `capabilities` and no `livemode`). So the mode is\n * recorded at the two moments Stripe does state it:\n *\n * 1. `account.updated` — the EVENT carries `livemode`, and it is Stripe's\n * own statement about the account the event is describing;\n * 2. onboarding — the account was just created or retrieved successfully\n * with the platform key, and Stripe hard-refuses cross-mode retrieval\n * (above), so the account's mode IS the key's mode; the key's mode is\n * then confirmed against the API via `resolvePlatformStripeMode`.\n *\n * The profile field is `stripeAccountLivemode`, and the rule that reads it —\n * refused on a live deployment when absent, refused in both directions when\n * it disagrees — is the contract's `merchantAccountReadiness`, which says why\n * it is asymmetric.\n *\n * WHAT IS SNIFFED, AND WHY THAT ONE IS FAIR. The SECRET KEY states its own\n * mode — `sk_live_`, `sk_test_`, `rk_live_`, `rk_test_` — and that is a\n * documented, stable Stripe invariant, unlike the account id. It is used only\n * to answer \"which mode is this deployment\", never \"which mode is this\n * account\", and even there `resolvePlatformStripeMode` prefers the API.\n *\n * HOW IT GOT THERE. A developer machine runs against PRODUCTION Firestore\n * (`FIREBASE_PROJECT_ID=aglyn-main` in every dev env file) while\n * `apps/console/.env.development.local` sets `STRIPE_SECRET_KEY` to the\n * `sk_test_` key by deliberate policy (AGL-1137: localhost must never touch\n * live Stripe). The connect route then creates a test-mode Express account\n * and writes it into the production database. Nothing about that is going to\n * change — the split key is the right call — so the gate has to be the thing\n * that notices.\n */\n\n/**\n * The mode a Stripe secret key states about itself, or `undefined` when the\n * string is not a Stripe secret key.\n *\n * Deliberately narrow: it matches `sk_`/`rk_` followed by `live`/`test`, and\n * refuses everything else rather than guessing. Handing it an `acct_…` id\n * returns `undefined` — the whole point is that account ids say nothing.\n */\nexport function platformStripeMode(\n key: string | undefined = process.env.STRIPE_SECRET_KEY,\n): PaymentMode | undefined {\n const match = /^[sr]k_(live|test)_/.exec(String(key ?? '').trim())\n return match ? (match[1] as PaymentMode) : undefined\n}\n\n/**\n * The platform's mode, asked of Stripe and only then of the key.\n *\n * `GET /v1/balance` is a singleton that carries `livemode`, so it states the\n * mode of whatever key made the call — no object has to be created to find\n * out. The key prefix is the fallback for a restricted key that cannot read\n * balance; without it, a self-hosted install with a scoped key could not\n * finish onboarding at all.\n */\nexport async function resolvePlatformStripeMode(\n key: string | undefined = process.env.STRIPE_SECRET_KEY,\n fetchImpl: typeof fetch = fetch,\n): Promise<PaymentMode | undefined> {\n const fromKey = platformStripeMode(key)\n if (!key) return fromKey\n try {\n const response = await fetchImpl('https://api.stripe.com/v1/balance', {\n method: 'GET',\n headers: { Authorization: `Bearer ${key}` },\n })\n if (response.ok) {\n const payload = await response.json()\n if (typeof payload?.livemode === 'boolean') {\n return payload.livemode ? 'live' : 'test'\n }\n }\n } catch {\n // Network or transport failure — fall through to the key, which is the\n // same answer we would have recorded before this existed.\n }\n return fromKey\n}\n\n/**\n * Whether Stripe's refusal to read an account says it lives in the other\n * mode — the contract's `refusedAsOtherMode`.\n *\n * Retrieving a test account with a live key answers 400 \"The account acct_…\n * was a test account created with a testmode key, and therefore can only be\n * used with testmode keys\" (measured, see the note above), and the live twin\n * names a \"livemode key\". Matched on that wording and nothing wider: a\n * refusal for any other reason (a network fault, an outage, a revoked\n * platform) must never retire an account that may be working.\n */\nexport function stripeRefusedAsOtherMode(message: unknown): boolean {\n return /\\b(test|live)\\s?mode keys?\\b/i.test(String(message ?? ''))\n}\n\n/**\n * A Stripe webhook event about a connected account, applied to the profiles in\n * `collection` that store it — the contract's `applyAccountEvent`.\n *\n * Three events describe a connected account, and each keeps the account id\n * somewhere different:\n *\n * - `account.updated` — its readiness changed (AGL-1997). The object IS the\n * Account, and the EVENT carries `livemode` (AGL-2471): the Account object\n * has no such field, and the event's is what lets a linkage whose mode was\n * never recorded heal itself instead of staying refused forever.\n * - `payout.failed` / `transfer.failed` — money headed for the account never\n * landed. A payout is the connected account's balance failing to reach its\n * bank, so its account id is `event.account`: the Payout's own\n * `destination` names the BANK. A transfer is the platform's balance\n * failing to reach the connected account, a platform event whose\n * `destination` IS the account. Recorded and surfaced, never retried:\n * Stripe runs its own retry schedule, and a second transfer against an\n * account that has just refused one is how a duplicate lands.\n * - `payout.paid` — a later payout landed, which retires the warning the\n * failure left on the profile. The history is kept.\n *\n * Every other event answers `false` without loading anything. A write that\n * fails throws, and the webhook's 500 earns the redelivery; every write\n * mirrors current state or is keyed by Stripe's id, so a redelivery converges.\n */\nexport async function applyStripeConnectAccountEvent(\n collection: string,\n delivered: PaymentProviderEvent,\n): Promise<boolean> {\n const type = delivered?.type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const object = delivered?.object as any\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const event = delivered?.event as any\n if (type === 'account.updated') {\n const { syncConnectAccountStatus } = await import(\n './payment-provider-stripe-connect-status'\n )\n await syncConnectAccountStatus(collection, object, event?.livemode)\n return true\n }\n if (type === 'payout.failed' || type === 'transfer.failed') {\n const failedAccountId =\n type === 'payout.failed'\n ? String(event?.account ?? '')\n : String(object?.destination?.id ?? object?.destination ?? '')\n const { recordConnectPayoutFailure } = await import(\n './payment-provider-stripe-connect-payouts'\n )\n await recordConnectPayoutFailure(collection, {\n kind: type === 'payout.failed' ? 'payout' : 'transfer',\n object,\n accountId: failedAccountId,\n livemode: event?.livemode,\n })\n return true\n }\n if (type === 'payout.paid') {\n const { clearConnectPayoutFailure } = await import(\n './payment-provider-stripe-connect-payouts'\n )\n await clearConnectPayoutFailure(collection, String(event?.account ?? ''))\n return true\n }\n return false\n}\n\n/** The adapter the contract returns. */\nexport const STRIPE_CONNECT_PAYMENT_PROVIDER: PaymentProvider = {\n id: 'stripe-connect',\n // Called with no argument, so the key is read when asked — not when this\n // module was first evaluated.\n platformMode: () => platformStripeMode(),\n resolvePlatformMode: () => resolvePlatformStripeMode(),\n refusedAsOtherMode: stripeRefusedAsOtherMode,\n applyAccountEvent: applyStripeConnectAccountEvent,\n}\n"],"names":["platformStripeMode","key","process","env","STRIPE_SECRET_KEY","match","exec","String","trim","undefined","resolvePlatformStripeMode","fetchImpl","fetch","fromKey","response","method","headers","Authorization","ok","payload","json","livemode","stripeRefusedAsOtherMode","message","test","applyStripeConnectAccountEvent","collection","delivered","type","object","event","syncConnectAccountStatus","failedAccountId","account","destination","id","recordConnectPayoutFailure","kind","accountId","clearConnectPayoutFailure","STRIPE_CONNECT_PAYMENT_PROVIDER","platformMode","resolvePlatformMode","refusedAsOtherMode","applyAccountEvent"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAID;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiEC,GAED;;;;;;;CAOC,GACD,OAAO,SAASA,mBACdC,MAA0BC,QAAQC,GAAG,CAACC,iBAAiB;IAEvD,MAAMC,QAAQ,sBAAsBC,IAAI,CAACC,OAAON,cAAAA,MAAO,IAAIO,IAAI;IAC/D,OAAOH,QAASA,KAAK,CAAC,EAAE,GAAmBI;AAC7C;AAEA;;;;;;;;CAQC,GACD,OAAO,eAAeC,0BACpBT,MAA0BC,QAAQC,GAAG,CAACC,iBAAiB,EACvDO,YAA0BC,KAAK;IAE/B,MA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,EAAEO,0BAA0B,EAAE,GAAG,MAAM,MAAM,CACjD;QAEF,MAAMA,2BAA2BV,YAAY;YAC3CW,MAAMT,SAAS,kBAAkB,WAAW;YAC5CC;YACAS,WAAWN;YACXX,QAAQ,EAAES,yBAAAA,MAAOT,QAAQ;QAC3B;QACA,OAAO;IACT;IACA,IAAIO,SAAS,eAAe;;QAC1B,MAAM,EAAEW,yBAAyB,EAAE,GAAG,MAAM,MAAM,CAChD;QAEF,MAAMA,0BAA0Bb,YAAYnB,gBAAOuB,yBAAAA,MAAOG,OAAO,oBAAI;QACrE,OAAO;IACT;IACA,OAAO;AACT;AAEA,sCAAsC,GACtC,OAAO,MAAMO,kCAAmD;IAC9DL,IAAI;IACJ,yEAAyE;IACzE,8BAA8B;IAC9BM,cAAc,IAAMzC;IACpB0C,qBAAqB,IAAMhC;IAC3BiC,oBAAoBrB;IACpBsB,mBAAmBnB;AACrB,EAAC"}
|
|
@@ -126,6 +126,13 @@ export interface PaymentProvider {
|
|
|
126
126
|
* has just retrieved.
|
|
127
127
|
*/
|
|
128
128
|
resolvePlatformMode(): Promise<PaymentMode | undefined>;
|
|
129
|
+
/**
|
|
130
|
+
* Whether the provider's refusal to read a stored merchant account says
|
|
131
|
+
* the account belongs to the OTHER mode: a test account read with a live
|
|
132
|
+
* credential, or the reverse. Such an account can never be used on this
|
|
133
|
+
* deployment, so onboarding replaces it instead of failing on it.
|
|
134
|
+
*/
|
|
135
|
+
refusedAsOtherMode(message: unknown): boolean;
|
|
129
136
|
/**
|
|
130
137
|
* Applies an event about a connected merchant account — its readiness
|
|
131
138
|
* changed, a payout to it failed, a later payout landed — to the documents
|
|
@@ -159,6 +166,35 @@ export declare function paymentProvider(): PaymentProvider;
|
|
|
159
166
|
* both directions, because it costs nothing to detect and is never right.
|
|
160
167
|
*/
|
|
161
168
|
export declare function merchantAccountReadiness(input: MerchantAccountReadinessInput): MerchantAccountReadiness;
|
|
169
|
+
/**
|
|
170
|
+
* Whether a stored merchant account is RECORDED as belonging to the other
|
|
171
|
+
* mode from this deployment: the `mode-mismatch` refusal, asked before the
|
|
172
|
+
* account is read, because a live credential cannot even read a test
|
|
173
|
+
* account. Only a literal boolean is a recorded mode, as in
|
|
174
|
+
* {@link merchantAccountReadiness}; an unrecorded one is settled by reading
|
|
175
|
+
* the account (see {@link PaymentProvider.refusedAsOtherMode}).
|
|
176
|
+
*/
|
|
177
|
+
export declare function merchantAccountInOtherMode(accountLivemode: unknown, platformMode: PaymentMode | undefined): boolean;
|
|
178
|
+
/** Where an onboarding route keeps the accounts it has replaced. */
|
|
179
|
+
export declare const PREVIOUS_MERCHANT_ACCOUNTS_FIELD = "previousStripeAccountIds";
|
|
180
|
+
/**
|
|
181
|
+
* The profile fields that replace a stored merchant account with a new one
|
|
182
|
+
* created in this deployment's mode.
|
|
183
|
+
*
|
|
184
|
+
* The replaced id is KEPT, appended to {@link PREVIOUS_MERCHANT_ACCOUNTS_FIELD}
|
|
185
|
+
* (once), so nothing that names it is orphaned: every order and payment
|
|
186
|
+
* records the account it was paid into on itself, and this list is the
|
|
187
|
+
* profile's own record that the account was once its. Everything the profile
|
|
188
|
+
* says about the old account is reset, so the new one cannot inherit it: its
|
|
189
|
+
* charges and payout readiness, its recorded mode and charge shape (written
|
|
190
|
+
* again from the new account by the same request), and a payout failure the
|
|
191
|
+
* old account reported.
|
|
192
|
+
*/
|
|
193
|
+
export declare function merchantAccountReplacement(input: {
|
|
194
|
+
previousAccountIds: unknown;
|
|
195
|
+
replacedAccountId: string;
|
|
196
|
+
newAccountId: string;
|
|
197
|
+
}): Record<string, unknown>;
|
|
162
198
|
/**
|
|
163
199
|
* The form every money door calls: `true` only when the account may be
|
|
164
200
|
* charged, with the two mode refusals reported to the server log.
|
|
@@ -51,6 +51,50 @@
|
|
|
51
51
|
}
|
|
52
52
|
return platformMode === 'live' ? 'mode-unverified' : 'ready';
|
|
53
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* Whether a stored merchant account is RECORDED as belonging to the other
|
|
56
|
+
* mode from this deployment: the `mode-mismatch` refusal, asked before the
|
|
57
|
+
* account is read, because a live credential cannot even read a test
|
|
58
|
+
* account. Only a literal boolean is a recorded mode, as in
|
|
59
|
+
* {@link merchantAccountReadiness}; an unrecorded one is settled by reading
|
|
60
|
+
* the account (see {@link PaymentProvider.refusedAsOtherMode}).
|
|
61
|
+
*/ export function merchantAccountInOtherMode(accountLivemode, platformMode) {
|
|
62
|
+
if (typeof accountLivemode !== 'boolean' || !platformMode) return false;
|
|
63
|
+
return accountLivemode !== (platformMode === 'live');
|
|
64
|
+
}
|
|
65
|
+
/** Where an onboarding route keeps the accounts it has replaced. */ export const PREVIOUS_MERCHANT_ACCOUNTS_FIELD = 'previousStripeAccountIds';
|
|
66
|
+
/**
|
|
67
|
+
* The profile fields that replace a stored merchant account with a new one
|
|
68
|
+
* created in this deployment's mode.
|
|
69
|
+
*
|
|
70
|
+
* The replaced id is KEPT, appended to {@link PREVIOUS_MERCHANT_ACCOUNTS_FIELD}
|
|
71
|
+
* (once), so nothing that names it is orphaned: every order and payment
|
|
72
|
+
* records the account it was paid into on itself, and this list is the
|
|
73
|
+
* profile's own record that the account was once its. Everything the profile
|
|
74
|
+
* says about the old account is reset, so the new one cannot inherit it: its
|
|
75
|
+
* charges and payout readiness, its recorded mode and charge shape (written
|
|
76
|
+
* again from the new account by the same request), and a payout failure the
|
|
77
|
+
* old account reported.
|
|
78
|
+
*/ export function merchantAccountReplacement(input) {
|
|
79
|
+
const kept = Array.isArray(input.previousAccountIds) ? input.previousAccountIds.filter((id)=>typeof id === 'string' && Boolean(id.trim())) : [];
|
|
80
|
+
const replaced = input.replacedAccountId.trim();
|
|
81
|
+
return {
|
|
82
|
+
stripeAccountId: input.newAccountId,
|
|
83
|
+
[PREVIOUS_MERCHANT_ACCOUNTS_FIELD]: replaced && !kept.includes(replaced) ? [
|
|
84
|
+
...kept,
|
|
85
|
+
replaced
|
|
86
|
+
] : kept,
|
|
87
|
+
stripeChargesEnabled: false,
|
|
88
|
+
stripePayoutsEnabled: null,
|
|
89
|
+
stripeAccountLivemode: null,
|
|
90
|
+
stripeChargeModel: null,
|
|
91
|
+
lastPayoutFailureId: null,
|
|
92
|
+
lastPayoutFailureKind: null,
|
|
93
|
+
lastPayoutFailureAtMs: null,
|
|
94
|
+
lastPayoutFailureCents: null,
|
|
95
|
+
lastPayoutFailureReason: null
|
|
96
|
+
};
|
|
97
|
+
}
|
|
54
98
|
/**
|
|
55
99
|
* The form every money door calls: `true` only when the account may be
|
|
56
100
|
* charged, with the two mode refusals reported to the server log.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/payment-provider.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 { STRIPE_CONNECT_PAYMENT_PROVIDER } from './payment-provider-stripe-connect'\n\n/**\n * The merchant's payment account — the one seam the payment vendor lives\n * behind when a TENANT takes money.\n *\n * ## Which money this is, and which it is not\n *\n * Two different accounts move money on this platform and only one of them is\n * here. The platform BILLS its customers — plans, add-ons, metered usage — on\n * its own account; that rail is infrastructure (`org-billing.ts`, the billing\n * webhook route, `api-idempotency.ts`, `stripe-deployment-mode.ts`) and names\n * its vendor where it runs. A tenant SELLS — a storefront order, a booked\n * appointment, a marketplace listing — into a connected merchant account of\n * its own, and every plugin that takes money reaches that account through\n * this contract: whether the account may be charged, which world (live or\n * test) the platform charges in, and what the provider says when the account\n * changes or a payout fails.\n *\n * Commerce's `PaymentProviderId` names the provider a CHECKOUT is created\n * with. This is the other half: the account the checkout pays into.\n *\n * ## One adapter, compiled in, and no registry — by failure direction\n *\n * Stripe Connect is the only adapter\n * (`payment-provider-stripe-connect.ts`), and {@link paymentProvider} returns\n * it without consulting any registry, the way the domain driver's built-ins\n * and the mail rail's are compiled into their libraries. A provider a plugin\n * registered could be ABSENT where a door reads it — a declaration that threw\n * part-way, a route bundle that evaluated the registry apart from boot's —\n * and every answer an absent provider could give at a money door is wrong: a\n * refusal takes every sale on every site down, and a default lets a checkout\n * proceed against an account nobody checked. Compiled in, it cannot be\n * absent, so neither can happen.\n *\n * It lives in this library rather than in a plugin because three plugins take\n * money into the same account — a storefront, a calendar and the marketplace\n * — and one plugin may not import another. A plugin that owned the adapter\n * would make the other two's sales depend on its install and on its\n * registration having run; the adapter itself sells nothing and holds no\n * product, only the platform's own connected-account integration.\n *\n * A second adapter is one module beside the first and a selector here. There\n * is no selector today because there is nothing to select: every plugin's\n * checkout is created against the same vendor.\n *\n * ## The contract every adapter owes\n *\n * 1. **An account the provider did not describe is never ready.** Every\n * {@link MerchantAccountReadiness} other than `'ready'` refuses the charge,\n * and only a literal boolean is a recorded answer.\n * 2. **Only what the provider stated is written.** An account event that\n * states nothing writes nothing, and a written record never invents a\n * `false` or a `true` from an absent field.\n * 3. **Failures propagate.** {@link PaymentProvider.applyAccountEvent} runs\n * inside the platform's billing webhook, and a throw is what earns the\n * redelivery; every write it makes is idempotent so that redelivery\n * converges.\n */\n\n/** Which world a platform credential or a merchant account charges in. */\nexport type PaymentMode = 'live' | 'test'\n\n/**\n * Why a stored merchant account may not be charged against. Every value\n * other than `'ready'` is a refusal.\n */\nexport type MerchantAccountReadiness =\n /** Charge away. */\n | 'ready'\n /** No merchant account is stored at all — the onboarding call to action. */\n | 'not-connected'\n /** The provider will not let this account take charges. */\n | 'charges-disabled'\n /**\n * The account's mode was never recorded (AGL-2471) AND this deployment is\n * LIVE. The onboarding route and the provider's account event both record\n * it, so a genuine merchant self-heals on the next of either.\n */\n | 'mode-unverified'\n /** The account belongs to the OTHER world. The AGL-2471 defect. */\n | 'mode-mismatch'\n\nexport interface MerchantAccountReadinessInput {\n /** The stored account id, whatever shape the document has. */\n accountId?: unknown\n /** Whether the provider said the account may take charges. */\n chargesEnabled?: unknown\n /** Whether the provider said the account is live — absent before AGL-2471. */\n accountLivemode?: unknown\n /** Defaults to {@link PaymentProvider.platformMode}. */\n platformMode?: PaymentMode | undefined\n}\n\n/** One event the platform's billing webhook received, as the provider sent it. */\nexport interface PaymentProviderEvent {\n /** The provider's own name for the event. */\n type: string\n /** The object the event describes. */\n object: unknown\n /** The whole event as delivered. */\n event: unknown\n}\n\nexport interface PaymentProvider {\n /** Stable id, for log lines. Never a display name. */\n readonly id: string\n /**\n * The mode this deployment's platform credential states about itself, read\n * without a network call; `undefined` when there is no credential or it\n * states nothing.\n */\n platformMode(): PaymentMode | undefined\n /**\n * The platform's mode, asked of the provider first and the credential\n * second — what an onboarding route records against a merchant account it\n * has just retrieved.\n */\n resolvePlatformMode(): Promise<PaymentMode | undefined>\n /**\n * Applies an event about a connected merchant account — its readiness\n * changed, a payout to it failed, a later payout landed — to the documents\n * in `collection` that store it. A plugin passes the collection holding ITS\n * merchant profiles; a non-matching account updates nothing.\n *\n * @returns `true` when the event was about a merchant account and has been\n * applied, so the caller's own sections have nothing to do with it;\n * `false` for every other event.\n */\n applyAccountEvent(\n collection: string,\n delivered: PaymentProviderEvent,\n ): Promise<boolean>\n}\n\n/** The provider every merchant account on this deployment is held at. */\nexport function paymentProvider(): PaymentProvider {\n return STRIPE_CONNECT_PAYMENT_PROVIDER\n}\n\n/**\n * Decides whether a stored merchant account may be charged against.\n *\n * Order matters: the two refusals that existed before AGL-2471 are asked\n * first, so an unconnected or restricted merchant still gets the answer they\n * always got, and only an account that WOULD have passed reaches the mode\n * question.\n *\n * WHY THE MODE RULE IS ASYMMETRIC, AND NOT \"REFUSE ANYTHING UNPROVEN\". An\n * unrecorded mode refuses only on a LIVE deployment. That is where real money\n * moves, and a live deployment can always re-establish the field: the\n * merchant reconnects, or the provider sends one account event. Everywhere\n * else — a test deployment, a developer machine, a self-hosted install still\n * in sandbox, the whole test suite — an unverified account keeps the\n * behavior it had before, because no real money can move there and the\n * provider enforces the mode boundary itself. A PROVEN mismatch is refused in\n * both directions, because it costs nothing to detect and is never right.\n */\nexport function merchantAccountReadiness(\n input: MerchantAccountReadinessInput,\n): MerchantAccountReadiness {\n const accountId =\n typeof input.accountId === 'string' ? input.accountId.trim() : ''\n if (!accountId) return 'not-connected'\n if (input.chargesEnabled !== true) return 'charges-disabled'\n const platformMode =\n 'platformMode' in input\n ? input.platformMode\n : paymentProvider().platformMode()\n // Three-valued on purpose, exactly as AGL-1997 reads `payoutsEnabled`: only\n // a literal boolean is a recorded answer. A string `'true'` or a `1` is a\n // field somebody else wrote, and inventing `true` from it would re-open the\n // hole this closes.\n if (typeof input.accountLivemode === 'boolean') {\n // A PROVEN mismatch is refused in either direction. It costs nothing to\n // detect and it is always wrong.\n if (!platformMode) return 'ready'\n return input.accountLivemode === (platformMode === 'live')\n ? 'ready'\n : 'mode-mismatch'\n }\n return platformMode === 'live' ? 'mode-unverified' : 'ready'\n}\n\n/**\n * The form every money door calls: `true` only when the account may be\n * charged, with the two mode refusals reported to the server log.\n *\n * The log line is the part the shopper's generic 409 cannot carry. Before\n * this, a mode mismatch surfaced as a 502 from the provider with nothing\n * anywhere naming the cause; the sale is still refused the same way, but now\n * somebody can find out why.\n */\nexport function merchantAccountIsReady(\n input: MerchantAccountReadinessInput,\n context?: { subject?: string },\n): boolean {\n const readiness = merchantAccountReadiness(input)\n if (readiness === 'mode-mismatch' || readiness === 'mode-unverified') {\n console.error(\n `[AGL-2471] Refusing a charge against ${paymentProvider().id} account ` +\n `${String(input.accountId)}${\n context?.subject ? ` (${context.subject})` : ''\n }: ${readiness}. The stored account is not verified for this ` +\n `deployment's payment mode; the merchant must re-onboard.`,\n )\n }\n return readiness === 'ready'\n}\n\n/*==========================================\n * WHO IS THE SELLER OF RECORD ON A SITE SALE\n *\n * Two shapes, decided by the seller's connected account, never by a flag the\n * request carries:\n *\n * - `direct`: the sale is created ON the seller's own Stripe account\n * (`Stripe-Account` header). The seller is the merchant of record: the\n * money lands in their balance, Stripe bills them its card fee, refunds\n * and chargebacks debit their balance, and Stripe Tax computes against\n * THEIR registrations. Aglyn takes its plan take as an\n * `application_fee_amount` and is charged nothing by Stripe for the sale.\n * Every account created from now on has this shape\n * (`DIRECT_CHARGE_ACCOUNT_PARAMS`).\n * - `destination`: the sale is created on AGLYN's account and transferred\n * on. Kept for the Express accounts created before the switch (Stripe\n * discourages direct charges on Express, whose dashboard cannot refund or\n * answer a dispute), for the register and Tap to Pay, which stay on the\n * platform account, and for plugin marketplace sales.\n *\n * The shape is recorded on the profile as `stripeChargeModel` by the connect\n * route, which reads it off the account Stripe returns. An absent value is\n * `destination`: the conservative reading, because a direct charge against an\n * Express account would put a refund and a dispute where nobody can act.\n *=========================================*/\nexport type SaleChargeModel = 'direct' | 'destination'\n\n/**\n * The `/v1/accounts` parameters for a new seller account: a full Stripe\n * account that Stripe bills and Stripe underwrites (the Standard shape, by\n * controller properties). The dashboard type cannot be changed later, which\n * is why it is set here and nowhere else.\n */\nexport const DIRECT_CHARGE_ACCOUNT_PARAMS: Readonly<Record<string, string>> = {\n 'controller[fees][payer]': 'account',\n 'controller[losses][payments]': 'stripe',\n 'controller[requirement_collection]': 'stripe',\n 'controller[stripe_dashboard][type]': 'full',\n}\n\n/** The charge shape a Stripe Account object supports. */\nexport function accountChargeModel(account: unknown): SaleChargeModel {\n const controller = (account as any)?.controller\n return controller?.fees?.payer === 'account' &&\n controller?.stripe_dashboard?.type === 'full'\n ? 'direct'\n : 'destination'\n}\n\n/** The charge shape recorded on a seller's profile (`stripeChargeModel`). */\nexport function saleChargeModel(recorded: unknown): SaleChargeModel {\n return recorded === 'direct' ? 'direct' : 'destination'\n}\n\n/**\n * The header that creates (or reads) a Stripe object ON the seller's account\n * for a direct charge, and nothing for a destination charge.\n */\nexport function connectedAccountHeader(\n model: SaleChargeModel,\n accountId: unknown,\n): Record<string, string> {\n const id = typeof accountId === 'string' ? accountId.trim() : ''\n return model === 'direct' && id ? { 'Stripe-Account': id } : {}\n}\n\n/**\n * The split for a DIRECT charge: Aglyn's take as the application fee, and no\n * `transfer_data`, because the money is already the seller's. Stripe rejects\n * a zero application fee, so a 0% plan sends no key at all.\n */\nexport function directChargeParams(\n feeCents: number,\n prefix: 'payment_intent_data' | '' = 'payment_intent_data',\n): Record<string, string> {\n const fee = Number.isFinite(feeCents) ? Math.max(0, Math.round(feeCents)) : 0\n if (fee <= 0) return {}\n const key = prefix ? `${prefix}[application_fee_amount]` : 'application_fee_amount'\n return { [key]: String(fee) }\n}\n"],"names":["STRIPE_CONNECT_PAYMENT_PROVIDER","paymentProvider","merchantAccountReadiness","input","accountId","trim","chargesEnabled","platformMode","accountLivemode","merchantAccountIsReady","context","readiness","console","error","id","String","subject","DIRECT_CHARGE_ACCOUNT_PARAMS","accountChargeModel","account","controller","fees","payer","stripe_dashboard","type","saleChargeModel","recorded","connectedAccountHeader","model","directChargeParams","feeCents","prefix","fee","Number","isFinite","Math","max","round","key"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,+BAA+B,QAAQ,uCAAmC;AAuInF,uEAAuE,GACvE,OAAO,SAASC;IACd,OAAOD;AACT;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASE,yBACdC,KAAoC;IAEpC,MAAMC,YACJ,OAAOD,MAAMC,SAAS,KAAK,WAAWD,MAAMC,SAAS,CAACC,IAAI,KAAK;IACjE,IAAI,CAACD,WAAW,OAAO;IACvB,IAAID,MAAMG,cAAc,KAAK,MAAM,OAAO;IAC1C,MAAMC,eACJ,kBAAkBJ,QACdA,MAAMI,YAAY,GAClBN,kBAAkBM,YAAY;IACpC,4EAA4E;IAC5E,0EAA0E;IAC1E,4EAA4E;IAC5E,oBAAoB;IACpB,IAAI,OAAOJ,MAAMK,eAAe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c,WAAWA,UAAUC,IAAI,KAAK;IAC9D,OAAOuB,UAAU,YAAYd,KAAK;QAAE,kBAAkBA;IAAG,IAAI,CAAC;AAChE;AAEA;;;;CAIC,GACD,OAAO,SAASe,mBACdC,QAAgB,EAChBC,SAAqC,qBAAqB;IAE1D,MAAMC,MAAMC,OAAOC,QAAQ,CAACJ,YAAYK,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACP,aAAa;IAC5E,IAAIE,OAAO,GAAG,OAAO,CAAC;IACtB,MAAMM,MAAMP,SAAS,GAAGA,OAAO,wBAAwB,CAAC,GAAG;IAC3D,OAAO;QAAE,CAACO,IAAI,EAAEvB,OAAOiB;IAAK;AAC9B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/payment-provider.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 { STRIPE_CONNECT_PAYMENT_PROVIDER } from './payment-provider-stripe-connect'\n\n/**\n * The merchant's payment account — the one seam the payment vendor lives\n * behind when a TENANT takes money.\n *\n * ## Which money this is, and which it is not\n *\n * Two different accounts move money on this platform and only one of them is\n * here. The platform BILLS its customers — plans, add-ons, metered usage — on\n * its own account; that rail is infrastructure (`org-billing.ts`, the billing\n * webhook route, `api-idempotency.ts`, `stripe-deployment-mode.ts`) and names\n * its vendor where it runs. A tenant SELLS — a storefront order, a booked\n * appointment, a marketplace listing — into a connected merchant account of\n * its own, and every plugin that takes money reaches that account through\n * this contract: whether the account may be charged, which world (live or\n * test) the platform charges in, and what the provider says when the account\n * changes or a payout fails.\n *\n * Commerce's `PaymentProviderId` names the provider a CHECKOUT is created\n * with. This is the other half: the account the checkout pays into.\n *\n * ## One adapter, compiled in, and no registry — by failure direction\n *\n * Stripe Connect is the only adapter\n * (`payment-provider-stripe-connect.ts`), and {@link paymentProvider} returns\n * it without consulting any registry, the way the domain driver's built-ins\n * and the mail rail's are compiled into their libraries. A provider a plugin\n * registered could be ABSENT where a door reads it — a declaration that threw\n * part-way, a route bundle that evaluated the registry apart from boot's —\n * and every answer an absent provider could give at a money door is wrong: a\n * refusal takes every sale on every site down, and a default lets a checkout\n * proceed against an account nobody checked. Compiled in, it cannot be\n * absent, so neither can happen.\n *\n * It lives in this library rather than in a plugin because three plugins take\n * money into the same account — a storefront, a calendar and the marketplace\n * — and one plugin may not import another. A plugin that owned the adapter\n * would make the other two's sales depend on its install and on its\n * registration having run; the adapter itself sells nothing and holds no\n * product, only the platform's own connected-account integration.\n *\n * A second adapter is one module beside the first and a selector here. There\n * is no selector today because there is nothing to select: every plugin's\n * checkout is created against the same vendor.\n *\n * ## The contract every adapter owes\n *\n * 1. **An account the provider did not describe is never ready.** Every\n * {@link MerchantAccountReadiness} other than `'ready'` refuses the charge,\n * and only a literal boolean is a recorded answer.\n * 2. **Only what the provider stated is written.** An account event that\n * states nothing writes nothing, and a written record never invents a\n * `false` or a `true` from an absent field.\n * 3. **Failures propagate.** {@link PaymentProvider.applyAccountEvent} runs\n * inside the platform's billing webhook, and a throw is what earns the\n * redelivery; every write it makes is idempotent so that redelivery\n * converges.\n */\n\n/** Which world a platform credential or a merchant account charges in. */\nexport type PaymentMode = 'live' | 'test'\n\n/**\n * Why a stored merchant account may not be charged against. Every value\n * other than `'ready'` is a refusal.\n */\nexport type MerchantAccountReadiness =\n /** Charge away. */\n | 'ready'\n /** No merchant account is stored at all — the onboarding call to action. */\n | 'not-connected'\n /** The provider will not let this account take charges. */\n | 'charges-disabled'\n /**\n * The account's mode was never recorded (AGL-2471) AND this deployment is\n * LIVE. The onboarding route and the provider's account event both record\n * it, so a genuine merchant self-heals on the next of either.\n */\n | 'mode-unverified'\n /** The account belongs to the OTHER world. The AGL-2471 defect. */\n | 'mode-mismatch'\n\nexport interface MerchantAccountReadinessInput {\n /** The stored account id, whatever shape the document has. */\n accountId?: unknown\n /** Whether the provider said the account may take charges. */\n chargesEnabled?: unknown\n /** Whether the provider said the account is live — absent before AGL-2471. */\n accountLivemode?: unknown\n /** Defaults to {@link PaymentProvider.platformMode}. */\n platformMode?: PaymentMode | undefined\n}\n\n/** One event the platform's billing webhook received, as the provider sent it. */\nexport interface PaymentProviderEvent {\n /** The provider's own name for the event. */\n type: string\n /** The object the event describes. */\n object: unknown\n /** The whole event as delivered. */\n event: unknown\n}\n\nexport interface PaymentProvider {\n /** Stable id, for log lines. Never a display name. */\n readonly id: string\n /**\n * The mode this deployment's platform credential states about itself, read\n * without a network call; `undefined` when there is no credential or it\n * states nothing.\n */\n platformMode(): PaymentMode | undefined\n /**\n * The platform's mode, asked of the provider first and the credential\n * second — what an onboarding route records against a merchant account it\n * has just retrieved.\n */\n resolvePlatformMode(): Promise<PaymentMode | undefined>\n /**\n * Whether the provider's refusal to read a stored merchant account says\n * the account belongs to the OTHER mode: a test account read with a live\n * credential, or the reverse. Such an account can never be used on this\n * deployment, so onboarding replaces it instead of failing on it.\n */\n refusedAsOtherMode(message: unknown): boolean\n /**\n * Applies an event about a connected merchant account — its readiness\n * changed, a payout to it failed, a later payout landed — to the documents\n * in `collection` that store it. A plugin passes the collection holding ITS\n * merchant profiles; a non-matching account updates nothing.\n *\n * @returns `true` when the event was about a merchant account and has been\n * applied, so the caller's own sections have nothing to do with it;\n * `false` for every other event.\n */\n applyAccountEvent(\n collection: string,\n delivered: PaymentProviderEvent,\n ): Promise<boolean>\n}\n\n/** The provider every merchant account on this deployment is held at. */\nexport function paymentProvider(): PaymentProvider {\n return STRIPE_CONNECT_PAYMENT_PROVIDER\n}\n\n/**\n * Decides whether a stored merchant account may be charged against.\n *\n * Order matters: the two refusals that existed before AGL-2471 are asked\n * first, so an unconnected or restricted merchant still gets the answer they\n * always got, and only an account that WOULD have passed reaches the mode\n * question.\n *\n * WHY THE MODE RULE IS ASYMMETRIC, AND NOT \"REFUSE ANYTHING UNPROVEN\". An\n * unrecorded mode refuses only on a LIVE deployment. That is where real money\n * moves, and a live deployment can always re-establish the field: the\n * merchant reconnects, or the provider sends one account event. Everywhere\n * else — a test deployment, a developer machine, a self-hosted install still\n * in sandbox, the whole test suite — an unverified account keeps the\n * behavior it had before, because no real money can move there and the\n * provider enforces the mode boundary itself. A PROVEN mismatch is refused in\n * both directions, because it costs nothing to detect and is never right.\n */\nexport function merchantAccountReadiness(\n input: MerchantAccountReadinessInput,\n): MerchantAccountReadiness {\n const accountId =\n typeof input.accountId === 'string' ? input.accountId.trim() : ''\n if (!accountId) return 'not-connected'\n if (input.chargesEnabled !== true) return 'charges-disabled'\n const platformMode =\n 'platformMode' in input\n ? input.platformMode\n : paymentProvider().platformMode()\n // Three-valued on purpose, exactly as AGL-1997 reads `payoutsEnabled`: only\n // a literal boolean is a recorded answer. A string `'true'` or a `1` is a\n // field somebody else wrote, and inventing `true` from it would re-open the\n // hole this closes.\n if (typeof input.accountLivemode === 'boolean') {\n // A PROVEN mismatch is refused in either direction. It costs nothing to\n // detect and it is always wrong.\n if (!platformMode) return 'ready'\n return input.accountLivemode === (platformMode === 'live')\n ? 'ready'\n : 'mode-mismatch'\n }\n return platformMode === 'live' ? 'mode-unverified' : 'ready'\n}\n\n/**\n * Whether a stored merchant account is RECORDED as belonging to the other\n * mode from this deployment: the `mode-mismatch` refusal, asked before the\n * account is read, because a live credential cannot even read a test\n * account. Only a literal boolean is a recorded mode, as in\n * {@link merchantAccountReadiness}; an unrecorded one is settled by reading\n * the account (see {@link PaymentProvider.refusedAsOtherMode}).\n */\nexport function merchantAccountInOtherMode(\n accountLivemode: unknown,\n platformMode: PaymentMode | undefined,\n): boolean {\n if (typeof accountLivemode !== 'boolean' || !platformMode) return false\n return accountLivemode !== (platformMode === 'live')\n}\n\n/** Where an onboarding route keeps the accounts it has replaced. */\nexport const PREVIOUS_MERCHANT_ACCOUNTS_FIELD = 'previousStripeAccountIds'\n\n/**\n * The profile fields that replace a stored merchant account with a new one\n * created in this deployment's mode.\n *\n * The replaced id is KEPT, appended to {@link PREVIOUS_MERCHANT_ACCOUNTS_FIELD}\n * (once), so nothing that names it is orphaned: every order and payment\n * records the account it was paid into on itself, and this list is the\n * profile's own record that the account was once its. Everything the profile\n * says about the old account is reset, so the new one cannot inherit it: its\n * charges and payout readiness, its recorded mode and charge shape (written\n * again from the new account by the same request), and a payout failure the\n * old account reported.\n */\nexport function merchantAccountReplacement(input: {\n previousAccountIds: unknown\n replacedAccountId: string\n newAccountId: string\n}): Record<string, unknown> {\n const kept = Array.isArray(input.previousAccountIds)\n ? input.previousAccountIds.filter(\n (id): id is string => typeof id === 'string' && Boolean(id.trim()),\n )\n : []\n const replaced = input.replacedAccountId.trim()\n return {\n stripeAccountId: input.newAccountId,\n [PREVIOUS_MERCHANT_ACCOUNTS_FIELD]:\n replaced && !kept.includes(replaced) ? [...kept, replaced] : kept,\n stripeChargesEnabled: false,\n stripePayoutsEnabled: null,\n stripeAccountLivemode: null,\n stripeChargeModel: null,\n lastPayoutFailureId: null,\n lastPayoutFailureKind: null,\n lastPayoutFailureAtMs: null,\n lastPayoutFailureCents: null,\n lastPayoutFailureReason: null,\n }\n}\n\n/**\n * The form every money door calls: `true` only when the account may be\n * charged, with the two mode refusals reported to the server log.\n *\n * The log line is the part the shopper's generic 409 cannot carry. Before\n * this, a mode mismatch surfaced as a 502 from the provider with nothing\n * anywhere naming the cause; the sale is still refused the same way, but now\n * somebody can find out why.\n */\nexport function merchantAccountIsReady(\n input: MerchantAccountReadinessInput,\n context?: { subject?: string },\n): boolean {\n const readiness = merchantAccountReadiness(input)\n if (readiness === 'mode-mismatch' || readiness === 'mode-unverified') {\n console.error(\n `[AGL-2471] Refusing a charge against ${paymentProvider().id} account ` +\n `${String(input.accountId)}${\n context?.subject ? ` (${context.subject})` : ''\n }: ${readiness}. The stored account is not verified for this ` +\n `deployment's payment mode; the merchant must re-onboard.`,\n )\n }\n return readiness === 'ready'\n}\n\n/*==========================================\n * WHO IS THE SELLER OF RECORD ON A SITE SALE\n *\n * Two shapes, decided by the seller's connected account, never by a flag the\n * request carries:\n *\n * - `direct`: the sale is created ON the seller's own Stripe account\n * (`Stripe-Account` header). The seller is the merchant of record: the\n * money lands in their balance, Stripe bills them its card fee, refunds\n * and chargebacks debit their balance, and Stripe Tax computes against\n * THEIR registrations. Aglyn takes its plan take as an\n * `application_fee_amount` and is charged nothing by Stripe for the sale.\n * Every account created from now on has this shape\n * (`DIRECT_CHARGE_ACCOUNT_PARAMS`).\n * - `destination`: the sale is created on AGLYN's account and transferred\n * on. Kept for the Express accounts created before the switch (Stripe\n * discourages direct charges on Express, whose dashboard cannot refund or\n * answer a dispute), for the register and Tap to Pay, which stay on the\n * platform account, and for plugin marketplace sales.\n *\n * The shape is recorded on the profile as `stripeChargeModel` by the connect\n * route, which reads it off the account Stripe returns. An absent value is\n * `destination`: the conservative reading, because a direct charge against an\n * Express account would put a refund and a dispute where nobody can act.\n *=========================================*/\nexport type SaleChargeModel = 'direct' | 'destination'\n\n/**\n * The `/v1/accounts` parameters for a new seller account: a full Stripe\n * account that Stripe bills and Stripe underwrites (the Standard shape, by\n * controller properties). The dashboard type cannot be changed later, which\n * is why it is set here and nowhere else.\n */\nexport const DIRECT_CHARGE_ACCOUNT_PARAMS: Readonly<Record<string, string>> = {\n 'controller[fees][payer]': 'account',\n 'controller[losses][payments]': 'stripe',\n 'controller[requirement_collection]': 'stripe',\n 'controller[stripe_dashboard][type]': 'full',\n}\n\n/** The charge shape a Stripe Account object supports. */\nexport function accountChargeModel(account: unknown): SaleChargeModel {\n const controller = (account as any)?.controller\n return controller?.fees?.payer === 'account' &&\n controller?.stripe_dashboard?.type === 'full'\n ? 'direct'\n : 'destination'\n}\n\n/** The charge shape recorded on a seller's profile (`stripeChargeModel`). */\nexport function saleChargeModel(recorded: unknown): SaleChargeModel {\n return recorded === 'direct' ? 'direct' : 'destination'\n}\n\n/**\n * The header that creates (or reads) a Stripe object ON the seller's account\n * for a direct charge, and nothing for a destination charge.\n */\nexport function connectedAccountHeader(\n model: SaleChargeModel,\n accountId: unknown,\n): Record<string, string> {\n const id = typeof accountId === 'string' ? accountId.trim() : ''\n return model === 'direct' && id ? { 'Stripe-Account': id } : {}\n}\n\n/**\n * The split for a DIRECT charge: Aglyn's take as the application fee, and no\n * `transfer_data`, because the money is already the seller's. Stripe rejects\n * a zero application fee, so a 0% plan sends no key at all.\n */\nexport function directChargeParams(\n feeCents: number,\n prefix: 'payment_intent_data' | '' = 'payment_intent_data',\n): Record<string, string> {\n const fee = Number.isFinite(feeCents) ? Math.max(0, Math.round(feeCents)) : 0\n if (fee <= 0) return {}\n const key = prefix ? `${prefix}[application_fee_amount]` : 'application_fee_amount'\n return { [key]: String(fee) }\n}\n"],"names":["STRIPE_CONNECT_PAYMENT_PROVIDER","paymentProvider","merchantAccountReadiness","input","accountId","trim","chargesEnabled","platformMode","accountLivemode","merchantAccountInOtherMode","PREVIOUS_MERCHANT_ACCOUNTS_FIELD","merchantAccountReplacement","kept","Array","isArray","previousAccountIds","filter","id","Boolean","replaced","replacedAccountId","stripeAccountId","newAccountId","includes","stripeChargesEnabled","stripePayoutsEnabled","stripeAccountLivemode","stripeChargeModel","lastPayoutFailureId","lastPayoutFailureKind","lastPayoutFailureAtMs","lastPayoutFailureCents","lastPayoutFailureReason","merchantAccountIsReady","context","readiness","console","error","String","subject","DIRECT_CHARGE_ACCOUNT_PARAMS","accountChargeModel","account","controller","fees","payer","stripe_dashboard","type","saleChargeModel","recorded","connectedAccountHeader","model","directChargeParams","feeCents","prefix","fee","Number","isFinite","Math","max","round","key"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,+BAA+B,QAAQ,uCAAmC;AA8InF,uEAAuE,GACvE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UC,IAAI,KAAK;IAC9D,OAAO8C,UAAU,YAAYlC,KAAK;QAAE,kBAAkBA;IAAG,IAAI,CAAC;AAChE;AAEA;;;;CAIC,GACD,OAAO,SAASmC,mBACdC,QAAgB,EAChBC,SAAqC,qBAAqB;IAE1D,MAAMC,MAAMC,OAAOC,QAAQ,CAACJ,YAAYK,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACP,aAAa;IAC5E,IAAIE,OAAO,GAAG,OAAO,CAAC;IACtB,MAAMM,MAAMP,SAAS,GAAGA,OAAO,wBAAwB,CAAC,GAAG;IAC3D,OAAO;QAAE,CAACO,IAAI,EAAEvB,OAAOiB;IAAK;AAC9B"}
|
|
@@ -28,6 +28,37 @@
|
|
|
28
28
|
*/
|
|
29
29
|
/** A domain as the check accepts one: labels of letters, digits and hyphens. */
|
|
30
30
|
export declare const TENANT_DNS_DOMAIN_PATTERN: RegExp;
|
|
31
|
+
/**
|
|
32
|
+
* IPv6 addresses answering for `domain` that the tenant edge does not answer
|
|
33
|
+
* with: the AAAA record a previous host left on the zone root (AGL-3963).
|
|
34
|
+
*
|
|
35
|
+
* Pointing a domain here replaces its A record (by hand, or through Domain
|
|
36
|
+
* Connect, whose `website` template writes `A @`), and nothing replaces the
|
|
37
|
+
* AAAA beside it. A visitor on IPv6 then reaches the previous host, and the
|
|
38
|
+
* edge's certificate challenge over IPv6 can fail with it. Cloudflare named
|
|
39
|
+
* this case when it onboarded our templates (2026-10-29).
|
|
40
|
+
*
|
|
41
|
+
* Today the edge answers no AAAA at all, so any AAAA on the name is a stray.
|
|
42
|
+
* The edge's own answer is subtracted anyway, so an edge that starts
|
|
43
|
+
* publishing IPv6 on `CNAME_TARGET` does not warn every customer at once; an
|
|
44
|
+
* IPv6 apex pool like `HOST_APEX_ADDRESSES` would need adding here too.
|
|
45
|
+
* Reported, never refused, for the same reason as `stray` below. Never throws,
|
|
46
|
+
* and gives up after `IPV6_LOOKUP_BUDGET_MS`: no answer reads as none.
|
|
47
|
+
*/
|
|
48
|
+
export declare function strayIpv6Addresses(domain: string): Promise<string[]>;
|
|
49
|
+
/** A record answering for a name that is not ours, as the status card lists it. */
|
|
50
|
+
export interface TenantDnsConflict {
|
|
51
|
+
type?: string;
|
|
52
|
+
name?: string;
|
|
53
|
+
value?: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* `conflicts` with each stray IPv6 address of `names` added as an AAAA entry,
|
|
57
|
+
* unless the platform already listed it (AGL-3963). The platform's own DNS
|
|
58
|
+
* check is not relied on to name these: it is the A record it checks. Never
|
|
59
|
+
* throws; within `IPV6_LOOKUP_BUDGET_MS`.
|
|
60
|
+
*/
|
|
61
|
+
export declare function withStrayIpv6Conflicts(names: readonly string[], conflicts: readonly TenantDnsConflict[]): Promise<TenantDnsConflict[]>;
|
|
31
62
|
/** What the check found for one name, as `/api/domains/verify` answers it. */
|
|
32
63
|
export interface TenantDnsCheck {
|
|
33
64
|
domain: string;
|
|
@@ -40,6 +71,8 @@ export interface TenantDnsCheck {
|
|
|
40
71
|
matchedBy?: 'apex-address';
|
|
41
72
|
/** Addresses answering for the name that are not ours (AGL-1913). */
|
|
42
73
|
strayAddresses?: string[];
|
|
74
|
+
/** IPv6 addresses answering for the name that are not ours (AGL-3963). */
|
|
75
|
+
strayIpv6Addresses?: string[];
|
|
43
76
|
}
|
|
44
77
|
/**
|
|
45
78
|
* Resolves `domain` and answers whether it points at the tenant edge: its
|
|
@@ -84,6 +84,135 @@ async function resolveARecords(domain) {
|
|
|
84
84
|
}
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
|
+
/**
|
|
88
|
+
* The most an IPv6 check may add to a request (AGL-3963). It is advice beside
|
|
89
|
+
* a check that already answered, so a slow resolver gives up and reads as
|
|
90
|
+
* "nothing found" rather than holding the domain card or the button.
|
|
91
|
+
*/ const IPV6_LOOKUP_BUDGET_MS = 2000;
|
|
92
|
+
function withinIpv6Budget(work, fallback) {
|
|
93
|
+
let timer;
|
|
94
|
+
const late = new Promise((resolve)=>{
|
|
95
|
+
timer = setTimeout(()=>resolve(fallback), IPV6_LOOKUP_BUDGET_MS);
|
|
96
|
+
});
|
|
97
|
+
return Promise.race([
|
|
98
|
+
work.catch(()=>fallback),
|
|
99
|
+
late
|
|
100
|
+
]).finally(()=>clearTimeout(timer));
|
|
101
|
+
}
|
|
102
|
+
/** One spelling per address, so `2001:DB8:0::1` and `2001:db8::1` match. */ function normaliseIpv6(address) {
|
|
103
|
+
const trimmed = address.trim();
|
|
104
|
+
try {
|
|
105
|
+
return new URL(`http://[${trimmed}]`).hostname.replace(/^\[|\]$/g, '');
|
|
106
|
+
} catch (unused) {
|
|
107
|
+
return trimmed.toLowerCase();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* AAAA records on the public resolvers, one short try each. No fallback to
|
|
112
|
+
* the runtime's resolver, unlike the A check: this is advice, and a second
|
|
113
|
+
* slow lookup would only spend the budget.
|
|
114
|
+
*/ async function resolveAaaaRecords(domain) {
|
|
115
|
+
try {
|
|
116
|
+
const resolver = new CallbackResolver({
|
|
117
|
+
timeout: 1500,
|
|
118
|
+
tries: 1
|
|
119
|
+
});
|
|
120
|
+
resolver.setServers(PUBLIC_RESOLVERS);
|
|
121
|
+
const records = await new Promise((resolve, reject)=>{
|
|
122
|
+
resolver.resolve6(domain, (error, addresses)=>error ? reject(error) : resolve(addresses));
|
|
123
|
+
});
|
|
124
|
+
return records.map(normaliseIpv6);
|
|
125
|
+
} catch (unused) {
|
|
126
|
+
return [];
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Each name's IPv6 addresses that the tenant edge does not answer with, with
|
|
131
|
+
* the edge looked up once. A name carrying a CNAME is skipped: a resolver
|
|
132
|
+
* follows the CNAME, so those addresses are its target's, and the record to
|
|
133
|
+
* fix is the CNAME, which the A side already reports.
|
|
134
|
+
*/ async function strayIpv6ByName(names) {
|
|
135
|
+
const work = (async ()=>{
|
|
136
|
+
const [edge, ...answers] = await Promise.all([
|
|
137
|
+
resolveAaaaRecords(CNAME_TARGET),
|
|
138
|
+
...names.map(async (name)=>{
|
|
139
|
+
const [cnames, addresses] = await Promise.all([
|
|
140
|
+
resolveCnameRecords(name),
|
|
141
|
+
resolveAaaaRecords(name)
|
|
142
|
+
]);
|
|
143
|
+
return {
|
|
144
|
+
name,
|
|
145
|
+
addresses: cnames.length ? [] : addresses
|
|
146
|
+
};
|
|
147
|
+
})
|
|
148
|
+
]);
|
|
149
|
+
const ours = new Set(edge);
|
|
150
|
+
const found = new Map();
|
|
151
|
+
for (const answer of answers){
|
|
152
|
+
const strays = answer.addresses.filter((address)=>!ours.has(address));
|
|
153
|
+
if (strays.length) found.set(answer.name, strays);
|
|
154
|
+
}
|
|
155
|
+
return found;
|
|
156
|
+
})();
|
|
157
|
+
return withinIpv6Budget(work, new Map());
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* IPv6 addresses answering for `domain` that the tenant edge does not answer
|
|
161
|
+
* with: the AAAA record a previous host left on the zone root (AGL-3963).
|
|
162
|
+
*
|
|
163
|
+
* Pointing a domain here replaces its A record (by hand, or through Domain
|
|
164
|
+
* Connect, whose `website` template writes `A @`), and nothing replaces the
|
|
165
|
+
* AAAA beside it. A visitor on IPv6 then reaches the previous host, and the
|
|
166
|
+
* edge's certificate challenge over IPv6 can fail with it. Cloudflare named
|
|
167
|
+
* this case when it onboarded our templates (2026-10-29).
|
|
168
|
+
*
|
|
169
|
+
* Today the edge answers no AAAA at all, so any AAAA on the name is a stray.
|
|
170
|
+
* The edge's own answer is subtracted anyway, so an edge that starts
|
|
171
|
+
* publishing IPv6 on `CNAME_TARGET` does not warn every customer at once; an
|
|
172
|
+
* IPv6 apex pool like `HOST_APEX_ADDRESSES` would need adding here too.
|
|
173
|
+
* Reported, never refused, for the same reason as `stray` below. Never throws,
|
|
174
|
+
* and gives up after `IPV6_LOOKUP_BUDGET_MS`: no answer reads as none.
|
|
175
|
+
*/ export async function strayIpv6Addresses(domain) {
|
|
176
|
+
var _get;
|
|
177
|
+
return (_get = (await strayIpv6ByName([
|
|
178
|
+
domain
|
|
179
|
+
])).get(domain)) != null ? _get : [];
|
|
180
|
+
}
|
|
181
|
+
function conflictKey(type, name, value) {
|
|
182
|
+
const kind = String(type != null ? type : '').toUpperCase();
|
|
183
|
+
const host = String(name != null ? name : '').trim().toLowerCase().replace(/\.+$/, '');
|
|
184
|
+
const data = kind === 'AAAA' ? normaliseIpv6(String(value != null ? value : '')) : String(value != null ? value : '').trim().toLowerCase();
|
|
185
|
+
return [
|
|
186
|
+
kind,
|
|
187
|
+
host,
|
|
188
|
+
data
|
|
189
|
+
].join('|');
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* `conflicts` with each stray IPv6 address of `names` added as an AAAA entry,
|
|
193
|
+
* unless the platform already listed it (AGL-3963). The platform's own DNS
|
|
194
|
+
* check is not relied on to name these: it is the A record it checks. Never
|
|
195
|
+
* throws; within `IPV6_LOOKUP_BUDGET_MS`.
|
|
196
|
+
*/ export async function withStrayIpv6Conflicts(names, conflicts) {
|
|
197
|
+
const merged = [
|
|
198
|
+
...conflicts
|
|
199
|
+
];
|
|
200
|
+
const listed = new Set(conflicts.map((conflict)=>conflictKey(conflict.type, conflict.name, conflict.value)));
|
|
201
|
+
const strays = await strayIpv6ByName(names);
|
|
202
|
+
for (const [name, addresses] of strays){
|
|
203
|
+
for (const value of addresses){
|
|
204
|
+
const key = conflictKey('AAAA', name, value);
|
|
205
|
+
if (listed.has(key)) continue;
|
|
206
|
+
listed.add(key);
|
|
207
|
+
merged.push({
|
|
208
|
+
type: 'AAAA',
|
|
209
|
+
name,
|
|
210
|
+
value
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return merged;
|
|
215
|
+
}
|
|
87
216
|
/**
|
|
88
217
|
* An apex (`aglyn.com`) cannot carry a CNAME — RFC 1034 forbids one alongside
|
|
89
218
|
* the SOA/NS records every zone apex must have. So the CNAME check below can
|
|
@@ -178,10 +307,16 @@ async function resolveARecords(domain) {
|
|
|
178
307
|
// A domain that DOES carry a CNAME but points somewhere else must keep
|
|
179
308
|
// failing — otherwise "pointed at the wrong place" and "pointed at an apex"
|
|
180
309
|
// would verify identically.
|
|
181
|
-
const apex = records.length ?
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
310
|
+
const [apex, strayIpv6] = records.length ? [
|
|
311
|
+
{
|
|
312
|
+
matched: false,
|
|
313
|
+
stray: []
|
|
314
|
+
},
|
|
315
|
+
[]
|
|
316
|
+
] : await Promise.all([
|
|
317
|
+
apexPointsAtTenantEdge(domain),
|
|
318
|
+
strayIpv6Addresses(domain)
|
|
319
|
+
]);
|
|
185
320
|
return _extends({
|
|
186
321
|
domain,
|
|
187
322
|
records,
|
|
@@ -191,6 +326,8 @@ async function resolveARecords(domain) {
|
|
|
191
326
|
matchedBy: 'apex-address'
|
|
192
327
|
}, apex.stray.length ? {
|
|
193
328
|
strayAddresses: apex.stray
|
|
329
|
+
} : {}, strayIpv6.length ? {
|
|
330
|
+
strayIpv6Addresses: strayIpv6
|
|
194
331
|
} : {});
|
|
195
332
|
}
|
|
196
333
|
|