@aglyn/tenant-data-admin 1.20.2 → 1.20.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.20.2",
3
+ "version": "1.20.3",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.20.2",
29
- "@aglyn/shared-util-email": "1.20.2",
30
- "@aglyn/shared-util-fbserver": "1.20.2",
31
- "@aglyn/shared-util-first-touch": "1.20.2",
32
- "@aglyn/shared-util-http": "1.20.2",
33
- "@aglyn/shared-util-tools": "1.20.2",
28
+ "@aglyn/aglyn": "1.20.3",
29
+ "@aglyn/shared-util-email": "1.20.3",
30
+ "@aglyn/shared-util-fbserver": "1.20.3",
31
+ "@aglyn/shared-util-first-touch": "1.20.3",
32
+ "@aglyn/shared-util-http": "1.20.3",
33
+ "@aglyn/shared-util-tools": "1.20.3",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -39,6 +39,7 @@ import { releasedHostNames } from "./host-released-names.js";
39
39
  import { readOrgBilling } from "./org-billing.js";
40
40
  import { disposeHostSendingDomain, readSendingDomainTeardownByLabel } from "./sending-domain-debt.js";
41
41
  import { addAdminAudit } from "./admin-audit-write.js";
42
+ import { retryTransientFirestore } from "./firestore-transient.js";
42
43
  /** The reversible hold before a requested erasure is executed (AGL-485). */ export const ERASURE_HOLD_MS = 7 * 24 * 60 * 60 * 1000;
43
44
  /**
44
45
  * The admin app is initialized without a default storageBucket, so every
@@ -223,6 +224,37 @@ import { addAdminAudit } from "./admin-audit-write.js";
223
224
  this.hold = hold;
224
225
  }
225
226
  }
227
+ /*==========================================
228
+ * ONE FAILED WRITE IN THE TREE IS NOT A FAILED DELETE.
229
+ *
230
+ * `recursiveDelete` is a bulk writer: a site is hundreds of deletes, and one
231
+ * that meets `UNAVAILABLE` or a deadline under load rejects the whole call
232
+ * with that write's code. Thrown from here it reached the delete route as a
233
+ * 500, for a site whose tree was gone, so the console said the delete failed
234
+ * and a retry found nothing to delete.
235
+ *
236
+ * So a transient failure runs the delete again, which is safe because a
237
+ * delete of what is already gone does nothing, and walks the subcollections
238
+ * whether or not the parent document still exists. When the retries are
239
+ * spent, or the failure was not transient, the host document decides: the
240
+ * bulk writer deletes it LAST, so its absence means the site is erased and
241
+ * no reader can route to it. What a write left behind is logged; the
242
+ * delete answers as done. A host document still standing is a real failure
243
+ * and is thrown.
244
+ *=========================================*/ async function eraseHostTree(firestore, hostRef, hostId) {
245
+ try {
246
+ await retryTransientFirestore(()=>firestore.recursiveDelete(hostRef), {
247
+ onRetry: (error, attempt)=>console.warn(`eraseHost: retrying the tree delete for ${hostId} (${attempt})`, error)
248
+ });
249
+ } catch (error) {
250
+ const remaining = await retryTransientFirestore(()=>hostRef.get()).catch(()=>null);
251
+ if (remaining && !remaining.exists) {
252
+ console.error(`eraseHost: the tree delete for ${hostId} reported a failure after the site was erased`, error);
253
+ return;
254
+ }
255
+ throw error;
256
+ }
257
+ }
226
258
  export async function eraseHost(hostId, options = {}) {
227
259
  var _hostSnapshot_get, _hostSnapshot_get1;
228
260
  const firestore = firebaseAdmin.app().firestore();
@@ -334,7 +366,7 @@ export async function eraseHost(hostId, options = {}) {
334
366
  });
335
367
  }
336
368
  // The host document tree (screens/layouts/versions/counters/products/…).
337
- await firestore.recursiveDelete(hostRef);
369
+ await eraseHostTree(firestore, hostRef, hostId);
338
370
  // The plugin rows keyed by the site that its tree does not hold (AGL-4214).
339
371
  // After the tree, so a register's display can no longer verify against it.
