@aglyn/tenant-data-admin 1.9.1 → 1.11.0
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/console-domains.d.ts +14 -0
- package/src/lib/server/console-domains.js +11 -4
- package/src/lib/server/console-domains.js.map +1 -1
- package/src/lib/server/upgrade-proposal.d.ts +28 -4
- package/src/lib/server/upgrade-proposal.js +68 -20
- package/src/lib/server/upgrade-proposal.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-data-admin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-util-email": "1.
|
|
30
|
-
"@aglyn/shared-util-fbserver": "1.
|
|
31
|
-
"@aglyn/shared-util-first-touch": "1.
|
|
32
|
-
"@aglyn/shared-util-http": "1.
|
|
33
|
-
"@aglyn/shared-util-tools": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.11.0",
|
|
29
|
+
"@aglyn/shared-util-email": "1.11.0",
|
|
30
|
+
"@aglyn/shared-util-fbserver": "1.11.0",
|
|
31
|
+
"@aglyn/shared-util-first-touch": "1.11.0",
|
|
32
|
+
"@aglyn/shared-util-http": "1.11.0",
|
|
33
|
+
"@aglyn/shared-util-tools": "1.11.0",
|
|
34
34
|
"@msgpack/msgpack": "^3.1.3",
|
|
35
35
|
"@swc/helpers": "0.5.23",
|
|
36
36
|
"sharp": "^0.35.5",
|
|
@@ -87,6 +87,20 @@ export declare class ConsoleDomainTakenError extends Error {
|
|
|
87
87
|
readonly domain: string;
|
|
88
88
|
constructor(domain: string);
|
|
89
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* The org's `whiteLabel` entitlement, read server-side.
|
|
92
|
+
*
|
|
93
|
+
* AGL-1354 removed `brandingProfile` from what a client may write, so a server
|
|
94
|
+
* route is now the only writer of `customConsoleDomain` — which makes this the
|
|
95
|
+
* only place the gate can live. A gate that is bypassable is not a gate, and
|
|
96
|
+
* this one was, on any plan, straight from the client SDK, until that landed.
|
|
97
|
+
*/
|
|
98
|
+
/**
|
|
99
|
+
* The 403 body for an org whose plan has no `whiteLabel` (AGL-4158): white
|
|
100
|
+
* label is the Custom plan's since pricing v4 (AGL-4126), and the name is read
|
|
101
|
+
* from `PLAN_ENTITLEMENTS` so it can never name a retired plan again.
|
|
102
|
+
*/
|
|
103
|
+
export declare const CONSOLE_DOMAIN_PLAN_REQUIRED_COPY: string;
|
|
90
104
|
/**
|
|
91
105
|
* Claim the primary and every twin in ONE transaction, or none of them.
|
|
92
106
|
*
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
var _planLabelGrantingFeature;
|
|
2
3
|
/**
|
|
3
4
|
* @license
|
|
4
5
|
* Copyright 2026 Aglyn LLC
|
|
@@ -75,6 +76,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
75
76
|
* introduced later without going through `consoleDomainNames` reopens the hole.
|
|
76
77
|
*/ import { randomBytes } from "crypto";
|
|
77
78
|
import { checkEntitlement } from "@aglyn/aglyn/server";
|
|
79
|
+
import { ENTERPRISE_PLAN_LABEL, planLabelGrantingFeature } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
78
80
|
import firebaseAdmin from "./firebase-admin.js";
|
|
79
81
|
import { challengeValue, recordsProveOwnership, resolveChallengeTxt, SSO_CHALLENGE_PREFIX } from "./sso-provisioning.js";
|
|
80
82
|
import { allowConsoleOrigin, allowlistSatisfied, reclaimConsoleOrigin } from "./recaptcha-allowlist.js";
|
|
@@ -169,7 +171,12 @@ function claimView(domain, data) {
|
|
|
169
171
|
* route is now the only writer of `customConsoleDomain` — which makes this the
|
|
170
172
|
* only place the gate can live. A gate that is bypassable is not a gate, and
|
|
171
173
|
* this one was, on any plan, straight from the client SDK, until that landed.
|
|
172
|
-
*/
|
|
174
|
+
*/ /**
|
|
175
|
+
* The 403 body for an org whose plan has no `whiteLabel` (AGL-4158): white
|
|
176
|
+
* label is the Custom plan's since pricing v4 (AGL-4126), and the name is read
|
|
177
|
+
* from `PLAN_ENTITLEMENTS` so it can never name a retired plan again.
|
|
178
|
+
*/ export const CONSOLE_DOMAIN_PLAN_REQUIRED_COPY = `A custom console domain is part of the ${(_planLabelGrantingFeature = planLabelGrantingFeature('whiteLabel')) != null ? _planLabelGrantingFeature : ENTERPRISE_PLAN_LABEL} plan`;
|
|
179
|
+
async function orgIsEntitled(orgId) {
|
|
173
180
|
const snapshot = await firestore().collection('orgs').doc(orgId).get();
|
|
174
181
|
if (!snapshot.exists) return false;
|
|
175
182
|
return checkEntitlement(snapshot.data(), 'whiteLabel');
|
|
@@ -251,7 +258,7 @@ function claimView(domain, data) {
|
|
|
251
258
|
if (!await orgIsEntitled(orgId)) {
|
|
252
259
|
return {
|
|
253
260
|
claim: null,
|
|
254
|
-
error:
|
|
261
|
+
error: CONSOLE_DOMAIN_PLAN_REQUIRED_COPY,
|
|
255
262
|
status: 403
|
|
256
263
|
};
|
|
257
264
|
}
|
|
@@ -307,7 +314,7 @@ function claimView(domain, data) {
|
|
|
307
314
|
if (!await orgIsEntitled(orgId)) {
|
|
308
315
|
return {
|
|
309
316
|
claim: null,
|
|
310
|
-
error:
|
|
317
|
+
error: CONSOLE_DOMAIN_PLAN_REQUIRED_COPY,
|
|
311
318
|
status: 403
|
|
312
319
|
};
|
|
313
320
|
}
|
|
@@ -378,7 +385,7 @@ function claimView(domain, data) {
|
|
|
378
385
|
if (!await orgIsEntitled(orgId)) {
|
|
379
386
|
return {
|
|
380
387
|
claim: null,
|
|
381
|
-
error:
|
|
388
|
+
error: CONSOLE_DOMAIN_PLAN_REQUIRED_COPY,
|
|
382
389
|
status: 403,
|
|
383
390
|
attachment: null
|
|
384
391
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/console-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\n/**\n * Registration, DNS ownership proof and Vercel attachment for a custom\n * **console** domain — the \"verify + attach\" half of AGL-1099 (AGL-1373).\n *\n * ⚠️ **THIS LANDS DARK, AND MUST STAY DARK.** AGL-1099 says it outright:\n * *\"Do NOT ship 1099b alone: attaching a domain that then cannot authenticate\n * is worse than not attaching it, because it looks finished.\"* Nothing here is\n * reachable from a user-facing path, nothing calls `activateConsoleDomain`, and\n * no domain has been attached. One thing must still land first:\n *\n * - **1099e — the handoff itself.** A console domain shares no parent domain\n * with `aglyn.com`, so the `.aglyn.com` session cookie cannot reach it.\n *\n * ## 1099d is no longer one of them (AGL-1378, closed 2026-08-23)\n *\n * The 1099a proof-of-concept (`docs/design/agl-1099a-poc-findings.md`)\n * measured that App Check, *not* Firebase's authorized-domain list, is the\n * gate: an unattested `signInWithCustomToken` 401s with \"Firebase App Check\n * token is invalid\" **before** token validation. Same page, same app id, only\n * the origin differing — an allowlisted origin minted a token and reached\n * credential validation; a non-allowlisted one failed at\n * `appCheck/recaptcha-error`. That finding stands, and it is why the allowlist\n * entry is a hard **functional** prerequisite rather than the commercial\n * ceiling the design called it.\n *\n * What was wrong was the conclusion that the entry could only be added by\n * hand. That rested on probing `aglyn-main`, which is not the project the key\n * lives in; the key was auto-migrated into `recaptcha-migrated-…`, where the\n * Enterprise API is enabled, we hold owner, and `projects.keys.patch` on\n * `webSettings.allowedDomains` answers 200. `activateConsoleDomain` now writes\n * the serving name through `recaptcha-allowlist.ts` and refuses to mark the\n * claim `active` if that write does not land.\n *\n * ## Why this is not `/api/domains/attach|verify|detach`\n *\n * Those routes are shaped around `hosts/{hostId}`, a `cname` field and the\n * `customDomain` entitlement. A console domain is keyed on the **domain**,\n * owned by an **org**, and gated on `whiteLabel`. Re-pointing them at the\n * console project would mean parameterising the auth model, the entitlement,\n * the uniqueness query and the Firestore shape — at which point it is not\n * reuse. What *is* reused is `workspace-domains.ts`, which already talks to\n * `VERCEL_CONSOLE_PROJECT_ID`, already carries a deadline, and already never\n * throws (AGL-1353 D8).\n *\n * ## The uniqueness invariant, which is the whole security property\n *\n * `attachProjectDomain` tolerates Vercel's `domain_already_in_use` as success.\n * That is only safe while the Firestore claim indexes **every** name Vercel\n * holds for us. If a name reaches Vercel without a claim, a second org can\n * claim it here, read `already-exists` as health, and have its visitors served\n * — or redirected — to a stranger's console. That is AGL-743 exactly: there,\n * `host.cname` was written client-side *before* the uniqueness check, so losing\n * the race still left the loser holding the domain and `get-host.ts` resolved\n * the duplicate by Firestore document order.\n *\n * So: **`claimConsoleDomain` claims the primary and every twin in ONE\n * transaction, or none of them**, and `activateConsoleDomain` attaches exactly\n * the set that transaction claimed. Neither half is optional, and a twin\n * introduced later without going through `consoleDomainNames` reopens the hole.\n */\n\nimport { randomBytes } from 'crypto'\nimport { checkEntitlement } from '@aglyn/aglyn/server'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/server'\nimport firebaseAdmin from './firebase-admin'\nimport {\n challengeValue,\n recordsProveOwnership,\n resolveChallengeTxt,\n SSO_CHALLENGE_PREFIX,\n type DomainCheck,\n} from './sso-provisioning'\nimport {\n allowConsoleOrigin,\n allowlistSatisfied,\n reclaimConsoleOrigin,\n type RecaptchaAllowlistResult,\n} from './recaptcha-allowlist'\nimport {\n attachProjectDomain,\n detachProjectDomain,\n pendingUploadCorsRemedy,\n type WorkspaceDomainResult,\n} from './workspace-domains'\n// The blocklist and the shape check, shared with the site custom-domain path\n// so a name added to one is added to both (AGL-1430).\nimport {\n normalizePlatformDomain,\n validatePlatformDomain,\n} from './platform-domain-names'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Collection name, kept in one place so the rules file and this agree. */\nexport const CONSOLE_DOMAINS_COLLECTION = 'consoleDomains'\n\n/**\n * Trim, lowercase, drop a trailing root dot, and tolerate a pasted URL.\n *\n * The console-flavoured name for the shared normaliser, kept because callers\n * and the docs use it.\n */\nexport const normalizeConsoleDomain = normalizePlatformDomain\n\n/**\n * Shape, length and reserved-name check.\n *\n * The RULES moved to `platform-domain-names.ts` (AGL-1430) so the site\n * custom-domain path could stop being the only surface without them — it was\n * the one with the live hole. Only the wording stays here: these two strings\n * are what a customer reads in the console-domain wizard.\n *\n * `{ domain, error }` with both keys always present rather than a discriminated\n * union, matching `validateSsoDomain` — `strictNullChecks` is off repo-wide and\n * an `{ ok: true } | { ok: false }` union does not narrow reliably once it\n * crosses a library boundary.\n */\nexport function validateConsoleDomain(input: string): DomainCheck {\n return validatePlatformDomain(input, {\n invalid: 'Enter a valid domain, for example console.acme.com',\n reserved: 'That domain is reserved and cannot be used as a console domain',\n })\n}\n\n/**\n * Every name this claim covers: the primary, then its twins.\n *\n * **A twin is a name we attach to Vercel that is not the one the customer\n * asked for**, and it is the sharp edge of the whole file. Attaching\n * `acme.com` without also attaching `www.acme.com` leaves half the traffic on\n * the floor; attaching `www.acme.com` without *claiming* it leaves a name in\n * our Vercel project that no Firestore document accounts for — and then a\n * second org claims it, `attachProjectDomain` answers `already-exists`, and\n * that org's visitors are redirected to the first org's console. The name is\n * therefore derived here, claimed here, and attached from the same list.\n *\n * The apex test is deliberately narrow: exactly two labels. `acme.co.uk` is\n * also an apex and gets no twin, which costs a customer a `www` redirect they\n * can ask for by hand. Guessing wrong in the other direction — treating\n * `console.acme.com` as an apex and quietly reserving `www.console.acme.com` —\n * would reserve names on an org's behalf that it never asked for, and a\n * reservation is the thing that locks another org out.\n */\nexport function consoleDomainNames(domain: string): string[] {\n const primary = normalizeConsoleDomain(domain)\n if (!primary) return []\n const labels = primary.split('.')\n if (labels.length !== 2) return [primary]\n return [primary, `www.${primary}`]\n}\n\nexport type ConsoleDomainStatus = 'pending' | 'verified' | 'active' | 'suspended'\n\nexport interface ConsoleDomainClaimView {\n domain: string\n orgId: string\n status: ConsoleDomainStatus\n token: string\n /** Every name the claim reserves — primary first. */\n names: string[]\n /** Fully-qualified host the TXT record goes on. */\n recordHost: string\n /** Exact value the TXT record must carry. */\n recordValue: string\n verified: boolean\n lastRecords?: string[]\n}\n\n/** Both keys always present, one always null — see `validateConsoleDomain`. */\nexport interface ConsoleDomainResult {\n claim: ConsoleDomainClaimView | null\n error: string | null\n /** HTTP status a route should return. 200 whenever `claim` is set. */\n status: number\n}\n\nexport class ConsoleDomainTakenError extends Error {\n readonly domain: string\n constructor(domain: string) {\n super(`Console domain already claimed: ${domain}`)\n this.name = 'ConsoleDomainTakenError'\n this.domain = domain\n }\n}\n\nconst claimRef = (domain: string) =>\n firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(domain)\n\nfunction claimView(\n domain: string,\n data: Record<string, unknown>,\n): ConsoleDomainClaimView {\n const token = String(data?.txtToken ?? '')\n const names = Array.isArray(data?.names)\n ? (data.names as string[])\n : consoleDomainNames(domain)\n return {\n domain,\n orgId: String(data?.orgId ?? ''),\n status: (data?.status as ConsoleDomainStatus) ?? 'pending',\n token,\n names,\n recordHost: `${SSO_CHALLENGE_PREFIX}.${domain}`,\n recordValue: challengeValue(token),\n verified: data?.status === 'verified' || data?.status === 'active',\n lastRecords: (data?.lastRecords as string[]) ?? undefined,\n }\n}\n\n/**\n * The org's `whiteLabel` entitlement, read server-side.\n *\n * AGL-1354 removed `brandingProfile` from what a client may write, so a server\n * route is now the only writer of `customConsoleDomain` — which makes this the\n * only place the gate can live. A gate that is bypassable is not a gate, and\n * this one was, on any plan, straight from the client SDK, until that landed.\n */\nasync function orgIsEntitled(orgId: string): Promise<boolean> {\n const snapshot = await firestore().collection('orgs').doc(orgId).get()\n if (!snapshot.exists) return false\n return checkEntitlement(\n snapshot.data() as Partial<AglynOrgBilling>,\n 'whiteLabel',\n )\n}\n\n/**\n * Claim the primary and every twin in ONE transaction, or none of them.\n *\n * Modelled on the `orgSlugs` reservation in `organizations.ts`: read inside the\n * transaction, refuse if someone else holds it, write in the same transaction.\n * Every name is read with a single `getAll` so the whole set is covered by one\n * transaction's read-set — claiming a twin in a follow-up write is precisely\n * the AGL-743 hole this exists to close.\n *\n * Idempotent for the owning org, and it **keeps the existing token**: reissuing\n * would invalidate a TXT record the customer may already have published and\n * turn a working setup into a mysterious failure (the same reasoning as\n * `issueDomainClaim`).\n *\n * Throws `ConsoleDomainTakenError` when any name in the set belongs to another\n * org. Exported for the integration test, which needs to drive the transaction\n * under real contention.\n */\nexport async function claimConsoleDomain(\n orgId: string,\n domain: string,\n): Promise<ConsoleDomainClaimView> {\n const names = consoleDomainNames(domain)\n const primary = names[0]\n const db = firestore()\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n return db.runTransaction(async (tx) => {\n const refs = names.map((name) =>\n db.collection(CONSOLE_DOMAINS_COLLECTION).doc(name),\n )\n // ONE read covering the whole set. Firestore requires every read before\n // every write in a transaction, so this also fixes the ordering.\n const snapshots = await tx.getAll(...refs)\n for (const snapshot of snapshots) {\n if (snapshot.exists && snapshot.get('orgId') !== orgId) {\n throw new ConsoleDomainTakenError(snapshot.id)\n }\n }\n const existing = snapshots[0]\n const token = existing.exists\n ? String(existing.get('txtToken') ?? '')\n : randomBytes(24).toString('hex')\n const status: ConsoleDomainStatus = existing.exists\n ? ((existing.get('status') as ConsoleDomainStatus) ?? 'pending')\n : 'pending'\n\n snapshots.forEach((snapshot, index) => {\n tx.set(\n refs[index],\n {\n orgId,\n primaryHost: primary,\n role: index === 0 ? 'primary' : 'redirect',\n names,\n txtToken: token,\n status,\n vercelState: snapshot.get('vercelState') ?? 'pending',\n createdAt: snapshot.exists ? snapshot.get('createdAt') : now,\n updatedAt: now,\n },\n { merge: true },\n )\n })\n return claimView(primary, { orgId, status, txtToken: token, names })\n })\n}\n\n/**\n * Start (or re-read) a registration: entitlement, validation, then the claim.\n *\n * The order matters. An org without `whiteLabel` must not be able to learn\n * whether a domain is free, and must not leave a `pending` claim behind that\n * blocks the org that *is* entitled to it.\n */\nexport async function registerConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<ConsoleDomainResult> {\n const orgId = String(options?.orgId ?? '')\n if (!orgId) return { claim: null, error: 'Unknown organization', status: 400 }\n if (!(await orgIsEntitled(orgId))) {\n return {\n claim: null,\n error: 'A custom console domain requires the Agency plan',\n status: 403,\n }\n }\n const { domain, error } = validateConsoleDomain(options?.domain)\n if (!domain) return { claim: null, error: error ?? 'Invalid domain', status: 400 }\n try {\n return { claim: await claimConsoleDomain(orgId, domain), error: null, status: 200 }\n } catch (thrown) {\n if (thrown instanceof ConsoleDomainTakenError) {\n return {\n claim: null,\n error: 'That domain is already connected to another organization',\n status: 409,\n }\n }\n throw thrown\n }\n}\n\n/**\n * Re-read DNS and record the verdict.\n *\n * Re-reads the claim first and refuses if the caller does not own it — the\n * `publishSsoDomains` discipline, where nothing reaches the collection sign-in\n * consults until a fresh lookup has seen the record. The comparison itself is\n * `recordsProveOwnership`, an exact match on a whole TXT record: a substring\n * test would accept `aglyn-domain-verification=<token>-and-more`, and a prefix\n * test would accept anything that merely starts the same way.\n */\nexport async function verifyConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<ConsoleDomainResult> {\n const orgId = String(options?.orgId ?? '')\n const { domain, error } = validateConsoleDomain(options?.domain)\n if (!domain) return { claim: null, error: error ?? 'Invalid domain', status: 400 }\n\n const snapshot = await claimRef(domain).get()\n if (!snapshot.exists || snapshot.get('orgId') !== orgId) {\n return { claim: null, error: 'No claim on that domain', status: 404 }\n }\n if (!(await orgIsEntitled(orgId))) {\n return {\n claim: null,\n error: 'A custom console domain requires the Agency plan',\n status: 403,\n }\n }\n\n const token = String(snapshot.get('txtToken') ?? '')\n const records = await resolveChallengeTxt(domain)\n const proved = recordsProveOwnership(records, token)\n const status: ConsoleDomainStatus = proved\n ? snapshot.get('status') === 'active'\n ? 'active'\n : 'verified'\n : 'pending'\n await claimRef(domain).set(\n {\n status,\n lastRecords: records.slice(0, 10),\n verifiedAt: proved\n ? (snapshot.get('verifiedAt') ??\n firebaseAdmin.firestore.FieldValue.serverTimestamp())\n : null,\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n const view = claimView(domain, {\n ...snapshot.data(),\n status,\n txtToken: token,\n lastRecords: records,\n })\n return proved\n ? { claim: view, error: null, status: 200 }\n : {\n claim: view,\n error: `No matching TXT record at ${view.recordHost}`,\n status: 409,\n }\n}\n\nexport interface ConsoleDomainAttachment {\n domain: string\n results: WorkspaceDomainResult[]\n /** Vercel's verdict alone: every claimed name is on the console project. */\n attached: boolean\n /**\n * Attached **and** able to attest — the only thing a caller may treat as\n * \"the customer can use this domain\". `attached && !ready` is a real and\n * reachable state: Vercel serves the name, App Check refuses it.\n */\n ready: boolean\n /**\n * Non-null when a name this claim SERVES on cannot complete a large upload\n * (AGL-1452), carrying the exact ordered command that fixes it.\n *\n * The attach itself still succeeds — the console does serve on the name, and\n * refusing the domain over the upload path would be the worse outcome. But\n * the customer's video, PDF and ZIP uploads will fail behind a generic \"try\n * again\" snackbar until this is cleared, and the whole point of surfacing it\n * here is that it stops being something a person has to remember: GCS\n * matches CORS origins EXACTLY, so a new console origin needs its own entry\n * and nothing about the eventual symptom points at bucket configuration.\n *\n * `attachProjectDomain` tries to add the entry itself; this is what is left\n * when it could not — in practice, a runtime service account without\n * `storage.buckets.update`.\n */\n uploadCorsRemedy: string | null\n /**\n * The App Check reCAPTCHA allowlist write for the SERVING name (AGL-1378).\n *\n * Unlike `uploadCorsRemedy` this is **not** advisory. A console origin the\n * key has never heard of cannot solve reCAPTCHA, so `getToken` fails with\n * `appCheck/recaptcha-error` and Identity Platform refuses the first\n * `signInWithCustomToken` with `401 UNAUTHENTICATED` — before it looks at\n * the token. The domain would serve a console that renders and can never\n * sign anyone in, and the customer-visible symptom is \"Missing or\n * insufficient permissions\", indistinguishable from a rules verdict.\n *\n * So this participates in `attached`: a claim does not reach `active` unless\n * `allowlistSatisfied()` says the origin can attest.\n */\n allowlist: RecaptchaAllowlistResult\n}\n\n/**\n * Attach every claimed name to the console Vercel project.\n *\n * ⚠️ Not called from anywhere. It exists so the mechanism is complete and\n * tested; wiring it to a route is 1099c's job and must not happen before 1099d\n * (see the header).\n *\n * Refuses unless the claim is this org's **and** currently verified, and unless\n * the org still passes `whiteLabel`. The names come from the stored claim, not\n * from `consoleDomainNames`, so a change to the twin rule can never attach a\n * name the transaction did not reserve.\n *\n * Twins are registered as per-domain **redirects to the primary**, and the\n * redirect value is a **bare hostname** — `attachProjectDomain` enforces that,\n * because `https://${target}` is rejected by Vercel with a message that blames\n * the target for being absent rather than the format (AGL-1365).\n */\nexport async function activateConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<ConsoleDomainResult & { attachment: ConsoleDomainAttachment | null }> {\n const orgId = String(options?.orgId ?? '')\n const { domain, error } = validateConsoleDomain(options?.domain)\n if (!domain) {\n return { claim: null, error: error ?? 'Invalid domain', status: 400, attachment: null }\n }\n const snapshot = await claimRef(domain).get()\n if (!snapshot.exists || snapshot.get('orgId') !== orgId) {\n return { claim: null, error: 'No claim on that domain', status: 404, attachment: null }\n }\n if (!(await orgIsEntitled(orgId))) {\n return {\n claim: null,\n error: 'A custom console domain requires the Agency plan',\n status: 403,\n attachment: null,\n }\n }\n const status = snapshot.get('status')\n if (status !== 'verified' && status !== 'active') {\n return {\n claim: null,\n error: 'Prove ownership of the domain before attaching it',\n status: 409,\n attachment: null,\n }\n }\n\n const names: string[] = Array.isArray(snapshot.get('names'))\n ? snapshot.get('names')\n : [domain]\n const primary = names[0]\n const results: WorkspaceDomainResult[] = []\n for (const [index, name] of names.entries()) {\n results.push(\n await attachProjectDomain(\n name,\n index === 0 ? {} : { redirectTo: primary },\n ),\n )\n }\n const attached = results.every(\n (result) => result.outcome === 'attached' || result.outcome === 'already-exists',\n )\n const uploadCorsRemedy = pendingUploadCorsRemedy(results)\n\n // AGL-1378. Vercel first, deliberately: allowlisting a name we do not\n // actually serve would hand that origin the right to use our App Check site\n // key for nothing in return. Only the primary — a twin is a 308 and never\n // executes the console.\n //\n // If this loses, the claim stays `verified`. A domain reported ready while\n // unlisted is the failure that costs a customer a day of \"permission\n // denied\" tickets against rules that are perfectly correct.\n const allowlist = attached\n ? await allowConsoleOrigin(primary)\n : ({ outcome: 'failed', domain: primary, detail: 'Vercel did not accept every name' } as const)\n const ready = attached && allowlistSatisfied(allowlist.outcome)\n\n await claimRef(domain).set(\n {\n status: ready ? 'active' : 'verified',\n vercelState: attached ? 'attached' : 'pending',\n appCheckState: allowlist.outcome,\n activatedAt: ready\n ? (snapshot.get('activatedAt') ??\n firebaseAdmin.firestore.FieldValue.serverTimestamp())\n : null,\n // Bumped on every activation so a session minted against a previous\n // attachment of the same name is not honoured (AGL-1353 D6).\n sessionEpoch: Date.now(),\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n const view = claimView(domain, {\n ...snapshot.data(),\n status: ready ? 'active' : 'verified',\n })\n return {\n claim: view,\n error: ready\n ? null\n : attached\n ? `The domain is attached but cannot pass App Check: ${allowlist.detail ?? allowlist.outcome}`\n : 'Vercel did not accept every name',\n status: ready ? 200 : 502,\n attachment: { domain: primary, results, attached, ready, uploadCorsRemedy, allowlist },\n }\n}\n\n/**\n * `sessionEpoch = now` across every name a claim covers.\n *\n * The revocation lever of AGL-1353 D6, factored out because D7 pulls it twice:\n * `suspendOnDowngrade` writes it alongside the suspension, and a release writes\n * it alone, before anything else happens. Epoch-ms via `Date.now()`, never\n * `serverTimestamp()` — the value is compared against a cookie's `iat` and an\n * `authorizedAt`, both plain numbers, and a sentinel that resolves later would\n * read as `NaN` at exactly the moment it is supposed to refuse.\n *\n * Never throws, for `suspendOnDowngrade`'s reason: this is defence in depth\n * behind the Vercel domain allowlist, and a caller that cannot persist the bump\n * still has work to do that is more important than the bump.\n */\nasync function bumpConsoleSessionEpoch(names: string[]): Promise<void> {\n if (!Array.isArray(names) || names.length === 0) return\n try {\n const batch = firestore().batch()\n for (const name of names) {\n batch.set(\n firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(name),\n {\n sessionEpoch: Date.now(),\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n await batch.commit()\n } catch (error) {\n console.error('[console-domains] session epoch bump failed', error)\n }\n}\n\n/**\n * Kill the sessions, detach every name, then drop the claim — in that order.\n *\n * **The epoch bump comes first, and that is D7's own ordering**: *\"`sessionEpoch\n * = now` first, then Vercel `DELETE`, then delete the doc. Order matters: kill\n * the sessions while we still control the host.\"* It was the one step of that\n * sentence this function never performed, while\n * {@link consoleSessionEpochRefuses} documented it as something release\n * already did.\n *\n * Two things went wrong without it, and neither is covered by the Vercel\n * detach:\n *\n * - **The in-flight window.** Vercel's `DELETE` and the allowlist reclaim are\n * network round trips. Across all of them the claim still reads `active`, so\n * `resolveConsoleDomain` says `servable` and `redeemConsoleHandoff` — which\n * sits on `/api/*`, outside the middleware matcher — happily cashes an\n * authorized handoff into a brand-new session on a domain we are in the\n * middle of giving up.\n * - **And that session then outlives the release entirely**, because the\n * document carrying the epoch is deleted a moment later and\n * `readConsoleSessionEpoch` reads a missing document as `0`, which every\n * caller treats as \"this control has nothing to say\" and FAILS OPEN. The\n * effect was that `suspendOnDowngrade` — the *lesser* action — revoked\n * sessions properly while an explicit release did not revoke them at all.\n *\n * Bumping first inverts that: an authorization that predates the bump is\n * refused `revoked` at redemption, so the window closes rather than merely\n * being short. What survives the release is still only Vercel's allowlist,\n * which is the boundary; this is the defence in depth behind it that D7 asked\n * for and the code had stopped providing.\n *\n * Vercel before the documents, though, for the reason the header gives: a claim\n * released while the name is still on the project is the unindexed-name hole,\n * opened deliberately. If a detach fails the claim is kept and the caller is\n * told, so the name stays reserved to the org that still holds it in Vercel —\n * and the epoch bump is exactly the right residue on that path too, since\n * sessions on a domain we just tried to release should not survive the attempt.\n */\nexport async function releaseConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<{\n released: boolean\n results: WorkspaceDomainResult[]\n /** Present once the reclaim was attempted — absent when Vercel refused first. */\n allowlist?: RecaptchaAllowlistResult\n error: string | null\n}> {\n const orgId = String(options?.orgId ?? '')\n const { domain } = validateConsoleDomain(options?.domain)\n if (!domain) return { released: false, results: [], error: 'Invalid domain' }\n const snapshot = await claimRef(domain).get()\n if (!snapshot.exists || snapshot.get('orgId') !== orgId) {\n return { released: false, results: [], error: 'No claim on that domain' }\n }\n const names: string[] = Array.isArray(snapshot.get('names'))\n ? snapshot.get('names')\n : [domain]\n\n // D7, step one. Across EVERY name, so a twin cannot outlive its primary —\n // the same reasoning `suspendOnDowngrade` uses, and the same failure posture:\n // never throw. A bump that does not persist still leaves the detach below to\n // run, and refusing to release over a transient Firestore error would leave\n // the domain both attached AND serving, which is the worse of the two.\n await bumpConsoleSessionEpoch(names)\n\n const results: WorkspaceDomainResult[] = []\n for (const name of names) results.push(await detachProjectDomain(name))\n const clear = results.every(\n (result) =>\n result.outcome === 'detached' ||\n result.outcome === 'not-found' ||\n result.outcome === 'skipped',\n )\n if (!clear) {\n return {\n released: false,\n results,\n error: 'The domain is still attached to the project',\n }\n }\n\n // AGL-1378, the reclaim half. Same ordering rule as Vercel: give the\n // capability back before dropping the record of it. A claim deleted while\n // the name is still on the reCAPTCHA key leaves an origin we no longer\n // serve holding a permanent right to mint App Check tokens against our site\n // key, with nothing left in Firestore that says why it is there — and it\n // silently spends one of the 250 slots forever.\n const allowlist = await reclaimConsoleOrigin(names[0])\n if (!allowlistSatisfied(allowlist.outcome)) {\n return {\n released: false,\n results,\n allowlist,\n error: `The domain is off Vercel but still on the App Check allowlist: ${allowlist.detail ?? allowlist.outcome}`,\n }\n }\n\n const batch = firestore().batch()\n for (const name of names) {\n batch.delete(firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(name))\n }\n await batch.commit()\n return { released: true, results, allowlist, error: null }\n}\n\n/**\n * Drop a claim that was never attached, without touching Vercel.\n *\n * The counterpart to claiming from the branding form: an org that clears or\n * changes `customConsoleDomain` must not leave its old reservation standing,\n * or it locks another org out of a name nobody is using. Deliberately refuses\n * once the claim has proved ownership or reached Vercel — releasing *that*\n * needs `releaseConsoleDomain`, because a claim dropped while the name is\n * still on the project is the unindexed-name hole in the header.\n */\nexport async function releasePendingConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<boolean> {\n const orgId = String(options?.orgId ?? '')\n const domain = normalizeConsoleDomain(options?.domain)\n if (!orgId || !domain) return false\n const snapshot = await claimRef(domain).get()\n if (!snapshot.exists || snapshot.get('orgId') !== orgId) return false\n if (snapshot.get('status') !== 'pending') return false\n if (snapshot.get('vercelState') === 'attached') return false\n const names: string[] = Array.isArray(snapshot.get('names'))\n ? snapshot.get('names')\n : [domain]\n const batch = firestore().batch()\n for (const name of names) {\n batch.delete(firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(name))\n }\n await batch.commit()\n return true\n}\n\n/**\n * Why a host may — or may not — be served the console (AGL-1099c).\n *\n * `reason` is not decoration. `unknown` and `degraded` both mean \"serve it,\n * this gate has no opinion\", and they mean it for opposite causes; every other\n * value means \"refuse\". Collapsing them into a boolean is how a lookup outage\n * would come to read the same as a revoked entitlement.\n */\nexport type ConsoleDomainReason =\n | 'active'\n | 'unknown'\n | 'no-org'\n | 'not-entitled'\n | 'not-active'\n | 'degraded'\n\nexport interface ConsoleDomainVerdict {\n /** A claim exists for this exact host. */\n known: boolean\n /** The console may be served here, pinned to `orgSlug`. */\n servable: boolean\n /**\n * Workspace slug of the owning org — where a refused visitor is sent, and\n * the org the path is rewritten under when servable. Never the `orgId`: a\n * verdict is read by an unauthenticated route.\n */\n orgSlug: string | null\n reason: ConsoleDomainReason\n /** The lookup could not be completed. Honour it, never cache it. */\n degraded: boolean\n}\n\nconst UNKNOWN_VERDICT: ConsoleDomainVerdict = {\n known: false,\n servable: false,\n orgSlug: null,\n reason: 'unknown',\n degraded: false,\n}\n\nconst DEGRADED_VERDICT: ConsoleDomainVerdict = {\n known: false,\n servable: false,\n orgSlug: null,\n reason: 'degraded',\n degraded: true,\n}\n\n/**\n * Stop serving a domain whose org no longer holds `whiteLabel`, and make it\n * stick.\n *\n * **This is the fail-closed half of the entitlement, and it is a write on a\n * read path on purpose.** Nothing in the codebase reacts to a plan change —\n * the Stripe webhook writes `plan` and says outright that entitlements resolve\n * at read time, which is sufficient for rendering and insufficient for a\n * hostname (AGL-1353 D7). Rather than add a fan-out to the webhook or a cron\n * that has to be believed, the first request to arrive after a downgrade\n * converts the read-time verdict into stored state: `status: 'suspended'` plus\n * a `sessionEpoch` bump, across **every** name the claim covers, so the twin\n * cannot outlive its primary.\n *\n * The epoch is what makes this more than cosmetic. A refusal that only lives\n * in a verdict leaves already-minted cookies valid; bumping the epoch is the\n * lever that invalidates them at our boundary (AGL-1353 D6).\n *\n * Deliberately NOT the inverse: re-upgrading does not re-activate. Activation\n * attaches names to Vercel and — until AGL-1378 resolves — depends on a manual\n * App Check allowlist entry, so it stays an explicit act through\n * `activateConsoleDomain`, never a side effect of a plan read.\n *\n * Never throws: a suspension that fails to persist still refuses this request,\n * and the next one tries again.\n */\nasync function suspendOnDowngrade(\n domain: string,\n snapshot: FirebaseFirestore.DocumentSnapshot,\n): Promise<void> {\n const status = snapshot.get('status')\n if (status === 'suspended') return\n const names: string[] = Array.isArray(snapshot.get('names'))\n ? snapshot.get('names')\n : [domain]\n try {\n const batch = firestore().batch()\n for (const name of names) {\n batch.set(\n firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(name),\n {\n status: 'suspended',\n suspendedReason: 'entitlement',\n sessionEpoch: Date.now(),\n suspendedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n await batch.commit()\n } catch (error) {\n console.error('[console-domains] suspend on downgrade failed', error)\n }\n}\n\n/**\n * Host → org, for the middleware gate and the session-route boundary.\n *\n * **One host pins exactly one org.** That is enforced by the document being\n * keyed on the host and claimed transactionally (see the header), not by\n * anything here — this function only ever reads the pin, and there is no input\n * by which a caller can ask for a different org.\n *\n * The three \"serve it anyway\" answers, and why each is right:\n *\n * - **`unknown`** — no claim on this host. localhost, preview deployments and\n * self-hosted installs all land here, and they must keep working. It is safe\n * because of the detach ordering `releaseConsoleDomain` enforces: Vercel\n * first, documents second, and the claim is kept if the detach fails. So a\n * name the console project still answers for always has a document, and a\n * name with no document cannot reach this deployment through the console\n * project at all (AGL-1430's correspondence — do not break it).\n * - **`degraded`** — Firestore could not be reached. Fails OPEN, matching the\n * workspace gate and for the reason AGL-1135 recorded: the Vercel domain\n * allowlist is the boundary, and a customer's console going dark because a\n * lookup timed out is worse than the residual exposure. Never cached.\n * - a claim that is `active` and entitled.\n *\n * Everything else refuses. In particular a `verified` claim is **not**\n * servable: until AGL-1378 clears, activation includes a manual App Check\n * allowlist entry, so \"ownership proved\" must never imply \"serve it\".\n */\nexport async function resolveConsoleDomain(\n host: string,\n): Promise<ConsoleDomainVerdict> {\n const domain = normalizeConsoleDomain(host)\n if (!domain) return UNKNOWN_VERDICT\n\n let snapshot: FirebaseFirestore.DocumentSnapshot\n try {\n snapshot = await claimRef(domain).get()\n } catch {\n return DEGRADED_VERDICT\n }\n if (!snapshot.exists) return UNKNOWN_VERDICT\n\n const orgId = String(snapshot.get('orgId') ?? '')\n if (!orgId) return { ...UNKNOWN_VERDICT, known: true, reason: 'no-org' }\n\n let orgSnapshot: FirebaseFirestore.DocumentSnapshot\n try {\n orgSnapshot = await firestore().collection('orgs').doc(orgId).get()\n } catch {\n return DEGRADED_VERDICT\n }\n // A claim pointing at an org that no longer exists refuses, but is NOT\n // suspended: `checkEntitlement(undefined)` resolves to the free plan, so\n // writing a suspension off a missing document would be recording an\n // entitlement verdict that was never actually read (the loading-default\n // class this repo keeps hitting). Refuse now, decide when there is data.\n if (!orgSnapshot.exists) {\n return { ...UNKNOWN_VERDICT, known: true, reason: 'no-org' }\n }\n\n const org = orgSnapshot.data() as Partial<AglynOrgBilling> & { slug?: string }\n const orgSlug = String(org?.slug ?? '') || null\n\n if (!checkEntitlement(org, 'whiteLabel')) {\n await suspendOnDowngrade(domain, snapshot)\n return { known: true, servable: false, orgSlug, reason: 'not-entitled', degraded: false }\n }\n if (snapshot.get('status') !== 'active') {\n return { known: true, servable: false, orgSlug, reason: 'not-active', degraded: false }\n }\n return { known: true, servable: true, orgSlug, reason: 'active', degraded: false }\n}\n\n/**\n * The org a console domain belongs to, or null.\n *\n * Read-only, and used today only to refuse a `customConsoleDomain` that another\n * org already holds. Routing reads `resolveConsoleDomain` instead, which asks\n * the entitlement question this one does not.\n */\nexport async function getConsoleDomainClaim(\n domain: string,\n): Promise<{ orgId: string; status: ConsoleDomainStatus } | null> {\n const normalized = normalizeConsoleDomain(domain)\n if (!normalized) return null\n const snapshot = await claimRef(normalized).get()\n if (!snapshot.exists) return null\n return {\n orgId: String(snapshot.get('orgId') ?? ''),\n status: (snapshot.get('status') as ConsoleDomainStatus) ?? 'pending',\n }\n}\n"],"names":["randomBytes","checkEntitlement","firebaseAdmin","challengeValue","recordsProveOwnership","resolveChallengeTxt","SSO_CHALLENGE_PREFIX","allowConsoleOrigin","allowlistSatisfied","reclaimConsoleOrigin","attachProjectDomain","detachProjectDomain","pendingUploadCorsRemedy","normalizePlatformDomain","validatePlatformDomain","firestore","app","CONSOLE_DOMAINS_COLLECTION","normalizeConsoleDomain","validateConsoleDomain","input","invalid","reserved","consoleDomainNames","domain","primary","labels","split","length","ConsoleDomainTakenError","Error","name","claimRef","collection","doc","claimView","data","token","String","txtToken","names","Array","isArray","orgId","status","recordHost","recordValue","verified","lastRecords","undefined","orgIsEntitled","snapshot","get","exists","claimConsoleDomain","db","now","FieldValue","serverTimestamp","runTransaction","tx","existing","refs","map","snapshots","getAll","id","toString","forEach","index","set","primaryHost","role","vercelState","createdAt","updatedAt","merge","registerConsoleDomain","options","claim","error","thrown","verifyConsoleDomain","records","proved","slice","verifiedAt","view","activateConsoleDomain","allowlist","attachment","results","entries","push","redirectTo","attached","every","result","outcome","uploadCorsRemedy","detail","ready","appCheckState","activatedAt","sessionEpoch","Date","bumpConsoleSessionEpoch","batch","commit","console","releaseConsoleDomain","released","clear","delete","releasePendingConsoleDomain","UNKNOWN_VERDICT","known","servable","orgSlug","reason","degraded","DEGRADED_VERDICT","suspendOnDowngrade","suspendedReason","suspendedAt","resolveConsoleDomain","host","orgSnapshot","org","slug","getConsoleDomainClaim","normalized"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2DC,GAED,SAASA,WAAW,QAAQ,SAAQ;AACpC,SAASC,gBAAgB,QAAQ,sBAAqB;AAEtD,OAAOC,mBAAmB,sBAAkB;AAC5C,SACEC,cAAc,EACdC,qBAAqB,EACrBC,mBAAmB,EACnBC,oBAAoB,QAEf,wBAAoB;AAC3B,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,oBAAoB,QAEf,2BAAuB;AAC9B,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,uBAAuB,QAElB,yBAAqB;AAC5B,6EAA6E;AAC7E,sDAAsD;AACtD,SACEC,uBAAuB,EACvBC,sBAAsB,QACjB,6BAAyB;AAEhC,MAAMC,YAAY,IAAMb,cAAcc,GAAG,GAAGD,SAAS;AAEr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MC,UAAU;QAAMC;QAASC,QAAQ;QAAUC,UAAU;IAAM;AACnF;AAEA;;;;;;CAMC,GACD,OAAO,eAAeU,sBACpB1G,MAAc;QAOE2B,eACLA;IANX,MAAMgF,aAAajH,uBAAuBM;IAC1C,IAAI,CAAC2G,YAAY,OAAO;IACxB,MAAMhF,WAAW,MAAMnB,SAASmG,YAAY/E,GAAG;IAC/C,IAAI,CAACD,SAASE,MAAM,EAAE,OAAO;IAC7B,OAAO;QACLV,OAAOL,QAAOa,gBAAAA,SAASC,GAAG,CAAC,oBAAbD,gBAAyB;QACvCP,MAAM,GAAGO,iBAAAA,SAASC,GAAG,CAAC,qBAAbD,iBAAkD;IAC7D;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/console-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\n/**\n * Registration, DNS ownership proof and Vercel attachment for a custom\n * **console** domain — the \"verify + attach\" half of AGL-1099 (AGL-1373).\n *\n * ⚠️ **THIS LANDS DARK, AND MUST STAY DARK.** AGL-1099 says it outright:\n * *\"Do NOT ship 1099b alone: attaching a domain that then cannot authenticate\n * is worse than not attaching it, because it looks finished.\"* Nothing here is\n * reachable from a user-facing path, nothing calls `activateConsoleDomain`, and\n * no domain has been attached. One thing must still land first:\n *\n * - **1099e — the handoff itself.** A console domain shares no parent domain\n * with `aglyn.com`, so the `.aglyn.com` session cookie cannot reach it.\n *\n * ## 1099d is no longer one of them (AGL-1378, closed 2026-08-23)\n *\n * The 1099a proof-of-concept (`docs/design/agl-1099a-poc-findings.md`)\n * measured that App Check, *not* Firebase's authorized-domain list, is the\n * gate: an unattested `signInWithCustomToken` 401s with \"Firebase App Check\n * token is invalid\" **before** token validation. Same page, same app id, only\n * the origin differing — an allowlisted origin minted a token and reached\n * credential validation; a non-allowlisted one failed at\n * `appCheck/recaptcha-error`. That finding stands, and it is why the allowlist\n * entry is a hard **functional** prerequisite rather than the commercial\n * ceiling the design called it.\n *\n * What was wrong was the conclusion that the entry could only be added by\n * hand. That rested on probing `aglyn-main`, which is not the project the key\n * lives in; the key was auto-migrated into `recaptcha-migrated-…`, where the\n * Enterprise API is enabled, we hold owner, and `projects.keys.patch` on\n * `webSettings.allowedDomains` answers 200. `activateConsoleDomain` now writes\n * the serving name through `recaptcha-allowlist.ts` and refuses to mark the\n * claim `active` if that write does not land.\n *\n * ## Why this is not `/api/domains/attach|verify|detach`\n *\n * Those routes are shaped around `hosts/{hostId}`, a `cname` field and the\n * `customDomain` entitlement. A console domain is keyed on the **domain**,\n * owned by an **org**, and gated on `whiteLabel`. Re-pointing them at the\n * console project would mean parameterising the auth model, the entitlement,\n * the uniqueness query and the Firestore shape — at which point it is not\n * reuse. What *is* reused is `workspace-domains.ts`, which already talks to\n * `VERCEL_CONSOLE_PROJECT_ID`, already carries a deadline, and already never\n * throws (AGL-1353 D8).\n *\n * ## The uniqueness invariant, which is the whole security property\n *\n * `attachProjectDomain` tolerates Vercel's `domain_already_in_use` as success.\n * That is only safe while the Firestore claim indexes **every** name Vercel\n * holds for us. If a name reaches Vercel without a claim, a second org can\n * claim it here, read `already-exists` as health, and have its visitors served\n * — or redirected — to a stranger's console. That is AGL-743 exactly: there,\n * `host.cname` was written client-side *before* the uniqueness check, so losing\n * the race still left the loser holding the domain and `get-host.ts` resolved\n * the duplicate by Firestore document order.\n *\n * So: **`claimConsoleDomain` claims the primary and every twin in ONE\n * transaction, or none of them**, and `activateConsoleDomain` attaches exactly\n * the set that transaction claimed. Neither half is optional, and a twin\n * introduced later without going through `consoleDomainNames` reopens the hole.\n */\n\nimport { randomBytes } from 'crypto'\nimport { checkEntitlement } from '@aglyn/aglyn/server'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/server'\nimport {\n ENTERPRISE_PLAN_LABEL,\n planLabelGrantingFeature,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport firebaseAdmin from './firebase-admin'\nimport {\n challengeValue,\n recordsProveOwnership,\n resolveChallengeTxt,\n SSO_CHALLENGE_PREFIX,\n type DomainCheck,\n} from './sso-provisioning'\nimport {\n allowConsoleOrigin,\n allowlistSatisfied,\n reclaimConsoleOrigin,\n type RecaptchaAllowlistResult,\n} from './recaptcha-allowlist'\nimport {\n attachProjectDomain,\n detachProjectDomain,\n pendingUploadCorsRemedy,\n type WorkspaceDomainResult,\n} from './workspace-domains'\n// The blocklist and the shape check, shared with the site custom-domain path\n// so a name added to one is added to both (AGL-1430).\nimport {\n normalizePlatformDomain,\n validatePlatformDomain,\n} from './platform-domain-names'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Collection name, kept in one place so the rules file and this agree. */\nexport const CONSOLE_DOMAINS_COLLECTION = 'consoleDomains'\n\n/**\n * Trim, lowercase, drop a trailing root dot, and tolerate a pasted URL.\n *\n * The console-flavoured name for the shared normaliser, kept because callers\n * and the docs use it.\n */\nexport const normalizeConsoleDomain = normalizePlatformDomain\n\n/**\n * Shape, length and reserved-name check.\n *\n * The RULES moved to `platform-domain-names.ts` (AGL-1430) so the site\n * custom-domain path could stop being the only surface without them — it was\n * the one with the live hole. Only the wording stays here: these two strings\n * are what a customer reads in the console-domain wizard.\n *\n * `{ domain, error }` with both keys always present rather than a discriminated\n * union, matching `validateSsoDomain` — `strictNullChecks` is off repo-wide and\n * an `{ ok: true } | { ok: false }` union does not narrow reliably once it\n * crosses a library boundary.\n */\nexport function validateConsoleDomain(input: string): DomainCheck {\n return validatePlatformDomain(input, {\n invalid: 'Enter a valid domain, for example console.acme.com',\n reserved: 'That domain is reserved and cannot be used as a console domain',\n })\n}\n\n/**\n * Every name this claim covers: the primary, then its twins.\n *\n * **A twin is a name we attach to Vercel that is not the one the customer\n * asked for**, and it is the sharp edge of the whole file. Attaching\n * `acme.com` without also attaching `www.acme.com` leaves half the traffic on\n * the floor; attaching `www.acme.com` without *claiming* it leaves a name in\n * our Vercel project that no Firestore document accounts for — and then a\n * second org claims it, `attachProjectDomain` answers `already-exists`, and\n * that org's visitors are redirected to the first org's console. The name is\n * therefore derived here, claimed here, and attached from the same list.\n *\n * The apex test is deliberately narrow: exactly two labels. `acme.co.uk` is\n * also an apex and gets no twin, which costs a customer a `www` redirect they\n * can ask for by hand. Guessing wrong in the other direction — treating\n * `console.acme.com` as an apex and quietly reserving `www.console.acme.com` —\n * would reserve names on an org's behalf that it never asked for, and a\n * reservation is the thing that locks another org out.\n */\nexport function consoleDomainNames(domain: string): string[] {\n const primary = normalizeConsoleDomain(domain)\n if (!primary) return []\n const labels = primary.split('.')\n if (labels.length !== 2) return [primary]\n return [primary, `www.${primary}`]\n}\n\nexport type ConsoleDomainStatus = 'pending' | 'verified' | 'active' | 'suspended'\n\nexport interface ConsoleDomainClaimView {\n domain: string\n orgId: string\n status: ConsoleDomainStatus\n token: string\n /** Every name the claim reserves — primary first. */\n names: string[]\n /** Fully-qualified host the TXT record goes on. */\n recordHost: string\n /** Exact value the TXT record must carry. */\n recordValue: string\n verified: boolean\n lastRecords?: string[]\n}\n\n/** Both keys always present, one always null — see `validateConsoleDomain`. */\nexport interface ConsoleDomainResult {\n claim: ConsoleDomainClaimView | null\n error: string | null\n /** HTTP status a route should return. 200 whenever `claim` is set. */\n status: number\n}\n\nexport class ConsoleDomainTakenError extends Error {\n readonly domain: string\n constructor(domain: string) {\n super(`Console domain already claimed: ${domain}`)\n this.name = 'ConsoleDomainTakenError'\n this.domain = domain\n }\n}\n\nconst claimRef = (domain: string) =>\n firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(domain)\n\nfunction claimView(\n domain: string,\n data: Record<string, unknown>,\n): ConsoleDomainClaimView {\n const token = String(data?.txtToken ?? '')\n const names = Array.isArray(data?.names)\n ? (data.names as string[])\n : consoleDomainNames(domain)\n return {\n domain,\n orgId: String(data?.orgId ?? ''),\n status: (data?.status as ConsoleDomainStatus) ?? 'pending',\n token,\n names,\n recordHost: `${SSO_CHALLENGE_PREFIX}.${domain}`,\n recordValue: challengeValue(token),\n verified: data?.status === 'verified' || data?.status === 'active',\n lastRecords: (data?.lastRecords as string[]) ?? undefined,\n }\n}\n\n/**\n * The org's `whiteLabel` entitlement, read server-side.\n *\n * AGL-1354 removed `brandingProfile` from what a client may write, so a server\n * route is now the only writer of `customConsoleDomain` — which makes this the\n * only place the gate can live. A gate that is bypassable is not a gate, and\n * this one was, on any plan, straight from the client SDK, until that landed.\n */\n/**\n * The 403 body for an org whose plan has no `whiteLabel` (AGL-4158): white\n * label is the Custom plan's since pricing v4 (AGL-4126), and the name is read\n * from `PLAN_ENTITLEMENTS` so it can never name a retired plan again.\n */\nexport const CONSOLE_DOMAIN_PLAN_REQUIRED_COPY = `A custom console domain is part of the ${\n planLabelGrantingFeature('whiteLabel') ?? ENTERPRISE_PLAN_LABEL\n} plan`\n\nasync function orgIsEntitled(orgId: string): Promise<boolean> {\n const snapshot = await firestore().collection('orgs').doc(orgId).get()\n if (!snapshot.exists) return false\n return checkEntitlement(\n snapshot.data() as Partial<AglynOrgBilling>,\n 'whiteLabel',\n )\n}\n\n/**\n * Claim the primary and every twin in ONE transaction, or none of them.\n *\n * Modelled on the `orgSlugs` reservation in `organizations.ts`: read inside the\n * transaction, refuse if someone else holds it, write in the same transaction.\n * Every name is read with a single `getAll` so the whole set is covered by one\n * transaction's read-set — claiming a twin in a follow-up write is precisely\n * the AGL-743 hole this exists to close.\n *\n * Idempotent for the owning org, and it **keeps the existing token**: reissuing\n * would invalidate a TXT record the customer may already have published and\n * turn a working setup into a mysterious failure (the same reasoning as\n * `issueDomainClaim`).\n *\n * Throws `ConsoleDomainTakenError` when any name in the set belongs to another\n * org. Exported for the integration test, which needs to drive the transaction\n * under real contention.\n */\nexport async function claimConsoleDomain(\n orgId: string,\n domain: string,\n): Promise<ConsoleDomainClaimView> {\n const names = consoleDomainNames(domain)\n const primary = names[0]\n const db = firestore()\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n return db.runTransaction(async (tx) => {\n const refs = names.map((name) =>\n db.collection(CONSOLE_DOMAINS_COLLECTION).doc(name),\n )\n // ONE read covering the whole set. Firestore requires every read before\n // every write in a transaction, so this also fixes the ordering.\n const snapshots = await tx.getAll(...refs)\n for (const snapshot of snapshots) {\n if (snapshot.exists && snapshot.get('orgId') !== orgId) {\n throw new ConsoleDomainTakenError(snapshot.id)\n }\n }\n const existing = snapshots[0]\n const token = existing.exists\n ? String(existing.get('txtToken') ?? '')\n : randomBytes(24).toString('hex')\n const status: ConsoleDomainStatus = existing.exists\n ? ((existing.get('status') as ConsoleDomainStatus) ?? 'pending')\n : 'pending'\n\n snapshots.forEach((snapshot, index) => {\n tx.set(\n refs[index],\n {\n orgId,\n primaryHost: primary,\n role: index === 0 ? 'primary' : 'redirect',\n names,\n txtToken: token,\n status,\n vercelState: snapshot.get('vercelState') ?? 'pending',\n createdAt: snapshot.exists ? snapshot.get('createdAt') : now,\n updatedAt: now,\n },\n { merge: true },\n )\n })\n return claimView(primary, { orgId, status, txtToken: token, names })\n })\n}\n\n/**\n * Start (or re-read) a registration: entitlement, validation, then the claim.\n *\n * The order matters. An org without `whiteLabel` must not be able to learn\n * whether a domain is free, and must not leave a `pending` claim behind that\n * blocks the org that *is* entitled to it.\n */\nexport async function registerConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<ConsoleDomainResult> {\n const orgId = String(options?.orgId ?? '')\n if (!orgId) return { claim: null, error: 'Unknown organization', status: 400 }\n if (!(await orgIsEntitled(orgId))) {\n return {\n claim: null,\n error: CONSOLE_DOMAIN_PLAN_REQUIRED_COPY,\n status: 403,\n }\n }\n const { domain, error } = validateConsoleDomain(options?.domain)\n if (!domain) return { claim: null, error: error ?? 'Invalid domain', status: 400 }\n try {\n return { claim: await claimConsoleDomain(orgId, domain), error: null, status: 200 }\n } catch (thrown) {\n if (thrown instanceof ConsoleDomainTakenError) {\n return {\n claim: null,\n error: 'That domain is already connected to another organization',\n status: 409,\n }\n }\n throw thrown\n }\n}\n\n/**\n * Re-read DNS and record the verdict.\n *\n * Re-reads the claim first and refuses if the caller does not own it — the\n * `publishSsoDomains` discipline, where nothing reaches the collection sign-in\n * consults until a fresh lookup has seen the record. The comparison itself is\n * `recordsProveOwnership`, an exact match on a whole TXT record: a substring\n * test would accept `aglyn-domain-verification=<token>-and-more`, and a prefix\n * test would accept anything that merely starts the same way.\n */\nexport async function verifyConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<ConsoleDomainResult> {\n const orgId = String(options?.orgId ?? '')\n const { domain, error } = validateConsoleDomain(options?.domain)\n if (!domain) return { claim: null, error: error ?? 'Invalid domain', status: 400 }\n\n const snapshot = await claimRef(domain).get()\n if (!snapshot.exists || snapshot.get('orgId') !== orgId) {\n return { claim: null, error: 'No claim on that domain', status: 404 }\n }\n if (!(await orgIsEntitled(orgId))) {\n return {\n claim: null,\n error: CONSOLE_DOMAIN_PLAN_REQUIRED_COPY,\n status: 403,\n }\n }\n\n const token = String(snapshot.get('txtToken') ?? '')\n const records = await resolveChallengeTxt(domain)\n const proved = recordsProveOwnership(records, token)\n const status: ConsoleDomainStatus = proved\n ? snapshot.get('status') === 'active'\n ? 'active'\n : 'verified'\n : 'pending'\n await claimRef(domain).set(\n {\n status,\n lastRecords: records.slice(0, 10),\n verifiedAt: proved\n ? (snapshot.get('verifiedAt') ??\n firebaseAdmin.firestore.FieldValue.serverTimestamp())\n : null,\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n const view = claimView(domain, {\n ...snapshot.data(),\n status,\n txtToken: token,\n lastRecords: records,\n })\n return proved\n ? { claim: view, error: null, status: 200 }\n : {\n claim: view,\n error: `No matching TXT record at ${view.recordHost}`,\n status: 409,\n }\n}\n\nexport interface ConsoleDomainAttachment {\n domain: string\n results: WorkspaceDomainResult[]\n /** Vercel's verdict alone: every claimed name is on the console project. */\n attached: boolean\n /**\n * Attached **and** able to attest — the only thing a caller may treat as\n * \"the customer can use this domain\". `attached && !ready` is a real and\n * reachable state: Vercel serves the name, App Check refuses it.\n */\n ready: boolean\n /**\n * Non-null when a name this claim SERVES on cannot complete a large upload\n * (AGL-1452), carrying the exact ordered command that fixes it.\n *\n * The attach itself still succeeds — the console does serve on the name, and\n * refusing the domain over the upload path would be the worse outcome. But\n * the customer's video, PDF and ZIP uploads will fail behind a generic \"try\n * again\" snackbar until this is cleared, and the whole point of surfacing it\n * here is that it stops being something a person has to remember: GCS\n * matches CORS origins EXACTLY, so a new console origin needs its own entry\n * and nothing about the eventual symptom points at bucket configuration.\n *\n * `attachProjectDomain` tries to add the entry itself; this is what is left\n * when it could not — in practice, a runtime service account without\n * `storage.buckets.update`.\n */\n uploadCorsRemedy: string | null\n /**\n * The App Check reCAPTCHA allowlist write for the SERVING name (AGL-1378).\n *\n * Unlike `uploadCorsRemedy` this is **not** advisory. A console origin the\n * key has never heard of cannot solve reCAPTCHA, so `getToken` fails with\n * `appCheck/recaptcha-error` and Identity Platform refuses the first\n * `signInWithCustomToken` with `401 UNAUTHENTICATED` — before it looks at\n * the token. The domain would serve a console that renders and can never\n * sign anyone in, and the customer-visible symptom is \"Missing or\n * insufficient permissions\", indistinguishable from a rules verdict.\n *\n * So this participates in `attached`: a claim does not reach `active` unless\n * `allowlistSatisfied()` says the origin can attest.\n */\n allowlist: RecaptchaAllowlistResult\n}\n\n/**\n * Attach every claimed name to the console Vercel project.\n *\n * ⚠️ Not called from anywhere. It exists so the mechanism is complete and\n * tested; wiring it to a route is 1099c's job and must not happen before 1099d\n * (see the header).\n *\n * Refuses unless the claim is this org's **and** currently verified, and unless\n * the org still passes `whiteLabel`. The names come from the stored claim, not\n * from `consoleDomainNames`, so a change to the twin rule can never attach a\n * name the transaction did not reserve.\n *\n * Twins are registered as per-domain **redirects to the primary**, and the\n * redirect value is a **bare hostname** — `attachProjectDomain` enforces that,\n * because `https://${target}` is rejected by Vercel with a message that blames\n * the target for being absent rather than the format (AGL-1365).\n */\nexport async function activateConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<ConsoleDomainResult & { attachment: ConsoleDomainAttachment | null }> {\n const orgId = String(options?.orgId ?? '')\n const { domain, error } = validateConsoleDomain(options?.domain)\n if (!domain) {\n return { claim: null, error: error ?? 'Invalid domain', status: 400, attachment: null }\n }\n const snapshot = await claimRef(domain).get()\n if (!snapshot.exists || snapshot.get('orgId') !== orgId) {\n return { claim: null, error: 'No claim on that domain', status: 404, attachment: null }\n }\n if (!(await orgIsEntitled(orgId))) {\n return {\n claim: null,\n error: CONSOLE_DOMAIN_PLAN_REQUIRED_COPY,\n status: 403,\n attachment: null,\n }\n }\n const status = snapshot.get('status')\n if (status !== 'verified' && status !== 'active') {\n return {\n claim: null,\n error: 'Prove ownership of the domain before attaching it',\n status: 409,\n attachment: null,\n }\n }\n\n const names: string[] = Array.isArray(snapshot.get('names'))\n ? snapshot.get('names')\n : [domain]\n const primary = names[0]\n const results: WorkspaceDomainResult[] = []\n for (const [index, name] of names.entries()) {\n results.push(\n await attachProjectDomain(\n name,\n index === 0 ? {} : { redirectTo: primary },\n ),\n )\n }\n const attached = results.every(\n (result) => result.outcome === 'attached' || result.outcome === 'already-exists',\n )\n const uploadCorsRemedy = pendingUploadCorsRemedy(results)\n\n // AGL-1378. Vercel first, deliberately: allowlisting a name we do not\n // actually serve would hand that origin the right to use our App Check site\n // key for nothing in return. Only the primary — a twin is a 308 and never\n // executes the console.\n //\n // If this loses, the claim stays `verified`. A domain reported ready while\n // unlisted is the failure that costs a customer a day of \"permission\n // denied\" tickets against rules that are perfectly correct.\n const allowlist = attached\n ? await allowConsoleOrigin(primary)\n : ({ outcome: 'failed', domain: primary, detail: 'Vercel did not accept every name' } as const)\n const ready = attached && allowlistSatisfied(allowlist.outcome)\n\n await claimRef(domain).set(\n {\n status: ready ? 'active' : 'verified',\n vercelState: attached ? 'attached' : 'pending',\n appCheckState: allowlist.outcome,\n activatedAt: ready\n ? (snapshot.get('activatedAt') ??\n firebaseAdmin.firestore.FieldValue.serverTimestamp())\n : null,\n // Bumped on every activation so a session minted against a previous\n // attachment of the same name is not honoured (AGL-1353 D6).\n sessionEpoch: Date.now(),\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n const view = claimView(domain, {\n ...snapshot.data(),\n status: ready ? 'active' : 'verified',\n })\n return {\n claim: view,\n error: ready\n ? null\n : attached\n ? `The domain is attached but cannot pass App Check: ${allowlist.detail ?? allowlist.outcome}`\n : 'Vercel did not accept every name',\n status: ready ? 200 : 502,\n attachment: { domain: primary, results, attached, ready, uploadCorsRemedy, allowlist },\n }\n}\n\n/**\n * `sessionEpoch = now` across every name a claim covers.\n *\n * The revocation lever of AGL-1353 D6, factored out because D7 pulls it twice:\n * `suspendOnDowngrade` writes it alongside the suspension, and a release writes\n * it alone, before anything else happens. Epoch-ms via `Date.now()`, never\n * `serverTimestamp()` — the value is compared against a cookie's `iat` and an\n * `authorizedAt`, both plain numbers, and a sentinel that resolves later would\n * read as `NaN` at exactly the moment it is supposed to refuse.\n *\n * Never throws, for `suspendOnDowngrade`'s reason: this is defence in depth\n * behind the Vercel domain allowlist, and a caller that cannot persist the bump\n * still has work to do that is more important than the bump.\n */\nasync function bumpConsoleSessionEpoch(names: string[]): Promise<void> {\n if (!Array.isArray(names) || names.length === 0) return\n try {\n const batch = firestore().batch()\n for (const name of names) {\n batch.set(\n firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(name),\n {\n sessionEpoch: Date.now(),\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n await batch.commit()\n } catch (error) {\n console.error('[console-domains] session epoch bump failed', error)\n }\n}\n\n/**\n * Kill the sessions, detach every name, then drop the claim — in that order.\n *\n * **The epoch bump comes first, and that is D7's own ordering**: *\"`sessionEpoch\n * = now` first, then Vercel `DELETE`, then delete the doc. Order matters: kill\n * the sessions while we still control the host.\"* It was the one step of that\n * sentence this function never performed, while\n * {@link consoleSessionEpochRefuses} documented it as something release\n * already did.\n *\n * Two things went wrong without it, and neither is covered by the Vercel\n * detach:\n *\n * - **The in-flight window.** Vercel's `DELETE` and the allowlist reclaim are\n * network round trips. Across all of them the claim still reads `active`, so\n * `resolveConsoleDomain` says `servable` and `redeemConsoleHandoff` — which\n * sits on `/api/*`, outside the middleware matcher — happily cashes an\n * authorized handoff into a brand-new session on a domain we are in the\n * middle of giving up.\n * - **And that session then outlives the release entirely**, because the\n * document carrying the epoch is deleted a moment later and\n * `readConsoleSessionEpoch` reads a missing document as `0`, which every\n * caller treats as \"this control has nothing to say\" and FAILS OPEN. The\n * effect was that `suspendOnDowngrade` — the *lesser* action — revoked\n * sessions properly while an explicit release did not revoke them at all.\n *\n * Bumping first inverts that: an authorization that predates the bump is\n * refused `revoked` at redemption, so the window closes rather than merely\n * being short. What survives the release is still only Vercel's allowlist,\n * which is the boundary; this is the defence in depth behind it that D7 asked\n * for and the code had stopped providing.\n *\n * Vercel before the documents, though, for the reason the header gives: a claim\n * released while the name is still on the project is the unindexed-name hole,\n * opened deliberately. If a detach fails the claim is kept and the caller is\n * told, so the name stays reserved to the org that still holds it in Vercel —\n * and the epoch bump is exactly the right residue on that path too, since\n * sessions on a domain we just tried to release should not survive the attempt.\n */\nexport async function releaseConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<{\n released: boolean\n results: WorkspaceDomainResult[]\n /** Present once the reclaim was attempted — absent when Vercel refused first. */\n allowlist?: RecaptchaAllowlistResult\n error: string | null\n}> {\n const orgId = String(options?.orgId ?? '')\n const { domain } = validateConsoleDomain(options?.domain)\n if (!domain) return { released: false, results: [], error: 'Invalid domain' }\n const snapshot = await claimRef(domain).get()\n if (!snapshot.exists || snapshot.get('orgId') !== orgId) {\n return { released: false, results: [], error: 'No claim on that domain' }\n }\n const names: string[] = Array.isArray(snapshot.get('names'))\n ? snapshot.get('names')\n : [domain]\n\n // D7, step one. Across EVERY name, so a twin cannot outlive its primary —\n // the same reasoning `suspendOnDowngrade` uses, and the same failure posture:\n // never throw. A bump that does not persist still leaves the detach below to\n // run, and refusing to release over a transient Firestore error would leave\n // the domain both attached AND serving, which is the worse of the two.\n await bumpConsoleSessionEpoch(names)\n\n const results: WorkspaceDomainResult[] = []\n for (const name of names) results.push(await detachProjectDomain(name))\n const clear = results.every(\n (result) =>\n result.outcome === 'detached' ||\n result.outcome === 'not-found' ||\n result.outcome === 'skipped',\n )\n if (!clear) {\n return {\n released: false,\n results,\n error: 'The domain is still attached to the project',\n }\n }\n\n // AGL-1378, the reclaim half. Same ordering rule as Vercel: give the\n // capability back before dropping the record of it. A claim deleted while\n // the name is still on the reCAPTCHA key leaves an origin we no longer\n // serve holding a permanent right to mint App Check tokens against our site\n // key, with nothing left in Firestore that says why it is there — and it\n // silently spends one of the 250 slots forever.\n const allowlist = await reclaimConsoleOrigin(names[0])\n if (!allowlistSatisfied(allowlist.outcome)) {\n return {\n released: false,\n results,\n allowlist,\n error: `The domain is off Vercel but still on the App Check allowlist: ${allowlist.detail ?? allowlist.outcome}`,\n }\n }\n\n const batch = firestore().batch()\n for (const name of names) {\n batch.delete(firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(name))\n }\n await batch.commit()\n return { released: true, results, allowlist, error: null }\n}\n\n/**\n * Drop a claim that was never attached, without touching Vercel.\n *\n * The counterpart to claiming from the branding form: an org that clears or\n * changes `customConsoleDomain` must not leave its old reservation standing,\n * or it locks another org out of a name nobody is using. Deliberately refuses\n * once the claim has proved ownership or reached Vercel — releasing *that*\n * needs `releaseConsoleDomain`, because a claim dropped while the name is\n * still on the project is the unindexed-name hole in the header.\n */\nexport async function releasePendingConsoleDomain(options: {\n orgId: string\n domain: string\n}): Promise<boolean> {\n const orgId = String(options?.orgId ?? '')\n const domain = normalizeConsoleDomain(options?.domain)\n if (!orgId || !domain) return false\n const snapshot = await claimRef(domain).get()\n if (!snapshot.exists || snapshot.get('orgId') !== orgId) return false\n if (snapshot.get('status') !== 'pending') return false\n if (snapshot.get('vercelState') === 'attached') return false\n const names: string[] = Array.isArray(snapshot.get('names'))\n ? snapshot.get('names')\n : [domain]\n const batch = firestore().batch()\n for (const name of names) {\n batch.delete(firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(name))\n }\n await batch.commit()\n return true\n}\n\n/**\n * Why a host may — or may not — be served the console (AGL-1099c).\n *\n * `reason` is not decoration. `unknown` and `degraded` both mean \"serve it,\n * this gate has no opinion\", and they mean it for opposite causes; every other\n * value means \"refuse\". Collapsing them into a boolean is how a lookup outage\n * would come to read the same as a revoked entitlement.\n */\nexport type ConsoleDomainReason =\n | 'active'\n | 'unknown'\n | 'no-org'\n | 'not-entitled'\n | 'not-active'\n | 'degraded'\n\nexport interface ConsoleDomainVerdict {\n /** A claim exists for this exact host. */\n known: boolean\n /** The console may be served here, pinned to `orgSlug`. */\n servable: boolean\n /**\n * Workspace slug of the owning org — where a refused visitor is sent, and\n * the org the path is rewritten under when servable. Never the `orgId`: a\n * verdict is read by an unauthenticated route.\n */\n orgSlug: string | null\n reason: ConsoleDomainReason\n /** The lookup could not be completed. Honour it, never cache it. */\n degraded: boolean\n}\n\nconst UNKNOWN_VERDICT: ConsoleDomainVerdict = {\n known: false,\n servable: false,\n orgSlug: null,\n reason: 'unknown',\n degraded: false,\n}\n\nconst DEGRADED_VERDICT: ConsoleDomainVerdict = {\n known: false,\n servable: false,\n orgSlug: null,\n reason: 'degraded',\n degraded: true,\n}\n\n/**\n * Stop serving a domain whose org no longer holds `whiteLabel`, and make it\n * stick.\n *\n * **This is the fail-closed half of the entitlement, and it is a write on a\n * read path on purpose.** Nothing in the codebase reacts to a plan change —\n * the Stripe webhook writes `plan` and says outright that entitlements resolve\n * at read time, which is sufficient for rendering and insufficient for a\n * hostname (AGL-1353 D7). Rather than add a fan-out to the webhook or a cron\n * that has to be believed, the first request to arrive after a downgrade\n * converts the read-time verdict into stored state: `status: 'suspended'` plus\n * a `sessionEpoch` bump, across **every** name the claim covers, so the twin\n * cannot outlive its primary.\n *\n * The epoch is what makes this more than cosmetic. A refusal that only lives\n * in a verdict leaves already-minted cookies valid; bumping the epoch is the\n * lever that invalidates them at our boundary (AGL-1353 D6).\n *\n * Deliberately NOT the inverse: re-upgrading does not re-activate. Activation\n * attaches names to Vercel and — until AGL-1378 resolves — depends on a manual\n * App Check allowlist entry, so it stays an explicit act through\n * `activateConsoleDomain`, never a side effect of a plan read.\n *\n * Never throws: a suspension that fails to persist still refuses this request,\n * and the next one tries again.\n */\nasync function suspendOnDowngrade(\n domain: string,\n snapshot: FirebaseFirestore.DocumentSnapshot,\n): Promise<void> {\n const status = snapshot.get('status')\n if (status === 'suspended') return\n const names: string[] = Array.isArray(snapshot.get('names'))\n ? snapshot.get('names')\n : [domain]\n try {\n const batch = firestore().batch()\n for (const name of names) {\n batch.set(\n firestore().collection(CONSOLE_DOMAINS_COLLECTION).doc(name),\n {\n status: 'suspended',\n suspendedReason: 'entitlement',\n sessionEpoch: Date.now(),\n suspendedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n }\n await batch.commit()\n } catch (error) {\n console.error('[console-domains] suspend on downgrade failed', error)\n }\n}\n\n/**\n * Host → org, for the middleware gate and the session-route boundary.\n *\n * **One host pins exactly one org.** That is enforced by the document being\n * keyed on the host and claimed transactionally (see the header), not by\n * anything here — this function only ever reads the pin, and there is no input\n * by which a caller can ask for a different org.\n *\n * The three \"serve it anyway\" answers, and why each is right:\n *\n * - **`unknown`** — no claim on this host. localhost, preview deployments and\n * self-hosted installs all land here, and they must keep working. It is safe\n * because of the detach ordering `releaseConsoleDomain` enforces: Vercel\n * first, documents second, and the claim is kept if the detach fails. So a\n * name the console project still answers for always has a document, and a\n * name with no document cannot reach this deployment through the console\n * project at all (AGL-1430's correspondence — do not break it).\n * - **`degraded`** — Firestore could not be reached. Fails OPEN, matching the\n * workspace gate and for the reason AGL-1135 recorded: the Vercel domain\n * allowlist is the boundary, and a customer's console going dark because a\n * lookup timed out is worse than the residual exposure. Never cached.\n * - a claim that is `active` and entitled.\n *\n * Everything else refuses. In particular a `verified` claim is **not**\n * servable: until AGL-1378 clears, activation includes a manual App Check\n * allowlist entry, so \"ownership proved\" must never imply \"serve it\".\n */\nexport async function resolveConsoleDomain(\n host: string,\n): Promise<ConsoleDomainVerdict> {\n const domain = normalizeConsoleDomain(host)\n if (!domain) return UNKNOWN_VERDICT\n\n let snapshot: FirebaseFirestore.DocumentSnapshot\n try {\n snapshot = await claimRef(domain).get()\n } catch {\n return DEGRADED_VERDICT\n }\n if (!snapshot.exists) return UNKNOWN_VERDICT\n\n const orgId = String(snapshot.get('orgId') ?? '')\n if (!orgId) return { ...UNKNOWN_VERDICT, known: true, reason: 'no-org' }\n\n let orgSnapshot: FirebaseFirestore.DocumentSnapshot\n try {\n orgSnapshot = await firestore().collection('orgs').doc(orgId).get()\n } catch {\n return DEGRADED_VERDICT\n }\n // A claim pointing at an org that no longer exists refuses, but is NOT\n // suspended: `checkEntitlement(undefined)` resolves to the free plan, so\n // writing a suspension off a missing document would be recording an\n // entitlement verdict that was never actually read (the loading-default\n // class this repo keeps hitting). Refuse now, decide when there is data.\n if (!orgSnapshot.exists) {\n return { ...UNKNOWN_VERDICT, known: true, reason: 'no-org' }\n }\n\n const org = orgSnapshot.data() as Partial<AglynOrgBilling> & { slug?: string }\n const orgSlug = String(org?.slug ?? '') || null\n\n if (!checkEntitlement(org, 'whiteLabel')) {\n await suspendOnDowngrade(domain, snapshot)\n return { known: true, servable: false, orgSlug, reason: 'not-entitled', degraded: false }\n }\n if (snapshot.get('status') !== 'active') {\n return { known: true, servable: false, orgSlug, reason: 'not-active', degraded: false }\n }\n return { known: true, servable: true, orgSlug, reason: 'active', degraded: false }\n}\n\n/**\n * The org a console domain belongs to, or null.\n *\n * Read-only, and used today only to refuse a `customConsoleDomain` that another\n * org already holds. Routing reads `resolveConsoleDomain` instead, which asks\n * the entitlement question this one does not.\n */\nexport async function getConsoleDomainClaim(\n domain: string,\n): Promise<{ orgId: string; status: ConsoleDomainStatus } | null> {\n const normalized = normalizeConsoleDomain(domain)\n if (!normalized) return null\n const snapshot = await claimRef(normalized).get()\n if (!snapshot.exists) return null\n return {\n orgId: String(snapshot.get('orgId') ?? ''),\n status: (snapshot.get('status') as ConsoleDomainStatus) ?? 'pending',\n }\n}\n"],"names":["planLabelGrantingFeature","randomBytes","checkEntitlement","ENTERPRISE_PLAN_LABEL","firebaseAdmin","challengeValue","recordsProveOwnership","resolveChallengeTxt","SSO_CHALLENGE_PREFIX","allowConsoleOrigin","allowlistSatisfied","reclaimConsoleOrigin","attachProjectDomain","detachProjectDomain","pendingUploadCorsRemedy","normalizePlatformDomain","validatePlatformDomain","firestore","app","CONSOLE_DOMAINS_COLLECTION","normalizeConsoleDomain","validateConsoleDomain","input","invalid","reserved","consoleDomainNames","domain","primary","labels","split","length","ConsoleDomainTakenError","Error","name","claimRef","collection","doc","claimView","data","token","String","txtToken","names","Array","isArray","orgId","status","recordHost","recordValue","verified","lastRecords","undefined","CONSOLE_DOMAIN_PLAN_REQUIRED_COPY","orgIsEntitled","snapshot","get","exists","claimConsoleDomain","db","now","FieldValue","serverTimestamp","runTransaction","tx","existing","refs","map","snapshots","getAll","id","toString","forEach","index","set","primaryHost","role","vercelState","createdAt","updatedAt","merge","registerConsoleDomain","options","claim","error","thrown","verifyConsoleDomain","records","proved","slice","verifiedAt","view","activateConsoleDomain","allowlist","attachment","results","entries","push","redirectTo","attached","every","result","outcome","uploadCorsRemedy","detail","ready","appCheckState","activatedAt","sessionEpoch","Date","bumpConsoleSessionEpoch","batch","commit","console","releaseConsoleDomain","released","clear","delete","releasePendingConsoleDomain","UNKNOWN_VERDICT","known","servable","orgSlug","reason","degraded","DEGRADED_VERDICT","suspendOnDowngrade","suspendedReason","suspendedAt","resolveConsoleDomain","host","orgSnapshot","org","slug","getConsoleDomainClaim","normalized"],"mappings":";IAoPEA;AApPF;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2DC,GAED,SAASC,WAAW,QAAQ,SAAQ;AACpC,SAASC,gBAAgB,QAAQ,sBAAqB;AAEtD,SACEC,qBAAqB,EACrBH,wBAAwB,QACnB,2CAA0C;AACjD,OAAOI,mBAAmB,sBAAkB;AAC5C,SACEC,cAAc,EACdC,qBAAqB,EACrBC,mBAAmB,EACnBC,oBAAoB,QAEf,wBAAoB;AAC3B,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,oBAAoB,QAEf,2BAAuB;AAC9B,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,uBAAuB,QAElB,yBAAqB;AAC5B,6EAA6E;AAC7E,sDAAsD;AACtD,SACEC,uBAAuB,EACvBC,sBAAsB,QACjB,6BAAyB;AAEhC,MAAMC,YAAY,IAAMb,cAAcc,GAAG,GAAGD,SAAS;AAErD,yEAAyE,GACzE,OAAO,MAAME,6BAA6B,iBAAgB;AAE1D;;;;;CAKC,GACD,OAAO,MAAMC,yBAAyBL,wBAAuB;AAE7D;;;;;;;;;;;;CAYC,GACD,OAAO,SAASM,sBAAsBC,KAAa;IACjD,OAAON,uBAAuBM,OAAO;QACnCC,SAAS;QACTC,UAAU;IACZ;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,mBAAmBC,MAAc;IAC/C,MAAMC,UAAUP,uBAAuBM;IACvC,IAAI,CAACC,SAAS,OAAO,EAAE;IACvB,MAAMC,SAASD,QAAQE,KAAK,CAAC;IAC7B,IAAID,OAAOE,MAAM,KAAK,GAAG,OAAO;QAACH;KAA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OL,QAAOc,gBAAAA,SAASC,GAAG,CAAC,oBAAbD,gBAAyB;QACvCR,MAAM,GAAGQ,iBAAAA,SAASC,GAAG,CAAC,qBAAbD,iBAAkD;IAC7D;AACF"}
|
|
@@ -27,6 +27,11 @@
|
|
|
27
27
|
* the subscription goes live, the proposal and the trial comp both clear,
|
|
28
28
|
* so a comp granted to evaluate cannot revive free access if the customer
|
|
29
29
|
* later cancels.
|
|
30
|
+
*
|
|
31
|
+
* A workspace that already subscribes can be proposed a CHANGE (AGL-4160):
|
|
32
|
+
* another plan or billing cadence, usually with a code for the switch. That
|
|
33
|
+
* proposal is marked `forSubscriber` and settled only when the subscription
|
|
34
|
+
* moves to it, since a subscription being live is what it starts from.
|
|
30
35
|
*/
|
|
31
36
|
import type { AglynOrgBilling, OrgUpgradeProposal } from '@aglyn/aglyn/server';
|
|
32
37
|
/** The override reason a sales-evaluation comp is granted under. */
|
|
@@ -74,9 +79,10 @@ export interface ProposeOrgUpgradeResult {
|
|
|
74
79
|
* commit and is best-effort: the card on the org home is the proposal, and
|
|
75
80
|
* an email that failed must not undo it.
|
|
76
81
|
*
|
|
77
|
-
* Refused
|
|
78
|
-
*
|
|
79
|
-
*
|
|
82
|
+
* Refused for any plan a customer cannot buy themselves. A workspace with a
|
|
83
|
+
* live subscription can be proposed a change of plan or cadence (AGL-4160),
|
|
84
|
+
* stored as `forSubscriber`; a proposal of the plan and cadence it already
|
|
85
|
+
* has is refused, since there is nothing to propose.
|
|
80
86
|
*/
|
|
81
87
|
export declare function proposeOrgUpgrade(options: ProposeOrgUpgradeOptions): Promise<ProposeOrgUpgradeResult>;
|
|
82
88
|
/**
|
|
@@ -90,9 +96,20 @@ export declare function buildUpgradeProposal(options: Pick<ProposeOrgUpgradeOpti
|
|
|
90
96
|
/**
|
|
91
97
|
* Read the org a proposal is for, inside the caller's transaction, refusing
|
|
92
98
|
* an unknown workspace and one whose subscription is already live — the
|
|
93
|
-
* question a proposal asks is then already answered.
|
|
99
|
+
* question a proposal asks is then already answered. The owner hand-off,
|
|
100
|
+
* which proposes a first plan, reads through this.
|
|
94
101
|
*/
|
|
95
102
|
export declare function readUpgradeProposalTarget(tx: FirebaseFirestore.Transaction, orgRef: FirebaseFirestore.DocumentReference): Promise<Partial<AglynOrgBilling>>;
|
|
103
|
+
/**
|
|
104
|
+
* Read the org a proposal is for, and whether its subscription is live
|
|
105
|
+
* (AGL-4160). A live subscription takes a proposal that CHANGES it — another
|
|
106
|
+
* plan, or the cadence it is not billed on — and refuses one it already
|
|
107
|
+
* answers, or no proposal at all.
|
|
108
|
+
*/
|
|
109
|
+
export declare function readUpgradeProposalChange(tx: FirebaseFirestore.Transaction, orgRef: FirebaseFirestore.DocumentReference, proposal: Pick<OrgUpgradeProposal, 'plan' | 'interval'> | null): Promise<{
|
|
110
|
+
data: Partial<AglynOrgBilling>;
|
|
111
|
+
live: boolean;
|
|
112
|
+
}>;
|
|
96
113
|
/**
|
|
97
114
|
* Write the proposal and its audit row into the caller's transaction, so
|
|
98
115
|
* they commit with whatever else the caller writes (AGL-1784) — the owner
|
|
@@ -136,6 +153,13 @@ export declare function withdrawOrgUpgrade(options: {
|
|
|
136
153
|
export declare function settleSubscriptionStart(orgId: string, context: {
|
|
137
154
|
status: string;
|
|
138
155
|
subscriptionId?: string | null;
|
|
156
|
+
/**
|
|
157
|
+
* The plan and cadence the live subscription is on (AGL-4160). A
|
|
158
|
+
* proposal made to a subscriber is settled only by the subscription
|
|
159
|
+
* reaching it; absent, the org doc's `plan` stands in for the plan.
|
|
160
|
+
*/
|
|
161
|
+
plan?: string | null;
|
|
162
|
+
interval?: string | null;
|
|
139
163
|
}): Promise<{
|
|
140
164
|
proposalCleared: boolean;
|
|
141
165
|
trialCompRemoved: boolean;
|
|
@@ -26,10 +26,15 @@
|
|
|
26
26
|
* the subscription goes live, the proposal and the trial comp both clear,
|
|
27
27
|
* so a comp granted to evaluate cannot revive free access if the customer
|
|
28
28
|
* later cancels.
|
|
29
|
+
*
|
|
30
|
+
* A workspace that already subscribes can be proposed a CHANGE (AGL-4160):
|
|
31
|
+
* another plan or billing cadence, usually with a code for the switch. That
|
|
32
|
+
* proposal is marked `forSubscriber` and settled only when the subscription
|
|
33
|
+
* moves to it, since a subscription being live is what it starts from.
|
|
29
34
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
30
35
|
import { PLAN_LABELS } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
31
36
|
import { PLATFORM_BRAND_NAME } from "@aglyn/aglyn/app-utils/platform-brand";
|
|
32
|
-
import { isUpgradeProposalPlan, normalizeUpgradeProposalBundle, normalizeUpgradeProposalNote, upgradeProposalDestination, upgradeProposalSummary } from "@aglyn/aglyn/app-utils/upgrade-proposal";
|
|
37
|
+
import { isUpgradeProposalPlan, normalizeUpgradeProposalBundle, normalizeUpgradeProposalNote, upgradeProposalAnsweredBy, upgradeProposalDestination, upgradeProposalSummary } from "@aglyn/aglyn/app-utils/upgrade-proposal";
|
|
33
38
|
// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).
|
|
34
39
|
import { isLiveSubscriptionStatus, ORG_BILLING_DOC_ID, ORG_BILLING_SUBCOLLECTION } from "@aglyn/aglyn/app-utils/org-billing-doc";
|
|
35
40
|
import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
|
|
@@ -56,23 +61,30 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
56
61
|
* commit and is best-effort: the card on the org home is the proposal, and
|
|
57
62
|
* an email that failed must not undo it.
|
|
58
63
|
*
|
|
59
|
-
* Refused
|
|
60
|
-
*
|
|
61
|
-
*
|
|
64
|
+
* Refused for any plan a customer cannot buy themselves. A workspace with a
|
|
65
|
+
* live subscription can be proposed a change of plan or cadence (AGL-4160),
|
|
66
|
+
* stored as `forSubscriber`; a proposal of the plan and cadence it already
|
|
67
|
+
* has is refused, since there is nothing to propose.
|
|
62
68
|
*/ export async function proposeOrgUpgrade(options) {
|
|
63
69
|
const { orgId, actor, origin } = options;
|
|
64
|
-
const
|
|
70
|
+
const built = buildUpgradeProposal(options);
|
|
65
71
|
const db = firestore();
|
|
66
72
|
const orgRef = db.collection('orgs').doc(orgId);
|
|
67
|
-
const org = await db.runTransaction(async (tx)=>{
|
|
68
|
-
const
|
|
73
|
+
const { org, proposal } = await db.runTransaction(async (tx)=>{
|
|
74
|
+
const target = await readUpgradeProposalChange(tx, orgRef, built);
|
|
75
|
+
const staged = target.live ? _extends({}, built, {
|
|
76
|
+
forSubscriber: true
|
|
77
|
+
}) : built;
|
|
69
78
|
stageUpgradeProposal(tx, db, {
|
|
70
79
|
orgId,
|
|
71
|
-
proposal,
|
|
72
|
-
before: data,
|
|
80
|
+
proposal: staged,
|
|
81
|
+
before: target.data,
|
|
73
82
|
actorUid: actor.uid
|
|
74
83
|
});
|
|
75
|
-
return
|
|
84
|
+
return {
|
|
85
|
+
org: target.data,
|
|
86
|
+
proposal: staged
|
|
87
|
+
};
|
|
76
88
|
});
|
|
77
89
|
await recordUpgradeProposalActivity(orgId, actor, proposal);
|
|
78
90
|
const emailed = await emailUpgradeProposal({
|
|
@@ -111,19 +123,43 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
111
123
|
/**
|
|
112
124
|
* Read the org a proposal is for, inside the caller's transaction, refusing
|
|
113
125
|
* an unknown workspace and one whose subscription is already live — the
|
|
114
|
-
* question a proposal asks is then already answered.
|
|
126
|
+
* question a proposal asks is then already answered. The owner hand-off,
|
|
127
|
+
* which proposes a first plan, reads through this.
|
|
115
128
|
*/ export async function readUpgradeProposalTarget(tx, orgRef) {
|
|
129
|
+
const target = await readUpgradeProposalChange(tx, orgRef, null);
|
|
130
|
+
return target.data;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Read the org a proposal is for, and whether its subscription is live
|
|
134
|
+
* (AGL-4160). A live subscription takes a proposal that CHANGES it — another
|
|
135
|
+
* plan, or the cadence it is not billed on — and refuses one it already
|
|
136
|
+
* answers, or no proposal at all.
|
|
137
|
+
*/ export async function readUpgradeProposalChange(tx, orgRef, proposal) {
|
|
116
138
|
var _ref;
|
|
117
|
-
var _billing_get;
|
|
118
139
|
const snapshot = await tx.get(orgRef);
|
|
119
140
|
if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404);
|
|
120
141
|
const data = snapshot.data();
|
|
121
142
|
const billing = await tx.get(orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID));
|
|
122
|
-
const
|
|
123
|
-
|
|
143
|
+
const subscription = billing.get('subscription');
|
|
144
|
+
const status = (_ref = subscription == null ? void 0 : subscription.status) != null ? _ref : data.billingStatus;
|
|
145
|
+
if (!isLiveSubscriptionStatus(status)) return {
|
|
146
|
+
data,
|
|
147
|
+
live: false
|
|
148
|
+
};
|
|
149
|
+
if (!proposal) {
|
|
124
150
|
throw new UpgradeProposalError('This workspace already has a live subscription, so there is nothing to propose', 409);
|
|
125
151
|
}
|
|
126
|
-
|
|
152
|
+
if (upgradeProposalAnsweredBy(proposal, {
|
|
153
|
+
plan: data.plan,
|
|
154
|
+
interval: subscription == null ? void 0 : subscription.interval
|
|
155
|
+
})) {
|
|
156
|
+
const cadence = (subscription == null ? void 0 : subscription.interval) === 'year' ? ', billed yearly' : (subscription == null ? void 0 : subscription.interval) === 'month' ? ', billed monthly' : '';
|
|
157
|
+
throw new UpgradeProposalError(`This workspace already subscribes to ${planName(data.plan)}${cadence}, so there is ` + 'nothing to propose. Propose another plan or billing cadence.', 409);
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
data,
|
|
161
|
+
live: true
|
|
162
|
+
};
|
|
127
163
|
}
|
|
128
164
|
/**
|
|
129
165
|
* Write the proposal and its audit row into the caller's transaction, so
|
|
@@ -227,11 +263,17 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
227
263
|
const db = firestore();
|
|
228
264
|
const orgRef = db.collection('orgs').doc(orgId);
|
|
229
265
|
const outcome = await db.runTransaction(async (tx)=>{
|
|
230
|
-
var _data_upgradeProposal, _data_entitlements;
|
|
266
|
+
var _data_upgradeProposal, _context_plan, _data_entitlements;
|
|
231
267
|
const snapshot = await tx.get(orgRef);
|
|
232
268
|
if (!snapshot.exists) return null;
|
|
233
269
|
const data = snapshot.data();
|
|
234
|
-
const
|
|
270
|
+
const stored = (_data_upgradeProposal = data.upgradeProposal) != null ? _data_upgradeProposal : null;
|
|
271
|
+
// A change proposed to a subscriber stands until the subscription is on
|
|
272
|
+
// it: being live is where it started, so it settles nothing.
|
|
273
|
+
const proposal = (stored == null ? void 0 : stored.forSubscriber) === true && !upgradeProposalAnsweredBy(stored, {
|
|
274
|
+
plan: (_context_plan = context.plan) != null ? _context_plan : data.plan,
|
|
275
|
+
interval: context.interval
|
|
276
|
+
}) ? null : stored;
|
|
235
277
|
const entitlements = (_data_entitlements = data.entitlements) != null ? _data_entitlements : null;
|
|
236
278
|
const comp = entitlements == null ? void 0 : entitlements['planComp'];
|
|
237
279
|
const trialComp = (comp == null ? void 0 : comp.reason) === TRIAL_PLAN_COMP_REASON ? comp : null;
|
|
@@ -258,7 +300,7 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
258
300
|
target: `orgs/${orgId}`,
|
|
259
301
|
reason: {
|
|
260
302
|
code: 'subscription_live',
|
|
261
|
-
note: `The subscription went live (${context.status})` + (context.subscriptionId ? `, ${context.subscriptionId}` : '') + ', which settles the upgrade proposal and ends the sales-trial comp.'
|
|
303
|
+
note: ((proposal == null ? void 0 : proposal.forSubscriber) ? `The subscription moved to the proposed plan (${context.status})` : `The subscription went live (${context.status})`) + (context.subscriptionId ? `, ${context.subscriptionId}` : '') + ', which settles the upgrade proposal and ends the sales-trial comp.'
|
|
262
304
|
},
|
|
263
305
|
before: {
|
|
264
306
|
upgradeProposal: proposal,
|
|
@@ -285,7 +327,7 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
285
327
|
if (outcome.proposal) {
|
|
286
328
|
await logOrgActivity(orgId, {
|
|
287
329
|
uid: null
|
|
288
|
-
}, `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live
|
|
330
|
+
}, `The ${planName(outcome.proposal.plan)} plan proposal closed — ` + (outcome.proposal.forSubscriber ? 'the subscription moved to it' : 'the subscription is live'), {
|
|
289
331
|
type: 'subscription',
|
|
290
332
|
id: orgId
|
|
291
333
|
});
|
|
@@ -322,15 +364,21 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
322
364
|
const summary = upgradeProposalSummary(proposal, {
|
|
323
365
|
brand: productName
|
|
324
366
|
});
|
|
367
|
+
// A workspace that already subscribes switches; one that does not starts
|
|
368
|
+
// a subscription (AGL-4160).
|
|
369
|
+
const nextStep = proposal.forSubscriber ? 'When you are ready, switch to it from Billing. The plan is already selected ' + 'there, and Billing shows what the switch costs today, with any code applied, ' + 'before anything is charged.' : 'When you are ready, start the subscription from Billing. The plan is already ' + 'selected there, beside the others so you can compare them first.';
|
|
370
|
+
const unchanged = proposal.forSubscriber ? 'Nothing changes until you switch.' : 'Nothing changes until you start the subscription.';
|
|
325
371
|
const content = await renderSystemEmailContent('org-upgrade-proposal', {
|
|
326
372
|
'org.name': orgName,
|
|
327
373
|
'plan.name': label,
|
|
328
374
|
'proposal.note': (_proposal_note = proposal.note) != null ? _proposal_note : '',
|
|
329
375
|
'proposal.summary': summary === label ? '' : summary,
|
|
376
|
+
'proposal.nextStep': nextStep,
|
|
377
|
+
'proposal.unchanged': unchanged,
|
|
330
378
|
billingUrl
|
|
331
379
|
}, brand, {
|
|
332
380
|
subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,
|
|
333
|
-
text: `Your ${productName} team proposed moving ${orgName} to the ${label} ` + (summary === label ? 'plan. ' : `plan (${summary}). `) + 'When you are ready, start the subscription from Billing, ' + `where the plan is already selected:\n\n${billingUrl}` + (proposal.note ? `\n\n${proposal.note}` : '')
|
|
381
|
+
text: `Your ${productName} team proposed moving ${orgName} to the ${label} ` + (summary === label ? 'plan. ' : `plan (${summary}). `) + (proposal.forSubscriber ? 'When you are ready, switch to it from Billing, ' : 'When you are ready, start the subscription from Billing, ') + `where the plan is already selected:\n\n${billingUrl}` + (proposal.note ? `\n\n${proposal.note}` : '')
|
|
334
382
|
});
|
|
335
383
|
const result = await sendEmail(_extends({
|
|
336
384
|
to,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upgrade-proposal.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 * The platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n normalizeUpgradeProposalNote,\n upgradeProposalDestination,\n upgradeProposalSummary,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /**\n * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any\n * shape `parseBundleAddons` reads; fitted to the plan before storing.\n */\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /**\n * A retired Aglyn AI tier (AGL-4025). Credits are sold by the block since\n * AGL-4144 (`ai:<blocks>` in `addons`), so a proposal naming a tier is\n * refused rather than stored with a price nobody sells.\n */\n aiTier?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused when the workspace already has a live subscription — the question\n * a proposal asks is already answered — and for any plan a customer cannot\n * buy themselves.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n const proposal = buildUpgradeProposal(options)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const org = await db.runTransaction(async (tx) => {\n const data = await readUpgradeProposalTarget(tx, orgRef)\n stageUpgradeProposal(tx, db, { orgId, proposal, before: data, actorUid: actor.uid })\n return data\n })\n await recordUpgradeProposalActivity(orgId, actor, proposal)\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/**\n * The proposal as it will be stored, or the refusal: a plan the workspace\n * can buy itself, a bounded note, and the bundle fitted to the plan\n * (AGL-3956). Nothing is read or written.\n */\nexport function buildUpgradeProposal(\n options: Pick<\n ProposeOrgUpgradeOptions,\n 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'aiTier' | 'actor'\n > & {\n now?: number\n },\n): OrgUpgradeProposal {\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n if (options.aiTier != null) {\n throw new UpgradeProposalError(\n 'AI tiers were replaced by AI credit blocks. Propose a number of blocks instead.',\n )\n }\n const note = normalizeUpgradeProposalNote(options.note)\n return {\n plan,\n proposedBy: options.actor.uid,\n proposedAt: options.now ?? Date.now(),\n ...(note ? { note } : {}),\n ...normalizeUpgradeProposalBundle(plan, options),\n }\n}\n\n/**\n * Read the org a proposal is for, inside the caller's transaction, refusing\n * an unknown workspace and one whose subscription is already live — the\n * question a proposal asks is then already answered.\n */\nexport async function readUpgradeProposalTarget(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Partial<AglynOrgBilling>> {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const status =\n (billing.get('subscription') as { status?: unknown } | undefined)?.status ??\n data.billingStatus\n if (isLiveSubscriptionStatus(status)) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n return data\n}\n\n/**\n * Write the proposal and its audit row into the caller's transaction, so\n * they commit with whatever else the caller writes (AGL-1784) — the owner\n * invitation, for a hand-off that proposes in the same act (AGL-3956).\n */\nexport function stageUpgradeProposal(\n tx: FirebaseFirestore.Transaction,\n db: FirebaseFirestore.Firestore,\n options: {\n orgId: string\n proposal: OrgUpgradeProposal\n before: Partial<AglynOrgBilling>\n actorUid: string\n },\n): void {\n const { orgId, proposal, before, actorUid } = options\n tx.set(\n db.collection('orgs').doc(orgId),\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: before.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n}\n\n/** \"Proposed the Starter plan\", naming the bundle when there is one. */\nexport function proposalActivityLine(proposal: OrgUpgradeProposal): string {\n const label = planName(proposal.plan)\n const summary = upgradeProposalSummary(proposal)\n return summary === label\n ? `Proposed the ${label} plan`\n : `Proposed the ${label} plan (${summary})`\n}\n\n/** The workspace's feed line for a proposal, after it commits. */\nexport async function recordUpgradeProposalActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n proposal: OrgUpgradeProposal,\n): Promise<void> {\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n proposalActivityLine(proposal),\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: { status: string; subscriptionId?: string | null },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const proposal = data.upgradeProposal ?? null\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n `The subscription went live (${context.status})` +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const summary = upgradeProposalSummary(proposal, { brand: productName })\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n 'proposal.summary': summary === label ? '' : summary,\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n (summary === label ? 'plan. ' : `plan (${summary}). `) +\n 'When you are ready, start the subscription from Billing, ' +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","normalizeUpgradeProposalNote","upgradeProposalDestination","upgradeProposalSummary","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","orgId","actor","origin","proposal","buildUpgradeProposal","db","orgRef","collection","doc","org","runTransaction","tx","data","readUpgradeProposalTarget","stageUpgradeProposal","before","actorUid","uid","recordUpgradeProposalActivity","emailed","emailUpgradeProposal","plan","aiTier","note","proposedBy","proposedAt","now","Date","billing","snapshot","get","exists","billingStatus","set","upgradeProposal","updatedAt","serverTimestamp","merge","action","target","after","at","proposalActivityLine","label","planName","summary","email","type","id","staffActorId","withdrawOrgUpgrade","withdrawn","stored","delete","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","productName","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAOD,SAASA,WAAW,QAAQ,2CAA0C;AACtE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,sBAAsB,QACjB,0CAAyC;AAChD,wEAAwE;AACxE,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,QACpB,yCAAwC;AAC/C,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AACnD,SAASC,aAAa,QAAQ,sBAAkB;AAChD,OAAO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src/lib/server/upgrade-proposal.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 * The platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n *\n * A workspace that already subscribes can be proposed a CHANGE (AGL-4160):\n * another plan or billing cadence, usually with a code for the switch. That\n * proposal is marked `forSubscriber` and settled only when the subscription\n * moves to it, since a subscription being live is what it starts from.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n normalizeUpgradeProposalNote,\n upgradeProposalAnsweredBy,\n upgradeProposalDestination,\n upgradeProposalSummary,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /**\n * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any\n * shape `parseBundleAddons` reads; fitted to the plan before storing.\n */\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /**\n * A retired Aglyn AI tier (AGL-4025). Credits are sold by the block since\n * AGL-4144 (`ai:<blocks>` in `addons`), so a proposal naming a tier is\n * refused rather than stored with a price nobody sells.\n */\n aiTier?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused for any plan a customer cannot buy themselves. A workspace with a\n * live subscription can be proposed a change of plan or cadence (AGL-4160),\n * stored as `forSubscriber`; a proposal of the plan and cadence it already\n * has is refused, since there is nothing to propose.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n const built = buildUpgradeProposal(options)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const { org, proposal } = await db.runTransaction(async (tx) => {\n const target = await readUpgradeProposalChange(tx, orgRef, built)\n const staged: OrgUpgradeProposal = target.live ? { ...built, forSubscriber: true } : built\n stageUpgradeProposal(tx, db, {\n orgId,\n proposal: staged,\n before: target.data,\n actorUid: actor.uid,\n })\n return { org: target.data, proposal: staged }\n })\n await recordUpgradeProposalActivity(orgId, actor, proposal)\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/**\n * The proposal as it will be stored, or the refusal: a plan the workspace\n * can buy itself, a bounded note, and the bundle fitted to the plan\n * (AGL-3956). Nothing is read or written.\n */\nexport function buildUpgradeProposal(\n options: Pick<\n ProposeOrgUpgradeOptions,\n 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'aiTier' | 'actor'\n > & {\n now?: number\n },\n): OrgUpgradeProposal {\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n if (options.aiTier != null) {\n throw new UpgradeProposalError(\n 'AI tiers were replaced by AI credit blocks. Propose a number of blocks instead.',\n )\n }\n const note = normalizeUpgradeProposalNote(options.note)\n return {\n plan,\n proposedBy: options.actor.uid,\n proposedAt: options.now ?? Date.now(),\n ...(note ? { note } : {}),\n ...normalizeUpgradeProposalBundle(plan, options),\n }\n}\n\n/**\n * Read the org a proposal is for, inside the caller's transaction, refusing\n * an unknown workspace and one whose subscription is already live — the\n * question a proposal asks is then already answered. The owner hand-off,\n * which proposes a first plan, reads through this.\n */\nexport async function readUpgradeProposalTarget(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Partial<AglynOrgBilling>> {\n const target = await readUpgradeProposalChange(tx, orgRef, null)\n return target.data\n}\n\n/**\n * Read the org a proposal is for, and whether its subscription is live\n * (AGL-4160). A live subscription takes a proposal that CHANGES it — another\n * plan, or the cadence it is not billed on — and refuses one it already\n * answers, or no proposal at all.\n */\nexport async function readUpgradeProposalChange(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n proposal: Pick<OrgUpgradeProposal, 'plan' | 'interval'> | null,\n): Promise<{ data: Partial<AglynOrgBilling>; live: boolean }> {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const subscription = billing.get('subscription') as\n | { status?: unknown; interval?: unknown }\n | undefined\n const status = subscription?.status ?? data.billingStatus\n if (!isLiveSubscriptionStatus(status)) return { data, live: false }\n if (!proposal) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n if (upgradeProposalAnsweredBy(proposal, { plan: data.plan, interval: subscription?.interval })) {\n const cadence =\n subscription?.interval === 'year'\n ? ', billed yearly'\n : subscription?.interval === 'month'\n ? ', billed monthly'\n : ''\n throw new UpgradeProposalError(\n `This workspace already subscribes to ${planName(data.plan)}${cadence}, so there is ` +\n 'nothing to propose. Propose another plan or billing cadence.',\n 409,\n )\n }\n return { data, live: true }\n}\n\n/**\n * Write the proposal and its audit row into the caller's transaction, so\n * they commit with whatever else the caller writes (AGL-1784) — the owner\n * invitation, for a hand-off that proposes in the same act (AGL-3956).\n */\nexport function stageUpgradeProposal(\n tx: FirebaseFirestore.Transaction,\n db: FirebaseFirestore.Firestore,\n options: {\n orgId: string\n proposal: OrgUpgradeProposal\n before: Partial<AglynOrgBilling>\n actorUid: string\n },\n): void {\n const { orgId, proposal, before, actorUid } = options\n tx.set(\n db.collection('orgs').doc(orgId),\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: before.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n}\n\n/** \"Proposed the Starter plan\", naming the bundle when there is one. */\nexport function proposalActivityLine(proposal: OrgUpgradeProposal): string {\n const label = planName(proposal.plan)\n const summary = upgradeProposalSummary(proposal)\n return summary === label\n ? `Proposed the ${label} plan`\n : `Proposed the ${label} plan (${summary})`\n}\n\n/** The workspace's feed line for a proposal, after it commits. */\nexport async function recordUpgradeProposalActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n proposal: OrgUpgradeProposal,\n): Promise<void> {\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n proposalActivityLine(proposal),\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: {\n status: string\n subscriptionId?: string | null\n /**\n * The plan and cadence the live subscription is on (AGL-4160). A\n * proposal made to a subscriber is settled only by the subscription\n * reaching it; absent, the org doc's `plan` stands in for the plan.\n */\n plan?: string | null\n interval?: string | null\n },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const stored = data.upgradeProposal ?? null\n // A change proposed to a subscriber stands until the subscription is on\n // it: being live is where it started, so it settles nothing.\n const proposal =\n stored?.forSubscriber === true &&\n !upgradeProposalAnsweredBy(stored, {\n plan: context.plan ?? data.plan,\n interval: context.interval,\n })\n ? null\n : stored\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n (proposal?.forSubscriber\n ? `The subscription moved to the proposed plan (${context.status})`\n : `The subscription went live (${context.status})`) +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — ` +\n (outcome.proposal.forSubscriber\n ? 'the subscription moved to it'\n : 'the subscription is live'),\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const summary = upgradeProposalSummary(proposal, { brand: productName })\n // A workspace that already subscribes switches; one that does not starts\n // a subscription (AGL-4160).\n const nextStep = proposal.forSubscriber\n ? 'When you are ready, switch to it from Billing. The plan is already selected ' +\n 'there, and Billing shows what the switch costs today, with any code applied, ' +\n 'before anything is charged.'\n : 'When you are ready, start the subscription from Billing. The plan is already ' +\n 'selected there, beside the others so you can compare them first.'\n const unchanged = proposal.forSubscriber\n ? 'Nothing changes until you switch.'\n : 'Nothing changes until you start the subscription.'\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n 'proposal.summary': summary === label ? '' : summary,\n 'proposal.nextStep': nextStep,\n 'proposal.unchanged': unchanged,\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n (summary === label ? 'plan. ' : `plan (${summary}). `) +\n (proposal.forSubscriber\n ? 'When you are ready, switch to it from Billing, '\n : 'When you are ready, start the subscription from Billing, ') +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","normalizeUpgradeProposalNote","upgradeProposalAnsweredBy","upgradeProposalDestination","upgradeProposalSummary","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","orgId","actor","origin","built","buildUpgradeProposal","db","orgRef","collection","doc","org","proposal","runTransaction","tx","target","readUpgradeProposalChange","staged","live","forSubscriber","stageUpgradeProposal","before","data","actorUid","uid","recordUpgradeProposalActivity","emailed","emailUpgradeProposal","plan","aiTier","note","proposedBy","proposedAt","now","Date","readUpgradeProposalTarget","snapshot","get","exists","billing","subscription","billingStatus","interval","cadence","planName","set","upgradeProposal","updatedAt","serverTimestamp","merge","action","after","at","proposalActivityLine","label","summary","email","type","id","staffActorId","withdrawOrgUpgrade","withdrawn","stored","delete","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","productName","nextStep","unchanged","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;CAkBC;AAOD,SAASA,WAAW,QAAQ,2CAA0C;AACtE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,yBAAyB,EAC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