@aglyn/tenant-data-admin 1.0.0-beta.176 → 1.0.0-beta.184

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/package.json +7 -6
  2. package/src/lib/server/account-acquisition.d.ts +84 -0
  3. package/src/lib/server/account-acquisition.js +107 -0
  4. package/src/lib/server/account-acquisition.js.map +1 -0
  5. package/src/lib/server/admin-audit.js +5 -1
  6. package/src/lib/server/admin-audit.js.map +1 -1
  7. package/src/lib/server/duplicate-resource.js +8 -1
  8. package/src/lib/server/duplicate-resource.js.map +1 -1
  9. package/src/lib/server/email-flow-gate.js +3 -1
  10. package/src/lib/server/email-flow-gate.js.map +1 -1
  11. package/src/lib/server/email-marketing-gate.d.ts +14 -0
  12. package/src/lib/server/email-marketing-gate.js +132 -17
  13. package/src/lib/server/email-marketing-gate.js.map +1 -1
  14. package/src/lib/server/email-sender-reputation.d.ts +11 -0
  15. package/src/lib/server/email-sender-reputation.js +4 -1
  16. package/src/lib/server/email-sender-reputation.js.map +1 -1
  17. package/src/lib/server/email-suppression.d.ts +58 -7
  18. package/src/lib/server/email-suppression.js +113 -28
  19. package/src/lib/server/email-suppression.js.map +1 -1
  20. package/src/lib/server/erase.d.ts +2 -0
  21. package/src/lib/server/erase.js +7 -0
  22. package/src/lib/server/erase.js.map +1 -1
  23. package/src/lib/server/first-party-hosts.d.ts +61 -0
  24. package/src/lib/server/first-party-hosts.js +110 -0
  25. package/src/lib/server/first-party-hosts.js.map +1 -0
  26. package/src/lib/server/first-touch-handoff.d.ts +51 -0
  27. package/src/lib/server/first-touch-handoff.js +88 -0
  28. package/src/lib/server/first-touch-handoff.js.map +1 -0
  29. package/src/lib/server/first-touch-route.d.ts +48 -0
  30. package/src/lib/server/first-touch-route.js +164 -0
  31. package/src/lib/server/first-touch-route.js.map +1 -0
  32. package/src/lib/server/host-email-tokens.js +10 -1
  33. package/src/lib/server/host-email-tokens.js.map +1 -1
  34. package/src/lib/server/live-page-usage.d.ts +33 -9
  35. package/src/lib/server/live-page-usage.js +26 -8
  36. package/src/lib/server/live-page-usage.js.map +1 -1
  37. package/src/lib/server/organizations.js +9 -0
  38. package/src/lib/server/organizations.js.map +1 -1
  39. package/src/lib/server/personal-data-export.js +11 -0
  40. package/src/lib/server/personal-data-export.js.map +1 -1
  41. package/src/lib/server/platform-marketing-consent.d.ts +157 -8
  42. package/src/lib/server/platform-marketing-consent.js +240 -21
  43. package/src/lib/server/platform-marketing-consent.js.map +1 -1
  44. package/src/lib/server/sending-domains.js +2 -2
  45. package/src/lib/server/sending-domains.js.map +1 -1
  46. package/src/lib/server/tracking-hosts.d.ts +98 -0
  47. package/src/lib/server/tracking-hosts.js +264 -0
  48. package/src/lib/server/tracking-hosts.js.map +1 -0
  49. package/src/lib/server/upsert-contact.d.ts +1 -1
  50. package/src/lib/server/upsert-contact.js +6 -0
  51. package/src/lib/server/upsert-contact.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/sending-domains.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 * CUSTOM SENDING DOMAINS — durable half.\n *\n * The record, the DNS lookups and the status transitions. The decisions all\n * live in `@aglyn/shared-util-email`'s `sending-domain.ts`, which is pure;\n * this module is the I/O around them, and it holds no policy of its own.\n *\n * ## Per-org record, per-host selection\n *\n * The record is at `orgs/{orgId}/sendingDomains/{domain}`, alongside\n * `orgs/{orgId}/ssoDomains/{domain}` and for the same reason: proving control\n * of a zone is a property of the ORG that proved it, and an agency running\n * four sites on `client.com` should publish the DKIM record once rather than\n * four times.\n *\n * Which identity a given site SENDS on is a separate per-host field,\n * `hosts/{hostId}.sendingDomain`. That split is what answers the two halves of\n * the question at once: per-org verification keeps the DNS chore down, and a\n * per-host selection is what an agency's client actually wants, because the\n * `From:` their recipients see belongs to the site, not to the agency.\n *\n * ## Reads are cheap on purpose\n *\n * `resolveHostSendingIdentity` is on the path of a campaign send, so it reads\n * the host document the caller already has and at most ONE org subcollection\n * document. It never scans, never lists, and never touches DNS — the standing\n * rule against unrequested reads on a hot path applies here more than most,\n * because a campaign resolves an identity once for thousands of messages.\n *\n * ## Why the provider call is not in here\n *\n * Issuing a DKIM key means creating a domain at the mail provider, which needs\n * a credential that can create things — a different one from the send-only\n * `RESEND_API_KEY`, which is exactly why `email-health.ts` can use the domains\n * endpoint as a read-only credential probe.\n *\n * That credential belongs to the console alone, so the driver that reads it\n * lives in the console app — `apps/console/utils/server/` — and not here.\n * **This library is imported by the tenant runtime**, which\n * serves untrusted published sites; a module it can import is a module whose\n * environment read is one bug away from being reachable from a site request.\n * A file in `apps/console` is not importable from the tenant app at all —\n * there is no path mapping to it and nx's module boundaries forbid app→app —\n * so the isolation is structural rather than a convention.\n *\n * What stays here is the seam: {@link recordIssuedSendingDomain} takes what a\n * provider returned, and {@link recordSendingDomainIssueFailure} takes what it\n * refused. `requestSendingDomain` still stops at `requested`, and a domain\n * stopped there refuses sends, which is the correct behavior for a domain that\n * has no signing key.\n */\n\nimport {\n assessDmarc,\n assessSendingRecords,\n isPlatformSendingDomain,\n isSharedSendingDomain,\n normalizeLocalPart,\n normalizeSendingDomain,\n resolveSendingIdentity,\n safeProviderDetail,\n SENDING_SUBDOMAIN,\n SENDING_TRACKING_SUBDOMAIN,\n sendingDnsRecords,\n sendingDomainRequiredRecords,\n sendingRecordKey,\n sharedTenantSendingFrom,\n validateSendingDomain,\n type DmarcAssessment,\n type SendingDnsRecord,\n type SendingDomainRecord,\n type SendingDomainSelection,\n type SendingIdentityPurpose,\n type SendingIdentityVerdict,\n type SendingVerification,\n} from '@aglyn/shared-util-email'\nimport firebaseAdmin from './firebase-admin'\nimport { lookupCaa, lookupMx, lookupTxt } from './dns-probe'\nimport { getOrgForHost } from './organizations'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Subcollection under the owning org. */\nexport const SENDING_DOMAINS_COLLECTION = 'sendingDomains'\n\nconst domainRef = (orgId: string, domain: string) =>\n firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(SENDING_DOMAINS_COLLECTION)\n .doc(domain)\n\n/**\n * The DKIM selector issued to one org for one domain.\n *\n * Includes the org id so two orgs verifying the same name occupy different\n * record names. Without that they would share `resend._domainkey.<domain>`,\n * and whichever verified second would overwrite the first — or, worse, inherit\n * the first's verification without ever publishing anything.\n */\nexport function sendingDkimSelector(orgId: string): string {\n const safe = String(orgId ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '')\n .slice(0, 24)\n return `aglyn${safe ? `-${safe}` : ''}`\n}\n\n/** Both keys always present, one always null — `strictNullChecks` is off. */\nexport interface SendingDomainResult {\n record: SendingDomainRecord | null\n error: string | null\n /** The HTTP status a route should answer with. */\n status: number\n}\n\n/**\n * One stored document as a record.\n *\n * Exported so the re-check sweep, which reaches these documents through a\n * collection-group query rather than by org and name, shapes them the same way\n * every other reader here does — a second reader with its own defaults is how\n * two callers come to disagree about what an absent field means.\n */\nexport function readSendingDomainRecord(\n snapshot: FirebaseFirestore.DocumentSnapshot,\n): SendingDomainRecord | null {\n if (!snapshot?.exists) return null\n const data = snapshot.data() ?? {}\n return {\n domain: String(data.domain ?? snapshot.id),\n status: data.status ?? 'requested',\n dkimSelector: String(data.dkimSelector ?? ''),\n dkimPublicKey: data.dkimPublicKey ?? null,\n returnPathHost: data.returnPathHost ?? null,\n providerDomainId: data.providerDomainId ?? null,\n trackingTarget: data.trackingTarget ?? null,\n createdAtMs: Number(data.createdAtMs) || null,\n verifiedAtMs: Number(data.verifiedAtMs) || null,\n lastCheckedAtMs: Number(data.lastCheckedAtMs) || null,\n lastIssueError: data.lastIssueError ?? null,\n lastIssueAtMs: Number(data.lastIssueAtMs) || null,\n lastMissing: Array.isArray(data.lastMissing) ? data.lastMissing : null,\n }\n}\n\n/**\n * Start (or re-read) a claim on a sending domain.\n *\n * Idempotent, and deliberately non-destructive on a re-request: an existing\n * record keeps its selector and its key, because reissuing either would\n * invalidate a record the customer may already have published and turn a\n * working setup into a mysterious failure. This mirrors `issueDomainClaim`.\n */\nexport async function requestSendingDomain(options: {\n orgId: string\n domain: string\n}): Promise<SendingDomainResult> {\n const { domain, error } = validateSendingDomain(options?.domain)\n if (!domain) return { record: null, error, status: 400 }\n if (!options?.orgId) {\n return { record: null, error: 'Missing organization', status: 400 }\n }\n\n const ref = domainRef(options.orgId, domain)\n const existing = await ref.get()\n if (existing.exists) {\n return { record: readSendingDomainRecord(existing), error: null, status: 200 }\n }\n\n const record: SendingDomainRecord = {\n domain,\n status: 'requested',\n dkimSelector: sendingDkimSelector(options.orgId),\n dkimPublicKey: null,\n returnPathHost: null,\n createdAtMs: Date.now(),\n }\n await ref.set(record, { merge: true })\n return { record, error: null, status: 201 }\n}\n\n/**\n * Record the key the mail provider issued, moving the domain to\n * `records-issued` so the customer has something to publish.\n *\n * Separated from {@link requestSendingDomain} because it needs a credential\n * that may not exist. Nothing here calls the provider: the caller supplies\n * what it was given, so a deployment whose key cannot create domains still has\n * a working path — an operator can complete this step by hand — and this\n * module never grows a dependency on a credential it cannot assume. The\n * console holds the credential and the driver that uses it; this library,\n * which the tenant runtime also imports, holds neither.\n *\n * ## `records-issued` is a promise that records exist\n *\n * The write is refused unless the resulting record actually yields a DKIM\n * record with a value. The alternative is the failure this whole feature is\n * arranged against: a status saying the customer has records to publish, next\n * to a records table with an empty DKIM row, which cannot ever verify and\n * reads to the customer as our bug.\n *\n * ## An issued key is never overwritten\n *\n * A second call carrying a DIFFERENT key is refused rather than applied. The\n * customer may already have published the first one, and replacing it turns a\n * finished setup into a domain that silently stops signing. Re-recording the\n * SAME key is a no-op and succeeds, so a retried request is safe.\n *\n * The SELECTOR, by contrast, comes from the provider when it supplies one:\n * the record a customer publishes has to be the name the provider will sign\n * under, and `sendingDkimSelector` only proposes it.\n */\nexport async function recordIssuedSendingDomain(options: {\n orgId: string\n domain: string\n dkimPublicKey: string\n /** The selector the provider issued, when it chose its own. */\n dkimSelector?: string\n returnPathHost?: string\n providerDomainId?: string\n /**\n * The provider's tracking host, when it issued one — see\n * `SendingDomainRecord.trackingTarget`. Absent leaves the domain sending\n * and unmeasured rather than unsent.\n */\n trackingTarget?: string | null\n}): Promise<SendingDomainResult> {\n const domain = normalizeSendingDomain(options?.domain)\n const key = String(options?.dkimPublicKey ?? '').trim()\n if (!domain) {\n return { record: null, error: 'Missing domain', status: 400 }\n }\n\n const ref = domainRef(options.orgId, domain)\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n return { record: null, error: 'No claim on that domain', status: 404 }\n }\n\n const existing = readSendingDomainRecord(snapshot)\n const held = String(existing?.dkimPublicKey ?? '').trim()\n if (held && held !== key) {\n return {\n record: existing,\n error:\n 'That domain already has an issued signing key. Release the domain ' +\n 'and add it again to start over.',\n status: 409,\n }\n }\n\n const selector =\n String(options?.dkimSelector ?? '').trim() || existing?.dkimSelector || ''\n const returnPathHost = options.returnPathHost || existing?.returnPathHost\n\n /*\n * The only thing standing between a caller and `records-issued`, and it is\n * asked of the SAME function that prints the records for the customer and\n * that the verifier compares against — not a truthiness check on the key,\n * which would be this write's private opinion of what \"publishable\" means\n * and could agree with nothing else.\n */\n const issued = sendingDomainRequiredRecords({\n domain,\n dkimSelector: selector,\n dkimPublicKey: key,\n returnPathHost,\n })\n if (!issued.some((entry) => entry.purpose === 'dkim')) {\n return {\n record: existing,\n error: 'Refusing to issue records for a domain with no publishable DKIM record',\n status: 400,\n }\n }\n\n await ref.set(\n {\n status: 'records-issued',\n dkimPublicKey: key,\n ...(selector ? { dkimSelector: selector } : {}),\n ...(options.returnPathHost\n ? { returnPathHost: options.returnPathHost }\n : {}),\n ...(options.providerDomainId\n ? { providerDomainId: String(options.providerDomainId) }\n : {}),\n // Only when the provider issued one. Writing an empty value would put a\n // tracking CNAME with no target in front of a customer, which is the\n // blank-record shape `sendingDnsRecords` refuses everywhere else.\n ...(String(options.trackingTarget ?? '').trim()\n ? { trackingTarget: String(options.trackingTarget).trim() }\n : {}),\n // A previous failure is not part of the record once it succeeded.\n lastIssueError: firebaseAdmin.firestore.FieldValue.delete(),\n },\n { merge: true },\n )\n return { record: readSendingDomainRecord(await ref.get()), error: null, status: 200 }\n}\n\n/**\n * Record that the provider did not issue anything, WITHOUT moving the status.\n *\n * The point of a separate function is that there is no path from a provider\n * failure to `records-issued`. A `4xx` or `5xx` means no key exists, so the\n * domain stays `requested` — where it refuses sends, which is correct for a\n * domain that cannot sign — and carries a reason an admin can act on instead\n * of appearing to have finished.\n *\n * `detail` is a short code the caller built from a fixed vocabulary, never a\n * provider's response body. {@link safeProviderDetail} is the second line:\n * an `Authorization` header echoed back by a provider must not become a\n * Firestore document.\n */\nexport async function recordSendingDomainIssueFailure(options: {\n orgId: string\n domain: string\n detail: string\n}): Promise<void> {\n const domain = normalizeSendingDomain(options?.domain)\n if (!options?.orgId || !domain) return\n const ref = domainRef(options.orgId, domain)\n if (!(await ref.get()).exists) return\n await ref.set(\n {\n lastIssueError: safeProviderDetail(options.detail) || 'unknown',\n lastIssueAtMs: Date.now(),\n },\n { merge: true },\n )\n}\n\nexport interface SendingDomainView {\n record: SendingDomainRecord\n /** Exactly what the customer must publish. */\n records: SendingDnsRecord[]\n /** Their DMARC policy, read and never written. */\n dmarc: DmarcAssessment | null\n}\n\n/** One domain plus the records it needs, for a surface that shows both. */\nexport async function getSendingDomain(\n orgId: string,\n rawDomain: string,\n): Promise<SendingDomainView | null> {\n const domain = normalizeSendingDomain(rawDomain)\n if (!orgId || !domain) return null\n const record = readSendingDomainRecord(await domainRef(orgId, domain).get())\n if (!record) return null\n return { record, records: sendingDnsRecords(record), dmarc: null }\n}\n\nexport async function listSendingDomains(\n orgId: string,\n): Promise<SendingDomainRecord[]> {\n if (!orgId) return []\n const snapshot = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(SENDING_DOMAINS_COLLECTION)\n .get()\n return snapshot.docs.map(readSendingDomainRecord).filter(Boolean)\n}\n\n/**\n * Read the customer's DMARC policy.\n *\n * Advisory in both directions: it never blocks verification and it is never\n * written. A domain under `p=reject` with our DKIM unpublished hard-fails\n * every message, and a customer deserves to be told that before they wonder\n * why their campaign vanished.\n */\nexport async function readDmarcPolicy(\n rawDomain: string,\n): Promise<DmarcAssessment | null> {\n const domain = normalizeSendingDomain(rawDomain)\n if (!domain) return null\n const lookup = await lookupTxt(`_dmarc.${domain}`)\n // An unreachable lookup is not \"they have no policy\" — saying so would tell\n // a customer under p=reject that they have no protection.\n if (!lookup.answered) return null\n return assessDmarc(lookup.records)\n}\n\n/**\n * Start (or read) the hold that keeps a tracked domain's links alive.\n *\n * Stamped on FIRST sighting rather than computed from an orphan timestamp,\n * because there is no reliable one: a label reassignment leaves no record of\n * when it happened, and the reaper re-infers the orphan on every pass. The\n * stamp is the record of when the hold began, so a domain cannot be held\n * forever by a sweep that keeps starting the clock over.\n *\n * @returns the instant the domain may be released, or `null` when there is\n * nothing to stamp it on — a domain with no org record cannot be\n * held, and refusing to release it on the strength of a hold nobody\n * can see would strand a provider slot permanently.\n */\nexport async function holdTrackedSendingDomain(options: {\n orgId: string | null\n domain: string\n nowMs: number\n windowMs: number\n}): Promise<number | null> {\n const orgId = String(options?.orgId ?? '').trim()\n const domain = normalizeSendingDomain(options?.domain)\n if (!orgId || !domain || options.windowMs <= 0) return null\n\n const ref = domainRef(orgId, domain)\n const snapshot = await ref.get().catch(() => null)\n if (!snapshot?.exists) return null\n\n const held = Number(snapshot.get('trackingRetentionUntilMs')) || 0\n if (held > 0) return held\n\n const until = options.nowMs + options.windowMs\n await ref\n .set({ trackingRetentionUntilMs: until }, { merge: true })\n // A stamp we could not write is a hold we cannot prove later, so the\n // caller is told there is none rather than being asked to wait on a\n // deadline that will restart on the next pass.\n .catch(() => null)\n return until\n}\n\n/**\n * Whether this domain publishes a CAA policy that would REFUSE the tracking\n * host's certificate.\n *\n * The question decides whether a customer is shown a CAA record at all, and\n * asking it is the difference between guidance and a footgun. CAA restricts\n * which authorities may issue, and the lookup stops at the first name in the\n * tree publishing any record — so:\n *\n * - A domain publishing NOTHING needs nothing. Any authority may already\n * issue, and handing over a CAA record to paste would be the change that\n * STARTS restricting them, breaking whatever else renews on that name.\n * - A domain that publishes some, none of which name our authority, has to\n * add one ALONGSIDE what it has.\n * - A domain that already names our authority is done.\n *\n * Walks up from the tracking host exactly as a certificate authority does,\n * and stops where a real lookup stops: at the first name with any record.\n *\n * @returns `null` when DNS could not be reached, which is not \"they publish\n * none\" — telling a customer to add a CAA on the strength of an\n * unanswered lookup is how a working zone gets narrowed by mistake.\n */\nexport async function readTrackingCaaNeed(\n rawDomain: string,\n authority: string,\n): Promise<'not-needed' | 'must-add' | 'satisfied' | null> {\n const domain = normalizeSendingDomain(rawDomain)\n const ca = String(authority ?? '').trim().toLowerCase()\n if (!domain || !ca) return null\n\n /*\n * From the tracking host upward. Every label is asked because a CAA on a\n * closer name overrides a broader one — a customer who already scoped a\n * policy to `links.` must not be told to widen their root.\n */\n const labels = `${SENDING_TRACKING_SUBDOMAIN}.${domain}`.split('.')\n for (let index = 0; index < labels.length - 1; index += 1) {\n const name = labels.slice(index).join('.')\n const lookup = await lookupCaa(name)\n if (!lookup.answered) return null\n if (!lookup.records.length) continue\n // The first name with any record is where issuance is decided.\n const issuers = lookup.records\n .filter((entry) => / issue \"/.test(entry))\n .map((entry) => entry.toLowerCase())\n return issuers.some((entry) => entry.includes(`\"${ca}\"`))\n ? 'satisfied'\n : 'must-add'\n }\n return 'not-needed'\n}\n\n/**\n * Read the live DNS for one record and say what it establishes. Writes\n * nothing.\n *\n * Split out so the two callers that need this answer ask the SAME question of\n * the SAME resolvers: {@link verifySendingDomain}, which acts on it\n * immediately, and the unattended re-check sweep, which counts conclusive\n * failures before it acts. A sweep that assessed the records its own way would\n * be a second opinion on \"are these published\", and the customer would meet\n * whichever one happened to run last.\n *\n * The three lookups run together because they are independent and the caller\n * is waiting on the slowest either way.\n */\nexport async function probeSendingRecords(\n record: SendingDomainRecord,\n): Promise<SendingVerification> {\n const domain = normalizeSendingDomain(record?.domain ?? '')\n const sendHost = `${SENDING_SUBDOMAIN}.${domain}`\n const dkimHost = `${record.dkimSelector}._domainkey.${domain}`\n const [spf, dkim, mx] = await Promise.all([\n lookupTxt(sendHost),\n lookupTxt(dkimHost),\n lookupMx(sendHost),\n ])\n\n return assessSendingRecords(record, {\n spfTxt: spf.records,\n dkimTxt: dkim.records,\n mx: mx.records,\n // All three, not any: a record we could not read is not a record that is\n // absent, and one unreadable lookup is enough to make the whole answer\n // evidence of nothing.\n conclusive: spf.answered && dkim.answered && mx.answered,\n })\n}\n\n/**\n * Check the live DNS and move the record to `verified` or `failed`.\n *\n * Never throws: a sweep across every org must not stop at the first bad zone.\n *\n * An INCONCLUSIVE result writes nothing but the check time. A resolver outage\n * must not un-verify a working domain — which would silently stop that\n * tenant's mail — and must not fail a customer who is midway through\n * publishing either. This is the `hold` arm the SSO drift sweep uses, and the\n * reason `assessSendingRecords` has three outcomes rather than two.\n *\n * Acts on ONE conclusive answer, and that is right for this caller: an admin\n * pressed Verify and is watching the result, so the check is attended and its\n * outcome is immediately visible and immediately retryable. The unattended\n * sweep over already-verified domains is the caller that cannot say that, and\n * `sending-domain-recheck.ts` is where the extra evidence it needs is\n * gathered.\n */\nexport async function verifySendingDomain(\n orgId: string,\n rawDomain: string,\n): Promise<{\n record: SendingDomainRecord | null\n missing: string[]\n inconclusive: boolean\n error: string | null\n}> {\n const domain = normalizeSendingDomain(rawDomain)\n if (!orgId || !domain) {\n return { record: null, missing: [], inconclusive: false, error: 'Invalid domain' }\n }\n\n const ref = domainRef(orgId, domain)\n const record = readSendingDomainRecord(await ref.get())\n if (!record) {\n return {\n record: null,\n missing: [],\n inconclusive: false,\n error: 'No claim on that domain — add it first.',\n }\n }\n\n const verdict = await probeSendingRecords(record)\n\n const now = Date.now()\n if (verdict.status === 'inconclusive') {\n await ref.set({ lastCheckedAtMs: now }, { merge: true })\n return { record, missing: [], inconclusive: true, error: null }\n }\n\n const verified = verdict.status === 'verified'\n await ref.set(\n {\n status: verified ? 'verified' : 'failed',\n lastCheckedAtMs: now,\n ...(verified\n ? {\n verifiedAtMs: now,\n lastMissing: firebaseAdmin.firestore.FieldValue.delete(),\n }\n : { lastMissing: verdict.missing }),\n },\n { merge: true },\n )\n\n return {\n record: readSendingDomainRecord(await ref.get()),\n missing: verdict.missing,\n inconclusive: false,\n error: null,\n }\n}\n\n/**\n * Drop a claim.\n *\n * The host selections pointing at it are NOT rewritten to the platform\n * identity. A site that was sending as its own domain and now has no verified\n * one must refuse, not quietly revert — silently moving a tenant's mail back\n * onto the shared domain is the exact fallback this feature exists to prevent,\n * and doing it during a delete would be no better than doing it during a send.\n */\nexport async function releaseSendingDomain(\n orgId: string,\n rawDomain: string,\n): Promise<void> {\n const domain = normalizeSendingDomain(rawDomain)\n if (!orgId || !domain) return\n await domainRef(orgId, domain)\n .delete()\n .catch(() => undefined)\n}\n\n/*==========================================\n The read on the send path\n==========================================*/\n\n/**\n * The identity one host sends on, ready to hand to `sendEmail`.\n *\n * Two document reads at most, and none at all for a host that has no\n * selection. The host document is passed in rather than re-fetched because\n * every caller already holds it.\n *\n * ## This function cannot return an `aglyn.com` address, and that is the point\n *\n * Every caller here is resolving mail FOR A SITE — that is what \"host\" in the\n * name means — so every verdict it produces is tenant mail by construction.\n * `audience: 'tenant'` is therefore passed unconditionally and is not a\n * parameter: a caller that could choose would eventually choose wrong, and the\n * wrong choice puts a merchant's list quality onto the domain the platform's\n * own invoices and password resets leave on.\n *\n * A site that has selected NOTHING does not reach `USAGE_EMAIL_FROM` either.\n * All of its mail goes on the shared pool member `hostSharedFrom` assigns it,\n * marketing included. What keeps the pool usable is measurement rather than\n * prohibition: a pooled campaign is graded against the stricter reputation\n * thresholds, so the site earning complaints is the one that stops.\n */\nexport async function resolveHostSendingIdentity(options: {\n orgId: string | null | undefined\n /** `hosts/{hostId}.sendingDomain`, the site's selection. */\n selectedDomain: string | null | undefined\n /** `hosts/{hostId}.sendingLocalPart`, defaulted when unset. */\n selectedLocalPart?: string | null\n platformFrom?: string | null\n /**\n * The site, so an unselected host can be assigned a pool member.\n *\n * Optional because two of the three callers resolve an identity for a host\n * they are already holding and one — the console's identity view — is asking\n * about a specific site by id. A caller that omits it gets no shared\n * identity, which is the honest answer: the pool assignment is per site, and\n * \"some pool member\" is not a thing to send a receipt from.\n */\n hostId?: string | null\n /**\n * A pool member this host is pinned to, overriding the hash.\n *\n * `hosts/{hostId}.sendingPoolMember`. The QUARANTINE lever: a site whose\n * transactional mail is generating complaints can be moved onto a member set\n * aside for it, without disturbing any of the other sites that hash to the\n * member it was on. Ignored unless it names a real member of the current\n * pool, so a stale or hand-edited value degrades to the ordinary assignment\n * rather than to an address nothing signs for.\n */\n poolMember?: string | null\n /** See `SendingIdentityPurpose`. Defaults to transactional. */\n purpose?: SendingIdentityPurpose\n}): Promise<SendingIdentityVerdict> {\n const platformFrom =\n options?.platformFrom ?? process.env.USAGE_EMAIL_FROM ?? null\n const domain = normalizeSendingDomain(options?.selectedDomain ?? '')\n const purpose = options?.purpose\n const sharedFrom = hostSharedFrom(options?.hostId, options?.poolMember)\n\n if (!domain || !options?.orgId) {\n return resolveSendingIdentity({\n selection: null,\n platformFrom,\n sharedFrom,\n purpose,\n audience: 'tenant',\n })\n }\n\n const record = readSendingDomainRecord(await domainRef(options.orgId, domain).get())\n\n /*\n * Whose domain this is, decided from the NAME rather than from the record.\n *\n * The record is what a released domain no longer has, and a site pointed at\n * a subdomain of our own apex is still pointed at a subdomain of our own\n * apex whether or not one exists for it. Deriving this from the name keeps\n * the two possible failures apart: a missing record for OUR name is our\n * provisioning that did not finish, a missing record for THEIRS is a domain\n * they asked to send as and nothing has verified.\n */\n const platformIssued = isPlatformSendingDomain(domain)\n\n /*\n * A selection naming a CUSTOMER'S domain with no record refuses rather than\n * falling back. The record can be gone because it was released, or because\n * the selection was written against a different org — both mean the site is\n * configured to send as a domain nothing has verified, and neither is a\n * reason to send as somebody else.\n *\n * `platformIssued` rides on the selection either way, and the resolver reads\n * it only on the unverified branch: a platform subdomain that has not\n * finished provisioning drops to the pool for transactional mail instead,\n * because nothing about it is a merchant instruction to contradict.\n */\n const selection: SendingDomainSelection = record\n ? {\n domain: record.domain,\n status: record.status,\n localPart: normalizeLocalPart(options.selectedLocalPart ?? '') || 'hello',\n missing: record.lastMissing ?? [],\n platformIssued,\n }\n : { domain, status: 'failed', localPart: '', missing: [], platformIssued }\n\n /*\n * `sharedFrom` is passed even here, where a selection exists and will decide\n * the outcome. It is inert by construction — the selection branch of\n * `resolveSendingIdentity` never reads it — and passing it unconditionally\n * keeps the call shape identical between the two arms, so a future edit\n * cannot produce a path that had a pool available and did not offer it.\n *\n * It must NOT become a fallback for an unverified selection, and it is the\n * resolver's structure rather than this call site that guarantees that.\n */\n return resolveSendingIdentity({\n selection,\n platformFrom,\n sharedFrom,\n purpose,\n audience: 'tenant',\n })\n}\n\n/**\n * The pool address for one host: the pinned member if it names a real one, the\n * hash assignment otherwise.\n *\n * The override is validated against the LIVE pool rather than trusted, because\n * a stale value is the expected case — an operator shrinks the pool, or a\n * quarantine was lifted by deleting the member rather than the field — and an\n * address on a domain that no longer exists is a send that fails at the\n * provider instead of one that quietly goes back to normal.\n */\nfunction hostSharedFrom(\n hostId: string | null | undefined,\n poolMember: string | null | undefined,\n): string {\n const id = String(hostId ?? '').trim()\n if (!id) return ''\n\n const pinned = normalizeSendingDomain(String(poolMember ?? ''))\n if (pinned && isSharedSendingDomain(pinned)) {\n const shared = sharedTenantSendingFrom(id)\n const at = shared.lastIndexOf('@')\n return at > 0 ? `${shared.slice(0, at)}@${pinned}` : ''\n }\n\n return sharedTenantSendingFrom(id)\n}\n\n/**\n * The identity one site sends on, from a `hostId` alone.\n *\n * The door every tenant sender uses. {@link resolveHostSendingIdentity} needs\n * the org id and the host's two selection fields, and a survey of the tenant\n * send sites found that all of them hold a `hostId` while only three hold an\n * org id and half never read the host document at all. Asking nineteen call\n * sites to each assemble the same three values is the shape that produces a\n * twentieth which does not — and the cost of forgetting here is a message\n * leaving on the platform's own domain.\n *\n * ## The cache is per-call-graph, not per-process\n *\n * Passed a `cache`, repeated resolutions for one host cost one pair of reads.\n * A sweep that mails two hundred abandoned carts across a dozen sites, or a\n * webhook that sends a receipt and a seller notice for the same order, holds\n * one map for the run and pays for each site once.\n *\n * Deliberately NOT a module-level cache. Verification status is exactly the\n * thing that changes underneath a long-lived process — the re-check sweep\n * un-verifies a domain whose records have gone — and a stale entry would keep\n * a site sending on a domain that no longer authenticates. A caller that\n * declares a cache has also declared how long it may be trusted.\n */\nexport async function hostSendingIdentity(\n hostId: string | null | undefined,\n cache?: Map<string, SendingIdentityVerdict>,\n): Promise<SendingIdentityVerdict> {\n const id = String(hostId ?? '').trim()\n if (!id) {\n /*\n * No host is not \"the platform is speaking\", and it is not \"any pool\n * member will do\" either. It is a caller that does not know which site it\n * is sending for, and the honest answer to that is a refusal.\n *\n * No `sharedFrom` is passed, which is what makes that structural rather\n * than a rule: the pool is assigned FROM the host id, so a caller without\n * one has nothing to be assigned.\n */\n return resolveSendingIdentity({ selection: null, audience: 'tenant' })\n }\n\n const hit = cache?.get(id)\n if (hit) return hit\n\n const snapshot = await firestore()\n .collection('hosts')\n .doc(id)\n .get()\n .catch(() => null)\n const owner = await getOrgForHost(id).catch(() => null)\n\n const verdict = await resolveHostSendingIdentity({\n orgId: owner?.orgId ?? null,\n selectedDomain: snapshot?.get('sendingDomain') ?? '',\n selectedLocalPart: snapshot?.get('sendingLocalPart') ?? '',\n hostId: id,\n poolMember: snapshot?.get('sendingPoolMember') ?? '',\n })\n\n cache?.set(id, verdict)\n return verdict\n}\n\n/** The record keys a surface highlights as outstanding. */\nexport function outstandingSendingRecords(\n record: SendingDomainRecord,\n): SendingDnsRecord[] {\n const missing = new Set(record?.lastMissing ?? [])\n if (!missing.size) return []\n return sendingDnsRecords(record).filter((entry) =>\n missing.has(sendingRecordKey(entry)),\n )\n}\n"],"names":["assessDmarc","assessSendingRecords","isPlatformSendingDomain","isSharedSendingDomain","normalizeLocalPart","normalizeSendingDomain","resolveSendingIdentity","safeProviderDetail","SENDING_SUBDOMAIN","SENDING_TRACKING_SUBDOMAIN","sendingDnsRecords","sendingDomainRequiredRecords","sendingRecordKey","sharedTenantSendingFrom","validateSendingDomain","firebaseAdmin","lookupCaa","lookupMx","lookupTxt","getOrgForHost","firestore","app","SENDING_DOMAINS_COLLECTION","domainRef","orgId","domain","collection","doc","sendingDkimSelector","safe","String","toLowerCase","replace","slice","readSendingDomainRecord","snapshot","data","exists","id","status","dkimSelector","dkimPublicKey","returnPathHost","providerDomainId","trackingTarget","createdAtMs","Number","verifiedAtMs","lastCheckedAtMs","lastIssueError","lastIssueAtMs","lastMissing","Array","isArray","requestSendingDomain","options","error","record","ref","existing","get","Date","now","set","merge","recordIssuedSendingDomain","key","trim","held","selector","issued","some","entry","purpose","FieldValue","delete","recordSendingDomainIssueFailure","detail","getSendingDomain","rawDomain","records","dmarc","listSendingDomains","docs","map","filter","Boolean","readDmarcPolicy","lookup","answered","holdTrackedSendingDomain","windowMs","catch","until","nowMs","trackingRetentionUntilMs","readTrackingCaaNeed","authority","ca","labels","split","index","length","name","join","issuers","test","includes","probeSendingRecords","sendHost","dkimHost","spf","dkim","mx","Promise","all","spfTxt","dkimTxt","conclusive","verifySendingDomain","missing","inconclusive","verdict","verified","releaseSendingDomain","undefined","resolveHostSendingIdentity","platformFrom","process","env","USAGE_EMAIL_FROM","selectedDomain","sharedFrom","hostSharedFrom","hostId","poolMember","selection","audience","platformIssued","localPart","selectedLocalPart","pinned","shared","at","lastIndexOf","hostSendingIdentity","cache","hit","owner","outstandingSendingRecords","Set","size","has"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkDC,GAED,SACEA,WAAW,EACXC,oBAAoB,EACpBC,uBAAuB,EACvBC,qBAAqB,EACrBC,kBAAkB,EAClBC,sBAAsB,EACtBC,sBAAsB,EACtBC,kBAAkB,EAClBC,iBAAiB,EACjBC,0BAA0B,EAC1BC,iBAAiB,EACjBC,4BAA4B,EAC5BC,gBAAgB,EAChBC,uBAAuB,EACvBC,qBAAqB,QAQhB,2BAA0B;AACjC,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,SAAS,EAAEC,QAAQ,EAAEC,SAAS,QAAQ,iBAAa;AAC5D,SAASC,aAAa,QAAQ,qBAAiB;AAE/C,MAAMC,YAAY,IAAML,cAAcM,GAAG,GAAGD,SAAS;AAErD,wCAAwC,GACxC,OAAO,MAAME,6BAA6B,iBAAgB;AAE1D,MAAMC,YAAY,CAACC,OAAeC,SAChCL,YACGM,UAAU,CAAC,QACXC,GAAG,CAACH,OACJE,UAAU,CAACJ,4BACXK,GAAG,CAACF;AAET;;;;;;;CAOC,GACD,OAAO,SAASG,oBAAoBJ,KAAa;IAC/C,MAAMK,OAAOC,OAAON,gBAAAA,QAAS,IAC1BO,WAAW,GACXC,OAAO,CAAC,cAAc,IACtBC,KAAK,CAAC,GAAG;IACZ,OAAO,CAAC,KAAK,EAAEJ,OAAO,CAAC,CAAC,EAAEA,MAAM,GAAG,IAAI;AACzC;AAUA;;;;;;;CAOC,GACD,OAAO,SAASK,wBACdC,QAA4C;QAG/BA,gBAEIC,cACPA,cACaA,oBACNA,qBACCA,sBACEA,wBACFA,sBAIAA;IAblB,IAAI,EAACD,4BAAAA,SAAUE,MAAM,GAAE,OAAO;IAC9B,MAAMD,QAAOD,iBAAAA,SAASC,IAAI,cAAbD,iBAAmB,CAAC;IACj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;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,eAAe2G,oBACpBX,MAAiC,EACjCY,KAA2C;;IAE3C,MAAM5G,KAAKR,OAAOwG,iBAAAA,SAAU,IAAInE,IAAI;IACpC,IAAI,CAAC7B,IAAI;QACP;;;;;;;;KAQC,GACD,OAAOhC,uBAAuB;YAAEkI,WAAW;YAAMC,UAAU;QAAS;IACtE;IAEA,MAAMU,MAAMD,yBAAAA,MAAOtF,GAAG,CAACtB;IACvB,IAAI6G,KAAK,OAAOA;IAEhB,MAAMhH,WAAW,MAAMf,YACpBM,UAAU,CAAC,SACXC,GAAG,CAACW,IACJsB,GAAG,GACHgC,KAAK,CAAC,IAAM;IACf,MAAMwD,QAAQ,MAAMjI,cAAcmB,IAAIsD,KAAK,CAAC,IAAM;IAElD,MAAM8B,UAAU,MAAMI,2BAA2B;QAC/CtG,KAAK,UAAE4H,yBAAAA,MAAO5H,KAAK,mBAAI;QACvB2G,cAAc,WAAEhG,4BAAAA,SAAUyB,GAAG,CAAC,oCAAoB;QAClDgF,iBAAiB,WAAEzG,4BAAAA,SAAUyB,GAAG,CAAC,uCAAuB;QACxD0E,QAAQhG;QACRiG,UAAU,WAAEpG,4BAAAA,SAAUyB,GAAG,CAAC,wCAAwB;IACpD;IAEAsF,yBAAAA,MAAOnF,GAAG,CAACzB,IAAIoF;IACf,OAAOA;AACT;AAEA,yDAAyD,GACzD,OAAO,SAAS2B,0BACd5F,MAA2B;;IAE3B,MAAM+D,UAAU,IAAI8B,YAAI7F,0BAAAA,OAAQN,WAAW,mBAAI,EAAE;IACjD,IAAI,CAACqE,QAAQ+B,IAAI,EAAE,OAAO,EAAE;IAC5B,OAAO7I,kBAAkB+C,QAAQ4B,MAAM,CAAC,CAACb,QACvCgD,QAAQgC,GAAG,CAAC5I,iBAAiB4D;AAEjC"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/sending-domains.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 * CUSTOM SENDING DOMAINS — durable half.\n *\n * The record, the DNS lookups and the status transitions. The decisions all\n * live in `@aglyn/shared-util-email`'s `sending-domain.ts`, which is pure;\n * this module is the I/O around them, and it holds no policy of its own.\n *\n * ## Per-org record, per-host selection\n *\n * The record is at `orgs/{orgId}/sendingDomains/{domain}`, alongside\n * `orgs/{orgId}/ssoDomains/{domain}` and for the same reason: proving control\n * of a zone is a property of the ORG that proved it, and an agency running\n * four sites on `client.com` should publish the DKIM record once rather than\n * four times.\n *\n * Which identity a given site SENDS on is a separate per-host field,\n * `hosts/{hostId}.sendingDomain`. That split is what answers the two halves of\n * the question at once: per-org verification keeps the DNS chore down, and a\n * per-host selection is what an agency's client actually wants, because the\n * `From:` their recipients see belongs to the site, not to the agency.\n *\n * ## Reads are cheap on purpose\n *\n * `resolveHostSendingIdentity` is on the path of a campaign send, so it reads\n * the host document the caller already has and at most ONE org subcollection\n * document. It never scans, never lists, and never touches DNS — the standing\n * rule against unrequested reads on a hot path applies here more than most,\n * because a campaign resolves an identity once for thousands of messages.\n *\n * ## Why the provider call is not in here\n *\n * Issuing a DKIM key means creating a domain at the mail provider, which needs\n * a credential that can create things — a different one from the send-only\n * `RESEND_API_KEY`, which is exactly why `email-health.ts` can use the domains\n * endpoint as a read-only credential probe.\n *\n * That credential belongs to the console alone, so the driver that reads it\n * lives in the console app — `apps/console/utils/server/` — and not here.\n * **This library is imported by the tenant runtime**, which\n * serves untrusted published sites; a module it can import is a module whose\n * environment read is one bug away from being reachable from a site request.\n * A file in `apps/console` is not importable from the tenant app at all —\n * there is no path mapping to it and nx's module boundaries forbid app→app —\n * so the isolation is structural rather than a convention.\n *\n * What stays here is the seam: {@link recordIssuedSendingDomain} takes what a\n * provider returned, and {@link recordSendingDomainIssueFailure} takes what it\n * refused. `requestSendingDomain` still stops at `requested`, and a domain\n * stopped there refuses sends, which is the correct behavior for a domain that\n * has no signing key.\n */\n\nimport {\n assessDmarc,\n assessSendingRecords,\n isPlatformSendingDomain,\n isSharedSendingDomain,\n normalizeLocalPart,\n normalizeSendingDomain,\n resolveSendingIdentity,\n safeProviderDetail,\n SENDING_SUBDOMAIN,\n sendingDnsRecords,\n sendingTrackingHost,\n sendingDomainRequiredRecords,\n sendingRecordKey,\n sharedTenantSendingFrom,\n validateSendingDomain,\n type DmarcAssessment,\n type SendingDnsRecord,\n type SendingDomainRecord,\n type SendingDomainSelection,\n type SendingIdentityPurpose,\n type SendingIdentityVerdict,\n type SendingVerification,\n} from '@aglyn/shared-util-email'\nimport firebaseAdmin from './firebase-admin'\nimport { lookupCaa, lookupMx, lookupTxt } from './dns-probe'\nimport { getOrgForHost } from './organizations'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Subcollection under the owning org. */\nexport const SENDING_DOMAINS_COLLECTION = 'sendingDomains'\n\nconst domainRef = (orgId: string, domain: string) =>\n firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(SENDING_DOMAINS_COLLECTION)\n .doc(domain)\n\n/**\n * The DKIM selector issued to one org for one domain.\n *\n * Includes the org id so two orgs verifying the same name occupy different\n * record names. Without that they would share `resend._domainkey.<domain>`,\n * and whichever verified second would overwrite the first — or, worse, inherit\n * the first's verification without ever publishing anything.\n */\nexport function sendingDkimSelector(orgId: string): string {\n const safe = String(orgId ?? '')\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '')\n .slice(0, 24)\n return `aglyn${safe ? `-${safe}` : ''}`\n}\n\n/** Both keys always present, one always null — `strictNullChecks` is off. */\nexport interface SendingDomainResult {\n record: SendingDomainRecord | null\n error: string | null\n /** The HTTP status a route should answer with. */\n status: number\n}\n\n/**\n * One stored document as a record.\n *\n * Exported so the re-check sweep, which reaches these documents through a\n * collection-group query rather than by org and name, shapes them the same way\n * every other reader here does — a second reader with its own defaults is how\n * two callers come to disagree about what an absent field means.\n */\nexport function readSendingDomainRecord(\n snapshot: FirebaseFirestore.DocumentSnapshot,\n): SendingDomainRecord | null {\n if (!snapshot?.exists) return null\n const data = snapshot.data() ?? {}\n return {\n domain: String(data.domain ?? snapshot.id),\n status: data.status ?? 'requested',\n dkimSelector: String(data.dkimSelector ?? ''),\n dkimPublicKey: data.dkimPublicKey ?? null,\n returnPathHost: data.returnPathHost ?? null,\n providerDomainId: data.providerDomainId ?? null,\n trackingTarget: data.trackingTarget ?? null,\n createdAtMs: Number(data.createdAtMs) || null,\n verifiedAtMs: Number(data.verifiedAtMs) || null,\n lastCheckedAtMs: Number(data.lastCheckedAtMs) || null,\n lastIssueError: data.lastIssueError ?? null,\n lastIssueAtMs: Number(data.lastIssueAtMs) || null,\n lastMissing: Array.isArray(data.lastMissing) ? data.lastMissing : null,\n }\n}\n\n/**\n * Start (or re-read) a claim on a sending domain.\n *\n * Idempotent, and deliberately non-destructive on a re-request: an existing\n * record keeps its selector and its key, because reissuing either would\n * invalidate a record the customer may already have published and turn a\n * working setup into a mysterious failure. This mirrors `issueDomainClaim`.\n */\nexport async function requestSendingDomain(options: {\n orgId: string\n domain: string\n}): Promise<SendingDomainResult> {\n const { domain, error } = validateSendingDomain(options?.domain)\n if (!domain) return { record: null, error, status: 400 }\n if (!options?.orgId) {\n return { record: null, error: 'Missing organization', status: 400 }\n }\n\n const ref = domainRef(options.orgId, domain)\n const existing = await ref.get()\n if (existing.exists) {\n return { record: readSendingDomainRecord(existing), error: null, status: 200 }\n }\n\n const record: SendingDomainRecord = {\n domain,\n status: 'requested',\n dkimSelector: sendingDkimSelector(options.orgId),\n dkimPublicKey: null,\n returnPathHost: null,\n createdAtMs: Date.now(),\n }\n await ref.set(record, { merge: true })\n return { record, error: null, status: 201 }\n}\n\n/**\n * Record the key the mail provider issued, moving the domain to\n * `records-issued` so the customer has something to publish.\n *\n * Separated from {@link requestSendingDomain} because it needs a credential\n * that may not exist. Nothing here calls the provider: the caller supplies\n * what it was given, so a deployment whose key cannot create domains still has\n * a working path — an operator can complete this step by hand — and this\n * module never grows a dependency on a credential it cannot assume. The\n * console holds the credential and the driver that uses it; this library,\n * which the tenant runtime also imports, holds neither.\n *\n * ## `records-issued` is a promise that records exist\n *\n * The write is refused unless the resulting record actually yields a DKIM\n * record with a value. The alternative is the failure this whole feature is\n * arranged against: a status saying the customer has records to publish, next\n * to a records table with an empty DKIM row, which cannot ever verify and\n * reads to the customer as our bug.\n *\n * ## An issued key is never overwritten\n *\n * A second call carrying a DIFFERENT key is refused rather than applied. The\n * customer may already have published the first one, and replacing it turns a\n * finished setup into a domain that silently stops signing. Re-recording the\n * SAME key is a no-op and succeeds, so a retried request is safe.\n *\n * The SELECTOR, by contrast, comes from the provider when it supplies one:\n * the record a customer publishes has to be the name the provider will sign\n * under, and `sendingDkimSelector` only proposes it.\n */\nexport async function recordIssuedSendingDomain(options: {\n orgId: string\n domain: string\n dkimPublicKey: string\n /** The selector the provider issued, when it chose its own. */\n dkimSelector?: string\n returnPathHost?: string\n providerDomainId?: string\n /**\n * The provider's tracking host, when it issued one — see\n * `SendingDomainRecord.trackingTarget`. Absent leaves the domain sending\n * and unmeasured rather than unsent.\n */\n trackingTarget?: string | null\n}): Promise<SendingDomainResult> {\n const domain = normalizeSendingDomain(options?.domain)\n const key = String(options?.dkimPublicKey ?? '').trim()\n if (!domain) {\n return { record: null, error: 'Missing domain', status: 400 }\n }\n\n const ref = domainRef(options.orgId, domain)\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n return { record: null, error: 'No claim on that domain', status: 404 }\n }\n\n const existing = readSendingDomainRecord(snapshot)\n const held = String(existing?.dkimPublicKey ?? '').trim()\n if (held && held !== key) {\n return {\n record: existing,\n error:\n 'That domain already has an issued signing key. Release the domain ' +\n 'and add it again to start over.',\n status: 409,\n }\n }\n\n const selector =\n String(options?.dkimSelector ?? '').trim() || existing?.dkimSelector || ''\n const returnPathHost = options.returnPathHost || existing?.returnPathHost\n\n /*\n * The only thing standing between a caller and `records-issued`, and it is\n * asked of the SAME function that prints the records for the customer and\n * that the verifier compares against — not a truthiness check on the key,\n * which would be this write's private opinion of what \"publishable\" means\n * and could agree with nothing else.\n */\n const issued = sendingDomainRequiredRecords({\n domain,\n dkimSelector: selector,\n dkimPublicKey: key,\n returnPathHost,\n })\n if (!issued.some((entry) => entry.purpose === 'dkim')) {\n return {\n record: existing,\n error: 'Refusing to issue records for a domain with no publishable DKIM record',\n status: 400,\n }\n }\n\n await ref.set(\n {\n status: 'records-issued',\n dkimPublicKey: key,\n ...(selector ? { dkimSelector: selector } : {}),\n ...(options.returnPathHost\n ? { returnPathHost: options.returnPathHost }\n : {}),\n ...(options.providerDomainId\n ? { providerDomainId: String(options.providerDomainId) }\n : {}),\n // Only when the provider issued one. Writing an empty value would put a\n // tracking CNAME with no target in front of a customer, which is the\n // blank-record shape `sendingDnsRecords` refuses everywhere else.\n ...(String(options.trackingTarget ?? '').trim()\n ? { trackingTarget: String(options.trackingTarget).trim() }\n : {}),\n // A previous failure is not part of the record once it succeeded.\n lastIssueError: firebaseAdmin.firestore.FieldValue.delete(),\n },\n { merge: true },\n )\n return { record: readSendingDomainRecord(await ref.get()), error: null, status: 200 }\n}\n\n/**\n * Record that the provider did not issue anything, WITHOUT moving the status.\n *\n * The point of a separate function is that there is no path from a provider\n * failure to `records-issued`. A `4xx` or `5xx` means no key exists, so the\n * domain stays `requested` — where it refuses sends, which is correct for a\n * domain that cannot sign — and carries a reason an admin can act on instead\n * of appearing to have finished.\n *\n * `detail` is a short code the caller built from a fixed vocabulary, never a\n * provider's response body. {@link safeProviderDetail} is the second line:\n * an `Authorization` header echoed back by a provider must not become a\n * Firestore document.\n */\nexport async function recordSendingDomainIssueFailure(options: {\n orgId: string\n domain: string\n detail: string\n}): Promise<void> {\n const domain = normalizeSendingDomain(options?.domain)\n if (!options?.orgId || !domain) return\n const ref = domainRef(options.orgId, domain)\n if (!(await ref.get()).exists) return\n await ref.set(\n {\n lastIssueError: safeProviderDetail(options.detail) || 'unknown',\n lastIssueAtMs: Date.now(),\n },\n { merge: true },\n )\n}\n\nexport interface SendingDomainView {\n record: SendingDomainRecord\n /** Exactly what the customer must publish. */\n records: SendingDnsRecord[]\n /** Their DMARC policy, read and never written. */\n dmarc: DmarcAssessment | null\n}\n\n/** One domain plus the records it needs, for a surface that shows both. */\nexport async function getSendingDomain(\n orgId: string,\n rawDomain: string,\n): Promise<SendingDomainView | null> {\n const domain = normalizeSendingDomain(rawDomain)\n if (!orgId || !domain) return null\n const record = readSendingDomainRecord(await domainRef(orgId, domain).get())\n if (!record) return null\n return { record, records: sendingDnsRecords(record), dmarc: null }\n}\n\nexport async function listSendingDomains(\n orgId: string,\n): Promise<SendingDomainRecord[]> {\n if (!orgId) return []\n const snapshot = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(SENDING_DOMAINS_COLLECTION)\n .get()\n return snapshot.docs.map(readSendingDomainRecord).filter(Boolean)\n}\n\n/**\n * Read the customer's DMARC policy.\n *\n * Advisory in both directions: it never blocks verification and it is never\n * written. A domain under `p=reject` with our DKIM unpublished hard-fails\n * every message, and a customer deserves to be told that before they wonder\n * why their campaign vanished.\n */\nexport async function readDmarcPolicy(\n rawDomain: string,\n): Promise<DmarcAssessment | null> {\n const domain = normalizeSendingDomain(rawDomain)\n if (!domain) return null\n const lookup = await lookupTxt(`_dmarc.${domain}`)\n // An unreachable lookup is not \"they have no policy\" — saying so would tell\n // a customer under p=reject that they have no protection.\n if (!lookup.answered) return null\n return assessDmarc(lookup.records)\n}\n\n/**\n * Start (or read) the hold that keeps a tracked domain's links alive.\n *\n * Stamped on FIRST sighting rather than computed from an orphan timestamp,\n * because there is no reliable one: a label reassignment leaves no record of\n * when it happened, and the reaper re-infers the orphan on every pass. The\n * stamp is the record of when the hold began, so a domain cannot be held\n * forever by a sweep that keeps starting the clock over.\n *\n * @returns the instant the domain may be released, or `null` when there is\n * nothing to stamp it on — a domain with no org record cannot be\n * held, and refusing to release it on the strength of a hold nobody\n * can see would strand a provider slot permanently.\n */\nexport async function holdTrackedSendingDomain(options: {\n orgId: string | null\n domain: string\n nowMs: number\n windowMs: number\n}): Promise<number | null> {\n const orgId = String(options?.orgId ?? '').trim()\n const domain = normalizeSendingDomain(options?.domain)\n if (!orgId || !domain || options.windowMs <= 0) return null\n\n const ref = domainRef(orgId, domain)\n const snapshot = await ref.get().catch(() => null)\n if (!snapshot?.exists) return null\n\n const held = Number(snapshot.get('trackingRetentionUntilMs')) || 0\n if (held > 0) return held\n\n const until = options.nowMs + options.windowMs\n await ref\n .set({ trackingRetentionUntilMs: until }, { merge: true })\n // A stamp we could not write is a hold we cannot prove later, so the\n // caller is told there is none rather than being asked to wait on a\n // deadline that will restart on the next pass.\n .catch(() => null)\n return until\n}\n\n/**\n * Whether this domain publishes a CAA policy that would REFUSE the tracking\n * host's certificate.\n *\n * The question decides whether a customer is shown a CAA record at all, and\n * asking it is the difference between guidance and a footgun. CAA restricts\n * which authorities may issue, and the lookup stops at the first name in the\n * tree publishing any record — so:\n *\n * - A domain publishing NOTHING needs nothing. Any authority may already\n * issue, and handing over a CAA record to paste would be the change that\n * STARTS restricting them, breaking whatever else renews on that name.\n * - A domain that publishes some, none of which name our authority, has to\n * add one ALONGSIDE what it has.\n * - A domain that already names our authority is done.\n *\n * Walks up from the tracking host exactly as a certificate authority does,\n * and stops where a real lookup stops: at the first name with any record.\n *\n * @returns `null` when DNS could not be reached, which is not \"they publish\n * none\" — telling a customer to add a CAA on the strength of an\n * unanswered lookup is how a working zone gets narrowed by mistake.\n */\nexport async function readTrackingCaaNeed(\n rawDomain: string,\n authority: string,\n): Promise<'not-needed' | 'must-add' | 'satisfied' | null> {\n const domain = normalizeSendingDomain(rawDomain)\n const ca = String(authority ?? '').trim().toLowerCase()\n if (!domain || !ca) return null\n\n /*\n * From the tracking host upward. Every label is asked because a CAA on a\n * closer name overrides a broader one — a customer who already scoped a\n * policy to `links.` must not be told to widen their root.\n */\n const labels = sendingTrackingHost(domain).split('.')\n for (let index = 0; index < labels.length - 1; index += 1) {\n const name = labels.slice(index).join('.')\n const lookup = await lookupCaa(name)\n if (!lookup.answered) return null\n if (!lookup.records.length) continue\n // The first name with any record is where issuance is decided.\n const issuers = lookup.records\n .filter((entry) => / issue \"/.test(entry))\n .map((entry) => entry.toLowerCase())\n return issuers.some((entry) => entry.includes(`\"${ca}\"`))\n ? 'satisfied'\n : 'must-add'\n }\n return 'not-needed'\n}\n\n/**\n * Read the live DNS for one record and say what it establishes. Writes\n * nothing.\n *\n * Split out so the two callers that need this answer ask the SAME question of\n * the SAME resolvers: {@link verifySendingDomain}, which acts on it\n * immediately, and the unattended re-check sweep, which counts conclusive\n * failures before it acts. A sweep that assessed the records its own way would\n * be a second opinion on \"are these published\", and the customer would meet\n * whichever one happened to run last.\n *\n * The three lookups run together because they are independent and the caller\n * is waiting on the slowest either way.\n */\nexport async function probeSendingRecords(\n record: SendingDomainRecord,\n): Promise<SendingVerification> {\n const domain = normalizeSendingDomain(record?.domain ?? '')\n const sendHost = `${SENDING_SUBDOMAIN}.${domain}`\n const dkimHost = `${record.dkimSelector}._domainkey.${domain}`\n const [spf, dkim, mx] = await Promise.all([\n lookupTxt(sendHost),\n lookupTxt(dkimHost),\n lookupMx(sendHost),\n ])\n\n return assessSendingRecords(record, {\n spfTxt: spf.records,\n dkimTxt: dkim.records,\n mx: mx.records,\n // All three, not any: a record we could not read is not a record that is\n // absent, and one unreadable lookup is enough to make the whole answer\n // evidence of nothing.\n conclusive: spf.answered && dkim.answered && mx.answered,\n })\n}\n\n/**\n * Check the live DNS and move the record to `verified` or `failed`.\n *\n * Never throws: a sweep across every org must not stop at the first bad zone.\n *\n * An INCONCLUSIVE result writes nothing but the check time. A resolver outage\n * must not un-verify a working domain — which would silently stop that\n * tenant's mail — and must not fail a customer who is midway through\n * publishing either. This is the `hold` arm the SSO drift sweep uses, and the\n * reason `assessSendingRecords` has three outcomes rather than two.\n *\n * Acts on ONE conclusive answer, and that is right for this caller: an admin\n * pressed Verify and is watching the result, so the check is attended and its\n * outcome is immediately visible and immediately retryable. The unattended\n * sweep over already-verified domains is the caller that cannot say that, and\n * `sending-domain-recheck.ts` is where the extra evidence it needs is\n * gathered.\n */\nexport async function verifySendingDomain(\n orgId: string,\n rawDomain: string,\n): Promise<{\n record: SendingDomainRecord | null\n missing: string[]\n inconclusive: boolean\n error: string | null\n}> {\n const domain = normalizeSendingDomain(rawDomain)\n if (!orgId || !domain) {\n return { record: null, missing: [], inconclusive: false, error: 'Invalid domain' }\n }\n\n const ref = domainRef(orgId, domain)\n const record = readSendingDomainRecord(await ref.get())\n if (!record) {\n return {\n record: null,\n missing: [],\n inconclusive: false,\n error: 'No claim on that domain — add it first.',\n }\n }\n\n const verdict = await probeSendingRecords(record)\n\n const now = Date.now()\n if (verdict.status === 'inconclusive') {\n await ref.set({ lastCheckedAtMs: now }, { merge: true })\n return { record, missing: [], inconclusive: true, error: null }\n }\n\n const verified = verdict.status === 'verified'\n await ref.set(\n {\n status: verified ? 'verified' : 'failed',\n lastCheckedAtMs: now,\n ...(verified\n ? {\n verifiedAtMs: now,\n lastMissing: firebaseAdmin.firestore.FieldValue.delete(),\n }\n : { lastMissing: verdict.missing }),\n },\n { merge: true },\n )\n\n return {\n record: readSendingDomainRecord(await ref.get()),\n missing: verdict.missing,\n inconclusive: false,\n error: null,\n }\n}\n\n/**\n * Drop a claim.\n *\n * The host selections pointing at it are NOT rewritten to the platform\n * identity. A site that was sending as its own domain and now has no verified\n * one must refuse, not quietly revert — silently moving a tenant's mail back\n * onto the shared domain is the exact fallback this feature exists to prevent,\n * and doing it during a delete would be no better than doing it during a send.\n */\nexport async function releaseSendingDomain(\n orgId: string,\n rawDomain: string,\n): Promise<void> {\n const domain = normalizeSendingDomain(rawDomain)\n if (!orgId || !domain) return\n await domainRef(orgId, domain)\n .delete()\n .catch(() => undefined)\n}\n\n/*==========================================\n The read on the send path\n==========================================*/\n\n/**\n * The identity one host sends on, ready to hand to `sendEmail`.\n *\n * Two document reads at most, and none at all for a host that has no\n * selection. The host document is passed in rather than re-fetched because\n * every caller already holds it.\n *\n * ## This function cannot return an `aglyn.com` address, and that is the point\n *\n * Every caller here is resolving mail FOR A SITE — that is what \"host\" in the\n * name means — so every verdict it produces is tenant mail by construction.\n * `audience: 'tenant'` is therefore passed unconditionally and is not a\n * parameter: a caller that could choose would eventually choose wrong, and the\n * wrong choice puts a merchant's list quality onto the domain the platform's\n * own invoices and password resets leave on.\n *\n * A site that has selected NOTHING does not reach `USAGE_EMAIL_FROM` either.\n * All of its mail goes on the shared pool member `hostSharedFrom` assigns it,\n * marketing included. What keeps the pool usable is measurement rather than\n * prohibition: a pooled campaign is graded against the stricter reputation\n * thresholds, so the site earning complaints is the one that stops.\n */\nexport async function resolveHostSendingIdentity(options: {\n orgId: string | null | undefined\n /** `hosts/{hostId}.sendingDomain`, the site's selection. */\n selectedDomain: string | null | undefined\n /** `hosts/{hostId}.sendingLocalPart`, defaulted when unset. */\n selectedLocalPart?: string | null\n platformFrom?: string | null\n /**\n * The site, so an unselected host can be assigned a pool member.\n *\n * Optional because two of the three callers resolve an identity for a host\n * they are already holding and one — the console's identity view — is asking\n * about a specific site by id. A caller that omits it gets no shared\n * identity, which is the honest answer: the pool assignment is per site, and\n * \"some pool member\" is not a thing to send a receipt from.\n */\n hostId?: string | null\n /**\n * A pool member this host is pinned to, overriding the hash.\n *\n * `hosts/{hostId}.sendingPoolMember`. The QUARANTINE lever: a site whose\n * transactional mail is generating complaints can be moved onto a member set\n * aside for it, without disturbing any of the other sites that hash to the\n * member it was on. Ignored unless it names a real member of the current\n * pool, so a stale or hand-edited value degrades to the ordinary assignment\n * rather than to an address nothing signs for.\n */\n poolMember?: string | null\n /** See `SendingIdentityPurpose`. Defaults to transactional. */\n purpose?: SendingIdentityPurpose\n}): Promise<SendingIdentityVerdict> {\n const platformFrom =\n options?.platformFrom ?? process.env.USAGE_EMAIL_FROM ?? null\n const domain = normalizeSendingDomain(options?.selectedDomain ?? '')\n const purpose = options?.purpose\n const sharedFrom = hostSharedFrom(options?.hostId, options?.poolMember)\n\n if (!domain || !options?.orgId) {\n return resolveSendingIdentity({\n selection: null,\n platformFrom,\n sharedFrom,\n purpose,\n audience: 'tenant',\n })\n }\n\n const record = readSendingDomainRecord(await domainRef(options.orgId, domain).get())\n\n /*\n * Whose domain this is, decided from the NAME rather than from the record.\n *\n * The record is what a released domain no longer has, and a site pointed at\n * a subdomain of our own apex is still pointed at a subdomain of our own\n * apex whether or not one exists for it. Deriving this from the name keeps\n * the two possible failures apart: a missing record for OUR name is our\n * provisioning that did not finish, a missing record for THEIRS is a domain\n * they asked to send as and nothing has verified.\n */\n const platformIssued = isPlatformSendingDomain(domain)\n\n /*\n * A selection naming a CUSTOMER'S domain with no record refuses rather than\n * falling back. The record can be gone because it was released, or because\n * the selection was written against a different org — both mean the site is\n * configured to send as a domain nothing has verified, and neither is a\n * reason to send as somebody else.\n *\n * `platformIssued` rides on the selection either way, and the resolver reads\n * it only on the unverified branch: a platform subdomain that has not\n * finished provisioning drops to the pool for transactional mail instead,\n * because nothing about it is a merchant instruction to contradict.\n */\n const selection: SendingDomainSelection = record\n ? {\n domain: record.domain,\n status: record.status,\n localPart: normalizeLocalPart(options.selectedLocalPart ?? '') || 'hello',\n missing: record.lastMissing ?? [],\n platformIssued,\n }\n : { domain, status: 'failed', localPart: '', missing: [], platformIssued }\n\n /*\n * `sharedFrom` is passed even here, where a selection exists and will decide\n * the outcome. It is inert by construction — the selection branch of\n * `resolveSendingIdentity` never reads it — and passing it unconditionally\n * keeps the call shape identical between the two arms, so a future edit\n * cannot produce a path that had a pool available and did not offer it.\n *\n * It must NOT become a fallback for an unverified selection, and it is the\n * resolver's structure rather than this call site that guarantees that.\n */\n return resolveSendingIdentity({\n selection,\n platformFrom,\n sharedFrom,\n purpose,\n audience: 'tenant',\n })\n}\n\n/**\n * The pool address for one host: the pinned member if it names a real one, the\n * hash assignment otherwise.\n *\n * The override is validated against the LIVE pool rather than trusted, because\n * a stale value is the expected case — an operator shrinks the pool, or a\n * quarantine was lifted by deleting the member rather than the field — and an\n * address on a domain that no longer exists is a send that fails at the\n * provider instead of one that quietly goes back to normal.\n */\nfunction hostSharedFrom(\n hostId: string | null | undefined,\n poolMember: string | null | undefined,\n): string {\n const id = String(hostId ?? '').trim()\n if (!id) return ''\n\n const pinned = normalizeSendingDomain(String(poolMember ?? ''))\n if (pinned && isSharedSendingDomain(pinned)) {\n const shared = sharedTenantSendingFrom(id)\n const at = shared.lastIndexOf('@')\n return at > 0 ? `${shared.slice(0, at)}@${pinned}` : ''\n }\n\n return sharedTenantSendingFrom(id)\n}\n\n/**\n * The identity one site sends on, from a `hostId` alone.\n *\n * The door every tenant sender uses. {@link resolveHostSendingIdentity} needs\n * the org id and the host's two selection fields, and a survey of the tenant\n * send sites found that all of them hold a `hostId` while only three hold an\n * org id and half never read the host document at all. Asking nineteen call\n * sites to each assemble the same three values is the shape that produces a\n * twentieth which does not — and the cost of forgetting here is a message\n * leaving on the platform's own domain.\n *\n * ## The cache is per-call-graph, not per-process\n *\n * Passed a `cache`, repeated resolutions for one host cost one pair of reads.\n * A sweep that mails two hundred abandoned carts across a dozen sites, or a\n * webhook that sends a receipt and a seller notice for the same order, holds\n * one map for the run and pays for each site once.\n *\n * Deliberately NOT a module-level cache. Verification status is exactly the\n * thing that changes underneath a long-lived process — the re-check sweep\n * un-verifies a domain whose records have gone — and a stale entry would keep\n * a site sending on a domain that no longer authenticates. A caller that\n * declares a cache has also declared how long it may be trusted.\n */\nexport async function hostSendingIdentity(\n hostId: string | null | undefined,\n cache?: Map<string, SendingIdentityVerdict>,\n): Promise<SendingIdentityVerdict> {\n const id = String(hostId ?? '').trim()\n if (!id) {\n /*\n * No host is not \"the platform is speaking\", and it is not \"any pool\n * member will do\" either. It is a caller that does not know which site it\n * is sending for, and the honest answer to that is a refusal.\n *\n * No `sharedFrom` is passed, which is what makes that structural rather\n * than a rule: the pool is assigned FROM the host id, so a caller without\n * one has nothing to be assigned.\n */\n return resolveSendingIdentity({ selection: null, audience: 'tenant' })\n }\n\n const hit = cache?.get(id)\n if (hit) return hit\n\n const snapshot = await firestore()\n .collection('hosts')\n .doc(id)\n .get()\n .catch(() => null)\n const owner = await getOrgForHost(id).catch(() => null)\n\n const verdict = await resolveHostSendingIdentity({\n orgId: owner?.orgId ?? null,\n selectedDomain: snapshot?.get('sendingDomain') ?? '',\n selectedLocalPart: snapshot?.get('sendingLocalPart') ?? '',\n hostId: id,\n poolMember: snapshot?.get('sendingPoolMember') ?? '',\n })\n\n cache?.set(id, verdict)\n return verdict\n}\n\n/** The record keys a surface highlights as outstanding. */\nexport function outstandingSendingRecords(\n record: SendingDomainRecord,\n): SendingDnsRecord[] {\n const missing = new Set(record?.lastMissing ?? [])\n if (!missing.size) return []\n return sendingDnsRecords(record).filter((entry) =>\n missing.has(sendingRecordKey(entry)),\n )\n}\n"],"names":["assessDmarc","assessSendingRecords","isPlatformSendingDomain","isSharedSendingDomain","normalizeLocalPart","normalizeSendingDomain","resolveSendingIdentity","safeProviderDetail","SENDING_SUBDOMAIN","sendingDnsRecords","sendingTrackingHost","sendingDomainRequiredRecords","sendingRecordKey","sharedTenantSendingFrom","validateSendingDomain","firebaseAdmin","lookupCaa","lookupMx","lookupTxt","getOrgForHost","firestore","app","SENDING_DOMAINS_COLLECTION","domainRef","orgId","domain","collection","doc","sendingDkimSelector","safe","String","toLowerCase","replace","slice","readSendingDomainRecord","snapshot","data","exists","id","status","dkimSelector","dkimPublicKey","returnPathHost","providerDomainId","trackingTarget","createdAtMs","Number","verifiedAtMs","lastCheckedAtMs","lastIssueError","lastIssueAtMs","lastMissing","Array","isArray","requestSendingDomain","options","error","record","ref","existing","get","Date","now","set","merge","recordIssuedSendingDomain","key","trim","held","selector","issued","some","entry","purpose","FieldValue","delete","recordSendingDomainIssueFailure","detail","getSendingDomain","rawDomain","records","dmarc","listSendingDomains","docs","map","filter","Boolean","readDmarcPolicy","lookup","answered","holdTrackedSendingDomain","windowMs","catch","until","nowMs","trackingRetentionUntilMs","readTrackingCaaNeed","authority","ca","labels","split","index","length","name","join","issuers","test","includes","probeSendingRecords","sendHost","dkimHost","spf","dkim","mx","Promise","all","spfTxt","dkimTxt","conclusive","verifySendingDomain","missing","inconclusive","verdict","verified","releaseSendingDomain","undefined","resolveHostSendingIdentity","platformFrom","process","env","USAGE_EMAIL_FROM","selectedDomain","sharedFrom","hostSharedFrom","hostId","poolMember","selection","audience","platformIssued","localPart","selectedLocalPart","pinned","shared","at","lastIndexOf","hostSendingIdentity","cache","hit","owner","outstandingSendingRecords","Set","size","has"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkDC,GAED,SACEA,WAAW,EACXC,oBAAoB,EACpBC,uBAAuB,EACvBC,qBAAqB,EACrBC,kBAAkB,EAClBC,sBAAsB,EACtBC,sBAAsB,EACtBC,kBAAkB,EAClBC,iBAAiB,EACjBC,iBAAiB,EACjBC,mBAAmB,EACnBC,4BAA4B,EAC5BC,gBAAgB,EAChBC,uBAAuB,EACvBC,qBAAqB,QAQhB,2BAA0B;AACjC,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,SAAS,EAAEC,QAAQ,EAAEC,SAAS,QAAQ,iBAAa;AAC5D,SAASC,aAAa,QAAQ,qBAAiB;AAE/C,MAAMC,YAAY,IAAML,cAAcM,GAAG,GAAGD,SAAS;AAErD,wCAAwC,GACxC,OAAO,MAAME,6BAA6B,iBAAgB;AAE1D,MAAMC,YAAY,CAACC,OAAeC,SAChCL,YACGM,UAAU,CAAC,QACXC,GAAG,CAACH,OACJE,UAAU,CAACJ,4BACXK,GAAG,CAACF;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D;IAEAsF,yBAAAA,MAAOnF,GAAG,CAACzB,IAAIoF;IACf,OAAOA;AACT;AAEA,yDAAyD,GACzD,OAAO,SAAS2B,0BACd5F,MAA2B;;IAE3B,MAAM+D,UAAU,IAAI8B,YAAI7F,0BAAAA,OAAQN,WAAW,mBAAI,EAAE;IACjD,IAAI,CAACqE,QAAQ+B,IAAI,EAAE,OAAO,EAAE;IAC5B,OAAO9I,kBAAkBgD,QAAQ4B,MAAM,CAAC,CAACb,QACvCgD,QAAQgC,GAAG,CAAC5I,iBAAiB4D;AAEjC"}
