@aglyn/tenant-data-admin 1.20.0 → 1.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.20.0",
3
+ "version": "1.20.2",
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.20.0",
29
- "@aglyn/shared-util-email": "1.20.0",
30
- "@aglyn/shared-util-fbserver": "1.20.0",
31
- "@aglyn/shared-util-first-touch": "1.20.0",
32
- "@aglyn/shared-util-http": "1.20.0",
33
- "@aglyn/shared-util-tools": "1.20.0",
28
+ "@aglyn/aglyn": "1.20.2",
29
+ "@aglyn/shared-util-email": "1.20.2",
30
+ "@aglyn/shared-util-fbserver": "1.20.2",
31
+ "@aglyn/shared-util-first-touch": "1.20.2",
32
+ "@aglyn/shared-util-http": "1.20.2",
33
+ "@aglyn/shared-util-tools": "1.20.2",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -57,7 +57,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
57
57
  * that a customer's month depends on. Neither is worth the hour of ramp it
58
58
  * would buy back, and the operator can see it: a degraded grant is reported
59
59
  * and surfaced on /admin/emails.
60
- */ import { EMAIL_SEND_RATE_WINDOW_MS, emailSendRateVerdict, emailSendRateWindowStartMs, normalizeEmailSendRateConfig, orgHourlyCampaignCeiling, setEmailSendGovernor } from "@aglyn/shared-util-email";
60
+ */ import { EMAIL_SEND_RATE_WINDOW_MS, emailSendRateVerdict, emailSendRateWindowStartMs, normalizeEmailSendRateConfig, orgHourlyCampaignCeiling, setEmailCredentialRefusalHandler, setEmailSendGovernor } from "@aglyn/shared-util-email";
61
61
  import { firebaseAdmin } from "./firebase-admin.js";
62
62
  import { RATE_LIMIT_COLLECTION } from "./rate-limit-store.js";
63
63
  /** Document id of the live ceiling. NEVER written with `expiresAt`. */ export const EMAIL_SEND_RATE_CONFIG_DOC = 'sendRateConfig';
@@ -444,5 +444,15 @@ let configPending;
444
444
  });
445
445
  }
446
446
  installEmailSendGovernor();
447
+ /** A real send was refused for its key: the alert the mail itself cannot send. */ setEmailCredentialRefusalHandler(async ()=>{
448
+ const { raiseOperatorAlert } = await import("./operator-alerts.js");
449
+ await raiseOperatorAlert('deliverability.providerCredentialsRejected', {
450
+ dedupeKey: 'credentials',
451
+ context: {
452
+ problem: 'the API key was rejected',
453
+ detail: 'The mail provider rejected its credential, so mail sent through it — ' + 'invites, password resets, receipts — is not leaving. Rotate or re-scope it.'
454
+ }
455
+ });
456
+ });
447
457
 