340
372
  await erasePluginHostKeyedCollections(hostId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/erase.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'\nimport { firebaseAdmin } from './firebase-admin'\nimport { eraseMediaDeliveryScope } from './media-delivery'\nimport { sweepScopeSharingAfterSiteChange } from './scope-sharing-sweep'\nimport {\n deleteHostProjectionForAllMembers,\n deleteHostProjectionForUids,\n} from './host-memberships'\nimport { detachWorkspaceDomain } from './workspace-domains'\nimport {\n CONSOLE_DOMAINS_COLLECTION,\n releaseConsoleDomain,\n} from './console-domains'\nimport { authForPool, findUserByUidAcrossPools } from './auth-pools'\nimport { eraseEmailDeliveriesForAddresses } from './email-delivery-log'\nimport {\n type AccountAddressSet,\n type AccountAddressSource,\n resolveAccountAddresses,\n} from './account-addresses'\nimport { EMAIL_IDENTITY_INDEX_COLLECTION } from './account-emails'\nimport { removeOrgMember } from './organizations'\nimport {\n runPluginUserErasers,\n type PluginUserErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-user-erasure'\nimport {\n PLUGIN_ORG_KEYED_COLLECTIONS,\n runPluginOrgErasers,\n type PluginOrgErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport { isBillingSubscription } from '@aglyn/aglyn/server'\n// The module path rather than the barrel: this module's specs substitute the\n// barrel, and which sites a consent group still needs is the rule itself.\nimport {\n type ConsentGroupSiteHold,\n consentGroupSiteHold,\n} from '@aglyn/aglyn/app-utils/consent-groups'\nimport { listPluginOrgCollections } from '@aglyn/aglyn/plugin-manager/plugin-host-collections'\nimport {\n PLUGIN_HOST_KEYED_COLLECTIONS,\n erasePluginSiteResources,\n previewPluginSiteResources,\n type PluginSiteResourcePreviewRow,\n} from '@aglyn/aglyn/plugin-manager/plugin-site-resources'\nimport { runPluginEventHandlers } from '@aglyn/aglyn/plugin-manager/plugin-events'\nimport { releasedHostNames } from './host-released-names'\nimport { readOrgBilling } from './org-billing'\nimport {\n disposeHostSendingDomain,\n readSendingDomainTeardownByLabel,\n type SendingDomainDisposition,\n type TeardownSendingDomainDriver,\n} from './sending-domain-debt'\nimport { addAdminAudit } from './admin-audit-write'\n\n/** The reversible hold before a requested erasure is executed (AGL-485). */\nexport const ERASURE_HOLD_MS = 7 * 24 * 60 * 60 * 1000\n\n/**\n * The admin app is initialized without a default storageBucket, so every\n * bucket access must name it explicitly (same as the media routes). Falls\n * through to the admin default if the env is somehow unset.\n */\nfunction storageBucket() {\n const name = process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET\n return firebaseAdmin.app().storage().bucket(name || undefined)\n}\n\n/**\n * `supplierDeliveries` — the dropship outbox, keyed by `hostId` as a FIELD.\n *\n * The literal rather than an import: the collection belongs to\n * `libs/plugins/commerce/src/lib/server/supplier-outbox.ts`\n * (`SUPPLIER_DELIVERY_COLLECTION`), which is tagged `aglyn:addons`, and this\n * library is `scope:data` — the nx boundary forbids the edge, and reaching\n * for a dynamic import to dodge it would poison the lint graph instead. The\n * emulator spec asserts the two spellings still agree by reading that file,\n * so a rename fails a test rather than silently un-wiring this sweep.\n */\nconst SUPPLIER_DELIVERY_COLLECTION = 'supplierDeliveries'\n\n/**\n * Destroy the site's DEAD-LETTERED supplier deliveries (AGL-1448).\n *\n * `supplierDeliveries/{id}` is TOP-LEVEL and carries `hostId` as a field, so\n * neither `recursiveDelete(hosts/{hostId})` here nor\n * `recursiveDelete(orgs/{orgId})` in `eraseOrg` can see it. That placement is\n * deliberate and correct — a subcollection would be editor-writable under the\n * permissive host catch-all, and the row carries the exact JSON body we sign\n * and POST to the supplier — so the fix is a sweep, not a move.\n *\n * **The gap is the dead letter, and the module that created it named it.**\n * `supplier-outbox.ts` DELETES a row the moment delivery succeeds, and its\n * docblock says why in terms: the body holds the buyer's email and name, and\n * a top-level document is outside the recursive delete an erasure runs. The\n * happy path was solved by that deletion. The failure path was not: after\n * `SUPPLIER_DELIVERY_MAX_ATTEMPTS` the row is left standing as `failed`,\n * because a human is supposed to act on it and the merchant has been told.\n * Nothing ever collects it afterwards — no TTL policy keys on it, no cron\n * reaps it, and the erasure could not reach it. So the one class of row that\n * survives is the one holding a THIRD PARTY's name, email and shipping\n * address, against a site whose owner has since asked to be erased and whom\n * nobody can ask to act on the dead letter any more.\n *\n * Bounded by the `hostId` field, never a collection sweep: this collection\n * holds every other merchant's orders. Chunked, because a batch caps at 500\n * and nothing bounds a dead-letter backlog below that.\n *\n * In `eraseHost` rather than `eraseOrg` on purpose — it is host-scoped data,\n * so the self-serve \"delete this site\" path gets the same cleanup as a full\n * org erasure instead of leaving the residue behind for the smaller action.\n *\n * Best-effort, like every other trailing cleanup in `eraseHost`: a site\n * delete must not fail because an outbox query did.\n */\nasync function eraseHostSupplierDeliveries(hostId: string): Promise<number> {\n if (!hostId) return 0\n try {\n const firestore = firebaseAdmin.app().firestore()\n const rows = await firestore\n .collection(SUPPLIER_DELIVERY_COLLECTION)\n .where('hostId', '==', hostId)\n .get()\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) {\n batch.delete(doc.ref)\n }\n await batch.commit()\n }\n return rows.size\n } catch (error) {\n console.error(`eraseHost: supplier outbox cleanup failed for ${hostId}`, error)\n return 0\n }\n}\n\n/**\n * Every in-app notification about the site, in every inbox (AGL-3719).\n *\n * `users/{uid}/notifications/{id}` names the site in `hostId` — \"Your site is\n * live\", \"Your site job needs you\", the staff operator alerts — and links into\n * it (`/{hostId}/ai-jobs/…`). Nothing else collects them: they carry no TTL,\n * the `recursiveDelete(hosts/{hostId})` below cannot see a user's tree, and\n * the inbox outlives the site, so every one became a link to a 404 that stood\n * forever. A 2026-10-09 audit found 14 of them against deleted test sites.\n *\n * A collection-group query rather than a walk of the org's members, because\n * the staff alerts land in inboxes that are not members of the org. That\n * query needs the `notifications.hostId` COLLECTION_GROUP override in\n * `cloud/firebase-firestore.indexes.json`.\n *\n * Best-effort, like every other trailing cleanup in `eraseHost`.\n */\nasync function eraseHostNotifications(hostId: string): Promise<number> {\n if (!hostId) return 0\n try {\n const firestore = firebaseAdmin.app().firestore()\n const rows = await firestore\n .collectionGroup('notifications')\n .where('hostId', '==', hostId)\n .get()\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) {\n batch.delete(doc.ref)\n }\n await batch.commit()\n }\n return rows.size\n } catch (error) {\n console.error(`eraseHost: notification cleanup failed for ${hostId}`, error)\n return 0\n }\n}\n\n/**\n * Destroy the org documents that belong to the site (AGL-3273).\n *\n * Some plugin storage is the organization's and names the site each document\n * belongs to — Marketing's email sends, `orgs/{orgId}/campaigns`, each naming\n * the site it was sent as. The `recursiveDelete(hosts/{hostId})` below does\n * not reach them, and they are still the site's: a send's sender, unsubscribe\n * page and the consent it relied on were that site's, and a send addressed to\n * a hand-typed list carries those addresses.\n *\n * Which collections, and which field names the site, is each plugin's own\n * declaration (`orgCollections` in `plugins.config.json`, read through\n * `listPluginOrgCollections`): a declaration with a `siteField` is a\n * collection whose documents belong to one site. One without — a campaign\n * container, placed on sites rather than owned by one — is left alone. Each\n * document goes with its subcollections, which is why this is a recursive\n * delete per document.\n *\n * Best-effort, like every other trailing cleanup in `eraseHost`, and per\n * collection, so one failed query leaves the others' cleanup standing.\n */\nasync function eraseHostOwnedOrgDocuments(orgId: string, hostId: string): Promise<number> {\n if (!orgId || !hostId) return 0\n const firestore = firebaseAdmin.app().firestore()\n let erased = 0\n for (const declared of listPluginOrgCollections()) {\n if (!declared.siteField) continue\n try {\n const rows = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(declared.name)\n .where(declared.siteField, '==', hostId)\n .get()\n for (const doc of rows.docs) await firestore.recursiveDelete(doc.ref)\n erased += rows.size\n } catch (error) {\n console.error(\n `eraseHost: ${declared.name} cleanup failed for ${hostId}`,\n error,\n )\n }\n }\n return erased\n}\n\n/**\n * Destroy the site's rows in every top-level plugin collection keyed by it\n * (AGL-4214): a register's customer-display state, pairing codes and tokens.\n *\n * Bounded by the declared field, like every top-level sweep here, because each\n * of these collections holds every other site's rows too. Best-effort and per\n * collection, like every other trailing cleanup in `eraseHost`, so one failed\n * query leaves the others' cleanup standing.\n */\nasync function erasePluginHostKeyedCollections(hostId: string): Promise<number> {\n let erased = 0\n for (const { name, siteField } of PLUGIN_HOST_KEYED_COLLECTIONS) {\n try {\n erased += await deleteDocsByOrgId(name, hostId, false, siteField)\n } catch (error) {\n console.error(`eraseHost: ${name} cleanup failed for ${hostId}`, error)\n }\n }\n return erased\n}\n\n/** What deleting a site takes with it, plugin by plugin (AGL-4003). */\nexport interface HostErasePreview {\n /**\n * Each plugin's resources shared with the site: the ones that go, with how\n * many items each holds, and how many stay. `preview: null` is a plugin\n * that could not answer, so the list is incomplete.\n */\n resources: PluginSiteResourcePreviewRow[]\n}\n\n/**\n * What the Delete site card shows before it asks (AGL-4003): the resources\n * plugins share with the site alone, which go with it — a dataset and its\n * records — and how many shared ones stay. Asked of the same erasers\n * {@link eraseHost} runs, so the list is what the delete does. Reads only.\n */\nexport async function previewHostErase(\n orgId: string,\n hostId: string,\n): Promise<HostErasePreview> {\n return { resources: await previewPluginSiteResources({ orgId, hostId }) }\n}\n\n/**\n * Permanently erase a single site and everything it owns (AGL-488).\n * Unlike deleting the host doc alone (which orphans data), this cleans up\n * every trailing reference:\n * - Storage objects under `hosts/{hostId}/` (media, CDN variants),\n * - the `hostIndex/{hostId}` routing entry (subdomain/cname resolution),\n * - the owning org's `hosts` routing-map entry, and\n * - the host's Firestore tree (screens, layouts, versions, counters, …)\n * via `recursiveDelete`.\n *\n * Shared by the self-serve delete-site route and the org-erasure pipeline\n * (AGL-487). Fail-soft on Storage/index cleanup so a partial failure never\n * blocks the Firestore delete; safe to re-run.\n */\nexport interface EraseHostOptions {\n /**\n * The console-side sending-domain teardown, injected because this library\n * may not hold the credentials it needs — see `sending-domain-debt.ts`.\n *\n * Absent, the site's domain is not released inline: the debt is recorded on\n * the surviving label claim and `/api/admin/reap-sending-domains` settles\n * it. That is the only correct default here. A library the tenant runtime\n * imports cannot reach a full-access mail credential, and an erasure must\n * not fail or stall because a vendor is unreachable.\n */\n tearDownSendingDomain?: TeardownSendingDomainDriver | null\n /**\n * Erase the site even while its consent group still needs it (AGL-3320).\n *\n * Only the organization's own erasure passes this: it takes every site and\n * the declaration with them, so no sibling is left to read the refusals.\n * Every other caller is refused with {@link SiteInConsentGroupError} for a\n * site that is in a declared group or in a change still running — its\n * opt-outs are read by its siblings, and erasing them would start mailing\n * people who said no.\n */\n allowInConsentGroup?: boolean\n}\n\n/**\n * {@link eraseHost} refused a site its consent group still needs (AGL-3320).\n * Nothing was erased; the site leaves its group, and is deleted after.\n */\nexport class SiteInConsentGroupError extends Error {\n readonly hostId: string\n readonly hold: ConsentGroupSiteHold\n\n constructor(hostId: string, hold: ConsentGroupSiteHold) {\n super(\n hold.reason === 'grouped'\n ? `Site ${hostId} is in the consent group \"${hold.name}\"; remove it from the group before deleting it`\n : `Site ${hostId} is in a consent group change that has not finished`,\n )\n this.name = 'SiteInConsentGroupError'\n this.hostId = hostId\n this.hold = hold\n }\n}\n\nexport interface EraseHostResult {\n /** What became of the site's dedicated sending domain, if it had one. */\n sendingDomain: SendingDomainDisposition\n}\n\nexport async function eraseHost(\n hostId: string,\n options: EraseHostOptions = {},\n): Promise<EraseHostResult> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n const orgId = hostSnapshot.get('orgId') as string | undefined\n // Everyone holding a role on the site itself, org member or not: each has a\n // `users/{uid}/hostMemberships/{hostId}` row the switcher and the console's\n // address resolution read, so each must lose it with the site.\n const hostMemberUids = Object.keys(\n (hostSnapshot.get('memberRoles') as Record<string, unknown> | undefined) ??\n {},\n )\n\n /*==========================================\n * A SITE ITS CONSENT GROUP STILL NEEDS IS NOT ERASED (AGL-3320).\n *\n * Asked before anything is destroyed. A grouped site's opt-outs are read by\n * every site in its group, so erasing them would let its siblings mail the\n * people who unsubscribed here, and would leave the declaration naming a\n * site that no longer exists. The site leaves the group first — the change\n * that removes it carries its refusals to the sites that stay.\n *=========================================*/\n if (orgId && options.allowInConsentGroup !== true) {\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const hold = consentGroupSiteHold(\n (orgSnapshot.data() ?? null) as Record<string, unknown> | null,\n hostId,\n )\n if (hold) throw new SiteInConsentGroupError(hostId, hold)\n }\n\n /*==========================================\n * THE SENDING DOMAIN, READ FIRST AND RELEASED LAST.\n *\n * Read here because the pinned label lives on the host document and the\n * `recursiveDelete` at the bottom of this function destroys it. Read\n * afterwards there would be nothing left to say WHICH provider domain holds\n * a plan-capped account slot and WHICH records in our zone carry a signing\n * key for a name a future site can claim.\n *\n * Released after everything else, so a teardown that dies partway leaves the\n * claim standing and the domain findable rather than orphaning two vendors'\n * resources with nothing pointing at them.\n *=========================================*/\n const sendingLabel = String(hostSnapshot.get('sendingLabel') ?? '').trim()\n const sendingTeardown = sendingLabel\n ? await readSendingDomainTeardownByLabel(sendingLabel).catch(() => null)\n : null\n\n // Storage first (best-effort — the object tree is derived, regenerable).\n try {\n await storageBucket().deleteFiles({ prefix: `hosts/${hostId}/` })\n } catch (error) {\n console.error(`eraseHost: storage cleanup failed for ${hostId}`, error)\n }\n // And the delivery provider's copies of the site's video (AGL-2824), held\n // under the same library prefix. Nothing runs when no provider is\n // configured to store; a failure is logged, like the bucket's.\n await eraseMediaDeliveryScope({ collection: 'hosts', scopeId: hostId })\n\n // Dead-lettered supplier deliveries (AGL-1448). See the note on\n // SUPPLIER_DELIVERY_COLLECTION below for why this is here and not implied\n // by the recursiveDelete at the end of this function.\n await eraseHostSupplierDeliveries(hostId)\n // In-app notifications about the site, in every inbox (AGL-3719).\n await eraseHostNotifications(hostId)\n\n // Routing: the middleware resolves a request to a host via hostIndex and\n // the owning org's hosts map — drop both so the subdomain/cname 404s.\n await firestore\n .collection('hostIndex')\n .doc(hostId)\n .delete()\n .catch(() => undefined)\n if (orgId) {\n // The routing entry and the site's POOLED SEATS go in the SAME write —\n // POS registers (AGL-1775) and collaborators (AGL-2439), which are the\n // same mechanism on two keys and must be released together or a deleted\n // site strands one pool while returning the other.\n //\n // `registerAllocations[hostId]` is capacity the org has\n // paid for and assigned here; a deleted site must return it to the pool\n // or the org keeps paying $89/mo for a seat pinned to a site that no\n // longer exists and cannot be reassigned from any surface. Releasing it\n // by deleting the key rather than by decrementing a counter means the\n // pool is `purchased - sum(allocations)` by arithmetic and has nothing to\n // drift out of step with.\n await firestore\n .collection('orgs')\n .doc(orgId)\n .set(\n {\n hosts: { [hostId]: FieldValue.delete() },\n registerAllocations: { [hostId]: FieldValue.delete() },\n collaboratorAllocations: { [hostId]: FieldValue.delete() },\n },\n { merge: true },\n )\n .catch(() => undefined)\n // Drop every member's reverse-index row for this host (AGL-844); the\n // members still exist here (recursiveDelete of the org, if any, is later).\n await deleteHostProjectionForAllMembers(\n orgId,\n hostId,\n hostMemberUids,\n ).catch((error) => {\n console.error(`eraseHost: projection cleanup failed for ${hostId}`, error)\n })\n await eraseHostOwnedOrgDocuments(orgId, hostId)\n // Before the plugins decide what is this site's own: a document shared with\n // all sites except some and reaching only this site comes off it here, so\n // it reads as the workspace's and stays (AGL-4047). Never throws.\n await sweepScopeSharingAfterSiteChange({ orgId, reason: 'site-removed', hostId })\n // What plugins share with this site alone — a dataset and its records —\n // and this site's place in the sharing of what it shares with others\n // (AGL-4003). Each plugin's share is isolated and never throws here.\n await erasePluginSiteResources({ orgId, hostId })\n }\n\n // The host document tree (screens/layouts/versions/counters/products/…).\n await firestore.recursiveDelete(hostRef)\n\n // The plugin rows keyed by the site that its tree does not hold (AGL-4214).\n // After the tree, so a register's display can no longer verify against it.\n await erasePluginHostKeyedCollections(hostId)\n\n // Once more now the site is gone: a membership sync that was mid-flight when\n // the first pass ran can write the row back afterwards, and a row for a\n // deleted site keeps it in the switcher and mapped to its subdomain. Last\n // thing that touches the rows, so nothing can follow it.\n await deleteHostProjectionForUids(hostId, hostMemberUids).catch(\n () => undefined,\n )\n\n // The site's names no longer serve it (AGL-3629): plugins undo what they\n // registered for each — commerce's Stripe payment method domains. Raised\n // after the delete, so a plugin checking whether ANOTHER site still serves\n // the name cannot find this one.\n for (const domain of releasedHostNames(hostSnapshot.data())) {\n await runPluginEventHandlers('host.domain.released', {\n orgId: orgId ?? null,\n hostId,\n domain,\n reason: 'site-deleted',\n })\n }\n\n // Never throws, and never leaves the slot unaccounted for: whatever the\n // vendors refuse is recorded on the label claim for the reaper to finish.\n return {\n sendingDomain: await disposeHostSendingDomain({\n teardown: sendingTeardown ? { ...sendingTeardown, hostId } : null,\n tearDown: options?.tearDownSendingDomain,\n }),\n }\n}\n\n/**\n * Delete a single resource document *and everything under it* (AGL-945).\n *\n * Firestore does not cascade: deleting `orgs/{o}/datasets/{d}` leaves every\n * `records/{r}` beneath it alive but unreachable from the console — still\n * billed, still matched by the rules (which match subcollection paths\n * independently of the parent), and resurrected wholesale if the parent id\n * is ever reused. Only the Admin SDK has `recursiveDelete`, so the console\n * cards route their deletes through /api/resources/erase, which lands here.\n *\n * Authorization belongs to the caller — this only walks the tree.\n */\nexport async function eraseSubtree(\n path: readonly [string, string, string, string],\n): Promise<void> {\n const firestore = firebaseAdmin.app().firestore()\n const [scope, scopeId, kind, id] = path\n await firestore.recursiveDelete(\n firestore.collection(scope).doc(scopeId).collection(kind).doc(id),\n )\n}\n\n/**\n * The collections the page-view beacon writes under `hosts/{hostId}`\n * (`apps/tenant/app/api/analytics/collect/route.ts`), with `set(…, merge)`.\n */\nexport const HOST_BEACON_COLLECTIONS: readonly string[] = [\n 'analytics',\n 'screenAnalytics',\n]\n\nexport interface ReapHostBeaconRemnantsResult {\n /** Phantom `hosts/{id}` trees removed. */\n reaped: string[]\n /** Phantoms holding anything else — left for a person to look at. */\n left: Array<{ hostId: string; collections: string[] }>\n}\n\n/**\n * Remove what a deleted site's late beacons wrote after `eraseHost` (AGL-3744).\n *\n * The beacon trusts a positive host-exists read for an hour per instance, so\n * a tab left open on a site that is then deleted still lands its dwell or\n * page view, and the merge-write recreates `hosts/{id}/analytics/{day}` or\n * `screenAnalytics/{screenId}:{day}` under a host with no document. Nothing\n * reads those again, and nothing else would ever delete them: a 2026-10-12\n * audit found one standing three days after its site was erased.\n *\n * A host document is written before any beacon can count for it, so a\n * missing document whose only children are the beacon's own counters is a\n * deleted site and nothing else. A phantom holding any other collection is\n * not this leak and is reported, never deleted.\n *\n * `listDocuments` lists every host id once, which is a run's whole cost.\n */\nexport async function reapHostBeaconRemnants(\n options: { dryRun?: boolean } = {},\n): Promise<ReapHostBeaconRemnantsResult> {\n const firestore = firebaseAdmin.app().firestore()\n const result: ReapHostBeaconRemnantsResult = { reaped: [], left: [] }\n const refs = await firestore.collection('hosts').listDocuments()\n for (let index = 0; index < refs.length; index += 300) {\n const snapshots = await firestore.getAll(...refs.slice(index, index + 300))\n for (const snapshot of snapshots) {\n if (snapshot.exists) continue\n const collections = (await snapshot.ref.listCollections()).map(\n (collection) => collection.id,\n )\n if (!collections.every((id) => HOST_BEACON_COLLECTIONS.includes(id))) {\n result.left.push({ hostId: snapshot.id, collections })\n continue\n }\n if (!options.dryRun) await firestore.recursiveDelete(snapshot.ref)\n result.reaped.push(snapshot.id)\n }\n }\n return result\n}\n\n/** Best-effort Stripe customer deletion — PII lives at the processor too. */\nasync function deleteStripeCustomer(customerId?: string): Promise<void> {\n const key = process.env.STRIPE_SECRET_KEY\n if (!key || !customerId) return\n try {\n await fetch(`https://api.stripe.com/v1/customers/${customerId}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${key}` },\n })\n } catch (error) {\n console.error(`eraseOrg: Stripe customer ${customerId} delete failed`, error)\n }\n}\n\n/**\n * Delete every API credential the org owns (AGL-1444).\n *\n * `apiKeys` is a TOP-LEVEL collection keyed by the SHA-256 of the token and\n * carrying `orgId` as a FIELD, so `recursiveDelete(orgRef)` cannot see it —\n * a path-scoped cascade is structurally blind to anything not under the path.\n * The credential therefore outlived the workspace: `verifyApiKey` kept\n * resolving the token to a live principal naming an org that no longer\n * existed. `authenticateApiV1` happens to refuse it (it reads the org doc and\n * 401s), but that is a gate one layer above the credential, and a key whose\n * revocation depends on every future caller repeating a lookup is not\n * revoked. The document is also a small record of the erased workspace in its\n * own right — a human-authored label, the creating uid, the granted scopes.\n *\n * Bounded by the `orgId` field, never a collection sweep: this collection\n * holds every other customer's integration credentials too.\n *\n * Returns the number destroyed, for the audit row — an erasure trail that\n * understates what it removed is the one record that has to be right.\n */\nasync function eraseOrgApiKeys(orgId: string, dryRun = false): Promise<number> {\n return deleteDocsByOrgId('apiKeys', orgId, dryRun)\n}\n\n/**\n * Sweep every top-level plugin collection keyed by this org (AGL-3080).\n *\n * The collections are the plugins' own, DECLARED by each owner in\n * `plugins.config.json` (`orgKeyedCollections`) and compiled into core, so the\n * sweep names none of them and runs in every process whether or not the\n * owner is loaded. Sequential and field-bounded like every other org-keyed\n * sweep: each of these collections holds every other workspace's rows too.\n *\n * Returns the count destroyed per collection, for the audit row.\n */\nasync function erasePluginOrgKeyedCollections(\n orgId: string,\n dryRun = false,\n): Promise<Record<string, number>> {\n const counts: Record<string, number> = {}\n for (const { name, orgField } of PLUGIN_ORG_KEYED_COLLECTIONS) {\n counts[name] = await deleteDocsByOrgId(name, orgId, dryRun, orgField)\n }\n return counts\n}\n\n/**\n * Delete every document in a TOP-LEVEL collection that names this org in its\n * `orgId` FIELD (AGL-1444/AGL-1448). `orgField` names another field, which is\n * how a site delete sweeps the collections keyed by a site (AGL-4214).\n *\n * The shared mechanism behind every collection a path-scoped cascade cannot\n * see. Two properties are the whole point, and neither is optional:\n *\n * - **Bounded by the field, never a collection sweep.** Every one of these\n * collections holds other customers' credentials, routing and billing\n * correlations. A `collection(name).get()` here would erase the estate.\n * - **Chunked**, because a batch caps at 500 writes and nothing bounds an\n * org's row count below that.\n *\n * Returns the number destroyed, for the audit row — an erasure trail that\n * understates what it removed is the one record that has to be right.\n *\n * `dryRun` runs the query and skips the commit (AGL-1481), so a plan counts\n * rows through the SAME function that deletes them. A separate counting pass\n * would be a second enumeration of the sweep list, which is precisely the\n * divergence AGL-1481 exists to remove.\n *\n * **`platformRevenue` must NEVER be added to this sweep (AGL-1811).** It is\n * org-keyed by field — exactly the shape this mechanism eats — and that is\n * the trap: those rows are per-transaction TAX FILING RECORDS (gross, tax,\n * jurisdiction) with a statutory retention obligation, and the quarterly\n * Texas return is their sum. GDPR Art. 17(3)(b) exempts them: erasure does\n * not extend to records retained for compliance with a legal obligation. An\n * erased org's rows deliberately outlive it — the\n * `erase-org-tax-retention.emulator.spec` pins survival, so an over-eager\n * future sweep fails a test instead of un-filing a tax period.\n *\n * **`storefrontTaxCollected` must NEVER be added either (AGL-1904).** Same\n * shape, same trap, same reason: it carries `orgId` as a field, and its rows\n * are the record of sales tax charged to shoppers on that org's storefront —\n * including the tax a `mode: 'stripe'` store collects under AGLYN's own\n * Texas registration, which Aglyn must be able to account for long after the\n * merchant has gone.\n *\n * **`posHardwareSales` must NEVER be added either (AGL-4038).** Same shape,\n * same trap: one row per card reader order a workspace bought from the\n * platform's hardware shop — the platform's OWN sale, on which it owes the\n * sales tax. The order under `orgs/{orgId}/hardwareOrders`, with the buyer's\n * name, street, phone and email, dies with the tree as it should; the row\n * keeps only the lines, amounts, tax, Stripe ids, status dates and the\n * country, state and postal code it shipped to. The\n * `erase-org-tax-retention.emulator.spec` pins its survival too.\n */\nasync function deleteDocsByOrgId(\n collection: string,\n orgId: string,\n dryRun = false,\n orgField = 'orgId',\n): Promise<number> {\n if (!orgId) return 0\n const firestore = firebaseAdmin.app().firestore()\n const rows = await firestore\n .collection(collection)\n .where(orgField, '==', orgId)\n .get()\n if (dryRun) return rows.size\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) batch.delete(doc.ref)\n await batch.commit()\n }\n return rows.size\n}\n\n/**\n * Drop the org's public SSO routing documents (AGL-1448).\n *\n * `ssoDomains/{domain}` is keyed by the DOMAIN and carries `orgId` as a field,\n * so `recursiveDelete(orgRef)` never reaches it. The org's own claims under\n * `orgs/{orgId}/ssoDomains/{domain}` do die with the tree; the public routing\n * doc — the one that decides where a sign-in goes — does not.\n *\n * **`unpublishSsoDomains` is not the fix, though it looks like it.** That\n * function is the reversible half of the console's SSO toggle: it sets\n * `active: false` and leaves the document standing precisely so re-enabling\n * restores the same pool and the same uids. Applied to an erasure it would\n * leave behind a record naming the deleted org, its GCIP tenant and provider\n * ids, its IdP display name and the customer's email domain — and, worse, a\n * live reservation: `issueDomainClaim` refuses a domain whose `ssoDomains` doc\n * belongs to another org REGARDLESS of `active`, so a ghost would hold a real\n * customer's domain against them with no way to appeal. Absence is the only\n * state that both stops the routing and releases the name.\n *\n * Deleting is safe on the read side: `/api/auth/sso-lookup` already treats a\n * missing doc and an inactive one identically (`{ ssoEnabled: false }`).\n */\nasync function eraseOrgSsoDomains(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n return deleteDocsByOrgId('ssoDomains', orgId, dryRun)\n}\n\n/**\n * Release every custom console domain the org holds (AGL-1448).\n *\n * `releaseConsoleDomain` already does exactly the right thing and was called\n * from nothing but its own spec. It is wired rather than reimplemented, and\n * the ordering it enforces is the reason: Vercel detach FIRST, documents\n * second, and the claim KEPT if a detach fails. `resolveConsoleDomain`'s\n * `unknown` verdict — the one that lets localhost, previews and self-hosted\n * installs work — is only safe while every name the console project still\n * answers for has a document (AGL-1430). Deleting the claim here directly\n * would break that correspondence and hand the name to the next org that\n * claims it, with Vercel's `already-exists` reading as health.\n *\n * It takes one domain, so the org-bounded query is the part that was missing.\n * Every name in a claim set — the primary and its `www` twin — carries the\n * same `orgId` and the same `primaryHost`, so releasing once per distinct\n * primary covers the set exactly, without a second pass over the twins.\n *\n * Best-effort, like every other external cleanup here: an erasure must not\n * fail because Vercel did. A name that could not be detached keeps its claim\n * and is reported in the audit row as un-released.\n */\nasync function releaseOrgConsoleDomains(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n const firestore = firebaseAdmin.app().firestore()\n const claims = await firestore\n .collection(CONSOLE_DOMAINS_COLLECTION)\n .where('orgId', '==', orgId)\n .get()\n const primaries = new Set(\n claims.docs.map((doc) => (doc.get('primaryHost') as string) || doc.id),\n )\n // A plan counts the claim sets it WOULD release. `releaseConsoleDomain`\n // detaches at Vercel, so it must not run for a dry run (AGL-1481).\n if (dryRun) return primaries.size\n let released = 0\n for (const domain of primaries) {\n const result = await releaseConsoleDomain({ orgId, domain }).catch(\n (error) => {\n console.error(`eraseOrg: console domain ${domain} release failed`, error)\n return { released: false }\n },\n )\n if (result.released) released += 1\n }\n return released\n}\n\n/**\n * Drop the local Stripe reverse index (AGL-1448, AGL-1028).\n *\n * `stripeCustomers/{stripeCustomerId} -> { orgId }` exists because AGL-1028\n * moved `stripeCustomerId` off the org doc into a manager-gated subcollection,\n * which broke the webhook's `where('stripeCustomerId', '==', …)` lookup. It is\n * denied to every client for one reason, stated in the rules: readable, it\n * maps a billing identity back to a workspace.\n *\n * The erasure had this exactly inverted. It deleted the customer AT STRIPE and\n * kept the local index — so the artefact that survived was the correlation the\n * whole issue existed to prevent, now pointing at an org that no longer exists\n * to be gated on. This deletes the local rows. The Stripe-side delete is\n * unchanged and still runs: PII lives at the processor too, and one is not a\n * substitute for the other.\n *\n * Bounded by the `orgId` field rather than by the org's CURRENT customer id,\n * because nothing cleans up the index when a customer id changes — an org that\n * was re-created in Stripe has more than one row pointing at it.\n */\nasync function eraseOrgStripeIndex(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n return deleteDocsByOrgId('stripeCustomers', orgId, dryRun)\n}\n\n/**\n * Drop the org's REST API replay keys (AGL-1448).\n *\n * `apiIdempotency/{sha256(orgId:key)}` dedupes `POST`s by `Idempotency-Key`\n * (AGL-618). Low severity — a replay key names an org and a record id and\n * authorises nothing — but it does NOT age out on its own, which is the part\n * worth writing down because the assumption runs the other way: the only TTL\n * policy on the database is `rateLimits.expiresAt`\n * (`docs/FIRESTORE_MANUAL_CONFIG.md`), and these documents carry no expiry\n * field for a policy to key on. Left alone they accumulate against a dead org\n * indefinitely.\n *\n * Taken with the credentials rather than at the end: the record ids they carry\n * point into the org tree that step 4 destroys.\n */\nasync function eraseOrgIdempotencyKeys(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n return deleteDocsByOrgId('apiIdempotency', orgId, dryRun)\n}\n\n/**\n * Release every slug the org has EVER held (AGL-1448).\n *\n * The erasure deleted `orgSlugs/{org.slug}` — the current name only. But\n * `changeOrgSlug` leaves a tombstone at the previous slug (`{ orgId, movedTo,\n * renamedAt }`) so old workspace URLs keep redirecting (AGL-585/AGL-236), and\n * nothing ever collected them. Every historical name an org held therefore\n * survived its erasure, in the one collection the rules make\n * `allow read: if true` — public because it doubles as the pre-auth health\n * probe. An erased workspace's naming history stayed world-readable, each\n * tombstone still naming the dead org id.\n *\n * Bounded by the `orgId` field, which is exactly the right boundary here and\n * not merely the safe one: claiming a tombstoned slug FULL-REPLACES the\n * document with the new owner's `{ orgId }`, so a name this org renamed away\n * from and somebody else has since taken does not match — and must not be\n * swept, because it is now a live tenant's reservation.\n *\n * The current slug is unioned in rather than assumed present: an org whose\n * reservation was lost to a legacy write would otherwise keep its workspace\n * subdomain attached to the project. ⛔ ONLY WHEN NOBODY HOLDS IT (AGL-2585).\n * A workspace address taken by an unverified signup is a reservation that\n * lapses, and a live workspace may since have claimed the name — at which\n * point `orgSlugs/{slug}` names THAT org, and the erasure of this one would\n * otherwise delete a working tenant's reservation and detach their subdomain.\n * The `orgId` query above already refuses that document; this is the one line\n * that used to add it back by assumption.\n *\n * Each name's `{slug}.aglyn.com` is detached too. `changeOrgSlug` deliberately\n * KEEPS the old subdomain attached so the tombstone's 308 has a hostname to\n * run on; once the tombstone goes, the attachment is a name resolving to a\n * console for an org that does not exist. Best-effort, like every other\n * external cleanup here: an erasure must not fail because a DNS API did.\n */\nasync function eraseOrgSlugs(\n orgId: string,\n currentSlug?: string,\n dryRun = false,\n): Promise<number> {\n const firestore = firebaseAdmin.app().firestore()\n const held = await firestore\n .collection('orgSlugs')\n .where('orgId', '==', orgId)\n .get()\n const slugs = new Set(held.docs.map((doc) => doc.id))\n if (currentSlug && !slugs.has(currentSlug)) {\n // Absent means the reservation was lost and only the DNS attachment is\n // left to clean up. Present but not matched by the query above means it\n // belongs to another org now, and is not this erasure's to touch.\n const reservation = await firestore\n .collection('orgSlugs')\n .doc(currentSlug)\n .get()\n .catch(() => null)\n if (reservation && !reservation.exists) slugs.add(currentSlug)\n }\n // `detachWorkspaceDomain` calls a live DNS API — never on a plan (AGL-1481).\n if (dryRun) return slugs.size\n for (const slug of slugs) {\n await firestore.collection('orgSlugs').doc(slug).delete().catch(() => undefined)\n await detachWorkspaceDomain(slug).catch(() => undefined)\n }\n return slugs.size\n}\n\n/**\n * Sweep up ORPHANED `hostIndex` rows the per-host loop cannot enumerate\n * (AGL-1448).\n *\n * `hostIndex/{hostId}` is `{ orgId, subdomain }` and `allow read: if\n * isSignedIn()`. It is deleted today inside `eraseHost`, which `eraseOrg`\n * calls once per document in `hosts where orgId == org` — so the row is\n * reached DERIVATIVELY, through a second collection, and only for as long as\n * the two agree.\n *\n * **The erasure is itself one of the ways they stop agreeing.** `eraseHost`'s\n * `hostIndex` delete is `.catch(() => undefined)` — fail-soft on purpose, so\n * a transient failure never blocks the Firestore delete — and the very next\n * statement `recursiveDelete`s `hosts/{hostId}`. The instant that lands, the\n * orphaned index row is unreachable from the org side forever: nothing points\n * at it, so neither this run nor any retry can ever enumerate it again. A\n * fail-soft that manufactures a PERMANENT orphan is not fail-soft, and the\n * residue is a signed-in-readable row naming a dead org and the subdomain its\n * customer chose.\n *\n * Bounded by the `orgId` field — this is the table the middleware resolves\n * every request on, so an unbounded sweep here does not lose an index, it\n * takes the estate offline.\n *\n * A BACKSTOP, not a replacement: the per-host loop still does the real work\n * (Storage, the org routing map, the member projections, the host tree). This\n * only collects what that loop structurally cannot see.\n */\nasync function eraseOrgHostIndex(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n return deleteDocsByOrgId('hostIndex', orgId, dryRun)\n}\n\n/**\n * Sweep up `hostMemberships` projections belonging to FORMER members\n * (AGL-1448).\n *\n * `users/{uid}/hostMemberships/{hostId}` carries `{ orgId, subdomain,\n * displayName, nameLower, role }` — the site switcher's row. It lives under a\n * USER, so `recursiveDelete(orgs/{orgId})` cannot reach it, and `eraseOrg`'s\n * members loop only walks `orgs/{orgId}/members`.\n *\n * `deleteHostProjectionForAllMembers(orgId, hostId)` clears the row for\n * everyone in that member list at the moment the erasure runs. **A former\n * member is not in it.** Their row is written by the projection fan-out and\n * removed by `removeOrgMember`, which is fail-soft in the same way as\n * everything else on that path; one missed fan-out leaves a row no later\n * erasure can find, because the enumeration starts from a membership that no\n * longer exists. The erased workspace's site NAME and subdomain then live on\n * in the user document of somebody who left the company.\n *\n * ## This is a COLLECTION-GROUP query, and that owes an index\n *\n * `hostMemberships` has two composite indexes, both `queryScope: COLLECTION`.\n * A collection-group equality on `orgId` needs a `COLLECTION_GROUP`\n * single-field index, which Firestore does NOT create automatically — the\n * automatic single-field indexes are collection-scoped except for\n * array-contains. `cloud/firebase-firestore.indexes.json` therefore gains a\n * `fieldOverrides` entry alongside the existing `members.uid` and\n * `messages.authorId` ones, and **it must be deployed by hand.**\n *\n * Until it is, the query throws `FAILED_PRECONDITION`. AGL-1793 is this\n * codebase's record of exactly that failure mode — both commerce crons\n * silently dead in production for want of a `COLLECTION_GROUP_ASC` override —\n * so this refuses to be the thing that kills an erasure. It is caught and\n * reported as `null`, which is deliberately NOT `0`: a zero would say \"there\n * was nothing to sweep\" and a missing index would wear that as a clean bill\n * of health. `null` in the audit row says \"attempted, could not run\", and the\n * spec asserts a NUMBER so the wired-and-indexed path is what is pinned.\n */\nasync function eraseOrgHostMemberships(\n orgId: string,\n dryRun = false,\n): Promise<number | null> {\n if (!orgId) return 0\n try {\n const firestore = firebaseAdmin.app().firestore()\n const rows = await firestore\n .collectionGroup('hostMemberships')\n .where('orgId', '==', orgId)\n .get()\n if (dryRun) return rows.size\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) {\n batch.delete(doc.ref)\n }\n await batch.commit()\n }\n return rows.size\n } catch (error) {\n console.error(\n `eraseOrg: hostMemberships projection sweep failed for ${orgId} — a missing COLLECTION_GROUP index on hostMemberships.orgId is the likeliest cause`,\n error,\n )\n return null\n }\n}\n\n/**\n * Destroy every support ticket the org opened, and the messages under each\n * (AGL-1971).\n *\n * `supportTickets/{id}` is top-level with `orgId` as a field — the exact shape\n * `deleteDocsByOrgId` exists for — and it was in neither sweep list. It is\n * also the highest-PII-density collection outside the org tree: `messages`\n * rows carry `authorId`, `authorEmail` and up to 5000 characters of prose a\n * customer wrote to us, which is where somebody pastes the invoice, the member\n * list, or the very data they are asking us to delete.\n *\n * **`deleteDocsByOrgId` is deliberately NOT used here**, though the query is\n * identical. It deletes documents, not subtrees, and a batch delete of the\n * ticket documents would leave every `messages` row alive under a parent that\n * no longer exists — the prose and the email surviving the delete that was\n * supposed to remove them, now unreachable by any query that starts from\n * `orgId`. `recursiveDelete` per ticket is the only correct shape.\n *\n * **No retention exception, and the alternative was considered.** A closed\n * support thread is arguable dispute evidence, which is the class of argument\n * that keeps `platformRevenue` alive (AGL-1811). It does not reach here: that\n * exemption is GDPR Art. 17(3)(b), *records retained to comply with a legal\n * obligation*, and no law requires us to keep a support thread — a Texas tax\n * return is filed from `platformRevenue`; nothing is filed from a ticket.\n * Live DPA §11 commits the other way in terms (\"delete or return Customer\n * Personal Data, except to the extent retention is required by law\"). What\n * remains as evidence is the `adminAudit` row: the erasure happened, when, at\n * whose instruction, and how many tickets it destroyed — ids and counts,\n * never content (AGL-1443).\n *\n * Sequential rather than parallel: `recursiveDelete` is itself a bulk writer,\n * and fanning N of them out at once is how a 60-second cron loses an erasure.\n */\nasync function eraseOrgSupportTickets(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n if (!orgId) return 0\n const firestore = firebaseAdmin.app().firestore()\n const tickets = await firestore\n .collection('supportTickets')\n .where('orgId', '==', orgId)\n .get()\n if (dryRun) return tickets.size\n for (const ticket of tickets.docs) {\n await firestore.recursiveDelete(ticket.ref)\n }\n return tickets.size\n}\n\n/**\n * The steps of `eraseOrg` after the hold check, named so a failed attempt can\n * say WHERE it stopped (AGL-1455).\n *\n * `export` used to lead this list, and its removal is the AGL-1443 change: an\n * erasure no longer writes anything before it starts deleting, so there is no\n * longer a step whose meaning is \"nothing is gone yet\". `credentials` is now\n * the first thing that can fail, and it destroys as it goes.\n */\ntype EraseStep =\n | 'plugins'\n | 'credentials'\n | 'support'\n | 'hosts'\n | 'org-storage'\n | 'stripe'\n | 'members'\n | 'org-tree'\n | 'slugs'\n\n/**\n * The two things an OPERATOR needs that a served caller does not (AGL-1481).\n *\n * `tools/scripts/erase-tenant.mjs` is the manual path staff reach for when the\n * cron is stuck. It used to be a second implementation of this function, and it\n * drifted: by the time AGL-1481 was filed it was missing four sweeps added that\n * week and still wrote a complete dump of the workspace to the operator's\n * working directory. The fix is that it CALLS this function — which means the\n * capabilities it had and this function lacked have to live here instead.\n *\n * Neither is a hold bypass, deliberately. The script refused to run before the\n * 7-day hold elapsed and this function refuses too; an `ignoreHold` flag would\n * have been the easy way to keep the two paths identical and is the one\n * difference worth preserving as a refusal on both.\n */\nexport interface EraseOrgOptions {\n /**\n * Count what an erasure WOULD destroy and destroy nothing. Every sweep runs\n * its query and skips its write, so the plan is produced by the same list of\n * sweeps that the erasure is — a separate counting pass would be exactly the\n * second enumeration this issue removed. Nothing external is touched (no\n * Storage, no Stripe, no Vercel, no DNS) and no audit row is written.\n *\n * Returns `ok: false` with `skippedReason: 'dry-run'`: `ok` means the org was\n * erased, and a plan did not erase it. A caller that treats a plan as an\n * erasure is the one mistake this shape has to make impossible.\n */\n dryRun?: boolean\n /**\n * Who is answerable for this erasure, for the audit row. Defaults to the\n * cron. A staff member running the script by hand is not the scheduler, and\n * an erasure trail that says otherwise names the wrong actor for the single\n * most irreversible action the platform performs.\n */\n actorUid?: string\n /**\n * The console-side sending-domain teardown, passed through to every host\n * this erasure destroys. See {@link EraseHostOptions.tearDownSendingDomain}.\n *\n * Never consulted on a dry run: a plan touches no vendor.\n */\n tearDownSendingDomain?: TeardownSendingDomainDriver | null\n /**\n * Erase a workspace that carries NO erasure request at all (AGL-2585).\n *\n * ⛔ EXACTLY ONE CALLER, and the option exists so that caller has to say so\n * out loud. `/api/admin/reap-unverified-orgs` collects workspaces created by\n * a signup whose address was never confirmed — there is nobody to ask for an\n * erasure, because nobody has been shown to exist. Every other path reaches\n * this function through `erasureRequestedAt`, which is a person's decision\n * with a seven-day hold on it, and none of them passes this.\n *\n * What it turns off is narrow and named: the `no-request` refusal and the\n * hold, and nothing else. Every sweep, every audit row and `dryRun` behave\n * identically — the caller supplies the proof that this workspace is\n * nobody's, and this records WHAT that proof was on the audit row.\n *\n * It does not skip the request when one exists. An org somebody has already\n * asked to erase is still that person's decision, and the reaper refuses\n * such an org before it ever gets here.\n */\n withoutRequest?: { reason: string } | null\n}\n\nexport interface EraseOrgResult {\n ok: boolean\n /**\n * Set when the org was NOT erased (flag missing, hold not elapsed, gone) —\n * and `'dry-run'` when nothing was erased because nothing was meant to be.\n */\n skippedReason?: string\n hosts?: number\n /** Member back-references cleaned up — reported so a plan can show them. */\n members?: number\n /** API credentials destroyed (AGL-1444) — outside the org path. */\n apiKeys?: number\n /**\n * What each plugin's workspace eraser did (AGL-2978), keyed by plugin id:\n * counts and flags, such as grants revoked at a provider. The erasers run\n * before anything below is deleted. **`null` means that plugin's eraser\n * failed** and its share may not be done; it is not zero. A plan carries\n * each eraser's count of what it would do.\n */\n plugins?: Record<string, PluginOrgErasureReport | null>\n /**\n * Rows destroyed from each plugin's top-level collection keyed by the org\n * (AGL-3080), keyed by collection: a connected mailbox's grant (AGL-2974),\n * a sequence email's tracking links (AGL-3297). Outside the org path, and\n * declared by their owners rather than named here.\n */\n pluginCollections?: Record<string, number>\n /** Public SSO routing docs destroyed (AGL-1448) — outside the org path. */\n ssoDomains?: number\n /** Custom console domains released (AGL-1448) — outside the org path. */\n consoleDomains?: number\n /** REST API replay keys destroyed (AGL-1448) — no TTL reaps these. */\n apiIdempotency?: number\n /** Local Stripe reverse-index rows destroyed (AGL-1448/AGL-1028). */\n stripeIndex?: number\n /** Slugs released — the current one AND every tombstone (AGL-1448). */\n slugs?: number\n /**\n * ORPHANED `hostIndex` rows collected (AGL-1448) — ones with no surviving\n * `hosts` document for the per-host loop to reach them through.\n */\n hostIndex?: number\n /**\n * `hostMemberships` projections collected (AGL-1448), including FORMER\n * members' rows that no membership list names.\n *\n * `null` means the sweep could not RUN — almost always the missing\n * `COLLECTION_GROUP` index on `hostMemberships.orgId`. Deliberately not\n * `0`: an erasure that could not reach a collection must not report the\n * same number as one that reached it and found nothing.\n */\n hostMemberships?: number | null\n /**\n * Support threads destroyed, each with its `messages` subtree (AGL-1971) —\n * the highest-PII-density collection outside the org path.\n */\n supportTickets?: number\n /**\n * What became of the erased sites' dedicated sending domains.\n *\n * `deferred` is the number an operator reads: those provider slots and zone\n * records are still held, the debt is on each label claim, and\n * `/api/admin/reap-sending-domains` is what settles them. The erasure itself\n * is complete either way — a vendor outage may delay a slot's release and\n * may not delay a deletion somebody has a legal right to.\n */\n sendingDomains?: {\n released: number\n deferred: number\n /** Shared pool members refused. Always 0; a non-zero is a real alarm. */\n protected: number\n }\n}\n\n/**\n * What an in-flight erasure has destroyed so far — counts only.\n *\n * `members` is excluded: the inventory already reports it as `before.members`\n * on both audit rows, and a second copy under `after` would say the same\n * number twice.\n */\ntype EraseProgress = Omit<EraseOrgResult, 'ok' | 'skippedReason' | 'members'>\n\n/**\n * A stable label for an error, carrying no free text (AGL-1455).\n *\n * The class name and the SDK's error code are enough to tell a Firestore\n * permission denial from a deadline exceeded from an out-of-memory kill. The\n * MESSAGE is deliberately not stored: a Firestore or Storage error quotes the\n * path — and sometimes the payload — it choked on, and this row lands in a\n * collection that must not become a second copy of what the erasure failed to\n * delete (AGL-1443). The full error still goes to `console.error`, which is\n * the log, not the record.\n */\nfunction errorLabel(error: unknown): string {\n const source = (error ?? {}) as { name?: unknown; code?: unknown }\n const parts = [source.name, source.code].filter(\n (part) => typeof part === 'string' || typeof part === 'number',\n )\n return parts.length ? parts.join(':') : 'unknown'\n}\n\n/**\n * Record a failed erasure attempt where somebody will actually find it\n * (AGL-1455).\n *\n * Aborting when the export cannot be written is correct and stays — the bug\n * was that the abort was invisible. `skippedReason` reached exactly one\n * place, the cron endpoint's HTTP response body, and nobody reads a\n * scheduler's 200. Meanwhile `erasureRequestedAt` stays set, so the same org\n * is retried on the next run and fails the same way indefinitely, and the\n * customer who requested the erasure is told nothing.\n *\n * An `adminAudit` row is the cheapest durable form and the one the success\n * path already uses, so the two read as a pair: same `actorUid`, same\n * `target`, same `before` inventory, and `after` carrying what actually\n * happened. Staff can find every stuck erasure by filtering the audit log on\n * the action, which is exactly the search that was impossible before.\n *\n * `after.exportWritten`/`after.exportPath` used to be the fields that\n * mattered here: they named the complete dump of a still-existing workspace\n * that a post-export failure left in the bucket. AGL-1443 removed the write,\n * so that state is no longer reachable and the fields no longer exist. What\n * replaces them is `after.requestedAt` — WHICH erasure request is stuck,\n * which the object's name used to be the only record of.\n *\n * Ids, counts, a step name and a timestamp. Never customer data.\n *\n * Best-effort and never throws: this runs while an erasure is already\n * failing, and losing the original error to a bookkeeping write would be\n * worse than losing the row.\n */\nasync function recordErasureFailure(entry: {\n orgId: string\n step: EraseStep\n error: unknown\n /** Whoever asked for the erasure — the cron, or a named operator. */\n actorUid: string\n /** Millis of the `erasureRequestedAt` this attempt was fulfilling. */\n requestedAt: number\n before: { hosts: number; members: number }\n after: Record<string, unknown>\n}): Promise<void> {\n await addAdminAudit(firebaseAdmin.app().firestore(), {\n actorUid: entry.actorUid,\n action: 'org.erase-failed',\n target: `orgs/${entry.orgId}`,\n before: entry.before,\n after: {\n failedStep: entry.step,\n error: errorLabel(entry.error),\n requestedAt: entry.requestedAt,\n ...entry.after,\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch((auditError) => {\n console.error(\n `eraseOrg: could not record the failed attempt for ${entry.orgId}`,\n auditError,\n )\n })\n}\n\n/**\n * Permanently erase an organization once its 7-day hold has elapsed\n * (AGL-485/487). Runs from the automated cron and the manual staff path.\n *\n * **Both of those are literally this function (AGL-1481).** The manual path,\n * `tools/scripts/erase-tenant.mjs`, used to be a second implementation, and a\n * second implementation of a cascade delete is a divergence with a schedule:\n * within a week of `eraseOrgApiKeys`, the SSO/console-domain release and the\n * org-keyed index sweeps landing here, the script was missing all four and\n * reporting success without them — leaving a live API credential, live domain\n * reservations, `orgSlugs` tombstones and the `stripeCustomers` reverse index\n * behind an erasure a human had been told was complete. The script now calls\n * this, and `EraseOrgOptions` is where the two capabilities it had and this\n * did not (a plan, and a named actor) live instead.\n *\n * Order matters and every step is defensive:\n * 1. Re-read the org and re-verify erasureRequestedAt + hold — never\n * delete on a stale/cancelled request.\n * 2. Nothing is written. This step used to persist a final JSON export of\n * the org and host trees to `erasures/{orgId}/…` and abort if it could\n * not — see the note below for why it is gone (AGL-1443).\n * 3. The plugins' erasers first (AGL-2978), while everything they may need\n * to act through still exists — a REQUIRED one (the marketplace's, which\n * erases the org's public publisher identity, AGL-1970) fails the step\n * rather than recording its share as undone. Then revoke the org's API\n * credentials (AGL-1444), its public routing — SSO domains and custom\n * console domains (AGL-1448) — and sweep every plugin collection keyed\n * by the org that its owner declared (a connected mailbox's OAuth grant,\n * AGL-2974). All of them are top-level collections keyed by something\n * other than a path under the org, so the org-tree delete cannot reach\n * them; doing them before the content delete also closes the mid-erasure\n * window, in which a credential, a domain or a public publisher page\n * still resolves to a half-deleted workspace.\n * 4. Delete each host (eraseHost), org-level Storage, the Stripe customer\n * AND its local reverse index, member back-references, then the org tree\n * and every slug the org ever held — tombstones included (AGL-1448).\n * 5. Audit.\n *\n * Every ending is audited, not just the successful one (AGL-1455). A throw\n * from any step writes an `org.erase-failed` row before re-throwing, because\n * `erasureRequestedAt` stays set on a failure: without a record the org is\n * retried and fails identically on every subsequent run, forever, and nothing\n * anywhere says so.\n *\n * **The erasure writes no copy of the workspace (AGL-1443).** It used to\n * persist `erasures/{orgId}/{requestedMs}.json` — and \"export\" understated\n * it: `exportDocTree` recursed `listCollections()` with no bound and copied\n * `snapshot.data()` wholesale, so the object was a complete verbatim copy of\n * the org tree and every host tree, carrying `webhooks.secret` (a plaintext\n * HMAC key), `orders.paymentLinkUrl` (a live bearer URL that lets its holder\n * pay), `screens.protection.passwordHash` and `ssoDomains.token`. It landed\n * on a prefix this function's own storage sweep does not cover, in a bucket\n * with no lifecycle rule, so the most sensitive object the platform can\n * produce outlived the request that deleted everything else — indefinitely,\n * unread, and belonging to a customer who had been told their workspace was\n * gone. Four facts decided it, and none of them is about tidiness:\n *\n * - **Nothing read it.** One producer, zero consumers in the repo; the\n * owner's confirmation email never mentioned it.\n * - **A governed full copy already exists.** Firestore backups run weekly\n * with 14-week retention (AGL-871), so the dump added no recoverability —\n * only a second, ungoverned place the data lived.\n * - **The minimum that proves an erasure was already being written.** The\n * `adminAudit` row below is ids and counts, in a collection with a\n * retention policy. The one thing the object's NAME carried that the row\n * did not — which request this run fulfilled — is now `after.requestedAt`.\n * - **The DPA commits to \"a limited period, after which deleted or\n * de-identified\"**, which indefinite retention of a full dump sits\n * outside of.\n *\n * Two consequences are deliberate, not side effects. The export-write abort\n * is gone with the write: there is nothing left to fail before the first\n * delete, so an erasure can no longer be blocked by Storage. And the export\n * was the only unbounded work in this function — it built the whole workspace\n * in memory inside a 60-second cron, so the larger the workspace the likelier\n * its erasure silently never happened (AGL-1455 half 1). That defect is\n * removed by deletion rather than by a streaming exporter.\n */\nexport async function eraseOrg(\n orgId: string,\n options: EraseOrgOptions = {},\n): Promise<EraseOrgResult> {\n const {\n dryRun = false,\n actorUid = 'cron:run-erasures',\n tearDownSendingDomain = null,\n withoutRequest = null,\n } = options\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const orgSnapshot = await orgRef.get()\n if (!orgSnapshot.exists) return { ok: false, skippedReason: 'not-found' }\n\n const requestedMs = orgSnapshot.get('erasureRequestedAt')?.toMillis?.() ?? null\n // The request and its hold, unless the caller carries its own proof\n // (AGL-2585). Both refusals are skipped together: a workspace with no\n // request has no stamp for a hold to run from, so keeping the second while\n // dropping the first would be a hold measured against `null`.\n if (!withoutRequest) {\n if (!requestedMs) return { ok: false, skippedReason: 'no-request' }\n if (Date.now() - requestedMs < ERASURE_HOLD_MS) {\n return { ok: false, skippedReason: 'hold-active' }\n }\n }\n\n const hosts = await firestore\n .collection('hosts')\n .where('orgId', '==', orgId)\n .get()\n const members = await orgRef.collection('members').get()\n const slug = orgSnapshot.get('slug') as string | undefined\n // AGL-1028: moved to `orgs/{orgId}/billing/stripe`; the helper falls back\n // to the org doc for orgs the backfill has not reached.\n const stripeCustomerId = (await readOrgBilling(orgId)).stripeCustomerId as\n | string\n | undefined\n\n // The inventory both audit rows report, taken before anything is touched.\n const before = { hosts: hosts.size, members: members.size }\n\n // No export. The write that used to stand here is gone (AGL-1443) — see\n // the note above this function. Nothing is persisted anywhere before the\n // deleting starts, and `requestedMs` now travels in the audit row rather\n // than in an object's name.\n\n // None of what follows was guarded (AGL-1455) — `eraseOrgApiKeys`,\n // `eraseOrgSsoDomains`, `eraseOrgIdempotencyKeys` and `recursiveDelete` all\n // throw. A throw here leaves a workspace half destroyed and still standing,\n // recorded nowhere. Each step now names itself, and the error is re-thrown\n // unchanged — this adds a record, it does not swallow the failure. What it\n // can no longer leave behind is the state that used to be the worst one: a\n // surviving workspace with its own complete dump already in the bucket.\n const progress: EraseProgress = {}\n let step: EraseStep = 'plugins'\n try {\n // The plugins' share first (AGL-2978), while the org, its roster and\n // every record swept below still exist: an eraser that revokes a grant at\n // its provider opens the stored grant to do it. Each eraser is isolated,\n // so a failing one is recorded as `null` and stops nothing; on a plan\n // each one counts and touches no provider.\n progress.plugins = await runPluginOrgErasers({ orgId, dryRun })\n\n step = 'credentials'\n // Credentials and routing BEFORE content (AGL-1444/AGL-1448). The org doc\n // survives until the recursiveDelete at the end, so a key presented — or a\n // sign-in routed, or a console domain resolved — mid-erasure would still\n // pass the org gate and reach a half-deleted workspace. Revoking first\n // closes that window as well as the permanent one.\n progress.apiKeys = await eraseOrgApiKeys(orgId, dryRun)\n // The plugins' top-level collections keyed by this org (AGL-3080) — a\n // connected mailbox's OAuth grant, a sequence email's tracking links.\n // Declared by the owning plugin and swept HERE, statically, not by its\n // eraser: an erasure cannot rely on a plugin being loaded, and a grant\n // that can still send as a person must not outlive the workspace it was\n // given to because an erasing process never loaded that plugin's bundle.\n progress.pluginCollections = await erasePluginOrgKeyedCollections(orgId, dryRun)\n progress.ssoDomains = await eraseOrgSsoDomains(orgId, dryRun)\n progress.consoleDomains = await releaseOrgConsoleDomains(orgId, dryRun)\n progress.apiIdempotency = await eraseOrgIdempotencyKeys(orgId, dryRun)\n\n\n // Support threads (AGL-1971). Its own step because it is the only sweep\n // here that walks a subtree per row, so it is the one most likely to be\n // where a large workspace's erasure runs out of time — and a failure that\n // cannot say WHICH step stopped it is the AGL-1455 defect again.\n step = 'support'\n progress.supportTickets = await eraseOrgSupportTickets(orgId, dryRun)\n\n /*\n * Hosts (Storage + routing + Firestore trees + the sending domain).\n *\n * Each site's dedicated domain is released here rather than by a sweep\n * that never existed: a workspace erasure used to leave one plan-capped\n * provider slot and three zone records per site standing forever, with\n * the DKIM key still live under a label a future site could claim.\n *\n * The driver is passed in and may be absent, and either way the erasure\n * finishes. What the vendors refuse is recorded as a debt on the label\n * claim, which survives the `recursiveDelete` of both the host and the\n * org, and the reaper settles it.\n */\n step = 'hosts'\n progress.hosts = 0\n progress.sendingDomains = { released: 0, deferred: 0, protected: 0 }\n for (const host of hosts.docs) {\n if (!dryRun) {\n // The whole organization goes, declaration and all, so no site is\n // left to read the refusals a grouped site holds.\n const erased = await eraseHost(host.id, {\n tearDownSendingDomain,\n allowInConsentGroup: true,\n })\n if (erased.sendingDomain === 'released') {\n progress.sendingDomains.released += 1\n }\n if (erased.sendingDomain === 'deferred') {\n progress.sendingDomains.deferred += 1\n }\n if (erased.sendingDomain === 'protected') {\n progress.sendingDomains.protected += 1\n }\n }\n progress.hosts += 1\n }\n\n // The backstop for what the loop above cannot enumerate (AGL-1448): a\n // `hostIndex` row whose `hosts` document is already gone. AFTER the loop\n // deliberately — the loop's own fail-soft delete is one of the things\n // that creates them, so sweeping first would leave this run's orphans\n // behind for a retry that can no longer see them.\n progress.hostIndex = await eraseOrgHostIndex(orgId, dryRun)\n\n // Org-level Storage (media/dataset assets outside the host prefix).\n step = 'org-storage'\n if (!dryRun) {\n try {\n await storageBucket().deleteFiles({ prefix: `orgs/${orgId}/` })\n } catch (error) {\n console.error(`eraseOrg: org storage cleanup failed for ${orgId}`, error)\n }\n // The org library's copies at the delivery provider (AGL-2824); each\n // site's went with its `eraseHost` above.\n await eraseMediaDeliveryScope({ collection: 'orgs', scopeId: orgId })\n }\n\n // Stripe: the customer at the processor, AND the local reverse index that\n // correlates that identity back to this workspace (AGL-1448). Deleting\n // only the first left exactly the record AGL-1028 denied to every client.\n step = 'stripe'\n // `readOrgBilling` hands back the customer for THIS deployment's Stripe\n // mode (AGL-2486), which is the only one `deleteStripeCustomer` could act\n // on anyway — it spends `STRIPE_SECRET_KEY`, and a live key cannot delete a\n // test customer. Known residue, deliberately not chased here: an org that\n // was also exercised in TEST mode leaves its test customer standing at\n // Stripe after a live erasure. That is synthetic data created by us, not\n // subject data supplied by the workspace, and reaching it would mean\n // erasure spending a second API key in a mode this deployment is not in.\n if (!dryRun) await deleteStripeCustomer(stripeCustomerId)\n progress.stripeIndex = await eraseOrgStripeIndex(orgId, dryRun)\n\n // Members' reverse index into this org.\n step = 'members'\n if (!dryRun) {\n for (const member of members.docs) {\n await firestore\n .collection('users')\n .doc(member.id)\n .collection('orgs')\n .doc(orgId)\n .delete()\n .catch(() => undefined)\n }\n }\n\n // The backstop for the members loop (AGL-1448): a `hostMemberships`\n // projection belonging to somebody who has LEFT the org, whom\n // `deleteHostProjectionForAllMembers` cannot enumerate because the\n // membership it would start from is already gone. Collection-group —\n // see the note on the function, and the index it owes.\n progress.hostMemberships = await eraseOrgHostMemberships(orgId, dryRun)\n\n // The org subtree, then every slug reservation it has ever held — the\n // current one and each rename tombstone (AGL-1448), with the matching\n // `{slug}.aglyn.com` detached (AGL-1136).\n step = 'org-tree'\n if (!dryRun) await firestore.recursiveDelete(orgRef)\n step = 'slugs'\n progress.slugs = await eraseOrgSlugs(orgId, slug, dryRun)\n } catch (error) {\n console.error(`eraseOrg: ${step} failed for ${orgId}`, error)\n await recordErasureFailure({\n orgId,\n step,\n error,\n actorUid,\n requestedAt: requestedMs,\n before,\n // How far it got, so the next reader knows what is already destroyed.\n after: { ...progress },\n })\n throw error\n }\n\n // A plan (AGL-1481). Every sweep above ran its query and skipped its write,\n // so these are the counts the real run would report — reached through the\n // same code, which is the whole point of the operator script calling this\n // function instead of listing the sweeps a second time. No audit row: an\n // erasure that did not happen is not a record of one.\n if (dryRun) {\n return {\n ok: false,\n skippedReason: 'dry-run',\n ...progress,\n hosts: hosts.size,\n members: members.size,\n }\n }\n\n // The proof of erasure, and now the only record of it: actor, action,\n // target, the request it fulfilled, the inventory found and what each sweep\n // destroyed. Ids and counts — never the content (AGL-1443).\n await addAdminAudit(firestore, {\n actorUid,\n action: 'org.erased',\n target: `orgs/${orgId}`,\n before,\n after: {\n requestedAt: requestedMs,\n // What stood in for a request, when nothing did (AGL-2585). Absent on\n // every ordinary erasure, so its presence is the whole flag.\n ...(withoutRequest ? { withoutRequest: withoutRequest.reason } : {}),\n ...progress,\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n return { ok: true, ...progress, hosts: hosts.size, members: members.size }\n}\n\n/**\n * Strip an erased person from the support threads they wrote in, WITHOUT\n * destroying the threads (AGL-1971).\n *\n * The asymmetry with `eraseOrgSupportTickets` is the whole point and is worth\n * stating rather than assuming. A ticket belongs to an ORG, not to the person\n * who happened to open it: it is the workspace's support history, other people\n * on the roster can read it, and it is evidence in a dispute the workspace may\n * still be having with us. Erasing one member must not delete it — and cannot,\n * honestly: for that thread Aglyn is the processor and the ORG is the\n * controller, so deleting it on a member's instruction is acting without the\n * controller's instruction, which `docs/PRIVACY_REQUESTS.md` §6 refuses in the\n * mirror-image case. `eraseUser` also already refuses to cascade into\n * `eraseOrg` for exactly this reason.\n *\n * So the narrow correct action is redaction: `authorId` and `authorEmail` go\n * to `null` and `authorErased: true` marks why, on that person's messages\n * only. What remains is the message BODY, deliberately — it is the workspace's\n * record of a conversation with us, and it is the workspace's to delete. An\n * erasure of the ORG destroys it, which is the path that reaches it.\n *\n * **A collection-group query, not a walk over their current memberships.** The\n * membership walk is the tempting version and it is wrong in a specific way:\n * `eraseUser` only knows the orgs the person belongs to NOW, so every ticket\n * they wrote in a workspace they have since left would keep their email — the\n * residual is invisible and grows with tenure. `messages` is used as a\n * subcollection name by `supportTickets` and by nothing else in the repo, so\n * the group is exactly the right set. It needs the COLLECTION_GROUP index\n * override on `messages.authorId` in `cloud/firebase-firestore.indexes.json`,\n * added with this change.\n *\n * Returns the number of messages redacted, or **`null` when the query could\n * not run** — a missing index in an environment where it was never deployed.\n * `null` is not zero and the caller must not flatten it: it means this erasure\n * did not reach the support messages at all, and an erasure that quietly\n * reports success for a step it skipped is the failure this whole file is\n * organised against. It is reported in the result and in the audit row rather\n * than thrown, because the account deletion itself must still complete.\n */\nasync function redactUserSupportMessages(uid: string): Promise<number | null> {\n if (!uid) return 0\n const firestore = firebaseAdmin.app().firestore()\n let rows: FirebaseFirestore.QuerySnapshot\n try {\n rows = await firestore\n .collectionGroup('messages')\n .where('authorId', '==', uid)\n .get()\n } catch (error) {\n console.error(\n `eraseUser: support message redaction could not run for ${uid}`,\n error,\n )\n return null\n }\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) {\n batch.set(\n doc.ref,\n { authorId: null, authorEmail: null, authorErased: true },\n { merge: true },\n )\n }\n await batch.commit()\n }\n return rows.size\n}\n\n/** An org that stops a person's account from being erased. */\nexport interface UserErasureBlocker {\n orgId: string\n orgName: string\n /** Whether the org still bills — the reason a human must intervene. */\n hasLiveSubscription: boolean\n /** Other people who would be stranded if this org lost its owner. */\n otherMembers: number\n}\n\nexport interface UserErasureCandidateOrg {\n orgId: string\n orgName: string\n ownerUid: string | null\n hasLiveSubscription: boolean\n memberCount: number\n}\n\n/**\n * Which orgs block erasing `uid` (AGL-1140).\n *\n * Pure so the policy can be tested without Firestore, because the policy is\n * the part worth arguing about — the deletion itself is mechanical.\n *\n * **Owning an org blocks erasure, always.** Not only when it bills, and not\n * only when other members would be stranded. The alternative — cascading\n * into `eraseOrg` — deletes a workspace, its sites and its data as a side\n * effect of someone closing a personal account, and no consent given to the\n * second act was given to the first. Blocking is recoverable; a cascade is\n * not.\n *\n * A live subscription and stranded members are reported rather than gating,\n * so the message can say WHY this org needs attention instead of a bare\n * refusal — \"transfer ownership\" is useless advice if you do not know which\n * of eleven workspaces is the problem.\n */\nexport function userErasureBlockers(\n uid: string,\n orgs: readonly UserErasureCandidateOrg[],\n): UserErasureBlocker[] {\n return orgs\n .filter((org) => org.ownerUid === uid)\n .map((org) => ({\n orgId: org.orgId,\n orgName: org.orgName,\n hasLiveSubscription: org.hasLiveSubscription,\n // The owner themselves is a member; anyone beyond that is stranded.\n otherMembers: Math.max(0, org.memberCount - 1),\n }))\n}\n\n/**\n * An address this account holds that a SECOND account also holds, which stops\n * the erasure until a human decides what it is.\n *\n * ⛔ Carries no address and no other uid. The whole question is about a second\n * customer, and a refusal that names them — or hands back an address in the\n * clear, which `emailDeliveries` is hashed precisely to avoid keeping —\n * discloses the person the refusal exists to protect. The staff account page\n * already lists this account's own addresses and marks the shared ones, so\n * the operator has the specifics without this record carrying them.\n */\nexport interface SharedAddressBlocker {\n /** `sha256(address)` — matches the delivery log's own key. Not readable. */\n key: string\n /** Where this account got it: `primary`, `provider`, `stored`. */\n sources: AccountAddressSource[]\n}\n\n/**\n * Which of an account's addresses a second account is also known to hold.\n *\n * Pure, and separate from the sweep, for the same reason `userErasureBlockers`\n * is: the policy is the arguable part. The mechanical part is deleting rows.\n *\n * ⚠️ `shared` is evidence in ONE direction. True proves a second holder;\n * false only means none was found, because no lookup exists for an account\n * holding an address through a federated provider. So this finds every case\n * we can SEE and cannot promise there is no other — which is exactly why the\n * sweep still tombstones every address it erases.\n */\nexport function sharedAddressBlockers(\n set: Pick<AccountAddressSet, 'addresses'>,\n): SharedAddressBlocker[] {\n return set.addresses\n .filter((entry) => entry.shared === true)\n .map((entry) => ({ key: entry.key, sources: [...entry.sources] }))\n}\n\nexport interface EraseUserResult {\n ok: boolean\n /** Set when the account was NOT erased. */\n skippedReason?: 'not-found' | 'owns-orgs' | 'shared-address'\n /** Orgs that must be handed over or deleted first. */\n blockers?: UserErasureBlocker[]\n /**\n * Addresses a second account also holds. Set with\n * `skippedReason: 'shared-address'`, and NOTHING was erased.\n */\n sharedAddresses?: SharedAddressBlocker[]\n /** What was actually removed, for the audit row and the caller's message. */\n deleted?: {\n subcollections: string[]\n authRecord: boolean\n photo: boolean\n /** `profiles/{uid}` — the world-readable public identity (AGL-1970). */\n profile: boolean\n /**\n * Support messages stripped of `authorId`/`authorEmail` (AGL-1971). The\n * threads themselves belong to the org and survive. **`null` means the\n * redaction could not run** — not that there was nothing to redact.\n */\n supportMessagesRedacted: number | null\n /**\n * What each plugin's eraser removed (AGL-2939), keyed by plugin id — the\n * data a plugin keeps about the person where neither the recursive\n * delete of the user document nor an org's cascade reaches, such as\n * documents under each org keyed by the uid. **`null` means that\n * plugin's eraser failed** and its data may remain; it is not zero.\n */\n plugins: Record<string, PluginUserErasureReport | null>\n /**\n * Messages removed from `emailDeliveries/{sha256(address)}/messages` —\n * the per-recipient delivery log. Zero for an account with no address on\n * file, or one we never mailed.\n *\n * Across EVERY address the account held, not just the current primary.\n */\n emailDeliveries: number\n /**\n * `emailIdentityIndex/{address}` rows released — the address-keyed\n * uniqueness claims, which no `recursiveDelete` of the user can reach.\n */\n emailIdentityIndex: number\n /**\n * How wide the address sweep actually was.\n *\n * ⚠️ `incomplete` is the field a compliance answer turns on: true means a\n * source could not be read and an address the account held may have been\n * missed, so this was not a complete erasure and must not be reported as\n * one. Counts only — never the addresses, which is the data being erased.\n */\n addressSweep: {\n /** Addresses found across the Auth record, its providers and the store. */\n resolved: number\n /** Addresses the delivery sweep actually visited. */\n erased: number\n /**\n * Addresses left INTACT because a second account also holds them.\n *\n * Always 0 on a successful erasure: a contested address refuses the\n * whole run before anything is destroyed. It is reported so the audit\n * row states that rather than leaving a reader to infer it.\n */\n contested: number\n incomplete: boolean\n }\n }\n}\n\n/**\n * Permanently erase a person's account (AGL-1140).\n *\n * Nothing did this before: `eraseHost`, `eraseSubtree` and `eraseOrg` existed\n * and no path anywhere deleted a `users/{uid}`. That was survivable while the\n * doc held a name and a phone; AGL-1133 added a postal address, and \"we have\n * no mechanism to delete it\" is a bad answer to an erasure request.\n *\n * `eraseOrg` is deliberately NOT the model here. An org is a workspace with\n * one owner; a person belongs to many orgs, so erasing them must not take\n * anything with it that outlives them.\n *\n * Order matters:\n * 1. Refuse if they own an org — see `userErasureBlockers`.\n * 1b. Refuse if a second account holds one of their addresses — see\n * `sharedAddressBlockers`. Both refusals come before any delete, so a\n * blocked erasure leaves the account exactly as it was.\n * 2. Remove their membership from every org they belong to, so no roster\n * keeps their email and no host projection keeps granting them access.\n * This runs BEFORE the profile delete: a half-erased account that still\n * appears on a roster is worse than one not yet started.\n * 3. Delete the `users/{uid}` subtree, the avatar, the world-readable\n * `profiles/{uid}` public identity (AGL-1970), redact their name and\n * email off every support message they wrote (AGL-1971), then the auth\n * record last — once that is gone there is no uid to retry with.\n */\nexport async function eraseUser(uid: string): Promise<EraseUserResult> {\n const firestore = firebaseAdmin.app().firestore()\n const userRef = firestore.collection('users').doc(uid)\n const snapshot = await userRef.get()\n const membership = await userRef.collection('orgs').get()\n // An absent profile doc is not an absent account — the doc is only born on\n // first save (AGL-1127), so the auth record and the org memberships can\n // outlive it. Treat \"nothing anywhere\" as not-found, not \"no doc\".\n if (!snapshot.exists && membership.empty) {\n const record = await findUserByUidAcrossPools(uid).catch(() => null)\n if (!record) return { ok: false, skippedReason: 'not-found' }\n }\n\n const candidates: UserErasureCandidateOrg[] = []\n for (const row of membership.docs) {\n const orgRef = firestore.collection('orgs').doc(row.id)\n const [org, members] = await Promise.all([\n orgRef.get(),\n orgRef.collection('members').count().get(),\n ])\n if (!org.exists) continue\n candidates.push({\n orgId: row.id,\n orgName: String(org.get('name') ?? row.id),\n ownerUid: (org.get('ownerUid') as string | undefined) ?? null,\n hasLiveSubscription: isBillingSubscription(org.data() as never),\n memberCount: Number(members.data().count ?? 0),\n })\n }\n const blockers = userErasureBlockers(uid, candidates)\n if (blockers.length) {\n return { ok: false, skippedReason: 'owns-orgs', blockers }\n }\n\n // Inventory BEFORE anything is deleted. Taken after the membership sweep\n // below, this under-reported: `removeOrgMember` empties `users/{uid}/orgs`,\n // and Firestore does not list a collection with no documents in it — so a\n // live run erased three subcollections and the audit record named two.\n // An erasure audit trail that understates what it destroyed is the one\n // record that has to be right. Measured 2026-08-01 (AGL-1140).\n const subcollections = (await userRef.listCollections()).map((c) => c.id)\n\n /*\n * EVERY ADDRESS, RESOLVED BEFORE ANY OF THEM IS DESTROYED.\n *\n * Two of the three sources are erased by this function itself:\n * `users/{uid}/emails` goes with the `recursiveDelete` below, and the Auth\n * record — the only place the primary lives — goes at the very end. Reading\n * them afterwards is reading nothing, and an erasure that resolves an empty\n * address set sweeps nothing while reporting success. That is the exact\n * shape of a spec passing because its fixture never reached the code, and\n * here it would be a live erasure reporting a completeness it does not have.\n *\n * `detectShared` because the SHARED case changes what the caller is told,\n * not what is destroyed — see `eraseEmailDeliveriesForAddresses`.\n */\n const pooledForAddresses = await findUserByUidAcrossPools(uid).catch(() => null)\n const addressSet: AccountAddressSet = await resolveAccountAddresses({\n uid,\n record: pooledForAddresses?.record ?? null,\n detectShared: true,\n firestore,\n }).catch(() => ({\n uid,\n primary: null,\n addresses: [],\n incomplete: true,\n }))\n\n /*\n * A SECOND ACCOUNT HOLDS ONE OF THESE ADDRESSES — REFUSE, HERE.\n *\n * The delivery log is filed under the address, so an address two accounts\n * hold has one set of rows answering \"what did you send me\" for two account\n * records. Whether that is one human with two accounts (the ordinary live\n * shape — a federated provider address that is another account's primary)\n * or a genuinely shared role mailbox like `billing@` decides whether\n * erasing those rows honours a request or destroys a stranger's history,\n * and NOTHING readable here distinguishes them. The data records that two\n * accounts name one address; it records nothing about the humans.\n *\n * Both automatic answers are unacceptable, and they fail differently:\n * erasing the second party's mail cannot be undone, while leaving it and\n * reporting the erasure complete is the gap this whole area was opened to\n * close. So neither is chosen — the erasure stops and says why.\n *\n * BEFORE the membership sweep, deliberately. A refusal raised after the\n * account is half-deleted is not a refusal, and the uid is the only handle\n * a human has to act on this: erase the auth record and there is no longer\n * anything to look at, no way to see which address was contested, and no\n * way to run the erasure once the question is settled. Refusing while the\n * account is whole is the only version of this that stays reversible.\n *\n * The remedy is ordinary staff work, not a special path: decide whether the\n * accounts are one person, detach the address from this one or merge them,\n * then run the erasure again. `/admin/users/[uid]` already lists this\n * account's addresses and marks the shared ones.\n */\n const contested = sharedAddressBlockers(addressSet)\n if (contested.length) {\n return {\n ok: false,\n skippedReason: 'shared-address',\n sharedAddresses: contested,\n }\n }\n\n // Memberships first — a roster row carries their email and a host\n // projection carries their access, and both outlive the profile doc.\n for (const candidate of candidates) {\n await removeOrgMember(candidate.orgId, uid).catch((error) => {\n console.error(`eraseUser: membership cleanup failed for ${candidate.orgId}`, error)\n })\n }\n\n // What the plugins keep about the person (AGL-2939). A document under an\n // org keyed by the uid is the shape no recursive delete on this path can\n // see — the same shape as the delivery log below. Each plugin's eraser\n // gets every workspace the person was in, because the memberships above\n // are already gone; one that fails is recorded as `null` and the erasure\n // goes on.\n const plugins = await runPluginUserErasers({\n uid,\n orgIds: candidates.map((candidate) => candidate.orgId),\n })\n\n // The avatar outlives the doc otherwise.\n let photo = false\n try {\n await storageBucket().deleteFiles({ prefix: `users/${uid}/` })\n photo = true\n } catch (error) {\n console.error(`eraseUser: storage cleanup failed for ${uid}`, error)\n }\n\n await firestore.recursiveDelete(userRef)\n\n // `profiles/{uid}` — the person's PUBLIC identity (AGL-1970).\n //\n // A separate top-level collection keyed by the uid AS THE DOCUMENT ID, so\n // `recursiveDelete(users/{uid})` above never reaches it and no reader\n // scanning this function for a sweep list is prompted to notice it. It is\n // `allow read: if true` in the rules and carries `handle`, `displayName`,\n // and `stripeAccountId`/`stripeChargesEnabled` — a Stripe Connect payout\n // destination written server-side after KYC. An erased person therefore\n // stayed publicly listed with a live payment-account identifier attached,\n // which Privacy Policy §5 (\"a genuine recursive delete… we keep no copy of\n // the erased content\") says in terms does not happen.\n //\n // No tombstone, unlike the org's publisher profile: the only reader of the\n // display name is the support forum's author rendering, and a forum post\n // losing its author name is the intended outcome of erasing its author.\n //\n // `recursiveDelete` rather than `delete` — nothing writes a subcollection\n // under a profile today, and a document delete would silently orphan the\n // first thing that does.\n let profile = false\n try {\n const profileRef = firestore.collection('profiles').doc(uid)\n profile = (await profileRef.get()).exists\n await firestore.recursiveDelete(profileRef)\n } catch (error) {\n console.error(`eraseUser: public profile delete failed for ${uid}`, error)\n }\n\n // Their name and email off every support message they wrote, in any\n // workspace, past or present (AGL-1971). The threads are the orgs' and\n // survive — see `redactUserSupportMessages`.\n const supportMessagesRedacted = await redactUserSupportMessages(uid)\n\n // Auth record LAST: once it is gone there is no uid to retry with, and\n // `authForPool` is required because a project-level delete cannot see an\n // SSO account at all (AGL-1122).\n //\n // The lookup is hoisted above the delete because the DELIVERY LOG is filed\n // under the ADDRESS, not the uid, and the auth record is the last place the\n // address exists. Erase it while there is still something to erase it by.\n let authRecord = false\n let emailDeliveries = 0\n /** Addresses actually swept — not the same as the ones we hold, on failure. */\n let erasedAddressCount = 0\n /** Addresses left intact because a second account also holds them. */\n let contestedAddressCount = 0\n /** Identity-index rows released, one per address that had one. */\n let emailIdentityIndex = 0\n try {\n const record = await findUserByUidAcrossPools(uid)\n if (record) {\n /*\n * `emailDeliveries/{sha256(address)}/messages` — every subject we ever\n * sent this person, with the times they opened and clicked. Personal\n * data by any reading of it, and reachable from neither\n * `recursiveDelete(users/{uid})` nor `profiles/{uid}` because it is\n * keyed by address in a third top-level collection. The same shape as\n * the `profiles/{uid}` omission this function already documents above:\n * a store nothing in the sweep list would prompt a reader to notice.\n *\n * EVERY ADDRESS, not the current primary. Passing one address left a\n * prior or provider-supplied address holding its full history —\n * recipient, subjects, open and click times — after the request had\n * been honoured and reported complete.\n *\n * Best-effort, like every other step here — a log that survives must\n * not stop the auth record from going.\n */\n const sweep = await eraseEmailDeliveriesForAddresses(\n addressSet.addresses,\n firestore,\n ).catch(() => null)\n emailDeliveries = sweep?.removed ?? 0\n erasedAddressCount = sweep?.addresses.length ?? 0\n contestedAddressCount = sweep?.contestedAddresses.length ?? 0\n\n /*\n * `emailIdentityIndex/{address}` — the SAME omission one collection\n * over.\n *\n * A top-level collection keyed by the address IN THE CLEAR, holding\n * `{uid, address, claimedAt}`. `recursiveDelete(users/{uid})` cannot\n * see it for exactly the reason it cannot see the delivery log, so an\n * erased account left a readable address still pointing at its uid.\n *\n * Released rather than tombstoned, unlike the delivery log: this is a\n * uniqueness claim, and `removeAccountEmail` already argues that\n * holding one after the address is gone burns the address for whoever\n * might legitimately want it next.\n *\n * ⛔ Only rows this uid actually owns. The index is the guard against\n * two accounts holding one address, and deleting another account's\n * claim would hand their sign-in identifier to the next taker.\n */\n for (const entry of addressSet.addresses) {\n try {\n const ref = firestore\n .collection(EMAIL_IDENTITY_INDEX_COLLECTION)\n .doc(entry.address)\n const indexed = await ref.get()\n if (indexed.exists && indexed.get('uid') === uid) {\n await ref.delete()\n emailIdentityIndex += 1\n }\n } catch (error) {\n console.error(`eraseUser: identity index release failed for ${uid}`, error)\n }\n }\n await authForPool(record.tenantId).deleteUser(uid)\n authRecord = true\n }\n } catch (error) {\n console.error(`eraseUser: auth record delete failed for ${uid}`, error)\n }\n\n /*\n * WHAT THE ADDRESS SWEEP ACTUALLY COVERED.\n *\n * Counts, never the addresses themselves: this collection is readable by\n * any staff role and `maskEmailAddress` exists because an audit row holding\n * a readable address made `adminAudit` the leakier of the two stores for\n * the same data. An erasure record listing the addresses it destroyed would\n * be the sharpest version of that — it would preserve, in the clear, the\n * exact set the request existed to remove.\n *\n * `addressesIncomplete` is the one that matters to a reader. It says a\n * source could not be read, so the sweep may have missed an address the\n * account held — the difference between \"erased everywhere\" and \"erased\n * everywhere we could see\", which is the difference a regulator asks about.\n */\n const addressSweep = {\n resolved: addressSet.addresses.length,\n erased: erasedAddressCount,\n contested: contestedAddressCount,\n incomplete: addressSet.incomplete,\n }\n\n await addAdminAudit(firestore, {\n actorUid: 'system:erase-user',\n action: 'user.erased',\n target: `users/${uid}`,\n before: { orgs: candidates.length },\n after: {\n subcollections,\n authRecord,\n photo,\n profile,\n supportMessagesRedacted,\n plugins,\n emailDeliveries,\n emailIdentityIndex,\n addressSweep,\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n return {\n ok: true,\n deleted: {\n subcollections,\n authRecord,\n photo,\n profile,\n supportMessagesRedacted,\n plugins,\n emailDeliveries,\n emailIdentityIndex,\n addressSweep,\n },\n }\n}\n"],"names":["FieldValue","firebaseAdmin","eraseMediaDeliveryScope","sweepScopeSharingAfterSiteChange","deleteHostProjectionForAllMembers","deleteHostProjectionForUids","detachWorkspaceDomain","CONSOLE_DOMAINS_COLLECTION","releaseConsoleDomain","authForPool","findUserByUidAcrossPools","eraseEmailDeliveriesForAddresses","resolveAccountAddresses","EMAIL_IDENTITY_INDEX_COLLECTION","removeOrgMember","runPluginUserErasers","PLUGIN_ORG_KEYED_COLLECTIONS","runPluginOrgErasers","isBillingSubscription","consentGroupSiteHold","listPluginOrgCollections","PLUGIN_HOST_KEYED_COLLECTIONS","erasePluginSiteResources","previewPluginSiteResources","runPluginEventHandlers","releasedHostNames","readOrgBilling","disposeHostSendingDomain","readSendingDomainTeardownByLabel","addAdminAudit","ERASURE_HOLD_MS","storageBucket","name","process","env","NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET","app","storage","bucket","undefined","SUPPLIER_DELIVERY_COLLECTION","eraseHostSupplierDeliveries","hostId","firestore","rows","collection","where","get","index","docs","length","batch","doc","slice","delete","ref","commit","size","error","console","eraseHostNotifications","collectionGroup","eraseHostOwnedOrgDocuments","orgId","erased","declared","siteField","recursiveDelete","erasePluginHostKeyedCollections","deleteDocsByOrgId","previewHostErase","resources","SiteInConsentGroupError","Error","hold","reason","eraseHost","options","hostSnapshot","hostRef","hostMemberUids","Object","keys","allowInConsentGroup","orgSnapshot","data","sendingLabel","String","trim","sendingTeardown","catch","deleteFiles","prefix","scopeId","set","hosts","registerAllocations","collaboratorAllocations","merge","domain","sendingDomain","teardown","tearDown","tearDownSendingDomain","eraseSubtree","path","scope","kind","id","HOST_BEACON_COLLECTIONS","reapHostBeaconRemnants","result","reaped","left","refs","listDocuments","snapshots","getAll","snapshot","exists","collections","listCollections","map","every","includes","push","dryRun","deleteStripeCustomer","customerId","key","STRIPE_SECRET_KEY","fetch","method","headers","Authorization","eraseOrgApiKeys","erasePluginOrgKeyedCollections","counts","orgField","eraseOrgSsoDomains","releaseOrgConsoleDomains","claims","primaries","Set","released","eraseOrgStripeIndex","eraseOrgIdempotencyKeys","eraseOrgSlugs","currentSlug","held","slugs","has","reservation","add","slug","eraseOrgHostIndex","eraseOrgHostMemberships","eraseOrgSupportTickets","tickets","ticket","errorLabel","source","parts","code","filter","part","join","recordErasureFailure","entry","actorUid","action","target","before","after","failedStep","step","requestedAt","at","serverTimestamp","auditError","eraseOrg","withoutRequest","orgRef","ok","skippedReason","requestedMs","toMillis","Date","now","members","stripeCustomerId","progress","plugins","apiKeys","pluginCollections","ssoDomains","consoleDomains","apiIdempotency","supportTickets","sendingDomains","deferred","protected","host","hostIndex","stripeIndex","member","hostMemberships","redactUserSupportMessages","uid","authorId","authorEmail","authorErased","userErasureBlockers","orgs","org","ownerUid","orgName","hasLiveSubscription","otherMembers","Math","max","memberCount","sharedAddressBlockers","addresses","shared","sources","eraseUser","userRef","membership","empty","record","candidates","row","Promise","all","count","Number","blockers","subcollections","c","pooledForAddresses","addressSet","detectShared","primary","incomplete","contested","sharedAddresses","candidate","orgIds","photo","profile","profileRef","supportMessagesRedacted","authRecord","emailDeliveries","erasedAddressCount","contestedAddressCount","emailIdentityIndex","sweep","removed","contestedAddresses","address","indexed","tenantId","deleteUser","addressSweep","resolved","deleted"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,uBAAuB,QAAQ,sBAAkB;AAC1D,SAASC,gCAAgC,QAAQ,2BAAuB;AACxE,SACEC,iCAAiC,EACjCC,2BAA2B,QACtB,wBAAoB;AAC3B,SAASC,qBAAqB,QAAQ,yBAAqB;AAC3D,SACEC,0BAA0B,EAC1BC,oBAAoB,QACf,uBAAmB;AAC1B,SAASC,WAAW,EAAEC,wBAAwB,QAAQ,kBAAc;AACpE,SAASC,gCAAgC,QAAQ,0BAAsB;AACvE,SAGEC,uBAAuB,QAClB,yBAAqB;AAC5B,SAASC,+BAA+B,QAAQ,sBAAkB;AAClE,SAASC,eAAe,QAAQ,qBAAiB;AACj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B;gBACF,EAAE,OAAOvM,OAAO;oBACdC,QAAQD,KAAK,CAAC,CAAC,6CAA6C,EAAEsJ,KAAK,EAAEtJ;gBACvE;YACF;YACA,MAAMjD,YAAY6N,OAAOiC,QAAQ,EAAEC,UAAU,CAACxD;YAC9C6C,aAAa;QACf;IACF,EAAE,OAAOnM,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,yCAAyC,EAAEsJ,KAAK,EAAEtJ;IACnE;IAEA;;;;;;;;;;;;;;GAcC,GACD,MAAM+M,eAAe;QACnBC,UAAUzB,WAAWlB,SAAS,CAAC7K,MAAM;QACrCc,QAAQ+L;QACRV,WAAWW;QACXZ,YAAYH,WAAWG,UAAU;IACnC;IAEA,MAAMvN,cAAcc,WAAW;QAC7B8H,UAAU;QACVC,QAAQ;QACRC,QAAQ,CAAC,MAAM,EAAEqC,KAAK;QACtBpC,QAAQ;YAAEyC,MAAMkB,WAAWrL,MAAM;QAAC;QAClC2H,OAAO;YACLiE;YACAe;YACAJ;YACAC;YACAE;YACA5D;YACA8D;YACAG;YACAQ;QACF;QACAxF,IAAIjL,WAAWkL,eAAe;IAChC,GACGxF,KAAK,CAAC,IAAMnD;IAEf,OAAO;QACLgJ,IAAI;QACJoF,SAAS;YACP7B;YACAe;YACAJ;YACAC;YACAE;YACA5D;YACA8D;YACAG;YACAQ;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/erase.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'\nimport { firebaseAdmin } from './firebase-admin'\nimport { eraseMediaDeliveryScope } from './media-delivery'\nimport { sweepScopeSharingAfterSiteChange } from './scope-sharing-sweep'\nimport {\n deleteHostProjectionForAllMembers,\n deleteHostProjectionForUids,\n} from './host-memberships'\nimport { detachWorkspaceDomain } from './workspace-domains'\nimport {\n CONSOLE_DOMAINS_COLLECTION,\n releaseConsoleDomain,\n} from './console-domains'\nimport { authForPool, findUserByUidAcrossPools } from './auth-pools'\nimport { eraseEmailDeliveriesForAddresses } from './email-delivery-log'\nimport {\n type AccountAddressSet,\n type AccountAddressSource,\n resolveAccountAddresses,\n} from './account-addresses'\nimport { EMAIL_IDENTITY_INDEX_COLLECTION } from './account-emails'\nimport { removeOrgMember } from './organizations'\nimport {\n runPluginUserErasers,\n type PluginUserErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-user-erasure'\nimport {\n PLUGIN_ORG_KEYED_COLLECTIONS,\n runPluginOrgErasers,\n type PluginOrgErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport { isBillingSubscription } from '@aglyn/aglyn/server'\n// The module path rather than the barrel: this module's specs substitute the\n// barrel, and which sites a consent group still needs is the rule itself.\nimport {\n type ConsentGroupSiteHold,\n consentGroupSiteHold,\n} from '@aglyn/aglyn/app-utils/consent-groups'\nimport { listPluginOrgCollections } from '@aglyn/aglyn/plugin-manager/plugin-host-collections'\nimport {\n PLUGIN_HOST_KEYED_COLLECTIONS,\n erasePluginSiteResources,\n previewPluginSiteResources,\n type PluginSiteResourcePreviewRow,\n} from '@aglyn/aglyn/plugin-manager/plugin-site-resources'\nimport { runPluginEventHandlers } from '@aglyn/aglyn/plugin-manager/plugin-events'\nimport { releasedHostNames } from './host-released-names'\nimport { readOrgBilling } from './org-billing'\nimport {\n disposeHostSendingDomain,\n readSendingDomainTeardownByLabel,\n type SendingDomainDisposition,\n type TeardownSendingDomainDriver,\n} from './sending-domain-debt'\nimport { addAdminAudit } from './admin-audit-write'\nimport { retryTransientFirestore } from './firestore-transient'\n\n/** The reversible hold before a requested erasure is executed (AGL-485). */\nexport const ERASURE_HOLD_MS = 7 * 24 * 60 * 60 * 1000\n\n/**\n * The admin app is initialized without a default storageBucket, so every\n * bucket access must name it explicitly (same as the media routes). Falls\n * through to the admin default if the env is somehow unset.\n */\nfunction storageBucket() {\n const name = process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET\n return firebaseAdmin.app().storage().bucket(name || undefined)\n}\n\n/**\n * `supplierDeliveries` — the dropship outbox, keyed by `hostId` as a FIELD.\n *\n * The literal rather than an import: the collection belongs to\n * `libs/plugins/commerce/src/lib/server/supplier-outbox.ts`\n * (`SUPPLIER_DELIVERY_COLLECTION`), which is tagged `aglyn:addons`, and this\n * library is `scope:data` — the nx boundary forbids the edge, and reaching\n * for a dynamic import to dodge it would poison the lint graph instead. The\n * emulator spec asserts the two spellings still agree by reading that file,\n * so a rename fails a test rather than silently un-wiring this sweep.\n */\nconst SUPPLIER_DELIVERY_COLLECTION = 'supplierDeliveries'\n\n/**\n * Destroy the site's DEAD-LETTERED supplier deliveries (AGL-1448).\n *\n * `supplierDeliveries/{id}` is TOP-LEVEL and carries `hostId` as a field, so\n * neither `recursiveDelete(hosts/{hostId})` here nor\n * `recursiveDelete(orgs/{orgId})` in `eraseOrg` can see it. That placement is\n * deliberate and correct — a subcollection would be editor-writable under the\n * permissive host catch-all, and the row carries the exact JSON body we sign\n * and POST to the supplier — so the fix is a sweep, not a move.\n *\n * **The gap is the dead letter, and the module that created it named it.**\n * `supplier-outbox.ts` DELETES a row the moment delivery succeeds, and its\n * docblock says why in terms: the body holds the buyer's email and name, and\n * a top-level document is outside the recursive delete an erasure runs. The\n * happy path was solved by that deletion. The failure path was not: after\n * `SUPPLIER_DELIVERY_MAX_ATTEMPTS` the row is left standing as `failed`,\n * because a human is supposed to act on it and the merchant has been told.\n * Nothing ever collects it afterwards — no TTL policy keys on it, no cron\n * reaps it, and the erasure could not reach it. So the one class of row that\n * survives is the one holding a THIRD PARTY's name, email and shipping\n * address, against a site whose owner has since asked to be erased and whom\n * nobody can ask to act on the dead letter any more.\n *\n * Bounded by the `hostId` field, never a collection sweep: this collection\n * holds every other merchant's orders. Chunked, because a batch caps at 500\n * and nothing bounds a dead-letter backlog below that.\n *\n * In `eraseHost` rather than `eraseOrg` on purpose — it is host-scoped data,\n * so the self-serve \"delete this site\" path gets the same cleanup as a full\n * org erasure instead of leaving the residue behind for the smaller action.\n *\n * Best-effort, like every other trailing cleanup in `eraseHost`: a site\n * delete must not fail because an outbox query did.\n */\nasync function eraseHostSupplierDeliveries(hostId: string): Promise<number> {\n if (!hostId) return 0\n try {\n const firestore = firebaseAdmin.app().firestore()\n const rows = await firestore\n .collection(SUPPLIER_DELIVERY_COLLECTION)\n .where('hostId', '==', hostId)\n .get()\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) {\n batch.delete(doc.ref)\n }\n await batch.commit()\n }\n return rows.size\n } catch (error) {\n console.error(`eraseHost: supplier outbox cleanup failed for ${hostId}`, error)\n return 0\n }\n}\n\n/**\n * Every in-app notification about the site, in every inbox (AGL-3719).\n *\n * `users/{uid}/notifications/{id}` names the site in `hostId` — \"Your site is\n * live\", \"Your site job needs you\", the staff operator alerts — and links into\n * it (`/{hostId}/ai-jobs/…`). Nothing else collects them: they carry no TTL,\n * the `recursiveDelete(hosts/{hostId})` below cannot see a user's tree, and\n * the inbox outlives the site, so every one became a link to a 404 that stood\n * forever. A 2026-10-09 audit found 14 of them against deleted test sites.\n *\n * A collection-group query rather than a walk of the org's members, because\n * the staff alerts land in inboxes that are not members of the org. That\n * query needs the `notifications.hostId` COLLECTION_GROUP override in\n * `cloud/firebase-firestore.indexes.json`.\n *\n * Best-effort, like every other trailing cleanup in `eraseHost`.\n */\nasync function eraseHostNotifications(hostId: string): Promise<number> {\n if (!hostId) return 0\n try {\n const firestore = firebaseAdmin.app().firestore()\n const rows = await firestore\n .collectionGroup('notifications')\n .where('hostId', '==', hostId)\n .get()\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) {\n batch.delete(doc.ref)\n }\n await batch.commit()\n }\n return rows.size\n } catch (error) {\n console.error(`eraseHost: notification cleanup failed for ${hostId}`, error)\n return 0\n }\n}\n\n/**\n * Destroy the org documents that belong to the site (AGL-3273).\n *\n * Some plugin storage is the organization's and names the site each document\n * belongs to — Marketing's email sends, `orgs/{orgId}/campaigns`, each naming\n * the site it was sent as. The `recursiveDelete(hosts/{hostId})` below does\n * not reach them, and they are still the site's: a send's sender, unsubscribe\n * page and the consent it relied on were that site's, and a send addressed to\n * a hand-typed list carries those addresses.\n *\n * Which collections, and which field names the site, is each plugin's own\n * declaration (`orgCollections` in `plugins.config.json`, read through\n * `listPluginOrgCollections`): a declaration with a `siteField` is a\n * collection whose documents belong to one site. One without — a campaign\n * container, placed on sites rather than owned by one — is left alone. Each\n * document goes with its subcollections, which is why this is a recursive\n * delete per document.\n *\n * Best-effort, like every other trailing cleanup in `eraseHost`, and per\n * collection, so one failed query leaves the others' cleanup standing.\n */\nasync function eraseHostOwnedOrgDocuments(orgId: string, hostId: string): Promise<number> {\n if (!orgId || !hostId) return 0\n const firestore = firebaseAdmin.app().firestore()\n let erased = 0\n for (const declared of listPluginOrgCollections()) {\n if (!declared.siteField) continue\n try {\n const rows = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(declared.name)\n .where(declared.siteField, '==', hostId)\n .get()\n for (const doc of rows.docs) await firestore.recursiveDelete(doc.ref)\n erased += rows.size\n } catch (error) {\n console.error(\n `eraseHost: ${declared.name} cleanup failed for ${hostId}`,\n error,\n )\n }\n }\n return erased\n}\n\n/**\n * Destroy the site's rows in every top-level plugin collection keyed by it\n * (AGL-4214): a register's customer-display state, pairing codes and tokens.\n *\n * Bounded by the declared field, like every top-level sweep here, because each\n * of these collections holds every other site's rows too. Best-effort and per\n * collection, like every other trailing cleanup in `eraseHost`, so one failed\n * query leaves the others' cleanup standing.\n */\nasync function erasePluginHostKeyedCollections(hostId: string): Promise<number> {\n let erased = 0\n for (const { name, siteField } of PLUGIN_HOST_KEYED_COLLECTIONS) {\n try {\n erased += await deleteDocsByOrgId(name, hostId, false, siteField)\n } catch (error) {\n console.error(`eraseHost: ${name} cleanup failed for ${hostId}`, error)\n }\n }\n return erased\n}\n\n/** What deleting a site takes with it, plugin by plugin (AGL-4003). */\nexport interface HostErasePreview {\n /**\n * Each plugin's resources shared with the site: the ones that go, with how\n * many items each holds, and how many stay. `preview: null` is a plugin\n * that could not answer, so the list is incomplete.\n */\n resources: PluginSiteResourcePreviewRow[]\n}\n\n/**\n * What the Delete site card shows before it asks (AGL-4003): the resources\n * plugins share with the site alone, which go with it — a dataset and its\n * records — and how many shared ones stay. Asked of the same erasers\n * {@link eraseHost} runs, so the list is what the delete does. Reads only.\n */\nexport async function previewHostErase(\n orgId: string,\n hostId: string,\n): Promise<HostErasePreview> {\n return { resources: await previewPluginSiteResources({ orgId, hostId }) }\n}\n\n/**\n * Permanently erase a single site and everything it owns (AGL-488).\n * Unlike deleting the host doc alone (which orphans data), this cleans up\n * every trailing reference:\n * - Storage objects under `hosts/{hostId}/` (media, CDN variants),\n * - the `hostIndex/{hostId}` routing entry (subdomain/cname resolution),\n * - the owning org's `hosts` routing-map entry, and\n * - the host's Firestore tree (screens, layouts, versions, counters, …)\n * via `recursiveDelete`.\n *\n * Shared by the self-serve delete-site route and the org-erasure pipeline\n * (AGL-487). Fail-soft on Storage/index cleanup so a partial failure never\n * blocks the Firestore delete; safe to re-run.\n */\nexport interface EraseHostOptions {\n /**\n * The console-side sending-domain teardown, injected because this library\n * may not hold the credentials it needs — see `sending-domain-debt.ts`.\n *\n * Absent, the site's domain is not released inline: the debt is recorded on\n * the surviving label claim and `/api/admin/reap-sending-domains` settles\n * it. That is the only correct default here. A library the tenant runtime\n * imports cannot reach a full-access mail credential, and an erasure must\n * not fail or stall because a vendor is unreachable.\n */\n tearDownSendingDomain?: TeardownSendingDomainDriver | null\n /**\n * Erase the site even while its consent group still needs it (AGL-3320).\n *\n * Only the organization's own erasure passes this: it takes every site and\n * the declaration with them, so no sibling is left to read the refusals.\n * Every other caller is refused with {@link SiteInConsentGroupError} for a\n * site that is in a declared group or in a change still running — its\n * opt-outs are read by its siblings, and erasing them would start mailing\n * people who said no.\n */\n allowInConsentGroup?: boolean\n}\n\n/**\n * {@link eraseHost} refused a site its consent group still needs (AGL-3320).\n * Nothing was erased; the site leaves its group, and is deleted after.\n */\nexport class SiteInConsentGroupError extends Error {\n readonly hostId: string\n readonly hold: ConsentGroupSiteHold\n\n constructor(hostId: string, hold: ConsentGroupSiteHold) {\n super(\n hold.reason === 'grouped'\n ? `Site ${hostId} is in the consent group \"${hold.name}\"; remove it from the group before deleting it`\n : `Site ${hostId} is in a consent group change that has not finished`,\n )\n this.name = 'SiteInConsentGroupError'\n this.hostId = hostId\n this.hold = hold\n }\n}\n\n/*==========================================\n * ONE FAILED WRITE IN THE TREE IS NOT A FAILED DELETE.\n *\n * `recursiveDelete` is a bulk writer: a site is hundreds of deletes, and one\n * that meets `UNAVAILABLE` or a deadline under load rejects the whole call\n * with that write's code. Thrown from here it reached the delete route as a\n * 500, for a site whose tree was gone, so the console said the delete failed\n * and a retry found nothing to delete.\n *\n * So a transient failure runs the delete again, which is safe because a\n * delete of what is already gone does nothing, and walks the subcollections\n * whether or not the parent document still exists. When the retries are\n * spent, or the failure was not transient, the host document decides: the\n * bulk writer deletes it LAST, so its absence means the site is erased and\n * no reader can route to it. What a write left behind is logged; the\n * delete answers as done. A host document still standing is a real failure\n * and is thrown.\n *=========================================*/\nasync function eraseHostTree(\n firestore: FirebaseFirestore.Firestore,\n hostRef: FirebaseFirestore.DocumentReference,\n hostId: string,\n): Promise<void> {\n try {\n await retryTransientFirestore(() => firestore.recursiveDelete(hostRef), {\n onRetry: (error, attempt) =>\n console.warn(`eraseHost: retrying the tree delete for ${hostId} (${attempt})`, error),\n })\n } catch (error) {\n const remaining = await retryTransientFirestore(() => hostRef.get()).catch(() => null)\n if (remaining && !remaining.exists) {\n console.error(\n `eraseHost: the tree delete for ${hostId} reported a failure after the site was erased`,\n error,\n )\n return\n }\n throw error\n }\n}\n\nexport interface EraseHostResult {\n /** What became of the site's dedicated sending domain, if it had one. */\n sendingDomain: SendingDomainDisposition\n}\n\nexport async function eraseHost(\n hostId: string,\n options: EraseHostOptions = {},\n): Promise<EraseHostResult> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n const orgId = hostSnapshot.get('orgId') as string | undefined\n // Everyone holding a role on the site itself, org member or not: each has a\n // `users/{uid}/hostMemberships/{hostId}` row the switcher and the console's\n // address resolution read, so each must lose it with the site.\n const hostMemberUids = Object.keys(\n (hostSnapshot.get('memberRoles') as Record<string, unknown> | undefined) ??\n {},\n )\n\n /*==========================================\n * A SITE ITS CONSENT GROUP STILL NEEDS IS NOT ERASED (AGL-3320).\n *\n * Asked before anything is destroyed. A grouped site's opt-outs are read by\n * every site in its group, so erasing them would let its siblings mail the\n * people who unsubscribed here, and would leave the declaration naming a\n * site that no longer exists. The site leaves the group first — the change\n * that removes it carries its refusals to the sites that stay.\n *=========================================*/\n if (orgId && options.allowInConsentGroup !== true) {\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const hold = consentGroupSiteHold(\n (orgSnapshot.data() ?? null) as Record<string, unknown> | null,\n hostId,\n )\n if (hold) throw new SiteInConsentGroupError(hostId, hold)\n }\n\n /*==========================================\n * THE SENDING DOMAIN, READ FIRST AND RELEASED LAST.\n *\n * Read here because the pinned label lives on the host document and the\n * `recursiveDelete` at the bottom of this function destroys it. Read\n * afterwards there would be nothing left to say WHICH provider domain holds\n * a plan-capped account slot and WHICH records in our zone carry a signing\n * key for a name a future site can claim.\n *\n * Released after everything else, so a teardown that dies partway leaves the\n * claim standing and the domain findable rather than orphaning two vendors'\n * resources with nothing pointing at them.\n *=========================================*/\n const sendingLabel = String(hostSnapshot.get('sendingLabel') ?? '').trim()\n const sendingTeardown = sendingLabel\n ? await readSendingDomainTeardownByLabel(sendingLabel).catch(() => null)\n : null\n\n // Storage first (best-effort — the object tree is derived, regenerable).\n try {\n await storageBucket().deleteFiles({ prefix: `hosts/${hostId}/` })\n } catch (error) {\n console.error(`eraseHost: storage cleanup failed for ${hostId}`, error)\n }\n // And the delivery provider's copies of the site's video (AGL-2824), held\n // under the same library prefix. Nothing runs when no provider is\n // configured to store; a failure is logged, like the bucket's.\n await eraseMediaDeliveryScope({ collection: 'hosts', scopeId: hostId })\n\n // Dead-lettered supplier deliveries (AGL-1448). See the note on\n // SUPPLIER_DELIVERY_COLLECTION below for why this is here and not implied\n // by the recursiveDelete at the end of this function.\n await eraseHostSupplierDeliveries(hostId)\n // In-app notifications about the site, in every inbox (AGL-3719).\n await eraseHostNotifications(hostId)\n\n // Routing: the middleware resolves a request to a host via hostIndex and\n // the owning org's hosts map — drop both so the subdomain/cname 404s.\n await firestore\n .collection('hostIndex')\n .doc(hostId)\n .delete()\n .catch(() => undefined)\n if (orgId) {\n // The routing entry and the site's POOLED SEATS go in the SAME write —\n // POS registers (AGL-1775) and collaborators (AGL-2439), which are the\n // same mechanism on two keys and must be released together or a deleted\n // site strands one pool while returning the other.\n //\n // `registerAllocations[hostId]` is capacity the org has\n // paid for and assigned here; a deleted site must return it to the pool\n // or the org keeps paying $89/mo for a seat pinned to a site that no\n // longer exists and cannot be reassigned from any surface. Releasing it\n // by deleting the key rather than by decrementing a counter means the\n // pool is `purchased - sum(allocations)` by arithmetic and has nothing to\n // drift out of step with.\n await firestore\n .collection('orgs')\n .doc(orgId)\n .set(\n {\n hosts: { [hostId]: FieldValue.delete() },\n registerAllocations: { [hostId]: FieldValue.delete() },\n collaboratorAllocations: { [hostId]: FieldValue.delete() },\n },\n { merge: true },\n )\n .catch(() => undefined)\n // Drop every member's reverse-index row for this host (AGL-844); the\n // members still exist here (recursiveDelete of the org, if any, is later).\n await deleteHostProjectionForAllMembers(\n orgId,\n hostId,\n hostMemberUids,\n ).catch((error) => {\n console.error(`eraseHost: projection cleanup failed for ${hostId}`, error)\n })\n await eraseHostOwnedOrgDocuments(orgId, hostId)\n // Before the plugins decide what is this site's own: a document shared with\n // all sites except some and reaching only this site comes off it here, so\n // it reads as the workspace's and stays (AGL-4047). Never throws.\n await sweepScopeSharingAfterSiteChange({ orgId, reason: 'site-removed', hostId })\n // What plugins share with this site alone — a dataset and its records —\n // and this site's place in the sharing of what it shares with others\n // (AGL-4003). Each plugin's share is isolated and never throws here.\n await erasePluginSiteResources({ orgId, hostId })\n }\n\n // The host document tree (screens/layouts/versions/counters/products/…).\n await eraseHostTree(firestore, hostRef, hostId)\n\n // The plugin rows keyed by the site that its tree does not hold (AGL-4214).\n // After the tree, so a register's display can no longer verify against it.\n await erasePluginHostKeyedCollections(hostId)\n\n // Once more now the site is gone: a membership sync that was mid-flight when\n // the first pass ran can write the row back afterwards, and a row for a\n // deleted site keeps it in the switcher and mapped to its subdomain. Last\n // thing that touches the rows, so nothing can follow it.\n await deleteHostProjectionForUids(hostId, hostMemberUids).catch(\n () => undefined,\n )\n\n // The site's names no longer serve it (AGL-3629): plugins undo what they\n // registered for each — commerce's Stripe payment method domains. Raised\n // after the delete, so a plugin checking whether ANOTHER site still serves\n // the name cannot find this one.\n for (const domain of releasedHostNames(hostSnapshot.data())) {\n await runPluginEventHandlers('host.domain.released', {\n orgId: orgId ?? null,\n hostId,\n domain,\n reason: 'site-deleted',\n })\n }\n\n // Never throws, and never leaves the slot unaccounted for: whatever the\n // vendors refuse is recorded on the label claim for the reaper to finish.\n return {\n sendingDomain: await disposeHostSendingDomain({\n teardown: sendingTeardown ? { ...sendingTeardown, hostId } : null,\n tearDown: options?.tearDownSendingDomain,\n }),\n }\n}\n\n/**\n * Delete a single resource document *and everything under it* (AGL-945).\n *\n * Firestore does not cascade: deleting `orgs/{o}/datasets/{d}` leaves every\n * `records/{r}` beneath it alive but unreachable from the console — still\n * billed, still matched by the rules (which match subcollection paths\n * independently of the parent), and resurrected wholesale if the parent id\n * is ever reused. Only the Admin SDK has `recursiveDelete`, so the console\n * cards route their deletes through /api/resources/erase, which lands here.\n *\n * Authorization belongs to the caller — this only walks the tree.\n */\nexport async function eraseSubtree(\n path: readonly [string, string, string, string],\n): Promise<void> {\n const firestore = firebaseAdmin.app().firestore()\n const [scope, scopeId, kind, id] = path\n await firestore.recursiveDelete(\n firestore.collection(scope).doc(scopeId).collection(kind).doc(id),\n )\n}\n\n/**\n * The collections the page-view beacon writes under `hosts/{hostId}`\n * (`apps/tenant/app/api/analytics/collect/route.ts`), with `set(…, merge)`.\n */\nexport const HOST_BEACON_COLLECTIONS: readonly string[] = [\n 'analytics',\n 'screenAnalytics',\n]\n\nexport interface ReapHostBeaconRemnantsResult {\n /** Phantom `hosts/{id}` trees removed. */\n reaped: string[]\n /** Phantoms holding anything else — left for a person to look at. */\n left: Array<{ hostId: string; collections: string[] }>\n}\n\n/**\n * Remove what a deleted site's late beacons wrote after `eraseHost` (AGL-3744).\n *\n * The beacon trusts a positive host-exists read for an hour per instance, so\n * a tab left open on a site that is then deleted still lands its dwell or\n * page view, and the merge-write recreates `hosts/{id}/analytics/{day}` or\n * `screenAnalytics/{screenId}:{day}` under a host with no document. Nothing\n * reads those again, and nothing else would ever delete them: a 2026-10-12\n * audit found one standing three days after its site was erased.\n *\n * A host document is written before any beacon can count for it, so a\n * missing document whose only children are the beacon's own counters is a\n * deleted site and nothing else. A phantom holding any other collection is\n * not this leak and is reported, never deleted.\n *\n * `listDocuments` lists every host id once, which is a run's whole cost.\n */\nexport async function reapHostBeaconRemnants(\n options: { dryRun?: boolean } = {},\n): Promise<ReapHostBeaconRemnantsResult> {\n const firestore = firebaseAdmin.app().firestore()\n const result: ReapHostBeaconRemnantsResult = { reaped: [], left: [] }\n const refs = await firestore.collection('hosts').listDocuments()\n for (let index = 0; index < refs.length; index += 300) {\n const snapshots = await firestore.getAll(...refs.slice(index, index + 300))\n for (const snapshot of snapshots) {\n if (snapshot.exists) continue\n const collections = (await snapshot.ref.listCollections()).map(\n (collection) => collection.id,\n )\n if (!collections.every((id) => HOST_BEACON_COLLECTIONS.includes(id))) {\n result.left.push({ hostId: snapshot.id, collections })\n continue\n }\n if (!options.dryRun) await firestore.recursiveDelete(snapshot.ref)\n result.reaped.push(snapshot.id)\n }\n }\n return result\n}\n\n/** Best-effort Stripe customer deletion — PII lives at the processor too. */\nasync function deleteStripeCustomer(customerId?: string): Promise<void> {\n const key = process.env.STRIPE_SECRET_KEY\n if (!key || !customerId) return\n try {\n await fetch(`https://api.stripe.com/v1/customers/${customerId}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${key}` },\n })\n } catch (error) {\n console.error(`eraseOrg: Stripe customer ${customerId} delete failed`, error)\n }\n}\n\n/**\n * Delete every API credential the org owns (AGL-1444).\n *\n * `apiKeys` is a TOP-LEVEL collection keyed by the SHA-256 of the token and\n * carrying `orgId` as a FIELD, so `recursiveDelete(orgRef)` cannot see it —\n * a path-scoped cascade is structurally blind to anything not under the path.\n * The credential therefore outlived the workspace: `verifyApiKey` kept\n * resolving the token to a live principal naming an org that no longer\n * existed. `authenticateApiV1` happens to refuse it (it reads the org doc and\n * 401s), but that is a gate one layer above the credential, and a key whose\n * revocation depends on every future caller repeating a lookup is not\n * revoked. The document is also a small record of the erased workspace in its\n * own right — a human-authored label, the creating uid, the granted scopes.\n *\n * Bounded by the `orgId` field, never a collection sweep: this collection\n * holds every other customer's integration credentials too.\n *\n * Returns the number destroyed, for the audit row — an erasure trail that\n * understates what it removed is the one record that has to be right.\n */\nasync function eraseOrgApiKeys(orgId: string, dryRun = false): Promise<number> {\n return deleteDocsByOrgId('apiKeys', orgId, dryRun)\n}\n\n/**\n * Sweep every top-level plugin collection keyed by this org (AGL-3080).\n *\n * The collections are the plugins' own, DECLARED by each owner in\n * `plugins.config.json` (`orgKeyedCollections`) and compiled into core, so the\n * sweep names none of them and runs in every process whether or not the\n * owner is loaded. Sequential and field-bounded like every other org-keyed\n * sweep: each of these collections holds every other workspace's rows too.\n *\n * Returns the count destroyed per collection, for the audit row.\n */\nasync function erasePluginOrgKeyedCollections(\n orgId: string,\n dryRun = false,\n): Promise<Record<string, number>> {\n const counts: Record<string, number> = {}\n for (const { name, orgField } of PLUGIN_ORG_KEYED_COLLECTIONS) {\n counts[name] = await deleteDocsByOrgId(name, orgId, dryRun, orgField)\n }\n return counts\n}\n\n/**\n * Delete every document in a TOP-LEVEL collection that names this org in its\n * `orgId` FIELD (AGL-1444/AGL-1448). `orgField` names another field, which is\n * how a site delete sweeps the collections keyed by a site (AGL-4214).\n *\n * The shared mechanism behind every collection a path-scoped cascade cannot\n * see. Two properties are the whole point, and neither is optional:\n *\n * - **Bounded by the field, never a collection sweep.** Every one of these\n * collections holds other customers' credentials, routing and billing\n * correlations. A `collection(name).get()` here would erase the estate.\n * - **Chunked**, because a batch caps at 500 writes and nothing bounds an\n * org's row count below that.\n *\n * Returns the number destroyed, for the audit row — an erasure trail that\n * understates what it removed is the one record that has to be right.\n *\n * `dryRun` runs the query and skips the commit (AGL-1481), so a plan counts\n * rows through the SAME function that deletes them. A separate counting pass\n * would be a second enumeration of the sweep list, which is precisely the\n * divergence AGL-1481 exists to remove.\n *\n * **`platformRevenue` must NEVER be added to this sweep (AGL-1811).** It is\n * org-keyed by field — exactly the shape this mechanism eats — and that is\n * the trap: those rows are per-transaction TAX FILING RECORDS (gross, tax,\n * jurisdiction) with a statutory retention obligation, and the quarterly\n * Texas return is their sum. GDPR Art. 17(3)(b) exempts them: erasure does\n * not extend to records retained for compliance with a legal obligation. An\n * erased org's rows deliberately outlive it — the\n * `erase-org-tax-retention.emulator.spec` pins survival, so an over-eager\n * future sweep fails a test instead of un-filing a tax period.\n *\n * **`storefrontTaxCollected` must NEVER be added either (AGL-1904).** Same\n * shape, same trap, same reason: it carries `orgId` as a field, and its rows\n * are the record of sales tax charged to shoppers on that org's storefront —\n * including the tax a `mode: 'stripe'` store collects under AGLYN's own\n * Texas registration, which Aglyn must be able to account for long after the\n * merchant has gone.\n *\n * **`posHardwareSales` must NEVER be added either (AGL-4038).** Same shape,\n * same trap: one row per card reader order a workspace bought from the\n * platform's hardware shop — the platform's OWN sale, on which it owes the\n * sales tax. The order under `orgs/{orgId}/hardwareOrders`, with the buyer's\n * name, street, phone and email, dies with the tree as it should; the row\n * keeps only the lines, amounts, tax, Stripe ids, status dates and the\n * country, state and postal code it shipped to. The\n * `erase-org-tax-retention.emulator.spec` pins its survival too.\n */\nasync function deleteDocsByOrgId(\n collection: string,\n orgId: string,\n dryRun = false,\n orgField = 'orgId',\n): Promise<number> {\n if (!orgId) return 0\n const firestore = firebaseAdmin.app().firestore()\n const rows = await firestore\n .collection(collection)\n .where(orgField, '==', orgId)\n .get()\n if (dryRun) return rows.size\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) batch.delete(doc.ref)\n await batch.commit()\n }\n return rows.size\n}\n\n/**\n * Drop the org's public SSO routing documents (AGL-1448).\n *\n * `ssoDomains/{domain}` is keyed by the DOMAIN and carries `orgId` as a field,\n * so `recursiveDelete(orgRef)` never reaches it. The org's own claims under\n * `orgs/{orgId}/ssoDomains/{domain}` do die with the tree; the public routing\n * doc — the one that decides where a sign-in goes — does not.\n *\n * **`unpublishSsoDomains` is not the fix, though it looks like it.** That\n * function is the reversible half of the console's SSO toggle: it sets\n * `active: false` and leaves the document standing precisely so re-enabling\n * restores the same pool and the same uids. Applied to an erasure it would\n * leave behind a record naming the deleted org, its GCIP tenant and provider\n * ids, its IdP display name and the customer's email domain — and, worse, a\n * live reservation: `issueDomainClaim` refuses a domain whose `ssoDomains` doc\n * belongs to another org REGARDLESS of `active`, so a ghost would hold a real\n * customer's domain against them with no way to appeal. Absence is the only\n * state that both stops the routing and releases the name.\n *\n * Deleting is safe on the read side: `/api/auth/sso-lookup` already treats a\n * missing doc and an inactive one identically (`{ ssoEnabled: false }`).\n */\nasync function eraseOrgSsoDomains(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n return deleteDocsByOrgId('ssoDomains', orgId, dryRun)\n}\n\n/**\n * Release every custom console domain the org holds (AGL-1448).\n *\n * `releaseConsoleDomain` already does exactly the right thing and was called\n * from nothing but its own spec. It is wired rather than reimplemented, and\n * the ordering it enforces is the reason: Vercel detach FIRST, documents\n * second, and the claim KEPT if a detach fails. `resolveConsoleDomain`'s\n * `unknown` verdict — the one that lets localhost, previews and self-hosted\n * installs work — is only safe while every name the console project still\n * answers for has a document (AGL-1430). Deleting the claim here directly\n * would break that correspondence and hand the name to the next org that\n * claims it, with Vercel's `already-exists` reading as health.\n *\n * It takes one domain, so the org-bounded query is the part that was missing.\n * Every name in a claim set — the primary and its `www` twin — carries the\n * same `orgId` and the same `primaryHost`, so releasing once per distinct\n * primary covers the set exactly, without a second pass over the twins.\n *\n * Best-effort, like every other external cleanup here: an erasure must not\n * fail because Vercel did. A name that could not be detached keeps its claim\n * and is reported in the audit row as un-released.\n */\nasync function releaseOrgConsoleDomains(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n const firestore = firebaseAdmin.app().firestore()\n const claims = await firestore\n .collection(CONSOLE_DOMAINS_COLLECTION)\n .where('orgId', '==', orgId)\n .get()\n const primaries = new Set(\n claims.docs.map((doc) => (doc.get('primaryHost') as string) || doc.id),\n )\n // A plan counts the claim sets it WOULD release. `releaseConsoleDomain`\n // detaches at Vercel, so it must not run for a dry run (AGL-1481).\n if (dryRun) return primaries.size\n let released = 0\n for (const domain of primaries) {\n const result = await releaseConsoleDomain({ orgId, domain }).catch(\n (error) => {\n console.error(`eraseOrg: console domain ${domain} release failed`, error)\n return { released: false }\n },\n )\n if (result.released) released += 1\n }\n return released\n}\n\n/**\n * Drop the local Stripe reverse index (AGL-1448, AGL-1028).\n *\n * `stripeCustomers/{stripeCustomerId} -> { orgId }` exists because AGL-1028\n * moved `stripeCustomerId` off the org doc into a manager-gated subcollection,\n * which broke the webhook's `where('stripeCustomerId', '==', …)` lookup. It is\n * denied to every client for one reason, stated in the rules: readable, it\n * maps a billing identity back to a workspace.\n *\n * The erasure had this exactly inverted. It deleted the customer AT STRIPE and\n * kept the local index — so the artefact that survived was the correlation the\n * whole issue existed to prevent, now pointing at an org that no longer exists\n * to be gated on. This deletes the local rows. The Stripe-side delete is\n * unchanged and still runs: PII lives at the processor too, and one is not a\n * substitute for the other.\n *\n * Bounded by the `orgId` field rather than by the org's CURRENT customer id,\n * because nothing cleans up the index when a customer id changes — an org that\n * was re-created in Stripe has more than one row pointing at it.\n */\nasync function eraseOrgStripeIndex(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n return deleteDocsByOrgId('stripeCustomers', orgId, dryRun)\n}\n\n/**\n * Drop the org's REST API replay keys (AGL-1448).\n *\n * `apiIdempotency/{sha256(orgId:key)}` dedupes `POST`s by `Idempotency-Key`\n * (AGL-618). Low severity — a replay key names an org and a record id and\n * authorises nothing — but it does NOT age out on its own, which is the part\n * worth writing down because the assumption runs the other way: the only TTL\n * policy on the database is `rateLimits.expiresAt`\n * (`docs/FIRESTORE_MANUAL_CONFIG.md`), and these documents carry no expiry\n * field for a policy to key on. Left alone they accumulate against a dead org\n * indefinitely.\n *\n * Taken with the credentials rather than at the end: the record ids they carry\n * point into the org tree that step 4 destroys.\n */\nasync function eraseOrgIdempotencyKeys(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n return deleteDocsByOrgId('apiIdempotency', orgId, dryRun)\n}\n\n/**\n * Release every slug the org has EVER held (AGL-1448).\n *\n * The erasure deleted `orgSlugs/{org.slug}` — the current name only. But\n * `changeOrgSlug` leaves a tombstone at the previous slug (`{ orgId, movedTo,\n * renamedAt }`) so old workspace URLs keep redirecting (AGL-585/AGL-236), and\n * nothing ever collected them. Every historical name an org held therefore\n * survived its erasure, in the one collection the rules make\n * `allow read: if true` — public because it doubles as the pre-auth health\n * probe. An erased workspace's naming history stayed world-readable, each\n * tombstone still naming the dead org id.\n *\n * Bounded by the `orgId` field, which is exactly the right boundary here and\n * not merely the safe one: claiming a tombstoned slug FULL-REPLACES the\n * document with the new owner's `{ orgId }`, so a name this org renamed away\n * from and somebody else has since taken does not match — and must not be\n * swept, because it is now a live tenant's reservation.\n *\n * The current slug is unioned in rather than assumed present: an org whose\n * reservation was lost to a legacy write would otherwise keep its workspace\n * subdomain attached to the project. ⛔ ONLY WHEN NOBODY HOLDS IT (AGL-2585).\n * A workspace address taken by an unverified signup is a reservation that\n * lapses, and a live workspace may since have claimed the name — at which\n * point `orgSlugs/{slug}` names THAT org, and the erasure of this one would\n * otherwise delete a working tenant's reservation and detach their subdomain.\n * The `orgId` query above already refuses that document; this is the one line\n * that used to add it back by assumption.\n *\n * Each name's `{slug}.aglyn.com` is detached too. `changeOrgSlug` deliberately\n * KEEPS the old subdomain attached so the tombstone's 308 has a hostname to\n * run on; once the tombstone goes, the attachment is a name resolving to a\n * console for an org that does not exist. Best-effort, like every other\n * external cleanup here: an erasure must not fail because a DNS API did.\n */\nasync function eraseOrgSlugs(\n orgId: string,\n currentSlug?: string,\n dryRun = false,\n): Promise<number> {\n const firestore = firebaseAdmin.app().firestore()\n const held = await firestore\n .collection('orgSlugs')\n .where('orgId', '==', orgId)\n .get()\n const slugs = new Set(held.docs.map((doc) => doc.id))\n if (currentSlug && !slugs.has(currentSlug)) {\n // Absent means the reservation was lost and only the DNS attachment is\n // left to clean up. Present but not matched by the query above means it\n // belongs to another org now, and is not this erasure's to touch.\n const reservation = await firestore\n .collection('orgSlugs')\n .doc(currentSlug)\n .get()\n .catch(() => null)\n if (reservation && !reservation.exists) slugs.add(currentSlug)\n }\n // `detachWorkspaceDomain` calls a live DNS API — never on a plan (AGL-1481).\n if (dryRun) return slugs.size\n for (const slug of slugs) {\n await firestore.collection('orgSlugs').doc(slug).delete().catch(() => undefined)\n await detachWorkspaceDomain(slug).catch(() => undefined)\n }\n return slugs.size\n}\n\n/**\n * Sweep up ORPHANED `hostIndex` rows the per-host loop cannot enumerate\n * (AGL-1448).\n *\n * `hostIndex/{hostId}` is `{ orgId, subdomain }` and `allow read: if\n * isSignedIn()`. It is deleted today inside `eraseHost`, which `eraseOrg`\n * calls once per document in `hosts where orgId == org` — so the row is\n * reached DERIVATIVELY, through a second collection, and only for as long as\n * the two agree.\n *\n * **The erasure is itself one of the ways they stop agreeing.** `eraseHost`'s\n * `hostIndex` delete is `.catch(() => undefined)` — fail-soft on purpose, so\n * a transient failure never blocks the Firestore delete — and the very next\n * statement `recursiveDelete`s `hosts/{hostId}`. The instant that lands, the\n * orphaned index row is unreachable from the org side forever: nothing points\n * at it, so neither this run nor any retry can ever enumerate it again. A\n * fail-soft that manufactures a PERMANENT orphan is not fail-soft, and the\n * residue is a signed-in-readable row naming a dead org and the subdomain its\n * customer chose.\n *\n * Bounded by the `orgId` field — this is the table the middleware resolves\n * every request on, so an unbounded sweep here does not lose an index, it\n * takes the estate offline.\n *\n * A BACKSTOP, not a replacement: the per-host loop still does the real work\n * (Storage, the org routing map, the member projections, the host tree). This\n * only collects what that loop structurally cannot see.\n */\nasync function eraseOrgHostIndex(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n return deleteDocsByOrgId('hostIndex', orgId, dryRun)\n}\n\n/**\n * Sweep up `hostMemberships` projections belonging to FORMER members\n * (AGL-1448).\n *\n * `users/{uid}/hostMemberships/{hostId}` carries `{ orgId, subdomain,\n * displayName, nameLower, role }` — the site switcher's row. It lives under a\n * USER, so `recursiveDelete(orgs/{orgId})` cannot reach it, and `eraseOrg`'s\n * members loop only walks `orgs/{orgId}/members`.\n *\n * `deleteHostProjectionForAllMembers(orgId, hostId)` clears the row for\n * everyone in that member list at the moment the erasure runs. **A former\n * member is not in it.** Their row is written by the projection fan-out and\n * removed by `removeOrgMember`, which is fail-soft in the same way as\n * everything else on that path; one missed fan-out leaves a row no later\n * erasure can find, because the enumeration starts from a membership that no\n * longer exists. The erased workspace's site NAME and subdomain then live on\n * in the user document of somebody who left the company.\n *\n * ## This is a COLLECTION-GROUP query, and that owes an index\n *\n * `hostMemberships` has two composite indexes, both `queryScope: COLLECTION`.\n * A collection-group equality on `orgId` needs a `COLLECTION_GROUP`\n * single-field index, which Firestore does NOT create automatically — the\n * automatic single-field indexes are collection-scoped except for\n * array-contains. `cloud/firebase-firestore.indexes.json` therefore gains a\n * `fieldOverrides` entry alongside the existing `members.uid` and\n * `messages.authorId` ones, and **it must be deployed by hand.**\n *\n * Until it is, the query throws `FAILED_PRECONDITION`. AGL-1793 is this\n * codebase's record of exactly that failure mode — both commerce crons\n * silently dead in production for want of a `COLLECTION_GROUP_ASC` override —\n * so this refuses to be the thing that kills an erasure. It is caught and\n * reported as `null`, which is deliberately NOT `0`: a zero would say \"there\n * was nothing to sweep\" and a missing index would wear that as a clean bill\n * of health. `null` in the audit row says \"attempted, could not run\", and the\n * spec asserts a NUMBER so the wired-and-indexed path is what is pinned.\n */\nasync function eraseOrgHostMemberships(\n orgId: string,\n dryRun = false,\n): Promise<number | null> {\n if (!orgId) return 0\n try {\n const firestore = firebaseAdmin.app().firestore()\n const rows = await firestore\n .collectionGroup('hostMemberships')\n .where('orgId', '==', orgId)\n .get()\n if (dryRun) return rows.size\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) {\n batch.delete(doc.ref)\n }\n await batch.commit()\n }\n return rows.size\n } catch (error) {\n console.error(\n `eraseOrg: hostMemberships projection sweep failed for ${orgId} — a missing COLLECTION_GROUP index on hostMemberships.orgId is the likeliest cause`,\n error,\n )\n return null\n }\n}\n\n/**\n * Destroy every support ticket the org opened, and the messages under each\n * (AGL-1971).\n *\n * `supportTickets/{id}` is top-level with `orgId` as a field — the exact shape\n * `deleteDocsByOrgId` exists for — and it was in neither sweep list. It is\n * also the highest-PII-density collection outside the org tree: `messages`\n * rows carry `authorId`, `authorEmail` and up to 5000 characters of prose a\n * customer wrote to us, which is where somebody pastes the invoice, the member\n * list, or the very data they are asking us to delete.\n *\n * **`deleteDocsByOrgId` is deliberately NOT used here**, though the query is\n * identical. It deletes documents, not subtrees, and a batch delete of the\n * ticket documents would leave every `messages` row alive under a parent that\n * no longer exists — the prose and the email surviving the delete that was\n * supposed to remove them, now unreachable by any query that starts from\n * `orgId`. `recursiveDelete` per ticket is the only correct shape.\n *\n * **No retention exception, and the alternative was considered.** A closed\n * support thread is arguable dispute evidence, which is the class of argument\n * that keeps `platformRevenue` alive (AGL-1811). It does not reach here: that\n * exemption is GDPR Art. 17(3)(b), *records retained to comply with a legal\n * obligation*, and no law requires us to keep a support thread — a Texas tax\n * return is filed from `platformRevenue`; nothing is filed from a ticket.\n * Live DPA §11 commits the other way in terms (\"delete or return Customer\n * Personal Data, except to the extent retention is required by law\"). What\n * remains as evidence is the `adminAudit` row: the erasure happened, when, at\n * whose instruction, and how many tickets it destroyed — ids and counts,\n * never content (AGL-1443).\n *\n * Sequential rather than parallel: `recursiveDelete` is itself a bulk writer,\n * and fanning N of them out at once is how a 60-second cron loses an erasure.\n */\nasync function eraseOrgSupportTickets(\n orgId: string,\n dryRun = false,\n): Promise<number> {\n if (!orgId) return 0\n const firestore = firebaseAdmin.app().firestore()\n const tickets = await firestore\n .collection('supportTickets')\n .where('orgId', '==', orgId)\n .get()\n if (dryRun) return tickets.size\n for (const ticket of tickets.docs) {\n await firestore.recursiveDelete(ticket.ref)\n }\n return tickets.size\n}\n\n/**\n * The steps of `eraseOrg` after the hold check, named so a failed attempt can\n * say WHERE it stopped (AGL-1455).\n *\n * `export` used to lead this list, and its removal is the AGL-1443 change: an\n * erasure no longer writes anything before it starts deleting, so there is no\n * longer a step whose meaning is \"nothing is gone yet\". `credentials` is now\n * the first thing that can fail, and it destroys as it goes.\n */\ntype EraseStep =\n | 'plugins'\n | 'credentials'\n | 'support'\n | 'hosts'\n | 'org-storage'\n | 'stripe'\n | 'members'\n | 'org-tree'\n | 'slugs'\n\n/**\n * The two things an OPERATOR needs that a served caller does not (AGL-1481).\n *\n * `tools/scripts/erase-tenant.mjs` is the manual path staff reach for when the\n * cron is stuck. It used to be a second implementation of this function, and it\n * drifted: by the time AGL-1481 was filed it was missing four sweeps added that\n * week and still wrote a complete dump of the workspace to the operator's\n * working directory. The fix is that it CALLS this function — which means the\n * capabilities it had and this function lacked have to live here instead.\n *\n * Neither is a hold bypass, deliberately. The script refused to run before the\n * 7-day hold elapsed and this function refuses too; an `ignoreHold` flag would\n * have been the easy way to keep the two paths identical and is the one\n * difference worth preserving as a refusal on both.\n */\nexport interface EraseOrgOptions {\n /**\n * Count what an erasure WOULD destroy and destroy nothing. Every sweep runs\n * its query and skips its write, so the plan is produced by the same list of\n * sweeps that the erasure is — a separate counting pass would be exactly the\n * second enumeration this issue removed. Nothing external is touched (no\n * Storage, no Stripe, no Vercel, no DNS) and no audit row is written.\n *\n * Returns `ok: false` with `skippedReason: 'dry-run'`: `ok` means the org was\n * erased, and a plan did not erase it. A caller that treats a plan as an\n * erasure is the one mistake this shape has to make impossible.\n */\n dryRun?: boolean\n /**\n * Who is answerable for this erasure, for the audit row. Defaults to the\n * cron. A staff member running the script by hand is not the scheduler, and\n * an erasure trail that says otherwise names the wrong actor for the single\n * most irreversible action the platform performs.\n */\n actorUid?: string\n /**\n * The console-side sending-domain teardown, passed through to every host\n * this erasure destroys. See {@link EraseHostOptions.tearDownSendingDomain}.\n *\n * Never consulted on a dry run: a plan touches no vendor.\n */\n tearDownSendingDomain?: TeardownSendingDomainDriver | null\n /**\n * Erase a workspace that carries NO erasure request at all (AGL-2585).\n *\n * ⛔ EXACTLY ONE CALLER, and the option exists so that caller has to say so\n * out loud. `/api/admin/reap-unverified-orgs` collects workspaces created by\n * a signup whose address was never confirmed — there is nobody to ask for an\n * erasure, because nobody has been shown to exist. Every other path reaches\n * this function through `erasureRequestedAt`, which is a person's decision\n * with a seven-day hold on it, and none of them passes this.\n *\n * What it turns off is narrow and named: the `no-request` refusal and the\n * hold, and nothing else. Every sweep, every audit row and `dryRun` behave\n * identically — the caller supplies the proof that this workspace is\n * nobody's, and this records WHAT that proof was on the audit row.\n *\n * It does not skip the request when one exists. An org somebody has already\n * asked to erase is still that person's decision, and the reaper refuses\n * such an org before it ever gets here.\n */\n withoutRequest?: { reason: string } | null\n}\n\nexport interface EraseOrgResult {\n ok: boolean\n /**\n * Set when the org was NOT erased (flag missing, hold not elapsed, gone) —\n * and `'dry-run'` when nothing was erased because nothing was meant to be.\n */\n skippedReason?: string\n hosts?: number\n /** Member back-references cleaned up — reported so a plan can show them. */\n members?: number\n /** API credentials destroyed (AGL-1444) — outside the org path. */\n apiKeys?: number\n /**\n * What each plugin's workspace eraser did (AGL-2978), keyed by plugin id:\n * counts and flags, such as grants revoked at a provider. The erasers run\n * before anything below is deleted. **`null` means that plugin's eraser\n * failed** and its share may not be done; it is not zero. A plan carries\n * each eraser's count of what it would do.\n */\n plugins?: Record<string, PluginOrgErasureReport | null>\n /**\n * Rows destroyed from each plugin's top-level collection keyed by the org\n * (AGL-3080), keyed by collection: a connected mailbox's grant (AGL-2974),\n * a sequence email's tracking links (AGL-3297). Outside the org path, and\n * declared by their owners rather than named here.\n */\n pluginCollections?: Record<string, number>\n /** Public SSO routing docs destroyed (AGL-1448) — outside the org path. */\n ssoDomains?: number\n /** Custom console domains released (AGL-1448) — outside the org path. */\n consoleDomains?: number\n /** REST API replay keys destroyed (AGL-1448) — no TTL reaps these. */\n apiIdempotency?: number\n /** Local Stripe reverse-index rows destroyed (AGL-1448/AGL-1028). */\n stripeIndex?: number\n /** Slugs released — the current one AND every tombstone (AGL-1448). */\n slugs?: number\n /**\n * ORPHANED `hostIndex` rows collected (AGL-1448) — ones with no surviving\n * `hosts` document for the per-host loop to reach them through.\n */\n hostIndex?: number\n /**\n * `hostMemberships` projections collected (AGL-1448), including FORMER\n * members' rows that no membership list names.\n *\n * `null` means the sweep could not RUN — almost always the missing\n * `COLLECTION_GROUP` index on `hostMemberships.orgId`. Deliberately not\n * `0`: an erasure that could not reach a collection must not report the\n * same number as one that reached it and found nothing.\n */\n hostMemberships?: number | null\n /**\n * Support threads destroyed, each with its `messages` subtree (AGL-1971) —\n * the highest-PII-density collection outside the org path.\n */\n supportTickets?: number\n /**\n * What became of the erased sites' dedicated sending domains.\n *\n * `deferred` is the number an operator reads: those provider slots and zone\n * records are still held, the debt is on each label claim, and\n * `/api/admin/reap-sending-domains` is what settles them. The erasure itself\n * is complete either way — a vendor outage may delay a slot's release and\n * may not delay a deletion somebody has a legal right to.\n */\n sendingDomains?: {\n released: number\n deferred: number\n /** Shared pool members refused. Always 0; a non-zero is a real alarm. */\n protected: number\n }\n}\n\n/**\n * What an in-flight erasure has destroyed so far — counts only.\n *\n * `members` is excluded: the inventory already reports it as `before.members`\n * on both audit rows, and a second copy under `after` would say the same\n * number twice.\n */\ntype EraseProgress = Omit<EraseOrgResult, 'ok' | 'skippedReason' | 'members'>\n\n/**\n * A stable label for an error, carrying no free text (AGL-1455).\n *\n * The class name and the SDK's error code are enough to tell a Firestore\n * permission denial from a deadline exceeded from an out-of-memory kill. The\n * MESSAGE is deliberately not stored: a Firestore or Storage error quotes the\n * path — and sometimes the payload — it choked on, and this row lands in a\n * collection that must not become a second copy of what the erasure failed to\n * delete (AGL-1443). The full error still goes to `console.error`, which is\n * the log, not the record.\n */\nfunction errorLabel(error: unknown): string {\n const source = (error ?? {}) as { name?: unknown; code?: unknown }\n const parts = [source.name, source.code].filter(\n (part) => typeof part === 'string' || typeof part === 'number',\n )\n return parts.length ? parts.join(':') : 'unknown'\n}\n\n/**\n * Record a failed erasure attempt where somebody will actually find it\n * (AGL-1455).\n *\n * Aborting when the export cannot be written is correct and stays — the bug\n * was that the abort was invisible. `skippedReason` reached exactly one\n * place, the cron endpoint's HTTP response body, and nobody reads a\n * scheduler's 200. Meanwhile `erasureRequestedAt` stays set, so the same org\n * is retried on the next run and fails the same way indefinitely, and the\n * customer who requested the erasure is told nothing.\n *\n * An `adminAudit` row is the cheapest durable form and the one the success\n * path already uses, so the two read as a pair: same `actorUid`, same\n * `target`, same `before` inventory, and `after` carrying what actually\n * happened. Staff can find every stuck erasure by filtering the audit log on\n * the action, which is exactly the search that was impossible before.\n *\n * `after.exportWritten`/`after.exportPath` used to be the fields that\n * mattered here: they named the complete dump of a still-existing workspace\n * that a post-export failure left in the bucket. AGL-1443 removed the write,\n * so that state is no longer reachable and the fields no longer exist. What\n * replaces them is `after.requestedAt` — WHICH erasure request is stuck,\n * which the object's name used to be the only record of.\n *\n * Ids, counts, a step name and a timestamp. Never customer data.\n *\n * Best-effort and never throws: this runs while an erasure is already\n * failing, and losing the original error to a bookkeeping write would be\n * worse than losing the row.\n */\nasync function recordErasureFailure(entry: {\n orgId: string\n step: EraseStep\n error: unknown\n /** Whoever asked for the erasure — the cron, or a named operator. */\n actorUid: string\n /** Millis of the `erasureRequestedAt` this attempt was fulfilling. */\n requestedAt: number\n before: { hosts: number; members: number }\n after: Record<string, unknown>\n}): Promise<void> {\n await addAdminAudit(firebaseAdmin.app().firestore(), {\n actorUid: entry.actorUid,\n action: 'org.erase-failed',\n target: `orgs/${entry.orgId}`,\n before: entry.before,\n after: {\n failedStep: entry.step,\n error: errorLabel(entry.error),\n requestedAt: entry.requestedAt,\n ...entry.after,\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch((auditError) => {\n console.error(\n `eraseOrg: could not record the failed attempt for ${entry.orgId}`,\n auditError,\n )\n })\n}\n\n/**\n * Permanently erase an organization once its 7-day hold has elapsed\n * (AGL-485/487). Runs from the automated cron and the manual staff path.\n *\n * **Both of those are literally this function (AGL-1481).** The manual path,\n * `tools/scripts/erase-tenant.mjs`, used to be a second implementation, and a\n * second implementation of a cascade delete is a divergence with a schedule:\n * within a week of `eraseOrgApiKeys`, the SSO/console-domain release and the\n * org-keyed index sweeps landing here, the script was missing all four and\n * reporting success without them — leaving a live API credential, live domain\n * reservations, `orgSlugs` tombstones and the `stripeCustomers` reverse index\n * behind an erasure a human had been told was complete. The script now calls\n * this, and `EraseOrgOptions` is where the two capabilities it had and this\n * did not (a plan, and a named actor) live instead.\n *\n * Order matters and every step is defensive:\n * 1. Re-read the org and re-verify erasureRequestedAt + hold — never\n * delete on a stale/cancelled request.\n * 2. Nothing is written. This step used to persist a final JSON export of\n * the org and host trees to `erasures/{orgId}/…` and abort if it could\n * not — see the note below for why it is gone (AGL-1443).\n * 3. The plugins' erasers first (AGL-2978), while everything they may need\n * to act through still exists — a REQUIRED one (the marketplace's, which\n * erases the org's public publisher identity, AGL-1970) fails the step\n * rather than recording its share as undone. Then revoke the org's API\n * credentials (AGL-1444), its public routing — SSO domains and custom\n * console domains (AGL-1448) — and sweep every plugin collection keyed\n * by the org that its owner declared (a connected mailbox's OAuth grant,\n * AGL-2974). All of them are top-level collections keyed by something\n * other than a path under the org, so the org-tree delete cannot reach\n * them; doing them before the content delete also closes the mid-erasure\n * window, in which a credential, a domain or a public publisher page\n * still resolves to a half-deleted workspace.\n * 4. Delete each host (eraseHost), org-level Storage, the Stripe customer\n * AND its local reverse index, member back-references, then the org tree\n * and every slug the org ever held — tombstones included (AGL-1448).\n * 5. Audit.\n *\n * Every ending is audited, not just the successful one (AGL-1455). A throw\n * from any step writes an `org.erase-failed` row before re-throwing, because\n * `erasureRequestedAt` stays set on a failure: without a record the org is\n * retried and fails identically on every subsequent run, forever, and nothing\n * anywhere says so.\n *\n * **The erasure writes no copy of the workspace (AGL-1443).** It used to\n * persist `erasures/{orgId}/{requestedMs}.json` — and \"export\" understated\n * it: `exportDocTree` recursed `listCollections()` with no bound and copied\n * `snapshot.data()` wholesale, so the object was a complete verbatim copy of\n * the org tree and every host tree, carrying `webhooks.secret` (a plaintext\n * HMAC key), `orders.paymentLinkUrl` (a live bearer URL that lets its holder\n * pay), `screens.protection.passwordHash` and `ssoDomains.token`. It landed\n * on a prefix this function's own storage sweep does not cover, in a bucket\n * with no lifecycle rule, so the most sensitive object the platform can\n * produce outlived the request that deleted everything else — indefinitely,\n * unread, and belonging to a customer who had been told their workspace was\n * gone. Four facts decided it, and none of them is about tidiness:\n *\n * - **Nothing read it.** One producer, zero consumers in the repo; the\n * owner's confirmation email never mentioned it.\n * - **A governed full copy already exists.** Firestore backups run weekly\n * with 14-week retention (AGL-871), so the dump added no recoverability —\n * only a second, ungoverned place the data lived.\n * - **The minimum that proves an erasure was already being written.** The\n * `adminAudit` row below is ids and counts, in a collection with a\n * retention policy. The one thing the object's NAME carried that the row\n * did not — which request this run fulfilled — is now `after.requestedAt`.\n * - **The DPA commits to \"a limited period, after which deleted or\n * de-identified\"**, which indefinite retention of a full dump sits\n * outside of.\n *\n * Two consequences are deliberate, not side effects. The export-write abort\n * is gone with the write: there is nothing left to fail before the first\n * delete, so an erasure can no longer be blocked by Storage. And the export\n * was the only unbounded work in this function — it built the whole workspace\n * in memory inside a 60-second cron, so the larger the workspace the likelier\n * its erasure silently never happened (AGL-1455 half 1). That defect is\n * removed by deletion rather than by a streaming exporter.\n */\nexport async function eraseOrg(\n orgId: string,\n options: EraseOrgOptions = {},\n): Promise<EraseOrgResult> {\n const {\n dryRun = false,\n actorUid = 'cron:run-erasures',\n tearDownSendingDomain = null,\n withoutRequest = null,\n } = options\n const firestore = firebaseAdmin.app().firestore()\n const orgRef = firestore.collection('orgs').doc(orgId)\n const orgSnapshot = await orgRef.get()\n if (!orgSnapshot.exists) return { ok: false, skippedReason: 'not-found' }\n\n const requestedMs = orgSnapshot.get('erasureRequestedAt')?.toMillis?.() ?? null\n // The request and its hold, unless the caller carries its own proof\n // (AGL-2585). Both refusals are skipped together: a workspace with no\n // request has no stamp for a hold to run from, so keeping the second while\n // dropping the first would be a hold measured against `null`.\n if (!withoutRequest) {\n if (!requestedMs) return { ok: false, skippedReason: 'no-request' }\n if (Date.now() - requestedMs < ERASURE_HOLD_MS) {\n return { ok: false, skippedReason: 'hold-active' }\n }\n }\n\n const hosts = await firestore\n .collection('hosts')\n .where('orgId', '==', orgId)\n .get()\n const members = await orgRef.collection('members').get()\n const slug = orgSnapshot.get('slug') as string | undefined\n // AGL-1028: moved to `orgs/{orgId}/billing/stripe`; the helper falls back\n // to the org doc for orgs the backfill has not reached.\n const stripeCustomerId = (await readOrgBilling(orgId)).stripeCustomerId as\n | string\n | undefined\n\n // The inventory both audit rows report, taken before anything is touched.\n const before = { hosts: hosts.size, members: members.size }\n\n // No export. The write that used to stand here is gone (AGL-1443) — see\n // the note above this function. Nothing is persisted anywhere before the\n // deleting starts, and `requestedMs` now travels in the audit row rather\n // than in an object's name.\n\n // None of what follows was guarded (AGL-1455) — `eraseOrgApiKeys`,\n // `eraseOrgSsoDomains`, `eraseOrgIdempotencyKeys` and `recursiveDelete` all\n // throw. A throw here leaves a workspace half destroyed and still standing,\n // recorded nowhere. Each step now names itself, and the error is re-thrown\n // unchanged — this adds a record, it does not swallow the failure. What it\n // can no longer leave behind is the state that used to be the worst one: a\n // surviving workspace with its own complete dump already in the bucket.\n const progress: EraseProgress = {}\n let step: EraseStep = 'plugins'\n try {\n // The plugins' share first (AGL-2978), while the org, its roster and\n // every record swept below still exist: an eraser that revokes a grant at\n // its provider opens the stored grant to do it. Each eraser is isolated,\n // so a failing one is recorded as `null` and stops nothing; on a plan\n // each one counts and touches no provider.\n progress.plugins = await runPluginOrgErasers({ orgId, dryRun })\n\n step = 'credentials'\n // Credentials and routing BEFORE content (AGL-1444/AGL-1448). The org doc\n // survives until the recursiveDelete at the end, so a key presented — or a\n // sign-in routed, or a console domain resolved — mid-erasure would still\n // pass the org gate and reach a half-deleted workspace. Revoking first\n // closes that window as well as the permanent one.\n progress.apiKeys = await eraseOrgApiKeys(orgId, dryRun)\n // The plugins' top-level collections keyed by this org (AGL-3080) — a\n // connected mailbox's OAuth grant, a sequence email's tracking links.\n // Declared by the owning plugin and swept HERE, statically, not by its\n // eraser: an erasure cannot rely on a plugin being loaded, and a grant\n // that can still send as a person must not outlive the workspace it was\n // given to because an erasing process never loaded that plugin's bundle.\n progress.pluginCollections = await erasePluginOrgKeyedCollections(orgId, dryRun)\n progress.ssoDomains = await eraseOrgSsoDomains(orgId, dryRun)\n progress.consoleDomains = await releaseOrgConsoleDomains(orgId, dryRun)\n progress.apiIdempotency = await eraseOrgIdempotencyKeys(orgId, dryRun)\n\n\n // Support threads (AGL-1971). Its own step because it is the only sweep\n // here that walks a subtree per row, so it is the one most likely to be\n // where a large workspace's erasure runs out of time — and a failure that\n // cannot say WHICH step stopped it is the AGL-1455 defect again.\n step = 'support'\n progress.supportTickets = await eraseOrgSupportTickets(orgId, dryRun)\n\n /*\n * Hosts (Storage + routing + Firestore trees + the sending domain).\n *\n * Each site's dedicated domain is released here rather than by a sweep\n * that never existed: a workspace erasure used to leave one plan-capped\n * provider slot and three zone records per site standing forever, with\n * the DKIM key still live under a label a future site could claim.\n *\n * The driver is passed in and may be absent, and either way the erasure\n * finishes. What the vendors refuse is recorded as a debt on the label\n * claim, which survives the `recursiveDelete` of both the host and the\n * org, and the reaper settles it.\n */\n step = 'hosts'\n progress.hosts = 0\n progress.sendingDomains = { released: 0, deferred: 0, protected: 0 }\n for (const host of hosts.docs) {\n if (!dryRun) {\n // The whole organization goes, declaration and all, so no site is\n // left to read the refusals a grouped site holds.\n const erased = await eraseHost(host.id, {\n tearDownSendingDomain,\n allowInConsentGroup: true,\n })\n if (erased.sendingDomain === 'released') {\n progress.sendingDomains.released += 1\n }\n if (erased.sendingDomain === 'deferred') {\n progress.sendingDomains.deferred += 1\n }\n if (erased.sendingDomain === 'protected') {\n progress.sendingDomains.protected += 1\n }\n }\n progress.hosts += 1\n }\n\n // The backstop for what the loop above cannot enumerate (AGL-1448): a\n // `hostIndex` row whose `hosts` document is already gone. AFTER the loop\n // deliberately — the loop's own fail-soft delete is one of the things\n // that creates them, so sweeping first would leave this run's orphans\n // behind for a retry that can no longer see them.\n progress.hostIndex = await eraseOrgHostIndex(orgId, dryRun)\n\n // Org-level Storage (media/dataset assets outside the host prefix).\n step = 'org-storage'\n if (!dryRun) {\n try {\n await storageBucket().deleteFiles({ prefix: `orgs/${orgId}/` })\n } catch (error) {\n console.error(`eraseOrg: org storage cleanup failed for ${orgId}`, error)\n }\n // The org library's copies at the delivery provider (AGL-2824); each\n // site's went with its `eraseHost` above.\n await eraseMediaDeliveryScope({ collection: 'orgs', scopeId: orgId })\n }\n\n // Stripe: the customer at the processor, AND the local reverse index that\n // correlates that identity back to this workspace (AGL-1448). Deleting\n // only the first left exactly the record AGL-1028 denied to every client.\n step = 'stripe'\n // `readOrgBilling` hands back the customer for THIS deployment's Stripe\n // mode (AGL-2486), which is the only one `deleteStripeCustomer` could act\n // on anyway — it spends `STRIPE_SECRET_KEY`, and a live key cannot delete a\n // test customer. Known residue, deliberately not chased here: an org that\n // was also exercised in TEST mode leaves its test customer standing at\n // Stripe after a live erasure. That is synthetic data created by us, not\n // subject data supplied by the workspace, and reaching it would mean\n // erasure spending a second API key in a mode this deployment is not in.\n if (!dryRun) await deleteStripeCustomer(stripeCustomerId)\n progress.stripeIndex = await eraseOrgStripeIndex(orgId, dryRun)\n\n // Members' reverse index into this org.\n step = 'members'\n if (!dryRun) {\n for (const member of members.docs) {\n await firestore\n .collection('users')\n .doc(member.id)\n .collection('orgs')\n .doc(orgId)\n .delete()\n .catch(() => undefined)\n }\n }\n\n // The backstop for the members loop (AGL-1448): a `hostMemberships`\n // projection belonging to somebody who has LEFT the org, whom\n // `deleteHostProjectionForAllMembers` cannot enumerate because the\n // membership it would start from is already gone. Collection-group —\n // see the note on the function, and the index it owes.\n progress.hostMemberships = await eraseOrgHostMemberships(orgId, dryRun)\n\n // The org subtree, then every slug reservation it has ever held — the\n // current one and each rename tombstone (AGL-1448), with the matching\n // `{slug}.aglyn.com` detached (AGL-1136).\n step = 'org-tree'\n if (!dryRun) await firestore.recursiveDelete(orgRef)\n step = 'slugs'\n progress.slugs = await eraseOrgSlugs(orgId, slug, dryRun)\n } catch (error) {\n console.error(`eraseOrg: ${step} failed for ${orgId}`, error)\n await recordErasureFailure({\n orgId,\n step,\n error,\n actorUid,\n requestedAt: requestedMs,\n before,\n // How far it got, so the next reader knows what is already destroyed.\n after: { ...progress },\n })\n throw error\n }\n\n // A plan (AGL-1481). Every sweep above ran its query and skipped its write,\n // so these are the counts the real run would report — reached through the\n // same code, which is the whole point of the operator script calling this\n // function instead of listing the sweeps a second time. No audit row: an\n // erasure that did not happen is not a record of one.\n if (dryRun) {\n return {\n ok: false,\n skippedReason: 'dry-run',\n ...progress,\n hosts: hosts.size,\n members: members.size,\n }\n }\n\n // The proof of erasure, and now the only record of it: actor, action,\n // target, the request it fulfilled, the inventory found and what each sweep\n // destroyed. Ids and counts — never the content (AGL-1443).\n await addAdminAudit(firestore, {\n actorUid,\n action: 'org.erased',\n target: `orgs/${orgId}`,\n before,\n after: {\n requestedAt: requestedMs,\n // What stood in for a request, when nothing did (AGL-2585). Absent on\n // every ordinary erasure, so its presence is the whole flag.\n ...(withoutRequest ? { withoutRequest: withoutRequest.reason } : {}),\n ...progress,\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n return { ok: true, ...progress, hosts: hosts.size, members: members.size }\n}\n\n/**\n * Strip an erased person from the support threads they wrote in, WITHOUT\n * destroying the threads (AGL-1971).\n *\n * The asymmetry with `eraseOrgSupportTickets` is the whole point and is worth\n * stating rather than assuming. A ticket belongs to an ORG, not to the person\n * who happened to open it: it is the workspace's support history, other people\n * on the roster can read it, and it is evidence in a dispute the workspace may\n * still be having with us. Erasing one member must not delete it — and cannot,\n * honestly: for that thread Aglyn is the processor and the ORG is the\n * controller, so deleting it on a member's instruction is acting without the\n * controller's instruction, which `docs/PRIVACY_REQUESTS.md` §6 refuses in the\n * mirror-image case. `eraseUser` also already refuses to cascade into\n * `eraseOrg` for exactly this reason.\n *\n * So the narrow correct action is redaction: `authorId` and `authorEmail` go\n * to `null` and `authorErased: true` marks why, on that person's messages\n * only. What remains is the message BODY, deliberately — it is the workspace's\n * record of a conversation with us, and it is the workspace's to delete. An\n * erasure of the ORG destroys it, which is the path that reaches it.\n *\n * **A collection-group query, not a walk over their current memberships.** The\n * membership walk is the tempting version and it is wrong in a specific way:\n * `eraseUser` only knows the orgs the person belongs to NOW, so every ticket\n * they wrote in a workspace they have since left would keep their email — the\n * residual is invisible and grows with tenure. `messages` is used as a\n * subcollection name by `supportTickets` and by nothing else in the repo, so\n * the group is exactly the right set. It needs the COLLECTION_GROUP index\n * override on `messages.authorId` in `cloud/firebase-firestore.indexes.json`,\n * added with this change.\n *\n * Returns the number of messages redacted, or **`null` when the query could\n * not run** — a missing index in an environment where it was never deployed.\n * `null` is not zero and the caller must not flatten it: it means this erasure\n * did not reach the support messages at all, and an erasure that quietly\n * reports success for a step it skipped is the failure this whole file is\n * organised against. It is reported in the result and in the audit row rather\n * than thrown, because the account deletion itself must still complete.\n */\nasync function redactUserSupportMessages(uid: string): Promise<number | null> {\n if (!uid) return 0\n const firestore = firebaseAdmin.app().firestore()\n let rows: FirebaseFirestore.QuerySnapshot\n try {\n rows = await firestore\n .collectionGroup('messages')\n .where('authorId', '==', uid)\n .get()\n } catch (error) {\n console.error(\n `eraseUser: support message redaction could not run for ${uid}`,\n error,\n )\n return null\n }\n for (let index = 0; index < rows.docs.length; index += 400) {\n const batch = firestore.batch()\n for (const doc of rows.docs.slice(index, index + 400)) {\n batch.set(\n doc.ref,\n { authorId: null, authorEmail: null, authorErased: true },\n { merge: true },\n )\n }\n await batch.commit()\n }\n return rows.size\n}\n\n/** An org that stops a person's account from being erased. */\nexport interface UserErasureBlocker {\n orgId: string\n orgName: string\n /** Whether the org still bills — the reason a human must intervene. */\n hasLiveSubscription: boolean\n /** Other people who would be stranded if this org lost its owner. */\n otherMembers: number\n}\n\nexport interface UserErasureCandidateOrg {\n orgId: string\n orgName: string\n ownerUid: string | null\n hasLiveSubscription: boolean\n memberCount: number\n}\n\n/**\n * Which orgs block erasing `uid` (AGL-1140).\n *\n * Pure so the policy can be tested without Firestore, because the policy is\n * the part worth arguing about — the deletion itself is mechanical.\n *\n * **Owning an org blocks erasure, always.** Not only when it bills, and not\n * only when other members would be stranded. The alternative — cascading\n * into `eraseOrg` — deletes a workspace, its sites and its data as a side\n * effect of someone closing a personal account, and no consent given to the\n * second act was given to the first. Blocking is recoverable; a cascade is\n * not.\n *\n * A live subscription and stranded members are reported rather than gating,\n * so the message can say WHY this org needs attention instead of a bare\n * refusal — \"transfer ownership\" is useless advice if you do not know which\n * of eleven workspaces is the problem.\n */\nexport function userErasureBlockers(\n uid: string,\n orgs: readonly UserErasureCandidateOrg[],\n): UserErasureBlocker[] {\n return orgs\n .filter((org) => org.ownerUid === uid)\n .map((org) => ({\n orgId: org.orgId,\n orgName: org.orgName,\n hasLiveSubscription: org.hasLiveSubscription,\n // The owner themselves is a member; anyone beyond that is stranded.\n otherMembers: Math.max(0, org.memberCount - 1),\n }))\n}\n\n/**\n * An address this account holds that a SECOND account also holds, which stops\n * the erasure until a human decides what it is.\n *\n * ⛔ Carries no address and no other uid. The whole question is about a second\n * customer, and a refusal that names them — or hands back an address in the\n * clear, which `emailDeliveries` is hashed precisely to avoid keeping —\n * discloses the person the refusal exists to protect. The staff account page\n * already lists this account's own addresses and marks the shared ones, so\n * the operator has the specifics without this record carrying them.\n */\nexport interface SharedAddressBlocker {\n /** `sha256(address)` — matches the delivery log's own key. Not readable. */\n key: string\n /** Where this account got it: `primary`, `provider`, `stored`. */\n sources: AccountAddressSource[]\n}\n\n/**\n * Which of an account's addresses a second account is also known to hold.\n *\n * Pure, and separate from the sweep, for the same reason `userErasureBlockers`\n * is: the policy is the arguable part. The mechanical part is deleting rows.\n *\n * ⚠️ `shared` is evidence in ONE direction. True proves a second holder;\n * false only means none was found, because no lookup exists for an account\n * holding an address through a federated provider. So this finds every case\n * we can SEE and cannot promise there is no other — which is exactly why the\n * sweep still tombstones every address it erases.\n */\nexport function sharedAddressBlockers(\n set: Pick<AccountAddressSet, 'addresses'>,\n): SharedAddressBlocker[] {\n return set.addresses\n .filter((entry) => entry.shared === true)\n .map((entry) => ({ key: entry.key, sources: [...entry.sources] }))\n}\n\nexport interface EraseUserResult {\n ok: boolean\n /** Set when the account was NOT erased. */\n skippedReason?: 'not-found' | 'owns-orgs' | 'shared-address'\n /** Orgs that must be handed over or deleted first. */\n blockers?: UserErasureBlocker[]\n /**\n * Addresses a second account also holds. Set with\n * `skippedReason: 'shared-address'`, and NOTHING was erased.\n */\n sharedAddresses?: SharedAddressBlocker[]\n /** What was actually removed, for the audit row and the caller's message. */\n deleted?: {\n subcollections: string[]\n authRecord: boolean\n photo: boolean\n /** `profiles/{uid}` — the world-readable public identity (AGL-1970). */\n profile: boolean\n /**\n * Support messages stripped of `authorId`/`authorEmail` (AGL-1971). The\n * threads themselves belong to the org and survive. **`null` means the\n * redaction could not run** — not that there was nothing to redact.\n */\n supportMessagesRedacted: number | null\n /**\n * What each plugin's eraser removed (AGL-2939), keyed by plugin id — the\n * data a plugin keeps about the person where neither the recursive\n * delete of the user document nor an org's cascade reaches, such as\n * documents under each org keyed by the uid. **`null` means that\n * plugin's eraser failed** and its data may remain; it is not zero.\n */\n plugins: Record<string, PluginUserErasureReport | null>\n /**\n * Messages removed from `emailDeliveries/{sha256(address)}/messages` —\n * the per-recipient delivery log. Zero for an account with no address on\n * file, or one we never mailed.\n *\n * Across EVERY address the account held, not just the current primary.\n */\n emailDeliveries: number\n /**\n * `emailIdentityIndex/{address}` rows released — the address-keyed\n * uniqueness claims, which no `recursiveDelete` of the user can reach.\n */\n emailIdentityIndex: number\n /**\n * How wide the address sweep actually was.\n *\n * ⚠️ `incomplete` is the field a compliance answer turns on: true means a\n * source could not be read and an address the account held may have been\n * missed, so this was not a complete erasure and must not be reported as\n * one. Counts only — never the addresses, which is the data being erased.\n */\n addressSweep: {\n /** Addresses found across the Auth record, its providers and the store. */\n resolved: number\n /** Addresses the delivery sweep actually visited. */\n erased: number\n /**\n * Addresses left INTACT because a second account also holds them.\n *\n * Always 0 on a successful erasure: a contested address refuses the\n * whole run before anything is destroyed. It is reported so the audit\n * row states that rather than leaving a reader to infer it.\n */\n contested: number\n incomplete: boolean\n }\n }\n}\n\n/**\n * Permanently erase a person's account (AGL-1140).\n *\n * Nothing did this before: `eraseHost`, `eraseSubtree` and `eraseOrg` existed\n * and no path anywhere deleted a `users/{uid}`. That was survivable while the\n * doc held a name and a phone; AGL-1133 added a postal address, and \"we have\n * no mechanism to delete it\" is a bad answer to an erasure request.\n *\n * `eraseOrg` is deliberately NOT the model here. An org is a workspace with\n * one owner; a person belongs to many orgs, so erasing them must not take\n * anything with it that outlives them.\n *\n * Order matters:\n * 1. Refuse if they own an org — see `userErasureBlockers`.\n * 1b. Refuse if a second account holds one of their addresses — see\n * `sharedAddressBlockers`. Both refusals come before any delete, so a\n * blocked erasure leaves the account exactly as it was.\n * 2. Remove their membership from every org they belong to, so no roster\n * keeps their email and no host projection keeps granting them access.\n * This runs BEFORE the profile delete: a half-erased account that still\n * appears on a roster is worse than one not yet started.\n * 3. Delete the `users/{uid}` subtree, the avatar, the world-readable\n * `profiles/{uid}` public identity (AGL-1970), redact their name and\n * email off every support message they wrote (AGL-1971), then the auth\n * record last — once that is gone there is no uid to retry with.\n */\nexport async function eraseUser(uid: string): Promise<EraseUserResult> {\n const firestore = firebaseAdmin.app().firestore()\n const userRef = firestore.collection('users').doc(uid)\n const snapshot = await userRef.get()\n const membership = await userRef.collection('orgs').get()\n // An absent profile doc is not an absent account — the doc is only born on\n // first save (AGL-1127), so the auth record and the org memberships can\n // outlive it. Treat \"nothing anywhere\" as not-found, not \"no doc\".\n if (!snapshot.exists && membership.empty) {\n const record = await findUserByUidAcrossPools(uid).catch(() => null)\n if (!record) return { ok: false, skippedReason: 'not-found' }\n }\n\n const candidates: UserErasureCandidateOrg[] = []\n for (const row of membership.docs) {\n const orgRef = firestore.collection('orgs').doc(row.id)\n const [org, members] = await Promise.all([\n orgRef.get(),\n orgRef.collection('members').count().get(),\n ])\n if (!org.exists) continue\n candidates.push({\n orgId: row.id,\n orgName: String(org.get('name') ?? row.id),\n ownerUid: (org.get('ownerUid') as string | undefined) ?? null,\n hasLiveSubscription: isBillingSubscription(org.data() as never),\n memberCount: Number(members.data().count ?? 0),\n })\n }\n const blockers = userErasureBlockers(uid, candidates)\n if (blockers.length) {\n return { ok: false, skippedReason: 'owns-orgs', blockers }\n }\n\n // Inventory BEFORE anything is deleted. Taken after the membership sweep\n // below, this under-reported: `removeOrgMember` empties `users/{uid}/orgs`,\n // and Firestore does not list a collection with no documents in it — so a\n // live run erased three subcollections and the audit record named two.\n // An erasure audit trail that understates what it destroyed is the one\n // record that has to be right. Measured 2026-08-01 (AGL-1140).\n const subcollections = (await userRef.listCollections()).map((c) => c.id)\n\n /*\n * EVERY ADDRESS, RESOLVED BEFORE ANY OF THEM IS DESTROYED.\n *\n * Two of the three sources are erased by this function itself:\n * `users/{uid}/emails` goes with the `recursiveDelete` below, and the Auth\n * record — the only place the primary lives — goes at the very end. Reading\n * them afterwards is reading nothing, and an erasure that resolves an empty\n * address set sweeps nothing while reporting success. That is the exact\n * shape of a spec passing because its fixture never reached the code, and\n * here it would be a live erasure reporting a completeness it does not have.\n *\n * `detectShared` because the SHARED case changes what the caller is told,\n * not what is destroyed — see `eraseEmailDeliveriesForAddresses`.\n */\n const pooledForAddresses = await findUserByUidAcrossPools(uid).catch(() => null)\n const addressSet: AccountAddressSet = await resolveAccountAddresses({\n uid,\n record: pooledForAddresses?.record ?? null,\n detectShared: true,\n firestore,\n }).catch(() => ({\n uid,\n primary: null,\n addresses: [],\n incomplete: true,\n }))\n\n /*\n * A SECOND ACCOUNT HOLDS ONE OF THESE ADDRESSES — REFUSE, HERE.\n *\n * The delivery log is filed under the address, so an address two accounts\n * hold has one set of rows answering \"what did you send me\" for two account\n * records. Whether that is one human with two accounts (the ordinary live\n * shape — a federated provider address that is another account's primary)\n * or a genuinely shared role mailbox like `billing@` decides whether\n * erasing those rows honours a request or destroys a stranger's history,\n * and NOTHING readable here distinguishes them. The data records that two\n * accounts name one address; it records nothing about the humans.\n *\n * Both automatic answers are unacceptable, and they fail differently:\n * erasing the second party's mail cannot be undone, while leaving it and\n * reporting the erasure complete is the gap this whole area was opened to\n * close. So neither is chosen — the erasure stops and says why.\n *\n * BEFORE the membership sweep, deliberately. A refusal raised after the\n * account is half-deleted is not a refusal, and the uid is the only handle\n * a human has to act on this: erase the auth record and there is no longer\n * anything to look at, no way to see which address was contested, and no\n * way to run the erasure once the question is settled. Refusing while the\n * account is whole is the only version of this that stays reversible.\n *\n * The remedy is ordinary staff work, not a special path: decide whether the\n * accounts are one person, detach the address from this one or merge them,\n * then run the erasure again. `/admin/users/[uid]` already lists this\n * account's addresses and marks the shared ones.\n */\n const contested = sharedAddressBlockers(addressSet)\n if (contested.length) {\n return {\n ok: false,\n skippedReason: 'shared-address',\n sharedAddresses: contested,\n }\n }\n\n // Memberships first — a roster row carries their email and a host\n // projection carries their access, and both outlive the profile doc.\n for (const candidate of candidates) {\n await removeOrgMember(candidate.orgId, uid).catch((error) => {\n console.error(`eraseUser: membership cleanup failed for ${candidate.orgId}`, error)\n })\n }\n\n // What the plugins keep about the person (AGL-2939). A document under an\n // org keyed by the uid is the shape no recursive delete on this path can\n // see — the same shape as the delivery log below. Each plugin's eraser\n // gets every workspace the person was in, because the memberships above\n // are already gone; one that fails is recorded as `null` and the erasure\n // goes on.\n const plugins = await runPluginUserErasers({\n uid,\n orgIds: candidates.map((candidate) => candidate.orgId),\n })\n\n // The avatar outlives the doc otherwise.\n let photo = false\n try {\n await storageBucket().deleteFiles({ prefix: `users/${uid}/` })\n photo = true\n } catch (error) {\n console.error(`eraseUser: storage cleanup failed for ${uid}`, error)\n }\n\n await firestore.recursiveDelete(userRef)\n\n // `profiles/{uid}` — the person's PUBLIC identity (AGL-1970).\n //\n // A separate top-level collection keyed by the uid AS THE DOCUMENT ID, so\n // `recursiveDelete(users/{uid})` above never reaches it and no reader\n // scanning this function for a sweep list is prompted to notice it. It is\n // `allow read: if true` in the rules and carries `handle`, `displayName`,\n // and `stripeAccountId`/`stripeChargesEnabled` — a Stripe Connect payout\n // destination written server-side after KYC. An erased person therefore\n // stayed publicly listed with a live payment-account identifier attached,\n // which Privacy Policy §5 (\"a genuine recursive delete… we keep no copy of\n // the erased content\") says in terms does not happen.\n //\n // No tombstone, unlike the org's publisher profile: the only reader of the\n // display name is the support forum's author rendering, and a forum post\n // losing its author name is the intended outcome of erasing its author.\n //\n // `recursiveDelete` rather than `delete` — nothing writes a subcollection\n // under a profile today, and a document delete would silently orphan the\n // first thing that does.\n let profile = false\n try {\n const profileRef = firestore.collection('profiles').doc(uid)\n profile = (await profileRef.get()).exists\n await firestore.recursiveDelete(profileRef)\n } catch (error) {\n console.error(`eraseUser: public profile delete failed for ${uid}`, error)\n }\n\n // Their name and email off every support message they wrote, in any\n // workspace, past or present (AGL-1971). The threads are the orgs' and\n // survive — see `redactUserSupportMessages`.\n const supportMessagesRedacted = await redactUserSupportMessages(uid)\n\n // Auth record LAST: once it is gone there is no uid to retry with, and\n // `authForPool` is required because a project-level delete cannot see an\n // SSO account at all (AGL-1122).\n //\n // The lookup is hoisted above the delete because the DELIVERY LOG is filed\n // under the ADDRESS, not the uid, and the auth record is the last place the\n // address exists. Erase it while there is still something to erase it by.\n let authRecord = false\n let emailDeliveries = 0\n /** Addresses actually swept — not the same as the ones we hold, on failure. */\n let erasedAddressCount = 0\n /** Addresses left intact because a second account also holds them. */\n let contestedAddressCount = 0\n /** Identity-index rows released, one per address that had one. */\n let emailIdentityIndex = 0\n try {\n const record = await findUserByUidAcrossPools(uid)\n if (record) {\n /*\n * `emailDeliveries/{sha256(address)}/messages` — every subject we ever\n * sent this person, with the times they opened and clicked. Personal\n * data by any reading of it, and reachable from neither\n * `recursiveDelete(users/{uid})` nor `profiles/{uid}` because it is\n * keyed by address in a third top-level collection. The same shape as\n * the `profiles/{uid}` omission this function already documents above:\n * a store nothing in the sweep list would prompt a reader to notice.\n *\n * EVERY ADDRESS, not the current primary. Passing one address left a\n * prior or provider-supplied address holding its full history —\n * recipient, subjects, open and click times — after the request had\n * been honoured and reported complete.\n *\n * Best-effort, like every other step here — a log that survives must\n * not stop the auth record from going.\n */\n const sweep = await eraseEmailDeliveriesForAddresses(\n addressSet.addresses,\n firestore,\n ).catch(() => null)\n emailDeliveries = sweep?.removed ?? 0\n erasedAddressCount = sweep?.addresses.length ?? 0\n contestedAddressCount = sweep?.contestedAddresses.length ?? 0\n\n /*\n * `emailIdentityIndex/{address}` — the SAME omission one collection\n * over.\n *\n * A top-level collection keyed by the address IN THE CLEAR, holding\n * `{uid, address, claimedAt}`. `recursiveDelete(users/{uid})` cannot\n * see it for exactly the reason it cannot see the delivery log, so an\n * erased account left a readable address still pointing at its uid.\n *\n * Released rather than tombstoned, unlike the delivery log: this is a\n * uniqueness claim, and `removeAccountEmail` already argues that\n * holding one after the address is gone burns the address for whoever\n * might legitimately want it next.\n *\n * ⛔ Only rows this uid actually owns. The index is the guard against\n * two accounts holding one address, and deleting another account's\n * claim would hand their sign-in identifier to the next taker.\n */\n for (const entry of addressSet.addresses) {\n try {\n const ref = firestore\n .collection(EMAIL_IDENTITY_INDEX_COLLECTION)\n .doc(entry.address)\n const indexed = await ref.get()\n if (indexed.exists && indexed.get('uid') === uid) {\n await ref.delete()\n emailIdentityIndex += 1\n }\n } catch (error) {\n console.error(`eraseUser: identity index release failed for ${uid}`, error)\n }\n }\n await authForPool(record.tenantId).deleteUser(uid)\n authRecord = true\n }\n } catch (error) {\n console.error(`eraseUser: auth record delete failed for ${uid}`, error)\n }\n\n /*\n * WHAT THE ADDRESS SWEEP ACTUALLY COVERED.\n *\n * Counts, never the addresses themselves: this collection is readable by\n * any staff role and `maskEmailAddress` exists because an audit row holding\n * a readable address made `adminAudit` the leakier of the two stores for\n * the same data. An erasure record listing the addresses it destroyed would\n * be the sharpest version of that — it would preserve, in the clear, the\n * exact set the request existed to remove.\n *\n * `addressesIncomplete` is the one that matters to a reader. It says a\n * source could not be read, so the sweep may have missed an address the\n * account held — the difference between \"erased everywhere\" and \"erased\n * everywhere we could see\", which is the difference a regulator asks about.\n */\n const addressSweep = {\n resolved: addressSet.addresses.length,\n erased: erasedAddressCount,\n contested: contestedAddressCount,\n incomplete: addressSet.incomplete,\n }\n\n await addAdminAudit(firestore, {\n actorUid: 'system:erase-user',\n action: 'user.erased',\n target: `users/${uid}`,\n before: { orgs: candidates.length },\n after: {\n subcollections,\n authRecord,\n photo,\n profile,\n supportMessagesRedacted,\n plugins,\n emailDeliveries,\n emailIdentityIndex,\n addressSweep,\n },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n return {\n ok: true,\n deleted: {\n subcollections,\n authRecord,\n photo,\n profile,\n supportMessagesRedacted,\n plugins,\n emailDeliveries,\n emailIdentityIndex,\n addressSweep,\n },\n }\n}\n"],"names":["FieldValue","firebaseAdmin","eraseMediaDeliveryScope","sweepScopeSharingAfterSiteChange","deleteHostProjectionForAllMembers","deleteHostProjectionForUids","detachWorkspaceDomain","CONSOLE_DOMAINS_COLLECTION","releaseConsoleDomain","authForPool","findUserByUidAcrossPools","eraseEmailDeliveriesForAddresses","resolveAccountAddresses","EMAIL_IDENTITY_INDEX_COLLECTION","removeOrgMember","runPluginUserErasers","PLUGIN_ORG_KEYED_COLLECTIONS","runPluginOrgErasers","isBillingSubscription","consentGroupSiteHold","listPluginOrgCollections","PLUGIN_HOST_KEYED_COLLECTIONS","erasePluginSiteResources","previewPluginSiteResources","runPluginEventHandlers","releasedHostNames","readOrgBilling","disposeHostSendingDomain","readSendingDomainTeardownByLabel","addAdminAudit","retryTransientFirestore","ERASURE_HOLD_MS","storageBucket","name","process","env","NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET","app","storage","bucket","undefined","SUPPLIER_DELIVERY_COLLECTION","eraseHostSupplierDeliveries","hostId","firestore","rows","collection","where","get","index","docs","length","batch","doc","slice","delete","ref","commit","size","error","console","eraseHostNotifications","collectionGroup","eraseHostOwnedOrgDocuments","orgId","erased","declared","siteField","recursiveDelete","erasePluginHostKeyedCollections","deleteDocsByOrgId","previewHostErase","resources","SiteInConsentGroupError","Error","hold","reason","eraseHostTree","hostRef","onRetry","attempt","warn","remaining","catch","exists","eraseHost","options","hostSnapshot","hostMemberUids","Object","keys","allowInConsentGroup","orgSnapshot","data","sendingLabel","String","trim","sendingTeardown","deleteFiles","prefix","scopeId","set","hosts","registerAllocations","collaboratorAllocations","merge","domain","sendingDomain","teardown","tearDown","tearDownSendingDomain","eraseSubtree","path","scope","kind","id","HOST_BEACON_COLLECTIONS","reapHostBeaconRemnants","result","reaped","left","refs","listDocuments","snapshots","getAll","snapshot","collections","listCollections","map","every","includes","push","dryRun","deleteStripeCustomer","customerId","key","STRIPE_SECRET_KEY","fetch","method","headers","Authorization","eraseOrgApiKeys","erasePluginOrgKeyedCollections","counts","orgField","eraseOrgSsoDomains","releaseOrgConsoleDomains","claims","primaries","Set","released","eraseOrgStripeIndex","eraseOrgIdempotencyKeys","eraseOrgSlugs","currentSlug","held","slugs","has","reservation","add","slug","eraseOrgHostIndex","eraseOrgHostMemberships","eraseOrgSupportTickets","tickets","ticket","errorLabel","source","parts","code","filter","part","join","recordErasureFailure","entry","actorUid","action","target","before","after","failedStep","step","requestedAt","at","serverTimestamp","auditError","eraseOrg","withoutRequest","orgRef","ok","skippedReason","requestedMs","toMillis","Date","now","members","stripeCustomerId","progress","plugins","apiKeys","pluginCollections","ssoDomains","consoleDomains","apiIdempotency","supportTickets","sendingDomains","deferred","protected","host","hostIndex","stripeIndex","member","hostMemberships","redactUserSupportMessages","uid","authorId","authorEmail","authorErased","userErasureBlockers","orgs","org","ownerUid","orgName","hasLiveSubscription","otherMembers","Math","max","memberCount","sharedAddressBlockers","addresses","shared","sources","eraseUser","userRef","membership","empty","record","candidates","row","Promise","all","count","Number","blockers","subcollections","c","pooledForAddresses","addressSet","detectShared","primary","incomplete","contested","sharedAddresses","candidate","orgIds","photo","profile","profileRef","supportMessagesRedacted","authRecord","emailDeliveries","erasedAddressCount","contestedAddressCount","emailIdentityIndex","sweep","removed","contestedAddresses","address","indexed","tenantId","deleteUser","addressSweep","resolved","de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C,QAAQ,EAAEC,UAAU,CAACxD;YAC9C6C,aAAa;QACf;IACF,EAAE,OAAOxM,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,yCAAyC,EAAE2J,KAAK,EAAE3J;IACnE;IAEA;;;;;;;;;;;;;;GAcC,GACD,MAAMoN,eAAe;QACnBC,UAAUzB,WAAWlB,SAAS,CAAClL,MAAM;QACrCc,QAAQoM;QACRV,WAAWW;QACXZ,YAAYH,WAAWG,UAAU;IACnC;IAEA,MAAM7N,cAAce,WAAW;QAC7BmI,UAAU;QACVC,QAAQ;QACRC,QAAQ,CAAC,MAAM,EAAEqC,KAAK;QACtBpC,QAAQ;YAAEyC,MAAMkB,WAAW1L,MAAM;QAAC;QAClCgI,OAAO;YACLiE;YACAe;YACAJ;YACAC;YACAE;YACA5D;YACA8D;YACAG;YACAQ;QACF;QACAxF,IAAIvL,WAAWwL,eAAe;IAChC,GACGrG,KAAK,CAAC,IAAM3C;IAEf,OAAO;QACLqJ,IAAI;QACJoF,SAAS;YACP7B;YACAe;YACAJ;YACAC;YACAE;YACA5D;YACA8D;YACAG;YACAQ;QACF;IACF;AACF"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export declare function isTransientFirestoreError(error: unknown): boolean;
18
+ export interface TransientFirestoreRetryOptions {
19
+ /**
20
+ * The wait before each retry, in order. Its length is the number of
21
+ * retries, so the total attempts are `delaysMs.length + 1`.
22
+ */
23
+ delaysMs?: readonly number[];
24
+ /** Called before each retry with the failure it follows. */
25
+ onRetry?: (error: unknown, attempt: number) => void;
26
+ }
27
+ /** 250 ms, 1 s, 2.5 s: past a burst without holding a request for long. */
28
+ export declare const DEFAULT_TRANSIENT_RETRY_DELAYS_MS: readonly number[];
29
+ /**
30
+ * Run `operation`, and run it again after a pause when it fails with a
31
+ * {@link isTransientFirestoreError | transient} code. Anything else, and the
32
+ * last transient failure once the delays are spent, is thrown as it came.
33
+ *
34
+ * Only for an operation that is safe to repeat: a delete, a merge set, an
35
+ * idempotent sweep. A retried `add` writes twice.
36
+ */
37
+ export declare function retryTransientFirestore<T>(operation: () => Promise<T>, options?: TransientFirestoreRetryOptions): Promise<T>;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * Firestore failures that a second attempt can succeed past: contention
18
+ * (`ABORTED`, which the admin SDK has already retried inside a transaction),
19
+ * an unreachable backend, a deadline, or a quota burst. The admin SDK reports
20
+ * gRPC codes as numbers. The string forms are kept for anything that
21
+ * normalises them.
22
+ *
23
+ * `recursiveDelete` reports a failed bulk delete with the LAST failed write's
24
+ * code copied onto its own error, so the same test classifies it.
25
+ */ const TRANSIENT_FIRESTORE_CODES = new Set([
26
+ 4,
27
+ 8,
28
+ 10,
29
+ 14,
30
+ 'deadline-exceeded',
31
+ 'resource-exhausted',
32
+ 'aborted',
33
+ 'unavailable'
34
+ ]);
35
+ export function isTransientFirestoreError(error) {
36
+ try {
37
+ return TRANSIENT_FIRESTORE_CODES.has(error == null ? void 0 : error.code);
38
+ } catch (unused) {
39
+ return false;
40
+ }
41
+ }
42
+ /** 250 ms, 1 s, 2.5 s: past a burst without holding a request for long. */ export const DEFAULT_TRANSIENT_RETRY_DELAYS_MS = [
43
+ 250,
44
+ 1000,
45
+ 2500
46
+ ];
47
+ /**
48
+ * Run `operation`, and run it again after a pause when it fails with a
49
+ * {@link isTransientFirestoreError | transient} code. Anything else, and the
50
+ * last transient failure once the delays are spent, is thrown as it came.
51
+ *
52
+ * Only for an operation that is safe to repeat: a delete, a merge set, an
53
+ * idempotent sweep. A retried `add` writes twice.
54
+ */ export async function retryTransientFirestore(operation, options = {}) {
55
+ var _options_delaysMs;
56
+ const delaysMs = (_options_delaysMs = options.delaysMs) != null ? _options_delaysMs : DEFAULT_TRANSIENT_RETRY_DELAYS_MS;
57
+ for(let attempt = 0;; attempt += 1){
58
+ try {
59
+ return await operation();
60
+ } catch (error) {
61
+ if (attempt >= delaysMs.length || !isTransientFirestoreError(error)) throw error;
62
+ options.onRetry == null ? void 0 : options.onRetry.call(options, error, attempt + 1);
63
+ await new Promise((resolve)=>setTimeout(resolve, delaysMs[attempt]));
64
+ }
65
+ }
66
+ }
67
+
68
+ //# sourceMappingURL=firestore-transient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/firestore-transient.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 * Firestore failures that a second attempt can succeed past: contention\n * (`ABORTED`, which the admin SDK has already retried inside a transaction),\n * an unreachable backend, a deadline, or a quota burst. The admin SDK reports\n * gRPC codes as numbers. The string forms are kept for anything that\n * normalises them.\n *\n * `recursiveDelete` reports a failed bulk delete with the LAST failed write's\n * code copied onto its own error, so the same test classifies it.\n */\nconst TRANSIENT_FIRESTORE_CODES = new Set<unknown>([\n 4, // DEADLINE_EXCEEDED\n 8, // RESOURCE_EXHAUSTED\n 10, // ABORTED\n 14, // UNAVAILABLE\n 'deadline-exceeded',\n 'resource-exhausted',\n 'aborted',\n 'unavailable',\n])\n\nexport function isTransientFirestoreError(error: unknown): boolean {\n try {\n return TRANSIENT_FIRESTORE_CODES.has((error as { code?: unknown } | null)?.code)\n } catch {\n return false\n }\n}\n\nexport interface TransientFirestoreRetryOptions {\n /**\n * The wait before each retry, in order. Its length is the number of\n * retries, so the total attempts are `delaysMs.length + 1`.\n */\n delaysMs?: readonly number[]\n /** Called before each retry with the failure it follows. */\n onRetry?: (error: unknown, attempt: number) => void\n}\n\n/** 250 ms, 1 s, 2.5 s: past a burst without holding a request for long. */\nexport const DEFAULT_TRANSIENT_RETRY_DELAYS_MS: readonly number[] = [250, 1000, 2500]\n\n/**\n * Run `operation`, and run it again after a pause when it fails with a\n * {@link isTransientFirestoreError | transient} code. Anything else, and the\n * last transient failure once the delays are spent, is thrown as it came.\n *\n * Only for an operation that is safe to repeat: a delete, a merge set, an\n * idempotent sweep. A retried `add` writes twice.\n */\nexport async function retryTransientFirestore<T>(\n operation: () => Promise<T>,\n options: TransientFirestoreRetryOptions = {},\n): Promise<T> {\n const delaysMs = options.delaysMs ?? DEFAULT_TRANSIENT_RETRY_DELAYS_MS\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await operation()\n } catch (error) {\n if (attempt >= delaysMs.length || !isTransientFirestoreError(error)) throw error\n options.onRetry?.(error, attempt + 1)\n await new Promise((resolve) => setTimeout(resolve, delaysMs[attempt]))\n }\n }\n}\n"],"names":["TRANSIENT_FIRESTORE_CODES","Set","isTransientFirestoreError","error","has","code","DEFAULT_TRANSIENT_RETRY_DELAYS_MS","retryTransientFirestore","operation","options","delaysMs","attempt","length","onRetry","Promise","resolve","setTimeout"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;CASC,GACD,MAAMA,4BAA4B,IAAIC,IAAa;IACjD;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,OAAO,SAASC,0BAA0BC,KAAc;IACtD,IAAI;QACF,OAAOH,0BAA0BI,GAAG,CAAED,yBAAD,AAACA,MAAqCE,IAAI;IACjF,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAYA,yEAAyE,GACzE,OAAO,MAAMC,oCAAuD;IAAC;IAAK;IAAM;CAAK,CAAA;AAErF;;;;;;;CAOC,GACD,OAAO,eAAeC,wBACpBC,SAA2B,EAC3BC,UAA0C,CAAC,CAAC;QAE3BA;IAAjB,MAAMC,YAAWD,oBAAAA,QAAQC,QAAQ,YAAhBD,oBAAoBH;IACrC,IAAK,IAAIK,UAAU,IAAKA,WAAW,EAAG;QACpC,IAAI;YACF,OAAO,MAAMH;QACf,EAAE,OAAOL,OAAO;YACd,IAAIQ,WAAWD,SAASE,MAAM,IAAI,CAACV,0BAA0BC,QAAQ,MAAMA;YAC3EM,QAAQI,OAAO,oBAAfJ,QAAQI,OAAO,MAAfJ,SAAkBN,OAAOQ,UAAU;YACnC,MAAM,IAAIG,QAAQ,CAACC,UAAYC,WAAWD,SAASL,QAAQ,CAACC,QAAQ;QACtE;IACF;AACF"}
@@ -28,6 +28,37 @@
28
28
  */
29
29
  /** A domain as the check accepts one: labels of letters, digits and hyphens. */
30
30
  export declare const TENANT_DNS_DOMAIN_PATTERN: RegExp;
31
+ /**
32
+ * IPv6 addresses answering for `domain` that the tenant edge does not answer
33
+ * with: the AAAA record a previous host left on the zone root (AGL-3963).
34
+ *
35
+ * Pointing a domain here replaces its A record (by hand, or through Domain
36
+ * Connect, whose `website` template writes `A @`), and nothing replaces the
37
+ * AAAA beside it. A visitor on IPv6 then reaches the previous host, and the
38
+ * edge's certificate challenge over IPv6 can fail with it. Cloudflare named
39
+ * this case when it onboarded our templates (2026-10-29).
40
+ *
41
+ * Today the edge answers no AAAA at all, so any AAAA on the name is a stray.
42
+ * The edge's own answer is subtracted anyway, so an edge that starts
43
+ * publishing IPv6 on `CNAME_TARGET` does not warn every customer at once; an
44
+ * IPv6 apex pool like `HOST_APEX_ADDRESSES` would need adding here too.
45
+ * Reported, never refused, for the same reason as `stray` below. Never throws,
46
+ * and gives up after `IPV6_LOOKUP_BUDGET_MS`: no answer reads as none.
47
+ */
48
+ export declare function strayIpv6Addresses(domain: string): Promise<string[]>;
49
+ /** A record answering for a name that is not ours, as the status card lists it. */
50
+ export interface TenantDnsConflict {
51
+ type?: string;
52
+ name?: string;
53
+ value?: string;
54
+ }
55
+ /**
56
+ * `conflicts` with each stray IPv6 address of `names` added as an AAAA entry,
57
+ * unless the platform already listed it (AGL-3963). The platform's own DNS
58
+ * check is not relied on to name these: it is the A record it checks. Never
59
+ * throws; within `IPV6_LOOKUP_BUDGET_MS`.
60
+ */
61
+ export declare function withStrayIpv6Conflicts(names: readonly string[], conflicts: readonly TenantDnsConflict[]): Promise<TenantDnsConflict[]>;
31
62
  /** What the check found for one name, as `/api/domains/verify` answers it. */
32
63
  export interface TenantDnsCheck {
33
64
  domain: string;
@@ -40,6 +71,8 @@ export interface TenantDnsCheck {
40
71
  matchedBy?: 'apex-address';
41
72
  /** Addresses answering for the name that are not ours (AGL-1913). */
42
73
  strayAddresses?: string[];
74
+ /** IPv6 addresses answering for the name that are not ours (AGL-3963). */
75
+ strayIpv6Addresses?: string[];
43
76
  }
44
77
  /**
45
78
  * Resolves `domain` and answers whether it points at the tenant edge: its
@@ -84,6 +84,135 @@ async function resolveARecords(domain) {
84
84
  }
85
85
  }
86
86
  }
87
+ /**
88
+ * The most an IPv6 check may add to a request (AGL-3963). It is advice beside
89
+ * a check that already answered, so a slow resolver gives up and reads as
90
+ * "nothing found" rather than holding the domain card or the button.
91
+ */ const IPV6_LOOKUP_BUDGET_MS = 2000;
92
+ function withinIpv6Budget(work, fallback) {
93
+ let timer;
94
+ const late = new Promise((resolve)=>{
95
+ timer = setTimeout(()=>resolve(fallback), IPV6_LOOKUP_BUDGET_MS);
96
+ });
97
+ return Promise.race([
98
+ work.catch(()=>fallback),
99
+ late
100
+ ]).finally(()=>clearTimeout(timer));
101
+ }
102
+ /** One spelling per address, so `2001:DB8:0::1` and `2001:db8::1` match. */ function normaliseIpv6(address) {
103
+ const trimmed = address.trim();
104
+ try {
105
+ return new URL(`http://[${trimmed}]`).hostname.replace(/^\[|\]$/g, '');
106
+ } catch (unused) {
107
+ return trimmed.toLowerCase();
108
+ }
109
+ }
110
+ /**
111
+ * AAAA records on the public resolvers, one short try each. No fallback to
112
+ * the runtime's resolver, unlike the A check: this is advice, and a second
113
+ * slow lookup would only spend the budget.
114
+ */ async function resolveAaaaRecords(domain) {
115
+ try {
116
+ const resolver = new CallbackResolver({
117
+ timeout: 1500,
118
+ tries: 1
119
+ });
120
+ resolver.setServers(PUBLIC_RESOLVERS);
121
+ const records = await new Promise((resolve, reject)=>{
122
+ resolver.resolve6(domain, (error, addresses)=>error ? reject(error) : resolve(addresses));
123
+ });
124
+ return records.map(normaliseIpv6);
125
+ } catch (unused) {
126
+ return [];
127
+ }
128
+ }
129
+ /**
130
+ * Each name's IPv6 addresses that the tenant edge does not answer with, with
131
+ * the edge looked up once. A name carrying a CNAME is skipped: a resolver
132
+ * follows the CNAME, so those addresses are its target's, and the record to
133
+ * fix is the CNAME, which the A side already reports.
134
+ */ async function strayIpv6ByName(names) {
135
+ const work = (async ()=>{
136
+ const [edge, ...answers] = await Promise.all([
137
+ resolveAaaaRecords(CNAME_TARGET),
138
+ ...names.map(async (name)=>{
139
+ const [cnames, addresses] = await Promise.all([
140
+ resolveCnameRecords(name),
141
+ resolveAaaaRecords(name)
142
+ ]);
143
+ return {
144
+ name,
145
+ addresses: cnames.length ? [] : addresses
146
+ };
147
+ })
148
+ ]);
149
+ const ours = new Set(edge);
150
+ const found = new Map();
151
+ for (const answer of answers){
152
+ const strays = answer.addresses.filter((address)=>!ours.has(address));
153
+ if (strays.length) found.set(answer.name, strays);
154
+ }
155
+ return found;
156
+ })();
157
+ return withinIpv6Budget(work, new Map());
158
+ }
159
+ /**
160
+ * IPv6 addresses answering for `domain` that the tenant edge does not answer
161
+ * with: the AAAA record a previous host left on the zone root (AGL-3963).
162
+ *
163
+ * Pointing a domain here replaces its A record (by hand, or through Domain
164
+ * Connect, whose `website` template writes `A @`), and nothing replaces the
165
+ * AAAA beside it. A visitor on IPv6 then reaches the previous host, and the
166
+ * edge's certificate challenge over IPv6 can fail with it. Cloudflare named
167
+ * this case when it onboarded our templates (2026-10-29).
168
+ *
169
+ * Today the edge answers no AAAA at all, so any AAAA on the name is a stray.
170
+ * The edge's own answer is subtracted anyway, so an edge that starts
171
+ * publishing IPv6 on `CNAME_TARGET` does not warn every customer at once; an
172
+ * IPv6 apex pool like `HOST_APEX_ADDRESSES` would need adding here too.
173
+ * Reported, never refused, for the same reason as `stray` below. Never throws,
174
+ * and gives up after `IPV6_LOOKUP_BUDGET_MS`: no answer reads as none.
175
+ */ export async function strayIpv6Addresses(domain) {
176
+ var _get;
177
+ return (_get = (await strayIpv6ByName([
178
+ domain
179
+ ])).get(domain)) != null ? _get : [];
180
+ }
181
+ function conflictKey(type, name, value) {
182
+ const kind = String(type != null ? type : '').toUpperCase();
183
+ const host = String(name != null ? name : '').trim().toLowerCase().replace(/\.+$/, '');
184
+ const data = kind === 'AAAA' ? normaliseIpv6(String(value != null ? value : '')) : String(value != null ? value : '').trim().toLowerCase();
185
+ return [
186
+ kind,
187
+ host,
188
+ data
189
+ ].join('|');
190
+ }
191
+ /**
192
+ * `conflicts` with each stray IPv6 address of `names` added as an AAAA entry,
193
+ * unless the platform already listed it (AGL-3963). The platform's own DNS
194
+ * check is not relied on to name these: it is the A record it checks. Never
195
+ * throws; within `IPV6_LOOKUP_BUDGET_MS`.
196
+ */ export async function withStrayIpv6Conflicts(names, conflicts) {
197
+ const merged = [
198
+ ...conflicts
199
+ ];
200
+ const listed = new Set(conflicts.map((conflict)=>conflictKey(conflict.type, conflict.name, conflict.value)));
201
+ const strays = await strayIpv6ByName(names);
202
+ for (const [name, addresses] of strays){
203
+ for (const value of addresses){
204
+ const key = conflictKey('AAAA', name, value);
205
+ if (listed.has(key)) continue;
206
+ listed.add(key);
207
+ merged.push({
208
+ type: 'AAAA',
209
+ name,
210
+ value
211
+ });
212
+ }
213
+ }
214
+ return merged;
215
+ }
87
216
  /**
88
217
  * An apex (`aglyn.com`) cannot carry a CNAME — RFC 1034 forbids one alongside
89
218
  * the SOA/NS records every zone apex must have. So the CNAME check below can
@@ -178,10 +307,16 @@ async function resolveARecords(domain) {
178
307
  // A domain that DOES carry a CNAME but points somewhere else must keep
179
308
  // failing — otherwise "pointed at the wrong place" and "pointed at an apex"
180
309
  // would verify identically.
181
- const apex = records.length ? {
182
- matched: false,
183
- stray: []
184
- } : await apexPointsAtTenantEdge(domain);
310
+ const [apex, strayIpv6] = records.length ? [
311
+ {
312
+ matched: false,
313
+ stray: []
314
+ },
315
+ []
316
+ ] : await Promise.all([
317
+ apexPointsAtTenantEdge(domain),
318
+ strayIpv6Addresses(domain)
319
+ ]);
185
320
  return _extends({
186
321
  domain,
187
322
  records,
@@ -191,6 +326,8 @@ async function resolveARecords(domain) {
191
326
  matchedBy: 'apex-address'
192
327
  }, apex.stray.length ? {
193
328
  strayAddresses: apex.stray
329
+ } : {}, strayIpv6.length ? {
330
+ strayIpv6Addresses: strayIpv6
194
331
  } : {});
195
332
  }
196
333
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/tenant-dns-check.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 { CNAME_TARGET, HOST_APEX_ADDRESSES } from '@aglyn/aglyn/app-utils/tenant-dns-targets'\nimport { promises as dns, Resolver as CallbackResolver } from 'dns'\nimport { PUBLIC_DNS_RESOLVERS as PUBLIC_RESOLVERS } from './dns-probe'\n\n/**\n * WHETHER A NAME POINTS AT THE TENANT EDGE: the check behind\n * `/api/domains/verify`, here so a caller with no request of its own reads\n * the same answer (AGL-3963). The domains plugin's one-click DNS asks it after\n * a DNS provider wrote the records, and its sweep asks it again for a session\n * whose owner closed the tab; neither can import the console app, and a\n * second copy of this rule is how the displayed target and the accepted one\n * came apart before (AGL-733).\n *\n * The targets are `@aglyn/aglyn/app-utils/tenant-dns-targets`, the values the\n * connect card prints.\n */\n\n/** A domain as the check accepts one: labels of letters, digits and hyphens. */\nexport const TENANT_DNS_DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/i\n\n/**\n * Resolve against public resolvers rather than the runtime's default (AGL-734).\n *\n * A stale zone left over from a nameserver migration made Vercel's own resolver\n * return NXDOMAIN for records that every public resolver could see — so a\n * correctly-configured domain reported \"no CNAME record found\" indefinitely,\n * while `dig` from anywhere else resolved it fine. Pinning the resolver makes\n * the check depend on public DNS, which is what the customer's browser will use\n * anyway, instead of on whatever cache a given lambda inherited.\n *\n * Falls back to the default resolver if the pinned ones are unreachable, so a\n * blocked egress path degrades to today's behaviour rather than failing shut.\n */\n\nasync function resolveCnameRecords(domain: string): Promise<string[]> {\n const normalise = (records: string[]) =>\n records.map((record) => record.toLowerCase().replace(/\\.$/, ''))\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n const records = await new Promise<string[]>((resolve, reject) => {\n resolver.resolveCname(domain, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n return normalise(records)\n } catch (error) {\n // ENOTFOUND/ENODATA are real answers — the name has no CNAME. Only fall\n // back when the pinned resolvers could not be reached at all.\n const code = (error as NodeJS.ErrnoException)?.code\n if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {\n return []\n }\n try {\n return normalise(await dns.resolveCname(domain))\n } catch {\n return []\n }\n }\n}\n\nasync function resolveARecords(domain: string): Promise<string[]> {\n const lookup = async (resolver?: CallbackResolver) =>\n resolver\n ? new Promise<string[]>((resolve, reject) => {\n resolver.resolve4(domain, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n : dns.resolve4(domain)\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n return await lookup(resolver)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code\n if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {\n return []\n }\n try {\n return await lookup()\n } catch {\n return []\n }\n }\n}\n\n/**\n * An apex (`aglyn.com`) cannot carry a CNAME — RFC 1034 forbids one alongside\n * the SOA/NS records every zone apex must have. So the CNAME check below can\n * never pass for a bare domain, and until this existed the wizard simply\n * refused every apex: customers could connect `www.` and nothing else.\n *\n * Instead, compare where the domain actually lands against where the CNAME\n * target lands. Both sides are resolved at check time rather than compared to\n * a hardcoded address list, because the edge IPs behind `sites.aglyn.app` are\n * the host's to change — pinning them here would turn a routine infrastructure\n * change into every customer's domain reporting itself broken.\n *\n * An intersection, not equality: the two names legitimately return different\n * subsets of the same anycast pool from one lookup to the next.\n *\n * `HOST_APEX_ADDRESSES` covers the case the intersection cannot: our platform\n * host publishes a small anycast pool for every apex it serves, routing by\n * `Host` rather than by IP. An apex pointed there therefore never shares an\n * address with `sites.aglyn.app`, yet is configured correctly.\n *\n * The list has to span the host's WHOLE pool, not just the address we happen\n * to have used. It shipped with only `76.76.21.21` — the host's legacy\n * address, which still resolves but is no longer what a newly-pointed apex\n * lands on, so every new customer would have failed the very check this\n * fallback exists to let them pass. Our own zones are the proof: after taking\n * the host's recommended records, `aglyn.com` and `aglyn.io` resolve into the\n * `216.198.79.x` / `64.29.17.x` range and not one of them is the legacy\n * address. Keep the legacy entry — zones still pointed at it work fine.\n *\n * Accepting an address match is deliberately a weaker claim — \"this domain\n * resolves to our platform\" rather than \"to this account\". That is sound\n * because it is not the ownership check: attaching a domain to the project is,\n * and the platform performs that itself. This only answers \"has DNS been\n * pointed yet\", which is what the customer is actually stuck on. Configurable\n * so the next range expansion is an env edit rather than a patch.\n *\n * The list itself lives in `tenant-dns-targets.ts` beside `CNAME_TARGET`, so the\n * wizard prints an address this check will actually accept rather than keeping\n * its own copy under a different env var (AGL-1275) — that env edit is exactly\n * the move which used to leave the two disagreeing.\n */\n/**\n * The `stray` half exists because the intersection above is deliberately an\n * `some`, and a name can answer with our addresses AND somebody else's at the\n * same time (AGL-1913).\n *\n * That is the shape a stale A record makes: a previous host's address left in\n * the zone answers alongside a correct ALIAS, the resolver hands out whichever\n * it likes, and the site loads for one visitor and not the next. Every check we\n * had reported that domain as verified, because it is — some of the time — and\n * \"it works when I try it\" is exactly why nobody finds it.\n *\n * Reported, not refused. Refusing would mean treating \"an address we do not\n * recognise\" as proof of misconfiguration, and the recognised set is an env var\n * plus a live lookup of one hostname: the day the platform widens its pool\n * ahead of our config, refusing would fail every correctly-pointed apex at\n * once. A warning costs a confused customer nothing and cannot take the flow\n * down.\n */\nasync function apexPointsAtTenantEdge(\n domain: string,\n): Promise<{ matched: boolean; stray: string[] }> {\n const [domainAddresses, targetAddresses] = await Promise.all([\n resolveARecords(domain),\n resolveARecords(CNAME_TARGET),\n ])\n if (!domainAddresses.length) return { matched: false, stray: [] }\n const acceptable = new Set([...targetAddresses, ...HOST_APEX_ADDRESSES])\n return {\n matched: domainAddresses.some((address) => acceptable.has(address)),\n stray: domainAddresses.filter((address) => !acceptable.has(address)),\n }\n}\n\n/** What the check found for one name, as `/api/domains/verify` answers it. */\nexport interface TenantDnsCheck {\n domain: string\n /** The name's CNAME targets, lowercased; empty when it carries none. */\n records: string[]\n /** The CNAME target a subdomain must name. */\n expected: string\n verified: boolean\n /** Set when an apex passed by the addresses it lands on. */\n matchedBy?: 'apex-address'\n /** Addresses answering for the name that are not ours (AGL-1913). */\n strayAddresses?: string[]\n}\n\n/**\n * Resolves `domain` and answers whether it points at the tenant edge: its\n * CNAME names `CNAME_TARGET`, or, carrying no CNAME, its addresses are ours.\n *\n * `softPass` accepts ANY CNAME and belongs to local development alone, where\n * nothing points at the edge. A caller passes `isDevelopmentRuntime()` and\n * never a guess: a soft pass that keys on a missing hosting variable is the\n * AGL-2180 hole, where any domain with any CNAME verified on a container.\n *\n * Expects a lowercased name that matched {@link TENANT_DNS_DOMAIN_PATTERN}.\n * Never throws: an unreachable resolver reads as no records.\n */\nexport async function checkTenantDnsPointing(\n domain: string,\n options: { softPass?: boolean } = {},\n): Promise<TenantDnsCheck> {\n // NXDOMAIN / no CNAME comes back as an empty list — reported as unverified.\n const records = await resolveCnameRecords(domain)\n const cnameVerified =\n records.includes(CNAME_TARGET) || (options.softPass === true && records.length > 0)\n // Only fall back to the address comparison when there is no CNAME at all.\n // A domain that DOES carry a CNAME but points somewhere else must keep\n // failing — otherwise \"pointed at the wrong place\" and \"pointed at an apex\"\n // would verify identically.\n const apex = records.length\n ? { matched: false, stray: [] as string[] }\n : await apexPointsAtTenantEdge(domain)\n return {\n domain,\n records,\n expected: CNAME_TARGET,\n verified: cnameVerified || apex.matched,\n // Which rule passed, so the wizard can explain itself rather than just\n // showing a tick.\n ...(apex.matched && { matchedBy: 'apex-address' as const }),\n // Addresses answering for the name that are not ours. A verified domain\n // with a non-empty list here is the one that loads intermittently.\n ...(apex.stray.length ? { strayAddresses: apex.stray } : {}),\n }\n}\n"],"names":["CNAME_TARGET","HOST_APEX_ADDRESSES","promises","dns","Resolver","CallbackResolver","PUBLIC_DNS_RESOLVERS","PUBLIC_RESOLVERS","TENANT_DNS_DOMAIN_PATTERN","resolveCnameRecords","domain","normalise","records","map","record","toLowerCase","replace","resolver","setServers","Promise","resolve","reject","resolveCname","error","addresses","code","resolveARecords","lookup","resolve4","apexPointsAtTenantEdge","domainAddresses","targetAddresses","all","length","matched","stray","acceptable","Set","some","address","has","filter","checkTenantDnsPointing","options","cnameVerified","includes","softPass","apex","expected","verified","matchedBy","strayAddresses"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,EAAEC,mBAAmB,QAAQ,4CAA2C;AAC7F,SAASC,YAAYC,GAAG,EAAEC,YAAYC,gBAAgB,QAAQ,MAAK;AACnE,SAASC,wBAAwBC,gBAAgB,QAAQ,iBAAa;AAEtE;;;;;;;;;;;CAWC,GAED,8EAA8E,GAC9E,OAAO,MAAMC,4BAA4B,8CAA6C;AAEtF;;;;;;;;;;;;CAYC,GAED,eAAeC,oBAAoBC,MAAc;IAC/C,MAAMC,YAAY,CAACC,UACjBA,QAAQC,GAAG,CAAC,CAACC,SAAWA,OAAOC,WAAW,GAAGC,OAAO,CAAC,OAAO;IAC9D,IAAI;QACF,MAAMC,WAAW,IAAIZ;QACrBY,SAASC,UAAU,CAACX;QACpB,MAAMK,UAAU,MAAM,IAAIO,QAAkB,CAACC,SAASC;YACpDJ,SAASK,YAAY,CAACZ,QAAQ,CAACa,OAAOC,YACpCD,QAAQF,OAAOE,SAASH,QAAQI;QAEpC;QACA,OAAOb,UAAUC;IACnB,EAAE,OAAOW,OAAO;QACd,wEAAwE;QACxE,8DAA8D;QAC9D,MAAME,OAAQF,yBAAD,AAACA,MAAiCE,IAAI;QACnD,IAAIA,SAAS,eAAeA,SAAS,aAAaA,SAAS,YAAY;YACrE,OAAO,EAAE;QACX;QACA,IAAI;YACF,OAAOd,UAAU,MAAMR,IAAImB,YAAY,CAACZ;QAC1C,EAAE,eAAM;YACN,OAAO,EAAE;QACX;IACF;AACF;AAEA,eAA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AAQiC,QAAQ,CAAC7C,iBAAkB2C,QAAQG,QAAQ,KAAK,QAAQlC,QAAQqB,MAAM,GAAG;IACnF,0EAA0E;IAC1E,uEAAuE;IACvE,4EAA4E;IAC5E,4BAA4B;IAC5B,MAAMc,OAAOnC,QAAQqB,MAAM,GACvB;QAAEC,SAAS;QAAOC,OAAO,EAAE;IAAa,IACxC,MAAMN,uBAAuBnB;IACjC,OAAO;QACLA;QACAE;QACAoC,UAAUhD;QACViD,UAAUL,iBAAiBG,KAAKb,OAAO;OAGnCa,KAAKb,OAAO,IAAI;QAAEgB,WAAW;IAAwB,GAGrDH,KAAKZ,KAAK,CAACF,MAAM,GAAG;QAAEkB,gBAAgBJ,KAAKZ,KAAK;IAAC,IAAI,CAAC;AAE9D"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/tenant-dns-check.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 { CNAME_TARGET, HOST_APEX_ADDRESSES } from '@aglyn/aglyn/app-utils/tenant-dns-targets'\nimport { promises as dns, Resolver as CallbackResolver } from 'dns'\nimport { PUBLIC_DNS_RESOLVERS as PUBLIC_RESOLVERS } from './dns-probe'\n\n/**\n * WHETHER A NAME POINTS AT THE TENANT EDGE: the check behind\n * `/api/domains/verify`, here so a caller with no request of its own reads\n * the same answer (AGL-3963). The domains plugin's one-click DNS asks it after\n * a DNS provider wrote the records, and its sweep asks it again for a session\n * whose owner closed the tab; neither can import the console app, and a\n * second copy of this rule is how the displayed target and the accepted one\n * came apart before (AGL-733).\n *\n * The targets are `@aglyn/aglyn/app-utils/tenant-dns-targets`, the values the\n * connect card prints.\n */\n\n/** A domain as the check accepts one: labels of letters, digits and hyphens. */\nexport const TENANT_DNS_DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/i\n\n/**\n * Resolve against public resolvers rather than the runtime's default (AGL-734).\n *\n * A stale zone left over from a nameserver migration made Vercel's own resolver\n * return NXDOMAIN for records that every public resolver could see — so a\n * correctly-configured domain reported \"no CNAME record found\" indefinitely,\n * while `dig` from anywhere else resolved it fine. Pinning the resolver makes\n * the check depend on public DNS, which is what the customer's browser will use\n * anyway, instead of on whatever cache a given lambda inherited.\n *\n * Falls back to the default resolver if the pinned ones are unreachable, so a\n * blocked egress path degrades to today's behaviour rather than failing shut.\n */\n\nasync function resolveCnameRecords(domain: string): Promise<string[]> {\n const normalise = (records: string[]) =>\n records.map((record) => record.toLowerCase().replace(/\\.$/, ''))\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n const records = await new Promise<string[]>((resolve, reject) => {\n resolver.resolveCname(domain, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n return normalise(records)\n } catch (error) {\n // ENOTFOUND/ENODATA are real answers — the name has no CNAME. Only fall\n // back when the pinned resolvers could not be reached at all.\n const code = (error as NodeJS.ErrnoException)?.code\n if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {\n return []\n }\n try {\n return normalise(await dns.resolveCname(domain))\n } catch {\n return []\n }\n }\n}\n\nasync function resolveARecords(domain: string): Promise<string[]> {\n const lookup = async (resolver?: CallbackResolver) =>\n resolver\n ? new Promise<string[]>((resolve, reject) => {\n resolver.resolve4(domain, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n : dns.resolve4(domain)\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n return await lookup(resolver)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code\n if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {\n return []\n }\n try {\n return await lookup()\n } catch {\n return []\n }\n }\n}\n\n/**\n * The most an IPv6 check may add to a request (AGL-3963). It is advice beside\n * a check that already answered, so a slow resolver gives up and reads as\n * \"nothing found\" rather than holding the domain card or the button.\n */\nconst IPV6_LOOKUP_BUDGET_MS = 2_000\n\nfunction withinIpv6Budget<T>(work: Promise<T>, fallback: T): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const late = new Promise<T>((resolve) => {\n timer = setTimeout(() => resolve(fallback), IPV6_LOOKUP_BUDGET_MS)\n })\n return Promise.race([work.catch(() => fallback), late]).finally(() => clearTimeout(timer))\n}\n\n/** One spelling per address, so `2001:DB8:0::1` and `2001:db8::1` match. */\nfunction normaliseIpv6(address: string): string {\n const trimmed = address.trim()\n try {\n return new URL(`http://[${trimmed}]`).hostname.replace(/^\\[|\\]$/g, '')\n } catch {\n return trimmed.toLowerCase()\n }\n}\n\n/**\n * AAAA records on the public resolvers, one short try each. No fallback to\n * the runtime's resolver, unlike the A check: this is advice, and a second\n * slow lookup would only spend the budget.\n */\nasync function resolveAaaaRecords(domain: string): Promise<string[]> {\n try {\n const resolver = new CallbackResolver({ timeout: 1_500, tries: 1 })\n resolver.setServers(PUBLIC_RESOLVERS)\n const records = await new Promise<string[]>((resolve, reject) => {\n resolver.resolve6(domain, (error, addresses) => (error ? reject(error) : resolve(addresses)))\n })\n return records.map(normaliseIpv6)\n } catch {\n return []\n }\n}\n\n/**\n * Each name's IPv6 addresses that the tenant edge does not answer with, with\n * the edge looked up once. A name carrying a CNAME is skipped: a resolver\n * follows the CNAME, so those addresses are its target's, and the record to\n * fix is the CNAME, which the A side already reports.\n */\nasync function strayIpv6ByName(names: readonly string[]): Promise<Map<string, string[]>> {\n const work = (async () => {\n const [edge, ...answers] = await Promise.all([\n resolveAaaaRecords(CNAME_TARGET),\n ...names.map(async (name) => {\n const [cnames, addresses] = await Promise.all([resolveCnameRecords(name), resolveAaaaRecords(name)])\n return { name, addresses: cnames.length ? [] : addresses }\n }),\n ])\n const ours = new Set(edge as string[])\n const found = new Map<string, string[]>()\n for (const answer of answers as Array<{ name: string; addresses: string[] }>) {\n const strays = answer.addresses.filter((address) => !ours.has(address))\n if (strays.length) found.set(answer.name, strays)\n }\n return found\n })()\n return withinIpv6Budget(work, new Map<string, string[]>())\n}\n\n/**\n * IPv6 addresses answering for `domain` that the tenant edge does not answer\n * with: the AAAA record a previous host left on the zone root (AGL-3963).\n *\n * Pointing a domain here replaces its A record (by hand, or through Domain\n * Connect, whose `website` template writes `A @`), and nothing replaces the\n * AAAA beside it. A visitor on IPv6 then reaches the previous host, and the\n * edge's certificate challenge over IPv6 can fail with it. Cloudflare named\n * this case when it onboarded our templates (2026-10-29).\n *\n * Today the edge answers no AAAA at all, so any AAAA on the name is a stray.\n * The edge's own answer is subtracted anyway, so an edge that starts\n * publishing IPv6 on `CNAME_TARGET` does not warn every customer at once; an\n * IPv6 apex pool like `HOST_APEX_ADDRESSES` would need adding here too.\n * Reported, never refused, for the same reason as `stray` below. Never throws,\n * and gives up after `IPV6_LOOKUP_BUDGET_MS`: no answer reads as none.\n */\nexport async function strayIpv6Addresses(domain: string): Promise<string[]> {\n return (await strayIpv6ByName([domain])).get(domain) ?? []\n}\n\n/** A record answering for a name that is not ours, as the status card lists it. */\nexport interface TenantDnsConflict {\n type?: string\n name?: string\n value?: string\n}\n\nfunction conflictKey(type: unknown, name: unknown, value: unknown): string {\n const kind = String(type ?? '').toUpperCase()\n const host = String(name ?? '').trim().toLowerCase().replace(/\\.+$/, '')\n const data = kind === 'AAAA' ? normaliseIpv6(String(value ?? '')) : String(value ?? '').trim().toLowerCase()\n return [kind, host, data].join('|')\n}\n\n/**\n * `conflicts` with each stray IPv6 address of `names` added as an AAAA entry,\n * unless the platform already listed it (AGL-3963). The platform's own DNS\n * check is not relied on to name these: it is the A record it checks. Never\n * throws; within `IPV6_LOOKUP_BUDGET_MS`.\n */\nexport async function withStrayIpv6Conflicts(\n names: readonly string[],\n conflicts: readonly TenantDnsConflict[],\n): Promise<TenantDnsConflict[]> {\n const merged = [...conflicts]\n const listed = new Set(conflicts.map((conflict) => conflictKey(conflict.type, conflict.name, conflict.value)))\n const strays = await strayIpv6ByName(names)\n for (const [name, addresses] of strays) {\n for (const value of addresses) {\n const key = conflictKey('AAAA', name, value)\n if (listed.has(key)) continue\n listed.add(key)\n merged.push({ type: 'AAAA', name, value })\n }\n }\n return merged\n}\n\n/**\n * An apex (`aglyn.com`) cannot carry a CNAME — RFC 1034 forbids one alongside\n * the SOA/NS records every zone apex must have. So the CNAME check below can\n * never pass for a bare domain, and until this existed the wizard simply\n * refused every apex: customers could connect `www.` and nothing else.\n *\n * Instead, compare where the domain actually lands against where the CNAME\n * target lands. Both sides are resolved at check time rather than compared to\n * a hardcoded address list, because the edge IPs behind `sites.aglyn.app` are\n * the host's to change — pinning them here would turn a routine infrastructure\n * change into every customer's domain reporting itself broken.\n *\n * An intersection, not equality: the two names legitimately return different\n * subsets of the same anycast pool from one lookup to the next.\n *\n * `HOST_APEX_ADDRESSES` covers the case the intersection cannot: our platform\n * host publishes a small anycast pool for every apex it serves, routing by\n * `Host` rather than by IP. An apex pointed there therefore never shares an\n * address with `sites.aglyn.app`, yet is configured correctly.\n *\n * The list has to span the host's WHOLE pool, not just the address we happen\n * to have used. It shipped with only `76.76.21.21` — the host's legacy\n * address, which still resolves but is no longer what a newly-pointed apex\n * lands on, so every new customer would have failed the very check this\n * fallback exists to let them pass. Our own zones are the proof: after taking\n * the host's recommended records, `aglyn.com` and `aglyn.io` resolve into the\n * `216.198.79.x` / `64.29.17.x` range and not one of them is the legacy\n * address. Keep the legacy entry — zones still pointed at it work fine.\n *\n * Accepting an address match is deliberately a weaker claim — \"this domain\n * resolves to our platform\" rather than \"to this account\". That is sound\n * because it is not the ownership check: attaching a domain to the project is,\n * and the platform performs that itself. This only answers \"has DNS been\n * pointed yet\", which is what the customer is actually stuck on. Configurable\n * so the next range expansion is an env edit rather than a patch.\n *\n * The list itself lives in `tenant-dns-targets.ts` beside `CNAME_TARGET`, so the\n * wizard prints an address this check will actually accept rather than keeping\n * its own copy under a different env var (AGL-1275) — that env edit is exactly\n * the move which used to leave the two disagreeing.\n */\n/**\n * The `stray` half exists because the intersection above is deliberately an\n * `some`, and a name can answer with our addresses AND somebody else's at the\n * same time (AGL-1913).\n *\n * That is the shape a stale A record makes: a previous host's address left in\n * the zone answers alongside a correct ALIAS, the resolver hands out whichever\n * it likes, and the site loads for one visitor and not the next. Every check we\n * had reported that domain as verified, because it is — some of the time — and\n * \"it works when I try it\" is exactly why nobody finds it.\n *\n * Reported, not refused. Refusing would mean treating \"an address we do not\n * recognise\" as proof of misconfiguration, and the recognised set is an env var\n * plus a live lookup of one hostname: the day the platform widens its pool\n * ahead of our config, refusing would fail every correctly-pointed apex at\n * once. A warning costs a confused customer nothing and cannot take the flow\n * down.\n */\nasync function apexPointsAtTenantEdge(\n domain: string,\n): Promise<{ matched: boolean; stray: string[] }> {\n const [domainAddresses, targetAddresses] = await Promise.all([\n resolveARecords(domain),\n resolveARecords(CNAME_TARGET),\n ])\n if (!domainAddresses.length) return { matched: false, stray: [] }\n const acceptable = new Set([...targetAddresses, ...HOST_APEX_ADDRESSES])\n return {\n matched: domainAddresses.some((address) => acceptable.has(address)),\n stray: domainAddresses.filter((address) => !acceptable.has(address)),\n }\n}\n\n/** What the check found for one name, as `/api/domains/verify` answers it. */\nexport interface TenantDnsCheck {\n domain: string\n /** The name's CNAME targets, lowercased; empty when it carries none. */\n records: string[]\n /** The CNAME target a subdomain must name. */\n expected: string\n verified: boolean\n /** Set when an apex passed by the addresses it lands on. */\n matchedBy?: 'apex-address'\n /** Addresses answering for the name that are not ours (AGL-1913). */\n strayAddresses?: string[]\n /** IPv6 addresses answering for the name that are not ours (AGL-3963). */\n strayIpv6Addresses?: string[]\n}\n\n/**\n * Resolves `domain` and answers whether it points at the tenant edge: its\n * CNAME names `CNAME_TARGET`, or, carrying no CNAME, its addresses are ours.\n *\n * `softPass` accepts ANY CNAME and belongs to local development alone, where\n * nothing points at the edge. A caller passes `isDevelopmentRuntime()` and\n * never a guess: a soft pass that keys on a missing hosting variable is the\n * AGL-2180 hole, where any domain with any CNAME verified on a container.\n *\n * Expects a lowercased name that matched {@link TENANT_DNS_DOMAIN_PATTERN}.\n * Never throws: an unreachable resolver reads as no records.\n */\nexport async function checkTenantDnsPointing(\n domain: string,\n options: { softPass?: boolean } = {},\n): Promise<TenantDnsCheck> {\n // NXDOMAIN / no CNAME comes back as an empty list — reported as unverified.\n const records = await resolveCnameRecords(domain)\n const cnameVerified =\n records.includes(CNAME_TARGET) || (options.softPass === true && records.length > 0)\n // Only fall back to the address comparison when there is no CNAME at all.\n // A domain that DOES carry a CNAME but points somewhere else must keep\n // failing — otherwise \"pointed at the wrong place\" and \"pointed at an apex\"\n // would verify identically.\n const [apex, strayIpv6] = records.length\n ? [{ matched: false, stray: [] as string[] }, [] as string[]]\n : await Promise.all([apexPointsAtTenantEdge(domain), strayIpv6Addresses(domain)])\n return {\n domain,\n records,\n expected: CNAME_TARGET,\n verified: cnameVerified || apex.matched,\n // Which rule passed, so the wizard can explain itself rather than just\n // showing a tick.\n ...(apex.matched && { matchedBy: 'apex-address' as const }),\n // Addresses answering for the name that are not ours. A verified domain\n // with a non-empty list here is the one that loads intermittently.\n ...(apex.stray.length ? { strayAddresses: apex.stray } : {}),\n // The previous host's AAAA, which pointing the A record here left in\n // place: IPv6 visitors still reach that host (AGL-3963).\n ...(strayIpv6.length ? { strayIpv6Addresses: strayIpv6 } : {}),\n }\n}\n"],"names":["CNAME_TARGET","HOST_APEX_ADDRESSES","promises","dns","Resolver","CallbackResolver","PUBLIC_DNS_RESOLVERS","PUBLIC_RESOLVERS","TENANT_DNS_DOMAIN_PATTERN","resolveCnameRecords","domain","normalise","records","map","record","toLowerCase","replace","resolver","setServers","Promise","resolve","reject","resolveCname","error","addresses","code","resolveARecords","lookup","resolve4","IPV6_LOOKUP_BUDGET_MS","withinIpv6Budget","work","fallback","timer","late","setTimeout","race","catch","finally","clearTimeout","normaliseIpv6","address","trimmed","trim","URL","hostname","resolveAaaaRecords","timeout","tries","resolve6","strayIpv6ByName","names","edge","answers","all","name","cnames","length","ours","Set","found","Map","answer","strays","filter","has","set","strayIpv6Addresses","get","conflictKey","type","value","kind","String","toUpperCase","host","data","join","withStrayIpv6Conflicts","conflicts","merged","listed","conflict","key","add","push","apexPointsAtTenantEdge","domainAddresses","targetAddresses","matched","stray","acceptable","some","checkTenantDnsPointing","options","cnameVerified","includes","softPass","apex","strayIpv6","expected","verified","matchedBy","strayAddresses"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,EAAEC,mBAAmB,QAAQ,4CAA2C;AAC7F,SAASC,YAAYC,GAAG,EAAEC,YAAYC,gBAAgB,QAAQ,MAAK;AACnE,SAASC,wBAAwBC,gBAAgB,QAAQ,iBAAa;AAEtE;;;;;;;;;;;CAWC,GAED,8EAA8E,GAC9E,OAAO,MAAMC,4BAA4B,8CAA6C;AAEtF;;;;;;;;;;;;CAYC,GAED,eAAeC,oBAAoBC,MAAc;IAC/C,MAAMC,YAAY,CAACC,UACjBA,QAAQC,GAAG,CAAC,CAACC,SAAWA,OAAOC,WAAW,GAAGC,OAAO,CAAC,OAAO;IAC9D,IAAI;QACF,MAAMC,WAAW,IAAIZ;QACrBY,SAASC,UAAU,CAACX;QACpB,MAAMK,UAAU,MAAM,IAAIO,QAAkB,CAACC,SAASC;YACpDJ,SAASK,YAAY,CAACZ,QAAQ,CAACa,OAAOC,YACpCD,QAAQF,OAAOE,SAASH,QAAQI;QAEpC;QACA,OAAOb,UAAUC;IACnB,EAAE,OAAOW,OAAO;QACd,wEAAwE;QACxE,8DAA8D;QAC9D,MAAME,OAAQF,yBAAD,AAACA,MAAiCE,IAAI;QACnD,IAAIA,SAAS,eAAeA,SAAS,aAAaA,SA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