@aglyn/tenant-data-admin 1.0.0-beta.284 → 1.0.0-beta.287

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.284",
3
+ "version": "1.0.0-beta.287",
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.284",
29
- "@aglyn/shared-util-email": "1.0.0-beta.284",
30
- "@aglyn/shared-util-fbserver": "1.0.0-beta.284",
31
- "@aglyn/shared-util-first-touch": "1.0.0-beta.284",
32
- "@aglyn/shared-util-http": "1.0.0-beta.284",
33
- "@aglyn/shared-util-tools": "1.0.0-beta.284",
28
+ "@aglyn/aglyn": "1.0.0-beta.287",
29
+ "@aglyn/shared-util-email": "1.0.0-beta.287",
30
+ "@aglyn/shared-util-fbserver": "1.0.0-beta.287",
31
+ "@aglyn/shared-util-first-touch": "1.0.0-beta.287",
32
+ "@aglyn/shared-util-http": "1.0.0-beta.287",
33
+ "@aglyn/shared-util-tools": "1.0.0-beta.287",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -13,7 +13,7 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { ACCOUNT_ACQUISITION_FIELD, buildAccountAcquisition, readAccountAcquisition, signUpDoorFor } from "@aglyn/aglyn/app-utils/account-acquisition";
16
+ */ import { ACCOUNT_ACQUISITION_FIELD, buildAccountAcquisition, readAccountAcquisition, signUpDoorFor, signUpProviderFor } from "@aglyn/aglyn/app-utils/account-acquisition";
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";
@@ -118,19 +118,24 @@ import firebaseAdmin from "./firebase-admin.js";
118
118
  *
119
119
  * `null` when the provider is not a sign-up door (SSO records its own).
