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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/api-keys.js +3 -3
  3. package/src/lib/server/api-keys.js.map +1 -1
  4. package/src/lib/server/api-v1-resources.d.ts +44 -3
  5. package/src/lib/server/api-v1-resources.js +82 -5
  6. package/src/lib/server/api-v1-resources.js.map +1 -1
  7. package/src/lib/server/collection-live-pages.d.ts +2 -2
  8. package/src/lib/server/collection-live-pages.js +1 -1
  9. package/src/lib/server/collection-live-pages.js.map +1 -1
  10. package/src/lib/server/email-delivery-log.d.ts +17 -73
  11. package/src/lib/server/email-delivery-log.js +44 -222
  12. package/src/lib/server/email-delivery-log.js.map +1 -1
  13. package/src/lib/server/email-flow-gate.js +27 -38
  14. package/src/lib/server/email-flow-gate.js.map +1 -1
  15. package/src/lib/server/erase-person.d.ts +34 -54
  16. package/src/lib/server/erase-person.js +44 -239
  17. package/src/lib/server/erase-person.js.map +1 -1
  18. package/src/lib/server/host-visitor-records.d.ts +12 -4
  19. package/src/lib/server/host-visitor-records.js +20 -10
  20. package/src/lib/server/host-visitor-records.js.map +1 -1
  21. package/src/lib/server/hosted-page-review.d.ts +7 -0
  22. package/src/lib/server/hosted-page-review.js +144 -20
  23. package/src/lib/server/hosted-page-review.js.map +1 -1
  24. package/src/lib/server/leaving-notice.d.ts +98 -0
  25. package/src/lib/server/leaving-notice.js +250 -0
  26. package/src/lib/server/leaving-notice.js.map +1 -0
  27. package/src/lib/server/link-reputation-review.d.ts +58 -0
  28. package/src/lib/server/link-reputation-review.js +185 -0
  29. package/src/lib/server/link-reputation-review.js.map +1 -0
  30. package/src/lib/server/live-page-drops.d.ts +67 -0
  31. package/src/lib/server/live-page-drops.js +57 -0
  32. package/src/lib/server/live-page-drops.js.map +1 -0
  33. package/src/lib/server/media-bandwidth-cap.d.ts +78 -0
  34. package/src/lib/server/media-bandwidth-cap.js +180 -0
  35. package/src/lib/server/media-bandwidth-cap.js.map +1 -0
  36. package/src/lib/server/media-cdn-icon.d.ts +77 -0
  37. package/src/lib/server/media-cdn-icon.js +140 -0
  38. package/src/lib/server/media-cdn-icon.js.map +1 -0
  39. package/src/lib/server/media-delivery-regeneration.d.ts +132 -0
  40. package/src/lib/server/media-delivery-regeneration.js +216 -0
  41. package/src/lib/server/media-delivery-regeneration.js.map +1 -0
  42. package/src/lib/server/media-delivery.d.ts +2 -0
  43. package/src/lib/server/media-delivery.js +2 -1
  44. package/src/lib/server/media-delivery.js.map +1 -1
  45. package/src/lib/server/media-serve-count.d.ts +50 -0
  46. package/src/lib/server/media-serve-count.js +62 -0
  47. package/src/lib/server/media-serve-count.js.map +1 -0
  48. package/src/lib/server/media-signing.d.ts +13 -2
  49. package/src/lib/server/media-signing.js +12 -8
  50. package/src/lib/server/media-signing.js.map +1 -1
  51. package/src/lib/server/media-tombstone.js +7 -5
  52. package/src/lib/server/media-tombstone.js.map +1 -1
  53. package/src/lib/server/media-variants.d.ts +151 -20
  54. package/src/lib/server/media-variants.js +204 -27
  55. package/src/lib/server/media-variants.js.map +1 -1
  56. package/src/lib/server/org-age.d.ts +15 -6
  57. package/src/lib/server/org-age.js +20 -8
  58. package/src/lib/server/org-age.js.map +1 -1
  59. package/src/lib/server/organizations.d.ts +102 -2
  60. package/src/lib/server/organizations.js +388 -58
  61. package/src/lib/server/organizations.js.map +1 -1
  62. package/src/lib/server/outbound-send-review.js +24 -6
  63. package/src/lib/server/outbound-send-review.js.map +1 -1
  64. package/src/lib/server/page-security-hold.d.ts +93 -0
  65. package/src/lib/server/page-security-hold.js +180 -0
  66. package/src/lib/server/page-security-hold.js.map +1 -0
  67. package/src/lib/server/paged-sweeps.d.ts +51 -0
  68. package/src/lib/server/paged-sweeps.js +79 -0
  69. package/src/lib/server/paged-sweeps.js.map +1 -0
  70. package/src/lib/server/platform-marketing-consent.d.ts +0 -49
  71. package/src/lib/server/platform-marketing-consent.js +27 -11
  72. package/src/lib/server/platform-marketing-consent.js.map +1 -1
  73. package/src/lib/server/serve-media-cdn.d.ts +69 -1
  74. package/src/lib/server/serve-media-cdn.js +424 -70
  75. package/src/lib/server/serve-media-cdn.js.map +1 -1
  76. package/src/lib/server/site-icon-render.d.ts +68 -0
  77. package/src/lib/server/site-icon-render.js +157 -0
  78. package/src/lib/server/site-icon-render.js.map +1 -0
  79. package/src/lib/server/staff-seat.d.ts +50 -0
  80. package/src/lib/server/staff-seat.js +118 -0
  81. package/src/lib/server/staff-seat.js.map +1 -0
  82. package/src/lib/server/transfer-export.d.ts +46 -0
  83. package/src/lib/server/transfer-export.js +221 -0
  84. package/src/lib/server/transfer-export.js.map +1 -0
  85. package/src/lib/server/transfer-jobs.d.ts +385 -0
  86. package/src/lib/server/transfer-jobs.js +2368 -0
  87. package/src/lib/server/transfer-jobs.js.map +1 -0
  88. package/src/lib/server/transfer-packages.d.ts +127 -0
  89. package/src/lib/server/transfer-packages.js +1036 -0
  90. package/src/lib/server/transfer-packages.js.map +1 -0
  91. package/src/lib/server/upgrade-proposal.d.ts +97 -0
  92. package/src/lib/server/upgrade-proposal.js +312 -0
  93. package/src/lib/server/upgrade-proposal.js.map +1 -0
  94. package/src/lib/server/upsert-contact.d.ts +17 -8
  95. package/src/lib/server/upsert-contact.js +82 -16
  96. package/src/lib/server/upsert-contact.js.map +1 -1
  97. package/src/lib/server/web-risk.d.ts +139 -0
  98. package/src/lib/server/web-risk.js +521 -0
  99. package/src/lib/server/web-risk.js.map +1 -0
  100. package/src/tenancy.d.ts +3 -1
  101. package/src/tenancy.js +5 -1
  102. package/src/tenancy.js.map +1 -1
  103. package/src/lib/server/campaign-attribution-store.d.ts +0 -55
  104. package/src/lib/server/campaign-attribution-store.js +0 -95
  105. package/src/lib/server/campaign-attribution-store.js.map +0 -1
  106. package/src/lib/server/campaign-conversion-attribution.d.ts +0 -283
  107. package/src/lib/server/campaign-conversion-attribution.js +0 -450
  108. package/src/lib/server/campaign-conversion-attribution.js.map +0 -1
  109. package/src/lib/server/dataset-live-pages.d.ts +0 -179
  110. package/src/lib/server/dataset-live-pages.js +0 -421
  111. package/src/lib/server/dataset-live-pages.js.map +0 -1
  112. package/src/lib/server/email-revenue-attribution.d.ts +0 -185
  113. package/src/lib/server/email-revenue-attribution.js +0 -321
  114. package/src/lib/server/email-revenue-attribution.js.map +0 -1