448
458
  //# sourceMappingURL=email-send-rate.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-send-rate.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 SEND-RATE GOVERNOR — durable half (AGL-2409).\n *\n * The policy is pure and lives in `@aglyn/shared-util-email`\n * (`send-rate.ts`); this adds the Firestore counter that makes the ceiling\n * global rather than per-instance, the configuration read that makes a ramp a\n * value change instead of a deploy, and the installation that puts the whole\n * thing on `sendEmail`'s path.\n *\n * ## Storage: the `rateLimits` collection, on purpose\n *\n * Both documents live in `rateLimits`, the same collection AGL-794's counters,\n * AGL-1679's degradation markers and AGL-1907's signup-refusal markers already\n * use, for the reason those two state: it inherits the deny-all security rule\n * and the `expiresAt` TTL policy that already exist rather than needing a new\n * collection, a rules deploy and a second TTL policy.\n *\n * - `rateLimits/sendRate_{windowStartMs}` — one document per hour, holding\n * the count. Carries `expiresAt`, so the TTL policy sweeps it.\n * - `rateLimits/sendRateConfig` — the ceiling. **Carries NO `expiresAt`, and\n * must never be given one**, or the TTL policy that serves the counters\n * would quietly delete the configuration and the platform would silently\n * revert to the compiled-in default. `emailSendRateConfigWrite` is the one\n * writer and `email-send-rate.spec.ts` asserts the field is absent.\n *\n * The window document does NOT carry `lastAtMs`. AGL-1693's rate-limiter\n * health probe queries this collection with `where('lastAtMs', '>=', cutoff)`;\n * a per-hour document in that range would compete with the degradation\n * markers the probe exists to find. It uses `sentAtMs`, which keeps the two\n * queries disjoint at the index level — the same reasoning, and the same\n * mistake avoided, as `refusedAtMs` on the signup markers.\n *\n * ## Failure posture: OPEN\n *\n * If the counter or the config cannot be read, every send is granted. That is\n * the opposite of `consumeRateLimit`'s fail-closed-on-contention rule, and the\n * difference is what the two controls protect. A brute-force limiter that\n * fails open lets an attacker in; this one failing open lets a campaign out.\n * The cost of failing CLOSED here is refusing a paying customer's campaign\n * because of an unrelated Firestore blip — and, worse, refusing a bulk sweep\n * that a customer's month depends on. Neither is worth the hour of ramp it\n * would buy back, and the operator can see it: a degraded grant is reported\n * and surfaced on /admin/emails.\n */\n\nimport {\n type EmailSendGovernorRequest,\n type EmailSendGovernorVerdict,\n type EmailSendPriority,\n type EmailSendRateConfig,\n type EmailSendRateVerdict,\n EMAIL_SEND_RATE_WINDOW_MS,\n emailSendRateVerdict,\n emailSendRateWindowStartMs,\n normalizeEmailSendRateConfig,\n orgHourlyCampaignCeiling,\n setEmailSendGovernor,\n} from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from './firebase-admin'\nimport { RATE_LIMIT_COLLECTION } from './rate-limit-store'\n\n/** Document id of the live ceiling. NEVER written with `expiresAt`. */\nexport const EMAIL_SEND_RATE_CONFIG_DOC = 'sendRateConfig'\n\n/** Id prefix for the per-hour counters. */\nexport const EMAIL_SEND_RATE_WINDOW_PREFIX = 'sendRate_'\n\n/** The counter document id for a window. */\nexport function emailSendRateWindowDocId(windowStartMs: number): string {\n return `${EMAIL_SEND_RATE_WINDOW_PREFIX}${windowStartMs}`\n}\n\n/**\n * Config cache TTL.\n *\n * 15s, the same number and the same reasoning as the platform lockdown doc:\n * this sits on a path that every outbound message crosses, so a per-send read\n * would be one Firestore read per email platform-wide, and 15s is the\n * worst-case lag between staff moving the ramp and a warm process honouring\n * it. A ramp is measured in hours; fifteen seconds is free.\n */\nconst CONFIG_TTL_MS = 15_000\n\nlet configCache: { at: number; config: EmailSendRateConfig } | undefined\nlet configPending: Promise<EmailSendRateConfig> | undefined\n\n/** Drop the in-process config cache — called by the console after a write. */\nexport function invalidateEmailSendRateConfigCache(): void {\n configCache = undefined\n configPending = undefined\n}\n\n/**\n * The live ceiling. Falls back to the compiled-in default on any read error,\n * which is the fail-open posture stated above: an unreachable config must not\n * be read as a ceiling of zero.\n */\nexport async function readEmailSendRateConfig(options?: {\n firestore?: any\n now?: number\n}): Promise<EmailSendRateConfig> {\n const now = options?.now ?? Date.now()\n if (!options?.firestore && configCache && now - configCache.at < CONFIG_TTL_MS) {\n return configCache.config\n }\n const load = async (): Promise<EmailSendRateConfig> => {\n let config = normalizeEmailSendRateConfig(null)\n try {\n const firestore = options?.firestore ?? firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(EMAIL_SEND_RATE_CONFIG_DOC)\n .get()\n config = normalizeEmailSendRateConfig(\n snapshot.exists ? (snapshot.data() as Partial<EmailSendRateConfig>) : null,\n )\n } catch {\n // Fail open: an unreachable config is an outage, not a ceiling of zero.\n }\n return config\n }\n // An injected firestore is a test or a one-off read; never cached, so a\n // spec cannot poison the process cache for the next one.\n if (options?.firestore) return load()\n if (!configPending) {\n configPending = load()\n .then((config) => {\n configCache = { at: now, config }\n return config\n })\n .finally(() => {\n configPending = undefined\n })\n }\n return configPending\n}\n\nexport interface ConsumeEmailSendBudgetOptions {\n priority: EmailSendPriority\n /** Messages this send would add. */\n count: number\n now?: number\n firestore?: any\n /** Injectable for tests; otherwise read (and cached) from Firestore. */\n config?: EmailSendRateConfig\n}\n\nexport interface ConsumeEmailSendBudgetResult extends EmailSendRateVerdict {\n windowStartMs: number\n /** True when the counter was unreachable and this failed open. */\n degraded: boolean\n}\n\n/**\n * Counts `count` messages against the current hour, globally, and answers\n * whether they may go.\n *\n * The transaction reads the counter and writes an ABSOLUTE value derived from\n * that read — not `FieldValue.increment` — because the read is the authority\n * for the decision. Firestore aborts and re-runs the callback when a\n * document it read has moved, so two concurrent sweeps cannot both see the\n * same headroom and both take it. An increment would be atomic on the number\n * and useless for the decision, which is exactly the read-then-write shape\n * AGL-2267 is about one surface over.\n *\n * A refused send writes NOTHING. A caller that will retry next hour must not\n * have spent budget on being told no.\n */\nexport async function consumeEmailSendBudget(\n options: ConsumeEmailSendBudgetOptions,\n): Promise<ConsumeEmailSendBudgetResult> {\n const now = options.now ?? Date.now()\n const windowStartMs = emailSendRateWindowStartMs(now)\n const resetMs = windowStartMs + EMAIL_SEND_RATE_WINDOW_MS\n const config =\n options.config ??\n (await readEmailSendRateConfig({ firestore: options.firestore, now }))\n\n const fallback = (): ConsumeEmailSendBudgetResult => ({\n ...emailSendRateVerdict({\n priority: options.priority,\n used: 0,\n count: options.count,\n ceiling: config.perHour,\n enabled: false,\n windowStartMs,\n }),\n windowStartMs,\n degraded: true,\n })\n\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const ref = firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailSendRateWindowDocId(windowStartMs))\n\n const verdict = await firestore.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = Number((snapshot.exists ? snapshot.get('count') : 0) ?? 0)\n const decision = emailSendRateVerdict({\n priority: options.priority,\n used,\n count: options.count,\n ceiling: config.perHour,\n enabled: config.enabled,\n windowStartMs,\n })\n if (!decision.allowed) return decision\n tx.set(\n ref,\n {\n count: decision.used + Math.max(0, Math.floor(Number(options.count) || 0)),\n windowStartMs,\n // NOT `lastAtMs` — see the storage note at the top of this file.\n sentAtMs: now,\n // The TTL field the counters in this collection already use. Two\n // windows of retention so the console can show the hour just gone.\n expiresAt: new Date(resetMs + EMAIL_SEND_RATE_WINDOW_MS),\n },\n { merge: true },\n )\n return decision\n })\n\n const decided = verdict as EmailSendRateVerdict\n if (!decided.allowed) {\n // Refusable mail is being deferred for the rest of the hour. Told once\n // per six hours (AGL-3377); the operator email itself is transactional,\n // which this governor never refuses.\n await raiseSendRateAlert('deliverability.sendRateSaturated', {\n scope: 'platform',\n detail: `${decided.used ?? '?'}/${decided.ceiling ?? config.perHour} this hour`,\n })\n }\n return { ...decided, windowStartMs, degraded: false }\n } catch (error) {\n console.error('[send-rate] counter unavailable — allowing', error)\n await raiseSendRateAlert('deliverability.sendRateUnavailable', {\n error: error instanceof Error ? error.message.slice(0, 200) : String(error),\n })\n return fallback()\n }\n}\n\n/**\n * Raises a governor alert, loaded lazily so the hot path imports no alert\n * pipeline until the governor actually has something to say. Never throws.\n */\nasync function raiseSendRateAlert(\n type: 'deliverability.sendRateSaturated' | 'deliverability.sendRateUnavailable',\n context: Record<string, string>,\n): Promise<void> {\n try {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert(type, { dedupeKey: type, context })\n } catch (error) {\n console.error(`[send-rate] ${type} could not be raised`, error)\n }\n}\n\n/**\n * What the current hour looks like. Read-only, for the staff console.\n *\n * Returns `used: 0` rather than throwing when the window document does not\n * exist, which is the ordinary state of a quiet hour.\n */\nexport async function readEmailSendRateWindow(options?: {\n firestore?: any\n now?: number\n}): Promise<{ windowStartMs: number; resetMs: number; used: number }> {\n const now = options?.now ?? Date.now()\n const windowStartMs = emailSendRateWindowStartMs(now)\n const resetMs = windowStartMs + EMAIL_SEND_RATE_WINDOW_MS\n try {\n const firestore = options?.firestore ?? firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailSendRateWindowDocId(windowStartMs))\n .get()\n const used = Number((snapshot.exists ? snapshot.get('count') : 0) ?? 0)\n return {\n windowStartMs,\n resetMs,\n used: Number.isFinite(used) && used > 0 ? Math.floor(used) : 0,\n }\n } catch {\n return { windowStartMs, resetMs, used: 0 }\n }\n}\n\n/** Id prefix for the per-org, per-hour campaign counters. */\nexport const EMAIL_ORG_SEND_RATE_WINDOW_PREFIX = 'sendRateOrg_'\n\n/**\n * The per-org counter document id for a window.\n *\n * A separate document per org rather than a map field on the platform window,\n * so two orgs sending in the same hour contend on their own documents instead\n * of serialising on one. The platform window is already a single hot document\n * and adding N org fields to it would make every campaign in the hour a write\n * conflict with every other.\n */\nexport function emailOrgSendRateWindowDocId(\n windowStartMs: number,\n orgId: string,\n): string {\n return `${EMAIL_ORG_SEND_RATE_WINDOW_PREFIX}${windowStartMs}_${orgId}`\n}\n\n/** The current hour for one org. Read-only, for a usage surface. */\nexport async function readOrgEmailSendWindow(options: {\n orgId: string\n firestore?: any\n now?: number\n}): Promise<{ windowStartMs: number; resetMs: number; used: number }> {\n const now = options.now ?? Date.now()\n const windowStartMs = emailSendRateWindowStartMs(now)\n const resetMs = windowStartMs + EMAIL_SEND_RATE_WINDOW_MS\n if (!options.orgId) return { windowStartMs, resetMs, used: 0 }\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailOrgSendRateWindowDocId(windowStartMs, options.orgId))\n .get()\n const used = Number((snapshot.exists ? snapshot.get('count') : 0) ?? 0)\n return {\n windowStartMs,\n resetMs,\n used: Number.isFinite(used) && used > 0 ? Math.floor(used) : 0,\n }\n } catch {\n return { windowStartMs, resetMs, used: 0 }\n }\n}\n\n/** The answer to a per-org hourly claim. Every field is a stated number. */\nexport interface OrgEmailSendClaimResult {\n allowed: boolean\n /** Count in this org's window BEFORE this send. */\n used: number\n /** What this org may send in an hour. */\n ceiling: number\n /** Headroom after this send, floored at 0. */\n remaining: number\n /** When the window rolls and a deferred campaign may go. */\n retryAtMs: number\n /** True when the counter was unreachable and this failed open. */\n degraded: boolean\n}\n\n/**\n * THE PER-ORG SHARE OF THE PLATFORM HOUR.\n *\n * The platform governor bounds total volume; it does not bound how much of\n * that total ONE tenant may take. Without this, a single org with a large\n * audience occupies the whole hour and every other customer's campaigns are\n * refused by a ceiling they did nothing to reach — one tenant denying service\n * to the rest, on a limit they cannot see.\n *\n * The ceiling is derived, not configured: `orgHourlyCampaignCeiling` is a\n * share of whatever the live platform ceiling currently is, so a staff ramp\n * moves both together and the two can never drift into contradiction. See\n * `send-ceilings.ts` for the arithmetic and the relations it maintains.\n *\n * **Campaigns only.** This function is not on `sendEmail`'s path and is called\n * from the campaign sender alone. A transactional message can never reach it,\n * which is the same boundary `emailSendRateVerdict` enforces one layer down\n * and for the same reason: a password reset refused by a throttle converts a\n * reputation risk into an outage on somebody else's business.\n *\n * ## Fails OPEN\n *\n * An unreachable counter grants the send, matching `consumeEmailSendBudget`.\n * A refusal produced by a Firestore blip is a refused campaign for a paying\n * customer, and the hour of pacing it buys back is not worth it.\n *\n * ## Claimed, not reconciled\n *\n * The claim is taken for the whole batch and never refunded, unlike the\n * monthly reservation. The window is one hour and TTL-swept, so an\n * undelivered remainder costs the org the rest of that hour and nothing\n * after it — where an unreconciled MONTHLY claim would cost the rest of the\n * month, which is why that one is reconciled and this one is not. The error\n * is in the direction that can only ever pace mail more, never let more out.\n */\nexport async function claimOrgEmailSendBudget(options: {\n orgId: string\n /** Messages this campaign would send. */\n count: number\n /** The live platform ceiling; the org share is derived from it. */\n platformPerHour: number\n /** False parks the control, exactly as the platform governor's flag does. */\n enabled?: boolean\n now?: number\n firestore?: any\n}): Promise<OrgEmailSendClaimResult> {\n const now = options.now ?? Date.now()\n const windowStartMs = emailSendRateWindowStartMs(now)\n const retryAtMs = windowStartMs + EMAIL_SEND_RATE_WINDOW_MS\n const ceiling = orgHourlyCampaignCeiling(options.platformPerHour)\n const count = Math.max(0, Math.floor(Number(options.count) || 0))\n\n const granted = (used: number, degraded: boolean): OrgEmailSendClaimResult => ({\n allowed: true,\n used,\n ceiling,\n remaining: Math.max(0, ceiling - (used + count)),\n retryAtMs,\n degraded,\n })\n\n // A parked control still reports the ceiling, so a surface reading this\n // shows a real number rather than blanking while the control is off.\n if (options.enabled === false) return granted(0, false)\n // No org means the counter has nowhere to live. The monthly reservation\n // refuses in this case because an unattributable campaign must not send\n // unbounded; here the monthly claim has already made that decision, so\n // failing open costs nothing it has not already been charged for.\n if (!options.orgId) return granted(0, true)\n\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const ref = firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailOrgSendRateWindowDocId(windowStartMs, options.orgId))\n\n return await firestore.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const rawUsed = Number((snapshot.exists ? snapshot.get('count') : 0) ?? 0)\n // A corrupt or negative counter must not read as headroom.\n const used =\n Number.isFinite(rawUsed) && rawUsed > 0 ? Math.floor(rawUsed) : 0\n if (used + count > ceiling) {\n // A refused claim writes NOTHING. A campaign that will be retried\n // next hour must not have spent budget on being told no.\n return {\n allowed: false,\n used,\n ceiling,\n remaining: Math.max(0, ceiling - used),\n retryAtMs,\n degraded: false,\n }\n }\n // An absolute write from this transaction's own read, not\n // `FieldValue.increment` — the read is the authority for the decision,\n // and an increment would be atomic on the number while proving nothing\n // about the value the decision was made from.\n tx.set(\n ref,\n {\n count: used + count,\n windowStartMs,\n orgId: options.orgId,\n // NOT `lastAtMs` — the rate-limiter health probe queries this\n // collection on that field and a per-hour document in its range\n // would compete with the markers it exists to find.\n sentAtMs: now,\n expiresAt: new Date(retryAtMs + EMAIL_SEND_RATE_WINDOW_MS),\n },\n { merge: true },\n )\n return granted(used, false)\n })\n } catch (error) {\n console.error('[send-rate] org window unavailable — allowing', error)\n await raiseSendRateAlert('deliverability.sendRateUnavailable', {\n error: error instanceof Error ? error.message.slice(0, 200) : String(error),\n })\n return granted(0, true)\n }\n}\n\n/**\n * The document the console writes when staff move the ramp.\n *\n * Returned rather than written so the route owns the write (and the audit row\n * beside it), and so a spec can assert the SHAPE without a Firestore. The one\n * thing it must never contain is `expiresAt`.\n */\nexport function emailSendRateConfigWrite(input: {\n perHour: number\n enabled: boolean\n actorEmail?: string | null\n note?: string\n now?: number\n}): Partial<EmailSendRateConfig> {\n const normalized = normalizeEmailSendRateConfig({\n perHour: input.perHour,\n enabled: input.enabled,\n note: input.note,\n updatedAtMs: input.now ?? Date.now(),\n updatedByEmail: input.actorEmail ?? null,\n })\n return {\n perHour: normalized.perHour,\n enabled: normalized.enabled,\n note: normalized.note,\n updatedAtMs: normalized.updatedAtMs,\n updatedByEmail: normalized.updatedByEmail,\n }\n}\n\n/**\n * Puts the durable governor on `sendEmail`'s path.\n *\n * **Called at module load**, from the bottom of this file, so that importing\n * `@aglyn/tenant-data-admin` anywhere is enough — every server surface in the\n * product already imports that barrel, and `export *` forces this module to\n * evaluate. The alternative, an `installEmailSendGovernor()` call at each\n * server entrypoint, is the 37-places-to-remember shape this codebase already\n * rejected once for the `context` tag.\n *\n * Idempotent: installing twice replaces the same closure with an equivalent\n * one, and the closure holds no state — the state is the Firestore document.\n */\nexport function installEmailSendGovernor(): void {\n setEmailSendGovernor(\n async (\n request: EmailSendGovernorRequest,\n ): Promise<EmailSendGovernorVerdict> => {\n const result = await consumeEmailSendBudget({\n priority: request.priority,\n count: request.count,\n })\n return {\n allowed: result.allowed,\n ceiling: result.ceiling,\n used: result.used,\n remaining: result.remaining,\n retryAtMs: result.retryAtMs,\n degraded: result.degraded,\n }\n },\n )\n}\n\ninstallEmailSendGovernor()\n"],"names":["EMAIL_SEND_RATE_WINDOW_MS","emailSendRateVerdict","emailSendRateWindowStartMs","normalizeEmailSendRateConfig","orgHourlyCampaignCeiling","setEmailSendGovernor","firebaseAdmin","RATE_LIMIT_COLLECTION","EMAIL_SEND_RATE_CONFIG_DOC","EMAIL_SEND_RATE_WINDOW_PREFIX","emailSendRateWindowDocId","windowStartMs","CONFIG_TTL_MS","configCache","configPending","invalidateEmailSendRateConfigCache","undefined","readEmailSendRateConfig","options","now","Date","firestore","at","config","load","app","snapshot","collection","doc","get","exists","data","then","finally","consumeEmailSendBudget","resetMs","fallback","priority","used","count","ceiling","perHour","enabled","degraded","ref","verdict","runTransaction","tx","Number","decision","allowed","set","Math","max","floor","sentAtMs","expiresAt","merge","decided","raiseSendRateAlert","scope","detail","error","console","Error","message","slice","String","type","context","raiseOperatorAlert","dedupeKey","readEmailSendRateWindow","isFinite","EMAIL_ORG_SEND_RATE_WINDOW_PREFIX","emailOrgSendRateWindowDocId","orgId","readOrgEmailSendWindow","claimOrgEmailSendBudget","retryAtMs","platformPerHour","granted","remaining","rawUsed","emailSendRateConfigWrite","input","normalized","note","updatedAtMs","updatedByEmail","actorEmail","installEmailSendGovernor","request","result"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED,SAMEA,yBAAyB,EACzBC,oBAAoB,EACpBC,0BAA0B,EAC1BC,4BAA4B,EAC5BC,wBAAwB,EACxBC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,qBAAqB,QAAQ,wBAAoB;AAE1D,qEAAqE,GACrE,OAAO,MAAMC,6BAA6B,iBAAgB;AAE1D,yCAAyC,GACzC,OAAO,MAAMC,gCAAgC,YAAW;AAExD,0CAA0C,GAC1C,OAAO,SAASC,yBAAyBC,aAAqB;IAC5D,OAAO,GAAGF,gCAAgCE,eAAe;AAC3D;AAEA;;;;;;;;CAQC,GACD,MAAMC,gBAAgB;AAEtB,IAAIC;AACJ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;IAC3C;AACF;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,SAASE;IACdtF,qBACE,OACEuF;QAEA,MAAMC,SAAS,MAAM3D,uBAAuB;YAC1CG,UAAUuD,QAAQvD,QAAQ;YAC1BE,OAAOqD,QAAQrD,KAAK;QACtB;QACA,OAAO;YACLW,SAAS2C,OAAO3C,OAAO;YACvBV,SAASqD,OAAOrD,OAAO;YACvBF,MAAMuD,OAAOvD,IAAI;YACjB4C,WAAWW,OAAOX,SAAS;YAC3BH,WAAWc,OAAOd,SAAS;YAC3BpC,UAAUkD,OAAOlD,QAAQ;QAC3B;IACF;AAEJ;AAEAgD"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-send-rate.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 SEND-RATE GOVERNOR — durable half (AGL-2409).\n *\n * The policy is pure and lives in `@aglyn/shared-util-email`\n * (`send-rate.ts`); this adds the Firestore counter that makes the ceiling\n * global rather than per-instance, the configuration read that makes a ramp a\n * value change instead of a deploy, and the installation that puts the whole\n * thing on `sendEmail`'s path.\n *\n * ## Storage: the `rateLimits` collection, on purpose\n *\n * Both documents live in `rateLimits`, the same collection AGL-794's counters,\n * AGL-1679's degradation markers and AGL-1907's signup-refusal markers already\n * use, for the reason those two state: it inherits the deny-all security rule\n * and the `expiresAt` TTL policy that already exist rather than needing a new\n * collection, a rules deploy and a second TTL policy.\n *\n * - `rateLimits/sendRate_{windowStartMs}` — one document per hour, holding\n * the count. Carries `expiresAt`, so the TTL policy sweeps it.\n * - `rateLimits/sendRateConfig` — the ceiling. **Carries NO `expiresAt`, and\n * must never be given one**, or the TTL policy that serves the counters\n * would quietly delete the configuration and the platform would silently\n * revert to the compiled-in default. `emailSendRateConfigWrite` is the one\n * writer and `email-send-rate.spec.ts` asserts the field is absent.\n *\n * The window document does NOT carry `lastAtMs`. AGL-1693's rate-limiter\n * health probe queries this collection with `where('lastAtMs', '>=', cutoff)`;\n * a per-hour document in that range would compete with the degradation\n * markers the probe exists to find. It uses `sentAtMs`, which keeps the two\n * queries disjoint at the index level — the same reasoning, and the same\n * mistake avoided, as `refusedAtMs` on the signup markers.\n *\n * ## Failure posture: OPEN\n *\n * If the counter or the config cannot be read, every send is granted. That is\n * the opposite of `consumeRateLimit`'s fail-closed-on-contention rule, and the\n * difference is what the two controls protect. A brute-force limiter that\n * fails open lets an attacker in; this one failing open lets a campaign out.\n * The cost of failing CLOSED here is refusing a paying customer's campaign\n * because of an unrelated Firestore blip — and, worse, refusing a bulk sweep\n * that a customer's month depends on. Neither is worth the hour of ramp it\n * would buy back, and the operator can see it: a degraded grant is reported\n * and surfaced on /admin/emails.\n */\n\nimport {\n type EmailSendGovernorRequest,\n type EmailSendGovernorVerdict,\n type EmailSendPriority,\n type EmailSendRateConfig,\n type EmailSendRateVerdict,\n EMAIL_SEND_RATE_WINDOW_MS,\n emailSendRateVerdict,\n emailSendRateWindowStartMs,\n normalizeEmailSendRateConfig,\n orgHourlyCampaignCeiling,\n setEmailCredentialRefusalHandler,\n setEmailSendGovernor,\n} from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from './firebase-admin'\nimport { RATE_LIMIT_COLLECTION } from './rate-limit-store'\n\n/** Document id of the live ceiling. NEVER written with `expiresAt`. */\nexport const EMAIL_SEND_RATE_CONFIG_DOC = 'sendRateConfig'\n\n/** Id prefix for the per-hour counters. */\nexport const EMAIL_SEND_RATE_WINDOW_PREFIX = 'sendRate_'\n\n/** The counter document id for a window. */\nexport function emailSendRateWindowDocId(windowStartMs: number): string {\n return `${EMAIL_SEND_RATE_WINDOW_PREFIX}${windowStartMs}`\n}\n\n/**\n * Config cache TTL.\n *\n * 15s, the same number and the same reasoning as the platform lockdown doc:\n * this sits on a path that every outbound message crosses, so a per-send read\n * would be one Firestore read per email platform-wide, and 15s is the\n * worst-case lag between staff moving the ramp and a warm process honouring\n * it. A ramp is measured in hours; fifteen seconds is free.\n */\nconst CONFIG_TTL_MS = 15_000\n\nlet configCache: { at: number; config: EmailSendRateConfig } | undefined\nlet configPending: Promise<EmailSendRateConfig> | undefined\n\n/** Drop the in-process config cache — called by the console after a write. */\nexport function invalidateEmailSendRateConfigCache(): void {\n configCache = undefined\n configPending = undefined\n}\n\n/**\n * The live ceiling. Falls back to the compiled-in default on any read error,\n * which is the fail-open posture stated above: an unreachable config must not\n * be read as a ceiling of zero.\n */\nexport async function readEmailSendRateConfig(options?: {\n firestore?: any\n now?: number\n}): Promise<EmailSendRateConfig> {\n const now = options?.now ?? Date.now()\n if (!options?.firestore && configCache && now - configCache.at < CONFIG_TTL_MS) {\n return configCache.config\n }\n const load = async (): Promise<EmailSendRateConfig> => {\n let config = normalizeEmailSendRateConfig(null)\n try {\n const firestore = options?.firestore ?? firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(EMAIL_SEND_RATE_CONFIG_DOC)\n .get()\n config = normalizeEmailSendRateConfig(\n snapshot.exists ? (snapshot.data() as Partial<EmailSendRateConfig>) : null,\n )\n } catch {\n // Fail open: an unreachable config is an outage, not a ceiling of zero.\n }\n return config\n }\n // An injected firestore is a test or a one-off read; never cached, so a\n // spec cannot poison the process cache for the next one.\n if (options?.firestore) return load()\n if (!configPending) {\n configPending = load()\n .then((config) => {\n configCache = { at: now, config }\n return config\n })\n .finally(() => {\n configPending = undefined\n })\n }\n return configPending\n}\n\nexport interface ConsumeEmailSendBudgetOptions {\n priority: EmailSendPriority\n /** Messages this send would add. */\n count: number\n now?: number\n firestore?: any\n /** Injectable for tests; otherwise read (and cached) from Firestore. */\n config?: EmailSendRateConfig\n}\n\nexport interface ConsumeEmailSendBudgetResult extends EmailSendRateVerdict {\n windowStartMs: number\n /** True when the counter was unreachable and this failed open. */\n degraded: boolean\n}\n\n/**\n * Counts `count` messages against the current hour, globally, and answers\n * whether they may go.\n *\n * The transaction reads the counter and writes an ABSOLUTE value derived from\n * that read — not `FieldValue.increment` — because the read is the authority\n * for the decision. Firestore aborts and re-runs the callback when a\n * document it read has moved, so two concurrent sweeps cannot both see the\n * same headroom and both take it. An increment would be atomic on the number\n * and useless for the decision, which is exactly the read-then-write shape\n * AGL-2267 is about one surface over.\n *\n * A refused send writes NOTHING. A caller that will retry next hour must not\n * have spent budget on being told no.\n */\nexport async function consumeEmailSendBudget(\n options: ConsumeEmailSendBudgetOptions,\n): Promise<ConsumeEmailSendBudgetResult> {\n const now = options.now ?? Date.now()\n const windowStartMs = emailSendRateWindowStartMs(now)\n const resetMs = windowStartMs + EMAIL_SEND_RATE_WINDOW_MS\n const config =\n options.config ??\n (await readEmailSendRateConfig({ firestore: options.firestore, now }))\n\n const fallback = (): ConsumeEmailSendBudgetResult => ({\n ...emailSendRateVerdict({\n priority: options.priority,\n used: 0,\n count: options.count,\n ceiling: config.perHour,\n enabled: false,\n windowStartMs,\n }),\n windowStartMs,\n degraded: true,\n })\n\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const ref = firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailSendRateWindowDocId(windowStartMs))\n\n const verdict = await firestore.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = Number((snapshot.exists ? snapshot.get('count') : 0) ?? 0)\n const decision = emailSendRateVerdict({\n priority: options.priority,\n used,\n count: options.count,\n ceiling: config.perHour,\n enabled: config.enabled,\n windowStartMs,\n })\n if (!decision.allowed) return decision\n tx.set(\n ref,\n {\n count: decision.used + Math.max(0, Math.floor(Number(options.count) || 0)),\n windowStartMs,\n // NOT `lastAtMs` — see the storage note at the top of this file.\n sentAtMs: now,\n // The TTL field the counters in this collection already use. Two\n // windows of retention so the console can show the hour just gone.\n expiresAt: new Date(resetMs + EMAIL_SEND_RATE_WINDOW_MS),\n },\n { merge: true },\n )\n return decision\n })\n\n const decided = verdict as EmailSendRateVerdict\n if (!decided.allowed) {\n // Refusable mail is being deferred for the rest of the hour. Told once\n // per six hours (AGL-3377); the operator email itself is transactional,\n // which this governor never refuses.\n await raiseSendRateAlert('deliverability.sendRateSaturated', {\n scope: 'platform',\n detail: `${decided.used ?? '?'}/${decided.ceiling ?? config.perHour} this hour`,\n })\n }\n return { ...decided, windowStartMs, degraded: false }\n } catch (error) {\n console.error('[send-rate] counter unavailable — allowing', error)\n await raiseSendRateAlert('deliverability.sendRateUnavailable', {\n error: error instanceof Error ? error.message.slice(0, 200) : String(error),\n })\n return fallback()\n }\n}\n\n/**\n * Raises a governor alert, loaded lazily so the hot path imports no alert\n * pipeline until the governor actually has something to say. Never throws.\n */\nasync function raiseSendRateAlert(\n type: 'deliverability.sendRateSaturated' | 'deliverability.sendRateUnavailable',\n context: Record<string, string>,\n): Promise<void> {\n try {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert(type, { dedupeKey: type, context })\n } catch (error) {\n console.error(`[send-rate] ${type} could not be raised`, error)\n }\n}\n\n/**\n * What the current hour looks like. Read-only, for the staff console.\n *\n * Returns `used: 0` rather than throwing when the window document does not\n * exist, which is the ordinary state of a quiet hour.\n */\nexport async function readEmailSendRateWindow(options?: {\n firestore?: any\n now?: number\n}): Promise<{ windowStartMs: number; resetMs: number; used: number }> {\n const now = options?.now ?? Date.now()\n const windowStartMs = emailSendRateWindowStartMs(now)\n const resetMs = windowStartMs + EMAIL_SEND_RATE_WINDOW_MS\n try {\n const firestore = options?.firestore ?? firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailSendRateWindowDocId(windowStartMs))\n .get()\n const used = Number((snapshot.exists ? snapshot.get('count') : 0) ?? 0)\n return {\n windowStartMs,\n resetMs,\n used: Number.isFinite(used) && used > 0 ? Math.floor(used) : 0,\n }\n } catch {\n return { windowStartMs, resetMs, used: 0 }\n }\n}\n\n/** Id prefix for the per-org, per-hour campaign counters. */\nexport const EMAIL_ORG_SEND_RATE_WINDOW_PREFIX = 'sendRateOrg_'\n\n/**\n * The per-org counter document id for a window.\n *\n * A separate document per org rather than a map field on the platform window,\n * so two orgs sending in the same hour contend on their own documents instead\n * of serialising on one. The platform window is already a single hot document\n * and adding N org fields to it would make every campaign in the hour a write\n * conflict with every other.\n */\nexport function emailOrgSendRateWindowDocId(\n windowStartMs: number,\n orgId: string,\n): string {\n return `${EMAIL_ORG_SEND_RATE_WINDOW_PREFIX}${windowStartMs}_${orgId}`\n}\n\n/** The current hour for one org. Read-only, for a usage surface. */\nexport async function readOrgEmailSendWindow(options: {\n orgId: string\n firestore?: any\n now?: number\n}): Promise<{ windowStartMs: number; resetMs: number; used: number }> {\n const now = options.now ?? Date.now()\n const windowStartMs = emailSendRateWindowStartMs(now)\n const resetMs = windowStartMs + EMAIL_SEND_RATE_WINDOW_MS\n if (!options.orgId) return { windowStartMs, resetMs, used: 0 }\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailOrgSendRateWindowDocId(windowStartMs, options.orgId))\n .get()\n const used = Number((snapshot.exists ? snapshot.get('count') : 0) ?? 0)\n return {\n windowStartMs,\n resetMs,\n used: Number.isFinite(used) && used > 0 ? Math.floor(used) : 0,\n }\n } catch {\n return { windowStartMs, resetMs, used: 0 }\n }\n}\n\n/** The answer to a per-org hourly claim. Every field is a stated number. */\nexport interface OrgEmailSendClaimResult {\n allowed: boolean\n /** Count in this org's window BEFORE this send. */\n used: number\n /** What this org may send in an hour. */\n ceiling: number\n /** Headroom after this send, floored at 0. */\n remaining: number\n /** When the window rolls and a deferred campaign may go. */\n retryAtMs: number\n /** True when the counter was unreachable and this failed open. */\n degraded: boolean\n}\n\n/**\n * THE PER-ORG SHARE OF THE PLATFORM HOUR.\n *\n * The platform governor bounds total volume; it does not bound how much of\n * that total ONE tenant may take. Without this, a single org with a large\n * audience occupies the whole hour and every other customer's campaigns are\n * refused by a ceiling they did nothing to reach — one tenant denying service\n * to the rest, on a limit they cannot see.\n *\n * The ceiling is derived, not configured: `orgHourlyCampaignCeiling` is a\n * share of whatever the live platform ceiling currently is, so a staff ramp\n * moves both together and the two can never drift into contradiction. See\n * `send-ceilings.ts` for the arithmetic and the relations it maintains.\n *\n * **Campaigns only.** This function is not on `sendEmail`'s path and is called\n * from the campaign sender alone. A transactional message can never reach it,\n * which is the same boundary `emailSendRateVerdict` enforces one layer down\n * and for the same reason: a password reset refused by a throttle converts a\n * reputation risk into an outage on somebody else's business.\n *\n * ## Fails OPEN\n *\n * An unreachable counter grants the send, matching `consumeEmailSendBudget`.\n * A refusal produced by a Firestore blip is a refused campaign for a paying\n * customer, and the hour of pacing it buys back is not worth it.\n *\n * ## Claimed, not reconciled\n *\n * The claim is taken for the whole batch and never refunded, unlike the\n * monthly reservation. The window is one hour and TTL-swept, so an\n * undelivered remainder costs the org the rest of that hour and nothing\n * after it — where an unreconciled MONTHLY claim would cost the rest of the\n * month, which is why that one is reconciled and this one is not. The error\n * is in the direction that can only ever pace mail more, never let more out.\n */\nexport async function claimOrgEmailSendBudget(options: {\n orgId: string\n /** Messages this campaign would send. */\n count: number\n /** The live platform ceiling; the org share is derived from it. */\n platformPerHour: number\n /** False parks the control, exactly as the platform governor's flag does. */\n enabled?: boolean\n now?: number\n firestore?: any\n}): Promise<OrgEmailSendClaimResult> {\n const now = options.now ?? Date.now()\n const windowStartMs = emailSendRateWindowStartMs(now)\n const retryAtMs = windowStartMs + EMAIL_SEND_RATE_WINDOW_MS\n const ceiling = orgHourlyCampaignCeiling(options.platformPerHour)\n const count = Math.max(0, Math.floor(Number(options.count) || 0))\n\n const granted = (used: number, degraded: boolean): OrgEmailSendClaimResult => ({\n allowed: true,\n used,\n ceiling,\n remaining: Math.max(0, ceiling - (used + count)),\n retryAtMs,\n degraded,\n })\n\n // A parked control still reports the ceiling, so a surface reading this\n // shows a real number rather than blanking while the control is off.\n if (options.enabled === false) return granted(0, false)\n // No org means the counter has nowhere to live. The monthly reservation\n // refuses in this case because an unattributable campaign must not send\n // unbounded; here the monthly claim has already made that decision, so\n // failing open costs nothing it has not already been charged for.\n if (!options.orgId) return granted(0, true)\n\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const ref = firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailOrgSendRateWindowDocId(windowStartMs, options.orgId))\n\n return await firestore.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const rawUsed = Number((snapshot.exists ? snapshot.get('count') : 0) ?? 0)\n // A corrupt or negative counter must not read as headroom.\n const used =\n Number.isFinite(rawUsed) && rawUsed > 0 ? Math.floor(rawUsed) : 0\n if (used + count > ceiling) {\n // A refused claim writes NOTHING. A campaign that will be retried\n // next hour must not have spent budget on being told no.\n return {\n allowed: false,\n used,\n ceiling,\n remaining: Math.max(0, ceiling - used),\n retryAtMs,\n degraded: false,\n }\n }\n // An absolute write from this transaction's own read, not\n // `FieldValue.increment` — the read is the authority for the decision,\n // and an increment would be atomic on the number while proving nothing\n // about the value the decision was made from.\n tx.set(\n ref,\n {\n count: used + count,\n windowStartMs,\n orgId: options.orgId,\n // NOT `lastAtMs` — the rate-limiter health probe queries this\n // collection on that field and a per-hour document in its range\n // would compete with the markers it exists to find.\n sentAtMs: now,\n expiresAt: new Date(retryAtMs + EMAIL_SEND_RATE_WINDOW_MS),\n },\n { merge: true },\n )\n return granted(used, false)\n })\n } catch (error) {\n console.error('[send-rate] org window unavailable — allowing', error)\n await raiseSendRateAlert('deliverability.sendRateUnavailable', {\n error: error instanceof Error ? error.message.slice(0, 200) : String(error),\n })\n return granted(0, true)\n }\n}\n\n/**\n * The document the console writes when staff move the ramp.\n *\n * Returned rather than written so the route owns the write (and the audit row\n * beside it), and so a spec can assert the SHAPE without a Firestore. The one\n * thing it must never contain is `expiresAt`.\n */\nexport function emailSendRateConfigWrite(input: {\n perHour: number\n enabled: boolean\n actorEmail?: string | null\n note?: string\n now?: number\n}): Partial<EmailSendRateConfig> {\n const normalized = normalizeEmailSendRateConfig({\n perHour: input.perHour,\n enabled: input.enabled,\n note: input.note,\n updatedAtMs: input.now ?? Date.now(),\n updatedByEmail: input.actorEmail ?? null,\n })\n return {\n perHour: normalized.perHour,\n enabled: normalized.enabled,\n note: normalized.note,\n updatedAtMs: normalized.updatedAtMs,\n updatedByEmail: normalized.updatedByEmail,\n }\n}\n\n/**\n * Puts the durable governor on `sendEmail`'s path.\n *\n * **Called at module load**, from the bottom of this file, so that importing\n * `@aglyn/tenant-data-admin` anywhere is enough — every server surface in the\n * product already imports that barrel, and `export *` forces this module to\n * evaluate. The alternative, an `installEmailSendGovernor()` call at each\n * server entrypoint, is the 37-places-to-remember shape this codebase already\n * rejected once for the `context` tag.\n *\n * Idempotent: installing twice replaces the same closure with an equivalent\n * one, and the closure holds no state — the state is the Firestore document.\n */\nexport function installEmailSendGovernor(): void {\n setEmailSendGovernor(\n async (\n request: EmailSendGovernorRequest,\n ): Promise<EmailSendGovernorVerdict> => {\n const result = await consumeEmailSendBudget({\n priority: request.priority,\n count: request.count,\n })\n return {\n allowed: result.allowed,\n ceiling: result.ceiling,\n used: result.used,\n remaining: result.remaining,\n retryAtMs: result.retryAtMs,\n degraded: result.degraded,\n }\n },\n )\n}\n\ninstallEmailSendGovernor()\n\n/** A real send was refused for its key: the alert the mail itself cannot send. */\nsetEmailCredentialRefusalHandler(async () => {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert('deliverability.providerCredentialsRejected', {\n dedupeKey: 'credentials',\n context: {\n problem: 'the API key was rejected',\n detail:\n 'The mail provider rejected its credential, so mail sent through it — ' +\n 'invites, password resets, receipts — is not leaving. Rotate or re-scope it.',\n },\n })\n})\n"],"names":["EMAIL_SEND_RATE_WINDOW_MS","emailSendRateVerdict","emailSendRateWindowStartMs","normalizeEmailSendRateConfig","orgHourlyCampaignCeiling","setEmailCredentialRefusalHandler","setEmailSendGovernor","firebaseAdmin","RATE_LIMIT_COLLECTION","EMAIL_SEND_RATE_CONFIG_DOC","EMAIL_SEND_RATE_WINDOW_PREFIX","emailSendRateWindowDocId","windowStartMs","CONFIG_TTL_MS","configCache","configPending","invalidateEmailSendRateConfigCache","undefined","readEmailSendRateConfig","options","now","Date","firestore","at","config","load","app","snapshot","collection","doc","get","exists","data","then","finally","consumeEmailSendBudget","resetMs","fallback","priority","used","count","ceiling","perHour","enabled","degraded","ref","verdict","runTransaction","tx","Number","decision","allowed","set","Math","max","floor","sentAtMs","expiresAt","merge","decided","raiseSendRateAlert","scope","detail","error","console","Error","message","slice","String","type","context","raiseOperatorAlert","dedupeKey","readEmailSendRateWindow","isFinite","EMAIL_ORG_SEND_RATE_WINDOW_PREFIX","emailOrgSendRateWindowDocId","orgId","readOrgEmailSendWindow","claimOrgEmailSendBudget","retryAtMs","platformPerHour","granted","remaining","rawUsed","emailSendRateConfigWrite","input","normalized","note","updatedAtMs","updatedByEmail","actorEmail","installEmailSendGovernor","request","result","problem"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED,SAMEA,yBAAyB,EACzBC,oBAAoB,EACpBC,0BAA0B,EAC1BC,4BAA4B,EAC5BC,wBAAwB,EACxBC,gCAAgC,EAChCC,oBAAoB,QACf,2BAA0B;AACjC,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,qBAAqB,QAAQ,wBAAoB;AAE1D,qEAAqE,GACrE,OAAO,MAAMC,6BAA6B,iBAAgB;AAE1D,yCAAyC,GACzC,OAAO,MAAMC,gCAAgC,YAAW;AAExD,0CAA0C,GAC1C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AS6C,WAAW7C,OAAO;QAC3BC,SAAS4C,WAAW5C,OAAO;QAC3B6C,MAAMD,WAAWC,IAAI;QACrBC,aAAaF,WAAWE,WAAW;QACnCC,gBAAgBH,WAAWG,cAAc;IAC3C;AACF;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,SAASE;IACdtF,qBACE,OACEuF;QAEA,MAAMC,SAAS,MAAM3D,uBAAuB;YAC1CG,UAAUuD,QAAQvD,QAAQ;YAC1BE,OAAOqD,QAAQrD,KAAK;QACtB;QACA,OAAO;YACLW,SAAS2C,OAAO3C,OAAO;YACvBV,SAASqD,OAAOrD,OAAO;YACvBF,MAAMuD,OAAOvD,IAAI;YACjB4C,WAAWW,OAAOX,SAAS;YAC3BH,WAAWc,OAAOd,SAAS;YAC3BpC,UAAUkD,OAAOlD,QAAQ;QAC3B;IACF;AAEJ;AAEAgD;AAEA,gFAAgF,GAChFvF,iCAAiC;IAC/B,MAAM,EAAEkE,kBAAkB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC5C,MAAMA,mBAAmB,8CAA8C;QACrEC,WAAW;QACXF,SAAS;YACPyB,SAAS;YACTjC,QACE,0EACA;QACJ;IACF;AACF"}
