@aglyn/tenant-data-admin 1.0.0-beta.288 → 1.0.0-beta.290

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.0.0-beta.288",
3
+ "version": "1.0.0-beta.290",
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.288",
29
- "@aglyn/shared-util-email": "1.0.0-beta.288",
30
- "@aglyn/shared-util-fbserver": "1.0.0-beta.288",
31
- "@aglyn/shared-util-first-touch": "1.0.0-beta.288",
32
- "@aglyn/shared-util-http": "1.0.0-beta.288",
33
- "@aglyn/shared-util-tools": "1.0.0-beta.288",
28
+ "@aglyn/aglyn": "1.0.0-beta.290",
29
+ "@aglyn/shared-util-email": "1.0.0-beta.290",
30
+ "@aglyn/shared-util-fbserver": "1.0.0-beta.290",
31
+ "@aglyn/shared-util-first-touch": "1.0.0-beta.290",
32
+ "@aglyn/shared-util-http": "1.0.0-beta.290",
33
+ "@aglyn/shared-util-tools": "1.0.0-beta.290",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -17,6 +17,7 @@
17
17
  import { readRequestCity, readRequestGeo, readRequestRegionLabel } from "@aglyn/aglyn/app-utils/request-geo";
18
18
  import { findUserByUidAcrossPools } from "./auth-pools.js";
19
19
  import firebaseAdmin from "./firebase-admin.js";