@@ -0,0 +1,98 @@
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
+ import { type TrackingHostRecord, type TrackingHostResult } from '@aglyn/shared-util-email';
18
+ import { type DomainProvider } from './domain-provider';
19
+ /**
20
+ * CLICK-TRACKING HOSTS THIS DEPLOYMENT SERVES — durable half.
21
+ *
22
+ * The record, the driver calls and the probe. The decisions live in
23
+ * `@aglyn/shared-util-email`'s `tracking-host.ts`; this module is the I/O
24
+ * around them, the same split `sending-domains.ts` makes.
25
+ *
26
+ * ## Per org, per sending domain
27
+ *
28
+ * At `orgs/{orgId}/trackingHosts/{domain}`, beside `sendingDomains` and for
29
+ * the same reason: the host is a fact about a domain the organization sends
30
+ * as. The org's erasure and its personal-data export reach it through the
31
+ * org's subtree like every other document under it. It is Admin SDK only —
32
+ * `status` decides where a recipient's click goes, and no client may write
33
+ * that.
34
+ *
35
+ * ## Why no claim across organizations
36
+ *
37
+ * The host is always `links.<the sending domain>`, and a caller only sets one
38
+ * up for a domain it already sends as (Sequences asks for its own mailboxes'
39
+ * domains). Two organizations sending as one domain both run on it
40
+ * legitimately, and every link id resolves on its own document whichever
41
+ * host carried it.
42
+ *
43
+ * ## The network never throws out of here
44
+ *
45
+ * The driver call and the probe are network calls a member is waiting on;
46
+ * each failure is caught and becomes a stored detail the card can print. A
47
+ * Firestore failure still propagates, as it does from every store.
48
+ */
49
+ /** Subcollection under the owning org. */
50
+ export declare const TRACKING_HOSTS_COLLECTION = "trackingHosts";
51
+ type Firestore = FirebaseFirestore.Firestore;
52
+ /** One stored document as a record, or `null` for one that is not there. */
53
+ export declare function readTrackingHostRecord(snapshot: FirebaseFirestore.DocumentSnapshot | null | undefined): TrackingHostRecord | null;
54
+ export declare function readTrackingHost(firestore: Firestore, orgId: string, domain: string): Promise<TrackingHostRecord | null>;
55
+ export declare function listTrackingHosts(firestore: Firestore, orgId: string): Promise<TrackingHostRecord[]>;
56
+ interface TrackingHostDeps {
57
+ firestore: Firestore;
58
+ orgId: string;
59
+ domain: string;
60
+ nowMs: number;
61
+ /** The deployment's domain driver; {@link domainProvider} by default. */
62
+ provider?: DomainProvider;
63
+ }
64
+ /**
65
+ * Set up `links.<domain>`: attach it through the domain driver and record the
66
+ * DNS to publish. Idempotent — attaching a name already attached is success,
67
+ * and a verified record is left verified.
68
+ */
69
+ export declare function setUpTrackingHost(input: TrackingHostDeps): Promise<TrackingHostResult>;
70
+ /** The probe's fetch, injectable for specs. */
71
+ export type TrackingHostFetch = (url: string, init: RequestInit) => Promise<Response>;
72
+ /**
73
+ * Ask the host whether it is live: the driver's status first (a name still
74
+ * waiting on DNS or a certificate is not worth a request), then an HTTPS
75
+ * request to the probe path, which only this app answers.
76
+ *
77
+ * A probe that cannot connect is `failed` with `unreachable` — except on a
78
+ * record already verified, which keeps its status: one lost request must not
79
+ * send every link back to the app address mid-sequence.
80
+ */
81
+ export declare function verifyTrackingHost(input: TrackingHostDeps & {
82
+ fetch?: TrackingHostFetch;
83
+ }): Promise<TrackingHostResult>;
84
+ /**
85
+ * Stop serving `links.<domain>`: detach it through the driver and delete the
86
+ * record. Every link already sent on it stops working on the host (the same
87
+ * ids keep answering on the app's own address), which the caller says before
88
+ * asking.
89
+ */
90
+ export declare function removeTrackingHost(input: TrackingHostDeps): Promise<TrackingHostResult>;
91
+ /**
92
+ * The origin tracked links in mail sent as `senderAddress` should use —
93
+ * `https://links.<its domain>` once that host is verified — or `null` for
94
+ * "the app's own address". One document read; never a network call, because
95
+ * this is on the send path.
96
+ */
97
+ export declare function resolveTrackingLinkOrigin(firestore: Firestore, orgId: string, senderAddress: string): Promise<string | null>;
98
+ export {};
@@ -0,0 +1,264 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { readTrackingHostProbe, sendingTrackingHost, TRACKING_HOST_DETAIL, TRACKING_HOST_PROBE_PATH, trackingHostLinkOrigin, trackingHostTarget, validateTrackingHostDomain } from "@aglyn/shared-util-email";
18
+ import { domainProvider, domainStateServes, DOMAIN_PROVIDER_TIMEOUT_MS } from "./domain-provider.js";
19
+ import { SENDING_DOMAINS_COLLECTION } from "./sending-domains.js";
20
+ /**
21
+ * CLICK-TRACKING HOSTS THIS DEPLOYMENT SERVES — durable half.
22
+ *
23
+ * The record, the driver calls and the probe. The decisions live in
24
+ * `@aglyn/shared-util-email`'s `tracking-host.ts`; this module is the I/O
25
+ * around them, the same split `sending-domains.ts` makes.
26
+ *
27
+ * ## Per org, per sending domain
28
+ *
29
+ * At `orgs/{orgId}/trackingHosts/{domain}`, beside `sendingDomains` and for
30
+ * the same reason: the host is a fact about a domain the organization sends
31
+ * as. The org's erasure and its personal-data export reach it through the
32
+ * org's subtree like every other document under it. It is Admin SDK only —
33
+ * `status` decides where a recipient's click goes, and no client may write
34
+ * that.
35
+ *
36
+ * ## Why no claim across organizations
37
+ *
38
+ * The host is always `links.<the sending domain>`, and a caller only sets one
39
+ * up for a domain it already sends as (Sequences asks for its own mailboxes'
40
+ * domains). Two organizations sending as one domain both run on it
41
+ * legitimately, and every link id resolves on its own document whichever
42
+ * host carried it.
43
+ *
44
+ * ## The network never throws out of here
45
+ *
46
+ * The driver call and the probe are network calls a member is waiting on;
47
+ * each failure is caught and becomes a stored detail the card can print. A
48
+ * Firestore failure still propagates, as it does from every store.
49
+ */ /** Subcollection under the owning org. */ export const TRACKING_HOSTS_COLLECTION = 'trackingHosts';
50
+ const hostRef = (firestore, orgId, domain)=>firestore.collection('orgs').doc(orgId).collection(TRACKING_HOSTS_COLLECTION).doc(domain);
51
+ /** One stored document as a record, or `null` for one that is not there. */ export function readTrackingHostRecord(snapshot) {
52
+ var _snapshot_data, _data_domain, _data_host, _data_status, _data_target, _data_provider, _data_lastDetail;
53
+ if (!(snapshot == null ? void 0 : snapshot.exists)) return null;
54
+ const data = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {};
55
+ const domain = String((_data_domain = data['domain']) != null ? _data_domain : snapshot.id);
56
+ return {
57
+ domain,
58
+ host: String((_data_host = data['host']) != null ? _data_host : sendingTrackingHost(domain)),
59
+ status: (_data_status = data['status']) != null ? _data_status : 'requested',
60
+ target: (_data_target = data['target']) != null ? _data_target : null,
61
+ provider: (_data_provider = data['provider']) != null ? _data_provider : null,
62
+ verification: Array.isArray(data['verification']) ? data['verification'] : null,
63
+ lastDetail: (_data_lastDetail = data['lastDetail']) != null ? _data_lastDetail : null,
64
+ createdAtMs: Number(data['createdAtMs']) || null,
65
+ verifiedAtMs: Number(data['verifiedAtMs']) || null,
66
+ lastCheckedAtMs: Number(data['lastCheckedAtMs']) || null
67
+ };
68
+ }
69
+ export async function readTrackingHost(firestore, orgId, domain) {
70
+ const checked = validateTrackingHostDomain(domain);
71
+ if (!checked.domain) return null;
72
+ return readTrackingHostRecord(await hostRef(firestore, orgId, checked.domain).get());
73
+ }
74
+ export async function listTrackingHosts(firestore, orgId) {
75
+ const snapshot = await firestore.collection('orgs').doc(orgId).collection(TRACKING_HOSTS_COLLECTION).get();
76
+ return snapshot.docs.map((doc)=>readTrackingHostRecord(doc)).filter((record)=>Boolean(record)).sort((a, b)=>a.domain.localeCompare(b.domain));
77
+ }
78
+ /**
79
+ * Whether campaign mail already owns `links.<domain>`: the org's sending
80
+ * domain for it was issued a tracking target by the mail provider, whose
81
+ * CNAME the customer publishes on the very same name.
82
+ */ async function providerTracked(firestore, orgId, domain) {
83
+ var _ref;
84
+ var _snapshot_data;
85
+ const snapshot = await firestore.collection('orgs').doc(orgId).collection(SENDING_DOMAINS_COLLECTION).doc(domain).get();
86
+ return Boolean(snapshot.exists && String((_ref = (_snapshot_data = snapshot.data()) == null ? void 0 : _snapshot_data['trackingTarget']) != null ? _ref : '').trim());
87
+ }
88
+ /**
89
+ * Set up `links.<domain>`: attach it through the domain driver and record the
90
+ * DNS to publish. Idempotent — attaching a name already attached is success,
91
+ * and a verified record is left verified.
92
+ */ export async function setUpTrackingHost(input) {
93
+ var _input_provider, _ref, _ref1, _ref2, _ref3, _ref4;
94
+ const checked = validateTrackingHostDomain(input.domain);
95
+ if (!checked.domain) return {
96
+ record: null,
97
+ error: checked.error,
98
+ status: 400
99
+ };
100
+ const domain = checked.domain;
101
+ const host = sendingTrackingHost(domain);
102
+ const ref = hostRef(input.firestore, input.orgId, domain);
103
+ if (await providerTracked(input.firestore, input.orgId, domain)) {
104
+ return {
105
+ record: null,
106
+ error: TRACKING_HOST_DETAIL['provider-tracked'],
107
+ status: 409
108
+ };
109
+ }
110
+ const provider = (_input_provider = input.provider) != null ? _input_provider : domainProvider();
111
+ const existing = readTrackingHostRecord(await ref.get());
112
+ const attached = await provider.attach('console', host).catch(()=>({
113
+ outcome: 'failed',
114
+ domain: host
115
+ }));
116
+ const failed = attached.outcome === 'failed';
117
+ const record = {
118
+ domain,
119
+ host,
120
+ status: (existing == null ? void 0 : existing.status) === 'verified' && !failed ? 'verified' : failed ? 'requested' : 'records-issued',
121
+ target: trackingHostTarget(provider.id),
122
+ provider: provider.id,
123
+ verification: (_ref = existing == null ? void 0 : existing.verification) != null ? _ref : null,
124
+ lastDetail: failed ? 'attach-failed' : (existing == null ? void 0 : existing.status) === 'verified' ? null : (_ref1 = existing == null ? void 0 : existing.lastDetail) != null ? _ref1 : null,
125
+ createdAtMs: (_ref2 = existing == null ? void 0 : existing.createdAtMs) != null ? _ref2 : input.nowMs,
126
+ verifiedAtMs: (_ref3 = existing == null ? void 0 : existing.verifiedAtMs) != null ? _ref3 : null,
127
+ lastCheckedAtMs: (_ref4 = existing == null ? void 0 : existing.lastCheckedAtMs) != null ? _ref4 : null
128
+ };
129
+ await ref.set(record, {
130
+ merge: true
131
+ });
132
+ return {
133
+ record,
134
+ error: null,
135
+ status: 200
136
+ };
137
+ }
138
+ /**
139
+ * Ask the host whether it is live: the driver's status first (a name still
140
+ * waiting on DNS or a certificate is not worth a request), then an HTTPS
141
+ * request to the probe path, which only this app answers.
142
+ *
143
+ * A probe that cannot connect is `failed` with `unreachable` — except on a
144
+ * record already verified, which keeps its status: one lost request must not
145
+ * send every link back to the app address mid-sequence.
146
+ */ export async function verifyTrackingHost(input) {
147
+ var _input_provider;
148
+ var _state_verification;
149
+ const checked = validateTrackingHostDomain(input.domain);
150
+ if (!checked.domain) return {
151
+ record: null,
152
+ error: checked.error,
153
+ status: 400
154
+ };
155
+ const ref = hostRef(input.firestore, input.orgId, checked.domain);
156
+ const existing = readTrackingHostRecord(await ref.get());
157
+ if (!existing) {
158
+ return {
159
+ record: null,
160
+ error: 'Set up the link domain before checking it.',
161
+ status: 404
162
+ };
163
+ }
164
+ const provider = (_input_provider = input.provider) != null ? _input_provider : domainProvider();
165
+ const host = existing.host;
166
+ const state = await provider.status('console', host).catch(()=>null);
167
+ let status;
168
+ let detail = null;
169
+ const verification = (state == null ? void 0 : (_state_verification = state.verification) == null ? void 0 : _state_verification.length) ? state.verification : null;
170
+ if (state && !domainStateServes(state.state)) {
171
+ detail = state.state === 'ownership-pending' || state.state === 'certificate-pending' || state.state === 'dns-misconfigured' ? state.state : 'dns-misconfigured';
172
+ status = existing.status === 'verified' ? 'verified' : state.state === 'dns-misconfigured' ? 'failed' : 'records-issued';
173
+ } else {
174
+ var _input_fetch;
175
+ const answer = await probe(host, (_input_fetch = input.fetch) != null ? _input_fetch : fetch);
176
+ if (answer === 'ok') {
177
+ status = 'verified';
178
+ } else {
179
+ detail = answer;
180
+ status = existing.status === 'verified' && answer === 'unreachable' ? 'verified' : 'failed';
181
+ }
182
+ }
183
+ const record = _extends({}, existing, {
184
+ status,
185
+ verification,
186
+ lastDetail: detail,
187
+ lastCheckedAtMs: input.nowMs,
188
+ verifiedAtMs: status === 'verified' ? existing.status === 'verified' ? existing.verifiedAtMs : input.nowMs : null
189
+ });
190
+ await ref.set(record, {
191
+ merge: true
192
+ });
193
+ return {
194
+ record,
195
+ error: null,
196
+ status: 200
197
+ };
198
+ }
199
+ async function probe(host, fetchImpl) {
200
+ let response;
201
+ try {
202
+ response = await fetchImpl(`https://${host}${TRACKING_HOST_PROBE_PATH}`, {
203
+ method: 'GET',
204
+ redirect: 'manual',
205
+ headers: {
206
+ accept: 'application/json'
207
+ },
208
+ signal: deadline()
209
+ });
210
+ } catch (unused) {
211
+ return 'unreachable';
212
+ }
213
+ if (!response.ok) return 'not-this-app';
214
+ const body = await response.json().catch(()=>null);
215
+ return readTrackingHostProbe(body, host) ? 'ok' : 'not-this-app';
216
+ }
217
+ function deadline() {
218
+ try {
219
+ return AbortSignal.timeout(DOMAIN_PROVIDER_TIMEOUT_MS);
220
+ } catch (unused) {
221
+ return undefined;
222
+ }
223
+ }
224
+ /**
225
+ * Stop serving `links.<domain>`: detach it through the driver and delete the
226
+ * record. Every link already sent on it stops working on the host (the same
227
+ * ids keep answering on the app's own address), which the caller says before
228
+ * asking.
229
+ */ export async function removeTrackingHost(input) {
230
+ var _input_provider;
231
+ const checked = validateTrackingHostDomain(input.domain);
232
+ if (!checked.domain) return {
233
+ record: null,
234
+ error: checked.error,
235
+ status: 400
236
+ };
237
+ const ref = hostRef(input.firestore, input.orgId, checked.domain);
238
+ const existing = readTrackingHostRecord(await ref.get());
239
+ if (!existing) return {
240
+ record: null,
241
+ error: null,
242
+ status: 200
243
+ };
244
+ const provider = (_input_provider = input.provider) != null ? _input_provider : domainProvider();
245
+ await provider.detach('console', existing.host).catch(()=>null);
246
+ await ref.delete();
247
+ return {
248
+ record: null,
249
+ error: null,
250
+ status: 200
251
+ };
252
+ }
253
+ /**
254
+ * The origin tracked links in mail sent as `senderAddress` should use —
255
+ * `https://links.<its domain>` once that host is verified — or `null` for
256
+ * "the app's own address". One document read; never a network call, because
257
+ * this is on the send path.
258
+ */ export async function resolveTrackingLinkOrigin(firestore, orgId, senderAddress) {
259
+ const checked = validateTrackingHostDomain(senderAddress);
260
+ if (!checked.domain) return null;
261
+ return trackingHostLinkOrigin(readTrackingHostRecord(await hostRef(firestore, orgId, checked.domain).get()));
262
+ }
263
+
264
+ //# sourceMappingURL=tracking-hosts.js.map