@@ -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,2BAA0B;AACrD,OAAOC,mB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QD,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 — and, in `'url'` mode (AGL-3459), its\n * links' addresses without their query strings — are looked up first,\n * against a cache (`web-risk.ts`), and noted beside the version it serves so\n * the daily re-check can look again: a harvester is often listed only after\n * it is published. A lookup that fails finds nothing, so it never holds a\n * 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 type ForeignReputationLinks,\n foreignLinksForReputation,\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 { lookupLinkReputation, 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), and the\n * addresses on them worth asking about (AGL-3459), 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, ForeignReputationLinks>()\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, the addresses on them worth asking\n * about, and the ones Google Web Risk lists (AGL-3451; addresses only in\n * `'url'` mode, AGL-3459). Foreign before the workspace is known: not the\n * platform's own, not a brand's own domain, not a common social link. The\n * addresses carry no query string or fragment. Never throws; a lookup that\n * failed lists nothing.\n */\nasync function pageLinkReputation(\n linkUrls: readonly string[],\n): Promise<ForeignReputationLinks & { 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 foreign = foreignLinksForReputation(linkUrls, {\n excludeDomains: platformReputationExclusions(),\n })\n if (!foreign.hosts.length) return { ...foreign, signals: [] }\n const answer = await lookupLinkReputation(foreign.hosts, { urls: foreign.urls })\n return { ...foreign, 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: [], urls: [], 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.linkUrls)\n if (reviewedForeignHosts.size >= REVIEWED_FOREIGN_HOSTS_MAX) reviewedForeignHosts.clear()\n reviewedForeignHosts.set(`${request.hostId}/${request.screenId}/${request.versionId}`, {\n hosts: reputation.hosts,\n urls: reputation.urls,\n })\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.linkUrls)\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, and the addresses on them, as\n // its review found them (AGL-3451, AGL-3459): noted beside it so the daily\n // link re-check can walk them. An address carries no query string.\n const foreign = reviewedForeignHosts.get(`${key}/${versionId}`)\n const linksKey = foreign ? `${foreign.hosts.join(',')}|${foreign.urls.join(',')}` : ''\n const memoValue = foreign ? `${versionId}|${linksKey}` : 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 storedHosts = snapshot.get('foreignHosts')\n const storedLinks = snapshot.get('foreignLinks')\n const linksMoved =\n foreign !== undefined &&\n `${Array.isArray(storedHosts) ? storedHosts.join(',') : ''}|${\n Array.isArray(storedLinks) ? storedLinks.join(',') : ''\n }` !== linksKey\n if (versionMoved || linksMoved) {\n await ref.set(\n {\n ...(versionMoved ? { servedVersionId: versionId, servedAtMs: Date.now() } : {}),\n ...(foreign\n ? {\n foreignHosts: foreign.hosts,\n foreignHostCount: foreign.hosts.length,\n foreignLinks: foreign.urls,\n }\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","foreignLinksForReputation","webRiskSignals","FieldValue","firebaseAdmin","describeHeldPage","notifyRiskEvent","orgAgeDays","requestPageSecurityHold","getHostDocAdmin","getOrgForHost","lookupLinkReputation","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","linkUrls","foreign","excludeDomains","hosts","length","answer","urls","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","linksKey","memoValue","versionMoved","storedHosts","storedLinks","linksMoved","Array","isArray","servedVersionId","servedAtMs","foreignHosts","foreignHostCount","foreignLinks","flagLookalikeDomain","brand","id","sending","link","where","notifyLookalikeLink","flagLookalikeCustomDomain"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA8E2C,GAE3C,SAASA,uBAAuB,QAAQ,sCAAqC;AAC7E,SACEC,mBAAmB,EACnBC,eAAe,EACfC,aAAa,EACbC,u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OC,GACD,OAAO,eAAeoJ,oBAAoB3C,KAQzC;QAGUA,cAEGA;IAJZ,MAAMpJ,gBAAgB;QACpBoH,MAAM;QACNvB,KAAK,GAAEuD,eAAAA,MAAMvD,KAAK,YAAXuD,eAAe;QACtBpI,QAAQoI,MAAMpI,MAAM;QACpB0C,QAAQ,GAAE0F,kBAAAA,MAAM1F,QAAQ,YAAd0F,kBAAkB;QAC5B5C,WAAW4C,MAAM5C,SAAS;QAC1BwB,MAAM;YACJd,OAAO,GAAGkC,MAAM0C,KAAK,CAAC,aAAa,EAAE1C,MAAMjG,MAAM,EAAE;YACnDkE,MAAM+B,MAAMpI,MAAM,GAAG,CAAC,CAAC,EAAEoI,MAAMpI,MAAM,CAAC,SAAS,CAAC,GAAG;QACrD;QACAwJ,eACE,CAAC,kBAAkB,EAAEpB,MAAM0C,KAAK,CAAC,IAAI,EAAE1C,MAAMjG,MAAM,CAAC,mBAAmB,EAAEiG,MAAMlC,KAAK,CAAC,EAAE,CAAC,GACxF;IACJ,GAAG7C,KAAK,CAAC,IAAMsB;AACjB;AAEA,iEAAiE,GACjE,OAAO,SAASqG,0BAA0B5C,KAIzC;IACC,OAAOqC,oBAAoB;QAAErE,MAAM;OAAWgC;AAChD"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type LeavingNoticeConfig } from '@aglyn/aglyn/app-utils/leaving-notice';
18
+ import { type SiteReturnHost } from '@aglyn/aglyn/app-utils/site-return-url';
19
+ /** How long a new free workspace's sites carry the notice. */
20
+ export declare const LEAVING_NOTICE_DAYS = 14;
21
+ /**
22
+ * The most outside addresses one page is signed for. A page with more is a
23
+ * link farm, and the ones past the cap still go through the notice — which
24
+ * refuses them — rather than around it.
25
+ */
26
+ export declare const LEAVING_NOTICE_MAX_DESTINATIONS = 500;
27
+ /**
28
+ * When a workspace's notice window closes (epoch ms), or `null` when its
29
+ * sites carry no notice: a paid plan, a workspace past its first
30
+ * {@link LEAVING_NOTICE_DAYS} days, or one whose creation date is unreadable.
31
+ *
32
+ * Takes the org as loaded anywhere — a live document, or the render cache's
33
+ * JSON copy, whose `createdAt` has lost its methods (`orgCreatedMs`).
34
+ */
35
+ export declare function leavingNoticeEndsAt(org: unknown, nowMs?: number): number | null;
36
+ /**
37
+ * The hosts a link may reach without the notice: the site's own (its
38
+ * subdomain, its custom domain and `www.` of it) and the platform's own — the
39
+ * marketing site, console, support and docs, each with every name under its
40
+ * registrable domain, plus the bare tenant apex.
41
+ *
42
+ * Other sites on the tenant apex are NOT exempt. They are other customers'
43
+ * sites, and a chain of two new free sites is the same hop as one.
44
+ */
45
+ export declare function leavingNoticeHosts(site: SiteReturnHost | null | undefined): string[];
46
+ /**
47
+ * Every outside address a rendered page could link to: each string in the
48
+ * payload that is one, and each one embedded in a string (Markdown, rich
49
+ * text HTML, a plain sentence). Over-collecting is harmless — a signature
50
+ * nobody follows is never read — and under-collecting only sends a link to a
51
+ * refusal, never around the notice.
52
+ *
53
+ * Returned normalized, the spelling the client looks signatures up by.
54
+ */
55
+ export declare function collectLeavingDestinations(value: unknown, hosts: readonly string[], limit?: number): string[];
56
+ /**
57
+ * The signature for one destination on one site. Throws when the deployment
58
+ * has no signing secret, like every signer of it.
59
+ */
60
+ export declare function signLeavingDestination(hostId: string, destination: string): string;
61
+ /**
62
+ * Whether `signature` was issued for `destination` on this site. False for
63
+ * anything else — another site's signature, an edited address, a missing
64
+ * secret (fail closed).
65
+ */
66
+ export declare function verifyLeavingDestination(hostId: string, destination: unknown, signature: unknown): boolean;
67
+ /** Signs a page's destinations for one site. */
68
+ export declare function signLeavingDestinations(hostId: string, destinations: readonly string[]): Record<string, string>;
69
+ /**
70
+ * What a published page of this site carries, or `null` when the site is not
71
+ * in its window.
72
+ *
73
+ * `content` is everything the page renders from — its props, its nodes —
74
+ * walked for outside addresses to sign.
75
+ *
76
+ * A deployment with no signing secret gets no notice, loudly. The route
77
+ * could verify nothing there and would refuse every link on every new free
78
+ * site; an outage of every outbound link is not a safer failure than the
79
+ * links working as they did before this existed.
80
+ */
81
+ export declare function leavingNoticeConfig(options: {
82
+ hostId: string | null | undefined;
83
+ site: SiteReturnHost | null | undefined;
84
+ org: unknown;
85
+ content?: unknown;
86
+ nowMs?: number;
87
+ }): LeavingNoticeConfig | null;
88
+ /**
89
+ * Only the signatures, for a payload that arrives after its page — a gated
90
+ * screen's nodes (`enrichGatedScreenPage`). `null` outside the window.
91
+ */
92
+ export declare function leavingNoticeSignatures(options: {
93
+ hostId: string | null | undefined;
94
+ site: SiteReturnHost | null | undefined;
95
+ org: unknown;
96
+ content: unknown;
97
+ nowMs?: number;
98
+ }): Record<string, string> | null;
@@ -0,0 +1,250 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /*==========================================
17
+ * THE "YOU'RE LEAVING THIS SITE" NOTICE, SERVER HALF (AGL-3452).
18
+ *
19
+ * Who gets it, which hosts are exempt, and the signature that keeps the
20
+ * notice route from becoming an open redirect. The client half — rewriting
21
+ * an href, the click interceptor — is `@aglyn/aglyn/app-utils/leaving-notice`.
22
+ *
23
+ * ## Who
24
+ *
25
+ * A site whose workspace is on the FREE plan (the effective plan, so a dead
26
+ * subscription counts as free, as it does for every entitlement) and in its
27
+ * first {@link LEAVING_NOTICE_DAYS} days — the same window, read through the
28
+ * same `isYoungWorkspaceAge`, as the soft phishing rules. Paid and older
29
+ * workspaces are untouched, and a workspace whose creation date cannot be
30
+ * read is an existing customer, never a new one.
31
+ *
32
+ * ## Why signed
33
+ *
34
+ * The notice lives on the site's own host and its Continue button goes
35
+ * wherever `?to=` says. Unsigned, any site's notice would be a page that
36
+ * vouches for any address anyone puts in a link — the hop this feature exists
37
+ * to remove. So the server signs each outside address it finds on a page it
38
+ * renders, bound to that site, and the route shows a Continue button only for
39
+ * an address whose signature checks out. Everything else is refused.
40
+ *
41
+ * The signature carries no expiry on purpose. The route never redirects on
42
+ * its own, so a signature that outlives its page buys nothing but one more
43
+ * view of the same warning — while an expiring one would break the links an
44
+ * ISR-cached page is still serving the moment the window closes.
45
+ *=========================================*/ import { createHmac } from "crypto";
46
+ import { DOCS_BASE_URL } from "@aglyn/aglyn/app-utils/docs-help";
47
+ import { leavingDestination, normalizeLeavingDestination } from "@aglyn/aglyn/app-utils/leaving-notice";
48
+ import { resolveEffectivePlan } from "@aglyn/aglyn/app-utils/plan-entitlements";
49
+ import { PLATFORM_HOME_URL, PLATFORM_SUPPORT_URL, platformConsoleOrigin } from "@aglyn/aglyn/app-utils/platform-brand";
50
+ import { siteOwnHosts } from "@aglyn/aglyn/app-utils/site-return-url";
51
+ import { TENANT_APEX } from "@aglyn/aglyn/app-utils/tenant-apex";
52
+ import { isYoungWorkspaceAge, OUTBOUND_REVIEW_YOUNG_DAYS, registrableDomain } from "@aglyn/shared-util-email/outbound-phishing-screen";
53
+ import { tokenSigningSecret } from "./media-signing.js";
54
+ import { orgAgeDays, orgCreatedMs } from "./org-age.js";
55
+ import { safeEqual } from "./safe-equal.js";
56
+ /** How long a new free workspace's sites carry the notice. */ export const LEAVING_NOTICE_DAYS = OUTBOUND_REVIEW_YOUNG_DAYS;
57
+ const DAY_MS = 86400000;
58
+ /**
59
+ * The most outside addresses one page is signed for. A page with more is a
60
+ * link farm, and the ones past the cap still go through the notice — which
61
+ * refuses them — rather than around it.
62
+ */ export const LEAVING_NOTICE_MAX_DESTINATIONS = 500;
63
+ /** Deepest a page payload is walked; composed node maps sit far above it. */ const MAX_WALK_DEPTH = 64;
64
+ /** Longest string scanned for embedded addresses (a long entry body). */ const MAX_SCANNED_STRING = 200000;
65
+ /**
66
+ * When a workspace's notice window closes (epoch ms), or `null` when its
67
+ * sites carry no notice: a paid plan, a workspace past its first
68
+ * {@link LEAVING_NOTICE_DAYS} days, or one whose creation date is unreadable.
69
+ *
70
+ * Takes the org as loaded anywhere — a live document, or the render cache's
71
+ * JSON copy, whose `createdAt` has lost its methods (`orgCreatedMs`).
72
+ */ export function leavingNoticeEndsAt(org, nowMs = Date.now()) {
73
+ if (!org || typeof org !== 'object') return null;
74
+ if (resolveEffectivePlan(org) !== 'free') return null;
75
+ const createdAt = org.createdAt;
76
+ if (!isYoungWorkspaceAge(orgAgeDays(createdAt, nowMs))) return null;
77
+ const createdMs = orgCreatedMs(createdAt);
78
+ return createdMs === null ? null : createdMs + LEAVING_NOTICE_DAYS * DAY_MS;
79
+ }
80
+ function hostnameOf(raw) {
81
+ if (!raw) return null;
82
+ try {
83
+ const url = new URL(raw);
84
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
85
+ return url.hostname.toLowerCase() || null;
86
+ } catch (unused) {
87
+ return null;
88
+ }
89
+ }
90
+ /**
91
+ * The hosts a link may reach without the notice: the site's own (its
92
+ * subdomain, its custom domain and `www.` of it) and the platform's own — the
93
+ * marketing site, console, support and docs, each with every name under its
94
+ * registrable domain, plus the bare tenant apex.
95
+ *
96
+ * Other sites on the tenant apex are NOT exempt. They are other customers'
97
+ * sites, and a chain of two new free sites is the same hop as one.
98
+ */ export function leavingNoticeHosts(site) {
99
+ const hosts = new Set(siteOwnHosts(site));
100
+ const apex = TENANT_APEX.toLowerCase();
101
+ hosts.add(apex);
102
+ const apexRegistrable = registrableDomain(apex);
103
+ for (const raw of [
104
+ PLATFORM_HOME_URL,
105
+ platformConsoleOrigin(),
106
+ PLATFORM_SUPPORT_URL,
107
+ DOCS_BASE_URL
108
+ ]){
109
+ const hostname = hostnameOf(raw);
110
+ if (!hostname) continue;
111
+ hosts.add(hostname);
112
+ const registrable = registrableDomain(hostname);
113
+ // A platform name under the tenant apex itself must not exempt the apex:
114
+ // that would exempt every customer's site with it.
115
+ if (registrable.includes('.') && registrable !== apexRegistrable) {
116
+ hosts.add(`.${registrable}`);
117
+ }
118
+ }
119
+ return [
120
+ ...hosts
121
+ ];
122
+ }
123
+ /** An address as it appears in text: scheme, then anything a URL may hold. */ const EMBEDDED_URL = /https?:\/\/[^\s"'<>()[\]{}\\^`|]+/gi;
124
+ /** Characters prose puts after an address that the address does not own. */ const TRAILING_PROSE = /[.,;:!?'"*_~]+$/;
125
+ /** A whole value shaped like an absolute or protocol-relative address. */ const ADDRESS_SHAPE = /^\s*(?:https?:|[\\/]{2})/i;
126
+ /**
127
+ * Every outside address a rendered page could link to: each string in the
128
+ * payload that is one, and each one embedded in a string (Markdown, rich
129
+ * text HTML, a plain sentence). Over-collecting is harmless — a signature
130
+ * nobody follows is never read — and under-collecting only sends a link to a
131
+ * refusal, never around the notice.
132
+ *
133
+ * Returned normalized, the spelling the client looks signatures up by.
134
+ */ export function collectLeavingDestinations(value, hosts, limit = LEAVING_NOTICE_MAX_DESTINATIONS) {
135
+ const found = new Set();
136
+ const consider = (candidate)=>{
137
+ if (found.size >= limit) return;
138
+ const destination = leavingDestination(candidate, hosts);
139
+ if (destination) found.add(destination);
140
+ };
141
+ const scan = (text)=>{
142
+ if (ADDRESS_SHAPE.test(text)) consider(text);
143
+ if (!text.includes('http')) return;
144
+ const scanned = text.length > MAX_SCANNED_STRING ? text.slice(0, MAX_SCANNED_STRING) : text;
145
+ for (const match of scanned.matchAll(EMBEDDED_URL)){
146
+ const raw = match[0];
147
+ consider(raw);
148
+ const trimmed = raw.replace(TRAILING_PROSE, '');
149
+ if (trimmed !== raw) consider(trimmed);
150
+ // An href inside stored HTML is entity-encoded; the DOM decodes it.
151
+ if (trimmed.includes('&amp;')) consider(trimmed.replace(/&amp;/g, '&'));
152
+ }
153
+ };
154
+ const walk = (node, depth)=>{
155
+ if (found.size >= limit || depth > MAX_WALK_DEPTH) return;
156
+ if (typeof node === 'string') {
157
+ scan(node);
158
+ } else if (Array.isArray(node)) {
159
+ for (const item of node)walk(item, depth + 1);
160
+ } else if (node && typeof node === 'object') {
161
+ for (const item of Object.values(node))walk(item, depth + 1);
162
+ }
163
+ };
164
+ walk(value, 0);
165
+ return [
166
+ ...found
167
+ ];
168
+ }
169
+ function leavingSignature(hostId, destination) {
170
+ return createHmac('sha256', tokenSigningSecret()).update(`leaving-notice:v1:${hostId}:${destination}`).digest('base64url');
171
+ }
172
+ /**
173
+ * The signature for one destination on one site. Throws when the deployment
174
+ * has no signing secret, like every signer of it.
175
+ */ export function signLeavingDestination(hostId, destination) {
176
+ const normalized = normalizeLeavingDestination(destination);
177
+ if (!hostId || !normalized) {
178
+ throw new Error('A leaving-notice signature needs a site and an address');
179
+ }
180
+ return leavingSignature(hostId, normalized);
181
+ }
182
+ /**
183
+ * Whether `signature` was issued for `destination` on this site. False for
184
+ * anything else — another site's signature, an edited address, a missing
185
+ * secret (fail closed).
186
+ */ export function verifyLeavingDestination(hostId, destination, signature) {
187
+ if (!hostId || typeof signature !== 'string' || signature.length > 128) {
188
+ return false;
189
+ }
190
+ const normalized = normalizeLeavingDestination(destination);
191
+ if (!normalized) return false;
192
+ let expected;
193
+ try {
194
+ expected = leavingSignature(hostId, normalized);
195
+ } catch (unused) {
196
+ return false;
197
+ }
198
+ return safeEqual(signature, expected);
199
+ }
200
+ /** Signs a page's destinations for one site. */ export function signLeavingDestinations(hostId, destinations) {
201
+ const sigs = {};
202
+ for (const destination of destinations){
203
+ sigs[destination] = leavingSignature(hostId, destination);
204
+ }
205
+ return sigs;
206
+ }
207
+ /** Whether this deployment can sign at all. */ function canSign() {
208
+ try {
209
+ tokenSigningSecret();
210
+ return true;
211
+ } catch (unused) {
212
+ return false;
213
+ }
214
+ }
215
+ /**
216
+ * What a published page of this site carries, or `null` when the site is not
217
+ * in its window.
218
+ *
219
+ * `content` is everything the page renders from — its props, its nodes —
220
+ * walked for outside addresses to sign.
221
+ *
222
+ * A deployment with no signing secret gets no notice, loudly. The route
223
+ * could verify nothing there and would refuse every link on every new free
224
+ * site; an outage of every outbound link is not a safer failure than the
225
+ * links working as they did before this existed.
226
+ */ export function leavingNoticeConfig(options) {
227
+ const { hostId, site, org, content } = options;
228
+ if (!hostId || !site) return null;
229
+ const until = leavingNoticeEndsAt(org, options.nowMs);
230
+ if (until === null) return null;
231
+ if (!canSign()) {
232
+ console.error('[leaving-notice] TOKEN_SIGNING_SECRET is not configured; the notice is off');
233
+ return null;
234
+ }
235
+ const hosts = leavingNoticeHosts(site);
236
+ return {
237
+ until,
238
+ hosts,
239
+ sigs: signLeavingDestinations(hostId, collectLeavingDestinations(content, hosts))
240
+ };
241
+ }
242
+ /**
243
+ * Only the signatures, for a payload that arrives after its page — a gated
244
+ * screen's nodes (`enrichGatedScreenPage`). `null` outside the window.
245
+ */ export function leavingNoticeSignatures(options) {
246
+ const config = leavingNoticeConfig(options);
247
+ return config && Object.keys(config.sigs).length ? config.sigs : null;
248
+ }
249
+
250
+ //# sourceMappingURL=leaving-notice.js.map