20
+ import { recordPlatformAccountContact } from "./platform-marketing-consent.js";
20
21
  /**
21
22
  * Write where an account came from, ONCE, at account creation (AGL-3289).
22
23
  *
@@ -67,7 +68,8 @@ import firebaseAdmin from "./firebase-admin.js";
67
68
  var _input_firestore, _input_nowMs, _input_invitedToOrgId;
68
69
  const firestore = (_input_firestore = input.firestore) != null ? _input_firestore : firebaseAdmin.app().firestore();
69
70
  const nowMs = (_input_nowMs = input.nowMs) != null ? _input_nowMs : Date.now();
70
- if (input.accountCreatedAtMs === null || !Number.isFinite(input.accountCreatedAtMs) || nowMs - input.accountCreatedAtMs > ACCOUNT_ACQUISITION_WINDOW_MS) {
71
+ const createdAtMs = input.accountCreatedAtMs;
72
+ if (createdAtMs === null || !Number.isFinite(createdAtMs) || nowMs - createdAtMs > ACCOUNT_ACQUISITION_WINDOW_MS) {
71
73
  return {
72
74
  status: 'not-new'
73
75
  };
@@ -79,12 +81,12 @@ import firebaseAdmin from "./firebase-admin.js";
79
81
  provider: input.provider,
80
82
  geo: requestGeography(input.headers),
81
83
  invitedToOrgId,
82
- accountCreatedAtMs: input.accountCreatedAtMs,
84
+ accountCreatedAtMs: createdAtMs,
83
85
  recordedBy: input.recordedBy,
84
86
  nowMs
85
87
  });
86
88
  const userRef = firestore.collection('users').doc(input.uid);
87
- return firestore.runTransaction(async (tx)=>{
89
+ const result = await firestore.runTransaction(async (tx)=>{
88
90
  const snapshot = await tx.get(userRef);
89
91
  const existing = snapshot.exists ? snapshot.get(ACCOUNT_ACQUISITION_FIELD) : undefined;
90
92
  if (existing !== undefined && existing !== null) {
@@ -103,6 +105,20 @@ import firebaseAdmin from "./firebase-admin.js";
103
105
  record
104
106
  };
105
107
  });
108
+ // Every door that creates an account passes here exactly once, so this is
109
+ // where the account becomes a contact in the operator's own CRM, whatever
110
+ // it said about marketing email. A failure there never fails the sign-up.
111
+ if (result.status === 'recorded') {
112
+ await recordPlatformAccountContact({
113
+ uid: input.uid,
114
+ email: input.email,
115
+ createdAtMs,
116
+ firestore
117
+ }).catch((error)=>{
118
+ console.error('[account-acquisition] platform contact failed', error);
119
+ });
120
+ }
121
+ return result;
106
122
  }
107
123
  /**
108
124
  * Record a self-serve sign-up's acquisition, deciding from the verified
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/account-acquisition.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ACCOUNT_ACQUISITION_FIELD,\n buildAccountAcquisition,\n readAccountAcquisition,\n signUpDoorFor,\n signUpProviderFor,\n type AccountAcquisition,\n type AcquisitionDoor,\n} from '@aglyn/aglyn/app-utils/account-acquisition'\nimport {\n readRequestCity,\n readRequestGeo,\n readRequestRegionLabel,\n type HeaderReader,\n} from '@aglyn/aglyn/app-utils/request-geo'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport firebaseAdmin from './firebase-admin'\n\n/**\n * Write where an account came from, ONCE, at account creation (AGL-3289).\n *\n * The capture kept the first touch on the visitor's device; the door that\n * created the account hands it here, with what only the server knows beside\n * it: the door, the sign-in provider from the verified token, where the\n * request came from as the edge reported it, and whether the address had an\n * invitation waiting. The record goes on `users/{uid}` inside a transaction\n * that writes nothing when one is already there — the first write wins, and\n * a retry, a second tab or a later call can never restate it.\n *\n * The rules deny the field to every client, so this Admin SDK write is the\n * only way in. `createOrganization` copies it onto the workspace the account\n * creates.\n */\n\n/**\n * How long after an account is created its door may still record where it\n * came from. A door calls within seconds of creating the account; a mobile\n * redirect or a slow verification page within minutes. Anything later is not\n * account creation, and a record written then would describe a later visit.\n */\nexport const ACCOUNT_ACQUISITION_WINDOW_MS = 30 * 60 * 1000\n\n/** What a door knows when it records an account. */\nexport interface RecordAccountAcquisitionInput {\n uid: string\n /** When the auth record says the account was created; null refuses. */\n accountCreatedAtMs: number | null\n /** The first touch the device kept — untrusted. */\n touch: unknown\n door: AcquisitionDoor\n /** From the verified token's `sign_in_provider`. */\n provider: string | null\n /** The account's address, for the invitation check; null when it has none. */\n email: string | null\n /** The organization an invitation the door already found came from. */\n invitedToOrgId?: string | null\n /** The account-creating request's headers, for its geography. */\n headers: HeaderReader\n recordedBy: 'signup' | 'sso'\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}\n\nexport type RecordAccountAcquisitionResult =\n | { status: 'recorded'; record: AccountAcquisition }\n | { status: 'exists'; record: AccountAcquisition | null }\n /** The account was not created just now, so this is not its creation. */\n | { status: 'not-new' }\n\n/**\n * The organization whose invitation this address has waiting, or null. The\n * same query the console's invitation banner runs, one address wide.\n */\nexport async function pendingInvitationOrgId(\n email: string | null,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<string | null> {\n const address = String(email ?? '').trim().toLowerCase()\n if (!address) return null\n try {\n const snapshot = await firestore\n .collectionGroup('invites')\n .where('email', 'in', [address])\n .where('acceptedAt', '==', null)\n .limit(1)\n .get()\n return snapshot.docs[0]?.ref.parent.parent?.id ?? null\n } catch (error) {\n // An unanswerable question costs the door's label, never the record.\n console.error('[account-acquisition] invitation lookup failed', error)\n return null\n }\n}\n\n/** Where the request came from, as a person reads it — no address, no coordinates. */\nexport function requestGeography(headers: HeaderReader): {\n country: string | null\n region: string | null\n city: string | null\n} {\n return {\n country: readRequestGeo(headers).country,\n region: readRequestRegionLabel(headers),\n city: readRequestCity(headers),\n }\n}\n\n/** Record the account's acquisition unless it already has one. */\nexport async function recordAccountAcquisition(\n input: RecordAccountAcquisitionInput,\n): Promise<RecordAccountAcquisitionResult> {\n const firestore = input.firestore ?? firebaseAdmin.app().firestore()\n const nowMs = input.nowMs ?? Date.now()\n if (\n input.accountCreatedAtMs === null ||\n !Number.isFinite(input.accountCreatedAtMs) ||\n nowMs - input.accountCreatedAtMs > ACCOUNT_ACQUISITION_WINDOW_MS\n ) {\n return { status: 'not-new' }\n }\n const invitedToOrgId =\n input.invitedToOrgId ??\n (input.door === 'signup-password' ||\n input.door === 'signup-google' ||\n input.door === 'signup-google-redirect'\n ? await pendingInvitationOrgId(input.email, firestore)\n : null)\n const record = buildAccountAcquisition({\n touch: input.touch,\n door: invitedToOrgId && input.door !== 'sso' ? 'invite' : input.door,\n provider: input.provider,\n geo: requestGeography(input.headers),\n invitedToOrgId,\n accountCreatedAtMs: input.accountCreatedAtMs,\n recordedBy: input.recordedBy,\n nowMs,\n })\n const userRef = firestore.collection('users').doc(input.uid)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(userRef)\n const existing = snapshot.exists ? snapshot.get(ACCOUNT_ACQUISITION_FIELD) : undefined\n if (existing !== undefined && existing !== null) {\n return { status: 'exists', record: readAccountAcquisition(existing) } as const\n }\n tx.set(userRef, { [ACCOUNT_ACQUISITION_FIELD]: record }, { merge: true })\n return { status: 'recorded', record } as const\n })\n}\n\n/** What a sign-up door knows about the account it is recording. */\nexport interface RecordSignUpAcquisitionInput {\n uid: string\n /** The verified token's `sign_in_provider`. */\n provider: string | null\n /** The verified token's address. */\n email: string | null\n /** The first touch the page sent, else the request's cookie — untrusted. */\n touch: unknown\n /** Which of the provider's doors the page says it was; see `signUpDoorFor`. */\n doorHint?: unknown\n headers: HeaderReader\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}\n\n/**\n * Record a self-serve sign-up's acquisition, deciding from the verified\n * provider and the auth record whether there is one to record.\n *\n * Shared by the two moments a sign-up passes through: the sign-up page's own\n * call, right after the account exists, and workspace creation, which is the\n * backstop for a page torn down before its call went out — the workspace\n * copies its creator's record at birth, so that is the last moment one can\n * still reach it. Both write through {@link recordAccountAcquisition}, so the\n * first one wins and neither can restate the other; an account older than\n * the window, or one a sign-up door did not create, writes nothing.\n *\n * `null` when the provider is not a sign-up door (SSO records its own).\n */\nexport async function recordSignUpAcquisition(\n input: RecordSignUpAcquisitionInput,\n): Promise<RecordAccountAcquisitionResult | null> {\n // A `custom` token can name no door until the auth record says which\n // provider made the account (AGL-3706), so the lookup comes first for it.\n const custom = input.provider === 'custom'\n if (!custom && !signUpDoorFor(input.provider, input.doorHint)) return null\n // Across every pool, not the project's alone (AGL-1122): a lookup that\n // cannot see an account answers \"not new\", which writes nothing.\n const pooled = await findUserByUidAcrossPools(input.uid)\n const provider = signUpProviderFor(\n input.provider,\n (pooled?.record.providerData ?? []).map((info) => info.providerId),\n )\n const door = signUpDoorFor(provider, input.doorHint)\n if (!door) return null\n const createdAtMs = Date.parse(pooled?.record.metadata.creationTime ?? '')\n return recordAccountAcquisition({\n uid: input.uid,\n accountCreatedAtMs: Number.isFinite(createdAtMs) ? createdAtMs : null,\n touch: input.touch,\n door,\n provider,\n email: input.email,\n headers: input.headers,\n recordedBy: 'signup',\n nowMs: input.nowMs,\n firestore: input.firestore,\n })\n}\n"],"names":["ACCOUNT_ACQUISITION_FIELD","buildAccountAcquisition","readAccountAcquisition","signUpDoorFor","signUpProviderFor","readRequestCity","readRequestGeo","readRequestRegionLabel","findUserByUidAcrossPools","firebaseAdmin","ACCOUNT_ACQUISITION_WINDOW_MS","pendingInvitationOrgId","email","firestore","app","address","String","trim","toLowerCase","snapshot","collectionGroup","where","limit","get","docs","ref","parent","id","error","console","requestGeography","headers","country","region","city","recordAccountAcquisition","input","nowMs","Date","now","accountCreatedAtMs","Number","isFinite","status","invitedToOrgId","door","record","touch","provider","geo","recordedBy","userRef","collection","doc","uid","runTransaction","tx","existing","exists","undefined","set","merge","recordSignUpAcquisition","custom","doorHint","pooled","providerData","map","info","providerId","createdAtMs","parse","metadata","creationTime"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,yBAAyB,EACzBC,uBAAuB,EACvBC,sBAAsB,EACtBC,aAAa,EACbC,iBAAiB,QAGZ,6CAA4C;AACnD,SACEC,eAAe,EACfC,cAAc,EACdC,sBAAsB,QAEjB,qCAAoC;AAC3C,SAASC,wBAAwB,QAAQ,kBAAc;AACvD,OAAOC,mB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AG,OAAO;IACtE,uEAAuE;IACvE,iEAAiE;IACjE,MAAMC,SAAS,MAAMzD,yBAAyB4B,MAAMkB,GAAG;IACvD,MAAMN,WAAW5C,kBACfgC,MAAMY,QAAQ,EACd,SAACiB,0BAAAA,OAAQnB,MAAM,CAACoB,YAAY,mBAAI,EAAE,EAAEC,GAAG,CAAC,CAACC,OAASA,KAAKC,UAAU;IAEnE,MAAMxB,OAAO1C,cAAc6C,UAAUZ,MAAM4B,QAAQ;IACnD,IAAI,CAACnB,MAAM,OAAO;IAClB,MAAMyB,cAAchC,KAAKiC,KAAK,UAACN,0BAAAA,OAAQnB,MAAM,CAAC0B,QAAQ,CAACC,YAAY,oBAAI;IACvE,OAAOtC,yBAAyB;QAC9BmB,KAAKlB,MAAMkB,GAAG;QACdd,oBAAoBC,OAAOC,QAAQ,CAAC4B,eAAeA,cAAc;QACjEvB,OAAOX,MAAMW,KAAK;QAClBF;QACAG;QACApC,OAAOwB,MAAMxB,KAAK;QAClBmB,SAASK,MAAML,OAAO;QACtBmB,YAAY;QACZb,OAAOD,MAAMC,KAAK;QAClBxB,WAAWuB,MAAMvB,SAAS;IAC5B;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/account-acquisition.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ACCOUNT_ACQUISITION_FIELD,\n buildAccountAcquisition,\n readAccountAcquisition,\n signUpDoorFor,\n signUpProviderFor,\n type AccountAcquisition,\n type AcquisitionDoor,\n} from '@aglyn/aglyn/app-utils/account-acquisition'\nimport {\n readRequestCity,\n readRequestGeo,\n readRequestRegionLabel,\n type HeaderReader,\n} from '@aglyn/aglyn/app-utils/request-geo'\nimport { findUserByUidAcrossPools } from './auth-pools'\nimport firebaseAdmin from './firebase-admin'\nimport { recordPlatformAccountContact } from './platform-marketing-consent'\n\n/**\n * Write where an account came from, ONCE, at account creation (AGL-3289).\n *\n * The capture kept the first touch on the visitor's device; the door that\n * created the account hands it here, with what only the server knows beside\n * it: the door, the sign-in provider from the verified token, where the\n * request came from as the edge reported it, and whether the address had an\n * invitation waiting. The record goes on `users/{uid}` inside a transaction\n * that writes nothing when one is already there — the first write wins, and\n * a retry, a second tab or a later call can never restate it.\n *\n * The rules deny the field to every client, so this Admin SDK write is the\n * only way in. `createOrganization` copies it onto the workspace the account\n * creates.\n */\n\n/**\n * How long after an account is created its door may still record where it\n * came from. A door calls within seconds of creating the account; a mobile\n * redirect or a slow verification page within minutes. Anything later is not\n * account creation, and a record written then would describe a later visit.\n */\nexport const ACCOUNT_ACQUISITION_WINDOW_MS = 30 * 60 * 1000\n\n/** What a door knows when it records an account. */\nexport interface RecordAccountAcquisitionInput {\n uid: string\n /** When the auth record says the account was created; null refuses. */\n accountCreatedAtMs: number | null\n /** The first touch the device kept — untrusted. */\n touch: unknown\n door: AcquisitionDoor\n /** From the verified token's `sign_in_provider`. */\n provider: string | null\n /** The account's address, for the invitation check; null when it has none. */\n email: string | null\n /** The organization an invitation the door already found came from. */\n invitedToOrgId?: string | null\n /** The account-creating request's headers, for its geography. */\n headers: HeaderReader\n recordedBy: 'signup' | 'sso'\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}\n\nexport type RecordAccountAcquisitionResult =\n | { status: 'recorded'; record: AccountAcquisition }\n | { status: 'exists'; record: AccountAcquisition | null }\n /** The account was not created just now, so this is not its creation. */\n | { status: 'not-new' }\n\n/**\n * The organization whose invitation this address has waiting, or null. The\n * same query the console's invitation banner runs, one address wide.\n */\nexport async function pendingInvitationOrgId(\n email: string | null,\n firestore: FirebaseFirestore.Firestore = firebaseAdmin.app().firestore(),\n): Promise<string | null> {\n const address = String(email ?? '').trim().toLowerCase()\n if (!address) return null\n try {\n const snapshot = await firestore\n .collectionGroup('invites')\n .where('email', 'in', [address])\n .where('acceptedAt', '==', null)\n .limit(1)\n .get()\n return snapshot.docs[0]?.ref.parent.parent?.id ?? null\n } catch (error) {\n // An unanswerable question costs the door's label, never the record.\n console.error('[account-acquisition] invitation lookup failed', error)\n return null\n }\n}\n\n/** Where the request came from, as a person reads it — no address, no coordinates. */\nexport function requestGeography(headers: HeaderReader): {\n country: string | null\n region: string | null\n city: string | null\n} {\n return {\n country: readRequestGeo(headers).country,\n region: readRequestRegionLabel(headers),\n city: readRequestCity(headers),\n }\n}\n\n/** Record the account's acquisition unless it already has one. */\nexport async function recordAccountAcquisition(\n input: RecordAccountAcquisitionInput,\n): Promise<RecordAccountAcquisitionResult> {\n const firestore = input.firestore ?? firebaseAdmin.app().firestore()\n const nowMs = input.nowMs ?? Date.now()\n const createdAtMs = input.accountCreatedAtMs\n if (\n createdAtMs === null ||\n !Number.isFinite(createdAtMs) ||\n nowMs - createdAtMs > ACCOUNT_ACQUISITION_WINDOW_MS\n ) {\n return { status: 'not-new' }\n }\n const invitedToOrgId =\n input.invitedToOrgId ??\n (input.door === 'signup-password' ||\n input.door === 'signup-google' ||\n input.door === 'signup-google-redirect'\n ? await pendingInvitationOrgId(input.email, firestore)\n : null)\n const record = buildAccountAcquisition({\n touch: input.touch,\n door: invitedToOrgId && input.door !== 'sso' ? 'invite' : input.door,\n provider: input.provider,\n geo: requestGeography(input.headers),\n invitedToOrgId,\n accountCreatedAtMs: createdAtMs,\n recordedBy: input.recordedBy,\n nowMs,\n })\n const userRef = firestore.collection('users').doc(input.uid)\n const result = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(userRef)\n const existing = snapshot.exists ? snapshot.get(ACCOUNT_ACQUISITION_FIELD) : undefined\n if (existing !== undefined && existing !== null) {\n return { status: 'exists', record: readAccountAcquisition(existing) } as const\n }\n tx.set(userRef, { [ACCOUNT_ACQUISITION_FIELD]: record }, { merge: true })\n return { status: 'recorded', record } as const\n })\n // Every door that creates an account passes here exactly once, so this is\n // where the account becomes a contact in the operator's own CRM, whatever\n // it said about marketing email. A failure there never fails the sign-up.\n if (result.status === 'recorded') {\n await recordPlatformAccountContact({\n uid: input.uid,\n email: input.email,\n createdAtMs,\n firestore,\n }).catch((error) => {\n console.error('[account-acquisition] platform contact failed', error)\n })\n }\n return result\n}\n\n/** What a sign-up door knows about the account it is recording. */\nexport interface RecordSignUpAcquisitionInput {\n uid: string\n /** The verified token's `sign_in_provider`. */\n provider: string | null\n /** The verified token's address. */\n email: string | null\n /** The first touch the page sent, else the request's cookie — untrusted. */\n touch: unknown\n /** Which of the provider's doors the page says it was; see `signUpDoorFor`. */\n doorHint?: unknown\n headers: HeaderReader\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}\n\n/**\n * Record a self-serve sign-up's acquisition, deciding from the verified\n * provider and the auth record whether there is one to record.\n *\n * Shared by the two moments a sign-up passes through: the sign-up page's own\n * call, right after the account exists, and workspace creation, which is the\n * backstop for a page torn down before its call went out — the workspace\n * copies its creator's record at birth, so that is the last moment one can\n * still reach it. Both write through {@link recordAccountAcquisition}, so the\n * first one wins and neither can restate the other; an account older than\n * the window, or one a sign-up door did not create, writes nothing.\n *\n * `null` when the provider is not a sign-up door (SSO records its own).\n */\nexport async function recordSignUpAcquisition(\n input: RecordSignUpAcquisitionInput,\n): Promise<RecordAccountAcquisitionResult | null> {\n // A `custom` token can name no door until the auth record says which\n // provider made the account (AGL-3706), so the lookup comes first for it.\n const custom = input.provider === 'custom'\n if (!custom && !signUpDoorFor(input.provider, input.doorHint)) return null\n // Across every pool, not the project's alone (AGL-1122): a lookup that\n // cannot see an account answers \"not new\", which writes nothing.\n const pooled = await findUserByUidAcrossPools(input.uid)\n const provider = signUpProviderFor(\n input.provider,\n (pooled?.record.providerData ?? []).map((info) => info.providerId),\n )\n const door = signUpDoorFor(provider, input.doorHint)\n if (!door) return null\n const createdAtMs = Date.parse(pooled?.record.metadata.creationTime ?? '')\n return recordAccountAcquisition({\n uid: input.uid,\n accountCreatedAtMs: Number.isFinite(createdAtMs) ? createdAtMs : null,\n touch: input.touch,\n door,\n provider,\n email: input.email,\n headers: input.headers,\n recordedBy: 'signup',\n nowMs: input.nowMs,\n firestore: input.firestore,\n })\n}\n"],"names":["ACCOUNT_ACQUISITION_FIELD","buildAccountAcquisition","readAccountAcquisition","signUpDoorFor","signUpProviderFor","readRequestCity","readRequestGeo","readRequestRegionLabel","findUserByUidAcrossPools","firebaseAdmin","recordPlatformAccountContact","ACCOUNT_ACQUISITION_WINDOW_MS","pendingInvitationOrgId","email","firestore","app","address","String","trim","toLowerCase","snapshot","collectionGroup","where","limit","get","docs","ref","parent","id","error","console","requestGeography","headers","country","region","city","recordAccountAcquisition","input","nowMs","Date","now","createdAtMs","accountCreatedAtMs","Number","isFinite","status","invitedToOrgId","door","record","touch","provider","geo","recordedBy","userRef","collection","doc","uid","result","runTransaction","tx","existing","exists","undefined","set","merge","catch","recordSignUpAcquisition","custom","doorHint","pooled","providerData","map","info","providerId","parse","metadata","creationTime"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,yBAAyB,EACzBC,uBAAuB,EACvBC,sBAAsB,EACtBC,aAAa,EACbC,iBAAiB,QAGZ,6CAA4C;AACnD,SACEC,eAAe,EACfC,cAAc,EACdC,sBAAsB,QAEjB,qCAAoC;AAC3C,SAASC,wBAAwB,QAAQ,kBAAc;AACvD,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,4BAA4B,QAAQ,kCAA8B;AAE3E;;;;;;;;;;;;;;CAcC,GAED;;;;;CAKC,GACD,OAAO,MAAMC,gCAAgC,KAAK,KAAK,KAAI;AA6B3D;;;CAGC,GACD,OAAO,eAAeC,uBACpBC,KAAoB,EACpBC,YAAyCL,cAAcM,GAAG,GAAG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C,IAAI,CAACiB,UAAU,CAAChE,cAAckC,MAAMa,QAAQ,EAAEb,MAAM+B,QAAQ,GAAG,OAAO;IACtE,uEAAuE;IACvE,iEAAiE;IACjE,MAAMC,SAAS,MAAM7D,yBAAyB6B,MAAMmB,GAAG;IACvD,MAAMN,WAAW9C,kBACfiC,MAAMa,QAAQ,EACd,SAACmB,0BAAAA,OAAQrB,MAAM,CAACsB,YAAY,mBAAI,EAAE,EAAEC,GAAG,CAAC,CAACC,OAASA,KAAKC,UAAU;IAEnE,MAAM1B,OAAO5C,cAAc+C,UAAUb,MAAM+B,QAAQ;IACnD,IAAI,CAACrB,MAAM,OAAO;IAClB,MAAMN,cAAcF,KAAKmC,KAAK,UAACL,0BAAAA,OAAQrB,MAAM,CAAC2B,QAAQ,CAACC,YAAY,oBAAI;IACvE,OAAOxC,yBAAyB;QAC9BoB,KAAKnB,MAAMmB,GAAG;QACdd,oBAAoBC,OAAOC,QAAQ,CAACH,eAAeA,cAAc;QACjEQ,OAAOZ,MAAMY,KAAK;QAClBF;QACAG;QACArC,OAAOwB,MAAMxB,KAAK;QAClBmB,SAASK,MAAML,OAAO;QACtBoB,YAAY;QACZd,OAAOD,MAAMC,KAAK;QAClBxB,WAAWuB,MAAMvB,SAAS;IAC5B;AACF"}
@@ -106,6 +106,39 @@ export interface RecordPlatformMarketingConsentResult {
106
106
  * operator's CRM band is not a reason to tell them their choice failed.
107
107
  */
108
108
  export declare function recordPlatformMarketingConsent(input: RecordPlatformMarketingConsentInput): Promise<RecordPlatformMarketingConsentResult>;
109
+ /** The timeline row an account's own contact opens with. */
110
+ export declare const PLATFORM_ACCOUNT_CREATED_SUMMARY = "Created an account";
111
+ export interface RecordPlatformAccountContactInput {
112
+ uid: string;
113
+ /** The account's address, from the verified token or the auth record. */
114
+ email: string | null | undefined;
115
+ /** The name the token or auth record carries, for an account whose document holds none. */
116
+ name?: string | null;
117
+ /** When the account was created, which is when its timeline row happened. */
118
+ createdAtMs: number;
119
+ /** Injectable for tests; defaults to the admin app's Firestore. */
120
+ firestore?: any;
121
+ /** Injectable for tests; defaults to {@link platformMarketingHostId}. */
122
+ hostId?: string | null;
123
+ /** Injectable for tests; defaults to the real capture door. */
124
+ upsert?: typeof upsertHostContact;
125
+ }
126
+ /**
127
+ * Makes the account a contact in the operator's own CRM, the moment it exists.
128
+ *
129
+ * The marketing box decides the person's marketing consent, not whether the
130
+ * operator knows them: an account is a lead for the platform's CRM either
131
+ * way. So the row is written at account creation, carrying no consent of its
132
+ * own, and a Yes or a No recorded later by
133
+ * {@link recordPlatformMarketingConsent} lands on this same row. Product email
134
+ * does not read this row's consent; the account's notification settings
135
+ * govern it.
136
+ *
137
+ * Quiet like the consent writer's contact half: a refused row is returned,
138
+ * never thrown, because nothing about creating an account should fail over
139
+ * the operator's CRM.
140
+ */
141
+ export declare function recordPlatformAccountContact(input: RecordPlatformAccountContactInput): Promise<PlatformMarketingContactOutcome>;
109
142
  /**
110
143
  * Stamps a prompt dismissal — no decision — so the console stays quiet for
111
144
  * the snooze window and asks once more after it.
@@ -228,6 +228,64 @@ const firestore = ()=>firebaseAdmin.app().firestore();
228
228
  stream
229
229
  };
230
230
  }
231
+ /** The timeline row an account's own contact opens with. */ export const PLATFORM_ACCOUNT_CREATED_SUMMARY = 'Created an account';
232
+ /**
233
+ * Makes the account a contact in the operator's own CRM, the moment it exists.
234
+ *
235
+ * The marketing box decides the person's marketing consent, not whether the
236
+ * operator knows them: an account is a lead for the platform's CRM either
237
+ * way. So the row is written at account creation, carrying no consent of its
238
+ * own, and a Yes or a No recorded later by
239
+ * {@link recordPlatformMarketingConsent} lands on this same row. Product email
240
+ * does not read this row's consent; the account's notification settings
241
+ * govern it.
242
+ *
243
+ * Quiet like the consent writer's contact half: a refused row is returned,
244
+ * never thrown, because nothing about creating an account should fail over
245
+ * the operator's CRM.
246
+ */ export async function recordPlatformAccountContact(input) {
247
+ var _input_uid, _input_email, _input_firestore, _input_upsert;
248
+ const uid = String((_input_uid = input.uid) != null ? _input_uid : '').trim();
249
+ if (!uid) throw new Error('recordPlatformAccountContact: uid is required');
250
+ const hostId = input.hostId === undefined ? platformMarketingHostId() : input.hostId;
251
+ if (!hostId) return {
252
+ status: 'unconfigured'
253
+ };
254
+ const email = String((_input_email = input.email) != null ? _input_email : '').trim();
255
+ if (!email) return {
256
+ status: 'no-email'
257
+ };
258
+ const snapshot = await ((_input_firestore = input.firestore) != null ? _input_firestore : firestore()).collection('users').doc(uid).get();
259
+ const name = accountName(snapshot, input.name);
260
+ const verdict = await ((_input_upsert = input.upsert) != null ? _input_upsert : upsertHostContact)(_extends({
261
+ hostId,
262
+ email
263
+ }, name ? {
264
+ name
265
+ } : {}, {
266
+ source: 'account',
267
+ interaction: {
268
+ atMs: input.createdAtMs,
269
+ summary: PLATFORM_ACCOUNT_CREATED_SUMMARY
270
+ },
271
+ initialLifecycleStage: 'lead'
272
+ }));
273
+ if ('refused' in verdict) return {
274
+ status: 'refused',
275
+ reason: verdict.refused
276
+ };
277
+ await stampRecordOrigin({
278
+ hostId,
279
+ email,
280
+ origin: 'account',
281
+ firstTouchOnly: true
282
+ });
283
+ return {
284
+ status: 'recorded',
285
+ contactId: verdict.contactId,
286
+ created: verdict.created
287
+ };
288
+ }
231
289
  /**
232
290
  * Stamps a prompt dismissal — no decision — so the console stays quiet for
233
291
  * the snooze window and asks once more after it.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/platform-marketing-consent.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 record a console door writes when a person decides about the\n * platform's own product email (AGL-3185).\n *\n * ## Two documents, one decision\n *\n * The decision goes onto the person's own `users/{uid}` first — the console\n * shows the preference from there, and it must not depend on the operator's\n * CRM accepting a row — and then onto the operator's marketing contact for\n * the same address through `upsertHostContact`, which is every other capture\n * door's path and the only one the send-time consent join reads. The contact\n * half carries the decision AND its provenance, so a campaign's audience\n * count reports this basis as the person's own click and never as something\n * asserted on their behalf.\n *\n * ## Server-side, because the client cannot and should not\n *\n * The sign-up page is a client of the person's own project; the operator's\n * marketing org is somebody else's data. Only the Admin SDK writes there, and\n * only after the person's ID token has been verified by the route in front\n * of this module. The user-document half could be a client write — the rules\n * make it owner-writable — but a mirror the client writes and the server\n * reads back is two writers of one fact, so both halves are written here.\n *\n * ## Which host, and why it is a setting\n *\n * The marketing host is the deployment's, not the code's: this repository is\n * what a self-hosted install runs, and an install with no product audience of\n * its own has nowhere for a contact to go. `PLATFORM_MARKETING_HOST_ID` names\n * it, and when it is unset the decision is recorded on the person's document\n * alone. No hostname or document id is hardcoded here for the same reason\n * `platform-marketing-host.ts` gives: nothing in the code knows which site\n * is the operator's.\n *\n * ## The site's own pages answer the same question, for one list (AGL-3305)\n *\n * The marketing site's emails carry their own way out, and it writes the\n * site's lists, not either consent record. An unsubscribe that was about the\n * list the console's question stands for — `PLATFORM_MARKETING_TOPIC_ID`, or\n * everything the site sends — is mirrored onto the ACCOUNT here, through an\n * email door; an unsubscribe from any other list is not, because the person\n * said nothing about product updates. The contact is left alone on purpose:\n * its basis covers every list the site sends, and declining it would stop the\n * newsletter for somebody who only left product updates.\n *\n * The console's switch undoes it the same way, one list wide: a Yes from a\n * verified account asks the plugin that keeps the site's preferences to\n * reopen that list and nothing else (`plugin-email-streams`).\n */\n\nimport { stampRecordOrigin } from '@aglyn/aglyn/plugin-manager/plugin-record-origin'\nimport {\n readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n type TopicSubscriptionEntry,\n type TopicSubscriptionState,\n} from '@aglyn/aglyn/app-utils/subscription-topics'\nimport {\n isPlatformMarketingConsentDecision,\n isPlatformMarketingConsoleSourceKind,\n isPlatformMarketingEmailSourceKind,\n type PlatformMarketingConsentDecision,\n type PlatformMarketingConsoleSourceKind,\n type PlatformMarketingConsentState,\n platformMarketingConsentSource,\n platformMarketingEmailSource,\n PLATFORM_MARKETING_TOPIC_ID,\n platformMarketingUserFields,\n readPlatformMarketingConsent,\n USER_MARKETING_PROMPT_DISMISSED_AT_FIELD,\n} from '@aglyn/aglyn/app-utils/platform-marketing-consent'\nimport {\n marketingConsentDecision,\n type MarketingBasis,\n type MarketingConsentAssertedBy,\n type MarketingConsentReason,\n type MarketingConsentVerdict,\n readMarketingBasis,\n resolveMarketingConsentPolicy,\n} from '@aglyn/aglyn/app-utils/marketing-consent'\nimport {\n type EmailStreamRejoinOutcome,\n rejoinEmailStream,\n} from '@aglyn/aglyn/plugin-manager/plugin-email-streams'\nimport { attributableAccountForAddress } from './account-addresses'\nimport { findPluginPerson } from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport {\n EMAIL_SUPPRESSIONS_COLLECTION,\n emailSuppressionKey,\n HOST_SUPPRESSIONS_SUBCOLLECTION,\n} from './email-suppression'\nimport firebaseAdmin from './firebase-admin'\nimport { consentGroupForSite, getOrgForHost } from './organizations'\nimport { upsertHostContact } from './upsert-contact'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/**\n * The variable naming the host whose contacts receive product-marketing\n * consent — the operator's own marketing site. Unset on a self-hosted\n * install, and honored as \"record the preference, capture no contact\".\n */\nexport const PLATFORM_MARKETING_HOST_ID_ENV = 'PLATFORM_MARKETING_HOST_ID'\n\n/**\n * The configured marketing host, or `null` when the deployment names none.\n *\n * Read at call time rather than at module load, so a test can set it and a\n * process that started without it picks up a later value the same way every\n * other runtime setting here does.\n */\nexport function platformMarketingHostId(): string | null {\n const value = String(process.env.PLATFORM_MARKETING_HOST_ID ?? '').trim()\n return value || null\n}\n\n/** What became of the contact half of the record. */\nexport type PlatformMarketingContactOutcome =\n | { status: 'recorded'; contactId: string; created: boolean }\n /** No marketing host is configured — a self-hosted install. */\n | { status: 'unconfigured' }\n /** The account carries no address a contact could be keyed on. */\n | { status: 'no-email' }\n /** The capture door refused the row — its band, an erasure, or an error. */\n | { status: 'refused'; reason: string }\n\nexport interface RecordPlatformMarketingConsentInput {\n uid: string\n /** The account's address, from the verified token. */\n email: string | null | undefined\n /** The name the token carries, for an account whose document holds none. */\n name?: string | null\n decision: PlatformMarketingConsentDecision\n /** A console door. An email door is recorded by the site's own pages. */\n source: PlatformMarketingConsoleSourceKind\n /** The wording version the door showed, stamped by the route. */\n textVersion: string\n /**\n * Whether the token proves the caller holds the mailbox — its email is\n * verified (AGL-3305). Only then does a Yes reopen the list on the\n * marketing site, because reopening it reverses what somebody did from\n * that mailbox; an unverified account could name a stranger's address.\n */\n mailboxVerified?: boolean\n /** Injectable for tests; defaults to the clock. */\n now?: number\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n hostId?: string | null\n /** Injectable for tests; defaults to the real capture door. */\n upsert?: typeof upsertHostContact\n /** Injectable for tests; defaults to the `plugin-email-streams` slot. */\n rejoin?: typeof rejoinEmailStream\n}\n\n/**\n * What a Yes did to the marketing site's own lists (AGL-3305). Absent for a\n * No, and whenever there is no site or no address to reopen a list for.\n */\nexport type PlatformMarketingStreamOutcome =\n | EmailStreamRejoinOutcome\n /** The token does not prove the mailbox, so nothing was reopened. */\n | { status: 'unverified' }\n\nexport interface RecordPlatformMarketingConsentResult {\n /** The timestamp both documents carry. */\n atMs: number\n contact: PlatformMarketingContactOutcome\n stream?: PlatformMarketingStreamOutcome\n}\n\n/**\n * The name the person's own document holds, else the one the caller has.\n *\n * The sign-up form writes `firstName`/`lastName` onto the document; a Google\n * account carries its name on the token instead. Either is the name the\n * contact row should show, and a blank is left blank rather than invented.\n */\nfunction accountName(\n snapshot: { get?: (field: string) => unknown } | null | undefined,\n fallback: string | null | undefined,\n): string | undefined {\n const first = String(snapshot?.get?.('firstName') ?? '').trim()\n const last = String(snapshot?.get?.('lastName') ?? '').trim()\n const stored = [first, last].filter(Boolean).join(' ')\n return stored || String(fallback ?? '').trim() || undefined\n}\n\n/**\n * Records a decision on both documents.\n *\n * Loud on bad input, like `recordLegalAcceptance`: a decision that cannot be\n * attributed to an account, a door and a wording is not a record of anything.\n * Quiet on the contact half — a refused row is returned, not thrown — because\n * the person's own preference has already been recorded by then, and the\n * operator's CRM band is not a reason to tell them their choice failed.\n */\nexport async function recordPlatformMarketingConsent(\n input: RecordPlatformMarketingConsentInput,\n): Promise<RecordPlatformMarketingConsentResult> {\n const uid = String(input.uid ?? '').trim()\n if (!uid) throw new Error('recordPlatformMarketingConsent: uid is required')\n if (!isPlatformMarketingConsentDecision(input.decision)) {\n throw new Error('recordPlatformMarketingConsent: decision is required')\n }\n if (!isPlatformMarketingConsoleSourceKind(input.source)) {\n throw new Error('recordPlatformMarketingConsent: a console source is required')\n }\n const textVersion = String(input.textVersion ?? '').trim()\n if (!textVersion) {\n throw new Error('recordPlatformMarketingConsent: textVersion is required')\n }\n\n const atMs = input.now ?? Date.now()\n const source = platformMarketingConsentSource({\n kind: input.source,\n decision: input.decision,\n uid,\n atMs,\n textVersion,\n })\n\n const userRef = (input.firestore ?? firestore()).collection('users').doc(uid)\n const snapshot = await userRef.get()\n await userRef.set(\n platformMarketingUserFields({ decision: input.decision, atMs, source }),\n { merge: true },\n )\n\n const hostId =\n input.hostId === undefined ? platformMarketingHostId() : input.hostId\n if (!hostId) return { atMs, contact: { status: 'unconfigured' } }\n const email = String(input.email ?? '').trim()\n if (!email) return { atMs, contact: { status: 'no-email' } }\n\n const name = accountName(snapshot, input.name)\n const verdict = await (input.upsert ?? upsertHostContact)({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'account',\n // The sentence the provenance carries is also the timeline row's: what\n // the person did, in the words an auditor reads.\n interaction: { atMs, summary: source.reason },\n ...(input.decision === 'granted'\n ? { marketingConsent: true }\n : { declineMarketingConsent: true }),\n marketingConsentSource: source,\n // An account on the platform is at least a lead for the platform's own\n // CRM, whichever way the marketing decision went; the floor never moves\n // a customer back.\n initialLifecycleStage: 'lead',\n })\n const contact: PlatformMarketingContactOutcome =\n 'refused' in verdict\n ? { status: 'refused', reason: verdict.refused }\n : { status: 'recorded', contactId: verdict.contactId, created: verdict.created }\n // Where the person came from (AGL-3519): an account sign-up, on a record\n // the platform's own CRM just started and that names no lead source.\n if (contact.status === 'recorded') {\n await stampRecordOrigin({ hostId, email, origin: 'account', firstTouchOnly: true })\n }\n if (input.decision !== 'granted') return { atMs, contact }\n\n /*\n * A Yes reopens the one list it stands for (AGL-3305).\n *\n * After the contact, whatever the contact's outcome: an erasure that\n * refused the row also left a suppression the plugin will not lift, and it\n * says so. One list wide, never \"resubscribe to everything\" — somebody who\n * left every list and now asks for product updates has asked for product\n * updates.\n */\n const stream: PlatformMarketingStreamOutcome = input.mailboxVerified\n ? await (input.rejoin ?? rejoinEmailStream)({\n hostId,\n email,\n topicId: PLATFORM_MARKETING_TOPIC_ID,\n })\n : { status: 'unverified' }\n return { atMs, contact, stream }\n}\n\n/**\n * Stamps a prompt dismissal — no decision — so the console stays quiet for\n * the snooze window and asks once more after it.\n */\nexport async function snoozePlatformMarketingPrompt(\n uid: string,\n options: { now?: number; firestore?: any } = {},\n): Promise<{ atMs: number }> {\n const trimmed = String(uid ?? '').trim()\n if (!trimmed) throw new Error('snoozePlatformMarketingPrompt: uid is required')\n const atMs = options.now ?? Date.now()\n await (options.firestore ?? firestore())\n .collection('users')\n .doc(trimmed)\n .set({ [USER_MARKETING_PROMPT_DISMISSED_AT_FIELD]: atMs }, { merge: true })\n return { atMs }\n}\n\n/** The decision the person's own document holds, for the console to show. */\nexport async function readPlatformMarketingConsentForUser(\n uid: string,\n options: { firestore?: any } = {},\n): Promise<PlatformMarketingConsentState> {\n const trimmed = String(uid ?? '').trim()\n if (!trimmed) throw new Error('readPlatformMarketingConsentForUser: uid is required')\n const snapshot = await (options.firestore ?? firestore())\n .collection('users')\n .doc(trimmed)\n .get()\n return readPlatformMarketingConsent(\n (snapshot?.data?.() as Record<string, unknown> | undefined) ?? null,\n )\n}\n\n/** An entry on one of the two lists every campaign send passes. */\nexport interface PlatformMarketingSuppression {\n /** `site`: the marketing site's own list. `platform`: every sender's. */\n list: 'site' | 'platform'\n /** `unsubscribe` on the site list; `bounce`, `complaint` or `staff` platform-wide. */\n reason: string\n}\n\n/**\n * What the operator's own product email would decide about one address\n * (AGL-3292), read the way a campaign from the marketing site reads it.\n *\n * The decision the person made lives on `users/{uid}`, and nothing a send\n * does looks there. A campaign from the configured marketing site reads the\n * CONTACT `recordPlatformMarketingConsent` wrote into that site's\n * organization — its basis for the site, under the organization's policy —\n * and then drops anybody on either suppression list, and a campaign on the\n * product-updates list anybody who left it. An unsubscribe writes those\n * lists; since AGL-3305 one about product updates also turns the account's\n * answer to No, but the contact's basis stays as it was, because it covers\n * every list the site sends. So a staff reader asking \"may we email them?\"\n * needs this half, and needs it from the sender's own readers — the same\n * basis read, consent group, policy and lists — or it answers a question no\n * send asks.\n */\nexport type PlatformMarketingReach =\n /** No marketing site is configured — a self-hosted install. */\n | { status: 'unconfigured' }\n /** The account carries no address a contact could be keyed on. */\n | { status: 'no-email' }\n /** A read failed. Nothing about the person follows from it. */\n | { status: 'unreadable'; hostId: string }\n | {\n status: 'read'\n hostId: string\n orgId: string\n orgSlug: string | null\n /** `null` when the operator's CRM holds no contact for the address. */\n contactId: string | null\n basis: MarketingBasis\n basisAtMs: number | null\n /** Whose act the basis is — a person's own, or an operator's assertion. */\n assertedBy: MarketingConsentAssertedBy | null\n /** Which door recorded the basis (`console-signup`, a form, a backfill). */\n basisKind: string | null\n /** The consent rule's answer alone, before either list is consulted. */\n verdict: MarketingConsentVerdict\n reason: MarketingConsentReason\n /** The list that stops every send to the address, when one does. */\n suppression: PlatformMarketingSuppression | null\n /**\n * The address on the list the account's answer stands for (AGL-3305):\n * `opted-out` when they left product updates, `pending` while a\n * confirmation is unanswered. A campaign on that list drops both.\n */\n topic: PlatformMarketingTopicState\n }\n\n/** One address on {@link PLATFORM_MARKETING_TOPIC_ID}, as the site stores it. */\nexport interface PlatformMarketingTopicState {\n id: string\n state: TopicSubscriptionState\n /** When they left it, for an `opted-out` state; else `null`. */\n leftAtMs: number | null\n}\n\n/**\n * The entry that suppresses `email` for sends from `hostId`, if any.\n *\n * The site's own list first, because it is the one a person puts themselves\n * on from this sender's footer; the platform list second. The same two reads\n * `filterSendableForHost` makes: a site entry suppresses by existing, and a\n * platform entry until it is released.\n */\nasync function readPlatformMarketingSuppression(\n db: any,\n hostId: string,\n email: string,\n): Promise<PlatformMarketingSuppression | null> {\n const key = emailSuppressionKey(email)\n if (!key) return null\n const [site, platform] = await Promise.all([\n db\n .collection('hosts')\n .doc(hostId)\n .collection(HOST_SUPPRESSIONS_SUBCOLLECTION)\n .doc(key)\n .get(),\n db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key).get(),\n ])\n if (site?.exists) {\n return { list: 'site', reason: String(site.get('reason') ?? 'unsubscribe') }\n }\n if (platform?.exists && !platform.get('releasedAt')) {\n return { list: 'platform', reason: String(platform.get('reason') ?? 'staff') }\n }\n return null\n}\n\n/** Milliseconds from a stored Firestore timestamp or a number, else `null`. */\nfunction storedMs(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n const toMillis = (value as { toMillis?: () => number } | null)?.toMillis\n return typeof toMillis === 'function' ? toMillis.call(value) : null\n}\n\n/**\n * Where the address stands on {@link PLATFORM_MARKETING_TOPIC_ID}.\n *\n * The site's per-topic record, read by key and through the one function that\n * knows its three states — the same read `filterTopicSendable` makes before\n * a campaign on that list goes out. No record is `subscribed`: nobody has\n * left a list they were never taken off.\n */\nasync function readPlatformMarketingTopic(\n db: any,\n hostId: string,\n email: string,\n): Promise<PlatformMarketingTopicState> {\n const key = emailSuppressionKey(email)\n const unrecorded = { id: PLATFORM_MARKETING_TOPIC_ID, state: 'subscribed' as const, leftAtMs: null }\n if (!key) return unrecorded\n const snapshot = await db\n .collection('hosts')\n .doc(hostId)\n .collection(TOPIC_OPT_OUTS_SUBCOLLECTION)\n .doc(key)\n .get()\n if (!snapshot?.exists) return unrecorded\n const entry = ((snapshot.get('topics') ?? {}) as Record<string, TopicSubscriptionEntry | undefined>)[\n PLATFORM_MARKETING_TOPIC_ID\n ]\n const state = readTopicSubscriptionState(entry)\n return {\n id: PLATFORM_MARKETING_TOPIC_ID,\n state,\n leftAtMs: state === 'opted-out' ? storedMs(entry?.optedOutAt) : null,\n }\n}\n\n/**\n * Reads {@link PlatformMarketingReach} for an address.\n *\n * Never throws: a failed read is `unreadable`, which the staff page shows as\n * unknown — never as \"no consent\", which would be a claim about the person.\n */\nexport async function readPlatformMarketingReach(input: {\n email: string | null | undefined\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n hostId?: string | null\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n}): Promise<PlatformMarketingReach> {\n const hostId =\n input.hostId === undefined ? platformMarketingHostId() : input.hostId\n if (!hostId) return { status: 'unconfigured' }\n const email = String(input.email ?? '').trim().toLowerCase()\n if (!email) return { status: 'no-email' }\n const db = input.firestore ?? firestore()\n try {\n const owner = await getOrgForHost(hostId)\n if (!owner) return { status: 'unreadable', hostId }\n const org = owner.org as Record<string, unknown>\n const [person, group, suppression, topic] = await Promise.all([\n // The operator's person for the address, asked of the plugin that\n // keeps people (AGL-3080) — the record the capture door wrote.\n findPluginPerson({ orgId: owner.orgId, hostId, email }),\n consentGroupForSite(hostId, org),\n readPlatformMarketingSuppression(db, hostId, email),\n readPlatformMarketingTopic(db, hostId, email),\n ])\n const record = readMarketingBasis(person ? { ...person.data } : null, group)\n const decision = marketingConsentDecision(\n record,\n resolveMarketingConsentPolicy(org['marketingConsentPolicy']),\n )\n return {\n status: 'read',\n hostId,\n orgId: owner.orgId,\n orgSlug: typeof org['slug'] === 'string' ? org['slug'] : null,\n contactId: person?.id ?? null,\n basis: record.basis,\n basisAtMs: record.basisAtMs,\n assertedBy: record.assertedBy,\n basisKind: record.source?.kind ?? null,\n verdict: decision.verdict,\n reason: decision.reason,\n suppression,\n topic,\n }\n } catch (error) {\n console.error('[platform-marketing-consent] reach read failed', error)\n return { status: 'unreadable', hostId }\n }\n}\n\n/**\n * Why somebody who said Yes will not receive product updates, in the terms\n * of what they can do about it (AGL-3305) — or `null` when nothing on the\n * marketing site's lists stands in the way.\n *\n * - `unsubscribed`: they left everything, or left product updates, from an\n * email. Theirs to undo, and a Yes from a verified account does.\n * - `unconfirmed`: a confirmation for the list was asked and not answered.\n * - `paused`: a bounce, a complaint, an erasure or a staff hold. Not a\n * preference, so no switch of theirs lifts it.\n *\n * The consent basis is not judged here: the Yes this is asked about is the\n * basis. Only the lists a Yes cannot overrule are.\n */\nexport type PlatformMarketingHold =\n | { kind: 'unsubscribed' }\n | { kind: 'unconfirmed' }\n | { kind: 'paused'; reason: string }\n\nexport function platformMarketingHold(\n reach: PlatformMarketingReach,\n): PlatformMarketingHold | null {\n if (reach.status !== 'read') return null\n if (reach.suppression) {\n return reach.suppression.list === 'site' && reach.suppression.reason === 'unsubscribe'\n ? { kind: 'unsubscribed' }\n : { kind: 'paused', reason: reach.suppression.reason }\n }\n if (reach.topic.state === 'opted-out') return { kind: 'unsubscribed' }\n if (reach.topic.state === 'pending') return { kind: 'unconfirmed' }\n return null\n}\n\n/** What mirroring an email-side change onto the account did (AGL-3305). */\nexport type PlatformMarketingMirrorOutcome =\n /** Another site's list. An account is never touched from one. */\n | { status: 'not-platform' }\n /** A list the account's answer is not about. */\n | { status: 'other-list' }\n /** No account holds the address — or more than one does. */\n | { status: 'no-account' }\n /** The account already says so, or the rule leaves it where it is. */\n | { status: 'unchanged' }\n | { status: 'recorded'; uid: string; decision: PlatformMarketingConsentDecision }\n /** Logged; the site's own write, which is what stops the mail, stands. */\n | { status: 'failed' }\n\nexport interface PlatformMarketingMirrorInput {\n /** The site whose page the person used. */\n hostId: string\n /** The address the signed link was for. */\n email: string\n /** Injectable for tests; defaults to the clock. */\n now?: number\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n platformHostId?: string | null\n /**\n * Injectable for tests; defaults to `attributableAccountForAddress`, which\n * answers `null` for nobody AND for more than one account. Changing the\n * wrong person's answer is worse than changing nobody's.\n */\n findAccount?: (email: string) => Promise<string | null>\n}\n\n/** The account a mirror would write, or the reason there is none. */\nasync function mirrorTarget(\n input: PlatformMarketingMirrorInput,\n): Promise<{ uid: string; ref: any; state: PlatformMarketingConsentState } | PlatformMarketingMirrorOutcome> {\n const platformHost =\n input.platformHostId === undefined ? platformMarketingHostId() : input.platformHostId\n if (!platformHost || input.hostId !== platformHost) return { status: 'not-platform' }\n const uid = await (input.findAccount ?? ((email: string) => attributableAccountForAddress(email)))(\n input.email,\n )\n if (!uid) return { status: 'no-account' }\n const ref = (input.firestore ?? firestore()).collection('users').doc(uid)\n const snapshot = await ref.get()\n return {\n uid,\n ref,\n state: readPlatformMarketingConsent(\n (snapshot?.data?.() as Record<string, unknown> | undefined) ?? null,\n ),\n }\n}\n\n/**\n * Mirrors an unsubscribe from the marketing site onto the account's answer.\n *\n * Called by the site's own pages AFTER their write, with what the person\n * left: `'everything'` for the site's list, or the topics left on the\n * preference page. Only the platform's marketing site counts, and only a\n * list the answer is about — {@link PLATFORM_MARKETING_TOPIC_ID}, which\n * everything includes. The first No keeps its date and its door: a second\n * unsubscribe is not a later decision.\n *\n * Never throws. The page has already stopped the mail; this is the account\n * catching up with it.\n */\nexport async function mirrorPlatformUnsubscribe(\n input: PlatformMarketingMirrorInput & { left: 'everything' | readonly string[] },\n): Promise<PlatformMarketingMirrorOutcome> {\n try {\n const everything = input.left === 'everything'\n if (!everything && !input.left.includes(PLATFORM_MARKETING_TOPIC_ID)) {\n // Cheaper to answer before the account lookup, and the answer does not\n // depend on the site: no other list is this one on any site.\n const platformHost =\n input.platformHostId === undefined ? platformMarketingHostId() : input.platformHostId\n return input.hostId === platformHost ? { status: 'other-list' } : { status: 'not-platform' }\n }\n const target = await mirrorTarget(input)\n if ('status' in target) return target\n if (target.state.decision === 'declined') return { status: 'unchanged' }\n const atMs = input.now ?? Date.now()\n const source = platformMarketingEmailSource(\n everything\n ? { kind: 'email-unsubscribe', decision: 'declined', uid: target.uid, atMs }\n : { kind: 'email-preferences', decision: 'declined', uid: target.uid, atMs },\n )\n await target.ref.set(\n platformMarketingUserFields({ decision: 'declined', atMs, source }),\n { merge: true },\n )\n return { status: 'recorded', uid: target.uid, decision: 'declined' }\n } catch (error) {\n console.error('[platform-marketing-consent] could not mirror an unsubscribe onto the account', error)\n return { status: 'failed' }\n }\n}\n\n/**\n * Mirrors a way back in from the marketing site: the resubscribe link, or\n * the list ticked again on the preference page.\n *\n * Narrower than the unsubscribe on purpose. It restores only a No that an\n * email door recorded — a No given in the console is the person's answer in\n * the console, and a link in an email does not overturn it — and only once\n * product updates would really reach them: nothing on either suppression\n * list, and the list itself not left. A resubscribe that lifted the site's\n * list while product updates stay unticked restores nothing.\n */\nexport async function mirrorPlatformResubscribe(\n input: PlatformMarketingMirrorInput & { via: 'email-resubscribe' | 'email-preferences' },\n): Promise<PlatformMarketingMirrorOutcome> {\n try {\n const target = await mirrorTarget(input)\n if ('status' in target) return target\n if (\n target.state.decision !== 'declined' ||\n !isPlatformMarketingEmailSourceKind(target.state.sourceKind)\n ) {\n return { status: 'unchanged' }\n }\n const db = input.firestore ?? firestore()\n const [suppression, topic] = await Promise.all([\n readPlatformMarketingSuppression(db, input.hostId, input.email),\n readPlatformMarketingTopic(db, input.hostId, input.email),\n ])\n if (suppression || topic.state !== 'subscribed') return { status: 'unchanged' }\n const atMs = input.now ?? Date.now()\n const source = platformMarketingEmailSource({\n kind: input.via,\n decision: 'granted',\n uid: target.uid,\n atMs,\n })\n await target.ref.set(\n platformMarketingUserFields({ decision: 'granted', atMs, source }),\n { merge: true },\n )\n return { status: 'recorded', uid: target.uid, decision: 'granted' }\n } catch (error) {\n console.error('[platform-marketing-consent] could not mirror a resubscribe onto the account', error)\n return { status: 'failed' }\n }\n}\n"],"names":["stampRecordOrigin","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","isPlatformMarketingConsentDecision","isPlatformMarketingConsoleSourceKind","isPlatformMarketingEmailSourceKind","platformMarketingConsentSource","platformMarketingEmailSource","PLATFORM_MARKETING_TOPIC_ID","platformMarketingUserFields","readPlatformMarketingConsent","USER_MARKETING_PROMPT_DISMISSED_AT_FIELD","marketingConsentDecision","readMarketingBasis","resolveMarketingConsentPolicy","rejoinEmailStream","attributableAccountForAddress","findPluginPerson","EMAIL_SUPPRESSIONS_COLLECTION","emailSuppressionKey","HOST_SUPPRESSIONS_SUBCOLLECTION","firebaseAdmin","consentGroupForSite","getOrgForHost","upsertHostContact","firestore","app","PLATFORM_MARKETING_HOST_ID_ENV","platformMarketingHostId","process","value","String","env","PLATFORM_MARKETING_HOST_ID","trim","accountName","snapshot","fallback","first","get","last","stored","filter","Boolean","join","undefined","recordPlatformMarketingConsent","input","uid","Error","decision","source","textVersion","atMs","now","Date","kind","userRef","collection","doc","set","merge","hostId","contact","status","email","name","verdict","upsert","interaction","summary","reason","marketingConsent","declineMarketingConsent","marketingConsentSource","initialLifecycleStage","refused","contactId","created","origin","firstTouchOnly","stream","mailboxVerified","rejoin","topicId","snoozePlatformMarketingPrompt","options","trimmed","readPlatformMarketingConsentForUser","data","readPlatformMarketingSuppression","db","key","site","platform","Promise","all","exists","list","storedMs","Number","isFinite","toMillis","call","readPlatformMarketingTopic","unrecorded","id","state","leftAtMs","entry","optedOutAt","readPlatformMarketingReach","toLowerCase","record","owner","org","person","group","suppression","topic","orgId","orgSlug","basis","basisAtMs","assertedBy","basisKind","error","console","platformMarketingHold","reach","mirrorTarget","platformHost","platformHostId","findAccount","ref","mirrorPlatformUns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AEG,QAAQ;YAAYhB,KAAK2F,OAAO3F,GAAG;YAAEE,UAAU;QAAU;IACpE,EAAE,OAAO4E,OAAO;QACdC,QAAQD,KAAK,CAAC,gFAAgFA;QAC9F,OAAO;YAAE9D,QAAQ;QAAS;IAC5B;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/platform-marketing-consent.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 record a console door writes when a person decides about the\n * platform's own product email (AGL-3185).\n *\n * ## Two documents, one decision\n *\n * The decision goes onto the person's own `users/{uid}` first — the console\n * shows the preference from there, and it must not depend on the operator's\n * CRM accepting a row — and then onto the operator's marketing contact for\n * the same address through `upsertHostContact`, which is every other capture\n * door's path and the only one the send-time consent join reads. The contact\n * half carries the decision AND its provenance, so a campaign's audience\n * count reports this basis as the person's own click and never as something\n * asserted on their behalf.\n *\n * ## Server-side, because the client cannot and should not\n *\n * The sign-up page is a client of the person's own project; the operator's\n * marketing org is somebody else's data. Only the Admin SDK writes there, and\n * only after the person's ID token has been verified by the route in front\n * of this module. The user-document half could be a client write — the rules\n * make it owner-writable — but a mirror the client writes and the server\n * reads back is two writers of one fact, so both halves are written here.\n *\n * ## Which host, and why it is a setting\n *\n * The marketing host is the deployment's, not the code's: this repository is\n * what a self-hosted install runs, and an install with no product audience of\n * its own has nowhere for a contact to go. `PLATFORM_MARKETING_HOST_ID` names\n * it, and when it is unset the decision is recorded on the person's document\n * alone. No hostname or document id is hardcoded here for the same reason\n * `platform-marketing-host.ts` gives: nothing in the code knows which site\n * is the operator's.\n *\n * ## The site's own pages answer the same question, for one list (AGL-3305)\n *\n * The marketing site's emails carry their own way out, and it writes the\n * site's lists, not either consent record. An unsubscribe that was about the\n * list the console's question stands for — `PLATFORM_MARKETING_TOPIC_ID`, or\n * everything the site sends — is mirrored onto the ACCOUNT here, through an\n * email door; an unsubscribe from any other list is not, because the person\n * said nothing about product updates. The contact is left alone on purpose:\n * its basis covers every list the site sends, and declining it would stop the\n * newsletter for somebody who only left product updates.\n *\n * The console's switch undoes it the same way, one list wide: a Yes from a\n * verified account asks the plugin that keeps the site's preferences to\n * reopen that list and nothing else (`plugin-email-streams`).\n */\n\nimport { stampRecordOrigin } from '@aglyn/aglyn/plugin-manager/plugin-record-origin'\nimport {\n readTopicSubscriptionState,\n TOPIC_OPT_OUTS_SUBCOLLECTION,\n type TopicSubscriptionEntry,\n type TopicSubscriptionState,\n} from '@aglyn/aglyn/app-utils/subscription-topics'\nimport {\n isPlatformMarketingConsentDecision,\n isPlatformMarketingConsoleSourceKind,\n isPlatformMarketingEmailSourceKind,\n type PlatformMarketingConsentDecision,\n type PlatformMarketingConsoleSourceKind,\n type PlatformMarketingConsentState,\n platformMarketingConsentSource,\n platformMarketingEmailSource,\n PLATFORM_MARKETING_TOPIC_ID,\n platformMarketingUserFields,\n readPlatformMarketingConsent,\n USER_MARKETING_PROMPT_DISMISSED_AT_FIELD,\n} from '@aglyn/aglyn/app-utils/platform-marketing-consent'\nimport {\n marketingConsentDecision,\n type MarketingBasis,\n type MarketingConsentAssertedBy,\n type MarketingConsentReason,\n type MarketingConsentVerdict,\n readMarketingBasis,\n resolveMarketingConsentPolicy,\n} from '@aglyn/aglyn/app-utils/marketing-consent'\nimport {\n type EmailStreamRejoinOutcome,\n rejoinEmailStream,\n} from '@aglyn/aglyn/plugin-manager/plugin-email-streams'\nimport { attributableAccountForAddress } from './account-addresses'\nimport { findPluginPerson } from '@aglyn/aglyn/plugin-manager/plugin-person-records'\nimport {\n EMAIL_SUPPRESSIONS_COLLECTION,\n emailSuppressionKey,\n HOST_SUPPRESSIONS_SUBCOLLECTION,\n} from './email-suppression'\nimport firebaseAdmin from './firebase-admin'\nimport { consentGroupForSite, getOrgForHost } from './organizations'\nimport { upsertHostContact } from './upsert-contact'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\n/**\n * The variable naming the host whose contacts receive product-marketing\n * consent — the operator's own marketing site. Unset on a self-hosted\n * install, and honored as \"record the preference, capture no contact\".\n */\nexport const PLATFORM_MARKETING_HOST_ID_ENV = 'PLATFORM_MARKETING_HOST_ID'\n\n/**\n * The configured marketing host, or `null` when the deployment names none.\n *\n * Read at call time rather than at module load, so a test can set it and a\n * process that started without it picks up a later value the same way every\n * other runtime setting here does.\n */\nexport function platformMarketingHostId(): string | null {\n const value = String(process.env.PLATFORM_MARKETING_HOST_ID ?? '').trim()\n return value || null\n}\n\n/** What became of the contact half of the record. */\nexport type PlatformMarketingContactOutcome =\n | { status: 'recorded'; contactId: string; created: boolean }\n /** No marketing host is configured — a self-hosted install. */\n | { status: 'unconfigured' }\n /** The account carries no address a contact could be keyed on. */\n | { status: 'no-email' }\n /** The capture door refused the row — its band, an erasure, or an error. */\n | { status: 'refused'; reason: string }\n\nexport interface RecordPlatformMarketingConsentInput {\n uid: string\n /** The account's address, from the verified token. */\n email: string | null | undefined\n /** The name the token carries, for an account whose document holds none. */\n name?: string | null\n decision: PlatformMarketingConsentDecision\n /** A console door. An email door is recorded by the site's own pages. */\n source: PlatformMarketingConsoleSourceKind\n /** The wording version the door showed, stamped by the route. */\n textVersion: string\n /**\n * Whether the token proves the caller holds the mailbox — its email is\n * verified (AGL-3305). Only then does a Yes reopen the list on the\n * marketing site, because reopening it reverses what somebody did from\n * that mailbox; an unverified account could name a stranger's address.\n */\n mailboxVerified?: boolean\n /** Injectable for tests; defaults to the clock. */\n now?: number\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n hostId?: string | null\n /** Injectable for tests; defaults to the real capture door. */\n upsert?: typeof upsertHostContact\n /** Injectable for tests; defaults to the `plugin-email-streams` slot. */\n rejoin?: typeof rejoinEmailStream\n}\n\n/**\n * What a Yes did to the marketing site's own lists (AGL-3305). Absent for a\n * No, and whenever there is no site or no address to reopen a list for.\n */\nexport type PlatformMarketingStreamOutcome =\n | EmailStreamRejoinOutcome\n /** The token does not prove the mailbox, so nothing was reopened. */\n | { status: 'unverified' }\n\nexport interface RecordPlatformMarketingConsentResult {\n /** The timestamp both documents carry. */\n atMs: number\n contact: PlatformMarketingContactOutcome\n stream?: PlatformMarketingStreamOutcome\n}\n\n/**\n * The name the person's own document holds, else the one the caller has.\n *\n * The sign-up form writes `firstName`/`lastName` onto the document; a Google\n * account carries its name on the token instead. Either is the name the\n * contact row should show, and a blank is left blank rather than invented.\n */\nfunction accountName(\n snapshot: { get?: (field: string) => unknown } | null | undefined,\n fallback: string | null | undefined,\n): string | undefined {\n const first = String(snapshot?.get?.('firstName') ?? '').trim()\n const last = String(snapshot?.get?.('lastName') ?? '').trim()\n const stored = [first, last].filter(Boolean).join(' ')\n return stored || String(fallback ?? '').trim() || undefined\n}\n\n/**\n * Records a decision on both documents.\n *\n * Loud on bad input, like `recordLegalAcceptance`: a decision that cannot be\n * attributed to an account, a door and a wording is not a record of anything.\n * Quiet on the contact half — a refused row is returned, not thrown — because\n * the person's own preference has already been recorded by then, and the\n * operator's CRM band is not a reason to tell them their choice failed.\n */\nexport async function recordPlatformMarketingConsent(\n input: RecordPlatformMarketingConsentInput,\n): Promise<RecordPlatformMarketingConsentResult> {\n const uid = String(input.uid ?? '').trim()\n if (!uid) throw new Error('recordPlatformMarketingConsent: uid is required')\n if (!isPlatformMarketingConsentDecision(input.decision)) {\n throw new Error('recordPlatformMarketingConsent: decision is required')\n }\n if (!isPlatformMarketingConsoleSourceKind(input.source)) {\n throw new Error('recordPlatformMarketingConsent: a console source is required')\n }\n const textVersion = String(input.textVersion ?? '').trim()\n if (!textVersion) {\n throw new Error('recordPlatformMarketingConsent: textVersion is required')\n }\n\n const atMs = input.now ?? Date.now()\n const source = platformMarketingConsentSource({\n kind: input.source,\n decision: input.decision,\n uid,\n atMs,\n textVersion,\n })\n\n const userRef = (input.firestore ?? firestore()).collection('users').doc(uid)\n const snapshot = await userRef.get()\n await userRef.set(\n platformMarketingUserFields({ decision: input.decision, atMs, source }),\n { merge: true },\n )\n\n const hostId =\n input.hostId === undefined ? platformMarketingHostId() : input.hostId\n if (!hostId) return { atMs, contact: { status: 'unconfigured' } }\n const email = String(input.email ?? '').trim()\n if (!email) return { atMs, contact: { status: 'no-email' } }\n\n const name = accountName(snapshot, input.name)\n const verdict = await (input.upsert ?? upsertHostContact)({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'account',\n // The sentence the provenance carries is also the timeline row's: what\n // the person did, in the words an auditor reads.\n interaction: { atMs, summary: source.reason },\n ...(input.decision === 'granted'\n ? { marketingConsent: true }\n : { declineMarketingConsent: true }),\n marketingConsentSource: source,\n // An account on the platform is at least a lead for the platform's own\n // CRM, whichever way the marketing decision went; the floor never moves\n // a customer back.\n initialLifecycleStage: 'lead',\n })\n const contact: PlatformMarketingContactOutcome =\n 'refused' in verdict\n ? { status: 'refused', reason: verdict.refused }\n : { status: 'recorded', contactId: verdict.contactId, created: verdict.created }\n // Where the person came from (AGL-3519): an account sign-up, on a record\n // the platform's own CRM just started and that names no lead source.\n if (contact.status === 'recorded') {\n await stampRecordOrigin({ hostId, email, origin: 'account', firstTouchOnly: true })\n }\n if (input.decision !== 'granted') return { atMs, contact }\n\n /*\n * A Yes reopens the one list it stands for (AGL-3305).\n *\n * After the contact, whatever the contact's outcome: an erasure that\n * refused the row also left a suppression the plugin will not lift, and it\n * says so. One list wide, never \"resubscribe to everything\" — somebody who\n * left every list and now asks for product updates has asked for product\n * updates.\n */\n const stream: PlatformMarketingStreamOutcome = input.mailboxVerified\n ? await (input.rejoin ?? rejoinEmailStream)({\n hostId,\n email,\n topicId: PLATFORM_MARKETING_TOPIC_ID,\n })\n : { status: 'unverified' }\n return { atMs, contact, stream }\n}\n\n/** The timeline row an account's own contact opens with. */\nexport const PLATFORM_ACCOUNT_CREATED_SUMMARY = 'Created an account'\n\nexport interface RecordPlatformAccountContactInput {\n uid: string\n /** The account's address, from the verified token or the auth record. */\n email: string | null | undefined\n /** The name the token or auth record carries, for an account whose document holds none. */\n name?: string | null\n /** When the account was created, which is when its timeline row happened. */\n createdAtMs: number\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n hostId?: string | null\n /** Injectable for tests; defaults to the real capture door. */\n upsert?: typeof upsertHostContact\n}\n\n/**\n * Makes the account a contact in the operator's own CRM, the moment it exists.\n *\n * The marketing box decides the person's marketing consent, not whether the\n * operator knows them: an account is a lead for the platform's CRM either\n * way. So the row is written at account creation, carrying no consent of its\n * own, and a Yes or a No recorded later by\n * {@link recordPlatformMarketingConsent} lands on this same row. Product email\n * does not read this row's consent; the account's notification settings\n * govern it.\n *\n * Quiet like the consent writer's contact half: a refused row is returned,\n * never thrown, because nothing about creating an account should fail over\n * the operator's CRM.\n */\nexport async function recordPlatformAccountContact(\n input: RecordPlatformAccountContactInput,\n): Promise<PlatformMarketingContactOutcome> {\n const uid = String(input.uid ?? '').trim()\n if (!uid) throw new Error('recordPlatformAccountContact: uid is required')\n const hostId =\n input.hostId === undefined ? platformMarketingHostId() : input.hostId\n if (!hostId) return { status: 'unconfigured' }\n const email = String(input.email ?? '').trim()\n if (!email) return { status: 'no-email' }\n\n const snapshot = await (input.firestore ?? firestore())\n .collection('users')\n .doc(uid)\n .get()\n const name = accountName(snapshot, input.name)\n const verdict = await (input.upsert ?? upsertHostContact)({\n hostId,\n email,\n ...(name ? { name } : {}),\n source: 'account',\n interaction: { atMs: input.createdAtMs, summary: PLATFORM_ACCOUNT_CREATED_SUMMARY },\n initialLifecycleStage: 'lead',\n })\n if ('refused' in verdict) return { status: 'refused', reason: verdict.refused }\n await stampRecordOrigin({ hostId, email, origin: 'account', firstTouchOnly: true })\n return { status: 'recorded', contactId: verdict.contactId, created: verdict.created }\n}\n\n/**\n * Stamps a prompt dismissal — no decision — so the console stays quiet for\n * the snooze window and asks once more after it.\n */\nexport async function snoozePlatformMarketingPrompt(\n uid: string,\n options: { now?: number; firestore?: any } = {},\n): Promise<{ atMs: number }> {\n const trimmed = String(uid ?? '').trim()\n if (!trimmed) throw new Error('snoozePlatformMarketingPrompt: uid is required')\n const atMs = options.now ?? Date.now()\n await (options.firestore ?? firestore())\n .collection('users')\n .doc(trimmed)\n .set({ [USER_MARKETING_PROMPT_DISMISSED_AT_FIELD]: atMs }, { merge: true })\n return { atMs }\n}\n\n/** The decision the person's own document holds, for the console to show. */\nexport async function readPlatformMarketingConsentForUser(\n uid: string,\n options: { firestore?: any } = {},\n): Promise<PlatformMarketingConsentState> {\n const trimmed = String(uid ?? '').trim()\n if (!trimmed) throw new Error('readPlatformMarketingConsentForUser: uid is required')\n const snapshot = await (options.firestore ?? firestore())\n .collection('users')\n .doc(trimmed)\n .get()\n return readPlatformMarketingConsent(\n (snapshot?.data?.() as Record<string, unknown> | undefined) ?? null,\n )\n}\n\n/** An entry on one of the two lists every campaign send passes. */\nexport interface PlatformMarketingSuppression {\n /** `site`: the marketing site's own list. `platform`: every sender's. */\n list: 'site' | 'platform'\n /** `unsubscribe` on the site list; `bounce`, `complaint` or `staff` platform-wide. */\n reason: string\n}\n\n/**\n * What the operator's own product email would decide about one address\n * (AGL-3292), read the way a campaign from the marketing site reads it.\n *\n * The decision the person made lives on `users/{uid}`, and nothing a send\n * does looks there. A campaign from the configured marketing site reads the\n * CONTACT `recordPlatformMarketingConsent` wrote into that site's\n * organization — its basis for the site, under the organization's policy —\n * and then drops anybody on either suppression list, and a campaign on the\n * product-updates list anybody who left it. An unsubscribe writes those\n * lists; since AGL-3305 one about product updates also turns the account's\n * answer to No, but the contact's basis stays as it was, because it covers\n * every list the site sends. So a staff reader asking \"may we email them?\"\n * needs this half, and needs it from the sender's own readers — the same\n * basis read, consent group, policy and lists — or it answers a question no\n * send asks.\n */\nexport type PlatformMarketingReach =\n /** No marketing site is configured — a self-hosted install. */\n | { status: 'unconfigured' }\n /** The account carries no address a contact could be keyed on. */\n | { status: 'no-email' }\n /** A read failed. Nothing about the person follows from it. */\n | { status: 'unreadable'; hostId: string }\n | {\n status: 'read'\n hostId: string\n orgId: string\n orgSlug: string | null\n /** `null` when the operator's CRM holds no contact for the address. */\n contactId: string | null\n basis: MarketingBasis\n basisAtMs: number | null\n /** Whose act the basis is — a person's own, or an operator's assertion. */\n assertedBy: MarketingConsentAssertedBy | null\n /** Which door recorded the basis (`console-signup`, a form, a backfill). */\n basisKind: string | null\n /** The consent rule's answer alone, before either list is consulted. */\n verdict: MarketingConsentVerdict\n reason: MarketingConsentReason\n /** The list that stops every send to the address, when one does. */\n suppression: PlatformMarketingSuppression | null\n /**\n * The address on the list the account's answer stands for (AGL-3305):\n * `opted-out` when they left product updates, `pending` while a\n * confirmation is unanswered. A campaign on that list drops both.\n */\n topic: PlatformMarketingTopicState\n }\n\n/** One address on {@link PLATFORM_MARKETING_TOPIC_ID}, as the site stores it. */\nexport interface PlatformMarketingTopicState {\n id: string\n state: TopicSubscriptionState\n /** When they left it, for an `opted-out` state; else `null`. */\n leftAtMs: number | null\n}\n\n/**\n * The entry that suppresses `email` for sends from `hostId`, if any.\n *\n * The site's own list first, because it is the one a person puts themselves\n * on from this sender's footer; the platform list second. The same two reads\n * `filterSendableForHost` makes: a site entry suppresses by existing, and a\n * platform entry until it is released.\n */\nasync function readPlatformMarketingSuppression(\n db: any,\n hostId: string,\n email: string,\n): Promise<PlatformMarketingSuppression | null> {\n const key = emailSuppressionKey(email)\n if (!key) return null\n const [site, platform] = await Promise.all([\n db\n .collection('hosts')\n .doc(hostId)\n .collection(HOST_SUPPRESSIONS_SUBCOLLECTION)\n .doc(key)\n .get(),\n db.collection(EMAIL_SUPPRESSIONS_COLLECTION).doc(key).get(),\n ])\n if (site?.exists) {\n return { list: 'site', reason: String(site.get('reason') ?? 'unsubscribe') }\n }\n if (platform?.exists && !platform.get('releasedAt')) {\n return { list: 'platform', reason: String(platform.get('reason') ?? 'staff') }\n }\n return null\n}\n\n/** Milliseconds from a stored Firestore timestamp or a number, else `null`. */\nfunction storedMs(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n const toMillis = (value as { toMillis?: () => number } | null)?.toMillis\n return typeof toMillis === 'function' ? toMillis.call(value) : null\n}\n\n/**\n * Where the address stands on {@link PLATFORM_MARKETING_TOPIC_ID}.\n *\n * The site's per-topic record, read by key and through the one function that\n * knows its three states — the same read `filterTopicSendable` makes before\n * a campaign on that list goes out. No record is `subscribed`: nobody has\n * left a list they were never taken off.\n */\nasync function readPlatformMarketingTopic(\n db: any,\n hostId: string,\n email: string,\n): Promise<PlatformMarketingTopicState> {\n const key = emailSuppressionKey(email)\n const unrecorded = { id: PLATFORM_MARKETING_TOPIC_ID, state: 'subscribed' as const, leftAtMs: null }\n if (!key) return unrecorded\n const snapshot = await db\n .collection('hosts')\n .doc(hostId)\n .collection(TOPIC_OPT_OUTS_SUBCOLLECTION)\n .doc(key)\n .get()\n if (!snapshot?.exists) return unrecorded\n const entry = ((snapshot.get('topics') ?? {}) as Record<string, TopicSubscriptionEntry | undefined>)[\n PLATFORM_MARKETING_TOPIC_ID\n ]\n const state = readTopicSubscriptionState(entry)\n return {\n id: PLATFORM_MARKETING_TOPIC_ID,\n state,\n leftAtMs: state === 'opted-out' ? storedMs(entry?.optedOutAt) : null,\n }\n}\n\n/**\n * Reads {@link PlatformMarketingReach} for an address.\n *\n * Never throws: a failed read is `unreadable`, which the staff page shows as\n * unknown — never as \"no consent\", which would be a claim about the person.\n */\nexport async function readPlatformMarketingReach(input: {\n email: string | null | undefined\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n hostId?: string | null\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n}): Promise<PlatformMarketingReach> {\n const hostId =\n input.hostId === undefined ? platformMarketingHostId() : input.hostId\n if (!hostId) return { status: 'unconfigured' }\n const email = String(input.email ?? '').trim().toLowerCase()\n if (!email) return { status: 'no-email' }\n const db = input.firestore ?? firestore()\n try {\n const owner = await getOrgForHost(hostId)\n if (!owner) return { status: 'unreadable', hostId }\n const org = owner.org as Record<string, unknown>\n const [person, group, suppression, topic] = await Promise.all([\n // The operator's person for the address, asked of the plugin that\n // keeps people (AGL-3080) — the record the capture door wrote.\n findPluginPerson({ orgId: owner.orgId, hostId, email }),\n consentGroupForSite(hostId, org),\n readPlatformMarketingSuppression(db, hostId, email),\n readPlatformMarketingTopic(db, hostId, email),\n ])\n const record = readMarketingBasis(person ? { ...person.data } : null, group)\n const decision = marketingConsentDecision(\n record,\n resolveMarketingConsentPolicy(org['marketingConsentPolicy']),\n )\n return {\n status: 'read',\n hostId,\n orgId: owner.orgId,\n orgSlug: typeof org['slug'] === 'string' ? org['slug'] : null,\n contactId: person?.id ?? null,\n basis: record.basis,\n basisAtMs: record.basisAtMs,\n assertedBy: record.assertedBy,\n basisKind: record.source?.kind ?? null,\n verdict: decision.verdict,\n reason: decision.reason,\n suppression,\n topic,\n }\n } catch (error) {\n console.error('[platform-marketing-consent] reach read failed', error)\n return { status: 'unreadable', hostId }\n }\n}\n\n/**\n * Why somebody who said Yes will not receive product updates, in the terms\n * of what they can do about it (AGL-3305) — or `null` when nothing on the\n * marketing site's lists stands in the way.\n *\n * - `unsubscribed`: they left everything, or left product updates, from an\n * email. Theirs to undo, and a Yes from a verified account does.\n * - `unconfirmed`: a confirmation for the list was asked and not answered.\n * - `paused`: a bounce, a complaint, an erasure or a staff hold. Not a\n * preference, so no switch of theirs lifts it.\n *\n * The consent basis is not judged here: the Yes this is asked about is the\n * basis. Only the lists a Yes cannot overrule are.\n */\nexport type PlatformMarketingHold =\n | { kind: 'unsubscribed' }\n | { kind: 'unconfirmed' }\n | { kind: 'paused'; reason: string }\n\nexport function platformMarketingHold(\n reach: PlatformMarketingReach,\n): PlatformMarketingHold | null {\n if (reach.status !== 'read') return null\n if (reach.suppression) {\n return reach.suppression.list === 'site' && reach.suppression.reason === 'unsubscribe'\n ? { kind: 'unsubscribed' }\n : { kind: 'paused', reason: reach.suppression.reason }\n }\n if (reach.topic.state === 'opted-out') return { kind: 'unsubscribed' }\n if (reach.topic.state === 'pending') return { kind: 'unconfirmed' }\n return null\n}\n\n/** What mirroring an email-side change onto the account did (AGL-3305). */\nexport type PlatformMarketingMirrorOutcome =\n /** Another site's list. An account is never touched from one. */\n | { status: 'not-platform' }\n /** A list the account's answer is not about. */\n | { status: 'other-list' }\n /** No account holds the address — or more than one does. */\n | { status: 'no-account' }\n /** The account already says so, or the rule leaves it where it is. */\n | { status: 'unchanged' }\n | { status: 'recorded'; uid: string; decision: PlatformMarketingConsentDecision }\n /** Logged; the site's own write, which is what stops the mail, stands. */\n | { status: 'failed' }\n\nexport interface PlatformMarketingMirrorInput {\n /** The site whose page the person used. */\n hostId: string\n /** The address the signed link was for. */\n email: string\n /** Injectable for tests; defaults to the clock. */\n now?: number\n /** Injectable for tests; defaults to the admin app's Firestore. */\n firestore?: any\n /** Injectable for tests; defaults to {@link platformMarketingHostId}. */\n platformHostId?: string | null\n /**\n * Injectable for tests; defaults to `attributableAccountForAddress`, which\n * answers `null` for nobody AND for more than one account. Changing the\n * wrong person's answer is worse than changing nobody's.\n */\n findAccount?: (email: string) => Promise<string | null>\n}\n\n/** The account a mirror would write, or the reason there is none. */\nasync function mirrorTarget(\n input: PlatformMarketingMirrorInput,\n): Promise<{ uid: string; ref: any; state: PlatformMarketingConsentState } | PlatformMarketingMirrorOutcome> {\n const platformHost =\n input.platformHostId === undefined ? platformMarketingHostId() : input.platformHostId\n if (!platformHost || input.hostId !== platformHost) return { status: 'not-platform' }\n const uid = await (input.findAccount ?? ((email: string) => attributableAccountForAddress(email)))(\n input.email,\n )\n if (!uid) return { status: 'no-account' }\n const ref = (input.firestore ?? firestore()).collection('users').doc(uid)\n const snapshot = await ref.get()\n return {\n uid,\n ref,\n state: readPlatformMarketingConsent(\n (snapshot?.data?.() as Record<string, unknown> | undefined) ?? null,\n ),\n }\n}\n\n/**\n * Mirrors an unsubscribe from the marketing site onto the account's answer.\n *\n * Called by the site's own pages AFTER their write, with what the person\n * left: `'everything'` for the site's list, or the topics left on the\n * preference page. Only the platform's marketing site counts, and only a\n * list the answer is about — {@link PLATFORM_MARKETING_TOPIC_ID}, which\n * everything includes. The first No keeps its date and its door: a second\n * unsubscribe is not a later decision.\n *\n * Never throws. The page has already stopped the mail; this is the account\n * catching up with it.\n */\nexport async function mirrorPlatformUnsubscribe(\n input: PlatformMarketingMirrorInput & { left: 'everything' | readonly string[] },\n): Promise<PlatformMarketingMirrorOutcome> {\n try {\n const everything = input.left === 'everything'\n if (!everything && !input.left.includes(PLATFORM_MARKETING_TOPIC_ID)) {\n // Cheaper to answer before the account lookup, and the answer does not\n // depend on the site: no other list is this one on any site.\n const platformHost =\n input.platformHostId === undefined ? platformMarketingHostId() : input.platformHostId\n return input.hostId === platformHost ? { status: 'other-list' } : { status: 'not-platform' }\n }\n const target = await mirrorTarget(input)\n if ('status' in target) return target\n if (target.state.decision === 'declined') return { status: 'unchanged' }\n const atMs = input.now ?? Date.now()\n const source = platformMarketingEmailSource(\n everything\n ? { kind: 'email-unsubscribe', decision: 'declined', uid: target.uid, atMs }\n : { kind: 'email-preferences', decision: 'declined', uid: target.uid, atMs },\n )\n await target.ref.set(\n platformMarketingUserFields({ decision: 'declined', atMs, source }),\n { merge: true },\n )\n return { status: 'recorded', uid: target.uid, decision: 'declined' }\n } catch (error) {\n console.error('[platform-marketing-consent] could not mirror an unsubscribe onto the account', error)\n return { status: 'failed' }\n }\n}\n\n/**\n * Mirrors a way back in from the marketing site: the resubscribe link, or\n * the list ticked again on the preference page.\n *\n * Narrower than the unsubscribe on purpose. It restores only a No that an\n * email door recorded — a No given in the console is the person's answer in\n * the console, and a link in an email does not overturn it — and only once\n * product updates would really reach them: nothing on either suppression\n * list, and the list itself not left. A resubscribe that lifted the site's\n * list while product updates stay unticked restores nothing.\n */\nexport async function mirrorPlatformResubscribe(\n input: PlatformMarketingMirrorInput & { via: 'email-resubscribe' | 'email-preferences' },\n): Promise<PlatformMarketingMirrorOutcome> {\n try {\n const target = await mirrorTarget(input)\n if ('status' in target) return target\n if (\n target.state.decision !== 'declined' ||\n !isPlatformMarketingEmailSourceKind(target.state.sourceKind)\n ) {\n return { status: 'unchanged' }\n }\n const db = input.firestore ?? firestore()\n const [suppression, topic] = await Promise.all([\n readPlatformMarketingSuppression(db, input.hostId, input.email),\n readPlatformMarketingTopic(db, input.hostId, input.email),\n ])\n if (suppression || topic.state !== 'subscribed') return { status: 'unchanged' }\n const atMs = input.now ?? Date.now()\n const source = platformMarketingEmailSource({\n kind: input.via,\n decision: 'granted',\n uid: target.uid,\n atMs,\n })\n await target.ref.set(\n platformMarketingUserFields({ decision: 'granted', atMs, source }),\n { merge: true },\n )\n return { status: 'recorded', uid: target.uid, decision: 'granted' }\n } catch (error) {\n console.error('[platform-marketing-consent] could not mirror a resubscribe onto the account', error)\n return { status: 'failed' }\n }\n}\n"],"names":["stampRecordOrigin","readTopicSubscriptionState","TOPIC_OPT_OUTS_SUBCOLLECTION","isPlatformMarketingConsentDecision","isPlatformMarketingConsoleSourceKind","isPlatformMarketingEmailSourceKind","platformMarketingConsentSource","platformMarketingEmailSource","PLATFORM_MARKETING_TOPIC_ID","platformMarketingUserFields","readPlatformMarketingConsent","USER_MARKETING_PROMPT_DISMISSED_AT_FIELD","marketingConsentDecision","readMarketingBasis","resolveMarketingConsentPolicy","rejoinEmailStream","attributableAccountForAddress","findPluginPerson","EMAIL_SUPPRESSIONS_COLLECTION","emailSuppressionKey","HOST_SUPPRESSIONS_SUBCOLLECTION","firebaseAdmin","consentGroupForSite","getOrgForHost","upsertHostContact","firestore","app","PLATFORM_MARKETING_HOST_ID_ENV","platformMarketingHostId","process","value","String","env","PLATFORM_MARKETING_HOST_ID","trim","accountName","snapshot","fallback","first","get","last","stored","filter","Boolean","join","undefined","recordPlatformMarketingConsent","input","uid","Error","decision","source","textVersion","atMs","now","Date","kind","userRef","collection","doc","set","merge","hostId","contact","status","email","name","verdict","upsert","interaction","summary","reason","marketingConsent","declineMarketingConsent","marketingConsentSource","initialLifecycleStage","refused","contactId","created","origin","firstTouchOnly","stream","mailboxVerified","rejoin","topicId","PLATFORM_ACCOUNT_CREATED_SUMMARY","recordPlatformAccountContact","createdAtMs","snoozePlatformMarketingPrompt","options","trimmed","readPlatformMarketingConsentForUser","data","readPlatformMarketingSuppression","db","key","site","platform","Promise","all","exists","list","storedMs","Number","isFinite","toMillis","call","readPlatformMarketingTopic","unrecorded","id","state","leftAtMs","entry","optedOutAt","readPlatformMarketingReach","toLowerCase","record","owner","org","person","group","suppression","topic","orgId","orgSlug","basis","basisAtMs","assertedBy","basisKind","error","console","platformMarketingHold","reach","mirrorTarget","platformHost","platformHostId","findAccount","ref","mirrorPlatformUnsubscribe","everything","left","includes","target","mirrorPlatformResubscribe","sourceKind","via"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDC,GAED,SAASA,iBAAiB,QAAQ,mDAAkD;AACpF,SACEC,0BAA0B,EAC1BC,4BAA4B,QAGvB,6CAA4C;AACnD,SACEC,kCAAkC,EAClCC,oCAAoC,EACpCC,kCAAkC,EAIlCC,8BAA8B,EAC9BC,4BAA4B,EAC5BC,2BAA2B,EAC3BC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,wCAAwC,QACnC,oDAAmD;AAC1D,SACEC,wBAAwB,EAKxBC,kBAAkB,EAClBC,6BAA6B,QACxB,2CAA0C;AACjD,SAEEC,iBAAiB,QACZ,mDAAkD;AACzD,SAASC,6BAA6B,QAAQ,yBAAqB;AACnE,SAASC,gBAAgB,QAAQ,oDAAmD;AACpF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fsB,mBAAmBtB;QAC9B,MAAM,CAACgG,aAAaC,MAAM,GAAG,MAAMxB,QAAQC,GAAG,CAAC;YAC7CN,iCAAiCC,IAAI/C,MAAMe,MAAM,EAAEf,MAAMkB,KAAK;YAC9D0C,2BAA2Bb,IAAI/C,MAAMe,MAAM,EAAEf,MAAMkB,KAAK;SACzD;QACD,IAAIwD,eAAeC,MAAMZ,KAAK,KAAK,cAAc,OAAO;YAAE9C,QAAQ;QAAY;QAC9E,MAAMX,QAAON,aAAAA,MAAMO,GAAG,YAATP,aAAaQ,KAAKD,GAAG;QAClC,MAAMH,SAAS5C,6BAA6B;YAC1CiD,MAAMT,MAAMkG,GAAG;YACf/F,UAAU;YACVF,KAAK8F,OAAO9F,GAAG;YACfK;QACF;QACA,MAAMyF,OAAOL,GAAG,CAAC7E,GAAG,CAClBnD,4BAA4B;YAAEyC,UAAU;YAAWG;YAAMF;QAAO,IAChE;YAAEU,OAAO;QAAK;QAEhB,OAAO;YAAEG,QAAQ;YAAYhB,KAAK8F,OAAO9F,GAAG;YAAEE,UAAU;QAAU;IACpE,EAAE,OAAO+E,OAAO;QACdC,QAAQD,KAAK,CAAC,gFAAgFA;QAC9F,OAAO;YAAEjE,QAAQ;QAAS;IAC5B;AACF"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { ProjectDomainStatus } from './domain-provider';
18
+ /** The host fields a domain decision reads, and nothing else. */
19
+ export interface HostDomainRecord {
20
+ id: string;
21
+ subdomain?: string | null;
22
+ cname?: string | null;
23
+ cnameTwin?: string | null;
24
+ cnameAttachmentPending?: boolean | null;
25
+ cnameDetachmentPending?: boolean | null;
26
+ cnameTwinPending?: boolean | null;
27
+ }
28
+ export type HostDomainField = 'subdomain' | 'cname' | 'cnameTwin';
29
+ export type PlatformServedVerdict = {
30
+ served: true;
31
+ via: 'subdomain' | 'cname' | 'twin';
32
+ hostId: string;
33
+ } | {
34
+ served: false;
35
+ reason:
36
+ /** Not a hostname at all, or the tenant apex itself. */
37
+ 'not-a-hostname'
38
+ /** No host carries the name. */
39
+ | 'no-host'
40
+ /** More than one host carries the name; connect-time uniqueness failed. */
41
+ | 'ambiguous'
42
+ /** A host carries it, but its attach, detach or twin never landed. */
43
+ | 'not-live'
44
+ /** The hosting platform does not say the name serves on our deployment now. */
45
+ | 'not-serving'
46
+ /** A read failed. */
47
+ | 'error';
48
+ };
49
+ export interface PlatformServedDeps {
50
+ /** At most two hosts whose `field` equals `value`. */
51
+ findHosts?: (field: HostDomainField, value: string) => Promise<HostDomainRecord[]>;
52
+ /** The hosting platform's live view of a name on the tenant deployment. */
53
+ domainStatus?: (hostname: string) => Promise<ProjectDomainStatus>;
54
+ }
55
+ /** A request's hostname, lowercased and without a trailing dot; null for anything else. */
56
+ export declare function normalizeServedHostname(input: string): string | null;
57
+ /** Whether a name serves on our deployment, and why not when it does not. Never throws. */
58
+ export declare function platformServedDomain(hostname: string, deps?: PlatformServedDeps): Promise<PlatformServedVerdict>;
59
+ /** {@link platformServedDomain} as a yes or no. */
60
+ export declare function isPlatformServedDomain(hostname: string, deps?: PlatformServedDeps): Promise<boolean>;