@aglyn/tenant-data-admin 1.0.0-beta.275 → 1.0.0-beta.282

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 (34) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/account-emails.js +18 -4
  3. package/src/lib/server/account-emails.js.map +1 -1
  4. package/src/lib/server/bundle-links.d.ts +5 -0
  5. package/src/lib/server/bundle-links.js +4 -2
  6. package/src/lib/server/bundle-links.js.map +1 -1
  7. package/src/lib/server/erase.js +9 -0
  8. package/src/lib/server/erase.js.map +1 -1
  9. package/src/lib/server/media-strong-digest.js +33 -5
  10. package/src/lib/server/media-strong-digest.js.map +1 -1
  11. package/src/lib/server/organizations.js +20 -0
  12. package/src/lib/server/organizations.js.map +1 -1
  13. package/src/lib/server/owner-handoff-emails.d.ts +43 -0
  14. package/src/lib/server/owner-handoff-emails.js +134 -0
  15. package/src/lib/server/owner-handoff-emails.js.map +1 -0
  16. package/src/lib/server/personal-data-export.js +18 -4
  17. package/src/lib/server/personal-data-export.js.map +1 -1
  18. package/src/lib/server/render-monitor.d.ts +8 -4
  19. package/src/lib/server/render-monitor.js +12 -8
  20. package/src/lib/server/render-monitor.js.map +1 -1
  21. package/src/lib/server/site-care-inbound.d.ts +75 -4
  22. package/src/lib/server/site-care-inbound.js +236 -26
  23. package/src/lib/server/site-care-inbound.js.map +1 -1
  24. package/src/lib/server/site-care-reconcile.d.ts +36 -2
  25. package/src/lib/server/site-care-reconcile.js +219 -54
  26. package/src/lib/server/site-care-reconcile.js.map +1 -1
  27. package/src/lib/server/site-care-requests.d.ts +43 -1
  28. package/src/lib/server/site-care-requests.js +117 -6
  29. package/src/lib/server/site-care-requests.js.map +1 -1
  30. package/src/lib/server/upgrade-proposal.d.ts +6 -1
  31. package/src/lib/server/upgrade-proposal.js.map +1 -1
  32. package/src/lib/server/upload-cors-reconcile.d.ts +2 -2
  33. package/src/lib/server/upload-cors-reconcile.js +2 -2
  34. package/src/lib/server/upload-cors-reconcile.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.0.0-beta.275",
3
+ "version": "1.0.0-beta.282",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.275",
29
- "@aglyn/shared-util-email": "1.0.0-beta.275",
30
- "@aglyn/shared-util-fbserver": "1.0.0-beta.275",
31
- "@aglyn/shared-util-first-touch": "1.0.0-beta.275",
32
- "@aglyn/shared-util-http": "1.0.0-beta.275",
33
- "@aglyn/shared-util-tools": "1.0.0-beta.275",
28
+ "@aglyn/aglyn": "1.0.0-beta.282",
29
+ "@aglyn/shared-util-email": "1.0.0-beta.282",
30
+ "@aglyn/shared-util-fbserver": "1.0.0-beta.282",
31
+ "@aglyn/shared-util-first-touch": "1.0.0-beta.282",
32
+ "@aglyn/shared-util-http": "1.0.0-beta.282",
33
+ "@aglyn/shared-util-tools": "1.0.0-beta.282",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -480,10 +480,24 @@ async function reconcilePrimaryFlag(uid, primaryAddress) {
480
480
  var _decision_message;
481
481
  return refuse(decision.verdict, String((_decision_message = decision.message) != null ? _decision_message : 'That change is not allowed.'));
482
482
  }
483
- await authForPool(context.tenantId).updateUser(uid, {
484
- email: address,
485
- emailVerified: true
486
- });
483
+ // The index entry being ours is not enough: an account created later can
484
+ // hold this address as its Auth email without ever touching the index (a
485
+ // federated sign-up with an address that was once our provider address,
486
+ // AGL-4041). Auth refuses the move with EMAIL_EXISTS, so ask first and
487
+ // answer with a refusal rather than letting it surface as a 500.
488
+ const taken = refuse('claimed-by-another-account', 'That address is now the sign-in email of another account, so it cannot be your primary.');
489
+ if (await addressTakenByAnother(address, uid)) return taken;
490
+ try {
491
+ await authForPool(context.tenantId).updateUser(uid, {
492
+ email: address,
493
+ emailVerified: true
494
+ });
495
+ } catch (error) {
496
+ // The same refusal when the other account appears between the check and
497
+ // the write.
498
+ if ((error == null ? void 0 : error.code) === 'auth/email-already-exists') return taken;
499
+ throw error;
500
+ }
487
501
  await reconcilePrimaryFlag(uid, address);
488
502
  return ok();
