@aglyn/tenant-data-admin 1.0.0-beta.220 → 1.0.0-beta.221
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/hosted-page-review.d.ts +7 -0
- package/src/lib/server/hosted-page-review.js +131 -20
- package/src/lib/server/hosted-page-review.js.map +1 -1
- package/src/lib/server/leaving-notice.d.ts +98 -0
- package/src/lib/server/leaving-notice.js +250 -0
- package/src/lib/server/leaving-notice.js.map +1 -0
- package/src/lib/server/link-reputation-review.d.ts +54 -0
- package/src/lib/server/link-reputation-review.js +144 -0
- package/src/lib/server/link-reputation-review.js.map +1 -0
- package/src/lib/server/org-age.d.ts +15 -6
- package/src/lib/server/org-age.js +20 -8
- package/src/lib/server/org-age.js.map +1 -1
- package/src/lib/server/outbound-send-review.js +23 -6
- package/src/lib/server/outbound-send-review.js.map +1 -1
- package/src/lib/server/page-security-hold.d.ts +93 -0
- package/src/lib/server/page-security-hold.js +180 -0
- package/src/lib/server/page-security-hold.js.map +1 -0
- package/src/lib/server/web-risk.d.ts +100 -0
- package/src/lib/server/web-risk.js +383 -0
- package/src/lib/server/web-risk.js.map +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-data-admin",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.221",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,12 +25,12 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.0.0-beta.
|
|
29
|
-
"@aglyn/shared-util-email": "1.0.0-beta.
|
|
30
|
-
"@aglyn/shared-util-fbserver": "1.0.0-beta.
|
|
31
|
-
"@aglyn/shared-util-first-touch": "1.0.0-beta.
|
|
32
|
-
"@aglyn/shared-util-http": "1.0.0-beta.
|
|
33
|
-
"@aglyn/shared-util-tools": "1.0.0-beta.
|
|
28
|
+
"@aglyn/aglyn": "1.0.0-beta.221",
|
|
29
|
+
"@aglyn/shared-util-email": "1.0.0-beta.221",
|
|
30
|
+
"@aglyn/shared-util-fbserver": "1.0.0-beta.221",
|
|
31
|
+
"@aglyn/shared-util-first-touch": "1.0.0-beta.221",
|
|
32
|
+
"@aglyn/shared-util-http": "1.0.0-beta.221",
|
|
33
|
+
"@aglyn/shared-util-tools": "1.0.0-beta.221",
|
|
34
34
|
"@msgpack/msgpack": "^3.1.3",
|
|
35
35
|
"@swc/helpers": "0.5.23",
|
|
36
36
|
"sharp": "^0.35.5",
|
|
@@ -36,6 +36,13 @@ export interface HostedPageReviewRequest {
|
|
|
36
36
|
* to name the page — never to decide whether it serves.
|
|
37
37
|
*/
|
|
38
38
|
page?: HostedPageContext | null;
|
|
39
|
+
/**
|
|
40
|
+
* Signals found about this page elsewhere, judged with the page's own
|
|
41
|
+
* (AGL-3451): the daily link re-check passes a link Web Risk has listed
|
|
42
|
+
* since the page went live, so the hold, its row and the young
|
|
43
|
+
* workspace's security hold all come from this one path.
|
|
44
|
+
*/
|
|
45
|
+
extraSignals?: readonly PhishingScreenSignal[];
|
|
39
46
|
}
|
|
40
47
|
export type HostedPageReviewOutcome = {
|
|
41
48
|
outcome: 'serve';
|
|
@@ -51,6 +51,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
51
51
|
* site's cache and the next render serves it) or mark it actioned to
|
|
52
52
|
* REJECT (it stays unserved; any later version carrying the same signals
|
|
53
53
|
* is refused without a new row).
|
|
54
|
+
* - A hold from a workspace in its first fortnight also asks for an
|
|
55
|
+
* automatic `security` hold on the workspace, the site and the publishing
|
|
56
|
+
* account (`page-security-hold.ts`, AGL-3450), which the console places.
|
|
54
57
|
* - Keyed on the SIGNALS, as the send seam's rows are: a composed page
|
|
55
58
|
* carries per-render values (dates, collection rows) that no content hash
|
|
56
59
|
* would survive, while what makes it phishing does not change between
|
|
@@ -58,12 +61,16 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
58
61
|
*
|
|
59
62
|
* ## Tiers
|
|
60
63
|
*
|
|
61
|
-
* `signalsThatHold`: a lookalike link or embed
|
|
62
|
-
* credential field
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
* for
|
|
64
|
+
* `signalsThatHold`: a lookalike link or embed, an author-defined
|
|
65
|
+
* credential field and a link to a host Google Web Risk lists
|
|
66
|
+
* (`web-risk-link`, AGL-3451) hold for EVERY workspace; a brand's call to
|
|
67
|
+
* action or lure, and a call to action that leaves the site beside a lure,
|
|
68
|
+
* only for a workspace in its first fortnight. The workspace's documents are
|
|
69
|
+
* read only when something was found, so a clean page costs no read for
|
|
70
|
+
* this. The page's foreign hosts are looked up first, against a cache
|
|
71
|
+
* (`web-risk.ts`), and noted beside the version it serves so the daily
|
|
72
|
+
* re-check can look again: a harvester is often listed only after it is
|
|
73
|
+
* published. A lookup that fails finds nothing, so it never holds a page.
|
|
67
74
|
*
|
|
68
75
|
* Fails CLOSED, unlike the send path: a page the pure screen flagged whose
|
|
69
76
|
* review cannot finish — the workspace read, the row write — is answered
|
|
@@ -81,17 +88,21 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
81
88
|
* {@link reviewSiteRedirect} before it serves one. Same screen
|
|
82
89
|
* (`screenSiteRedirect`), same tiers, same row and the same staff decision:
|
|
83
90
|
* a held rule does not fire, and is filed as a `page` hold on its rule's
|
|
84
|
-
* document.
|
|
91
|
+
* document. Its destination is looked up against the reputation list too
|
|
92
|
+
* (AGL-3451), so a redirect to a listed site holds for every workspace.
|
|
85
93
|
*=========================================*/ import { ABUSE_REPORT_COLLECTION } from "@aglyn/aglyn/app-utils/abuse-report";
|
|
86
94
|
import { heldPageConsolePath, heldPageDetails, heldPageLabel, heldPageVisitorSentence } from "@aglyn/shared-util-email/held-page";
|
|
87
95
|
import { screenHostedPage, screenSiteRedirect } from "@aglyn/shared-util-email/hosted-page-screen";
|
|
88
96
|
import { lookalikeBrandForHost, phishingScreenBrandLabel, describePhishingScreenSignals, isYoungWorkspaceAge, signalsThatHold } from "@aglyn/shared-util-email/outbound-phishing-screen";
|
|
97
|
+
import { foreignHostsForReputation, webRiskSignals } from "@aglyn/shared-util-email/link-reputation";
|
|
89
98
|
import { FieldValue } from "firebase-admin/firestore";
|
|
90
99
|
import firebaseAdmin from "./firebase-admin.js";
|
|
91
100
|
import { describeHeldPage } from "./held-page-subject.js";
|
|
92
101
|
import { notifyRiskEvent } from "./risk-notice.js";
|
|
93
102
|
import { orgAgeDays } from "./org-age.js";
|
|
103
|
+
import { requestPageSecurityHold } from "./page-security-hold.js";
|
|
94
104
|
import { getHostDocAdmin, getOrgForHost } from "./organizations.js";
|
|
105
|
+
import { lookupHostReputation, platformReputationExclusions } from "./web-risk.js";
|
|
95
106
|
import { canonicalJson, fileOutboundHold, flaggedHostOf, heldOutboundReference, heldOutboundReviewId, outboundContentHash, workspaceScreenIdentity } from "./outbound-send-review.js";
|
|
96
107
|
/** Where the last version a page served clean is noted: a hint, re-screened before use. */ export const PAGE_REVIEW_SUBCOLLECTION = 'pageReviews';
|
|
97
108
|
/** The review row's id for a page and the signals that held. */ export function pageReviewId(hostId, screenId, signals) {
|
|
@@ -105,10 +116,53 @@ const pageMemo = new Map();
|
|
|
105
116
|
/** The version each page last served clean, as this process last wrote it. */ const servedMemo = new Map();
|
|
106
117
|
/** Lookalike hosts this process already flagged for an established page, and when. */ const flaggedMemo = new Map();
|
|
107
118
|
const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
119
|
+
/**
|
|
120
|
+
* The foreign hosts each reviewed page version links to (AGL-3451), for
|
|
121
|
+
* {@link recordServedPageVersion} to note beside the version it served, which
|
|
122
|
+
* is what the daily link re-check walks. Bounded: a process that reviews more
|
|
123
|
+
* pages than this starts again.
|
|
124
|
+
*/ const reviewedForeignHosts = new Map();
|
|
125
|
+
const REVIEWED_FOREIGN_HOSTS_MAX = 10000;
|
|
108
126
|
/** Test seam: forget what this process learned. */ export function resetHostedPageReviewMemoForTests() {
|
|
109
127
|
pageMemo.clear();
|
|
110
128
|
servedMemo.clear();
|
|
111
129
|
flaggedMemo.clear();
|
|
130
|
+
reviewedForeignHosts.clear();
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Every foreign host the page links to, and the ones Google Web Risk lists
|
|
134
|
+
* (AGL-3451). Foreign before the workspace is known: not the platform's
|
|
135
|
+
* own, not a brand's own domain, not a common social link. Never throws; a
|
|
136
|
+
* lookup that failed lists nothing.
|
|
137
|
+
*/ async function pageLinkReputation(linkHosts) {
|
|
138
|
+
// Runs before the review's fail-closed `try`, so it must not throw: an
|
|
139
|
+
// answer it cannot give is no listing, never a reason to hold.
|
|
140
|
+
try {
|
|
141
|
+
const hosts = foreignHostsForReputation(linkHosts, {
|
|
142
|
+
excludeDomains: platformReputationExclusions()
|
|
143
|
+
});
|
|
144
|
+
if (!hosts.length) return {
|
|
145
|
+
hosts,
|
|
146
|
+
signals: []
|
|
147
|
+
};
|
|
148
|
+
const answer = await lookupHostReputation(hosts);
|
|
149
|
+
return {
|
|
150
|
+
hosts,
|
|
151
|
+
signals: webRiskSignals(answer.hits)
|
|
152
|
+
};
|
|
153
|
+
} catch (error) {
|
|
154
|
+
console.warn('[page-review] link reputation could not be read — no listing assumed', error);
|
|
155
|
+
return {
|
|
156
|
+
hosts: [],
|
|
157
|
+
signals: []
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/** Is this host one of the workspace's own? */ function isOwnHost(host, ownDomains) {
|
|
162
|
+
return (ownDomains != null ? ownDomains : []).some((own)=>{
|
|
163
|
+
const domain = String(own != null ? own : '').trim().toLowerCase();
|
|
164
|
+
return Boolean(domain) && (host === domain || host.endsWith(`.${domain}`));
|
|
165
|
+
});
|
|
112
166
|
}
|
|
113
167
|
/**
|
|
114
168
|
* The subject a row already stored, or a fresh description (AGL-3374). A row
|
|
@@ -132,11 +186,21 @@ const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
|
132
186
|
* Screen one page as a visitor would receive it, and say whether it may be
|
|
133
187
|
* served. See the module header.
|
|
134
188
|
*/ export async function reviewHostedPage(request) {
|
|
135
|
-
var _request_nowMs;
|
|
189
|
+
var _request_extraSignals, _request_nowMs;
|
|
136
190
|
const found = screenHostedPage({
|
|
137
191
|
nodes: request.nodes
|
|
138
192
|
});
|
|
139
|
-
|
|
193
|
+
// Every foreign host it points at, against the reputation list
|
|
194
|
+
// (AGL-3451): a harvester known to be bad anywhere holds however plain the
|
|
195
|
+
// page around it is. Strong, so it holds at any workspace age.
|
|
196
|
+
const reputation = await pageLinkReputation(found.linkHosts);
|
|
197
|
+
if (reviewedForeignHosts.size >= REVIEWED_FOREIGN_HOSTS_MAX) reviewedForeignHosts.clear();
|
|
198
|
+
reviewedForeignHosts.set(`${request.hostId}/${request.screenId}/${request.versionId}`, reputation.hosts);
|
|
199
|
+
const listed = [
|
|
200
|
+
...reputation.signals,
|
|
201
|
+
...(_request_extraSignals = request.extraSignals) != null ? _request_extraSignals : []
|
|
202
|
+
];
|
|
203
|
+
if (!found.signals.length && !listed.length) return {
|
|
140
204
|
outcome: 'serve'
|
|
141
205
|
};
|
|
142
206
|
const nowMs = (_request_nowMs = request.nowMs) != null ? _request_nowMs : Date.now();
|
|
@@ -160,6 +224,11 @@ const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
|
160
224
|
const verdict = screenHostedPage(_extends({
|
|
161
225
|
nodes: request.nodes
|
|
162
226
|
}, identity));
|
|
227
|
+
// A listing of the workspace's own host is not a link away from it.
|
|
228
|
+
const screened = [
|
|
229
|
+
...verdict.signals,
|
|
230
|
+
...listed.filter((signal)=>!('host' in signal) || !isOwnHost(signal.host, identity.ownDomains))
|
|
231
|
+
];
|
|
163
232
|
const ageDays = orgAgeDays(org == null ? void 0 : org.createdAt, nowMs);
|
|
164
233
|
// Every workspace is screened, however old: an established account can
|
|
165
234
|
// be compromised, and a compromised account publishing a lure is the
|
|
@@ -174,7 +243,7 @@ const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
|
174
243
|
// - content ALREADY LIVE keeps serving, and is flagged to staff as
|
|
175
244
|
// urgent, who lock the site if it is impersonation.
|
|
176
245
|
if (!isYoungWorkspaceAge(ageDays)) {
|
|
177
|
-
const strong = signalsThatHold(
|
|
246
|
+
const strong = signalsThatHold(screened, {
|
|
178
247
|
ageDays
|
|
179
248
|
});
|
|
180
249
|
if (!strong.length) return {
|
|
@@ -198,7 +267,7 @@ const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
|
198
267
|
};
|
|
199
268
|
}
|
|
200
269
|
}
|
|
201
|
-
const signals = signalsThatHold(
|
|
270
|
+
const signals = signalsThatHold(screened, {
|
|
202
271
|
ageDays
|
|
203
272
|
});
|
|
204
273
|
if (!signals.length) return {
|
|
@@ -272,6 +341,25 @@ const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
|
272
341
|
url,
|
|
273
342
|
reportedHostname: flagged
|
|
274
343
|
});
|
|
344
|
+
// A hold from a workspace in its first fortnight also holds the
|
|
345
|
+
// workspace, the site and the account that published it (AGL-3450).
|
|
346
|
+
if (state === 'held') {
|
|
347
|
+
await requestPageSecurityHold({
|
|
348
|
+
orgId: orgId != null ? orgId : '',
|
|
349
|
+
org,
|
|
350
|
+
hostId: request.hostId,
|
|
351
|
+
screenId: request.screenId,
|
|
352
|
+
versionId: request.versionId,
|
|
353
|
+
reviewId,
|
|
354
|
+
reference,
|
|
355
|
+
signals,
|
|
356
|
+
ageDays,
|
|
357
|
+
pageLabel: label,
|
|
358
|
+
pageUrl: url,
|
|
359
|
+
siteName: typeof (host == null ? void 0 : host['name']) === 'string' ? host['name'] : null,
|
|
360
|
+
nowMs
|
|
361
|
+
});
|
|
362
|
+
}
|
|
275
363
|
pageMemo.set(reviewId, {
|
|
276
364
|
state,
|
|
277
365
|
atMs: nowMs
|
|
@@ -288,7 +376,10 @@ const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
|
288
376
|
// review that could not finish has not cleared it. Not remembered, so
|
|
289
377
|
// the next render reviews it again.
|
|
290
378
|
console.error('[page-review] a flagged page could not be reviewed — holding it', error);
|
|
291
|
-
const reviewId = pageReviewId(request.hostId, request.screenId,
|
|
379
|
+
const reviewId = pageReviewId(request.hostId, request.screenId, [
|
|
380
|
+
...found.signals,
|
|
381
|
+
...listed
|
|
382
|
+
]);
|
|
292
383
|
return {
|
|
293
384
|
outcome: 'held',
|
|
294
385
|
reviewId,
|
|
@@ -317,7 +408,10 @@ const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
|
317
408
|
source: request.source,
|
|
318
409
|
destination: request.destination
|
|
319
410
|
});
|
|
320
|
-
|
|
411
|
+
// Where it sends visitors, against the reputation list (AGL-3451): a
|
|
412
|
+
// listed destination holds for every workspace, as a listed link does.
|
|
413
|
+
const reputation = await pageLinkReputation(found.linkHosts);
|
|
414
|
+
if (!found.signals.length && !reputation.signals.length) return {
|
|
321
415
|
outcome: 'serve'
|
|
322
416
|
};
|
|
323
417
|
const nowMs = (_request_nowMs = request.nowMs) != null ? _request_nowMs : Date.now();
|
|
@@ -340,8 +434,12 @@ const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
|
340
434
|
source: request.source,
|
|
341
435
|
destination: request.destination
|
|
342
436
|
}, identity));
|
|
437
|
+
const screened = [
|
|
438
|
+
...verdict.signals,
|
|
439
|
+
...reputation.signals.filter((signal)=>!('host' in signal) || !isOwnHost(signal.host, identity.ownDomains))
|
|
440
|
+
];
|
|
343
441
|
const ageDays = orgAgeDays(org == null ? void 0 : org.createdAt, nowMs);
|
|
344
|
-
const signals = signalsThatHold(
|
|
442
|
+
const signals = signalsThatHold(screened, {
|
|
345
443
|
ageDays
|
|
346
444
|
});
|
|
347
445
|
if (!signals.length) return {
|
|
@@ -407,7 +505,10 @@ const FLAGGED_MEMO_TTL_MS = 60 * 60000;
|
|
|
407
505
|
} catch (error) {
|
|
408
506
|
// Closed, as a page is: the screen found a signal and nothing cleared it.
|
|
409
507
|
console.error('[page-review] a flagged redirect could not be reviewed — holding it', error);
|
|
410
|
-
const reviewId = redirectReviewId(request.hostId, request.ruleId,
|
|
508
|
+
const reviewId = redirectReviewId(request.hostId, request.ruleId, [
|
|
509
|
+
...found.signals,
|
|
510
|
+
...reputation.signals
|
|
511
|
+
]);
|
|
411
512
|
return {
|
|
412
513
|
outcome: 'held',
|
|
413
514
|
reviewId,
|
|
@@ -549,19 +650,29 @@ async function isAlreadyLive(hostId, screenId, versionId, nowMs) {
|
|
|
549
650
|
* after that, however often the page is rendered.
|
|
550
651
|
*/ export async function recordServedPageVersion(hostId, screenId, versionId) {
|
|
551
652
|
const key = `${hostId}/${screenId}`;
|
|
552
|
-
|
|
653
|
+
// The foreign hosts this version links to, as its review found them
|
|
654
|
+
// (AGL-3451): noted beside it so the daily link re-check can walk them.
|
|
655
|
+
const foreignHosts = reviewedForeignHosts.get(`${key}/${versionId}`);
|
|
656
|
+
const memoValue = foreignHosts ? `${versionId}|${foreignHosts.join(',')}` : versionId;
|
|
657
|
+
if (!versionId || servedMemo.get(key) === memoValue) return;
|
|
553
658
|
try {
|
|
554
659
|
const ref = pageReviewRef(hostId, screenId);
|
|
555
660
|
const snapshot = await ref.get();
|
|
556
|
-
|
|
557
|
-
|
|
661
|
+
const versionMoved = snapshot.get('servedVersionId') !== versionId;
|
|
662
|
+
const stored = snapshot.get('foreignHosts');
|
|
663
|
+
const hostsMoved = foreignHosts !== undefined && (Array.isArray(stored) ? stored.join(',') : '') !== foreignHosts.join(',');
|
|
664
|
+
if (versionMoved || hostsMoved) {
|
|
665
|
+
await ref.set(_extends({}, versionMoved ? {
|
|
558
666
|
servedVersionId: versionId,
|
|
559
667
|
servedAtMs: Date.now()
|
|
560
|
-
}, {
|
|
668
|
+
} : {}, foreignHosts ? {
|
|
669
|
+
foreignHosts,
|
|
670
|
+
foreignHostCount: foreignHosts.length
|
|
671
|
+
} : {}), {
|
|
561
672
|
merge: true
|
|
562
673
|
});
|
|
563
674
|
}
|
|
564
|
-
servedMemo.set(key,
|
|
675
|
+
servedMemo.set(key, memoValue);
|
|
565
676
|
} catch (error) {
|
|
566
677
|
console.warn('[page-review] the served version could not be noted', error);
|
|
567
678
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/hosted-page-review.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 * HELD FOR REVIEW: a published page (AGL-3362).\n *\n * ## Why the check sits where a page is COMPOSED, not where it is published\n *\n * A publish is a browser write. The besigner toolbar, the versions panel,\n * the screen details page, page-from-template, the layout and component\n * besigners and the form besigner each move a pointer (`versionId`, the\n * host's `screens` map, a component's own `nodes`) straight from the\n * client SDK; the scheduled-publish beat moves it from the server; an\n * experiment serves a version no pointer names; and an author may rewrite\n * the LIVE version document itself without moving any pointer at all. A\n * check on any one of those writes is a check the next one walks around.\n *\n * They all meet in one place: `composeScreenNodes` (`@aglyn/tenant-runtime`),\n * which every published render, the password unlock, the collection and\n * product templates and every experiment variant go through, and which\n * returns the page exactly as a visitor will receive it — the screen, its\n * layout chrome, its grafted components and its forms. So the screen is read\n * there, and a held page is one that is never composed for a visitor. For a\n * visitor, \"publish\" is the first render after the pointer moved; this is\n * that moment.\n *\n * ## What a hold does\n *\n * - The version is not served. The last version this page served clean\n * ({@link servedPageVersion}) is composed instead — screened again, since\n * a version document can be edited in place — and if there is none, or it\n * holds too, the page is not found. A first publish that holds therefore\n * serves nothing.\n * - One review row per (page, signal set) lands in the abuse queue at\n * `/admin/abuse-reports`, the same `phishing` row a held email files\n * (`fileOutboundHold`), with `heldSend.kind: 'page'`, the page's URL and\n * the held version. Staff dismiss it to RELEASE (the admin route drops the\n * site's cache and the next render serves it) or mark it actioned to\n * REJECT (it stays unserved; any later version carrying the same signals\n * is refused without a new row).\n * - Keyed on the SIGNALS, as the send seam's rows are: a composed page\n * carries per-render values (dates, collection rows) that no content hash\n * would survive, while what makes it phishing does not change between\n * renders.\n *\n * ## Tiers\n *\n * `signalsThatHold`: a lookalike link or embed and an author-defined\n * credential field hold for EVERY workspace; a brand's call to action or\n * lure, and a call to action that leaves the site beside a lure, only for a\n * workspace in its first fortnight. The workspace's documents are read only\n * when the pure screen has found something, so a clean page costs no read\n * for this.\n *\n * Fails CLOSED, unlike the send path: a page the pure screen flagged whose\n * review cannot finish — the workspace read, the row write — is answered\n * `held`, and the composer serves its last clean version or nothing. The\n * answer is not remembered, so the next render reviews it again. Composition\n * itself reads the store, so an outage here is an outage on the render\n * already, and the only cost of not serving a page the screen flagged is a\n * false positive's wait; serving it is the phishing page this exists to\n * stop. A page the screen found nothing on never reaches this.\n *\n * ## Site redirects\n *\n * A redirect rule that sends a path off the site is a page whose one call to\n * action fires on arrival, so the redirects plugin asks\n * {@link reviewSiteRedirect} before it serves one. Same screen\n * (`screenSiteRedirect`), same tiers, same row and the same staff decision:\n * a held rule does not fire, and is filed as a `page` hold on its rule's\n * document.\n *=========================================*/\n\nimport { ABUSE_REPORT_COLLECTION } from '@aglyn/aglyn/app-utils/abuse-report'\nimport {\n heldPageConsolePath,\n heldPageDetails,\n heldPageLabel,\n heldPageVisitorSentence,\n type HeldPageSubject,\n} from '@aglyn/shared-util-email/held-page'\nimport { screenHostedPage, screenSiteRedirect } from '@aglyn/shared-util-email/hosted-page-screen'\nimport {\n lookalikeBrandForHost,\n phishingScreenBrandLabel,\n type PhishingScreenSignal,\n describePhishingScreenSignals,\n isYoungWorkspaceAge,\n signalsThatHold,\n} from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\nimport { describeHeldPage, type HostedPageContext } from './held-page-subject'\nimport { notifyRiskEvent } from './risk-notice'\nimport { orgAgeDays } from './org-age'\nimport { getHostDocAdmin, getOrgForHost } from './organizations'\nimport {\n canonicalJson,\n fileOutboundHold,\n flaggedHostOf,\n heldOutboundReference,\n heldOutboundReviewId,\n outboundContentHash,\n type HeldOutboundSendState,\n workspaceScreenIdentity,\n} from './outbound-send-review'\n\n/** Where the last version a page served clean is noted: a hint, re-screened before use. */\nexport const PAGE_REVIEW_SUBCOLLECTION = 'pageReviews'\n\nexport interface HostedPageReviewRequest {\n hostId: string\n screenId: string\n versionId: string\n /** The page as composed for a visitor. */\n nodes: unknown\n /** The host and org documents, when the caller already holds them. */\n host?: Record<string, unknown> | null\n org?: Record<string, unknown> | null\n orgId?: string | null\n nowMs?: number\n /**\n * What the composer knows about the page (AGL-3374): the screen document,\n * the template route it is rendering, the variant, and a way to read the\n * layouts and components composed into it. Read only when a row is filed,\n * to name the page — never to decide whether it serves.\n */\n page?: HostedPageContext | null\n}\n\nexport type HostedPageReviewOutcome =\n | { outcome: 'serve' }\n | { outcome: 'held' | 'rejected'; reviewId: string; reference: string }\n\n/** The review row's id for a page and the signals that held. */\nexport function pageReviewId(\n hostId: string,\n screenId: string,\n signals: readonly PhishingScreenSignal[],\n): string {\n const key = signals\n .map((signal) => canonicalJson(signal))\n .sort()\n .join('\\n')\n return heldOutboundReviewId(`hosts/${hostId}/screens/${screenId}`, outboundContentHash([key]))\n}\n\n/** How long this process trusts a page row's state — the send seam's minute. */\nconst PAGE_MEMO_TTL_MS = 60_000\nconst pageMemo = new Map<string, { state: HeldOutboundSendState; atMs: number }>()\n/** The version each page last served clean, as this process last wrote it. */\nconst servedMemo = new Map<string, string>()\n/** Lookalike hosts this process already flagged for an established page, and when. */\nconst flaggedMemo = new Map<string, number>()\nconst FLAGGED_MEMO_TTL_MS = 60 * 60_000\n\n/** Test seam: forget what this process learned. */\nexport function resetHostedPageReviewMemoForTests(): void {\n pageMemo.clear()\n servedMemo.clear()\n flaggedMemo.clear()\n}\n\n/**\n * The subject a row already stored, or a fresh description (AGL-3374). A row\n * that names its page is not described again, so the reads the description\n * may make are paid once per row, not once per render.\n */\nasync function subjectForRow(\n reviewId: string,\n describe: () => Promise<HeldPageSubject>,\n): Promise<HeldPageSubject> {\n const stored = await firebaseAdmin\n .app()\n .firestore()\n .collection(ABUSE_REPORT_COLLECTION)\n .doc(reviewId)\n .get()\n .then((row) => storedSubject(row.get('heldPage')))\n .catch(() => null)\n return stored ?? describe()\n}\n\n/** A row's stored subject, when it has one. */\nfunction storedSubject(heldPage: unknown): HeldPageSubject | null {\n const subject = (heldPage as { subject?: HeldPageSubject } | null | undefined)?.subject\n return subject && typeof subject === 'object' && subject.screenId ? subject : null\n}\n\n/** The row's first line, naming the page and where it was seen. */\nfunction pageHeadline(subject: HeldPageSubject, siteName: string): string {\n return [`${heldPageLabel(subject)} of ${siteName}.`, ...heldPageDetails(subject)].join(' ')\n}\n\n/**\n * Screen one page as a visitor would receive it, and say whether it may be\n * served. See the module header.\n */\nexport async function reviewHostedPage(\n request: HostedPageReviewRequest,\n): Promise<HostedPageReviewOutcome> {\n const found = screenHostedPage({ nodes: request.nodes })\n if (!found.signals.length) return { outcome: 'serve' }\n\n const nowMs = request.nowMs ?? Date.now()\n try {\n const [host, owner] = await Promise.all([\n request.host !== undefined ? request.host : getHostDocAdmin(request.hostId),\n request.org !== undefined\n ? { orgId: request.orgId ?? null, org: request.org }\n : getOrgForHost(request.hostId),\n ])\n const org = (owner?.org as Record<string, unknown> | null | undefined) ?? null\n const orgId = owner?.orgId ?? null\n // Again, now knowing whose page it is: a brand in the workspace's own\n // name or domain is its own, and a link to its own site is not away.\n const identity = workspaceScreenIdentity({ org, host })\n const verdict = screenHostedPage({ nodes: request.nodes, ...identity })\n const ageDays = orgAgeDays((org as { createdAt?: unknown } | null)?.createdAt, nowMs)\n // Every workspace is screened, however old: an established account can\n // be compromised, and a compromised account publishing a lure is the\n // same harm as a new one. What differs is what a hold may take DOWN.\n // Holding content that is already live serves its last clean version or\n // nothing, and on a real business's home page that is an outage the\n // screen caused (aglyn.com, 2026-09-28, a page that had served clean\n // until a rule changed). So for an established workspace:\n // - NEW content (a new version of a live page, or a page that has\n // never been live) holds, exactly as for a young workspace; the live\n // page keeps serving its last clean version, or the new page waits;\n // - content ALREADY LIVE keeps serving, and is flagged to staff as\n // urgent, who lock the site if it is impersonation.\n if (!isYoungWorkspaceAge(ageDays)) {\n const strong = signalsThatHold(verdict.signals, { ageDays })\n if (!strong.length) return { outcome: 'serve' }\n if (await isAlreadyLive(request.hostId, request.screenId, request.versionId, nowMs)) {\n await flagLivePage({\n hostId: request.hostId,\n screenId: request.screenId,\n versionId: request.versionId,\n orgId,\n host,\n signals: strong,\n nowMs,\n page: request.page ?? null,\n identity,\n })\n return { outcome: 'serve' }\n }\n }\n const signals = signalsThatHold(verdict.signals, { ageDays })\n if (!signals.length) return { outcome: 'serve' }\n\n const reviewId = pageReviewId(request.hostId, request.screenId, signals)\n const reference = heldOutboundReference(reviewId)\n const memo = pageMemo.get(reviewId)\n if (memo && nowMs - memo.atMs < PAGE_MEMO_TTL_MS) {\n return memo.state === 'released'\n ? { outcome: 'serve' }\n : { outcome: memo.state === 'rejected' ? 'rejected' : 'held', reviewId, reference }\n }\n // The page by its real name and route (AGL-3374): a template, a list,\n // a variant, or a page whose flagged content lives in its layout.\n const subject = await subjectForRow(reviewId, async () =>\n describeHeldPage({\n hostId: request.hostId,\n screenId: request.screenId,\n versionId: request.versionId,\n host,\n page: request.page,\n signals,\n identity,\n live: false,\n previousVersionId: await servedPageVersion(request.hostId, request.screenId),\n }),\n )\n const url = subject.entryUrl ?? subject.url\n const flagged = flaggedHostOf(signals)\n const siteName =\n typeof host?.['name'] === 'string' && host['name'] ? `\"${host['name']}\"` : 'a site'\n const label = heldPageLabel(subject)\n const state = await fileOutboundHold({\n reviewId,\n heldSend: {\n kind: 'page',\n path: `hosts/${request.hostId}/screens/${request.screenId}`,\n hostId: request.hostId,\n orgId,\n contentHash: outboundContentHash([signals]),\n subject: label.slice(0, 300),\n fromName: null,\n signals,\n state: 'held',\n heldAtMs: nowMs,\n ageDays,\n },\n extra: {\n heldPage: { screenId: request.screenId, versionId: request.versionId, url, subject },\n },\n headline:\n `Held ${pageHeadline(subject, siteName)} Version ${request.versionId}, from a ` +\n `workspace ${ageDays ?? '?'} day(s) old. ${heldPageVisitorSentence(subject)}`,\n alertTitle: 'Published page held for review — possible phishing',\n alertBody: `${label.charAt(0).toUpperCase()}${label.slice(1)} was held before it went live.`,\n // The owners' words for it, and where they fix it (AGL-3368, AGL-3374).\n item: { label, path: heldPageConsolePath(subject, request.hostId) },\n page: subject,\n // The page itself is what was reported; the flagged host, when there\n // is one, is named in the details and on `reportedHostname`.\n url,\n reportedHostname: flagged,\n })\n pageMemo.set(reviewId, { state, atMs: nowMs })\n return state === 'released'\n ? { outcome: 'serve' }\n : { outcome: state === 'rejected' ? 'rejected' : 'held', reviewId, reference }\n } catch (error) {\n // Closed: the screen has already found a signal on this page, and a\n // review that could not finish has not cleared it. Not remembered, so\n // the next render reviews it again.\n console.error('[page-review] a flagged page could not be reviewed — holding it', error)\n const reviewId = pageReviewId(request.hostId, request.screenId, found.signals)\n return { outcome: 'held', reviewId, reference: heldOutboundReference(reviewId) }\n }\n}\n\nexport interface SiteRedirectReviewRequest {\n hostId: string\n /** The rule's document id under `hosts/{hostId}/redirects`. */\n ruleId: string\n /** The path, or the pattern, the rule answers. */\n source: string\n /** Where it sends the visitor, after any `$n` substitution. */\n destination: string\n /** The host and org documents, when the caller already holds them. */\n host?: Record<string, unknown> | null\n org?: Record<string, unknown> | null\n orgId?: string | null\n nowMs?: number\n}\n\n/** The review row's id for a redirect rule and the signals that held. */\nexport function redirectReviewId(\n hostId: string,\n ruleId: string,\n signals: readonly PhishingScreenSignal[],\n): string {\n const key = signals\n .map((signal) => canonicalJson(signal))\n .sort()\n .join('\\n')\n return heldOutboundReviewId(`hosts/${hostId}/redirects/${ruleId}`, outboundContentHash([key]))\n}\n\n/**\n * Screen one redirect rule before it sends a visitor off the site\n * (AGL-3447), and say whether it may fire. See the module header.\n *\n * Every workspace is screened and the tiers decide, as for a page: a\n * destination that wears a brand holds for all of them, a lure path sent\n * off the site only for a workspace in its first fortnight. A held rule is\n * filed once per (rule, signal set) and decided by staff on that row:\n * dismissed, it fires; actioned, it never does with those signals.\n */\nexport async function reviewSiteRedirect(\n request: SiteRedirectReviewRequest,\n): Promise<HostedPageReviewOutcome> {\n const found = screenSiteRedirect({ source: request.source, destination: request.destination })\n if (!found.signals.length) return { outcome: 'serve' }\n\n const nowMs = request.nowMs ?? Date.now()\n try {\n const [host, owner] = await Promise.all([\n request.host !== undefined ? request.host : getHostDocAdmin(request.hostId),\n request.org !== undefined\n ? { orgId: request.orgId ?? null, org: request.org }\n : getOrgForHost(request.hostId),\n ])\n const org = (owner?.org as Record<string, unknown> | null | undefined) ?? null\n const orgId = owner?.orgId ?? null\n const identity = workspaceScreenIdentity({ org, host })\n const verdict = screenSiteRedirect({\n source: request.source,\n destination: request.destination,\n ...identity,\n })\n const ageDays = orgAgeDays((org as { createdAt?: unknown } | null)?.createdAt, nowMs)\n const signals = signalsThatHold(verdict.signals, { ageDays })\n if (!signals.length) return { outcome: 'serve' }\n\n const reviewId = redirectReviewId(request.hostId, request.ruleId, signals)\n const reference = heldOutboundReference(reviewId)\n const memo = pageMemo.get(reviewId)\n if (memo && nowMs - memo.atMs < PAGE_MEMO_TTL_MS) {\n return memo.state === 'released'\n ? { outcome: 'serve' }\n : { outcome: memo.state === 'rejected' ? 'rejected' : 'held', reviewId, reference }\n }\n const source = request.source.slice(0, 200)\n const destination = request.destination.slice(0, 500)\n const label = `the redirect from ${source}`\n const siteName =\n typeof host?.['name'] === 'string' && host['name'] ? `\"${host['name']}\"` : 'a site'\n const [subdomainHost, customDomain] = identity.ownDomains ?? []\n const siteHost = customDomain || subdomainHost\n const state = await fileOutboundHold({\n reviewId,\n heldSend: {\n kind: 'page',\n path: `hosts/${request.hostId}/redirects/${request.ruleId}`,\n hostId: request.hostId,\n orgId,\n contentHash: outboundContentHash([signals]),\n subject: label.slice(0, 300),\n fromName: null,\n signals,\n state: 'held',\n heldAtMs: nowMs,\n ageDays,\n },\n headline:\n `Held ${label} of ${siteName}, which sends visitors to ${destination}, from a ` +\n `workspace ${ageDays ?? '?'} day(s) old. The rule does not fire until this is decided.`,\n alertTitle: 'Site redirect held for review — possible phishing',\n alertBody: `The redirect from ${source} was held before it sent anyone off the site.`,\n // Where the owners fix it: the site's Redirects page.\n item: { label, path: `/${request.hostId}/redirects` },\n url: siteHost && source.startsWith('/') ? `https://${siteHost}${source}` : destination,\n reportedHostname: flaggedHostOf(signals),\n })\n pageMemo.set(reviewId, { state, atMs: nowMs })\n return state === 'released'\n ? { outcome: 'serve' }\n : { outcome: state === 'rejected' ? 'rejected' : 'held', reviewId, reference }\n } catch (error) {\n // Closed, as a page is: the screen found a signal and nothing cleared it.\n console.error('[page-review] a flagged redirect could not be reviewed — holding it', error)\n const reviewId = redirectReviewId(request.hostId, request.ruleId, found.signals)\n return { outcome: 'held', reviewId, reference: heldOutboundReference(reviewId) }\n }\n}\n\nfunction pageReviewRef(hostId: string, screenId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection(PAGE_REVIEW_SUBCOLLECTION)\n .doc(screenId)\n}\n\n/**\n * Is this version of the page already what visitors receive? It is when it\n * is the version the page last served clean, or when the page has no record\n * at all and is not new: it went live before the screen existed. A page\n * created in the last {@link NEW_PAGE_DAYS} days with no record has never\n * been live, so holding it takes nothing down.\n */\nconst NEW_PAGE_DAYS = 7\nasync function isAlreadyLive(\n hostId: string,\n screenId: string,\n versionId: string,\n nowMs: number,\n): Promise<boolean> {\n const lastClean = await servedPageVersion(hostId, screenId)\n if (lastClean) return lastClean === versionId\n try {\n const screen = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('screens')\n .doc(screenId)\n .get()\n const created = screen.get('createdAt') as { toMillis?: () => number } | number | undefined\n const createdMs =\n typeof created === 'number' ? created : typeof created?.toMillis === 'function' ? created.toMillis() : null\n // No readable creation time: an old page, so live.\n return createdMs === null || nowMs - createdMs >= NEW_PAGE_DAYS * 24 * 60 * 60 * 1000\n } catch {\n return true\n }\n}\n\n/**\n * A page ALREADY LIVE carries a strong signal: file one urgent abuse row for\n * it (keyed on the page and its signals, so a busy page is one row) and, the\n * first time, tell staff and the owners through the `page-flagged` notice.\n * The page keeps serving; staff lock the site if it is impersonation or the\n * account looks compromised. Once per page and signal set per process.\n */\nasync function flagLivePage(input: {\n hostId: string\n screenId: string\n versionId: string\n orgId: string | null\n host: Record<string, unknown> | null\n signals: readonly PhishingScreenSignal[]\n nowMs: number\n page?: HostedPageContext | null\n identity?: ReturnType<typeof workspaceScreenIdentity>\n}): Promise<void> {\n const key = `${input.hostId}\\n${input.screenId}\\n${input.signals.map((signal) => canonicalJson(signal)).sort().join('\\n')}`\n const at = flaggedMemo.get(key)\n if (at !== undefined && input.nowMs - at < FLAGGED_MEMO_TTL_MS) return\n flaggedMemo.set(key, input.nowMs)\n try {\n const reviewId = pageReviewId(input.hostId, `${input.screenId}/live`, input.signals)\n const reference = heldOutboundReference(reviewId)\n const evidence = describePhishingScreenSignals(input.signals).join(' ')\n const flagged = flaggedHostOf(input.signals)\n const ref = firebaseAdmin.app().firestore().collection(ABUSE_REPORT_COLLECTION).doc(reviewId)\n const existing = await ref.get()\n const first = !existing.exists\n // Named once, when the row is new (AGL-3374).\n const subject =\n (existing.exists ? storedSubject(existing.get('heldPage')) : null) ??\n (await describeHeldPage({\n hostId: input.hostId,\n screenId: input.screenId,\n versionId: input.versionId,\n host: input.host,\n page: input.page,\n signals: input.signals,\n identity: input.identity ?? workspaceScreenIdentity({ host: input.host }),\n live: true,\n previousVersionId: null,\n }))\n const url = subject.entryUrl ?? subject.url\n const siteName =\n typeof input.host?.['name'] === 'string' && input.host['name']\n ? `\"${input.host['name']}\"`\n : 'a site'\n await ref.set(\n {\n reference,\n category: 'phishing',\n severity: 'urgent',\n source: 'outbound-screen',\n url,\n reportedHostname: flagged,\n hostId: input.hostId,\n orgId: input.orgId,\n details: [\n `LIVE: ${pageHeadline(subject, siteName)} It was flagged by the phishing screen and is still serving.`,\n evidence,\n 'Lock the site if it is impersonation or the account looks compromised; dismiss this if the content is theirs.',\n ].join('\\n'),\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n heldPage: { screenId: input.screenId, versionId: input.versionId, url, subject },\n riskNotice: { kind: 'page-flagged' },\n reportCount: FieldValue.increment(1),\n updatedAt: FieldValue.serverTimestamp(),\n ...(first ? { status: 'open', createdAt: FieldValue.serverTimestamp() } : {}),\n },\n { merge: true },\n )\n if (!first) return\n await notifyRiskEvent({\n kind: 'page-flagged',\n orgId: input.orgId,\n hostId: input.hostId,\n reviewId,\n reference,\n item: { label: heldPageLabel(subject), path: heldPageConsolePath(subject, input.hostId) },\n page: subject,\n staffEvidence: [...heldPageDetails(subject), evidence].join(' '),\n })\n } catch (error) {\n console.error('[page-review] a live page could not be flagged', error)\n }\n}\n\n/**\n * The version this page last served clean, or null. A HINT, not a\n * clearance: the caller composes and screens it again before serving it,\n * because a version document can be edited after it was served.\n */\nexport async function servedPageVersion(hostId: string, screenId: string): Promise<string | null> {\n try {\n const snapshot = await pageReviewRef(hostId, screenId).get()\n const value = snapshot.get('servedVersionId')\n return typeof value === 'string' && value ? value : null\n } catch {\n return null\n }\n}\n\n/**\n * Note that this page served `versionId` clean. One read the first time a\n * process renders a page, a write only when the version moved; nothing\n * after that, however often the page is rendered.\n */\nexport async function recordServedPageVersion(\n hostId: string,\n screenId: string,\n versionId: string,\n): Promise<void> {\n const key = `${hostId}/${screenId}`\n if (!versionId || servedMemo.get(key) === versionId) return\n try {\n const ref = pageReviewRef(hostId, screenId)\n const snapshot = await ref.get()\n if (snapshot.get('servedVersionId') !== versionId) {\n await ref.set({ servedVersionId: versionId, servedAtMs: Date.now() }, { merge: true })\n }\n servedMemo.set(key, versionId)\n } catch (error) {\n console.warn('[page-review] the served version could not be noted', error)\n }\n}\n\n/**\n * A domain a workspace attached that wears a brand (AGL-3356, AGL-3362):\n * filed in the abuse queue as an urgent `phishing` row for staff, not\n * refused. Two kinds, one rule:\n *\n * - `site` — a custom domain a site is served on (the attach route);\n * - `sending` — a custom domain a workspace sends email as, when it is\n * added and again when it verifies (`sending-domains.ts`);\n * - `link` — a link a merchant configured that a buyer or a server would\n * follow: a product's paid download or video hotlink, a supplier's order\n * webhook (AGL-3363). The link itself is refused where it is followed; this\n * files it, and tells the site's managers once ({@link notifyLookalikeLink}).\n *\n * Not refused, because the domain is the merchant's own registration and\n * the platform cannot tell a brand's own agency attaching `paypal-promo.com`\n * from a kit — but a brand's lookalike on a site or in a `From:` line is\n * exactly what staff look at first. The site's pages are still screened as\n * they are served, and mail FROM a lookalike domain is held at the send seam\n * for every workspace. The test is the phishing screen's own lookalike rule\n * (`lookalikeBrandForHost`), the one that holds a link in an email. One row\n * per (owner, kind, domain), so a re-attach or a re-verify counts rather than\n * re-alerts.\n *\n * Never throws: the write it rides on has already happened.\n */\nexport async function flagLookalikeDomain(input: {\n kind: 'site' | 'sending' | 'link'\n hostId: string | null\n orgId: string | null\n domain: string\n /** For a `link`: where it was configured, as staff read it. */\n where?: string\n}): Promise<'flagged' | 'clean' | 'failed'> {\n const domain = String(input.domain ?? '').trim().toLowerCase()\n const brand = lookalikeBrandForHost(domain)\n if (!brand) return 'clean'\n const label = phishingScreenBrandLabel(brand.id)\n const sending = input.kind === 'sending'\n const link = input.kind === 'link'\n try {\n const firestore = firebaseAdmin.app().firestore()\n const owner = sending\n ? `orgs/${input.orgId ?? ''}/sendingDomains`\n : link\n ? `hosts/${input.hostId ?? ''}/links`\n : `hosts/${input.hostId ?? ''}/cname`\n const reviewId = heldOutboundReviewId(owner, domain)\n const reference = heldOutboundReference(reviewId)\n const ref = firestore.collection(ABUSE_REPORT_COLLECTION).doc(reviewId)\n const first = !(await ref.get()).exists\n await ref.set(\n {\n reference,\n category: 'phishing',\n severity: 'urgent',\n source: 'outbound-screen',\n url: `https://${domain}/`,\n reportedHostname: domain,\n hostId: input.hostId,\n orgId: input.orgId,\n details: [\n sending\n ? `A workspace added ${domain} as a domain to send email from.`\n : link\n ? `A site configured a link to ${domain} (${input.where ?? 'a commerce link'}).`\n : `A site attached the custom domain ${domain}.`,\n `${domain} wears the ${label} name but is not ${label}'s domain.`,\n sending\n ? 'Email from it is held at the send seam for every workspace. Mark this actioned ' +\n 'and lock the workspace if it is impersonation; dismiss it if the brand is theirs.'\n : link\n ? 'Nobody is sent to it: the link is refused wherever it is followed. Mark this ' +\n 'actioned and lock the site if it is impersonation.'\n : 'Its pages are still screened as they are served. Mark this actioned ' +\n 'and lock the site if it is impersonation; dismiss it if the brand is theirs.',\n ].join('\\n'),\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n reportCount: FieldValue.increment(1),\n updatedAt: FieldValue.serverTimestamp(),\n ...(first ? { status: 'open', createdAt: FieldValue.serverTimestamp() } : {}),\n },\n { merge: true },\n )\n if (first && link) {\n await notifyLookalikeLink({\n hostId: input.hostId,\n orgId: input.orgId,\n domain,\n label,\n where: input.where ?? 'a commerce link',\n reference,\n reviewId,\n })\n } else if (first) {\n // The owners hear that the domain is waiting on a routine review — not\n // which name it resembles; staff get the brand and a link to the row.\n await notifyRiskEvent({\n kind: 'domain-flagged',\n orgId: input.orgId,\n hostId: input.hostId,\n reviewId,\n reference,\n item: {\n label: sending ? `the sending domain ${domain}` : `the custom domain ${domain}`,\n // Emails → Sending, or the site's Domain settings.\n path: sending ? '/org/emails/sending' : input.hostId ? `/${input.hostId}/admin/domain` : null,\n },\n staffEvidence:\n `${sending ? 'Sending domain' : 'Custom domain'} ${domain} looks like ${label}.`,\n })\n }\n return 'flagged'\n } catch (error) {\n console.error('[page-review] a lookalike domain could not be flagged', error)\n return 'failed'\n }\n}\n\n/**\n * Tell staff and the site's managers and the workspace's owners, once per\n * (site, domain), that a link the merchant configured was refused because it\n * wears another brand's name (AGL-3363), through the risk notice seam\n * (AGL-3368). The merchant reads the catalog's `link-blocked` words — what\n * was refused and how to fix it, never how the check works; staff get the\n * brand and a link to the row. Never throws.\n */\nexport async function notifyLookalikeLink(input: {\n hostId: string | null\n orgId?: string | null\n domain: string\n label: string\n where: string\n reference: string\n reviewId?: string | null\n}): Promise<void> {\n await notifyRiskEvent({\n kind: 'link-blocked',\n orgId: input.orgId ?? null,\n hostId: input.hostId,\n reviewId: input.reviewId ?? null,\n reference: input.reference,\n item: {\n label: `${input.where} pointing to ${input.domain}`,\n path: input.hostId ? `/${input.hostId}/products` : null,\n },\n staffEvidence:\n `A site configured ${input.where} to ${input.domain}, which looks like ${input.label}. ` +\n 'It is refused wherever it is followed.',\n }).catch(() => undefined)\n}\n\n/** A site's custom domain, through {@link flagLookalikeDomain}. */\nexport function flagLookalikeCustomDomain(input: {\n hostId: string\n orgId: string | null\n domain: string\n}): Promise<'flagged' | 'clean' | 'failed'> {\n return flagLookalikeDomain({ kind: 'site', ...input })\n}\n"],"names":["ABUSE_REPORT_COLLECTION","heldPageConsolePath","heldPageDetails","heldPageLabel","heldPageVisitorSentence","screenHostedPage","screenSiteRedirect","lookalikeBrandForHost","phishingScreenBrandLabel","describePhishingScreenSignals","isYoungWorkspaceAge","signalsThatHold","FieldValue","firebaseAdmin","describeHeldPage","notifyRiskEvent","orgAgeDays","getHostDocAdmin","getOrgForHost","canonicalJson","fileOutboundHold","flaggedHostOf","heldOutboundReference","heldOutboundReviewId","outboundContentHash","workspaceScreenIdentity","PAGE_REVIEW_SUBCOLLECTION","pageReviewId","hostId","screenId","signals","key","map","signal","sort","join","PAGE_MEMO_TTL_MS","pageMemo","Map","servedMemo","flaggedMemo","FLAGGED_MEMO_TTL_MS","resetHostedPageReviewMemoForTests","clear","subjectForRow","reviewId","describe","stored","app","firestore","collection","doc","get","then","row","storedSubject","catch","heldPage","subject","pageHeadline","siteName","reviewHostedPage","request","found","nodes","length","outcome","nowMs","Date","now","host","owner","Promise","all","undefined","org","orgId","identity","verdict","ageDays","createdAt","strong","isAlreadyLive","versionId","flagLivePage","page","reference","memo","atMs","state","live","previousVersionId","servedPageVersion","url","entryUrl","flagged","label","heldSend","kind","path","contentHash","slice","fromName","heldAtMs","extra","headline","alertTitle","alertBody","charAt","toUpperCase","item","reportedHostname","set","error","console","redirectReviewId","ruleId","reviewSiteRedirect","source","destination","subdomainHost","customDomain","ownDomains","siteHost","startsWith","pageReviewRef","NEW_PAGE_DAYS","lastClean","screen","created","createdMs","toMillis","input","at","existing","evidence","ref","first","exists","category","severity","details","reporterEmail","reporterName","dmca","riskNotice","reportCount","increment","updatedAt","serverTimestamp","status","merge","staffEvidence","snapshot","value","recordServedPageVersion","servedVersionId","servedAtMs","warn","flagLookalikeDomain","domain","String","trim","toLowerCase","brand","id","sending","link","where","notifyLookalikeLink","flagLookalikeCustomDomain"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAoE2C,GAE3C,SAASA,uBAAuB,QAAQ,sCAAqC;AAC7E,SACEC,mBAAmB,EACnBC,eAAe,EACfC,aAAa,EACbC,uBAAuB,QAElB,qCAAoC;AAC3C,SAASC,gBAAgB,EAAEC,kBAAkB,QAAQ,8CAA6C;AAClG,SACEC,qBAAqB,EACrBC,wBAAwB,EAExBC,6BAA6B,EAC7BC,mBAAmB,EACnBC,eAAe,QACV,oDAAmD;AAC1D,SAASC,UAAU,QAAQ,2BAA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iB,OAAO;QACdC,QAAQD,KAAK,CAAC,yDAAyDA;QACvE,OAAO;IACT;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAewD,oBAAoBrC,KAQzC;QAGUA,cAEGA;IAJZ,MAAMrH,gBAAgB;QACpBmF,MAAM;QACNtB,KAAK,GAAEwD,eAAAA,MAAMxD,KAAK,YAAXwD,eAAe;QACtBxG,QAAQwG,MAAMxG,MAAM;QACpBiB,QAAQ,GAAEuF,kBAAAA,MAAMvF,QAAQ,YAAduF,kBAAkB;QAC5B9C,WAAW8C,MAAM9C,SAAS;QAC1BwB,MAAM;YACJd,OAAO,GAAGoC,MAAMoC,KAAK,CAAC,aAAa,EAAEpC,MAAM4B,MAAM,EAAE;YACnD7D,MAAMiC,MAAMxG,MAAM,GAAG,CAAC,CAAC,EAAEwG,MAAMxG,MAAM,CAAC,SAAS,CAAC,GAAG;QACrD;QACA4H,eACE,CAAC,kBAAkB,EAAEpB,MAAMoC,KAAK,CAAC,IAAI,EAAEpC,MAAM4B,MAAM,CAAC,mBAAmB,EAAE5B,MAAMpC,KAAK,CAAC,EAAE,CAAC,GACxF;IACJ,GAAGxC,KAAK,CAAC,IAAMkB;AACjB;AAEA,iEAAiE,GACjE,OAAO,SAASgG,0BAA0BtC,KAIzC;IACC,OAAO2B,oBAAoB;QAAE7D,MAAM;OAAWkC;AAChD"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/hosted-page-review.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 * HELD FOR REVIEW: a published page (AGL-3362).\n *\n * ## Why the check sits where a page is COMPOSED, not where it is published\n *\n * A publish is a browser write. The besigner toolbar, the versions panel,\n * the screen details page, page-from-template, the layout and component\n * besigners and the form besigner each move a pointer (`versionId`, the\n * host's `screens` map, a component's own `nodes`) straight from the\n * client SDK; the scheduled-publish beat moves it from the server; an\n * experiment serves a version no pointer names; and an author may rewrite\n * the LIVE version document itself without moving any pointer at all. A\n * check on any one of those writes is a check the next one walks around.\n *\n * They all meet in one place: `composeScreenNodes` (`@aglyn/tenant-runtime`),\n * which every published render, the password unlock, the collection and\n * product templates and every experiment variant go through, and which\n * returns the page exactly as a visitor will receive it — the screen, its\n * layout chrome, its grafted components and its forms. So the screen is read\n * there, and a held page is one that is never composed for a visitor. For a\n * visitor, \"publish\" is the first render after the pointer moved; this is\n * that moment.\n *\n * ## What a hold does\n *\n * - The version is not served. The last version this page served clean\n * ({@link servedPageVersion}) is composed instead — screened again, since\n * a version document can be edited in place — and if there is none, or it\n * holds too, the page is not found. A first publish that holds therefore\n * serves nothing.\n * - One review row per (page, signal set) lands in the abuse queue at\n * `/admin/abuse-reports`, the same `phishing` row a held email files\n * (`fileOutboundHold`), with `heldSend.kind: 'page'`, the page's URL and\n * the held version. Staff dismiss it to RELEASE (the admin route drops the\n * site's cache and the next render serves it) or mark it actioned to\n * REJECT (it stays unserved; any later version carrying the same signals\n * is refused without a new row).\n * - A hold from a workspace in its first fortnight also asks for an\n * automatic `security` hold on the workspace, the site and the publishing\n * account (`page-security-hold.ts`, AGL-3450), which the console places.\n * - Keyed on the SIGNALS, as the send seam's rows are: a composed page\n * carries per-render values (dates, collection rows) that no content hash\n * would survive, while what makes it phishing does not change between\n * renders.\n *\n * ## Tiers\n *\n * `signalsThatHold`: a lookalike link or embed, an author-defined\n * credential field and a link to a host Google Web Risk lists\n * (`web-risk-link`, AGL-3451) hold for EVERY workspace; a brand's call to\n * action or lure, and a call to action that leaves the site beside a lure,\n * only for a workspace in its first fortnight. The workspace's documents are\n * read only when something was found, so a clean page costs no read for\n * this. The page's foreign hosts are looked up first, against a cache\n * (`web-risk.ts`), and noted beside the version it serves so the daily\n * re-check can look again: a harvester is often listed only after it is\n * published. A lookup that fails finds nothing, so it never holds a page.\n *\n * Fails CLOSED, unlike the send path: a page the pure screen flagged whose\n * review cannot finish — the workspace read, the row write — is answered\n * `held`, and the composer serves its last clean version or nothing. The\n * answer is not remembered, so the next render reviews it again. Composition\n * itself reads the store, so an outage here is an outage on the render\n * already, and the only cost of not serving a page the screen flagged is a\n * false positive's wait; serving it is the phishing page this exists to\n * stop. A page the screen found nothing on never reaches this.\n *\n * ## Site redirects\n *\n * A redirect rule that sends a path off the site is a page whose one call to\n * action fires on arrival, so the redirects plugin asks\n * {@link reviewSiteRedirect} before it serves one. Same screen\n * (`screenSiteRedirect`), same tiers, same row and the same staff decision:\n * a held rule does not fire, and is filed as a `page` hold on its rule's\n * document. Its destination is looked up against the reputation list too\n * (AGL-3451), so a redirect to a listed site holds for every workspace.\n *=========================================*/\n\nimport { ABUSE_REPORT_COLLECTION } from '@aglyn/aglyn/app-utils/abuse-report'\nimport {\n heldPageConsolePath,\n heldPageDetails,\n heldPageLabel,\n heldPageVisitorSentence,\n type HeldPageSubject,\n} from '@aglyn/shared-util-email/held-page'\nimport { screenHostedPage, screenSiteRedirect } from '@aglyn/shared-util-email/hosted-page-screen'\nimport {\n lookalikeBrandForHost,\n phishingScreenBrandLabel,\n type PhishingScreenSignal,\n describePhishingScreenSignals,\n isYoungWorkspaceAge,\n signalsThatHold,\n} from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport {\n foreignHostsForReputation,\n webRiskSignals,\n} from '@aglyn/shared-util-email/link-reputation'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport firebaseAdmin from './firebase-admin'\nimport { describeHeldPage, type HostedPageContext } from './held-page-subject'\nimport { notifyRiskEvent } from './risk-notice'\nimport { orgAgeDays } from './org-age'\nimport { requestPageSecurityHold } from './page-security-hold'\nimport { getHostDocAdmin, getOrgForHost } from './organizations'\nimport { lookupHostReputation, platformReputationExclusions } from './web-risk'\nimport {\n canonicalJson,\n fileOutboundHold,\n flaggedHostOf,\n heldOutboundReference,\n heldOutboundReviewId,\n outboundContentHash,\n type HeldOutboundSendState,\n workspaceScreenIdentity,\n} from './outbound-send-review'\n\n/** Where the last version a page served clean is noted: a hint, re-screened before use. */\nexport const PAGE_REVIEW_SUBCOLLECTION = 'pageReviews'\n\nexport interface HostedPageReviewRequest {\n hostId: string\n screenId: string\n versionId: string\n /** The page as composed for a visitor. */\n nodes: unknown\n /** The host and org documents, when the caller already holds them. */\n host?: Record<string, unknown> | null\n org?: Record<string, unknown> | null\n orgId?: string | null\n nowMs?: number\n /**\n * What the composer knows about the page (AGL-3374): the screen document,\n * the template route it is rendering, the variant, and a way to read the\n * layouts and components composed into it. Read only when a row is filed,\n * to name the page — never to decide whether it serves.\n */\n page?: HostedPageContext | null\n /**\n * Signals found about this page elsewhere, judged with the page's own\n * (AGL-3451): the daily link re-check passes a link Web Risk has listed\n * since the page went live, so the hold, its row and the young\n * workspace's security hold all come from this one path.\n */\n extraSignals?: readonly PhishingScreenSignal[]\n}\n\nexport type HostedPageReviewOutcome =\n | { outcome: 'serve' }\n | { outcome: 'held' | 'rejected'; reviewId: string; reference: string }\n\n/** The review row's id for a page and the signals that held. */\nexport function pageReviewId(\n hostId: string,\n screenId: string,\n signals: readonly PhishingScreenSignal[],\n): string {\n const key = signals\n .map((signal) => canonicalJson(signal))\n .sort()\n .join('\\n')\n return heldOutboundReviewId(`hosts/${hostId}/screens/${screenId}`, outboundContentHash([key]))\n}\n\n/** How long this process trusts a page row's state — the send seam's minute. */\nconst PAGE_MEMO_TTL_MS = 60_000\nconst pageMemo = new Map<string, { state: HeldOutboundSendState; atMs: number }>()\n/** The version each page last served clean, as this process last wrote it. */\nconst servedMemo = new Map<string, string>()\n/** Lookalike hosts this process already flagged for an established page, and when. */\nconst flaggedMemo = new Map<string, number>()\nconst FLAGGED_MEMO_TTL_MS = 60 * 60_000\n/**\n * The foreign hosts each reviewed page version links to (AGL-3451), for\n * {@link recordServedPageVersion} to note beside the version it served, which\n * is what the daily link re-check walks. Bounded: a process that reviews more\n * pages than this starts again.\n */\nconst reviewedForeignHosts = new Map<string, string[]>()\nconst REVIEWED_FOREIGN_HOSTS_MAX = 10_000\n\n/** Test seam: forget what this process learned. */\nexport function resetHostedPageReviewMemoForTests(): void {\n pageMemo.clear()\n servedMemo.clear()\n flaggedMemo.clear()\n reviewedForeignHosts.clear()\n}\n\n/**\n * Every foreign host the page links to, and the ones Google Web Risk lists\n * (AGL-3451). Foreign before the workspace is known: not the platform's\n * own, not a brand's own domain, not a common social link. Never throws; a\n * lookup that failed lists nothing.\n */\nasync function pageLinkReputation(\n linkHosts: readonly string[],\n): Promise<{ hosts: string[]; signals: PhishingScreenSignal[] }> {\n // Runs before the review's fail-closed `try`, so it must not throw: an\n // answer it cannot give is no listing, never a reason to hold.\n try {\n const hosts = foreignHostsForReputation(linkHosts, {\n excludeDomains: platformReputationExclusions(),\n })\n if (!hosts.length) return { hosts, signals: [] }\n const answer = await lookupHostReputation(hosts)\n return { hosts, signals: webRiskSignals(answer.hits) }\n } catch (error) {\n console.warn('[page-review] link reputation could not be read — no listing assumed', error)\n return { hosts: [], signals: [] }\n }\n}\n\n/** Is this host one of the workspace's own? */\nfunction isOwnHost(host: string, ownDomains: readonly (string | null | undefined)[] | undefined): boolean {\n return (ownDomains ?? []).some((own) => {\n const domain = String(own ?? '').trim().toLowerCase()\n return Boolean(domain) && (host === domain || host.endsWith(`.${domain}`))\n })\n}\n\n/**\n * The subject a row already stored, or a fresh description (AGL-3374). A row\n * that names its page is not described again, so the reads the description\n * may make are paid once per row, not once per render.\n */\nasync function subjectForRow(\n reviewId: string,\n describe: () => Promise<HeldPageSubject>,\n): Promise<HeldPageSubject> {\n const stored = await firebaseAdmin\n .app()\n .firestore()\n .collection(ABUSE_REPORT_COLLECTION)\n .doc(reviewId)\n .get()\n .then((row) => storedSubject(row.get('heldPage')))\n .catch(() => null)\n return stored ?? describe()\n}\n\n/** A row's stored subject, when it has one. */\nfunction storedSubject(heldPage: unknown): HeldPageSubject | null {\n const subject = (heldPage as { subject?: HeldPageSubject } | null | undefined)?.subject\n return subject && typeof subject === 'object' && subject.screenId ? subject : null\n}\n\n/** The row's first line, naming the page and where it was seen. */\nfunction pageHeadline(subject: HeldPageSubject, siteName: string): string {\n return [`${heldPageLabel(subject)} of ${siteName}.`, ...heldPageDetails(subject)].join(' ')\n}\n\n/**\n * Screen one page as a visitor would receive it, and say whether it may be\n * served. See the module header.\n */\nexport async function reviewHostedPage(\n request: HostedPageReviewRequest,\n): Promise<HostedPageReviewOutcome> {\n const found = screenHostedPage({ nodes: request.nodes })\n // Every foreign host it points at, against the reputation list\n // (AGL-3451): a harvester known to be bad anywhere holds however plain the\n // page around it is. Strong, so it holds at any workspace age.\n const reputation = await pageLinkReputation(found.linkHosts)\n if (reviewedForeignHosts.size >= REVIEWED_FOREIGN_HOSTS_MAX) reviewedForeignHosts.clear()\n reviewedForeignHosts.set(`${request.hostId}/${request.screenId}/${request.versionId}`, reputation.hosts)\n const listed = [...reputation.signals, ...(request.extraSignals ?? [])]\n if (!found.signals.length && !listed.length) return { outcome: 'serve' }\n\n const nowMs = request.nowMs ?? Date.now()\n try {\n const [host, owner] = await Promise.all([\n request.host !== undefined ? request.host : getHostDocAdmin(request.hostId),\n request.org !== undefined\n ? { orgId: request.orgId ?? null, org: request.org }\n : getOrgForHost(request.hostId),\n ])\n const org = (owner?.org as Record<string, unknown> | null | undefined) ?? null\n const orgId = owner?.orgId ?? null\n // Again, now knowing whose page it is: a brand in the workspace's own\n // name or domain is its own, and a link to its own site is not away.\n const identity = workspaceScreenIdentity({ org, host })\n const verdict = screenHostedPage({ nodes: request.nodes, ...identity })\n // A listing of the workspace's own host is not a link away from it.\n const screened = [\n ...verdict.signals,\n ...listed.filter(\n (signal) => !('host' in signal) || !isOwnHost(signal.host, identity.ownDomains),\n ),\n ]\n const ageDays = orgAgeDays((org as { createdAt?: unknown } | null)?.createdAt, nowMs)\n // Every workspace is screened, however old: an established account can\n // be compromised, and a compromised account publishing a lure is the\n // same harm as a new one. What differs is what a hold may take DOWN.\n // Holding content that is already live serves its last clean version or\n // nothing, and on a real business's home page that is an outage the\n // screen caused (aglyn.com, 2026-09-28, a page that had served clean\n // until a rule changed). So for an established workspace:\n // - NEW content (a new version of a live page, or a page that has\n // never been live) holds, exactly as for a young workspace; the live\n // page keeps serving its last clean version, or the new page waits;\n // - content ALREADY LIVE keeps serving, and is flagged to staff as\n // urgent, who lock the site if it is impersonation.\n if (!isYoungWorkspaceAge(ageDays)) {\n const strong = signalsThatHold(screened, { ageDays })\n if (!strong.length) return { outcome: 'serve' }\n if (await isAlreadyLive(request.hostId, request.screenId, request.versionId, nowMs)) {\n await flagLivePage({\n hostId: request.hostId,\n screenId: request.screenId,\n versionId: request.versionId,\n orgId,\n host,\n signals: strong,\n nowMs,\n page: request.page ?? null,\n identity,\n })\n return { outcome: 'serve' }\n }\n }\n const signals = signalsThatHold(screened, { ageDays })\n if (!signals.length) return { outcome: 'serve' }\n\n const reviewId = pageReviewId(request.hostId, request.screenId, signals)\n const reference = heldOutboundReference(reviewId)\n const memo = pageMemo.get(reviewId)\n if (memo && nowMs - memo.atMs < PAGE_MEMO_TTL_MS) {\n return memo.state === 'released'\n ? { outcome: 'serve' }\n : { outcome: memo.state === 'rejected' ? 'rejected' : 'held', reviewId, reference }\n }\n // The page by its real name and route (AGL-3374): a template, a list,\n // a variant, or a page whose flagged content lives in its layout.\n const subject = await subjectForRow(reviewId, async () =>\n describeHeldPage({\n hostId: request.hostId,\n screenId: request.screenId,\n versionId: request.versionId,\n host,\n page: request.page,\n signals,\n identity,\n live: false,\n previousVersionId: await servedPageVersion(request.hostId, request.screenId),\n }),\n )\n const url = subject.entryUrl ?? subject.url\n const flagged = flaggedHostOf(signals)\n const siteName =\n typeof host?.['name'] === 'string' && host['name'] ? `\"${host['name']}\"` : 'a site'\n const label = heldPageLabel(subject)\n const state = await fileOutboundHold({\n reviewId,\n heldSend: {\n kind: 'page',\n path: `hosts/${request.hostId}/screens/${request.screenId}`,\n hostId: request.hostId,\n orgId,\n contentHash: outboundContentHash([signals]),\n subject: label.slice(0, 300),\n fromName: null,\n signals,\n state: 'held',\n heldAtMs: nowMs,\n ageDays,\n },\n extra: {\n heldPage: { screenId: request.screenId, versionId: request.versionId, url, subject },\n },\n headline:\n `Held ${pageHeadline(subject, siteName)} Version ${request.versionId}, from a ` +\n `workspace ${ageDays ?? '?'} day(s) old. ${heldPageVisitorSentence(subject)}`,\n alertTitle: 'Published page held for review — possible phishing',\n alertBody: `${label.charAt(0).toUpperCase()}${label.slice(1)} was held before it went live.`,\n // The owners' words for it, and where they fix it (AGL-3368, AGL-3374).\n item: { label, path: heldPageConsolePath(subject, request.hostId) },\n page: subject,\n // The page itself is what was reported; the flagged host, when there\n // is one, is named in the details and on `reportedHostname`.\n url,\n reportedHostname: flagged,\n })\n // A hold from a workspace in its first fortnight also holds the\n // workspace, the site and the account that published it (AGL-3450).\n if (state === 'held') {\n await requestPageSecurityHold({\n orgId: orgId ?? '',\n org,\n hostId: request.hostId,\n screenId: request.screenId,\n versionId: request.versionId,\n reviewId,\n reference,\n signals,\n ageDays,\n pageLabel: label,\n pageUrl: url,\n siteName: typeof host?.['name'] === 'string' ? host['name'] : null,\n nowMs,\n })\n }\n pageMemo.set(reviewId, { state, atMs: nowMs })\n return state === 'released'\n ? { outcome: 'serve' }\n : { outcome: state === 'rejected' ? 'rejected' : 'held', reviewId, reference }\n } catch (error) {\n // Closed: the screen has already found a signal on this page, and a\n // review that could not finish has not cleared it. Not remembered, so\n // the next render reviews it again.\n console.error('[page-review] a flagged page could not be reviewed — holding it', error)\n const reviewId = pageReviewId(request.hostId, request.screenId, [...found.signals, ...listed])\n return { outcome: 'held', reviewId, reference: heldOutboundReference(reviewId) }\n }\n}\n\nexport interface SiteRedirectReviewRequest {\n hostId: string\n /** The rule's document id under `hosts/{hostId}/redirects`. */\n ruleId: string\n /** The path, or the pattern, the rule answers. */\n source: string\n /** Where it sends the visitor, after any `$n` substitution. */\n destination: string\n /** The host and org documents, when the caller already holds them. */\n host?: Record<string, unknown> | null\n org?: Record<string, unknown> | null\n orgId?: string | null\n nowMs?: number\n}\n\n/** The review row's id for a redirect rule and the signals that held. */\nexport function redirectReviewId(\n hostId: string,\n ruleId: string,\n signals: readonly PhishingScreenSignal[],\n): string {\n const key = signals\n .map((signal) => canonicalJson(signal))\n .sort()\n .join('\\n')\n return heldOutboundReviewId(`hosts/${hostId}/redirects/${ruleId}`, outboundContentHash([key]))\n}\n\n/**\n * Screen one redirect rule before it sends a visitor off the site\n * (AGL-3447), and say whether it may fire. See the module header.\n *\n * Every workspace is screened and the tiers decide, as for a page: a\n * destination that wears a brand holds for all of them, a lure path sent\n * off the site only for a workspace in its first fortnight. A held rule is\n * filed once per (rule, signal set) and decided by staff on that row:\n * dismissed, it fires; actioned, it never does with those signals.\n */\nexport async function reviewSiteRedirect(\n request: SiteRedirectReviewRequest,\n): Promise<HostedPageReviewOutcome> {\n const found = screenSiteRedirect({ source: request.source, destination: request.destination })\n // Where it sends visitors, against the reputation list (AGL-3451): a\n // listed destination holds for every workspace, as a listed link does.\n const reputation = await pageLinkReputation(found.linkHosts)\n if (!found.signals.length && !reputation.signals.length) return { outcome: 'serve' }\n\n const nowMs = request.nowMs ?? Date.now()\n try {\n const [host, owner] = await Promise.all([\n request.host !== undefined ? request.host : getHostDocAdmin(request.hostId),\n request.org !== undefined\n ? { orgId: request.orgId ?? null, org: request.org }\n : getOrgForHost(request.hostId),\n ])\n const org = (owner?.org as Record<string, unknown> | null | undefined) ?? null\n const orgId = owner?.orgId ?? null\n const identity = workspaceScreenIdentity({ org, host })\n const verdict = screenSiteRedirect({\n source: request.source,\n destination: request.destination,\n ...identity,\n })\n const screened = [\n ...verdict.signals,\n ...reputation.signals.filter(\n (signal) => !('host' in signal) || !isOwnHost(signal.host, identity.ownDomains),\n ),\n ]\n const ageDays = orgAgeDays((org as { createdAt?: unknown } | null)?.createdAt, nowMs)\n const signals = signalsThatHold(screened, { ageDays })\n if (!signals.length) return { outcome: 'serve' }\n\n const reviewId = redirectReviewId(request.hostId, request.ruleId, signals)\n const reference = heldOutboundReference(reviewId)\n const memo = pageMemo.get(reviewId)\n if (memo && nowMs - memo.atMs < PAGE_MEMO_TTL_MS) {\n return memo.state === 'released'\n ? { outcome: 'serve' }\n : { outcome: memo.state === 'rejected' ? 'rejected' : 'held', reviewId, reference }\n }\n const source = request.source.slice(0, 200)\n const destination = request.destination.slice(0, 500)\n const label = `the redirect from ${source}`\n const siteName =\n typeof host?.['name'] === 'string' && host['name'] ? `\"${host['name']}\"` : 'a site'\n const [subdomainHost, customDomain] = identity.ownDomains ?? []\n const siteHost = customDomain || subdomainHost\n const state = await fileOutboundHold({\n reviewId,\n heldSend: {\n kind: 'page',\n path: `hosts/${request.hostId}/redirects/${request.ruleId}`,\n hostId: request.hostId,\n orgId,\n contentHash: outboundContentHash([signals]),\n subject: label.slice(0, 300),\n fromName: null,\n signals,\n state: 'held',\n heldAtMs: nowMs,\n ageDays,\n },\n headline:\n `Held ${label} of ${siteName}, which sends visitors to ${destination}, from a ` +\n `workspace ${ageDays ?? '?'} day(s) old. The rule does not fire until this is decided.`,\n alertTitle: 'Site redirect held for review — possible phishing',\n alertBody: `The redirect from ${source} was held before it sent anyone off the site.`,\n // Where the owners fix it: the site's Redirects page.\n item: { label, path: `/${request.hostId}/redirects` },\n url: siteHost && source.startsWith('/') ? `https://${siteHost}${source}` : destination,\n reportedHostname: flaggedHostOf(signals),\n })\n pageMemo.set(reviewId, { state, atMs: nowMs })\n return state === 'released'\n ? { outcome: 'serve' }\n : { outcome: state === 'rejected' ? 'rejected' : 'held', reviewId, reference }\n } catch (error) {\n // Closed, as a page is: the screen found a signal and nothing cleared it.\n console.error('[page-review] a flagged redirect could not be reviewed — holding it', error)\n const reviewId = redirectReviewId(request.hostId, request.ruleId, [\n ...found.signals,\n ...reputation.signals,\n ])\n return { outcome: 'held', reviewId, reference: heldOutboundReference(reviewId) }\n }\n}\n\nfunction pageReviewRef(hostId: string, screenId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection(PAGE_REVIEW_SUBCOLLECTION)\n .doc(screenId)\n}\n\n/**\n * Is this version of the page already what visitors receive? It is when it\n * is the version the page last served clean, or when the page has no record\n * at all and is not new: it went live before the screen existed. A page\n * created in the last {@link NEW_PAGE_DAYS} days with no record has never\n * been live, so holding it takes nothing down.\n */\nconst NEW_PAGE_DAYS = 7\nasync function isAlreadyLive(\n hostId: string,\n screenId: string,\n versionId: string,\n nowMs: number,\n): Promise<boolean> {\n const lastClean = await servedPageVersion(hostId, screenId)\n if (lastClean) return lastClean === versionId\n try {\n const screen = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('screens')\n .doc(screenId)\n .get()\n const created = screen.get('createdAt') as { toMillis?: () => number } | number | undefined\n const createdMs =\n typeof created === 'number' ? created : typeof created?.toMillis === 'function' ? created.toMillis() : null\n // No readable creation time: an old page, so live.\n return createdMs === null || nowMs - createdMs >= NEW_PAGE_DAYS * 24 * 60 * 60 * 1000\n } catch {\n return true\n }\n}\n\n/**\n * A page ALREADY LIVE carries a strong signal: file one urgent abuse row for\n * it (keyed on the page and its signals, so a busy page is one row) and, the\n * first time, tell staff and the owners through the `page-flagged` notice.\n * The page keeps serving; staff lock the site if it is impersonation or the\n * account looks compromised. Once per page and signal set per process.\n */\nasync function flagLivePage(input: {\n hostId: string\n screenId: string\n versionId: string\n orgId: string | null\n host: Record<string, unknown> | null\n signals: readonly PhishingScreenSignal[]\n nowMs: number\n page?: HostedPageContext | null\n identity?: ReturnType<typeof workspaceScreenIdentity>\n}): Promise<void> {\n const key = `${input.hostId}\\n${input.screenId}\\n${input.signals.map((signal) => canonicalJson(signal)).sort().join('\\n')}`\n const at = flaggedMemo.get(key)\n if (at !== undefined && input.nowMs - at < FLAGGED_MEMO_TTL_MS) return\n flaggedMemo.set(key, input.nowMs)\n try {\n const reviewId = pageReviewId(input.hostId, `${input.screenId}/live`, input.signals)\n const reference = heldOutboundReference(reviewId)\n const evidence = describePhishingScreenSignals(input.signals).join(' ')\n const flagged = flaggedHostOf(input.signals)\n const ref = firebaseAdmin.app().firestore().collection(ABUSE_REPORT_COLLECTION).doc(reviewId)\n const existing = await ref.get()\n const first = !existing.exists\n // Named once, when the row is new (AGL-3374).\n const subject =\n (existing.exists ? storedSubject(existing.get('heldPage')) : null) ??\n (await describeHeldPage({\n hostId: input.hostId,\n screenId: input.screenId,\n versionId: input.versionId,\n host: input.host,\n page: input.page,\n signals: input.signals,\n identity: input.identity ?? workspaceScreenIdentity({ host: input.host }),\n live: true,\n previousVersionId: null,\n }))\n const url = subject.entryUrl ?? subject.url\n const siteName =\n typeof input.host?.['name'] === 'string' && input.host['name']\n ? `\"${input.host['name']}\"`\n : 'a site'\n await ref.set(\n {\n reference,\n category: 'phishing',\n severity: 'urgent',\n source: 'outbound-screen',\n url,\n reportedHostname: flagged,\n hostId: input.hostId,\n orgId: input.orgId,\n details: [\n `LIVE: ${pageHeadline(subject, siteName)} It was flagged by the phishing screen and is still serving.`,\n evidence,\n 'Lock the site if it is impersonation or the account looks compromised; dismiss this if the content is theirs.',\n ].join('\\n'),\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n heldPage: { screenId: input.screenId, versionId: input.versionId, url, subject },\n riskNotice: { kind: 'page-flagged' },\n reportCount: FieldValue.increment(1),\n updatedAt: FieldValue.serverTimestamp(),\n ...(first ? { status: 'open', createdAt: FieldValue.serverTimestamp() } : {}),\n },\n { merge: true },\n )\n if (!first) return\n await notifyRiskEvent({\n kind: 'page-flagged',\n orgId: input.orgId,\n hostId: input.hostId,\n reviewId,\n reference,\n item: { label: heldPageLabel(subject), path: heldPageConsolePath(subject, input.hostId) },\n page: subject,\n staffEvidence: [...heldPageDetails(subject), evidence].join(' '),\n })\n } catch (error) {\n console.error('[page-review] a live page could not be flagged', error)\n }\n}\n\n/**\n * The version this page last served clean, or null. A HINT, not a\n * clearance: the caller composes and screens it again before serving it,\n * because a version document can be edited after it was served.\n */\nexport async function servedPageVersion(hostId: string, screenId: string): Promise<string | null> {\n try {\n const snapshot = await pageReviewRef(hostId, screenId).get()\n const value = snapshot.get('servedVersionId')\n return typeof value === 'string' && value ? value : null\n } catch {\n return null\n }\n}\n\n/**\n * Note that this page served `versionId` clean. One read the first time a\n * process renders a page, a write only when the version moved; nothing\n * after that, however often the page is rendered.\n */\nexport async function recordServedPageVersion(\n hostId: string,\n screenId: string,\n versionId: string,\n): Promise<void> {\n const key = `${hostId}/${screenId}`\n // The foreign hosts this version links to, as its review found them\n // (AGL-3451): noted beside it so the daily link re-check can walk them.\n const foreignHosts = reviewedForeignHosts.get(`${key}/${versionId}`)\n const memoValue = foreignHosts ? `${versionId}|${foreignHosts.join(',')}` : versionId\n if (!versionId || servedMemo.get(key) === memoValue) return\n try {\n const ref = pageReviewRef(hostId, screenId)\n const snapshot = await ref.get()\n const versionMoved = snapshot.get('servedVersionId') !== versionId\n const stored = snapshot.get('foreignHosts')\n const hostsMoved =\n foreignHosts !== undefined &&\n (Array.isArray(stored) ? stored.join(',') : '') !== foreignHosts.join(',')\n if (versionMoved || hostsMoved) {\n await ref.set(\n {\n ...(versionMoved ? { servedVersionId: versionId, servedAtMs: Date.now() } : {}),\n ...(foreignHosts\n ? { foreignHosts, foreignHostCount: foreignHosts.length }\n : {}),\n },\n { merge: true },\n )\n }\n servedMemo.set(key, memoValue)\n } catch (error) {\n console.warn('[page-review] the served version could not be noted', error)\n }\n}\n\n/**\n * A domain a workspace attached that wears a brand (AGL-3356, AGL-3362):\n * filed in the abuse queue as an urgent `phishing` row for staff, not\n * refused. Two kinds, one rule:\n *\n * - `site` — a custom domain a site is served on (the attach route);\n * - `sending` — a custom domain a workspace sends email as, when it is\n * added and again when it verifies (`sending-domains.ts`);\n * - `link` — a link a merchant configured that a buyer or a server would\n * follow: a product's paid download or video hotlink, a supplier's order\n * webhook (AGL-3363). The link itself is refused where it is followed; this\n * files it, and tells the site's managers once ({@link notifyLookalikeLink}).\n *\n * Not refused, because the domain is the merchant's own registration and\n * the platform cannot tell a brand's own agency attaching `paypal-promo.com`\n * from a kit — but a brand's lookalike on a site or in a `From:` line is\n * exactly what staff look at first. The site's pages are still screened as\n * they are served, and mail FROM a lookalike domain is held at the send seam\n * for every workspace. The test is the phishing screen's own lookalike rule\n * (`lookalikeBrandForHost`), the one that holds a link in an email. One row\n * per (owner, kind, domain), so a re-attach or a re-verify counts rather than\n * re-alerts.\n *\n * Never throws: the write it rides on has already happened.\n */\nexport async function flagLookalikeDomain(input: {\n kind: 'site' | 'sending' | 'link'\n hostId: string | null\n orgId: string | null\n domain: string\n /** For a `link`: where it was configured, as staff read it. */\n where?: string\n}): Promise<'flagged' | 'clean' | 'failed'> {\n const domain = String(input.domain ?? '').trim().toLowerCase()\n const brand = lookalikeBrandForHost(domain)\n if (!brand) return 'clean'\n const label = phishingScreenBrandLabel(brand.id)\n const sending = input.kind === 'sending'\n const link = input.kind === 'link'\n try {\n const firestore = firebaseAdmin.app().firestore()\n const owner = sending\n ? `orgs/${input.orgId ?? ''}/sendingDomains`\n : link\n ? `hosts/${input.hostId ?? ''}/links`\n : `hosts/${input.hostId ?? ''}/cname`\n const reviewId = heldOutboundReviewId(owner, domain)\n const reference = heldOutboundReference(reviewId)\n const ref = firestore.collection(ABUSE_REPORT_COLLECTION).doc(reviewId)\n const first = !(await ref.get()).exists\n await ref.set(\n {\n reference,\n category: 'phishing',\n severity: 'urgent',\n source: 'outbound-screen',\n url: `https://${domain}/`,\n reportedHostname: domain,\n hostId: input.hostId,\n orgId: input.orgId,\n details: [\n sending\n ? `A workspace added ${domain} as a domain to send email from.`\n : link\n ? `A site configured a link to ${domain} (${input.where ?? 'a commerce link'}).`\n : `A site attached the custom domain ${domain}.`,\n `${domain} wears the ${label} name but is not ${label}'s domain.`,\n sending\n ? 'Email from it is held at the send seam for every workspace. Mark this actioned ' +\n 'and lock the workspace if it is impersonation; dismiss it if the brand is theirs.'\n : link\n ? 'Nobody is sent to it: the link is refused wherever it is followed. Mark this ' +\n 'actioned and lock the site if it is impersonation.'\n : 'Its pages are still screened as they are served. Mark this actioned ' +\n 'and lock the site if it is impersonation; dismiss it if the brand is theirs.',\n ].join('\\n'),\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n reportCount: FieldValue.increment(1),\n updatedAt: FieldValue.serverTimestamp(),\n ...(first ? { status: 'open', createdAt: FieldValue.serverTimestamp() } : {}),\n },\n { merge: true },\n )\n if (first && link) {\n await notifyLookalikeLink({\n hostId: input.hostId,\n orgId: input.orgId,\n domain,\n label,\n where: input.where ?? 'a commerce link',\n reference,\n reviewId,\n })\n } else if (first) {\n // The owners hear that the domain is waiting on a routine review — not\n // which name it resembles; staff get the brand and a link to the row.\n await notifyRiskEvent({\n kind: 'domain-flagged',\n orgId: input.orgId,\n hostId: input.hostId,\n reviewId,\n reference,\n item: {\n label: sending ? `the sending domain ${domain}` : `the custom domain ${domain}`,\n // Emails → Sending, or the site's Domain settings.\n path: sending ? '/org/emails/sending' : input.hostId ? `/${input.hostId}/admin/domain` : null,\n },\n staffEvidence:\n `${sending ? 'Sending domain' : 'Custom domain'} ${domain} looks like ${label}.`,\n })\n }\n return 'flagged'\n } catch (error) {\n console.error('[page-review] a lookalike domain could not be flagged', error)\n return 'failed'\n }\n}\n\n/**\n * Tell staff and the site's managers and the workspace's owners, once per\n * (site, domain), that a link the merchant configured was refused because it\n * wears another brand's name (AGL-3363), through the risk notice seam\n * (AGL-3368). The merchant reads the catalog's `link-blocked` words — what\n * was refused and how to fix it, never how the check works; staff get the\n * brand and a link to the row. Never throws.\n */\nexport async function notifyLookalikeLink(input: {\n hostId: string | null\n orgId?: string | null\n domain: string\n label: string\n where: string\n reference: string\n reviewId?: string | null\n}): Promise<void> {\n await notifyRiskEvent({\n kind: 'link-blocked',\n orgId: input.orgId ?? null,\n hostId: input.hostId,\n reviewId: input.reviewId ?? null,\n reference: input.reference,\n item: {\n label: `${input.where} pointing to ${input.domain}`,\n path: input.hostId ? `/${input.hostId}/products` : null,\n },\n staffEvidence:\n `A site configured ${input.where} to ${input.domain}, which looks like ${input.label}. ` +\n 'It is refused wherever it is followed.',\n }).catch(() => undefined)\n}\n\n/** A site's custom domain, through {@link flagLookalikeDomain}. */\nexport function flagLookalikeCustomDomain(input: {\n hostId: string\n orgId: string | null\n domain: string\n}): Promise<'flagged' | 'clean' | 'failed'> {\n return flagLookalikeDomain({ kind: 'site', ...input })\n}\n"],"names":["ABUSE_REPORT_COLLECTION","heldPageConsolePath","heldPageDetails","heldPageLabel","heldPageVisitorSentence","screenHostedPage","screenSiteRedirect","lookalikeBrandForHost","phishingScreenBrandLabel","describePhishingScreenSignals","isYoungWorkspaceAge","signalsThatHold","foreignHostsForReputation","webRiskSignals","FieldValue","firebaseAdmin","describeHeldPage","notifyRiskEvent","orgAgeDays","requestPageSecurityHold","getHostDocAdmin","getOrgForHost","lookupHostReputation","platformReputationExclusions","canonicalJson","fileOutboundHold","flaggedHostOf","heldOutboundReference","heldOutboundReviewId","outboundContentHash","workspaceScreenIdentity","PAGE_REVIEW_SUBCOLLECTION","pageReviewId","hostId","screenId","signals","key","map","signal","sort","join","PAGE_MEMO_TTL_MS","pageMemo","Map","servedMemo","flaggedMemo","FLAGGED_MEMO_TTL_MS","reviewedForeignHosts","REVIEWED_FOREIGN_HOSTS_MAX","resetHostedPageReviewMemoForTests","clear","pageLinkReputation","linkHosts","hosts","excludeDomains","length","answer","hits","error","console","warn","isOwnHost","host","ownDomains","some","own","domain","String","trim","toLowerCase","Boolean","endsWith","subjectForRow","reviewId","describe","stored","app","firestore","collection","doc","get","then","row","storedSubject","catch","heldPage","subject","pageHeadline","siteName","reviewHostedPage","request","found","nodes","reputation","size","set","versionId","listed","extraSignals","outcome","nowMs","Date","now","owner","Promise","all","undefined","org","orgId","identity","verdict","screened","filter","ageDays","createdAt","strong","isAlreadyLive","flagLivePage","page","reference","memo","atMs","state","live","previousVersionId","servedPageVersion","url","entryUrl","flagged","label","heldSend","kind","path","contentHash","slice","fromName","heldAtMs","extra","headline","alertTitle","alertBody","charAt","toUpperCase","item","reportedHostname","pageLabel","pageUrl","redirectReviewId","ruleId","reviewSiteRedirect","source","destination","subdomainHost","customDomain","siteHost","startsWith","pageReviewRef","NEW_PAGE_DAYS","lastClean","screen","created","createdMs","toMillis","input","at","existing","evidence","ref","first","exists","category","severity","details","reporterEmail","reporterName","dmca","riskNotice","reportCount","increment","updatedAt","serverTimestamp","status","merge","staffEvidence","snapshot","value","recordServedPageVersion","foreignHosts","memoValue","versionMoved","hostsMoved","Array","isArray","servedVersionId","servedAtMs","foreignHostCount","flagLookalikeDomain","brand","id","sending","link","where","notifyLookalikeLink","flagLookalikeCustomDomain"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA4E2C,GAE3C,SAASA,uBAAuB,QAAQ,sCAAqC;AAC7E,SACEC,mBAAmB,EACnBC,eAAe,EACfC,aAAa,EACbC,uBAAuB,QAElB,qCAAoC;AAC3C,SAASC,gBAAgB,EAAEC,kBAAkB,QAAQ,8CAA6C;AAClG,SACEC,qBAAqB,EACrBC,wBAAwB,EAExBC,6BAA6B,EAC7BC,mBAAmB,EACnBC,eAAe,QACV,oDAAmD;AAC1D,SACEC,yBAAyB,EACzBC,cAAc,QACT,2CAA0C;AACjD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,gBAAgB,QAAgC,yBAAqB;AAC9E,SAASC,eAAe,QAAQ,mBAAe;AAC/C,SAASC,UAAU,QAAQ,eAAW;AACtC,SAASC,uBAAuB,QAAQ,0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