@aglyn/tenant-data-admin 1.0.0-beta.160 → 1.0.0-beta.163
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 +6 -6
- package/src/lib/server/campaign-conversion-attribution.d.ts +48 -3
- package/src/lib/server/campaign-conversion-attribution.js +95 -2
- package/src/lib/server/campaign-conversion-attribution.js.map +1 -1
- package/src/lib/server/crm-email-activity.d.ts +6 -0
- package/src/lib/server/crm-email-activity.js +8 -3
- package/src/lib/server/crm-email-activity.js.map +1 -1
- package/src/lib/server/email-delivery-log.d.ts +14 -1
- package/src/lib/server/email-delivery-log.js +31 -8
- package/src/lib/server/email-delivery-log.js.map +1 -1
- package/src/lib/server/email-suppression.d.ts +5 -0
- package/src/lib/server/email-suppression.js +20 -0
- package/src/lib/server/email-suppression.js.map +1 -1
- package/src/lib/server/org-member-notice.d.ts +52 -0
- package/src/lib/server/org-member-notice.js +90 -0
- package/src/lib/server/org-member-notice.js.map +1 -0
|
@@ -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 readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/email-topics'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\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 /** 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\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 /** 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 await ref.set(\n {\n email: String(input.email).trim().toLowerCase(),\n reason: input.reason,\n context: input.context ?? null,\n hostId: input.hostId ?? null,\n releasedAt: null,\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 * 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 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 // 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 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 * ## 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. Reading the whole collection instead — which is what\n * the campaign sender did — is bounded by however large the collection has\n * grown, so a site with more suppressions than the read window fails OPEN on\n * the remainder: the people most certain not to want the mail are the ones a\n * truncated read drops.\n */\nexport async function filterSendableForHost(\n hostId: string,\n emails: readonly string[],\n injectedFirestore?: any,\n): Promise<string[]> {\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 const hostList = db\n .collection('hosts')\n .doc(hostId)\n .collection(HOST_SUPPRESSIONS_SUBCOLLECTION)\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 snapshots = await db.getAll(\n ...keyed.map((entry) => hostList.doc(entry.key)),\n )\n return keyed\n .filter((_entry, index) => !snapshots[index]?.exists)\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 */\nexport async function filterTopicSendable(\n hostId: string,\n topicId: string | null | undefined,\n emails: readonly string[],\n injectedFirestore?: any,\n): Promise<string[]> {\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 optOuts = db\n .collection('hosts')\n .doc(hostId)\n .collection(TOPIC_OPT_OUTS_SUBCOLLECTION)\n const snapshots = await db.getAll(\n ...lookups.map((entry) => optOuts.doc(entry.key)),\n )\n const gone = new Set<string>()\n lookups.forEach((entry, index) => {\n const snapshot = snapshots[index]\n if (!snapshot?.exists) return\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 record = (snapshot.get('topics') ?? {})[topic]\n if (readTopicSubscriptionState(record) !== '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 firestore?: any\n}): Promise<Array<EmailSuppressionRecord & { $id: string }>> {\n const db = options?.firestore ?? defaultFirestore()\n let query = db\n .collection(EMAIL_SUPPRESSIONS_COLLECTION)\n .orderBy('suppressedAt', 'desc')\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 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","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","personKey","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","set","String","trim","toLowerCase","context","hostId","releasedAt","suppressedAt","serverTimestamp","exists","createdAt","merge","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","filterSendableForHost","platformSendable","length","hostList","keyed","snapshots","getAll","entry","_entry","filterTopicSendable","topic","lookups","optOuts","gone","forEach","record","listEmailSuppressions","options","query","orderBy","cursor","suppressionCursorTimestamp","startAfter","limit","Math","min","max","docs","$id","id","data","suppressionCursorFrom","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,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AACb,iCACXc,GAAG,CAACP,KACJS,GAAG;QACN,OACEyF,QAAQ1F,4BAAAA,SAAUW,MAAM,KACxBX,SAASC,GAAG,CAAC,cAAcsF;IAE/B,EAAE,OAAO9D,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 readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/email-topics'\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 /** 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\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 await ref.set(\n {\n email: String(input.email).trim().toLowerCase(),\n reason: input.reason,\n context: input.context ?? null,\n hostId: input.hostId ?? null,\n releasedAt: null,\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 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 // 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 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 * ## 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. Reading the whole collection instead — which is what\n * the campaign sender did — is bounded by however large the collection has\n * grown, so a site with more suppressions than the read window fails OPEN on\n * the remainder: the people most certain not to want the mail are the ones a\n * truncated read drops.\n */\nexport async function filterSendableForHost(\n hostId: string,\n emails: readonly string[],\n injectedFirestore?: any,\n): Promise<string[]> {\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 const hostList = db\n .collection('hosts')\n .doc(hostId)\n .collection(HOST_SUPPRESSIONS_SUBCOLLECTION)\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 snapshots = await db.getAll(\n ...keyed.map((entry) => hostList.doc(entry.key)),\n )\n return keyed\n .filter((_entry, index) => !snapshots[index]?.exists)\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 */\nexport async function filterTopicSendable(\n hostId: string,\n topicId: string | null | undefined,\n emails: readonly string[],\n injectedFirestore?: any,\n): Promise<string[]> {\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 optOuts = db\n .collection('hosts')\n .doc(hostId)\n .collection(TOPIC_OPT_OUTS_SUBCOLLECTION)\n const snapshots = await db.getAll(\n ...lookups.map((entry) => optOuts.doc(entry.key)),\n )\n const gone = new Set<string>()\n lookups.forEach((entry, index) => {\n const snapshot = snapshots[index]\n if (!snapshot?.exists) return\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 record = (snapshot.get('topics') ?? {})[topic]\n if (readTopicSubscriptionState(record) !== '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 firestore?: any\n}): Promise<Array<EmailSuppressionRecord & { $id: string }>> {\n const db = options?.firestore ?? defaultFirestore()\n let query = db\n .collection(EMAIL_SUPPRESSIONS_COLLECTION)\n .orderBy('suppressedAt', 'desc')\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 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","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","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","set","String","trim","toLowerCase","context","hostId","releasedAt","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","filterSendableForHost","platformSendable","length","hostList","keyed","snapshots","getAll","entry","_entry","filterTopicSendable","topic","lookups","optOuts","gone","forEach","record","listEmailSuppressions","options","query","orderBy","cursor","suppressionCursorTimestamp","startAfter","limit","Math","min","max","docs","$id","id","data","suppressionCursorFrom","at","seconds","_seconds","nanoseconds","_nanoseconds","rawSeconds","rawNanos","split","Number","isFinite","HOST_ERASURE_SUPPRESSION_REASON","suppressEmailForHostErasure","hostRefusesCaptureForErasure","Boolean"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsE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GAAG;IAC9B,MAAMJ,IAAIK,GAAG,CACX;QACEb,OAAO;QACPM,QAAQoG;QACRtF,cAAcnC,WAAWoC,eAAe;OACpCV,SAASW,MAAM,GAAG,CAAC,IAAI;QAAEC,WAAWtC,WAAWoC,eAAe;IAAG,IAEvE;QAAEG,OAAO;IAAK;IAEhB,OAAO;QAAErB;QAAK8B,SAAS,CAACtB,SAASW,MAAM;IAAC;AAC1C;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,eAAesF,6BACpB1F,MAAc,EACdlB,KAAgC,EAChC+C,iBAAuB;IAEvB,MAAM5C,MAAMJ,oBAAoBC;IAChC,IAAI,CAACG,KAAK,OAAO;IACjB,IAAI;QACF,MAAMI,KAAKwC,4BAAAA,oBAAqBvD;QAChC,MAAMmB,WAAW,MAAMJ,GACpBE,UAAU,CAAC,SACXC,GAAG,CAACQ,QACJT,UAAU,CAACb,iCACXc,GAAG,CAACP,KACJS,GAAG;QACN,OACEiG,QAAQlG,4BAAAA,SAAUW,MAAM,KACxBX,SAASC,GAAG,CAAC,cAAc8F;IAE/B,EAAE,OAAO9D,OAAO;QACdC,QAAQD,KAAK,CACX,mEACAA;QAEF,OAAO;IACT;AACF"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* A NOTICE TO NAMED MEMBERS OF AN ORGANIZATION, BY EMAIL (AGL-3244).
|
|
19
|
+
*
|
|
20
|
+
* The console notification (`notifications.ts`) is the record, and its email
|
|
21
|
+
* channel is a preference that defaults off. Some things cannot wait on a
|
|
22
|
+
* preference: a sequence mailbox that paused itself holds every enrollment
|
|
23
|
+
* on it until its owner acts, and the owner is not watching the page. This
|
|
24
|
+
* sends the email regardless, to the members named and — when asked — to
|
|
25
|
+
* the organization's owners and admins beside them, one send per address
|
|
26
|
+
* so nobody is shown anyone else's.
|
|
27
|
+
*
|
|
28
|
+
* Addresses come from the roster (`orgs/{orgId}/members/{uid}.email`), and
|
|
29
|
+
* for a member whose row carries none, from the directory. Suppressed
|
|
30
|
+
* addresses are skipped, the send is metered to the organization, and
|
|
31
|
+
* nothing here throws: the notice is a courtesy beside a state the caller
|
|
32
|
+
* already wrote.
|
|
33
|
+
*/
|
|
34
|
+
export interface OrgMemberNoticeInput {
|
|
35
|
+
orgId: string;
|
|
36
|
+
/** The members to write to, by uid. */
|
|
37
|
+
uids: readonly string[];
|
|
38
|
+
/** Also the organization's owners and admins. */
|
|
39
|
+
includeAdmins?: boolean;
|
|
40
|
+
subject: string;
|
|
41
|
+
text: string;
|
|
42
|
+
/** Resend tag / log label. */
|
|
43
|
+
context: string;
|
|
44
|
+
}
|
|
45
|
+
export interface OrgMemberNoticeResult {
|
|
46
|
+
/** Addresses the notice went to. */
|
|
47
|
+
sent: number;
|
|
48
|
+
/** Why nothing could be sent at all, when nothing could. */
|
|
49
|
+
reason?: 'unconfigured' | 'no-recipients' | 'failed';
|
|
50
|
+
}
|
|
51
|
+
/** Sends one notice to each member — see the module note. */
|
|
52
|
+
export declare function sendOrgMemberNotice(input: OrgMemberNoticeInput): Promise<OrgMemberNoticeResult>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
|
|
17
|
+
import { findUserByUidAcrossPools } from "./auth-pools.js";
|
|
18
|
+
import { filterSuppressedEmails } from "./email-suppression.js";
|
|
19
|
+
import { listOrgMembers } from "./organizations.js";
|
|
20
|
+
/** At most this many directory lookups, and this many sends, per notice. */ const MAX_LOOKUPS = 10;
|
|
21
|
+
const MAX_SENDS = 25;
|
|
22
|
+
/** Sends one notice to each member — see the module note. */ export async function sendOrgMemberNotice(input) {
|
|
23
|
+
if (!isEmailConfigured()) return {
|
|
24
|
+
sent: 0,
|
|
25
|
+
reason: 'unconfigured'
|
|
26
|
+
};
|
|
27
|
+
try {
|
|
28
|
+
const members = await listOrgMembers(input.orgId);
|
|
29
|
+
const rosterEmail = new Map();
|
|
30
|
+
for (const member of members){
|
|
31
|
+
var _member_email;
|
|
32
|
+
const address = String((_member_email = member.email) != null ? _member_email : '').trim().toLowerCase();
|
|
33
|
+
if (address.includes('@')) rosterEmail.set(member.$id, address);
|
|
34
|
+
}
|
|
35
|
+
const uids = new Set(input.uids.filter(Boolean));
|
|
36
|
+
if (input.includeAdmins) {
|
|
37
|
+
for (const member of members){
|
|
38
|
+
if (member.role === 'owner' || member.role === 'admin') uids.add(member.$id);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const addresses = new Set();
|
|
42
|
+
let lookups = 0;
|
|
43
|
+
for (const uid of uids){
|
|
44
|
+
var _rosterEmail_get;
|
|
45
|
+
let address = (_rosterEmail_get = rosterEmail.get(uid)) != null ? _rosterEmail_get : '';
|
|
46
|
+
if (!address && lookups < MAX_LOOKUPS) {
|
|
47
|
+
var _ref;
|
|
48
|
+
var _pooled_record;
|
|
49
|
+
lookups += 1;
|
|
50
|
+
const pooled = await findUserByUidAcrossPools(uid).catch(()=>null);
|
|
51
|
+
address = String((_ref = pooled == null ? void 0 : (_pooled_record = pooled.record) == null ? void 0 : _pooled_record.email) != null ? _ref : '').trim().toLowerCase();
|
|
52
|
+
}
|
|
53
|
+
if (address.includes('@')) addresses.add(address);
|
|
54
|
+
}
|
|
55
|
+
const recipients = await filterSuppressedEmails([
|
|
56
|
+
...addresses
|
|
57
|
+
]);
|
|
58
|
+
if (!recipients.length) return {
|
|
59
|
+
sent: 0,
|
|
60
|
+
reason: 'no-recipients'
|
|
61
|
+
};
|
|
62
|
+
let sent = 0;
|
|
63
|
+
for (const to of recipients.slice(0, MAX_SENDS)){
|
|
64
|
+
const result = await sendEmail({
|
|
65
|
+
to,
|
|
66
|
+
subject: input.subject,
|
|
67
|
+
text: input.text,
|
|
68
|
+
context: input.context
|
|
69
|
+
});
|
|
70
|
+
if (!result.sent) continue;
|
|
71
|
+
sent += 1;
|
|
72
|
+
const { meterOrgEmail } = await import("./email-metering.js");
|
|
73
|
+
await meterOrgEmail(input.orgId).catch(()=>undefined);
|
|
74
|
+
}
|
|
75
|
+
return sent ? {
|
|
76
|
+
sent
|
|
77
|
+
} : {
|
|
78
|
+
sent: 0,
|
|
79
|
+
reason: 'failed'
|
|
80
|
+
};
|
|
81
|
+
} catch (error) {
|
|
82
|
+
console.error('[org-member-notice] send failed', error);
|
|
83
|
+
return {
|
|
84
|
+
sent: 0,
|
|
85
|
+
reason: 'failed'
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=org-member-notice.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/org-member-notice.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport { filterSuppressedEmails } from './email-suppression'\nimport { listOrgMembers } from './organizations'\n\n/**\n * A NOTICE TO NAMED MEMBERS OF AN ORGANIZATION, BY EMAIL (AGL-3244).\n *\n * The console notification (`notifications.ts`) is the record, and its email\n * channel is a preference that defaults off. Some things cannot wait on a\n * preference: a sequence mailbox that paused itself holds every enrollment\n * on it until its owner acts, and the owner is not watching the page. This\n * sends the email regardless, to the members named and — when asked — to\n * the organization's owners and admins beside them, one send per address\n * so nobody is shown anyone else's.\n *\n * Addresses come from the roster (`orgs/{orgId}/members/{uid}.email`), and\n * for a member whose row carries none, from the directory. Suppressed\n * addresses are skipped, the send is metered to the organization, and\n * nothing here throws: the notice is a courtesy beside a state the caller\n * already wrote.\n */\n\nexport interface OrgMemberNoticeInput {\n orgId: string\n /** The members to write to, by uid. */\n uids: readonly string[]\n /** Also the organization's owners and admins. */\n includeAdmins?: boolean\n subject: string\n text: string\n /** Resend tag / log label. */\n context: string\n}\n\nexport interface OrgMemberNoticeResult {\n /** Addresses the notice went to. */\n sent: number\n /** Why nothing could be sent at all, when nothing could. */\n reason?: 'unconfigured' | 'no-recipients' | 'failed'\n}\n\n/** At most this many directory lookups, and this many sends, per notice. */\nconst MAX_LOOKUPS = 10\nconst MAX_SENDS = 25\n\n/** Sends one notice to each member — see the module note. */\nexport async function sendOrgMemberNotice(input: OrgMemberNoticeInput): Promise<OrgMemberNoticeResult> {\n if (!isEmailConfigured()) return { sent: 0, reason: 'unconfigured' }\n try {\n const members = await listOrgMembers(input.orgId)\n const rosterEmail = new Map<string, string>()\n for (const member of members) {\n const address = String(member.email ?? '')\n .trim()\n .toLowerCase()\n if (address.includes('@')) rosterEmail.set(member.$id, address)\n }\n const uids = new Set(input.uids.filter(Boolean))\n if (input.includeAdmins) {\n for (const member of members) {\n if (member.role === 'owner' || member.role === 'admin') uids.add(member.$id)\n }\n }\n const addresses = new Set<string>()\n let lookups = 0\n for (const uid of uids) {\n let address = rosterEmail.get(uid) ?? ''\n if (!address && lookups < MAX_LOOKUPS) {\n lookups += 1\n const pooled = await findUserByUidAcrossPools(uid).catch(() => null)\n address = String(pooled?.record?.email ?? '')\n .trim()\n .toLowerCase()\n }\n if (address.includes('@')) addresses.add(address)\n }\n const recipients = await filterSuppressedEmails([...addresses])\n if (!recipients.length) return { sent: 0, reason: 'no-recipients' }\n let sent = 0\n for (const to of recipients.slice(0, MAX_SENDS)) {\n const result = await sendEmail({ to, subject: input.subject, text: input.text, context: input.context })\n if (!result.sent) continue\n sent += 1\n const { meterOrgEmail } = await import('./email-metering')\n await meterOrgEmail(input.orgId).catch(() => undefined)\n }\n return sent ? { sent } : { sent: 0, reason: 'failed' }\n } catch (error) {\n console.error('[org-member-notice] send failed', error)\n return { sent: 0, reason: 'failed' }\n }\n}\n"],"names":["isEmailConfigured","sendEmail","findUserByUidAcrossPools","filterSuppressedEmails","listOrgMembers","MAX_LOOKUPS","MAX_SENDS","sendOrgMemberNotice","input","sent","reason","members","orgId","rosterEmail","Map","member","address","String","email","trim","toLowerCase","includes","set","$id","uids","Set","filter","Boolean","includeAdmins","role","add","addresses","lookups","uid","get","pooled","catch","record","recipients","length","to","slice","result","subject","text","context","meterOrgEmail","undefined","error","console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