@aglyn/tenant-data-admin 1.0.0-beta.220 → 1.0.0-beta.222

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/api-keys.js +3 -3
  3. package/src/lib/server/api-keys.js.map +1 -1
  4. package/src/lib/server/api-v1-resources.d.ts +44 -3
  5. package/src/lib/server/api-v1-resources.js +82 -5
  6. package/src/lib/server/api-v1-resources.js.map +1 -1
  7. package/src/lib/server/collection-live-pages.d.ts +2 -2
  8. package/src/lib/server/collection-live-pages.js +1 -1
  9. package/src/lib/server/collection-live-pages.js.map +1 -1
  10. package/src/lib/server/email-delivery-log.d.ts +17 -73
  11. package/src/lib/server/email-delivery-log.js +44 -222
  12. package/src/lib/server/email-delivery-log.js.map +1 -1
  13. package/src/lib/server/email-flow-gate.js +27 -38
  14. package/src/lib/server/email-flow-gate.js.map +1 -1
  15. package/src/lib/server/erase-person.d.ts +34 -54
  16. package/src/lib/server/erase-person.js +44 -239
  17. package/src/lib/server/erase-person.js.map +1 -1
  18. package/src/lib/server/host-visitor-records.d.ts +12 -4
  19. package/src/lib/server/host-visitor-records.js +20 -10
  20. package/src/lib/server/host-visitor-records.js.map +1 -1
  21. package/src/lib/server/hosted-page-review.d.ts +7 -0
  22. package/src/lib/server/hosted-page-review.js +144 -20
  23. package/src/lib/server/hosted-page-review.js.map +1 -1
  24. package/src/lib/server/leaving-notice.d.ts +98 -0
  25. package/src/lib/server/leaving-notice.js +250 -0
  26. package/src/lib/server/leaving-notice.js.map +1 -0
  27. package/src/lib/server/link-reputation-review.d.ts +58 -0
  28. package/src/lib/server/link-reputation-review.js +185 -0
  29. package/src/lib/server/link-reputation-review.js.map +1 -0
  30. package/src/lib/server/live-page-drops.d.ts +67 -0
  31. package/src/lib/server/live-page-drops.js +57 -0
  32. package/src/lib/server/live-page-drops.js.map +1 -0
  33. package/src/lib/server/media-bandwidth-cap.d.ts +78 -0
  34. package/src/lib/server/media-bandwidth-cap.js +180 -0
  35. package/src/lib/server/media-bandwidth-cap.js.map +1 -0
  36. package/src/lib/server/media-cdn-icon.d.ts +77 -0
  37. package/src/lib/server/media-cdn-icon.js +140 -0
  38. package/src/lib/server/media-cdn-icon.js.map +1 -0
  39. package/src/lib/server/media-delivery-regeneration.d.ts +132 -0
  40. package/src/lib/server/media-delivery-regeneration.js +216 -0
  41. package/src/lib/server/media-delivery-regeneration.js.map +1 -0
  42. package/src/lib/server/media-delivery.d.ts +2 -0
  43. package/src/lib/server/media-delivery.js +2 -1
  44. package/src/lib/server/media-delivery.js.map +1 -1
  45. package/src/lib/server/media-serve-count.d.ts +50 -0
  46. package/src/lib/server/media-serve-count.js +62 -0
  47. package/src/lib/server/media-serve-count.js.map +1 -0
  48. package/src/lib/server/media-signing.d.ts +13 -2
  49. package/src/lib/server/media-signing.js +12 -8
  50. package/src/lib/server/media-signing.js.map +1 -1
  51. package/src/lib/server/media-tombstone.js +7 -5
  52. package/src/lib/server/media-tombstone.js.map +1 -1
  53. package/src/lib/server/media-variants.d.ts +151 -20
  54. package/src/lib/server/media-variants.js +204 -27
  55. package/src/lib/server/media-variants.js.map +1 -1
  56. package/src/lib/server/org-age.d.ts +15 -6
  57. package/src/lib/server/org-age.js +20 -8
  58. package/src/lib/server/org-age.js.map +1 -1
  59. package/src/lib/server/organizations.d.ts +102 -2
  60. package/src/lib/server/organizations.js +388 -58
  61. package/src/lib/server/organizations.js.map +1 -1
  62. package/src/lib/server/outbound-send-review.js +24 -6
  63. package/src/lib/server/outbound-send-review.js.map +1 -1
  64. package/src/lib/server/page-security-hold.d.ts +93 -0
  65. package/src/lib/server/page-security-hold.js +180 -0
  66. package/src/lib/server/page-security-hold.js.map +1 -0
  67. package/src/lib/server/paged-sweeps.d.ts +51 -0
  68. package/src/lib/server/paged-sweeps.js +79 -0
  69. package/src/lib/server/paged-sweeps.js.map +1 -0
  70. package/src/lib/server/platform-marketing-consent.d.ts +0 -49
  71. package/src/lib/server/platform-marketing-consent.js +27 -11
  72. package/src/lib/server/platform-marketing-consent.js.map +1 -1
  73. package/src/lib/server/serve-media-cdn.d.ts +69 -1
  74. package/src/lib/server/serve-media-cdn.js +424 -70
  75. package/src/lib/server/serve-media-cdn.js.map +1 -1
  76. package/src/lib/server/site-icon-render.d.ts +68 -0
  77. package/src/lib/server/site-icon-render.js +157 -0
  78. package/src/lib/server/site-icon-render.js.map +1 -0
  79. package/src/lib/server/staff-seat.d.ts +50 -0
  80. package/src/lib/server/staff-seat.js +118 -0
  81. package/src/lib/server/staff-seat.js.map +1 -0
  82. package/src/lib/server/transfer-export.d.ts +46 -0
  83. package/src/lib/server/transfer-export.js +221 -0
  84. package/src/lib/server/transfer-export.js.map +1 -0
  85. package/src/lib/server/transfer-jobs.d.ts +385 -0
  86. package/src/lib/server/transfer-jobs.js +2368 -0
  87. package/src/lib/server/transfer-jobs.js.map +1 -0
  88. package/src/lib/server/transfer-packages.d.ts +127 -0
  89. package/src/lib/server/transfer-packages.js +1036 -0
  90. package/src/lib/server/transfer-packages.js.map +1 -0
  91. package/src/lib/server/upgrade-proposal.d.ts +97 -0
  92. package/src/lib/server/upgrade-proposal.js +312 -0
  93. package/src/lib/server/upgrade-proposal.js.map +1 -0
  94. package/src/lib/server/upsert-contact.d.ts +17 -8
  95. package/src/lib/server/upsert-contact.js +82 -16
  96. package/src/lib/server/upsert-contact.js.map +1 -1
  97. package/src/lib/server/web-risk.d.ts +139 -0
  98. package/src/lib/server/web-risk.js +521 -0
  99. package/src/lib/server/web-risk.js.map +1 -0
  100. package/src/tenancy.d.ts +3 -1
  101. package/src/tenancy.js +5 -1
  102. package/src/tenancy.js.map +1 -1
  103. package/src/lib/server/campaign-attribution-store.d.ts +0 -55
  104. package/src/lib/server/campaign-attribution-store.js +0 -95
  105. package/src/lib/server/campaign-attribution-store.js.map +0 -1
  106. package/src/lib/server/campaign-conversion-attribution.d.ts +0 -283
  107. package/src/lib/server/campaign-conversion-attribution.js +0 -450
  108. package/src/lib/server/campaign-conversion-attribution.js.map +0 -1
  109. package/src/lib/server/dataset-live-pages.d.ts +0 -179
  110. package/src/lib/server/dataset-live-pages.js +0 -421
  111. package/src/lib/server/dataset-live-pages.js.map +0 -1
  112. package/src/lib/server/email-revenue-attribution.d.ts +0 -185
  113. package/src/lib/server/email-revenue-attribution.js +0 -321
  114. package/src/lib/server/email-revenue-attribution.js.map +0 -1
