@aglyn/tenant-data-admin 1.0.0-beta.270 → 1.0.0-beta.272

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/append-only-history-write.d.ts +38 -0
  3. package/src/lib/server/append-only-history-write.js +60 -0
  4. package/src/lib/server/append-only-history-write.js.map +1 -0
  5. package/src/lib/server/billing-addons.d.ts +58 -32
  6. package/src/lib/server/billing-addons.js +100 -86
  7. package/src/lib/server/billing-addons.js.map +1 -1
  8. package/src/lib/server/bundle-links.d.ts +166 -0
  9. package/src/lib/server/bundle-links.js +286 -0
  10. package/src/lib/server/bundle-links.js.map +1 -0
  11. package/src/lib/server/client-build.d.ts +74 -0
  12. package/src/lib/server/client-build.js +264 -0
  13. package/src/lib/server/client-build.js.map +1 -0
  14. package/src/lib/server/domain-ownership.d.ts +205 -0
  15. package/src/lib/server/domain-ownership.js +575 -0
  16. package/src/lib/server/domain-ownership.js.map +1 -0
  17. package/src/lib/server/erase.d.ts +17 -0
  18. package/src/lib/server/erase.js +21 -0
  19. package/src/lib/server/erase.js.map +1 -1
  20. package/src/lib/server/host-memberships.d.ts +35 -2
  21. package/src/lib/server/host-memberships.js +63 -2
  22. package/src/lib/server/host-memberships.js.map +1 -1
  23. package/src/lib/server/org-billing.d.ts +4 -2
  24. package/src/lib/server/org-billing.js +5 -0
  25. package/src/lib/server/org-billing.js.map +1 -1
  26. package/src/lib/server/site-care-emails.d.ts +53 -0
  27. package/src/lib/server/site-care-emails.js +97 -0
  28. package/src/lib/server/site-care-emails.js.map +1 -0
  29. package/src/lib/server/site-care-inbound.d.ts +123 -0
  30. package/src/lib/server/site-care-inbound.js +197 -0
  31. package/src/lib/server/site-care-inbound.js.map +1 -0
  32. package/src/lib/server/site-care-project-reconcile.d.ts +64 -0
  33. package/src/lib/server/site-care-project-reconcile.js +211 -0
  34. package/src/lib/server/site-care-project-reconcile.js.map +1 -0
  35. package/src/lib/server/site-care-project-stripe.d.ts +114 -0
  36. package/src/lib/server/site-care-project-stripe.js +305 -0
  37. package/src/lib/server/site-care-project-stripe.js.map +1 -0
  38. package/src/lib/server/site-care-projects.d.ts +169 -0
  39. package/src/lib/server/site-care-projects.js +882 -0
  40. package/src/lib/server/site-care-projects.js.map +1 -0
  41. package/src/lib/server/site-care-reconcile.d.ts +81 -0
  42. package/src/lib/server/site-care-reconcile.js +349 -0
  43. package/src/lib/server/site-care-reconcile.js.map +1 -0
  44. package/src/lib/server/site-care-requests.d.ts +243 -0
  45. package/src/lib/server/site-care-requests.js +1414 -0
  46. package/src/lib/server/site-care-requests.js.map +1 -0
  47. package/src/lib/server/site-care-stripe.d.ts +175 -0
  48. package/src/lib/server/site-care-stripe.js +375 -0
  49. package/src/lib/server/site-care-stripe.js.map +1 -0
  50. package/src/lib/server/sso-provisioning.d.ts +6 -0
  51. package/src/lib/server/sso-provisioning.js +7 -0
  52. package/src/lib/server/sso-provisioning.js.map +1 -1
  53. package/src/lib/server/upgrade-proposal.d.ts +40 -1
  54. package/src/lib/server/upgrade-proposal.js +92 -50
  55. package/src/lib/server/upgrade-proposal.js.map +1 -1
  56. package/src/tenancy.d.ts +1 -0
  57. package/src/tenancy.js +2 -0
  58. package/src/tenancy.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/sso-provisioning.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 * Self-serve enterprise SSO provisioning (AGL-1210).\n *\n * Before this, `tenantManager()` appeared six times in the repo and every one\n * was `authForTenant(...)` — authenticating against a pool somebody had made by\n * hand in the Firebase console. There was no `createTenant` and no\n * `createProviderConfig` anywhere, so onboarding an SSO org meant a person\n * clicking through GCIP and then writing `tenantId`/`providerId` onto the org\n * doc. This module is the write half that removes that step.\n *\n * ## Domain verification is the security gate, not a formality\n *\n * `ssoDomains/{domain}` routes every sign-in for a domain to whichever org\n * claims it. Letting an org self-assert that claim would be an\n * account-takeover vector: claim `competitor.com`, and their employees' sign-in\n * attempts arrive at your IdP. `domainVerified` used to be staff-attested,\n * which is exactly the human step self-serve removes — so the attestation has\n * to be replaced by proof, not deleted.\n *\n * The proof is a DNS TXT record at `_aglyn-challenge.<domain>` carrying a token\n * we generated for THAT org and THAT domain. Only someone who controls the\n * domain's zone can publish it, and a token issued to one org is worthless to\n * another. Nothing reaches `sso.domains` — the array sign-in actually consults\n * — until a lookup has seen the record.\n *\n * DNS resolution mirrors `/api/domains/verify` (AGL-734): pinned public\n * resolvers rather than the runtime's default, because a stale zone once made\n * Vercel's own resolver return NXDOMAIN for records every public resolver could\n * see. The fallback is deliberately narrow — a genuine \"no such record\" answer\n * must stay a failure, and only an unreachable resolver falls through.\n */\n\nimport { promises as dns, Resolver as CallbackResolver } from 'dns'\nimport { randomBytes } from 'crypto'\nimport type { BaseAuth } from 'firebase-admin/auth'\nimport firebaseAdmin from './firebase-admin'\nimport type { DomainProbe } from './sso-drift-logic'\n\nconst auth = () => firebaseAdmin.app().auth()\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Subdomain the challenge record is published at. */\nexport const SSO_CHALLENGE_PREFIX = '_aglyn-challenge'\n\n/** Prefix on the TXT value, so an unrelated record cannot pass by accident. */\nexport const SSO_TXT_PREFIX = 'aglyn-domain-verification='\n\nconst DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/\n\n/** Same pinned resolvers as the custom-domain check — see the header note. */\nconst PUBLIC_RESOLVERS = ['1.1.1.1', '8.8.8.8']\n\n/**\n * Domains nobody may claim for SSO, however well they prove ownership.\n *\n * A consumer mailbox provider is shared by millions of unrelated people, so\n * \"proves control of the zone\" and \"is entitled to govern every account on it\"\n * come apart completely. Verifying `gmail.com` is possible for exactly one\n * party, and routing every Gmail user's sign-in to their IdP is not a thing\n * that party should be able to do either.\n */\nconst PUBLIC_EMAIL_DOMAINS = new Set([\n 'gmail.com',\n 'googlemail.com',\n 'outlook.com',\n 'hotmail.com',\n 'live.com',\n 'msn.com',\n 'yahoo.com',\n 'ymail.com',\n 'aol.com',\n 'icloud.com',\n 'me.com',\n 'mac.com',\n 'proton.me',\n 'protonmail.com',\n 'pm.me',\n 'gmx.com',\n 'gmx.net',\n 'mail.com',\n 'zoho.com',\n 'yandex.com',\n 'fastmail.com',\n 'hey.com',\n 'qq.com',\n '163.com',\n '126.com',\n])\n\nexport function normalizeSsoDomain(input: string): string {\n const raw = String(input ?? '')\n .trim()\n .toLowerCase()\n const at = raw.lastIndexOf('@')\n return (at >= 0 ? raw.slice(at + 1) : raw).replace(/^@+/, '').replace(/\\.$/, '')\n}\n\n/**\n * `{ value, error }` rather than a discriminated union on purpose: an\n * `{ ok: true } | { ok: false }` union does not narrow reliably once it crosses\n * a library boundary in this repo (`strictNullChecks` is off), and the caller\n * ends up unable to reach either arm's fields. Both keys always present, one of\n * them always null.\n */\nexport interface DomainCheck {\n domain: string | null\n error: string | null\n}\n\nexport function validateSsoDomain(input: string): DomainCheck {\n const domain = normalizeSsoDomain(input)\n if (!domain || !DOMAIN_PATTERN.test(domain)) {\n return { domain: null, error: 'Enter a valid domain, for example acme.com' }\n }\n if (PUBLIC_EMAIL_DOMAINS.has(domain)) {\n return {\n domain: null,\n error:\n 'Public email domains cannot be used for SSO — they are shared by ' +\n 'people outside your organization. Use a domain your organization owns.',\n }\n }\n return { domain, error: null }\n}\n\n/**\n * TXT records at the challenge host, lowercased and unwrapped.\n *\n * A TXT answer arrives as an array of string CHUNKS per record (DNS splits\n * strings over 255 bytes), so each record is joined before comparison —\n * otherwise a long token would never match.\n */\nexport async function resolveChallengeTxt(domain: string): Promise<string[]> {\n const host = `${SSO_CHALLENGE_PREFIX}.${domain}`\n const flatten = (records: string[][]) =>\n records.map((chunks) => chunks.join('').trim())\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n const records = await new Promise<string[][]>((resolve, reject) => {\n resolver.resolveTxt(host, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n return flatten(records)\n } catch (error) {\n // ENOTFOUND/ENODATA are real answers — the name has no TXT record. Only an\n // unreachable resolver falls through, so a genuine miss stays a failure.\n const code = (error as NodeJS.ErrnoException)?.code\n if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {\n return []\n }\n try {\n return flatten(await dns.resolveTxt(host))\n } catch {\n return []\n }\n }\n}\n\n/** The exact TXT value an org must publish for a domain. */\nexport function challengeValue(token: string): string {\n return `${SSO_TXT_PREFIX}${token}`\n}\n\n/**\n * Does this set of TXT records prove control of the zone for THIS token?\n *\n * Extracted so the comparison that domain verification rests on is reachable\n * from a test without standing up Firestore. It is deliberately an exact match\n * on a whole record: a substring test would accept\n * `aglyn-domain-verification=<token>-and-more`, and a prefix test would accept\n * any record that merely starts the same way. Neither proves anything.\n */\nexport function recordsProveOwnership(\n records: readonly string[],\n token: string,\n): boolean {\n if (!token) return false\n return records.includes(challengeValue(token))\n}\n\n/*==========================================\n * PERIODIC RE-VERIFICATION (AGL-1210, the residual the 2026-08-23 audit named).\n *\n * A domain is proven ONCE, when an admin presses Verify, and then routes that\n * domain's sign-ins forever. A company that lets its domain lapse — or sells\n * it — keeps the routing until a human revokes it. The audit called that\n * \"the account-takeover shape in slow motion\", and it is the last residual on\n * an otherwise strong proof.\n *\n * ## Why this REPORTS and never revokes\n *\n * The obvious fix — re-run the lookup, drop the domain when it fails — is a\n * worse bug than the one it closes. `resolveChallengeTxt` cannot tell \"the\n * record is gone\" from \"the resolver did not answer\", because BOTH return an\n * empty array. So a resolver blip during the sweep looks exactly like every\n * customer simultaneously deleting their TXT record, and an automated revoke\n * would log out every enterprise on the platform at once. That is the\n * `reverify-plugin-versions` argument — a lint that can stop a plugin in every\n * workspace is a kill switch with no human in it — and the lockdown argument,\n * where an unreachable Firestore is an outage rather than a verdict.\n *\n * So this half adds two things and deliberately nothing else:\n *\n * 1. {@link probeChallengeTxt} — a THIRD state. `unreachable` is not\n * evidence, and is never counted as a failure.\n * 2. {@link assessDomainDrift} — consecutive CONCLUSIVE failures over a\n * minimum wall-clock age before a domain is even reported as drifted.\n *\n * Revocation stays exactly where it was: {@link revokeDomain}, an explicit act\n * by a person. Detection with a human decision beats an automated action that\n * can log out a paying customer.\n *\n * ## Why the risk tolerates a slow answer\n *\n * The threat needs a domain to lapse, clear ~30 days of registrar grace and\n * ~30 days of redemption, drop, and be re-bought. That is months, not days.\n * And the first harm is not silent credential theft: routing still points at\n * the ORIGINAL org's IdP, where the new owner's staff have no account. The\n * concrete harm is that the new legitimate owner cannot claim their own domain\n * (`issueDomainClaim` refuses a domain another org already routes) and their\n * users are misdirected. Weeks of grace cost that risk almost nothing, and buy\n * immunity from the resolver blip that would otherwise be self-inflicted.\n *=========================================*/\n\n/**\n * The pure half of re-verification — the probe STATES and the decision made\n * from them — lives in `sso-drift-logic.ts` and is re-exported here so the\n * public surface is one module. It has no imports at all, which is what lets\n * the console route's spec run the REAL decision against faked I/O.\n */\nexport {\n assessDomainDrift,\n SSO_DRIFT_FAILURES_BEFORE_REPORT,\n SSO_DRIFT_MIN_AGE_MS,\n type DomainDriftAction,\n type DomainDriftState,\n type DomainDriftVerdict,\n type DomainProbe,\n type DomainProbeStatus,\n} from './sso-drift-logic'\n\n/**\n * Re-check a claim's TXT record, distinguishing silence from absence.\n *\n * Same pinned public resolvers and same fallback as {@link resolveChallengeTxt}\n * — this is not a second opinion about DNS, it is the same lookup reporting one\n * more bit. NXDOMAIN/ENOTFOUND/ENODATA are ANSWERS (\"that name has no TXT\n * record\") and stay conclusive; anything else from both the pinned resolvers\n * and the runtime fallback is `unreachable`.\n *\n * Never throws: a sweep across every org must not stop at the first bad zone.\n */\nexport async function probeChallengeTxt(\n domain: string,\n token: string,\n): Promise<DomainProbe> {\n const host = `${SSO_CHALLENGE_PREFIX}.${domain}`\n const flatten = (records: string[][]) =>\n records.map((chunks) => chunks.join('').trim())\n const settle = (records: string[]): DomainProbe => ({\n status: recordsProveOwnership(records, token) ? 'proven' : 'missing',\n records: records.slice(0, 5),\n })\n /** Codes that are a real answer rather than a failure to get one. */\n const conclusive = (code: string) =>\n code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN'\n\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n const records = await new Promise<string[][]>((resolve, reject) => {\n resolver.resolveTxt(host, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n return settle(flatten(records))\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code\n if (conclusive(code)) return settle([])\n try {\n return settle(flatten(await dns.resolveTxt(host)))\n } catch (fallbackError) {\n const fallbackCode = (fallbackError as NodeJS.ErrnoException)?.code\n // The pinned resolvers gave us nothing usable. Only the fallback's own\n // answer can still make this conclusive; otherwise we genuinely do not\n // know, and saying so is the entire feature.\n if (conclusive(fallbackCode)) return settle([])\n return { status: 'unreachable', records: [] }\n }\n }\n}\n\nexport interface SsoDomainClaimView {\n domain: string\n token: string\n verified: boolean\n /** Fully-qualified host the record goes on. */\n recordHost: string\n /** Exact value the record must carry. */\n recordValue: string\n lastRecords?: string[]\n}\n\nconst claimRef = (orgId: string, domain: string) =>\n firestore().collection('orgs').doc(orgId).collection('ssoDomains').doc(domain)\n\n/**\n * Start (or re-read) a claim on a domain. Idempotent: an existing claim keeps\n * its token, because reissuing would invalidate a record the customer may have\n * already published and turn a working setup into a mysterious failure.\n */\nexport async function issueDomainClaim(\n orgId: string,\n rawDomain: string,\n): Promise<{ claim: SsoDomainClaimView | null; error: string | null }> {\n const { domain, error } = validateSsoDomain(rawDomain)\n if (!domain) return { claim: null, error: error ?? 'Invalid domain' }\n\n // One domain, one org. Without this a second org could hold a live claim on\n // a domain already governed elsewhere and race it at verification time.\n const existing = await firestore()\n .collection('ssoDomains')\n .doc(domain)\n .get()\n if (existing.exists && existing.get('orgId') !== orgId) {\n return {\n claim: null,\n error: 'That domain is already verified by another organization.',\n }\n }\n\n const ref = claimRef(orgId, domain)\n const snapshot = await ref.get()\n const stored = snapshot.exists\n ? (snapshot.get('token') as string | undefined)\n : undefined\n const token = stored || randomBytes(24).toString('base64url')\n if (!snapshot.exists) {\n await ref.set({\n domain,\n token,\n verified: false,\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n } else if (!stored) {\n // A claim document that EXISTS but carries NO token is a shape AGL-1887\n // introduced: {@link attestSsoDomain} writes the attestation marker and\n // nothing else, because a staff attestation has no DNS challenge behind\n // it. Before self-serve, every claim document was created here and so\n // always had a token — `exists` and `has a token` were the same fact.\n //\n // They are not any more, and conflating them broke the upgrade path for\n // exactly the orgs AGL-1887 exists to serve. `exists` alone decided\n // whether to persist, so \"Set up DNS proof\" on an attested domain minted\n // a token, showed the admin a TXT record built from it, and stored it\n // NOWHERE — a different value on every click. `verifyDomainClaim` re-reads\n // `snapshot.get('token')`, finds `undefined`, and could never match the\n // record they had just published. An attested domain could never become a\n // verified one.\n //\n // MERGE, and `verified` is deliberately NOT written: the attestation has\n // to survive being upgraded, and a claim already midway through DNS is not\n // this branch's to demote.\n await ref.set({ domain, token }, { merge: true })\n }\n return {\n error: null,\n claim: {\n domain,\n token,\n verified: Boolean(snapshot.get('verified')),\n recordHost: `${SSO_CHALLENGE_PREFIX}.${domain}`,\n recordValue: challengeValue(token),\n lastRecords: snapshot.get('lastRecords') as string[] | undefined,\n },\n }\n}\n\nexport interface DomainVerifyResult {\n domain: string\n verified: boolean\n /** What the lookup actually saw — the difference between \"missing\" and \"wrong\". */\n records: string[]\n expected: string\n}\n\n/**\n * Check a claim against live DNS and, on success, promote the domain into\n * `sso.domains` — the array that sign-in consults.\n *\n * Failure is recorded but never destructive: a transient DNS outage must not\n * silently un-govern a domain mid-flight. Removal is `revokeDomain`, which is\n * an explicit act.\n */\nexport async function verifyDomainClaim(\n orgId: string,\n rawDomain: string,\n): Promise<{ result: DomainVerifyResult | null; error: string | null }> {\n const { domain, error } = validateSsoDomain(rawDomain)\n if (!domain) return { result: null, error: error ?? 'Invalid domain' }\n\n const ref = claimRef(orgId, domain)\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n return { result: null, error: 'No claim on that domain — add it first.' }\n }\n const token = snapshot.get('token') as string\n const expected = challengeValue(token)\n const records = await resolveChallengeTxt(domain)\n const verified = recordsProveOwnership(records, token)\n\n await ref.set(\n {\n verified,\n lastCheckedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n ...(verified\n ? {\n verifiedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n lastRecords: firebaseAdmin.firestore.FieldValue.delete(),\n }\n : { lastRecords: records.slice(0, 5) }),\n },\n { merge: true },\n )\n\n if (verified) {\n await firestore()\n .collection('orgs')\n .doc(orgId)\n .set(\n {\n sso: {\n domains: firebaseAdmin.firestore.FieldValue.arrayUnion(domain),\n domainVerified: true,\n },\n },\n { merge: true },\n )\n }\n\n return { error: null, result: { domain, verified, records, expected } }\n}\n\n/**\n * Drop a domain: out of `sso.domains`, and its public routing doc deactivated.\n *\n * Order matters. The public doc goes first, because it is the one an attacker\n * would benefit from: while it says `active`, sign-ins for the domain still\n * route to this org's IdP regardless of what the org doc says.\n */\nexport async function revokeDomain(\n orgId: string,\n rawDomain: string,\n): Promise<void> {\n const domain = normalizeSsoDomain(rawDomain)\n if (!domain) return\n const publicRef = firestore().collection('ssoDomains').doc(domain)\n const publicSnapshot = await publicRef.get()\n if (publicSnapshot.exists && publicSnapshot.get('orgId') === orgId) {\n await publicRef.set({ active: false }, { merge: true })\n }\n await firestore()\n .collection('orgs')\n .doc(orgId)\n .set(\n {\n sso: {\n domains: firebaseAdmin.firestore.FieldValue.arrayRemove(domain),\n },\n },\n { merge: true },\n )\n await claimRef(orgId, domain).delete().catch(() => undefined)\n}\n\n/**\n * What the customer needs to type into their IdP. Derived, never stored —\n * these are properties of OUR deployment, and a stale stored copy would send\n * somebody to configure an ACS URL we no longer serve.\n *\n * The callback is Firebase Auth's own handler on the project `authDomain`;\n * `rpEntityId` is the relying-party entity id their IdP will see.\n */\nexport interface SsoServiceMetadata {\n acsUrl: string\n entityId: string\n authDomain: string\n}\n\n/**\n * Thrown by `ssoServiceMetadata()` when this deployment has no auth origin at\n * all (AGL-2020).\n *\n * Deliberately names the variables and NOT a value: handing the operator\n * a `*.firebaseapp.com` example here is how they end up pasting somebody\n * else's project id into their IdP. `sso-provisioning.spec.ts` asserts this\n * string mentions no Aglyn host.\n */\nexport const SSO_AUTH_ORIGIN_UNCONFIGURED_MESSAGE =\n 'Single sign-on is not configured for this deployment: no auth origin ' +\n 'could be resolved. Set NEXT_PUBLIC_FIREBASE_PROJECT_ID — or one of ' +\n 'NEXT_PUBLIC_FIREBASE_AUTH_HANDLER_HOST, NEXT_PUBLIC_WORKSPACE_DOMAIN or ' +\n 'NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN — and rebuild.'\n\n/**\n * A HOST, never a URL.\n *\n * These strings are compared byte for byte — by GCIP against the assertion's\n * Audience, and by the IdP against the Reply URL it posts to. An operator who\n * pastes `https://auth.aglyn.com/` into the env var would otherwise produce\n * `https://https://auth.aglyn.com//__/auth/handler` and reject every\n * assertion, which presents as \"SSO stopped working\" with nothing in the\n * config that looks wrong.\n */\nfunction normalizeAuthHost(value: string): string {\n return String(value ?? '')\n .trim()\n .replace(/^https?:\\/\\//i, '')\n .replace(/\\/.*$/, '')\n .toLowerCase()\n}\n\n/**\n * The auth origin this deployment actually serves (AGL-1381).\n *\n * Mirrors `resolveFirebaseAuthDomain()` in the client's `firebase-config`: on a\n * workspace deployment the whole OAuth/SAML handshake is funnelled through one\n * dedicated same-site origin, `auth.<workspaceDomain>`, which reverse-proxies\n * Firebase's `/__/auth/*` helpers (AGL-462). The IdP has to post the assertion\n * to THAT origin — the one holding the pending-redirect state — or browser\n * storage partitioning severs the two halves of the flow.\n *\n * The order is load-bearing:\n *\n * 1. `NEXT_PUBLIC_FIREBASE_AUTH_HANDLER_HOST` — an explicit override wins.\n * 2. `auth.<NEXT_PUBLIC_WORKSPACE_DOMAIN>` — the deployed workspace origin.\n * Derived only when the variable is actually set, never defaulted: falling\n * back to `auth.aglyn.com` would point a self-hosted install at OUR auth\n * origin, and it would also make the `firebaseapp.com` arm unreachable.\n * It sits ABOVE `AUTH_DOMAIN` because production sets both, and the\n * branded host is the one production serves.\n * 3–4. the project's `*.firebaseapp.com` domain — localhost, previews that\n * are not on the workspace domain, the emulator, and self-host installs\n * that have not stood up an auth subdomain.\n *\n * When all four are absent this THROWS (AGL-2020). It used to default the\n * project id to `aglyn-main` — ours — which is the anti-pattern AGL-1919\n * exists to prevent, and it was silent in both directions that matter:\n * `provisionSsoPool()` wrote our origin into the operator's OWN GCIP provider\n * as `rpEntityId`/`callbackURL`, and the console printed it as the Reply URL\n * for their customer to paste into their IdP. A third party's SAML assertions\n * would then be posted at infrastructure the operator does not run.\n *\n * Throwing rather than degrading is deliberate, and this is the one place in\n * the self-host audit where \"run with the feature off\" is not available: there\n * is no empty value to fall back to. `authDomain: ''` emits\n * `https:///__/auth/handler`, which GCIP accepts on write and which then\n * rejects every assertion afterwards with nothing in the config that looks\n * wrong — the same \"looks configured, works never\" shape as an App Check\n * provider built on `undefined`. SSO is opt-in and deliberately configured, so\n * an operator reaching this has asked for it; a named error telling them which\n * variable to set is strictly better than either wrong origin.\n *\n * The READ path degrades instead of 500ing: `/api/orgs/sso?action=status`\n * catches this and returns `metadata: null` with the message, so the settings\n * page renders the reason rather than a wrong instruction. The WRITE path\n * (`provisionSsoPool`) lets it fly.\n *\n * `entityId` carries the scheme. It is not cosmetic: live GCIP for the first\n * SSO org holds `https://auth.aglyn.com`, and Google Workspace is already\n * sending that exact Audience. Emitting the bare host here would be written\n * over the working config by the next `provisionSsoPool()` save and lock out\n * every SSO-only user in the org. `sso-provisioning.spec.ts` pins both strings\n * character for character for that reason.\n */\nexport function ssoServiceMetadata(): SsoServiceMetadata {\n const workspaceDomain = normalizeAuthHost(\n process.env['NEXT_PUBLIC_WORKSPACE_DOMAIN'],\n )\n const projectId = String(\n process.env['NEXT_PUBLIC_FIREBASE_PROJECT_ID'] ?? '',\n ).trim()\n const authDomain =\n normalizeAuthHost(process.env['NEXT_PUBLIC_FIREBASE_AUTH_HANDLER_HOST']) ||\n (workspaceDomain ? `auth.${workspaceDomain}` : '') ||\n normalizeAuthHost(process.env['NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN']) ||\n (projectId ? `${projectId}.firebaseapp.com` : '')\n if (!authDomain) throw new Error(SSO_AUTH_ORIGIN_UNCONFIGURED_MESSAGE)\n return {\n authDomain,\n acsUrl: `https://${authDomain}/__/auth/handler`,\n entityId: `https://${authDomain}`,\n }\n}\n\n/**\n * GCIP display names are constrained (4–20 chars, must start with a letter,\n * letters/digits/hyphens only). An org slug can violate every one of those, so\n * derive rather than pass through — a rejected display name would surface as an\n * opaque provisioning failure at the worst moment.\n */\nexport function poolDisplayName(orgSlug: string, orgId: string): string {\n const base = `${orgSlug || orgId}`\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '')\n .replace(/^[^a-z]+/, '')\n const padded = (base || 'org').slice(0, 20)\n return padded.length >= 4 ? padded : `${padded}-org`.slice(0, 20)\n}\n\nexport interface SamlIdpMetadata {\n entityId: string\n ssoUrl: string\n certificates: string[]\n}\n\nexport interface ProvisionResult {\n tenantId: string\n providerId: string\n /** True when this call created the pool rather than reusing one. */\n createdPool: boolean\n /** True when this call created the provider rather than updating one. */\n createdProvider: boolean\n}\n\n/**\n * Create (or update) the org's GCIP pool and its SAML provider.\n *\n * Idempotent by construction: an org that already has a `tenantId` reuses it,\n * and a provider that already exists is UPDATED rather than recreated. Creating\n * a second pool would strand every user in the first one — they are separate\n * user namespaces, so \"just make a new one\" silently locks out everybody who\n * has already signed in.\n */\nexport async function provisionSsoPool(options: {\n orgId: string\n orgSlug: string\n existingTenantId?: string\n existingProviderId?: string\n displayName: string\n idp: SamlIdpMetadata\n}): Promise<ProvisionResult> {\n const { orgId, orgSlug, existingTenantId, existingProviderId, idp } = options\n const manager = auth().tenantManager()\n const metadata = ssoServiceMetadata()\n\n let tenantId = existingTenantId\n let createdPool = false\n if (!tenantId) {\n const tenant = await manager.createTenant({\n displayName: poolDisplayName(orgSlug, orgId),\n emailSignInConfig: { enabled: false, passwordRequired: false },\n })\n tenantId = tenant.tenantId\n createdPool = true\n }\n\n const tenantAuth: BaseAuth = manager.authForTenant(tenantId)\n const providerId = existingProviderId || `saml.${poolDisplayName(orgSlug, orgId)}`\n const config = {\n displayName: options.displayName || 'Single sign-on',\n enabled: true,\n idpEntityId: idp.entityId,\n ssoURL: idp.ssoUrl,\n x509Certificates: idp.certificates,\n rpEntityId: metadata.entityId,\n callbackURL: metadata.acsUrl,\n }\n\n let createdProvider = false\n try {\n await tenantAuth.getProviderConfig(providerId)\n await tenantAuth.updateProviderConfig(providerId, config)\n } catch {\n await tenantAuth.createProviderConfig({ providerId, ...config })\n createdProvider = true\n }\n\n return { tenantId, providerId, createdPool, createdProvider }\n}\n\n/**\n * Is this claim a STAFF ATTESTATION that the org owns the domain? (AGL-1887)\n *\n * The second of exactly two ways a domain can be proven, and the one that\n * exists for orgs onboarded before self-serve. Their domain was written onto\n * `sso.domains` by a person who checked, with no claim document behind it — so\n * `unpublishSsoDomains` deactivated their routing happily and\n * `publishSsoDomains` then refused to bring it back. Off worked, on did not,\n * and for `aglyn-org` the owner's only credential lives inside the pool that\n * stops answering (AGL-1888).\n *\n * A POSITIVE MARKER, never an absence. The rejected alternative was to treat\n * \"a routing doc already exists naming this org\" as permission to re-publish,\n * which makes `unpublish` non-final and would let a domain whose claim was\n * revoked come back. What is trusted here is a field a staff member wrote on\n * purpose, and it says WHO, so the trust is attributable.\n *\n * WHY THIS IS NOT A CLIENT-REACHABLE HOLE, which is the only question that\n * matters about it:\n *\n * - `orgs/{orgId}/ssoDomains/{domain}` is `allow read, write: if false` in\n * `cloud/firebase-firestore.rules` — deny-all for every client, reads\n * included. Only the Admin SDK, which bypasses rules, can write here.\n * - No customer-reachable route writes this field. `issueDomainClaim` is the\n * only claim writer on the org's own path and it writes `domain`, `token`,\n * `verified: false` and `createdAt` — never `attestedBy`.\n * - {@link attestSsoDomain} is the only writer, and it is staff-only by\n * construction: it lives here, server-side, and takes the attesting uid.\n *\n * That is why AGL-1887's proposed rules change is NOT part of this: the\n * subcollection is already deny-all, and adding a rule permitting a narrower\n * write than \"none\" would loosen it, not tighten it.\n *\n * A non-empty STRING, checked strictly. `true`, `1` or `{}` are not an\n * attestation by anybody, and a field that can be satisfied by any truthy\n * value is one a future careless write can satisfy by accident.\n */\nexport function isStaffAttestedClaim(attestedBy: unknown): boolean {\n return typeof attestedBy === 'string' && attestedBy.trim().length > 0\n}\n\n/**\n * Record that staff have verified, out of band, that an org owns a domain\n * (AGL-1887).\n *\n * This is the write half of the attestation {@link isStaffAttestedClaim}\n * reads, and it exists so there is exactly ONE way the marker can be created\n * and it is a named function with an actor on it — rather than a field somebody\n * sets by hand in the Firebase console with no record of who or why.\n *\n * `verified` is left FALSE and untouched. The two facts are different: DNS\n * verification is a proof we re-ran ourselves, an attestation is a person\n * vouching. Collapsing them would make an attested domain indistinguishable\n * from a DNS-proven one in the data, and the `verified` flag is what\n * `verifyDomainClaim` owns.\n *\n * Not exposed through `/api/orgs/sso`, deliberately. An org admin proving\n * their own domain has DNS for that; an attestation is us saying we checked,\n * and a customer-reachable path that wrote it would be a customer-reachable\n * path to publishing any domain.\n */\nexport async function attestSsoDomain(options: {\n orgId: string\n domain: string\n /** The staff member vouching. Recorded, and required. */\n attestedByUid: string\n note?: string | null\n}): Promise<{ domain: string | null; error: string | null }> {\n const { domain, error } = validateSsoDomain(options.domain)\n if (!domain) return { domain: null, error: error ?? 'Invalid domain' }\n if (!isStaffAttestedClaim(options.attestedByUid)) {\n return { domain: null, error: 'An attestation needs the staff uid making it.' }\n }\n\n // Same uniqueness rule `issueDomainClaim` enforces. An attestation must not\n // be a way around \"one domain, one org\" — if another org already holds live\n // routing for this domain, that conflict is resolved by a human before\n // anything is written, not by whoever attests last.\n const existing = await firestore().collection('ssoDomains').doc(domain).get()\n if (existing.exists && existing.get('orgId') !== options.orgId) {\n return {\n domain: null,\n error: 'That domain is already verified by another organization.',\n }\n }\n\n await claimRef(options.orgId, domain).set(\n {\n domain,\n attestedBy: options.attestedByUid.trim(),\n attestedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n attestationNote: options.note?.trim() || null,\n },\n // MERGE, so an existing claim keeps its token and its `verified` state. A\n // fresh document is created for the pre-self-serve orgs that have none,\n // which is the whole point, but an attestation must never reset a claim\n // the org is midway through proving by DNS.\n { merge: true },\n )\n return { domain, error: null }\n}\n\n/**\n * Publish the public routing docs — the last step, and the one that actually\n * turns SSO on for a domain.\n *\n * Only PROVEN domains are written — DNS-verified, or staff-attested per\n * {@link isStaffAttestedClaim}. This function is the single writer of\n * `ssoDomains`, so the invariant \"a live routing doc implies proven ownership\"\n * is enforceable by reading one place.\n */\nexport async function publishSsoDomains(options: {\n orgId: string\n tenantId: string\n providerId: string\n protocol: 'saml' | 'oidc'\n displayName?: string\n domains: string[]\n}): Promise<string[]> {\n const { orgId, tenantId, providerId, protocol, displayName } = options\n const published: string[] = []\n const batch = firestore().batch()\n for (const raw of options.domains) {\n const domain = normalizeSsoDomain(raw)\n if (!domain) continue\n // Re-read the claim rather than trusting the caller's list: this is the\n // boundary where an unverified domain would become live, so the check\n // belongs here and not only at the call site.\n //\n // TWO ways to be proven, and no third (AGL-1887). `verified === true` is\n // DNS, re-checked by us; `attestedBy` is a named staff member vouching for\n // an org onboarded before self-serve existed. Both are POSITIVE markers on\n // the org's own claim document, which no client can write.\n //\n // What this must never become is an unconditional accept, or an inference\n // from the routing doc already existing. That check is what stops an org\n // publishing routing for a domain it does not own and intercepting another\n // company's sign-ins — see `sso-publish-gate.emulator.spec.ts`, which\n // exercises every refusal branch, and `sso-attested-restore.spec.ts`,\n // which pins the boundary this loosening must not cross.\n const claim = await claimRef(orgId, domain).get()\n if (!claim.exists) continue\n const proven =\n claim.get('verified') === true ||\n isStaffAttestedClaim(claim.get('attestedBy'))\n if (!proven) continue\n batch.set(\n firestore().collection('ssoDomains').doc(domain),\n {\n orgId,\n tenantId,\n providerId,\n protocol,\n displayName: displayName ?? null,\n active: true,\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n published.push(domain)\n }\n await batch.commit()\n return published\n}\n\n/** Deactivate every routing doc this org owns (disable, not delete). */\nexport async function unpublishSsoDomains(orgId: string): Promise<void> {\n const owned = await firestore()\n .collection('ssoDomains')\n .where('orgId', '==', orgId)\n .get()\n if (owned.empty) return\n const batch = firestore().batch()\n owned.docs.forEach((doc) => batch.set(doc.ref, { active: false }, { merge: true }))\n await batch.commit()\n}\n"],"names":["promises","dns","Resolver","CallbackResolver","randomBytes","firebaseAdmin","auth","app","firestore","SSO_CHALLENGE_PREFIX","SSO_TXT_PREFIX","DOMAIN_PATTERN","PUBLIC_RESOLVERS","PUBLIC_EMAIL_DOMAINS","Set","normalizeSsoDomain","input","raw","String","trim","toLowerCase","at","lastIndexOf","slice","replace","validateSsoDomain","domain","test","error","has","resolveChallengeTxt","host","flatten","records","map","chunks","join","resolver","setServers","Promise","resolve","reject","resolveTxt","addresses","code","challengeValue","token","recordsProveOwnership","includes","assessDomainDrift","SSO_DRIFT_FAILURES_BEFORE_REPORT","SSO_DRIFT_MIN_AGE_MS","probeChallengeTxt","settle","status","conclusive","fallbackError","fallbackCode","claimRef","orgId","collection","doc","issueDomainClaim","rawDomain","claim","existing","get","exists","ref","snapshot","stored","undefined","toString","set","verified","createdAt","FieldValue","serverTimestamp","merge","Boolean","recordHost","recordValue","lastRecords","verifyDomainClaim","result","expected","lastCheckedAt","verifiedAt","delete","sso","domains","arrayUnion","domainVerified","revokeDomain","publicRef","publicSnapshot","active","arrayRemove","catch","SSO_AUTH_ORIGIN_UNCONFIGURED_MESSAGE","normalizeAuthHost","value","ssoServiceMetadata","process","workspaceDomain","env","projectId","authDomain","Error","acsUrl","entityId","poolDisplayName","orgSlug","base","padded","length","provisionSsoPool","options","existingTenantId","existingProviderId","idp","manager","tenantManager","metadata","tenantId","createdPool","tenant","createTenant","displayName","emailSignInConfig","enabled","passwordRequired","tenantAuth","authForTenant","providerId","config","idpEntityId","ssoURL","ssoUrl","x509Certificates","certificates","rpEntityId","callbackURL","createdProvider","getProviderConfig","updateProviderConfig","createProviderConfig","isStaffAttestedClaim","attestedBy","attestSsoDomain","attestedByUid","attestedAt","attestationNote","note","publishSsoDomains","protocol","published","batch","proven","updatedAt","push","commit","unpublishSsoDomains","owned","where","empty","docs","forEach"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GAED,SAASA,YAAYC,GAAG,EAAEC,YAAYC,gBAAgB,QAAQ,MAAK;AACnE,SAASC,WAAW,QAAQ,SAAQ;AAEpC,OAAOC,mBAAmB,sBAAkB;AAG5C,MAAMC,OAAO,IAAMD,cAAcE,GAAG,GAAGD,IAAI;AAC3C,MAAME,YAAY,IAAMH,cAAcE,GAAG,GAAGC,SAAS;AAErD,oDAAoD,GACpD,OAAO,MAAMC,uBAAuB,mBAAkB;AAEtD,6EAA6E,GAC7E,OAAO,MAAMC,iBAAiB,6BAA4B;AAE1D,MAAMC,iBAAiB;AAEvB,4EAA4E,GAC5E,MAAMC,mBAAmB;IAAC;IAAW;CAAU;AAE/C;;;;;;;;CAQC,GAC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B,MAAMR,QAAQrJ,YAAYqJ,KAAK;IAC/BM,MAAMG,IAAI,CAACC,OAAO,CAAC,CAAC1G,MAAQgG,MAAMpF,GAAG,CAACZ,IAAIO,GAAG,EAAE;YAAE4B,QAAQ;QAAM,GAAG;YAAElB,OAAO;QAAK;IAChF,MAAM+E,MAAMI,MAAM;AACpB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/sso-provisioning.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 * Self-serve enterprise SSO provisioning (AGL-1210).\n *\n * Before this, `tenantManager()` appeared six times in the repo and every one\n * was `authForTenant(...)` — authenticating against a pool somebody had made by\n * hand in the Firebase console. There was no `createTenant` and no\n * `createProviderConfig` anywhere, so onboarding an SSO org meant a person\n * clicking through GCIP and then writing `tenantId`/`providerId` onto the org\n * doc. This module is the write half that removes that step.\n *\n * ## Domain verification is the security gate, not a formality\n *\n * `ssoDomains/{domain}` routes every sign-in for a domain to whichever org\n * claims it. Letting an org self-assert that claim would be an\n * account-takeover vector: claim `competitor.com`, and their employees' sign-in\n * attempts arrive at your IdP. `domainVerified` used to be staff-attested,\n * which is exactly the human step self-serve removes — so the attestation has\n * to be replaced by proof, not deleted.\n *\n * The proof is a DNS TXT record at `_aglyn-challenge.<domain>` carrying a token\n * we generated for THAT org and THAT domain. Only someone who controls the\n * domain's zone can publish it, and a token issued to one org is worthless to\n * another. Nothing reaches `sso.domains` — the array sign-in actually consults\n * — until a lookup has seen the record.\n *\n * DNS resolution mirrors `/api/domains/verify` (AGL-734): pinned public\n * resolvers rather than the runtime's default, because a stale zone once made\n * Vercel's own resolver return NXDOMAIN for records every public resolver could\n * see. The fallback is deliberately narrow — a genuine \"no such record\" answer\n * must stay a failure, and only an unreachable resolver falls through.\n */\n\nimport { promises as dns, Resolver as CallbackResolver } from 'dns'\nimport { randomBytes } from 'crypto'\nimport type { BaseAuth } from 'firebase-admin/auth'\nimport firebaseAdmin from './firebase-admin'\nimport type { DomainProbe } from './sso-drift-logic'\n\nconst auth = () => firebaseAdmin.app().auth()\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/** Subdomain the challenge record is published at. */\nexport const SSO_CHALLENGE_PREFIX = '_aglyn-challenge'\n\n/** Prefix on the TXT value, so an unrelated record cannot pass by accident. */\nexport const SSO_TXT_PREFIX = 'aglyn-domain-verification='\n\nconst DOMAIN_PATTERN = /^(?!-)[a-z0-9-]{1,63}(\\.[a-z0-9-]{1,63})+$/\n\n/** Same pinned resolvers as the custom-domain check — see the header note. */\nconst PUBLIC_RESOLVERS = ['1.1.1.1', '8.8.8.8']\n\n/**\n * Domains nobody may claim for SSO, however well they prove ownership.\n *\n * A consumer mailbox provider is shared by millions of unrelated people, so\n * \"proves control of the zone\" and \"is entitled to govern every account on it\"\n * come apart completely. Verifying `gmail.com` is possible for exactly one\n * party, and routing every Gmail user's sign-in to their IdP is not a thing\n * that party should be able to do either.\n */\nconst PUBLIC_EMAIL_DOMAINS = new Set([\n 'gmail.com',\n 'googlemail.com',\n 'outlook.com',\n 'hotmail.com',\n 'live.com',\n 'msn.com',\n 'yahoo.com',\n 'ymail.com',\n 'aol.com',\n 'icloud.com',\n 'me.com',\n 'mac.com',\n 'proton.me',\n 'protonmail.com',\n 'pm.me',\n 'gmx.com',\n 'gmx.net',\n 'mail.com',\n 'zoho.com',\n 'yandex.com',\n 'fastmail.com',\n 'hey.com',\n 'qq.com',\n '163.com',\n '126.com',\n])\n\n/**\n * Whether `domain` is a consumer mailbox provider's, shared by people who\n * have nothing to do with each other. A proof of control means nothing there,\n * so neither SSO nor a domain ownership claim accepts one.\n */\nexport function isPublicEmailDomain(domain: string): boolean {\n return PUBLIC_EMAIL_DOMAINS.has(String(domain ?? '').trim().toLowerCase())\n}\n\nexport function normalizeSsoDomain(input: string): string {\n const raw = String(input ?? '')\n .trim()\n .toLowerCase()\n const at = raw.lastIndexOf('@')\n return (at >= 0 ? raw.slice(at + 1) : raw).replace(/^@+/, '').replace(/\\.$/, '')\n}\n\n/**\n * `{ value, error }` rather than a discriminated union on purpose: an\n * `{ ok: true } | { ok: false }` union does not narrow reliably once it crosses\n * a library boundary in this repo (`strictNullChecks` is off), and the caller\n * ends up unable to reach either arm's fields. Both keys always present, one of\n * them always null.\n */\nexport interface DomainCheck {\n domain: string | null\n error: string | null\n}\n\nexport function validateSsoDomain(input: string): DomainCheck {\n const domain = normalizeSsoDomain(input)\n if (!domain || !DOMAIN_PATTERN.test(domain)) {\n return { domain: null, error: 'Enter a valid domain, for example acme.com' }\n }\n if (PUBLIC_EMAIL_DOMAINS.has(domain)) {\n return {\n domain: null,\n error:\n 'Public email domains cannot be used for SSO — they are shared by ' +\n 'people outside your organization. Use a domain your organization owns.',\n }\n }\n return { domain, error: null }\n}\n\n/**\n * TXT records at the challenge host, lowercased and unwrapped.\n *\n * A TXT answer arrives as an array of string CHUNKS per record (DNS splits\n * strings over 255 bytes), so each record is joined before comparison —\n * otherwise a long token would never match.\n */\nexport async function resolveChallengeTxt(domain: string): Promise<string[]> {\n const host = `${SSO_CHALLENGE_PREFIX}.${domain}`\n const flatten = (records: string[][]) =>\n records.map((chunks) => chunks.join('').trim())\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n const records = await new Promise<string[][]>((resolve, reject) => {\n resolver.resolveTxt(host, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n return flatten(records)\n } catch (error) {\n // ENOTFOUND/ENODATA are real answers — the name has no TXT record. Only an\n // unreachable resolver falls through, so a genuine miss stays a failure.\n const code = (error as NodeJS.ErrnoException)?.code\n if (code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN') {\n return []\n }\n try {\n return flatten(await dns.resolveTxt(host))\n } catch {\n return []\n }\n }\n}\n\n/** The exact TXT value an org must publish for a domain. */\nexport function challengeValue(token: string): string {\n return `${SSO_TXT_PREFIX}${token}`\n}\n\n/**\n * Does this set of TXT records prove control of the zone for THIS token?\n *\n * Extracted so the comparison that domain verification rests on is reachable\n * from a test without standing up Firestore. It is deliberately an exact match\n * on a whole record: a substring test would accept\n * `aglyn-domain-verification=<token>-and-more`, and a prefix test would accept\n * any record that merely starts the same way. Neither proves anything.\n */\nexport function recordsProveOwnership(\n records: readonly string[],\n token: string,\n): boolean {\n if (!token) return false\n return records.includes(challengeValue(token))\n}\n\n/*==========================================\n * PERIODIC RE-VERIFICATION (AGL-1210, the residual the 2026-08-23 audit named).\n *\n * A domain is proven ONCE, when an admin presses Verify, and then routes that\n * domain's sign-ins forever. A company that lets its domain lapse — or sells\n * it — keeps the routing until a human revokes it. The audit called that\n * \"the account-takeover shape in slow motion\", and it is the last residual on\n * an otherwise strong proof.\n *\n * ## Why this REPORTS and never revokes\n *\n * The obvious fix — re-run the lookup, drop the domain when it fails — is a\n * worse bug than the one it closes. `resolveChallengeTxt` cannot tell \"the\n * record is gone\" from \"the resolver did not answer\", because BOTH return an\n * empty array. So a resolver blip during the sweep looks exactly like every\n * customer simultaneously deleting their TXT record, and an automated revoke\n * would log out every enterprise on the platform at once. That is the\n * `reverify-plugin-versions` argument — a lint that can stop a plugin in every\n * workspace is a kill switch with no human in it — and the lockdown argument,\n * where an unreachable Firestore is an outage rather than a verdict.\n *\n * So this half adds two things and deliberately nothing else:\n *\n * 1. {@link probeChallengeTxt} — a THIRD state. `unreachable` is not\n * evidence, and is never counted as a failure.\n * 2. {@link assessDomainDrift} — consecutive CONCLUSIVE failures over a\n * minimum wall-clock age before a domain is even reported as drifted.\n *\n * Revocation stays exactly where it was: {@link revokeDomain}, an explicit act\n * by a person. Detection with a human decision beats an automated action that\n * can log out a paying customer.\n *\n * ## Why the risk tolerates a slow answer\n *\n * The threat needs a domain to lapse, clear ~30 days of registrar grace and\n * ~30 days of redemption, drop, and be re-bought. That is months, not days.\n * And the first harm is not silent credential theft: routing still points at\n * the ORIGINAL org's IdP, where the new owner's staff have no account. The\n * concrete harm is that the new legitimate owner cannot claim their own domain\n * (`issueDomainClaim` refuses a domain another org already routes) and their\n * users are misdirected. Weeks of grace cost that risk almost nothing, and buy\n * immunity from the resolver blip that would otherwise be self-inflicted.\n *=========================================*/\n\n/**\n * The pure half of re-verification — the probe STATES and the decision made\n * from them — lives in `sso-drift-logic.ts` and is re-exported here so the\n * public surface is one module. It has no imports at all, which is what lets\n * the console route's spec run the REAL decision against faked I/O.\n */\nexport {\n assessDomainDrift,\n SSO_DRIFT_FAILURES_BEFORE_REPORT,\n SSO_DRIFT_MIN_AGE_MS,\n type DomainDriftAction,\n type DomainDriftState,\n type DomainDriftVerdict,\n type DomainProbe,\n type DomainProbeStatus,\n} from './sso-drift-logic'\n\n/**\n * Re-check a claim's TXT record, distinguishing silence from absence.\n *\n * Same pinned public resolvers and same fallback as {@link resolveChallengeTxt}\n * — this is not a second opinion about DNS, it is the same lookup reporting one\n * more bit. NXDOMAIN/ENOTFOUND/ENODATA are ANSWERS (\"that name has no TXT\n * record\") and stay conclusive; anything else from both the pinned resolvers\n * and the runtime fallback is `unreachable`.\n *\n * Never throws: a sweep across every org must not stop at the first bad zone.\n */\nexport async function probeChallengeTxt(\n domain: string,\n token: string,\n): Promise<DomainProbe> {\n const host = `${SSO_CHALLENGE_PREFIX}.${domain}`\n const flatten = (records: string[][]) =>\n records.map((chunks) => chunks.join('').trim())\n const settle = (records: string[]): DomainProbe => ({\n status: recordsProveOwnership(records, token) ? 'proven' : 'missing',\n records: records.slice(0, 5),\n })\n /** Codes that are a real answer rather than a failure to get one. */\n const conclusive = (code: string) =>\n code === 'ENOTFOUND' || code === 'ENODATA' || code === 'NXDOMAIN'\n\n try {\n const resolver = new CallbackResolver()\n resolver.setServers(PUBLIC_RESOLVERS)\n const records = await new Promise<string[][]>((resolve, reject) => {\n resolver.resolveTxt(host, (error, addresses) =>\n error ? reject(error) : resolve(addresses),\n )\n })\n return settle(flatten(records))\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code\n if (conclusive(code)) return settle([])\n try {\n return settle(flatten(await dns.resolveTxt(host)))\n } catch (fallbackError) {\n const fallbackCode = (fallbackError as NodeJS.ErrnoException)?.code\n // The pinned resolvers gave us nothing usable. Only the fallback's own\n // answer can still make this conclusive; otherwise we genuinely do not\n // know, and saying so is the entire feature.\n if (conclusive(fallbackCode)) return settle([])\n return { status: 'unreachable', records: [] }\n }\n }\n}\n\nexport interface SsoDomainClaimView {\n domain: string\n token: string\n verified: boolean\n /** Fully-qualified host the record goes on. */\n recordHost: string\n /** Exact value the record must carry. */\n recordValue: string\n lastRecords?: string[]\n}\n\nconst claimRef = (orgId: string, domain: string) =>\n firestore().collection('orgs').doc(orgId).collection('ssoDomains').doc(domain)\n\n/**\n * Start (or re-read) a claim on a domain. Idempotent: an existing claim keeps\n * its token, because reissuing would invalidate a record the customer may have\n * already published and turn a working setup into a mysterious failure.\n */\nexport async function issueDomainClaim(\n orgId: string,\n rawDomain: string,\n): Promise<{ claim: SsoDomainClaimView | null; error: string | null }> {\n const { domain, error } = validateSsoDomain(rawDomain)\n if (!domain) return { claim: null, error: error ?? 'Invalid domain' }\n\n // One domain, one org. Without this a second org could hold a live claim on\n // a domain already governed elsewhere and race it at verification time.\n const existing = await firestore()\n .collection('ssoDomains')\n .doc(domain)\n .get()\n if (existing.exists && existing.get('orgId') !== orgId) {\n return {\n claim: null,\n error: 'That domain is already verified by another organization.',\n }\n }\n\n const ref = claimRef(orgId, domain)\n const snapshot = await ref.get()\n const stored = snapshot.exists\n ? (snapshot.get('token') as string | undefined)\n : undefined\n const token = stored || randomBytes(24).toString('base64url')\n if (!snapshot.exists) {\n await ref.set({\n domain,\n token,\n verified: false,\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n })\n } else if (!stored) {\n // A claim document that EXISTS but carries NO token is a shape AGL-1887\n // introduced: {@link attestSsoDomain} writes the attestation marker and\n // nothing else, because a staff attestation has no DNS challenge behind\n // it. Before self-serve, every claim document was created here and so\n // always had a token — `exists` and `has a token` were the same fact.\n //\n // They are not any more, and conflating them broke the upgrade path for\n // exactly the orgs AGL-1887 exists to serve. `exists` alone decided\n // whether to persist, so \"Set up DNS proof\" on an attested domain minted\n // a token, showed the admin a TXT record built from it, and stored it\n // NOWHERE — a different value on every click. `verifyDomainClaim` re-reads\n // `snapshot.get('token')`, finds `undefined`, and could never match the\n // record they had just published. An attested domain could never become a\n // verified one.\n //\n // MERGE, and `verified` is deliberately NOT written: the attestation has\n // to survive being upgraded, and a claim already midway through DNS is not\n // this branch's to demote.\n await ref.set({ domain, token }, { merge: true })\n }\n return {\n error: null,\n claim: {\n domain,\n token,\n verified: Boolean(snapshot.get('verified')),\n recordHost: `${SSO_CHALLENGE_PREFIX}.${domain}`,\n recordValue: challengeValue(token),\n lastRecords: snapshot.get('lastRecords') as string[] | undefined,\n },\n }\n}\n\nexport interface DomainVerifyResult {\n domain: string\n verified: boolean\n /** What the lookup actually saw — the difference between \"missing\" and \"wrong\". */\n records: string[]\n expected: string\n}\n\n/**\n * Check a claim against live DNS and, on success, promote the domain into\n * `sso.domains` — the array that sign-in consults.\n *\n * Failure is recorded but never destructive: a transient DNS outage must not\n * silently un-govern a domain mid-flight. Removal is `revokeDomain`, which is\n * an explicit act.\n */\nexport async function verifyDomainClaim(\n orgId: string,\n rawDomain: string,\n): Promise<{ result: DomainVerifyResult | null; error: string | null }> {\n const { domain, error } = validateSsoDomain(rawDomain)\n if (!domain) return { result: null, error: error ?? 'Invalid domain' }\n\n const ref = claimRef(orgId, domain)\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n return { result: null, error: 'No claim on that domain — add it first.' }\n }\n const token = snapshot.get('token') as string\n const expected = challengeValue(token)\n const records = await resolveChallengeTxt(domain)\n const verified = recordsProveOwnership(records, token)\n\n await ref.set(\n {\n verified,\n lastCheckedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n ...(verified\n ? {\n verifiedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n lastRecords: firebaseAdmin.firestore.FieldValue.delete(),\n }\n : { lastRecords: records.slice(0, 5) }),\n },\n { merge: true },\n )\n\n if (verified) {\n await firestore()\n .collection('orgs')\n .doc(orgId)\n .set(\n {\n sso: {\n domains: firebaseAdmin.firestore.FieldValue.arrayUnion(domain),\n domainVerified: true,\n },\n },\n { merge: true },\n )\n }\n\n return { error: null, result: { domain, verified, records, expected } }\n}\n\n/**\n * Drop a domain: out of `sso.domains`, and its public routing doc deactivated.\n *\n * Order matters. The public doc goes first, because it is the one an attacker\n * would benefit from: while it says `active`, sign-ins for the domain still\n * route to this org's IdP regardless of what the org doc says.\n */\nexport async function revokeDomain(\n orgId: string,\n rawDomain: string,\n): Promise<void> {\n const domain = normalizeSsoDomain(rawDomain)\n if (!domain) return\n const publicRef = firestore().collection('ssoDomains').doc(domain)\n const publicSnapshot = await publicRef.get()\n if (publicSnapshot.exists && publicSnapshot.get('orgId') === orgId) {\n await publicRef.set({ active: false }, { merge: true })\n }\n await firestore()\n .collection('orgs')\n .doc(orgId)\n .set(\n {\n sso: {\n domains: firebaseAdmin.firestore.FieldValue.arrayRemove(domain),\n },\n },\n { merge: true },\n )\n await claimRef(orgId, domain).delete().catch(() => undefined)\n}\n\n/**\n * What the customer needs to type into their IdP. Derived, never stored —\n * these are properties of OUR deployment, and a stale stored copy would send\n * somebody to configure an ACS URL we no longer serve.\n *\n * The callback is Firebase Auth's own handler on the project `authDomain`;\n * `rpEntityId` is the relying-party entity id their IdP will see.\n */\nexport interface SsoServiceMetadata {\n acsUrl: string\n entityId: string\n authDomain: string\n}\n\n/**\n * Thrown by `ssoServiceMetadata()` when this deployment has no auth origin at\n * all (AGL-2020).\n *\n * Deliberately names the variables and NOT a value: handing the operator\n * a `*.firebaseapp.com` example here is how they end up pasting somebody\n * else's project id into their IdP. `sso-provisioning.spec.ts` asserts this\n * string mentions no Aglyn host.\n */\nexport const SSO_AUTH_ORIGIN_UNCONFIGURED_MESSAGE =\n 'Single sign-on is not configured for this deployment: no auth origin ' +\n 'could be resolved. Set NEXT_PUBLIC_FIREBASE_PROJECT_ID — or one of ' +\n 'NEXT_PUBLIC_FIREBASE_AUTH_HANDLER_HOST, NEXT_PUBLIC_WORKSPACE_DOMAIN or ' +\n 'NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN — and rebuild.'\n\n/**\n * A HOST, never a URL.\n *\n * These strings are compared byte for byte — by GCIP against the assertion's\n * Audience, and by the IdP against the Reply URL it posts to. An operator who\n * pastes `https://auth.aglyn.com/` into the env var would otherwise produce\n * `https://https://auth.aglyn.com//__/auth/handler` and reject every\n * assertion, which presents as \"SSO stopped working\" with nothing in the\n * config that looks wrong.\n */\nfunction normalizeAuthHost(value: string): string {\n return String(value ?? '')\n .trim()\n .replace(/^https?:\\/\\//i, '')\n .replace(/\\/.*$/, '')\n .toLowerCase()\n}\n\n/**\n * The auth origin this deployment actually serves (AGL-1381).\n *\n * Mirrors `resolveFirebaseAuthDomain()` in the client's `firebase-config`: on a\n * workspace deployment the whole OAuth/SAML handshake is funnelled through one\n * dedicated same-site origin, `auth.<workspaceDomain>`, which reverse-proxies\n * Firebase's `/__/auth/*` helpers (AGL-462). The IdP has to post the assertion\n * to THAT origin — the one holding the pending-redirect state — or browser\n * storage partitioning severs the two halves of the flow.\n *\n * The order is load-bearing:\n *\n * 1. `NEXT_PUBLIC_FIREBASE_AUTH_HANDLER_HOST` — an explicit override wins.\n * 2. `auth.<NEXT_PUBLIC_WORKSPACE_DOMAIN>` — the deployed workspace origin.\n * Derived only when the variable is actually set, never defaulted: falling\n * back to `auth.aglyn.com` would point a self-hosted install at OUR auth\n * origin, and it would also make the `firebaseapp.com` arm unreachable.\n * It sits ABOVE `AUTH_DOMAIN` because production sets both, and the\n * branded host is the one production serves.\n * 3–4. the project's `*.firebaseapp.com` domain — localhost, previews that\n * are not on the workspace domain, the emulator, and self-host installs\n * that have not stood up an auth subdomain.\n *\n * When all four are absent this THROWS (AGL-2020). It used to default the\n * project id to `aglyn-main` — ours — which is the anti-pattern AGL-1919\n * exists to prevent, and it was silent in both directions that matter:\n * `provisionSsoPool()` wrote our origin into the operator's OWN GCIP provider\n * as `rpEntityId`/`callbackURL`, and the console printed it as the Reply URL\n * for their customer to paste into their IdP. A third party's SAML assertions\n * would then be posted at infrastructure the operator does not run.\n *\n * Throwing rather than degrading is deliberate, and this is the one place in\n * the self-host audit where \"run with the feature off\" is not available: there\n * is no empty value to fall back to. `authDomain: ''` emits\n * `https:///__/auth/handler`, which GCIP accepts on write and which then\n * rejects every assertion afterwards with nothing in the config that looks\n * wrong — the same \"looks configured, works never\" shape as an App Check\n * provider built on `undefined`. SSO is opt-in and deliberately configured, so\n * an operator reaching this has asked for it; a named error telling them which\n * variable to set is strictly better than either wrong origin.\n *\n * The READ path degrades instead of 500ing: `/api/orgs/sso?action=status`\n * catches this and returns `metadata: null` with the message, so the settings\n * page renders the reason rather than a wrong instruction. The WRITE path\n * (`provisionSsoPool`) lets it fly.\n *\n * `entityId` carries the scheme. It is not cosmetic: live GCIP for the first\n * SSO org holds `https://auth.aglyn.com`, and Google Workspace is already\n * sending that exact Audience. Emitting the bare host here would be written\n * over the working config by the next `provisionSsoPool()` save and lock out\n * every SSO-only user in the org. `sso-provisioning.spec.ts` pins both strings\n * character for character for that reason.\n */\nexport function ssoServiceMetadata(): SsoServiceMetadata {\n const workspaceDomain = normalizeAuthHost(\n process.env['NEXT_PUBLIC_WORKSPACE_DOMAIN'],\n )\n const projectId = String(\n process.env['NEXT_PUBLIC_FIREBASE_PROJECT_ID'] ?? '',\n ).trim()\n const authDomain =\n normalizeAuthHost(process.env['NEXT_PUBLIC_FIREBASE_AUTH_HANDLER_HOST']) ||\n (workspaceDomain ? `auth.${workspaceDomain}` : '') ||\n normalizeAuthHost(process.env['NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN']) ||\n (projectId ? `${projectId}.firebaseapp.com` : '')\n if (!authDomain) throw new Error(SSO_AUTH_ORIGIN_UNCONFIGURED_MESSAGE)\n return {\n authDomain,\n acsUrl: `https://${authDomain}/__/auth/handler`,\n entityId: `https://${authDomain}`,\n }\n}\n\n/**\n * GCIP display names are constrained (4–20 chars, must start with a letter,\n * letters/digits/hyphens only). An org slug can violate every one of those, so\n * derive rather than pass through — a rejected display name would surface as an\n * opaque provisioning failure at the worst moment.\n */\nexport function poolDisplayName(orgSlug: string, orgId: string): string {\n const base = `${orgSlug || orgId}`\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '')\n .replace(/^[^a-z]+/, '')\n const padded = (base || 'org').slice(0, 20)\n return padded.length >= 4 ? padded : `${padded}-org`.slice(0, 20)\n}\n\nexport interface SamlIdpMetadata {\n entityId: string\n ssoUrl: string\n certificates: string[]\n}\n\nexport interface ProvisionResult {\n tenantId: string\n providerId: string\n /** True when this call created the pool rather than reusing one. */\n createdPool: boolean\n /** True when this call created the provider rather than updating one. */\n createdProvider: boolean\n}\n\n/**\n * Create (or update) the org's GCIP pool and its SAML provider.\n *\n * Idempotent by construction: an org that already has a `tenantId` reuses it,\n * and a provider that already exists is UPDATED rather than recreated. Creating\n * a second pool would strand every user in the first one — they are separate\n * user namespaces, so \"just make a new one\" silently locks out everybody who\n * has already signed in.\n */\nexport async function provisionSsoPool(options: {\n orgId: string\n orgSlug: string\n existingTenantId?: string\n existingProviderId?: string\n displayName: string\n idp: SamlIdpMetadata\n}): Promise<ProvisionResult> {\n const { orgId, orgSlug, existingTenantId, existingProviderId, idp } = options\n const manager = auth().tenantManager()\n const metadata = ssoServiceMetadata()\n\n let tenantId = existingTenantId\n let createdPool = false\n if (!tenantId) {\n const tenant = await manager.createTenant({\n displayName: poolDisplayName(orgSlug, orgId),\n emailSignInConfig: { enabled: false, passwordRequired: false },\n })\n tenantId = tenant.tenantId\n createdPool = true\n }\n\n const tenantAuth: BaseAuth = manager.authForTenant(tenantId)\n const providerId = existingProviderId || `saml.${poolDisplayName(orgSlug, orgId)}`\n const config = {\n displayName: options.displayName || 'Single sign-on',\n enabled: true,\n idpEntityId: idp.entityId,\n ssoURL: idp.ssoUrl,\n x509Certificates: idp.certificates,\n rpEntityId: metadata.entityId,\n callbackURL: metadata.acsUrl,\n }\n\n let createdProvider = false\n try {\n await tenantAuth.getProviderConfig(providerId)\n await tenantAuth.updateProviderConfig(providerId, config)\n } catch {\n await tenantAuth.createProviderConfig({ providerId, ...config })\n createdProvider = true\n }\n\n return { tenantId, providerId, createdPool, createdProvider }\n}\n\n/**\n * Is this claim a STAFF ATTESTATION that the org owns the domain? (AGL-1887)\n *\n * The second of exactly two ways a domain can be proven, and the one that\n * exists for orgs onboarded before self-serve. Their domain was written onto\n * `sso.domains` by a person who checked, with no claim document behind it — so\n * `unpublishSsoDomains` deactivated their routing happily and\n * `publishSsoDomains` then refused to bring it back. Off worked, on did not,\n * and for `aglyn-org` the owner's only credential lives inside the pool that\n * stops answering (AGL-1888).\n *\n * A POSITIVE MARKER, never an absence. The rejected alternative was to treat\n * \"a routing doc already exists naming this org\" as permission to re-publish,\n * which makes `unpublish` non-final and would let a domain whose claim was\n * revoked come back. What is trusted here is a field a staff member wrote on\n * purpose, and it says WHO, so the trust is attributable.\n *\n * WHY THIS IS NOT A CLIENT-REACHABLE HOLE, which is the only question that\n * matters about it:\n *\n * - `orgs/{orgId}/ssoDomains/{domain}` is `allow read, write: if false` in\n * `cloud/firebase-firestore.rules` — deny-all for every client, reads\n * included. Only the Admin SDK, which bypasses rules, can write here.\n * - No customer-reachable route writes this field. `issueDomainClaim` is the\n * only claim writer on the org's own path and it writes `domain`, `token`,\n * `verified: false` and `createdAt` — never `attestedBy`.\n * - {@link attestSsoDomain} is the only writer, and it is staff-only by\n * construction: it lives here, server-side, and takes the attesting uid.\n *\n * That is why AGL-1887's proposed rules change is NOT part of this: the\n * subcollection is already deny-all, and adding a rule permitting a narrower\n * write than \"none\" would loosen it, not tighten it.\n *\n * A non-empty STRING, checked strictly. `true`, `1` or `{}` are not an\n * attestation by anybody, and a field that can be satisfied by any truthy\n * value is one a future careless write can satisfy by accident.\n */\nexport function isStaffAttestedClaim(attestedBy: unknown): boolean {\n return typeof attestedBy === 'string' && attestedBy.trim().length > 0\n}\n\n/**\n * Record that staff have verified, out of band, that an org owns a domain\n * (AGL-1887).\n *\n * This is the write half of the attestation {@link isStaffAttestedClaim}\n * reads, and it exists so there is exactly ONE way the marker can be created\n * and it is a named function with an actor on it — rather than a field somebody\n * sets by hand in the Firebase console with no record of who or why.\n *\n * `verified` is left FALSE and untouched. The two facts are different: DNS\n * verification is a proof we re-ran ourselves, an attestation is a person\n * vouching. Collapsing them would make an attested domain indistinguishable\n * from a DNS-proven one in the data, and the `verified` flag is what\n * `verifyDomainClaim` owns.\n *\n * Not exposed through `/api/orgs/sso`, deliberately. An org admin proving\n * their own domain has DNS for that; an attestation is us saying we checked,\n * and a customer-reachable path that wrote it would be a customer-reachable\n * path to publishing any domain.\n */\nexport async function attestSsoDomain(options: {\n orgId: string\n domain: string\n /** The staff member vouching. Recorded, and required. */\n attestedByUid: string\n note?: string | null\n}): Promise<{ domain: string | null; error: string | null }> {\n const { domain, error } = validateSsoDomain(options.domain)\n if (!domain) return { domain: null, error: error ?? 'Invalid domain' }\n if (!isStaffAttestedClaim(options.attestedByUid)) {\n return { domain: null, error: 'An attestation needs the staff uid making it.' }\n }\n\n // Same uniqueness rule `issueDomainClaim` enforces. An attestation must not\n // be a way around \"one domain, one org\" — if another org already holds live\n // routing for this domain, that conflict is resolved by a human before\n // anything is written, not by whoever attests last.\n const existing = await firestore().collection('ssoDomains').doc(domain).get()\n if (existing.exists && existing.get('orgId') !== options.orgId) {\n return {\n domain: null,\n error: 'That domain is already verified by another organization.',\n }\n }\n\n await claimRef(options.orgId, domain).set(\n {\n domain,\n attestedBy: options.attestedByUid.trim(),\n attestedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n attestationNote: options.note?.trim() || null,\n },\n // MERGE, so an existing claim keeps its token and its `verified` state. A\n // fresh document is created for the pre-self-serve orgs that have none,\n // which is the whole point, but an attestation must never reset a claim\n // the org is midway through proving by DNS.\n { merge: true },\n )\n return { domain, error: null }\n}\n\n/**\n * Publish the public routing docs — the last step, and the one that actually\n * turns SSO on for a domain.\n *\n * Only PROVEN domains are written — DNS-verified, or staff-attested per\n * {@link isStaffAttestedClaim}. This function is the single writer of\n * `ssoDomains`, so the invariant \"a live routing doc implies proven ownership\"\n * is enforceable by reading one place.\n */\nexport async function publishSsoDomains(options: {\n orgId: string\n tenantId: string\n providerId: string\n protocol: 'saml' | 'oidc'\n displayName?: string\n domains: string[]\n}): Promise<string[]> {\n const { orgId, tenantId, providerId, protocol, displayName } = options\n const published: string[] = []\n const batch = firestore().batch()\n for (const raw of options.domains) {\n const domain = normalizeSsoDomain(raw)\n if (!domain) continue\n // Re-read the claim rather than trusting the caller's list: this is the\n // boundary where an unverified domain would become live, so the check\n // belongs here and not only at the call site.\n //\n // TWO ways to be proven, and no third (AGL-1887). `verified === true` is\n // DNS, re-checked by us; `attestedBy` is a named staff member vouching for\n // an org onboarded before self-serve existed. Both are POSITIVE markers on\n // the org's own claim document, which no client can write.\n //\n // What this must never become is an unconditional accept, or an inference\n // from the routing doc already existing. That check is what stops an org\n // publishing routing for a domain it does not own and intercepting another\n // company's sign-ins — see `sso-publish-gate.emulator.spec.ts`, which\n // exercises every refusal branch, and `sso-attested-restore.spec.ts`,\n // which pins the boundary this loosening must not cross.\n const claim = await claimRef(orgId, domain).get()\n if (!claim.exists) continue\n const proven =\n claim.get('verified') === true ||\n isStaffAttestedClaim(claim.get('attestedBy'))\n if (!proven) continue\n batch.set(\n firestore().collection('ssoDomains').doc(domain),\n {\n orgId,\n tenantId,\n providerId,\n protocol,\n displayName: displayName ?? null,\n active: true,\n updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n published.push(domain)\n }\n await batch.commit()\n return published\n}\n\n/** Deactivate every routing doc this org owns (disable, not delete). */\nexport async function unpublishSsoDomains(orgId: string): Promise<void> {\n const owned = await firestore()\n .collection('ssoDomains')\n .where('orgId', '==', orgId)\n .get()\n if (owned.empty) return\n const batch = firestore().batch()\n owned.docs.forEach((doc) => batch.set(doc.ref, { active: false }, { merge: true }))\n await batch.commit()\n}\n"],"names":["promises","dns","Resolver","CallbackResolver","randomBytes","firebaseAdmin","auth","app","firestore","SSO_CHALLENGE_PREFIX","SSO_TXT_PREFIX","DOMAIN_PATTERN","PUBLIC_RESOLVERS","PUBLIC_EMAIL_DOMAINS","Set","isPublicEmailDomain","domain","has","String","trim","toLowerCase","normalizeSsoDomain","input","raw","at","lastIndexOf","slice","replace","validateSsoDomain","test","error","resolveChallengeTxt","host","flatten","records","map","chunks","join","resolver","setServers","Promise","resolve","reject","resolveTxt","addresses","code","challengeValue","token","recordsProveOwnership","includes","assessDomainDrift","SSO_DRIFT_FAILURES_BEFORE_REPORT","SSO_DRIFT_MIN_AGE_MS","probeChallengeTxt","settle","status","conclusive","fallbackError","fallbackCode","claimRef","orgId","collection","doc","issueDomainClaim","rawDomain","claim","existing","get","exists","ref","snapshot","stored","undefined","toString","set","verified","createdAt","FieldValue","serverTimestamp","merge","Boolean","recordHost","recordValue","lastRecords","verifyDomainClaim","result","expected","lastCheckedAt","verifiedAt","delete","sso","domains","arrayUnion","domainVerified","revokeDomain","publicRef","publicSnapshot","active","arrayRemove","catch","SSO_AUTH_ORIGIN_UNCONFIGURED_MESSAGE","normalizeAuthHost","value","ssoServiceMetadata","process","workspaceDomain","env","projectId","authDomain","Error","acsUrl","entityId","poolDisplayName","orgSlug","base","padded","length","provisionSsoPool","options","existingTenantId","existingProviderId","idp","manager","tenantManager","metadata","tenantId","createdPool","tenant","createTenant","displayName","emailSignInConfig","enabled","passwordRequired","tenantAuth","authForTenant","providerId","config","idpEntityId","ssoURL","ssoUrl","x509Certificates","certificates","rpEntityId","callbackURL","createdProvider","getProviderConfig","updateProviderConfig","createProviderConfig","isStaffAttestedClaim","attestedBy","attestSsoDomain","attestedByUid","attestedAt","attestationNote","note","publishSsoDomains","protocol","published","batch","proven","updatedAt","push","commit","unpublishSsoDomains","owned","where","empty","docs","forEach"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GAED,SAASA,YAAYC,GAAG,EAAEC,YAAYC,gBAAgB,QAAQ,MAAK;AACnE,SAASC,WAAW,QAAQ,SAAQ;AAEpC,OAAOC,mBAAmB,sBAAkB;AAG5C,MAAMC,OAAO,IAAMD,cAAcE,GAAG,GAAGD,IAAI;AAC3C,MAAME,YAAY,IAAMH,cAAcE,GAAG,GAAGC,SAAS;AAErD,oDAAoD,GACpD,OAAO,MAAMC,uBAAuB,mBAAkB;AAEtD,6EAA6E,GAC7E,OAAO,MAAMC,iBAAiB,6BAA4B;AAE1D,MAAMC,iBAAiB;AAEvB,4EAA4E,GAC5E,MAAMC,mBAAmB;IAAC;IAAW;CAAU;AAE/C;;;;;;;;CAQC,GACD,MAAMC,uBAAuB,IAAIC,IAAI;IACnC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,MAAc;IAChD,OAAOH,qBAAqBI,GAAG,CAACC,OAAOF,iBAAAA,SAAU,IAAIG,IAAI,GAAGC,WAAW;AACzE;AAEA,OAAO,SAASC,mBAAmBC,KAAa;IAC9C,MAAMC,MAAML,OAAOI,gBAAAA,QAAS,IACzBH,IAAI,GACJC,WAAW;IACd,MAAMI,K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29
