@aglyn/tenant-data-admin 1.8.0 → 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/server/api-http.js +2 -1
- package/src/lib/server/api-http.js.map +1 -1
- package/src/lib/server/billing-addons.d.ts +19 -47
- package/src/lib/server/billing-addons.js +41 -85
- package/src/lib/server/billing-addons.js.map +1 -1
- package/src/lib/server/bundle-links.d.ts +3 -5
- package/src/lib/server/bundle-links.js +4 -5
- package/src/lib/server/bundle-links.js.map +1 -1
- package/src/lib/server/email-metering.d.ts +12 -4
- package/src/lib/server/email-metering.js +12 -4
- package/src/lib/server/email-metering.js.map +1 -1
- package/src/lib/server/email-transactional-ceiling.d.ts +122 -0
- package/src/lib/server/email-transactional-ceiling.js +244 -0
- package/src/lib/server/email-transactional-ceiling.js.map +1 -0
- package/src/lib/server/org-billing.d.ts +2 -4
- package/src/lib/server/org-billing.js +0 -5
- package/src/lib/server/org-billing.js.map +1 -1
- package/src/lib/server/sending-domains.d.ts +1 -0
- package/src/lib/server/sending-domains.js +13 -1
- package/src/lib/server/sending-domains.js.map +1 -1
- package/src/lib/server/upgrade-proposal.d.ts +3 -2
- package/src/lib/server/upgrade-proposal.js +3 -0
- package/src/lib/server/upgrade-proposal.js.map +1 -1
- package/src/lib/server/upsert-contact.js +10 -4
- package/src/lib/server/upsert-contact.js.map +1 -1
- package/src/tenancy.d.ts +1 -0
- package/src/tenancy.js +5 -0
- package/src/tenancy.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 headerSafeText,\n isPlatformSendingDomain,\n isSharedSendingDomain,\n normalizeLocalPart,\n normalizeSendingDomain,\n resolveSendingIdentity,\n safeProviderDetail,\n SENDING_FROM_NAME_MAX,\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 {\n lockdownMode,\n resolveBrandingProfile,\n resolveHostToken,\n} from '@aglyn/aglyn/server'\nimport firebaseAdmin from './firebase-admin'\nimport { lookupCaa, lookupMx, lookupTxt } from './dns-probe'\nimport { getOrgForHost } from './organizations'\nimport { getSiteLockdown } from './tenant-write-lockdown'\n// Also INSTALLS the outbound phishing screen's review store on `sendEmail`\n// (AGL-3356): every sender whose identity comes from `hostSendingIdentity`\n// has therefore installed the gate the workspace stamped below is read by.\nimport { sendingWorkspaceFor } from './outbound-send-review'\nimport { flagLookalikeDomain } from './hosted-page-review'\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 // A domain that wears a brand (`paypa1.com`) goes to staff in the abuse\n // queue the moment it is claimed — flagged, not refused (AGL-3362). Mail\n // from it is held at the send seam whatever staff decide. Never throws.\n await flagLookalikeDomain({ kind: 'sending', hostId: null, orgId: options.orgId, domain })\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 // Again on verification, the moment it can actually send (AGL-3362): a\n // claim added before this check existed is caught here. One row per\n // domain, so this counts rather than re-alerts.\n if (verified) {\n await flagLookalikeDomain({ kind: 'sending', hostId: null, orgId, domain })\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 /*\n * A SUSPENDED SITE SENDS NOTHING (AGL-3356).\n *\n * This is the door every tenant sender but the campaign core uses, so it\n * is where one check covers them all — workflow and automation steps, the\n * CRM's one-off mail, inbox replies, member posts, receipts, reminders.\n * Refusing here rather than at each caller is the same argument this\n * function's own docblock makes about identities: nineteen call sites\n * asked to remember produce a twentieth that does not, and the incident\n * behind this was exactly that — a locked workspace whose workflow could\n * still mail for it.\n *\n * FULL locks only. A read-only lock is a maintenance window whose point\n * is that the site keeps serving and earning, and a receipt for an order\n * taken before it began must still arrive. Staff suspensions for abuse,\n * fraud and billing are full locks, which is the case this closes.\n *\n * The documents read above are handed to the verdict, so the check costs\n * the TTL-cached platform read and nothing else. It inherits the\n * verdict's fail-open posture and its takedown ratchet.\n */\n const lock = await getSiteLockdown(id, Date.now(), {\n org: (owner?.org as Record<string, unknown> | undefined) ?? null,\n host: snapshot?.exists\n ? ((snapshot.data() as Record<string, unknown>) ?? null)\n : null,\n })\n if (lock && lockdownMode(lock) === 'full') {\n const suspended = suspendedSendingIdentity(lock.scope)\n cache?.set(id, suspended)\n return suspended\n }\n\n const resolved = 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 /*\n * THE WORKSPACE, STAMPED FOR THE PHISHING SCREEN (AGL-3356).\n *\n * `sendEmail` screens every tenant message whose identity carries this,\n * so stamping it here is what puts CRM mail, inbox replies, newsletters,\n * member posts, sweeps, flow steps and receipts behind one screen without\n * any of them passing anything. Built from the two documents read above:\n * the screen costs no read of its own.\n */\n const verdict: SendingIdentityVerdict = {\n ...resolved,\n workspace: sendingWorkspaceFor({\n hostId: id,\n orgId: owner?.orgId ?? null,\n org: (owner?.org as Record<string, unknown> | undefined) ?? null,\n host: snapshot?.exists\n ? ((snapshot.data() as Record<string, unknown>) ?? null)\n : null,\n }),\n /*\n * THE NAME THE SITE SENDS UNDER (AGL-3442), from the same two documents,\n * so it costs no read. `sendEmail` puts it where a sender passed the\n * org's branding default; the address above is untouched.\n */\n ...siteSenderNames({\n org: (owner?.org as Record<string, unknown> | undefined) ?? null,\n host: snapshot?.exists\n ? ((snapshot.data() as Record<string, unknown>) ?? null)\n : null,\n }),\n }\n\n cache?.set(id, verdict)\n return verdict\n}\n\n/**\n * The display name one site's mail leaves under, and the org default it\n * replaces (AGL-3442).\n *\n * The site's business name — what its emails render as\n * `{{host.businessName}}`, which is its SEO entity name or else its display\n * name — and the org's branding default when the site has neither, which is\n * \"Aglyn\" for an org without white-label. The name sent is flattened as every\n * sender name is, because it reaches a `From:` header and the site's owner\n * typed it. The default is kept exactly as `resolveBrandingProfile` returns\n * it, because `sendEmail` recognizes it by comparing it with what a sender\n * passed, and senders pass that value unchanged.\n */\nexport function siteSenderNames(input: {\n org: Record<string, unknown> | null\n host: Record<string, unknown> | null\n}): Pick<SendingIdentityVerdict, 'fromName' | 'brandFromName'> {\n const brandFromName = String(\n resolveBrandingProfile(input.org as never).fromName ?? '',\n ).trim()\n const siteName = headerSafeText(\n resolveHostToken('businessName', input.host as never),\n SENDING_FROM_NAME_MAX,\n )\n return {\n fromName: siteName || headerSafeText(brandFromName, SENDING_FROM_NAME_MAX),\n brandFromName,\n }\n}\n\n/**\n * The verdict a suspended site's mail gets: a refusal, whatever identity the\n * site would otherwise have sent on. `sendEmail` reads it and answers\n * `suspended` without calling the provider.\n */\nexport function suspendedSendingIdentity(\n scope: string | null | undefined,\n): SendingIdentityVerdict {\n const what =\n scope === 'platform'\n ? 'Sending is paused platform-wide'\n : scope === 'org'\n ? 'This workspace is suspended'\n : 'This site is suspended'\n const message = `${what}, so no email is sent on its behalf until the suspension is lifted.`\n return {\n from: null,\n source: null,\n domain: null,\n summary: message,\n refusal: {\n code: 'workspace-suspended',\n domain: null,\n message,\n missing: [],\n },\n }\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","headerSafeText","isPlatformSendingDomain","isSharedSendingDomain","normalizeLocalPart","normalizeSendingDomain","resolveSendingIdentity","safeProviderDetail","SENDING_FROM_NAME_MAX","SENDING_SUBDOMAIN","sendingDnsRecords","sendingTrackingHost","sendingDomainRequiredRecords","sendingRecordKey","sharedTenantSendingFrom","validateSendingDomain","lockdownMode","resolveBrandingProfile","resolveHostToken","firebaseAdmin","lookupCaa","lookupMx","lookupTxt","getOrgForHost","getSiteLockdown","sendingWorkspaceFor","flagLookalikeDomain","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","kind","hostId","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","poolMember","selection","audience","platformIssued","localPart","selectedLocalPart","pinned","shared","at","lastIndexOf","hostSendingIdentity","cache","hit","owner","lock","org","host","suspended","suspendedSendingIdentity","scope","resolved","workspace","siteSenderNames","input","brandFromName","fromName","siteName","what","message","from","source","summary","refusal","code","outstandingSendingRecords","Set","size","has"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkDC,GAED,SACEA,WAAW,EACXC,oBAAoB,EACpBC,cAAc,EACdC,uBAAuB,EACvBC,qBAAqB,EACrBC,kBAAkB,EAClBC,sBAAsB,EACtBC,sBAAsB,EACtBC,kBAAkB,EAClBC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,EAC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TI,SAAS;YACPC,MAAM;YACNhJ,QAAQ;YACR2I;YACA1C,SAAS,EAAE;QACb;IACF;AACF;AAEA,yDAAyD,GACzD,OAAO,SAASgD,0BACdjH,MAA2B;;IAE3B,MAAMiE,UAAU,IAAIiD,YAAIlH,0BAAAA,OAAQN,WAAW,mBAAI,EAAE;IACjD,IAAI,CAACuE,QAAQkD,IAAI,EAAE,OAAO,EAAE;IAC5B,OAAOzK,kBAAkBsD,QAAQ8B,MAAM,CAAC,CAACb,QACvCgD,QAAQmD,GAAG,CAACvK,iBAAiBoE;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 headerSafeText,\n isPlatformSendingDomain,\n isSharedSendingDomain,\n normalizeLocalPart,\n normalizeSendingDomain,\n resolveSendingIdentity,\n safeProviderDetail,\n SENDING_FROM_NAME_MAX,\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 {\n lockdownMode,\n resolveBrandingProfile,\n resolveHostToken,\n} from '@aglyn/aglyn/server'\nimport firebaseAdmin from './firebase-admin'\nimport { lookupCaa, lookupMx, lookupTxt } from './dns-probe'\nimport { getOrgForHost } from './organizations'\nimport { getSiteLockdown } from './tenant-write-lockdown'\n// Also INSTALLS the outbound phishing screen's review store on `sendEmail`\n// (AGL-3356): every sender whose identity comes from `hostSendingIdentity`\n// has therefore installed the gate the workspace stamped below is read by.\nimport { sendingWorkspaceFor } from './outbound-send-review'\nimport { flagLookalikeDomain } from './hosted-page-review'\nimport { resolveTransactionalEmailDailyCeiling } from '@aglyn/aglyn/app-utils/transactional-email-ceiling'\n// Also INSTALLS the daily transactional ceiling's counter on `sendEmail`\n// (AGL-4145), for the same reason: the ceiling stamped on the workspace below\n// is only read by a send path that has the gate installed.\nimport './email-transactional-ceiling'\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 // A domain that wears a brand (`paypa1.com`) goes to staff in the abuse\n // queue the moment it is claimed — flagged, not refused (AGL-3362). Mail\n // from it is held at the send seam whatever staff decide. Never throws.\n await flagLookalikeDomain({ kind: 'sending', hostId: null, orgId: options.orgId, domain })\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 // Again on verification, the moment it can actually send (AGL-3362): a\n // claim added before this check existed is caught here. One row per\n // domain, so this counts rather than re-alerts.\n if (verified) {\n await flagLookalikeDomain({ kind: 'sending', hostId: null, orgId, domain })\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 /*\n * A SUSPENDED SITE SENDS NOTHING (AGL-3356).\n *\n * This is the door every tenant sender but the campaign core uses, so it\n * is where one check covers them all — workflow and automation steps, the\n * CRM's one-off mail, inbox replies, member posts, receipts, reminders.\n * Refusing here rather than at each caller is the same argument this\n * function's own docblock makes about identities: nineteen call sites\n * asked to remember produce a twentieth that does not, and the incident\n * behind this was exactly that — a locked workspace whose workflow could\n * still mail for it.\n *\n * FULL locks only. A read-only lock is a maintenance window whose point\n * is that the site keeps serving and earning, and a receipt for an order\n * taken before it began must still arrive. Staff suspensions for abuse,\n * fraud and billing are full locks, which is the case this closes.\n *\n * The documents read above are handed to the verdict, so the check costs\n * the TTL-cached platform read and nothing else. It inherits the\n * verdict's fail-open posture and its takedown ratchet.\n */\n const lock = await getSiteLockdown(id, Date.now(), {\n org: (owner?.org as Record<string, unknown> | undefined) ?? null,\n host: snapshot?.exists\n ? ((snapshot.data() as Record<string, unknown>) ?? null)\n : null,\n })\n if (lock && lockdownMode(lock) === 'full') {\n const suspended = suspendedSendingIdentity(lock.scope)\n cache?.set(id, suspended)\n return suspended\n }\n\n const resolved = 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 /*\n * THE WORKSPACE, STAMPED FOR THE PHISHING SCREEN (AGL-3356).\n *\n * `sendEmail` screens every tenant message whose identity carries this,\n * so stamping it here is what puts CRM mail, inbox replies, newsletters,\n * member posts, sweeps, flow steps and receipts behind one screen without\n * any of them passing anything. Built from the two documents read above:\n * the screen costs no read of its own.\n */\n const verdict: SendingIdentityVerdict = {\n ...resolved,\n workspace: {\n ...sendingWorkspaceFor({\n hostId: id,\n orgId: owner?.orgId ?? null,\n org: (owner?.org as Record<string, unknown> | undefined) ?? null,\n host: snapshot?.exists\n ? ((snapshot.data() as Record<string, unknown>) ?? null)\n : null,\n }),\n /*\n * THE DAILY TRANSACTIONAL CEILING (AGL-4145), from the same org\n * document, so the send seam's count costs no read of its own. No\n * organization read means no ceiling known, and none is applied —\n * an unreadable org must not put a paying store on Free's figure.\n */\n transactionalEmailsPerDay: owner?.org\n ? resolveTransactionalEmailDailyCeiling(owner.org as never)\n : null,\n },\n /*\n * THE NAME THE SITE SENDS UNDER (AGL-3442), from the same two documents,\n * so it costs no read. `sendEmail` puts it where a sender passed the\n * org's branding default; the address above is untouched.\n */\n ...siteSenderNames({\n org: (owner?.org as Record<string, unknown> | undefined) ?? null,\n host: snapshot?.exists\n ? ((snapshot.data() as Record<string, unknown>) ?? null)\n : null,\n }),\n }\n\n cache?.set(id, verdict)\n return verdict\n}\n\n/**\n * The display name one site's mail leaves under, and the org default it\n * replaces (AGL-3442).\n *\n * The site's business name — what its emails render as\n * `{{host.businessName}}`, which is its SEO entity name or else its display\n * name — and the org's branding default when the site has neither, which is\n * \"Aglyn\" for an org without white-label. The name sent is flattened as every\n * sender name is, because it reaches a `From:` header and the site's owner\n * typed it. The default is kept exactly as `resolveBrandingProfile` returns\n * it, because `sendEmail` recognizes it by comparing it with what a sender\n * passed, and senders pass that value unchanged.\n */\nexport function siteSenderNames(input: {\n org: Record<string, unknown> | null\n host: Record<string, unknown> | null\n}): Pick<SendingIdentityVerdict, 'fromName' | 'brandFromName'> {\n const brandFromName = String(\n resolveBrandingProfile(input.org as never).fromName ?? '',\n ).trim()\n const siteName = headerSafeText(\n resolveHostToken('businessName', input.host as never),\n SENDING_FROM_NAME_MAX,\n )\n return {\n fromName: siteName || headerSafeText(brandFromName, SENDING_FROM_NAME_MAX),\n brandFromName,\n }\n}\n\n/**\n * The verdict a suspended site's mail gets: a refusal, whatever identity the\n * site would otherwise have sent on. `sendEmail` reads it and answers\n * `suspended` without calling the provider.\n */\nexport function suspendedSendingIdentity(\n scope: string | null | undefined,\n): SendingIdentityVerdict {\n const what =\n scope === 'platform'\n ? 'Sending is paused platform-wide'\n : scope === 'org'\n ? 'This workspace is suspended'\n : 'This site is suspended'\n const message = `${what}, so no email is sent on its behalf until the suspension is lifted.`\n return {\n from: null,\n source: null,\n domain: null,\n summary: message,\n refusal: {\n code: 'workspace-suspended',\n domain: null,\n message,\n missing: [],\n },\n }\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","headerSafeText","isPlatformSendingDomain","isSharedSendingDomain","normalizeLocalPart","normalizeSendingDomain","resolveSendingIdentity","safeProviderDetail","SENDING_FROM_NAME_MAX","SENDING_SUBDOMAIN","sendingDnsRecords","sendingTrackingHost","sendingDomainRequiredRecords","sendingRecordKey","sharedTenantSendingFrom","validateSendingDomain","lockdownMode","resolveBrandingProfile","resolveHostToken","firebaseAdmin","lookupCaa","lookupMx","lookupTxt","getOrgForHost","getSiteLockdown","sendingWorkspaceFor","flagLookalikeDomain","resolveTransactionalEmailDailyCeiling","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","kind","hostId","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","poolMember","selection","audience","platformIssued","localPart","selectedLocalPart","pinned","shared","at","lastIndexOf","hostSendingIdentity","cache","hit","owner","lock","org","host","suspended","suspendedSendingIdentity","scope","resolved","workspace","transactionalEmailsPerDay","siteSenderNames","input","brandFromName","fromName","siteName","what","message","from","source","summary","refusal","code","outstandingSendingRecords","Set","size","has"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkDC,GAED,SACEA,WAAW,EACXC,oBAAoB,EACpBC,cAAc,EACdC,uBAAuB,EACvBC,qBAAqB,EACrBC,kBAAkB,EAClBC,sBAAsB,EACtBC,sBAAsB,EACtBC,kBAAkB,EAClBC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,EACjBC,mBAAmB,EACnBC,4BAA4B,EAC5BC,gBAAgB,EAChBC,uBAAuB,EACvBC,qBAAqB,QAQhB,2BAA0B;AACjC,SACEC,YAAY,EACZC,sBAAsB,EACtBC,gBAAgB,QACX,sBAAqB;AAC5B,OAAOC,mBAAmB,sBAAkB;AAC5C,SAAS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QACR+I,SAASH;QACTI,SAAS;YACPC,MAAM;YACNjJ,QAAQ;YACR4I;YACA3C,SAAS,EAAE;QACb;IACF;AACF;AAEA,yDAAyD,GACzD,OAAO,SAASiD,0BACdlH,MAA2B;;IAE3B,MAAMiE,UAAU,IAAIkD,YAAInH,0BAAAA,OAAQN,WAAW,mBAAI,EAAE;IACjD,IAAI,CAACuE,QAAQmD,IAAI,EAAE,OAAO,EAAE;IAC5B,OAAO3K,kBAAkBuD,QAAQ8B,MAAM,CAAC,CAACb,QACvCgD,QAAQoD,GAAG,CAACzK,iBAAiBqE;AAEjC"}
|
|
@@ -48,8 +48,9 @@ export interface ProposeOrgUpgradeOptions {
|
|
|
48
48
|
interval?: unknown;
|
|
49
49
|
coupon?: unknown;
|
|
50
50
|
/**
|
|
51
|
-
*
|
|
52
|
-
*
|
|
51
|
+
* A retired Aglyn AI tier (AGL-4025). Credits are sold by the block since
|
|
52
|
+
* AGL-4144 (`ai:<blocks>` in `addons`), so a proposal naming a tier is
|
|
53
|
+
* refused rather than stored with a price nobody sells.
|
|
53
54
|
*/
|
|
54
55
|
aiTier?: unknown;
|
|
55
56
|
/** The staff member proposing. */
|
|
@@ -96,6 +96,9 @@ const firestore = ()=>firebaseAdmin.app().firestore();
|
|
|
96
96
|
throw new UpgradeProposalError('Choose a paid plan the workspace can buy itself');
|
|
97
97
|
}
|
|
98
98
|
const plan = options.plan;
|
|
99
|
+
if (options.aiTier != null) {
|
|
100
|
+
throw new UpgradeProposalError('AI tiers were replaced by AI credit blocks. Propose a number of blocks instead.');
|
|
101
|
+
}
|
|
99
102
|
const note = normalizeUpgradeProposalNote(options.note);
|
|
100
103
|
return _extends({
|
|
101
104
|
plan,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upgrade-proposal.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n normalizeUpgradeProposalNote,\n upgradeProposalDestination,\n upgradeProposalSummary,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /**\n * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any\n * shape `parseBundleAddons` reads; fitted to the plan before storing.\n */\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /**\n * The Aglyn AI tier chosen with the AI add-on (AGL-4025); an `ai:<tier>`\n * entry in `addons` names one too, and this wins when both do.\n */\n aiTier?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused when the workspace already has a live subscription — the question\n * a proposal asks is already answered — and for any plan a customer cannot\n * buy themselves.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n const proposal = buildUpgradeProposal(options)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const org = await db.runTransaction(async (tx) => {\n const data = await readUpgradeProposalTarget(tx, orgRef)\n stageUpgradeProposal(tx, db, { orgId, proposal, before: data, actorUid: actor.uid })\n return data\n })\n await recordUpgradeProposalActivity(orgId, actor, proposal)\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/**\n * The proposal as it will be stored, or the refusal: a plan the workspace\n * can buy itself, a bounded note, and the bundle fitted to the plan\n * (AGL-3956). Nothing is read or written.\n */\nexport function buildUpgradeProposal(\n options: Pick<\n ProposeOrgUpgradeOptions,\n 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'aiTier' | 'actor'\n > & {\n now?: number\n },\n): OrgUpgradeProposal {\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n const note = normalizeUpgradeProposalNote(options.note)\n return {\n plan,\n proposedBy: options.actor.uid,\n proposedAt: options.now ?? Date.now(),\n ...(note ? { note } : {}),\n ...normalizeUpgradeProposalBundle(plan, options),\n }\n}\n\n/**\n * Read the org a proposal is for, inside the caller's transaction, refusing\n * an unknown workspace and one whose subscription is already live — the\n * question a proposal asks is then already answered.\n */\nexport async function readUpgradeProposalTarget(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Partial<AglynOrgBilling>> {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const status =\n (billing.get('subscription') as { status?: unknown } | undefined)?.status ??\n data.billingStatus\n if (isLiveSubscriptionStatus(status)) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n return data\n}\n\n/**\n * Write the proposal and its audit row into the caller's transaction, so\n * they commit with whatever else the caller writes (AGL-1784) — the owner\n * invitation, for a hand-off that proposes in the same act (AGL-3956).\n */\nexport function stageUpgradeProposal(\n tx: FirebaseFirestore.Transaction,\n db: FirebaseFirestore.Firestore,\n options: {\n orgId: string\n proposal: OrgUpgradeProposal\n before: Partial<AglynOrgBilling>\n actorUid: string\n },\n): void {\n const { orgId, proposal, before, actorUid } = options\n tx.set(\n db.collection('orgs').doc(orgId),\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: before.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n}\n\n/** \"Proposed the Starter plan\", naming the bundle when there is one. */\nexport function proposalActivityLine(proposal: OrgUpgradeProposal): string {\n const label = planName(proposal.plan)\n const summary = upgradeProposalSummary(proposal)\n return summary === label\n ? `Proposed the ${label} plan`\n : `Proposed the ${label} plan (${summary})`\n}\n\n/** The workspace's feed line for a proposal, after it commits. */\nexport async function recordUpgradeProposalActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n proposal: OrgUpgradeProposal,\n): Promise<void> {\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n proposalActivityLine(proposal),\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: { status: string; subscriptionId?: string | null },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const proposal = data.upgradeProposal ?? null\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n `The subscription went live (${context.status})` +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const summary = upgradeProposalSummary(proposal, { brand: productName })\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n 'proposal.summary': summary === label ? '' : summary,\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n (summary === label ? 'plan. ' : `plan (${summary}). `) +\n 'When you are ready, start the subscription from Billing, ' +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","normalizeUpgradeProposalNote","upgradeProposalDestination","upgradeProposalSummary","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","orgId","actor","origin","proposal","buildUpgradeProposal","db","orgRef","collection","doc","org","runTransaction","tx","data","readUpgradeProposalTarget","stageUpgradeProposal","before","actorUid","uid","recordUpgradeProposalActivity","emailed","emailUpgradeProposal","plan","note","proposedBy","proposedAt","now","Date","billing","snapshot","get","exists","billingStatus","set","upgradeProposal","updatedAt","serverTimestamp","merge","action","target","after","at","proposalActivityLine","label","planName","summary","email","type","id","staffActorId","withdrawOrgUpgrade","withdrawn","stored","delete","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","productName","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAOD,SAASA,WAAW,QAAQ,2CAA0C;AACtE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,sBAAsB,QACjB,0CAAyC;AAChD,wEAAwE;AACxE,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,QACpB,yCAAwC;AAC/C,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AACnD,SAASC,aAAa,QAAQ,sBAAkB;AAChD,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,cAAc,QAAQ,qBAAiB;AAChD,SACEC,wBAAwB,EACxBC,gBAAgB,QACX,2BAAuB;AAE9B,MAAMC,YAAY,IAAMJ,cAAcK,GAAG,GAAGD,SAAS;AAErD,kEAAkE,GAClE,OAAO,MAAME,yBAAyB,QAAO;AAE7C,oDAAoD,GACpD,OAAO,MAAMC,6BAA6BC;IAExC,YAAYC,OAAe,EAAEC,SAAS,GAAG,CAAE;QACzC,KAAK,CAACD;QACN,IAAI,CAACE,IAAI,GAAG;QACZ,IAAI,CAACD,MAAM,GAAGA;IAChB;AACF;AA8BA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeE,kBACpBC,OAAiC;IAEjC,MAAM,EAAEC,KAAK,EAAEC,KAAK,EAAEC,MAAM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AAC,IAAI,EAAEnB,SAASmB,IAAI,EAAE,GAAG,EAAC;QAC/C;QAEF,MAAM2D,SAAS,MAAMnG,UAAU;YAC7B0F;YACAO,SAASD,QAAQC,OAAO;YACxBC,MAAMF,QAAQE,IAAI;WACdF,QAAQI,IAAI,GAAG;YAAEA,MAAMJ,QAAQI,IAAI;QAAC,IAAI,CAAC,GACzCT,MAAMU,QAAQ,GAAG;YAAEA,UAAUV,MAAMU,QAAQ;QAAC,IAAI,CAAC;YACrD7B,SAAS;;QAEX,IAAI2B,OAAOG,IAAI,EAAE,MAAMnG,cAAce;QACrC,OAAOiF,OAAOG,IAAI;IACpB,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,yCAAyCA;QACvD,OAAO;IACT;AACF;AAEA,SAAS1C,SAAStB,IAAa;IAC7B,OAAO,OAAOA,SAAS,YAAYA,QAAQlD,cACvCA,WAAW,CAACkD,KAAgB,GAC5BkE,OAAOlE,eAAAA,OAAQ;AACrB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/upgrade-proposal.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The platform team's ask that a workspace buy a plan, server side\n * (AGL-3466): staff propose and withdraw it, and a live subscription settles\n * it.\n *\n * The sequence it serves: staff build a workspace for a client, comp it to\n * the tier being sold with the `trial` reason, and hand it over. The client\n * evaluates on that tier with no upgrade asked of them. When the evaluation\n * is done, staff record a proposal here; the owner is emailed and the\n * workspace's billing managers see a card with the plan preselected. When\n * the subscription goes live, the proposal and the trial comp both clear,\n * so a comp granted to evaluate cannot revive free access if the customer\n * later cancels.\n */\n\nimport type {\n AglynOrgBilling,\n OrgPlan,\n OrgUpgradeProposal,\n} from '@aglyn/aglyn/server'\nimport { PLAN_LABELS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n normalizeUpgradeProposalNote,\n upgradeProposalDestination,\n upgradeProposalSummary,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\n// Leaf modules, as `organizations.ts` imports its constants (AGL-1289).\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport { meterOrgEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { logOrgActivity } from './organizations'\nimport {\n renderSystemEmailContent,\n systemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** The override reason a sales-evaluation comp is granted under. */\nexport const TRIAL_PLAN_COMP_REASON = 'trial'\n\n/** A proposal refused before anything was written. */\nexport class UpgradeProposalError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'UpgradeProposalError'\n this.status = status\n }\n}\n\nexport interface ProposeOrgUpgradeOptions {\n orgId: string\n plan: unknown\n note?: unknown\n /**\n * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any\n * shape `parseBundleAddons` reads; fitted to the plan before storing.\n */\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /**\n * A retired Aglyn AI tier (AGL-4025). Credits are sold by the block since\n * AGL-4144 (`ai:<blocks>` in `addons`), so a proposal naming a tier is\n * refused rather than stored with a price nobody sells.\n */\n aiTier?: unknown\n /** The staff member proposing. */\n actor: { uid: string; email?: string | null }\n /** The console origin the email's link is built on. */\n origin: string\n}\n\nexport interface ProposeOrgUpgradeResult {\n proposal: OrgUpgradeProposal\n /** Whether the owner's email actually went out. */\n emailed: boolean\n}\n\n/**\n * Record a proposal on the org, audit it, and email the owner.\n *\n * The org write and its audit row commit together, the property every staff\n * write to an org document keeps (AGL-1784). The email is sent after the\n * commit and is best-effort: the card on the org home is the proposal, and\n * an email that failed must not undo it.\n *\n * Refused when the workspace already has a live subscription — the question\n * a proposal asks is already answered — and for any plan a customer cannot\n * buy themselves.\n */\nexport async function proposeOrgUpgrade(\n options: ProposeOrgUpgradeOptions,\n): Promise<ProposeOrgUpgradeResult> {\n const { orgId, actor, origin } = options\n const proposal = buildUpgradeProposal(options)\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const org = await db.runTransaction(async (tx) => {\n const data = await readUpgradeProposalTarget(tx, orgRef)\n stageUpgradeProposal(tx, db, { orgId, proposal, before: data, actorUid: actor.uid })\n return data\n })\n await recordUpgradeProposalActivity(orgId, actor, proposal)\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\n}\n\n/**\n * The proposal as it will be stored, or the refusal: a plan the workspace\n * can buy itself, a bounded note, and the bundle fitted to the plan\n * (AGL-3956). Nothing is read or written.\n */\nexport function buildUpgradeProposal(\n options: Pick<\n ProposeOrgUpgradeOptions,\n 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'aiTier' | 'actor'\n > & {\n now?: number\n },\n): OrgUpgradeProposal {\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new UpgradeProposalError(\n 'Choose a paid plan the workspace can buy itself',\n )\n }\n const plan: OrgPlan = options.plan\n if (options.aiTier != null) {\n throw new UpgradeProposalError(\n 'AI tiers were replaced by AI credit blocks. Propose a number of blocks instead.',\n )\n }\n const note = normalizeUpgradeProposalNote(options.note)\n return {\n plan,\n proposedBy: options.actor.uid,\n proposedAt: options.now ?? Date.now(),\n ...(note ? { note } : {}),\n ...normalizeUpgradeProposalBundle(plan, options),\n }\n}\n\n/**\n * Read the org a proposal is for, inside the caller's transaction, refusing\n * an unknown workspace and one whose subscription is already live — the\n * question a proposal asks is then already answered.\n */\nexport async function readUpgradeProposalTarget(\n tx: FirebaseFirestore.Transaction,\n orgRef: FirebaseFirestore.DocumentReference,\n): Promise<Partial<AglynOrgBilling>> {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const billing = await tx.get(\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID),\n )\n const status =\n (billing.get('subscription') as { status?: unknown } | undefined)?.status ??\n data.billingStatus\n if (isLiveSubscriptionStatus(status)) {\n throw new UpgradeProposalError(\n 'This workspace already has a live subscription, so there is nothing to propose',\n 409,\n )\n }\n return data\n}\n\n/**\n * Write the proposal and its audit row into the caller's transaction, so\n * they commit with whatever else the caller writes (AGL-1784) — the owner\n * invitation, for a hand-off that proposes in the same act (AGL-3956).\n */\nexport function stageUpgradeProposal(\n tx: FirebaseFirestore.Transaction,\n db: FirebaseFirestore.Firestore,\n options: {\n orgId: string\n proposal: OrgUpgradeProposal\n before: Partial<AglynOrgBilling>\n actorUid: string\n },\n): void {\n const { orgId, proposal, before, actorUid } = options\n tx.set(\n db.collection('orgs').doc(orgId),\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: before.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n}\n\n/** \"Proposed the Starter plan\", naming the bundle when there is one. */\nexport function proposalActivityLine(proposal: OrgUpgradeProposal): string {\n const label = planName(proposal.plan)\n const summary = upgradeProposalSummary(proposal)\n return summary === label\n ? `Proposed the ${label} plan`\n : `Proposed the ${label} plan (${summary})`\n}\n\n/** The workspace's feed line for a proposal, after it commits. */\nexport async function recordUpgradeProposalActivity(\n orgId: string,\n actor: { uid: string; email?: string | null },\n proposal: OrgUpgradeProposal,\n): Promise<void> {\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n proposalActivityLine(proposal),\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n}\n\n/** Remove a standing proposal, audited. Answers whether one stood. */\nexport async function withdrawOrgUpgrade(options: {\n orgId: string\n actor: { uid: string; email?: string | null }\n}): Promise<boolean> {\n const { orgId, actor } = options\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const withdrawn = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404)\n const stored = snapshot.get('upgradeProposal') as OrgUpgradeProposal | undefined\n if (!stored) return null\n tx.set(\n orgRef,\n { upgradeProposal: FieldValue.delete(), updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.withdraw',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: stored },\n after: { upgradeProposal: null },\n at: FieldValue.serverTimestamp(),\n })\n return stored\n })\n if (!withdrawn) return false\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Withdrew the ${planName(withdrawn.plan)} plan proposal`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n return true\n}\n\n/**\n * What a live subscription settles (AGL-3466), cleared in one transaction\n * with an audit row that says why:\n *\n * - the standing `upgradeProposal`, whose question the purchase answered;\n * - a stored plan comp granted for a sales TRIAL. A comp waits dormant under\n * a live subscription and applies again if it ends (`resolvePlanComp`), so\n * a trial comp left in place would hand a customer who cancels the tier for\n * free. Comps granted for any other reason are left alone: those are\n * decisions staff made for reasons a purchase does not answer.\n *\n * Called by the Stripe webhook once its mirror has recorded a live status.\n * Idempotent: a redelivery finds nothing to clear and writes nothing.\n */\nexport async function settleSubscriptionStart(\n orgId: string,\n context: { status: string; subscriptionId?: string | null },\n): Promise<{ proposalCleared: boolean; trialCompRemoved: boolean }> {\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const outcome = await db.runTransaction(async (tx) => {\n const snapshot = await tx.get(orgRef)\n if (!snapshot.exists) return null\n const data = snapshot.data() as Partial<AglynOrgBilling>\n const proposal = data.upgradeProposal ?? null\n const entitlements = (data.entitlements ?? null) as Record<string, unknown> | null\n const comp = entitlements?.['planComp'] as\n | { plan?: string; reason?: string }\n | undefined\n const trialComp = comp?.reason === TRIAL_PLAN_COMP_REASON ? comp : null\n if (!proposal && !trialComp) return null\n // The map goes with its last key, so the staff list's override count\n // never reads an empty `entitlements` as one.\n const onlyComp =\n !!entitlements && Object.keys(entitlements).every((key) => key === 'planComp')\n tx.set(\n orgRef,\n {\n ...(proposal ? { upgradeProposal: FieldValue.delete() } : {}),\n ...(trialComp\n ? onlyComp\n ? { entitlements: FieldValue.delete() }\n : { entitlements: { planComp: FieldValue.delete() } }\n : {}),\n updatedAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: 'system',\n action: 'org.subscriptionStarted.settle',\n target: `orgs/${orgId}`,\n reason: {\n code: 'subscription_live',\n note:\n `The subscription went live (${context.status})` +\n (context.subscriptionId ? `, ${context.subscriptionId}` : '') +\n ', which settles the upgrade proposal and ends the sales-trial comp.',\n },\n before: { upgradeProposal: proposal, planComp: comp ?? null },\n after: {\n upgradeProposal: null,\n // A comp granted for any other reason stays exactly as it was.\n planComp: trialComp ? null : (comp ?? null),\n },\n at: FieldValue.serverTimestamp(),\n })\n return { proposal, trialComp }\n })\n if (!outcome) return { proposalCleared: false, trialCompRemoved: false }\n // Nobody is present at a Stripe flip, and the row says so rather than\n // naming whoever last touched billing.\n if (outcome.proposal) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.proposal.plan)} plan proposal closed — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n if (outcome.trialComp) {\n await logOrgActivity(\n orgId,\n { uid: null },\n `The ${planName(outcome.trialComp.plan)} sales-trial comp ended — the subscription is live`,\n { type: 'subscription', id: orgId },\n )\n }\n return {\n proposalCleared: !!outcome.proposal,\n trialCompRemoved: !!outcome.trialComp,\n }\n}\n\n/** Mail the owner the proposal, in the workspace's brand. Never throws. */\nasync function emailUpgradeProposal(options: {\n orgId: string\n org: Partial<AglynOrgBilling>\n proposal: OrgUpgradeProposal\n origin: string\n}): Promise<boolean> {\n const { orgId, org, proposal, origin } = options\n try {\n if (!isEmailConfigured()) return false\n const ownerUid = (org as { ownerUid?: unknown }).ownerUid\n if (typeof ownerUid !== 'string' || !ownerUid) return false\n const owner = await firestore()\n .collection('orgs')\n .doc(orgId)\n .collection('members')\n .doc(ownerUid)\n .get()\n const to = owner.get('email')\n if (typeof to !== 'string' || !to) return false\n const brand = systemEmailBrand(org as Record<string, unknown>)\n const orgName = brand.orgName || 'your workspace'\n const slug = typeof org.slug === 'string' ? org.slug : ''\n const billingUrl = slug\n ? `${origin}${upgradeProposalDestination(slug, proposal)}`\n : origin\n const label = planName(proposal.plan)\n const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME\n const summary = upgradeProposalSummary(proposal, { brand: productName })\n const content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\n 'proposal.summary': summary === label ? '' : summary,\n billingUrl,\n },\n brand,\n {\n subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,\n text:\n `Your ${productName} team proposed moving ${orgName} to the ${label} ` +\n (summary === label ? 'plan. ' : `plan (${summary}). `) +\n 'When you are ready, start the subscription from Billing, ' +\n `where the plan is already selected:\\n\\n${billingUrl}` +\n (proposal.note ? `\\n\\n${proposal.note}` : ''),\n },\n )\n const result = await sendEmail({\n to,\n subject: content.subject,\n text: content.text,\n ...(content.html ? { html: content.html } : {}),\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: 'org-upgrade-proposal',\n })\n if (result.sent) await meterOrgEmail(orgId)\n return result.sent\n } catch (error) {\n console.error('[upgrade-proposal] owner email failed', error)\n return false\n }\n}\n\nfunction planName(plan: unknown): string {\n return typeof plan === 'string' && plan in PLAN_LABELS\n ? PLAN_LABELS[plan as OrgPlan]\n : String(plan ?? 'proposed')\n}\n"],"names":["PLAN_LABELS","PLATFORM_BRAND_NAME","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","normalizeUpgradeProposalNote","upgradeProposalDestination","upgradeProposalSummary","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","isEmailConfigured","sendEmail","FieldValue","setAdminAudit","meterOrgEmail","firebaseAdmin","logOrgActivity","renderSystemEmailContent","systemEmailBrand","firestore","app","TRIAL_PLAN_COMP_REASON","UpgradeProposalError","Error","message","status","name","proposeOrgUpgrade","options","orgId","actor","origin","proposal","buildUpgradeProposal","db","orgRef","collection","doc","org","runTransaction","tx","data","readUpgradeProposalTarget","stageUpgradeProposal","before","actorUid","uid","recordUpgradeProposalActivity","emailed","emailUpgradeProposal","plan","aiTier","note","proposedBy","proposedAt","now","Date","billing","snapshot","get","exists","billingStatus","set","upgradeProposal","updatedAt","serverTimestamp","merge","action","target","after","at","proposalActivityLine","label","planName","summary","email","type","id","staffActorId","withdrawOrgUpgrade","withdrawn","stored","delete","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","productName","content","subject","text","result","html","fromName","sent","error","console","String"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;CAaC;AAOD,SAASA,WAA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AAUV,MAAMU,QAAQ;QAAC,IAAI,CAAC;YACrD7B,SAAS;;QAEX,IAAI2B,OAAOG,IAAI,EAAE,MAAMpG,cAAce;QACrC,OAAOkF,OAAOG,IAAI;IACpB,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,yCAAyCA;QACvD,OAAO;IACT;AACF;AAEA,SAAS1C,SAASvB,IAAa;IAC7B,OAAO,OAAOA,SAAS,YAAYA,QAAQlD,cACvCA,WAAW,CAACkD,KAAgB,GAC5BmE,OAAOnE,eAAAA,OAAQ;AACrB"}
|
|
@@ -365,8 +365,14 @@ export async function upsertHostContact(options) {
|
|
|
365
365
|
* merge-set, and the counts settle after it.
|
|
366
366
|
*/ const link = profile.companyId !== undefined ? planContactCompanyLink(readContactCompanyLink(docSnapshot.data(), group.groupId), profile.companyId) : null;
|
|
367
367
|
const mirror = link ? contactCompanyMirrorValue(link) : undefined;
|
|
368
|
-
|
|
369
|
-
|
|
368
|
+
/*
|
|
369
|
+
* THE NUMBER THE PERSON IS FOUND BY (AGL-4122), as New contact stores
|
|
370
|
+
* it: the Phone, or the mobile of a holder with no other number. A
|
|
371
|
+
* door that carried only a mobile leaves a Phone this holder already
|
|
372
|
+
* has as the number, and one that carried neither writes no echo.
|
|
373
|
+
*/ const phoneEcho = profile.phone || (profile.mobilePhone ? facet.phone || profile.mobilePhone : '');
|
|
374
|
+
await docSnapshot.ref.set(_extends({}, facetName ? nameSearchFields(facetName) : {}, phoneEcho ? {
|
|
375
|
+
phone: phoneEcho
|
|
370
376
|
} : {}, profile.companyName ? {
|
|
371
377
|
companyName: profile.companyName
|
|
372
378
|
} : {}, mirror !== undefined ? {
|
|
@@ -541,8 +547,8 @@ export async function upsertHostContact(options) {
|
|
|
541
547
|
ORG_SCOPE_TOKEN
|
|
542
548
|
] : consentGroupScope(group),
|
|
543
549
|
email
|
|
544
|
-
}, canonicalName ? nameSearchFields(canonicalName) : {}, profile.phone ? {
|
|
545
|
-
phone: profile.phone
|
|
550
|
+
}, canonicalName ? nameSearchFields(canonicalName) : {}, profile.phone || profile.mobilePhone ? {
|
|
551
|
+
phone: profile.phone || profile.mobilePhone
|
|
546
552
|
} : {}, profile.companyName ? {
|
|
547
553
|
companyName: profile.companyName
|
|
548
554
|
} : {}, profile.companyId ? {
|