120
120
  */ export async function recordSignUpAcquisition(input) {
121
- var _ref;
122
- const door = signUpDoorFor(input.provider, input.doorHint);
123
- if (!door) return null;
121
+ var _ref, _ref1;
122
+ // A `custom` token can name no door until the auth record says which
123
+ // provider made the account (AGL-3706), so the lookup comes first for it.
124
+ const custom = input.provider === 'custom';
125
+ if (!custom && !signUpDoorFor(input.provider, input.doorHint)) return null;
124
126
  // Across every pool, not the project's alone (AGL-1122): a lookup that
125
127
  // cannot see an account answers "not new", which writes nothing.
126
128
  const pooled = await findUserByUidAcrossPools(input.uid);
127
- const createdAtMs = Date.parse((_ref = pooled == null ? void 0 : pooled.record.metadata.creationTime) != null ? _ref : '');
129
+ const provider = signUpProviderFor(input.provider, ((_ref = pooled == null ? void 0 : pooled.record.providerData) != null ? _ref : []).map((info)=>info.providerId));
130
+ const door = signUpDoorFor(provider, input.doorHint);
131
+ if (!door) return null;
132
+ const createdAtMs = Date.parse((_ref1 = pooled == null ? void 0 : pooled.record.metadata.creationTime) != null ? _ref1 : '');
128
133
  return recordAccountAcquisition({
129
134
  uid: input.uid,
130
135
  accountCreatedAtMs: Number.isFinite(createdAtMs) ? createdAtMs : null,
131
136
  touch: input.touch,
132
137
  door,
133
- provider: input.provider,
138
+ provider,
134
139
  email: input.email,
135
140
  headers: input.headers,
136
141
  recordedBy: 'signup',
@@ -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 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 const door = signUpDoorFor(input.provider, input.doorHint)\n if (!door) 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 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: input.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","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","doorHint","pooled","createdAtMs","parse","metadata","creationTime"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,yBAAyB,EACzBC,uBAAuB,EACvBC,sBAAsB,EACtBC,aAAa,QAGR,6CAA4C;AACnD,SACEC,eAAe,EACfC,cAAc,EACdC,sBAAsB,QAEjB,qCAAoC;AAC3C,SAASC,wBAAwB,QAAQ,kBAAc;AACvD,OAAOC,mBAAmB,sBAAkB;AAE5C;;;;;;;;;;;;;;CAcC,GAED;;;;;CAKC,GACD,OAAO,MAAMC,gCAAgC,KAAK,KAAK,KAAI;AA6B3D;;;CAGC,GACD,OAAO,eAAeC,uBACpBC,KAAoB,EACpBC,YAAyCJ,cAAcK,GAAG,GAAGD,SAAS,EAAE;IAExE,MAAME,UAAUC,OAAOJ,gBAAAA,QAAS,IAAIK,IAAI,GAAGC,WAAW;IACtD,IAAI,CAACH,SAAS,OAAO;IACrB,IAAI;;YAOKI,mCAAAA;QANP,MAAMA,WAAW,MAAMN,UACpBO,eAAe,CAAC,WACh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OD,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'\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,EACd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ClC,IAAI,CAACe,UAAU,CAAC5D,cAAciC,MAAMY,QAAQ,EAAEZ,MAAM4B,QAAQ,GAAG,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"}
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- import { type AdAudienceAccount, type AdAudienceConfig, type AdAudienceExclusion, type AdAudienceProvider } from './ad-audience-sync';
17
+ import { type AdAudienceAccount, type AdAudienceConfig, type AdAudienceExclusion, type AdAudienceProvider, type AdAudienceStage } from './ad-audience-sync';
18
18
  /**
19
19
  * THE ACCOUNT-HOLDER AD AUDIENCE (AGL-3780) — reading, sending, recording.
20
20
  *
@@ -31,9 +31,16 @@ import { type AdAudienceAccount, type AdAudienceConfig, type AdAudienceExclusion
31
31
  * the only way to take it out of a Google list or a LinkedIn segment is the
32
32
  * hash this sync sent it under. Admin-SDK only; no client rule opens either.
33
33
  * No address is stored, and neither addresses nor hashes are ever logged.
34
+ *
35
+ * A STAGE list (AGL-4072) keeps the same two things under its own document,
36
+ * `adAudienceSync/{provider}--{stage}`, so each stage has its own ledger, its
37
+ * own diff and its own shrink guard, and nothing one list does can touch what
38
+ * another was sent.
34
39
  */
35
40
  export declare const AD_AUDIENCE_SYNC_COLLECTION = "adAudienceSync";
36
41
  export declare const AD_AUDIENCE_MEMBERS_SUBCOLLECTION = "members";
42
+ /** The ledger document of one list: the provider's own, or `{provider}--{stage}`. */
43
+ export declare function adAudienceLedgerId(provider: AdAudienceProvider, stage?: AdAudienceStage | null): string;
37
44
  /** The Auth page reader, as `listUsersAcrossPools` answers it. */
38
45
  export type ListUsersPage = (pageSize: number, pageToken?: string) => Promise<{
39
46
  users: Array<{
@@ -43,6 +50,13 @@ export type ListUsersPage = (pageSize: number, pageToken?: string) => Promise<{
43
50
  emailVerified: boolean;
44
51
  disabled: boolean;
45
52
  customClaims?: Record<string, unknown>;
53
+ /**
54
+ * Only `creationTime` is read. `lastSignInTime` and `lastRefreshTime`
55
+ * are never activity: a silent re-sign-in moves both with nobody there.
56
+ */
57
+ metadata?: {
58
+ creationTime?: string;
59
+ };
46
60
  };
47
61
  }>;
48
62
  nextPageToken: string | null | undefined;
@@ -53,6 +67,16 @@ export interface AdAudienceReadDeps {
53
67
  /** The account-ban list's answer for these addresses, lowercased. */
54
68
  bannedEmails: (emails: readonly string[]) => Promise<Set<string>>;
55
69
  now: number;
70
+ /**
71
+ * The operator's own domains. Only narrows whose recent activity is read:
72
+ * an internal account is in no list, so its change log is not looked at.
73
+ */
74
+ internalDomains?: readonly string[];
75
+ /**
76
+ * The newest real activity of one account since `sinceMs`, or null. The
77
+ * Firestore reader `readRecentActivityAtMs` unless a spec passes its own.
78
+ */
79
+ recentActivity?: (uid: string, sinceMs: number) => Promise<number | null>;
56
80
  }
57
81
  /** A number for each reason; never a person. */
58
82
  export type ExclusionCounts = Record<AdAudienceExclusion, number>;
@@ -65,17 +89,39 @@ export interface AdAudienceSelection {
65
89
  billing: number;
66
90
  signup: number;
67
91
  };
92
+ /** The eligible accounts in each stage (AGL-4072). */
93
+ stages: Record<AdAudienceStage, AdAudienceAccount[]>;
68
94
  }
69
- /** Every account, with the facts eligibility reads. */
95
+ /** Every account, with the facts eligibility and the stage lists read. */
70
96
  export declare function readAdAudienceAccounts(deps: AdAudienceReadDeps): Promise<{
71
97
  accounts: AdAudienceAccount[];
72
98
  }>;
73
- /** The eligible accounts and the counts of everyone left out. */
74
- export declare function selectAdAudience(accounts: readonly AdAudienceAccount[], internalDomains: readonly string[]): AdAudienceSelection;
99
+ /**
100
+ * The newest thing one account DID since `sinceMs`, or null when nothing was
101
+ * recorded. Two signals, both read through collection-group indexes that
102
+ * already exist for the staff activity feed and the AI job list:
103
+ *
104
+ * - **Change-log entries** under the account's id, on any site's or
105
+ * workspace's log (`hosts/{id}/activity`, `orgs/{id}/activity`): page
106
+ * edits, publishes, form and CRM actions, settings. Entries the platform
107
+ * writes under the person's id without them acting
108
+ * (`isRealActivityAction`) are skipped.
109
+ * - **AI jobs the account started** (`orgs/{id}/aiJobs` by `createdBy`). The
110
+ * start only: a job's later updates are the platform's.
111
+ *
112
+ * Firebase's sign-in and token-refresh times, and the device "last seen"
113
+ * stamps, are never read: a silent re-sign-in moves them with nobody there.
114
+ */
115
+ export declare function readRecentActivityAtMs(db: FirebaseFirestore.Firestore, uid: string, sinceMs: number): Promise<number | null>;
116
+ /** The eligible accounts, the counts of everyone left out, and each stage. */
117
+ export declare function selectAdAudience(accounts: readonly AdAudienceAccount[], internalDomains: readonly string[], now?: number): AdAudienceSelection;
75
118
  /** The set one provider should hold. Two addresses may share a hash. */
76
119
  export declare function providerHashes(provider: AdAudienceProvider, eligible: readonly AdAudienceAccount[]): string[];
77
- /** What one provider was last sent. */
78
- export declare function readSentHashes(firestore: FirebaseFirestore.Firestore, provider: AdAudienceProvider): Promise<string[]>;
120
+ /**
121
+ * What one list was last sent: the provider's all-holders list, or with
122
+ * `stage` that stage's list, each from its own ledger.
123
+ */
124
+ export declare function readSentHashes(firestore: FirebaseFirestore.Firestore, provider: AdAudienceProvider, stage?: AdAudienceStage | null): Promise<string[]>;
79
125
  export type AudienceFetch = (url: string, init: {
80
126
  method: string;
81
127
  headers: Record<string, string>;
@@ -103,6 +149,16 @@ export interface ProviderReport {
103
149
  /** For `failed`: the provider's status and message, never a payload. */
104
150
  error?: string;
105
151
  }
152
+ /** One stage's list on every provider (AGL-4072). */
153
+ export interface StageReport {
154
+ /**
155
+ * The eligible accounts in the stage. Counted for every stage on every
156
+ * run, whether or not any of its lists is configured, so the report says
157
+ * when a stage is big enough to be worth a list.
158
+ */
159
+ eligible: number;
160
+ providers: Record<AdAudienceProvider, ProviderReport>;
161
+ }
106
162
  export interface AdAudienceSyncReport {
107
163
  dryRun: boolean;
108
164
  flagOn: boolean;
@@ -114,6 +170,7 @@ export interface AdAudienceSyncReport {
114
170
  signup: number;
115
171
  };
116
172
  providers: Record<AdAudienceProvider, ProviderReport>;
173
+ stages: Record<AdAudienceStage, StageReport>;
117
174
  }
118
175
  export interface AdAudienceRunOptions {
119
176
  /** Report what would change and send nothing. */