489
503
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/account-emails.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 store behind several email addresses per account (AGL-2486).\n *\n * The policy — which address anything is allowed to READ — lives in\n * `@aglyn/aglyn/app-utils/account-emails`, pure and client-importable. This\n * module is the Admin-SDK half: the writes, the uniqueness guard, and the\n * verification round-trip.\n *\n * ## Storage, and why every bit of it is server-only\n *\n * - `users/{uid}/emails/{address}` — the rows. SERVER-WRITE ONLY. This is\n * not a style choice: `users/{uid}` itself is `allow read, write` for its\n * owner under the rules, with no field validation whatsoever, so anything\n * stored ON that document is a field its owner can set to whatever they\n * like. An owner-writable `verified: true` is the entire feature defeated\n * — claim `ceo@acme.com`, flip the bit, and you hold a sign-in identifier\n * for an address you have never been able to receive mail at. So the rows\n * live in a subcollection with `allow write: if false`, exactly like\n * `passkeys` and `legalAcceptances`, and for exactly the same reason:\n * a client-writable credential store is an auth bypass.\n * - `emailIdentityIndex/{address}` — `{ uid }`, deny-all. THE uniqueness\n * guard. Two accounts holding the same verified address makes the sign-in\n * identifier ambiguous, which is an account-takeover vector, not a\n * cosmetic clash. Modelled on `passkeyCredentialIndex`.\n * - `emailVerifications/{tokenId}` — `{ uid, address, digest, expiresAt }`,\n * deny-all, single-use. Only the DIGEST is stored, so a database read does\n * not yield a working confirmation link. Modelled on\n * `webauthnChallenges`.\n *\n * ## What is deliberately NOT here\n *\n * There is no `domainsFor(uid)`, no `emailsInDomain(domain)`, and no lookup\n * that answers \"which orgs could this account belong to\". Adding one would be\n * the whole hazard: `sso-jit` grants org membership from a verified email's\n * domain, and a helper that handed it this account's OTHER addresses would\n * turn \"add an address\" into \"join an organization\". The SSO paths read the\n * address the IdP asserted at sign-in and nothing else — see\n * `apps/console/specs/account-emails-never-reach-sso.spec.ts`, which fails if\n * that stops being true.\n */\n\nimport { createHash, randomBytes, timingSafeEqual } from 'node:crypto'\nimport {\n MAX_ACCOUNT_EMAILS,\n evaluatePrimaryChange,\n canRemoveAccountEmail,\n normalizeAccountEmail,\n type AccountEmail,\n type PrimaryChangeVerdict,\n} from '@aglyn/aglyn/app-utils/account-emails'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\nimport { authForPool, findUserByEmailAcrossPools } from './auth-pools'\nimport { ssoDomainEnforcementEnabled, ssoRequiredDomains } from './sso-domain-policy'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport const ACCOUNT_EMAILS_SUBCOLLECTION = 'emails'\nexport const EMAIL_IDENTITY_INDEX_COLLECTION = 'emailIdentityIndex'\nexport const EMAIL_VERIFICATIONS_COLLECTION = 'emailVerifications'\n\n/**\n * Long enough that a confirmation link survives a mail client's queue and a\n * user who reads mail in the evening; short enough that a link sitting in a\n * forwarded thread stops working. Firebase's own action links use one day.\n */\nexport const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000\n\n/** Stored row shape. `address` mirrors the document id. */\ninterface StoredAccountEmail {\n address: string\n verified: boolean\n primary: boolean\n createdAt?: unknown\n verifiedAt?: unknown\n}\n\nexport interface AccountEmailRow extends AccountEmail {\n /** Null until the round-trip completes. ISO string for the API surface. */\n verifiedAt: string | null\n}\n\n/** Every refusal this module can produce, as a stable machine-readable code. */\nexport type AccountEmailRefusal =\n | 'invalid-address'\n | 'cap-reached'\n | 'already-on-this-account'\n | 'claimed-by-another-account'\n | 'unknown-address'\n | 'cannot-remove-primary'\n | 'last-verified-address'\n | 'token-invalid'\n | 'token-expired'\n | PrimaryChangeVerdict\n\nexport interface AccountEmailResult {\n ok: boolean\n refusal: AccountEmailRefusal | null\n message: string | null\n}\n\nconst ok = (): AccountEmailResult => ({ ok: true, refusal: null, message: null })\nconst refuse = (\n refusal: AccountEmailRefusal,\n message: string,\n): AccountEmailResult => ({ ok: false, refusal, message })\n\nfunction emailsRef(uid: string) {\n return firestore().collection('users').doc(uid).collection(ACCOUNT_EMAILS_SUBCOLLECTION)\n}\n\nfunction indexRef(address: string) {\n return firestore().collection(EMAIL_IDENTITY_INDEX_COLLECTION).doc(address)\n}\n\nfunction toRow(data: StoredAccountEmail): AccountEmailRow {\n const verifiedAt = data.verifiedAt as { toDate?: () => Date } | undefined\n return {\n address: data.address,\n verified: data.verified === true,\n primary: data.primary === true,\n verifiedAt:\n verifiedAt !== undefined &&\n verifiedAt !== null &&\n typeof verifiedAt.toDate === 'function'\n ? verifiedAt.toDate().toISOString()\n : null,\n }\n}\n\n/**\n * Read the account's addresses, seeding the primary row from Firebase Auth on\n * first read.\n *\n * THE BACKFILL IS NOT OPTIONAL. Every account that exists today predates this\n * subcollection, so without the seed an established user opens the card and\n * is told they have no addresses — while `decoded.email` says otherwise — and\n * then \"you cannot remove your last verified address\" would be enforced\n * against an empty set. The Firebase Auth record is the authority for the\n * primary, so the seed is a mirror rather than a new fact.\n *\n * `authEmailVerified` is carried through honestly: an account that has never\n * confirmed its own sign-up address gets an UNVERIFIED primary row, which is\n * the truth and which the card then offers to fix.\n */\nexport async function listAccountEmails(\n uid: string,\n authEmail: string | null | undefined,\n authEmailVerified: boolean,\n): Promise<AccountEmailRow[]> {\n const snapshot = await emailsRef(uid).get()\n const rows = snapshot.docs.map((doc) => toRow(doc.data() as StoredAccountEmail))\n\n const primaryAddress = normalizeAccountEmail(authEmail)\n if (primaryAddress === null) return rows\n\n const known = rows.find((row) => row.address === primaryAddress)\n if (known !== undefined) {\n // The Auth record is the authority for WHICH address is primary. If they\n // ever disagree — a staff email change through the admin console, say —\n // Auth wins and the mirror is corrected, rather than the card showing a\n // primary the token does not carry.\n if (known.primary !== true) {\n await reconcilePrimaryFlag(uid, primaryAddress)\n return listAccountEmails(uid, authEmail, authEmailVerified)\n }\n return rows\n }\n\n await emailsRef(uid)\n .doc(primaryAddress)\n .set(\n {\n address: primaryAddress,\n verified: authEmailVerified === true,\n primary: true,\n createdAt: FieldValue.serverTimestamp(),\n ...(authEmailVerified === true\n ? { verifiedAt: FieldValue.serverTimestamp() }\n : {}),\n },\n { merge: true },\n )\n /*\n * CLEAR THE FLAG OFF WHATEVER USED TO HOLD IT.\n *\n * This branch runs when Auth's address is not among the stored rows — which\n * is exactly what a staff email change produces, since it writes the Auth\n * record directly. Setting the new row primary without clearing the old one\n * left TWO rows flagged primary, and every reader that takes the first match\n * then answers with whichever Firestore returned first.\n *\n * Only when there were pre-existing rows: a first-ever seed has nothing to\n * reconcile and must not pay for a second read and a batch commit.\n */\n if (rows.length > 0) await reconcilePrimaryFlag(uid, primaryAddress)\n // Claim the index for it too, but never steal one: an address already\n // indexed to somebody else is a real conflict that a backfill must not\n // paper over. Best-effort — a failed claim must not stop someone reading\n // their own settings page.\n if (authEmailVerified === true) {\n try {\n await claimIndexEntry(primaryAddress, uid)\n } catch (error) {\n console.error('[account-emails] primary index backfill failed', error)\n }\n }\n return [\n ...rows,\n {\n address: primaryAddress,\n verified: authEmailVerified === true,\n primary: true,\n verifiedAt: null,\n },\n ]\n}\n\nasync function reconcilePrimaryFlag(uid: string, primaryAddress: string): Promise<void> {\n const snapshot = await emailsRef(uid).get()\n const batch = firestore().batch()\n for (const doc of snapshot.docs) {\n const shouldBePrimary = doc.id === primaryAddress\n if ((doc.get('primary') === true) !== shouldBePrimary) {\n batch.set(doc.ref, { primary: shouldBePrimary }, { merge: true })\n }\n }\n await batch.commit()\n}\n\n/**\n * Claim `address` for `uid` in the uniqueness index, transactionally.\n *\n * Returns false when another account already holds it. Re-claiming your own\n * is a no-op success, which is what makes the whole flow idempotent.\n */\nasync function claimIndexEntry(address: string, uid: string): Promise<boolean> {\n return firestore().runTransaction(async (transaction) => {\n const ref = indexRef(address)\n const existing = await transaction.get(ref)\n if (existing.exists) {\n const owner = existing.get('uid')\n if (owner !== uid) return false\n return true\n }\n transaction.set(ref, { uid, address, claimedAt: FieldValue.serverTimestamp() })\n return true\n })\n}\n\n/**\n * Is `address` spoken for by an account other than `uid`?\n *\n * Consults BOTH the index and Firebase Auth, and the Auth half is the\n * load-bearing one. The index only knows about addresses that have been\n * through this feature; every account that existed before it has its primary\n * in the Auth record and nowhere else. Checking the index alone would let a\n * brand-new account claim an established user's sign-up address, which is the\n * exact ambiguity the uniqueness rule exists to prevent.\n *\n * `findUserByEmailAcrossPools` rather than a project-pool `getUserByEmail`:\n * an SSO user lives in their org's GCIP tenant and is invisible to\n * project-level lookups (AGL-1122), so the narrow call would report an\n * enterprise customer's address as free.\n */\nasync function addressTakenByAnother(address: string, uid: string): Promise<boolean> {\n const indexed = await indexRef(address).get()\n if (indexed.exists && indexed.get('uid') !== uid) return true\n const pooled = await findUserByEmailAcrossPools(address)\n if (pooled !== null && pooled !== undefined && pooled.record.uid !== uid) return true\n return false\n}\n\n/**\n * Stage a new address and return the secret for its confirmation link.\n *\n * The address is stored UNVERIFIED and does nothing until the round-trip\n * completes: it is not a sign-in identifier, it receives no account mail, and\n * — importantly — it does NOT claim the uniqueness index. Claiming on `add`\n * would make this endpoint a squatting tool: anyone could park an address\n * they do not own and lock its real owner out of adding it. The index is\n * claimed by {@link confirmAccountEmail}, so the first account to prove\n * delivery wins, and proving delivery is the only way to win.\n *\n * The pre-flight `addressTakenByAnother` here is a courtesy, not the guard —\n * it turns the common case into an immediate, honest error instead of a\n * confirmation email that fails at the end. The real check runs again inside\n * the confirmation transaction, because anything can change in between.\n */\nexport async function addAccountEmail(\n uid: string,\n input: unknown,\n): Promise<AccountEmailResult & { address: string | null; secret: string | null }> {\n const address = normalizeAccountEmail(input)\n if (address === null) {\n return {\n ...refuse('invalid-address', 'Enter a valid email address.'),\n address: null,\n secret: null,\n }\n }\n\n const existing = await emailsRef(uid).get()\n if (existing.docs.some((doc) => doc.id === address)) {\n return {\n ...refuse('already-on-this-account', 'That address is already on this account.'),\n address,\n secret: null,\n }\n }\n // THE CAP (see MAX_ACCOUNT_EMAILS). Counted from a server read immediately\n // before the write — a number read anywhere else is a number that can be\n // stale by the time it is trusted.\n if (existing.size >= MAX_ACCOUNT_EMAILS) {\n return {\n ...refuse(\n 'cap-reached',\n `An account can hold ${MAX_ACCOUNT_EMAILS} email addresses. ` +\n 'Remove one before adding another.',\n ),\n address,\n secret: null,\n }\n }\n if (await addressTakenByAnother(address, uid)) {\n return {\n ...refuse(\n 'claimed-by-another-account',\n 'That address is already in use on another account.',\n ),\n address,\n secret: null,\n }\n }\n\n await emailsRef(uid).doc(address).set(\n {\n address,\n verified: false,\n primary: false,\n createdAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n const secret = await issueVerificationToken(uid, address)\n return { ...ok(), address, secret }\n}\n\n/**\n * Mint a single-use confirmation secret and store only its digest.\n *\n * The returned string is `{tokenId}.{secret}`; the caller puts it in the\n * emailed link and never persists it. A reader of the database therefore\n * cannot confirm anybody's address — they hold a SHA-256 of the half that\n * matters.\n */\nexport async function issueVerificationToken(\n uid: string,\n address: string,\n): Promise<string> {\n const tokenId = randomBytes(16).toString('hex')\n const secret = randomBytes(32).toString('hex')\n await firestore()\n .collection(EMAIL_VERIFICATIONS_COLLECTION)\n .doc(tokenId)\n .set({\n uid,\n address,\n digest: createHash('sha256').update(secret).digest('hex'),\n createdAt: FieldValue.serverTimestamp(),\n expiresAt: Date.now() + EMAIL_VERIFICATION_TTL_MS,\n })\n return `${tokenId}.${secret}`\n}\n\n/** Constant-time compare of two hex digests of equal length. */\nfunction digestsMatch(a: unknown, b: string): boolean {\n if (typeof a !== 'string' || a.length !== b.length) return false\n return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'))\n}\n\n/**\n * Complete the round-trip: the bearer of this link can receive mail at the\n * address, so the address becomes verified and the account claims it.\n *\n * Deliberately NOT authenticated against the current session. The person\n * clicking the link is whoever opened the mailbox, and requiring them to be\n * signed in as the right account first is how confirmation links strand\n * people who read mail on a different device. The token itself carries the\n * uid, and it can do nothing except verify the one address it was minted for.\n *\n * The uniqueness claim happens HERE and inside the same logical step as the\n * flag flip, so two accounts racing on one address cannot both end up\n * verified.\n */\nexport async function confirmAccountEmail(\n token: unknown,\n): Promise<AccountEmailResult & { address: string | null; uid: string | null }> {\n const raw = String(token ?? '')\n const separator = raw.indexOf('.')\n if (separator <= 0) {\n return {\n ...refuse('token-invalid', 'That confirmation link is not valid.'),\n address: null,\n uid: null,\n }\n }\n const tokenId = raw.slice(0, separator)\n const secret = raw.slice(separator + 1)\n if (!/^[a-f0-9]{32}$/.test(tokenId) || !/^[a-f0-9]{64}$/.test(secret)) {\n return {\n ...refuse('token-invalid', 'That confirmation link is not valid.'),\n address: null,\n uid: null,\n }\n }\n\n const tokenRef = firestore().collection(EMAIL_VERIFICATIONS_COLLECTION).doc(tokenId)\n const snapshot = await tokenRef.get()\n if (!snapshot.exists) {\n return {\n ...refuse('token-invalid', 'That confirmation link has already been used.'),\n address: null,\n uid: null,\n }\n }\n if (!digestsMatch(snapshot.get('digest'), createHash('sha256').update(secret).digest('hex'))) {\n return {\n ...refuse('token-invalid', 'That confirmation link is not valid.'),\n address: null,\n uid: null,\n }\n }\n const expiresAt = Number(snapshot.get('expiresAt') ?? 0)\n if (!Number.isFinite(expiresAt) || expiresAt < Date.now()) {\n await tokenRef.delete()\n return {\n ...refuse('token-expired', 'That confirmation link has expired — send a new one.'),\n address: null,\n uid: null,\n }\n }\n\n const uid = String(snapshot.get('uid') ?? '')\n const address = String(snapshot.get('address') ?? '')\n if (!uid || !address) {\n await tokenRef.delete()\n return {\n ...refuse('token-invalid', 'That confirmation link is not valid.'),\n address: null,\n uid: null,\n }\n }\n\n // Single-use: burned before the claim, so a link cannot be replayed even if\n // the claim below fails.\n await tokenRef.delete()\n\n if (await addressTakenByAnother(address, uid)) {\n return {\n ...refuse(\n 'claimed-by-another-account',\n 'That address has since been confirmed on another account.',\n ),\n address,\n uid,\n }\n }\n const claimed = await claimIndexEntry(address, uid)\n if (!claimed) {\n return {\n ...refuse(\n 'claimed-by-another-account',\n 'That address has since been confirmed on another account.',\n ),\n address,\n uid,\n }\n }\n\n await emailsRef(uid)\n .doc(address)\n .set(\n { address, verified: true, verifiedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n return { ...ok(), address, uid }\n}\n\n/**\n * Remove an address, freeing its index entry.\n *\n * The index entry is released so the address can be used again — on this\n * account or another. Leaving it behind would make removal a way to burn an\n * address permanently, including somebody else's if they ever wanted it.\n */\nexport async function removeAccountEmail(\n uid: string,\n input: unknown,\n): Promise<AccountEmailResult> {\n const address = normalizeAccountEmail(input)\n if (address === null) return refuse('invalid-address', 'Enter a valid email address.')\n\n const snapshot = await emailsRef(uid).get()\n const rows: AccountEmail[] = snapshot.docs.map((doc) => ({\n address: String(doc.get('address') ?? doc.id),\n verified: doc.get('verified') === true,\n primary: doc.get('primary') === true,\n }))\n const verdict = canRemoveAccountEmail(address, rows)\n if (!verdict.allowed) {\n const row = rows.find((entry) => entry.address === address)\n // Distinct codes so the card can say WHICH floor it hit — \"make another\n // address primary first\" and \"this is your only confirmed address\" are\n // different instructions, and a single code would collapse them into one\n // unhelpful sentence.\n const code: AccountEmailRefusal =\n row === undefined\n ? 'unknown-address'\n : row.primary === true\n ? 'cannot-remove-primary'\n : 'last-verified-address'\n return refuse(code, String(verdict.message ?? 'That address cannot be removed.'))\n }\n\n await emailsRef(uid).doc(address).delete()\n const indexed = await indexRef(address).get()\n if (indexed.exists && indexed.get('uid') === uid) {\n await indexRef(address).delete()\n }\n return ok()\n}\n\nexport interface SetPrimaryContext {\n /** `decoded.firebase?.tenant` — the pool the caller signed in through. */\n tenantId: string | null\n}\n\n/**\n * Re-designate the primary address.\n *\n * THE MOST SECURITY-SENSITIVE WRITE IN THIS MODULE, because the primary IS\n * the Firebase Auth record's email, which is what `decoded.email` carries,\n * which is what `evaluateSsoDomainPolicy` reads at the session mint and what\n * the invite-accept comparison matches on. Changing it changes an\n * authorization input — so it goes through `evaluatePrimaryChange` first, and\n * that function refuses to move a primary off a domain the deployment\n * requires SSO for. See its docstring for why that refusal ignores the\n * enforcement switch.\n *\n * The Auth record is updated in the account's OWN pool via `authForPool`: a\n * project-level `updateUser` cannot see a GCIP tenant account, so the narrow\n * call would silently fail for exactly the enterprise users this policy is\n * about.\n *\n * `emailVerified: true` is set alongside the address, and it is honest — the\n * only addresses that can reach this point are ones this module verified by\n * an emailed round-trip. Omitting it would flip the account to unverified and\n * lock it out of every route behind `emailUnverifiedResponse()`.\n */\nexport async function setPrimaryAccountEmail(\n uid: string,\n input: unknown,\n context: SetPrimaryContext,\n): Promise<AccountEmailResult> {\n const address = normalizeAccountEmail(input)\n if (address === null) return refuse('invalid-address', 'Enter a valid email address.')\n\n const snapshot = await emailsRef(uid).get()\n const rows: AccountEmail[] = snapshot.docs.map((doc) => ({\n address: String(doc.get('address') ?? doc.id),\n verified: doc.get('verified') === true,\n primary: doc.get('primary') === true,\n }))\n const current = rows.find((row) => row.primary === true) ?? null\n const next = rows.find((row) => row.address === address) ?? null\n\n const decision = evaluatePrimaryChange({\n current,\n next,\n requiredDomains: ssoRequiredDomains(),\n tenantId: context.tenantId ?? null,\n enforcementEnabled: ssoDomainEnforcementEnabled(),\n })\n if (!decision.allowed) {\n return refuse(decision.verdict, String(decision.message ?? 'That change is not allowed.'))\n }\n\n await authForPool(context.tenantId).updateUser(uid, {\n email: address,\n emailVerified: true,\n })\n await reconcilePrimaryFlag(uid, address)\n return ok()\n}\n\n/**\n * The account that holds `address` as a VERIFIED alias, or null.\n *\n * ## Read this before calling it\n *\n * This is the one lookup that maps an arbitrary address to an account, and it\n * exists for exactly two callers: resolving a sign-in identifier, and\n * matching an org invitation. Both are safe for the same reason — neither\n * GRANTS anything on the strength of the address:\n *\n * - a sign-in identifier still has to be followed by the account's password;\n * - an invitation is an explicit grant the ORG made, and this only decides\n * which of the recipient's mailboxes it may arrive at.\n *\n * It must never be wired into an SSO path. `sso-jit` resolves the org from\n * the GCIP tenant on a re-verified token and matches the domain the IdP\n * asserted; giving it this function would let a user add an address and be\n * provisioned into the matching organization, which is the escalation this\n * whole feature was designed around.\n *\n * Returns null for an unverified row by construction: the index is only ever\n * written by the confirmation path.\n */\nexport async function findAccountByVerifiedAlias(\n input: unknown,\n): Promise<{ uid: string; address: string } | null> {\n const address = normalizeAccountEmail(input)\n if (address === null) return null\n const indexed = await indexRef(address).get()\n if (!indexed.exists) return null\n const uid = String(indexed.get('uid') ?? '')\n if (!uid) return null\n return { uid, address }\n}\n\n/*==========================================\n * PROVIDER-SUPPLIED ADDRESSES.\n *\n * A federated provider asserts its own address, and `providerData[].email`\n * can differ from the primary. Until now nothing registered one: it was\n * absent from `users/{uid}/emails`, held no `emailIdentityIndex` entry, and\n * so lived entirely OUTSIDE the uniqueness guard — while remaining a real\n * mailbox, a working sign-in identifier, and a recipient of real mail.\n *\n * The consequence is a collision the guard was built to prevent and could not\n * see: one address that is one account's primary and another account's Google\n * provider address. Anything mapping address → uid then answers confidently\n * and wrongly.\n *=========================================*/\n\n/** What one {@link registerProviderAddresses} pass did. */\nexport interface ProviderAddressRegistration {\n /** Addresses newly claimed for this account. */\n claimed: string[]\n /** Addresses another account already holds — recorded, never taken. */\n conflicted: string[]\n}\n\n/**\n * Providers whose asserted address counts as proven.\n *\n * `password` is excluded because its address is the primary, already handled,\n * and its verification state lives on the Auth record rather than in the\n * provider entry. Everything else here is a federated IdP that has itself\n * established control of the mailbox — the same standard\n * {@link confirmAccountEmail} applies, met by a different party.\n */\nfunction isFederatedProvider(providerId: string | null | undefined): boolean {\n const id = String(providerId ?? '')\n return id !== '' && id !== 'password' && id !== 'phone' && id !== 'anonymous'\n}\n\n/**\n * Register the addresses a federated provider asserts for this account.\n *\n * Called from the session mint — the one place every interactive sign-in\n * passes through with a verified token — and BEST-EFFORT by contract.\n *\n * ## Three rules, in priority order\n *\n * 1. **Sign-in must not depend on this.** It is bookkeeping. A person locked\n * out because an index write failed is a worse outcome than the collision\n * it was preventing, so every failure here is swallowed and logged, and\n * the caller runs it off the critical path.\n * 2. **A claim never takes an entry another account holds.**\n * {@link claimIndexEntry} already refuses; what was missing is that the\n * refusal went nowhere. A conflict now lands on the row as\n * `indexConflict`, which the staff account page reads — silently skipping\n * is exactly what produced the live collision.\n * 3. **A conflicted address is stored UNVERIFIED.** This is the conservative\n * half and it matters: `verifiedAccountEmails` feeds invitation matching,\n * so marking a contested address verified on both accounts would make one\n * invitation match two people. Unverified, the row is a record that the\n * address exists on this account and grants nothing.\n *\n * ⛔ It does not merge, reassign or disable anything. Two real accounts\n * sharing an address is a human decision — the row makes it visible and stops\n * there.\n *\n * ⚠️ Registering here CANNOT reach SSO provisioning. `sso-jit` reads the\n * address the IdP asserted at sign-in and never consults this store;\n * `apps/console/specs/account-emails-never-reach-sso.spec.ts` fails if that\n * stops being true. That guard is what makes this safe to write at all.\n */\nexport async function registerProviderAddresses(\n uid: string,\n record: {\n email?: string | null\n providerData?: readonly {\n providerId?: string | null\n email?: string | null\n }[]\n } | null,\n): Promise<ProviderAddressRegistration> {\n const claimed: string[] = []\n const conflicted: string[] = []\n const primary = normalizeAccountEmail(record?.email ?? null)\n\n const candidates = new Set<string>()\n for (const provider of record?.providerData ?? []) {\n if (!isFederatedProvider(provider?.providerId)) continue\n const address = normalizeAccountEmail(provider?.email ?? null)\n // The primary is registered by `listAccountEmails`' own backfill, on the\n // Auth record's authority. Re-doing it here would race that seed.\n if (address === null || address === primary) continue\n candidates.add(address)\n }\n\n for (const address of candidates) {\n try {\n const won = await claimIndexEntry(address, uid)\n if (won) claimed.push(address)\n else conflicted.push(address)\n\n await emailsRef(uid)\n .doc(address)\n .set(\n {\n address,\n // Only when the claim was won — see rule 3.\n verified: won,\n primary: false,\n source: 'provider',\n ...(won\n ? { verifiedAt: FieldValue.serverTimestamp(), indexConflict: false }\n : { indexConflict: true, indexConflictAtMs: Date.now() }),\n createdAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n } catch (error) {\n // Rule 1. Never rethrow: the caller is a sign-in.\n console.error('[account-emails] provider address registration failed', uid, error)\n }\n }\n\n if (conflicted.length) {\n // Loud, per rule 2 — a conflict that only ever landed in a document would\n // be discovered by whoever happened to open the right page.\n console.error(\n '[account-emails] provider address already claimed by another account',\n JSON.stringify({ uid, conflicted: conflicted.length }),\n )\n }\n return { claimed, conflicted }\n}\n\n/**\n * Every VERIFIED address on an account, for matching an invitation.\n *\n * Bounded by {@link MAX_ACCOUNT_EMAILS}, which is what makes it safe to feed\n * straight into a Firestore `in` query (limit 30).\n *\n * ⛔ NOT the answer to \"every address this account holds\" — it is verified-only,\n * subcollection-only and silently truncating, all correct here and all wrong\n * there. `account-addresses.ts` is that resolver and explains why at length.\n */\nexport async function verifiedAccountEmails(uid: string): Promise<string[]> {\n const snapshot = await emailsRef(uid).get()\n return snapshot.docs\n .filter((doc) => doc.get('verified') === true)\n .map((doc) => String(doc.get('address') ?? doc.id))\n .slice(0, MAX_ACCOUNT_EMAILS)\n}\n"],"names":["createHash","randomBytes","timingSafeEqual","MAX_ACCOUNT_EMAILS","evaluatePrimaryChange","canRemoveAccountEmail","normalizeAccountEmail","FieldValue","firebaseAdmin","authForPool","findUserByEmailAcrossPools","ssoDomainEnforcementEnabled","ssoRequiredDomains","firestore","app","ACCOUNT_EMAILS_SUBCOLLECTION","EMAIL_IDENTITY_INDEX_COLLECTION","EMAIL_VERIFICATIONS_COLLECTION","EMAIL_VERIFICATION_TTL_MS","ok","refusal","message","refuse","emailsRef","uid","collection","doc","indexRef","address","toRow","data","verifiedAt","verified","primary","undefined","toDate","toISOString","listAccountEmails","authEmail","authEmailVerified","snapshot","get","rows","docs","map","primaryAddress","known","find","row","reconcilePrimaryFlag","set","createdAt","serverTimestamp","merge","length","claimIndexEntry","error","console","batch","shouldBePrimary","id","ref","commit","runTransaction","transaction","existing","exists","owner","claimedAt","addressTakenByAnother","indexed","pooled","record","addAccountEmail","input","secret","some","size","issueVerificationToken","tokenId","toString","digest","update","expiresAt","Date","now","digestsMatch","a","b","Buffer","from","confirmAccountEmail","token","raw","String","separator","indexOf","slice","test","tokenRef","Number","isFinite","delete","claimed","removeAccountEmail","verdict","allowed","entry","code","setPrimaryAccountEmail","context","current","next","decision","requiredDomains","tenantId","enforcementEnabled","updateUser","email","emailVerified","findAccountByVerifiedAlias","isFederatedProvider","providerId","registerProviderAddresses","conflicted","candidates","Set","provider","providerData","add","won","push","source","indexConflict","indexConflictAtMs","JSON","stringify","verifiedAccountEmails","filter"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GAED,SAASA,UAAU,EAAEC,WAAW,EAAEC,eAAe,QAAQ,cAAa;AACtE,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,qBAAqB,EACrBC,qBAAqB,QAGhB,wCAAuC;AAC9C,SAASC,UAAU,QAAQ,2BAA0B;AACrD,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,WAAW,EAAEC,0BAA0B,QAAQ,kBAAc;AACtE,SAASC,2BAA2B,EAAEC,kBAAkB,QAAQ,yBAAqB;AAErF,MAAMC,YAAY,IAAML,cAAcM,GAAG,GAAGD,SAAS;AAErD,OAAO,MAAME,+BAA+B,SAAQ;AACpD,OAAO,MAAMC,kCAAkC,qBAAoB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../../../../../libs/tenant/data/admin/src/lib/server/account-emails.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 store behind several email addresses per account (AGL-2486).\n *\n * The policy — which address anything is allowed to READ — lives in\n * `@aglyn/aglyn/app-utils/account-emails`, pure and client-importable. This\n * module is the Admin-SDK half: the writes, the uniqueness guard, and the\n * verification round-trip.\n *\n * ## Storage, and why every bit of it is server-only\n *\n * - `users/{uid}/emails/{address}` — the rows. SERVER-WRITE ONLY. This is\n * not a style choice: `users/{uid}` itself is `allow read, write` for its\n * owner under the rules, with no field validation whatsoever, so anything\n * stored ON that document is a field its owner can set to whatever they\n * like. An owner-writable `verified: true` is the entire feature defeated\n * — claim `ceo@acme.com`, flip the bit, and you hold a sign-in identifier\n * for an address you have never been able to receive mail at. So the rows\n * live in a subcollection with `allow write: if false`, exactly like\n * `passkeys` and `legalAcceptances`, and for exactly the same reason:\n * a client-writable credential store is an auth bypass.\n * - `emailIdentityIndex/{address}` — `{ uid }`, deny-all. THE uniqueness\n * guard. Two accounts holding the same verified address makes the sign-in\n * identifier ambiguous, which is an account-takeover vector, not a\n * cosmetic clash. Modelled on `passkeyCredentialIndex`.\n * - `emailVerifications/{tokenId}` — `{ uid, address, digest, expiresAt }`,\n * deny-all, single-use. Only the DIGEST is stored, so a database read does\n * not yield a working confirmation link. Modelled on\n * `webauthnChallenges`.\n *\n * ## What is deliberately NOT here\n *\n * There is no `domainsFor(uid)`, no `emailsInDomain(domain)`, and no lookup\n * that answers \"which orgs could this account belong to\". Adding one would be\n * the whole hazard: `sso-jit` grants org membership from a verified email's\n * domain, and a helper that handed it this account's OTHER addresses would\n * turn \"add an address\" into \"join an organization\". The SSO paths read the\n * address the IdP asserted at sign-in and nothing else — see\n * `apps/console/specs/account-emails-never-reach-sso.spec.ts`, which fails if\n * that stops being true.\n */\n\nimport { createHash, randomBytes, timingSafeEqual } from 'node:crypto'\nimport {\n MAX_ACCOUNT_EMAILS,\n evaluatePrimaryChange,\n canRemoveAccountEmail,\n normalizeAccountEmail,\n type AccountEmail,\n type PrimaryChangeVerdict,\n} from '@aglyn/aglyn/app-utils/account-emails'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\nimport { authForPool, findUserByEmailAcrossPools } from './auth-pools'\nimport { ssoDomainEnforcementEnabled, ssoRequiredDomains } from './sso-domain-policy'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport const ACCOUNT_EMAILS_SUBCOLLECTION = 'emails'\nexport const EMAIL_IDENTITY_INDEX_COLLECTION = 'emailIdentityIndex'\nexport const EMAIL_VERIFICATIONS_COLLECTION = 'emailVerifications'\n\n/**\n * Long enough that a confirmation link survives a mail client's queue and a\n * user who reads mail in the evening; short enough that a link sitting in a\n * forwarded thread stops working. Firebase's own action links use one day.\n */\nexport const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000\n\n/** Stored row shape. `address` mirrors the document id. */\ninterface StoredAccountEmail {\n address: string\n verified: boolean\n primary: boolean\n createdAt?: unknown\n verifiedAt?: unknown\n}\n\nexport interface AccountEmailRow extends AccountEmail {\n /** Null until the round-trip completes. ISO string for the API surface. */\n verifiedAt: string | null\n}\n\n/** Every refusal this module can produce, as a stable machine-readable code. */\nexport type AccountEmailRefusal =\n | 'invalid-address'\n | 'cap-reached'\n | 'already-on-this-account'\n | 'claimed-by-another-account'\n | 'unknown-address'\n | 'cannot-remove-primary'\n | 'last-verified-address'\n | 'token-invalid'\n | 'token-expired'\n | PrimaryChangeVerdict\n\nexport interface AccountEmailResult {\n ok: boolean\n refusal: AccountEmailRefusal | null\n message: string | null\n}\n\nconst ok = (): AccountEmailResult => ({ ok: true, refusal: null, message: null })\nconst refuse = (\n refusal: AccountEmailRefusal,\n message: string,\n): AccountEmailResult => ({ ok: false, refusal, message })\n\nfunction emailsRef(uid: string) {\n return firestore().collection('users').doc(uid).collection(ACCOUNT_EMAILS_SUBCOLLECTION)\n}\n\nfunction indexRef(address: string) {\n return firestore().collection(EMAIL_IDENTITY_INDEX_COLLECTION).doc(address)\n}\n\nfunction toRow(data: StoredAccountEmail): AccountEmailRow {\n const verifiedAt = data.verifiedAt as { toDate?: () => Date } | undefined\n return {\n address: data.address,\n verified: data.verified === true,\n primary: data.primary === true,\n verifiedAt:\n verifiedAt !== undefined &&\n verifiedAt !== null &&\n typeof verifiedAt.toDate === 'function'\n ? verifiedAt.toDate().toISOString()\n : null,\n }\n}\n\n/**\n * Read the account's addresses, seeding the primary row from Firebase Auth on\n * first read.\n *\n * THE BACKFILL IS NOT OPTIONAL. Every account that exists today predates this\n * subcollection, so without the seed an established user opens the card and\n * is told they have no addresses — while `decoded.email` says otherwise — and\n * then \"you cannot remove your last verified address\" would be enforced\n * against an empty set. The Firebase Auth record is the authority for the\n * primary, so the seed is a mirror rather than a new fact.\n *\n * `authEmailVerified` is carried through honestly: an account that has never\n * confirmed its own sign-up address gets an UNVERIFIED primary row, which is\n * the truth and which the card then offers to fix.\n */\nexport async function listAccountEmails(\n uid: string,\n authEmail: string | null | undefined,\n authEmailVerified: boolean,\n): Promise<AccountEmailRow[]> {\n const snapshot = await emailsRef(uid).get()\n const rows = snapshot.docs.map((doc) => toRow(doc.data() as StoredAccountEmail))\n\n const primaryAddress = normalizeAccountEmail(authEmail)\n if (primaryAddress === null) return rows\n\n const known = rows.find((row) => row.address === primaryAddress)\n if (known !== undefined) {\n // The Auth record is the authority for WHICH address is primary. If they\n // ever disagree — a staff email change through the admin console, say —\n // Auth wins and the mirror is corrected, rather than the card showing a\n // primary the token does not carry.\n if (known.primary !== true) {\n await reconcilePrimaryFlag(uid, primaryAddress)\n return listAccountEmails(uid, authEmail, authEmailVerified)\n }\n return rows\n }\n\n await emailsRef(uid)\n .doc(primaryAddress)\n .set(\n {\n address: primaryAddress,\n verified: authEmailVerified === true,\n primary: true,\n createdAt: FieldValue.serverTimestamp(),\n ...(authEmailVerified === true\n ? { verifiedAt: FieldValue.serverTimestamp() }\n : {}),\n },\n { merge: true },\n )\n /*\n * CLEAR THE FLAG OFF WHATEVER USED TO HOLD IT.\n *\n * This branch runs when Auth's address is not among the stored rows — which\n * is exactly what a staff email change produces, since it writes the Auth\n * record directly. Setting the new row primary without clearing the old one\n * left TWO rows flagged primary, and every reader that takes the first match\n * then answers with whichever Firestore returned first.\n *\n * Only when there were pre-existing rows: a first-ever seed has nothing to\n * reconcile and must not pay for a second read and a batch commit.\n */\n if (rows.length > 0) await reconcilePrimaryFlag(uid, primaryAddress)\n // Claim the index for it too, but never steal one: an address already\n // indexed to somebody else is a real conflict that a backfill must not\n // paper over. Best-effort — a failed claim must not stop someone reading\n // their own settings page.\n if (authEmailVerified === true) {\n try {\n await claimIndexEntry(primaryAddress, uid)\n } catch (error) {\n console.error('[account-emails] primary index backfill failed', error)\n }\n }\n return [\n ...rows,\n {\n address: primaryAddress,\n verified: authEmailVerified === true,\n primary: true,\n verifiedAt: null,\n },\n ]\n}\n\nasync function reconcilePrimaryFlag(uid: string, primaryAddress: string): Promise<void> {\n const snapshot = await emailsRef(uid).get()\n const batch = firestore().batch()\n for (const doc of snapshot.docs) {\n const shouldBePrimary = doc.id === primaryAddress\n if ((doc.get('primary') === true) !== shouldBePrimary) {\n batch.set(doc.ref, { primary: shouldBePrimary }, { merge: true })\n }\n }\n await batch.commit()\n}\n\n/**\n * Claim `address` for `uid` in the uniqueness index, transactionally.\n *\n * Returns false when another account already holds it. Re-claiming your own\n * is a no-op success, which is what makes the whole flow idempotent.\n */\nasync function claimIndexEntry(address: string, uid: string): Promise<boolean> {\n return firestore().runTransaction(async (transaction) => {\n const ref = indexRef(address)\n const existing = await transaction.get(ref)\n if (existing.exists) {\n const owner = existing.get('uid')\n if (owner !== uid) return false\n return true\n }\n transaction.set(ref, { uid, address, claimedAt: FieldValue.serverTimestamp() })\n return true\n })\n}\n\n/**\n * Is `address` spoken for by an account other than `uid`?\n *\n * Consults BOTH the index and Firebase Auth, and the Auth half is the\n * load-bearing one. The index only knows about addresses that have been\n * through this feature; every account that existed before it has its primary\n * in the Auth record and nowhere else. Checking the index alone would let a\n * brand-new account claim an established user's sign-up address, which is the\n * exact ambiguity the uniqueness rule exists to prevent.\n *\n * `findUserByEmailAcrossPools` rather than a project-pool `getUserByEmail`:\n * an SSO user lives in their org's GCIP tenant and is invisible to\n * project-level lookups (AGL-1122), so the narrow call would report an\n * enterprise customer's address as free.\n */\nasync function addressTakenByAnother(address: string, uid: string): Promise<boolean> {\n const indexed = await indexRef(address).get()\n if (indexed.exists && indexed.get('uid') !== uid) return true\n const pooled = await findUserByEmailAcrossPools(address)\n if (pooled !== null && pooled !== undefined && pooled.record.uid !== uid) return true\n return false\n}\n\n/**\n * Stage a new address and return the secret for its confirmation link.\n *\n * The address is stored UNVERIFIED and does nothing until the round-trip\n * completes: it is not a sign-in identifier, it receives no account mail, and\n * — importantly — it does NOT claim the uniqueness index. Claiming on `add`\n * would make this endpoint a squatting tool: anyone could park an address\n * they do not own and lock its real owner out of adding it. The index is\n * claimed by {@link confirmAccountEmail}, so the first account to prove\n * delivery wins, and proving delivery is the only way to win.\n *\n * The pre-flight `addressTakenByAnother` here is a courtesy, not the guard —\n * it turns the common case into an immediate, honest error instead of a\n * confirmation email that fails at the end. The real check runs again inside\n * the confirmation transaction, because anything can change in between.\n */\nexport async function addAccountEmail(\n uid: string,\n input: unknown,\n): Promise<AccountEmailResult & { address: string | null; secret: string | null }> {\n const address = normalizeAccountEmail(input)\n if (address === null) {\n return {\n ...refuse('invalid-address', 'Enter a valid email address.'),\n address: null,\n secret: null,\n }\n }\n\n const existing = await emailsRef(uid).get()\n if (existing.docs.some((doc) => doc.id === address)) {\n return {\n ...refuse('already-on-this-account', 'That address is already on this account.'),\n address,\n secret: null,\n }\n }\n // THE CAP (see MAX_ACCOUNT_EMAILS). Counted from a server read immediately\n // before the write — a number read anywhere else is a number that can be\n // stale by the time it is trusted.\n if (existing.size >= MAX_ACCOUNT_EMAILS) {\n return {\n ...refuse(\n 'cap-reached',\n `An account can hold ${MAX_ACCOUNT_EMAILS} email addresses. ` +\n 'Remove one before adding another.',\n ),\n address,\n secret: null,\n }\n }\n if (await addressTakenByAnother(address, uid)) {\n return {\n ...refuse(\n 'claimed-by-another-account',\n 'That address is already in use on another account.',\n ),\n address,\n secret: null,\n }\n }\n\n await emailsRef(uid).doc(address).set(\n {\n address,\n verified: false,\n primary: false,\n createdAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n\n const secret = await issueVerificationToken(uid, address)\n return { ...ok(), address, secret }\n}\n\n/**\n * Mint a single-use confirmation secret and store only its digest.\n *\n * The returned string is `{tokenId}.{secret}`; the caller puts it in the\n * emailed link and never persists it. A reader of the database therefore\n * cannot confirm anybody's address — they hold a SHA-256 of the half that\n * matters.\n */\nexport async function issueVerificationToken(\n uid: string,\n address: string,\n): Promise<string> {\n const tokenId = randomBytes(16).toString('hex')\n const secret = randomBytes(32).toString('hex')\n await firestore()\n .collection(EMAIL_VERIFICATIONS_COLLECTION)\n .doc(tokenId)\n .set({\n uid,\n address,\n digest: createHash('sha256').update(secret).digest('hex'),\n createdAt: FieldValue.serverTimestamp(),\n expiresAt: Date.now() + EMAIL_VERIFICATION_TTL_MS,\n })\n return `${tokenId}.${secret}`\n}\n\n/** Constant-time compare of two hex digests of equal length. */\nfunction digestsMatch(a: unknown, b: string): boolean {\n if (typeof a !== 'string' || a.length !== b.length) return false\n return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'))\n}\n\n/**\n * Complete the round-trip: the bearer of this link can receive mail at the\n * address, so the address becomes verified and the account claims it.\n *\n * Deliberately NOT authenticated against the current session. The person\n * clicking the link is whoever opened the mailbox, and requiring them to be\n * signed in as the right account first is how confirmation links strand\n * people who read mail on a different device. The token itself carries the\n * uid, and it can do nothing except verify the one address it was minted for.\n *\n * The uniqueness claim happens HERE and inside the same logical step as the\n * flag flip, so two accounts racing on one address cannot both end up\n * verified.\n */\nexport async function confirmAccountEmail(\n token: unknown,\n): Promise<AccountEmailResult & { address: string | null; uid: string | null }> {\n const raw = String(token ?? '')\n const separator = raw.indexOf('.')\n if (separator <= 0) {\n return {\n ...refuse('token-invalid', 'That confirmation link is not valid.'),\n address: null,\n uid: null,\n }\n }\n const tokenId = raw.slice(0, separator)\n const secret = raw.slice(separator + 1)\n if (!/^[a-f0-9]{32}$/.test(tokenId) || !/^[a-f0-9]{64}$/.test(secret)) {\n return {\n ...refuse('token-invalid', 'That confirmation link is not valid.'),\n address: null,\n uid: null,\n }\n }\n\n const tokenRef = firestore().collection(EMAIL_VERIFICATIONS_COLLECTION).doc(tokenId)\n const snapshot = await tokenRef.get()\n if (!snapshot.exists) {\n return {\n ...refuse('token-invalid', 'That confirmation link has already been used.'),\n address: null,\n uid: null,\n }\n }\n if (!digestsMatch(snapshot.get('digest'), createHash('sha256').update(secret).digest('hex'))) {\n return {\n ...refuse('token-invalid', 'That confirmation link is not valid.'),\n address: null,\n uid: null,\n }\n }\n const expiresAt = Number(snapshot.get('expiresAt') ?? 0)\n if (!Number.isFinite(expiresAt) || expiresAt < Date.now()) {\n await tokenRef.delete()\n return {\n ...refuse('token-expired', 'That confirmation link has expired — send a new one.'),\n address: null,\n uid: null,\n }\n }\n\n const uid = String(snapshot.get('uid') ?? '')\n const address = String(snapshot.get('address') ?? '')\n if (!uid || !address) {\n await tokenRef.delete()\n return {\n ...refuse('token-invalid', 'That confirmation link is not valid.'),\n address: null,\n uid: null,\n }\n }\n\n // Single-use: burned before the claim, so a link cannot be replayed even if\n // the claim below fails.\n await tokenRef.delete()\n\n if (await addressTakenByAnother(address, uid)) {\n return {\n ...refuse(\n 'claimed-by-another-account',\n 'That address has since been confirmed on another account.',\n ),\n address,\n uid,\n }\n }\n const claimed = await claimIndexEntry(address, uid)\n if (!claimed) {\n return {\n ...refuse(\n 'claimed-by-another-account',\n 'That address has since been confirmed on another account.',\n ),\n address,\n uid,\n }\n }\n\n await emailsRef(uid)\n .doc(address)\n .set(\n { address, verified: true, verifiedAt: FieldValue.serverTimestamp() },\n { merge: true },\n )\n return { ...ok(), address, uid }\n}\n\n/**\n * Remove an address, freeing its index entry.\n *\n * The index entry is released so the address can be used again — on this\n * account or another. Leaving it behind would make removal a way to burn an\n * address permanently, including somebody else's if they ever wanted it.\n */\nexport async function removeAccountEmail(\n uid: string,\n input: unknown,\n): Promise<AccountEmailResult> {\n const address = normalizeAccountEmail(input)\n if (address === null) return refuse('invalid-address', 'Enter a valid email address.')\n\n const snapshot = await emailsRef(uid).get()\n const rows: AccountEmail[] = snapshot.docs.map((doc) => ({\n address: String(doc.get('address') ?? doc.id),\n verified: doc.get('verified') === true,\n primary: doc.get('primary') === true,\n }))\n const verdict = canRemoveAccountEmail(address, rows)\n if (!verdict.allowed) {\n const row = rows.find((entry) => entry.address === address)\n // Distinct codes so the card can say WHICH floor it hit — \"make another\n // address primary first\" and \"this is your only confirmed address\" are\n // different instructions, and a single code would collapse them into one\n // unhelpful sentence.\n const code: AccountEmailRefusal =\n row === undefined\n ? 'unknown-address'\n : row.primary === true\n ? 'cannot-remove-primary'\n : 'last-verified-address'\n return refuse(code, String(verdict.message ?? 'That address cannot be removed.'))\n }\n\n await emailsRef(uid).doc(address).delete()\n const indexed = await indexRef(address).get()\n if (indexed.exists && indexed.get('uid') === uid) {\n await indexRef(address).delete()\n }\n return ok()\n}\n\nexport interface SetPrimaryContext {\n /** `decoded.firebase?.tenant` — the pool the caller signed in through. */\n tenantId: string | null\n}\n\n/**\n * Re-designate the primary address.\n *\n * THE MOST SECURITY-SENSITIVE WRITE IN THIS MODULE, because the primary IS\n * the Firebase Auth record's email, which is what `decoded.email` carries,\n * which is what `evaluateSsoDomainPolicy` reads at the session mint and what\n * the invite-accept comparison matches on. Changing it changes an\n * authorization input — so it goes through `evaluatePrimaryChange` first, and\n * that function refuses to move a primary off a domain the deployment\n * requires SSO for. See its docstring for why that refusal ignores the\n * enforcement switch.\n *\n * The Auth record is updated in the account's OWN pool via `authForPool`: a\n * project-level `updateUser` cannot see a GCIP tenant account, so the narrow\n * call would silently fail for exactly the enterprise users this policy is\n * about.\n *\n * `emailVerified: true` is set alongside the address, and it is honest — the\n * only addresses that can reach this point are ones this module verified by\n * an emailed round-trip. Omitting it would flip the account to unverified and\n * lock it out of every route behind `emailUnverifiedResponse()`.\n */\nexport async function setPrimaryAccountEmail(\n uid: string,\n input: unknown,\n context: SetPrimaryContext,\n): Promise<AccountEmailResult> {\n const address = normalizeAccountEmail(input)\n if (address === null) return refuse('invalid-address', 'Enter a valid email address.')\n\n const snapshot = await emailsRef(uid).get()\n const rows: AccountEmail[] = snapshot.docs.map((doc) => ({\n address: String(doc.get('address') ?? doc.id),\n verified: doc.get('verified') === true,\n primary: doc.get('primary') === true,\n }))\n const current = rows.find((row) => row.primary === true) ?? null\n const next = rows.find((row) => row.address === address) ?? null\n\n const decision = evaluatePrimaryChange({\n current,\n next,\n requiredDomains: ssoRequiredDomains(),\n tenantId: context.tenantId ?? null,\n enforcementEnabled: ssoDomainEnforcementEnabled(),\n })\n if (!decision.allowed) {\n return refuse(decision.verdict, String(decision.message ?? 'That change is not allowed.'))\n }\n\n // The index entry being ours is not enough: an account created later can\n // hold this address as its Auth email without ever touching the index (a\n // federated sign-up with an address that was once our provider address,\n // AGL-4041). Auth refuses the move with EMAIL_EXISTS, so ask first and\n // answer with a refusal rather than letting it surface as a 500.\n const taken = refuse(\n 'claimed-by-another-account',\n 'That address is now the sign-in email of another account, so it cannot be your primary.',\n )\n if (await addressTakenByAnother(address, uid)) return taken\n\n try {\n await authForPool(context.tenantId).updateUser(uid, {\n email: address,\n emailVerified: true,\n })\n } catch (error) {\n // The same refusal when the other account appears between the check and\n // the write.\n if ((error as { code?: unknown })?.code === 'auth/email-already-exists') return taken\n throw error\n }\n await reconcilePrimaryFlag(uid, address)\n return ok()\n}\n\n/**\n * The account that holds `address` as a VERIFIED alias, or null.\n *\n * ## Read this before calling it\n *\n * This is the one lookup that maps an arbitrary address to an account, and it\n * exists for exactly two callers: resolving a sign-in identifier, and\n * matching an org invitation. Both are safe for the same reason — neither\n * GRANTS anything on the strength of the address:\n *\n * - a sign-in identifier still has to be followed by the account's password;\n * - an invitation is an explicit grant the ORG made, and this only decides\n * which of the recipient's mailboxes it may arrive at.\n *\n * It must never be wired into an SSO path. `sso-jit` resolves the org from\n * the GCIP tenant on a re-verified token and matches the domain the IdP\n * asserted; giving it this function would let a user add an address and be\n * provisioned into the matching organization, which is the escalation this\n * whole feature was designed around.\n *\n * Returns null for an unverified row by construction: the index is only ever\n * written by the confirmation path.\n */\nexport async function findAccountByVerifiedAlias(\n input: unknown,\n): Promise<{ uid: string; address: string } | null> {\n const address = normalizeAccountEmail(input)\n if (address === null) return null\n const indexed = await indexRef(address).get()\n if (!indexed.exists) return null\n const uid = String(indexed.get('uid') ?? '')\n if (!uid) return null\n return { uid, address }\n}\n\n/*==========================================\n * PROVIDER-SUPPLIED ADDRESSES.\n *\n * A federated provider asserts its own address, and `providerData[].email`\n * can differ from the primary. Until now nothing registered one: it was\n * absent from `users/{uid}/emails`, held no `emailIdentityIndex` entry, and\n * so lived entirely OUTSIDE the uniqueness guard — while remaining a real\n * mailbox, a working sign-in identifier, and a recipient of real mail.\n *\n * The consequence is a collision the guard was built to prevent and could not\n * see: one address that is one account's primary and another account's Google\n * provider address. Anything mapping address → uid then answers confidently\n * and wrongly.\n *=========================================*/\n\n/** What one {@link registerProviderAddresses} pass did. */\nexport interface ProviderAddressRegistration {\n /** Addresses newly claimed for this account. */\n claimed: string[]\n /** Addresses another account already holds — recorded, never taken. */\n conflicted: string[]\n}\n\n/**\n * Providers whose asserted address counts as proven.\n *\n * `password` is excluded because its address is the primary, already handled,\n * and its verification state lives on the Auth record rather than in the\n * provider entry. Everything else here is a federated IdP that has itself\n * established control of the mailbox — the same standard\n * {@link confirmAccountEmail} applies, met by a different party.\n */\nfunction isFederatedProvider(providerId: string | null | undefined): boolean {\n const id = String(providerId ?? '')\n return id !== '' && id !== 'password' && id !== 'phone' && id !== 'anonymous'\n}\n\n/**\n * Register the addresses a federated provider asserts for this account.\n *\n * Called from the session mint — the one place every interactive sign-in\n * passes through with a verified token — and BEST-EFFORT by contract.\n *\n * ## Three rules, in priority order\n *\n * 1. **Sign-in must not depend on this.** It is bookkeeping. A person locked\n * out because an index write failed is a worse outcome than the collision\n * it was preventing, so every failure here is swallowed and logged, and\n * the caller runs it off the critical path.\n * 2. **A claim never takes an entry another account holds.**\n * {@link claimIndexEntry} already refuses; what was missing is that the\n * refusal went nowhere. A conflict now lands on the row as\n * `indexConflict`, which the staff account page reads — silently skipping\n * is exactly what produced the live collision.\n * 3. **A conflicted address is stored UNVERIFIED.** This is the conservative\n * half and it matters: `verifiedAccountEmails` feeds invitation matching,\n * so marking a contested address verified on both accounts would make one\n * invitation match two people. Unverified, the row is a record that the\n * address exists on this account and grants nothing.\n *\n * ⛔ It does not merge, reassign or disable anything. Two real accounts\n * sharing an address is a human decision — the row makes it visible and stops\n * there.\n *\n * ⚠️ Registering here CANNOT reach SSO provisioning. `sso-jit` reads the\n * address the IdP asserted at sign-in and never consults this store;\n * `apps/console/specs/account-emails-never-reach-sso.spec.ts` fails if that\n * stops being true. That guard is what makes this safe to write at all.\n */\nexport async function registerProviderAddresses(\n uid: string,\n record: {\n email?: string | null\n providerData?: readonly {\n providerId?: string | null\n email?: string | null\n }[]\n } | null,\n): Promise<ProviderAddressRegistration> {\n const claimed: string[] = []\n const conflicted: string[] = []\n const primary = normalizeAccountEmail(record?.email ?? null)\n\n const candidates = new Set<string>()\n for (const provider of record?.providerData ?? []) {\n if (!isFederatedProvider(provider?.providerId)) continue\n const address = normalizeAccountEmail(provider?.email ?? null)\n // The primary is registered by `listAccountEmails`' own backfill, on the\n // Auth record's authority. Re-doing it here would race that seed.\n if (address === null || address === primary) continue\n candidates.add(address)\n }\n\n for (const address of candidates) {\n try {\n const won = await claimIndexEntry(address, uid)\n if (won) claimed.push(address)\n else conflicted.push(address)\n\n await emailsRef(uid)\n .doc(address)\n .set(\n {\n address,\n // Only when the claim was won — see rule 3.\n verified: won,\n primary: false,\n source: 'provider',\n ...(won\n ? { verifiedAt: FieldValue.serverTimestamp(), indexConflict: false }\n : { indexConflict: true, indexConflictAtMs: Date.now() }),\n createdAt: FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n } catch (error) {\n // Rule 1. Never rethrow: the caller is a sign-in.\n console.error('[account-emails] provider address registration failed', uid, error)\n }\n }\n\n if (conflicted.length) {\n // Loud, per rule 2 — a conflict that only ever landed in a document would\n // be discovered by whoever happened to open the right page.\n console.error(\n '[account-emails] provider address already claimed by another account',\n JSON.stringify({ uid, conflicted: conflicted.length }),\n )\n }\n return { claimed, conflicted }\n}\n\n/**\n * Every VERIFIED address on an account, for matching an invitation.\n *\n * Bounded by {@link MAX_ACCOUNT_EMAILS}, which is what makes it safe to feed\n * straight into a Firestore `in` query (limit 30).\n *\n * ⛔ NOT the answer to \"every address this account holds\" — it is verified-only,\n * subcollection-only and silently truncating, all correct here and all wrong\n * there. `account-addresses.ts` is that resolver and explains why at length.\n */\nexport async function verifiedAccountEmails(uid: string): Promise<string[]> {\n const snapshot = await emailsRef(uid).get()\n return snapshot.docs\n .filter((doc) => doc.get('verified') === true)\n .map((doc) => String(doc.get('address') ?? doc.id))\n .slice(0, MAX_ACCOUNT_EMAILS)\n}\n"],"names":["createHash","randomBytes","timingSafeEqual","MAX_ACCOUNT_EMAILS","evaluatePrimaryChange","canRemoveAccountEmail","normalizeAccountEmail","FieldValue","firebaseAdmin","authForPool","findUserByEmailAcrossPools","ssoDomainEnforcementEnabled","ssoRequiredDomains","firestore","app","ACCOUNT_EMAILS_SUBCOLLECTION","EMAIL_IDENTITY_INDEX_COLLECTION","EMAIL_VERIFICATIONS_COLLECTION","EMAIL_VERIFICATION_TTL_MS","ok","refusal","message","refuse","emailsRef","uid","collection","doc","indexRef","address","toRow","data","verifiedAt","verified","primary","undefined","toDate","toISOString","listAccountEmails","authEmail","authEmailVerified","snapshot","get","rows","docs","map","primaryAddress","known","find","row","reconcilePrimaryFlag","set","createdAt","serverTimestamp","merge","length","claimIndexEntry","error","console","batch","shouldBePrimary","id","ref","commit","runTransaction","transaction","existing","exists","owner","claimedAt","addressTakenByAnother","indexed","pooled","record","addAccountEmail","input","secret","some","size","issueVerificationToken","tokenId","toString","digest","update","expiresAt","Date","now","digestsMatch","a","b","Buffer","from","confirmAccountEmail","token","raw","String","separator","indexOf","slice","test","tokenRef","Number","isFinite","delete","claimed","removeAccountEmail","verdict","allowed","entry","code","setPrimaryAccountEmail","context","current","next","decision","requiredDomains","tenantId","enforcementEnabled","taken","updateUser","email","emailVerified","findAccountByVerifiedAlias","isFederatedProvider","providerId","registerProviderAddresses","conflicted","candidates","Set","provider","providerData","add","won","push","source","indexConflict","indexConflictAtMs","JSON","stringify","verifiedAccountEmails","filter"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GAED,SAASA,UAAU,EAAEC,WAAW,EAAEC,eAAe,QAAQ,cAAa;AACtE,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,qBAAqB,EACrBC,qBAAqB,QAGhB,wCAAuC;AAC9C,SAASC,UAAU,QAAQ,2BAA0B;AACrD,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,WAAW,EAAEC,0BAA0B,QAAQ,kBAAc;AACtE,SAASC,2BAA2B,EAAEC,kBAAkB,QAAQ,yBAAqB;AAErF,MAAMC,YAAY,IAAML,cAAcM,GAAG,GAAGD,SAAS;AAErD,OAAO,MAAME,+BAA+B,SAAQ;AAC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,GACD,OAAO,eAAea,sBAAsBlH,GAAW;IACrD,MAAMgB,WAAW,MAAMjB,UAAUC,KAAKiB,GAAG;IACzC,OAAOD,SAASG,IAAI,CACjBgG,MAAM,CAAC,CAACjH,MAAQA,IAAIe,GAAG,CAAC,gBAAgB,MACxCG,GAAG,CAAC,CAAClB;YAAeA;eAAPoE,QAAOpE,WAAAA,IAAIe,GAAG,CAAC,sBAARf,WAAsBA,IAAIkC,EAAE;OAChDqC,KAAK,CAAC,GAAG9F;AACd"}
@@ -105,6 +105,11 @@ export interface MintBundleLinkOptions {
105
105
  addons?: unknown;
106
106
  interval?: unknown;
107
107
  coupon?: unknown;
108
+ /**
109
+ * The Aglyn AI tier staff chose (AGL-4025), kept with the AI add-on; an
110
+ * `ai:<tier>` entry in `addons` names one too, and this wins when both do.
111
+ */
112
+ aiTier?: unknown;
108
113
  /** The chosen domain, quoted from the registrar's search; optional. */
109
114
  domain?: {
110
115
  name?: unknown;
@@ -43,6 +43,7 @@
43
43
  import { fitBundleAddonsToPlan, normalizeBundleDomain, parseBundleAddons } from "@aglyn/aglyn/app-utils/bundle-intent";
44
44
  import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
45
45
  import { onboardingDestination } from "@aglyn/aglyn/app-utils/onboarding-deep-link";
46
+ import { isAiTierId } from "@aglyn/aglyn/app-utils/plan-entitlements";
46
47
  import { isUpgradeProposalPlan, normalizeUpgradeProposalBundle, upgradeProposalIntent } from "@aglyn/aglyn/app-utils/upgrade-proposal";
47
48
  import { isLiveSubscriptionStatus, ORG_BILLING_DOC_ID, ORG_BILLING_SUBCOLLECTION } from "@aglyn/aglyn/app-utils/org-billing-doc";
48
49
  import { FieldValue } from "firebase-admin/firestore";
@@ -93,8 +94,9 @@ function cents(value) {
93
94
  addons: fitted.addons,
94
95
  interval: options.interval,
95
96
  coupon: options.coupon,
96
- // The tier an `ai:<tier>` entry named (AGL-3965), kept with the AI add-on.
97
- aiTier: parsed.aiTier
97
+ // The tier staff chose (AGL-4025), or the one an `ai:<tier>` entry named
98
+ // (AGL-3965), kept with the AI add-on.
99
+ aiTier: isAiTierId(options.aiTier) ? options.aiTier : parsed.aiTier
98
100
  });
99
101
  const intent = _extends({
100
102
  plan
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/bundle-links.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 * A STAFF-MINTED BUNDLE CHECKOUT LINK (AGL-3955).\n *\n * At a booth or on a doorstep, a staff member who built the owner's site\n * shows a QR; the owner scans it on their own phone and lands on Billing with\n * the plan, the add-ons, the cadence and the coupon already chosen, one tap\n * from paid. The link itself is an ordinary Billing URL — the query the\n * marketing CTAs and the upgrade proposal already speak — so it works without\n * any record at all.\n *\n * The RECORD is for two things the URL cannot carry honestly:\n *\n * - the chosen domain and its price, which the Billing page shows as a line\n * of its own and the owner then buys on the site's Custom Domain page. Read\n * from the record, never from the URL, so an edited link cannot show a name\n * or a price nobody quoted.\n * - the staff accountability that lets the link stand in for the domains\n * plugin's 72-hour paid-invoice gate, once (Zach, 2026-10-19). A staff\n * member met the owner and is named on the `billing.bundle-link-minted`\n * audit row; the link is for one workspace, lives 24 hours and is spent by\n * the first purchase it pre-clears. The plugin asks through\n * `core.purchase-gate-preclearance` and never reads this collection.\n *\n * Documents live in the top-level `bundleLinks` collection, keyed by an\n * unguessable id and carrying the workspace. Only the Admin SDK reads or\n * writes them; the rules deny every client, staff included.\n */\n\nimport type { AiTierId, OrgPlan } from '@aglyn/aglyn/server'\nimport {\n fitBundleAddonsToPlan,\n normalizeBundleDomain,\n parseBundleAddons,\n type AddonKind,\n type BundleAddons,\n} from '@aglyn/aglyn/app-utils/bundle-intent'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { onboardingDestination } from '@aglyn/aglyn/app-utils/onboarding-deep-link'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n upgradeProposalIntent,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport type {\n PurchaseGatePreclearance,\n PurchaseGatePreclearanceInput,\n} from '@aglyn/aglyn/plugin-manager/purchase-gate-preclearance'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport firebaseAdmin from './firebase-admin'\n\nexport const BUNDLE_LINKS_COLLECTION = 'bundleLinks'\n\n/** How long a link pre-clears, from its minting. */\nexport const BUNDLE_LINK_TTL_MS = 24 * 60 * 60 * 1000\n\n/** The query param that names the record, on a link that carries a domain. */\nexport const BUNDLE_LINK_PARAM = 'bundle'\n\n/** The audit action every mint writes, with the staff member's uid. */\nexport const BUNDLE_LINK_AUDIT_ACTION = 'billing.bundle-link-minted'\n\n/** The most a quoted domain may cost a year, in cents, before it reads as a typo. */\nconst DOMAIN_PRICE_MAX_CENTS = 100_000\n\n/** Whether this deployment sells domains: the registrar the domains plugin buys through. */\nexport function domainsRegistrarConfigured(): boolean {\n return Boolean(String(process.env['DOMAINS_REGISTRAR'] ?? '').trim())\n}\n\nexport interface BundleLinkDomain {\n /** The registrable name, lower-cased. */\n name: string\n /** The registrar's first-year price when the link was minted, in cents. */\n firstYearCents: number\n /** The yearly renewal price, in cents. */\n renewalCents: number\n /** The site the name is for: where the owner lands to buy it. */\n hostId: string\n}\n\nexport interface BundleLinkDoc {\n /** The staff member accountable for the link. */\n mintedBy: string\n mintedByEmail: string | null\n /** The one workspace the link is for. */\n workspaceId: string\n createdAt: number\n expiresAt: number\n /** When a purchase spent the link's preclearance; null until then. */\n usedAt: number | null\n /** Which gate the purchase that spent it waived. */\n usedFor?: string\n /** A staff-minted link stands in for the domains plugin's invoice-age gate, once. */\n preclearsDomainGate: true\n intent: {\n plan: OrgPlan\n addons?: BundleAddons\n interval?: 'month' | 'year'\n coupon?: string\n /** The Aglyn AI tier an `ai:<tier>` entry named (AGL-3965). */\n aiTier?: AiTierId\n }\n domain?: BundleLinkDomain\n}\n\n/** A mint refused before anything was written. */\nexport class BundleLinkError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'BundleLinkError'\n this.status = status\n }\n}\n\nexport interface MintBundleLinkOptions {\n orgId: string\n /** The staff member minting it. */\n actor: { uid: string; email?: string | null }\n /** The console origin the link is built on. */\n origin: string\n plan: unknown\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /** The chosen domain, quoted from the registrar's search; optional. */\n domain?: {\n name?: unknown\n firstYearCents?: unknown\n renewalCents?: unknown\n hostId?: unknown\n } | null\n /** Clock seam. */\n now?: number\n}\n\nexport interface MintedBundleLink {\n id: string\n url: string\n expiresAt: number\n intent: BundleLinkDoc['intent']\n domain: BundleLinkDomain | null\n /** Add-ons asked for that the plan does not sell, left off the link. */\n droppedAddons: Array<AddonKind | string>\n}\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nfunction cents(value: unknown): number | null {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 && number <= DOMAIN_PRICE_MAX_CENTS ? number : null\n}\n\n/**\n * Mint a link for one workspace: validate the bundle the way the proposal\n * does, write the record and its audit row in one batch, and answer the URL.\n *\n * Refused for a plan the workspace cannot buy itself, for a workspace with a\n * live subscription (checkout would refuse it; plan changes are Billing's),\n * and for a domain on a deployment that does not sell domains, for a site\n * outside the workspace, or without a price.\n */\nexport async function mintBundleLink(options: MintBundleLinkOptions): Promise<MintedBundleLink> {\n const { orgId, actor, origin } = options\n const now = options.now ?? Date.now()\n if (!orgId) throw new BundleLinkError('Missing orgId')\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new BundleLinkError('Choose a paid plan the workspace can buy itself')\n }\n const plan: OrgPlan = options.plan\n const parsed = parseBundleAddons(options.addons)\n const fitted = fitBundleAddonsToPlan(parsed.addons, plan)\n const bundle = normalizeUpgradeProposalBundle(plan, {\n addons: fitted.addons,\n interval: options.interval,\n coupon: options.coupon,\n // The tier an `ai:<tier>` entry named (AGL-3965), kept with the AI add-on.\n aiTier: parsed.aiTier,\n })\n const intent: BundleLinkDoc['intent'] = { plan, ...bundle }\n\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const [orgSnapshot, billingSnapshot] = await Promise.all([\n orgRef.get(),\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID).get(),\n ])\n if (!orgSnapshot.exists) throw new BundleLinkError('Unknown organization', 404)\n const slug = orgSnapshot.get('slug')\n if (typeof slug !== 'string' || !slug) {\n throw new BundleLinkError('This workspace has no address yet, so no link can point at it', 409)\n }\n const status =\n (billingSnapshot.get('subscription') as { status?: unknown } | undefined)?.status ??\n orgSnapshot.get('billingStatus')\n if (isLiveSubscriptionStatus(status)) {\n throw new BundleLinkError(\n 'This workspace already has a live subscription; change its plan from Billing instead',\n 409,\n )\n }\n\n let domain: BundleLinkDomain | null = null\n if (options.domain && options.domain.name) {\n if (!domainsRegistrarConfigured()) {\n throw new BundleLinkError('Buying a domain is not available on this deployment yet', 409)\n }\n const name = normalizeBundleDomain(options.domain.name)\n if (!name) throw new BundleLinkError('That is not a domain name')\n const firstYearCents = cents(options.domain.firstYearCents)\n const renewalCents = cents(options.domain.renewalCents)\n if (firstYearCents === null || renewalCents === null) {\n throw new BundleLinkError('Quote the domain’s first-year and renewal prices from its search')\n }\n const hostId = String(options.domain.hostId ?? '').trim()\n const host = hostId ? await db.collection('hosts').doc(hostId).get() : null\n if (!host?.exists || host.get('orgId') !== orgId) {\n throw new BundleLinkError('Choose the site in this workspace the domain is for')\n }\n domain = { name, firstYearCents, renewalCents, hostId }\n }\n\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(createResourceUid())\n const doc: BundleLinkDoc = {\n mintedBy: actor.uid,\n mintedByEmail: actor.email ?? null,\n workspaceId: orgId,\n createdAt: now,\n expiresAt: now + BUNDLE_LINK_TTL_MS,\n usedAt: null,\n preclearsDomainGate: true,\n intent,\n ...(domain ? { domain } : {}),\n }\n const batch = db.batch()\n batch.set(ref, doc)\n setAdminAudit(batch, db, {\n actorUid: actor.uid,\n ...(actor.email ? { actorEmail: actor.email } : {}),\n action: BUNDLE_LINK_AUDIT_ACTION,\n target: `orgs/${orgId}`,\n after: {\n bundleLinkId: ref.id,\n intent,\n domain,\n expiresAt: doc.expiresAt,\n preclearsDomainGate: true,\n },\n at: FieldValue.serverTimestamp(),\n })\n await batch.commit()\n\n const path = onboardingDestination(slug, upgradeProposalIntent(intent))\n const url = `${origin}${path}${domain ? `&${BUNDLE_LINK_PARAM}=${ref.id}` : ''}`\n return {\n id: ref.id,\n url,\n expiresAt: doc.expiresAt,\n intent,\n domain,\n droppedAddons: [...parsed.dropped, ...fitted.notSold],\n }\n}\n\n/** Whether a stored link still pre-clears: unused, unexpired, and flagged. */\nexport function bundleLinkIsLive(doc: Partial<BundleLinkDoc> | undefined, now: number): boolean {\n return (\n !!doc &&\n doc.preclearsDomainGate === true &&\n (doc.usedAt === null || doc.usedAt === undefined) &&\n typeof doc.expiresAt === 'number' &&\n doc.expiresAt > now\n )\n}\n\n/**\n * The workspace's live link, or null. Read by the workspace alone (a\n * single-field equality, no composite index) and narrowed here: a workspace\n * holds a handful of links at most, each gone in a day.\n */\nasync function liveLinkFor(orgId: string, now: number): Promise<{ id: string } | null> {\n const snapshot = await firestore()\n .collection(BUNDLE_LINKS_COLLECTION)\n .where('workspaceId', '==', orgId)\n .limit(50)\n .get()\n const live = snapshot.docs\n .filter((doc) => bundleLinkIsLive(doc.data() as Partial<BundleLinkDoc>, now))\n .sort((a, b) => Number(b.get('createdAt') ?? 0) - Number(a.get('createdAt') ?? 0))\n return live[0] ? { id: live[0].id } : null\n}\n\n/**\n * The bundle links' answer to `core.purchase-gate-preclearance`.\n *\n * `check` reads only. `consume` marks the link used in a transaction that\n * writes only when nothing has, so two purchases racing on one link spend it\n * once: the second reads `usedAt` set and answers false.\n */\nexport function bundleLinkPreclearance(options: { now?: () => number } = {}): PurchaseGatePreclearance {\n const clock = options.now ?? (() => Date.now())\n return {\n async check(input: PurchaseGatePreclearanceInput) {\n const orgId = String(input?.orgId ?? '').trim()\n if (!orgId || input?.gate !== 'domain-payment-history') return null\n const live = await liveLinkFor(orgId, clock())\n return live ? { preclearanceId: live.id } : null\n },\n async consume(preclearanceId: string) {\n const id = String(preclearanceId ?? '').trim()\n if (!id || id.includes('/')) return false\n const db = firestore()\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(id)\n return db.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const now = clock()\n if (!bundleLinkIsLive(snapshot.data() as Partial<BundleLinkDoc>, now)) return false\n tx.update(ref, { usedAt: now, usedFor: 'domain-payment-history' })\n return true\n })\n },\n }\n}\n\nexport interface BundleLinkDomainLine {\n name: string\n firstYearCents: number\n renewalCents: number\n /** The site's Custom Domain page segment: its subdomain, else its id. */\n host: string\n hostId: string\n}\n\n/**\n * The domain line Billing shows for a link (AGL-3955), or why there is none:\n * the link is for another workspace, is spent or expired, names no domain,\n * or this deployment does not sell domains (`available: false`, so the page\n * can show the line disabled with the reason rather than hide it).\n */\nexport async function readBundleLinkDomain(\n orgId: string,\n linkId: string,\n now: number = Date.now(),\n): Promise<{ domain: BundleLinkDomainLine | null; available: boolean }> {\n const available = domainsRegistrarConfigured()\n const id = String(linkId ?? '').trim()\n if (!orgId || !id || id.includes('/')) return { domain: null, available }\n const db = firestore()\n const snapshot = await db.collection(BUNDLE_LINKS_COLLECTION).doc(id).get()\n const doc = snapshot.data() as Partial<BundleLinkDoc> | undefined\n if (!snapshot.exists || doc?.workspaceId !== orgId || !doc?.domain) {\n return { domain: null, available }\n }\n if (!bundleLinkIsLive(doc, now)) return { domain: null, available }\n const host = await db.collection('hosts').doc(doc.domain.hostId).get()\n if (!host.exists || host.get('orgId') !== orgId) return { domain: null, available }\n return {\n available,\n domain: {\n name: doc.domain.name,\n firstYearCents: doc.domain.firstYearCents,\n renewalCents: doc.domain.renewalCents,\n hostId: doc.domain.hostId,\n host: String(host.get('subdomain') ?? doc.domain.hostId),\n },\n }\n}\n"],"names":["fitBundleAddonsToPlan","normalizeBundleDomain","parseBundleAddons","createResourceUid","onboardingDestination","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","upgradeProposalIntent","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","FieldValue","setAdminAudit","firebaseAdmin","BUNDLE_LINKS_COLLECTION","BUNDLE_LINK_TTL_MS","BUNDLE_LINK_PARAM","BUNDLE_LINK_AUDIT_ACTION","DOMAIN_PRICE_MAX_CENTS","domainsRegistrarConfigured","process","Boolean","String","env","trim","BundleLinkError","Error","message","status","name","firestore","app","cents","value","number","Math","round","Number","isFinite","mintBundleLink","options","actor","billingSnapshot","orgId","origin","now","Date","plan","parsed","addons","fitted","bundle","interval","coupon","aiTier","intent","db","orgRef","collection","doc","orgSnapshot","Promise","all","get","exists","slug","domain","firstYearCents","renewalCents","hostId","host","ref","mintedBy","uid","mintedByEmail","email","workspaceId","createdAt","expiresAt","usedAt","preclearsDomainGate","batch","set","actorUid","actorEmail","action","target","after","bundleLinkId","id","at","serverTimestamp","commit","path","url","droppedAddons","dropped","notSold","bundleLinkIsLive","undefined","liveLinkFor","snapshot","where","limit","live","docs","filter","data","sort","a","b","bundleLinkPreclearance","clock","check","input","gate","preclearanceId","consume","includes","runTransaction","tx","update","usedFor","readBundleLinkDomain","link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CC,QAAQV,IAAIO,MAAM,CAACG,MAAM;YACzBC,MAAMhD,QAAOgD,YAAAA,KAAKP,GAAG,CAAC,wBAATO,YAAyBX,IAAIO,MAAM,CAACG,MAAM;QACzD;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/bundle-links.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 * A STAFF-MINTED BUNDLE CHECKOUT LINK (AGL-3955).\n *\n * At a booth or on a doorstep, a staff member who built the owner's site\n * shows a QR; the owner scans it on their own phone and lands on Billing with\n * the plan, the add-ons, the cadence and the coupon already chosen, one tap\n * from paid. The link itself is an ordinary Billing URL — the query the\n * marketing CTAs and the upgrade proposal already speak — so it works without\n * any record at all.\n *\n * The RECORD is for two things the URL cannot carry honestly:\n *\n * - the chosen domain and its price, which the Billing page shows as a line\n * of its own and the owner then buys on the site's Custom Domain page. Read\n * from the record, never from the URL, so an edited link cannot show a name\n * or a price nobody quoted.\n * - the staff accountability that lets the link stand in for the domains\n * plugin's 72-hour paid-invoice gate, once (Zach, 2026-10-19). A staff\n * member met the owner and is named on the `billing.bundle-link-minted`\n * audit row; the link is for one workspace, lives 24 hours and is spent by\n * the first purchase it pre-clears. The plugin asks through\n * `core.purchase-gate-preclearance` and never reads this collection.\n *\n * Documents live in the top-level `bundleLinks` collection, keyed by an\n * unguessable id and carrying the workspace. Only the Admin SDK reads or\n * writes them; the rules deny every client, staff included.\n */\n\nimport type { AiTierId, OrgPlan } from '@aglyn/aglyn/server'\nimport {\n fitBundleAddonsToPlan,\n normalizeBundleDomain,\n parseBundleAddons,\n type AddonKind,\n type BundleAddons,\n} from '@aglyn/aglyn/app-utils/bundle-intent'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { onboardingDestination } from '@aglyn/aglyn/app-utils/onboarding-deep-link'\nimport { isAiTierId } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n isUpgradeProposalPlan,\n normalizeUpgradeProposalBundle,\n upgradeProposalIntent,\n} from '@aglyn/aglyn/app-utils/upgrade-proposal'\nimport {\n isLiveSubscriptionStatus,\n ORG_BILLING_DOC_ID,\n ORG_BILLING_SUBCOLLECTION,\n} from '@aglyn/aglyn/app-utils/org-billing-doc'\nimport type {\n PurchaseGatePreclearance,\n PurchaseGatePreclearanceInput,\n} from '@aglyn/aglyn/plugin-manager/purchase-gate-preclearance'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { setAdminAudit } from './admin-audit-write'\nimport firebaseAdmin from './firebase-admin'\n\nexport const BUNDLE_LINKS_COLLECTION = 'bundleLinks'\n\n/** How long a link pre-clears, from its minting. */\nexport const BUNDLE_LINK_TTL_MS = 24 * 60 * 60 * 1000\n\n/** The query param that names the record, on a link that carries a domain. */\nexport const BUNDLE_LINK_PARAM = 'bundle'\n\n/** The audit action every mint writes, with the staff member's uid. */\nexport const BUNDLE_LINK_AUDIT_ACTION = 'billing.bundle-link-minted'\n\n/** The most a quoted domain may cost a year, in cents, before it reads as a typo. */\nconst DOMAIN_PRICE_MAX_CENTS = 100_000\n\n/** Whether this deployment sells domains: the registrar the domains plugin buys through. */\nexport function domainsRegistrarConfigured(): boolean {\n return Boolean(String(process.env['DOMAINS_REGISTRAR'] ?? '').trim())\n}\n\nexport interface BundleLinkDomain {\n /** The registrable name, lower-cased. */\n name: string\n /** The registrar's first-year price when the link was minted, in cents. */\n firstYearCents: number\n /** The yearly renewal price, in cents. */\n renewalCents: number\n /** The site the name is for: where the owner lands to buy it. */\n hostId: string\n}\n\nexport interface BundleLinkDoc {\n /** The staff member accountable for the link. */\n mintedBy: string\n mintedByEmail: string | null\n /** The one workspace the link is for. */\n workspaceId: string\n createdAt: number\n expiresAt: number\n /** When a purchase spent the link's preclearance; null until then. */\n usedAt: number | null\n /** Which gate the purchase that spent it waived. */\n usedFor?: string\n /** A staff-minted link stands in for the domains plugin's invoice-age gate, once. */\n preclearsDomainGate: true\n intent: {\n plan: OrgPlan\n addons?: BundleAddons\n interval?: 'month' | 'year'\n coupon?: string\n /** The Aglyn AI tier an `ai:<tier>` entry named (AGL-3965). */\n aiTier?: AiTierId\n }\n domain?: BundleLinkDomain\n}\n\n/** A mint refused before anything was written. */\nexport class BundleLinkError extends Error {\n readonly status: number\n constructor(message: string, status = 400) {\n super(message)\n this.name = 'BundleLinkError'\n this.status = status\n }\n}\n\nexport interface MintBundleLinkOptions {\n orgId: string\n /** The staff member minting it. */\n actor: { uid: string; email?: string | null }\n /** The console origin the link is built on. */\n origin: string\n plan: unknown\n addons?: unknown\n interval?: unknown\n coupon?: unknown\n /**\n * The Aglyn AI tier staff chose (AGL-4025), kept with the AI add-on; an\n * `ai:<tier>` entry in `addons` names one too, and this wins when both do.\n */\n aiTier?: unknown\n /** The chosen domain, quoted from the registrar's search; optional. */\n domain?: {\n name?: unknown\n firstYearCents?: unknown\n renewalCents?: unknown\n hostId?: unknown\n } | null\n /** Clock seam. */\n now?: number\n}\n\nexport interface MintedBundleLink {\n id: string\n url: string\n expiresAt: number\n intent: BundleLinkDoc['intent']\n domain: BundleLinkDomain | null\n /** Add-ons asked for that the plan does not sell, left off the link. */\n droppedAddons: Array<AddonKind | string>\n}\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nfunction cents(value: unknown): number | null {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 && number <= DOMAIN_PRICE_MAX_CENTS ? number : null\n}\n\n/**\n * Mint a link for one workspace: validate the bundle the way the proposal\n * does, write the record and its audit row in one batch, and answer the URL.\n *\n * Refused for a plan the workspace cannot buy itself, for a workspace with a\n * live subscription (checkout would refuse it; plan changes are Billing's),\n * and for a domain on a deployment that does not sell domains, for a site\n * outside the workspace, or without a price.\n */\nexport async function mintBundleLink(options: MintBundleLinkOptions): Promise<MintedBundleLink> {\n const { orgId, actor, origin } = options\n const now = options.now ?? Date.now()\n if (!orgId) throw new BundleLinkError('Missing orgId')\n if (!isUpgradeProposalPlan(options.plan)) {\n throw new BundleLinkError('Choose a paid plan the workspace can buy itself')\n }\n const plan: OrgPlan = options.plan\n const parsed = parseBundleAddons(options.addons)\n const fitted = fitBundleAddonsToPlan(parsed.addons, plan)\n const bundle = normalizeUpgradeProposalBundle(plan, {\n addons: fitted.addons,\n interval: options.interval,\n coupon: options.coupon,\n // The tier staff chose (AGL-4025), or the one an `ai:<tier>` entry named\n // (AGL-3965), kept with the AI add-on.\n aiTier: isAiTierId(options.aiTier) ? options.aiTier : parsed.aiTier,\n })\n const intent: BundleLinkDoc['intent'] = { plan, ...bundle }\n\n const db = firestore()\n const orgRef = db.collection('orgs').doc(orgId)\n const [orgSnapshot, billingSnapshot] = await Promise.all([\n orgRef.get(),\n orgRef.collection(ORG_BILLING_SUBCOLLECTION).doc(ORG_BILLING_DOC_ID).get(),\n ])\n if (!orgSnapshot.exists) throw new BundleLinkError('Unknown organization', 404)\n const slug = orgSnapshot.get('slug')\n if (typeof slug !== 'string' || !slug) {\n throw new BundleLinkError('This workspace has no address yet, so no link can point at it', 409)\n }\n const status =\n (billingSnapshot.get('subscription') as { status?: unknown } | undefined)?.status ??\n orgSnapshot.get('billingStatus')\n if (isLiveSubscriptionStatus(status)) {\n throw new BundleLinkError(\n 'This workspace already has a live subscription; change its plan from Billing instead',\n 409,\n )\n }\n\n let domain: BundleLinkDomain | null = null\n if (options.domain && options.domain.name) {\n if (!domainsRegistrarConfigured()) {\n throw new BundleLinkError('Buying a domain is not available on this deployment yet', 409)\n }\n const name = normalizeBundleDomain(options.domain.name)\n if (!name) throw new BundleLinkError('That is not a domain name')\n const firstYearCents = cents(options.domain.firstYearCents)\n const renewalCents = cents(options.domain.renewalCents)\n if (firstYearCents === null || renewalCents === null) {\n throw new BundleLinkError('Quote the domain’s first-year and renewal prices from its search')\n }\n const hostId = String(options.domain.hostId ?? '').trim()\n const host = hostId ? await db.collection('hosts').doc(hostId).get() : null\n if (!host?.exists || host.get('orgId') !== orgId) {\n throw new BundleLinkError('Choose the site in this workspace the domain is for')\n }\n domain = { name, firstYearCents, renewalCents, hostId }\n }\n\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(createResourceUid())\n const doc: BundleLinkDoc = {\n mintedBy: actor.uid,\n mintedByEmail: actor.email ?? null,\n workspaceId: orgId,\n createdAt: now,\n expiresAt: now + BUNDLE_LINK_TTL_MS,\n usedAt: null,\n preclearsDomainGate: true,\n intent,\n ...(domain ? { domain } : {}),\n }\n const batch = db.batch()\n batch.set(ref, doc)\n setAdminAudit(batch, db, {\n actorUid: actor.uid,\n ...(actor.email ? { actorEmail: actor.email } : {}),\n action: BUNDLE_LINK_AUDIT_ACTION,\n target: `orgs/${orgId}`,\n after: {\n bundleLinkId: ref.id,\n intent,\n domain,\n expiresAt: doc.expiresAt,\n preclearsDomainGate: true,\n },\n at: FieldValue.serverTimestamp(),\n })\n await batch.commit()\n\n const path = onboardingDestination(slug, upgradeProposalIntent(intent))\n const url = `${origin}${path}${domain ? `&${BUNDLE_LINK_PARAM}=${ref.id}` : ''}`\n return {\n id: ref.id,\n url,\n expiresAt: doc.expiresAt,\n intent,\n domain,\n droppedAddons: [...parsed.dropped, ...fitted.notSold],\n }\n}\n\n/** Whether a stored link still pre-clears: unused, unexpired, and flagged. */\nexport function bundleLinkIsLive(doc: Partial<BundleLinkDoc> | undefined, now: number): boolean {\n return (\n !!doc &&\n doc.preclearsDomainGate === true &&\n (doc.usedAt === null || doc.usedAt === undefined) &&\n typeof doc.expiresAt === 'number' &&\n doc.expiresAt > now\n )\n}\n\n/**\n * The workspace's live link, or null. Read by the workspace alone (a\n * single-field equality, no composite index) and narrowed here: a workspace\n * holds a handful of links at most, each gone in a day.\n */\nasync function liveLinkFor(orgId: string, now: number): Promise<{ id: string } | null> {\n const snapshot = await firestore()\n .collection(BUNDLE_LINKS_COLLECTION)\n .where('workspaceId', '==', orgId)\n .limit(50)\n .get()\n const live = snapshot.docs\n .filter((doc) => bundleLinkIsLive(doc.data() as Partial<BundleLinkDoc>, now))\n .sort((a, b) => Number(b.get('createdAt') ?? 0) - Number(a.get('createdAt') ?? 0))\n return live[0] ? { id: live[0].id } : null\n}\n\n/**\n * The bundle links' answer to `core.purchase-gate-preclearance`.\n *\n * `check` reads only. `consume` marks the link used in a transaction that\n * writes only when nothing has, so two purchases racing on one link spend it\n * once: the second reads `usedAt` set and answers false.\n */\nexport function bundleLinkPreclearance(options: { now?: () => number } = {}): PurchaseGatePreclearance {\n const clock = options.now ?? (() => Date.now())\n return {\n async check(input: PurchaseGatePreclearanceInput) {\n const orgId = String(input?.orgId ?? '').trim()\n if (!orgId || input?.gate !== 'domain-payment-history') return null\n const live = await liveLinkFor(orgId, clock())\n return live ? { preclearanceId: live.id } : null\n },\n async consume(preclearanceId: string) {\n const id = String(preclearanceId ?? '').trim()\n if (!id || id.includes('/')) return false\n const db = firestore()\n const ref = db.collection(BUNDLE_LINKS_COLLECTION).doc(id)\n return db.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const now = clock()\n if (!bundleLinkIsLive(snapshot.data() as Partial<BundleLinkDoc>, now)) return false\n tx.update(ref, { usedAt: now, usedFor: 'domain-payment-history' })\n return true\n })\n },\n }\n}\n\nexport interface BundleLinkDomainLine {\n name: string\n firstYearCents: number\n renewalCents: number\n /** The site's Custom Domain page segment: its subdomain, else its id. */\n host: string\n hostId: string\n}\n\n/**\n * The domain line Billing shows for a link (AGL-3955), or why there is none:\n * the link is for another workspace, is spent or expired, names no domain,\n * or this deployment does not sell domains (`available: false`, so the page\n * can show the line disabled with the reason rather than hide it).\n */\nexport async function readBundleLinkDomain(\n orgId: string,\n linkId: string,\n now: number = Date.now(),\n): Promise<{ domain: BundleLinkDomainLine | null; available: boolean }> {\n const available = domainsRegistrarConfigured()\n const id = String(linkId ?? '').trim()\n if (!orgId || !id || id.includes('/')) return { domain: null, available }\n const db = firestore()\n const snapshot = await db.collection(BUNDLE_LINKS_COLLECTION).doc(id).get()\n const doc = snapshot.data() as Partial<BundleLinkDoc> | undefined\n if (!snapshot.exists || doc?.workspaceId !== orgId || !doc?.domain) {\n return { domain: null, available }\n }\n if (!bundleLinkIsLive(doc, now)) return { domain: null, available }\n const host = await db.collection('hosts').doc(doc.domain.hostId).get()\n if (!host.exists || host.get('orgId') !== orgId) return { domain: null, available }\n return {\n available,\n domain: {\n name: doc.domain.name,\n firstYearCents: doc.domain.firstYearCents,\n renewalCents: doc.domain.renewalCents,\n hostId: doc.domain.hostId,\n host: String(host.get('subdomain') ?? doc.domain.hostId),\n },\n }\n}\n"],"names":["fitBundleAddonsToPlan","normalizeBundleDomain","parseBundleAddons","createResourceUid","onboardingDestination","isAiTierId","isUpgradeProposalPlan","normalizeUpgradeProposalBundle","upgradeProposalIntent","isLiveSubscriptionStatus","ORG_BILLING_DOC_ID","ORG_BILLING_SUBCOLLECTION","FieldValue","setAdminAudit","firebaseAdmin","BUNDLE_LINKS_COLLECTION","BUNDLE_LINK_TTL_MS","BUNDLE_LINK_PARAM","BUNDLE_LINK_AUDIT_ACTION","DOMAIN_PRICE_MAX_CENTS","domainsRegistrarConfigured","process","Boolean","String","env","trim","BundleLinkError","Error","message","status","name","firestore","app","cents","value","number","Math","round","Number","isFinite","mintBundleLink","options","actor","billingSnapshot","orgId","origin","now","Date","plan","parsed","addons","fitted","bundle","interval","coupon","aiTier","intent","db","orgRef","collection","doc","orgSnapshot","Promise","all","get","exists","slug","domain","firstYearCents","renewalCents","hostId","host","ref","mintedBy","uid","mintedByEmail","email","workspaceId","createdAt","expiresAt","usedAt","preclearsDomainGate","batch","set","actorUid","actorEmail","action","target","after","bundleLinkId","id","at","serverTimestamp","commit","path","url","droppedAddons","dropped","notSold","bundleLinkIsLive","undefined","liveLinkFor","snapshot","where","limit","live","docs","filter","data","sort","a","b","bundleLinkPreclearance","clock","check","input","gate","preclearanceId","consume","includes","runTransaction","tx","update","usedFor","readBundleLinkDomain","linkId","available"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC;AAGD,SACEA,qBAAqB,EACrBC,qBAAqB,EACrBC,iBAAiB,QAGZ,uCAAsC;AAC7C,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,UAAU,QAAQ,2CAA0C;AACrE,SACEC,qBAAqB,EACrBC,8BAA8B,EAC9BC,qBAAqB,QAChB,0CAAyC;AAChD,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,yBAAyB,QACpB,yCAAwC;AAK/C,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,yBAAqB;AACnD,OAAOC,mBAAmB,sBAAkB;AAE5C,OAAO,MAAMC,0BAA0B,cAAa;AAEpD,kDAAkD,GAClD,OAAO,MAAMC,qBAAqB,KAAK,KAAK,KAAK,KAAI;AAErD,4EAA4E,GAC5E,OAAO,MAAMC,oBAAoB,SAAQ;AAEzC,qEAAqE,GACrE,OAAO,MAAMC,2BAA2B,6BAA4B;AAEpE,mFAAmF,GACnF,MAAMC,yBAAyB;AAE/B,0FAA0F,GAC1F,OAAO,SAASC;QACQC;IAAtB,OAAOC,QAAQC,QAAOF,iCAAAA,QAAQG,GAAG,CAAC,oBAAoB,YAAhCH,iCAAoC,IAAII,IAAI;AACpE;AAsCA,gDAAgD,GAChD,OAAO,MAAMC,wBAAwBC;IAEnC,YAAYC,OAAe,EAAEC,SAAS,GAAG,CAAE;QACzC,KAAK,CAACD;QACN,IAAI,CAACE,IAAI,GAAG;QACZ,IAAI,CAACD,MAAM,GA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G,MAAM,EAAEN,GAAG;IACpE,IAAI,CAACO,KAAKN,MAAM,IAAIM,KAAKP,GAAG,CAAC,aAAapB,OAAO,OAAO;QAAEuB,QAAQ;QAAM2D;IAAU;IAClF,OAAO;QACLA;QACA3D,QAAQ;YACNrC,MAAM8B,IAAIO,MAAM,CAACrC,IAAI;YACrBsC,gBAAgBR,IAAIO,MAAM,CAACC,cAAc;YACzCC,cAAcT,IAAIO,MAAM,CAACE,YAAY;YACrCC,QAAQV,IAAIO,MAAM,CAACG,MAAM;YACzBC,MAAMhD,QAAOgD,YAAAA,KAAKP,GAAG,CAAC,wBAATO,YAAyBX,IAAIO,MAAM,CAACG,MAAM;QACzD;IACF;AACF"}
@@ -489,6 +489,15 @@ export async function eraseHost(hostId, options = {}) {
489
489
  * including the tax a `mode: 'stripe'` store collects under AGLYN's own
490
490
  * Texas registration, which Aglyn must be able to account for long after the
491
491
  * merchant has gone.
492
+ *
493
+ * **`posHardwareSales` must NEVER be added either (AGL-4038).** Same shape,
494
+ * same trap: one row per card reader order a workspace bought from the
495
+ * platform's hardware shop — the platform's OWN sale, on which it owes the
496
+ * sales tax. The order under `orgs/{orgId}/hardwareOrders`, with the buyer's
497
+ * name, street, phone and email, dies with the tree as it should; the row
498
+ * keeps only the lines, amounts, tax, Stripe ids, status dates and the
499
+ * country, state and postal code it shipped to. The
500
+ * `erase-org-tax-retention.emulator.spec` pins its survival too.
492
501
  */ async function deleteDocsByOrgId(collection, orgId, dryRun = false, orgField = 'orgId') {
493
502
  if (!orgId) return 0;
494
503
  const firestore = firebaseAdmin.app().firestore();