@@ -33,7 +33,7 @@ import { isBillingSubscription } from "@aglyn/aglyn/server";
33
33
  // barrel, and which sites a consent group still needs is the rule itself.
34
34
  import { consentGroupSiteHold } from "@aglyn/aglyn/app-utils/consent-groups";
35
35
  import { listPluginOrgCollections } from "@aglyn/aglyn/plugin-manager/plugin-host-collections";
36
- import { erasePluginSiteResources, previewPluginSiteResources } from "@aglyn/aglyn/plugin-manager/plugin-site-resources";
36
+ import { PLUGIN_HOST_KEYED_COLLECTIONS, erasePluginSiteResources, previewPluginSiteResources } from "@aglyn/aglyn/plugin-manager/plugin-site-resources";
37
37
  import { runPluginEventHandlers } from "@aglyn/aglyn/plugin-manager/plugin-events";
38
38
  import { releasedHostNames } from "./host-released-names.js";
39
39
  import { readOrgBilling } from "./org-billing.js";
@@ -180,6 +180,25 @@ import { addAdminAudit } from "./admin-audit-write.js";
180
180
  }
181
181
  return erased;
182
182
  }
183
+ /**
184
+ * Destroy the site's rows in every top-level plugin collection keyed by it
185
+ * (AGL-4214): a register's customer-display state, pairing codes and tokens.
186
+ *
187
+ * Bounded by the declared field, like every top-level sweep here, because each
188
+ * of these collections holds every other site's rows too. Best-effort and per
189
+ * collection, like every other trailing cleanup in `eraseHost`, so one failed
190
+ * query leaves the others' cleanup standing.
191
+ */ async function erasePluginHostKeyedCollections(hostId) {
192
+ let erased = 0;
193
+ for (const { name, siteField } of PLUGIN_HOST_KEYED_COLLECTIONS){
194
+ try {
195
+ erased += await deleteDocsByOrgId(name, hostId, false, siteField);
196
+ } catch (error) {
197
+ console.error(`eraseHost: ${name} cleanup failed for ${hostId}`, error);
198
+ }
199
+ }
200
+ return erased;
201
+ }
183
202
  /**
184
203
  * What the Delete site card shows before it asks (AGL-4003): the resources
185
204
  * plugins share with the site alone, which go with it — a dataset and its
@@ -316,6 +335,9 @@ export async function eraseHost(hostId, options = {}) {
316
335
  }
317
336
  // The host document tree (screens/layouts/versions/counters/products/…).
318
337
  await firestore.recursiveDelete(hostRef);
338
+ // The plugin rows keyed by the site that its tree does not hold (AGL-4214).
339
+ // After the tree, so a register's display can no longer verify against it.
340
+ await erasePluginHostKeyedCollections(hostId);
319
341
  // Once more now the site is gone: a membership sync that was mid-flight when
320
342
  // the first pass ran can write the row back afterwards, and a row for a
321
343
  // deleted site keeps it in the switcher and mapped to its subdomain. Last
@@ -463,7 +485,8 @@ export async function eraseHost(hostId, options = {}) {
463
485
  }
464
486
  /**
465
487
  * Delete every document in a TOP-LEVEL collection that names this org in its
466
- * `orgId` FIELD (AGL-1444/AGL-1448).
488
+ * `orgId` FIELD (AGL-1444/AGL-1448). `orgField` names another field, which is
489
+ * how a site delete sweeps the collections keyed by a site (AGL-4214).
467
490
  *
468
491
  * The shared mechanism behind every collection a path-scoped cascade cannot
469
492
  * see. Two properties are the whole point, and neither is optional: