@aglyn/tenant-data-admin 1.0.0-beta.199 → 1.0.0-beta.200

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.
Files changed (59) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/admin-audit-write.d.ts +28 -0
  3. package/src/lib/server/admin-audit-write.js +46 -0
  4. package/src/lib/server/admin-audit-write.js.map +1 -0
  5. package/src/lib/server/admin-audit.d.ts +4 -9
  6. package/src/lib/server/admin-audit.js +12 -31
  7. package/src/lib/server/admin-audit.js.map +1 -1
  8. package/src/lib/server/consent-group-carry.js +2 -0
  9. package/src/lib/server/consent-group-carry.js.map +1 -1
  10. package/src/lib/server/contact-company-link.js +3 -0
  11. package/src/lib/server/contact-company-link.js.map +1 -1
  12. package/src/lib/server/contact-lifecycle-floor.js +3 -0
  13. package/src/lib/server/contact-lifecycle-floor.js.map +1 -1
  14. package/src/lib/server/contact-merge.js +4 -0
  15. package/src/lib/server/contact-merge.js.map +1 -1
  16. package/src/lib/server/crm-booking-activity.js +3 -2
  17. package/src/lib/server/crm-booking-activity.js.map +1 -1
  18. package/src/lib/server/crm-records.d.ts +15 -0
  19. package/src/lib/server/crm-records.js +52 -0
  20. package/src/lib/server/crm-records.js.map +1 -1
  21. package/src/lib/server/csp-aggregate.d.ts +16 -0
  22. package/src/lib/server/csp-aggregate.js +36 -0
  23. package/src/lib/server/csp-aggregate.js.map +1 -1
  24. package/src/lib/server/duplicate-resource.js +12 -5
  25. package/src/lib/server/duplicate-resource.js.map +1 -1
  26. package/src/lib/server/email-delivery-log.d.ts +33 -0
  27. package/src/lib/server/email-delivery-log.js +43 -2
  28. package/src/lib/server/email-delivery-log.js.map +1 -1
  29. package/src/lib/server/email-suppression.d.ts +11 -14
  30. package/src/lib/server/email-suppression.js +14 -31
  31. package/src/lib/server/email-suppression.js.map +1 -1
  32. package/src/lib/server/erase-person.js +22 -3
  33. package/src/lib/server/erase-person.js.map +1 -1
  34. package/src/lib/server/erase.js +4 -3
  35. package/src/lib/server/erase.js.map +1 -1
  36. package/src/lib/server/host-memberships.d.ts +34 -0
  37. package/src/lib/server/host-memberships.js +89 -1
  38. package/src/lib/server/host-memberships.js.map +1 -1
  39. package/src/lib/server/host-visitor-records.js +23 -3
  40. package/src/lib/server/host-visitor-records.js.map +1 -1
  41. package/src/lib/server/list-members.d.ts +11 -0
  42. package/src/lib/server/list-members.js +28 -1
  43. package/src/lib/server/list-members.js.map +1 -1
  44. package/src/lib/server/list-query.d.ts +36 -0
  45. package/src/lib/server/list-query.js +49 -0
  46. package/src/lib/server/list-query.js.map +1 -0
  47. package/src/lib/server/media-tombstone.js +8 -2
  48. package/src/lib/server/media-tombstone.js.map +1 -1
  49. package/src/lib/server/org-member-list-fields.d.ts +31 -0
  50. package/src/lib/server/org-member-list-fields.js +38 -0
  51. package/src/lib/server/org-member-list-fields.js.map +1 -0
  52. package/src/lib/server/organizations.js +37 -7
  53. package/src/lib/server/organizations.js.map +1 -1
  54. package/src/lib/server/replay-erasures.js +2 -1
  55. package/src/lib/server/replay-erasures.js.map +1 -1
  56. package/src/lib/server/sso-enforcement.js +2 -1
  57. package/src/lib/server/sso-enforcement.js.map +1 -1
  58. package/src/lib/server/upsert-contact.js +8 -4
  59. package/src/lib/server/upsert-contact.js.map +1 -1
@@ -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 { nameSearchTokens } from '@aglyn/aglyn/app-utils/name-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.\n *\n * Every prefix, up to `NAME_TOKEN_MAX_PREFIX` characters, of each of: the\n * whole address, the domain, the domain behind an `@`, and each piece of the\n * local part and of the domain. So `jane.doe@mail.example.com` is found by\n * `jane`, `doe`, `jane.doe@ma`, `example`, `example.com`, `mail.example` and\n * `@mail`. A query becomes one token through `nameSearchToken`, which caps\n * it at the same length, so a typed address longer than that narrows by its\n * first twelve characters rather than matching nothing.\n *\n * Mirrored by `tools/scripts/backfill-email-suppression-filters.mjs`, which\n * stamps the records written before this field existed; the two share the\n * same fixtures.\n */\nexport function emailSearchTokens(email: string | null | undefined): string[] {\n const address = String(email ?? '')\n .trim()\n .toLowerCase()\n if (!address) return []\n const at = address.lastIndexOf('@')\n const local = at === -1 ? address : address.slice(0, at)\n const domain = at === -1 ? '' : address.slice(at + 1)\n const words = [\n address,\n ...(domain ? [domain, `@${domain}`] : []),\n ...local.split(/[._+-]+/),\n ...domain.split('.'),\n ]\n return nameSearchTokens(words.filter(Boolean).join(' '))\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 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 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","nameSearchTokens","personKey","stampRecordEmailState","firebaseAdmin","defaultFirestore","app","firestore","EMAIL_SUPPRESSIONS_COLLECTION","HOST_SUPPRESSIONS_SUBCOLLECTION","PLATFORM_SUPPRESSION_REASONS","UNSUBSCRIBE_SUPPRESSION_REASON","emailSuppressionKey","email","emailSearchTokens","address","String","trim","toLowerCase","at","lastIndexOf","local","slice","domain","words","split","filter","Boolean","join","suppressEmail","input","key","Error","includes","reason","db","ref","collection","doc","snapshot","get","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","_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","seconds","_seconds","nanoseconds","_nanoseconds","rawSeconds","rawNanos","Number","isFinite","HOST_ERASURE_SUPPRESSION_REASON","suppressEmailForHostErasure","hostRefusesCaptureForErasure"],"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,gBAAgB,QAAQ,qCAAoC;AACrE,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;AAmB7D;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GAC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MH,IAAII,GAAG;IAC9B,MAAMJ,IAAIK,GAAG,CACX;QACE5B,OAAO;QACPqB,QAAQ4G;QACR/F,cAAcpD,WAAWqD,eAAe;OACpCT,SAASU,MAAM,GAAG,CAAC,IAAI;QAAEC,WAAWvD,WAAWqD,eAAe;IAAG,IAEvE;QAAEG,OAAO;IAAK;IAEhB,OAAO;QAAEpB;QAAK6B,SAAS,CAACrB,SAASU,MAAM;IAAC;AAC1C;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,eAAe+F,6BACpBpG,MAAc,EACd/B,KAAgC,EAChC6D,iBAAuB;IAEvB,MAAM3C,MAAMnB,oBAAoBC;IAChC,IAAI,CAACkB,KAAK,OAAO;IACjB,IAAI;QACF,MAAMI,KAAKuC,4BAAAA,oBAAqBrE;QAChC,MAAMkC,WAAW,MAAMJ,GACpBE,UAAU,CAAC,SACXC,GAAG,CAACM,QACJP,UAAU,CAAC5B,iCACX6B,GAAG,CAACP,KACJS,GAAG;QACN,OACEb,QAAQY,4BAAAA,SAAUU,MAAM,KACxBV,SAASC,GAAG,CAAC,cAAcsG;IAE/B,EAAE,OAAOvE,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/**\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,mBAAmB,IAAMD,cAAcE,GAAG,GAAGC,SAAS;AAE5D,OAAO,MAAMC,gCAAgC,oBAAmB;AAEhE;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,kCAAkC,eAAc;AAmB7D;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,MAAMC,+BAAkE;IAC7E;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;IAC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,MAAMC,MAAMJ,oBAAoBG,MAAMF,KAAK;IAC3C,IAAI,CAACG,KAAK,OAAO;IACjB,MAAMI,MAAKL,mBAAAA,MAAMR,SAAS,YAAfQ,mBAAmBV;IAC9B,MAAMgB,MAAMD,GACTE,UAAU,CAAC,SACXC,GAAG,CAACR,MAAMiB,MAAM,EAChBV,UAAU,CAACb,iCACXc,GAAG,CAACP;IACP,MAAMQ,WAAW,MAAMH,IAAII,GAAG;IAC9B,MAAMJ,IAAIQ,GAAG,CACX;QACEhB,OAAO;QACP,uEAAuE;QACvE,kCAAkC;QAClCiB,aAAa,EAAE;QACfX,QAAQkH;QACRlG,cAAcxC,WAAWyC,eAAe;OACpCZ,SAASa,MAAM,GAAG,CAAC,IAAI;QAAEC,WAAW3C,WAAWyC,eAAe;IAAG,IAEvE;QAAEG,OAAO;IAAK;IAEhB,OAAO;QAAEvB;QAAKgC,SAAS,CAACxB,SAASa,MAAM;IAAC;AAC1C;AAEA;;;;;;;;;;;;CAYC,GACD,OAAO,eAAekG,6BACpBvG,MAAc,EACdnB,KAAgC,EAChCiD,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"}
@@ -26,6 +26,7 @@ import { eraseEmailDeliveriesForAddresses } from "./email-delivery-log.js";
26
26
  import { suppressEmailForHostErasure } from "./email-suppression.js";
27
27
  import firebaseAdmin from "./firebase-admin.js";
28
28
  import { listMemberDocIds } from "./list-members.js";
29
+ import { addAdminAudit } from "./admin-audit-write.js";
29
30
  const defaultFirestore = ()=>firebaseAdmin.app().firestore();
30
31
  /** Firestore caps a batch at 500 writes; a page under it keeps a margin. */ const PAGE = 400;
31
32
  /**
@@ -168,6 +169,24 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
168
169
  billingAddress: FieldValue.delete(),
169
170
  customerErasedAtMs: now
170
171
  };
172
+ /*
173
+ * The address also lives in what the orders list queries by (AGL-3321):
174
+ * its lower-cased key, its search prefixes, and the quick search's token
175
+ * array, which holds those prefixes beside the order number's and the item
176
+ * names'. The first two go; the prefixes are taken back out of the third.
177
+ * A prefix the number or an item name shares with the address goes with
178
+ * it — a search for that prefix misses this order until the orders
179
+ * backfill restamps it — and nothing left on the order answers to the
180
+ * address.
181
+ */ const erasedOrderFor = (data)=>{
182
+ const addressTokens = new Set(Array.isArray(data == null ? void 0 : data.customerEmailTokens) ? data.customerEmailTokens : []);
183
+ return _extends({}, erasedOrder, {
184
+ customerEmailLower: null,
185
+ customerEmailTokens: []
186
+ }, Array.isArray(data == null ? void 0 : data.searchTokens) ? {
187
+ searchTokens: data.searchTokens.filter((token)=>!addressTokens.has(token))
188
+ } : {});
189
+ };
171
190
  const erasedBooking = {
172
191
  email: null,
173
192
  name: FieldValue.delete(),
@@ -204,7 +223,7 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
204
223
  } catch (error) {
205
224
  console.error(`erasePerson: legacy lead delete failed for ${hostId}`, error);
206
225
  }
207
- counts.orders += await updateWhere(db, hostRef.collection('orders'), 'customerEmail', email, erasedOrder);
226
+ counts.orders += await updateWhere(db, hostRef.collection('orders'), 'customerEmail', email, erasedOrderFor);
208
227
  counts.bookings += await updateWhere(db, hostRef.collection('bookings'), 'email', email, erasedBooking);
209
228
  }
210
229
  try {
@@ -232,7 +251,7 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
232
251
  } catch (error) {
233
252
  console.error('erasePerson: delivery log sweep failed', error);
234
253
  }
235
- await db.collection('adminAudit').add({
254
+ await addAdminAudit(db, {
236
255
  actorUid: 'system:erase-person',
237
256
  action: 'person.erased',
238
257
  target: `orgs/${options.orgId}/people/${key}`,
@@ -277,7 +296,7 @@ const defaultFirestore = ()=>firebaseAdmin.app().firestore();
277
296
  const page = await collection.where(field, '==', value).limit(PAGE).get();
278
297
  if (page.empty) break;
279
298
  const batch = db.batch();
280
- page.docs.forEach((doc)=>batch.update(doc.ref, patch));
299
+ page.docs.forEach((doc)=>batch.update(doc.ref, typeof patch === 'function' ? patch(doc.data()) : patch));
281
300
  await batch.commit();
282
301
  changed += page.size;
283
302
  if (page.size < PAGE) break;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/erase-person.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 { FieldValue } from 'firebase-admin/firestore'\n// The leaves, not the barrel — see `email-suppression.ts` for why: a spec\n// of this sweep substitutes a store, not the pure helpers it leans on.\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport {\n runPluginPersonErasers,\n type PluginPersonErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-erasure'\nimport { companyContactsCountFields } from './contact-company-link'\nimport { eraseEmailDeliveriesForAddresses } from './email-delivery-log'\nimport { suppressEmailForHostErasure } from './email-suppression'\nimport firebaseAdmin from './firebase-admin'\nimport { listMemberDocIds } from './list-members'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\n/** Firestore caps a batch at 500 writes; a page under it keeps a margin. */\nconst PAGE = 400\n\n/**\n * A pathological collection must not hold the erasure open indefinitely:\n * twenty pages of four hundred is eight thousand rows of one kind for one\n * person, past anything a real relationship produces.\n */\nconst MAX_PAGES = 20\n\nexport interface ErasePersonOptions {\n orgId: string\n /** Any spelling; normalized before anything is looked up. */\n email: unknown\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n /** Injectable for tests; defaults to `Date.now()`. */\n now?: number\n}\n\n/**\n * Counts, never identities: this is what the request document and the\n * audit row record, and both are read by people who must not learn the\n * address from them.\n */\nexport interface ErasePersonCounts {\n /** Sites in the workspace the sweep walked. */\n hosts: number\n /** Suppression rows written, one per site. */\n hostsSuppressed: number\n /** Contact documents deleted — the row every site shared. */\n contacts: number\n /** Companies whose contact count moved down. */\n companyLinks: number\n /** Deals whose `contactId` was removed. */\n deals: number\n tasks: number\n activities: number\n /** `hosts/{hostId}/leads/{personKey}` rows deleted. */\n leads: number\n /** Audience-list member rows deleted, across every list. */\n listMemberships: number\n /** Orders with the buyer's identity removed; the record stays. */\n orders: number\n /** Bookings with the person's identity removed; the record stays. */\n bookings: number\n /** Delivery-log messages deleted under the address. */\n emailDeliveries: number\n /**\n * Each plugin's share (AGL-2981), by plugin id: its eraser's own counts,\n * or `null` for an eraser that failed — its data may remain.\n */\n plugins: Record<string, PluginPersonErasureReport | null>\n}\n\nexport type ErasePersonResult =\n | ({ ok: true } & ErasePersonCounts)\n | { ok: false; skippedReason: 'invalid-email' }\n\n/**\n * Remove one person from one workspace (AGL-2623).\n *\n * `planContactDetach` is deliberately not consulted: the CRM's delete is a\n * detach that leaves the row for the other holders, and this is the act\n * that must not. The contact document goes whole — every site's facet,\n * every consent entry, every attribution — and with it everything the\n * workspace keeps beside the person.\n *\n * ## Order\n *\n * 1. **Suppress first.** One row per site on the per-site suppression\n * list, before any delete: a form filled in while the sweep runs must\n * already find the door closed, or the sweep deletes a row that the\n * capture re-creates a moment later.\n * 2. The plugins' share: every eraser registered on\n * `plugin-person-erasure`, handed the address, its key and the ids of\n * the contacts about to go, while those documents still exist.\n * 3. The contact and its satellites — company counts, deals unlinked,\n * tasks and activities deleted — by the contact's id, then the\n * document itself.\n * 4. Leads, list memberships, orders and bookings by the address, on\n * every site of the workspace.\n * 5. The delivery log, last: it is filed under the address alone, and the\n * tombstone it leaves is what keeps a later import from refilling it.\n *\n * ## What is anonymized rather than deleted\n *\n * An order is the merchant's record of a sale and a booking of an\n * appointment; the amounts, the line items and the tax are theirs to keep\n * and the law expects them kept. The person is taken OFF those records —\n * name, email, phone, addresses — and a stamp says when. A deal is the\n * team's own pipeline record and is unlinked. Everything else that names\n * the person is about the person and is deleted.\n *\n * ## What is not reached, and why\n *\n * A form submission keeps the address inside `fields`, under whatever the\n * form called it — there is no key to query by and a scan of every\n * submission on every site is unbounded. A site member's login is their\n * own account. A subscription carries the address it bills, and a live one\n * cannot be anonymized without breaking its receipts. Each is named to the\n * admin by the dialog so they can finish by hand.\n *\n * Every sweep is best-effort against the others: a failure in one is\n * logged and counted as zero, and the request's counts say what happened.\n * The caller decides whether zero contacts on a person it could see is a\n * failure to retry.\n */\nexport async function erasePerson(\n options: ErasePersonOptions,\n): Promise<ErasePersonResult> {\n const email = normalizeContactEmail(options.email)\n const key = email ? personKey(email) : null\n if (!email || !key) return { ok: false, skippedReason: 'invalid-email' }\n const db = options.firestore ?? defaultFirestore()\n const now = options.now ?? Date.now()\n const orgRef = db.collection('orgs').doc(options.orgId)\n\n const counts: ErasePersonCounts = {\n hosts: 0,\n hostsSuppressed: 0,\n contacts: 0,\n companyLinks: 0,\n deals: 0,\n tasks: 0,\n activities: 0,\n leads: 0,\n listMemberships: 0,\n orders: 0,\n bookings: 0,\n emailDeliveries: 0,\n plugins: {},\n }\n\n const hosts = await db\n .collection('hosts')\n .where('orgId', '==', options.orgId)\n .get()\n const hostIds: string[] = hosts.docs.map((doc: any) => String(doc.id))\n counts.hosts = hostIds.length\n\n for (const hostId of hostIds) {\n try {\n const written = await suppressEmailForHostErasure({ hostId, email, firestore: db })\n if (written) counts.hostsSuppressed += 1\n } catch (error) {\n console.error(`erasePerson: suppression write failed for ${hostId}`, error)\n }\n }\n\n const contacts = await orgRef.collection('contacts').where('email', '==', email).get()\n\n // What the plugins keep about the person (AGL-2981): records filed under\n // the organization by the contact or by the address, which none of the\n // sweeps here can see. Every site's door is already closed above, and\n // the contacts are still there for an eraser that reads one. Isolated\n // per plugin: one that fails is recorded as `null` and the erasure goes\n // on. This erasure has no plan of its own, so it is never a dry run.\n counts.plugins = await runPluginPersonErasers({\n orgId: options.orgId,\n email,\n key,\n contactIds: contacts.docs.map((contact: any) => String(contact.id)),\n dryRun: false,\n })\n\n for (const contact of contacts.docs) {\n const contactId = String(contact.id)\n const companyIds: unknown = contact.get('companyIds')\n const linked = Array.isArray(companyIds)\n ? companyIds.filter((id): id is string => typeof id === 'string' && !!id)\n : []\n for (const companyId of new Set(linked)) {\n try {\n await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .doc(companyId)\n .update(companyContactsCountFields(-1))\n counts.companyLinks += 1\n } catch (error) {\n console.error(`erasePerson: company count could not move for ${companyId}`, error)\n }\n }\n counts.deals += await updateWhere(\n db,\n orgRef.collection(CRM_COLLECTIONS.deals),\n 'contactId',\n contactId,\n { contactId: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n )\n counts.tasks += await deleteWhere(db, orgRef.collection(CRM_COLLECTIONS.tasks), 'contactId', contactId)\n counts.activities += await deleteWhere(\n db,\n orgRef.collection(CRM_COLLECTIONS.activities),\n 'contactId',\n contactId,\n )\n try {\n await contact.ref.delete()\n counts.contacts += 1\n } catch (error) {\n console.error(`erasePerson: contact delete failed for ${contactId}`, error)\n }\n }\n\n const erasedOrder = {\n customerEmail: null,\n customerName: null,\n shippingAddress: FieldValue.delete(),\n billingAddress: FieldValue.delete(),\n customerErasedAtMs: now,\n }\n const erasedBooking = {\n email: null,\n name: FieldValue.delete(),\n phone: FieldValue.delete(),\n customerErasedAtMs: now,\n }\n /*\n * THE ORG ROW, ONCE (AGL-3275) — and then every legacy row still standing.\n *\n * A lead is one document for the whole org now, so the delete leaves the\n * per-site loop. It is not the caller that may assume the migration is\n * finished, though: until AGL-3276 has folded every site and AGL-3277 has\n * removed the fallback, a person can still be held at\n * `hosts/{hostId}/leads`, and an erasure that deleted only the org row would\n * leave that copy behind. So both are swept, and `counts.leads` is what was\n * actually destroyed rather than how many places were looked at.\n */\n try {\n const orgLead = orgRef.collection('leads').doc(key)\n if ((await orgLead.get()).exists) {\n await orgLead.delete()\n counts.leads += 1\n }\n } catch (error) {\n console.error('erasePerson: org lead delete failed', error)\n }\n for (const hostId of hostIds) {\n const hostRef = db.collection('hosts').doc(hostId)\n try {\n const lead = hostRef.collection('leads').doc(key)\n if ((await lead.get()).exists) {\n await lead.delete()\n counts.leads += 1\n }\n } catch (error) {\n console.error(`erasePerson: legacy lead delete failed for ${hostId}`, error)\n }\n counts.orders += await updateWhere(db, hostRef.collection('orders'), 'customerEmail', email, erasedOrder)\n counts.bookings += await updateWhere(db, hostRef.collection('bookings'), 'email', email, erasedBooking)\n }\n\n try {\n const memberIds = listMemberDocIds(email)\n const lists = await orgRef.collection('lists').get()\n for (const list of lists.docs) {\n const refs = memberIds.map((id) => list.ref.collection('members').doc(id))\n const found = await db.getAll(...refs)\n for (const member of found) {\n if (!member.exists) continue\n await member.ref.delete()\n counts.listMemberships += 1\n }\n }\n } catch (error) {\n console.error('erasePerson: list membership sweep failed', error)\n }\n\n try {\n const sweep = await eraseEmailDeliveriesForAddresses([{ address: email }], db)\n counts.emailDeliveries = sweep.removed\n } catch (error) {\n console.error('erasePerson: delivery log sweep failed', error)\n }\n\n await db\n .collection('adminAudit')\n .add({\n actorUid: 'system:erase-person',\n action: 'person.erased',\n target: `orgs/${options.orgId}/people/${key}`,\n before: null,\n after: counts,\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n return { ok: true, ...counts }\n}\n\n/**\n * Delete every document in `collection` whose `field` equals `value`, a\n * page at a time. Returns how many went; a failure logs and stops, and the\n * count says how far it got.\n */\nasync function deleteWhere(\n db: any,\n collection: any,\n field: string,\n value: string,\n): Promise<number> {\n let removed = 0\n try {\n for (let pass = 0; pass < MAX_PAGES; pass += 1) {\n const page = await collection.where(field, '==', value).limit(PAGE).get()\n if (page.empty) break\n const batch = db.batch()\n page.docs.forEach((doc: any) => batch.delete(doc.ref))\n await batch.commit()\n removed += page.size\n if (page.size < PAGE) break\n }\n } catch (error) {\n console.error(`erasePerson: delete sweep failed on ${field}`, error)\n }\n return removed\n}\n\n/**\n * Apply `patch` to every document in `collection` whose `field` equals\n * `value`. Because the patch clears the very field that was matched on, a\n * second page never sees the first page's rows again, so the loop needs no\n * cursor; the page cap is the only bound.\n */\nasync function updateWhere(\n db: any,\n collection: any,\n field: string,\n value: string,\n patch: Record<string, unknown>,\n): Promise<number> {\n let changed = 0\n try {\n for (let pass = 0; pass < MAX_PAGES; pass += 1) {\n const page = await collection.where(field, '==', value).limit(PAGE).get()\n if (page.empty) break\n const batch = db.batch()\n page.docs.forEach((doc: any) => batch.update(doc.ref, patch))\n await batch.commit()\n changed += page.size\n if (page.size < PAGE) break\n }\n } catch (error) {\n console.error(`erasePerson: update sweep failed on ${field}`, error)\n }\n return changed\n}\n"],"names":["FieldValue","normalizeContactEmail","CRM_COLLECTIONS","personKey","runPluginPersonErasers","companyContactsCountFields","eraseEmailDeliveriesForAddresses","suppressEmailForHostErasure","firebaseAdmin","listMemberDocIds","defaultFirestore","app","firestore","PAGE","MAX_PAGES","erasePerson","options","email","key","ok","skippedReason","db","now","Date","orgRef","collection","doc","orgId","counts","hosts","hostsSuppressed","contacts","companyLinks","deals","tasks","activities","leads","listMemberships","orders","bookings","emailDeliveries","plugins","where","get","hostIds","docs","map","String","id","length","hostId","written","error","console","contactIds","contact","dryRun","contactId","companyIds","linked","Array","isArray","filter","companyId","Set","companies","update","updateWhere","delete","updatedAt","serverTimestamp","deleteWhere","ref","erasedOrder","customerEmail","customerName","shippingAddress","billingAddress","customerErasedAtMs","erasedBooking","name","phone","orgLead","exists","hostRef","lead","memberIds","lists","list","refs","found","getAll","member","sweep","address","removed","add","actorUid","action","target","before","after","at","catch","undefined","field","value","pass","page","limit","empty","batch","forEach","commit","size","patch","changed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,2BAA0B;AACrD,0EAA0E;AAC1E,uEAAuE;AACvE,SAASC,qBAAqB,QAAQ,kCAAiC;AACvE,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,SAAS,QAAQ,oCAAmC;AAC7D,SACEC,sBAAsB,QAEjB,oDAAmD;AAC1D,SAASC,0BAA0B,QAAQ,4BAAwB;AACnE,SAASC,gCAAgC,QAAQ,0BAAsB;AACvE,SAASC,2BAA2B,QAAQ,yBAAqB;AACjE,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,gBAAgB,QAAQ,oBAAgB;AAEjD,MAAMC,mBAAmB,IAAMF,cAAcG,GAAG,GAAGC,SAAS;AAE5D,0EAA0E,GAC1E,MAAMC,OAAO;AAEb;;;;CAIC,GACD,MAAMC,YAAY;AAmDlB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDC,GACD,OAAO,eAAeC,YACpBC,OAA2B;QAKhBA,oBACCA;IAJZ,MAAMC,QAAQhB,sBAAsBe,QAAQC,KAAK;IACjD,MAAMC,MAAMD,QAAQd,UAAUc,SAAS;IACvC,IAAI,CAACA,SAAS,CAACC,KAAK,OAAO;QAAEC,IAAI;QAAOC,eAAe;IAAgB;IACvE,MAAMC,MAAKL,qBAAAA,QAAQJ,SAAS,YAAjBI,qBAAqBN;IAChC,MAAMY,OAAMN,eAAAA,QAAQM,GAAG,YAAXN,eAAeO,KAAKD,GAAG;IACnC,MAAME,SAASH,GAAG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AM;QACxB;IACF,EAAE,OAAOuC,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,oCAAoC,EAAEqD,OAAO,EAAErD;IAChE;IACA,OAAO2C;AACT;AAEA;;;;;CAKC,GACD,eAAe5B,YACb9C,EAAO,EACPI,UAAe,EACfgF,KAAa,EACbC,KAAa,EACbS,KAA8B;IAE9B,IAAIC,UAAU;IACd,IAAI;QACF,IAAK,IAAIT,OAAO,GAAGA,OAAO7F,WAAW6F,QAAQ,EAAG;YAC9C,MAAMC,OAAO,MAAMnF,WAAWiB,KAAK,CAAC+D,OAAO,MAAMC,OAAOG,KAAK,CAAChG,MAAM8B,GAAG;YACvE,IAAIiE,KAAKE,KAAK,EAAE;YAChB,MAAMC,QAAQ1F,GAAG0F,KAAK;YACtBH,KAAK/D,IAAI,CAACmE,OAAO,CAAC,CAACtF,MAAaqF,MAAM7C,MAAM,CAACxC,IAAI8C,GAAG,EAAE2C;YACtD,MAAMJ,MAAME,MAAM;YAClBG,WAAWR,KAAKM,IAAI;YACpB,IAAIN,KAAKM,IAAI,GAAGrG,MAAM;QACxB;IACF,EAAE,OAAOuC,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,oCAAoC,EAAEqD,OAAO,EAAErD;IAChE;IACA,OAAOgE;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/erase-person.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 { FieldValue } from 'firebase-admin/firestore'\n// The leaves, not the barrel — see `email-suppression.ts` for why: a spec\n// of this sweep substitutes a store, not the pure helpers it leans on.\nimport { normalizeContactEmail } from '@aglyn/aglyn/app-utils/contacts'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport { personKey } from '@aglyn/aglyn/app-utils/person-key'\nimport {\n runPluginPersonErasers,\n type PluginPersonErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-erasure'\nimport { companyContactsCountFields } from './contact-company-link'\nimport { eraseEmailDeliveriesForAddresses } from './email-delivery-log'\nimport { suppressEmailForHostErasure } from './email-suppression'\nimport firebaseAdmin from './firebase-admin'\nimport { listMemberDocIds } from './list-members'\nimport { addAdminAudit } from './admin-audit-write'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\n/** Firestore caps a batch at 500 writes; a page under it keeps a margin. */\nconst PAGE = 400\n\n/**\n * A pathological collection must not hold the erasure open indefinitely:\n * twenty pages of four hundred is eight thousand rows of one kind for one\n * person, past anything a real relationship produces.\n */\nconst MAX_PAGES = 20\n\nexport interface ErasePersonOptions {\n orgId: string\n /** Any spelling; normalized before anything is looked up. */\n email: unknown\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n /** Injectable for tests; defaults to `Date.now()`. */\n now?: number\n}\n\n/**\n * Counts, never identities: this is what the request document and the\n * audit row record, and both are read by people who must not learn the\n * address from them.\n */\nexport interface ErasePersonCounts {\n /** Sites in the workspace the sweep walked. */\n hosts: number\n /** Suppression rows written, one per site. */\n hostsSuppressed: number\n /** Contact documents deleted — the row every site shared. */\n contacts: number\n /** Companies whose contact count moved down. */\n companyLinks: number\n /** Deals whose `contactId` was removed. */\n deals: number\n tasks: number\n activities: number\n /** `hosts/{hostId}/leads/{personKey}` rows deleted. */\n leads: number\n /** Audience-list member rows deleted, across every list. */\n listMemberships: number\n /** Orders with the buyer's identity removed; the record stays. */\n orders: number\n /** Bookings with the person's identity removed; the record stays. */\n bookings: number\n /** Delivery-log messages deleted under the address. */\n emailDeliveries: number\n /**\n * Each plugin's share (AGL-2981), by plugin id: its eraser's own counts,\n * or `null` for an eraser that failed — its data may remain.\n */\n plugins: Record<string, PluginPersonErasureReport | null>\n}\n\nexport type ErasePersonResult =\n | ({ ok: true } & ErasePersonCounts)\n | { ok: false; skippedReason: 'invalid-email' }\n\n/**\n * Remove one person from one workspace (AGL-2623).\n *\n * `planContactDetach` is deliberately not consulted: the CRM's delete is a\n * detach that leaves the row for the other holders, and this is the act\n * that must not. The contact document goes whole — every site's facet,\n * every consent entry, every attribution — and with it everything the\n * workspace keeps beside the person.\n *\n * ## Order\n *\n * 1. **Suppress first.** One row per site on the per-site suppression\n * list, before any delete: a form filled in while the sweep runs must\n * already find the door closed, or the sweep deletes a row that the\n * capture re-creates a moment later.\n * 2. The plugins' share: every eraser registered on\n * `plugin-person-erasure`, handed the address, its key and the ids of\n * the contacts about to go, while those documents still exist.\n * 3. The contact and its satellites — company counts, deals unlinked,\n * tasks and activities deleted — by the contact's id, then the\n * document itself.\n * 4. Leads, list memberships, orders and bookings by the address, on\n * every site of the workspace.\n * 5. The delivery log, last: it is filed under the address alone, and the\n * tombstone it leaves is what keeps a later import from refilling it.\n *\n * ## What is anonymized rather than deleted\n *\n * An order is the merchant's record of a sale and a booking of an\n * appointment; the amounts, the line items and the tax are theirs to keep\n * and the law expects them kept. The person is taken OFF those records —\n * name, email, phone, addresses — and a stamp says when. A deal is the\n * team's own pipeline record and is unlinked. Everything else that names\n * the person is about the person and is deleted.\n *\n * ## What is not reached, and why\n *\n * A form submission keeps the address inside `fields`, under whatever the\n * form called it — there is no key to query by and a scan of every\n * submission on every site is unbounded. A site member's login is their\n * own account. A subscription carries the address it bills, and a live one\n * cannot be anonymized without breaking its receipts. Each is named to the\n * admin by the dialog so they can finish by hand.\n *\n * Every sweep is best-effort against the others: a failure in one is\n * logged and counted as zero, and the request's counts say what happened.\n * The caller decides whether zero contacts on a person it could see is a\n * failure to retry.\n */\nexport async function erasePerson(\n options: ErasePersonOptions,\n): Promise<ErasePersonResult> {\n const email = normalizeContactEmail(options.email)\n const key = email ? personKey(email) : null\n if (!email || !key) return { ok: false, skippedReason: 'invalid-email' }\n const db = options.firestore ?? defaultFirestore()\n const now = options.now ?? Date.now()\n const orgRef = db.collection('orgs').doc(options.orgId)\n\n const counts: ErasePersonCounts = {\n hosts: 0,\n hostsSuppressed: 0,\n contacts: 0,\n companyLinks: 0,\n deals: 0,\n tasks: 0,\n activities: 0,\n leads: 0,\n listMemberships: 0,\n orders: 0,\n bookings: 0,\n emailDeliveries: 0,\n plugins: {},\n }\n\n const hosts = await db\n .collection('hosts')\n .where('orgId', '==', options.orgId)\n .get()\n const hostIds: string[] = hosts.docs.map((doc: any) => String(doc.id))\n counts.hosts = hostIds.length\n\n for (const hostId of hostIds) {\n try {\n const written = await suppressEmailForHostErasure({ hostId, email, firestore: db })\n if (written) counts.hostsSuppressed += 1\n } catch (error) {\n console.error(`erasePerson: suppression write failed for ${hostId}`, error)\n }\n }\n\n const contacts = await orgRef.collection('contacts').where('email', '==', email).get()\n\n // What the plugins keep about the person (AGL-2981): records filed under\n // the organization by the contact or by the address, which none of the\n // sweeps here can see. Every site's door is already closed above, and\n // the contacts are still there for an eraser that reads one. Isolated\n // per plugin: one that fails is recorded as `null` and the erasure goes\n // on. This erasure has no plan of its own, so it is never a dry run.\n counts.plugins = await runPluginPersonErasers({\n orgId: options.orgId,\n email,\n key,\n contactIds: contacts.docs.map((contact: any) => String(contact.id)),\n dryRun: false,\n })\n\n for (const contact of contacts.docs) {\n const contactId = String(contact.id)\n const companyIds: unknown = contact.get('companyIds')\n const linked = Array.isArray(companyIds)\n ? companyIds.filter((id): id is string => typeof id === 'string' && !!id)\n : []\n for (const companyId of new Set(linked)) {\n try {\n await orgRef\n .collection(CRM_COLLECTIONS.companies)\n .doc(companyId)\n .update(companyContactsCountFields(-1))\n counts.companyLinks += 1\n } catch (error) {\n console.error(`erasePerson: company count could not move for ${companyId}`, error)\n }\n }\n counts.deals += await updateWhere(\n db,\n orgRef.collection(CRM_COLLECTIONS.deals),\n 'contactId',\n contactId,\n { contactId: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n )\n counts.tasks += await deleteWhere(db, orgRef.collection(CRM_COLLECTIONS.tasks), 'contactId', contactId)\n counts.activities += await deleteWhere(\n db,\n orgRef.collection(CRM_COLLECTIONS.activities),\n 'contactId',\n contactId,\n )\n try {\n await contact.ref.delete()\n counts.contacts += 1\n } catch (error) {\n console.error(`erasePerson: contact delete failed for ${contactId}`, error)\n }\n }\n\n const erasedOrder = {\n customerEmail: null,\n customerName: null,\n shippingAddress: FieldValue.delete(),\n billingAddress: FieldValue.delete(),\n customerErasedAtMs: now,\n }\n /*\n * The address also lives in what the orders list queries by (AGL-3321):\n * its lower-cased key, its search prefixes, and the quick search's token\n * array, which holds those prefixes beside the order number's and the item\n * names'. The first two go; the prefixes are taken back out of the third.\n * A prefix the number or an item name shares with the address goes with\n * it — a search for that prefix misses this order until the orders\n * backfill restamps it — and nothing left on the order answers to the\n * address.\n */\n const erasedOrderFor = (data: Record<string, unknown> | undefined) => {\n const addressTokens = new Set(\n Array.isArray(data?.customerEmailTokens) ? data.customerEmailTokens : [],\n )\n return {\n ...erasedOrder,\n customerEmailLower: null,\n customerEmailTokens: [],\n ...(Array.isArray(data?.searchTokens)\n ? {\n searchTokens: data.searchTokens.filter(\n (token: unknown) => !addressTokens.has(token),\n ),\n }\n : {}),\n }\n }\n const erasedBooking = {\n email: null,\n name: FieldValue.delete(),\n phone: FieldValue.delete(),\n customerErasedAtMs: now,\n }\n /*\n * THE ORG ROW, ONCE (AGL-3275) — and then every legacy row still standing.\n *\n * A lead is one document for the whole org now, so the delete leaves the\n * per-site loop. It is not the caller that may assume the migration is\n * finished, though: until AGL-3276 has folded every site and AGL-3277 has\n * removed the fallback, a person can still be held at\n * `hosts/{hostId}/leads`, and an erasure that deleted only the org row would\n * leave that copy behind. So both are swept, and `counts.leads` is what was\n * actually destroyed rather than how many places were looked at.\n */\n try {\n const orgLead = orgRef.collection('leads').doc(key)\n if ((await orgLead.get()).exists) {\n await orgLead.delete()\n counts.leads += 1\n }\n } catch (error) {\n console.error('erasePerson: org lead delete failed', error)\n }\n for (const hostId of hostIds) {\n const hostRef = db.collection('hosts').doc(hostId)\n try {\n const lead = hostRef.collection('leads').doc(key)\n if ((await lead.get()).exists) {\n await lead.delete()\n counts.leads += 1\n }\n } catch (error) {\n console.error(`erasePerson: legacy lead delete failed for ${hostId}`, error)\n }\n counts.orders += await updateWhere(db, hostRef.collection('orders'), 'customerEmail', email, erasedOrderFor)\n counts.bookings += await updateWhere(db, hostRef.collection('bookings'), 'email', email, erasedBooking)\n }\n\n try {\n const memberIds = listMemberDocIds(email)\n const lists = await orgRef.collection('lists').get()\n for (const list of lists.docs) {\n const refs = memberIds.map((id) => list.ref.collection('members').doc(id))\n const found = await db.getAll(...refs)\n for (const member of found) {\n if (!member.exists) continue\n await member.ref.delete()\n counts.listMemberships += 1\n }\n }\n } catch (error) {\n console.error('erasePerson: list membership sweep failed', error)\n }\n\n try {\n const sweep = await eraseEmailDeliveriesForAddresses([{ address: email }], db)\n counts.emailDeliveries = sweep.removed\n } catch (error) {\n console.error('erasePerson: delivery log sweep failed', error)\n }\n\n await addAdminAudit(db, {\n actorUid: 'system:erase-person',\n action: 'person.erased',\n target: `orgs/${options.orgId}/people/${key}`,\n before: null,\n after: counts,\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n return { ok: true, ...counts }\n}\n\n/**\n * Delete every document in `collection` whose `field` equals `value`, a\n * page at a time. Returns how many went; a failure logs and stops, and the\n * count says how far it got.\n */\nasync function deleteWhere(\n db: any,\n collection: any,\n field: string,\n value: string,\n): Promise<number> {\n let removed = 0\n try {\n for (let pass = 0; pass < MAX_PAGES; pass += 1) {\n const page = await collection.where(field, '==', value).limit(PAGE).get()\n if (page.empty) break\n const batch = db.batch()\n page.docs.forEach((doc: any) => batch.delete(doc.ref))\n await batch.commit()\n removed += page.size\n if (page.size < PAGE) break\n }\n } catch (error) {\n console.error(`erasePerson: delete sweep failed on ${field}`, error)\n }\n return removed\n}\n\n/**\n * Apply `patch` to every document in `collection` whose `field` equals\n * `value`. Because the patch clears the very field that was matched on, a\n * second page never sees the first page's rows again, so the loop needs no\n * cursor; the page cap is the only bound.\n */\nasync function updateWhere(\n db: any,\n collection: any,\n field: string,\n value: string,\n patch: Record<string, unknown> | ((data: Record<string, unknown> | undefined) => Record<string, unknown>),\n): Promise<number> {\n let changed = 0\n try {\n for (let pass = 0; pass < MAX_PAGES; pass += 1) {\n const page = await collection.where(field, '==', value).limit(PAGE).get()\n if (page.empty) break\n const batch = db.batch()\n page.docs.forEach((doc: any) =>\n batch.update(doc.ref, typeof patch === 'function' ? patch(doc.data()) : patch),\n )\n await batch.commit()\n changed += page.size\n if (page.size < PAGE) break\n }\n } catch (error) {\n console.error(`erasePerson: update sweep failed on ${field}`, error)\n }\n return changed\n}\n"],"names":["FieldValue","normalizeContactEmail","CRM_COLLECTIONS","personKey","runPluginPersonErasers","companyContactsCountFields","eraseEmailDeliveriesForAddresses","suppressEmailForHostErasure","firebaseAdmin","listMemberDocIds","addAdminAudit","defaultFirestore","app","firestore","PAGE","MAX_PAGES","erasePerson","options","email","key","ok","skippedReason","db","now","Date","orgRef","collection","doc","orgId","counts","hosts","hostsSuppressed","contacts","companyLinks","deals","tasks","activities","leads","listMemberships","orders","bookings","emailDeliveries","plugins","where","get","hostIds","docs","map","String","id","length","hostId","written","error","console","contactIds","contact","dryRun","contactId","companyIds","linked","Array","isArray","filter","companyId","Set","companies","update","updateWhere","delete","updatedAt","serverTimestamp","deleteWhere","ref","erasedOrder","customerEmail","customerName","shippingAddress","billingAddress","customerErasedAtMs","erasedOrderFor","data","addressTokens","customerEmailTokens","customerEmailLower","searchTokens","token","has","erasedBooking","name","phone","orgLead","exists","hostRef","lead","memberIds","lists","list","refs","found","getAll","member","sweep","address","removed","actorUid","action","target","before","after","at","catch","undefined","field","value","pass","page","limit","empty","batch","forEach","commit","size","patch","changed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CAAC7F,MAAa4F,MAAMlD,MAAM,CAAC1C,IAAI8C,GAAG;YACpD,MAAM8C,MAAME,MAAM;YAClBjB,WAAWY,KAAKM,IAAI;YACpB,IAAIN,KAAKM,IAAI,GAAG5G,MAAM;QACxB;IACF,EAAE,OAAOuC,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,oCAAoC,EAAE4D,OAAO,EAAE5D;IAChE;IACA,OAAOmD;AACT;AAEA;;;;;CAKC,GACD,eAAepC,YACb9C,EAAO,EACPI,UAAe,EACfuF,KAAa,EACbC,KAAa,EACbS,KAAyG;IAEzG,IAAIC,UAAU;IACd,IAAI;QACF,IAAK,IAAIT,OAAO,GAAGA,OAAOpG,WAAWoG,QAAQ,EAAG;YAC9C,MAAMC,OAAO,MAAM1F,WAAWiB,KAAK,CAACsE,OAAO,MAAMC,OAAOG,KAAK,CAACvG,MAAM8B,GAAG;YACvE,IAAIwE,KAAKE,KAAK,EAAE;YAChB,MAAMC,QAAQjG,GAAGiG,KAAK;YACtBH,KAAKtE,IAAI,CAAC0E,OAAO,CAAC,CAAC7F,MACjB4F,MAAMpD,MAAM,CAACxC,IAAI8C,GAAG,EAAE,OAAOkD,UAAU,aAAaA,MAAMhG,IAAIsD,IAAI,MAAM0C;YAE1E,MAAMJ,MAAME,MAAM;YAClBG,WAAWR,KAAKM,IAAI;YACpB,IAAIN,KAAKM,IAAI,GAAG5G,MAAM;QACxB;IACF,EAAE,OAAOuC,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,oCAAoC,EAAE4D,OAAO,EAAE5D;IAChE;IACA,OAAOuE;AACT"}
@@ -34,6 +34,7 @@ import { consentGroupSiteHold } from "@aglyn/aglyn/app-utils/consent-groups";
34
34
  import { listPluginOrgCollections } from "@aglyn/aglyn/plugin-manager/plugin-host-collections";
35
35
  import { readOrgBilling } from "./org-billing.js";
36
36
  import { disposeHostSendingDomain, readSendingDomainTeardownByLabel } from "./sending-domain-debt.js";
37
+ import { addAdminAudit } from "./admin-audit-write.js";
37
38
  /** The reversible hold before a requested erasure is executed (AGL-485). */ export const ERASURE_HOLD_MS = 7 * 24 * 60 * 60 * 1000;
38
39
  /**
39
40
  * The admin app is initialized without a default storageBucket, so every
@@ -827,7 +828,7 @@ export async function eraseHost(hostId, options = {}) {
827
828
  * failing, and losing the original error to a bookkeeping write would be
828
829
  * worse than losing the row.
829
830
  */ async function recordErasureFailure(entry) {
830
- await firebaseAdmin.app().firestore().collection('adminAudit').add({
831
+ await addAdminAudit(firebaseAdmin.app().firestore(), {
831
832
  actorUid: entry.actorUid,
832
833
  action: 'org.erase-failed',
833
834
  target: `orgs/${entry.orgId}`,
@@ -1132,7 +1133,7 @@ export async function eraseHost(hostId, options = {}) {
1132
1133
  // The proof of erasure, and now the only record of it: actor, action,
1133
1134
  // target, the request it fulfilled, the inventory found and what each sweep
1134
1135
  // destroyed. Ids and counts — never the content (AGL-1443).
1135
- await firestore.collection('adminAudit').add({
1136
+ await addAdminAudit(firestore, {
1136
1137
  actorUid,
1137
1138
  action: 'org.erased',
1138
1139
  target: `orgs/${orgId}`,
@@ -1543,7 +1544,7 @@ export async function eraseHost(hostId, options = {}) {
1543
1544
  contested: contestedAddressCount,
1544
1545
  incomplete: addressSet.incomplete
1545
1546
  };
1546
- await firestore.collection('adminAudit').add({
1547
+ await addAdminAudit(firestore, {
1547
1548
  actorUid: 'system:erase-user',
1548
1549
  action: 'user.erased',
1549
1550
  target: `users/${uid}`,