@aglyn/tenant-data-admin 1.0.0-beta.221 → 1.0.0-beta.223
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/server/api-keys.js +3 -3
- package/src/lib/server/api-keys.js.map +1 -1
- package/src/lib/server/api-v1-resources.d.ts +44 -3
- package/src/lib/server/api-v1-resources.js +82 -5
- package/src/lib/server/api-v1-resources.js.map +1 -1
- package/src/lib/server/collection-live-pages.d.ts +2 -2
- package/src/lib/server/collection-live-pages.js +1 -1
- package/src/lib/server/collection-live-pages.js.map +1 -1
- package/src/lib/server/email-delivery-log.d.ts +17 -73
- package/src/lib/server/email-delivery-log.js +44 -222
- package/src/lib/server/email-delivery-log.js.map +1 -1
- package/src/lib/server/email-flow-gate.js +27 -38
- package/src/lib/server/email-flow-gate.js.map +1 -1
- package/src/lib/server/erase-person.d.ts +34 -54
- package/src/lib/server/erase-person.js +44 -239
- package/src/lib/server/erase-person.js.map +1 -1
- package/src/lib/server/ga4-measurement-protocol.js +41 -28
- package/src/lib/server/ga4-measurement-protocol.js.map +1 -1
- package/src/lib/server/host-visitor-records.d.ts +25 -4
- package/src/lib/server/host-visitor-records.js +39 -11
- package/src/lib/server/host-visitor-records.js.map +1 -1
- package/src/lib/server/hosted-page-review.js +52 -36
- package/src/lib/server/hosted-page-review.js.map +1 -1
- package/src/lib/server/link-reputation-review.d.ts +6 -2
- package/src/lib/server/link-reputation-review.js +61 -20
- package/src/lib/server/link-reputation-review.js.map +1 -1
- package/src/lib/server/live-page-drops.d.ts +67 -0
- package/src/lib/server/live-page-drops.js +57 -0
- package/src/lib/server/live-page-drops.js.map +1 -0
- package/src/lib/server/media-bandwidth-cap.d.ts +78 -0
- package/src/lib/server/media-bandwidth-cap.js +180 -0
- package/src/lib/server/media-bandwidth-cap.js.map +1 -0
- package/src/lib/server/media-cdn-icon.d.ts +77 -0
- package/src/lib/server/media-cdn-icon.js +140 -0
- package/src/lib/server/media-cdn-icon.js.map +1 -0
- package/src/lib/server/media-delivery-regeneration.d.ts +132 -0
- package/src/lib/server/media-delivery-regeneration.js +216 -0
- package/src/lib/server/media-delivery-regeneration.js.map +1 -0
- package/src/lib/server/media-delivery.d.ts +2 -0
- package/src/lib/server/media-delivery.js +2 -1
- package/src/lib/server/media-delivery.js.map +1 -1
- package/src/lib/server/media-serve-count.d.ts +50 -0
- package/src/lib/server/media-serve-count.js +62 -0
- package/src/lib/server/media-serve-count.js.map +1 -0
- package/src/lib/server/media-signing.d.ts +13 -2
- package/src/lib/server/media-signing.js +12 -8
- package/src/lib/server/media-signing.js.map +1 -1
- package/src/lib/server/media-tombstone.js +7 -5
- package/src/lib/server/media-tombstone.js.map +1 -1
- package/src/lib/server/media-variants.d.ts +151 -20
- package/src/lib/server/media-variants.js +204 -27
- package/src/lib/server/media-variants.js.map +1 -1
- package/src/lib/server/organizations.d.ts +102 -2
- package/src/lib/server/organizations.js +388 -58
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/outbound-send-review.js +11 -7
- package/src/lib/server/outbound-send-review.js.map +1 -1
- package/src/lib/server/paged-sweeps.d.ts +51 -0
- package/src/lib/server/paged-sweeps.js +79 -0
- package/src/lib/server/paged-sweeps.js.map +1 -0
- package/src/lib/server/payment-fraud-signal.d.ts +49 -9
- package/src/lib/server/payment-fraud-signal.js +192 -48
- package/src/lib/server/payment-fraud-signal.js.map +1 -1
- package/src/lib/server/platform-marketing-consent.d.ts +0 -49
- package/src/lib/server/platform-marketing-consent.js +27 -11
- package/src/lib/server/platform-marketing-consent.js.map +1 -1
- package/src/lib/server/render-monitor.d.ts +166 -0
- package/src/lib/server/render-monitor.js +412 -0
- package/src/lib/server/render-monitor.js.map +1 -0
- package/src/lib/server/risk-notice.d.ts +7 -0
- package/src/lib/server/risk-notice.js +6 -0
- package/src/lib/server/risk-notice.js.map +1 -1
- package/src/lib/server/serve-media-cdn.d.ts +69 -1
- package/src/lib/server/serve-media-cdn.js +424 -70
- package/src/lib/server/serve-media-cdn.js.map +1 -1
- package/src/lib/server/site-icon-render.d.ts +68 -0
- package/src/lib/server/site-icon-render.js +157 -0
- package/src/lib/server/site-icon-render.js.map +1 -0
- package/src/lib/server/staff-seat.d.ts +50 -0
- package/src/lib/server/staff-seat.js +118 -0
- package/src/lib/server/staff-seat.js.map +1 -0
- package/src/lib/server/transfer-export.d.ts +46 -0
- package/src/lib/server/transfer-export.js +221 -0
- package/src/lib/server/transfer-export.js.map +1 -0
- package/src/lib/server/transfer-jobs.d.ts +385 -0
- package/src/lib/server/transfer-jobs.js +2368 -0
- package/src/lib/server/transfer-jobs.js.map +1 -0
- package/src/lib/server/transfer-packages.d.ts +127 -0
- package/src/lib/server/transfer-packages.js +1036 -0
- package/src/lib/server/transfer-packages.js.map +1 -0
- package/src/lib/server/upgrade-proposal.d.ts +97 -0
- package/src/lib/server/upgrade-proposal.js +312 -0
- package/src/lib/server/upgrade-proposal.js.map +1 -0
- package/src/lib/server/upsert-contact.d.ts +17 -8
- package/src/lib/server/upsert-contact.js +82 -16
- package/src/lib/server/upsert-contact.js.map +1 -1
- package/src/lib/server/web-risk.d.ts +50 -9
- package/src/lib/server/web-risk.js +290 -155
- package/src/lib/server/web-risk.js.map +1 -1
- package/src/tenancy.d.ts +3 -3
- package/src/tenancy.js +5 -3
- package/src/tenancy.js.map +1 -1
- package/src/lib/server/campaign-attribution-store.d.ts +0 -55
- package/src/lib/server/campaign-attribution-store.js +0 -95
- package/src/lib/server/campaign-attribution-store.js.map +0 -1
- package/src/lib/server/campaign-conversion-attribution.d.ts +0 -283
- package/src/lib/server/campaign-conversion-attribution.js +0 -450
- package/src/lib/server/campaign-conversion-attribution.js.map +0 -1
- package/src/lib/server/crm-email-activity.d.ts +0 -118
- package/src/lib/server/crm-email-activity.js +0 -148
- package/src/lib/server/crm-email-activity.js.map +0 -1
- package/src/lib/server/crm-next-activity.d.ts +0 -74
- package/src/lib/server/crm-next-activity.js +0 -194
- package/src/lib/server/crm-next-activity.js.map +0 -1
- package/src/lib/server/dataset-live-pages.d.ts +0 -179
- package/src/lib/server/dataset-live-pages.js +0 -421
- package/src/lib/server/dataset-live-pages.js.map +0 -1
- package/src/lib/server/email-revenue-attribution.d.ts +0 -185
- package/src/lib/server/email-revenue-attribution.js +0 -321
- package/src/lib/server/email-revenue-attribution.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/web-risk.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 * GOOGLE WEB RISK (AGL-3451): the lookup behind the link reputation screen.\n *\n * `@aglyn/shared-util-email/link-reputation` decides which hosts are foreign\n * and turns a listing into a strong `web-risk-link` signal. This is the store\n * half: the `uris.search` client, the cache, the kill switch.\n *\n * ## The client\n *\n * {@link WebRiskClient} is the contract: one URI in, the threat types it is\n * listed for and how long that answer may be kept. The default\n * implementation calls `webrisk.googleapis.com/v1/uris:search` for\n * SOCIAL_ENGINEERING, MALWARE and UNWANTED_SOFTWARE as the platform's own\n * service account — the firebase-admin credential every other server-side\n * Google call here already uses (`client-error-report.ts`), so there is no\n * key of its own. Only `https://<host>/` is ever sent: see the module header\n * of `link-reputation.ts`.\n *\n * ## Not evidence when it fails\n *\n * A call is given {@link WEB_RISK_TIMEOUT_MS}, and a whole lookup\n * {@link WEB_RISK_DEADLINE_MS}. A host whose answer did not arrive, or whose\n * call failed, is UNKNOWN: it holds nothing and logs a warning. A credential\n * the API refuses (the API is not enabled on a self-hosted project, say) backs\n * the lookup off for a quarter of an hour, so a misconfiguration is one log\n * line rather than one per page.\n *\n * ## The cache\n *\n * Per host, in two layers:\n *\n * - this process's memory — a listed host until the answer's `expireTime`,\n * which Web Risk sets and which may not be exceeded; a clean one for\n * {@link WEB_RISK_MEMORY_CLEAN_TTL_MS}, short so a listing the daily\n * re-check writes reaches every warm render within minutes;\n * - `webRiskVerdicts/{host}` — server-only, one document per host, a clean\n * answer kept {@link WEB_RISK_CLEAN_TTL_MS}. Bounded by the number of\n * distinct foreign hosts and rewritten in place, so it needs no TTL policy.\n *\n * Read in one `getAll` per lookup, so a page's twenty hosts cost one round\n * trip, and nothing at all once they are in memory.\n *\n * ## The kill switch\n *\n * `platformSettings/webRisk` `{ enabled: false }` stops every lookup within a\n * minute — every host reads unknown, so nothing holds on it — without a\n * deploy. Absent or anything else means on.\n *=========================================*/\n\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport {\n LINK_THREAT_TYPES,\n type LinkReputationAnswer,\n type LinkThreatType,\n MAX_REPUTATION_HOSTS_PER_LOOKUP,\n normalizeReputationHost,\n setLinkReputationLookup,\n} from '@aglyn/shared-util-email/link-reputation'\nimport { getApp } from 'firebase-admin/app'\nimport firebaseAdmin from './firebase-admin'\n\nexport const WEB_RISK_SEARCH_ENDPOINT = 'https://webrisk.googleapis.com/v1/uris:search'\nexport const WEB_RISK_CACHE_COLLECTION = 'webRiskVerdicts'\n/** The kill switch: `{ enabled: false }` turns every lookup off. */\nexport const WEB_RISK_SETTINGS_COLLECTION = 'platformSettings'\nexport const WEB_RISK_SETTINGS_DOC = 'webRisk'\n\n/** One call's budget. */\nexport const WEB_RISK_TIMEOUT_MS = 1_000\n/** One lookup's budget, however many hosts it asks about. */\nexport const WEB_RISK_DEADLINE_MS = 1_200\n/** How long a clean answer is kept in the store. */\nexport const WEB_RISK_CLEAN_TTL_MS = 12 * 60 * 60_000\n/** How long a clean answer is trusted from this process's memory. */\nexport const WEB_RISK_MEMORY_CLEAN_TTL_MS = 10 * 60_000\n/** A listing whose answer named no `expireTime` is kept this long. */\nexport const WEB_RISK_LISTED_FALLBACK_TTL_MS = 5 * 60_000\n/** How long the switch's answer is trusted. */\nconst SWITCH_TTL_MS = 60_000\n/** How long a refused credential stops the lookup. */\nconst REFUSED_BACKOFF_MS = 15 * 60_000\n/** How long a rate limit stops the lookup. */\nconst THROTTLED_BACKOFF_MS = 60_000\n/** At most one warning per this long, so an outage is not a log flood. */\nconst WARN_EVERY_MS = 60_000\n\n/** What `uris.search` answered for one URI. */\nexport interface WebRiskSearchResult {\n /** The lists it is on; empty when it is on none. */\n threats: LinkThreatType[]\n /** Until when the answer may be kept, when the API said. */\n expireTimeMs: number | null\n}\n\n/** The contract: one URI, its listing. Throws on anything but an answer. */\nexport interface WebRiskClient {\n searchUri(uri: string): Promise<WebRiskSearchResult>\n}\n\n/** The API answered with a status that is not an answer. */\nexport class WebRiskHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Web Risk answered ${status}: ${detail.slice(0, 200)}`)\n this.name = 'WebRiskHttpError'\n }\n}\n\n/** There is no credential to call with. */\nexport class WebRiskUnavailableError extends Error {\n constructor(reason: string) {\n super(reason)\n this.name = 'WebRiskUnavailableError'\n }\n}\n\n/** `uris.search`'s body, read defensively: an empty object is \"not listed\". */\nexport function parseWebRiskSearch(body: unknown): WebRiskSearchResult {\n const threat = (body as { threat?: { threatTypes?: unknown; expireTime?: unknown } } | null)\n ?.threat\n if (!threat || typeof threat !== 'object') return { threats: [], expireTimeMs: null }\n const listed = Array.isArray(threat.threatTypes) ? threat.threatTypes : []\n const threats = LINK_THREAT_TYPES.filter((type) => listed.includes(type))\n const expireTimeMs =\n typeof threat.expireTime === 'string' ? Date.parse(threat.expireTime) : Number.NaN\n return { threats, expireTimeMs: Number.isFinite(expireTimeMs) ? expireTimeMs : null }\n}\n\n/** The URI a host is looked up as. Only the host: never a path or a query. */\nexport function webRiskUriForHost(host: string): string {\n return `https://${host}/`\n}\n\n/** The default client: `uris.search` over HTTPS with a bearer token. */\nexport function createWebRiskHttpClient(options: {\n accessToken: () => Promise<string | null>\n fetch?: typeof fetch\n timeoutMs?: number\n endpoint?: string\n}): WebRiskClient {\n const request = options.fetch ?? fetch\n const timeoutMs = options.timeoutMs ?? WEB_RISK_TIMEOUT_MS\n return {\n async searchUri(uri: string): Promise<WebRiskSearchResult> {\n const token = await options.accessToken()\n if (!token) throw new WebRiskUnavailableError('no service-account credential')\n const url = new URL(options.endpoint ?? WEB_RISK_SEARCH_ENDPOINT)\n for (const type of LINK_THREAT_TYPES) url.searchParams.append('threatTypes', type)\n url.searchParams.set('uri', uri)\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const response = await request(url.toString(), {\n method: 'GET',\n headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },\n signal: controller.signal,\n })\n if (!response.ok) {\n throw new WebRiskHttpError(response.status, await response.text().catch(() => ''))\n }\n return parseWebRiskSearch(await response.json())\n } finally {\n clearTimeout(timer)\n }\n },\n }\n}\n\n/**\n * The platform service account's access token, or null when this deployment\n * has none — the same credential `client-error-report.ts` writes logs with.\n */\nasync function serviceAccountAccessToken(): Promise<string | null> {\n try {\n const credential = getApp().options.credential\n if (!credential) return null\n return (await credential.getAccessToken())?.access_token ?? null\n } catch {\n return null\n }\n}\n\nlet defaultClient: WebRiskClient | null = null\nlet clientOverride: WebRiskClient | null | undefined\n\nfunction activeClient(): WebRiskClient | null {\n if (clientOverride !== undefined) return clientOverride\n defaultClient ??= createWebRiskHttpClient({ accessToken: serviceAccountAccessToken })\n return defaultClient\n}\n\ninterface Verdict {\n threats: LinkThreatType[]\n checkedAtMs: number\n /** When the answer stops being good, in the store. */\n expiresAtMs: number\n}\n\nconst memory = new Map<string, Verdict & { memoryUntilMs: number }>()\nlet switchMemo: { off: boolean; atMs: number } | null = null\nlet backoffUntilMs = 0\nlet lastWarnAtMs = 0\n\n/** Test seam: forget the caches, the switch, the back-off; optionally stand in a client. */\nexport function resetWebRiskForTests(client?: WebRiskClient | null): void {\n memory.clear()\n switchMemo = null\n backoffUntilMs = 0\n lastWarnAtMs = 0\n clientOverride = client\n defaultClient = null\n}\n\nfunction warn(nowMs: number, message: string, error?: unknown): void {\n if (nowMs - lastWarnAtMs < WARN_EVERY_MS) return\n lastWarnAtMs = nowMs\n console.warn(`[web-risk] ${message} — the host reads unknown, which is not evidence`, error ?? '')\n}\n\n/** Is the lookup switched off? Read at most once a minute; an unreadable switch is on. */\nasync function switchedOff(nowMs: number): Promise<boolean> {\n if (switchMemo && nowMs - switchMemo.atMs < SWITCH_TTL_MS) return switchMemo.off\n const off = await firebaseAdmin\n .app()\n .firestore()\n .collection(WEB_RISK_SETTINGS_COLLECTION)\n .doc(WEB_RISK_SETTINGS_DOC)\n .get()\n .then(\n (snapshot) => snapshot.get('enabled') === false,\n () => false,\n )\n switchMemo = { off, atMs: nowMs }\n return off\n}\n\n/**\n * Hosts that are the platform's own: every site's subdomain on the tenant\n * apex. Never looked up — a neighbour's site is screened on its own page.\n */\nexport function platformReputationExclusions(): string[] {\n return [TENANT_APEX].filter(Boolean)\n}\n\nfunction isPlatformHost(host: string): boolean {\n return platformReputationExclusions().some(\n (domain) => host === domain || host.endsWith(`.${domain}`),\n )\n}\n\nfunction verdictFrom(data: Record<string, unknown> | undefined): Verdict | null {\n if (!data) return null\n const threats = Array.isArray(data['threats'])\n ? LINK_THREAT_TYPES.filter((type) => (data['threats'] as unknown[]).includes(type))\n : []\n const checkedAtMs = Number(data['checkedAtMs'])\n const expiresAtMs = Number(data['expiresAtMs'])\n if (!Number.isFinite(checkedAtMs) || !Number.isFinite(expiresAtMs)) return null\n return { threats, checkedAtMs, expiresAtMs }\n}\n\nfunction remember(host: string, verdict: Verdict, nowMs: number): void {\n memory.set(host, {\n ...verdict,\n memoryUntilMs: verdict.threats.length\n ? verdict.expiresAtMs\n : Math.min(verdict.expiresAtMs, nowMs + WEB_RISK_MEMORY_CLEAN_TTL_MS),\n })\n}\n\nexport interface HostReputationLookupOptions {\n /** How long the caller will wait, overall. */\n deadlineMs?: number\n /** The most hosts asked about; the rest read unknown. */\n maxHosts?: number\n nowMs?: number\n}\n\n/** What a lookup answered, and how many hosts it had to ask the API about. */\nexport interface HostReputationLookupResult extends LinkReputationAnswer {\n looked: number\n}\n\n/**\n * The reputation of each host: listed, clean, or unknown. Platform hosts are\n * clean without asking. Never throws, and never waits longer than the\n * deadline: a call still running then finishes in the background and fills\n * the caches for the next asker.\n *\n * \"Never throws\" covers the store as well as the API: a missing app, a\n * settings read that fails before it is a promise, or a cache reference\n * that cannot be built all read every host as unknown. The page review\n * calls this before its own fail-closed `try`, so a throw here would take\n * down every page with a link off the site.\n */\nexport async function lookupHostReputation(\n hosts: readonly string[],\n options: HostReputationLookupOptions = {},\n): Promise<HostReputationLookupResult> {\n try {\n return await lookupHostReputationOrThrow(hosts, options)\n } catch (error) {\n warn(options.nowMs ?? Date.now(), 'a lookup failed before it could answer', error)\n const unknown = [\n ...new Set(\n hosts\n .map((raw) => normalizeReputationHost(raw))\n .filter((host): host is string => Boolean(host)),\n ),\n ]\n return { hits: [], clean: [], unknown, looked: 0 }\n }\n}\n\nasync function lookupHostReputationOrThrow(\n hosts: readonly string[],\n options: HostReputationLookupOptions,\n): Promise<HostReputationLookupResult> {\n const nowMs = options.nowMs ?? Date.now()\n const result: HostReputationLookupResult = { hits: [], clean: [], unknown: [], looked: 0 }\n const wanted: string[] = []\n for (const raw of hosts) {\n const host = normalizeReputationHost(raw)\n if (!host || wanted.includes(host) || result.clean.includes(host)) continue\n if (isPlatformHost(host)) result.clean.push(host)\n else if (wanted.length < (options.maxHosts ?? MAX_REPUTATION_HOSTS_PER_LOOKUP)) wanted.push(host)\n else result.unknown.push(host)\n }\n if (!wanted.length) return result\n\n const settle = (host: string, verdict: Verdict) => {\n if (verdict.threats.length) result.hits.push({ host, threats: verdict.threats })\n else result.clean.push(host)\n }\n\n // 1. This process's memory.\n let missing = wanted.filter((host) => {\n const known = memory.get(host)\n if (known && nowMs < known.memoryUntilMs) {\n settle(host, known)\n return false\n }\n return true\n })\n if (!missing.length) return result\n\n // 2. The switch. Off reads every remaining host as unknown.\n if (await switchedOff(nowMs)) {\n result.unknown.push(...missing)\n return result\n }\n\n // 3. The store, in one round trip.\n const firestore = firebaseAdmin.app().firestore()\n const collection = firestore.collection(WEB_RISK_CACHE_COLLECTION)\n try {\n const snapshots = await firestore.getAll(...missing.map((host) => collection.doc(host)))\n const stored = new Map<string, Verdict>()\n for (const snapshot of snapshots) {\n const verdict = verdictFrom(snapshot.exists ? (snapshot.data() as Record<string, unknown>) : undefined)\n if (verdict && nowMs < verdict.expiresAtMs) stored.set(snapshot.id, verdict)\n }\n missing = missing.filter((host) => {\n const verdict = stored.get(host)\n if (!verdict) return true\n remember(host, verdict, nowMs)\n settle(host, verdict)\n return false\n })\n } catch (error) {\n warn(nowMs, 'the verdict cache could not be read', error)\n }\n if (!missing.length) return result\n\n // 4. The API, every remaining host at once, within the deadline.\n const client = activeClient()\n if (!client || nowMs < backoffUntilMs) {\n result.unknown.push(...missing)\n return result\n }\n result.looked = missing.length\n const answers = new Map<string, Verdict>()\n const calls = missing.map(async (host) => {\n try {\n const answer = await client.searchUri(webRiskUriForHost(host))\n const checkedAtMs = Date.now()\n const verdict: Verdict = {\n threats: answer.threats,\n checkedAtMs,\n expiresAtMs: answer.threats.length\n ? (answer.expireTimeMs ?? checkedAtMs + WEB_RISK_LISTED_FALLBACK_TTL_MS)\n : checkedAtMs + WEB_RISK_CLEAN_TTL_MS,\n }\n answers.set(host, verdict)\n remember(host, verdict, checkedAtMs)\n await collection\n .doc(host)\n .set({ host, ...verdict, listed: verdict.threats.length > 0 })\n .catch((error: unknown) => warn(checkedAtMs, 'a verdict could not be cached', error))\n } catch (error) {\n if (error instanceof WebRiskHttpError && [401, 403, 404].includes(error.status)) {\n backoffUntilMs = Date.now() + REFUSED_BACKOFF_MS\n console.error('[web-risk] the API refused the credential — lookups paused for 15 minutes', error)\n } else if (error instanceof WebRiskHttpError && error.status === 429) {\n backoffUntilMs = Date.now() + THROTTLED_BACKOFF_MS\n warn(Date.now(), 'the API is rate limiting', error)\n } else if (error instanceof WebRiskUnavailableError) {\n backoffUntilMs = Date.now() + REFUSED_BACKOFF_MS\n warn(Date.now(), 'no credential to call the API with', error)\n } else {\n warn(Date.now(), `the lookup of ${host} failed or timed out`, error)\n }\n }\n })\n let timer: ReturnType<typeof setTimeout> | undefined\n await Promise.race([\n Promise.allSettled(calls),\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, options.deadlineMs ?? WEB_RISK_DEADLINE_MS)\n }),\n ])\n if (timer) clearTimeout(timer)\n const late = missing.filter((host) => !answers.has(host))\n for (const host of missing) {\n const verdict = answers.get(host)\n if (verdict) settle(host, verdict)\n }\n result.unknown.push(...late)\n if (late.length) warn(Date.now(), `${late.length} host(s) had no answer within the deadline`)\n return result\n}\n\n/**\n * Puts this lookup behind the shared screen's reputation seam, so the send\n * seam (`screenTenantMessage`) asks it. Called by\n * `installOutboundScreenGate`, at that module's load.\n */\nexport function installLinkReputationLookup(): void {\n if (typeof setLinkReputationLookup !== 'function') return\n setLinkReputationLookup((hosts, options) =>\n lookupHostReputation(hosts, { deadlineMs: options?.deadlineMs }),\n )\n}\n"],"names":["TENANT_APEX","LINK_THREAT_TYPES","MAX_REPUTATION_HOSTS_PER_LOOKUP","normalizeReputationHost","setLinkReputationLookup","getApp","firebaseAdmin","WEB_RISK_SEARCH_ENDPOINT","WEB_RISK_CACHE_COLLECTION","WEB_RISK_SETTINGS_COLLECTION","WEB_RISK_SETTINGS_DOC","WEB_RISK_TIMEOUT_MS","WEB_RISK_DEADLINE_MS","WEB_RISK_CLEAN_TTL_MS","WEB_RISK_MEMORY_CLEAN_TTL_MS","WEB_RISK_LISTED_FALLBACK_TTL_MS","SWITCH_TTL_MS","REFUSED_BACKOFF_MS","THROTTLED_BACKOFF_MS","WARN_EVERY_MS","WebRiskHttpError","Error","status","detail","slice","name","WebRiskUnavailableError","reason","parseWebRiskSearch","body","threat","threats","expireTimeMs","listed","Array","isArray","threatTypes","filter","type","includes","expireTime","Date","parse","Number","NaN","isFinite","webRiskUriForHost","host","createWebRiskHttpClient","options","request","fetch","timeoutMs","searchUri","uri","token","accessToken","url","URL","endpoint","searchParams","append","set","controller","AbortController","timer","setTimeout","abort","response","toString","method","headers","Authorization","Accept","signal","ok","text","catch","json","clearTimeout","serviceAccountAccessToken","credential","getAccessToken","access_token","defaultClient","clientOverride","activeClient","undefined","memory","Map","switchMemo","backoffUntilMs","lastWarnAtMs","resetWebRiskForTests","client","clear","warn","nowMs","message","error","console","switchedOff","atMs","off","app","firestore","collection","doc","get","then","snapshot","platformReputationExclusions","Boolean","isPlatformHost","some","domain","endsWith","verdictFrom","data","checkedAtMs","expiresAtMs","remember","verdict","memoryUntilMs","length","Math","min","lookupHostReputation","hosts","lookupHostReputationOrThrow","now","unknown","Set","map","raw","hits","clean","looked","result","wanted","push","maxHosts","settle","missing","known","snapshots","getAll","stored","exists","id","answers","calls","answer","Promise","race","allSettled","resolve","deadlineMs","late","has","installLinkReputationLookup"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA+C2C,GAE3C,SAASA,WAAW,QAAQ,qCAAoC;AAChE,SACEC,iBAAiB,EAGjBC,+BAA+B,EAC/BC,uBAAuB,EACvBC,uBAAuB,QAClB,2CAA0C;AACjD,SAASC,MAAM,QAAQ,qBAAoB;AAC3C,OAAOC,mBAAmB,sBAAkB;AAE5C,OAAO,MAAMC,2BAA2B,gDAA+C;AACvF,OAAO,MAAMC,4BAA4B,kBAAiB;AAC1D,kEAAkE,GAClE,OAAO,MAAMC,+BAA+B,mBAAkB;AAC9D,OAAO,MAAMC,wBAAwB,UAAS;AAE9C,uBAAuB,GACvB,OAAO,MAAMC,sBAAsB,KAAK;AACxC,2D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,WAAW0F,UAAS3G,sBAAAA,QAAQ4G,UAAU,YAAlB5G,sBAAsBrC;QACpD;KACD;IACD,IAAIqD,OAAOc,aAAad;IACxB,MAAM6F,OAAOf,QAAQ1G,MAAM,CAAC,CAACU,OAAS,CAACuG,QAAQS,GAAG,CAAChH;IACnD,KAAK,MAAMA,QAAQgG,QAAS;QAC1B,MAAMrB,UAAU4B,QAAQ1C,GAAG,CAAC7D;QAC5B,IAAI2E,SAASoB,OAAO/F,MAAM2E;IAC5B;IACAgB,OAAOP,OAAO,CAACS,IAAI,IAAIkB;IACvB,IAAIA,KAAKlC,MAAM,EAAE5B,KAAKvD,KAAKyF,GAAG,IAAI,GAAG4B,KAAKlC,MAAM,CAAC,0CAA0C,CAAC;IAC5F,OAAOc;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASsB;IACd,IAAI,OAAO5J,4BAA4B,YAAY;IACnDA,wBAAwB,CAAC4H,OAAO/E,UAC9B8E,qBAAqBC,OAAO;YAAE6B,UAAU,EAAE5G,2BAAAA,QAAS4G,UAAU;QAAC;AAElE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/web-risk.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/*==========================================\n * GOOGLE WEB RISK (AGL-3451): the lookup behind the link reputation screen.\n *\n * `@aglyn/shared-util-email/link-reputation` decides which hosts are foreign\n * and turns a listing into a strong `web-risk-link` signal. This is the store\n * half: the `uris.search` client, the cache, the switches.\n *\n * ## The client\n *\n * {@link WebRiskClient} is the contract: one URI in, the threat types it is\n * listed for and how long that answer may be kept. The default\n * implementation calls `webrisk.googleapis.com/v1/uris:search` for\n * SOCIAL_ENGINEERING, MALWARE and UNWANTED_SOFTWARE as the platform's own\n * service account — the firebase-admin credential every other server-side\n * Google call here already uses (`client-error-report.ts`), so there is no\n * key of its own. What is sent depends on the lookup mode, below.\n *\n * ## The lookup mode (AGL-3459)\n *\n * `platformSettings/webRisk.lookupMode`:\n *\n * - `'host'` — the default, and anything that is not `'url'`. Only\n * `https://<host>/` is ever sent.\n * - `'url'` — the host first, from the cache or a call; then, for a host\n * that is not itself listed, each of its links' addresses as\n * `normalizeReputationLink` reduced them: scheme, host and path, never a\n * query string, a fragment or a `user:password@`. A listed address is a\n * hit on a clean host, so a kit at a path on a compromised site holds the\n * page. At most `MAX_REPUTATION_URLS_PER_LOOKUP` addresses per lookup,\n * inside the same deadline as the hosts.\n *\n * `'url'` sends more than a host to Google, so it stays off until the\n * Subprocessors page names that purpose — see the `webrisk.googleapis.com`\n * entry in `apps/console/constants/subprocessor-inventory.ts`.\n *\n * ## Not evidence when it fails\n *\n * A call is given {@link WEB_RISK_TIMEOUT_MS}, and a whole lookup\n * {@link WEB_RISK_DEADLINE_MS} — hosts and addresses together. A host or an\n * address whose answer did not arrive, or whose call failed, is UNKNOWN: it\n * holds nothing and logs a warning. A credential the API refuses (the API is\n * not enabled on a self-hosted project, say) backs the lookup off for a\n * quarter of an hour, so a misconfiguration is one log line rather than one\n * per page.\n *\n * ## The cache\n *\n * Per host and per address, in two layers, with the same rules for both:\n *\n * - this process's memory — a listing until the answer's `expireTime`,\n * which Web Risk sets and which may not be exceeded; a clean answer for\n * {@link WEB_RISK_MEMORY_CLEAN_TTL_MS}, short so a listing the daily\n * re-check writes reaches every warm render within minutes. Capped at\n * {@link WEB_RISK_MEMORY_MAX_ENTRIES}, then started again;\n * - the store, server-only, a clean answer kept {@link WEB_RISK_CLEAN_TTL_MS}:\n * `webRiskVerdicts/{host}`, bounded by the number of distinct foreign\n * hosts and rewritten in place; and `webRiskUrlVerdicts/{sha256(address)}`,\n * whose answers the daily re-check deletes a day after they expire\n * ({@link reapExpiredWebRiskUrlVerdicts}), because addresses are many more\n * than hosts and a path is worth keeping no longer than it is used.\n *\n * Read in one `getAll` per lookup, so a page's hosts and addresses cost one\n * round trip, and nothing at all once they are in memory.\n *\n * ## The kill switch\n *\n * `platformSettings/webRisk` `{ enabled: false }` stops every lookup within a\n * minute — every host reads unknown, so nothing holds on it — without a\n * deploy. Absent or anything else means on.\n *=========================================*/\n\nimport { createHash } from 'crypto'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/tenant-apex'\nimport {\n LINK_THREAT_TYPES,\n type LinkReputationAnswer,\n type LinkThreatType,\n MAX_REPUTATION_HOSTS_PER_LOOKUP,\n MAX_REPUTATION_URLS_PER_LOOKUP,\n normalizeReputationHost,\n normalizeReputationLink,\n pickReputationUrls,\n setLinkReputationLookup,\n} from '@aglyn/shared-util-email/link-reputation'\nimport { boundedAwait } from '@aglyn/shared-util-http/bounded-await'\nimport { getApp } from 'firebase-admin/app'\nimport firebaseAdmin from './firebase-admin'\n\nexport const WEB_RISK_SEARCH_ENDPOINT = 'https://webrisk.googleapis.com/v1/uris:search'\n/** One answer per host. */\nexport const WEB_RISK_CACHE_COLLECTION = 'webRiskVerdicts'\n/** One answer per address, in `'url'` mode (AGL-3459), keyed by the address's SHA-256. */\nexport const WEB_RISK_URL_CACHE_COLLECTION = 'webRiskUrlVerdicts'\n/**\n * The switches: `{ enabled: false }` turns every lookup off;\n * `lookupMode: 'url'` looks up links' addresses as well as their hosts.\n */\nexport const WEB_RISK_SETTINGS_COLLECTION = 'platformSettings'\nexport const WEB_RISK_SETTINGS_DOC = 'webRisk'\n\n/** What a lookup sends: the host only (the default), or the address too. */\nexport type WebRiskLookupMode = 'host' | 'url'\n\n/** One call's budget. */\nexport const WEB_RISK_TIMEOUT_MS = 1_000\n/** One lookup's budget, however many hosts and addresses it asks about. */\nexport const WEB_RISK_DEADLINE_MS = 1_200\n/** The service account's token exchange; a cached token answers at once. */\nexport const WEB_RISK_TOKEN_DEADLINE_MS = 3_000\n/** How long a clean answer is kept in the store. */\nexport const WEB_RISK_CLEAN_TTL_MS = 12 * 60 * 60_000\n/** How long a clean answer is trusted from this process's memory. */\nexport const WEB_RISK_MEMORY_CLEAN_TTL_MS = 10 * 60_000\n/** A listing whose answer named no `expireTime` is kept this long. */\nexport const WEB_RISK_LISTED_FALLBACK_TTL_MS = 5 * 60_000\n/** The most answers this process remembers before it starts again. */\nexport const WEB_RISK_MEMORY_MAX_ENTRIES = 20_000\n/** How long past its expiry an address's stored answer is deleted. */\nexport const WEB_RISK_URL_VERDICT_GRACE_MS = 24 * 60 * 60_000\n/** How long the switches' answer is trusted. */\nconst SWITCH_TTL_MS = 60_000\n/** How long a refused credential stops the lookup. */\nconst REFUSED_BACKOFF_MS = 15 * 60_000\n/** How long a rate limit stops the lookup. */\nconst THROTTLED_BACKOFF_MS = 60_000\n/** At most one warning per this long, so an outage is not a log flood. */\nconst WARN_EVERY_MS = 60_000\n\n/** What `uris.search` answered for one URI. */\nexport interface WebRiskSearchResult {\n /** The lists it is on; empty when it is on none. */\n threats: LinkThreatType[]\n /** Until when the answer may be kept, when the API said. */\n expireTimeMs: number | null\n}\n\n/** The contract: one URI, its listing. Throws on anything but an answer. */\nexport interface WebRiskClient {\n searchUri(uri: string): Promise<WebRiskSearchResult>\n}\n\n/** The API answered with a status that is not an answer. */\nexport class WebRiskHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Web Risk answered ${status}: ${detail.slice(0, 200)}`)\n this.name = 'WebRiskHttpError'\n }\n}\n\n/** There is no credential to call with. */\nexport class WebRiskUnavailableError extends Error {\n constructor(reason: string) {\n super(reason)\n this.name = 'WebRiskUnavailableError'\n }\n}\n\n/** `uris.search`'s body, read defensively: an empty object is \"not listed\". */\nexport function parseWebRiskSearch(body: unknown): WebRiskSearchResult {\n const threat = (body as { threat?: { threatTypes?: unknown; expireTime?: unknown } } | null)\n ?.threat\n if (!threat || typeof threat !== 'object') return { threats: [], expireTimeMs: null }\n const listed = Array.isArray(threat.threatTypes) ? threat.threatTypes : []\n const threats = LINK_THREAT_TYPES.filter((type) => listed.includes(type))\n const expireTimeMs =\n typeof threat.expireTime === 'string' ? Date.parse(threat.expireTime) : Number.NaN\n return { threats, expireTimeMs: Number.isFinite(expireTimeMs) ? expireTimeMs : null }\n}\n\n/** The URI a host is looked up as. Only the host: never a path or a query. */\nexport function webRiskUriForHost(host: string): string {\n return `https://${host}/`\n}\n\n/** The default client: `uris.search` over HTTPS with a bearer token. */\nexport function createWebRiskHttpClient(options: {\n accessToken: () => Promise<string | null>\n fetch?: typeof fetch\n timeoutMs?: number\n endpoint?: string\n}): WebRiskClient {\n const timeoutMs = options.timeoutMs ?? WEB_RISK_TIMEOUT_MS\n return {\n async searchUri(uri: string): Promise<WebRiskSearchResult> {\n const token = await options.accessToken()\n if (!token) throw new WebRiskUnavailableError('no service-account credential')\n const url = new URL(options.endpoint ?? WEB_RISK_SEARCH_ENDPOINT)\n for (const type of LINK_THREAT_TYPES) url.searchParams.append('threatTypes', type)\n url.searchParams.set('uri', uri)\n // A real deadline over the request AND its body: the signal alone did\n // not bound Next's patched fetch (AGL-3565). It still cancels the\n // request where it can.\n const answer = await boundedAwait(\n async (signal) => {\n const response = await (options.fetch ?? fetch)(url.toString(), {\n method: 'GET',\n headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },\n signal,\n })\n if (!response.ok) {\n throw new WebRiskHttpError(response.status, await response.text().catch(() => ''))\n }\n return parseWebRiskSearch(await response.json())\n },\n timeoutMs,\n null,\n 'web-risk.search',\n )\n if (!answer) throw new Error(`Web Risk did not answer within ${timeoutMs} ms`)\n return answer\n },\n }\n}\n\n/**\n * The platform service account's access token, or null when this deployment\n * has none — the same credential `client-error-report.ts` writes logs with.\n */\nasync function serviceAccountAccessToken(): Promise<string | null> {\n try {\n const credential = getApp().options.credential\n if (!credential) return null\n // A token exchange with Google, on a page render's path (AGL-3565).\n const token = await boundedAwait(\n credential.getAccessToken(),\n WEB_RISK_TOKEN_DEADLINE_MS,\n null,\n 'web-risk.access-token',\n )\n return token?.access_token ?? null\n } catch {\n return null\n }\n}\n\nlet defaultClient: WebRiskClient | null = null\nlet clientOverride: WebRiskClient | null | undefined\n\nfunction activeClient(): WebRiskClient | null {\n if (clientOverride !== undefined) return clientOverride\n defaultClient ??= createWebRiskHttpClient({ accessToken: serviceAccountAccessToken })\n return defaultClient\n}\n\ninterface Verdict {\n threats: LinkThreatType[]\n checkedAtMs: number\n /** When the answer stops being good, in the store. */\n expiresAtMs: number\n}\n\n/** Hosts and addresses share one memory: an address always holds `://`, a host never does. */\nconst memory = new Map<string, Verdict & { memoryUntilMs: number }>()\nlet settingsMemo: { off: boolean; mode: WebRiskLookupMode; atMs: number } | null = null\nlet backoffUntilMs = 0\nlet lastWarnAtMs = 0\n\n/** Test seam: forget the caches, the switches, the back-off; optionally stand in a client. */\nexport function resetWebRiskForTests(client?: WebRiskClient | null): void {\n memory.clear()\n settingsMemo = null\n backoffUntilMs = 0\n lastWarnAtMs = 0\n clientOverride = client\n defaultClient = null\n}\n\nfunction warn(nowMs: number, message: string, error?: unknown): void {\n if (nowMs - lastWarnAtMs < WARN_EVERY_MS) return\n lastWarnAtMs = nowMs\n console.warn(`[web-risk] ${message} — it reads unknown, which is not evidence`, error ?? '')\n}\n\n/**\n * The switches, read at most once a minute. An unreadable document is on,\n * in `'host'` mode; a mode that is not exactly `'url'` is `'host'`.\n */\nasync function webRiskSettings(nowMs: number): Promise<{ off: boolean; mode: WebRiskLookupMode }> {\n if (settingsMemo && nowMs - settingsMemo.atMs < SWITCH_TTL_MS) return settingsMemo\n const settings = await firebaseAdmin\n .app()\n .firestore()\n .collection(WEB_RISK_SETTINGS_COLLECTION)\n .doc(WEB_RISK_SETTINGS_DOC)\n .get()\n .then(\n (snapshot) => ({\n off: snapshot.get('enabled') === false,\n mode: snapshot.get('lookupMode') === 'url' ? ('url' as const) : ('host' as const),\n }),\n () => ({ off: false, mode: 'host' as const }),\n )\n settingsMemo = { ...settings, atMs: nowMs }\n return settings\n}\n\n/**\n * The lookup mode in force (AGL-3459): `'url'` only while the lookup is on\n * and `platformSettings/webRisk.lookupMode` is exactly `'url'`.\n */\nexport async function webRiskLookupMode(nowMs: number = Date.now()): Promise<WebRiskLookupMode> {\n const settings = await webRiskSettings(nowMs)\n return settings.off ? 'host' : settings.mode\n}\n\n/**\n * Hosts that are the platform's own: every site's subdomain on the tenant\n * apex. Never looked up — a neighbour's site is screened on its own page.\n */\nexport function platformReputationExclusions(): string[] {\n return [TENANT_APEX].filter(Boolean)\n}\n\nfunction isPlatformHost(host: string): boolean {\n return platformReputationExclusions().some(\n (domain) => host === domain || host.endsWith(`.${domain}`),\n )\n}\n\n/** An address's document id in {@link WEB_RISK_URL_CACHE_COLLECTION}: an address holds `/`, a hash does not. */\nexport function webRiskUrlVerdictId(url: string): string {\n return createHash('sha256').update(url).digest('hex')\n}\n\nfunction isAddress(key: string): boolean {\n return key.includes('://')\n}\n\n/** A stored answer, or null. An address's must name the address it was asked for. */\nfunction verdictFrom(data: Record<string, unknown> | undefined, url?: string): Verdict | null {\n if (!data) return null\n if (url !== undefined && data['url'] !== url) return null\n const threats = Array.isArray(data['threats'])\n ? LINK_THREAT_TYPES.filter((type) => (data['threats'] as unknown[]).includes(type))\n : []\n const checkedAtMs = Number(data['checkedAtMs'])\n const expiresAtMs = Number(data['expiresAtMs'])\n if (!Number.isFinite(checkedAtMs) || !Number.isFinite(expiresAtMs)) return null\n return { threats, checkedAtMs, expiresAtMs }\n}\n\nfunction remember(key: string, verdict: Verdict, nowMs: number): void {\n if (memory.size >= WEB_RISK_MEMORY_MAX_ENTRIES && !memory.has(key)) memory.clear()\n memory.set(key, {\n ...verdict,\n memoryUntilMs: verdict.threats.length\n ? verdict.expiresAtMs\n : Math.min(verdict.expiresAtMs, nowMs + WEB_RISK_MEMORY_CLEAN_TTL_MS),\n })\n}\n\nfunction fromMemory(key: string, nowMs: number): Verdict | null {\n const known = memory.get(key)\n return known && nowMs < known.memoryUntilMs ? known : null\n}\n\nexport interface HostReputationLookupOptions {\n /** How long the caller will wait, overall. */\n deadlineMs?: number\n /** The most hosts asked about; the rest read unknown. */\n maxHosts?: number\n /**\n * The links' addresses, looked up on the hosts asked about in `'url'`\n * mode (AGL-3459) and ignored in `'host'` mode. Normalized again here, so\n * a query string handed in is still never sent.\n */\n urls?: readonly string[]\n /** The most addresses asked about ({@link MAX_REPUTATION_URLS_PER_LOOKUP}); the rest are not asked about. */\n maxUrls?: number\n nowMs?: number\n}\n\n/** What a lookup answered, and how many calls it made to the API. */\nexport interface HostReputationLookupResult extends LinkReputationAnswer {\n looked: number\n}\n\n/**\n * The reputation of each host — and, in `'url'` mode, of each address on a\n * host that is not itself listed: listed, clean, or unknown. Platform hosts\n * are clean without asking. Never throws, and never waits on the API longer\n * than the deadline: a call still running then finishes in the background\n * and fills the caches for the next asker.\n *\n * \"Never throws\" covers the store as well as the API: a missing app, a\n * settings read that fails before it is a promise, or a cache reference\n * that cannot be built all read every host as unknown. The page review\n * calls this before its own fail-closed `try`, so a throw here would take\n * down every page with a link off the site.\n */\nexport async function lookupLinkReputation(\n hosts: readonly string[],\n options: HostReputationLookupOptions = {},\n): Promise<HostReputationLookupResult> {\n try {\n return await lookupLinkReputationOrThrow(hosts, options)\n } catch (error) {\n warn(options.nowMs ?? Date.now(), 'a lookup failed before it could answer', error)\n const unknown = [\n ...new Set(\n hosts\n .map((raw) => normalizeReputationHost(raw))\n .filter((host): host is string => Boolean(host)),\n ),\n ]\n return { hits: [], clean: [], unknown, looked: 0 }\n }\n}\n\nasync function lookupLinkReputationOrThrow(\n hosts: readonly string[],\n options: HostReputationLookupOptions,\n): Promise<HostReputationLookupResult> {\n const nowMs = options.nowMs ?? Date.now()\n const result: HostReputationLookupResult = { hits: [], clean: [], unknown: [], looked: 0 }\n const wanted: string[] = []\n for (const raw of hosts) {\n const host = normalizeReputationHost(raw)\n if (!host || wanted.includes(host) || result.clean.includes(host)) continue\n if (isPlatformHost(host)) result.clean.push(host)\n else if (wanted.length < (options.maxHosts ?? MAX_REPUTATION_HOSTS_PER_LOOKUP)) wanted.push(host)\n else result.unknown.push(host)\n }\n if (!wanted.length) return result\n let urls = options.urls?.length\n ? pickReputationUrls(options.urls, wanted, options.maxUrls ?? MAX_REPUTATION_URLS_PER_LOOKUP)\n : []\n const hostOf = new Map(urls.map((url) => [url, normalizeReputationLink(url)?.host ?? '']))\n\n // What is known before the API is asked, host or address.\n const known = new Map<string, Verdict>()\n const unknownTo = (keys: readonly string[]) =>\n keys.filter((key) => {\n const verdict = fromMemory(key, nowMs)\n if (verdict) known.set(key, verdict)\n return !verdict\n })\n\n // 1. This process's memory, for the hosts.\n let missingHosts = unknownTo(wanted)\n let missingUrls: string[] = []\n let mayAsk = true\n\n // 2. The switches — read only when a host is left to ask about, or\n // addresses wait on the mode. Off reads everything left as unknown.\n if (missingHosts.length || urls.length) {\n const settings = await webRiskSettings(nowMs)\n if (settings.off || settings.mode !== 'url') urls = []\n if (settings.off) mayAsk = false\n // An address on a host already known to be listed adds nothing.\n urls = urls.filter((url) => !known.get(hostOf.get(url) ?? '')?.threats.length)\n // 1b. This process's memory, for the addresses.\n missingUrls = unknownTo(urls)\n }\n\n // 3. The store, hosts and addresses in one round trip.\n const firestore = firebaseAdmin.app().firestore()\n const hostCollection = firestore.collection(WEB_RISK_CACHE_COLLECTION)\n const urlCollection = firestore.collection(WEB_RISK_URL_CACHE_COLLECTION)\n if (mayAsk && (missingHosts.length || missingUrls.length)) {\n const keys = [...missingHosts, ...missingUrls]\n try {\n const snapshots = await firestore.getAll(\n ...keys.map((key) =>\n isAddress(key) ? urlCollection.doc(webRiskUrlVerdictId(key)) : hostCollection.doc(key),\n ),\n )\n snapshots.forEach((snapshot, index) => {\n const key = keys[index]\n const data = snapshot.exists ? (snapshot.data() as Record<string, unknown>) : undefined\n const verdict = verdictFrom(data, isAddress(key) ? key : undefined)\n if (!verdict || nowMs >= verdict.expiresAtMs) return\n remember(key, verdict, nowMs)\n known.set(key, verdict)\n })\n missingHosts = missingHosts.filter((host) => !known.has(host))\n missingUrls = missingUrls.filter((url) => !known.has(url))\n } catch (error) {\n warn(nowMs, 'the verdict cache could not be read', error)\n }\n }\n\n // 4. The API, everything left at once, within the deadline: each host\n // first, then — unless the host itself is listed — its addresses.\n const answered = new Map<string, Verdict>()\n const client = activeClient()\n if (mayAsk && client && nowMs >= backoffUntilMs && (missingHosts.length || missingUrls.length)) {\n let looked = 0\n const ask = async (key: string): Promise<Verdict | null> => {\n if (Date.now() < backoffUntilMs) return null\n looked += 1\n try {\n const answer = await client.searchUri(isAddress(key) ? key : webRiskUriForHost(key))\n const checkedAtMs = Date.now()\n const verdict: Verdict = {\n threats: answer.threats,\n checkedAtMs,\n expiresAtMs: answer.threats.length\n ? (answer.expireTimeMs ?? checkedAtMs + WEB_RISK_LISTED_FALLBACK_TTL_MS)\n : checkedAtMs + WEB_RISK_CLEAN_TTL_MS,\n }\n answered.set(key, verdict)\n remember(key, verdict, checkedAtMs)\n const document = isAddress(key)\n ? urlCollection\n .doc(webRiskUrlVerdictId(key))\n .set({ host: hostOf.get(key) ?? '', url: key, ...verdict, listed: verdict.threats.length > 0 })\n : hostCollection.doc(key).set({ host: key, ...verdict, listed: verdict.threats.length > 0 })\n await document.catch((error: unknown) => warn(checkedAtMs, 'a verdict could not be cached', error))\n return verdict\n } catch (error) {\n if (error instanceof WebRiskHttpError && [401, 403, 404].includes(error.status)) {\n backoffUntilMs = Date.now() + REFUSED_BACKOFF_MS\n console.error('[web-risk] the API refused the credential — lookups paused for 15 minutes', error)\n } else if (error instanceof WebRiskHttpError && error.status === 429) {\n backoffUntilMs = Date.now() + THROTTLED_BACKOFF_MS\n warn(Date.now(), 'the API is rate limiting', error)\n } else if (error instanceof WebRiskUnavailableError) {\n backoffUntilMs = Date.now() + REFUSED_BACKOFF_MS\n warn(Date.now(), 'no credential to call the API with', error)\n } else {\n warn(Date.now(), `the lookup of ${key} failed or timed out`, error)\n }\n return null\n }\n }\n const pipelines = wanted.map(async (host) => {\n const hostVerdict = known.get(host) ?? (missingHosts.includes(host) ? await ask(host) : null)\n if (hostVerdict?.threats.length) return\n await Promise.all(missingUrls.filter((url) => hostOf.get(url) === host).map((url) => ask(url)))\n })\n await boundedAwait(\n Promise.allSettled(pipelines),\n options.deadlineMs ?? WEB_RISK_DEADLINE_MS,\n undefined,\n 'web-risk.lookup',\n )\n result.looked = looked\n const late = [...missingHosts, ...missingUrls].filter((key) => !answered.has(key)).length\n if (late) warn(Date.now(), `${late} host(s) or address(es) had no answer within the deadline`)\n }\n\n // 5. The answer. An address on a listed host is not reported: the host's\n // listing already names it.\n const verdictOf = (key: string) => known.get(key) ?? answered.get(key)\n for (const host of wanted) {\n const verdict = verdictOf(host)\n if (!verdict) result.unknown.push(host)\n else if (verdict.threats.length) result.hits.push({ host, threats: verdict.threats })\n else result.clean.push(host)\n }\n for (const url of urls) {\n const host = hostOf.get(url) ?? ''\n if (verdictOf(host)?.threats.length) continue\n const verdict = verdictOf(url)\n if (!verdict) result.unknown.push(url)\n else if (verdict.threats.length) result.hits.push({ host, url, threats: verdict.threats })\n else result.clean.push(url)\n }\n return result\n}\n\n/**\n * Delete the addresses' stored answers that expired more than\n * {@link WEB_RISK_URL_VERDICT_GRACE_MS} ago (AGL-3459), at most `limit` at a\n * time. The daily re-check calls it once per walk. A host's answers are not\n * reaped: they are few and rewritten in place. Never throws.\n */\nexport async function reapExpiredWebRiskUrlVerdicts(\n options: { nowMs?: number; limit?: number; firestore?: FirebaseFirestore.Firestore } = {},\n): Promise<number> {\n const nowMs = options.nowMs ?? Date.now()\n const firestore = options.firestore ?? firebaseAdmin.app().firestore()\n try {\n const stale = await firestore\n .collection(WEB_RISK_URL_CACHE_COLLECTION)\n .where('expiresAtMs', '<', nowMs - WEB_RISK_URL_VERDICT_GRACE_MS)\n .limit(options.limit ?? 500)\n .get()\n await Promise.all(stale.docs.map((snapshot) => snapshot.ref.delete()))\n return stale.docs.length\n } catch (error) {\n console.warn('[web-risk] expired address verdicts could not be deleted', error)\n return 0\n }\n}\n\n/**\n * Puts this lookup behind the shared screen's reputation seam, so the send\n * seam (`screenTenantMessage`) asks it. Called by\n * `installOutboundScreenGate`, at that module's load.\n */\nexport function installLinkReputationLookup(): void {\n if (typeof setLinkReputationLookup !== 'function') return\n setLinkReputationLookup((hosts, options) =>\n lookupLinkReputation(hosts, { deadlineMs: options?.deadlineMs, urls: options?.urls }),\n )\n}\n"],"names":["createHash","TENANT_APEX","LINK_THREAT_TYPES","MAX_REPUTATION_HOSTS_PER_LOOKUP","MAX_REPUTATION_URLS_PER_LOOKUP","normalizeReputationHost","normalizeReputationLink","pickReputationUrls","setLinkReputationLookup","boundedAwait","getApp","firebaseAdmin","WEB_RISK_SEARCH_ENDPOINT","WEB_RISK_CACHE_COLLECTION","WEB_RISK_URL_CACHE_COLLECTION","WEB_RISK_SETTINGS_COLLECTION","WEB_RISK_SETTINGS_DOC","WEB_RISK_TIMEOUT_MS","WEB_RISK_DEADLINE_MS","WEB_RISK_TOKEN_DEADLINE_MS","WEB_RISK_CLEAN_TTL_MS","WEB_RISK_MEMORY_CLEAN_TTL_MS","WEB_RISK_LISTED_FALLBACK_TTL_MS","WEB_RISK_MEMORY_MAX_ENTRIES","WEB_RISK_URL_VERDICT_GRACE_MS","SWITCH_TTL_MS","REFUSED_BACKOFF_MS","THROTTLED_BACKOFF_MS","WARN_EVERY_MS","WebRiskHttpError","Error","status","detail","slice","name","WebRiskUnavailableError","reason","parseWebRiskSearch","body","threat","threats","expireTimeMs","listed","Array","isArray","threatTypes","filter","type","includes","expireTime","Date","parse","Number","NaN","isFinite","webRiskUriForHost","host","createWebRiskHttpClient","options","timeoutMs","searchUri","uri","token","accessToken","url","URL","endpoint","searchParams","append","set","answer","signal","response","fetch","toString","method","headers","Authorization","Accept","ok","text","catch","json","serviceAccountAccessToken","credential","getAccessToken","access_token","defaultClient","clientOverride","activeClient","undefined","memory","Map","settingsMemo","backoffUntilMs","lastWarnAtMs","resetWebRiskForTests","client","clear","warn","nowMs","message","error","console","webRiskSettings","atMs","settings","app","firestore","collection","doc","get","then","snapshot","off","mode","webRiskLookupMode","now","platformReputationExclusions","Boolean","isPlatformHost","some","domain","endsWith","webRiskUrlVerdictId","update","digest","isAddress","key","verdictFrom","data","checkedAtMs","expiresAtMs","remember","verdict","size","has","memoryUntilMs","length","Math","min","fromMemory","known","lookupLinkReputation","hosts","lookupLinkReputationOrThrow","unknown","Set","map","raw","hits","clean","looked","result","wanted","push","maxHosts","urls","maxUrls","hostOf","unknownTo","keys","missingHosts","missingUrls","mayAsk","hostCollection","urlCollection","snapshots","getAll","forEach","index","exists","answered","ask","document","pipelines","hostVerdict","Promise","all","allSettled","deadlineMs","late","verdictOf","reapExpiredWebRiskUrlVerdicts","stale","where","limit","docs","ref","delete","installLinkReputationLookup"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAqE2C,GAE3C,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,WAAW,QAAQ,qCAAoC;AAChE,SACEC,iBAAiB,EAGjBC,+BAA+B,EAC/BC,8BAA8B,EAC9BC,uBAAuB,EACvBC,uBAAuB,EACvBC,kBAAkB,EAClBC,uBAAuB,QAClB,2CAA0C;AACjD,SAASC,YAAY,QAAQ,wCAAuC;AACpE,SAASC,MAAM,QAAQ,qBAAoB;AAC3C,OAAOC,mBAAmB,sBAAkB;AAE5C,OAAO,MAAMC,2BAA2B,gDAA+C;AACvF,yBAAyB,GACzB,OAAO,MAAMC,4BAA4B,kBAAiB;AAC1D,wFAAwF,GACxF,OAAO,MAAMC,gCAAgC,qBAAoB;AACjE;;;CAGC,GACD,OAAO,MAAMC,+BAA+B,m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
52
52
|
export * from './lib/server/edit-access-token';
|
|
53
53
|
export * from './lib/server/edit-hint-token';
|
|
54
54
|
export * from './lib/server/email-metering';
|
|
55
|
-
export * from './lib/server/campaign-conversion-attribution';
|
|
56
55
|
export * from './lib/server/email-send-rate';
|
|
57
56
|
export * from './lib/server/email-deliverability';
|
|
58
57
|
export * from './lib/server/email-sender-reputation';
|
|
@@ -77,6 +76,8 @@ export * from './lib/server/operator-alerts';
|
|
|
77
76
|
export * from './lib/server/operator-health';
|
|
78
77
|
export * from './lib/server/org-billing';
|
|
79
78
|
export * from './lib/server/organizations';
|
|
79
|
+
export * from './lib/server/staff-seat';
|
|
80
|
+
export * from './lib/server/upgrade-proposal';
|
|
80
81
|
export * from './lib/server/duplicate-activity';
|
|
81
82
|
export * from './lib/server/duplicate-resource';
|
|
82
83
|
export * from './lib/server/workspace-domains';
|
|
@@ -102,6 +103,7 @@ export * from './lib/server/media-storage-path';
|
|
|
102
103
|
export * from './lib/server/safe-equal';
|
|
103
104
|
export * from './lib/server/media-strong-digest';
|
|
104
105
|
export * from './lib/server/media-tombstone';
|
|
106
|
+
export * from './lib/server/media-delivery-regeneration';
|
|
105
107
|
export * from './lib/server/media-variants';
|
|
106
108
|
export * from './lib/server/serve-media-cdn';
|
|
107
109
|
export * from './lib/server/serve-plugin-fetch';
|
|
@@ -115,8 +117,6 @@ export * from './lib/server/contact-company-link';
|
|
|
115
117
|
export * from './lib/server/contact-email-index';
|
|
116
118
|
export * from './lib/server/upsert-contact';
|
|
117
119
|
export * from './lib/server/crm-records';
|
|
118
|
-
export * from './lib/server/crm-next-activity';
|
|
119
|
-
export * from './lib/server/crm-email-activity';
|
|
120
120
|
export * from './lib/server/member-email-aliases';
|
|
121
121
|
export * from './lib/server/user-profiles';
|
|
122
122
|
export * from './lib/server/new-account-announcement';
|
package/src/tenancy.js
CHANGED
|
@@ -71,7 +71,6 @@ export * from "./lib/server/email-metering.js";
|
|
|
71
71
|
// Side-effecting on purpose (AGL-2409): evaluating this module INSTALLS the
|
|
72
72
|
// platform send-rate governor on `sendEmail`. Every server surface already
|
|
73
73
|
// imports this barrel, so nothing has to remember to call an installer.
|
|
74
|
-
export * from "./lib/server/campaign-conversion-attribution.js";
|
|
75
74
|
export * from "./lib/server/email-send-rate.js";
|
|
76
75
|
// Side-effecting on purpose, for the same reason (AGL-3328): evaluating this
|
|
77
76
|
// module INSTALLS the deliverability preflight on `sendEmail`, so a recipient
|
|
@@ -104,6 +103,10 @@ export * from "./lib/server/operator-alerts.js";
|
|
|
104
103
|
export * from "./lib/server/operator-health.js";
|
|
105
104
|
export * from "./lib/server/org-billing.js";
|
|
106
105
|
export * from "./lib/server/organizations.js";
|
|
106
|
+
// Platform staff take no customer seat, and a workspace is asked to upgrade
|
|
107
|
+
// as a separate step after it is handed over (AGL-3466).
|
|
108
|
+
export * from "./lib/server/staff-seat.js";
|
|
109
|
+
export * from "./lib/server/upgrade-proposal.js";
|
|
107
110
|
export * from "./lib/server/duplicate-activity.js";
|
|
108
111
|
export * from "./lib/server/duplicate-resource.js";
|
|
109
112
|
export * from "./lib/server/workspace-domains.js";
|
|
@@ -129,6 +132,7 @@ export * from "./lib/server/media-storage-path.js";
|
|
|
129
132
|
export * from "./lib/server/safe-equal.js";
|
|
130
133
|
export * from "./lib/server/media-strong-digest.js";
|
|
131
134
|
export * from "./lib/server/media-tombstone.js";
|
|
135
|
+
export * from "./lib/server/media-delivery-regeneration.js";
|
|
132
136
|
export * from "./lib/server/media-variants.js";
|
|
133
137
|
export * from "./lib/server/serve-media-cdn.js";
|
|
134
138
|
export * from "./lib/server/serve-plugin-fetch.js";
|
|
@@ -144,10 +148,8 @@ export * from "./lib/server/upsert-contact.js";
|
|
|
144
148
|
export * from "./lib/server/crm-records.js";
|
|
145
149
|
// The `nextTaskAtMs` a contact, a company and a deal carry, recomputed from
|
|
146
150
|
// their open tasks by every server-side task writer (AGL-2661).
|
|
147
|
-
export * from "./lib/server/crm-next-activity.js";
|
|
148
151
|
// Where a one-to-one email's activity row lives and how the delivery
|
|
149
152
|
// webhook advances it (AGL-2615).
|
|
150
|
-
export * from "./lib/server/crm-email-activity.js";
|
|
151
153
|
// A member's own addresses in a workspace, and the signed link that
|
|
152
154
|
// confirms one (AGL-2975).
|
|
153
155
|
export * from "./lib/server/member-email-aliases.js";
|
package/src/tenancy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/tenant/data/admin/src/tenancy.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 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\nexport * from './lib/server/analytics-retention'\nexport * from './lib/server/api-http'\nexport * from './lib/server/api-keys'\nexport * from './lib/server/account-emails'\nexport * from './lib/server/auth-pools'\nexport * from './lib/server/client-error-report'\n// The merchant's payment account, as a contract. Its adapter is not exported:\n// a plugin asks the contract, and the doors that only need the readiness rule\n// import `@aglyn/tenant-data-admin/server/payment-provider` directly, which\n// loads no Firebase.\nexport {\n merchantAccountIsReady,\n merchantAccountReadiness,\n paymentProvider,\n} from './lib/server/payment-provider'\nexport type {\n MerchantAccountReadiness,\n MerchantAccountReadinessInput,\n PaymentMode,\n PaymentProvider,\n PaymentProviderEvent,\n} from './lib/server/payment-provider'\nexport * from './lib/server/auth-handoff'\nexport * from './lib/server/console-domains'\nexport * from './lib/server/dns-probe'\nexport * from './lib/server/sending-domains'\nexport * from './lib/server/sender-readiness'\nexport * from './lib/server/host-sending-domain'\nexport * from './lib/server/sending-domain-debt'\nexport * from './lib/server/sending-domain-recheck'\n// The hosting seam itself, so a door can ask whether this deployment is able\n// to register a name at all before it promises the caller one.\n// `workspace-domains` re-exports the pieces its own callers share with it; the\n// provider behind it is not among them.\nexport { domainProvider } from './lib/server/domain-provider'\nexport type {\n DomainProvider,\n DomainProviderId,\n DomainScope,\n} from './lib/server/domain-provider'\nexport * from './lib/server/platform-domain-names'\nexport * from './lib/server/consume-once'\nexport * from './lib/server/csp-aggregate'\nexport * from './lib/server/data-storage-gate'\nexport * from './lib/server/contact-suppression'\nexport * from './lib/server/email-suppression'\n// The double opt-in quarantine, after the module whose keying it shares and\n// whose `filterTopicSendable` is the reader that makes it a quarantine rather\n// than a stored fact.\nexport * from './lib/server/topic-subscriptions'\nexport * from './lib/server/email-unsubscribe-link'\nexport * from './lib/server/email-flow-gate'\n// Side-effecting on purpose, for the reason `email-send-rate` below is:\n// evaluating this module INSTALLS the marketing gate on `sendEmail`, so the\n// unsubscribe header, the suppression check and the frequency ceiling reach\n// every bulk sender without a call at each server entrypoint.\nexport * from './lib/server/email-marketing-gate'\n// A consent group change (AGL-3320): the carries of the three stores above,\n// and the executor that runs a change around them.\nexport * from './lib/server/consent-group-carry'\nexport * from './lib/server/consent-group-change'\n// A person's refusal kept after the record it was written on is deleted\n// (AGL-3338): the delete's write, the list gate's read, and the change's carry.\nexport * from './lib/server/retained-refusals'\nexport * from './lib/server/sms-keywords'\nexport * from './lib/server/document-id'\nexport * from './lib/server/collection-preview-token'\nexport * from './lib/server/edit-access-authz'\nexport * from './lib/server/edit-access-token'\nexport * from './lib/server/edit-hint-token'\nexport * from './lib/server/email-metering'\n// Side-effecting on purpose (AGL-2409): evaluating this module INSTALLS the\n// platform send-rate governor on `sendEmail`. Every server surface already\n// imports this barrel, so nothing has to remember to call an installer.\nexport * from './lib/server/campaign-conversion-attribution'\nexport * from './lib/server/email-send-rate'\n// Side-effecting on purpose, for the same reason (AGL-3328): evaluating this\n// module INSTALLS the deliverability preflight on `sendEmail`, so a recipient\n// whose domain takes no mail is refused, and bulk mail behind a gateway that\n// refused its sending domain twice is held, on every send path at once.\nexport * from './lib/server/email-deliverability'\nexport * from './lib/server/email-sender-reputation'\nexport * from './lib/server/erase'\nexport * from './lib/server/erase-person'\nexport * from './lib/server/dynamic-list-materialize'\nexport * from './lib/server/firebase-admin'\nexport * from './lib/server/free-workspace-cap'\nexport * from './lib/server/ga4-measurement-protocol'\nexport * from './lib/server/host-memberships'\nexport * from './lib/server/host-visitor-records'\nexport * from './lib/server/list-members'\nexport * from './lib/server/lockdown'\nexport * from './lib/server/token-revocation'\nexport * from './lib/server/tenant-write-lockdown'\nexport * from './lib/server/outbound-send-review'\n// The same review for a published page, read where it is composed (AGL-3356).\nexport * from './lib/server/hosted-page-review'\n// Every hold, flag, lock and pause tells owners and staff through one seam (AGL-3368).\nexport * from './lib/server/risk-notice'\nexport * from './lib/server/host-email-tokens'\nexport * from './lib/server/notifications'\n// Every operator alert raises through one entry point, and every health check\n// remembers its state (AGL-3377).\nexport * from './lib/server/operator-alerts'\nexport * from './lib/server/operator-health'\nexport * from './lib/server/org-billing'\nexport * from './lib/server/organizations'\nexport * from './lib/server/duplicate-activity'\nexport * from './lib/server/duplicate-resource'\nexport * from './lib/server/workspace-domains'\nexport * from './lib/server/membership-recover-throttle'\nexport * from './lib/server/password-reset-throttle'\nexport * from './lib/server/rate-limit-store'\nexport * from './lib/server/verify-email-cooldown'\nexport * from './lib/server/vercel-drain-signature'\nexport * from './lib/server/vercel-log-drain'\nexport * from './lib/server/visitor-write-rate-limit'\nexport * from './lib/server/card-payment-velocity'\nexport * from './lib/server/console-api-rate-limit'\nexport * from './lib/server/realm-plugins'\nexport * from './lib/server/release-flags'\nexport * from './lib/server/resolve-people'\nexport * from './lib/server/member-photo'\nexport * from './lib/server/personal-data-export'\nexport * from './lib/server/media-delivery'\nexport * from './lib/server/media-download-tokens'\nexport * from './lib/server/media-quarantine'\nexport * from './lib/server/media-signing'\nexport * from './lib/server/media-storage-path'\nexport * from './lib/server/safe-equal'\nexport * from './lib/server/media-strong-digest'\nexport * from './lib/server/media-tombstone'\nexport * from './lib/server/media-variants'\nexport * from './lib/server/serve-media-cdn'\nexport * from './lib/server/serve-plugin-fetch'\nexport * from './lib/server/configured-url-fetch'\nexport * from './lib/server/sso-break-glass-owners'\nexport * from './lib/server/sso-domain-policy'\nexport * from './lib/server/sso-enforcement'\nexport * from './lib/server/sso-provisioning'\nexport * from './lib/server/update-existing'\nexport * from './lib/server/contact-company-link'\nexport * from './lib/server/contact-email-index'\nexport * from './lib/server/upsert-contact'\nexport * from './lib/server/crm-records'\n// The `nextTaskAtMs` a contact, a company and a deal carry, recomputed from\n// their open tasks by every server-side task writer (AGL-2661).\nexport * from './lib/server/crm-next-activity'\n// Where a one-to-one email's activity row lives and how the delivery\n// webhook advances it (AGL-2615).\nexport * from './lib/server/crm-email-activity'\n// A member's own addresses in a workspace, and the signed link that\n// confirms one (AGL-2975).\nexport * from './lib/server/member-email-aliases'\nexport * from './lib/server/user-profiles'\n// The one \"New account\" staff notice per account, keyed on the auth\n// record's creation (AGL-3225).\nexport * from './lib/server/new-account-announcement'\nexport * from './lib/server/legal-acceptance'\n// The person's decision about the platform's own product email, on their\n// document and on the operator's marketing contact (AGL-3185).\nexport * from './lib/server/platform-marketing-consent'\n"],"names":["merchantAccountIsReady","merchantAccountReadiness","paymentProvider","domainProvider"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,cAAc,sCAAkC;AAChD,cAAc,2BAAuB;AACrC,cAAc,2BAAuB;AACrC,cAAc,iCAA6B;AAC3C,cAAc,6BAAyB;AACvC,cAAc,sCAAkC;AAChD,8EAA8E;AAC9E,8EAA8E;AAC9E,4EAA4E;AAC5E,qBAAqB;AACrB,SACEA,sBAAsB,EACtBC,wBAAwB,EACxBC,eAAe,QACV,mCAA+B;AAQtC,cAAc,+BAA2B;AACzC,cAAc,kCAA8B;AAC5C,cAAc,4BAAwB;AACtC,cAAc,kCAA8B;AAC5C,cAAc,mCAA+B;AAC7C,cAAc,sCAAkC;AAChD,cAAc,sCAAkC;AAChD,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D;AAC/D,cAAc,6CAAyC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/tenant/data/admin/src/tenancy.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 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\nexport * from './lib/server/analytics-retention'\nexport * from './lib/server/api-http'\nexport * from './lib/server/api-keys'\nexport * from './lib/server/account-emails'\nexport * from './lib/server/auth-pools'\nexport * from './lib/server/client-error-report'\n// The merchant's payment account, as a contract. Its adapter is not exported:\n// a plugin asks the contract, and the doors that only need the readiness rule\n// import `@aglyn/tenant-data-admin/server/payment-provider` directly, which\n// loads no Firebase.\nexport {\n merchantAccountIsReady,\n merchantAccountReadiness,\n paymentProvider,\n} from './lib/server/payment-provider'\nexport type {\n MerchantAccountReadiness,\n MerchantAccountReadinessInput,\n PaymentMode,\n PaymentProvider,\n PaymentProviderEvent,\n} from './lib/server/payment-provider'\nexport * from './lib/server/auth-handoff'\nexport * from './lib/server/console-domains'\nexport * from './lib/server/dns-probe'\nexport * from './lib/server/sending-domains'\nexport * from './lib/server/sender-readiness'\nexport * from './lib/server/host-sending-domain'\nexport * from './lib/server/sending-domain-debt'\nexport * from './lib/server/sending-domain-recheck'\n// The hosting seam itself, so a door can ask whether this deployment is able\n// to register a name at all before it promises the caller one.\n// `workspace-domains` re-exports the pieces its own callers share with it; the\n// provider behind it is not among them.\nexport { domainProvider } from './lib/server/domain-provider'\nexport type {\n DomainProvider,\n DomainProviderId,\n DomainScope,\n} from './lib/server/domain-provider'\nexport * from './lib/server/platform-domain-names'\nexport * from './lib/server/consume-once'\nexport * from './lib/server/csp-aggregate'\nexport * from './lib/server/data-storage-gate'\nexport * from './lib/server/contact-suppression'\nexport * from './lib/server/email-suppression'\n// The double opt-in quarantine, after the module whose keying it shares and\n// whose `filterTopicSendable` is the reader that makes it a quarantine rather\n// than a stored fact.\nexport * from './lib/server/topic-subscriptions'\nexport * from './lib/server/email-unsubscribe-link'\nexport * from './lib/server/email-flow-gate'\n// Side-effecting on purpose, for the reason `email-send-rate` below is:\n// evaluating this module INSTALLS the marketing gate on `sendEmail`, so the\n// unsubscribe header, the suppression check and the frequency ceiling reach\n// every bulk sender without a call at each server entrypoint.\nexport * from './lib/server/email-marketing-gate'\n// A consent group change (AGL-3320): the carries of the three stores above,\n// and the executor that runs a change around them.\nexport * from './lib/server/consent-group-carry'\nexport * from './lib/server/consent-group-change'\n// A person's refusal kept after the record it was written on is deleted\n// (AGL-3338): the delete's write, the list gate's read, and the change's carry.\nexport * from './lib/server/retained-refusals'\nexport * from './lib/server/sms-keywords'\nexport * from './lib/server/document-id'\nexport * from './lib/server/collection-preview-token'\nexport * from './lib/server/edit-access-authz'\nexport * from './lib/server/edit-access-token'\nexport * from './lib/server/edit-hint-token'\nexport * from './lib/server/email-metering'\n// Side-effecting on purpose (AGL-2409): evaluating this module INSTALLS the\n// platform send-rate governor on `sendEmail`. Every server surface already\n// imports this barrel, so nothing has to remember to call an installer.\nexport * from './lib/server/email-send-rate'\n// Side-effecting on purpose, for the same reason (AGL-3328): evaluating this\n// module INSTALLS the deliverability preflight on `sendEmail`, so a recipient\n// whose domain takes no mail is refused, and bulk mail behind a gateway that\n// refused its sending domain twice is held, on every send path at once.\nexport * from './lib/server/email-deliverability'\nexport * from './lib/server/email-sender-reputation'\nexport * from './lib/server/erase'\nexport * from './lib/server/erase-person'\nexport * from './lib/server/dynamic-list-materialize'\nexport * from './lib/server/firebase-admin'\nexport * from './lib/server/free-workspace-cap'\nexport * from './lib/server/ga4-measurement-protocol'\nexport * from './lib/server/host-memberships'\nexport * from './lib/server/host-visitor-records'\nexport * from './lib/server/list-members'\nexport * from './lib/server/lockdown'\nexport * from './lib/server/token-revocation'\nexport * from './lib/server/tenant-write-lockdown'\nexport * from './lib/server/outbound-send-review'\n// The same review for a published page, read where it is composed (AGL-3356).\nexport * from './lib/server/hosted-page-review'\n// Every hold, flag, lock and pause tells owners and staff through one seam (AGL-3368).\nexport * from './lib/server/risk-notice'\nexport * from './lib/server/host-email-tokens'\nexport * from './lib/server/notifications'\n// Every operator alert raises through one entry point, and every health check\n// remembers its state (AGL-3377).\nexport * from './lib/server/operator-alerts'\nexport * from './lib/server/operator-health'\nexport * from './lib/server/org-billing'\nexport * from './lib/server/organizations'\n// Platform staff take no customer seat, and a workspace is asked to upgrade\n// as a separate step after it is handed over (AGL-3466).\nexport * from './lib/server/staff-seat'\nexport * from './lib/server/upgrade-proposal'\nexport * from './lib/server/duplicate-activity'\nexport * from './lib/server/duplicate-resource'\nexport * from './lib/server/workspace-domains'\nexport * from './lib/server/membership-recover-throttle'\nexport * from './lib/server/password-reset-throttle'\nexport * from './lib/server/rate-limit-store'\nexport * from './lib/server/verify-email-cooldown'\nexport * from './lib/server/vercel-drain-signature'\nexport * from './lib/server/vercel-log-drain'\nexport * from './lib/server/visitor-write-rate-limit'\nexport * from './lib/server/card-payment-velocity'\nexport * from './lib/server/console-api-rate-limit'\nexport * from './lib/server/realm-plugins'\nexport * from './lib/server/release-flags'\nexport * from './lib/server/resolve-people'\nexport * from './lib/server/member-photo'\nexport * from './lib/server/personal-data-export'\nexport * from './lib/server/media-delivery'\nexport * from './lib/server/media-download-tokens'\nexport * from './lib/server/media-quarantine'\nexport * from './lib/server/media-signing'\nexport * from './lib/server/media-storage-path'\nexport * from './lib/server/safe-equal'\nexport * from './lib/server/media-strong-digest'\nexport * from './lib/server/media-tombstone'\nexport * from './lib/server/media-delivery-regeneration'\nexport * from './lib/server/media-variants'\nexport * from './lib/server/serve-media-cdn'\nexport * from './lib/server/serve-plugin-fetch'\nexport * from './lib/server/configured-url-fetch'\nexport * from './lib/server/sso-break-glass-owners'\nexport * from './lib/server/sso-domain-policy'\nexport * from './lib/server/sso-enforcement'\nexport * from './lib/server/sso-provisioning'\nexport * from './lib/server/update-existing'\nexport * from './lib/server/contact-company-link'\nexport * from './lib/server/contact-email-index'\nexport * from './lib/server/upsert-contact'\nexport * from './lib/server/crm-records'\n// The `nextTaskAtMs` a contact, a company and a deal carry, recomputed from\n// their open tasks by every server-side task writer (AGL-2661).\n// Where a one-to-one email's activity row lives and how the delivery\n// webhook advances it (AGL-2615).\n// A member's own addresses in a workspace, and the signed link that\n// confirms one (AGL-2975).\nexport * from './lib/server/member-email-aliases'\nexport * from './lib/server/user-profiles'\n// The one \"New account\" staff notice per account, keyed on the auth\n// record's creation (AGL-3225).\nexport * from './lib/server/new-account-announcement'\nexport * from './lib/server/legal-acceptance'\n// The person's decision about the platform's own product email, on their\n// document and on the operator's marketing contact (AGL-3185).\nexport * from './lib/server/platform-marketing-consent'\n"],"names":["merchantAccountIsReady","merchantAccountReadiness","paymentProvider","domainProvider"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,cAAc,sCAAkC;AAChD,cAAc,2BAAuB;AACrC,cAAc,2BAAuB;AACrC,cAAc,iCAA6B;AAC3C,cAAc,6BAAyB;AACvC,cAAc,sCAAkC;AAChD,8EAA8E;AAC9E,8EAA8E;AAC9E,4EAA4E;AAC5E,qBAAqB;AACrB,SACEA,sBAAsB,EACtBC,wBAAwB,EACxBC,eAAe,QACV,mCAA+B;AAQtC,cAAc,+BAA2B;AACzC,cAAc,kCAA8B;AAC5C,cAAc,4BAAwB;AACtC,cAAc,kCAA8B;AAC5C,cAAc,mCAA+B;AAC7C,cAAc,sCAAkC;AAChD,cAAc,sCAAkC;AAChD,cAAc,yCAAqC;AACnD,6EAA6E;AAC7E,+DAA+D;AAC/D,+EAA+E;AAC/E,wCAAwC;AACxC,SAASC,cAAc,QAAQ,kCAA8B;AAM7D,cAAc,wCAAoC;AAClD,cAAc,+BAA2B;A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
|
-
*
|
|
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
|
-
/** The per-host collection of conversion attribution records. */
|
|
18
|
-
export declare const CAMPAIGN_ATTRIBUTIONS_COLLECTION = "campaignAttributions";
|
|
19
|
-
/**
|
|
20
|
-
* Removes every conversion attributed to one person, across every site.
|
|
21
|
-
*
|
|
22
|
-
* ## Why an erasure reaches these at all
|
|
23
|
-
*
|
|
24
|
-
* An attribution is a claim about a person: "this human came from that
|
|
25
|
-
* campaign and then did this". It is the same personal fact as the click
|
|
26
|
-
* stamp it was derived from, and the erasure path already deletes those —
|
|
27
|
-
* `eraseEmailDeliveriesForAddresses` drops `campaignTouches` alongside the
|
|
28
|
-
* engagement stamps and says why. A summary that outlived its source would
|
|
29
|
-
* leave an erasure that removed the evidence and kept the conclusion.
|
|
30
|
-
*
|
|
31
|
-
* ## Why a collection-group query
|
|
32
|
-
*
|
|
33
|
-
* The record is per HOST, because that is where a site's own reporting reads
|
|
34
|
-
* it. An erasure arrives as an ADDRESS and knows nothing about which sites
|
|
35
|
-
* that person ever visited. The collection group is the join between the two,
|
|
36
|
-
* and `personKey` is on the record precisely so one exists — declared in
|
|
37
|
-
* `cloud/firebase-firestore.indexes.json` with `COLLECTION_GROUP` scope,
|
|
38
|
-
* because a collection-group query gets no automatic single-field index and
|
|
39
|
-
* would otherwise fail with FAILED_PRECONDITION at the moment somebody asked
|
|
40
|
-
* to be forgotten.
|
|
41
|
-
*
|
|
42
|
-
* ## The order's own record is NOT touched
|
|
43
|
-
*
|
|
44
|
-
* `emailAttributions` holds a commercial fact about a sale, keyed by the
|
|
45
|
-
* order's id and carrying no address — the revenue join says so where it
|
|
46
|
-
* writes it. This holds a record of a person's behavior under a key derived
|
|
47
|
-
* from their address. Different facts, different answers, and the split is
|
|
48
|
-
* why both are defensible.
|
|
49
|
-
*
|
|
50
|
-
* Never throws: an erasure that fails on one leg must still complete the
|
|
51
|
-
* others, and the caller reports what it removed.
|
|
52
|
-
*
|
|
53
|
-
* @returns how many records were removed.
|
|
54
|
-
*/
|
|
55
|
-
export declare function eraseCampaignAttributionsForPersonKey(key: string | null | undefined, firestore?: any): Promise<number>;
|
|
@@ -1,95 +0,0 @@
|
|
|
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
|
-
* Where conversion attributions are kept, and how an erasure reaches them.
|
|
18
|
-
*
|
|
19
|
-
* ## Why this is a leaf module and not part of the join
|
|
20
|
-
*
|
|
21
|
-
* The erasure runs from `email-delivery-log.ts`, in the same function that
|
|
22
|
-
* drops a person's campaign touches — which is the point, because an
|
|
23
|
-
* attribution is a conclusion drawn from those touches and a conclusion that
|
|
24
|
-
* outlives its evidence is an erasure that did not happen. But the join
|
|
25
|
-
* itself READS that module (`readEmailCampaignTouch` is one half of the
|
|
26
|
-
* last-touch comparison), so putting the erasure beside the join would make
|
|
27
|
-
* the two modules import each other. Under jest that cycle resolves to
|
|
28
|
-
* `undefined` at import time rather than failing loudly, which is how an
|
|
29
|
-
* erasure comes to silently do nothing while its test passes.
|
|
30
|
-
*
|
|
31
|
-
* So the collection name and the sweep live here, importing nothing but
|
|
32
|
-
* Firestore, and both sides import this.
|
|
33
|
-
*/ import firebaseAdmin from "./firebase-admin.js";
|
|
34
|
-
const defaultFirestore = ()=>firebaseAdmin.app().firestore();
|
|
35
|
-
/** The per-host collection of conversion attribution records. */ export const CAMPAIGN_ATTRIBUTIONS_COLLECTION = 'campaignAttributions';
|
|
36
|
-
/** How many records one erasure pass removes per batch. */ const ERASURE_BATCH = 400;
|
|
37
|
-
/**
|
|
38
|
-
* Removes every conversion attributed to one person, across every site.
|
|
39
|
-
*
|
|
40
|
-
* ## Why an erasure reaches these at all
|
|
41
|
-
*
|
|
42
|
-
* An attribution is a claim about a person: "this human came from that
|
|
43
|
-
* campaign and then did this". It is the same personal fact as the click
|
|
44
|
-
* stamp it was derived from, and the erasure path already deletes those —
|
|
45
|
-
* `eraseEmailDeliveriesForAddresses` drops `campaignTouches` alongside the
|
|
46
|
-
* engagement stamps and says why. A summary that outlived its source would
|
|
47
|
-
* leave an erasure that removed the evidence and kept the conclusion.
|
|
48
|
-
*
|
|
49
|
-
* ## Why a collection-group query
|
|
50
|
-
*
|
|
51
|
-
* The record is per HOST, because that is where a site's own reporting reads
|
|
52
|
-
* it. An erasure arrives as an ADDRESS and knows nothing about which sites
|
|
53
|
-
* that person ever visited. The collection group is the join between the two,
|
|
54
|
-
* and `personKey` is on the record precisely so one exists — declared in
|
|
55
|
-
* `cloud/firebase-firestore.indexes.json` with `COLLECTION_GROUP` scope,
|
|
56
|
-
* because a collection-group query gets no automatic single-field index and
|
|
57
|
-
* would otherwise fail with FAILED_PRECONDITION at the moment somebody asked
|
|
58
|
-
* to be forgotten.
|
|
59
|
-
*
|
|
60
|
-
* ## The order's own record is NOT touched
|
|
61
|
-
*
|
|
62
|
-
* `emailAttributions` holds a commercial fact about a sale, keyed by the
|
|
63
|
-
* order's id and carrying no address — the revenue join says so where it
|
|
64
|
-
* writes it. This holds a record of a person's behavior under a key derived
|
|
65
|
-
* from their address. Different facts, different answers, and the split is
|
|
66
|
-
* why both are defensible.
|
|
67
|
-
*
|
|
68
|
-
* Never throws: an erasure that fails on one leg must still complete the
|
|
69
|
-
* others, and the caller reports what it removed.
|
|
70
|
-
*
|
|
71
|
-
* @returns how many records were removed.
|
|
72
|
-
*/ export async function eraseCampaignAttributionsForPersonKey(key, firestore) {
|
|
73
|
-
if (!key || typeof key !== 'string') return 0;
|
|
74
|
-
const db = firestore != null ? firestore : defaultFirestore();
|
|
75
|
-
let removed = 0;
|
|
76
|
-
try {
|
|
77
|
-
// Bounded rather than `while (true)`: a pathological volume must not be
|
|
78
|
-
// able to hold an erasure request open indefinitely, and the pass that
|
|
79
|
-
// runs next picks up whatever a bounded one left.
|
|
80
|
-
for(let pass = 0; pass < 20; pass += 1){
|
|
81
|
-
const snapshot = await db.collectionGroup(CAMPAIGN_ATTRIBUTIONS_COLLECTION).where('personKey', '==', key).limit(ERASURE_BATCH).get();
|
|
82
|
-
if (snapshot.empty) break;
|
|
83
|
-
const batch = db.batch();
|
|
84
|
-
snapshot.docs.forEach((doc)=>batch.delete(doc.ref));
|
|
85
|
-
await batch.commit();
|
|
86
|
-
removed += snapshot.size;
|
|
87
|
-
if (snapshot.size < ERASURE_BATCH) break;
|
|
88
|
-
}
|
|
89
|
-
} catch (error) {
|
|
90
|
-
console.error('eraseCampaignAttributionsForPersonKey failed', error);
|
|
91
|
-
}
|
|
92
|
-
return removed;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
//# sourceMappingURL=campaign-attribution-store.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/campaign-attribution-store.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 * Where conversion attributions are kept, and how an erasure reaches them.\n *\n * ## Why this is a leaf module and not part of the join\n *\n * The erasure runs from `email-delivery-log.ts`, in the same function that\n * drops a person's campaign touches — which is the point, because an\n * attribution is a conclusion drawn from those touches and a conclusion that\n * outlives its evidence is an erasure that did not happen. But the join\n * itself READS that module (`readEmailCampaignTouch` is one half of the\n * last-touch comparison), so putting the erasure beside the join would make\n * the two modules import each other. Under jest that cycle resolves to\n * `undefined` at import time rather than failing loudly, which is how an\n * erasure comes to silently do nothing while its test passes.\n *\n * So the collection name and the sweep live here, importing nothing but\n * Firestore, and both sides import this.\n */\n\nimport firebaseAdmin from './firebase-admin'\n\nconst defaultFirestore = () => firebaseAdmin.app().firestore()\n\n/** The per-host collection of conversion attribution records. */\nexport const CAMPAIGN_ATTRIBUTIONS_COLLECTION = 'campaignAttributions'\n\n/** How many records one erasure pass removes per batch. */\nconst ERASURE_BATCH = 400\n\n/**\n * Removes every conversion attributed to one person, across every site.\n *\n * ## Why an erasure reaches these at all\n *\n * An attribution is a claim about a person: \"this human came from that\n * campaign and then did this\". It is the same personal fact as the click\n * stamp it was derived from, and the erasure path already deletes those —\n * `eraseEmailDeliveriesForAddresses` drops `campaignTouches` alongside the\n * engagement stamps and says why. A summary that outlived its source would\n * leave an erasure that removed the evidence and kept the conclusion.\n *\n * ## Why a collection-group query\n *\n * The record is per HOST, because that is where a site's own reporting reads\n * it. An erasure arrives as an ADDRESS and knows nothing about which sites\n * that person ever visited. The collection group is the join between the two,\n * and `personKey` is on the record precisely so one exists — declared in\n * `cloud/firebase-firestore.indexes.json` with `COLLECTION_GROUP` scope,\n * because a collection-group query gets no automatic single-field index and\n * would otherwise fail with FAILED_PRECONDITION at the moment somebody asked\n * to be forgotten.\n *\n * ## The order's own record is NOT touched\n *\n * `emailAttributions` holds a commercial fact about a sale, keyed by the\n * order's id and carrying no address — the revenue join says so where it\n * writes it. This holds a record of a person's behavior under a key derived\n * from their address. Different facts, different answers, and the split is\n * why both are defensible.\n *\n * Never throws: an erasure that fails on one leg must still complete the\n * others, and the caller reports what it removed.\n *\n * @returns how many records were removed.\n */\nexport async function eraseCampaignAttributionsForPersonKey(\n key: string | null | undefined,\n firestore?: any,\n): Promise<number> {\n if (!key || typeof key !== 'string') return 0\n const db = firestore ?? defaultFirestore()\n let removed = 0\n try {\n // Bounded rather than `while (true)`: a pathological volume must not be\n // able to hold an erasure request open indefinitely, and the pass that\n // runs next picks up whatever a bounded one left.\n for (let pass = 0; pass < 20; pass += 1) {\n const snapshot = await db\n .collectionGroup(CAMPAIGN_ATTRIBUTIONS_COLLECTION)\n .where('personKey', '==', key)\n .limit(ERASURE_BATCH)\n .get()\n if (snapshot.empty) break\n const batch = db.batch()\n snapshot.docs.forEach((doc: any) => batch.delete(doc.ref))\n await batch.commit()\n removed += snapshot.size\n if (snapshot.size < ERASURE_BATCH) break\n }\n } catch (error) {\n console.error('eraseCampaignAttributionsForPersonKey failed', error)\n }\n return removed\n}\n"],"names":["firebaseAdmin","defaultFirestore","app","firestore","CAMPAIGN_ATTRIBUTIONS_COLLECTION","ERASURE_BATCH","eraseCampaignAttributionsForPersonKey","key","db","removed","pass","snapshot","collectionGroup","where","limit","get","empty","batch","docs","forEach","doc","delete","ref","commit","size","error","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC,GAED,OAAOA,mBAAmB,sBAAkB;AAE5C,MAAMC,mBAAmB,IAAMD,cAAcE,GAAG,GAAGC,SAAS;AAE5D,+DAA+D,GAC/D,OAAO,MAAMC,mCAAmC,uBAAsB;AAEtE,yDAAyD,GACzD,MAAMC,gBAAgB;AAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCC,GACD,OAAO,eAAeC,sCACpBC,GAA8B,EAC9BJ,SAAe;IAEf,IAAI,CAACI,OAAO,OAAOA,QAAQ,UAAU,OAAO;IAC5C,MAAMC,KAAKL,oBAAAA,YAAaF;IACxB,IAAIQ,UAAU;IACd,IAAI;QACF,wEAAwE;QACxE,uEAAuE;QACvE,kDAAkD;QAClD,IAAK,IAAIC,OAAO,GAAGA,OAAO,IAAIA,QAAQ,EAAG;YACvC,MAAMC,WAAW,MAAMH,GACpBI,eAAe,CAACR,kCAChBS,KAAK,CAAC,aAAa,MAAMN,KACzBO,KAAK,CAACT,eACNU,GAAG;YACN,IAAIJ,SAASK,KAAK,EAAE;YACpB,MAAMC,QAAQT,GAAGS,KAAK;YACtBN,SAASO,IAAI,CAACC,OAAO,CAAC,CAACC,MAAaH,MAAMI,MAAM,CAACD,IAAIE,GAAG;YACxD,MAAML,MAAMM,MAAM;YAClBd,WAAWE,SAASa,IAAI;YACxB,IAAIb,SAASa,IAAI,GAAGnB,eAAe;QACrC;IACF,EAAE,OAAOoB,OAAO;QACdC,QAAQD,KAAK,CAAC,gDAAgDA;IAChE;IACA,OAAOhB;AACT"}
|