29
  * later cancels.
30
30
  */
31
- import type { OrgUpgradeProposal } from '@aglyn/aglyn/server';
31
+ import type { AglynOrgBilling, OrgUpgradeProposal } from '@aglyn/aglyn/server';
32
32
  /** The override reason a sales-evaluation comp is granted under. */
33
33
  export declare const TRIAL_PLAN_COMP_REASON = "trial";
34
34
  /** A proposal refused before anything was written. */
@@ -40,6 +40,13 @@ export interface ProposeOrgUpgradeOptions {
40
40
  orgId: string;
41
41
  plan: unknown;
42
42
  note?: unknown;
43
+ /**
44
+ * The add-ons, cadence and coupon proposed with the plan (AGL-3956), in any
45
+ * shape `parseBundleAddons` reads; fitted to the plan before storing.
46
+ */
47
+ addons?: unknown;
48
+ interval?: unknown;
49
+ coupon?: unknown;
43
50
  /** The staff member proposing. */
44
51
  actor: {
45
52
  uid: string;
@@ -66,6 +73,38 @@ export interface ProposeOrgUpgradeResult {
66
73
  * buy themselves.
67
74
  */
68
75
  export declare function proposeOrgUpgrade(options: ProposeOrgUpgradeOptions): Promise<ProposeOrgUpgradeResult>;
76
+ /**
77
+ * The proposal as it will be stored, or the refusal: a plan the workspace
78
+ * can buy itself, a bounded note, and the bundle fitted to the plan
79
+ * (AGL-3956). Nothing is read or written.
80
+ */
81
+ export declare function buildUpgradeProposal(options: Pick<ProposeOrgUpgradeOptions, 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'actor'> & {
82
+ now?: number;
83
+ }): OrgUpgradeProposal;
84
+ /**
85
+ * Read the org a proposal is for, inside the caller's transaction, refusing
86
+ * an unknown workspace and one whose subscription is already live — the
87
+ * question a proposal asks is then already answered.
88
+ */
89
+ export declare function readUpgradeProposalTarget(tx: FirebaseFirestore.Transaction, orgRef: FirebaseFirestore.DocumentReference): Promise<Partial<AglynOrgBilling>>;
90
+ /**
91
+ * Write the proposal and its audit row into the caller's transaction, so
92
+ * they commit with whatever else the caller writes (AGL-1784) — the owner
93
+ * invitation, for a hand-off that proposes in the same act (AGL-3956).
94
+ */
95
+ export declare function stageUpgradeProposal(tx: FirebaseFirestore.Transaction, db: FirebaseFirestore.Firestore, options: {
96
+ orgId: string;
97
+ proposal: OrgUpgradeProposal;
98
+ before: Partial<AglynOrgBilling>;
99
+ actorUid: string;
100
+ }): void;
101
+ /** "Proposed the Starter plan", naming the bundle when there is one. */
102
+ export declare function proposalActivityLine(proposal: OrgUpgradeProposal): string;
103
+ /** The workspace's feed line for a proposal, after it commits. */
104
+ export declare function recordUpgradeProposalActivity(orgId: string, actor: {
105
+ uid: string;
106
+ email?: string | null;
107
+ }, proposal: OrgUpgradeProposal): Promise<void>;
69
108
  /** Remove a standing proposal, audited. Answers whether one stood. */
70
109
  export declare function withdrawOrgUpgrade(options: {
71
110
  orgId: string;
@@ -29,7 +29,7 @@
29
29
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
30
30
  import { PLAN_LABELS } from "@aglyn/aglyn/app-utils/plan-entitlements";
31
31
  import { PLATFORM_BRAND_NAME } from "@aglyn/aglyn/app-utils/platform-brand";
32
- import { isUpgradeProposalPlan, normalizeUpgradeProposalNote, upgradeProposalDestination } from "@aglyn/aglyn/app-utils/upgrade-proposal";
32
+ import { isUpgradeProposalPlan, normalizeUpgradeProposalBundle, normalizeUpgradeProposalNote, upgradeProposalDestination, upgradeProposalSummary } from "@aglyn/aglyn/app-utils/upgrade-proposal";
33
33
  // Leaf modules, as `organizations.ts` imports its constants (AGL-1289).
34
34
  import { isLiveSubscriptionStatus, ORG_BILLING_DOC_ID, ORG_BILLING_SUBCOLLECTION } from "@aglyn/aglyn/app-utils/org-billing-doc";
35
35
  import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
@@ -60,72 +60,110 @@ const firestore = ()=>firebaseAdmin.app().firestore();
60
60
  * a proposal asks is already answered — and for any plan a customer cannot
61
61
  * buy themselves.
62
62
  */ export async function proposeOrgUpgrade(options) {
63
- var _actor_email;
64
63
  const { orgId, actor, origin } = options;
64
+ const proposal = buildUpgradeProposal(options);
65
+ const db = firestore();
66
+ const orgRef = db.collection('orgs').doc(orgId);
67
+ const org = await db.runTransaction(async (tx)=>{
68
+ const data = await readUpgradeProposalTarget(tx, orgRef);
69
+ stageUpgradeProposal(tx, db, {
70
+ orgId,
71
+ proposal,
72
+ before: data,
73
+ actorUid: actor.uid
74
+ });
75
+ return data;
76
+ });
77
+ await recordUpgradeProposalActivity(orgId, actor, proposal);
78
+ const emailed = await emailUpgradeProposal({
79
+ orgId,
80
+ org,
81
+ proposal,
82
+ origin
83
+ });
84
+ return {
85
+ proposal,
86
+ emailed
87
+ };
88
+ }
89
+ /**
90
+ * The proposal as it will be stored, or the refusal: a plan the workspace
91
+ * can buy itself, a bounded note, and the bundle fitted to the plan
92
+ * (AGL-3956). Nothing is read or written.
93
+ */ export function buildUpgradeProposal(options) {
94
+ var _options_now;
65
95
  if (!isUpgradeProposalPlan(options.plan)) {
66
96
  throw new UpgradeProposalError('Choose a paid plan the workspace can buy itself');
67
97
  }
68
98
  const plan = options.plan;
69
99
  const note = normalizeUpgradeProposalNote(options.note);
70
- const db = firestore();
71
- const orgRef = db.collection('orgs').doc(orgId);
72
- const proposal = _extends({
100
+ return _extends({
73
101
  plan,
74
- proposedBy: actor.uid,
75
- proposedAt: Date.now()
102
+ proposedBy: options.actor.uid,
103
+ proposedAt: (_options_now = options.now) != null ? _options_now : Date.now()
76
104
  }, note ? {
77
105
  note
78
- } : {});
79
- const org = await db.runTransaction(async (tx)=>{
80
- var _ref, _data_upgradeProposal;
81
- var _billing_get;
82
- const snapshot = await tx.get(orgRef);
83
- if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404);
84
- const data = snapshot.data();
85
- const billing = await tx.get(orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID));
86
- const status = (_ref = (_billing_get = billing.get('subscription')) == null ? void 0 : _billing_get.status) != null ? _ref : data.billingStatus;
87
- if (isLiveSubscriptionStatus(status)) {
88
- throw new UpgradeProposalError('This workspace already has a live subscription, so there is nothing to propose', 409);
89
- }
90
- tx.set(orgRef, {
91
- upgradeProposal: proposal,
92
- updatedAt: FieldValue.serverTimestamp()
93
- }, {
94
- merge: true
95
- });
96
- setAdminAudit(tx, db, {
97
- actorUid: actor.uid,
98
- action: 'org.upgradeProposal.propose',
99
- target: `orgs/${orgId}`,
100
- before: {
101
- upgradeProposal: (_data_upgradeProposal = data.upgradeProposal) != null ? _data_upgradeProposal : null
102
- },
103
- after: {
104
- upgradeProposal: proposal
105
- },
106
- at: FieldValue.serverTimestamp()
107
- });
108
- return data;
106
+ } : {}, normalizeUpgradeProposalBundle(plan, options));
107
+ }
108
+ /**
109
+ * Read the org a proposal is for, inside the caller's transaction, refusing
110
+ * an unknown workspace and one whose subscription is already live — the
111
+ * question a proposal asks is then already answered.
112
+ */ export async function readUpgradeProposalTarget(tx, orgRef) {
113
+ var _ref;
114
+ var _billing_get;
115
+ const snapshot = await tx.get(orgRef);
116
+ if (!snapshot.exists) throw new UpgradeProposalError('Unknown organization', 404);
117
+ const data = snapshot.data();
118
+ const billing = await tx.get(orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID));
119
+ const status = (_ref = (_billing_get = billing.get('subscription')) == null ? void 0 : _billing_get.status) != null ? _ref : data.billingStatus;
120
+ if (isLiveSubscriptionStatus(status)) {
121
+ throw new UpgradeProposalError('This workspace already has a live subscription, so there is nothing to propose', 409);
122
+ }
123
+ return data;
124
+ }
125
+ /**
126
+ * Write the proposal and its audit row into the caller's transaction, so
127
+ * they commit with whatever else the caller writes (AGL-1784) — the owner
128
+ * invitation, for a hand-off that proposes in the same act (AGL-3956).
129
+ */ export function stageUpgradeProposal(tx, db, options) {
130
+ var _before_upgradeProposal;
131
+ const { orgId, proposal, before, actorUid } = options;
132
+ tx.set(db.collection('orgs').doc(orgId), {
133
+ upgradeProposal: proposal,
134
+ updatedAt: FieldValue.serverTimestamp()
135
+ }, {
136
+ merge: true
109
137
  });
138
+ setAdminAudit(tx, db, {
139
+ actorUid,
140
+ action: 'org.upgradeProposal.propose',
141
+ target: `orgs/${orgId}`,
142
+ before: {
143
+ upgradeProposal: (_before_upgradeProposal = before.upgradeProposal) != null ? _before_upgradeProposal : null
144
+ },
145
+ after: {
146
+ upgradeProposal: proposal
147
+ },
148
+ at: FieldValue.serverTimestamp()
149
+ });
150
+ }
151
+ /** "Proposed the Starter plan", naming the bundle when there is one. */ export function proposalActivityLine(proposal) {
152
+ const label = planName(proposal.plan);
153
+ const summary = upgradeProposalSummary(proposal);
154
+ return summary === label ? `Proposed the ${label} plan` : `Proposed the ${label} plan (${summary})`;
155
+ }
156
+ /** The workspace's feed line for a proposal, after it commits. */ export async function recordUpgradeProposalActivity(orgId, actor, proposal) {
157
+ var _actor_email;
110
158
  await logOrgActivity(orgId, {
111
159
  uid: actor.uid,
112
160
  email: (_actor_email = actor.email) != null ? _actor_email : null
113
- }, `Proposed the ${PLAN_LABELS[plan]} plan`, {
161
+ }, proposalActivityLine(proposal), {
114
162
  type: 'subscription',
115
163
  id: orgId
116
164
  }, {
117
165
  staffActorId: actor.uid
118
166
  });
119
- const emailed = await emailUpgradeProposal({
120
- orgId,
121
- org,
122
- proposal,
123
- origin
124
- });
125
- return {
126
- proposal,
127
- emailed
128
- };
129
167
  }
130
168
  /** Remove a standing proposal, audited. Answers whether one stood. */ export async function withdrawOrgUpgrade(options) {
131
169
  var _actor_email;
@@ -278,14 +316,18 @@ const firestore = ()=>firebaseAdmin.app().firestore();
278
316
  const billingUrl = slug ? `${origin}${upgradeProposalDestination(slug, proposal)}` : origin;
279
317
  const label = planName(proposal.plan);
280
318
  const productName = brand.merge['brand.productName'] || PLATFORM_BRAND_NAME;
319
+ const summary = upgradeProposalSummary(proposal, {
320
+ brand: productName
321
+ });
281
322
  const content = await renderSystemEmailContent('org-upgrade-proposal', {
282
323
  'org.name': orgName,
283
324
  'plan.name': label,
284
325
  'proposal.note': (_proposal_note = proposal.note) != null ? _proposal_note : '',
326
+ 'proposal.summary': summary === label ? '' : summary,
285
327
  billingUrl
286
328
  }, brand, {
287
329
  subject: `Your ${productName} team proposed the ${label} plan for ${orgName}`,
288
- text: `Your ${productName} team proposed moving ${orgName} to the ${label} ` + 'plan. When you are ready, start the subscription from Billing, ' + `where the plan is already selected:\n\n${billingUrl}` + (proposal.note ? `\n\n${proposal.note}` : '')
330
+ text: `Your ${productName} team proposed moving ${orgName} to the ${label} ` + (summary === label ? 'plan. ' : `plan (${summary}). `) + 'When you are ready, start the subscription from Billing, ' + `where the plan is already selected:\n\n${billingUrl}` + (proposal.note ? `\n\n${proposal.note}` : '')
289
331
  });
290
332
  const result = await sendEmail(_extends({
291
333
  to,
@@ -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 normalizeUpgradeProposalNote,\n upgradeProposalDestination,\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 /** 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 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 const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const proposal: OrgUpgradeProposal = {\n plan,\n proposedBy: actor.uid,\n proposedAt: Date.now(),\n ...(note ? { note } : {}),\n }\n const org = await db.runTransaction(async (tx) => {\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 tx.set(\n orgRef,\n { upgradeProposal: proposal, updatedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n setAdminAudit(tx, db, {\n actorUid: actor.uid,\n action: 'org.upgradeProposal.propose',\n target: `orgs/${orgId}`,\n before: { upgradeProposal: data.upgradeProposal ?? null },\n after: { upgradeProposal: proposal },\n at: FieldValue.serverTimestamp(),\n })\n return data\n })\n await logOrgActivity(\n orgId,\n { uid: actor.uid, email: actor.email ?? null },\n `Proposed the ${PLAN_LABELS[plan]} plan`,\n { type: 'subscription', id: orgId },\n { staffActorId: actor.uid },\n )\n const emailed = await emailUpgradeProposal({ orgId, org, proposal, origin })\n return { proposal, emailed }\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 content = await renderSystemEmailContent(\n 'org-upgrade-proposal',\n {\n 'org.name': orgName,\n 'plan.name': label,\n 'proposal.note': proposal.note ?? '',\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 'plan. 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","normalizeUpgradeProposalNote","upgradeProposalDestination","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","actor","orgId","origin","plan","note","db","orgRef","collection","doc","proposal","proposedBy","uid","proposedAt","Date","now","org","runTransaction","tx","data","billing","snapshot","get","exists","billingStatus","set","upgradeProposal","updatedAt","serverTimestamp","merge","actorUid","action","target","before","after","at","email","type","id","staffActorId","emailed","emailUpgradeProposal","withdrawOrgUpgrade","withdrawn","stored","delete","planName","settleSubscriptionStart","context","outcome","entitlements","comp","trialComp","reason","onlyComp","Object","keys","every","key","planComp","code","subscriptionId","proposalCleared","trialCompRemoved","ownerUid","owner","to","brand","orgName","slug","billingUrl","label","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,4BAA4B,EAC5BC,0BAA0B,QACrB,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,GAAG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EAAEH,SAAS;YAC7EO,MACE,CAAC,KAAK,EAAEH,YAAY,sBAAsB,EAAEJ,QAAQ,QAAQ,EAAEG,MAAM,CAAC,CAAC,GACtE,oEACA,CAAC,uCAAuC,EAAED,YAAY,GACrD5D,CAAAA,SAASL,IAAI,GAAG,CAAC,IAAI,EAAEK,SAASL,IAAI,EAAE,GAAG,EAAC;QAC/C;QAEF,MAAMuE,SAAS,MAAM7F,UAAU;YAC7BmF;YACAQ,SAASD,QAAQC,OAAO;YACxBC,MAAMF,QAAQE,IAAI;WACdF,QAAQI,IAAI,GAAG;YAAEA,MAAMJ,QAAQI,IAAI;QAAC,IAAI,CAAC,GACzCV,MAAMW,QAAQ,GAAG;YAAEA,UAAUX,MAAMW,QAAQ;QAAC,IAAI,CAAC;YACrD9B,SAAS;;QAEX,IAAI4B,OAAOG,IAAI,EAAE,MAAM7F,cAAcgB;QACrC,OAAO0E,OAAOG,IAAI;IACpB,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,yCAAyCA;QACvD,OAAO;IACT;AACF;AAEA,SAASlC,SAAS1C,IAAa;IAC7B,OAAO,OAAOA,SAAS,YAAYA,QAAQ9B,cACvCA,WAAW,CAAC8B,KAAgB,GAC5B8E,OAAO9E,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 /** 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<ProposeOrgUpgradeOptions, 'plan' | 'note' | 'addons' | 'interval' | 'coupon' | 'actor'> & {\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;AAC3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