@@ -0,0 +1,521 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ /*==========================================
18
+ * GOOGLE WEB RISK (AGL-3451): the lookup behind the link reputation screen.
19
+ *
20
+ * `@aglyn/shared-util-email/link-reputation` decides which hosts are foreign
21
+ * and turns a listing into a strong `web-risk-link` signal. This is the store
22
+ * half: the `uris.search` client, the cache, the switches.
23
+ *
24
+ * ## The client
25
+ *
26
+ * {@link WebRiskClient} is the contract: one URI in, the threat types it is
27
+ * listed for and how long that answer may be kept. The default
28
+ * implementation calls `webrisk.googleapis.com/v1/uris:search` for
29
+ * SOCIAL_ENGINEERING, MALWARE and UNWANTED_SOFTWARE as the platform's own
30
+ * service account — the firebase-admin credential every other server-side
31
+ * Google call here already uses (`client-error-report.ts`), so there is no
32
+ * key of its own. What is sent depends on the lookup mode, below.
33
+ *
34
+ * ## The lookup mode (AGL-3459)
35
+ *
36
+ * `platformSettings/webRisk.lookupMode`:
37
+ *
38
+ * - `'host'` — the default, and anything that is not `'url'`. Only
39
+ * `https://<host>/` is ever sent.
40
+ * - `'url'` — the host first, from the cache or a call; then, for a host
41
+ * that is not itself listed, each of its links' addresses as
42
+ * `normalizeReputationLink` reduced them: scheme, host and path, never a
43
+ * query string, a fragment or a `user:password@`. A listed address is a
44
+ * hit on a clean host, so a kit at a path on a compromised site holds the
45
+ * page. At most `MAX_REPUTATION_URLS_PER_LOOKUP` addresses per lookup,
46
+ * inside the same deadline as the hosts.
47
+ *
48
+ * `'url'` sends more than a host to Google, so it stays off until the
49
+ * Subprocessors page names that purpose — see the `webrisk.googleapis.com`
50
+ * entry in `apps/console/constants/subprocessor-inventory.ts`.
51
+ *
52
+ * ## Not evidence when it fails
53
+ *
54
+ * A call is given {@link WEB_RISK_TIMEOUT_MS}, and a whole lookup
55
+ * {@link WEB_RISK_DEADLINE_MS} — hosts and addresses together. A host or an
56
+ * address whose answer did not arrive, or whose call failed, is UNKNOWN: it
57
+ * holds nothing and logs a warning. A credential the API refuses (the API is
58
+ * not enabled on a self-hosted project, say) backs the lookup off for a
59
+ * quarter of an hour, so a misconfiguration is one log line rather than one
60
+ * per page.
61
+ *
62
+ * ## The cache
63
+ *
64
+ * Per host and per address, in two layers, with the same rules for both:
65
+ *
66
+ * - this process's memory — a listing until the answer's `expireTime`,
67
+ * which Web Risk sets and which may not be exceeded; a clean answer for
68
+ * {@link WEB_RISK_MEMORY_CLEAN_TTL_MS}, short so a listing the daily
69
+ * re-check writes reaches every warm render within minutes. Capped at
70
+ * {@link WEB_RISK_MEMORY_MAX_ENTRIES}, then started again;
71
+ * - the store, server-only, a clean answer kept {@link WEB_RISK_CLEAN_TTL_MS}:
72
+ * `webRiskVerdicts/{host}`, bounded by the number of distinct foreign
73
+ * hosts and rewritten in place; and `webRiskUrlVerdicts/{sha256(address)}`,
74
+ * whose answers the daily re-check deletes a day after they expire
75
+ * ({@link reapExpiredWebRiskUrlVerdicts}), because addresses are many more
76
+ * than hosts and a path is worth keeping no longer than it is used.
77
+ *
78
+ * Read in one `getAll` per lookup, so a page's hosts and addresses cost one
79
+ * round trip, and nothing at all once they are in memory.
80
+ *
81
+ * ## The kill switch
82
+ *
83
+ * `platformSettings/webRisk` `{ enabled: false }` stops every lookup within a
84
+ * minute — every host reads unknown, so nothing holds on it — without a
85
+ * deploy. Absent or anything else means on.
86
+ *=========================================*/ import { createHash } from "crypto";
87
+ import { TENANT_APEX } from "@aglyn/aglyn/app-utils/tenant-apex";
88
+ import { LINK_THREAT_TYPES, MAX_REPUTATION_HOSTS_PER_LOOKUP, MAX_REPUTATION_URLS_PER_LOOKUP, normalizeReputationHost, normalizeReputationLink, pickReputationUrls, setLinkReputationLookup } from "@aglyn/shared-util-email/link-reputation";
89
+ import { getApp } from "firebase-admin/app";
90
+ import firebaseAdmin from "./firebase-admin.js";
91
+ export const WEB_RISK_SEARCH_ENDPOINT = 'https://webrisk.googleapis.com/v1/uris:search';
92
+ /** One answer per host. */ export const WEB_RISK_CACHE_COLLECTION = 'webRiskVerdicts';
93
+ /** One answer per address, in `'url'` mode (AGL-3459), keyed by the address's SHA-256. */ export const WEB_RISK_URL_CACHE_COLLECTION = 'webRiskUrlVerdicts';
94
+ /**
95
+ * The switches: `{ enabled: false }` turns every lookup off;
96
+ * `lookupMode: 'url'` looks up links' addresses as well as their hosts.
97
+ */ export const WEB_RISK_SETTINGS_COLLECTION = 'platformSettings';
98
+ export const WEB_RISK_SETTINGS_DOC = 'webRisk';
99
+ /** One call's budget. */ export const WEB_RISK_TIMEOUT_MS = 1000;
100
+ /** One lookup's budget, however many hosts and addresses it asks about. */ export const WEB_RISK_DEADLINE_MS = 1200;
101
+ /** How long a clean answer is kept in the store. */ export const WEB_RISK_CLEAN_TTL_MS = 12 * 60 * 60000;
102
+ /** How long a clean answer is trusted from this process's memory. */ export const WEB_RISK_MEMORY_CLEAN_TTL_MS = 10 * 60000;
103
+ /** A listing whose answer named no `expireTime` is kept this long. */ export const WEB_RISK_LISTED_FALLBACK_TTL_MS = 5 * 60000;
104
+ /** The most answers this process remembers before it starts again. */ export const WEB_RISK_MEMORY_MAX_ENTRIES = 20000;
105
+ /** How long past its expiry an address's stored answer is deleted. */ export const WEB_RISK_URL_VERDICT_GRACE_MS = 24 * 60 * 60000;
106
+ /** How long the switches' answer is trusted. */ const SWITCH_TTL_MS = 60000;
107
+ /** How long a refused credential stops the lookup. */ const REFUSED_BACKOFF_MS = 15 * 60000;
108
+ /** How long a rate limit stops the lookup. */ const THROTTLED_BACKOFF_MS = 60000;
109
+ /** At most one warning per this long, so an outage is not a log flood. */ const WARN_EVERY_MS = 60000;
110
+ /** The API answered with a status that is not an answer. */ export class WebRiskHttpError extends Error {
111
+ constructor(status, detail){
112
+ super(`Web Risk answered ${status}: ${detail.slice(0, 200)}`), this.status = status;
113
+ this.name = 'WebRiskHttpError';
114
+ }
115
+ }
116
+ /** There is no credential to call with. */ export class WebRiskUnavailableError extends Error {
117
+ constructor(reason){
118
+ super(reason);
119
+ this.name = 'WebRiskUnavailableError';
120
+ }
121
+ }
122
+ /** `uris.search`'s body, read defensively: an empty object is "not listed". */ export function parseWebRiskSearch(body) {
123
+ const threat = body == null ? void 0 : body.threat;
124
+ if (!threat || typeof threat !== 'object') return {
125
+ threats: [],
126
+ expireTimeMs: null
127
+ };
128
+ const listed = Array.isArray(threat.threatTypes) ? threat.threatTypes : [];
129
+ const threats = LINK_THREAT_TYPES.filter((type)=>listed.includes(type));
130
+ const expireTimeMs = typeof threat.expireTime === 'string' ? Date.parse(threat.expireTime) : Number.NaN;
131
+ return {
132
+ threats,
133
+ expireTimeMs: Number.isFinite(expireTimeMs) ? expireTimeMs : null
134
+ };
135
+ }
136
+ /** The URI a host is looked up as. Only the host: never a path or a query. */ export function webRiskUriForHost(host) {
137
+ return `https://${host}/`;
138
+ }
139
+ /** The default client: `uris.search` over HTTPS with a bearer token. */ export function createWebRiskHttpClient(options) {
140
+ var _options_fetch, _options_timeoutMs;
141
+ const request = (_options_fetch = options.fetch) != null ? _options_fetch : fetch;
142
+ const timeoutMs = (_options_timeoutMs = options.timeoutMs) != null ? _options_timeoutMs : WEB_RISK_TIMEOUT_MS;
143
+ return {
144
+ async searchUri (uri) {
145
+ var _options_endpoint;
146
+ const token = await options.accessToken();
147
+ if (!token) throw new WebRiskUnavailableError('no service-account credential');
148
+ const url = new URL((_options_endpoint = options.endpoint) != null ? _options_endpoint : WEB_RISK_SEARCH_ENDPOINT);
149
+ for (const type of LINK_THREAT_TYPES)url.searchParams.append('threatTypes', type);
150
+ url.searchParams.set('uri', uri);
151
+ const controller = new AbortController();
152
+ const timer = setTimeout(()=>controller.abort(), timeoutMs);
153
+ try {
154
+ const response = await request(url.toString(), {
155
+ method: 'GET',
156
+ headers: {
157
+ Authorization: `Bearer ${token}`,
158
+ Accept: 'application/json'
159
+ },
160
+ signal: controller.signal
161
+ });
162
+ if (!response.ok) {
163
+ throw new WebRiskHttpError(response.status, await response.text().catch(()=>''));
164
+ }
165
+ return parseWebRiskSearch(await response.json());
166
+ } finally{
167
+ clearTimeout(timer);
168
+ }
169
+ }
170
+ };
171
+ }
172
+ /**
173
+ * The platform service account's access token, or null when this deployment
174
+ * has none — the same credential `client-error-report.ts` writes logs with.
175
+ */ async function serviceAccountAccessToken() {
176
+ try {
177
+ var _ref;
178
+ var _this;
179
+ const credential = getApp().options.credential;
180
+ if (!credential) return null;
181
+ return (_ref = (_this = await credential.getAccessToken()) == null ? void 0 : _this.access_token) != null ? _ref : null;
182
+ } catch (unused) {
183
+ return null;
184
+ }
185
+ }
186
+ let defaultClient = null;
187
+ let clientOverride;
188
+ function activeClient() {
189
+ if (clientOverride !== undefined) return clientOverride;
190
+ defaultClient != null ? defaultClient : defaultClient = createWebRiskHttpClient({
191
+ accessToken: serviceAccountAccessToken
192
+ });
193
+ return defaultClient;
194
+ }
195
+ /** Hosts and addresses share one memory: an address always holds `://`, a host never does. */ const memory = new Map();
196
+ let settingsMemo = null;
197
+ let backoffUntilMs = 0;
198
+ let lastWarnAtMs = 0;
199
+ /** Test seam: forget the caches, the switches, the back-off; optionally stand in a client. */ export function resetWebRiskForTests(client) {
200
+ memory.clear();
201
+ settingsMemo = null;
202
+ backoffUntilMs = 0;
203
+ lastWarnAtMs = 0;
204
+ clientOverride = client;
205
+ defaultClient = null;
206
+ }
207
+ function warn(nowMs, message, error) {
208
+ if (nowMs - lastWarnAtMs < WARN_EVERY_MS) return;
209
+ lastWarnAtMs = nowMs;
210
+ console.warn(`[web-risk] ${message} — it reads unknown, which is not evidence`, error != null ? error : '');
211
+ }
212
+ /**
213
+ * The switches, read at most once a minute. An unreadable document is on,
214
+ * in `'host'` mode; a mode that is not exactly `'url'` is `'host'`.
215
+ */ async function webRiskSettings(nowMs) {
216
+ if (settingsMemo && nowMs - settingsMemo.atMs < SWITCH_TTL_MS) return settingsMemo;
217
+ const settings = await firebaseAdmin.app().firestore().collection(WEB_RISK_SETTINGS_COLLECTION).doc(WEB_RISK_SETTINGS_DOC).get().then((snapshot)=>({
218
+ off: snapshot.get('enabled') === false,
219
+ mode: snapshot.get('lookupMode') === 'url' ? 'url' : 'host'
220
+ }), ()=>({
221
+ off: false,
222
+ mode: 'host'
223
+ }));
224
+ settingsMemo = _extends({}, settings, {
225
+ atMs: nowMs
226
+ });
227
+ return settings;
228
+ }
229
+ /**
230
+ * The lookup mode in force (AGL-3459): `'url'` only while the lookup is on
231
+ * and `platformSettings/webRisk.lookupMode` is exactly `'url'`.
232
+ */ export async function webRiskLookupMode(nowMs = Date.now()) {
233
+ const settings = await webRiskSettings(nowMs);
234
+ return settings.off ? 'host' : settings.mode;
235
+ }
236
+ /**
237
+ * Hosts that are the platform's own: every site's subdomain on the tenant
238
+ * apex. Never looked up — a neighbour's site is screened on its own page.
239
+ */ export function platformReputationExclusions() {
240
+ return [
241
+ TENANT_APEX
242
+ ].filter(Boolean);
243
+ }
244
+ function isPlatformHost(host) {
245
+ return platformReputationExclusions().some((domain)=>host === domain || host.endsWith(`.${domain}`));
246
+ }
247
+ /** An address's document id in {@link WEB_RISK_URL_CACHE_COLLECTION}: an address holds `/`, a hash does not. */ export function webRiskUrlVerdictId(url) {
248
+ return createHash('sha256').update(url).digest('hex');
249
+ }
250
+ function isAddress(key) {
251
+ return key.includes('://');
252
+ }
253
+ /** A stored answer, or null. An address's must name the address it was asked for. */ function verdictFrom(data, url) {
254
+ if (!data) return null;
255
+ if (url !== undefined && data['url'] !== url) return null;
256
+ const threats = Array.isArray(data['threats']) ? LINK_THREAT_TYPES.filter((type)=>data['threats'].includes(type)) : [];
257
+ const checkedAtMs = Number(data['checkedAtMs']);
258
+ const expiresAtMs = Number(data['expiresAtMs']);
259
+ if (!Number.isFinite(checkedAtMs) || !Number.isFinite(expiresAtMs)) return null;
260
+ return {
261
+ threats,
262
+ checkedAtMs,
263
+ expiresAtMs
264
+ };
265
+ }
266
+ function remember(key, verdict, nowMs) {
267
+ if (memory.size >= WEB_RISK_MEMORY_MAX_ENTRIES && !memory.has(key)) memory.clear();
268
+ memory.set(key, _extends({}, verdict, {
269
+ memoryUntilMs: verdict.threats.length ? verdict.expiresAtMs : Math.min(verdict.expiresAtMs, nowMs + WEB_RISK_MEMORY_CLEAN_TTL_MS)
270
+ }));
271
+ }
272
+ function fromMemory(key, nowMs) {
273
+ const known = memory.get(key);
274
+ return known && nowMs < known.memoryUntilMs ? known : null;
275
+ }
276
+ /**
277
+ * The reputation of each host — and, in `'url'` mode, of each address on a
278
+ * host that is not itself listed: listed, clean, or unknown. Platform hosts
279
+ * are clean without asking. Never throws, and never waits on the API longer
280
+ * than the deadline: a call still running then finishes in the background
281
+ * and fills the caches for the next asker.
282
+ *
283
+ * "Never throws" covers the store as well as the API: a missing app, a
284
+ * settings read that fails before it is a promise, or a cache reference
285
+ * that cannot be built all read every host as unknown. The page review
286
+ * calls this before its own fail-closed `try`, so a throw here would take
287
+ * down every page with a link off the site.
288
+ */ export async function lookupLinkReputation(hosts, options = {}) {
289
+ try {
290
+ return await lookupLinkReputationOrThrow(hosts, options);
291
+ } catch (error) {
292
+ var _options_nowMs;
293
+ warn((_options_nowMs = options.nowMs) != null ? _options_nowMs : Date.now(), 'a lookup failed before it could answer', error);
294
+ const unknown = [
295
+ ...new Set(hosts.map((raw)=>normalizeReputationHost(raw)).filter((host)=>Boolean(host)))
296
+ ];
297
+ return {
298
+ hits: [],
299
+ clean: [],
300
+ unknown,
301
+ looked: 0
302
+ };
303
+ }
304
+ }
305
+ async function lookupLinkReputationOrThrow(hosts, options) {
306
+ var _options_nowMs, _options_maxUrls;
307
+ var _options_urls;
308
+ const nowMs = (_options_nowMs = options.nowMs) != null ? _options_nowMs : Date.now();
309
+ const result = {
310
+ hits: [],
311
+ clean: [],
312
+ unknown: [],
313
+ looked: 0
314
+ };
315
+ const wanted = [];
316
+ for (const raw of hosts){
317
+ var _options_maxHosts;
318
+ const host = normalizeReputationHost(raw);
319
+ if (!host || wanted.includes(host) || result.clean.includes(host)) continue;
320
+ if (isPlatformHost(host)) result.clean.push(host);
321
+ else if (wanted.length < ((_options_maxHosts = options.maxHosts) != null ? _options_maxHosts : MAX_REPUTATION_HOSTS_PER_LOOKUP)) wanted.push(host);
322
+ else result.unknown.push(host);
323
+ }
324
+ if (!wanted.length) return result;
325
+ let urls = ((_options_urls = options.urls) == null ? void 0 : _options_urls.length) ? pickReputationUrls(options.urls, wanted, (_options_maxUrls = options.maxUrls) != null ? _options_maxUrls : MAX_REPUTATION_URLS_PER_LOOKUP) : [];
326
+ const hostOf = new Map(urls.map((url)=>{
327
+ var _ref;
328
+ var _normalizeReputationLink;
329
+ return [
330
+ url,
331
+ (_ref = (_normalizeReputationLink = normalizeReputationLink(url)) == null ? void 0 : _normalizeReputationLink.host) != null ? _ref : ''
332
+ ];
333
+ }));
334
+ // What is known before the API is asked, host or address.
335
+ const known = new Map();
336
+ const unknownTo = (keys)=>keys.filter((key)=>{
337
+ const verdict = fromMemory(key, nowMs);
338
+ if (verdict) known.set(key, verdict);
339
+ return !verdict;
340
+ });
341
+ // 1. This process's memory, for the hosts.
342
+ let missingHosts = unknownTo(wanted);
343
+ let missingUrls = [];
344
+ let mayAsk = true;
345
+ // 2. The switches — read only when a host is left to ask about, or
346
+ // addresses wait on the mode. Off reads everything left as unknown.
347
+ if (missingHosts.length || urls.length) {
348
+ const settings = await webRiskSettings(nowMs);
349
+ if (settings.off || settings.mode !== 'url') urls = [];
350
+ if (settings.off) mayAsk = false;
351
+ // An address on a host already known to be listed adds nothing.
352
+ urls = urls.filter((url)=>{
353
+ var _hostOf_get;
354
+ var _known_get;
355
+ return !((_known_get = known.get((_hostOf_get = hostOf.get(url)) != null ? _hostOf_get : '')) == null ? void 0 : _known_get.threats.length);
356
+ });
357
+ // 1b. This process's memory, for the addresses.
358
+ missingUrls = unknownTo(urls);
359
+ }
360
+ // 3. The store, hosts and addresses in one round trip.
361
+ const firestore = firebaseAdmin.app().firestore();
362
+ const hostCollection = firestore.collection(WEB_RISK_CACHE_COLLECTION);
363
+ const urlCollection = firestore.collection(WEB_RISK_URL_CACHE_COLLECTION);
364
+ if (mayAsk && (missingHosts.length || missingUrls.length)) {
365
+ const keys = [
366
+ ...missingHosts,
367
+ ...missingUrls
368
+ ];
369
+ try {
370
+ const snapshots = await firestore.getAll(...keys.map((key)=>isAddress(key) ? urlCollection.doc(webRiskUrlVerdictId(key)) : hostCollection.doc(key)));
371
+ snapshots.forEach((snapshot, index)=>{
372
+ const key = keys[index];
373
+ const data = snapshot.exists ? snapshot.data() : undefined;
374
+ const verdict = verdictFrom(data, isAddress(key) ? key : undefined);
375
+ if (!verdict || nowMs >= verdict.expiresAtMs) return;
376
+ remember(key, verdict, nowMs);
377
+ known.set(key, verdict);
378
+ });
379
+ missingHosts = missingHosts.filter((host)=>!known.has(host));
380
+ missingUrls = missingUrls.filter((url)=>!known.has(url));
381
+ } catch (error) {
382
+ warn(nowMs, 'the verdict cache could not be read', error);
383
+ }
384
+ }
385
+ // 4. The API, everything left at once, within the deadline: each host
386
+ // first, then — unless the host itself is listed — its addresses.
387
+ const answered = new Map();
388
+ const client = activeClient();
389
+ if (mayAsk && client && nowMs >= backoffUntilMs && (missingHosts.length || missingUrls.length)) {
390
+ let looked = 0;
391
+ const ask = async (key)=>{
392
+ if (Date.now() < backoffUntilMs) return null;
393
+ looked += 1;
394
+ try {
395
+ var _answer_expireTimeMs, _hostOf_get;
396
+ const answer = await client.searchUri(isAddress(key) ? key : webRiskUriForHost(key));
397
+ const checkedAtMs = Date.now();
398
+ const verdict = {
399
+ threats: answer.threats,
400
+ checkedAtMs,
401
+ expiresAtMs: answer.threats.length ? (_answer_expireTimeMs = answer.expireTimeMs) != null ? _answer_expireTimeMs : checkedAtMs + WEB_RISK_LISTED_FALLBACK_TTL_MS : checkedAtMs + WEB_RISK_CLEAN_TTL_MS
402
+ };
403
+ answered.set(key, verdict);
404
+ remember(key, verdict, checkedAtMs);
405
+ const document = isAddress(key) ? urlCollection.doc(webRiskUrlVerdictId(key)).set(_extends({
406
+ host: (_hostOf_get = hostOf.get(key)) != null ? _hostOf_get : '',
407
+ url: key
408
+ }, verdict, {
409
+ listed: verdict.threats.length > 0
410
+ })) : hostCollection.doc(key).set(_extends({
411
+ host: key
412
+ }, verdict, {
413
+ listed: verdict.threats.length > 0
414
+ }));
415
+ await document.catch((error)=>warn(checkedAtMs, 'a verdict could not be cached', error));
416
+ return verdict;
417
+ } catch (error) {
418
+ if (error instanceof WebRiskHttpError && [
419
+ 401,
420
+ 403,
421
+ 404
422
+ ].includes(error.status)) {
423
+ backoffUntilMs = Date.now() + REFUSED_BACKOFF_MS;
424
+ console.error('[web-risk] the API refused the credential — lookups paused for 15 minutes', error);
425
+ } else if (error instanceof WebRiskHttpError && error.status === 429) {
426
+ backoffUntilMs = Date.now() + THROTTLED_BACKOFF_MS;
427
+ warn(Date.now(), 'the API is rate limiting', error);
428
+ } else if (error instanceof WebRiskUnavailableError) {
429
+ backoffUntilMs = Date.now() + REFUSED_BACKOFF_MS;
430
+ warn(Date.now(), 'no credential to call the API with', error);
431
+ } else {
432
+ warn(Date.now(), `the lookup of ${key} failed or timed out`, error);
433
+ }
434
+ return null;
435
+ }
436
+ };
437
+ const pipelines = wanted.map(async (host)=>{
438
+ var _known_get;
439
+ const hostVerdict = (_known_get = known.get(host)) != null ? _known_get : missingHosts.includes(host) ? await ask(host) : null;
440
+ if (hostVerdict == null ? void 0 : hostVerdict.threats.length) return;
441
+ await Promise.all(missingUrls.filter((url)=>hostOf.get(url) === host).map((url)=>ask(url)));
442
+ });
443
+ let timer;
444
+ await Promise.race([
445
+ Promise.allSettled(pipelines),
446
+ new Promise((resolve)=>{
447
+ var _options_deadlineMs;
448
+ timer = setTimeout(resolve, (_options_deadlineMs = options.deadlineMs) != null ? _options_deadlineMs : WEB_RISK_DEADLINE_MS);
449
+ })
450
+ ]);
451
+ if (timer) clearTimeout(timer);
452
+ result.looked = looked;
453
+ const late = [
454
+ ...missingHosts,
455
+ ...missingUrls
456
+ ].filter((key)=>!answered.has(key)).length;
457
+ if (late) warn(Date.now(), `${late} host(s) or address(es) had no answer within the deadline`);
458
+ }
459
+ // 5. The answer. An address on a listed host is not reported: the host's
460
+ // listing already names it.
461
+ const verdictOf = (key)=>{
462
+ var _known_get;
463
+ return (_known_get = known.get(key)) != null ? _known_get : answered.get(key);
464
+ };
465
+ for (const host of wanted){
466
+ const verdict = verdictOf(host);
467
+ if (!verdict) result.unknown.push(host);
468
+ else if (verdict.threats.length) result.hits.push({
469
+ host,
470
+ threats: verdict.threats
471
+ });
472
+ else result.clean.push(host);
473
+ }
474
+ for (const url of urls){
475
+ var _hostOf_get;
476
+ var _verdictOf;
477
+ const host = (_hostOf_get = hostOf.get(url)) != null ? _hostOf_get : '';
478
+ if ((_verdictOf = verdictOf(host)) == null ? void 0 : _verdictOf.threats.length) continue;
479
+ const verdict = verdictOf(url);
480
+ if (!verdict) result.unknown.push(url);
481
+ else if (verdict.threats.length) result.hits.push({
482
+ host,
483
+ url,
484
+ threats: verdict.threats
485
+ });
486
+ else result.clean.push(url);
487
+ }
488
+ return result;
489
+ }
490
+ /**
491
+ * Delete the addresses' stored answers that expired more than
492
+ * {@link WEB_RISK_URL_VERDICT_GRACE_MS} ago (AGL-3459), at most `limit` at a
493
+ * time. The daily re-check calls it once per walk. A host's answers are not
494
+ * reaped: they are few and rewritten in place. Never throws.
495
+ */ export async function reapExpiredWebRiskUrlVerdicts(options = {}) {
496
+ var _options_nowMs, _options_firestore;
497
+ const nowMs = (_options_nowMs = options.nowMs) != null ? _options_nowMs : Date.now();
498
+ const firestore = (_options_firestore = options.firestore) != null ? _options_firestore : firebaseAdmin.app().firestore();
499
+ try {
500
+ var _options_limit;
501
+ const stale = await firestore.collection(WEB_RISK_URL_CACHE_COLLECTION).where('expiresAtMs', '<', nowMs - WEB_RISK_URL_VERDICT_GRACE_MS).limit((_options_limit = options.limit) != null ? _options_limit : 500).get();
502
+ await Promise.all(stale.docs.map((snapshot)=>snapshot.ref.delete()));
503
+ return stale.docs.length;
504
+ } catch (error) {
505
+ console.warn('[web-risk] expired address verdicts could not be deleted', error);
506
+ return 0;
507
+ }
508
+ }
509
+ /**
510
+ * Puts this lookup behind the shared screen's reputation seam, so the send
511
+ * seam (`screenTenantMessage`) asks it. Called by
512
+ * `installOutboundScreenGate`, at that module's load.
513
+ */ export function installLinkReputationLookup() {
514
+ if (typeof setLinkReputationLookup !== 'function') return;
515
+ setLinkReputationLookup((hosts, options)=>lookupLinkReputation(hosts, {
516
+ deadlineMs: options == null ? void 0 : options.deadlineMs,
517
+ urls: options == null ? void 0 : options.urls
518
+ }));
519
+ }
520
+
521
+ //# sourceMappingURL=web-risk.js.map
@@ -0,0 +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/*==========================================\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 { 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/** 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 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\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 let timer: ReturnType<typeof setTimeout> | undefined\n await Promise.race([\n Promise.allSettled(pipelines),\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, options.deadlineMs ?? WEB_RISK_DEADLINE_MS)\n }),\n ])\n if (timer) clearTimeout(timer)\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","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_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","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","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","answer","document","pipelines","hostVerdict","Promise","all","race","allSettled","resolve","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,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,qBAAo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IAAI,CAAC/F;aAC7B,IAAI0E,QAAQpG,OAAO,CAACwG,MAAM,EAAEe,OAAOH,IAAI,CAACK,IAAI,CAAC;YAAEzG;YAAMU;YAAK1B,SAASoG,QAAQpG,OAAO;QAAC;aACnFuH,OAAOF,KAAK,CAACI,IAAI,CAAC/F;IACzB;IACA,OAAO6F;AACT;AAEA;;;;;CAKC,GACD,OAAO,eAAeiC,8BACpBtI,UAAuF,CAAC,CAAC;QAE3EA,gBACIA;IADlB,MAAMgD,SAAQhD,iBAAAA,QAAQgD,KAAK,YAAbhD,iBAAiBR,KAAKyE,GAAG;IACvC,MAAMT,aAAYxD,qBAAAA,QAAQwD,SAAS,YAAjBxD,qBAAqB9C,cAAcqG,GAAG,GAAGC,SAAS;IACpE,IAAI;YAIOxD;QAHT,MAAMuI,QAAQ,MAAM/E,UACjBC,UAAU,CAACpG,+BACXmL,KAAK,CAAC,eAAe,KAAKxF,QAAQlF,+BAClC2K,KAAK,EAACzI,iBAAAA,QAAQyI,KAAK,YAAbzI,iBAAiB,KACvB2D,GAAG;QACN,MAAMmE,QAAQC,GAAG,CAACQ,MAAMG,IAAI,CAAC1C,GAAG,CAAC,CAACnC,WAAaA,SAAS8E,GAAG,CAACC,MAAM;QAClE,OAAOL,MAAMG,IAAI,CAACpD,MAAM;IAC1B,EAAE,OAAOpC,OAAO;QACdC,QAAQJ,IAAI,CAAC,4DAA4DG;QACzE,OAAO;IACT;AACF;AAEA;;;;CAIC,GACD,OAAO,SAAS2F;IACd,IAAI,OAAO7L,4BAA4B,YAAY;IACnDA,wBAAwB,CAAC4I,OAAO5F,UAC9B2F,qBAAqBC,OAAO;YAAEuC,UAAU,EAAEnI,2BAAAA,QAASmI,UAAU;YAAE1B,IAAI,EAAEzG,2BAAAA,QAASyG,IAAI;QAAC;AAEvF"}
package/src/tenancy.d.ts CHANGED
@@ -52,7 +52,6 @@ export * from './lib/server/edit-access-authz';
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';