@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.
- package/package.json +7 -7
- package/src/lib/server/api-keys.js +3 -3
- package/src/lib/server/api-keys.js.map +1 -1
- package/src/lib/server/api-v1-resources.d.ts +44 -3
- package/src/lib/server/api-v1-resources.js +82 -5
- package/src/lib/server/api-v1-resources.js.map +1 -1
- package/src/lib/server/collection-live-pages.d.ts +2 -2
- package/src/lib/server/collection-live-pages.js +1 -1
- package/src/lib/server/collection-live-pages.js.map +1 -1
- package/src/lib/server/email-delivery-log.d.ts +17 -73
- package/src/lib/server/email-delivery-log.js +44 -222
- package/src/lib/server/email-delivery-log.js.map +1 -1
- package/src/lib/server/email-flow-gate.js +27 -38
- package/src/lib/server/email-flow-gate.js.map +1 -1
- package/src/lib/server/erase-person.d.ts +34 -54
- package/src/lib/server/erase-person.js +44 -239
- package/src/lib/server/erase-person.js.map +1 -1
- package/src/lib/server/host-visitor-records.d.ts +12 -4
- package/src/lib/server/host-visitor-records.js +20 -10
- package/src/lib/server/host-visitor-records.js.map +1 -1
- package/src/lib/server/hosted-page-review.d.ts +7 -0
- package/src/lib/server/hosted-page-review.js +144 -20
- package/src/lib/server/hosted-page-review.js.map +1 -1
- package/src/lib/server/leaving-notice.d.ts +98 -0
- package/src/lib/server/leaving-notice.js +250 -0
- package/src/lib/server/leaving-notice.js.map +1 -0
- package/src/lib/server/link-reputation-review.d.ts +58 -0
- package/src/lib/server/link-reputation-review.js +185 -0
- package/src/lib/server/link-reputation-review.js.map +1 -0
- package/src/lib/server/live-page-drops.d.ts +67 -0
- package/src/lib/server/live-page-drops.js +57 -0
- package/src/lib/server/live-page-drops.js.map +1 -0
- package/src/lib/server/media-bandwidth-cap.d.ts +78 -0
- package/src/lib/server/media-bandwidth-cap.js +180 -0
- package/src/lib/server/media-bandwidth-cap.js.map +1 -0
- package/src/lib/server/media-cdn-icon.d.ts +77 -0
- package/src/lib/server/media-cdn-icon.js +140 -0
- package/src/lib/server/media-cdn-icon.js.map +1 -0
- package/src/lib/server/media-delivery-regeneration.d.ts +132 -0
- package/src/lib/server/media-delivery-regeneration.js +216 -0
- package/src/lib/server/media-delivery-regeneration.js.map +1 -0
- package/src/lib/server/media-delivery.d.ts +2 -0
- package/src/lib/server/media-delivery.js +2 -1
- package/src/lib/server/media-delivery.js.map +1 -1
- package/src/lib/server/media-serve-count.d.ts +50 -0
- package/src/lib/server/media-serve-count.js +62 -0
- package/src/lib/server/media-serve-count.js.map +1 -0
- package/src/lib/server/media-signing.d.ts +13 -2
- package/src/lib/server/media-signing.js +12 -8
- package/src/lib/server/media-signing.js.map +1 -1
- package/src/lib/server/media-tombstone.js +7 -5
- package/src/lib/server/media-tombstone.js.map +1 -1
- package/src/lib/server/media-variants.d.ts +151 -20
- package/src/lib/server/media-variants.js +204 -27
- package/src/lib/server/media-variants.js.map +1 -1
- package/src/lib/server/org-age.d.ts +15 -6
- package/src/lib/server/org-age.js +20 -8
- package/src/lib/server/org-age.js.map +1 -1
- package/src/lib/server/organizations.d.ts +102 -2
- package/src/lib/server/organizations.js +388 -58
- package/src/lib/server/organizations.js.map +1 -1
- package/src/lib/server/outbound-send-review.js +24 -6
- package/src/lib/server/outbound-send-review.js.map +1 -1
- package/src/lib/server/page-security-hold.d.ts +93 -0
- package/src/lib/server/page-security-hold.js +180 -0
- package/src/lib/server/page-security-hold.js.map +1 -0
- package/src/lib/server/paged-sweeps.d.ts +51 -0
- package/src/lib/server/paged-sweeps.js +79 -0
- package/src/lib/server/paged-sweeps.js.map +1 -0
- package/src/lib/server/platform-marketing-consent.d.ts +0 -49
- package/src/lib/server/platform-marketing-consent.js +27 -11
- package/src/lib/server/platform-marketing-consent.js.map +1 -1
- package/src/lib/server/serve-media-cdn.d.ts +69 -1
- package/src/lib/server/serve-media-cdn.js +424 -70
- package/src/lib/server/serve-media-cdn.js.map +1 -1
- package/src/lib/server/site-icon-render.d.ts +68 -0
- package/src/lib/server/site-icon-render.js +157 -0
- package/src/lib/server/site-icon-render.js.map +1 -0
- package/src/lib/server/staff-seat.d.ts +50 -0
- package/src/lib/server/staff-seat.js +118 -0
- package/src/lib/server/staff-seat.js.map +1 -0
- package/src/lib/server/transfer-export.d.ts +46 -0
- package/src/lib/server/transfer-export.js +221 -0
- package/src/lib/server/transfer-export.js.map +1 -0
- package/src/lib/server/transfer-jobs.d.ts +385 -0
- package/src/lib/server/transfer-jobs.js +2368 -0
- package/src/lib/server/transfer-jobs.js.map +1 -0
- package/src/lib/server/transfer-packages.d.ts +127 -0
- package/src/lib/server/transfer-packages.js +1036 -0
- package/src/lib/server/transfer-packages.js.map +1 -0
- package/src/lib/server/upgrade-proposal.d.ts +97 -0
- package/src/lib/server/upgrade-proposal.js +312 -0
- package/src/lib/server/upgrade-proposal.js.map +1 -0
- package/src/lib/server/upsert-contact.d.ts +17 -8
- package/src/lib/server/upsert-contact.js +82 -16
- package/src/lib/server/upsert-contact.js.map +1 -1
- package/src/lib/server/web-risk.d.ts +139 -0
- package/src/lib/server/web-risk.js +521 -0
- package/src/lib/server/web-risk.js.map +1 -0
- package/src/tenancy.d.ts +3 -1
- package/src/tenancy.js +5 -1
- package/src/tenancy.js.map +1 -1
- package/src/lib/server/campaign-attribution-store.d.ts +0 -55
- package/src/lib/server/campaign-attribution-store.js +0 -95
- package/src/lib/server/campaign-attribution-store.js.map +0 -1
- package/src/lib/server/campaign-conversion-attribution.d.ts +0 -283
- package/src/lib/server/campaign-conversion-attribution.js +0 -450
- package/src/lib/server/campaign-conversion-attribution.js.map +0 -1
- package/src/lib/server/dataset-live-pages.d.ts +0 -179
- package/src/lib/server/dataset-live-pages.js +0 -421
- package/src/lib/server/dataset-live-pages.js.map +0 -1
- package/src/lib/server/email-revenue-attribution.d.ts +0 -185
- package/src/lib/server/email-revenue-attribution.js +0 -321
- package/src/lib/server/email-revenue-attribution.js.map +0 -1
|
@@ -53,12 +53,14 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
53
53
|
*=========================================*/ import { createHash } from "crypto";
|
|
54
54
|
import { ABUSE_REPORT_COLLECTION } from "@aglyn/aglyn/app-utils/abuse-report";
|
|
55
55
|
import { TENANT_APEX } from "@aglyn/aglyn/app-utils/host-naming";
|
|
56
|
-
import {
|
|
56
|
+
import { linkReputationSignals } from "@aglyn/shared-util-email/link-reputation";
|
|
57
|
+
import { describePhishingScreenSignals, isYoungWorkspaceAge, linkUrlsIn, OUTBOUND_REVIEW_YOUNG_DAYS, screenOutboundEmail, signalsThatHold } from "@aglyn/shared-util-email/outbound-phishing-screen";
|
|
57
58
|
import { setOutboundScreenGate } from "@aglyn/shared-util-email/outbound-screen-gate";
|
|
58
59
|
import { FieldValue } from "firebase-admin/firestore";
|
|
59
60
|
import { orgAgeDays } from "./org-age.js";
|
|
60
61
|
import firebaseAdmin from "./firebase-admin.js";
|
|
61
62
|
import { notifyRiskEvent } from "./risk-notice.js";
|
|
63
|
+
import { installLinkReputationLookup } from "./web-risk.js";
|
|
62
64
|
/** A workspace younger than this many days has the soft rules applied. */ export { OUTBOUND_REVIEW_YOUNG_DAYS };
|
|
63
65
|
/**
|
|
64
66
|
* Where a held campaign is parked: a send time no processor run reaches.
|
|
@@ -292,6 +294,10 @@ import { notifyRiskEvent } from "./risk-notice.js";
|
|
|
292
294
|
var _request_org;
|
|
293
295
|
const nowMs = (_request_nowMs = request.nowMs) != null ? _request_nowMs : Date.now();
|
|
294
296
|
const ageDays = orgAgeDays((_request_org = request.org) == null ? void 0 : _request_org.createdAt, nowMs);
|
|
297
|
+
const identity = workspaceScreenIdentity({
|
|
298
|
+
org: request.org,
|
|
299
|
+
host: request.host
|
|
300
|
+
});
|
|
295
301
|
const verdict = screenOutboundEmail(_extends({
|
|
296
302
|
subject: request.subject,
|
|
297
303
|
fromName: (_request_fromName = request.fromName) != null ? _request_fromName : null,
|
|
@@ -299,11 +305,21 @@ import { notifyRiskEvent } from "./risk-notice.js";
|
|
|
299
305
|
replyTo: (_request_replyTo = request.replyTo) != null ? _request_replyTo : null,
|
|
300
306
|
preheader: (_request_preheader = request.preheader) != null ? _request_preheader : null,
|
|
301
307
|
bodies: request.bodies
|
|
302
|
-
},
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
const
|
|
308
|
+
}, identity));
|
|
309
|
+
// Every foreign link it carries, against the reputation list (AGL-3451):
|
|
310
|
+
// its host, and in 'url' mode its address (AGL-3459). A listing holds for
|
|
311
|
+
// every workspace, a failed lookup holds nothing.
|
|
312
|
+
const reputation = await linkReputationSignals(linkUrlsIn([
|
|
313
|
+
request.subject,
|
|
314
|
+
request.preheader,
|
|
315
|
+
...request.bodies
|
|
316
|
+
].filter(Boolean).join('\n')), {
|
|
317
|
+
ownDomains: identity.ownDomains
|
|
318
|
+
});
|
|
319
|
+
const signals = signalsThatHold([
|
|
320
|
+
...verdict.signals,
|
|
321
|
+
...reputation
|
|
322
|
+
], {
|
|
307
323
|
ageDays
|
|
308
324
|
});
|
|
309
325
|
if (!signals.length) return {
|
|
@@ -484,6 +500,8 @@ const seamMemo = new Map();
|
|
|
484
500
|
*/ export function installOutboundScreenGate() {
|
|
485
501
|
if (typeof setOutboundScreenGate !== 'function') return;
|
|
486
502
|
setOutboundScreenGate((request)=>screenSeamMessage(request));
|
|
503
|
+
// And the link reputation lookup the same screen asks (AGL-3451).
|
|
504
|
+
installLinkReputationLookup();
|
|
487
505
|
}
|
|
488
506
|
/**
|
|
489
507
|
* Apply a staff decision to a held send (the admin abuse route, in the same
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/outbound-send-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: outbound mail from a young workspace (AGL-3356).\n *\n * The phishing screen (`screenOutboundEmail`, shared-util-email) decides\n * whether a message carries a phishing signal, and `signalsThatHold` beside\n * it decides which signals hold for whom. This module is what happens next,\n * for every surface that screens — the send seam every tenant message\n * crosses ({@link installOutboundScreenGate}), the campaign core and the\n * automation step before they commit, and a site publish\n * (`hosted-page-review.ts`) — so none restates it:\n *\n * - WHO IS SCREENED. Every workspace, in two tiers. A lookalike link holds\n * whatever the workspace's age. The soft rules (a brand in the sender\n * name, the three-part lure) hold only for a workspace younger than\n * {@link OUTBOUND_REVIEW_YOUNG_DAYS}: the incident's workspace was days\n * old, and an established customer's clumsy copy never waits on them. An\n * org whose creation date cannot be read is an existing customer (the same\n * reading `orgAgeDays` gives the sending ramp) and is not young.\n * - WHERE A HOLD GOES. Into the abuse queue at `/admin/abuse-reports` — the\n * staff surface that already exists to answer \"is this phishing\", with its\n * audit trail, its urgent count and its staff notification — as a\n * `phishing` row whose `heldSend` names the message. Not a new queue: a\n * second place to look is a place nobody looks.\n * - HOW STAFF DECIDE. By the row's existing status. `dismissed` (a false\n * positive) RELEASES the send; `actioned` REJECTS it. The admin route\n * calls {@link decideHeldOutboundSend} in the same act as the status\n * write, so the decision and its audit row cannot come apart.\n * - WHAT A RELEASE COVERS. Exactly the content that was held: the review\n * row's id is derived from the message's source and a hash of its\n * content, so an edited message is screened afresh rather than riding a\n * release granted to different words.\n *\n * A hold is never a drop. A held campaign is parked as a scheduled send that\n * a release puts back on the clock; a held automation step fails that one\n * run with a reason the merchant can read, or — after a wait — stays queued\n * until the decision.\n *=========================================*/\n\nimport { createHash } from 'crypto'\nimport { ABUSE_REPORT_COLLECTION } from '@aglyn/aglyn/app-utils/abuse-report'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/host-naming'\nimport {\n describePhishingScreenSignals,\n isYoungWorkspaceAge,\n OUTBOUND_REVIEW_YOUNG_DAYS,\n type PhishingScreenInput,\n type PhishingScreenSignal,\n screenOutboundEmail,\n signalsThatHold,\n} from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport {\n type OutboundScreenGateRequest,\n type OutboundScreenGateVerdict,\n type SendingWorkspace,\n setOutboundScreenGate,\n} from '@aglyn/shared-util-email/outbound-screen-gate'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { orgAgeDays } from './org-age'\nimport firebaseAdmin from './firebase-admin'\nimport { notifyRiskEvent, type RiskEventInput, type RiskEventItem } from './risk-notice'\n\n/** A workspace younger than this many days has the soft rules applied. */\nexport { OUTBOUND_REVIEW_YOUNG_DAYS }\n\n/**\n * Where a held campaign is parked: a send time no processor run reaches.\n * A release replaces it with \"now\"; nothing else ever does, so a hold that\n * nobody decides stays a hold rather than lapsing into a send.\n */\nexport const HELD_SEND_AT_MS = 253402300799000\n\n/**\n * Which surface held it: a campaign, an automation step, any other tenant\n * message at the send seam (`message`), a site publish (`page`), or a\n * submission to a public catalog a plugin keeps — a marketplace listing, its\n * publisher profile (`listing`, AGL-3365).\n */\nexport type HeldOutboundSendKind =\n | 'campaign'\n | 'action'\n | 'workflow'\n | 'orgAutomation'\n | 'message'\n | 'page'\n | 'listing'\n\n/** The decision state a held send carries on its review row. */\nexport type HeldOutboundSendState = 'held' | 'released' | 'rejected'\n\n/** What the review row records about the message it holds. */\nexport interface HeldOutboundSend {\n kind: HeldOutboundSendKind\n /** The document the message came from — a send, an action, a workflow. */\n path: string\n hostId: string\n orgId: string | null\n contentHash: string\n subject: string\n fromName: string | null\n signals: PhishingScreenSignal[]\n state: HeldOutboundSendState\n heldAtMs: number\n /** Workspace age in days when it was held, for the reviewer. */\n ageDays: number | null\n}\n\n/**\n * Is this workspace young enough to screen?\n *\n * Age alone, deliberately. Payment history was the other candidate and the\n * incident is the argument against it: the actor PAID, on a card that never\n * met 3-D Secure, within days of signing up. A paid invoice proves a card\n * worked, not that its holder is who they say.\n */\nexport function isYoungWorkspace(\n org: { createdAt?: unknown } | null | undefined,\n nowMs: number = Date.now(),\n): boolean {\n return isYoungWorkspaceAge(orgAgeDays(org?.createdAt, nowMs))\n}\n\n/**\n * The workspace a host's mail belongs to, as the send seam's screen reads it\n * — stamped on the sending identity by `hostSendingIdentity` from the host\n * and org documents it has already read.\n */\nexport function sendingWorkspaceFor(input: {\n hostId: string\n orgId: string | null\n org?: Record<string, unknown> | null\n host?: Record<string, unknown> | null\n nowMs?: number\n}): SendingWorkspace {\n const identity = workspaceScreenIdentity({ org: input.org, host: input.host })\n return {\n hostId: input.hostId,\n orgId: input.orgId,\n ageDays: orgAgeDays(\n (input.org as { createdAt?: unknown } | null | undefined)?.createdAt,\n input.nowMs ?? Date.now(),\n ),\n ownNames: (identity.ownNames ?? []).filter((name): name is string => Boolean(name)),\n ownDomains: (identity.ownDomains ?? []).filter((domain): domain is string => Boolean(domain)),\n }\n}\n\n/**\n * The workspace's own names and hosts, as the screen reads them: a brand in\n * its own name is its own, and a link to its own site is not \"elsewhere\".\n */\nexport function workspaceScreenIdentity(input: {\n org?: Record<string, unknown> | null\n host?: Record<string, unknown> | null\n}): Pick<PhishingScreenInput, 'ownNames' | 'ownDomains'> {\n const org = input.org ?? {}\n const host = input.host ?? {}\n const text = (value: unknown) => (typeof value === 'string' ? value : '')\n const subdomain = text(host['subdomain'])\n return {\n ownNames: [text(org['name']), text(host['name']), subdomain],\n ownDomains: [\n subdomain ? `${subdomain}.${TENANT_APEX}` : '',\n text(host['cname']),\n text(host['sendingDomain']),\n ],\n }\n}\n\n/**\n * JSON with every object's keys sorted, so the same design serializes to the\n * same string however it was read. Firestore hands back a map's keys in an\n * order that differs by reader, and a release keyed on a hash of an unsorted\n * serialization would not match the very content it released.\n */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(value, (_key, entry) =>\n entry && typeof entry === 'object' && !Array.isArray(entry)\n ? Object.fromEntries(\n Object.keys(entry as Record<string, unknown>)\n .sort()\n .map((key) => [key, (entry as Record<string, unknown>)[key]]),\n )\n : entry,\n )\n}\n\n/** A stable hash of what a message says, so a release covers these words only. */\nexport function outboundContentHash(parts: readonly unknown[]): string {\n return createHash('sha256').update(canonicalJson(parts)).digest('hex')\n}\n\n/**\n * The review row's id: one row per (source, content). Hex, so the admin\n * route's report-id pattern addresses it like any intake row.\n */\nexport function heldOutboundReviewId(path: string, contentHash: string): string {\n return createHash('sha256')\n .update(`outbound-hold:${path}:${contentHash}`)\n .digest('hex')\n .slice(0, 40)\n}\n\n/** The staff-facing reference, in the intake's `AR-` style. */\nexport function heldOutboundReference(reviewId: string): string {\n return `HS-${reviewId.slice(0, 10).toUpperCase()}`\n}\n\nexport interface OutboundScreenRequest {\n kind: HeldOutboundSendKind\n path: string\n hostId: string\n orgId: string | null\n org: Record<string, unknown> | null\n host: Record<string, unknown> | null\n subject: string\n fromName?: string | null\n /**\n * The address it leaves from (AGL-3362). Read by the lookalike rule only,\n * and kept out of the content hash so a release granted before this was\n * read still names the same row.\n */\n fromAddress?: string | null\n replyTo?: string | readonly string[] | null\n preheader?: string | null\n bodies: readonly (string | null | undefined)[]\n nowMs?: number\n}\n\n/** What a screen answers for one piece of content. */\nexport type OutboundScreenOutcome =\n | {\n outcome: 'send'\n /** The review row staff released this content under, when there is one. */\n releasedReviewId?: string\n }\n | { outcome: 'held' | 'rejected'; reviewId: string; reference: string; contentHash: string }\n\n/** What a surface files when its screen holds, for {@link fileOutboundHold}. */\nexport interface OutboundHoldFiling {\n reviewId: string\n heldSend: HeldOutboundSend\n /** Extra fields a surface records beside `heldSend` (a page's version). */\n extra?: Record<string, unknown>\n /** The first line of the row's details, naming what was held. */\n headline: string\n /** The staff alert's title and body, the first time. */\n alertTitle: string\n alertBody: string\n /** The URL the row reports: the flagged host, or the held page. */\n url: string | null\n reportedHostname: string | null\n /**\n * What the workspace's owners are told the first time (AGL-3368): the held\n * item in their words and its console page. The alert title and body above\n * are the STAFF half; the owners read the catalog's own words, which never\n * name the signals.\n */\n item?: RiskEventItem | null\n /** A held page, described (AGL-3374): stored on the owners' notice for the console. */\n page?: RiskEventInput['page']\n}\n\n/**\n * The held item as the owners see it, from the surface and the source path\n * (AGL-3368): the campaign's own email page, the automation list, or nothing\n * for a message the send seam held (the notice then leads to Holds & reviews).\n */\nexport function heldSendItem(input: {\n kind: HeldOutboundSendKind\n path: string\n hostId: string\n subject: string\n context?: string | null\n}): RiskEventItem {\n const subject = input.subject.slice(0, 120)\n const id = input.path.split('/').pop() ?? ''\n switch (input.kind) {\n case 'campaign':\n return {\n label: `the campaign \"${subject}\"`,\n path: id ? `/org/emails/messages/${encodeURIComponent(id)}` : null,\n }\n case 'orgAutomation':\n return { label: `the automated email \"${subject}\"`, path: '/org/automation' }\n case 'workflow':\n case 'action':\n return { label: `the automated email \"${subject}\"`, path: `/${input.hostId}/automation` }\n case 'page':\n // A page's subject is its label (`heldPageLabel`, AGL-3374); a row\n // filed before that carried its URL.\n return { label: /^https?:\\/\\//.test(subject) ? `the page ${subject}` : subject, path: null }\n case 'listing':\n // The publisher's own Listings section of the Marketplace hub.\n return { label: `the marketplace submission \"${subject}\"`, path: '/org/marketplace/listings' }\n default:\n return {\n label: input.context\n ? `the email \"${subject}\" (${input.context})`\n : `the email \"${subject}\"`,\n path: null,\n }\n }\n}\n\n/**\n * Write (or count) the review row for a hold, and tell staff the first time.\n * Returns the row's decision state — a row staff already decided answers\n * with that decision and is not written.\n *\n * One writer for every surface, so a campaign, a seam message and a page\n * land in the queue in the one shape the admin route and page already read.\n */\nexport async function fileOutboundHold(\n filing: OutboundHoldFiling,\n): Promise<HeldOutboundSendState> {\n const firestore = firebaseAdmin.app().firestore()\n const ref = firestore.collection(ABUSE_REPORT_COLLECTION).doc(filing.reviewId)\n const reference = heldOutboundReference(filing.reviewId)\n let first = false\n let state = 'held' as HeldOutboundSendState\n await firestore.runTransaction(async (transaction) => {\n const existing = await transaction.get(ref)\n first = !existing.exists\n const stored = existing.exists\n ? (existing.get('heldSend') as Partial<HeldOutboundSend> | undefined)\n : undefined\n state = stored?.state === 'released' || stored?.state === 'rejected'\n ? stored.state\n : 'held'\n if (state !== 'held') return\n transaction.set(\n ref,\n {\n reference,\n category: 'phishing',\n severity: 'urgent',\n // Who filed it: the screen, not a person. The queue reads it to\n // say so, and a reporter-contact field stays honestly empty.\n source: 'outbound-screen',\n // The flagged host as TEXT — the page never renders a reported URL\n // as a link, and this one may be a phishing kit's.\n url: filing.url,\n reportedHostname: filing.reportedHostname,\n hostId: filing.heldSend.hostId,\n orgId: filing.heldSend.orgId,\n details: [\n filing.headline,\n ...describePhishingScreenSignals(filing.heldSend.signals),\n filing.heldSend.kind === 'page'\n ? 'Dismiss to release this publish; mark it actioned to reject it.'\n : filing.heldSend.kind === 'listing'\n ? 'Dismiss to release this submission (the publisher submits it again and it ' +\n 'goes through); mark it actioned to reject it.'\n : 'Dismiss to release this send; mark it actioned to reject it.',\n ]\n .join('\\n')\n .slice(0, 5000),\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n // Every message the same content held counts here, so a workflow\n // firing on each new contact reads as the volume it is.\n reportCount: FieldValue.increment(1),\n heldSend: first\n ? filing.heldSend\n : { ...filing.heldSend, heldAtMs: stored?.heldAtMs ?? filing.heldSend.heldAtMs },\n ...(filing.extra ?? {}),\n updatedAt: FieldValue.serverTimestamp(),\n ...(first\n ? { status: 'open', createdAt: FieldValue.serverTimestamp() }\n : {}),\n },\n { merge: true },\n )\n })\n if (first && state === 'held') {\n // The owners learn what was held and how to ask for a review; staff get\n // the alert with the evidence and a link to this row. One seam, once.\n await notifyRiskEvent({\n kind:\n filing.heldSend.kind === 'page'\n ? 'page-held'\n : filing.heldSend.kind === 'listing'\n ? 'listing-held'\n : 'email-held',\n orgId: filing.heldSend.orgId,\n hostId: filing.heldSend.hostId,\n reviewId: filing.reviewId,\n reference,\n occurredAtMs: filing.heldSend.heldAtMs,\n item:\n filing.item ??\n heldSendItem({\n kind: filing.heldSend.kind,\n path: filing.heldSend.path,\n hostId: filing.heldSend.hostId,\n subject: filing.heldSend.subject,\n }),\n page: filing.page ?? null,\n staffEvidence: [\n filing.alertBody,\n ...describePhishingScreenSignals(filing.heldSend.signals),\n ].join(' '),\n })\n }\n return state\n}\n\n/** The first signal that names a host, for the row's reported URL. */\nexport function flaggedHostOf(signals: readonly PhishingScreenSignal[]): string | null {\n const flagged = signals.find(\n (signal): signal is Extract<PhishingScreenSignal, { host: string }> => 'host' in signal,\n )\n return flagged?.host ?? null\n}\n\n/**\n * The screen's answer for one message, and what to do with it.\n *\n * - `send` — clean under the tiers, or held earlier and RELEASED by staff\n * for exactly this content (then `releasedReviewId` names the row, and the\n * caller hands it to `sendEmail` so the seam's screen honors it too).\n * - `held` — hold it. The review row is written (or its count bumped) and\n * staff are told the first time.\n * - `rejected` — staff rejected exactly this content. Never sent.\n *\n * Every workspace is screened; `signalsThatHold` applies the tiers, so an\n * established workspace is held only by a lookalike link.\n *\n * Fails OPEN on a store error, the posture of every other control on the\n * send path: an outage on the review queue must not become an outage on\n * every workspace's mail. The screen itself cannot fail.\n */\nexport async function screenOutboundSend(\n request: OutboundScreenRequest,\n): Promise<OutboundScreenOutcome> {\n const nowMs = request.nowMs ?? Date.now()\n const ageDays = orgAgeDays(\n (request.org as { createdAt?: unknown } | null)?.createdAt,\n nowMs,\n )\n const verdict = screenOutboundEmail({\n subject: request.subject,\n fromName: request.fromName ?? null,\n fromAddress: request.fromAddress ?? null,\n replyTo: request.replyTo ?? null,\n preheader: request.preheader ?? null,\n bodies: request.bodies,\n ...workspaceScreenIdentity({ org: request.org, host: request.host }),\n })\n const signals = signalsThatHold(verdict.signals, { ageDays })\n if (!signals.length) return { outcome: 'send' }\n\n const contentHash = outboundContentHash([\n request.subject,\n request.fromName ?? '',\n request.replyTo ?? '',\n request.preheader ?? '',\n ...request.bodies.map((body) => body ?? ''),\n ])\n const reviewId = heldOutboundReviewId(request.path, contentHash)\n const reference = heldOutboundReference(reviewId)\n try {\n const heldSend: HeldOutboundSend = {\n kind: request.kind,\n path: request.path,\n hostId: request.hostId,\n orgId: request.orgId,\n contentHash,\n subject: request.subject.slice(0, 300),\n fromName: request.fromName ? String(request.fromName).slice(0, 120) : null,\n signals,\n state: 'held',\n heldAtMs: nowMs,\n ageDays,\n }\n const flagged = flaggedHostOf(signals)\n const state = await fileOutboundHold({\n reviewId,\n heldSend,\n headline:\n `Held ${request.kind === 'campaign' ? 'campaign' : `${request.kind} email step`} ` +\n `\"${heldSend.subject}\" from a workspace ${ageDays ?? '?'} day(s) old.`,\n alertTitle: 'Outbound email held for review — possible phishing',\n alertBody:\n `A ${request.kind === 'campaign' ? 'campaign' : 'automated email'} ` +\n `was held: \"${request.subject.slice(0, 120)}\".`,\n url: flagged ? `https://${flagged}/` : null,\n reportedHostname: flagged,\n })\n if (state === 'released') return { outcome: 'send', releasedReviewId: reviewId }\n return { outcome: state === 'rejected' ? 'rejected' : 'held', reviewId, reference, contentHash }\n } catch (error) {\n console.error('[outbound-review] hold could not be recorded — allowing', error)\n return { outcome: 'send' }\n }\n}\n\n/**\n * How long this process trusts what it last learned about a seam row: that\n * it is held (so the next message carrying the same signals skips the\n * write), or how staff decided it. Short, because a decision must reach a\n * sender within a minute; long enough that a newsletter fanned out to a\n * thousand people costs one transaction rather than a thousand on one\n * document.\n */\nconst SEAM_MEMO_TTL_MS = 60_000\nconst seamMemo = new Map<string, { state: HeldOutboundSendState; atMs: number }>()\n\n/** Test seam: forget what this process learned about seam rows. */\nexport function resetOutboundSeamMemoForTests(): void {\n seamMemo.clear()\n}\n\n/**\n * The seam row's id for a site and the signals that held. Keyed on the\n * SIGNALS rather than the words: a message at the seam is already\n * personalized per recipient, so its words differ for every person while\n * what makes it phishing — the lookalike host, the brand and the lure — does\n * not. A release therefore covers this site's use of exactly these signals,\n * and a message carrying any other signal is screened afresh.\n */\nexport function seamReviewId(hostId: string, signals: readonly PhishingScreenSignal[]): string {\n const key = signals\n .map((signal) => canonicalJson(signal))\n .sort()\n .join('\\n')\n return heldOutboundReviewId(`hosts/${hostId}/outbound`, outboundContentHash([key]))\n}\n\n/** Is this row a staff RELEASE for this site? */\nasync function isReleaseForHost(reviewId: string, hostId: string): Promise<boolean> {\n const memoKey = `release:${hostId}:${reviewId}`\n const memo = seamMemo.get(memoKey)\n if (memo && Date.now() - memo.atMs < SEAM_MEMO_TTL_MS) return memo.state === 'released'\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection(ABUSE_REPORT_COLLECTION)\n .doc(reviewId)\n .get()\n const held = snapshot.get('heldSend') as Partial<HeldOutboundSend> | undefined\n const released = held?.state === 'released' && held?.hostId === hostId\n seamMemo.set(memoKey, { state: released ? 'released' : 'held', atMs: Date.now() })\n return released\n}\n\n/**\n * The send seam's gate: what `sendEmail` asks when a tenant message carries\n * a signal that holds (see `outbound-screen-gate.ts`). Installed at module\n * load by {@link installOutboundScreenGate}.\n *\n * A seam hold REFUSES that one message (`held-for-review`) — the sender's own\n * failure handling reports it, the way it reports a suppression — and files\n * one row per site and signal set. Once staff release it, the site's next\n * message carrying those signals sends; reject it, and none does.\n */\nexport async function screenSeamMessage(\n request: OutboundScreenGateRequest,\n): Promise<OutboundScreenGateVerdict> {\n const { workspace } = request\n if (\n request.releasedReviewId &&\n (await isReleaseForHost(request.releasedReviewId, workspace.hostId))\n ) {\n return { outcome: 'send' }\n }\n const reviewId = seamReviewId(workspace.hostId, request.signals)\n const reference = heldOutboundReference(reviewId)\n const memo = seamMemo.get(reviewId)\n if (memo && Date.now() - memo.atMs < SEAM_MEMO_TTL_MS) {\n return memo.state === 'released'\n ? { outcome: 'send' }\n : { outcome: memo.state === 'rejected' ? 'rejected' : 'held', reference }\n }\n const nowMs = Date.now()\n const subject = String(request.subject ?? '').slice(0, 300)\n const context = request.context ? String(request.context).slice(0, 80) : null\n const flagged = flaggedHostOf(request.signals)\n const state = await fileOutboundHold({\n reviewId,\n heldSend: {\n kind: 'message',\n path: `hosts/${workspace.hostId}`,\n hostId: workspace.hostId,\n orgId: workspace.orgId,\n contentHash: outboundContentHash([request.signals]),\n subject,\n fromName: request.fromName ? String(request.fromName).slice(0, 120) : null,\n signals: request.signals,\n state: 'held',\n heldAtMs: nowMs,\n ageDays: workspace.ageDays,\n },\n extra: { heldContext: context },\n item: heldSendItem({ kind: 'message', path: `hosts/${workspace.hostId}`, hostId: workspace.hostId, subject, context }),\n headline:\n `Held ${context ? `\"${context}\" ` : ''}email \"${subject}\" from a workspace ` +\n `${workspace.ageDays ?? '?'} day(s) old. Every later message from this site ` +\n 'carrying the same signals waits on this decision.',\n alertTitle: 'Outbound email held for review — possible phishing',\n alertBody: `An email from a site was held: \"${subject.slice(0, 120)}\".`,\n url: flagged ? `https://${flagged}/` : null,\n reportedHostname: flagged,\n })\n seamMemo.set(reviewId, { state, atMs: Date.now() })\n return state === 'released'\n ? { outcome: 'send' }\n : { outcome: state === 'rejected' ? 'rejected' : 'held', reference }\n}\n\n/**\n * Puts the review store on `sendEmail`'s phishing screen.\n *\n * **Called at module load**, from the bottom of this file, for the reason\n * `installEmailSendGovernor` is — and this module is also imported by\n * `sending-domains.ts`, so any sender that resolved its identity through\n * `hostSendingIdentity` (the only thing that stamps a workspace on it, and\n * so the only thing the seam screens) has installed it.\n */\nexport function installOutboundScreenGate(): void {\n if (typeof setOutboundScreenGate !== 'function') return\n setOutboundScreenGate((request) => screenSeamMessage(request))\n}\n\n/**\n * Apply a staff decision to a held send (the admin abuse route, in the same\n * act as the row's status change).\n *\n * The row's `heldSend.state` is written first: it is what the screen reads,\n * so an automation step released here sends on its next run whatever\n * happens to the rest. A CAMPAIGN is also put back on the clock (released)\n * or canceled (rejected) — but only while it is still the parked send this\n * row held: a send that has since been edited, sent or canceled by the\n * merchant is left alone, and the answer says so.\n */\nexport async function decideHeldOutboundSend(input: {\n reviewId: string\n decision: 'release' | 'reject'\n actorUid: string\n actorEmail: string | null\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}): Promise<'released' | 'rejected' | 'not-held' | 'campaign-moved'> {\n const nowMs = input.nowMs ?? Date.now()\n const firestore = input.firestore ?? firebaseAdmin.app().firestore()\n const ref = firestore.collection(ABUSE_REPORT_COLLECTION).doc(input.reviewId)\n const snapshot = await ref.get()\n const heldSend = snapshot.get('heldSend') as HeldOutboundSend | undefined\n if (!heldSend?.path || !heldSend.contentHash) return 'not-held'\n const state: HeldOutboundSendState =\n input.decision === 'release' ? 'released' : 'rejected'\n const decided = {\n state,\n decidedAtMs: nowMs,\n decidedByUid: input.actorUid,\n decidedByEmail: input.actorEmail,\n }\n await ref.set(\n { heldSend: { ...heldSend, ...decided } },\n { merge: true },\n )\n if (heldSend.kind !== 'campaign') return state\n\n const sendRef = firestore.doc(heldSend.path)\n const moved = await firestore.runTransaction(async (transaction) => {\n const send = await transaction.get(sendRef)\n const review = send.get('staffReview') as\n | { reviewId?: string; state?: string }\n | undefined\n const status = String(send.get('status') ?? '')\n if (\n !send.exists ||\n review?.reviewId !== input.reviewId ||\n (status !== 'scheduled' && status !== 'draft')\n ) {\n return true\n }\n transaction.set(\n sendRef,\n input.decision === 'release'\n ? {\n status: 'scheduled',\n // Due now: the next processor run sends it, and the screen\n // finds this row released for exactly this content.\n sendAtMs: nowMs,\n staffReview: { ...review, ...decided },\n }\n : {\n status: 'canceled',\n sendAtMs: FieldValue.delete(),\n staffReview: { ...review, ...decided },\n },\n { merge: true },\n )\n return false\n })\n return moved ? 'campaign-moved' : state\n}\n\ninstallOutboundScreenGate()\n"],"names":["createHash","ABUSE_REPORT_COLLECTION","TENANT_APEX","describePhishingScreenSignals","isYoungWorkspaceAge","OUTBOUND_REVIEW_YOUNG_DAYS","screenOutboundEmail","signalsThatHold","setOutboundScreenGate","FieldValue","orgAgeDays","firebaseAdmin","notifyRiskEvent","HELD_SEND_AT_MS","isYoungWorkspace","org","nowMs","Date","now","createdAt","sendingWorkspaceFor","input","identity","workspaceScreenIdentity","host","hostId","orgId","ageDays","ownNames","filter","name","Boolean","ownDomains","domain","text","value","subdomain","canonicalJson","JSON","stringify","_key","entry","Array","isArray","Object","fromEntries","keys","sort","map","key","outboundContentHash","parts","update","digest","heldOutboundReviewId","path","contentHash","slice","heldOutboundReference","reviewId","toUpperCase","heldSendItem","subject","id","split","pop","kind","label","encodeURIComponent","test","context","fileOutboundHold","filing","firestore","app","ref","collection","doc","reference","first","state","runTransaction","transaction","existing","get","exists","stored","undefined","set","category","severity","source","url","reportedHostname","heldSend","details","headline","signals","join","reporterEmail","reporterName","dmca","reportCount","increment","heldAtMs","extra","updatedAt","serverTimestamp","status","merge","occurredAtMs","item","page","staffEvidence","alertBody","flaggedHostOf","flagged","find","signal","screenOutboundSend","request","verdict","fromName","fromAddress","replyTo","preheader","bodies","length","outcome","body","String","alertTitle","releasedReviewId","error","console","SEAM_MEMO_TTL_MS","seamMemo","Map","resetOutboundSeamMemoForTests","clear","seamReviewId","isReleaseForHost","memoKey","memo","atMs","snapshot","held","released","screenSeamMessage","workspace","heldContext","installOutboundScreenGate","decideHeldOutboundSend","decision","decided","decidedAtMs","decidedByUid","actorUid","decidedByEmail","actorEmail","sendRef","moved","send","review","sendAtMs","staffReview","delete"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAoC2C,GAE3C,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,uBAAuB,QAAQ,sCAAqC;AAC7E,SAASC,WAAW,QAAQ,qCAAoC;AAChE,SACEC,6BAA6B,EAC7BC,mBAAmB,EACnBC,0BAA0B,EAG1BC,mBAAmB,EACnBC,eAAe,QACV,oDAAmD;AAC1D,SAIEC,qBAAqB,QAChB,gDAA+C;AACtD,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,UAAU,QAAQ,eAAW;AACtC,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,eAAe,QAAiD,mBAAe;A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Q,MAAMxF,UAAUQ,cAAc,CAAC,OAAOC;YAK5BgF;QAJtB,MAAMA,OAAO,MAAMhF,YAAYE,GAAG,CAAC4E;QACnC,MAAMG,SAASD,KAAK9E,GAAG,CAAC;QAGxB,MAAMwB,SAASsB,QAAOgC,YAAAA,KAAK9E,GAAG,CAAC,qBAAT8E,YAAsB;QAC5C,IACE,CAACA,KAAK7E,MAAM,IACZ8E,CAAAA,0BAAAA,OAAQxG,QAAQ,MAAKtC,MAAMsC,QAAQ,IAClCiD,WAAW,eAAeA,WAAW,SACtC;YACA,OAAO;QACT;QACA1B,YAAYM,GAAG,CACbwE,SACA3I,MAAMoI,QAAQ,KAAK,YACf;YACE7C,QAAQ;YACR,2DAA2D;YAC3D,oDAAoD;YACpDwD,UAAUpJ;YACVqJ,aAAa,aAAKF,QAAWT;QAC/B,IACA;YACE9C,QAAQ;YACRwD,UAAU3J,WAAW6J,MAAM;YAC3BD,aAAa,aAAKF,QAAWT;QAC/B,GACJ;YAAE7C,OAAO;QAAK;QAEhB,OAAO;IACT;IACA,OAAOoD,QAAQ,mBAAmBjF;AACpC;AAEAuE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/outbound-send-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: outbound mail from a young workspace (AGL-3356).\n *\n * The phishing screen (`screenOutboundEmail`, shared-util-email) decides\n * whether a message carries a phishing signal, and `signalsThatHold` beside\n * it decides which signals hold for whom. This module is what happens next,\n * for every surface that screens — the send seam every tenant message\n * crosses ({@link installOutboundScreenGate}), the campaign core and the\n * automation step before they commit, and a site publish\n * (`hosted-page-review.ts`) — so none restates it:\n *\n * - WHO IS SCREENED. Every workspace, in two tiers. A lookalike link holds\n * whatever the workspace's age. The soft rules (a brand in the sender\n * name, the three-part lure) hold only for a workspace younger than\n * {@link OUTBOUND_REVIEW_YOUNG_DAYS}: the incident's workspace was days\n * old, and an established customer's clumsy copy never waits on them. An\n * org whose creation date cannot be read is an existing customer (the same\n * reading `orgAgeDays` gives the sending ramp) and is not young.\n * - WHERE A HOLD GOES. Into the abuse queue at `/admin/abuse-reports` — the\n * staff surface that already exists to answer \"is this phishing\", with its\n * audit trail, its urgent count and its staff notification — as a\n * `phishing` row whose `heldSend` names the message. Not a new queue: a\n * second place to look is a place nobody looks.\n * - HOW STAFF DECIDE. By the row's existing status. `dismissed` (a false\n * positive) RELEASES the send; `actioned` REJECTS it. The admin route\n * calls {@link decideHeldOutboundSend} in the same act as the status\n * write, so the decision and its audit row cannot come apart.\n * - WHAT A RELEASE COVERS. Exactly the content that was held: the review\n * row's id is derived from the message's source and a hash of its\n * content, so an edited message is screened afresh rather than riding a\n * release granted to different words.\n *\n * A hold is never a drop. A held campaign is parked as a scheduled send that\n * a release puts back on the clock; a held automation step fails that one\n * run with a reason the merchant can read, or — after a wait — stays queued\n * until the decision.\n *=========================================*/\n\nimport { createHash } from 'crypto'\nimport { ABUSE_REPORT_COLLECTION } from '@aglyn/aglyn/app-utils/abuse-report'\nimport { TENANT_APEX } from '@aglyn/aglyn/app-utils/host-naming'\nimport { linkReputationSignals } from '@aglyn/shared-util-email/link-reputation'\nimport {\n describePhishingScreenSignals,\n isYoungWorkspaceAge,\n linkUrlsIn,\n OUTBOUND_REVIEW_YOUNG_DAYS,\n type PhishingScreenInput,\n type PhishingScreenSignal,\n screenOutboundEmail,\n signalsThatHold,\n} from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport {\n type OutboundScreenGateRequest,\n type OutboundScreenGateVerdict,\n type SendingWorkspace,\n setOutboundScreenGate,\n} from '@aglyn/shared-util-email/outbound-screen-gate'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { orgAgeDays } from './org-age'\nimport firebaseAdmin from './firebase-admin'\nimport { notifyRiskEvent, type RiskEventInput, type RiskEventItem } from './risk-notice'\nimport { installLinkReputationLookup } from './web-risk'\n\n/** A workspace younger than this many days has the soft rules applied. */\nexport { OUTBOUND_REVIEW_YOUNG_DAYS }\n\n/**\n * Where a held campaign is parked: a send time no processor run reaches.\n * A release replaces it with \"now\"; nothing else ever does, so a hold that\n * nobody decides stays a hold rather than lapsing into a send.\n */\nexport const HELD_SEND_AT_MS = 253402300799000\n\n/**\n * Which surface held it: a campaign, an automation step, any other tenant\n * message at the send seam (`message`), a site publish (`page`), or a\n * submission to a public catalog a plugin keeps — a marketplace listing, its\n * publisher profile (`listing`, AGL-3365).\n */\nexport type HeldOutboundSendKind =\n | 'campaign'\n | 'action'\n | 'workflow'\n | 'orgAutomation'\n | 'message'\n | 'page'\n | 'listing'\n\n/** The decision state a held send carries on its review row. */\nexport type HeldOutboundSendState = 'held' | 'released' | 'rejected'\n\n/** What the review row records about the message it holds. */\nexport interface HeldOutboundSend {\n kind: HeldOutboundSendKind\n /** The document the message came from — a send, an action, a workflow. */\n path: string\n hostId: string\n orgId: string | null\n contentHash: string\n subject: string\n fromName: string | null\n signals: PhishingScreenSignal[]\n state: HeldOutboundSendState\n heldAtMs: number\n /** Workspace age in days when it was held, for the reviewer. */\n ageDays: number | null\n}\n\n/**\n * Is this workspace young enough to screen?\n *\n * Age alone, deliberately. Payment history was the other candidate and the\n * incident is the argument against it: the actor PAID, on a card that never\n * met 3-D Secure, within days of signing up. A paid invoice proves a card\n * worked, not that its holder is who they say.\n */\nexport function isYoungWorkspace(\n org: { createdAt?: unknown } | null | undefined,\n nowMs: number = Date.now(),\n): boolean {\n return isYoungWorkspaceAge(orgAgeDays(org?.createdAt, nowMs))\n}\n\n/**\n * The workspace a host's mail belongs to, as the send seam's screen reads it\n * — stamped on the sending identity by `hostSendingIdentity` from the host\n * and org documents it has already read.\n */\nexport function sendingWorkspaceFor(input: {\n hostId: string\n orgId: string | null\n org?: Record<string, unknown> | null\n host?: Record<string, unknown> | null\n nowMs?: number\n}): SendingWorkspace {\n const identity = workspaceScreenIdentity({ org: input.org, host: input.host })\n return {\n hostId: input.hostId,\n orgId: input.orgId,\n ageDays: orgAgeDays(\n (input.org as { createdAt?: unknown } | null | undefined)?.createdAt,\n input.nowMs ?? Date.now(),\n ),\n ownNames: (identity.ownNames ?? []).filter((name): name is string => Boolean(name)),\n ownDomains: (identity.ownDomains ?? []).filter((domain): domain is string => Boolean(domain)),\n }\n}\n\n/**\n * The workspace's own names and hosts, as the screen reads them: a brand in\n * its own name is its own, and a link to its own site is not \"elsewhere\".\n */\nexport function workspaceScreenIdentity(input: {\n org?: Record<string, unknown> | null\n host?: Record<string, unknown> | null\n}): Pick<PhishingScreenInput, 'ownNames' | 'ownDomains'> {\n const org = input.org ?? {}\n const host = input.host ?? {}\n const text = (value: unknown) => (typeof value === 'string' ? value : '')\n const subdomain = text(host['subdomain'])\n return {\n ownNames: [text(org['name']), text(host['name']), subdomain],\n ownDomains: [\n subdomain ? `${subdomain}.${TENANT_APEX}` : '',\n text(host['cname']),\n text(host['sendingDomain']),\n ],\n }\n}\n\n/**\n * JSON with every object's keys sorted, so the same design serializes to the\n * same string however it was read. Firestore hands back a map's keys in an\n * order that differs by reader, and a release keyed on a hash of an unsorted\n * serialization would not match the very content it released.\n */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(value, (_key, entry) =>\n entry && typeof entry === 'object' && !Array.isArray(entry)\n ? Object.fromEntries(\n Object.keys(entry as Record<string, unknown>)\n .sort()\n .map((key) => [key, (entry as Record<string, unknown>)[key]]),\n )\n : entry,\n )\n}\n\n/** A stable hash of what a message says, so a release covers these words only. */\nexport function outboundContentHash(parts: readonly unknown[]): string {\n return createHash('sha256').update(canonicalJson(parts)).digest('hex')\n}\n\n/**\n * The review row's id: one row per (source, content). Hex, so the admin\n * route's report-id pattern addresses it like any intake row.\n */\nexport function heldOutboundReviewId(path: string, contentHash: string): string {\n return createHash('sha256')\n .update(`outbound-hold:${path}:${contentHash}`)\n .digest('hex')\n .slice(0, 40)\n}\n\n/** The staff-facing reference, in the intake's `AR-` style. */\nexport function heldOutboundReference(reviewId: string): string {\n return `HS-${reviewId.slice(0, 10).toUpperCase()}`\n}\n\nexport interface OutboundScreenRequest {\n kind: HeldOutboundSendKind\n path: string\n hostId: string\n orgId: string | null\n org: Record<string, unknown> | null\n host: Record<string, unknown> | null\n subject: string\n fromName?: string | null\n /**\n * The address it leaves from (AGL-3362). Read by the lookalike rule only,\n * and kept out of the content hash so a release granted before this was\n * read still names the same row.\n */\n fromAddress?: string | null\n replyTo?: string | readonly string[] | null\n preheader?: string | null\n bodies: readonly (string | null | undefined)[]\n nowMs?: number\n}\n\n/** What a screen answers for one piece of content. */\nexport type OutboundScreenOutcome =\n | {\n outcome: 'send'\n /** The review row staff released this content under, when there is one. */\n releasedReviewId?: string\n }\n | { outcome: 'held' | 'rejected'; reviewId: string; reference: string; contentHash: string }\n\n/** What a surface files when its screen holds, for {@link fileOutboundHold}. */\nexport interface OutboundHoldFiling {\n reviewId: string\n heldSend: HeldOutboundSend\n /** Extra fields a surface records beside `heldSend` (a page's version). */\n extra?: Record<string, unknown>\n /** The first line of the row's details, naming what was held. */\n headline: string\n /** The staff alert's title and body, the first time. */\n alertTitle: string\n alertBody: string\n /** The URL the row reports: the flagged host, or the held page. */\n url: string | null\n reportedHostname: string | null\n /**\n * What the workspace's owners are told the first time (AGL-3368): the held\n * item in their words and its console page. The alert title and body above\n * are the STAFF half; the owners read the catalog's own words, which never\n * name the signals.\n */\n item?: RiskEventItem | null\n /** A held page, described (AGL-3374): stored on the owners' notice for the console. */\n page?: RiskEventInput['page']\n}\n\n/**\n * The held item as the owners see it, from the surface and the source path\n * (AGL-3368): the campaign's own email page, the automation list, or nothing\n * for a message the send seam held (the notice then leads to Holds & reviews).\n */\nexport function heldSendItem(input: {\n kind: HeldOutboundSendKind\n path: string\n hostId: string\n subject: string\n context?: string | null\n}): RiskEventItem {\n const subject = input.subject.slice(0, 120)\n const id = input.path.split('/').pop() ?? ''\n switch (input.kind) {\n case 'campaign':\n return {\n label: `the campaign \"${subject}\"`,\n path: id ? `/org/emails/messages/${encodeURIComponent(id)}` : null,\n }\n case 'orgAutomation':\n return { label: `the automated email \"${subject}\"`, path: '/org/automation' }\n case 'workflow':\n case 'action':\n return { label: `the automated email \"${subject}\"`, path: `/${input.hostId}/automation` }\n case 'page':\n // A page's subject is its label (`heldPageLabel`, AGL-3374); a row\n // filed before that carried its URL.\n return { label: /^https?:\\/\\//.test(subject) ? `the page ${subject}` : subject, path: null }\n case 'listing':\n // The publisher's own Listings section of the Marketplace hub.\n return { label: `the marketplace submission \"${subject}\"`, path: '/org/marketplace/listings' }\n default:\n return {\n label: input.context\n ? `the email \"${subject}\" (${input.context})`\n : `the email \"${subject}\"`,\n path: null,\n }\n }\n}\n\n/**\n * Write (or count) the review row for a hold, and tell staff the first time.\n * Returns the row's decision state — a row staff already decided answers\n * with that decision and is not written.\n *\n * One writer for every surface, so a campaign, a seam message and a page\n * land in the queue in the one shape the admin route and page already read.\n */\nexport async function fileOutboundHold(\n filing: OutboundHoldFiling,\n): Promise<HeldOutboundSendState> {\n const firestore = firebaseAdmin.app().firestore()\n const ref = firestore.collection(ABUSE_REPORT_COLLECTION).doc(filing.reviewId)\n const reference = heldOutboundReference(filing.reviewId)\n let first = false\n let state = 'held' as HeldOutboundSendState\n await firestore.runTransaction(async (transaction) => {\n const existing = await transaction.get(ref)\n first = !existing.exists\n const stored = existing.exists\n ? (existing.get('heldSend') as Partial<HeldOutboundSend> | undefined)\n : undefined\n state = stored?.state === 'released' || stored?.state === 'rejected'\n ? stored.state\n : 'held'\n if (state !== 'held') return\n transaction.set(\n ref,\n {\n reference,\n category: 'phishing',\n severity: 'urgent',\n // Who filed it: the screen, not a person. The queue reads it to\n // say so, and a reporter-contact field stays honestly empty.\n source: 'outbound-screen',\n // The flagged host as TEXT — the page never renders a reported URL\n // as a link, and this one may be a phishing kit's.\n url: filing.url,\n reportedHostname: filing.reportedHostname,\n hostId: filing.heldSend.hostId,\n orgId: filing.heldSend.orgId,\n details: [\n filing.headline,\n ...describePhishingScreenSignals(filing.heldSend.signals),\n filing.heldSend.kind === 'page'\n ? 'Dismiss to release this publish; mark it actioned to reject it.'\n : filing.heldSend.kind === 'listing'\n ? 'Dismiss to release this submission (the publisher submits it again and it ' +\n 'goes through); mark it actioned to reject it.'\n : 'Dismiss to release this send; mark it actioned to reject it.',\n ]\n .join('\\n')\n .slice(0, 5000),\n reporterEmail: null,\n reporterName: null,\n dmca: null,\n // Every message the same content held counts here, so a workflow\n // firing on each new contact reads as the volume it is.\n reportCount: FieldValue.increment(1),\n heldSend: first\n ? filing.heldSend\n : { ...filing.heldSend, heldAtMs: stored?.heldAtMs ?? filing.heldSend.heldAtMs },\n ...(filing.extra ?? {}),\n updatedAt: FieldValue.serverTimestamp(),\n ...(first\n ? { status: 'open', createdAt: FieldValue.serverTimestamp() }\n : {}),\n },\n { merge: true },\n )\n })\n if (first && state === 'held') {\n // The owners learn what was held and how to ask for a review; staff get\n // the alert with the evidence and a link to this row. One seam, once.\n await notifyRiskEvent({\n kind:\n filing.heldSend.kind === 'page'\n ? 'page-held'\n : filing.heldSend.kind === 'listing'\n ? 'listing-held'\n : 'email-held',\n orgId: filing.heldSend.orgId,\n hostId: filing.heldSend.hostId,\n reviewId: filing.reviewId,\n reference,\n occurredAtMs: filing.heldSend.heldAtMs,\n item:\n filing.item ??\n heldSendItem({\n kind: filing.heldSend.kind,\n path: filing.heldSend.path,\n hostId: filing.heldSend.hostId,\n subject: filing.heldSend.subject,\n }),\n page: filing.page ?? null,\n staffEvidence: [\n filing.alertBody,\n ...describePhishingScreenSignals(filing.heldSend.signals),\n ].join(' '),\n })\n }\n return state\n}\n\n/** The first signal that names a host, for the row's reported URL. */\nexport function flaggedHostOf(signals: readonly PhishingScreenSignal[]): string | null {\n const flagged = signals.find(\n (signal): signal is Extract<PhishingScreenSignal, { host: string }> => 'host' in signal,\n )\n return flagged?.host ?? null\n}\n\n/**\n * The screen's answer for one message, and what to do with it.\n *\n * - `send` — clean under the tiers, or held earlier and RELEASED by staff\n * for exactly this content (then `releasedReviewId` names the row, and the\n * caller hands it to `sendEmail` so the seam's screen honors it too).\n * - `held` — hold it. The review row is written (or its count bumped) and\n * staff are told the first time.\n * - `rejected` — staff rejected exactly this content. Never sent.\n *\n * Every workspace is screened; `signalsThatHold` applies the tiers, so an\n * established workspace is held only by a lookalike link.\n *\n * Fails OPEN on a store error, the posture of every other control on the\n * send path: an outage on the review queue must not become an outage on\n * every workspace's mail. The screen itself cannot fail.\n */\nexport async function screenOutboundSend(\n request: OutboundScreenRequest,\n): Promise<OutboundScreenOutcome> {\n const nowMs = request.nowMs ?? Date.now()\n const ageDays = orgAgeDays(\n (request.org as { createdAt?: unknown } | null)?.createdAt,\n nowMs,\n )\n const identity = workspaceScreenIdentity({ org: request.org, host: request.host })\n const verdict = screenOutboundEmail({\n subject: request.subject,\n fromName: request.fromName ?? null,\n fromAddress: request.fromAddress ?? null,\n replyTo: request.replyTo ?? null,\n preheader: request.preheader ?? null,\n bodies: request.bodies,\n ...identity,\n })\n // Every foreign link it carries, against the reputation list (AGL-3451):\n // its host, and in 'url' mode its address (AGL-3459). A listing holds for\n // every workspace, a failed lookup holds nothing.\n const reputation = await linkReputationSignals(\n linkUrlsIn([request.subject, request.preheader, ...request.bodies].filter(Boolean).join('\\n')),\n { ownDomains: identity.ownDomains },\n )\n const signals = signalsThatHold([...verdict.signals, ...reputation], { ageDays })\n if (!signals.length) return { outcome: 'send' }\n\n const contentHash = outboundContentHash([\n request.subject,\n request.fromName ?? '',\n request.replyTo ?? '',\n request.preheader ?? '',\n ...request.bodies.map((body) => body ?? ''),\n ])\n const reviewId = heldOutboundReviewId(request.path, contentHash)\n const reference = heldOutboundReference(reviewId)\n try {\n const heldSend: HeldOutboundSend = {\n kind: request.kind,\n path: request.path,\n hostId: request.hostId,\n orgId: request.orgId,\n contentHash,\n subject: request.subject.slice(0, 300),\n fromName: request.fromName ? String(request.fromName).slice(0, 120) : null,\n signals,\n state: 'held',\n heldAtMs: nowMs,\n ageDays,\n }\n const flagged = flaggedHostOf(signals)\n const state = await fileOutboundHold({\n reviewId,\n heldSend,\n headline:\n `Held ${request.kind === 'campaign' ? 'campaign' : `${request.kind} email step`} ` +\n `\"${heldSend.subject}\" from a workspace ${ageDays ?? '?'} day(s) old.`,\n alertTitle: 'Outbound email held for review — possible phishing',\n alertBody:\n `A ${request.kind === 'campaign' ? 'campaign' : 'automated email'} ` +\n `was held: \"${request.subject.slice(0, 120)}\".`,\n url: flagged ? `https://${flagged}/` : null,\n reportedHostname: flagged,\n })\n if (state === 'released') return { outcome: 'send', releasedReviewId: reviewId }\n return { outcome: state === 'rejected' ? 'rejected' : 'held', reviewId, reference, contentHash }\n } catch (error) {\n console.error('[outbound-review] hold could not be recorded — allowing', error)\n return { outcome: 'send' }\n }\n}\n\n/**\n * How long this process trusts what it last learned about a seam row: that\n * it is held (so the next message carrying the same signals skips the\n * write), or how staff decided it. Short, because a decision must reach a\n * sender within a minute; long enough that a newsletter fanned out to a\n * thousand people costs one transaction rather than a thousand on one\n * document.\n */\nconst SEAM_MEMO_TTL_MS = 60_000\nconst seamMemo = new Map<string, { state: HeldOutboundSendState; atMs: number }>()\n\n/** Test seam: forget what this process learned about seam rows. */\nexport function resetOutboundSeamMemoForTests(): void {\n seamMemo.clear()\n}\n\n/**\n * The seam row's id for a site and the signals that held. Keyed on the\n * SIGNALS rather than the words: a message at the seam is already\n * personalized per recipient, so its words differ for every person while\n * what makes it phishing — the lookalike host, the brand and the lure — does\n * not. A release therefore covers this site's use of exactly these signals,\n * and a message carrying any other signal is screened afresh.\n */\nexport function seamReviewId(hostId: string, signals: readonly PhishingScreenSignal[]): string {\n const key = signals\n .map((signal) => canonicalJson(signal))\n .sort()\n .join('\\n')\n return heldOutboundReviewId(`hosts/${hostId}/outbound`, outboundContentHash([key]))\n}\n\n/** Is this row a staff RELEASE for this site? */\nasync function isReleaseForHost(reviewId: string, hostId: string): Promise<boolean> {\n const memoKey = `release:${hostId}:${reviewId}`\n const memo = seamMemo.get(memoKey)\n if (memo && Date.now() - memo.atMs < SEAM_MEMO_TTL_MS) return memo.state === 'released'\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection(ABUSE_REPORT_COLLECTION)\n .doc(reviewId)\n .get()\n const held = snapshot.get('heldSend') as Partial<HeldOutboundSend> | undefined\n const released = held?.state === 'released' && held?.hostId === hostId\n seamMemo.set(memoKey, { state: released ? 'released' : 'held', atMs: Date.now() })\n return released\n}\n\n/**\n * The send seam's gate: what `sendEmail` asks when a tenant message carries\n * a signal that holds (see `outbound-screen-gate.ts`). Installed at module\n * load by {@link installOutboundScreenGate}.\n *\n * A seam hold REFUSES that one message (`held-for-review`) — the sender's own\n * failure handling reports it, the way it reports a suppression — and files\n * one row per site and signal set. Once staff release it, the site's next\n * message carrying those signals sends; reject it, and none does.\n */\nexport async function screenSeamMessage(\n request: OutboundScreenGateRequest,\n): Promise<OutboundScreenGateVerdict> {\n const { workspace } = request\n if (\n request.releasedReviewId &&\n (await isReleaseForHost(request.releasedReviewId, workspace.hostId))\n ) {\n return { outcome: 'send' }\n }\n const reviewId = seamReviewId(workspace.hostId, request.signals)\n const reference = heldOutboundReference(reviewId)\n const memo = seamMemo.get(reviewId)\n if (memo && Date.now() - memo.atMs < SEAM_MEMO_TTL_MS) {\n return memo.state === 'released'\n ? { outcome: 'send' }\n : { outcome: memo.state === 'rejected' ? 'rejected' : 'held', reference }\n }\n const nowMs = Date.now()\n const subject = String(request.subject ?? '').slice(0, 300)\n const context = request.context ? String(request.context).slice(0, 80) : null\n const flagged = flaggedHostOf(request.signals)\n const state = await fileOutboundHold({\n reviewId,\n heldSend: {\n kind: 'message',\n path: `hosts/${workspace.hostId}`,\n hostId: workspace.hostId,\n orgId: workspace.orgId,\n contentHash: outboundContentHash([request.signals]),\n subject,\n fromName: request.fromName ? String(request.fromName).slice(0, 120) : null,\n signals: request.signals,\n state: 'held',\n heldAtMs: nowMs,\n ageDays: workspace.ageDays,\n },\n extra: { heldContext: context },\n item: heldSendItem({ kind: 'message', path: `hosts/${workspace.hostId}`, hostId: workspace.hostId, subject, context }),\n headline:\n `Held ${context ? `\"${context}\" ` : ''}email \"${subject}\" from a workspace ` +\n `${workspace.ageDays ?? '?'} day(s) old. Every later message from this site ` +\n 'carrying the same signals waits on this decision.',\n alertTitle: 'Outbound email held for review — possible phishing',\n alertBody: `An email from a site was held: \"${subject.slice(0, 120)}\".`,\n url: flagged ? `https://${flagged}/` : null,\n reportedHostname: flagged,\n })\n seamMemo.set(reviewId, { state, atMs: Date.now() })\n return state === 'released'\n ? { outcome: 'send' }\n : { outcome: state === 'rejected' ? 'rejected' : 'held', reference }\n}\n\n/**\n * Puts the review store on `sendEmail`'s phishing screen.\n *\n * **Called at module load**, from the bottom of this file, for the reason\n * `installEmailSendGovernor` is — and this module is also imported by\n * `sending-domains.ts`, so any sender that resolved its identity through\n * `hostSendingIdentity` (the only thing that stamps a workspace on it, and\n * so the only thing the seam screens) has installed it.\n */\nexport function installOutboundScreenGate(): void {\n if (typeof setOutboundScreenGate !== 'function') return\n setOutboundScreenGate((request) => screenSeamMessage(request))\n // And the link reputation lookup the same screen asks (AGL-3451).\n installLinkReputationLookup()\n}\n\n/**\n * Apply a staff decision to a held send (the admin abuse route, in the same\n * act as the row's status change).\n *\n * The row's `heldSend.state` is written first: it is what the screen reads,\n * so an automation step released here sends on its next run whatever\n * happens to the rest. A CAMPAIGN is also put back on the clock (released)\n * or canceled (rejected) — but only while it is still the parked send this\n * row held: a send that has since been edited, sent or canceled by the\n * merchant is left alone, and the answer says so.\n */\nexport async function decideHeldOutboundSend(input: {\n reviewId: string\n decision: 'release' | 'reject'\n actorUid: string\n actorEmail: string | null\n nowMs?: number\n firestore?: FirebaseFirestore.Firestore\n}): Promise<'released' | 'rejected' | 'not-held' | 'campaign-moved'> {\n const nowMs = input.nowMs ?? Date.now()\n const firestore = input.firestore ?? firebaseAdmin.app().firestore()\n const ref = firestore.collection(ABUSE_REPORT_COLLECTION).doc(input.reviewId)\n const snapshot = await ref.get()\n const heldSend = snapshot.get('heldSend') as HeldOutboundSend | undefined\n if (!heldSend?.path || !heldSend.contentHash) return 'not-held'\n const state: HeldOutboundSendState =\n input.decision === 'release' ? 'released' : 'rejected'\n const decided = {\n state,\n decidedAtMs: nowMs,\n decidedByUid: input.actorUid,\n decidedByEmail: input.actorEmail,\n }\n await ref.set(\n { heldSend: { ...heldSend, ...decided } },\n { merge: true },\n )\n if (heldSend.kind !== 'campaign') return state\n\n const sendRef = firestore.doc(heldSend.path)\n const moved = await firestore.runTransaction(async (transaction) => {\n const send = await transaction.get(sendRef)\n const review = send.get('staffReview') as\n | { reviewId?: string; state?: string }\n | undefined\n const status = String(send.get('status') ?? '')\n if (\n !send.exists ||\n review?.reviewId !== input.reviewId ||\n (status !== 'scheduled' && status !== 'draft')\n ) {\n return true\n }\n transaction.set(\n sendRef,\n input.decision === 'release'\n ? {\n status: 'scheduled',\n // Due now: the next processor run sends it, and the screen\n // finds this row released for exactly this content.\n sendAtMs: nowMs,\n staffReview: { ...review, ...decided },\n }\n : {\n status: 'canceled',\n sendAtMs: FieldValue.delete(),\n staffReview: { ...review, ...decided },\n },\n { merge: true },\n )\n return false\n })\n return moved ? 'campaign-moved' : state\n}\n\ninstallOutboundScreenGate()\n"],"names":["createHash","ABUSE_REPORT_COLLECTION","TENANT_APEX","linkReputationSignals","describePhishingScreenSignals","isYoungWorkspaceAge","linkUrlsIn","OUTBOUND_REVIEW_YOUNG_DAYS","screenOutboundEmail","signalsThatHold","setOutboundScreenGate","FieldValue","orgAgeDays","firebaseAdmin","notifyRiskEvent","installLinkReputationLookup","HELD_SEND_AT_MS","isYoungWorkspace","org","nowMs","Date","now","createdAt","sendingWorkspaceFor","input","identity","workspaceScreenIdentity","host","hostId","orgId","ageDays","ownNames","filter","name","Boolean","ownDomains","domain","text","value","subdomain","canonicalJson","JSON","stringify","_key","entry","Array","isArray","Object","fromEntries","keys","sort","map","key","outboundContentHash","parts","update","digest","heldOutboundReviewId","path","contentHash","slice","heldOutboundReference","reviewId","toUpperCase","heldSendItem","subject","id","split","pop","kind","label","encodeURIComponent","test","context","fileOutboundHold","filing","firestore","app","ref","collection","doc","reference","first","state","runTransaction","transaction","existing","get","exists","stored","undefined","set","category","severity","source","url","reportedHostname","heldSend","details","headline","signals","join","reporterEmail","reporterName","dmca","reportCount","increment","heldAtMs","extra","updatedAt","serverTimestamp","status","merge","occurredAtMs","item","page","staffEvidence","alertBody","flaggedHostOf","flagged","find","signal","screenOutboundSend","request","verdict","fromName","fromAddress","replyTo","preheader","bodies","reputation","length","outcome","body","String","alertTitle","releasedReviewId","error","console","SEAM_MEMO_TTL_MS","seamMemo","Map","resetOutboundSeamMemoForTests","clear","seamReviewId","isReleaseForHost","memoKey","memo","atMs","snapshot","held","released","screenSeamMessage","workspace","heldContext","installOutboundScreenGate","decideHeldOutboundSend","decision","decided","decidedAtMs","decidedByUid","actorUid","decidedByEmail","actorEmail","sendRef","moved","send","review","sendAtMs","staffReview","delete"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAoC2C,GAE3C,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,uBAAuB,QAAQ,sCAAqC;AAC7E,SAASC,WAAW,QAAQ,qCAAoC;AAChE,SAASC,qBAAqB,QAAQ,2CAA0C;AAChF,SACEC,6BAA6B,EAC7BC,mBAAmB,EACnBC,UAAU,EACVC,0BAA0B,EAG1BC,mBAAmB,EACnBC,eAAe,QACV,oDAAmD;AAC1D,SAIEC,qBAAqB,QAChB,gDAA+C;A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
+
* 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 PhishingScreenSignal } from '@aglyn/shared-util-email/outbound-phishing-screen';
|
|
18
|
+
/** Where a workspace's automatic hold is recorded: one document per workspace. */
|
|
19
|
+
export declare const SECURITY_HOLD_COLLECTION = "securityHolds";
|
|
20
|
+
/** The actor every automatic hold's audit rows name. */
|
|
21
|
+
export declare const SECURITY_HOLD_ACTOR_UID = "system:page-screen";
|
|
22
|
+
/** How long one console run may hold a claim before another may take it over. */
|
|
23
|
+
export declare const SECURITY_HOLD_CLAIM_LEASE_MS: number;
|
|
24
|
+
/** The lock reason a hold places. Never `abuse`: see the module header. */
|
|
25
|
+
export declare const SECURITY_HOLD_LOCK_REASON = "security";
|
|
26
|
+
/**
|
|
27
|
+
* - `pending` — requested; the console has not applied it yet.
|
|
28
|
+
* - `applying` — a console run claimed it.
|
|
29
|
+
* - `applied` — the locks were placed (see `outcome` for each).
|
|
30
|
+
* - `skipped` — nothing was locked, and `outcome.skipped` says why: the house,
|
|
31
|
+
* a staff-owned workspace, a workspace already gone.
|
|
32
|
+
*/
|
|
33
|
+
export type SecurityHoldState = 'pending' | 'applying' | 'applied' | 'skipped';
|
|
34
|
+
/** What a held page asks the console to hold. */
|
|
35
|
+
export interface SecurityHoldRequest {
|
|
36
|
+
orgId: string;
|
|
37
|
+
hostId: string;
|
|
38
|
+
screenId: string;
|
|
39
|
+
versionId: string;
|
|
40
|
+
/** The abuse row the page hold filed, and its `HS-…` reference. */
|
|
41
|
+
reviewId: string;
|
|
42
|
+
reference: string;
|
|
43
|
+
signals: readonly PhishingScreenSignal[];
|
|
44
|
+
ageDays: number | null;
|
|
45
|
+
/** The page, in the words the review row names it. */
|
|
46
|
+
pageLabel: string;
|
|
47
|
+
pageUrl: string | null;
|
|
48
|
+
siteName: string | null;
|
|
49
|
+
}
|
|
50
|
+
/** The stored document. */
|
|
51
|
+
export interface SecurityHoldRecord extends SecurityHoldRequest {
|
|
52
|
+
state: SecurityHoldState;
|
|
53
|
+
/** The signals, in the words staff read on the abuse row. */
|
|
54
|
+
evidence: string;
|
|
55
|
+
requestedAtMs: number;
|
|
56
|
+
claimedAtMs?: number | null;
|
|
57
|
+
settledAtMs?: number | null;
|
|
58
|
+
/** What the console did, step by step. */
|
|
59
|
+
outcome?: Record<string, unknown> | null;
|
|
60
|
+
}
|
|
61
|
+
export type SecurityHoldRequestOutcome = 'requested' | 'exists' | 'not-young' | 'no-workspace' | 'house' | 'failed';
|
|
62
|
+
/**
|
|
63
|
+
* Does this workspace own the platform's own marketing site? Read from the
|
|
64
|
+
* org document the caller already holds, so asking costs nothing. `false` on
|
|
65
|
+
* an install that names no marketing host.
|
|
66
|
+
*/
|
|
67
|
+
export declare function isHouseWorkspace(input: {
|
|
68
|
+
hostId?: string | null;
|
|
69
|
+
org?: Record<string, unknown> | null;
|
|
70
|
+
}): boolean;
|
|
71
|
+
/** Test seam: forget what this process asked. */
|
|
72
|
+
export declare function resetPageSecurityHoldMemoForTests(): void;
|
|
73
|
+
/**
|
|
74
|
+
* Ask for a held page's workspace to be held. Creates the workspace's hold
|
|
75
|
+
* document when there is none; answers `exists` when there is. A workspace
|
|
76
|
+
* that is not young, has no id or is the house is never held.
|
|
77
|
+
*
|
|
78
|
+
* Never throws: the page hold it rides on has already happened.
|
|
79
|
+
*/
|
|
80
|
+
export declare function requestPageSecurityHold(request: SecurityHoldRequest & {
|
|
81
|
+
org?: Record<string, unknown> | null;
|
|
82
|
+
nowMs?: number;
|
|
83
|
+
}): Promise<SecurityHoldRequestOutcome>;
|
|
84
|
+
/** The pending holds, oldest first by nothing more than the store's order. */
|
|
85
|
+
export declare function listPendingSecurityHolds(firestore: FirebaseFirestore.Firestore, limit?: number): Promise<SecurityHoldRecord[]>;
|
|
86
|
+
/**
|
|
87
|
+
* Claim one hold for this run. A hold another run claimed inside the lease
|
|
88
|
+
* is left to it; one whose claim lapsed (that run died) is taken over.
|
|
89
|
+
* Answers the claimed record, or null.
|
|
90
|
+
*/
|
|
91
|
+
export declare function claimSecurityHold(firestore: FirebaseFirestore.Firestore, orgId: string, nowMs?: number): Promise<SecurityHoldRecord | null>;
|
|
92
|
+
/** Record what the console did with a claimed hold. */
|
|
93
|
+
export declare function settleSecurityHold(firestore: FirebaseFirestore.Firestore, orgId: string, state: 'applied' | 'skipped', outcome: Record<string, unknown>, nowMs?: number): Promise<void>;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ /*==========================================
|
|
18
|
+
* THE AUTOMATIC SECURITY HOLD (AGL-3450).
|
|
19
|
+
*
|
|
20
|
+
* The page screen (`hosted-page-review.ts`) holds a phishing page: the
|
|
21
|
+
* version is not served and an urgent `phishing` row lands in the abuse
|
|
22
|
+
* queue. When the workspace is in its first fortnight
|
|
23
|
+
* ({@link isYoungWorkspaceAge}), a hold is also the moment to stop the
|
|
24
|
+
* ACCOUNT: the two document-share harvesters found on 2026-10-01 were each
|
|
25
|
+
* one page in a days-old workspace, and nothing stopped the same account
|
|
26
|
+
* publishing the next one. So a held page from a young workspace places a
|
|
27
|
+
* `security` lock on the workspace, on the site (`takedown`, so it stays down
|
|
28
|
+
* through an outage) and on the account that published it.
|
|
29
|
+
*
|
|
30
|
+
* `security`, never `abuse`: `abuse` is a permanent ban, and a screen is not
|
|
31
|
+
* a person. The hold is reversible and precautionary; staff confirm it and
|
|
32
|
+
* re-place it as `abuse` by hand, or lift it on Staff → Lockdown, so a false
|
|
33
|
+
* positive costs a support email rather than an account.
|
|
34
|
+
*
|
|
35
|
+
* ## Split by where each half can run
|
|
36
|
+
*
|
|
37
|
+
* The review runs wherever a page is composed — the published-site runtime
|
|
38
|
+
* on every render, and the console's link re-check. The lock does not: it is
|
|
39
|
+
* the staff lockdown path (`apps/console/utils/server/org-lockdown.ts` and
|
|
40
|
+
* its neighbours), which revokes sessions, evicts the tenant cache, emails
|
|
41
|
+
* the owners and writes the audit trail, and which only the console holds.
|
|
42
|
+
* So this module is the DURABLE half: a `securityHolds/{orgId}` document,
|
|
43
|
+
* created once, that says "this workspace is to be held, and why". The
|
|
44
|
+
* console applies every pending one on its fifteen-minute tick and at the
|
|
45
|
+
* end of any console sweep that held a page.
|
|
46
|
+
*
|
|
47
|
+
* ## Idempotent by construction
|
|
48
|
+
*
|
|
49
|
+
* One document per WORKSPACE, created in a transaction only when absent. A
|
|
50
|
+
* second held page from the same workspace finds it and does nothing: no
|
|
51
|
+
* second lock, notice or alert. Once staff have looked at a workspace and
|
|
52
|
+
* lifted its hold, its next held page is held and queued for them as usual,
|
|
53
|
+
* and is not locked again automatically — staff are the ones who know it now.
|
|
54
|
+
*
|
|
55
|
+
* ## Never the house
|
|
56
|
+
*
|
|
57
|
+
* A workspace that owns the platform's own marketing site
|
|
58
|
+
* (`PLATFORM_MARKETING_HOST_ID`) is never held here; the console re-checks
|
|
59
|
+
* that and refuses a workspace owned by a staff account before it locks
|
|
60
|
+
* anything.
|
|
61
|
+
*=========================================*/ import { describePhishingScreenSignals, isYoungWorkspaceAge } from "@aglyn/shared-util-email/outbound-phishing-screen";
|
|
62
|
+
import firebaseAdmin from "./firebase-admin.js";
|
|
63
|
+
import { platformMarketingHostId } from "./platform-marketing-consent.js";
|
|
64
|
+
/** Where a workspace's automatic hold is recorded: one document per workspace. */ export const SECURITY_HOLD_COLLECTION = 'securityHolds';
|
|
65
|
+
/** The actor every automatic hold's audit rows name. */ export const SECURITY_HOLD_ACTOR_UID = 'system:page-screen';
|
|
66
|
+
/** How long one console run may hold a claim before another may take it over. */ export const SECURITY_HOLD_CLAIM_LEASE_MS = 10 * 60000;
|
|
67
|
+
/** The lock reason a hold places. Never `abuse`: see the module header. */ export const SECURITY_HOLD_LOCK_REASON = 'security';
|
|
68
|
+
/**
|
|
69
|
+
* Does this workspace own the platform's own marketing site? Read from the
|
|
70
|
+
* org document the caller already holds, so asking costs nothing. `false` on
|
|
71
|
+
* an install that names no marketing host.
|
|
72
|
+
*/ export function isHouseWorkspace(input) {
|
|
73
|
+
var _input_org;
|
|
74
|
+
const house = platformMarketingHostId();
|
|
75
|
+
if (!house) return false;
|
|
76
|
+
if (input.hostId === house) return true;
|
|
77
|
+
const hosts = (_input_org = input.org) == null ? void 0 : _input_org['hosts'];
|
|
78
|
+
return Boolean(hosts && typeof hosts === 'object' && house in hosts);
|
|
79
|
+
}
|
|
80
|
+
/** Workspaces this process already asked about, so a busy held page asks once. */ const requestedMemo = new Set();
|
|
81
|
+
/** Test seam: forget what this process asked. */ export function resetPageSecurityHoldMemoForTests() {
|
|
82
|
+
requestedMemo.clear();
|
|
83
|
+
}
|
|
84
|
+
function holdsCollection(firestore) {
|
|
85
|
+
return (firestore != null ? firestore : firebaseAdmin.app().firestore()).collection(SECURITY_HOLD_COLLECTION);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Ask for a held page's workspace to be held. Creates the workspace's hold
|
|
89
|
+
* document when there is none; answers `exists` when there is. A workspace
|
|
90
|
+
* that is not young, has no id or is the house is never held.
|
|
91
|
+
*
|
|
92
|
+
* Never throws: the page hold it rides on has already happened.
|
|
93
|
+
*/ export async function requestPageSecurityHold(request) {
|
|
94
|
+
if (!isYoungWorkspaceAge(request.ageDays)) return 'not-young';
|
|
95
|
+
if (!request.orgId) return 'no-workspace';
|
|
96
|
+
if (isHouseWorkspace({
|
|
97
|
+
hostId: request.hostId,
|
|
98
|
+
org: request.org
|
|
99
|
+
})) return 'house';
|
|
100
|
+
if (requestedMemo.has(request.orgId)) return 'exists';
|
|
101
|
+
try {
|
|
102
|
+
var _request_pageLabel, _request_nowMs;
|
|
103
|
+
const firestore = firebaseAdmin.app().firestore();
|
|
104
|
+
const ref = holdsCollection(firestore).doc(request.orgId);
|
|
105
|
+
const record = {
|
|
106
|
+
orgId: request.orgId,
|
|
107
|
+
hostId: request.hostId,
|
|
108
|
+
screenId: request.screenId,
|
|
109
|
+
versionId: request.versionId,
|
|
110
|
+
reviewId: request.reviewId,
|
|
111
|
+
reference: request.reference,
|
|
112
|
+
signals: [
|
|
113
|
+
...request.signals
|
|
114
|
+
],
|
|
115
|
+
ageDays: request.ageDays,
|
|
116
|
+
pageLabel: String((_request_pageLabel = request.pageLabel) != null ? _request_pageLabel : '').slice(0, 300),
|
|
117
|
+
pageUrl: request.pageUrl ? String(request.pageUrl).slice(0, 500) : null,
|
|
118
|
+
siteName: request.siteName ? String(request.siteName).slice(0, 200) : null,
|
|
119
|
+
evidence: describePhishingScreenSignals(request.signals).join(' ').slice(0, 2000),
|
|
120
|
+
state: 'pending',
|
|
121
|
+
requestedAtMs: (_request_nowMs = request.nowMs) != null ? _request_nowMs : Date.now(),
|
|
122
|
+
claimedAtMs: null,
|
|
123
|
+
settledAtMs: null,
|
|
124
|
+
outcome: null
|
|
125
|
+
};
|
|
126
|
+
const created = await firestore.runTransaction(async (transaction)=>{
|
|
127
|
+
const existing = await transaction.get(ref);
|
|
128
|
+
if (existing.exists) return false;
|
|
129
|
+
transaction.set(ref, record);
|
|
130
|
+
return true;
|
|
131
|
+
});
|
|
132
|
+
requestedMemo.add(request.orgId);
|
|
133
|
+
return created ? 'requested' : 'exists';
|
|
134
|
+
} catch (error) {
|
|
135
|
+
console.error('[security-hold] the hold could not be requested', request.orgId, error);
|
|
136
|
+
return 'failed';
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** The pending holds, oldest first by nothing more than the store's order. */ export async function listPendingSecurityHolds(firestore, limit = 20) {
|
|
140
|
+
const snapshot = await holdsCollection(firestore).where('state', 'in', [
|
|
141
|
+
'pending',
|
|
142
|
+
'applying'
|
|
143
|
+
]).limit(limit).get();
|
|
144
|
+
return snapshot.docs.map((doc)=>doc.data());
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Claim one hold for this run. A hold another run claimed inside the lease
|
|
148
|
+
* is left to it; one whose claim lapsed (that run died) is taken over.
|
|
149
|
+
* Answers the claimed record, or null.
|
|
150
|
+
*/ export async function claimSecurityHold(firestore, orgId, nowMs = Date.now()) {
|
|
151
|
+
const ref = holdsCollection(firestore).doc(orgId);
|
|
152
|
+
return firestore.runTransaction(async (transaction)=>{
|
|
153
|
+
const snapshot = await transaction.get(ref);
|
|
154
|
+
if (!snapshot.exists) return null;
|
|
155
|
+
const record = snapshot.data();
|
|
156
|
+
const claimLive = record.state === 'applying' && typeof record.claimedAtMs === 'number' && nowMs - record.claimedAtMs < SECURITY_HOLD_CLAIM_LEASE_MS;
|
|
157
|
+
if (record.state !== 'pending' && !(record.state === 'applying' && !claimLive)) return null;
|
|
158
|
+
transaction.set(ref, {
|
|
159
|
+
state: 'applying',
|
|
160
|
+
claimedAtMs: nowMs
|
|
161
|
+
}, {
|
|
162
|
+
merge: true
|
|
163
|
+
});
|
|
164
|
+
return _extends({}, record, {
|
|
165
|
+
state: 'applying',
|
|
166
|
+
claimedAtMs: nowMs
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
/** Record what the console did with a claimed hold. */ export async function settleSecurityHold(firestore, orgId, state, outcome, nowMs = Date.now()) {
|
|
171
|
+
await holdsCollection(firestore).doc(orgId).set({
|
|
172
|
+
state,
|
|
173
|
+
outcome,
|
|
174
|
+
settledAtMs: nowMs
|
|
175
|
+
}, {
|
|
176
|
+
merge: true
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
//# sourceMappingURL=page-security-hold.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/page-security-hold.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 * THE AUTOMATIC SECURITY HOLD (AGL-3450).\n *\n * The page screen (`hosted-page-review.ts`) holds a phishing page: the\n * version is not served and an urgent `phishing` row lands in the abuse\n * queue. When the workspace is in its first fortnight\n * ({@link isYoungWorkspaceAge}), a hold is also the moment to stop the\n * ACCOUNT: the two document-share harvesters found on 2026-10-01 were each\n * one page in a days-old workspace, and nothing stopped the same account\n * publishing the next one. So a held page from a young workspace places a\n * `security` lock on the workspace, on the site (`takedown`, so it stays down\n * through an outage) and on the account that published it.\n *\n * `security`, never `abuse`: `abuse` is a permanent ban, and a screen is not\n * a person. The hold is reversible and precautionary; staff confirm it and\n * re-place it as `abuse` by hand, or lift it on Staff → Lockdown, so a false\n * positive costs a support email rather than an account.\n *\n * ## Split by where each half can run\n *\n * The review runs wherever a page is composed — the published-site runtime\n * on every render, and the console's link re-check. The lock does not: it is\n * the staff lockdown path (`apps/console/utils/server/org-lockdown.ts` and\n * its neighbours), which revokes sessions, evicts the tenant cache, emails\n * the owners and writes the audit trail, and which only the console holds.\n * So this module is the DURABLE half: a `securityHolds/{orgId}` document,\n * created once, that says \"this workspace is to be held, and why\". The\n * console applies every pending one on its fifteen-minute tick and at the\n * end of any console sweep that held a page.\n *\n * ## Idempotent by construction\n *\n * One document per WORKSPACE, created in a transaction only when absent. A\n * second held page from the same workspace finds it and does nothing: no\n * second lock, notice or alert. Once staff have looked at a workspace and\n * lifted its hold, its next held page is held and queued for them as usual,\n * and is not locked again automatically — staff are the ones who know it now.\n *\n * ## Never the house\n *\n * A workspace that owns the platform's own marketing site\n * (`PLATFORM_MARKETING_HOST_ID`) is never held here; the console re-checks\n * that and refuses a workspace owned by a staff account before it locks\n * anything.\n *=========================================*/\n\nimport {\n describePhishingScreenSignals,\n isYoungWorkspaceAge,\n type PhishingScreenSignal,\n} from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport firebaseAdmin from './firebase-admin'\nimport { platformMarketingHostId } from './platform-marketing-consent'\n\n/** Where a workspace's automatic hold is recorded: one document per workspace. */\nexport const SECURITY_HOLD_COLLECTION = 'securityHolds'\n\n/** The actor every automatic hold's audit rows name. */\nexport const SECURITY_HOLD_ACTOR_UID = 'system:page-screen'\n\n/** How long one console run may hold a claim before another may take it over. */\nexport const SECURITY_HOLD_CLAIM_LEASE_MS = 10 * 60_000\n\n/** The lock reason a hold places. Never `abuse`: see the module header. */\nexport const SECURITY_HOLD_LOCK_REASON = 'security'\n\n/**\n * - `pending` — requested; the console has not applied it yet.\n * - `applying` — a console run claimed it.\n * - `applied` — the locks were placed (see `outcome` for each).\n * - `skipped` — nothing was locked, and `outcome.skipped` says why: the house,\n * a staff-owned workspace, a workspace already gone.\n */\nexport type SecurityHoldState = 'pending' | 'applying' | 'applied' | 'skipped'\n\n/** What a held page asks the console to hold. */\nexport interface SecurityHoldRequest {\n orgId: string\n hostId: string\n screenId: string\n versionId: string\n /** The abuse row the page hold filed, and its `HS-…` reference. */\n reviewId: string\n reference: string\n signals: readonly PhishingScreenSignal[]\n ageDays: number | null\n /** The page, in the words the review row names it. */\n pageLabel: string\n pageUrl: string | null\n siteName: string | null\n}\n\n/** The stored document. */\nexport interface SecurityHoldRecord extends SecurityHoldRequest {\n state: SecurityHoldState\n /** The signals, in the words staff read on the abuse row. */\n evidence: string\n requestedAtMs: number\n claimedAtMs?: number | null\n settledAtMs?: number | null\n /** What the console did, step by step. */\n outcome?: Record<string, unknown> | null\n}\n\nexport type SecurityHoldRequestOutcome =\n | 'requested'\n | 'exists'\n | 'not-young'\n | 'no-workspace'\n | 'house'\n | 'failed'\n\n/**\n * Does this workspace own the platform's own marketing site? Read from the\n * org document the caller already holds, so asking costs nothing. `false` on\n * an install that names no marketing host.\n */\nexport function isHouseWorkspace(input: {\n hostId?: string | null\n org?: Record<string, unknown> | null\n}): boolean {\n const house = platformMarketingHostId()\n if (!house) return false\n if (input.hostId === house) return true\n const hosts = input.org?.['hosts']\n return Boolean(hosts && typeof hosts === 'object' && house in (hosts as Record<string, unknown>))\n}\n\n/** Workspaces this process already asked about, so a busy held page asks once. */\nconst requestedMemo = new Set<string>()\n\n/** Test seam: forget what this process asked. */\nexport function resetPageSecurityHoldMemoForTests(): void {\n requestedMemo.clear()\n}\n\nfunction holdsCollection(firestore?: FirebaseFirestore.Firestore) {\n return (firestore ?? firebaseAdmin.app().firestore()).collection(SECURITY_HOLD_COLLECTION)\n}\n\n/**\n * Ask for a held page's workspace to be held. Creates the workspace's hold\n * document when there is none; answers `exists` when there is. A workspace\n * that is not young, has no id or is the house is never held.\n *\n * Never throws: the page hold it rides on has already happened.\n */\nexport async function requestPageSecurityHold(\n request: SecurityHoldRequest & {\n org?: Record<string, unknown> | null\n nowMs?: number\n },\n): Promise<SecurityHoldRequestOutcome> {\n if (!isYoungWorkspaceAge(request.ageDays)) return 'not-young'\n if (!request.orgId) return 'no-workspace'\n if (isHouseWorkspace({ hostId: request.hostId, org: request.org })) return 'house'\n if (requestedMemo.has(request.orgId)) return 'exists'\n try {\n const firestore = firebaseAdmin.app().firestore()\n const ref = holdsCollection(firestore).doc(request.orgId)\n const record: SecurityHoldRecord = {\n orgId: request.orgId,\n hostId: request.hostId,\n screenId: request.screenId,\n versionId: request.versionId,\n reviewId: request.reviewId,\n reference: request.reference,\n signals: [...request.signals],\n ageDays: request.ageDays,\n pageLabel: String(request.pageLabel ?? '').slice(0, 300),\n pageUrl: request.pageUrl ? String(request.pageUrl).slice(0, 500) : null,\n siteName: request.siteName ? String(request.siteName).slice(0, 200) : null,\n evidence: describePhishingScreenSignals(request.signals).join(' ').slice(0, 2000),\n state: 'pending',\n requestedAtMs: request.nowMs ?? Date.now(),\n claimedAtMs: null,\n settledAtMs: null,\n outcome: null,\n }\n const created = await firestore.runTransaction(async (transaction) => {\n const existing = await transaction.get(ref)\n if (existing.exists) return false\n transaction.set(ref, record)\n return true\n })\n requestedMemo.add(request.orgId)\n return created ? 'requested' : 'exists'\n } catch (error) {\n console.error('[security-hold] the hold could not be requested', request.orgId, error)\n return 'failed'\n }\n}\n\n/** The pending holds, oldest first by nothing more than the store's order. */\nexport async function listPendingSecurityHolds(\n firestore: FirebaseFirestore.Firestore,\n limit = 20,\n): Promise<SecurityHoldRecord[]> {\n const snapshot = await holdsCollection(firestore)\n .where('state', 'in', ['pending', 'applying'])\n .limit(limit)\n .get()\n return snapshot.docs.map((doc) => doc.data() as SecurityHoldRecord)\n}\n\n/**\n * Claim one hold for this run. A hold another run claimed inside the lease\n * is left to it; one whose claim lapsed (that run died) is taken over.\n * Answers the claimed record, or null.\n */\nexport async function claimSecurityHold(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n nowMs: number = Date.now(),\n): Promise<SecurityHoldRecord | null> {\n const ref = holdsCollection(firestore).doc(orgId)\n return firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) return null\n const record = snapshot.data() as SecurityHoldRecord\n const claimLive =\n record.state === 'applying' &&\n typeof record.claimedAtMs === 'number' &&\n nowMs - record.claimedAtMs < SECURITY_HOLD_CLAIM_LEASE_MS\n if (record.state !== 'pending' && !(record.state === 'applying' && !claimLive)) return null\n transaction.set(ref, { state: 'applying', claimedAtMs: nowMs }, { merge: true })\n return { ...record, state: 'applying', claimedAtMs: nowMs }\n })\n}\n\n/** Record what the console did with a claimed hold. */\nexport async function settleSecurityHold(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n state: 'applied' | 'skipped',\n outcome: Record<string, unknown>,\n nowMs: number = Date.now(),\n): Promise<void> {\n await holdsCollection(firestore)\n .doc(orgId)\n .set({ state, outcome, settledAtMs: nowMs }, { merge: true })\n}\n"],"names":["describePhishingScreenSignals","isYoungWorkspaceAge","firebaseAdmin","platformMarketingHostId","SECURITY_HOLD_COLLECTION","SECURITY_HOLD_ACTOR_UID","SECURITY_HOLD_CLAIM_LEASE_MS","SECURITY_HOLD_LOCK_REASON","isHouseWorkspace","input","house","hostId","hosts","org","Boolean","requestedMemo","Set","resetPageSecurityHoldMemoForTests","clear","holdsCollection","firestore","app","collection","requestPageSecurityHold","request","ageDays","orgId","has","ref","doc","record","screenId","versionId","reviewId","reference","signals","pageLabel","String","slice","pageUrl","siteName","evidence","join","state","requestedAtMs","nowMs","Date","now","claimedAtMs","settledAtMs","outcome","created","runTransaction","transaction","existing","get","exists","set","add","error","console","listPendingSecurityHolds","limit","snapshot","where","docs","map","data","claimSecurityHold","claimLive","merge","settleSecurityHold"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA4C2C,GAE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