@aglyn/tenant-data-admin 1.8.0 → 1.9.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/bundle-links.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 * A STAFF-MINTED BUNDLE CHECKOUT LINK (AGL-3955).\n *\n * At a booth or on a doorstep, a staff member who built the owner's site\n * shows a QR; the owner scans it on their own phone and lands on Billing with\n * the plan, the add-ons, the cadence and the coupon already chosen, one tap\n * from paid. The link itself is an ordinary Billing URL — the query the\n * marketing CTAs and the upgrade proposal already speak — so it works without\n * any record at all.\n *\n * The RECORD is for two things the URL cannot carry honestly:\n *\n * - the chosen domain and its price, which the Billing page shows as a line\n * of its own and the owner then buys on the site's Custom Domain page. Read\n * from the record, never from the URL, so an edited link cannot show a name\n * or a price nobody quoted.\n * - the staff accountability that lets the link stand in for the domains\n * plugin's 72-hour paid-invoice gate, once (Zach, 2026-10-19). A staff\n * member met the owner and is named on the `billing.bundle-link-minted`\n * audit row; the link is for one workspace, lives 24 hours and is spent by\n * the first purchase it pre-clears. The plugin asks through\n * `core.purchase-gate-preclearance` and never reads this collection.\n *\n * Documents live in the top-level `bundleLinks` collection, keyed by an\n * unguessable id and carrying the workspace. Only the Admin SDK reads or\n * writes them; the rules deny every client, staff included.\n */\n\nimport type { AiTierId, OrgPlan } from '@aglyn/aglyn/server'\nimport {\n fitBundleAddonsToPlan,\n normalizeBundleDomain,\n parseBundleAddons,\n type AddonKind,\n type BundleAddons,\n} from '@aglyn/aglyn/app-utils/bundle-intent'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { onboardingDestination } from '@aglyn/aglyn/app-utils/onboarding-deep-link'\nimport { isAiTierId } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n upgradeProposalIntent,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport type {\n PurchaseGatePreclearance,\n PurchaseGatePreclearanceInput,\n} from '@aglyn/aglyn/plugin-manager/purchase-gate-preclearance'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport firebaseAdmin from './firebase-admin'\n\nexport const BUNDLE_LINKS_COLLECTION = 'bundleLinks'\n\n/** How long a link pre-clears, from its minting. */\nexport const BUNDLE_LINK_TTL_MS = 24 * 60 * 60 * 1000\n\n/** The query param that names the record, on a link that carries a domain. */\nexport const BUNDLE_LINK_PARAM = 'bundle'\n\n/** The audit action every mint writes, with the staff member's uid. */\nexport const BUNDLE_LINK_AUDIT_ACTION = 'billing.bundle-link-minted'\n\n/** The most a quoted domain may cost a year, in cents, before it reads as a typo. */\nconst DOMAIN_PRICE_MAX_CENTS = 100_000\n\n/** Whether this deployment sells domains: the registrar the domains plugin buys through. */\nexport function domainsRegistrarConfigured(): boolean {\n return Boolean(String(process.env['DOMAINS_REGISTRAR'] ?? '').trim())\n}\n\nexport interface BundleLinkDomain {\n /** The registrable name, lower-cased. */\n name: string\n /** The registrar's first-year price when the link was minted, in cents. */\n firstYearCents: number\n /** The yearly renewal price, in cents. */\n renewalCents: number\n /** The site the name is for: where the owner lands to buy it. */\n hostId: string\n}\n\nexport interface BundleLinkDoc {\n /** The staff member accountable for the link. */\n mintedBy: string\n mintedByEmail: string | null\n /** The one workspace the link is for. */\n workspaceId: string\n createdAt: number\n expiresAt: number\n /** When a purchase spent the link's preclearance; null until then. */\n usedAt: number | null\n /** Which gate the purchase that spent it waived. */\n usedFor?: string\n /** A staff-minted link stands in for the domains plugin's invoice-age gate, once. */\n preclearsDomainGate: true\n intent: {\n plan: OrgPlan\n addons?: BundleAddons\n interval?: 'month' | 'year'\n coupon?: string\n /** The Aglyn AI tier an `ai:<tier>` entry named (AGL-3965). */\n aiTier?: AiTierId\n }\n domain?: BundleLinkDomain\n}\n\n/** A mint refused before anything was written. */\nexport class BundleLinkError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'BundleLinkError'\n this.status = status\n }\n}\n\nexport interface MintBundleLinkOptions {\n orgId: string\n /** The staff member minting it. */\n actor: { uid: string; email?: string | null }\n /** The console origin the link is built on. */\n origin: string\n plan: unknown\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /**\n * The Aglyn AI tier staff chose (AGL-4025), kept with the AI add-on; an\n * `ai:<tier>` entry in `addons` names one too, and this wins when both do.\n */\n aiTier?: unknown\n /** The chosen domain, quoted from the registrar's search; optional. */\n domain?: {\n name?: unknown\n firstYearCents?: unknown\n renewalCents?: unknown\n hostId?: unknown\n } | null\n /** Clock seam. */\n now?: number\n}\n\nexport interface MintedBundleLink {\n id: string\n url: string\n expiresAt: number\n intent: BundleLinkDoc['intent']\n domain: BundleLinkDomain | null\n /** Add-ons asked for that the plan does not sell, left off the link. */\n droppedAddons: Array<AddonKind | string>\n}\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nfunction cents(value: unknown): number | null {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 && number <= DOMAIN_PRICE_MAX_CENTS ? number : null\n}\n\n/**\n * Mint a link for one workspace: validate the bundle the way the proposal\n * does, write the record and its audit row in one batch, and answer the URL.\n *\n * Refused for a plan the workspace cannot buy itself, for a workspace with a\n * live subscription (checkout would refuse it; plan changes are Billing's),\n * and for a domain on a deployment that does not sell domains, for a site\n * outside the workspace, or without a price.\n */\nexport async function mintBundleLink(options: MintBundleLinkOptions): Promise<MintedBundleLink> {\n const { orgId, actor, origin } = options\n const now = options.now ?? Date.now()\n if (!orgId) throw new BundleLinkError('Missing orgId')\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new BundleLinkError('Choose a paid plan the workspace can buy itself')\n }\n const plan: OrgPlan = options.plan\n const parsed = parseBundleAddons(options.addons)\n const fitted = fitBundleAddonsToPlan(parsed.addons, plan)\n const bundle = normalizeUpgradeProposalBundle(plan, {\n addons: fitted.addons,\n interval: options.interval,\n coupon: options.coupon,\n // The tier staff chose (AGL-4025), or the one an `ai:<tier>` entry named\n // (AGL-3965), kept with the AI add-on.\n aiTier: isAiTierId(options.aiTier) ? options.aiTier : parsed.aiTier,\n })\n const intent: BundleLinkDoc['intent'] = { plan, ...bundle }\n\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const [orgSnapshot, billingSnapshot] = await Promise.all([\n orgRef.get(),\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID).get(),\n ])\n if (!orgSnapshot.exists) throw new BundleLinkError('Unknown organization', 404)\n const slug = orgSnapshot.get('slug')\n if (typeof slug !== 'string' || !slug) {\n throw new BundleLinkError('This workspace has no address yet, so no link can point at it', 409)\n }\n const status =\n (billingSnapshot.get('subscription') as { status?: unknown } | undefined)?.status ??\n orgSnapshot.get('billingStatus')\n if (isLiveSubscriptionStatus(status)) {\n throw new BundleLinkError(\n 'This workspace already has a live subscription; change its plan from Billing instead',\n 409,\n )\n }\n\n let domain: BundleLinkDomain | null = null\n if (options.domain && options.domain.name) {\n if (!domainsRegistrarConfigured()) {\n throw new BundleLinkError('Buying a domain is not available on this deployment yet', 409)\n }\n const name = normalizeBundleDomain(options.domain.name)\n if (!name) throw new BundleLinkError('That is not a domain name')\n const firstYearCents = cents(options.domain.firstYearCents)\n const renewalCents = cents(options.domain.renewalCents)\n if (firstYearCents === null || renewalCents === null) {\n throw new BundleLinkError('Quote the domain’s first-year and renewal prices from its search')\n }\n const hostId = String(options.domain.hostId ?? '').trim()\n const host = hostId ? await db.collection('hosts').doc(hostId).get() : null\n if (!host?.exists || host.get('orgId') !== orgId) {\n throw new BundleLinkError('Choose the site in this workspace the domain is for')\n }\n domain = { name, firstYearCents, renewalCents, hostId }\n }\n\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(createResourceUid())\n const doc: BundleLinkDoc = {\n mintedBy: actor.uid,\n mintedByEmail: actor.email ?? null,\n workspaceId: orgId,\n createdAt: now,\n expiresAt: now + BUNDLE_LINK_TTL_MS,\n usedAt: null,\n preclearsDomainGate: true,\n intent,\n ...(domain ? { domain } : {}),\n }\n const batch = db.batch()\n batch.set(ref, doc)\n setAdminAudit(batch, db, {\n actorUid: actor.uid,\n ...(actor.email ? { actorEmail: actor.email } : {}),\n action: BUNDLE_LINK_AUDIT_ACTION,\n target: `orgs/${orgId}`,\n after: {\n bundleLinkId: ref.id,\n intent,\n domain,\n expiresAt: doc.expiresAt,\n preclearsDomainGate: true,\n },\n at: FieldValue.serverTimestamp(),\n })\n await batch.commit()\n\n const path = onboardingDestination(slug, upgradeProposalIntent(intent))\n const url = `${origin}${path}${domain ? `&${BUNDLE_LINK_PARAM}=${ref.id}` : ''}`\n return {\n id: ref.id,\n url,\n expiresAt: doc.expiresAt,\n intent,\n domain,\n droppedAddons: [...parsed.dropped, ...fitted.notSold],\n }\n}\n\n/** Whether a stored link still pre-clears: unused, unexpired, and flagged. */\nexport function bundleLinkIsLive(doc: Partial<BundleLinkDoc> | undefined, now: number): boolean {\n return (\n !!doc &&\n doc.preclearsDomainGate === true &&\n (doc.usedAt === null || doc.usedAt === undefined) &&\n typeof doc.expiresAt === 'number' &&\n doc.expiresAt > now\n )\n}\n\n/**\n * The workspace's live link, or null. Read by the workspace alone (a\n * single-field equality, no composite index) and narrowed here: a workspace\n * holds a handful of links at most, each gone in a day.\n */\nasync function liveLinkFor(orgId: string, now: number): Promise<{ id: string } | null> {\n const snapshot = await firestore()\n .collection(BUNDLE_LINKS_COLLECTION)\n .where('workspaceId', '==', orgId)\n .limit(50)\n .get()\n const live = snapshot.docs\n .filter((doc) => bundleLinkIsLive(doc.data() as Partial<BundleLinkDoc>, now))\n .sort((a, b) => Number(b.get('createdAt') ?? 0) - Number(a.get('createdAt') ?? 0))\n return live[0] ? { id: live[0].id } : null\n}\n\n/**\n * The bundle links' answer to `core.purchase-gate-preclearance`.\n *\n * `check` reads only. `consume` marks the link used in a transaction that\n * writes only when nothing has, so two purchases racing on one link spend it\n * once: the second reads `usedAt` set and answers false.\n */\nexport function bundleLinkPreclearance(options: { now?: () => number } = {}): PurchaseGatePreclearance {\n const clock = options.now ?? (() => Date.now())\n return {\n async check(input: PurchaseGatePreclearanceInput) {\n const orgId = String(input?.orgId ?? '').trim()\n if (!orgId || input?.gate !== 'domain-payment-history') return null\n const live = await liveLinkFor(orgId, clock())\n return live ? { preclearanceId: live.id } : null\n },\n async consume(preclearanceId: string) {\n const id = String(preclearanceId ?? '').trim()\n if (!id || id.includes('/')) return false\n const db = firestore()\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(id)\n return db.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const now = clock()\n if (!bundleLinkIsLive(snapshot.data() as Partial<BundleLinkDoc>, now)) return false\n tx.update(ref, { usedAt: now, usedFor: 'domain-payment-history' })\n return true\n })\n },\n }\n}\n\nexport interface BundleLinkDomainLine {\n name: string\n firstYearCents: number\n renewalCents: number\n /** The site's Custom Domain page segment: its subdomain, else its id. */\n host: string\n hostId: string\n}\n\n/**\n * The domain line Billing shows for a link (AGL-3955), or why there is none:\n * the link is for another workspace, is spent or expired, names no domain,\n * or this deployment does not sell domains (`available: false`, so the page\n * can show the line disabled with the reason rather than hide it).\n */\nexport async function readBundleLinkDomain(\n orgId: string,\n linkId: string,\n now: number = Date.now(),\n): Promise<{ domain: BundleLinkDomainLine | null; available: boolean }> {\n const available = domainsRegistrarConfigured()\n const id = String(linkId ?? '').trim()\n if (!orgId || !id || id.includes('/')) return { domain: null, available }\n const db = firestore()\n const snapshot = await db.collection(BUNDLE_LINKS_COLLECTION).doc(id).get()\n const doc = snapshot.data() as Partial<BundleLinkDoc> | undefined\n if (!snapshot.exists || doc?.workspaceId !== orgId || !doc?.domain) {\n return { domain: null, available }\n }\n if (!bundleLinkIsLive(doc, now)) return { domain: null, available }\n const host = await db.collection('hosts').doc(doc.domain.hostId).get()\n if (!host.exists || host.get('orgId') !== orgId) return { domain: null, available }\n return {\n available,\n domain: {\n name: doc.domain.name,\n firstYearCents: doc.domain.firstYearCents,\n renewalCents: doc.domain.renewalCents,\n hostId: doc.domain.hostId,\n host: String(host.get('subdomain') ?? doc.domain.hostId),\n },\n }\n}\n"],"names":["fitBundleAddonsToPlan","normalizeBundleDomain","parseBundleAddons","createResourceUid","onboardingDestination","isAiTierId","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","upgradeProposalIntent","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","FieldValue","setAdminAudit","firebaseAdmin","BUNDLE_LINKS_COLLECTION","BUNDLE_LINK_TTL_MS","BUNDLE_LINK_PARAM","BUNDLE_LINK_AUDIT_ACTION","DOMAIN_PRICE_MAX_CENTS","domainsRegistrarConfigured","process","Boolean","String","env","trim","BundleLinkError","Error","message","status","name","firestore","app","cents","value","number","Math","round","Number","isFinite","mintBundleLink","options","actor","billingSnapshot","orgId","origin","now","Date","plan","parsed","addons","fitted","bundle","interval","coupon","aiTier","intent","db","orgRef","collection","doc","orgSnapshot","Promise","all","get","exists","slug","domain","firstYearCents","renewalCents","hostId","host","ref","mintedBy","uid","mintedByEmail","email","workspaceId","createdAt","expiresAt","usedAt","preclearsDomainGate","batch","set","actorUid","actorEmail","action","target","after","bundleLinkId","id","at","serverTimestamp","commit","path","url","droppedAddons","dropped","notSold","bundleLinkIsLive","undefined","liveLinkFor","snapshot","where","limit","live","docs","filter","data","sort","a","b","bundleLinkPreclearance","clock","check","input","gate","preclearanceId","consume","includes","runTransaction","tx","update","usedFor","readBundleLinkDomain","linkId","available"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC;AAGD,SACEA,qBAAqB,EACrBC,qBAAqB,EACrBC,iBAAiB,QAGZ,uCAAsC;AAC7C,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,UAAU,QAAQ,2CAA0C;AACrE,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,qBAAqB,QAChB,0CAAyC;AAChD,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,QACpB,yCAAwC;AAK/C,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AACnD,OAAOC,mBAAmB,sBAAkB;AAE5C,OAAO,MAAMC,0BAA0B,cAAa;AAEpD,kDAAkD,GAClD,OAAO,MAAMC,qBAAqB,KAAK,KAAK,KAAK,KAAI;AAErD,4EAA4E,GAC5E,OAAO,MAAMC,oBAAoB,SAAQ;AAEzC,qEAAqE,GACrE,OAAO,MAAMC,2BAA2B,6BAA4B;AAEpE,mFAAmF,GACnF,MAAMC,yBAAyB;AAE/B,0FAA0F,GAC1F,OAAO,SAASC;QACQC;IAAtB,OAAOC,QAAQC,QAAOF,iCAAAA,QAAQG,GAAG,CAAC,oBAAoB,YAAhCH,iCAAoC,IAAII,IAAI;AACpE;AAsCA,gDAAgD,GAChD,OAAO,MAAMC,wBAAwBC;IAEnC,YAAYC,OAAe,EAAEC,SAAS,GAAG,CAAE;QACzC,KAAK,CAACD;QACN,IAAI,CAACE,IAAI,GAAG;QACZ,IAAI,CAACD,MAAM,GAAGA;IAChB;AACF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,GAAG;IACpE,IAAI,CAACO,KAAKN,MAAM,IAAIM,KAAKP,GAAG,CAAC,aAAapB,OAAO,OAAO;QAAEuB,QAAQ;QAAM2D;IAAU;IAClF,OAAO;QACLA;QACA3D,QAAQ;YACNrC,MAAM8B,IAAIO,MAAM,CAACrC,IAAI;YACrBsC,gBAAgBR,IAAIO,MAAM,CAACC,cAAc;YACzCC,cAAcT,IAAIO,MAAM,CAACE,YAAY;YACrCC,QAAQV,IAAIO,MAAM,CAACG,MAAM;YACzBC,MAAMhD,QAAOgD,YAAAA,KAAKP,GAAG,CAAC,wBAATO,YAAyBX,IAAIO,MAAM,CAACG,MAAM;QACzD;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/bundle-links.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 * A STAFF-MINTED BUNDLE CHECKOUT LINK (AGL-3955).\n *\n * At a booth or on a doorstep, a staff member who built the owner's site\n * shows a QR; the owner scans it on their own phone and lands on Billing with\n * the plan, the add-ons, the cadence and the coupon already chosen, one tap\n * from paid. The link itself is an ordinary Billing URL — the query the\n * marketing CTAs and the upgrade proposal already speak — so it works without\n * any record at all.\n *\n * The RECORD is for two things the URL cannot carry honestly:\n *\n * - the chosen domain and its price, which the Billing page shows as a line\n * of its own and the owner then buys on the site's Custom Domain page. Read\n * from the record, never from the URL, so an edited link cannot show a name\n * or a price nobody quoted.\n * - the staff accountability that lets the link stand in for the domains\n * plugin's 72-hour paid-invoice gate, once (Zach, 2026-10-19). A staff\n * member met the owner and is named on the `billing.bundle-link-minted`\n * audit row; the link is for one workspace, lives 24 hours and is spent by\n * the first purchase it pre-clears. The plugin asks through\n * `core.purchase-gate-preclearance` and never reads this collection.\n *\n * Documents live in the top-level `bundleLinks` collection, keyed by an\n * unguessable id and carrying the workspace. Only the Admin SDK reads or\n * writes them; the rules deny every client, staff included.\n */\n\nimport type { OrgPlan } from '@aglyn/aglyn/server'\nimport {\n fitBundleAddonsToPlan,\n normalizeBundleDomain,\n parseBundleAddons,\n type AddonKind,\n type BundleAddons,\n} from '@aglyn/aglyn/app-utils/bundle-intent'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { onboardingDestination } from '@aglyn/aglyn/app-utils/onboarding-deep-link'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n upgradeProposalIntent,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport type {\n PurchaseGatePreclearance,\n PurchaseGatePreclearanceInput,\n} from '@aglyn/aglyn/plugin-manager/purchase-gate-preclearance'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport firebaseAdmin from './firebase-admin'\n\nexport const BUNDLE_LINKS_COLLECTION = 'bundleLinks'\n\n/** How long a link pre-clears, from its minting. */\nexport const BUNDLE_LINK_TTL_MS = 24 * 60 * 60 * 1000\n\n/** The query param that names the record, on a link that carries a domain. */\nexport const BUNDLE_LINK_PARAM = 'bundle'\n\n/** The audit action every mint writes, with the staff member's uid. */\nexport const BUNDLE_LINK_AUDIT_ACTION = 'billing.bundle-link-minted'\n\n/** The most a quoted domain may cost a year, in cents, before it reads as a typo. */\nconst DOMAIN_PRICE_MAX_CENTS = 100_000\n\n/** Whether this deployment sells domains: the registrar the domains plugin buys through. */\nexport function domainsRegistrarConfigured(): boolean {\n return Boolean(String(process.env['DOMAINS_REGISTRAR'] ?? '').trim())\n}\n\nexport interface BundleLinkDomain {\n /** The registrable name, lower-cased. */\n name: string\n /** The registrar's first-year price when the link was minted, in cents. */\n firstYearCents: number\n /** The yearly renewal price, in cents. */\n renewalCents: number\n /** The site the name is for: where the owner lands to buy it. */\n hostId: string\n}\n\nexport interface BundleLinkDoc {\n /** The staff member accountable for the link. */\n mintedBy: string\n mintedByEmail: string | null\n /** The one workspace the link is for. */\n workspaceId: string\n createdAt: number\n expiresAt: number\n /** When a purchase spent the link's preclearance; null until then. */\n usedAt: number | null\n /** Which gate the purchase that spent it waived. */\n usedFor?: string\n /** A staff-minted link stands in for the domains plugin's invoice-age gate, once. */\n preclearsDomainGate: true\n intent: {\n plan: OrgPlan\n addons?: BundleAddons\n interval?: 'month' | 'year'\n coupon?: string\n }\n domain?: BundleLinkDomain\n}\n\n/** A mint refused before anything was written. */\nexport class BundleLinkError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'BundleLinkError'\n this.status = status\n }\n}\n\nexport interface MintBundleLinkOptions {\n orgId: string\n /** The staff member minting it. */\n actor: { uid: string; email?: string | null }\n /** The console origin the link is built on. */\n origin: string\n plan: unknown\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 link naming a tier is refused.\n */\n aiTier?: unknown\n /** The chosen domain, quoted from the registrar's search; optional. */\n domain?: {\n name?: unknown\n firstYearCents?: unknown\n renewalCents?: unknown\n hostId?: unknown\n } | null\n /** Clock seam. */\n now?: number\n}\n\nexport interface MintedBundleLink {\n id: string\n url: string\n expiresAt: number\n intent: BundleLinkDoc['intent']\n domain: BundleLinkDomain | null\n /** Add-ons asked for that the plan does not sell, left off the link. */\n droppedAddons: Array<AddonKind | string>\n}\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nfunction cents(value: unknown): number | null {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 && number <= DOMAIN_PRICE_MAX_CENTS ? number : null\n}\n\n/**\n * Mint a link for one workspace: validate the bundle the way the proposal\n * does, write the record and its audit row in one batch, and answer the URL.\n *\n * Refused for a plan the workspace cannot buy itself, for a workspace with a\n * live subscription (checkout would refuse it; plan changes are Billing's),\n * and for a domain on a deployment that does not sell domains, for a site\n * outside the workspace, or without a price.\n */\nexport async function mintBundleLink(options: MintBundleLinkOptions): Promise<MintedBundleLink> {\n const { orgId, actor, origin } = options\n const now = options.now ?? Date.now()\n if (!orgId) throw new BundleLinkError('Missing orgId')\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new BundleLinkError('Choose a paid plan the workspace can buy itself')\n }\n const plan: OrgPlan = options.plan\n if (options.aiTier != null) {\n throw new BundleLinkError(\n 'AI tiers were replaced by AI credit blocks. Choose a number of blocks instead.',\n )\n }\n const parsed = parseBundleAddons(options.addons)\n const fitted = fitBundleAddonsToPlan(parsed.addons, plan)\n const bundle = normalizeUpgradeProposalBundle(plan, {\n addons: fitted.addons,\n interval: options.interval,\n coupon: options.coupon,\n })\n const intent: BundleLinkDoc['intent'] = { plan, ...bundle }\n\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const [orgSnapshot, billingSnapshot] = await Promise.all([\n orgRef.get(),\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID).get(),\n ])\n if (!orgSnapshot.exists) throw new BundleLinkError('Unknown organization', 404)\n const slug = orgSnapshot.get('slug')\n if (typeof slug !== 'string' || !slug) {\n throw new BundleLinkError('This workspace has no address yet, so no link can point at it', 409)\n }\n const status =\n (billingSnapshot.get('subscription') as { status?: unknown } | undefined)?.status ??\n orgSnapshot.get('billingStatus')\n if (isLiveSubscriptionStatus(status)) {\n throw new BundleLinkError(\n 'This workspace already has a live subscription; change its plan from Billing instead',\n 409,\n )\n }\n\n let domain: BundleLinkDomain | null = null\n if (options.domain && options.domain.name) {\n if (!domainsRegistrarConfigured()) {\n throw new BundleLinkError('Buying a domain is not available on this deployment yet', 409)\n }\n const name = normalizeBundleDomain(options.domain.name)\n if (!name) throw new BundleLinkError('That is not a domain name')\n const firstYearCents = cents(options.domain.firstYearCents)\n const renewalCents = cents(options.domain.renewalCents)\n if (firstYearCents === null || renewalCents === null) {\n throw new BundleLinkError('Quote the domain’s first-year and renewal prices from its search')\n }\n const hostId = String(options.domain.hostId ?? '').trim()\n const host = hostId ? await db.collection('hosts').doc(hostId).get() : null\n if (!host?.exists || host.get('orgId') !== orgId) {\n throw new BundleLinkError('Choose the site in this workspace the domain is for')\n }\n domain = { name, firstYearCents, renewalCents, hostId }\n }\n\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(createResourceUid())\n const doc: BundleLinkDoc = {\n mintedBy: actor.uid,\n mintedByEmail: actor.email ?? null,\n workspaceId: orgId,\n createdAt: now,\n expiresAt: now + BUNDLE_LINK_TTL_MS,\n usedAt: null,\n preclearsDomainGate: true,\n intent,\n ...(domain ? { domain } : {}),\n }\n const batch = db.batch()\n batch.set(ref, doc)\n setAdminAudit(batch, db, {\n actorUid: actor.uid,\n ...(actor.email ? { actorEmail: actor.email } : {}),\n action: BUNDLE_LINK_AUDIT_ACTION,\n target: `orgs/${orgId}`,\n after: {\n bundleLinkId: ref.id,\n intent,\n domain,\n expiresAt: doc.expiresAt,\n preclearsDomainGate: true,\n },\n at: FieldValue.serverTimestamp(),\n })\n await batch.commit()\n\n const path = onboardingDestination(slug, upgradeProposalIntent(intent))\n const url = `${origin}${path}${domain ? `&${BUNDLE_LINK_PARAM}=${ref.id}` : ''}`\n return {\n id: ref.id,\n url,\n expiresAt: doc.expiresAt,\n intent,\n domain,\n droppedAddons: [...parsed.dropped, ...fitted.notSold],\n }\n}\n\n/** Whether a stored link still pre-clears: unused, unexpired, and flagged. */\nexport function bundleLinkIsLive(doc: Partial<BundleLinkDoc> | undefined, now: number): boolean {\n return (\n !!doc &&\n doc.preclearsDomainGate === true &&\n (doc.usedAt === null || doc.usedAt === undefined) &&\n typeof doc.expiresAt === 'number' &&\n doc.expiresAt > now\n )\n}\n\n/**\n * The workspace's live link, or null. Read by the workspace alone (a\n * single-field equality, no composite index) and narrowed here: a workspace\n * holds a handful of links at most, each gone in a day.\n */\nasync function liveLinkFor(orgId: string, now: number): Promise<{ id: string } | null> {\n const snapshot = await firestore()\n .collection(BUNDLE_LINKS_COLLECTION)\n .where('workspaceId', '==', orgId)\n .limit(50)\n .get()\n const live = snapshot.docs\n .filter((doc) => bundleLinkIsLive(doc.data() as Partial<BundleLinkDoc>, now))\n .sort((a, b) => Number(b.get('createdAt') ?? 0) - Number(a.get('createdAt') ?? 0))\n return live[0] ? { id: live[0].id } : null\n}\n\n/**\n * The bundle links' answer to `core.purchase-gate-preclearance`.\n *\n * `check` reads only. `consume` marks the link used in a transaction that\n * writes only when nothing has, so two purchases racing on one link spend it\n * once: the second reads `usedAt` set and answers false.\n */\nexport function bundleLinkPreclearance(options: { now?: () => number } = {}): PurchaseGatePreclearance {\n const clock = options.now ?? (() => Date.now())\n return {\n async check(input: PurchaseGatePreclearanceInput) {\n const orgId = String(input?.orgId ?? '').trim()\n if (!orgId || input?.gate !== 'domain-payment-history') return null\n const live = await liveLinkFor(orgId, clock())\n return live ? { preclearanceId: live.id } : null\n },\n async consume(preclearanceId: string) {\n const id = String(preclearanceId ?? '').trim()\n if (!id || id.includes('/')) return false\n const db = firestore()\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(id)\n return db.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const now = clock()\n if (!bundleLinkIsLive(snapshot.data() as Partial<BundleLinkDoc>, now)) return false\n tx.update(ref, { usedAt: now, usedFor: 'domain-payment-history' })\n return true\n })\n },\n }\n}\n\nexport interface BundleLinkDomainLine {\n name: string\n firstYearCents: number\n renewalCents: number\n /** The site's Custom Domain page segment: its subdomain, else its id. */\n host: string\n hostId: string\n}\n\n/**\n * The domain line Billing shows for a link (AGL-3955), or why there is none:\n * the link is for another workspace, is spent or expired, names no domain,\n * or this deployment does not sell domains (`available: false`, so the page\n * can show the line disabled with the reason rather than hide it).\n */\nexport async function readBundleLinkDomain(\n orgId: string,\n linkId: string,\n now: number = Date.now(),\n): Promise<{ domain: BundleLinkDomainLine | null; available: boolean }> {\n const available = domainsRegistrarConfigured()\n const id = String(linkId ?? '').trim()\n if (!orgId || !id || id.includes('/')) return { domain: null, available }\n const db = firestore()\n const snapshot = await db.collection(BUNDLE_LINKS_COLLECTION).doc(id).get()\n const doc = snapshot.data() as Partial<BundleLinkDoc> | undefined\n if (!snapshot.exists || doc?.workspaceId !== orgId || !doc?.domain) {\n return { domain: null, available }\n }\n if (!bundleLinkIsLive(doc, now)) return { domain: null, available }\n const host = await db.collection('hosts').doc(doc.domain.hostId).get()\n if (!host.exists || host.get('orgId') !== orgId) return { domain: null, available }\n return {\n available,\n domain: {\n name: doc.domain.name,\n firstYearCents: doc.domain.firstYearCents,\n renewalCents: doc.domain.renewalCents,\n hostId: doc.domain.hostId,\n host: String(host.get('subdomain') ?? doc.domain.hostId),\n },\n }\n}\n"],"names":["fitBundleAddonsToPlan","normalizeBundleDomain","parseBundleAddons","createResourceUid","onboardingDestination","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","upgradeProposalIntent","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","FieldValue","setAdminAudit","firebaseAdmin","BUNDLE_LINKS_COLLECTION","BUNDLE_LINK_TTL_MS","BUNDLE_LINK_PARAM","BUNDLE_LINK_AUDIT_ACTION","DOMAIN_PRICE_MAX_CENTS","domainsRegistrarConfigured","process","Boolean","String","env","trim","BundleLinkError","Error","message","status","name","firestore","app","cents","value","number","Math","round","Number","isFinite","mintBundleLink","options","actor","billingSnapshot","orgId","origin","now","Date","plan","aiTier","parsed","addons","fitted","bundle","interval","coupon","intent","db","orgRef","collection","doc","orgSnapshot","Promise","all","get","exists","slug","domain","firstYearCents","renewalCents","hostId","host","ref","mintedBy","uid","mintedByEmail","email","workspaceId","createdAt","expiresAt","usedAt","preclearsDomainGate","batch","set","actorUid","actorEmail","action","target","after","bundleLinkId","id","at","serverTimestamp","commit","path","url","droppedAddons","dropped","notSold","bundleLinkIsLive","undefined","liveLinkFor","snapshot","where","limit","live","docs","filter","data","sort","a","b","bundleLinkPreclearance","clock","check","input","gate","preclearanceId","consume","includes","runTransaction","tx","update","usedFor","readBundleLinkDomain","linkId","available"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC;AAGD,SACEA,qBAAqB,EACrBC,qBAAqB,EACrBC,iBAAiB,QAGZ,uCAAsC;AAC7C,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,qBAAqB,QAChB,0CAAyC;AAChD,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,QACpB,yCAAwC;AAK/C,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AACnD,OAAOC,mBAAmB,sBAAkB;AAE5C,OAAO,MAAMC,0BAA0B,cAAa;AAEpD,kDAAkD,GAClD,OAAO,MAAMC,qBAAqB,KAAK,KAAK,KAAK,KAAI;AAErD,4EAA4E,GAC5E,OAAO,MAAMC,oBAAoB,SAAQ;AAEzC,qEAAqE,GACrE,OAAO,MAAMC,2BAA2B,6BAA4B;AAEpE,mFAAmF,GACnF,MAAMC,yBAAyB;AAE/B,0FAA0F,GAC1F,OAAO,SAASC;QACQC;IAAtB,OAAOC,QAAQC,QAAOF,iCAAAA,QAAQG,GAAG,CAAC,oBAAoB,YAAhCH,iCAAoC,IAAII,IAAI;AACpE;AAoCA,gDAAgD,GAChD,OAAO,MAAMC,wBAAwBC;IAEnC,YAAYC,OAAe,EA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O,MAAMd,GAAGE,UAAU,CAAC,SAASC,GAAG,CAACA,IAAIO,MAAM,CAACG,MAAM,EAAEN,GAAG;IACpE,IAAI,CAACO,KAAKN,MAAM,IAAIM,KAAKP,GAAG,CAAC,aAAapB,OAAO,OAAO;QAAEuB,QAAQ;QAAM2D;IAAU;IAClF,OAAO;QACLA;QACA3D,QAAQ;YACNrC,MAAM8B,IAAIO,MAAM,CAACrC,IAAI;YACrBsC,gBAAgBR,IAAIO,MAAM,CAACC,cAAc;YACzCC,cAAcT,IAAIO,MAAM,CAACE,YAAY;YACrCC,QAAQV,IAAIO,MAAM,CAACG,MAAM;YACzBC,MAAMhD,QAAOgD,YAAAA,KAAKP,GAAG,CAAC,wBAATO,YAAyBX,IAAIO,MAAM,CAACG,MAAM;QACzD;IACF;AACF"}
@@ -36,10 +36,13 @@
36
36
  * ### `emailSends` — the COST meter. Counts everything. Gates nothing.
37
37
  *
38
38
  * Every `sendEmail` call site increments this, whatever sent it. It is what the
39
- * monthly rollup carries for COGS, and it is RECORDED, NOT PRICED — there is
40
- * still no per-email rate anywhere, so it enters neither `billedCents` nor
41
- * `costUsd` nor `ORG_COGS_UNIT_RATES_USD`. Pricing it is a decision with an
42
- * invoice month behind it.
39
+ * monthly rollup carries for COGS: `report-usage` sums every site's counter and
40
+ * the org's own into the rollup's `emailSends`, and `orgMonthlyCogsUsd` prices
41
+ * that figure at `ORG_COGS_UNIT_RATES_USD.perEmailSend` — campaigns and
42
+ * transactional mail alike, which is what the staff margin readouts read
43
+ * (`transactional-sends-reach-the-cost-meter.spec.ts`). Only the overage past
44
+ * a plan's band can reach an invoice, and only from the month
45
+ * `BILL_EMAIL_SEND_OVERAGE_FROM` names.
43
46
  *
44
47
  * ### `campaignEmailSends` — the ENFORCEABLE meter. Counts campaigns only.
45
48
  *
@@ -59,6 +62,11 @@
59
62
  * takes: rate limiting fails soft, robots/sitemap fail open so a transient
60
63
  * error cannot de-index a customer's site.
61
64
  *
65
+ * The one bound on it is not a quota (AGL-4145): a per-organization ABUSE
66
+ * ceiling per UTC day on a site's non-campaign mail, sized so no real store
67
+ * reaches it, with security mail exempt even from that. It counts on its own
68
+ * counter (`email-transactional-ceiling.ts`), never on these two.
69
+ *
62
70
  * ### Not double-counted
63
71
  *
64
72
  * One call site, one call to this function, and a campaign send increments BOTH
@@ -36,10 +36,13 @@
36
36
  * ### `emailSends` — the COST meter. Counts everything. Gates nothing.
37
37
  *
38
38
  * Every `sendEmail` call site increments this, whatever sent it. It is what the
39
- * monthly rollup carries for COGS, and it is RECORDED, NOT PRICED — there is
40
- * still no per-email rate anywhere, so it enters neither `billedCents` nor
41
- * `costUsd` nor `ORG_COGS_UNIT_RATES_USD`. Pricing it is a decision with an
42
- * invoice month behind it.
39
+ * monthly rollup carries for COGS: `report-usage` sums every site's counter and
40
+ * the org's own into the rollup's `emailSends`, and `orgMonthlyCogsUsd` prices
41
+ * that figure at `ORG_COGS_UNIT_RATES_USD.perEmailSend` — campaigns and
42
+ * transactional mail alike, which is what the staff margin readouts read
43
+ * (`transactional-sends-reach-the-cost-meter.spec.ts`). Only the overage past
44
+ * a plan's band can reach an invoice, and only from the month
45
+ * `BILL_EMAIL_SEND_OVERAGE_FROM` names.
43
46
  *
44
47
  * ### `campaignEmailSends` — the ENFORCEABLE meter. Counts campaigns only.
45
48
  *
@@ -59,6 +62,11 @@
59
62
  * takes: rate limiting fails soft, robots/sitemap fail open so a transient
60
63
  * error cannot de-index a customer's site.
61
64
  *
65
+ * The one bound on it is not a quota (AGL-4145): a per-organization ABUSE
66
+ * ceiling per UTC day on a site's non-campaign mail, sized so no real store
67
+ * reaches it, with security mail exempt even from that. It counts on its own
68
+ * counter (`email-transactional-ceiling.ts`), never on these two.
69
+ *
62
70
  * ### Not double-counted
63
71
  *
64
72
  * One call site, one call to this function, and a campaign send increments BOTH
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-metering.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * The email meters (AGL-1438). **Two of them, deliberately.**\n *\n * Before this, `hosts/{hostId}/counters/emailSends` was written by exactly one\n * caller — the marketing campaign sender. Workflows, commerce, bookings and\n * invites all called `sendEmail` and counted nothing, so the counter that named\n * itself \"email sends\" held campaign sends alone. Two things followed from\n * that: `emailSendsPerMonth` under-enforced, and the COGS figure AGL-1134\n * started recording off this counter under-reported real email cost by however\n * much non-campaign volume an org sent.\n *\n * UNITS: plain COUNTS — one per recipient address handed to the sender —\n * for the calendar month named by the `YYYY-MM` FIELD on the counter document.\n * Not bytes, not currency, not a running total: each month's field is\n * independent, so summing months is a legitimate year-to-date and reading one\n * is that month alone. Same unit as `workflowRuns`/`actionRuns` beside it, and\n * the same unit `orgCounterTotals` sums, so a campaign of 300 and 300 workflow\n * notifications are the same 300 on the meter.\n *\n * ### `emailSends` — the COST meter. Counts everything. Gates nothing.\n *\n * Every `sendEmail` call site increments this, whatever sent it. It is what the\n * monthly rollup carries for COGS, and it is RECORDED, NOT PRICED — there is\n * still no per-email rate anywhere, so it enters neither `billedCents` nor\n * `costUsd` nor `ORG_COGS_UNIT_RATES_USD`. Pricing it is a decision with an\n * invoice month behind it.\n *\n * ### `campaignEmailSends` — the ENFORCEABLE meter. Counts campaigns only.\n *\n * `emailSendsPerMonth` is checked against this and nothing else. A campaign is\n * discretionary: refusing one at the cap is the outcome the plan sells, the\n * customer sees a clear message, and they upgrade or wait.\n *\n * **Transactional mail is never blocked by a quota, at any tier.** Password\n * resets, invites, order confirmations, booking reminders and workflow\n * notifications send regardless of counter state; they count toward cost and\n * cannot be refused. The failure modes are not symmetric — a blocked password\n * reset locks somebody out of their own account, and the message explaining\n * why is itself an email that will not send; a dropped order confirmation\n * reads to the buyer as a failed order. That converts a billing event into an\n * outage on somebody else's business, where the overage it saved was bounded\n * and billable. It is the same fail-open posture the rest of this codebase\n * takes: rate limiting fails soft, robots/sitemap fail open so a transient\n * error cannot de-index a customer's site.\n *\n * ### Not double-counted\n *\n * One call site, one call to this function, and a campaign send increments BOTH\n * counters from that single call rather than incrementing `emailSends` here and\n * again somewhere else. The counter is keyed by month ON THE DOCUMENT, so\n * nothing accumulates across a re-read, and the rollup re-derives rather than\n * adds. A meter that double-counts is worse than no meter, because it looks\n * authoritative (AGL-1402).\n *\n * ### Transition note\n *\n * `campaignEmailSends` starts empty. For the month this ships, campaign volume\n * already sent is recorded only under the old `emailSends`, so the campaign cap\n * effectively restarts once. That loosens for at most one month, which is the\n * correct direction to be wrong in — the alternative, seeding the enforceable\n * meter from a counter that now also holds transactional mail, would refuse\n * campaigns because of order confirmations.\n */\n\n/** Every send, whatever produced it. The cost meter. */\nexport const EMAIL_SENDS_COUNTER = 'emailSends'\n\n/** Campaign sends alone. The only meter `emailSendsPerMonth` may refuse. */\nexport const CAMPAIGN_EMAIL_SENDS_COUNTER = 'campaignEmailSends'\n\n/** Top-level home for platform-scoped meters: `meters/platform/counters/*`. */\nexport const PLATFORM_METER_COLLECTION = 'meters'\nexport const PLATFORM_METER_DOC = 'platform'\n\n/**\n * Who the send is attributed to.\n *\n * - `host` — a site sent it: campaigns, receipts, booking mail, workflow\n * notifications, member mail. Rolls up to the owning org.\n * - `org` — the org sent it with no site involved: invites, member-added,\n * the welcome mail, usage summaries, erasure notices.\n * - `platform` — Aglyn's own account and staff mail: password resets and\n * verification (which happen before any org is known), new-device and\n * passkey alerts, staff alerts, the system-email test send. Real cost, but\n * not any one customer's, so it is counted apart from every org rollup and\n * never reaches a COGS figure or an invoice.\n */\nexport type EmailMeterScope =\n | { kind: 'host'; hostId: string }\n | { kind: 'org'; orgId: string }\n | { kind: 'platform' }\n\n/**\n * Whether a quota may refuse this send.\n *\n * `campaign` is the ONLY discretionary class. Everything else is\n * `transactional`, which means: count it, never gate on it.\n */\nexport type EmailSendClass = 'campaign' | 'transactional'\n\nexport interface RecordEmailSendsOptions {\n scope: EmailMeterScope\n /** Emails actually handed to the sender. Zero and negatives are no-ops. */\n count: number\n sendClass: EmailSendClass\n /** `YYYY-MM`; defaults to the current UTC month. */\n month?: string\n /** Injectable for tests; defaults to the Admin SDK's Firestore. */\n firestore?: any\n}\n\n/** The counters document for a scope, e.g. `hosts/{id}/counters/emailSends`. */\nexport function emailMeterRef(\n firestore: any,\n scope: EmailMeterScope,\n counter: string,\n): any {\n if (scope.kind === 'host') {\n return firestore\n .collection('hosts')\n .doc(scope.hostId)\n .collection('counters')\n .doc(counter)\n }\n if (scope.kind === 'org') {\n return firestore\n .collection('orgs')\n .doc(scope.orgId)\n .collection('counters')\n .doc(counter)\n }\n return firestore\n .collection(PLATFORM_METER_COLLECTION)\n .doc(PLATFORM_METER_DOC)\n .collection('counters')\n .doc(counter)\n}\n\n/** Current calendar month as `YYYY-MM`, matching every other counter here. */\nexport function currentMeterMonth(now: Date = new Date()): string {\n return now.toISOString().slice(0, 7)\n}\n\n/**\n * Records `count` emails against the cost meter, and against the campaign\n * meter too when the send was a campaign.\n *\n * **Never throws.** Metering is bookkeeping that runs after mail has already\n * gone out — a counter write that fails must not turn a delivered receipt into\n * a 500 for the buyer, and must certainly not be able to stop the next send.\n * Failures are logged and swallowed, the same posture `sendEmail` itself takes.\n */\nexport async function recordEmailSends(\n options: RecordEmailSendsOptions,\n): Promise<void> {\n const { scope, sendClass } = options\n const count = Math.floor(Number(options.count))\n // A send that did not happen is not a cost. `sendEmail` reports `sent` per\n // message, and callers pass the delivered count, so 0 is the ordinary\n // outcome of an unconfigured environment rather than an error.\n if (!Number.isFinite(count) || count <= 0) return\n if (scope.kind === 'host' && !scope.hostId) return\n if (scope.kind === 'org' && !scope.orgId) return\n\n const month = options.month || currentMeterMonth()\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const increment = firebaseAdmin.firestore.FieldValue.increment(count)\n const counters =\n sendClass === 'campaign'\n ? [EMAIL_SENDS_COUNTER, CAMPAIGN_EMAIL_SENDS_COUNTER]\n : [EMAIL_SENDS_COUNTER]\n await Promise.all(\n counters.map((counter) =>\n emailMeterRef(firestore, scope, counter).set(\n { [month]: increment },\n { merge: true },\n ),\n ),\n )\n } catch (error) {\n console.error('email meter write failed', error)\n }\n}\n\n/**\n * One transactional (or, with `sendClass`, campaign) send attributed to a site.\n *\n * The overwhelmingly common call — `await meterHostEmail(hostId)` right after\n * a `sendEmail` — so it reads as one line at every call site and there is one\n * place to change if the counter ever moves.\n */\nexport function meterHostEmail(\n hostId: string,\n count = 1,\n sendClass: EmailSendClass = 'transactional',\n): Promise<void> {\n return recordEmailSends({\n scope: { kind: 'host', hostId },\n count,\n sendClass,\n })\n}\n\n/** Org-scoped transactional mail: invites, welcome, usage summaries. */\nexport function meterOrgEmail(orgId: string, count = 1): Promise<void> {\n return recordEmailSends({\n scope: { kind: 'org', orgId },\n count,\n sendClass: 'transactional',\n })\n}\n\n/**\n * Account and staff mail that belongs to no org at send time — a password\n * reset knows only an address, and a staff alert has no customer at all.\n */\nexport function meterPlatformEmail(count = 1): Promise<void> {\n return recordEmailSends({\n scope: { kind: 'platform' },\n count,\n sendClass: 'transactional',\n })\n}\n\n/**\n * The enforceable figure for a site this month: campaign sends alone.\n *\n * Reads the campaign meter and NOT `emailSends`, which now also holds every\n * receipt and password reset the site sent. Enforcing the plan's cap against\n * that total is exactly the behaviour this issue exists to prevent.\n */\nexport async function campaignEmailSendsForMonth(\n hostRef: any,\n month: string,\n): Promise<number> {\n const snapshot = await hostRef\n .collection('counters')\n .doc(CAMPAIGN_EMAIL_SENDS_COUNTER)\n .get()\n const used = Number(snapshot.get(month) ?? 0)\n // An absent counter is 0, and a corrupt negative must not read as unused\n // headroom that a cap then honours.\n return Number.isFinite(used) && used > 0 ? used : 0\n}\n\n/**\n * The org-level campaign meter, and the ONLY figure `emailSendsPerMonth` is\n * enforced against since AGL-2267.\n *\n * ## Why a second counter and not the per-host one\n *\n * `hosts/{hostId}/counters/campaignEmailSends` is per SITE. `emailSendsPerMonth`\n * is an ORG entitlement. An org with N sites therefore received N × the cap it\n * bought — invisible on Free and Starter (`hostLimit: 1`) and growing with the\n * plan, so the customers who paid most got the most cap they had not paid for.\n *\n * The per-host counter is UNCHANGED and still written, by `meterHostEmail`, on\n * the delivered count. It is per-site history and it feeds the cost meter;\n * nothing about it was wrong except being asked a question about an org.\n *\n * ## Why folding the existing per-site counters in was rejected\n *\n * Summing N site counters into one org total retroactively puts multi-site\n * paying customers over a limit they have been under all along — a limit that\n * then refuses a campaign they had every reason to expect to send, days after\n * they bought the plan. This counter therefore STARTS EMPTY, and the campaign\n * cap effectively restarts once for the month this ships.\n *\n * That is the same transition `campaignEmailSends` itself was given, and the\n * same reasoning: it loosens for at most one month, which is the correct\n * direction to be wrong in, and it needs no production measurement of who is\n * currently over — a measurement that could only be taken against live\n * customer data and would have blocked the fix indefinitely.\n */\nexport const ORG_CAMPAIGN_EMAIL_SENDS_COUNTER = CAMPAIGN_EMAIL_SENDS_COUNTER\n\n/** A granted claim on the org's monthly campaign allowance. */\nexport interface CampaignSendReservation {\n orgId: string\n month: string\n /** Messages claimed up front. */\n reserved: number\n}\n\nexport type ReserveCampaignSendsResult =\n | { ok: true; reservation: CampaignSendReservation; used: number; limit: number }\n | { ok: false; used: number; limit: number }\n\n/** Reads an org-scoped monthly counter field, clamped like every other. */\nfunction readMonthField(snapshot: any, month: string): number {\n const used = Number((snapshot?.exists ? snapshot.get(month) : 0) ?? 0)\n return Number.isFinite(used) && used > 0 ? Math.floor(used) : 0\n}\n\n/**\n * The enforceable figure for an ORG this month: campaign sends alone.\n *\n * Read-only. Used by the campaign composer's recipient preview, which must\n * not reserve anything (AGL-2178 — \"nothing has been written above this\n * line\"), and by anything that reports headroom.\n */\nexport async function orgCampaignEmailSendsForMonth(\n orgId: string,\n month: string,\n firestore?: any,\n): Promise<number> {\n if (!orgId) return 0\n const db = firestore ?? firebaseAdmin.app().firestore()\n const snapshot = await db\n .collection('orgs')\n .doc(orgId)\n .collection('counters')\n .doc(ORG_CAMPAIGN_EMAIL_SENDS_COUNTER)\n .get()\n return readMonthField(snapshot, month)\n}\n\n/**\n * Claims `count` campaign sends against the org's monthly allowance, ATOMICALLY.\n *\n * ## Why a reservation and not a check\n *\n * The cap used to be read before the send and incremented after delivery, so\n * two concurrent campaigns both passed the same reading and both sent — the\n * cap was advisory in exactly the conditions it existed for. **A read-then-write\n * cap is not a cap.**\n *\n * The transaction reads the counter and writes an ABSOLUTE value derived from\n * that read, deliberately not `FieldValue.increment`. Firestore aborts and\n * re-runs the callback when a document the transaction read has moved, so a\n * second sender that starts inside the first one's window re-reads the raised\n * figure and is refused. An increment would be atomic on the number and\n * useless for the decision, because the decision is made from a value the\n * write never proves it still held.\n *\n * A refused reservation writes NOTHING.\n *\n * ## Why reserve-then-reconcile rather than reserve-and-keep\n *\n * A campaign reserves against a PARTIAL delivery: `sendEmail` reports per\n * message, and only some of a 500-address batch may go out. Keeping the whole\n * reservation would charge a customer's allowance for mail that never left.\n * So the claim is taken in full up front — that is what makes it a cap — and\n * {@link reconcileCampaignSendReservation} gives back the difference once the\n * delivered count is known.\n *\n * **The failure mode is stated rather than hidden**: if the process dies\n * between reserving and reconciling, the org is charged for the undelivered\n * remainder for the rest of that calendar month. That is conservative in the\n * direction this issue cares about — it can only ever refuse more mail, never\n * let more out — and it self-heals at the month boundary, because each month\n * is an independent field on the document.\n *\n * `limit` may be `Infinity` (`UNLIMITED`), which admits everything.\n */\nexport async function reserveCampaignEmailSends(options: {\n orgId: string\n month: string\n count: number\n limit: number\n firestore?: any\n}): Promise<ReserveCampaignSendsResult> {\n const count = Math.max(0, Math.floor(Number(options.count) || 0))\n const limit = Number(options.limit)\n // A plan-less or unresolvable org must not be a bypass. The caller resolves\n // free-tier entitlements for it (AGL-247) and the cap is 0, so an empty\n // orgId that reached here means the counter has nowhere to live — refuse\n // rather than send unbounded.\n if (!options.orgId) {\n return { ok: false, used: 0, limit: Number.isFinite(limit) ? limit : 0 }\n }\n const db = options.firestore ?? firebaseAdmin.app().firestore()\n const ref = db\n .collection('orgs')\n .doc(options.orgId)\n .collection('counters')\n .doc(ORG_CAMPAIGN_EMAIL_SENDS_COUNTER)\n\n return db.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = readMonthField(snapshot, options.month)\n if (used + count > limit) return { ok: false, used, limit }\n tx.set(ref, { [options.month]: used + count }, { merge: true })\n return {\n ok: true,\n reservation: { orgId: options.orgId, month: options.month, reserved: count },\n used,\n limit,\n }\n })\n}\n\n/**\n * Returns the undelivered part of a reservation.\n *\n * Also a transaction, and also an absolute write from its own read: a refund\n * computed from a stale figure would undo a reservation another campaign took\n * in the meantime, which is the same defect one direction over.\n *\n * **Never throws** and never drives the counter below zero. This runs after\n * mail has already gone out; a bookkeeping failure must not turn a delivered\n * campaign into a 500, exactly like `recordEmailSends` above. The cost of\n * swallowing it is that the org keeps a claim it did not use for the rest of\n * the month, which is the safe direction.\n */\nexport async function reconcileCampaignSendReservation(\n reservation: CampaignSendReservation | null | undefined,\n delivered: number,\n firestore?: any,\n): Promise<void> {\n if (!reservation?.orgId) return\n const sent = Math.max(0, Math.floor(Number(delivered) || 0))\n const refund = Math.max(0, reservation.reserved - sent)\n if (refund <= 0) return\n try {\n const db = firestore ?? firebaseAdmin.app().firestore()\n const ref = db\n .collection('orgs')\n .doc(reservation.orgId)\n .collection('counters')\n .doc(ORG_CAMPAIGN_EMAIL_SENDS_COUNTER)\n await db.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = readMonthField(snapshot, reservation.month)\n tx.set(\n ref,\n { [reservation.month]: Math.max(0, used - refund) },\n { merge: true },\n )\n })\n } catch (error) {\n console.error('campaign reservation reconcile failed', error)\n }\n}\n\n/**\n * Volume above the plan's included band, in emails — RE-EXPORTED, not defined\n * here, the same move AGL-2155 made for the bandwidth helpers.\n *\n * The definition moved down to `@aglyn/aglyn/app-utils/plan-entitlements`\n * because the billing page has to render the overage BEFORE it is charged,\n * and that page is a client component which cannot import this module: the\n * Admin SDK comes with it. A second copy of the subtraction on the client is\n * the shape where the readout and the invoice quietly stop agreeing.\n *\n * Re-exported so every server caller keeps importing it from the module it\n * always did — one definition, no drift, no import churn.\n *\n * @see priceEmailSendOverage — what the excess costs, at the plan's rate.\n */\nexport { emailSendsOverage } from '@aglyn/aglyn/app-utils/plan-entitlements'\n\nexport default recordEmailSends\n"],"names":["firebaseAdmin","EMAIL_SENDS_COUNTER","CAMPAIGN_EMAIL_SENDS_COUNTER","PLATFORM_METER_COLLECTION","PLATFORM_METER_DOC","emailMeterRef","firestore","scope","counter","kind","collection","doc","hostId","orgId","currentMeterMonth","now","Date","toISOString","slice","recordEmailSends","options","sendClass","count","Math","floor","Number","isFinite","month","app","increment","FieldValue","counters","Promise","all","map","set","merge","error","console","meterHostEmail","meterOrgEmail","meterPlatformEmail","campaignEmailSendsForMonth","hostRef","snapshot","get","used","ORG_CAMPAIGN_EMAIL_SENDS_COUNTER","readMonthField","exists","orgCampaignEmailSendsForMonth","db","reserveCampaignEmailSends","max","limit","ok","ref","runTransaction","tx","reservation","reserved","reconcileCampaignSendReservation","delivered","sent","refund","emailSendsOverage"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,sBAAkB;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8DC,GAED,sDAAsD,GACtD,OAAO,MAAMC,sBAAsB,aAAY;AAE/C,0EAA0E,GAC1E,OAAO,MAAMC,+BAA+B,qBAAoB;AAEhE,6EAA6E,GAC7E,OAAO,MA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AOkB;YAAQ,GAClD;gBAAE5B,OAAO;YAAK;QAElB;IACF,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,yCAAyCA;IACzD;AACF;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAAS4B,iBAAiB,QAAQ,2CAA0C;AAE5E,eAAe9C,iBAAgB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-metering.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * The email meters (AGL-1438). **Two of them, deliberately.**\n *\n * Before this, `hosts/{hostId}/counters/emailSends` was written by exactly one\n * caller — the marketing campaign sender. Workflows, commerce, bookings and\n * invites all called `sendEmail` and counted nothing, so the counter that named\n * itself \"email sends\" held campaign sends alone. Two things followed from\n * that: `emailSendsPerMonth` under-enforced, and the COGS figure AGL-1134\n * started recording off this counter under-reported real email cost by however\n * much non-campaign volume an org sent.\n *\n * UNITS: plain COUNTS — one per recipient address handed to the sender —\n * for the calendar month named by the `YYYY-MM` FIELD on the counter document.\n * Not bytes, not currency, not a running total: each month's field is\n * independent, so summing months is a legitimate year-to-date and reading one\n * is that month alone. Same unit as `workflowRuns`/`actionRuns` beside it, and\n * the same unit `orgCounterTotals` sums, so a campaign of 300 and 300 workflow\n * notifications are the same 300 on the meter.\n *\n * ### `emailSends` — the COST meter. Counts everything. Gates nothing.\n *\n * Every `sendEmail` call site increments this, whatever sent it. It is what the\n * monthly rollup carries for COGS: `report-usage` sums every site's counter and\n * the org's own into the rollup's `emailSends`, and `orgMonthlyCogsUsd` prices\n * that figure at `ORG_COGS_UNIT_RATES_USD.perEmailSend` — campaigns and\n * transactional mail alike, which is what the staff margin readouts read\n * (`transactional-sends-reach-the-cost-meter.spec.ts`). Only the overage past\n * a plan's band can reach an invoice, and only from the month\n * `BILL_EMAIL_SEND_OVERAGE_FROM` names.\n *\n * ### `campaignEmailSends` — the ENFORCEABLE meter. Counts campaigns only.\n *\n * `emailSendsPerMonth` is checked against this and nothing else. A campaign is\n * discretionary: refusing one at the cap is the outcome the plan sells, the\n * customer sees a clear message, and they upgrade or wait.\n *\n * **Transactional mail is never blocked by a quota, at any tier.** Password\n * resets, invites, order confirmations, booking reminders and workflow\n * notifications send regardless of counter state; they count toward cost and\n * cannot be refused. The failure modes are not symmetric — a blocked password\n * reset locks somebody out of their own account, and the message explaining\n * why is itself an email that will not send; a dropped order confirmation\n * reads to the buyer as a failed order. That converts a billing event into an\n * outage on somebody else's business, where the overage it saved was bounded\n * and billable. It is the same fail-open posture the rest of this codebase\n * takes: rate limiting fails soft, robots/sitemap fail open so a transient\n * error cannot de-index a customer's site.\n *\n * The one bound on it is not a quota (AGL-4145): a per-organization ABUSE\n * ceiling per UTC day on a site's non-campaign mail, sized so no real store\n * reaches it, with security mail exempt even from that. It counts on its own\n * counter (`email-transactional-ceiling.ts`), never on these two.\n *\n * ### Not double-counted\n *\n * One call site, one call to this function, and a campaign send increments BOTH\n * counters from that single call rather than incrementing `emailSends` here and\n * again somewhere else. The counter is keyed by month ON THE DOCUMENT, so\n * nothing accumulates across a re-read, and the rollup re-derives rather than\n * adds. A meter that double-counts is worse than no meter, because it looks\n * authoritative (AGL-1402).\n *\n * ### Transition note\n *\n * `campaignEmailSends` starts empty. For the month this ships, campaign volume\n * already sent is recorded only under the old `emailSends`, so the campaign cap\n * effectively restarts once. That loosens for at most one month, which is the\n * correct direction to be wrong in — the alternative, seeding the enforceable\n * meter from a counter that now also holds transactional mail, would refuse\n * campaigns because of order confirmations.\n */\n\n/** Every send, whatever produced it. The cost meter. */\nexport const EMAIL_SENDS_COUNTER = 'emailSends'\n\n/** Campaign sends alone. The only meter `emailSendsPerMonth` may refuse. */\nexport const CAMPAIGN_EMAIL_SENDS_COUNTER = 'campaignEmailSends'\n\n/** Top-level home for platform-scoped meters: `meters/platform/counters/*`. */\nexport const PLATFORM_METER_COLLECTION = 'meters'\nexport const PLATFORM_METER_DOC = 'platform'\n\n/**\n * Who the send is attributed to.\n *\n * - `host` — a site sent it: campaigns, receipts, booking mail, workflow\n * notifications, member mail. Rolls up to the owning org.\n * - `org` — the org sent it with no site involved: invites, member-added,\n * the welcome mail, usage summaries, erasure notices.\n * - `platform` — Aglyn's own account and staff mail: password resets and\n * verification (which happen before any org is known), new-device and\n * passkey alerts, staff alerts, the system-email test send. Real cost, but\n * not any one customer's, so it is counted apart from every org rollup and\n * never reaches a COGS figure or an invoice.\n */\nexport type EmailMeterScope =\n | { kind: 'host'; hostId: string }\n | { kind: 'org'; orgId: string }\n | { kind: 'platform' }\n\n/**\n * Whether a quota may refuse this send.\n *\n * `campaign` is the ONLY discretionary class. Everything else is\n * `transactional`, which means: count it, never gate on it.\n */\nexport type EmailSendClass = 'campaign' | 'transactional'\n\nexport interface RecordEmailSendsOptions {\n scope: EmailMeterScope\n /** Emails actually handed to the sender. Zero and negatives are no-ops. */\n count: number\n sendClass: EmailSendClass\n /** `YYYY-MM`; defaults to the current UTC month. */\n month?: string\n /** Injectable for tests; defaults to the Admin SDK's Firestore. */\n firestore?: any\n}\n\n/** The counters document for a scope, e.g. `hosts/{id}/counters/emailSends`. */\nexport function emailMeterRef(\n firestore: any,\n scope: EmailMeterScope,\n counter: string,\n): any {\n if (scope.kind === 'host') {\n return firestore\n .collection('hosts')\n .doc(scope.hostId)\n .collection('counters')\n .doc(counter)\n }\n if (scope.kind === 'org') {\n return firestore\n .collection('orgs')\n .doc(scope.orgId)\n .collection('counters')\n .doc(counter)\n }\n return firestore\n .collection(PLATFORM_METER_COLLECTION)\n .doc(PLATFORM_METER_DOC)\n .collection('counters')\n .doc(counter)\n}\n\n/** Current calendar month as `YYYY-MM`, matching every other counter here. */\nexport function currentMeterMonth(now: Date = new Date()): string {\n return now.toISOString().slice(0, 7)\n}\n\n/**\n * Records `count` emails against the cost meter, and against the campaign\n * meter too when the send was a campaign.\n *\n * **Never throws.** Metering is bookkeeping that runs after mail has already\n * gone out — a counter write that fails must not turn a delivered receipt into\n * a 500 for the buyer, and must certainly not be able to stop the next send.\n * Failures are logged and swallowed, the same posture `sendEmail` itself takes.\n */\nexport async function recordEmailSends(\n options: RecordEmailSendsOptions,\n): Promise<void> {\n const { scope, sendClass } = options\n const count = Math.floor(Number(options.count))\n // A send that did not happen is not a cost. `sendEmail` reports `sent` per\n // message, and callers pass the delivered count, so 0 is the ordinary\n // outcome of an unconfigured environment rather than an error.\n if (!Number.isFinite(count) || count <= 0) return\n if (scope.kind === 'host' && !scope.hostId) return\n if (scope.kind === 'org' && !scope.orgId) return\n\n const month = options.month || currentMeterMonth()\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const increment = firebaseAdmin.firestore.FieldValue.increment(count)\n const counters =\n sendClass === 'campaign'\n ? [EMAIL_SENDS_COUNTER, CAMPAIGN_EMAIL_SENDS_COUNTER]\n : [EMAIL_SENDS_COUNTER]\n await Promise.all(\n counters.map((counter) =>\n emailMeterRef(firestore, scope, counter).set(\n { [month]: increment },\n { merge: true },\n ),\n ),\n )\n } catch (error) {\n console.error('email meter write failed', error)\n }\n}\n\n/**\n * One transactional (or, with `sendClass`, campaign) send attributed to a site.\n *\n * The overwhelmingly common call — `await meterHostEmail(hostId)` right after\n * a `sendEmail` — so it reads as one line at every call site and there is one\n * place to change if the counter ever moves.\n */\nexport function meterHostEmail(\n hostId: string,\n count = 1,\n sendClass: EmailSendClass = 'transactional',\n): Promise<void> {\n return recordEmailSends({\n scope: { kind: 'host', hostId },\n count,\n sendClass,\n })\n}\n\n/** Org-scoped transactional mail: invites, welcome, usage summaries. */\nexport function meterOrgEmail(orgId: string, count = 1): Promise<void> {\n return recordEmailSends({\n scope: { kind: 'org', orgId },\n count,\n sendClass: 'transactional',\n })\n}\n\n/**\n * Account and staff mail that belongs to no org at send time — a password\n * reset knows only an address, and a staff alert has no customer at all.\n */\nexport function meterPlatformEmail(count = 1): Promise<void> {\n return recordEmailSends({\n scope: { kind: 'platform' },\n count,\n sendClass: 'transactional',\n })\n}\n\n/**\n * The enforceable figure for a site this month: campaign sends alone.\n *\n * Reads the campaign meter and NOT `emailSends`, which now also holds every\n * receipt and password reset the site sent. Enforcing the plan's cap against\n * that total is exactly the behaviour this issue exists to prevent.\n */\nexport async function campaignEmailSendsForMonth(\n hostRef: any,\n month: string,\n): Promise<number> {\n const snapshot = await hostRef\n .collection('counters')\n .doc(CAMPAIGN_EMAIL_SENDS_COUNTER)\n .get()\n const used = Number(snapshot.get(month) ?? 0)\n // An absent counter is 0, and a corrupt negative must not read as unused\n // headroom that a cap then honours.\n return Number.isFinite(used) && used > 0 ? used : 0\n}\n\n/**\n * The org-level campaign meter, and the ONLY figure `emailSendsPerMonth` is\n * enforced against since AGL-2267.\n *\n * ## Why a second counter and not the per-host one\n *\n * `hosts/{hostId}/counters/campaignEmailSends` is per SITE. `emailSendsPerMonth`\n * is an ORG entitlement. An org with N sites therefore received N × the cap it\n * bought — invisible on Free and Starter (`hostLimit: 1`) and growing with the\n * plan, so the customers who paid most got the most cap they had not paid for.\n *\n * The per-host counter is UNCHANGED and still written, by `meterHostEmail`, on\n * the delivered count. It is per-site history and it feeds the cost meter;\n * nothing about it was wrong except being asked a question about an org.\n *\n * ## Why folding the existing per-site counters in was rejected\n *\n * Summing N site counters into one org total retroactively puts multi-site\n * paying customers over a limit they have been under all along — a limit that\n * then refuses a campaign they had every reason to expect to send, days after\n * they bought the plan. This counter therefore STARTS EMPTY, and the campaign\n * cap effectively restarts once for the month this ships.\n *\n * That is the same transition `campaignEmailSends` itself was given, and the\n * same reasoning: it loosens for at most one month, which is the correct\n * direction to be wrong in, and it needs no production measurement of who is\n * currently over — a measurement that could only be taken against live\n * customer data and would have blocked the fix indefinitely.\n */\nexport const ORG_CAMPAIGN_EMAIL_SENDS_COUNTER = CAMPAIGN_EMAIL_SENDS_COUNTER\n\n/** A granted claim on the org's monthly campaign allowance. */\nexport interface CampaignSendReservation {\n orgId: string\n month: string\n /** Messages claimed up front. */\n reserved: number\n}\n\nexport type ReserveCampaignSendsResult =\n | { ok: true; reservation: CampaignSendReservation; used: number; limit: number }\n | { ok: false; used: number; limit: number }\n\n/** Reads an org-scoped monthly counter field, clamped like every other. */\nfunction readMonthField(snapshot: any, month: string): number {\n const used = Number((snapshot?.exists ? snapshot.get(month) : 0) ?? 0)\n return Number.isFinite(used) && used > 0 ? Math.floor(used) : 0\n}\n\n/**\n * The enforceable figure for an ORG this month: campaign sends alone.\n *\n * Read-only. Used by the campaign composer's recipient preview, which must\n * not reserve anything (AGL-2178 — \"nothing has been written above this\n * line\"), and by anything that reports headroom.\n */\nexport async function orgCampaignEmailSendsForMonth(\n orgId: string,\n month: string,\n firestore?: any,\n): Promise<number> {\n if (!orgId) return 0\n const db = firestore ?? firebaseAdmin.app().firestore()\n const snapshot = await db\n .collection('orgs')\n .doc(orgId)\n .collection('counters')\n .doc(ORG_CAMPAIGN_EMAIL_SENDS_COUNTER)\n .get()\n return readMonthField(snapshot, month)\n}\n\n/**\n * Claims `count` campaign sends against the org's monthly allowance, ATOMICALLY.\n *\n * ## Why a reservation and not a check\n *\n * The cap used to be read before the send and incremented after delivery, so\n * two concurrent campaigns both passed the same reading and both sent — the\n * cap was advisory in exactly the conditions it existed for. **A read-then-write\n * cap is not a cap.**\n *\n * The transaction reads the counter and writes an ABSOLUTE value derived from\n * that read, deliberately not `FieldValue.increment`. Firestore aborts and\n * re-runs the callback when a document the transaction read has moved, so a\n * second sender that starts inside the first one's window re-reads the raised\n * figure and is refused. An increment would be atomic on the number and\n * useless for the decision, because the decision is made from a value the\n * write never proves it still held.\n *\n * A refused reservation writes NOTHING.\n *\n * ## Why reserve-then-reconcile rather than reserve-and-keep\n *\n * A campaign reserves against a PARTIAL delivery: `sendEmail` reports per\n * message, and only some of a 500-address batch may go out. Keeping the whole\n * reservation would charge a customer's allowance for mail that never left.\n * So the claim is taken in full up front — that is what makes it a cap — and\n * {@link reconcileCampaignSendReservation} gives back the difference once the\n * delivered count is known.\n *\n * **The failure mode is stated rather than hidden**: if the process dies\n * between reserving and reconciling, the org is charged for the undelivered\n * remainder for the rest of that calendar month. That is conservative in the\n * direction this issue cares about — it can only ever refuse more mail, never\n * let more out — and it self-heals at the month boundary, because each month\n * is an independent field on the document.\n *\n * `limit` may be `Infinity` (`UNLIMITED`), which admits everything.\n */\nexport async function reserveCampaignEmailSends(options: {\n orgId: string\n month: string\n count: number\n limit: number\n firestore?: any\n}): Promise<ReserveCampaignSendsResult> {\n const count = Math.max(0, Math.floor(Number(options.count) || 0))\n const limit = Number(options.limit)\n // A plan-less or unresolvable org must not be a bypass. The caller resolves\n // free-tier entitlements for it (AGL-247) and the cap is 0, so an empty\n // orgId that reached here means the counter has nowhere to live — refuse\n // rather than send unbounded.\n if (!options.orgId) {\n return { ok: false, used: 0, limit: Number.isFinite(limit) ? limit : 0 }\n }\n const db = options.firestore ?? firebaseAdmin.app().firestore()\n const ref = db\n .collection('orgs')\n .doc(options.orgId)\n .collection('counters')\n .doc(ORG_CAMPAIGN_EMAIL_SENDS_COUNTER)\n\n return db.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = readMonthField(snapshot, options.month)\n if (used + count > limit) return { ok: false, used, limit }\n tx.set(ref, { [options.month]: used + count }, { merge: true })\n return {\n ok: true,\n reservation: { orgId: options.orgId, month: options.month, reserved: count },\n used,\n limit,\n }\n })\n}\n\n/**\n * Returns the undelivered part of a reservation.\n *\n * Also a transaction, and also an absolute write from its own read: a refund\n * computed from a stale figure would undo a reservation another campaign took\n * in the meantime, which is the same defect one direction over.\n *\n * **Never throws** and never drives the counter below zero. This runs after\n * mail has already gone out; a bookkeeping failure must not turn a delivered\n * campaign into a 500, exactly like `recordEmailSends` above. The cost of\n * swallowing it is that the org keeps a claim it did not use for the rest of\n * the month, which is the safe direction.\n */\nexport async function reconcileCampaignSendReservation(\n reservation: CampaignSendReservation | null | undefined,\n delivered: number,\n firestore?: any,\n): Promise<void> {\n if (!reservation?.orgId) return\n const sent = Math.max(0, Math.floor(Number(delivered) || 0))\n const refund = Math.max(0, reservation.reserved - sent)\n if (refund <= 0) return\n try {\n const db = firestore ?? firebaseAdmin.app().firestore()\n const ref = db\n .collection('orgs')\n .doc(reservation.orgId)\n .collection('counters')\n .doc(ORG_CAMPAIGN_EMAIL_SENDS_COUNTER)\n await db.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = readMonthField(snapshot, reservation.month)\n tx.set(\n ref,\n { [reservation.month]: Math.max(0, used - refund) },\n { merge: true },\n )\n })\n } catch (error) {\n console.error('campaign reservation reconcile failed', error)\n }\n}\n\n/**\n * Volume above the plan's included band, in emails — RE-EXPORTED, not defined\n * here, the same move AGL-2155 made for the bandwidth helpers.\n *\n * The definition moved down to `@aglyn/aglyn/app-utils/plan-entitlements`\n * because the billing page has to render the overage BEFORE it is charged,\n * and that page is a client component which cannot import this module: the\n * Admin SDK comes with it. A second copy of the subtraction on the client is\n * the shape where the readout and the invoice quietly stop agreeing.\n *\n * Re-exported so every server caller keeps importing it from the module it\n * always did — one definition, no drift, no import churn.\n *\n * @see priceEmailSendOverage — what the excess costs, at the plan's rate.\n */\nexport { emailSendsOverage } from '@aglyn/aglyn/app-utils/plan-entitlements'\n\nexport default recordEmailSends\n"],"names":["firebaseAdmin","EMAIL_SENDS_COUNTER","CAMPAIGN_EMAIL_SENDS_COUNTER","PLATFORM_METER_COLLECTION","PLATFORM_METER_DOC","emailMeterRef","firestore","scope","counter","kind","collection","doc","hostId","orgId","currentMeterMonth","now","Date","toISOString","slice","recordEmailSends","options","sendClass","count","Math","floor","Number","isFinite","month","app","increment","FieldValue","counters","Promise","all","map","set","merge","error","console","meterHostEmail","meterOrgEmail","meterPlatformEmail","campaignEmailSendsForMonth","hostRef","snapshot","get","used","ORG_CAMPAIGN_EMAIL_SENDS_COUNTER","readMonthField","exists","orgCampaignEmailSendsForMonth","db","reserveCampaignEmailSends","max","limit","ok","ref","runTransaction","tx","reservation","reserved","reconcileCampaignSendReservation","delivered","sent","refund","emailSendsOverage"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,sBAAkB;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsEC,GAED,sDAAsD,GACtD,OAAO,MAAMC,sBAAsB,aAAY;AAE/C,0EAA0E,GAC1E,OAAO,MAAMC,+BAA+B,qBAAoB;AAEhE,6EAA6E,GAC7E,OAAO,MAAMC,4BAA4B,SAAQ;AACjD,OAAO,MAAMC,qBAAqB,WAAU;AAuC5C,8EAA8E,GAC9E,OAAO,SAASC,cACdC,SAAc,EACdC,KAAsB,EACtBC,OAAe;IAEf,IAAID,MAAME,IAAI,KAAK,QAAQ;QACzB,OAAOH,UACJI,UAAU,CAAC,SACXC,GAAG,CAACJ,MAAMK,MAAM,EAChBF,UAAU,CAAC,YACXC,GAAG,CAACH;IACT;IACA,IAAID,MAAME,IAAI,KAAK,OAAO;QACxB,OAAOH,UACJI,UAAU,CAAC,QACXC,GAAG,CAACJ,MAAMM,KAAK,EACfH,UAAU,CAAC,YACXC,GAAG,CAACH;IACT;IACA,OAAOF,UACJI,UAAU,CAACP,2BACXQ,GAAG,CAACP,oBACJM,UAAU,CAAC,YACXC,GAAG,CAACH;AACT;AAEA,4EAA4E,GAC5E,OAAO,SAASM,kBAAkBC,MAAY,IAAIC,MAAM;IACtD,OAAOD,IAAIE,WAAW,GAAGC,KAAK,CAAC,GAAG;AACpC;AAEA;;;;;;;;CAQC,GACD,OAAO,eAAeC,iB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AG9B,KAAKC,KAAK,CAACC,OAAOqC,cAAc;IACzD,MAAME,SAASzC,KAAK8B,GAAG,CAAC,GAAGM,YAAYC,QAAQ,GAAGG;IAClD,IAAIC,UAAU,GAAG;IACjB,IAAI;QACF,MAAMb,KAAK7C,oBAAAA,YAAaN,cAAc4B,GAAG,GAAGtB,SAAS;QACrD,MAAMkD,MAAML,GACTzC,UAAU,CAAC,QACXC,GAAG,CAACgD,YAAY9C,KAAK,EACrBH,UAAU,CAAC,YACXC,GAAG,CAACoC;QACP,MAAMI,GAAGM,cAAc,CAAC,OAAOC;YAC7B,MAAMd,WAAW,MAAMc,GAAGb,GAAG,CAACW;YAC9B,MAAMV,OAAOE,eAAeJ,UAAUe,YAAYhC,KAAK;YACvD+B,GAAGvB,GAAG,CACJqB,KACA;gBAAE,CAACG,YAAYhC,KAAK,CAAC,EAAEJ,KAAK8B,GAAG,CAAC,GAAGP,OAAOkB;YAAQ,GAClD;gBAAE5B,OAAO;YAAK;QAElB;IACF,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,yCAAyCA;IACzD;AACF;AAEA;;;;;;;;;;;;;;CAcC,GACD,SAAS4B,iBAAiB,QAAQ,2CAA0C;AAE5E,eAAe9C,iBAAgB"}
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * The durable half of the daily transactional ceiling (AGL-4145): the
19
+ * counter a site's non-campaign mail is claimed against, and the record a
20
+ * refusal leaves for staff.
21
+ *
22
+ * Which messages are governed, and what the send seam does with a refusal,
23
+ * is `transactional-send-ceiling.ts` in `@aglyn/shared-util-email`. The
24
+ * figures are `transactional-email-ceiling.ts` in `@aglyn/aglyn`, and the one
25
+ * for a workspace is stamped on its sending identity by `hostSendingIdentity`
26
+ * from the org document it already read, so the count below is the only
27
+ * thing this costs a send.
28
+ *
29
+ * ## The counter
30
+ *
31
+ * `orgs/{orgId}/counters/transactionalEmailSends`, one field per UTC day
32
+ * (`YYYY-MM-DD`) holding a count — the shape `campaignEmailSends` beside it
33
+ * has per month, and ORG-scoped for the reason that one became org-scoped in
34
+ * AGL-2267: the ceiling is the organization's, and a per-site count would
35
+ * hand an org with N sites N ceilings. Each day is its own field, so the
36
+ * ceiling starts again at 00:00 UTC with nobody doing anything.
37
+ *
38
+ * It is the CEILING's count, not the cost meter. `emailSends` still counts
39
+ * every delivered message for COGS through `recordEmailSends`, exactly as
40
+ * before; this counts claims, and a claim whose message did not leave is
41
+ * handed back.
42
+ *
43
+ * ## A claim, not a check
44
+ *
45
+ * The transaction reads the day's figure and writes an ABSOLUTE value
46
+ * derived from that read, the campaign reservation's and the governor's
47
+ * shape: a read-then-increment would let two concurrent sends both pass the
48
+ * last slot. A refused claim writes nothing to the counter.
49
+ *
50
+ * ## A refusal is never silent
51
+ *
52
+ * Every refusal is logged and counted on
53
+ * `orgs/{orgId}/counters/transactionalEmailsRefused` (per day, with the
54
+ * ceiling it met and when) — the counters-document shape the form abuse
55
+ * ceiling's `formSubmissionsRefused` uses. The first refusal of the day
56
+ * raises the `deliverability.transactionalCeilingReached` operator alert,
57
+ * which is the staff console notification, the operator email and the
58
+ * webhook. Nothing goes to the workspace: the ceiling is not something its
59
+ * plan names, and no customer-facing surface changes.
60
+ *
61
+ * ## Fails open
62
+ *
63
+ * A counter that cannot be read or written allows the message, the posture
64
+ * of every control on the send path: an outage on the ceiling must not
65
+ * become an outage on every store's receipts.
66
+ */
67
+ import { type TransactionalSendCeilingClaim, type TransactionalSendCeilingRequest, type TransactionalSendCeilingVerdict } from '@aglyn/shared-util-email';
68
+ /** The ceiling's count, per organization per UTC day. */
69
+ export declare const TRANSACTIONAL_EMAIL_SENDS_COUNTER = "transactionalEmailSends";
70
+ /** Refusals past the ceiling, per organization per UTC day. */
71
+ export declare const TRANSACTIONAL_EMAILS_REFUSED_COUNTER = "transactionalEmailsRefused";
72
+ /** The operator alert the first refusal of a day raises. */
73
+ export declare const TRANSACTIONAL_CEILING_ALERT_TYPE = "deliverability.transactionalCeilingReached";
74
+ /**
75
+ * Claims `count` messages against the organization's day, atomically.
76
+ *
77
+ * Allowed: the day's figure is raised by `count` and the claim comes back to
78
+ * be released if the message does not leave. Refused: nothing is written to
79
+ * the counter and `retryAtMs` is the next UTC midnight. The refusal's record
80
+ * is {@link recordTransactionalCeilingRefusal}, which the send seam asks for
81
+ * separately, outside the time budget it gives this claim.
82
+ */
83
+ export declare function claimTransactionalEmailSends(request: TransactionalSendCeilingRequest & {
84
+ firestore?: any;
85
+ }): Promise<TransactionalSendCeilingVerdict>;
86
+ /**
87
+ * Gives back a claim whose message did not leave. Also a transaction, and
88
+ * also an absolute write from its own read, so a release computed from a
89
+ * stale figure cannot undo a claim another send took in the meantime. Never
90
+ * drives the day below zero and never throws: the cost of a failed release
91
+ * is a day counted a little high, which is the safe direction.
92
+ */
93
+ export declare function releaseTransactionalEmailSends(claim: TransactionalSendCeilingClaim | null | undefined, firestore?: any): Promise<void>;
94
+ /**
95
+ * Makes a refusal observable: a log line, the day's refusal count, and — on
96
+ * the first refusal of the day only — the operator alert. An alert per
97
+ * refused message would be the flood again, delivered to staff.
98
+ *
99
+ * Best-effort throughout, like the form ceiling's bookkeeping: a failure here
100
+ * must not turn a contained refusal into a send failure of another kind.
101
+ */
102
+ export declare function recordTransactionalCeilingRefusal(input: {
103
+ orgId: string;
104
+ hostId: string | null;
105
+ dayKey: string;
106
+ count: number;
107
+ used: number;
108
+ ceiling: number;
109
+ context: string | null;
110
+ nowMs: number;
111
+ firestore?: any;
112
+ }): Promise<void>;
113
+ /**
114
+ * Puts the durable ceiling on `sendEmail`'s path.
115
+ *
116
+ * Called at module load, from the bottom of this file, for the reason the
117
+ * governor's installer is: every server surface imports the
118
+ * `@aglyn/tenant-data-admin` barrel, so importing it is enough, and there is
119
+ * no installer for an entrypoint to forget. Idempotent; the state is the
120
+ * Firestore document.
121
+ */
122
+ export declare function installTransactionalSendCeiling(): void;