@aglyn/tenant-data-admin 1.0.0-beta.200 → 1.0.0-beta.202
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 +8 -7
- package/src/lib/server/card-payment-velocity.d.ts +85 -0
- package/src/lib/server/card-payment-velocity.js +202 -0
- package/src/lib/server/card-payment-velocity.js.map +1 -0
- package/src/lib/server/configured-url-fetch.d.ts +42 -0
- package/src/lib/server/configured-url-fetch.js +118 -0
- package/src/lib/server/configured-url-fetch.js.map +1 -0
- package/src/lib/server/dns-probe.d.ts +7 -0
- package/src/lib/server/dns-probe.js +52 -0
- package/src/lib/server/dns-probe.js.map +1 -1
- package/src/lib/server/email-deliverability.d.ts +150 -0
- package/src/lib/server/email-deliverability.js +538 -0
- package/src/lib/server/email-deliverability.js.map +1 -0
- package/src/lib/server/email-sender-reputation.d.ts +2 -11
- package/src/lib/server/email-sender-reputation.js +8 -25
- package/src/lib/server/email-sender-reputation.js.map +1 -1
- package/src/lib/server/email-suppression.d.ts +10 -1
- package/src/lib/server/email-suppression.js +4 -3
- package/src/lib/server/email-suppression.js.map +1 -1
- package/src/lib/server/erase-person.js +31 -3
- package/src/lib/server/erase-person.js.map +1 -1
- package/src/lib/server/host-visitor-records.d.ts +16 -2
- package/src/lib/server/host-visitor-records.js +31 -6
- package/src/lib/server/host-visitor-records.js.map +1 -1
- package/src/lib/server/hosted-page-review.d.ts +112 -0
- package/src/lib/server/hosted-page-review.js +378 -0
- package/src/lib/server/hosted-page-review.js.map +1 -0
- package/src/lib/server/member-email-aliases.js +18 -7
- package/src/lib/server/member-email-aliases.js.map +1 -1
- package/src/lib/server/notifications.d.ts +8 -0
- package/src/lib/server/notifications.js +92 -17
- package/src/lib/server/notifications.js.map +1 -1
- package/src/lib/server/org-age.d.ts +27 -0
- package/src/lib/server/org-age.js +44 -0
- package/src/lib/server/org-age.js.map +1 -0
- package/src/lib/server/org-member-notice.js +20 -5
- package/src/lib/server/org-member-notice.js.map +1 -1
- package/src/lib/server/organizations.d.ts +10 -1
- package/src/lib/server/organizations.js +12 -4
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/outbound-send-review.d.ts +224 -0
- package/src/lib/server/outbound-send-review.js +479 -0
- package/src/lib/server/outbound-send-review.js.map +1 -0
- package/src/lib/server/payment-fraud-signal.d.ts +156 -0
- package/src/lib/server/payment-fraud-signal.js +368 -0
- package/src/lib/server/payment-fraud-signal.js.map +1 -0
- package/src/lib/server/payment-risk-record.d.ts +59 -0
- package/src/lib/server/payment-risk-record.js +76 -0
- package/src/lib/server/payment-risk-record.js.map +1 -0
- package/src/lib/server/render-system-email.d.ts +176 -0
- package/src/lib/server/render-system-email.js +315 -0
- package/src/lib/server/render-system-email.js.map +1 -0
- package/src/lib/server/sending-domains.d.ts +6 -0
- package/src/lib/server/sending-domains.js +98 -6
- package/src/lib/server/sending-domains.js.map +1 -1
- package/src/lib/server/staff-alert-email.d.ts +2 -1
- package/src/lib/server/staff-alert-email.js +16 -5
- package/src/lib/server/staff-alert-email.js.map +1 -1
- package/src/lib/server/stripe-card-authentication.d.ts +35 -0
- package/src/lib/server/stripe-card-authentication.js +63 -0
- package/src/lib/server/stripe-card-authentication.js.map +1 -0
- package/src/lib/server/tenant-write-lockdown.d.ts +32 -2
- package/src/lib/server/tenant-write-lockdown.js +33 -3
- package/src/lib/server/tenant-write-lockdown.js.map +1 -1
- package/src/tenancy.d.ts +5 -0
- package/src/tenancy.js +10 -0
- package/src/tenancy.js.map +1 -1
|
@@ -69,6 +69,8 @@
|
|
|
69
69
|
* sending; the refusal it would produce is not bounded by anything.
|
|
70
70
|
*/
|
|
71
71
|
import { type EmailRampVerdict, type EmailReputationCounts, type EmailReputationPolicy, type EmailReputationVerdict } from '@aglyn/shared-util-email';
|
|
72
|
+
import { orgAgeDays } from './org-age';
|
|
73
|
+
export { orgAgeDays };
|
|
72
74
|
/** Id prefix for the per-org, per-day reputation documents. */
|
|
73
75
|
export declare const EMAIL_REPUTATION_DOC_PREFIX = "emailRep_";
|
|
74
76
|
/** The document id for one workspace's day. */
|
|
@@ -313,16 +315,5 @@ export declare function claimOrgEmailSendDay(options: {
|
|
|
313
315
|
* `reconcileCampaignSendReservation` does one surface over.
|
|
314
316
|
*/
|
|
315
317
|
export declare function reconcileOrgEmailSendDay(reservation: OrgEmailSendDayReservation | null | undefined, delivered: number, firestore?: any): Promise<void>;
|
|
316
|
-
/**
|
|
317
|
-
* How old a workspace is, in days, from whatever its `createdAt` turns out to
|
|
318
|
-
* be.
|
|
319
|
-
*
|
|
320
|
-
* Firestore hands back a `Timestamp`, a restore or a fixture can leave a
|
|
321
|
-
* number, and an org written before the field existed has nothing. All three
|
|
322
|
-
* are handled and the last one answers `null`, which
|
|
323
|
-
* {@link claimOrgEmailSendDay} reads as graduated — the only safe direction,
|
|
324
|
-
* for the reason stated there.
|
|
325
|
-
*/
|
|
326
|
-
export declare function orgAgeDays(createdAt: unknown, now?: number): number | null;
|
|
327
318
|
/** Re-exported so a caller reads one module for the whole control. */
|
|
328
319
|
export type { EmailReputationPolicy, EmailRampVerdict };
|
|
@@ -67,10 +67,17 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
67
67
|
* and a refusal produced by a Firestore blip is an outage dressed as a policy
|
|
68
68
|
* decision. The reputation risk it fails to catch is bounded by an hour of
|
|
69
69
|
* sending; the refusal it would produce is not bounded by anything.
|
|
70
|
-
*/ import { EMAIL_REPUTATION_WINDOW_DAYS, emailRampVerdict, emailReputationVerdict, normalizeEmailReputationPolicy, orgDailyCampaignCeiling, reputationDayKey, reputationWindowDayKeys
|
|
70
|
+
*/ import { EMAIL_REPUTATION_WINDOW_DAYS, emailRampVerdict, emailReputationVerdict, normalizeEmailReputationPolicy, orgDailyCampaignCeiling, reputationDayKey, reputationWindowDayKeys } from "@aglyn/shared-util-email";
|
|
71
71
|
import { readEmailSendRateConfig } from "./email-send-rate.js";
|
|
72
72
|
import { firebaseAdmin } from "./firebase-admin.js";
|
|
73
73
|
import { RATE_LIMIT_COLLECTION } from "./rate-limit-store.js";
|
|
74
|
+
/*
|
|
75
|
+
* `orgAgeDays` lives in its own leaf so a caller that needs only the age —
|
|
76
|
+
* the outbound phishing screen (AGL-3356) — does not load this module, whose
|
|
77
|
+
* import installs the platform send-rate governor. Re-exported, so every
|
|
78
|
+
* existing reader of it here is unchanged.
|
|
79
|
+
*/ import { orgAgeDays } from "./org-age.js";
|
|
80
|
+
export { orgAgeDays };
|
|
74
81
|
/** Id prefix for the per-org, per-day reputation documents. */ export const EMAIL_REPUTATION_DOC_PREFIX = 'emailRep_';
|
|
75
82
|
/** One day in ms, named so the arithmetic below reads as arithmetic. */ const DAY_MS = 86400000;
|
|
76
83
|
/** The document id for one workspace's day. */ export function emailReputationDocId(dayKey, orgId) {
|
|
@@ -439,29 +446,5 @@ function reputationRef(firestore, dayKey, orgId) {
|
|
|
439
446
|
console.error('[sender-reputation] day reconcile failed', error);
|
|
440
447
|
}
|
|
441
448
|
}
|
|
442
|
-
/**
|
|
443
|
-
* How old a workspace is, in days, from whatever its `createdAt` turns out to
|
|
444
|
-
* be.
|
|
445
|
-
*
|
|
446
|
-
* Firestore hands back a `Timestamp`, a restore or a fixture can leave a
|
|
447
|
-
* number, and an org written before the field existed has nothing. All three
|
|
448
|
-
* are handled and the last one answers `null`, which
|
|
449
|
-
* {@link claimOrgEmailSendDay} reads as graduated — the only safe direction,
|
|
450
|
-
* for the reason stated there.
|
|
451
|
-
*/ export function orgAgeDays(createdAt, now = Date.now()) {
|
|
452
|
-
const raw = createdAt;
|
|
453
|
-
let createdMs = 0;
|
|
454
|
-
if (typeof raw === 'number') createdMs = raw;
|
|
455
|
-
else if (typeof raw === 'string') createdMs = Date.parse(raw);
|
|
456
|
-
else if (typeof (raw == null ? void 0 : raw.toMillis) === 'function') createdMs = raw.toMillis();
|
|
457
|
-
else if (typeof (raw == null ? void 0 : raw.seconds) === 'number') createdMs = raw.seconds * 1000;
|
|
458
|
-
/*
|
|
459
|
-
* The one check, and it has to answer `null` rather than 0. A creation date
|
|
460
|
-
* that could not be read is an org whose record predates the field, which
|
|
461
|
-
* is an EXISTING customer; `0` would say "created today" and ramp every
|
|
462
|
-
* paying tenant on the platform down to the first step.
|
|
463
|
-
*/ if (!Number.isFinite(createdMs) || createdMs <= 0) return null;
|
|
464
|
-
return daysBetween(createdMs, now);
|
|
465
|
-
}
|
|
466
449
|
|
|
467
450
|
//# sourceMappingURL=email-sender-reputation.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-sender-reputation.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 * PER-TENANT SENDING REPUTATION — the durable half.\n *\n * The policy is pure and lives in `@aglyn/shared-util-email`\n * (`sender-reputation.ts`); this adds the counters that make a rate a fact\n * rather than an intention, and the daily claim that paces a workspace's\n * first week.\n *\n * ## One document per workspace per day\n *\n * `rateLimits/emailRep_{YYYY-MM-DD}_{orgId}` holds four numbers:\n *\n * - `claimed` — campaign messages the day's ramp has granted. The PACING\n * counter, taken before a send and reconciled to what actually left.\n * - `accepted` — campaign messages that actually left. The DENOMINATOR every\n * rate divides by.\n * - `bounced`, `complained` — what the provider reported back.\n *\n * A day per document rather than a map of days on one, because the day is\n * what the TTL policy can sweep: `rateLimits` already carries an `expiresAt`\n * policy, and a document that ages out is a window that prunes itself. A map\n * of every day a workspace has ever sent would grow forever and would have to\n * be pruned by a job nobody would write.\n *\n * A per-ORG document rather than per-site, because the org is the tenant: the\n * plan, the monthly allowance and the hourly share are all keyed on it, and a\n * merchant with three sites on one domain is one sender to a mailbox\n * provider.\n *\n * The window document deliberately carries **no `lastAtMs`** — the\n * rate-limiter health probe queries this collection on that field, and a\n * per-day document in its range would compete with the degradation markers it\n * exists to find. The same reasoning as `sendRate_*` and `sendRateOrg_*`\n * beside it.\n *\n * ## Which day a bounce is filed under\n *\n * The day the EVENT arrived, not the day the message was sent. The webhook\n * knows the first and would need a per-message lookup for the second, and\n * over a seven-day window the two differ only at the edges — a bounce lands\n * within minutes and a complaint within hours or a day. Stated because the\n * rate is a ratio of two things counted on slightly different clocks, and a\n * reader comparing it against a provider's dashboard should know why they\n * will not agree to the last decimal.\n *\n * ## Failure posture: OPEN, and that is not the usual answer here\n *\n * An unreadable counter grades `ok` and grants the send, matching\n * `consumeEmailSendBudget` and `claimOrgEmailSendBudget`. The breaker is the\n * one control in this file that could refuse a paying customer's campaign,\n * and a refusal produced by a Firestore blip is an outage dressed as a policy\n * decision. The reputation risk it fails to catch is bounded by an hour of\n * sending; the refusal it would produce is not bounded by anything.\n */\n\nimport {\n EMAIL_REPUTATION_WINDOW_DAYS,\n emailRampVerdict,\n emailReputationVerdict,\n normalizeEmailReputationPolicy,\n orgDailyCampaignCeiling,\n reputationDayKey,\n reputationWindowDayKeys,\n daysBetween,\n type EmailRampVerdict,\n type EmailReputationCounts,\n type EmailReputationPolicy,\n type EmailReputationVerdict,\n} from '@aglyn/shared-util-email'\nimport { readEmailSendRateConfig } from './email-send-rate'\nimport { firebaseAdmin } from './firebase-admin'\nimport { RATE_LIMIT_COLLECTION } from './rate-limit-store'\n\n/** Id prefix for the per-org, per-day reputation documents. */\nexport const EMAIL_REPUTATION_DOC_PREFIX = 'emailRep_'\n\n/** One day in ms, named so the arithmetic below reads as arithmetic. */\nconst DAY_MS = 86_400_000\n\n/** The document id for one workspace's day. */\nexport function emailReputationDocId(dayKey: string, orgId: string): string {\n return `${EMAIL_REPUTATION_DOC_PREFIX}${dayKey}_${orgId}`\n}\n\n/** The counted fields, so a writer cannot invent a fifth by typo. */\nexport type EmailReputationCounter =\n | 'claimed'\n | 'accepted'\n | 'bounced'\n | 'complained'\n\nfunction reputationRef(firestore: any, dayKey: string, orgId: string): any {\n return firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailReputationDocId(dayKey, orgId))\n}\n\n/** A stored count, clamped. A corrupt negative reads as 0, never as headroom. */\nfunction storedCount(snapshot: any, field: EmailReputationCounter): number {\n const value = Number((snapshot?.exists ? snapshot.get(field) : 0) ?? 0)\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0\n}\n\n/**\n * When a day's document may be swept.\n *\n * One window plus a day of slack past the end of the day it counts, so the\n * oldest day a rate still divides by is never deleted underneath the read\n * that needs it.\n */\nfunction reputationExpiresAt(dayStartMs: number): Date {\n return new Date(dayStartMs + (EMAIL_REPUTATION_WINDOW_DAYS + 2) * DAY_MS)\n}\n\n/** Midnight UTC of the day a timestamp falls in. */\nfunction dayStartMs(atMs: number): number {\n return Math.floor(atMs / DAY_MS) * DAY_MS\n}\n\n/**\n * Adds to one of a workspace's daily counters.\n *\n * **Never throws.** Reputation accounting runs after mail has gone out, or\n * inside a webhook the provider will retry — a counter write that failed must\n * not turn a delivered campaign into a 500 or a webhook into a retry storm.\n * `FieldValue.increment` rather than a transaction because nothing decides\n * anything from this write: the decision is made by a separate read, and an\n * increment is the contention-free way to record a fact.\n */\nexport async function recordEmailReputationEvent(options: {\n orgId: string\n counter: EmailReputationCounter\n count?: number\n atMs?: number\n firestore?: any\n}): Promise<void> {\n const orgId = String(options.orgId ?? '')\n const count = Math.floor(Number(options.count ?? 1))\n if (!orgId || !Number.isFinite(count) || count <= 0) return\n const atMs = Number(options.atMs ?? Date.now())\n const at = Number.isFinite(atMs) && atMs > 0 ? atMs : Date.now()\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n await reputationRef(firestore, reputationDayKey(at), orgId).set(\n {\n [options.counter]: firebaseAdmin.firestore.FieldValue.increment(count),\n orgId,\n dayKey: reputationDayKey(at),\n // NOT `lastAtMs` — see the storage note at the top of this file.\n expiresAt: reputationExpiresAt(dayStartMs(at)),\n },\n { merge: true },\n )\n } catch (error) {\n console.error('[sender-reputation] counter write failed', error)\n }\n}\n\n/** Campaign messages that actually left, for a workspace. The denominator. */\nexport function recordCampaignAccepted(\n orgId: string,\n count: number,\n options?: { atMs?: number; firestore?: any },\n): Promise<void> {\n return recordEmailReputationEvent({\n orgId,\n counter: 'accepted',\n count,\n ...options,\n })\n}\n\n/**\n * A permanent bounce or a spam complaint, attributed to the workspace that\n * sent it.\n *\n * The suppression the same event produces is a separate act and is not\n * conditional on this: an address comes off the list whether or not the\n * counter write lands.\n */\nexport function recordEmailReputationFailure(\n orgId: string,\n kind: 'bounce' | 'complaint',\n options?: { atMs?: number; firestore?: any },\n): Promise<void> {\n return recordEmailReputationEvent({\n orgId,\n counter: kind === 'complaint' ? 'complained' : 'bounced',\n count: 1,\n ...options,\n })\n}\n\n/** The counts a workspace's window holds, plus what the ramp needs. */\nexport interface SenderReputationWindow extends EmailReputationCounts {\n /**\n * Campaign messages the ramp has granted TODAY.\n *\n * Read here rather than by a second query because today's document is\n * already in this window: the ramp needs one number off it and the rates\n * need three off all of them, and two reads of one document to answer two\n * questions about the same workspace is a round trip nobody has to pay.\n */\n claimedToday: number\n /**\n * Campaign messages accepted TODAY and YESTERDAY (UTC), summed.\n *\n * What the List-Unsubscribe bulk guard counts as \"the last 24 hours\"\n * (AGL-3307). The counters are per calendar day, so a rolling 24 hours is\n * not available — and two days is a superset of it: it never counts fewer\n * messages than the trailing 24 hours held, so the guard can only err\n * toward carrying the header. Read off the window's own documents, at no\n * extra cost.\n */\n acceptedLastTwoDays: number\n /** Days the window covers. */\n windowDays: number\n /** True when the window could not be read and everything below is zero. */\n degraded: boolean\n}\n\n/**\n * Sums a workspace's last {@link EMAIL_REPUTATION_WINDOW_DAYS} days.\n *\n * One `getAll` over the window's day documents — seven reads per campaign,\n * not per message, and none at all for a workspace that has never sent. An\n * absent day is a quiet day and reads as zero.\n */\nexport async function readSenderReputationWindow(options: {\n orgId: string\n now?: number\n windowDays?: number\n firestore?: any\n}): Promise<SenderReputationWindow> {\n const windowDays = Math.max(\n 1,\n Math.floor(Number(options.windowDays ?? EMAIL_REPUTATION_WINDOW_DAYS)) ||\n EMAIL_REPUTATION_WINDOW_DAYS,\n )\n const empty: SenderReputationWindow = {\n accepted: 0,\n bounced: 0,\n complained: 0,\n claimedToday: 0,\n acceptedLastTwoDays: 0,\n windowDays,\n degraded: false,\n }\n const orgId = String(options.orgId ?? '')\n if (!orgId) return empty\n const now = Number(options.now ?? Date.now())\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const dayKeys = reputationWindowDayKeys(now, windowDays)\n const today = reputationDayKey(now)\n const yesterday = reputationDayKey(now - DAY_MS)\n const snapshots = await firestore.getAll(\n ...dayKeys.map((dayKey) => reputationRef(firestore, dayKey, orgId)),\n )\n return snapshots.reduce(\n (totals: SenderReputationWindow, snapshot: any, index: number) => ({\n ...totals,\n accepted: totals.accepted + storedCount(snapshot, 'accepted'),\n bounced: totals.bounced + storedCount(snapshot, 'bounced'),\n complained: totals.complained + storedCount(snapshot, 'complained'),\n claimedToday:\n dayKeys[index] === today\n ? totals.claimedToday + storedCount(snapshot, 'claimed')\n : totals.claimedToday,\n acceptedLastTwoDays:\n dayKeys[index] === today || dayKeys[index] === yesterday\n ? totals.acceptedLastTwoDays + storedCount(snapshot, 'accepted')\n : totals.acceptedLastTwoDays,\n }),\n empty,\n )\n } catch (error) {\n console.error('[sender-reputation] window unavailable — grading ok', error)\n return { ...empty, degraded: true }\n }\n}\n\n/** A workspace's reputation, and whether its campaigns may go out. */\nexport interface SenderReputationRead extends EmailReputationVerdict {\n /** True when the window could not be read, so nothing was graded. */\n degraded: boolean\n /** The counts the grade was made from, so a caller can size a ramp too. */\n window: SenderReputationWindow\n}\n\n/**\n * Grades one workspace.\n *\n * The policy and the grace period come from the ORG DOCUMENT, which the\n * campaign sender has already read — passed in rather than re-fetched, so\n * this costs the window read and nothing else.\n */\nexport async function readSenderReputation(options: {\n orgId: string\n policy?: unknown\n reinstatedUntilMs?: unknown\n now?: number\n firestore?: any\n}): Promise<SenderReputationRead> {\n const now = Number(options.now ?? Date.now())\n const window = await readSenderReputationWindow({\n orgId: options.orgId,\n now,\n firestore: options.firestore,\n })\n const verdict = emailReputationVerdict({\n counts: window,\n // A degraded read grades against zeroes, which is `ok` by construction.\n // Stated rather than special-cased: the fail-open posture at the top of\n // this file is the reason, and a branch here would be a second place for\n // it to be got wrong.\n policy: normalizeEmailReputationPolicy(options.policy),\n windowDays: window.windowDays,\n reinstatedUntilMs: Number(options.reinstatedUntilMs ?? 0) || null,\n now,\n })\n return { ...verdict, degraded: window.degraded, window }\n}\n\n/**\n * The ramp step a workspace has EARNED, from a window it has already read.\n *\n * A thin wrapper over the pure policy that supplies the one number the policy\n * cannot know: what a graduated workspace's day is, which is a share of the\n * live platform ceiling and therefore moves with a staff ramp.\n */\nexport function resolveOrgEmailRamp(options: {\n /** Days since the workspace was created; null or absent graduates it. */\n ageDays: number | null | undefined\n /** Campaign messages it has delivered inside the window. */\n deliveredLifetime: number\n /** The live platform ceiling. */\n platformPerHour: number\n}): EmailRampVerdict {\n return emailRampVerdict({\n ageDays: options.ageDays,\n deliveredLifetime: options.deliveredLifetime,\n graduatedPerDay: orgDailyCampaignCeiling(options.platformPerHour),\n })\n}\n\n/** A workspace's ramp step, and whether the history behind it was readable. */\nexport interface OrgEmailRampRead {\n /** The step, from the age and the delivery history that resolved. */\n ramp: EmailRampVerdict\n /**\n * True when the ramp BINDS and the window it is sized from was unreadable,\n * so {@link ramp} is a floor rather than an answer.\n *\n * A caller that pages a batch — the campaign path — may treat this as the\n * step and carry on, because the floor is the lowest step and erring low\n * defers mail rather than sending it. A caller that admits or refuses ONE\n * message has no such third answer and must refuse: see\n * {@link readOrgEmailRamp}.\n */\n degraded: boolean\n}\n\n/**\n * A workspace's ramp step, resolved from its record and its history.\n *\n * The reads {@link resolveOrgEmailRamp} needs, in the order that pays for\n * the fewest of them. The platform ceiling comes first because it is process-\n * cached for fifteen seconds and therefore free; the seven-day window is a\n * `getAll` and is only paid when the ramp can still bind.\n *\n * ## A graduated workspace pays nothing\n *\n * Age alone decides graduation — delivery volume can only RAISE a step, never\n * reach past the last one — so a workspace past its first week is answered\n * from the org record with no window read at all. That is every existing\n * customer and every org whose record predates the creation timestamp, which\n * is to say almost every call.\n *\n * ## An unreadable window is `degraded`, and it is the caller's to answer\n *\n * The window read grades itself rather than throwing, and an unreadable one\n * reads as zero delivered — the LOWEST step, which is the conservative\n * direction for a ceiling. What it is not is a fact, so it is flagged: a\n * surface admitting one message at a time cannot defer the remainder to\n * tomorrow the way a campaign can, and a limiter with no answer must refuse\n * rather than admit.\n *\n * ## The platform flag parks this control\n *\n * `enabled: false` on the send-rate config graduates every workspace here,\n * exactly as it parks the hourly share and {@link claimOrgEmailSendDay} — one\n * switch, and it turns the ramp off everywhere it is consulted.\n */\nexport async function readOrgEmailRamp(options: {\n orgId: string\n /** The org record's `createdAt`, in whatever shape it was stored. */\n createdAt: unknown\n now?: number\n firestore?: any\n}): Promise<OrgEmailRampRead> {\n const now = Number(options.now ?? Date.now())\n const at = Number.isFinite(now) && now > 0 ? now : Date.now()\n const config = await readEmailSendRateConfig(\n options.firestore ? { firestore: options.firestore, now: at } : { now: at },\n )\n const platformPerHour = config.perHour\n if (!config.enabled) {\n // A parked control answers with the verdict an established workspace\n // gets, so a surface reading the step does not blank while it is off.\n const parked = resolveOrgEmailRamp({\n ageDays: null,\n deliveredLifetime: 0,\n platformPerHour,\n })\n return { ramp: parked, degraded: false }\n }\n const ageDays = orgAgeDays(options.createdAt, at)\n /*\n * The step this workspace would be on having delivered nothing. It is the\n * graduation test and the floor in one value: delivered volume only ever\n * raises a step, so a verdict that graduates here graduates at any volume,\n * and one that does not is the lowest step the workspace can be on.\n */\n const floor = resolveOrgEmailRamp({\n ageDays,\n deliveredLifetime: 0,\n platformPerHour,\n })\n if (floor.graduated) return { ramp: floor, degraded: false }\n const window = await readSenderReputationWindow({\n orgId: options.orgId,\n now: at,\n firestore: options.firestore,\n })\n if (window.degraded) return { ramp: floor, degraded: true }\n return {\n ramp: resolveOrgEmailRamp({\n ageDays,\n deliveredLifetime: window.accepted,\n platformPerHour,\n }),\n degraded: false,\n }\n}\n\n/** The answer to a per-day ramp claim. Every field is a stated number. */\nexport interface OrgEmailSendDayClaim {\n allowed: boolean\n /** Messages claimed today BEFORE this send. */\n used: number\n /** What this workspace may send today. */\n ceiling: number\n /** Headroom after this send, floored at 0. */\n remaining: number\n /** When the day rolls and a deferred campaign may go, ms. */\n retryAtMs: number\n /** The ramp decision the ceiling came from. */\n ramp: EmailRampVerdict\n /** True when the counter was unreachable and this failed open. */\n degraded: boolean\n /**\n * What to hand {@link reconcileOrgEmailSendDay} once the batch is done.\n * Null when nothing was claimed — a graduated workspace, a parked control,\n * or a refusal.\n */\n reservation: OrgEmailSendDayReservation | null\n}\n\n/** A claim on a day's ramp, so an undelivered remainder can be given back. */\nexport interface OrgEmailSendDayReservation {\n orgId: string\n dayKey: string\n claimed: number\n}\n\n/**\n * THE NEW-SENDER RAMP, ENFORCED.\n *\n * Claims `count` campaign messages against what this workspace may send\n * today, atomically. The transaction reads the counter and writes an ABSOLUTE\n * value derived from that read rather than an increment, for the reason\n * `reserveCampaignEmailSends` and `claimOrgEmailSendBudget` both do: the read\n * is the authority for the decision, and an increment proves nothing about\n * the value the decision was made from.\n *\n * The ceiling arrives as a resolved {@link EmailRampVerdict} rather than\n * being derived here, because the caller has already paid the window read\n * that decides which step the workspace is on — see\n * {@link resolveOrgEmailRamp}. A graduated workspace claims nothing at all:\n * the ramp does not bind it, and the hourly share that does has already been\n * claimed by the time this runs.\n *\n * **Campaigns only**, like the hourly claim beside it. This function is not\n * on `sendEmail`'s path and cannot be reached by a transactional message.\n *\n * A refused claim writes NOTHING — a campaign that resumes tomorrow must not\n * have spent tomorrow's budget on being told no.\n */\nexport async function claimOrgEmailSendDay(options: {\n orgId: string\n /** Messages this batch would send. */\n count: number\n /** What this workspace may send today, from {@link resolveOrgEmailRamp}. */\n ramp: EmailRampVerdict\n /** False parks the control, exactly as the platform governor's flag does. */\n enabled?: boolean\n now?: number\n firestore?: any\n}): Promise<OrgEmailSendDayClaim> {\n const now = Number(options.now ?? Date.now())\n const at = Number.isFinite(now) && now > 0 ? now : Date.now()\n const dayKey = reputationDayKey(at)\n const retryAtMs = dayStartMs(at) + DAY_MS\n const count = Math.max(0, Math.floor(Number(options.count) || 0))\n const orgId = String(options.orgId ?? '')\n const ramp = options.ramp\n\n const granted = (\n used: number,\n degraded: boolean,\n reservation: OrgEmailSendDayReservation | null,\n ): OrgEmailSendDayClaim => ({\n allowed: true,\n used,\n ceiling: ramp.perDay,\n remaining: Math.max(0, ramp.perDay - (used + count)),\n retryAtMs,\n ramp,\n degraded,\n reservation,\n })\n\n // A parked control still reports a real ceiling, so a surface reading this\n // does not blank while the control is off.\n if (options.enabled === false) return granted(0, false, null)\n // A graduated workspace is not paced by the ramp at all. No read, no write,\n // and no claim to give back.\n if (ramp.graduated) return granted(0, false, null)\n if (!orgId) return granted(0, true, null)\n\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const ref = reputationRef(firestore, dayKey, orgId)\n return await firestore.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = storedCount(snapshot, 'claimed')\n if (used + count > ramp.perDay) {\n // A refused claim writes NOTHING.\n return {\n allowed: false,\n used,\n ceiling: ramp.perDay,\n remaining: Math.max(0, ramp.perDay - used),\n retryAtMs,\n ramp,\n degraded: false,\n reservation: null,\n }\n }\n tx.set(\n ref,\n {\n claimed: used + count,\n orgId,\n dayKey,\n expiresAt: reputationExpiresAt(dayStartMs(at)),\n },\n { merge: true },\n )\n return granted(used, false, { orgId, dayKey, claimed: count })\n })\n } catch (error) {\n console.error('[sender-reputation] day window unavailable — allowing', error)\n return granted(0, true, null)\n }\n}\n\n/**\n * Returns the undelivered part of a day's ramp claim.\n *\n * The hourly claim is deliberately never reconciled — its window is an hour\n * and an unrefunded remainder costs the org the rest of it. A DAY is long\n * enough that the same choice would cost a new workspace its whole first day\n * over one failed batch, which is the opposite of what a ramp is for.\n *\n * **Never throws** and never drives the counter below zero, exactly as\n * `reconcileCampaignSendReservation` does one surface over.\n */\nexport async function reconcileOrgEmailSendDay(\n reservation: OrgEmailSendDayReservation | 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.claimed - sent)\n if (refund <= 0) return\n try {\n const db = firestore ?? firebaseAdmin.app().firestore()\n const ref = reputationRef(db, reservation.dayKey, reservation.orgId)\n await db.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = storedCount(snapshot, 'claimed')\n tx.set(ref, { claimed: Math.max(0, used - refund) }, { merge: true })\n })\n } catch (error) {\n console.error('[sender-reputation] day reconcile failed', error)\n }\n}\n\n/**\n * How old a workspace is, in days, from whatever its `createdAt` turns out to\n * be.\n *\n * Firestore hands back a `Timestamp`, a restore or a fixture can leave a\n * number, and an org written before the field existed has nothing. All three\n * are handled and the last one answers `null`, which\n * {@link claimOrgEmailSendDay} reads as graduated — the only safe direction,\n * for the reason stated there.\n */\nexport function orgAgeDays(\n createdAt: unknown,\n now: number = Date.now(),\n): number | null {\n const raw = createdAt as\n | { toMillis?: () => number; seconds?: number }\n | number\n | string\n | null\n | undefined\n let createdMs = 0\n if (typeof raw === 'number') createdMs = raw\n else if (typeof raw === 'string') createdMs = Date.parse(raw)\n else if (typeof raw?.toMillis === 'function') createdMs = raw.toMillis()\n else if (typeof raw?.seconds === 'number') createdMs = raw.seconds * 1000\n /*\n * The one check, and it has to answer `null` rather than 0. A creation date\n * that could not be read is an org whose record predates the field, which\n * is an EXISTING customer; `0` would say \"created today\" and ramp every\n * paying tenant on the platform down to the first step.\n */\n if (!Number.isFinite(createdMs) || createdMs <= 0) return null\n return daysBetween(createdMs, now)\n}\n\n/** Re-exported so a caller reads one module for the whole control. */\nexport type { EmailReputationPolicy, EmailRampVerdict }\n"],"names":["EMAIL_REPUTATION_WINDOW_DAYS","emailRampVerdict","emailReputationVerdict","normalizeEmailReputationPolicy","orgDailyCampaignCeiling","reputationDayKey","reputationWindowDayKeys","daysBetween","readEmailSendRateConfig","firebaseAdmin","RATE_LIMIT_COLLECTION","EMAIL_REPUTATION_DOC_PREFIX","DAY_MS","emailReputationDocId","dayKey","orgId","reputationRef","firestore","collection","doc","storedCount","snapshot","field","value","Number","exists","get","isFinite","Math","floor","reputationExpiresAt","dayStartMs","Date","atMs","recordEmailReputationEvent","options","String","count","now","at","app","set","counter","FieldValue","increment","expiresAt","merge","error","console","recordCampaignAccepted","recordEmailReputationFailure","kind","readSenderReputationWindow","windowDays","max","empty","accepted","bounced","complained","claimedToday","acceptedLastTwoDays","degraded","dayKeys","today","yesterday","snapshots","getAll","map","reduce","totals","index","readSenderReputation","window","verdict","counts","policy","reinstatedUntilMs","resolveOrgEmailRamp","ageDays","deliveredLifetime","graduatedPerDay","platformPerHour","readOrgEmailRamp","config","perHour","enabled","parked","ramp","orgAgeDays","createdAt","graduated","claimOrgEmailSendDay","retryAtMs","granted","used","reservation","allowed","ceiling","perDay","remaining","ref","runTransaction","tx","claimed","reconcileOrgEmailSendDay","delivered","sent","refund","db","raw","createdMs","parse","toMillis","seconds"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDC,GAED,SACEA,4BAA4B,EAC5BC,gBAAgB,EAChBC,sBAAsB,EACtBC,8BAA8B,EAC9BC,uBAAuB,EACvBC,gBAAgB,EAChBC,uBAAuB,EACvBC,WAAW,QAKN,2BAA0B;AACjC,SAASC,uBAAuB,QAAQ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,OAAO;IAC1D,OAAOvG,YAAYuG,WAAWxE;AAChC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-sender-reputation.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 * PER-TENANT SENDING REPUTATION — the durable half.\n *\n * The policy is pure and lives in `@aglyn/shared-util-email`\n * (`sender-reputation.ts`); this adds the counters that make a rate a fact\n * rather than an intention, and the daily claim that paces a workspace's\n * first week.\n *\n * ## One document per workspace per day\n *\n * `rateLimits/emailRep_{YYYY-MM-DD}_{orgId}` holds four numbers:\n *\n * - `claimed` — campaign messages the day's ramp has granted. The PACING\n * counter, taken before a send and reconciled to what actually left.\n * - `accepted` — campaign messages that actually left. The DENOMINATOR every\n * rate divides by.\n * - `bounced`, `complained` — what the provider reported back.\n *\n * A day per document rather than a map of days on one, because the day is\n * what the TTL policy can sweep: `rateLimits` already carries an `expiresAt`\n * policy, and a document that ages out is a window that prunes itself. A map\n * of every day a workspace has ever sent would grow forever and would have to\n * be pruned by a job nobody would write.\n *\n * A per-ORG document rather than per-site, because the org is the tenant: the\n * plan, the monthly allowance and the hourly share are all keyed on it, and a\n * merchant with three sites on one domain is one sender to a mailbox\n * provider.\n *\n * The window document deliberately carries **no `lastAtMs`** — the\n * rate-limiter health probe queries this collection on that field, and a\n * per-day document in its range would compete with the degradation markers it\n * exists to find. The same reasoning as `sendRate_*` and `sendRateOrg_*`\n * beside it.\n *\n * ## Which day a bounce is filed under\n *\n * The day the EVENT arrived, not the day the message was sent. The webhook\n * knows the first and would need a per-message lookup for the second, and\n * over a seven-day window the two differ only at the edges — a bounce lands\n * within minutes and a complaint within hours or a day. Stated because the\n * rate is a ratio of two things counted on slightly different clocks, and a\n * reader comparing it against a provider's dashboard should know why they\n * will not agree to the last decimal.\n *\n * ## Failure posture: OPEN, and that is not the usual answer here\n *\n * An unreadable counter grades `ok` and grants the send, matching\n * `consumeEmailSendBudget` and `claimOrgEmailSendBudget`. The breaker is the\n * one control in this file that could refuse a paying customer's campaign,\n * and a refusal produced by a Firestore blip is an outage dressed as a policy\n * decision. The reputation risk it fails to catch is bounded by an hour of\n * sending; the refusal it would produce is not bounded by anything.\n */\n\nimport {\n EMAIL_REPUTATION_WINDOW_DAYS,\n emailRampVerdict,\n emailReputationVerdict,\n normalizeEmailReputationPolicy,\n orgDailyCampaignCeiling,\n reputationDayKey,\n reputationWindowDayKeys,\n type EmailRampVerdict,\n type EmailReputationCounts,\n type EmailReputationPolicy,\n type EmailReputationVerdict,\n} from '@aglyn/shared-util-email'\nimport { readEmailSendRateConfig } from './email-send-rate'\nimport { firebaseAdmin } from './firebase-admin'\nimport { RATE_LIMIT_COLLECTION } from './rate-limit-store'\n/*\n * `orgAgeDays` lives in its own leaf so a caller that needs only the age —\n * the outbound phishing screen (AGL-3356) — does not load this module, whose\n * import installs the platform send-rate governor. Re-exported, so every\n * existing reader of it here is unchanged.\n */\nimport { orgAgeDays } from './org-age'\nexport { orgAgeDays }\n\n/** Id prefix for the per-org, per-day reputation documents. */\nexport const EMAIL_REPUTATION_DOC_PREFIX = 'emailRep_'\n\n/** One day in ms, named so the arithmetic below reads as arithmetic. */\nconst DAY_MS = 86_400_000\n\n/** The document id for one workspace's day. */\nexport function emailReputationDocId(dayKey: string, orgId: string): string {\n return `${EMAIL_REPUTATION_DOC_PREFIX}${dayKey}_${orgId}`\n}\n\n/** The counted fields, so a writer cannot invent a fifth by typo. */\nexport type EmailReputationCounter =\n | 'claimed'\n | 'accepted'\n | 'bounced'\n | 'complained'\n\nfunction reputationRef(firestore: any, dayKey: string, orgId: string): any {\n return firestore\n .collection(RATE_LIMIT_COLLECTION)\n .doc(emailReputationDocId(dayKey, orgId))\n}\n\n/** A stored count, clamped. A corrupt negative reads as 0, never as headroom. */\nfunction storedCount(snapshot: any, field: EmailReputationCounter): number {\n const value = Number((snapshot?.exists ? snapshot.get(field) : 0) ?? 0)\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0\n}\n\n/**\n * When a day's document may be swept.\n *\n * One window plus a day of slack past the end of the day it counts, so the\n * oldest day a rate still divides by is never deleted underneath the read\n * that needs it.\n */\nfunction reputationExpiresAt(dayStartMs: number): Date {\n return new Date(dayStartMs + (EMAIL_REPUTATION_WINDOW_DAYS + 2) * DAY_MS)\n}\n\n/** Midnight UTC of the day a timestamp falls in. */\nfunction dayStartMs(atMs: number): number {\n return Math.floor(atMs / DAY_MS) * DAY_MS\n}\n\n/**\n * Adds to one of a workspace's daily counters.\n *\n * **Never throws.** Reputation accounting runs after mail has gone out, or\n * inside a webhook the provider will retry — a counter write that failed must\n * not turn a delivered campaign into a 500 or a webhook into a retry storm.\n * `FieldValue.increment` rather than a transaction because nothing decides\n * anything from this write: the decision is made by a separate read, and an\n * increment is the contention-free way to record a fact.\n */\nexport async function recordEmailReputationEvent(options: {\n orgId: string\n counter: EmailReputationCounter\n count?: number\n atMs?: number\n firestore?: any\n}): Promise<void> {\n const orgId = String(options.orgId ?? '')\n const count = Math.floor(Number(options.count ?? 1))\n if (!orgId || !Number.isFinite(count) || count <= 0) return\n const atMs = Number(options.atMs ?? Date.now())\n const at = Number.isFinite(atMs) && atMs > 0 ? atMs : Date.now()\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n await reputationRef(firestore, reputationDayKey(at), orgId).set(\n {\n [options.counter]: firebaseAdmin.firestore.FieldValue.increment(count),\n orgId,\n dayKey: reputationDayKey(at),\n // NOT `lastAtMs` — see the storage note at the top of this file.\n expiresAt: reputationExpiresAt(dayStartMs(at)),\n },\n { merge: true },\n )\n } catch (error) {\n console.error('[sender-reputation] counter write failed', error)\n }\n}\n\n/** Campaign messages that actually left, for a workspace. The denominator. */\nexport function recordCampaignAccepted(\n orgId: string,\n count: number,\n options?: { atMs?: number; firestore?: any },\n): Promise<void> {\n return recordEmailReputationEvent({\n orgId,\n counter: 'accepted',\n count,\n ...options,\n })\n}\n\n/**\n * A permanent bounce or a spam complaint, attributed to the workspace that\n * sent it.\n *\n * The suppression the same event produces is a separate act and is not\n * conditional on this: an address comes off the list whether or not the\n * counter write lands.\n */\nexport function recordEmailReputationFailure(\n orgId: string,\n kind: 'bounce' | 'complaint',\n options?: { atMs?: number; firestore?: any },\n): Promise<void> {\n return recordEmailReputationEvent({\n orgId,\n counter: kind === 'complaint' ? 'complained' : 'bounced',\n count: 1,\n ...options,\n })\n}\n\n/** The counts a workspace's window holds, plus what the ramp needs. */\nexport interface SenderReputationWindow extends EmailReputationCounts {\n /**\n * Campaign messages the ramp has granted TODAY.\n *\n * Read here rather than by a second query because today's document is\n * already in this window: the ramp needs one number off it and the rates\n * need three off all of them, and two reads of one document to answer two\n * questions about the same workspace is a round trip nobody has to pay.\n */\n claimedToday: number\n /**\n * Campaign messages accepted TODAY and YESTERDAY (UTC), summed.\n *\n * What the List-Unsubscribe bulk guard counts as \"the last 24 hours\"\n * (AGL-3307). The counters are per calendar day, so a rolling 24 hours is\n * not available — and two days is a superset of it: it never counts fewer\n * messages than the trailing 24 hours held, so the guard can only err\n * toward carrying the header. Read off the window's own documents, at no\n * extra cost.\n */\n acceptedLastTwoDays: number\n /** Days the window covers. */\n windowDays: number\n /** True when the window could not be read and everything below is zero. */\n degraded: boolean\n}\n\n/**\n * Sums a workspace's last {@link EMAIL_REPUTATION_WINDOW_DAYS} days.\n *\n * One `getAll` over the window's day documents — seven reads per campaign,\n * not per message, and none at all for a workspace that has never sent. An\n * absent day is a quiet day and reads as zero.\n */\nexport async function readSenderReputationWindow(options: {\n orgId: string\n now?: number\n windowDays?: number\n firestore?: any\n}): Promise<SenderReputationWindow> {\n const windowDays = Math.max(\n 1,\n Math.floor(Number(options.windowDays ?? EMAIL_REPUTATION_WINDOW_DAYS)) ||\n EMAIL_REPUTATION_WINDOW_DAYS,\n )\n const empty: SenderReputationWindow = {\n accepted: 0,\n bounced: 0,\n complained: 0,\n claimedToday: 0,\n acceptedLastTwoDays: 0,\n windowDays,\n degraded: false,\n }\n const orgId = String(options.orgId ?? '')\n if (!orgId) return empty\n const now = Number(options.now ?? Date.now())\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const dayKeys = reputationWindowDayKeys(now, windowDays)\n const today = reputationDayKey(now)\n const yesterday = reputationDayKey(now - DAY_MS)\n const snapshots = await firestore.getAll(\n ...dayKeys.map((dayKey) => reputationRef(firestore, dayKey, orgId)),\n )\n return snapshots.reduce(\n (totals: SenderReputationWindow, snapshot: any, index: number) => ({\n ...totals,\n accepted: totals.accepted + storedCount(snapshot, 'accepted'),\n bounced: totals.bounced + storedCount(snapshot, 'bounced'),\n complained: totals.complained + storedCount(snapshot, 'complained'),\n claimedToday:\n dayKeys[index] === today\n ? totals.claimedToday + storedCount(snapshot, 'claimed')\n : totals.claimedToday,\n acceptedLastTwoDays:\n dayKeys[index] === today || dayKeys[index] === yesterday\n ? totals.acceptedLastTwoDays + storedCount(snapshot, 'accepted')\n : totals.acceptedLastTwoDays,\n }),\n empty,\n )\n } catch (error) {\n console.error('[sender-reputation] window unavailable — grading ok', error)\n return { ...empty, degraded: true }\n }\n}\n\n/** A workspace's reputation, and whether its campaigns may go out. */\nexport interface SenderReputationRead extends EmailReputationVerdict {\n /** True when the window could not be read, so nothing was graded. */\n degraded: boolean\n /** The counts the grade was made from, so a caller can size a ramp too. */\n window: SenderReputationWindow\n}\n\n/**\n * Grades one workspace.\n *\n * The policy and the grace period come from the ORG DOCUMENT, which the\n * campaign sender has already read — passed in rather than re-fetched, so\n * this costs the window read and nothing else.\n */\nexport async function readSenderReputation(options: {\n orgId: string\n policy?: unknown\n reinstatedUntilMs?: unknown\n now?: number\n firestore?: any\n}): Promise<SenderReputationRead> {\n const now = Number(options.now ?? Date.now())\n const window = await readSenderReputationWindow({\n orgId: options.orgId,\n now,\n firestore: options.firestore,\n })\n const verdict = emailReputationVerdict({\n counts: window,\n // A degraded read grades against zeroes, which is `ok` by construction.\n // Stated rather than special-cased: the fail-open posture at the top of\n // this file is the reason, and a branch here would be a second place for\n // it to be got wrong.\n policy: normalizeEmailReputationPolicy(options.policy),\n windowDays: window.windowDays,\n reinstatedUntilMs: Number(options.reinstatedUntilMs ?? 0) || null,\n now,\n })\n return { ...verdict, degraded: window.degraded, window }\n}\n\n/**\n * The ramp step a workspace has EARNED, from a window it has already read.\n *\n * A thin wrapper over the pure policy that supplies the one number the policy\n * cannot know: what a graduated workspace's day is, which is a share of the\n * live platform ceiling and therefore moves with a staff ramp.\n */\nexport function resolveOrgEmailRamp(options: {\n /** Days since the workspace was created; null or absent graduates it. */\n ageDays: number | null | undefined\n /** Campaign messages it has delivered inside the window. */\n deliveredLifetime: number\n /** The live platform ceiling. */\n platformPerHour: number\n}): EmailRampVerdict {\n return emailRampVerdict({\n ageDays: options.ageDays,\n deliveredLifetime: options.deliveredLifetime,\n graduatedPerDay: orgDailyCampaignCeiling(options.platformPerHour),\n })\n}\n\n/** A workspace's ramp step, and whether the history behind it was readable. */\nexport interface OrgEmailRampRead {\n /** The step, from the age and the delivery history that resolved. */\n ramp: EmailRampVerdict\n /**\n * True when the ramp BINDS and the window it is sized from was unreadable,\n * so {@link ramp} is a floor rather than an answer.\n *\n * A caller that pages a batch — the campaign path — may treat this as the\n * step and carry on, because the floor is the lowest step and erring low\n * defers mail rather than sending it. A caller that admits or refuses ONE\n * message has no such third answer and must refuse: see\n * {@link readOrgEmailRamp}.\n */\n degraded: boolean\n}\n\n/**\n * A workspace's ramp step, resolved from its record and its history.\n *\n * The reads {@link resolveOrgEmailRamp} needs, in the order that pays for\n * the fewest of them. The platform ceiling comes first because it is process-\n * cached for fifteen seconds and therefore free; the seven-day window is a\n * `getAll` and is only paid when the ramp can still bind.\n *\n * ## A graduated workspace pays nothing\n *\n * Age alone decides graduation — delivery volume can only RAISE a step, never\n * reach past the last one — so a workspace past its first week is answered\n * from the org record with no window read at all. That is every existing\n * customer and every org whose record predates the creation timestamp, which\n * is to say almost every call.\n *\n * ## An unreadable window is `degraded`, and it is the caller's to answer\n *\n * The window read grades itself rather than throwing, and an unreadable one\n * reads as zero delivered — the LOWEST step, which is the conservative\n * direction for a ceiling. What it is not is a fact, so it is flagged: a\n * surface admitting one message at a time cannot defer the remainder to\n * tomorrow the way a campaign can, and a limiter with no answer must refuse\n * rather than admit.\n *\n * ## The platform flag parks this control\n *\n * `enabled: false` on the send-rate config graduates every workspace here,\n * exactly as it parks the hourly share and {@link claimOrgEmailSendDay} — one\n * switch, and it turns the ramp off everywhere it is consulted.\n */\nexport async function readOrgEmailRamp(options: {\n orgId: string\n /** The org record's `createdAt`, in whatever shape it was stored. */\n createdAt: unknown\n now?: number\n firestore?: any\n}): Promise<OrgEmailRampRead> {\n const now = Number(options.now ?? Date.now())\n const at = Number.isFinite(now) && now > 0 ? now : Date.now()\n const config = await readEmailSendRateConfig(\n options.firestore ? { firestore: options.firestore, now: at } : { now: at },\n )\n const platformPerHour = config.perHour\n if (!config.enabled) {\n // A parked control answers with the verdict an established workspace\n // gets, so a surface reading the step does not blank while it is off.\n const parked = resolveOrgEmailRamp({\n ageDays: null,\n deliveredLifetime: 0,\n platformPerHour,\n })\n return { ramp: parked, degraded: false }\n }\n const ageDays = orgAgeDays(options.createdAt, at)\n /*\n * The step this workspace would be on having delivered nothing. It is the\n * graduation test and the floor in one value: delivered volume only ever\n * raises a step, so a verdict that graduates here graduates at any volume,\n * and one that does not is the lowest step the workspace can be on.\n */\n const floor = resolveOrgEmailRamp({\n ageDays,\n deliveredLifetime: 0,\n platformPerHour,\n })\n if (floor.graduated) return { ramp: floor, degraded: false }\n const window = await readSenderReputationWindow({\n orgId: options.orgId,\n now: at,\n firestore: options.firestore,\n })\n if (window.degraded) return { ramp: floor, degraded: true }\n return {\n ramp: resolveOrgEmailRamp({\n ageDays,\n deliveredLifetime: window.accepted,\n platformPerHour,\n }),\n degraded: false,\n }\n}\n\n/** The answer to a per-day ramp claim. Every field is a stated number. */\nexport interface OrgEmailSendDayClaim {\n allowed: boolean\n /** Messages claimed today BEFORE this send. */\n used: number\n /** What this workspace may send today. */\n ceiling: number\n /** Headroom after this send, floored at 0. */\n remaining: number\n /** When the day rolls and a deferred campaign may go, ms. */\n retryAtMs: number\n /** The ramp decision the ceiling came from. */\n ramp: EmailRampVerdict\n /** True when the counter was unreachable and this failed open. */\n degraded: boolean\n /**\n * What to hand {@link reconcileOrgEmailSendDay} once the batch is done.\n * Null when nothing was claimed — a graduated workspace, a parked control,\n * or a refusal.\n */\n reservation: OrgEmailSendDayReservation | null\n}\n\n/** A claim on a day's ramp, so an undelivered remainder can be given back. */\nexport interface OrgEmailSendDayReservation {\n orgId: string\n dayKey: string\n claimed: number\n}\n\n/**\n * THE NEW-SENDER RAMP, ENFORCED.\n *\n * Claims `count` campaign messages against what this workspace may send\n * today, atomically. The transaction reads the counter and writes an ABSOLUTE\n * value derived from that read rather than an increment, for the reason\n * `reserveCampaignEmailSends` and `claimOrgEmailSendBudget` both do: the read\n * is the authority for the decision, and an increment proves nothing about\n * the value the decision was made from.\n *\n * The ceiling arrives as a resolved {@link EmailRampVerdict} rather than\n * being derived here, because the caller has already paid the window read\n * that decides which step the workspace is on — see\n * {@link resolveOrgEmailRamp}. A graduated workspace claims nothing at all:\n * the ramp does not bind it, and the hourly share that does has already been\n * claimed by the time this runs.\n *\n * **Campaigns only**, like the hourly claim beside it. This function is not\n * on `sendEmail`'s path and cannot be reached by a transactional message.\n *\n * A refused claim writes NOTHING — a campaign that resumes tomorrow must not\n * have spent tomorrow's budget on being told no.\n */\nexport async function claimOrgEmailSendDay(options: {\n orgId: string\n /** Messages this batch would send. */\n count: number\n /** What this workspace may send today, from {@link resolveOrgEmailRamp}. */\n ramp: EmailRampVerdict\n /** False parks the control, exactly as the platform governor's flag does. */\n enabled?: boolean\n now?: number\n firestore?: any\n}): Promise<OrgEmailSendDayClaim> {\n const now = Number(options.now ?? Date.now())\n const at = Number.isFinite(now) && now > 0 ? now : Date.now()\n const dayKey = reputationDayKey(at)\n const retryAtMs = dayStartMs(at) + DAY_MS\n const count = Math.max(0, Math.floor(Number(options.count) || 0))\n const orgId = String(options.orgId ?? '')\n const ramp = options.ramp\n\n const granted = (\n used: number,\n degraded: boolean,\n reservation: OrgEmailSendDayReservation | null,\n ): OrgEmailSendDayClaim => ({\n allowed: true,\n used,\n ceiling: ramp.perDay,\n remaining: Math.max(0, ramp.perDay - (used + count)),\n retryAtMs,\n ramp,\n degraded,\n reservation,\n })\n\n // A parked control still reports a real ceiling, so a surface reading this\n // does not blank while the control is off.\n if (options.enabled === false) return granted(0, false, null)\n // A graduated workspace is not paced by the ramp at all. No read, no write,\n // and no claim to give back.\n if (ramp.graduated) return granted(0, false, null)\n if (!orgId) return granted(0, true, null)\n\n try {\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n const ref = reputationRef(firestore, dayKey, orgId)\n return await firestore.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = storedCount(snapshot, 'claimed')\n if (used + count > ramp.perDay) {\n // A refused claim writes NOTHING.\n return {\n allowed: false,\n used,\n ceiling: ramp.perDay,\n remaining: Math.max(0, ramp.perDay - used),\n retryAtMs,\n ramp,\n degraded: false,\n reservation: null,\n }\n }\n tx.set(\n ref,\n {\n claimed: used + count,\n orgId,\n dayKey,\n expiresAt: reputationExpiresAt(dayStartMs(at)),\n },\n { merge: true },\n )\n return granted(used, false, { orgId, dayKey, claimed: count })\n })\n } catch (error) {\n console.error('[sender-reputation] day window unavailable — allowing', error)\n return granted(0, true, null)\n }\n}\n\n/**\n * Returns the undelivered part of a day's ramp claim.\n *\n * The hourly claim is deliberately never reconciled — its window is an hour\n * and an unrefunded remainder costs the org the rest of it. A DAY is long\n * enough that the same choice would cost a new workspace its whole first day\n * over one failed batch, which is the opposite of what a ramp is for.\n *\n * **Never throws** and never drives the counter below zero, exactly as\n * `reconcileCampaignSendReservation` does one surface over.\n */\nexport async function reconcileOrgEmailSendDay(\n reservation: OrgEmailSendDayReservation | 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.claimed - sent)\n if (refund <= 0) return\n try {\n const db = firestore ?? firebaseAdmin.app().firestore()\n const ref = reputationRef(db, reservation.dayKey, reservation.orgId)\n await db.runTransaction(async (tx: any) => {\n const snapshot = await tx.get(ref)\n const used = storedCount(snapshot, 'claimed')\n tx.set(ref, { claimed: Math.max(0, used - refund) }, { merge: true })\n })\n } catch (error) {\n console.error('[sender-reputation] day reconcile failed', error)\n }\n}\n\n/** Re-exported so a caller reads one module for the whole control. */\nexport type { EmailReputationPolicy, EmailRampVerdict }\n"],"names":["EMAIL_REPUTATION_WINDOW_DAYS","emailRampVerdict","emailReputationVerdict","normalizeEmailReputationPolicy","orgDailyCampaignCeiling","reputationDayKey","reputationWindowDayKeys","readEmailSendRateConfig","firebaseAdmin","RATE_LIMIT_COLLECTION","orgAgeDays","EMAIL_REPUTATION_DOC_PREFIX","DAY_MS","emailReputationDocId","dayKey","orgId","reputationRef","firestore","collection","doc","storedCount","snapshot","field","value","Number","exists","get","isFinite","Math","floor","reputationExpiresAt","dayStartMs","Date","atMs","recordEmailReputationEvent","options","String","count","now","at","app","set","counter","FieldValue","increment","expiresAt","merge","error","console","recordCampaignAccepted","recordEmailReputationFailure","kind","readSenderReputationWindow","windowDays","max","empty","accepted","bounced","complained","claimedToday","acceptedLastTwoDays","degraded","dayKeys","today","yesterday","snapshots","getAll","map","reduce","totals","index","readSenderReputation","window","verdict","counts","policy","reinstatedUntilMs","resolveOrgEmailRamp","ageDays","deliveredLifetime","graduatedPerDay","platformPerHour","readOrgEmailRamp","config","perHour","enabled","parked","ramp","createdAt","graduated","claimOrgEmailSendDay","retryAtMs","granted","used","reservation","allowed","ceiling","perDay","remaining","ref","runTransaction","tx","claimed","reconcileOrgEmailSendDay","delivered","sent","refund","db"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDC,GAED,SACEA,4BAA4B,EAC5BC,gBAAgB,EAChBC,sBAAsB,EACtBC,8BAA8B,EAC9BC,uBAAuB,EACvBC,gBAAgB,EAChBC,uBAAuB,QAKlB,2BAA0B;AACjC,SAASC,uBAAuB,QAAQ,uBAAmB;AAC3D,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,qBAAqB,QAAQ,wBAAoB;AAC1D;;;;;CAKC,GACD,SAASC,UAAU,QAAQ,eAAW;AACtC,SAASA,UAAU,GAAE;AAErB,6DAA6D,GAC7D,OAAO,MAAMC,8BAA8B,YAAW;AAEtD,sEAAsE,GACtE,MAAMC,SAAS;AAEf,6CAA6C,GAC7C,OAAO,SAASC,qBAAqBC,MAAc,EAAEC,KAAa;IAChE,OAAO,GAAGJ,8BAA8BG,OAAO,CAAC,EAAEC,OAAO;AAC3D;AASA,SAASC,cAAcC,SAAc,EAAEH,MAAc,EAAEC,KAAa;IAClE,OAAOE,UACJC,UAAU,CAACT,uBACXU,GAAG,CAACN,qBAAqBC,QAAQC;AACtC;AAEA,+EAA+E,GAC/E,SAASK,YAAYC,QAAa,EAAEC,KAA6B;QACzCD;IAAtB,MAAME,QAAQC,QAAQH,OAAAA,CAAAA,4BAAAA,SAAUI,MAAM,IAAGJ,SAASK,GAAG,CAACJ,SAAS,aAAzCD,OAA+C;IACrE,OAAOG,OAAOG,QAAQ,CAACJ,UAAUA,QAAQ,IAAIK,KAAKC,KAAK,CAACN,SAAS;AACnE;AAEA;;;;;;CAMC,GACD,SAASO,oBAAoBC,UAAkB;IAC7C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,KAAK,CAAC,4CAA4CA;IAC5D;AACF"}
|
|
@@ -116,7 +116,16 @@ export type EmailSuppressionReason =
|
|
|
116
116
|
/** The recipient pressed "report spam". */
|
|
117
117
|
| 'complaint'
|
|
118
118
|
/** Recorded by staff (a written request, a court order, a correction). */
|
|
119
|
-
| 'staff'
|
|
119
|
+
| 'staff'
|
|
120
|
+
/**
|
|
121
|
+
* The address's domain takes no mail — no MX and no address record, or a
|
|
122
|
+
* null MX — as the deliverability preflight found before a send
|
|
123
|
+
* (AGL-3328). Filed without a bounce ever happening, which is the point:
|
|
124
|
+
* the bounce is what it prevents. A fact about the address for everyone,
|
|
125
|
+
* like a bounce; a staff release lifts it, and the preflight files it
|
|
126
|
+
* again only if the domain still takes no mail.
|
|
127
|
+
*/
|
|
128
|
+
| 'no_mail_server';
|
|
120
129
|
/**
|
|
121
130
|
* The reasons that may be filed PLATFORM-WIDE, as a runtime set.
|
|
122
131
|
*
|
|
@@ -138,7 +138,8 @@ export const EMAIL_SUPPRESSIONS_COLLECTION = 'emailSuppressions';
|
|
|
138
138
|
*/ export const PLATFORM_SUPPRESSION_REASONS = [
|
|
139
139
|
'bounce',
|
|
140
140
|
'complaint',
|
|
141
|
-
'staff'
|
|
141
|
+
'staff',
|
|
142
|
+
'no_mail_server'
|
|
142
143
|
];
|
|
143
144
|
/**
|
|
144
145
|
* The reason a self-service opt-out is filed under, on the PER-SITE list.
|
|
@@ -228,9 +229,9 @@ export const EMAIL_SUPPRESSIONS_COLLECTION = 'emailSuppressions';
|
|
|
228
229
|
hostId: input.hostId,
|
|
229
230
|
email: input.email,
|
|
230
231
|
state: {
|
|
231
|
-
status: input.reason === 'complaint' ? 'complained' : 'bounced',
|
|
232
|
+
status: input.reason === 'complaint' ? 'complained' : input.reason === 'no_mail_server' ? 'undeliverable' : 'bounced',
|
|
232
233
|
atMs: Date.now(),
|
|
233
|
-
source: 'campaign',
|
|
234
|
+
source: input.reason === 'no_mail_server' ? 'check' : 'campaign',
|
|
234
235
|
detail: input.context ? `Reported by the ${input.context} send.` : null
|
|
235
236
|
}
|
|
236
237
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-suppression.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-WIDE email suppression list, `emailSuppressions/{emailKey}`\n * (AGL-2407).\n *\n * ## What was missing\n *\n * AGL-1918 (`7a8f3cd68`) made `email.bounced` (permanent) and\n * `email.complained` write a suppression — into `hosts/{hostId}/suppressions`,\n * found from a Resend tag that only `campaign-send.ts` stamped. That closed\n * the campaign half and could close no other, because there was nowhere to\n * file the rest:\n *\n * Every other sender in the product goes through the shared `sendEmail` —\n * invites,\n * password resets, verification, receipts, booking confirmations, the monthly\n * usage summary, the usage-alert fan-out, restock and abandoned-cart mail, the\n * merchant-authored workflow `sendEmail` step. A bounce on any of those\n * arrived at the webhook with no site to place it against and was answered\n * `200 {ignored:true}`. A dead address was re-mailed on every subsequent send,\n * forever, and a spam complaint had no effect on anything.\n *\n * That matters most exactly when it is hardest to fix: on Sept 1 the signup\n * door opens, and verification and invite mail — addressed by strangers typing\n * addresses — is the highest-bounce-rate mail we send, on the same Resend key\n * and the same From address as everything else.\n *\n * ## Why a sibling of `contactSuppressions` and not a channel on it\n *\n * `contact-suppression.ts` is the same idea for phones and every argument it\n * makes holds here: keyed on the identifier because that is what the sender\n * holds at send time; one `get()` by document id, no query and no composite\n * index that could go missing and fail the lookup open; a revocation is a\n * FIELD and not a delete, because the record is the evidence that the\n * suppression was honoured while it was in force.\n *\n * It is a separate collection for one concrete reason: the document id. That\n * list's key is the E.164 digits, and its docblock argues at length that a\n * phone number must NOT be hashed (NANP is ~10^10 values, so a hash buys the\n * appearance of de-identification and none of the substance). An email address\n * is not enumerable, `hosts/{hostId}/suppressions` already keys on\n * `sha256(email)`, and one collection holding two incompatible key spaces is\n * how a lookup comes to be performed against the wrong derivation. The\n * address is stored in the document in the clear regardless, exactly as the\n * per-host list stores it, so a staff reader still shows a human something\n * they can act on.\n *\n * ## Who reads it, and who deliberately does NOT\n *\n * AGL-1438's rule is that a QUOTA may only ever refuse a campaign, because\n * refusing a receipt or a password reset converts a billing event into an\n * outage on a customer's business. A suppression is not a quota, but the same\n * proportionality applies and lands in the same place:\n *\n * - **Bulk mail consults this list.** The monthly usage summary, the\n * usage-alert fan-out and the marketplace review fan-out to a publisher's\n * owners and admins go to a LIST of people who did not ask for that\n * particular message, on a schedule or on every submission, forever. They\n * are the sends that re-hit a dead mailbox every month and teach a mailbox\n * provider that `aglyn.com` does not listen.\n * - **Transactional mail does NOT.** A password reset, a verification, an\n * invite, a receipt or a booking confirmation answers something the human\n * just did. Refusing one because an address bounced or because somebody\n * once pressed \"report spam\" on an unrelated message would lock a real\n * customer out of their own account. The shared sender is therefore left\n * unconditional on purpose, and this is the note that says so.\n *\n * (Written throughout without a literal call expression, on purpose:\n * `email-send-metering-coverage.spec.ts` enumerates senders by grepping the\n * tree for one, and a prose mention here would enrol a module that sends\n * nothing into the AGL-1438 cost-meter sweep.)\n */\n\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\n// The leaf entry, not the `@aglyn/aglyn` barrel, for the reason\n// `document-id.ts` gives at length: a barrel import resolves to whatever a\n// spec's `jest.mock` happens to contain, and this module's neighbours are\n// mocked in nearly every spec that touches them.\nimport {\n consentGroupOptOutHosts,\n consentGroupTopicState,\n type ConsentGroup,\n} from '@aglyn/aglyn/app-utils/consent-groups'\nimport {\n readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/email-topics'\nimport { emailSearchTokens } from '@aglyn/aglyn/app-utils/email-search'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport { stampRecordEmailState } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport firebaseAdmin from './firebase-admin'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\nexport const EMAIL_SUPPRESSIONS_COLLECTION = 'emailSuppressions'\n\n/**\n * The PER-SITE list, `hosts/{hostId}/suppressions/{emailKey}` — unsubscribes\n * from one site's campaigns, plus the bounces and complaints that arrived\n * carrying that site's tag.\n *\n * Named here rather than at each call site because the two lists are read\n * together by {@link filterSendableForHost}, and a sender that knows one path\n * as a string literal and the other through this module is one rename away\n * from consulting a collection that does not exist and finding nobody\n * suppressed.\n */\nexport const HOST_SUPPRESSIONS_SUBCOLLECTION = 'suppressions'\n\n/**\n * Why an address is suppressed.\n *\n * `bounce` means PERMANENT only. Resend reports `data.bounce.type` as\n * `Permanent` or `Transient`, and a transient bounce is a full mailbox or a\n * greylisting server — recording one here would suppress a real recipient over\n * a temporary condition at their provider. The webhook makes that distinction;\n * this type only names the outcome.\n */\nexport type EmailSuppressionReason =\n /** Permanent bounce — the mailbox does not exist. */\n | 'bounce'\n /** The recipient pressed \"report spam\". */\n | 'complaint'\n /** Recorded by staff (a written request, a court order, a correction). */\n | 'staff'\n\n/**\n * The reasons that may be filed PLATFORM-WIDE, as a runtime set.\n *\n * ## The split this constant enforces\n *\n * A bounce and a complaint are facts about a MAILBOX and about the sending\n * domain every tenant's mail leaves by: the address does not exist for\n * anybody, and somebody who pressed \"report spam\" on `noreply@aglyn.com` has\n * told every sender behind that domain at once. Those belong everywhere,\n * immediately.\n *\n * An UNSUBSCRIBE is not that. It is a preference a person expressed to ONE\n * brand — the sender line they read, the newsletter they joined — and an\n * agency running twelve unrelated clients out of one account would, on a\n * platform-wide entry, stop mailing that person on behalf of eleven brands\n * they never heard from. So an unsubscribe lives only in\n * `hosts/{hostId}/suppressions`, and {@link suppressEmail} refuses it.\n *\n * ## Why a runtime refusal and not just the type\n *\n * {@link EmailSuppressionReason} already excludes it, and a type is not a\n * guard: every caller here builds its reason from a webhook payload or a\n * ternary, `as` casts exist, and the plugin API surface is untyped at the\n * boundary. The cost of the type being wrong once is an opt-out from one\n * brand silently applied to every brand in the account, which is invisible\n * from the console — the mail simply never arrives, and the merchant's own\n * suppression list does not mention it.\n */\nexport const PLATFORM_SUPPRESSION_REASONS: readonly EmailSuppressionReason[] = [\n 'bounce',\n 'complaint',\n 'staff',\n]\n\n/**\n * The reason a self-service opt-out is filed under, on the PER-SITE list.\n *\n * Named because three call sites compare against it — the unsubscribe writes\n * it, the resubscribe link refuses to reverse anything else, and the\n * preference page reads it to decide whether an address may opt back in. A\n * literal in three places is a literal that can be changed in two.\n */\nexport const UNSUBSCRIBE_SUPPRESSION_REASON = 'unsubscribe'\n\nexport interface EmailSuppressionRecord {\n /** The address, in the clear, lowercased. The id is its hash. */\n email: string\n reason: EmailSuppressionReason\n /**\n * The `context` tag the send carried (`'invite'`, `'usage-summary'`,\n * `'campaign'`, …), so a human reading the list can tell which of our\n * senders produced the address that died. Null when the send carried none.\n */\n context: string | null\n /** The site the failure was attributed to, when the send named one. */\n hostId: string | null\n /** Non-null once released. A released record does not suppress. */\n releasedAt: unknown | null\n /**\n * `releasedAt` as a boolean, which the staff list filters by EQUALITY\n * beneath its `suppressedAt` cursor: \"released\" read from `releasedAt`\n * would be `!= null`, an inequality Firestore makes the first sort.\n * Absent on records written before it existed until\n * `tools/scripts/backfill-email-suppression-filters.mjs` stamps them.\n */\n released?: boolean\n /** Search tokens for the address; see {@link emailSearchTokens}. */\n emailTokens?: string[]\n /** What lifted it. Absent on records written before releases were typed. */\n releasedVia?: EmailReleaseChannel\n /** The site whose confirmed double opt-in lifted it, when one did. */\n releasedHostId?: string | null\n /** The stream that was confirmed, likewise. */\n releasedTopicId?: string | null\n}\n\n/**\n * Document id for an address: `sha256` of the lowercased, trimmed form.\n *\n * The SAME derivation `campaign-send.ts` uses for `hosts/{hostId}/suppressions`\n * — deliberately, so the two lists can never disagree about which document\n * describes which person.\n *\n * @returns the id, or `null` for anything that is not an address. Never a\n * best-guess id: suppressing the wrong person and believing you\n * suppressed the right one is worse than refusing.\n */\nexport function emailSuppressionKey(\n email: string | null | undefined,\n): string | null {\n /*\n * Delegated, not reimplemented. A second hash of the same address is how\n * this area got two derivations that agreed only by accident; `personKey`\n * is the one that normalizes and the one the unsubscribe route already\n * hashes through, so a suppression filed by either is found by both.\n */\n return personKey(email)\n}\n\n/**\n * The `array-contains` search tokens for an address — shared with every list\n * that searches one (`@aglyn/aglyn/app-utils/email-search`), re-exported here\n * for the callers that have always imported it from this module.\n *\n * Mirrored for the backfills that stamp the rows written before the field\n * (`backfill-email-suppression-filters.mjs`, `backfill-host-suppression-filters.mjs`,\n * `backfill-email-list-filters.mjs`) by ONE script-side twin,\n * `tools/scripts/lib/email-search-tokens.mjs`; the spec and the twin's test\n * both assert `email-search-tokens.fixtures.json`.\n */\nexport { emailSearchTokens }\n\nexport interface SuppressEmailInput {\n email: string\n reason: EmailSuppressionReason\n /** The `context` tag the failed send carried, when it carried one. */\n context?: string | null\n /** The site the failed send was attributed to, when it named one. */\n hostId?: string | null\n /**\n * Whether to say so on the person's record too (AGL-3245); on by default.\n * A sender that stamps a richer verdict of its own passes `false`.\n */\n stampRecord?: boolean\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n}\n\n/**\n * Record a platform-wide suppression. Idempotent by document id.\n *\n * `createdAt` is stamped only when the document is new, matching the per-host\n * list: a second bounce must not overwrite the moment the address first went\n * bad, because that is the date a human is told when they ask. `suppressedAt`\n * moves every time, so \"when did we last see this fail\" stays answerable.\n *\n * A previously released record is un-released — a fresh failure is a fresh\n * failure.\n *\n * @returns `created: false` when the address was already on the list.\n */\nexport async function suppressEmail(input: SuppressEmailInput): Promise<{\n key: string\n created: boolean\n}> {\n const key = emailSuppressionKey(input.email)\n if (!key) {\n throw new Error('[email-suppression] cannot key a suppression for that value')\n }\n if (!PLATFORM_SUPPRESSION_REASONS.includes(input.reason)) {\n throw new Error(\n `[email-suppression] ${input.reason} is a per-site preference and ` +\n 'cannot be filed platform-wide',\n )\n }\n const db = input.firestore ?? defaultFirestore()\n const ref = db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key)\n const snapshot = await ref.get()\n const email = String(input.email).trim().toLowerCase()\n await ref.set(\n {\n email,\n emailTokens: emailSearchTokens(email),\n reason: input.reason,\n context: input.context ?? null,\n hostId: input.hostId ?? null,\n releasedAt: null,\n released: false,\n suppressedAt: FieldValue.serverTimestamp(),\n ...(snapshot.exists ? {} : { createdAt: FieldValue.serverTimestamp() }),\n },\n { merge: true },\n )\n /*\n * The same verdict on the record the person reads (AGL-3245), through\n * whichever plugin keeps the workspace's records: a bounce or a complaint\n * on a send that named a site stamps the site's records. A send that\n * named none has no records to find, and a caller that stamps its own,\n * richer verdict — the sequence runtime, with the domain block and the\n * enrollment — says `stampRecord: false` and is left to it.\n */\n if (input.hostId && input.stampRecord !== false && input.reason !== 'staff') {\n await stampRecordEmailState({\n hostId: input.hostId,\n email: input.email,\n state: {\n status: input.reason === 'complaint' ? 'complained' : 'bounced',\n atMs: Date.now(),\n source: 'campaign',\n detail: input.context ? `Reported by the ${input.context} send.` : null,\n },\n })\n }\n return { key, created: !snapshot.exists }\n}\n\n/**\n * What lifted a suppression, recorded on the record it lifted.\n *\n * Written explicitly by both paths rather than left to \"absent means staff\".\n * The two are held to different rules — a staff release may lift any reason,\n * a confirmed opt-in may lift exactly one — so the audit answer to \"how did\n * this address get back on the domain\" has to be a stored fact and not an\n * inference from which field happens to be missing.\n */\nexport type EmailReleaseChannel =\n /** A staff correction through the admin suppressions surface. */\n | 'staff'\n /** A recipient completed a double opt-in from this address. */\n | 'double-opt-in'\n\n/**\n * Put an address back in circulation (a staff correction, or the person asking\n * to be re-added). The record is kept and marked released, never deleted —\n * same reasoning as `releasePhoneContact`: a deleted record cannot show that\n * the suppression was honored while it stood.\n *\n * Unconditional on the reason, and that is what separates it from\n * {@link releaseEmailForConfirmedOptIn}: a human with the staff role has read\n * the record and is accountable for the row, so they may lift a complaint —\n * a report filed against the wrong message, an address entered by mistake.\n * Nothing automatic gets that latitude.\n *\n * @returns false when there was no live record to release.\n */\nexport async function releaseEmail(input: {\n email: string\n releasedByUid?: string | null\n note?: string | null\n firestore?: any\n}): Promise<boolean> {\n const key = emailSuppressionKey(input.email)\n if (!key) return false\n const db = input.firestore ?? defaultFirestore()\n const ref = db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key)\n const snapshot = await ref.get()\n if (!snapshot.exists || snapshot.get('releasedAt')) return false\n await ref.set(\n {\n releasedAt: FieldValue.serverTimestamp(),\n released: true,\n releasedByUid: input.releasedByUid ?? null,\n releasedNote: input.note ?? null,\n releasedVia: 'staff' satisfies EmailReleaseChannel,\n },\n { merge: true },\n )\n return true\n}\n\n/**\n * The ONLY reason a completed round trip may lift, as a runtime set.\n *\n * ## Why a bounce is releasable\n *\n * A `bounce` record is a claim about a MAILBOX at a moment: mail addressed\n * here was permanently refused. Somebody clicking a confirmation link that\n * was delivered to that mailbox has refuted the claim with the only evidence\n * that could refute it — the message arrived, a human read it, and the round\n * trip closed. Leaving the record standing after that makes one transient\n * failure recorded as permanent — a mailbox that was full, a receiving server\n * that answered 550 while it was misconfigured — a life sentence no route can\n * undo.\n *\n * ## Why a complaint is NOT, and never will be\n *\n * `complaint` is not a deliverability fact. It is a person stating they do not\n * want this mail, and a round trip proves nothing about that statement — it\n * proves the mailbox works, which nobody doubted. Releasing one here would\n * make a public signup form into a laundry for spam complaints: submit the\n * complainant's address, they receive a confirmation (the shared sender is\n * transactional and consults no list), and one click anywhere in the chain\n * puts them back on the sending domain that the complaint was filed against.\n * The same reasoning refuses `staff`, which is a written request, a\n * correction, or a legal instruction, and is nobody's to reverse from a link.\n *\n * A runtime set and not just the type, for the reason\n * {@link PLATFORM_SUPPRESSION_REASONS} gives: reasons arrive from webhook\n * payloads through an untyped boundary, and the cost of the type being wrong\n * once here is a complaint silently laundered.\n */\nexport const OPT_IN_RELEASABLE_REASONS: readonly EmailSuppressionReason[] = [\n 'bounce',\n]\n\n/** What a completed double opt-in did to a platform suppression. */\nexport type ConfirmedOptInRelease =\n /** A live `bounce` record was lifted. The address is mailable again. */\n | 'released'\n /** Nothing was suppressed, or it was already released. */\n | 'nothing-to-release'\n /** A record stands that a round trip may not lift — see the constant. */\n | 'refused'\n /** The read or the write failed. The record, whatever it is, still stands. */\n | 'failed'\n\n/**\n * Lift a platform suppression that a completed double opt-in has disproved.\n *\n * THE ONE PLACE THE AUTOMATIC RULE IS STATED, mirroring\n * `releaseSiteSuppression` for the per-site list: every path that puts an\n * address back in circulation without a human deciding goes through here, so\n * there is one line to read and one line to change.\n *\n * ## Platform-wide, from one site's round trip\n *\n * The record being lifted asserts something host-independent — this mailbox\n * does not exist, learned anywhere in the product, including on transactional\n * mail that carried no site tag. A confirmation delivered to that mailbox\n * disproves it just as host-independently, so scoping the release to the\n * confirming site would leave a record standing that says the mailbox is dead\n * while we hold proof that it is not. The site and the topic are written onto\n * the record instead, which is what makes the release reviewable: an operator\n * reading the row sees which site's round trip lifted it and when.\n *\n * ## The per-site list is NOT touched\n *\n * `hosts/{hostId}/suppressions` mixes a deliverability fact with a stated\n * preference — an unsubscribe from that one site lives there too — and the\n * email plugin's `releaseSiteSuppression` is the single guarded path that\n * lifts one. Reaching around it from here would put a second, differently\n * reasoned releaser on a list whose whole protection is that there is one.\n *\n * Never throws: it runs inside a recipient's confirmation click, and a\n * Firestore failure must degrade to a suppression that stays in force, not to\n * a person told their confirmation failed.\n */\nexport async function releaseEmailForConfirmedOptIn(input: {\n email: string\n /** The site whose confirmation link was clicked, for the audit trail. */\n hostId: string\n /** The stream that was confirmed, likewise. */\n topicId: string\n firestore?: any\n}): Promise<ConfirmedOptInRelease> {\n const key = emailSuppressionKey(input.email)\n if (!key) return 'nothing-to-release'\n try {\n const db = input.firestore ?? defaultFirestore()\n const ref = db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key)\n const snapshot = await ref.get()\n if (!snapshot.exists || snapshot.get('releasedAt')) {\n return 'nothing-to-release'\n }\n if (!OPT_IN_RELEASABLE_REASONS.includes(snapshot.get('reason'))) {\n return 'refused'\n }\n await ref.set(\n {\n releasedAt: FieldValue.serverTimestamp(),\n released: true,\n // No human released this, so the field says so rather than naming\n // whoever last touched the record.\n releasedByUid: null,\n releasedVia: 'double-opt-in' satisfies EmailReleaseChannel,\n releasedHostId: input.hostId || null,\n releasedTopicId: input.topicId || null,\n },\n { merge: true },\n )\n return 'released'\n } catch (error) {\n console.error(\n '[email-suppression] opt-in release failed; suppression stands',\n error,\n )\n return 'failed'\n }\n}\n\n/**\n * The BULK-SEND gate. See the module note for which senders must call this and\n * which must not.\n *\n * FAILS CLOSED, like `isPhoneContactSuppressed`: a read that throws answers\n * `true`, meaning \"treat as suppressed\". The cost of failing closed here is\n * one delayed informational email — every caller is a cron that runs again —\n * and it is nearly free besides, because every one of them is already deep\n * inside a Firestore-backed sweep that a Firestore outage has stopped anyway.\n * The cost of failing open is another delivery attempt at a mailbox that has\n * already told us permanently that it does not exist, which is precisely the\n * behaviour a provider scores a sending domain on. Never \"fix\" a flaky read\n * here by returning false.\n */\nexport async function isEmailSuppressed(\n email: string | null | undefined,\n injectedFirestore?: any,\n): Promise<boolean> {\n const key = emailSuppressionKey(email)\n // An unusable value is one we cannot check against the list, so it is one we\n // must not send to. Same fail-closed rule.\n if (!key) return true\n try {\n const db = injectedFirestore ?? defaultFirestore()\n const snapshot = await db\n .collection(EMAIL_SUPPRESSIONS_COLLECTION)\n .doc(key)\n .get()\n if (!snapshot.exists) return false\n return !snapshot.get('releasedAt')\n } catch (error) {\n console.error('[email-suppression] lookup failed; failing closed', error)\n return true\n }\n}\n\n/**\n * The sendable subset of a recipient list, for the bulk senders.\n *\n * One `get()` per DISTINCT address rather than a query, so the check needs no\n * index and cannot fail open on a missing one. The list is deduplicated first\n * because the callers build it by fanning out over an org's owners and admins,\n * which routinely names the same person twice.\n */\nexport async function filterSuppressedEmails(\n emails: readonly string[],\n injectedFirestore?: any,\n): Promise<string[]> {\n const seen = new Set<string>()\n const candidates: string[] = []\n for (const email of emails) {\n const normalized = String(email ?? '')\n .trim()\n .toLowerCase()\n if (!normalized || seen.has(normalized)) continue\n seen.add(normalized)\n candidates.push(normalized)\n }\n const verdicts = await Promise.all(\n candidates.map((email) => isEmailSuppressed(email, injectedFirestore)),\n )\n return candidates.filter((_email, index) => !verdicts[index])\n}\n\n/*==========================================\n * THE SENDER A PERSON LEAVES IS THE CONSENT GROUP, NOT THE SITE.\n *\n * `consent-groups.ts` lets an org declare several sites ONE sender — a shop,\n * a booking page and a blog under one name, disclosed as one on every\n * capture form. To the person on the other end those are one sender, so\n * leaving any of them is leaving it: an unsubscribe filed by site A has to\n * withhold site B's mail too, or the recipient is made to unsubscribe once\n * per site of a sender they only ever knew as one.\n *\n * Every opt-out is written against the ONE site the person acted on and read\n * across the sending site's CURRENT group. Reading rather than copying on\n * write is what makes a site that joins a group inherit every refusal already\n * standing against its siblings, and it reaches every row already stored and\n * every link already sitting in an inbox — none of which a write-time fan-out\n * could.\n *\n * All three per-site facts are read this way: the site suppression list (an\n * unsubscribe, a hand-added opt-out, an erasure, and the bounces and\n * complaints the platform list already carries), the topic opt-outs, and the\n * recipient's cadence. A sibling's pending confirmation joins them only when\n * the org turned its group's confirmation switch on — see\n * {@link filterTopicSendable}. The group of one — every site of an org that\n * declared nothing — reads exactly the documents these filters always read,\n * in the same round trips.\n *=========================================*/\n\n/**\n * The sites whose opt-out lists answer for a send made BY `hostId`, the\n * sending site first.\n *\n * The sending site's consent group: every site it names, because a refusal\n * standing on any of them is a refusal of the sender. Absent, or a group of\n * one, is the site alone.\n *\n * The group is the one `consentGroupForHost` resolved — never a set a caller\n * built from `org.hosts` or a shared domain, which would be inferring a\n * controller (see `consent-groups.ts`).\n *\n * Throws on a group resolved for a DIFFERENT site. That is a wiring defect no\n * runtime value produces, and the failure it would hide is one site's send\n * decided against another site's lists — the same refusal\n * `splitByMarketingConsent` makes over a consent map read for the wrong host.\n */\nexport function optOutHostIds(\n hostId: string,\n group?: Pick<ConsentGroup, 'hostId' | 'hostIds'> | null,\n): string[] {\n if (!group) return [hostId]\n if (group.hostId !== hostId) {\n throw new Error(\n `[email-suppression] a consent group resolved for ${group.hostId} ` +\n `cannot decide a send from ${hostId}`,\n )\n }\n return consentGroupOptOutHosts(group)\n}\n\n/**\n * One keyed `getAll` per site in `hostIds`, positionally aligned with `keys`.\n *\n * Per site rather than one call over every (site, address) pair, so each\n * round trip is exactly the size the single-site read always was — a batch\n * of a campaign — and a group multiplies the number of calls, run in\n * parallel, rather than the size of one. A group of one is one call, over\n * the same references in the same order.\n *\n * Rejects when any read does; each caller keeps its own posture on that.\n */\nexport async function getAllAcrossSites(\n db: any,\n hostIds: readonly string[],\n subcollection: string,\n keys: readonly string[],\n): Promise<any[][]> {\n return Promise.all(\n hostIds.map((id) => {\n const list = db.collection('hosts').doc(id).collection(subcollection)\n return db.getAll(...keys.map((key) => list.doc(key)))\n }),\n )\n}\n\n/**\n * The sendable subset for a send made in ONE SITE's name — BOTH lists.\n *\n * A per-site suppression says \"not from this site\". A platform suppression\n * says the address hard-bounced or somebody pressed \"report spam\", learned\n * anywhere in the product — including on transactional mail that carried no\n * site tag at all and could therefore never have reached the per-site list.\n * Consulting only the site's own list mails a known-dead or complaining\n * address from the one shared sending domain every tenant's mail leaves by,\n * which makes it every tenant's deliverability problem rather than one\n * merchant's.\n *\n * Composed from {@link filterSuppressedEmails} rather than reimplementing the\n * platform half: normalization, de-duplication and the fail-closed posture\n * live there, and a second copy of them is a second set of rules for two\n * senders to disagree about.\n *\n * ## \"This site\" means its consent group\n *\n * `group` is the sending site's consent group, and an entry on ANY of its\n * sites' lists withholds — see the section above. Every entry counts, whatever\n * its reason: an unsubscribe and a hand-added opt-out are the person leaving\n * the sender, an erasure is already written on every site of the workspace,\n * and a bounce or a complaint is on the platform list besides. Omitted, the\n * site alone, which is also the whole answer for an org that declared no\n * group.\n *\n * ## Both halves fail CLOSED\n *\n * A read that throws answers \"suppressed\". The platform half already does; the\n * per-site half matches it, because a list we could not read is not a list\n * that said this address is safe to mail. The cost of the other choice is a\n * message delivered to somebody who asked us to stop.\n *\n * ## One `getAll`, keyed, rather than a scan of the collection\n *\n * The per-site half looks up exactly the addresses being mailed, by document\n * id, in one round trip per site. Reading the whole collection instead —\n * which is what the campaign sender did — is bounded by however large the\n * collection has grown, so a site with more suppressions than the read window\n * fails OPEN on the remainder: the people most certain not to want the mail\n * are the ones a truncated read drops.\n */\nexport async function filterSendableForHost(\n hostId: string,\n emails: readonly string[],\n injectedFirestore?: any,\n group?: Pick<ConsentGroup, 'hostId' | 'hostIds'> | null,\n): Promise<string[]> {\n const hostIds = optOutHostIds(hostId, group)\n const platformSendable = await filterSuppressedEmails(\n emails,\n injectedFirestore,\n )\n // `getAll` rejects an empty reference list, and there is nothing to ask.\n if (!platformSendable.length) return []\n const db = injectedFirestore ?? defaultFirestore()\n // Every survivor of the platform half is keyable — `isEmailSuppressed`\n // answers `true` for an address it cannot key — so this narrows the type\n // rather than dropping anybody.\n const keyed: Array<{ email: string; key: string }> = []\n for (const email of platformSendable) {\n const key = emailSuppressionKey(email)\n if (key) keyed.push({ email, key })\n }\n if (!keyed.length) return []\n try {\n const bySite = await getAllAcrossSites(\n db,\n hostIds,\n HOST_SUPPRESSIONS_SUBCOLLECTION,\n keyed.map((entry) => entry.key),\n )\n return keyed\n .filter(\n (_entry, index) =>\n !bySite.some((snapshots) => snapshots[index]?.exists),\n )\n .map((entry) => entry.email)\n } catch (error) {\n console.error(\n '[email-suppression] per-site lookup failed; failing closed',\n error,\n )\n return []\n }\n}\n\n/**\n * The subset of `emails` that may be mailed about `topicId` on this site.\n *\n * The third filter a campaign passes, after the platform list and the site's\n * own: the two suppression lists answer \"may we mail this person at all\", and\n * this answers \"may we mail them about THIS\". A recipient who unticked\n * \"Promotions and offers\" on the preference page is not suppressed — they\n * still get the newsletter — so the fact cannot live on either suppression\n * list without meaning something it does not mean.\n *\n * ## Two ways to be excluded, and both are held here\n *\n * Somebody who LEFT the stream, and somebody who has been asked to confirm\n * joining it and has not. The second is what makes a double opt-in worth\n * recording: an unconfirmed subscriber has to be a real quarantine, not a\n * field the send path never looks at. Both come back from\n * `readTopicSubscriptionState`, which is the only place the three states are\n * decided.\n *\n * Keyed by {@link emailSuppressionKey} and read with one `getAll`, which is\n * both halves of the point: the same derivation as the two lists it runs\n * beside, so one person is one document id everywhere; and one round trip\n * bounded by the size of the send, so adding topics does not make a campaign\n * cost more to resolve.\n *\n * ## This one fails OPEN, and that is the opposite of its neighbors\n *\n * Every other filter in this module answers \"suppressed\" when a read throws,\n * because the cost of guessing wrong is mailing somebody who told us to stop.\n * Here the cost of guessing wrong in that direction is refusing to send a\n * newsletter somebody asked for, on a read that failed for an unrelated\n * reason — and the campaign has already passed both suppression lists, so\n * nobody who asked us to stop entirely can reach this line. A topic\n * preference is a narrower fact than a suppression and it gets the treatment\n * that matches. A caller that wants the strict posture already has it one\n * layer up.\n *\n * An empty `topicId` is a campaign from before topics existed, or one whose\n * topic was never resolved. It filters nobody: there is no stream to have\n * left.\n *\n * ## Leaving a stream is leaving it for the whole consent group\n *\n * The topic catalog is the org's, so \"Newsletter\" on one site of a declared\n * group is the same stream on its siblings, and a person who left it on one\n * has left it from the sender. `group` extends the read to every site in it,\n * exactly as {@link filterSendableForHost} does for the suppression list.\n *\n * A sibling's REFUSAL always holds. A sibling's pending confirmation holds\n * only when the group `awaitsConfirmation` — the org's switch, resolved into\n * the group, so asking it reads nothing the refusal read did not already\n * read. Off, the question stays the concern of the site whose form asked it.\n */\nexport async function filterTopicSendable(\n hostId: string,\n topicId: string | null | undefined,\n emails: readonly string[],\n injectedFirestore?: any,\n group?: Pick<ConsentGroup, 'hostId' | 'hostIds' | 'awaitsConfirmation'> | null,\n): Promise<string[]> {\n const hostIds = optOutHostIds(hostId, group)\n const topic = String(topicId ?? '').trim()\n if (!topic || !emails.length) return [...emails]\n // An unkeyable address cannot carry an opt-out record, so it cannot have\n // left this topic. It is dropped from the LOOKUP and kept in the answer —\n // the suppression filters above have already refused it on their own\n // stricter rule, so this one has no business refusing it a second time.\n const lookups: Array<{ email: string; key: string }> = []\n for (const email of emails) {\n const key = emailSuppressionKey(email)\n if (key) lookups.push({ email, key })\n }\n if (!lookups.length) return [...emails]\n try {\n const db = injectedFirestore ?? defaultFirestore()\n const bySite = await getAllAcrossSites(\n db,\n hostIds,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n lookups.map((entry) => entry.key),\n )\n /*\n * The shared state reader, never a field test written out here.\n *\n * An entry means one of three things and only that function knows all\n * three. The shorthand this replaced — \"an entry with no\n * `resubscribedAt` is a live opt-out\" — reads a CONFIRMED double\n * opt-in, which carries `pendingAt` and `confirmedAt` and no\n * `resubscribedAt`, as somebody who left.\n */\n const stateIn = (snapshot: any) =>\n snapshot?.exists\n ? readTopicSubscriptionState((snapshot.get('topics') ?? {})[topic])\n : 'subscribed'\n // The sending site first, as `optOutHostIds` ordered the reads — which\n // is how the fold tells its own pending question from a sibling's.\n const awaits = { awaitsConfirmation: group?.awaitsConfirmation === true }\n const gone = new Set<string>()\n lookups.forEach((entry, index) => {\n const states = bySite.map((snapshots) => stateIn(snapshots[index]))\n if (consentGroupTopicState(awaits, states) !== 'subscribed') {\n gone.add(entry.email)\n }\n })\n return emails.filter((email) => !gone.has(email))\n } catch (error) {\n console.error(\n '[email-suppression] topic opt-out lookup failed; failing open',\n error,\n )\n return [...emails]\n }\n}\n\n/*\n * THE FOURTH FILTER IS NOT IN THIS FILE, and where it is is forced.\n *\n * `filterCadenceSendable` — the subset that has not asked this site for mail\n * less often than right now — lives in `email-marketing-gate.ts`, because it\n * reads the per-recipient counter document that module owns and names. That\n * module already imports this one for the two suppression lists, so putting\n * the cadence filter here would close a cycle. A campaign's subtraction chain\n * therefore reads: this file's two lists, this file's topic opt-outs, then\n * that file's cadence.\n */\n\n/**\n * The staff queue, newest first, ordered by `suppressedAt` so a re-recorded or\n * released entry surfaces again — the operator's question is \"what changed\",\n * not \"what was first written\". Mirrors `listContactSuppressions`.\n */\nexport async function listEmailSuppressions(options?: {\n limit?: number\n /**\n * Where the NEXT page starts: the `suppressedAt` of the last row already\n * shown, as `seconds.nanoseconds`.\n *\n * The full timestamp rather than milliseconds, because `startAfter` skips\n * exactly the value it is given: a millisecond-truncated cursor sits BEFORE\n * the record it names, so that record would arrive again at the top of the\n * following page. Repeating a row is a smaller fault than skipping one and\n * neither is necessary.\n */\n startAfter?: string | null\n /**\n * Predicates the caller adds beneath the ordering — equalities, one\n * `array-contains`, and ranges over `suppressedAt` itself, which are the\n * only shapes that keep this cursor valid. It must not add an `orderBy`.\n */\n narrow?: (query: any) => any\n firestore?: any\n}): Promise<Array<EmailSuppressionRecord & { $id: string }>> {\n const db = options?.firestore ?? defaultFirestore()\n const collection = db.collection(EMAIL_SUPPRESSIONS_COLLECTION)\n let query = (options?.narrow ? options.narrow(collection) : collection).orderBy(\n 'suppressedAt',\n 'desc',\n )\n const cursor = suppressionCursorTimestamp(options?.startAfter)\n if (cursor) query = query.startAfter(cursor)\n const snapshot = await query\n .limit(Math.min(Math.max(options?.limit ?? 100, 1), 500))\n .get()\n return snapshot.docs.map((doc: any) => ({\n $id: doc.id,\n ...(doc.data() as EmailSuppressionRecord),\n }))\n}\n\n/**\n * The cursor a page hands back, from the last row on it.\n *\n * Null when the row carries no `suppressedAt` — every entry written since\n * AGL-1918 does, and `orderBy` has already excluded any that does not, so\n * this is the type narrowing rather than a case that occurs.\n */\nexport function suppressionCursorFrom(\n record: Record<string, any> | null | undefined,\n): string | null {\n const at = record?.['suppressedAt'] as\n | { seconds?: number; _seconds?: number; nanoseconds?: number; _nanoseconds?: number }\n | undefined\n const seconds = at?.seconds ?? at?._seconds\n if (typeof seconds !== 'number') return null\n const nanoseconds = at?.nanoseconds ?? at?._nanoseconds ?? 0\n return `${seconds}.${nanoseconds}`\n}\n\n/** The inverse, for the query. Invalid input yields no cursor, never a guess. */\nexport function suppressionCursorTimestamp(\n cursor: string | null | undefined,\n): Timestamp | null {\n const [rawSeconds, rawNanos] = String(cursor ?? '').split('.')\n const seconds = Number(rawSeconds)\n const nanoseconds = Number(rawNanos ?? 0)\n if (!Number.isFinite(seconds) || !seconds) return null\n return new Timestamp(seconds, Number.isFinite(nanoseconds) ? nanoseconds : 0)\n}\n\n/*==========================================\n * THE ERASURE ROW ON THE PER-SITE LIST (AGL-2623).\n *\n * A person erased from a workspace must not be quietly rebuilt by the next\n * form they fill in or the next order they place, and must not be mailed by\n * a campaign either. Both gates already read `hosts/{hostId}/suppressions`\n * — every campaign filter refuses an address with a row there — so the\n * erasure writes one row per site of the workspace rather than inventing a\n * third list, and the capture door reads the same row.\n *\n * The row carries NO address. Every other writer of this list stores the\n * email in the clear beside the hash, because a hub admin releasing an\n * unsubscribe needs to see who it was; an erasure row is the one whose\n * whole purpose is that the address is no longer held, so the id — the\n * hash — is the entire record, and a row that already held the address in\n * the clear has it removed. The hub's list renders such a row as an entry\n * with no address, which it already knows how to do.\n *\n * Per SITE, not platform-wide, on purpose: the erasure was asked of one\n * workspace, and a second workspace that knows the same person has a\n * relationship this request has no claim on. The platform list is for\n * bounces and complaints, which are facts about the address everywhere.\n *=========================================*/\n\n/** The `reason` an erasure row carries. Read by the capture door, below. */\nexport const HOST_ERASURE_SUPPRESSION_REASON = 'erasure'\n\n/**\n * Suppress an address on one site because the person was erased. Idempotent:\n * a second erasure of the same person merges onto the same row.\n */\nexport async function suppressEmailForHostErasure(input: {\n hostId: string\n email: string\n firestore?: any\n}): Promise<{ key: string; created: boolean } | null> {\n const key = emailSuppressionKey(input.email)\n if (!key) return null\n const db = input.firestore ?? defaultFirestore()\n const ref = db\n .collection('hosts')\n .doc(input.hostId)\n .collection(HOST_SUPPRESSIONS_SUBCOLLECTION)\n .doc(key)\n const snapshot = await ref.get()\n await ref.set(\n {\n email: null,\n // The address's search tokens are the address in pieces, so an erasure\n // clears them with it (AGL-3321).\n emailTokens: [],\n reason: HOST_ERASURE_SUPPRESSION_REASON,\n suppressedAt: FieldValue.serverTimestamp(),\n ...(snapshot.exists ? {} : { createdAt: FieldValue.serverTimestamp() }),\n },\n { merge: true },\n )\n return { key, created: !snapshot.exists }\n}\n\n/**\n * Whether a site has erased this address, so a capture must not create a\n * contact for it. Only an ERASURE row refuses: an ordinary unsubscribe is a\n * mailing preference, and a person who unsubscribed and then bought\n * something is still a customer whose order the CRM should know about.\n *\n * Fails OPEN. A read that throws answers `false` and logs: the alternative\n * refuses every capture on the site for as long as the list is unreadable,\n * which turns a transient read failure into a silent drop of the site's\n * leads and orders. The window this leaves — a recreate during an outage\n * of the suppression read — is logged, and the next erasure run finds the\n * recreated record by the same address.\n */\nexport async function hostRefusesCaptureForErasure(\n hostId: string,\n email: string | null | undefined,\n injectedFirestore?: any,\n): Promise<boolean> {\n const key = emailSuppressionKey(email)\n if (!key) return false\n try {\n const db = injectedFirestore ?? defaultFirestore()\n const snapshot = await db\n .collection('hosts')\n .doc(hostId)\n .collection(HOST_SUPPRESSIONS_SUBCOLLECTION)\n .doc(key)\n .get()\n return (\n Boolean(snapshot?.exists) &&\n snapshot.get('reason') === HOST_ERASURE_SUPPRESSION_REASON\n )\n } catch (error) {\n console.error(\n '[email-suppression] erasure lookup failed; the capture proceeds',\n error,\n )\n return false\n }\n}\n"],"names":["FieldValue","Timestamp","consentGroupOptOutHosts","consentGroupTopicState","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","emailSearchTokens","personKey","stampRecordEmailState","firebaseAdmin","defaultFirestore","app","firestore","EMAIL_SUPPRESSIONS_COLLECTION","HOST_SUPPRESSIONS_SUBCOLLECTION","PLATFORM_SUPPRESSION_REASONS","UNSUBSCRIBE_SUPPRESSION_REASON","emailSuppressionKey","email","suppressEmail","input","key","Error","includes","reason","db","ref","collection","doc","snapshot","get","String","trim","toLowerCase","set","emailTokens","context","hostId","releasedAt","released","suppressedAt","serverTimestamp","exists","createdAt","merge","stampRecord","state","status","atMs","Date","now","source","detail","created","releaseEmail","releasedByUid","releasedNote","note","releasedVia","OPT_IN_RELEASABLE_REASONS","releaseEmailForConfirmedOptIn","releasedHostId","releasedTopicId","topicId","error","console","isEmailSuppressed","injectedFirestore","filterSuppressedEmails","emails","seen","Set","candidates","normalized","has","add","push","verdicts","Promise","all","map","filter","_email","index","optOutHostIds","group","getAllAcrossSites","hostIds","subcollection","keys","id","list","getAll","filterSendableForHost","platformSendable","length","keyed","bySite","entry","_entry","some","snapshots","filterTopicSendable","topic","lookups","stateIn","awaits","awaitsConfirmation","gone","forEach","states","listEmailSuppressions","options","query","narrow","orderBy","cursor","suppressionCursorTimestamp","startAfter","limit","Math","min","max","docs","$id","data","suppressionCursorFrom","record","at","seconds","_seconds","nanoseconds","_nanoseconds","rawSeconds","rawNanos","split","Number","isFinite","HOST_ERASURE_SUPPRESSION_REASON","suppressEmailForHostErasure","hostRefusesCaptureForErasure","Boolean"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsEC,GAED,SAASA,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,gEAAgE;AAChE,2EAA2E;AAC3E,0EAA0E;AAC1E,iDAAiD;AACjD,SACEC,uBAAuB,EACvBC,sBAAsB,QAEjB,wCAAuC;AAC9C,SACEC,0BAA0B,EAC1BC,4BAA4B,QACvB,sCAAqC;AAC5C,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SAASC,qBAAqB,QAAQ,wDAAuD;AAC7F,OAAOC,mBAAmB,sBAAkB;AAE5C,MAAMC,mBA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CiD,iBAAuB;IAEvB,MAAM9C,MAAMJ,oBAAoBC;IAChC,IAAI,CAACG,KAAK,OAAO;IACjB,IAAI;QACF,MAAMI,KAAK0C,4BAAAA,oBAAqBzD;QAChC,MAAMmB,WAAW,MAAMJ,GACpBE,UAAU,CAAC,SACXC,GAAG,CAACS,QACJV,UAAU,CAACb,iCACXc,GAAG,CAACP,KACJS,GAAG;QACN,OACE+G,QAAQhH,4BAAAA,SAAUa,MAAM,KACxBb,SAASC,GAAG,CAAC,cAAc4G;IAE/B,EAAE,OAAO1E,OAAO;QACdC,QAAQD,KAAK,CACX,mEACAA;QAEF,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/email-suppression.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-WIDE email suppression list, `emailSuppressions/{emailKey}`\n * (AGL-2407).\n *\n * ## What was missing\n *\n * AGL-1918 (`7a8f3cd68`) made `email.bounced` (permanent) and\n * `email.complained` write a suppression — into `hosts/{hostId}/suppressions`,\n * found from a Resend tag that only `campaign-send.ts` stamped. That closed\n * the campaign half and could close no other, because there was nowhere to\n * file the rest:\n *\n * Every other sender in the product goes through the shared `sendEmail` —\n * invites,\n * password resets, verification, receipts, booking confirmations, the monthly\n * usage summary, the usage-alert fan-out, restock and abandoned-cart mail, the\n * merchant-authored workflow `sendEmail` step. A bounce on any of those\n * arrived at the webhook with no site to place it against and was answered\n * `200 {ignored:true}`. A dead address was re-mailed on every subsequent send,\n * forever, and a spam complaint had no effect on anything.\n *\n * That matters most exactly when it is hardest to fix: on Sept 1 the signup\n * door opens, and verification and invite mail — addressed by strangers typing\n * addresses — is the highest-bounce-rate mail we send, on the same Resend key\n * and the same From address as everything else.\n *\n * ## Why a sibling of `contactSuppressions` and not a channel on it\n *\n * `contact-suppression.ts` is the same idea for phones and every argument it\n * makes holds here: keyed on the identifier because that is what the sender\n * holds at send time; one `get()` by document id, no query and no composite\n * index that could go missing and fail the lookup open; a revocation is a\n * FIELD and not a delete, because the record is the evidence that the\n * suppression was honoured while it was in force.\n *\n * It is a separate collection for one concrete reason: the document id. That\n * list's key is the E.164 digits, and its docblock argues at length that a\n * phone number must NOT be hashed (NANP is ~10^10 values, so a hash buys the\n * appearance of de-identification and none of the substance). An email address\n * is not enumerable, `hosts/{hostId}/suppressions` already keys on\n * `sha256(email)`, and one collection holding two incompatible key spaces is\n * how a lookup comes to be performed against the wrong derivation. The\n * address is stored in the document in the clear regardless, exactly as the\n * per-host list stores it, so a staff reader still shows a human something\n * they can act on.\n *\n * ## Who reads it, and who deliberately does NOT\n *\n * AGL-1438's rule is that a QUOTA may only ever refuse a campaign, because\n * refusing a receipt or a password reset converts a billing event into an\n * outage on a customer's business. A suppression is not a quota, but the same\n * proportionality applies and lands in the same place:\n *\n * - **Bulk mail consults this list.** The monthly usage summary, the\n * usage-alert fan-out and the marketplace review fan-out to a publisher's\n * owners and admins go to a LIST of people who did not ask for that\n * particular message, on a schedule or on every submission, forever. They\n * are the sends that re-hit a dead mailbox every month and teach a mailbox\n * provider that `aglyn.com` does not listen.\n * - **Transactional mail does NOT.** A password reset, a verification, an\n * invite, a receipt or a booking confirmation answers something the human\n * just did. Refusing one because an address bounced or because somebody\n * once pressed \"report spam\" on an unrelated message would lock a real\n * customer out of their own account. The shared sender is therefore left\n * unconditional on purpose, and this is the note that says so.\n *\n * (Written throughout without a literal call expression, on purpose:\n * `email-send-metering-coverage.spec.ts` enumerates senders by grepping the\n * tree for one, and a prose mention here would enrol a module that sends\n * nothing into the AGL-1438 cost-meter sweep.)\n */\n\nimport { FieldValue, Timestamp } from 'firebase-admin/firestore'\n// The leaf entry, not the `@aglyn/aglyn` barrel, for the reason\n// `document-id.ts` gives at length: a barrel import resolves to whatever a\n// spec's `jest.mock` happens to contain, and this module's neighbours are\n// mocked in nearly every spec that touches them.\nimport {\n consentGroupOptOutHosts,\n consentGroupTopicState,\n type ConsentGroup,\n} from '@aglyn/aglyn/app-utils/consent-groups'\nimport {\n readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/email-topics'\nimport { emailSearchTokens } from '@aglyn/aglyn/app-utils/email-search'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport { stampRecordEmailState } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport firebaseAdmin from './firebase-admin'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\nexport const EMAIL_SUPPRESSIONS_COLLECTION = 'emailSuppressions'\n\n/**\n * The PER-SITE list, `hosts/{hostId}/suppressions/{emailKey}` — unsubscribes\n * from one site's campaigns, plus the bounces and complaints that arrived\n * carrying that site's tag.\n *\n * Named here rather than at each call site because the two lists are read\n * together by {@link filterSendableForHost}, and a sender that knows one path\n * as a string literal and the other through this module is one rename away\n * from consulting a collection that does not exist and finding nobody\n * suppressed.\n */\nexport const HOST_SUPPRESSIONS_SUBCOLLECTION = 'suppressions'\n\n/**\n * Why an address is suppressed.\n *\n * `bounce` means PERMANENT only. Resend reports `data.bounce.type` as\n * `Permanent` or `Transient`, and a transient bounce is a full mailbox or a\n * greylisting server — recording one here would suppress a real recipient over\n * a temporary condition at their provider. The webhook makes that distinction;\n * this type only names the outcome.\n */\nexport type EmailSuppressionReason =\n /** Permanent bounce — the mailbox does not exist. */\n | 'bounce'\n /** The recipient pressed \"report spam\". */\n | 'complaint'\n /** Recorded by staff (a written request, a court order, a correction). */\n | 'staff'\n /**\n * The address's domain takes no mail — no MX and no address record, or a\n * null MX — as the deliverability preflight found before a send\n * (AGL-3328). Filed without a bounce ever happening, which is the point:\n * the bounce is what it prevents. A fact about the address for everyone,\n * like a bounce; a staff release lifts it, and the preflight files it\n * again only if the domain still takes no mail.\n */\n | 'no_mail_server'\n\n/**\n * The reasons that may be filed PLATFORM-WIDE, as a runtime set.\n *\n * ## The split this constant enforces\n *\n * A bounce and a complaint are facts about a MAILBOX and about the sending\n * domain every tenant's mail leaves by: the address does not exist for\n * anybody, and somebody who pressed \"report spam\" on `noreply@aglyn.com` has\n * told every sender behind that domain at once. Those belong everywhere,\n * immediately.\n *\n * An UNSUBSCRIBE is not that. It is a preference a person expressed to ONE\n * brand — the sender line they read, the newsletter they joined — and an\n * agency running twelve unrelated clients out of one account would, on a\n * platform-wide entry, stop mailing that person on behalf of eleven brands\n * they never heard from. So an unsubscribe lives only in\n * `hosts/{hostId}/suppressions`, and {@link suppressEmail} refuses it.\n *\n * ## Why a runtime refusal and not just the type\n *\n * {@link EmailSuppressionReason} already excludes it, and a type is not a\n * guard: every caller here builds its reason from a webhook payload or a\n * ternary, `as` casts exist, and the plugin API surface is untyped at the\n * boundary. The cost of the type being wrong once is an opt-out from one\n * brand silently applied to every brand in the account, which is invisible\n * from the console — the mail simply never arrives, and the merchant's own\n * suppression list does not mention it.\n */\nexport const PLATFORM_SUPPRESSION_REASONS: readonly EmailSuppressionReason[] = [\n 'bounce',\n 'complaint',\n 'staff',\n 'no_mail_server',\n]\n\n/**\n * The reason a self-service opt-out is filed under, on the PER-SITE list.\n *\n * Named because three call sites compare against it — the unsubscribe writes\n * it, the resubscribe link refuses to reverse anything else, and the\n * preference page reads it to decide whether an address may opt back in. A\n * literal in three places is a literal that can be changed in two.\n */\nexport const UNSUBSCRIBE_SUPPRESSION_REASON = 'unsubscribe'\n\nexport interface EmailSuppressionRecord {\n /** The address, in the clear, lowercased. The id is its hash. */\n email: string\n reason: EmailSuppressionReason\n /**\n * The `context` tag the send carried (`'invite'`, `'usage-summary'`,\n * `'campaign'`, …), so a human reading the list can tell which of our\n * senders produced the address that died. Null when the send carried none.\n */\n context: string | null\n /** The site the failure was attributed to, when the send named one. */\n hostId: string | null\n /** Non-null once released. A released record does not suppress. */\n releasedAt: unknown | null\n /**\n * `releasedAt` as a boolean, which the staff list filters by EQUALITY\n * beneath its `suppressedAt` cursor: \"released\" read from `releasedAt`\n * would be `!= null`, an inequality Firestore makes the first sort.\n * Absent on records written before it existed until\n * `tools/scripts/backfill-email-suppression-filters.mjs` stamps them.\n */\n released?: boolean\n /** Search tokens for the address; see {@link emailSearchTokens}. */\n emailTokens?: string[]\n /** What lifted it. Absent on records written before releases were typed. */\n releasedVia?: EmailReleaseChannel\n /** The site whose confirmed double opt-in lifted it, when one did. */\n releasedHostId?: string | null\n /** The stream that was confirmed, likewise. */\n releasedTopicId?: string | null\n}\n\n/**\n * Document id for an address: `sha256` of the lowercased, trimmed form.\n *\n * The SAME derivation `campaign-send.ts` uses for `hosts/{hostId}/suppressions`\n * — deliberately, so the two lists can never disagree about which document\n * describes which person.\n *\n * @returns the id, or `null` for anything that is not an address. Never a\n * best-guess id: suppressing the wrong person and believing you\n * suppressed the right one is worse than refusing.\n */\nexport function emailSuppressionKey(\n email: string | null | undefined,\n): string | null {\n /*\n * Delegated, not reimplemented. A second hash of the same address is how\n * this area got two derivations that agreed only by accident; `personKey`\n * is the one that normalizes and the one the unsubscribe route already\n * hashes through, so a suppression filed by either is found by both.\n */\n return personKey(email)\n}\n\n/**\n * The `array-contains` search tokens for an address — shared with every list\n * that searches one (`@aglyn/aglyn/app-utils/email-search`), re-exported here\n * for the callers that have always imported it from this module.\n *\n * Mirrored for the backfills that stamp the rows written before the field\n * (`backfill-email-suppression-filters.mjs`, `backfill-host-suppression-filters.mjs`,\n * `backfill-email-list-filters.mjs`) by ONE script-side twin,\n * `tools/scripts/lib/email-search-tokens.mjs`; the spec and the twin's test\n * both assert `email-search-tokens.fixtures.json`.\n */\nexport { emailSearchTokens }\n\nexport interface SuppressEmailInput {\n email: string\n reason: EmailSuppressionReason\n /** The `context` tag the failed send carried, when it carried one. */\n context?: string | null\n /** The site the failed send was attributed to, when it named one. */\n hostId?: string | null\n /**\n * Whether to say so on the person's record too (AGL-3245); on by default.\n * A sender that stamps a richer verdict of its own passes `false`.\n */\n stampRecord?: boolean\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n}\n\n/**\n * Record a platform-wide suppression. Idempotent by document id.\n *\n * `createdAt` is stamped only when the document is new, matching the per-host\n * list: a second bounce must not overwrite the moment the address first went\n * bad, because that is the date a human is told when they ask. `suppressedAt`\n * moves every time, so \"when did we last see this fail\" stays answerable.\n *\n * A previously released record is un-released — a fresh failure is a fresh\n * failure.\n *\n * @returns `created: false` when the address was already on the list.\n */\nexport async function suppressEmail(input: SuppressEmailInput): Promise<{\n key: string\n created: boolean\n}> {\n const key = emailSuppressionKey(input.email)\n if (!key) {\n throw new Error('[email-suppression] cannot key a suppression for that value')\n }\n if (!PLATFORM_SUPPRESSION_REASONS.includes(input.reason)) {\n throw new Error(\n `[email-suppression] ${input.reason} is a per-site preference and ` +\n 'cannot be filed platform-wide',\n )\n }\n const db = input.firestore ?? defaultFirestore()\n const ref = db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key)\n const snapshot = await ref.get()\n const email = String(input.email).trim().toLowerCase()\n await ref.set(\n {\n email,\n emailTokens: emailSearchTokens(email),\n reason: input.reason,\n context: input.context ?? null,\n hostId: input.hostId ?? null,\n releasedAt: null,\n released: false,\n suppressedAt: FieldValue.serverTimestamp(),\n ...(snapshot.exists ? {} : { createdAt: FieldValue.serverTimestamp() }),\n },\n { merge: true },\n )\n /*\n * The same verdict on the record the person reads (AGL-3245), through\n * whichever plugin keeps the workspace's records: a bounce or a complaint\n * on a send that named a site stamps the site's records. A send that\n * named none has no records to find, and a caller that stamps its own,\n * richer verdict — the sequence runtime, with the domain block and the\n * enrollment — says `stampRecord: false` and is left to it.\n */\n if (input.hostId && input.stampRecord !== false && input.reason !== 'staff') {\n await stampRecordEmailState({\n hostId: input.hostId,\n email: input.email,\n state: {\n status:\n input.reason === 'complaint'\n ? 'complained'\n : input.reason === 'no_mail_server'\n ? 'undeliverable'\n : 'bounced',\n atMs: Date.now(),\n source: input.reason === 'no_mail_server' ? 'check' : 'campaign',\n detail: input.context ? `Reported by the ${input.context} send.` : null,\n },\n })\n }\n return { key, created: !snapshot.exists }\n}\n\n/**\n * What lifted a suppression, recorded on the record it lifted.\n *\n * Written explicitly by both paths rather than left to \"absent means staff\".\n * The two are held to different rules — a staff release may lift any reason,\n * a confirmed opt-in may lift exactly one — so the audit answer to \"how did\n * this address get back on the domain\" has to be a stored fact and not an\n * inference from which field happens to be missing.\n */\nexport type EmailReleaseChannel =\n /** A staff correction through the admin suppressions surface. */\n | 'staff'\n /** A recipient completed a double opt-in from this address. */\n | 'double-opt-in'\n\n/**\n * Put an address back in circulation (a staff correction, or the person asking\n * to be re-added). The record is kept and marked released, never deleted —\n * same reasoning as `releasePhoneContact`: a deleted record cannot show that\n * the suppression was honored while it stood.\n *\n * Unconditional on the reason, and that is what separates it from\n * {@link releaseEmailForConfirmedOptIn}: a human with the staff role has read\n * the record and is accountable for the row, so they may lift a complaint —\n * a report filed against the wrong message, an address entered by mistake.\n * Nothing automatic gets that latitude.\n *\n * @returns false when there was no live record to release.\n */\nexport async function releaseEmail(input: {\n email: string\n releasedByUid?: string | null\n note?: string | null\n firestore?: any\n}): Promise<boolean> {\n const key = emailSuppressionKey(input.email)\n if (!key) return false\n const db = input.firestore ?? defaultFirestore()\n const ref = db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key)\n const snapshot = await ref.get()\n if (!snapshot.exists || snapshot.get('releasedAt')) return false\n await ref.set(\n {\n releasedAt: FieldValue.serverTimestamp(),\n released: true,\n releasedByUid: input.releasedByUid ?? null,\n releasedNote: input.note ?? null,\n releasedVia: 'staff' satisfies EmailReleaseChannel,\n },\n { merge: true },\n )\n return true\n}\n\n/**\n * The ONLY reason a completed round trip may lift, as a runtime set.\n *\n * ## Why a bounce is releasable\n *\n * A `bounce` record is a claim about a MAILBOX at a moment: mail addressed\n * here was permanently refused. Somebody clicking a confirmation link that\n * was delivered to that mailbox has refuted the claim with the only evidence\n * that could refute it — the message arrived, a human read it, and the round\n * trip closed. Leaving the record standing after that makes one transient\n * failure recorded as permanent — a mailbox that was full, a receiving server\n * that answered 550 while it was misconfigured — a life sentence no route can\n * undo.\n *\n * ## Why a complaint is NOT, and never will be\n *\n * `complaint` is not a deliverability fact. It is a person stating they do not\n * want this mail, and a round trip proves nothing about that statement — it\n * proves the mailbox works, which nobody doubted. Releasing one here would\n * make a public signup form into a laundry for spam complaints: submit the\n * complainant's address, they receive a confirmation (the shared sender is\n * transactional and consults no list), and one click anywhere in the chain\n * puts them back on the sending domain that the complaint was filed against.\n * The same reasoning refuses `staff`, which is a written request, a\n * correction, or a legal instruction, and is nobody's to reverse from a link.\n *\n * A runtime set and not just the type, for the reason\n * {@link PLATFORM_SUPPRESSION_REASONS} gives: reasons arrive from webhook\n * payloads through an untyped boundary, and the cost of the type being wrong\n * once here is a complaint silently laundered.\n */\nexport const OPT_IN_RELEASABLE_REASONS: readonly EmailSuppressionReason[] = [\n 'bounce',\n]\n\n/** What a completed double opt-in did to a platform suppression. */\nexport type ConfirmedOptInRelease =\n /** A live `bounce` record was lifted. The address is mailable again. */\n | 'released'\n /** Nothing was suppressed, or it was already released. */\n | 'nothing-to-release'\n /** A record stands that a round trip may not lift — see the constant. */\n | 'refused'\n /** The read or the write failed. The record, whatever it is, still stands. */\n | 'failed'\n\n/**\n * Lift a platform suppression that a completed double opt-in has disproved.\n *\n * THE ONE PLACE THE AUTOMATIC RULE IS STATED, mirroring\n * `releaseSiteSuppression` for the per-site list: every path that puts an\n * address back in circulation without a human deciding goes through here, so\n * there is one line to read and one line to change.\n *\n * ## Platform-wide, from one site's round trip\n *\n * The record being lifted asserts something host-independent — this mailbox\n * does not exist, learned anywhere in the product, including on transactional\n * mail that carried no site tag. A confirmation delivered to that mailbox\n * disproves it just as host-independently, so scoping the release to the\n * confirming site would leave a record standing that says the mailbox is dead\n * while we hold proof that it is not. The site and the topic are written onto\n * the record instead, which is what makes the release reviewable: an operator\n * reading the row sees which site's round trip lifted it and when.\n *\n * ## The per-site list is NOT touched\n *\n * `hosts/{hostId}/suppressions` mixes a deliverability fact with a stated\n * preference — an unsubscribe from that one site lives there too — and the\n * email plugin's `releaseSiteSuppression` is the single guarded path that\n * lifts one. Reaching around it from here would put a second, differently\n * reasoned releaser on a list whose whole protection is that there is one.\n *\n * Never throws: it runs inside a recipient's confirmation click, and a\n * Firestore failure must degrade to a suppression that stays in force, not to\n * a person told their confirmation failed.\n */\nexport async function releaseEmailForConfirmedOptIn(input: {\n email: string\n /** The site whose confirmation link was clicked, for the audit trail. */\n hostId: string\n /** The stream that was confirmed, likewise. */\n topicId: string\n firestore?: any\n}): Promise<ConfirmedOptInRelease> {\n const key = emailSuppressionKey(input.email)\n if (!key) return 'nothing-to-release'\n try {\n const db = input.firestore ?? defaultFirestore()\n const ref = db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key)\n const snapshot = await ref.get()\n if (!snapshot.exists || snapshot.get('releasedAt')) {\n return 'nothing-to-release'\n }\n if (!OPT_IN_RELEASABLE_REASONS.includes(snapshot.get('reason'))) {\n return 'refused'\n }\n await ref.set(\n {\n releasedAt: FieldValue.serverTimestamp(),\n released: true,\n // No human released this, so the field says so rather than naming\n // whoever last touched the record.\n releasedByUid: null,\n releasedVia: 'double-opt-in' satisfies EmailReleaseChannel,\n releasedHostId: input.hostId || null,\n releasedTopicId: input.topicId || null,\n },\n { merge: true },\n )\n return 'released'\n } catch (error) {\n console.error(\n '[email-suppression] opt-in release failed; suppression stands',\n error,\n )\n return 'failed'\n }\n}\n\n/**\n * The BULK-SEND gate. See the module note for which senders must call this and\n * which must not.\n *\n * FAILS CLOSED, like `isPhoneContactSuppressed`: a read that throws answers\n * `true`, meaning \"treat as suppressed\". The cost of failing closed here is\n * one delayed informational email — every caller is a cron that runs again —\n * and it is nearly free besides, because every one of them is already deep\n * inside a Firestore-backed sweep that a Firestore outage has stopped anyway.\n * The cost of failing open is another delivery attempt at a mailbox that has\n * already told us permanently that it does not exist, which is precisely the\n * behaviour a provider scores a sending domain on. Never \"fix\" a flaky read\n * here by returning false.\n */\nexport async function isEmailSuppressed(\n email: string | null | undefined,\n injectedFirestore?: any,\n): Promise<boolean> {\n const key = emailSuppressionKey(email)\n // An unusable value is one we cannot check against the list, so it is one we\n // must not send to. Same fail-closed rule.\n if (!key) return true\n try {\n const db = injectedFirestore ?? defaultFirestore()\n const snapshot = await db\n .collection(EMAIL_SUPPRESSIONS_COLLECTION)\n .doc(key)\n .get()\n if (!snapshot.exists) return false\n return !snapshot.get('releasedAt')\n } catch (error) {\n console.error('[email-suppression] lookup failed; failing closed', error)\n return true\n }\n}\n\n/**\n * The sendable subset of a recipient list, for the bulk senders.\n *\n * One `get()` per DISTINCT address rather than a query, so the check needs no\n * index and cannot fail open on a missing one. The list is deduplicated first\n * because the callers build it by fanning out over an org's owners and admins,\n * which routinely names the same person twice.\n */\nexport async function filterSuppressedEmails(\n emails: readonly string[],\n injectedFirestore?: any,\n): Promise<string[]> {\n const seen = new Set<string>()\n const candidates: string[] = []\n for (const email of emails) {\n const normalized = String(email ?? '')\n .trim()\n .toLowerCase()\n if (!normalized || seen.has(normalized)) continue\n seen.add(normalized)\n candidates.push(normalized)\n }\n const verdicts = await Promise.all(\n candidates.map((email) => isEmailSuppressed(email, injectedFirestore)),\n )\n return candidates.filter((_email, index) => !verdicts[index])\n}\n\n/*==========================================\n * THE SENDER A PERSON LEAVES IS THE CONSENT GROUP, NOT THE SITE.\n *\n * `consent-groups.ts` lets an org declare several sites ONE sender — a shop,\n * a booking page and a blog under one name, disclosed as one on every\n * capture form. To the person on the other end those are one sender, so\n * leaving any of them is leaving it: an unsubscribe filed by site A has to\n * withhold site B's mail too, or the recipient is made to unsubscribe once\n * per site of a sender they only ever knew as one.\n *\n * Every opt-out is written against the ONE site the person acted on and read\n * across the sending site's CURRENT group. Reading rather than copying on\n * write is what makes a site that joins a group inherit every refusal already\n * standing against its siblings, and it reaches every row already stored and\n * every link already sitting in an inbox — none of which a write-time fan-out\n * could.\n *\n * All three per-site facts are read this way: the site suppression list (an\n * unsubscribe, a hand-added opt-out, an erasure, and the bounces and\n * complaints the platform list already carries), the topic opt-outs, and the\n * recipient's cadence. A sibling's pending confirmation joins them only when\n * the org turned its group's confirmation switch on — see\n * {@link filterTopicSendable}. The group of one — every site of an org that\n * declared nothing — reads exactly the documents these filters always read,\n * in the same round trips.\n *=========================================*/\n\n/**\n * The sites whose opt-out lists answer for a send made BY `hostId`, the\n * sending site first.\n *\n * The sending site's consent group: every site it names, because a refusal\n * standing on any of them is a refusal of the sender. Absent, or a group of\n * one, is the site alone.\n *\n * The group is the one `consentGroupForHost` resolved — never a set a caller\n * built from `org.hosts` or a shared domain, which would be inferring a\n * controller (see `consent-groups.ts`).\n *\n * Throws on a group resolved for a DIFFERENT site. That is a wiring defect no\n * runtime value produces, and the failure it would hide is one site's send\n * decided against another site's lists — the same refusal\n * `splitByMarketingConsent` makes over a consent map read for the wrong host.\n */\nexport function optOutHostIds(\n hostId: string,\n group?: Pick<ConsentGroup, 'hostId' | 'hostIds'> | null,\n): string[] {\n if (!group) return [hostId]\n if (group.hostId !== hostId) {\n throw new Error(\n `[email-suppression] a consent group resolved for ${group.hostId} ` +\n `cannot decide a send from ${hostId}`,\n )\n }\n return consentGroupOptOutHosts(group)\n}\n\n/**\n * One keyed `getAll` per site in `hostIds`, positionally aligned with `keys`.\n *\n * Per site rather than one call over every (site, address) pair, so each\n * round trip is exactly the size the single-site read always was — a batch\n * of a campaign — and a group multiplies the number of calls, run in\n * parallel, rather than the size of one. A group of one is one call, over\n * the same references in the same order.\n *\n * Rejects when any read does; each caller keeps its own posture on that.\n */\nexport async function getAllAcrossSites(\n db: any,\n hostIds: readonly string[],\n subcollection: string,\n keys: readonly string[],\n): Promise<any[][]> {\n return Promise.all(\n hostIds.map((id) => {\n const list = db.collection('hosts').doc(id).collection(subcollection)\n return db.getAll(...keys.map((key) => list.doc(key)))\n }),\n )\n}\n\n/**\n * The sendable subset for a send made in ONE SITE's name — BOTH lists.\n *\n * A per-site suppression says \"not from this site\". A platform suppression\n * says the address hard-bounced or somebody pressed \"report spam\", learned\n * anywhere in the product — including on transactional mail that carried no\n * site tag at all and could therefore never have reached the per-site list.\n * Consulting only the site's own list mails a known-dead or complaining\n * address from the one shared sending domain every tenant's mail leaves by,\n * which makes it every tenant's deliverability problem rather than one\n * merchant's.\n *\n * Composed from {@link filterSuppressedEmails} rather than reimplementing the\n * platform half: normalization, de-duplication and the fail-closed posture\n * live there, and a second copy of them is a second set of rules for two\n * senders to disagree about.\n *\n * ## \"This site\" means its consent group\n *\n * `group` is the sending site's consent group, and an entry on ANY of its\n * sites' lists withholds — see the section above. Every entry counts, whatever\n * its reason: an unsubscribe and a hand-added opt-out are the person leaving\n * the sender, an erasure is already written on every site of the workspace,\n * and a bounce or a complaint is on the platform list besides. Omitted, the\n * site alone, which is also the whole answer for an org that declared no\n * group.\n *\n * ## Both halves fail CLOSED\n *\n * A read that throws answers \"suppressed\". The platform half already does; the\n * per-site half matches it, because a list we could not read is not a list\n * that said this address is safe to mail. The cost of the other choice is a\n * message delivered to somebody who asked us to stop.\n *\n * ## One `getAll`, keyed, rather than a scan of the collection\n *\n * The per-site half looks up exactly the addresses being mailed, by document\n * id, in one round trip per site. Reading the whole collection instead —\n * which is what the campaign sender did — is bounded by however large the\n * collection has grown, so a site with more suppressions than the read window\n * fails OPEN on the remainder: the people most certain not to want the mail\n * are the ones a truncated read drops.\n */\nexport async function filterSendableForHost(\n hostId: string,\n emails: readonly string[],\n injectedFirestore?: any,\n group?: Pick<ConsentGroup, 'hostId' | 'hostIds'> | null,\n): Promise<string[]> {\n const hostIds = optOutHostIds(hostId, group)\n const platformSendable = await filterSuppressedEmails(\n emails,\n injectedFirestore,\n )\n // `getAll` rejects an empty reference list, and there is nothing to ask.\n if (!platformSendable.length) return []\n const db = injectedFirestore ?? defaultFirestore()\n // Every survivor of the platform half is keyable — `isEmailSuppressed`\n // answers `true` for an address it cannot key — so this narrows the type\n // rather than dropping anybody.\n const keyed: Array<{ email: string; key: string }> = []\n for (const email of platformSendable) {\n const key = emailSuppressionKey(email)\n if (key) keyed.push({ email, key })\n }\n if (!keyed.length) return []\n try {\n const bySite = await getAllAcrossSites(\n db,\n hostIds,\n HOST_SUPPRESSIONS_SUBCOLLECTION,\n keyed.map((entry) => entry.key),\n )\n return keyed\n .filter(\n (_entry, index) =>\n !bySite.some((snapshots) => snapshots[index]?.exists),\n )\n .map((entry) => entry.email)\n } catch (error) {\n console.error(\n '[email-suppression] per-site lookup failed; failing closed',\n error,\n )\n return []\n }\n}\n\n/**\n * The subset of `emails` that may be mailed about `topicId` on this site.\n *\n * The third filter a campaign passes, after the platform list and the site's\n * own: the two suppression lists answer \"may we mail this person at all\", and\n * this answers \"may we mail them about THIS\". A recipient who unticked\n * \"Promotions and offers\" on the preference page is not suppressed — they\n * still get the newsletter — so the fact cannot live on either suppression\n * list without meaning something it does not mean.\n *\n * ## Two ways to be excluded, and both are held here\n *\n * Somebody who LEFT the stream, and somebody who has been asked to confirm\n * joining it and has not. The second is what makes a double opt-in worth\n * recording: an unconfirmed subscriber has to be a real quarantine, not a\n * field the send path never looks at. Both come back from\n * `readTopicSubscriptionState`, which is the only place the three states are\n * decided.\n *\n * Keyed by {@link emailSuppressionKey} and read with one `getAll`, which is\n * both halves of the point: the same derivation as the two lists it runs\n * beside, so one person is one document id everywhere; and one round trip\n * bounded by the size of the send, so adding topics does not make a campaign\n * cost more to resolve.\n *\n * ## This one fails OPEN, and that is the opposite of its neighbors\n *\n * Every other filter in this module answers \"suppressed\" when a read throws,\n * because the cost of guessing wrong is mailing somebody who told us to stop.\n * Here the cost of guessing wrong in that direction is refusing to send a\n * newsletter somebody asked for, on a read that failed for an unrelated\n * reason — and the campaign has already passed both suppression lists, so\n * nobody who asked us to stop entirely can reach this line. A topic\n * preference is a narrower fact than a suppression and it gets the treatment\n * that matches. A caller that wants the strict posture already has it one\n * layer up.\n *\n * An empty `topicId` is a campaign from before topics existed, or one whose\n * topic was never resolved. It filters nobody: there is no stream to have\n * left.\n *\n * ## Leaving a stream is leaving it for the whole consent group\n *\n * The topic catalog is the org's, so \"Newsletter\" on one site of a declared\n * group is the same stream on its siblings, and a person who left it on one\n * has left it from the sender. `group` extends the read to every site in it,\n * exactly as {@link filterSendableForHost} does for the suppression list.\n *\n * A sibling's REFUSAL always holds. A sibling's pending confirmation holds\n * only when the group `awaitsConfirmation` — the org's switch, resolved into\n * the group, so asking it reads nothing the refusal read did not already\n * read. Off, the question stays the concern of the site whose form asked it.\n */\nexport async function filterTopicSendable(\n hostId: string,\n topicId: string | null | undefined,\n emails: readonly string[],\n injectedFirestore?: any,\n group?: Pick<ConsentGroup, 'hostId' | 'hostIds' | 'awaitsConfirmation'> | null,\n): Promise<string[]> {\n const hostIds = optOutHostIds(hostId, group)\n const topic = String(topicId ?? '').trim()\n if (!topic || !emails.length) return [...emails]\n // An unkeyable address cannot carry an opt-out record, so it cannot have\n // left this topic. It is dropped from the LOOKUP and kept in the answer —\n // the suppression filters above have already refused it on their own\n // stricter rule, so this one has no business refusing it a second time.\n const lookups: Array<{ email: string; key: string }> = []\n for (const email of emails) {\n const key = emailSuppressionKey(email)\n if (key) lookups.push({ email, key })\n }\n if (!lookups.length) return [...emails]\n try {\n const db = injectedFirestore ?? defaultFirestore()\n const bySite = await getAllAcrossSites(\n db,\n hostIds,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n lookups.map((entry) => entry.key),\n )\n /*\n * The shared state reader, never a field test written out here.\n *\n * An entry means one of three things and only that function knows all\n * three. The shorthand this replaced — \"an entry with no\n * `resubscribedAt` is a live opt-out\" — reads a CONFIRMED double\n * opt-in, which carries `pendingAt` and `confirmedAt` and no\n * `resubscribedAt`, as somebody who left.\n */\n const stateIn = (snapshot: any) =>\n snapshot?.exists\n ? readTopicSubscriptionState((snapshot.get('topics') ?? {})[topic])\n : 'subscribed'\n // The sending site first, as `optOutHostIds` ordered the reads — which\n // is how the fold tells its own pending question from a sibling's.\n const awaits = { awaitsConfirmation: group?.awaitsConfirmation === true }\n const gone = new Set<string>()\n lookups.forEach((entry, index) => {\n const states = bySite.map((snapshots) => stateIn(snapshots[index]))\n if (consentGroupTopicState(awaits, states) !== 'subscribed') {\n gone.add(entry.email)\n }\n })\n return emails.filter((email) => !gone.has(email))\n } catch (error) {\n console.error(\n '[email-suppression] topic opt-out lookup failed; failing open',\n error,\n )\n return [...emails]\n }\n}\n\n/*\n * THE FOURTH FILTER IS NOT IN THIS FILE, and where it is is forced.\n *\n * `filterCadenceSendable` — the subset that has not asked this site for mail\n * less often than right now — lives in `email-marketing-gate.ts`, because it\n * reads the per-recipient counter document that module owns and names. That\n * module already imports this one for the two suppression lists, so putting\n * the cadence filter here would close a cycle. A campaign's subtraction chain\n * therefore reads: this file's two lists, this file's topic opt-outs, then\n * that file's cadence.\n */\n\n/**\n * The staff queue, newest first, ordered by `suppressedAt` so a re-recorded or\n * released entry surfaces again — the operator's question is \"what changed\",\n * not \"what was first written\". Mirrors `listContactSuppressions`.\n */\nexport async function listEmailSuppressions(options?: {\n limit?: number\n /**\n * Where the NEXT page starts: the `suppressedAt` of the last row already\n * shown, as `seconds.nanoseconds`.\n *\n * The full timestamp rather than milliseconds, because `startAfter` skips\n * exactly the value it is given: a millisecond-truncated cursor sits BEFORE\n * the record it names, so that record would arrive again at the top of the\n * following page. Repeating a row is a smaller fault than skipping one and\n * neither is necessary.\n */\n startAfter?: string | null\n /**\n * Predicates the caller adds beneath the ordering — equalities, one\n * `array-contains`, and ranges over `suppressedAt` itself, which are the\n * only shapes that keep this cursor valid. It must not add an `orderBy`.\n */\n narrow?: (query: any) => any\n firestore?: any\n}): Promise<Array<EmailSuppressionRecord & { $id: string }>> {\n const db = options?.firestore ?? defaultFirestore()\n const collection = db.collection(EMAIL_SUPPRESSIONS_COLLECTION)\n let query = (options?.narrow ? options.narrow(collection) : collection).orderBy(\n 'suppressedAt',\n 'desc',\n )\n const cursor = suppressionCursorTimestamp(options?.startAfter)\n if (cursor) query = query.startAfter(cursor)\n const snapshot = await query\n .limit(Math.min(Math.max(options?.limit ?? 100, 1), 500))\n .get()\n return snapshot.docs.map((doc: any) => ({\n $id: doc.id,\n ...(doc.data() as EmailSuppressionRecord),\n }))\n}\n\n/**\n * The cursor a page hands back, from the last row on it.\n *\n * Null when the row carries no `suppressedAt` — every entry written since\n * AGL-1918 does, and `orderBy` has already excluded any that does not, so\n * this is the type narrowing rather than a case that occurs.\n */\nexport function suppressionCursorFrom(\n record: Record<string, any> | null | undefined,\n): string | null {\n const at = record?.['suppressedAt'] as\n | { seconds?: number; _seconds?: number; nanoseconds?: number; _nanoseconds?: number }\n | undefined\n const seconds = at?.seconds ?? at?._seconds\n if (typeof seconds !== 'number') return null\n const nanoseconds = at?.nanoseconds ?? at?._nanoseconds ?? 0\n return `${seconds}.${nanoseconds}`\n}\n\n/** The inverse, for the query. Invalid input yields no cursor, never a guess. */\nexport function suppressionCursorTimestamp(\n cursor: string | null | undefined,\n): Timestamp | null {\n const [rawSeconds, rawNanos] = String(cursor ?? '').split('.')\n const seconds = Number(rawSeconds)\n const nanoseconds = Number(rawNanos ?? 0)\n if (!Number.isFinite(seconds) || !seconds) return null\n return new Timestamp(seconds, Number.isFinite(nanoseconds) ? nanoseconds : 0)\n}\n\n/*==========================================\n * THE ERASURE ROW ON THE PER-SITE LIST (AGL-2623).\n *\n * A person erased from a workspace must not be quietly rebuilt by the next\n * form they fill in or the next order they place, and must not be mailed by\n * a campaign either. Both gates already read `hosts/{hostId}/suppressions`\n * — every campaign filter refuses an address with a row there — so the\n * erasure writes one row per site of the workspace rather than inventing a\n * third list, and the capture door reads the same row.\n *\n * The row carries NO address. Every other writer of this list stores the\n * email in the clear beside the hash, because a hub admin releasing an\n * unsubscribe needs to see who it was; an erasure row is the one whose\n * whole purpose is that the address is no longer held, so the id — the\n * hash — is the entire record, and a row that already held the address in\n * the clear has it removed. The hub's list renders such a row as an entry\n * with no address, which it already knows how to do.\n *\n * Per SITE, not platform-wide, on purpose: the erasure was asked of one\n * workspace, and a second workspace that knows the same person has a\n * relationship this request has no claim on. The platform list is for\n * bounces and complaints, which are facts about the address everywhere.\n *=========================================*/\n\n/** The `reason` an erasure row carries. Read by the capture door, below. */\nexport const HOST_ERASURE_SUPPRESSION_REASON = 'erasure'\n\n/**\n * Suppress an address on one site because the person was erased. Idempotent:\n * a second erasure of the same person merges onto the same row.\n */\nexport async function suppressEmailForHostErasure(input: {\n hostId: string\n email: string\n firestore?: any\n}): Promise<{ key: string; created: boolean } | null> {\n const key = emailSuppressionKey(input.email)\n if (!key) return null\n const db = input.firestore ?? defaultFirestore()\n const ref = db\n .collection('hosts')\n .doc(input.hostId)\n .collection(HOST_SUPPRESSIONS_SUBCOLLECTION)\n .doc(key)\n const snapshot = await ref.get()\n await ref.set(\n {\n email: null,\n // The address's search tokens are the address in pieces, so an erasure\n // clears them with it (AGL-3321).\n emailTokens: [],\n reason: HOST_ERASURE_SUPPRESSION_REASON,\n suppressedAt: FieldValue.serverTimestamp(),\n ...(snapshot.exists ? {} : { createdAt: FieldValue.serverTimestamp() }),\n },\n { merge: true },\n )\n return { key, created: !snapshot.exists }\n}\n\n/**\n * Whether a site has erased this address, so a capture must not create a\n * contact for it. Only an ERASURE row refuses: an ordinary unsubscribe is a\n * mailing preference, and a person who unsubscribed and then bought\n * something is still a customer whose order the CRM should know about.\n *\n * Fails OPEN. A read that throws answers `false` and logs: the alternative\n * refuses every capture on the site for as long as the list is unreadable,\n * which turns a transient read failure into a silent drop of the site's\n * leads and orders. The window this leaves — a recreate during an outage\n * of the suppression read — is logged, and the next erasure run finds the\n * recreated record by the same address.\n */\nexport async function hostRefusesCaptureForErasure(\n hostId: string,\n email: string | null | undefined,\n injectedFirestore?: any,\n): Promise<boolean> {\n const key = emailSuppressionKey(email)\n if (!key) return false\n try {\n const db = injectedFirestore ?? defaultFirestore()\n const snapshot = await db\n .collection('hosts')\n .doc(hostId)\n .collection(HOST_SUPPRESSIONS_SUBCOLLECTION)\n .doc(key)\n .get()\n return (\n Boolean(snapshot?.exists) &&\n snapshot.get('reason') === HOST_ERASURE_SUPPRESSION_REASON\n )\n } catch (error) {\n console.error(\n '[email-suppression] erasure lookup failed; the capture proceeds',\n error,\n )\n return false\n }\n}\n"],"names":["FieldValue","Timestamp","consentGroupOptOutHosts","consentGroupTopicState","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","emailSearchTokens","personKey","stampRecordEmailState","firebaseAdmin","defaultFirestore","app","firestore","EMAIL_SUPPRESSIONS_COLLECTION","HOST_SUPPRESSIONS_SUBCOLLECTION","PLATFORM_SUPPRESSION_REASONS","UNSUBSCRIBE_SUPPRESSION_REASON","emailSuppressionKey","email","suppressEmail","input","key","Error","includes","reason","db","ref","collection","doc","snapshot","get","String","trim","toLowerCase","set","emailTokens","context","hostId","releasedAt","released","suppressedAt","serverTimestamp","exists","createdAt","merge","stampRecord","state","status","atMs","Date","now","source","detail","created","releaseEmail","releasedByUid","releasedNote","note","releasedVia","OPT_IN_RELEASABLE_REASONS","releaseEmailForConfirmedOptIn","releasedHostId","releasedTopicId","topicId","error","console","isEmailSuppressed","injectedFirestore","filterSuppressedEmails","emails","seen","Set","candidates","normalized","has","add","push","verdicts","Promise","all","map","filter","_email","index","optOutHostIds","group","getAllAcrossSites","hostIds","subcollection","keys","id","list","getAll","filterSendableForHost","platformSendable","length","keyed","bySite","entry","_entry","some","snapshots","filterTopicSendable","topic","lookups","stateIn","awaits","awaitsConfirmation","gone","forEach","states","listEmailSuppressions","options","query","narrow","orderBy","cursor","suppressionCursorTimestamp","startAfter","limit","Math","min","max","docs","$id","data","suppressionCursorFrom","record","at","seconds","_seconds","nanoseconds","_nanoseconds","rawSeconds","rawNanos","split","Number","isFinite","HOST_ERASURE_SUPPRESSION_REASON","suppressEmailForHostErasure","hostRefusesCaptureForErasure","Boolean"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsEC,GAED,SAASA,UAAU,EAAEC,SAAS,QAAQ,2BAA0B;AAChE,gEAAgE;AAChE,2EAA2E;AAC3E,0EAA0E;AAC1E,iDAAiD;AACjD,SACEC,uBAAuB,EACvBC,sBAAsB,QAEjB,wCAAuC;AAC9C,SACEC,0BAA0B,EAC1BC,4BAA4B,QACvB,sCAAqC;AAC5C,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SAASC,qBAAqB,QAAQ,wDAAuD;AAC7F,OAAOC,mBAAmB,sBAAkB;AAE5C,MAAMC,mBAAmB,IAAMD,cAAcE,GAAG,GAAGC,SAAS;AAE5D,OAAO,MAAMC,gCAAgC,oBAAmB;AAEhE;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,kCAAkC,eAAc;AA4B7D;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,MAAMC,+BAAkE;IAC7E;IACA;IACA;IACA;CACD,CAAA;AAED;;;;;;;CAOC,GACD,OAAO,MAAMC,iCAAiC,cAAa;AAkC3D;;;;;;;;;;CAUC,GACD,OAAO,SAASC,oBACdC,KAAgC;IAEhC;;;;;GAKC,GACD,OAAOX,UAAUW;AACnB;AAEA;;;;;;;;;;CAUC,GACD,SAASZ,iBAAiB,GAAE;AAkB5B;;;;;;;;;;;;CAYC,GACD,OAAO,eAAea,cAAcC,KAAyB;QAchDA,kBASEA,gBACDA;IApBZ,MAAMC,MAAMJ,oBAAoBG,MAAMF,KAAK;IAC3C,IAAI,CAACG,KAAK;QACR,MAAM,IAAIC,MAAM;IAClB;IACA,IAAI,CAACP,6BAA6B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