@aglyn/shared-util-email 1.0.0-beta.221 → 1.0.0-beta.223

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -163,12 +163,16 @@ export type PhishingScreenSignal = {
163
163
  * A link, embed, redirect or form action whose host Google Web Risk lists
164
164
  * as phishing, malware or unwanted software (AGL-3451,
165
165
  * `link-reputation.ts`). Strong: a harvester already known to be bad
166
- * anywhere is bad whatever page or message surrounds it.
166
+ * anywhere is bad whatever page or message surrounds it. `url` is set
167
+ * when the listing names one page on the host rather than the host
168
+ * (AGL-3459, `platformSettings/webRisk.lookupMode: 'url'`): the address
169
+ * as looked up, scheme, host and path, never a query string.
167
170
  */
168
171
  | {
169
172
  code: 'web-risk-link';
170
173
  host: string;
171
174
  threats: string[];
175
+ url?: string;
172
176
  };
173
177
  export interface PhishingScreenInput {
174
178
  subject?: string | null;
@@ -252,6 +256,13 @@ export declare function lookalikeBrandForHost(host: string): PhishingScreenBrand
252
256
  export declare function visibleTextOf(html: string | null | undefined): string;
253
257
  /** The hosts every link in the text points at, lowercased. */
254
258
  export declare function linkHostsIn(text: string): string[];
259
+ /**
260
+ * Every link in the text as written — `www.` read as `https://`, prose
261
+ * punctuation after it dropped — in the order found, each once. Query
262
+ * strings and fragments are still on them: read them through
263
+ * `normalizeReputationLink` (`link-reputation.ts`) before they go anywhere.
264
+ */
265
+ export declare function linkUrlsIn(text: string): string[];
255
266
  /** Lowercased alphanumerics only, so "Wells-Fargo Advisors" contains `wellsfargo`. */
256
267
  declare function squash(text: string): string;
257
268
  /** Is this brand the workspace's own, by name or by a domain it holds? */
@@ -846,6 +846,22 @@ const URL_PATTERN = /\b(?:https?:\/\/|www\.)[^\s"'<>()\\[\]{}]+/gi;
846
846
  ...hosts
847
847
  ];
848
848
  }
849
+ /**
850
+ * Every link in the text as written — `www.` read as `https://`, prose
851
+ * punctuation after it dropped — in the order found, each once. Query
852
+ * strings and fragments are still on them: read them through
853
+ * `normalizeReputationLink` (`link-reputation.ts`) before they go anywhere.
854
+ */ export function linkUrlsIn(text) {
855
+ var _decodeEntities_match;
856
+ const urls = new Set();
857
+ for (const match of (_decodeEntities_match = decodeEntities(String(text != null ? text : '')).match(URL_PATTERN)) != null ? _decodeEntities_match : []){
858
+ const url = match.replace(/[.,;:!]+$/, '');
859
+ urls.add(/^www\./i.test(url) ? `https://${url}` : url);
860
+ }
861
+ return [
862
+ ...urls
863
+ ];
864
+ }
849
865
  /** Every link in the text, with what it carries after its path. */ function linkTargetsIn(text) {
850
866
  var _decodeEntities_match;
851
867
  const targets = [];
@@ -1100,7 +1116,8 @@ const ADDRESS_HOST_PATTERN = /[a-z0-9._%+-]+@([a-z0-9-]+(?:\.[a-z0-9-]+)+)/gi;
1100
1116
  case 'recipient-prefill-link':
1101
1117
  return `Links to ${signal.host} with the recipient's own address in the ${signal.place === 'fragment' ? 'fragment' : 'link'}, so a sign-in form there opens filled in, beside "${signal.lure}".`;
1102
1118
  case 'web-risk-link':
1103
- return `Links to ${signal.host}, which Google Web Risk lists as ${describeLinkThreats(signal.threats)}.`;
1119
+ var _signal_url;
1120
+ return `Links to ${(_signal_url = signal.url) != null ? _signal_url : signal.host}, which Google Web Risk lists as ${describeLinkThreats(signal.threats)}.`;
1104
1121
  default:
1105
1122
  return 'Phishing signal.';
1106
1123
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/outbound-phishing-screen.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 OUTBOUND PHISHING SCREEN (AGL-3356).\n *\n * A fraud actor signed up, paid with a card that never met 3-D Secure, and\n * used a workspace to send two kinds of mail: a campaign of Booking.com-style\n * \"guest feedback regarding your property\" lures to hotels, and a workflow\n * that mailed \"Poshmark Order — one of the items from your Seller Account has\n * finally sold\", linking to `poshmark.id63835663.shop`.\n *\n * This module answers one question about a message a YOUNG workspace is\n * about to send: does its content carry a STRONG phishing signal? The caller\n * decides who is young and what happens to a positive answer — the answer is\n * a hold for staff review, never a drop.\n *\n * ## Conservative by construction\n *\n * A false positive costs a real merchant's first campaign a wait for a\n * human; a miss costs strangers their bank logins. Both are real, so only\n * four shapes hold, and each is one a legitimate merchant essentially never\n * produces:\n *\n * 1. **A lookalike link** — a link or reply address whose host carries a\n * brand's name without being the brand's own domain: the brand as a label\n * of an unrelated registrable domain (`poshmark.id63835663.shop`), hyphen-\n * joined to one (`paypal-secure.com`, `secure-paypal.net`), the brand's\n * real domain embedded in a longer host (`booking.com.guest-review.top`),\n * or leetspeak for it (`paypa1.com`). Holds on its own.\n * 2. **A brand in the sender's display name** that is not the workspace's\n * own name — mail that says it is FROM PayPal.\n * 3. **The three-part lure**: a brand named in the copy, AND credential or\n * account-action phrasing (\"verify your account\", \"has finally sold\",\n * \"feedback regarding your property\"), AND a link to a domain that is\n * neither the brand's, nor the workspace's, nor a common social or maps\n * link. Any two of the three are ordinary marketing — \"our book is on\n * Amazon\", \"sign in to your account\", a link to the shop — and pass.\n * 4. **A prefilled sign-in** (AGL-3453): account or password phrasing\n * (\"your password expires today\") beside a link to such a domain that\n * carries the reader's own address, so the harvester's form opens with\n * it filled in: `…/ss/c/…#victim@example.com`.\n *\n * Mentioning a brand, alone, never holds. Brands and lures are read from\n * what the reader SEES ({@link visibleTextOf}), never from the raw HTML, in\n * which a kit splits every letter with a tag; links are read from the raw\n * HTML, where an href lives.\n *\n * ## The brand list is small on purpose\n *\n * The brands phishing kits most often wear, plus the two in the incident, and\n * the file-share and mail-security names a document-share lure wears — a\n * \"Secure Document Access Portal\" under Proofpoint's or SharePoint's name\n * whose one button leaves for the kit (AGL-3447). A brand is added when it\n * has been seen impersonated, not because it is big: every entry is a set of\n * words that can now hold somebody's newsletter.\n * Each carries its REAL domains, so a link to the brand itself is never\n * suspicious, and host tokens chosen so a common word (`booking`, `apple`,\n * `outlook`, `box`, `adobe`) does not match an unrelated host by itself.\n *\n * Pure: no DNS, no store, no clock. Everything the caller knows about the\n * workspace arrives as input.\n *=========================================*/\n\n/** One brand the screen recognizes. */\nexport interface PhishingScreenBrand {\n /** Stable id, as stored on a hold. */\n id: string\n /** How staff read it. */\n label: string\n /** Copy that names the brand — subject, body, sender. Case-insensitive. */\n mention: RegExp\n /**\n * Host labels that name the brand. Matched against each dot-separated\n * label of a link's host, whole or hyphen-joined, after leetspeak is\n * folded — never as a bare substring, which is how `amazonaws` or\n * `bookingengine` would read as a brand.\n */\n hostTokens: readonly string[]\n /**\n * Registrable domains the brand genuinely links from. The FIRST is its\n * primary domain, the one a kit embeds in a longer host.\n */\n officialDomains: readonly string[]\n /**\n * The brand's name is an ordinary word (`apple`, `amazon`), so a host\n * label names the brand only when it IS the word — `apple.example.top` —\n * and never hyphen-joined or leet-folded, which `apple-orchard-farm.com`\n * would otherwise be.\n */\n wordToken?: boolean\n /**\n * Whether `<brand>.<country code>` (and `<brand>.co.<cc>`) is the brand's\n * too — true for the marketplaces that run a site per country.\n */\n countryDomains?: boolean\n /**\n * Registrable domains the brand runs but where OTHER people's content lives —\n * the platform's own tenant apex, where every site is `<name>.<apex>`. A\n * host there never wears the brand as a disguise, so the lookalike rule\n * skips it; but it is not the brand's own domain either, so a link to a\n * neighbor's site still counts as \"somewhere else\" to the lure rules, and a\n * workspace hosted there does not own the brand by being hosted there.\n */\n hostedDomains?: readonly string[]\n}\n\nexport const PHISHING_SCREEN_BRANDS: readonly PhishingScreenBrand[] = [\n {\n id: 'poshmark',\n label: 'Poshmark',\n mention: /\\bposhmark\\b/i,\n hostTokens: ['poshmark'],\n officialDomains: ['poshmark.com', 'posh.mk'],\n },\n {\n id: 'booking',\n label: 'Booking.com',\n // Never the bare word: \"booking\" is every hotel's and every salon's.\n mention: /\\bbooking\\.com\\b/i,\n hostTokens: ['bookingcom', 'booking-com'],\n officialDomains: ['booking.com', 'bstatic.com'],\n },\n {\n id: 'airbnb',\n label: 'Airbnb',\n mention: /\\bairbnb\\b/i,\n hostTokens: ['airbnb'],\n officialDomains: ['airbnb.com', 'abnb.me', 'muscache.com'],\n countryDomains: true,\n },\n {\n id: 'paypal',\n label: 'PayPal',\n mention: /\\bpay\\s?pal\\b/i,\n hostTokens: ['paypal'],\n officialDomains: ['paypal.com', 'paypal.me', 'paypalobjects.com'],\n countryDomains: true,\n },\n {\n id: 'amazon',\n label: 'Amazon',\n mention: /\\bamazon\\b/i,\n hostTokens: ['amazon', 'amzn'],\n wordToken: true,\n officialDomains: [\n 'amazon.com',\n 'amzn.to',\n 'amzn.com',\n 'amazonaws.com',\n 'media-amazon.com',\n 'ssl-images-amazon.com',\n ],\n countryDomains: true,\n },\n {\n id: 'apple',\n label: 'Apple',\n // The fruit is on every bakery's menu; the account is what gets phished.\n mention: /\\bapple\\s?(?:id|support|account)\\b|\\bicloud\\b|\\bitunes\\b/i,\n hostTokens: ['apple', 'appleid', 'icloud', 'itunes'],\n wordToken: true,\n officialDomains: ['apple.com', 'icloud.com', 'apple.co', 'itunes.com', 'me.com', 'mzstatic.com'],\n countryDomains: true,\n },\n {\n id: 'microsoft',\n label: 'Microsoft',\n // Outlook only as the product — \"our 2026 outlook\" is every advisor's\n // newsletter.\n mention:\n /\\bmicrosoft\\b|\\b(?:office|ms|m)\\s?365\\b|\\bonedrive\\b|\\bsharepoint\\b|\\boutlook(?:\\.com|\\s+(?:web\\s+app|web\\s+access|online|account|365))\\b/i,\n hostTokens: [\n 'microsoft',\n 'microsoft365',\n 'office365',\n 'office-365',\n 'outlook365',\n 'onedrive',\n 'sharepoint',\n 'microsoftonline',\n 'msonline',\n ],\n officialDomains: [\n 'microsoft.com',\n 'office.com',\n 'office365.com',\n 'microsoft365.com',\n 'live.com',\n 'outlook.com',\n 'microsoftonline.com',\n 'sharepoint.com',\n 'sharepointonline.com',\n 'onedrive.com',\n '1drv.ms',\n 'aka.ms',\n ],\n },\n {\n id: 'docusign',\n label: 'DocuSign',\n mention: /\\bdocu\\s?sign\\b/i,\n hostTokens: ['docusign'],\n officialDomains: ['docusign.com', 'docusign.net'],\n },\n {\n id: 'google',\n label: 'Google',\n // The account and the files, never the bare name: \"find us on Google\"\n // and \"Google Maps\" are on every shop's contact page.\n mention: /\\bgoogle\\s?(?:drive|docs?|sheets|slides|workspace|account)\\b|\\bgmail\\b|\\bg\\s?suite\\b/i,\n // The products and the account, never the bare name: Google runs\n // hyphenated hosts of its own that a page embeds, and a bare `google`\n // token would read each as its lookalike. `docs.google.com.<kit>` is\n // still read, by the primary-domain rule.\n hostTokens: [\n 'gmail',\n 'gsuite',\n 'googledocs',\n 'googledrive',\n 'google-docs',\n 'google-drive',\n 'google-workspace',\n 'google-account',\n 'google-login',\n 'google-mail',\n 'docs-google',\n 'drive-google',\n ],\n officialDomains: [\n 'google.com',\n 'goo.gl',\n 'g.co',\n 'g.page',\n 'forms.gle',\n 'gmail.com',\n 'googleapis.com',\n 'gstatic.com',\n 'googleusercontent.com',\n 'withgoogle.com',\n ],\n countryDomains: true,\n },\n {\n id: 'adobe',\n label: 'Adobe',\n // \"Adobe\" alone is a house, a grill and an inn across the Southwest;\n // the products are what a lure names.\n mention:\n /\\badobe\\s?(?:acrobat|sign|id|account|document\\s?cloud|reader|pdf|creative\\s?cloud)\\b|\\bacrobat\\s?(?:reader|sign|pro)\\b|\\bechosign\\b/i,\n hostTokens: ['adobe', 'adobeid', 'adobesign', 'adobeacrobat', 'echosign'],\n wordToken: true,\n officialDomains: [\n 'adobe.com',\n 'adobe.io',\n 'adobe.ly',\n 'adobelogin.com',\n 'adobesign.com',\n 'echosign.com',\n 'acrobat.com',\n 'typekit.net',\n 'adobedtm.com',\n ],\n },\n {\n id: 'dropbox',\n label: 'Dropbox',\n // One word only: a \"drop box\" is by every library's door.\n mention: /\\bdropbox\\b/i,\n hostTokens: ['dropbox'],\n officialDomains: ['dropbox.com', 'db.tt', 'dropboxusercontent.com', 'dropboxstatic.com', 'hellosign.com'],\n },\n {\n // Never the bare word, as an id either — `brandForSubdomainLabel` reads\n // ids as words, and \"box\" is every lunch box's and subscription box's.\n id: 'boxcom',\n label: 'Box',\n mention: /\\bbox\\.com\\b|\\bbox\\s+drive\\b/i,\n hostTokens: ['boxcom', 'box-com'],\n officialDomains: ['box.com', 'box.net', 'boxcdn.net', 'boxcloud.com'],\n },\n {\n id: 'wetransfer',\n label: 'WeTransfer',\n // One word only: \"we transfer\" is a moving company's sentence.\n mention: /\\bwetransfer\\b/i,\n hostTokens: ['wetransfer'],\n officialDomains: ['wetransfer.com', 'we.tl'],\n },\n {\n id: 'sharefile',\n label: 'ShareFile',\n mention: /\\bshare\\s?file\\b/i,\n hostTokens: ['sharefile'],\n officialDomains: ['sharefile.com', 'sharefile.eu', 'citrix.com'],\n },\n {\n // A secure-mail gateway's name is what makes a document lure read as\n // safe: \"Proofpoint Encryption for your sensitive documents\".\n id: 'proofpoint',\n label: 'Proofpoint',\n // One word only: a \"proof point\" is every pitch deck's.\n mention: /\\bproofpoint\\b/i,\n hostTokens: ['proofpoint'],\n officialDomains: ['proofpoint.com', 'urldefense.com', 'pphosted.com', 'ppe-hosted.com'],\n },\n {\n id: 'mimecast',\n label: 'Mimecast',\n mention: /\\bmimecast\\b/i,\n hostTokens: ['mimecast'],\n officialDomains: ['mimecast.com', 'mimecastprotect.com'],\n },\n {\n id: 'netflix',\n label: 'Netflix',\n mention: /\\bnetflix\\b/i,\n hostTokens: ['netflix'],\n officialDomains: ['netflix.com', 'nflxext.com', 'nflximg.net'],\n },\n {\n id: 'wellsfargo',\n label: 'Wells Fargo',\n mention: /\\bwells\\s?fargo\\b/i,\n hostTokens: ['wellsfargo', 'wells-fargo'],\n officialDomains: ['wellsfargo.com'],\n },\n {\n id: 'bankofamerica',\n label: 'Bank of America',\n mention: /\\bbank\\s+of\\s+america\\b/i,\n hostTokens: ['bankofamerica', 'bofa'],\n officialDomains: ['bankofamerica.com', 'bofa.com'],\n },\n {\n id: 'coinbase',\n label: 'Coinbase',\n mention: /\\bcoinbase\\b/i,\n hostTokens: ['coinbase'],\n officialDomains: ['coinbase.com'],\n },\n {\n id: 'usps',\n label: 'USPS',\n mention: /\\busps\\b/i,\n hostTokens: ['usps'],\n officialDomains: ['usps.com'],\n },\n {\n id: 'fedex',\n label: 'FedEx',\n mention: /\\bfed\\s?ex\\b/i,\n hostTokens: ['fedex'],\n officialDomains: ['fedex.com'],\n },\n {\n id: 'dhl',\n label: 'DHL',\n mention: /\\bdhl\\b/i,\n hostTokens: ['dhl'],\n officialDomains: ['dhl.com'],\n countryDomains: true,\n },\n {\n // The platform itself (AGL-3365). A marketplace listing, a page or an\n // email that wears the platform's name — \"Aglyn Support\", a link to\n // `aglyn-billing.com`, \"official Aglyn plugin\" — is the one impersonation\n // every customer is primed to trust. The workspace named for it (the\n // platform's own org) owns it by name, as any brand's own workspace does.\n id: 'aglyn',\n label: 'Aglyn',\n mention: /\\baglyn\\b/i,\n hostTokens: ['aglyn'],\n officialDomains: ['aglyn.com', 'aglyn.io', 'aglyn.dev'],\n hostedDomains: ['aglyn.app'],\n },\n]\n\n/**\n * Account and credential phrasing: the lure that asks the reader to DO\n * something with an account — verify it, confirm it, sign in to it.\n */\nexport const ACCOUNT_LURE_PATTERNS: readonly RegExp[] = [\n /\\bverify\\s+your\\s+(?:account|identity|information|details|payment|email)\\b/i,\n /\\bconfirm\\s+your\\s+(?:account|identity|details|payment|password|billing|information)\\b/i,\n /\\b(?:account|payment|card)\\s+(?:has\\s+been\\s+|is\\s+|was\\s+|will\\s+be\\s+)?(?:suspended|locked|limited|restricted|disabled|deactivated|terminated|on\\s+hold)\\b/i,\n /\\bunusual\\s+(?:sign[-\\s]?in|login|activity)\\b/i,\n /\\bupdate\\s+your\\s+(?:payment|billing|card|account)\\s*(?:details|information|method)?\\b/i,\n /\\b(?:sign|log)\\s?in\\s+to\\s+(?:your|view|confirm|claim|release)\\b/i,\n // \"Password Expired\", \"your password expires today\", \"will expire\".\n /\\bpassword\\s+(?:has\\s+|will\\s+)?expire/i,\n /\\bkeep\\s+(?:your|my|the)\\s+(?:current\\s+|active\\s+|existing\\s+|same\\s+)?password\\b/i,\n /\\bchange\\s+(?:your\\s+)?password\\s+settings?\\b/i,\n /\\bmailbox\\s+(?:storage\\s+|quota\\s+)?(?:is\\s+)?(?:almost\\s+|nearly\\s+)?(?:full|exceeded)\\b/i,\n /\\bsecurity\\s+alert\\b/i,\n]\n\n/**\n * Document-share phrasing (AGL-3447): the lure that says a file is waiting\n * behind a secure door — \"Secure Document Access Portal\", \"Continue to\n * Document\", \"shared a file with you\", \"encrypted message\". The credential\n * harvest is on the far side of the button, so these are the words the page\n * or the mail itself carries.\n */\nexport const DOCUMENT_SHARE_LURE_PATTERNS: readonly RegExp[] = [\n /\\b(?:document|invoice|agreement)s?\\s+(?:is\\s+|are\\s+)?(?:ready|waiting|pending)\\s+(?:for\\s+)?(?:your\\s+)?(?:review|signature|to\\s+sign)\\b/i,\n /\\b(?:view|access|open)\\s+(?:the\\s+|your\\s+)?secure\\s+(?:file|document|message)s?\\b/i,\n /\\bsecure\\s+(?:file|document|message)s?\\b/i,\n /\\bdocument\\s+access\\b/i,\n /\\baccess\\s+portal\\b/i,\n /\\b(?:continue|proceed)\\s+to\\s+(?:the\\s+|your\\s+)?(?:document|file)s?\\b/i,\n /\\bshared\\s+(?:a|an|the)\\s+(?:file|document|folder)\\s+with\\s+you\\b/i,\n /\\b(?:file|document|folder)s?\\s+(?:has\\s+been|have\\s+been|was|were)\\s+shared\\s+with\\s+you\\b/i,\n /\\bencrypted\\s+(?:message|document|file|email)s?\\b/i,\n]\n\n/**\n * Marketplace, booking and parcel phrasing: the lure that says a sale, a\n * guest or a delivery needs the reader. The incident's Poshmark and\n * Booking.com mail.\n */\nconst SALE_AND_PARCEL_LURE_PATTERNS: readonly RegExp[] = [\n /\\b(?:has|have)\\s+(?:finally\\s+)?sold\\b/i,\n /\\bseller\\s+account\\b/i,\n /\\b(?:guest|customer)\\s+(?:complaint|review|feedback)\\b/i,\n /\\bfeedback\\s+regarding\\s+your\\s+(?:property|listing|stay|booking|reservation)\\b/i,\n /\\bclaim\\s+your\\s+(?:refund|reward|prize|package|payment|funds)\\b/i,\n /\\b(?:delivery|shipment)\\s+(?:failed|attempt|suspended|on\\s+hold)\\b/i,\n /\\b(?:package|parcel)\\s+(?:is\\s+)?(?:on\\s+hold|held|awaiting|undeliverable)\\b/i,\n]\n\n/**\n * Every lure — the half of the three-part lure that asks the reader to act.\n * Only ever counted beside a brand AND a foreign link; alone, several of\n * these are ordinary transactional copy.\n */\nexport const PHISHING_LURE_PATTERNS: readonly RegExp[] = [\n ...ACCOUNT_LURE_PATTERNS,\n ...DOCUMENT_SHARE_LURE_PATTERNS,\n ...SALE_AND_PARCEL_LURE_PATTERNS,\n]\n\n/**\n * Link targets a merchant's mail ordinarily carries that are not theirs:\n * social profiles, maps, review sites, video. Counted as neither foreign nor\n * suspicious in the three-part lure, so \"leave us a review on Google\" with a\n * brand named elsewhere does not become a hold. Never consulted by the\n * lookalike check, which holds on the host's own shape.\n */\nconst COMMON_LINK_DOMAINS: ReadonlySet<string> = new Set([\n 'facebook.com',\n 'fb.com',\n 'instagram.com',\n 'x.com',\n 'twitter.com',\n 'linkedin.com',\n 'youtube.com',\n 'youtu.be',\n 'tiktok.com',\n 'pinterest.com',\n 'google.com',\n 'goo.gl',\n 'g.page',\n 'yelp.com',\n 'tripadvisor.com',\n 'wa.me',\n 'whatsapp.com',\n])\n\n/**\n * Two-label public suffixes, so `evil.co.uk` registers as `evil.co.uk` and\n * not as `co.uk`. Deliberately a short list of the ones mail actually\n * arrives from rather than the whole public suffix list: a suffix missing\n * here makes the registrable domain one label too short, which can only\n * widen what counts as \"the same domain\" for a link — never invent a brand\n * label that is not in the host.\n */\nconst TWO_LABEL_SUFFIXES: ReadonlySet<string> = new Set([\n 'co.uk', 'org.uk', 'ac.uk', 'gov.uk', 'me.uk',\n 'com.au', 'net.au', 'org.au',\n 'co.nz', 'co.jp', 'co.kr', 'co.in', 'co.za', 'co.il', 'co.id', 'co.th',\n 'com.br', 'com.mx', 'com.ar', 'com.tr', 'com.cn', 'com.hk', 'com.sg',\n 'com.tw', 'com.my', 'com.ph', 'com.co', 'com.pe', 'com.sa', 'com.eg',\n])\n\n/** A signal the screen found. */\nexport type PhishingScreenSignal =\n | { code: 'lookalike-link'; brand: string; host: string }\n | { code: 'brand-sender'; brand: string; fromName: string }\n | { code: 'brand-lure-link'; brand: string; lure: string; host: string }\n /**\n * A published page asks for a password, a card number or a one-time code\n * in a field that is not one of the platform's own sign-in or checkout\n * elements (`hosted-page-screen.ts`). Strong.\n */\n | { code: 'credential-field'; field: 'password' | 'card' | 'otp'; label: string }\n /**\n * A published page names a brand that is not the workspace's beside a\n * sign-in, verify or payment call to action (`hosted-page-screen.ts`).\n * Soft.\n */\n | { code: 'brand-action-page'; brand: string; action: string }\n /**\n * The same, read over the page as a WHOLE (AGL-3447): a brand that is not\n * the workspace's anywhere on a page that carries an account or\n * document-share lure anywhere, or whose call to action leaves the site\n * worded as one, and that links away (`hosted-page-screen.ts`). Soft.\n */\n | { code: 'brand-lure-page'; brand: string; lure: string; host: string }\n /**\n * A published page's call to action — its only one, or one worded as an\n * account or document action — sends visitors to a host that is not the\n * site's, a listed brand's or a common link, on a page that carries an\n * account or document-share lure (`hosted-page-screen.ts`, AGL-3447). No\n * brand needed. Soft.\n */\n | { code: 'offsite-action-page'; action: string; lure: string; host: string }\n /**\n * A site redirect whose path reads as an account or document-share lure\n * sends visitors to such a host (`screenSiteRedirect`, AGL-3447). Soft.\n */\n | { code: 'offsite-redirect'; source: string; lure: string; host: string }\n /**\n * Account or password phrasing beside a link elsewhere that carries the\n * reader's own address (AGL-3453). STRONG when the address is the whole\n * fragment (`#victim@example.com`), which only a landing page's script\n * reads; soft when it is a query parameter or part of a longer fragment.\n * The address itself is never stored.\n */\n | { code: 'recipient-prefill-link'; host: string; lure: string; place: 'fragment' | 'parameter' }\n /**\n * A link, embed, redirect or form action whose host Google Web Risk lists\n * as phishing, malware or unwanted software (AGL-3451,\n * `link-reputation.ts`). Strong: a harvester already known to be bad\n * anywhere is bad whatever page or message surrounds it.\n */\n | { code: 'web-risk-link'; host: string; threats: string[] }\n\nexport interface PhishingScreenInput {\n subject?: string | null\n /** The display name in front of the sending address. */\n fromName?: string | null\n /**\n * The ADDRESS the message leaves from (AGL-3362) — a `From:` domain is a\n * link the recipient never has to click, so its host is read by the\n * lookalike rule exactly like a link's: mail from `support@paypa1.com` is\n * the disguise whoever sends it. Not an own domain for the lure's \"is this\n * elsewhere\" test either way; it only ever adds a lookalike signal.\n */\n fromAddress?: string | null\n replyTo?: string | readonly string[] | null\n preheader?: string | null\n /**\n * Everything else the recipient reads or clicks: the body, the plain-text\n * part, a design's nodes serialized — any string. Links are found by\n * shape, so a JSON-encoded design is as readable here as HTML.\n */\n bodies?: readonly (string | null | undefined)[]\n /**\n * The workspace's own names — org, site, subdomain. A brand in one of them\n * is the workspace's own, and `brand-sender` / `brand-lure-link` do not\n * fire for it. The lookalike check does not consult names: a workspace\n * NAMED \"Poshmark\" linking to `poshmark.id63835663.shop` is the incident.\n */\n ownNames?: readonly (string | null | undefined)[]\n /**\n * The workspace's own hosts — its subdomain on the tenant apex, custom\n * domain, sending domain. A link to one of them, or below one, is never\n * the \"somewhere else\" of a lure. Matched by host, never by registrable\n * domain: every site's subdomain shares the tenant apex, and a link to a\n * NEIGHBOR's site is somewhere else.\n *\n * Not an exemption from the lookalike check. A host shaped like\n * `paypal-secure.com` is a lookalike whoever attached it, and a workspace\n * that attached it has attached the disguise.\n */\n ownDomains?: readonly (string | null | undefined)[]\n}\n\nexport interface PhishingScreenVerdict {\n /** True when the message should be held for staff review. */\n hold: boolean\n signals: PhishingScreenSignal[]\n}\n\n/** The registrable domain of a host: `a.b.evil.co.uk` → `evil.co.uk`. */\nexport function registrableDomain(host: string): string {\n const labels = String(host ?? '')\n .toLowerCase()\n .replace(/\\.+$/, '')\n .split('.')\n .filter(Boolean)\n if (labels.length <= 2) return labels.join('.')\n const lastTwo = labels.slice(-2).join('.')\n return TWO_LABEL_SUFFIXES.has(lastTwo)\n ? labels.slice(-3).join('.')\n : lastTwo\n}\n\n/** `<label>.<suffix>` of a registrable domain, split once. */\nfunction splitRegistrable(registrable: string): { label: string; suffix: string } {\n const dot = registrable.indexOf('.')\n return dot < 0\n ? { label: registrable, suffix: '' }\n : { label: registrable.slice(0, dot), suffix: registrable.slice(dot + 1) }\n}\n\nfunction isOfficialDomain(brand: PhishingScreenBrand, registrable: string): boolean {\n if (brand.officialDomains.includes(registrable)) return true\n if (!brand.countryDomains) return false\n const base = splitRegistrable(brand.officialDomains[0]).label\n const { label, suffix } = splitRegistrable(registrable)\n return label === base && (/^[a-z]{2}$/.test(suffix) || TWO_LABEL_SUFFIXES.has(suffix))\n}\n\n/**\n * Is the workspace the brand itself, by DOMAIN: one of its own domains is\n * one of the brand's official ones (Aglyn's site on aglyn.com linking to\n * its own account on a video or help-desk vendor). Deliberately not by name — a workspace can call itself\n * \"Poshmark\", but it cannot serve on poshmark.com.\n */\nexport function isBrandsOwnDomain(\n brand: PhishingScreenBrand,\n ownRegistrables: ReadonlySet<string>,\n): boolean {\n return [...ownRegistrables].some((registrable) => isOfficialDomain(brand, registrable))\n}\n\n/** Every brand's real domains, for \"is this link just the brand itself\". */\nfunction isAnyOfficialDomain(registrable: string): boolean {\n return PHISHING_SCREEN_BRANDS.some((brand) => isOfficialDomain(brand, registrable))\n}\n\n/** Leetspeak folded, so `paypa1` reads as `paypal`. */\nfunction foldLeet(label: string): string {\n return label\n .replace(/0/g, 'o')\n .replace(/1/g, 'l')\n .replace(/3/g, 'e')\n .replace(/4/g, 'a')\n .replace(/5/g, 's')\n .replace(/7/g, 't')\n}\n\n/** Does one host label name the brand — whole, or hyphen-joined? */\nfunction labelNamesBrand(label: string, token: string, wordToken: boolean): boolean {\n if (wordToken) return label === token\n for (const candidate of new Set([label, foldLeet(label)])) {\n if (candidate === token) return true\n const parts = candidate.split('-')\n // A hyphen-joined token (`booking-com`) spans parts, so it is matched\n // as a run of parts rather than one of them.\n const tokenParts = token.split('-')\n for (let at = 0; at + tokenParts.length <= parts.length; at += 1) {\n if (tokenParts.every((part, offset) => parts[at + offset] === part)) {\n return true\n }\n }\n }\n return false\n}\n\n/**\n * Video and audio platforms whose account subdomains and embed URLs a page\n * or email plays media from: `player.vimeo.com`, `www.youtube.com/embed/…`.\n * A video plugin's own hosts are the plugin's to declare, not listed here. Anyone may embed or link media from these, so a\n * host on one is never a lookalike, whatever name its subdomain carries.\n */\nexport const MEDIA_EMBED_HOSTS: ReadonlySet<string> = new Set([\n 'vimeo.com', 'vimeocdn.com', 'youtube.com', 'youtu.be',\n 'youtube-nocookie.com', 'ytimg.com', 'loom.com', 'vidyard.com', 'brightcove.net',\n 'brightcove.com', 'jwplayer.com', 'jwpcdn.com', 'mux.com', 'cloudflarestream.com',\n 'videodelivery.net', 'dailymotion.com', 'twitch.tv', 'spotify.com', 'soundcloud.com',\n 'podbean.com', 'buzzsprout.com', 'simplecast.com', 'transistor.fm', 'anchor.fm',\n])\n\n/** The brand a host impersonates, or null. */\nexport function lookalikeBrandForHost(host: string): PhishingScreenBrand | null {\n const normalized = String(host ?? '').toLowerCase().replace(/\\.+$/, '')\n if (!normalized.includes('.')) return null\n const registrable = registrableDomain(normalized)\n if (MEDIA_EMBED_HOSTS.has(registrable)) return null\n for (const brand of PHISHING_SCREEN_BRANDS) {\n if (isOfficialDomain(brand, registrable)) continue\n if (brand.hostedDomains?.includes(registrable)) continue\n const labels = normalized.split('.')\n if (\n labels.some((label) =>\n brand.hostTokens.some((token) => labelNamesBrand(label, token, brand.wordToken === true)),\n )\n ) {\n return brand\n }\n // The brand's primary domain embedded in a longer, different one:\n // `booking.com.guest-review.top`, `paypal.com-secure.net`. Only the\n // primary: a short secondary (`me.com`, `aka.ms`) would match too much.\n const primary = brand.officialDomains[0]\n if (\n normalized.startsWith(`${primary}.`) ||\n normalized.startsWith(`${primary}-`) ||\n normalized.includes(`.${primary}.`) ||\n normalized.includes(`.${primary}-`)\n ) {\n return brand\n }\n }\n return null\n}\n\n/**\n * The few entity forms a phishing kit uses to keep a URL away from a naive\n * scanner (`&#46;` for a dot, `&amp;` inside a query). Decoded before links\n * are read; everything else is left alone.\n */\nfunction decodeEntities(text: string): string {\n return text\n .replace(/&#x([0-9a-f]{1,6});/gi, (_, hex: string) => safeCodePoint(parseInt(hex, 16)))\n .replace(/&#(\\d{1,7});/g, (_, dec: string) => safeCodePoint(parseInt(dec, 10)))\n .replace(/&amp;/gi, '&')\n}\n\nfunction safeCodePoint(value: number): string {\n return Number.isFinite(value) && value > 0 && value <= 0x10ffff\n ? String.fromCodePoint(value)\n : ''\n}\n\n/** Named entities a body uses for spacing, quoting and invisible splitting. */\nconst NAMED_ENTITIES: Record<string, string> = {\n nbsp: ' ',\n ensp: ' ',\n emsp: ' ',\n thinsp: ' ',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n shy: '',\n zwnj: '',\n zwj: '',\n}\n\n/*\n * Markup is read in single forward passes, never with a pattern that can\n * rescan to the end of the body from every `<`: the screen reads every\n * tenant message, and the tenant writes the body, so a million unclosed\n * `<` must cost a linear read.\n */\n/** An element whose contents a reader never sees: the start of its opening tag. */\nconst UNSEEN_ELEMENT_OPEN = /<(style|script|head|template)\\b/gi\n/** The name at the start of a tag that breaks a line or a block: a reader sees a gap there. */\nconst BREAKING_TAG_NAME =\n /^\\/?(?:br|p|div|li|ul|ol|tr|td|th|table|tbody|thead|h[1-6]|section|article|header|footer|blockquote|hr|center)\\b/i\n/** Characters that render as nothing, used to split a word for a scanner. */\nconst INVISIBLE_CHARACTERS = /[\\u00ad\\u200b-\\u200d\\u2060\\ufeff]/g\n\n/**\n * The text between the tags, joined with NO separator — or, with `breaks`,\n * with a space where a line or block breaks. A comment is dropped; a `<`\n * with no `>` after it is text.\n */\nfunction stripMarkup(html: string, breaks: boolean): string {\n let text = ''\n let at = 0\n while (at < html.length) {\n const open = html.indexOf('<', at)\n if (open < 0) return text + html.slice(at)\n text += html.slice(at, open)\n if (html.startsWith('<!--', open)) {\n const end = html.indexOf('-->', open + 4)\n if (end < 0) return text\n at = end + 3\n continue\n }\n const close = html.indexOf('>', open + 1)\n if (close < 0) return text + html.slice(open)\n if (breaks && BREAKING_TAG_NAME.test(html.slice(open + 1, Math.min(close, open + 12)))) text += ' '\n at = close + 1\n }\n return text\n}\n\n/** The markup with every unseen element and its contents taken out, in one pass. */\nfunction dropUnseenElements(html: string): string {\n const lower = html.toLowerCase()\n const open = new RegExp(UNSEEN_ELEMENT_OPEN.source, 'gi')\n let kept = ''\n let at = 0\n // Each search starts at or after the last; what it found (or that it found\n // nothing) still answers the next one, so no stretch is scanned twice.\n const found = new Map<string, number>()\n const find = (needle: string, from: number) => {\n const known = found.get(needle)\n if (known !== undefined && (known < 0 || known >= from)) return known\n const position = lower.indexOf(needle, from)\n found.set(needle, position)\n return position\n }\n for (let match = open.exec(html); match; match = open.exec(html)) {\n // No `>` after it: neither this nor anything later is a tag.\n const tagEnd = find('>', open.lastIndex)\n if (tagEnd < 0) break\n kept += `${html.slice(at, match.index)} `\n const name = match[1].toLowerCase()\n const close = find(`</${name}`, tagEnd + 1)\n // A head nobody closed ends where the body starts, as a browser reads it.\n const body = name === 'head' ? find('<body', tagEnd + 1) : -1\n if (body >= 0 && (close < 0 || body < close)) {\n at = body\n } else {\n const end = close < 0 ? -1 : find('>', close)\n // Never closed: only the opening tag goes, and what follows is still\n // read, so an unclosed `<style>` cannot hide the lure after it.\n at = end < 0 ? tagEnd + 1 : end + 1\n }\n open.lastIndex = at\n }\n return kept + html.slice(at)\n}\n\n/**\n * What a reader SEES in a body (AGL-3453): its text with the markup taken\n * out, the way a mail client or a browser draws it.\n *\n * A kit splits every letter of a brand and a lure with a tag —\n * `G<SPAN class=…>o<SPAN …>o…gle`, `P<SPAN …>a<SPAN …>s…word E<SPAN …>x…pired`\n * — so the raw HTML never contains the word a reader reads. Tags are\n * therefore removed with NO separator, which rejoins the letters; `<style>`,\n * `<script>` and `<head>` are dropped with their contents; comments and\n * zero-width characters are dropped; entities are decoded; whitespace is\n * collapsed. A second reading that puts a space where a line or block\n * breaks is added when it differs, so two words in two paragraphs are still\n * two words. Links are NOT read from this: an href lives inside a tag.\n */\nexport function visibleTextOf(html: string | null | undefined): string {\n const text = String(html ?? '')\n const source = text.includes('<') ? dropUnseenElements(text) : text\n const read = (breaks: boolean) =>\n decodeVisibleEntities(stripMarkup(source, breaks))\n .replace(INVISIBLE_CHARACTERS, '')\n .replace(/\\s+/g, ' ')\n .trim()\n const joined = read(false)\n const broken = read(true)\n return broken === joined ? joined : `${joined}\\n${broken}`\n}\n\n/** {@link decodeEntities}, after the named entities a body reads with. */\nfunction decodeVisibleEntities(text: string): string {\n return decodeEntities(\n text.replace(/&([a-z]{2,8});/gi, (entity, name: string) => NAMED_ENTITIES[name.toLowerCase()] ?? entity),\n )\n}\n\nconst URL_PATTERN = /\\b(?:https?:\\/\\/|www\\.)[^\\s\"'<>()\\\\[\\]{}]+/gi\n\n/** The hosts every link in the text points at, lowercased. */\nexport function linkHostsIn(text: string): string[] {\n const hosts = new Set<string>()\n for (const match of decodeEntities(String(text ?? '')).match(URL_PATTERN) ?? []) {\n let rest = match.replace(/^https?:\\/\\//i, '')\n rest = rest.split(/[/?#]/)[0]\n // `https://paypal.com@evil.top/` resolves to evil.top — and the part\n // before the `@` is exactly the disguise, so it is kept as a host too.\n const at = rest.lastIndexOf('@')\n const disguise = at >= 0 ? rest.slice(0, at) : ''\n rest = at >= 0 ? rest.slice(at + 1) : rest\n for (const candidate of [rest, disguise]) {\n const host = candidate.replace(/:\\d+$/, '').replace(/\\.+$/, '').toLowerCase()\n // A merge tag inside a URL is not a host anybody can visit yet.\n if (host && host.includes('.') && !host.includes('{') && !host.includes('%7b')) {\n hosts.add(host)\n }\n }\n }\n return [...hosts]\n}\n\n/** One link: the host it goes to, and its query and fragment, URL-decoded. */\ninterface LinkTarget {\n host: string\n query: string\n fragment: string\n}\n\n/** Every link in the text, with what it carries after its path. */\nfunction linkTargetsIn(text: string): LinkTarget[] {\n const targets: LinkTarget[] = []\n for (const match of decodeEntities(String(text ?? '')).match(URL_PATTERN) ?? []) {\n // The first host is where the browser goes; a userinfo disguise is not.\n const [host] = linkHostsIn(match)\n if (!host) continue\n const hash = match.indexOf('#')\n const beforeHash = hash < 0 ? match : match.slice(0, hash)\n const question = beforeHash.indexOf('?')\n targets.push({\n host,\n query: question < 0 ? '' : decodeUrlPart(beforeHash.slice(question + 1)),\n fragment: hash < 0 ? '' : decodeUrlPart(match.slice(hash + 1)),\n })\n }\n return targets\n}\n\nfunction decodeUrlPart(part: string): string {\n try {\n return decodeURIComponent(part)\n } catch {\n return part\n }\n}\n\nconst EMAIL_ADDRESS = /^[a-z0-9._%+-]+@[a-z0-9-]+(?:\\.[a-z0-9-]+)+$/i\nconst EMAIL_ADDRESS_IN_TEXT = /[a-z0-9._%+-]+@([a-z0-9-]+(?:\\.[a-z0-9-]+)+)/gi\nconst BASE64_TEXT = /^[a-z0-9+/_-]{8,}={0,2}$/i\n\n/** A fragment read as base64, the other way a kit carries the address, or ''. */\nfunction base64Text(fragment: string): string {\n const decode = (globalThis as { atob?: (data: string) => string }).atob\n if (!decode || !BASE64_TEXT.test(fragment)) return ''\n try {\n return decode(fragment.replace(/-/g, '+').replace(/_/g, '/'))\n } catch {\n return ''\n }\n}\n\n/**\n * Where a link carries a reader's own address (AGL-3453), or null.\n *\n * - `fragment`: the WHOLE fragment is an address, plain or base64 —\n * `…#victim@example.com`. A fragment never reaches the server; the only\n * thing that reads it is the landing page's script, filling a sign-in\n * form so the reader sees their own address and types the password.\n * - `parameter`: an address that is not the workspace's own inside a query\n * or a longer fragment — `?email=victim@example.com`, a hash route's\n * `#/login?email=…`. Ordinary in a sign-up or a SaaS login link, so softer.\n */\nfunction prefilledAddressIn(\n target: LinkTarget,\n isOwnHost: (host: string) => boolean,\n): 'fragment' | 'parameter' | null {\n const fragment = target.fragment.trim()\n if (fragment && (EMAIL_ADDRESS.test(fragment) || EMAIL_ADDRESS.test(base64Text(fragment).trim()))) {\n return 'fragment'\n }\n for (const part of [target.query, target.fragment]) {\n // An address is short; a tracking token can be kilobytes of the\n // characters an address is made of, so only the head of one is read.\n if (!part.includes('@')) continue\n for (const match of part.slice(0, 4096).matchAll(EMAIL_ADDRESS_IN_TEXT)) {\n if (!isOwnHost(match[1].toLowerCase())) return 'parameter'\n }\n }\n return null\n}\n\nconst ADDRESS_HOST_PATTERN = /[a-z0-9._%+-]+@([a-z0-9-]+(?:\\.[a-z0-9-]+)+)/gi\n\n/** The host of every email address in the text — a reply-to, a `mailto:`. */\nfunction addressHostsIn(text: string): string[] {\n const hosts = new Set<string>()\n for (const match of decodeEntities(String(text ?? '')).matchAll(ADDRESS_HOST_PATTERN)) {\n hosts.add(match[1].toLowerCase().replace(/\\.+$/, ''))\n }\n return [...hosts]\n}\n\n/** Lowercased alphanumerics only, so \"Wells-Fargo Advisors\" contains `wellsfargo`. */\nfunction squash(text: string): string {\n return text.toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\n/** Is this brand the workspace's own, by name or by a domain it holds? */\nfunction isOwnBrand(\n brand: PhishingScreenBrand,\n ownNames: string,\n ownRegistrables: ReadonlySet<string>,\n): boolean {\n const labels = [brand.id, squash(brand.label), ...brand.hostTokens.map(squash)]\n if (labels.some((label) => label && ownNames.includes(label))) return true\n return [...ownRegistrables].some((registrable) => isOfficialDomain(brand, registrable))\n}\n\n/*\n * The same judgements, for the other surfaces that read content with this\n * screen's data (`hosted-page-screen.ts`). Exported under these names rather\n * than copied, so a page and an email can never disagree about what a\n * brand's own domain is or whose brand a name is.\n */\n\n/** `squash`: lowercased alphanumerics, the form own-name matching reads. */\nexport const squashScreenText = squash\n/** Is this brand the workspace's own, by name (squashed) or by a domain it holds? */\nexport const isWorkspaceOwnBrand = isOwnBrand\n/** Is this registrable domain one of any listed brand's own? */\nexport const isAnyOfficialBrandDomain = isAnyOfficialDomain\n/** Is this registrable domain a social, maps or review link merchants ordinarily carry? */\nexport function isCommonLinkDomain(registrable: string): boolean {\n return COMMON_LINK_DOMAINS.has(registrable)\n}\n\n/**\n * Screen one outbound message. See the module header for what holds and why.\n */\nexport function screenOutboundEmail(input: PhishingScreenInput): PhishingScreenVerdict {\n const signals: PhishingScreenSignal[] = []\n const ownNames = squash((input.ownNames ?? []).filter(Boolean).join(' '))\n const ownHosts = (input.ownDomains ?? [])\n .map((domain) => String(domain ?? '').trim().toLowerCase().replace(/\\.+$/, ''))\n .filter((domain) => domain.includes('.'))\n const ownRegistrables = new Set(ownHosts.map(registrableDomain))\n const isOwnHost = (host: string) =>\n ownHosts.some((own) => host === own || host.endsWith(`.${own}`))\n\n const parts = [input.subject, input.preheader, ...(input.bodies ?? [])].filter(\n (part): part is string => typeof part === 'string' && part.length > 0,\n )\n // Links are read from the raw copy, where an href lives; brands and lures\n // from what a reader sees, where a tag cannot split a word (AGL-3453).\n const copy = parts.join('\\n')\n const visibleCopy = parts.map(visibleTextOf).join('\\n')\n const replyTo = Array.isArray(input.replyTo)\n ? input.replyTo.join(' ')\n : String(input.replyTo ?? '')\n const linkHosts = linkHostsIn(copy)\n\n // 1. A lookalike host, anywhere a recipient could click, write back, or\n // read as the sender.\n const seenLookalike = new Set<string>()\n const fromAddress = String(input.fromAddress ?? '')\n for (const host of [...linkHosts, ...addressHostsIn(`${copy}\\n${replyTo}\\n${fromAddress}`)]) {\n if (seenLookalike.has(host)) continue\n const brand = lookalikeBrandForHost(host)\n if (brand && !isBrandsOwnDomain(brand, ownRegistrables)) {\n seenLookalike.add(host)\n signals.push({ code: 'lookalike-link', brand: brand.id, host })\n }\n }\n\n // 2. A brand in the sender's display name that is not the workspace's.\n const fromName = String(input.fromName ?? '').trim()\n if (fromName) {\n for (const brand of PHISHING_SCREEN_BRANDS) {\n if (brand.mention.test(fromName) && !isOwnBrand(brand, ownNames, ownRegistrables)) {\n signals.push({ code: 'brand-sender', brand: brand.id, fromName: fromName.slice(0, 120) })\n }\n }\n }\n\n // 3. Brand + lure + a link to somewhere that is nobody's we know.\n const isElsewhere = (host: string) => {\n if (isOwnHost(host)) return false\n const registrable = registrableDomain(host)\n return !isAnyOfficialDomain(registrable) && !COMMON_LINK_DOMAINS.has(registrable)\n }\n const lure = PHISHING_LURE_PATTERNS.map((pattern) => visibleCopy.match(pattern)?.[0])\n .find(Boolean)\n if (lure) {\n const foreign = linkHosts.find(isElsewhere)\n if (foreign) {\n const namedInCopy = `${visibleCopy}\\n${fromName}`\n for (const brand of PHISHING_SCREEN_BRANDS) {\n if (brand.mention.test(namedInCopy) && !isOwnBrand(brand, ownNames, ownRegistrables)) {\n signals.push({\n code: 'brand-lure-link',\n brand: brand.id,\n lure: lure.slice(0, 120),\n host: foreign,\n })\n break\n }\n }\n }\n }\n\n // 4. An account lure beside a link elsewhere that carries the reader's own\n // address, filled in for the sign-in form at the far end (AGL-3453).\n const accountLure = ACCOUNT_LURE_PATTERNS.map((pattern) => visibleCopy.match(pattern)?.[0]).find(Boolean)\n if (accountLure) {\n let prefill: { host: string; place: 'fragment' | 'parameter' } | null = null\n for (const target of linkTargetsIn(copy)) {\n if (!isElsewhere(target.host)) continue\n const place = prefilledAddressIn(target, isOwnHost)\n if (place && (!prefill || (place === 'fragment' && prefill.place !== 'fragment'))) {\n prefill = { host: target.host, place }\n }\n }\n if (prefill) {\n signals.push({\n code: 'recipient-prefill-link',\n host: prefill.host,\n lure: accountLure.slice(0, 120),\n place: prefill.place,\n })\n }\n }\n\n return { hold: signals.length > 0, signals }\n}\n\n/** The brand's label for a stored id, for the staff surface. */\nexport function phishingScreenBrandLabel(id: string): string {\n return PHISHING_SCREEN_BRANDS.find((brand) => brand.id === id)?.label ?? id\n}\n\n/** Web Risk's threat types, in the words staff read (AGL-3451). */\nconst LINK_THREAT_WORDS: Record<string, string> = {\n SOCIAL_ENGINEERING: 'phishing or social engineering',\n MALWARE: 'malware',\n UNWANTED_SOFTWARE: 'unwanted software',\n}\n\n/** \"phishing or social engineering and malware\", from Web Risk's threat types. */\nexport function describeLinkThreats(threats: readonly string[]): string {\n const words = [...new Set(threats)].map((threat) => LINK_THREAT_WORDS[threat] ?? threat.toLowerCase())\n if (!words.length) return 'unsafe'\n return words.length === 1 ? words[0] : `${words.slice(0, -1).join(', ')} and ${words[words.length - 1]}`\n}\n\n/** One line per signal, in words staff read on the review row. */\nexport function describePhishingScreenSignals(\n signals: readonly PhishingScreenSignal[],\n): string[] {\n return signals.map((signal) => {\n const brand = 'brand' in signal ? phishingScreenBrandLabel(signal.brand) : ''\n switch (signal.code) {\n case 'lookalike-link':\n return `Links to ${signal.host}, which wears the ${brand} name but is not ${brand}'s domain.`\n case 'brand-sender':\n return `Sends as \"${signal.fromName}\", naming ${brand}, which is not this workspace.`\n case 'brand-lure-link':\n return `Names ${brand}, asks the reader to act (\"${signal.lure}\"), and links to ${signal.host}.`\n case 'credential-field':\n return `Asks for a ${\n signal.field === 'card' ? 'card number' : signal.field === 'otp' ? 'one-time code' : 'password'\n } in its own field (\"${signal.label}\"), outside the platform's sign-in and checkout elements.`\n case 'brand-action-page':\n return `Names ${brand} beside a call to action (\"${signal.action}\"), and this workspace is not ${brand}.`\n case 'brand-lure-page':\n return `Names ${brand} on a page that asks visitors to act (\"${signal.lure}\") and links to ${signal.host}, and this workspace is not ${brand}.`\n case 'offsite-action-page':\n return `Its call to action (\"${signal.action}\") sends visitors off the site to ${signal.host}, on a page that reads \"${signal.lure}\".`\n case 'offsite-redirect':\n return `Redirects ${signal.source}, a path that reads \"${signal.lure}\", off the site to ${signal.host}.`\n case 'recipient-prefill-link':\n return `Links to ${signal.host} with the recipient's own address in the ${\n signal.place === 'fragment' ? 'fragment' : 'link'\n }, so a sign-in form there opens filled in, beside \"${signal.lure}\".`\n case 'web-risk-link':\n return `Links to ${signal.host}, which Google Web Risk lists as ${describeLinkThreats(signal.threats)}.`\n default:\n return 'Phishing signal.'\n }\n })\n}\n\n/*==========================================\n * RISK TIERS: who a signal holds for (AGL-3356, widened to every surface).\n *\n * The screen above finds signals; this decides which of them hold, the same\n * way on every surface that asks — an email at the send seam, a campaign\n * before it is claimed, a page at publish, a subdomain at creation.\n *\n * - STRONG: a lookalike host. A link to `poshmark.id63835663.shop` or\n * `paypa1.com` is a disguise whoever wears it and however old the\n * workspace is, so it holds for EVERY workspace, on every message and\n * page, transactional mail included. A merchant has no ordinary reason to\n * link to a host shaped like somebody else's brand.\n * - STRONG, too: account or password phrasing beside a link elsewhere whose\n * whole FRAGMENT is the reader's address (AGL-3453). A fragment never\n * reaches a server, so the address there is for the landing page's script\n * to fill a sign-in form with; a merchant's own reset mail links to its\n * own domain, and a SaaS login link puts the address in its query, which\n * is soft.\n * - SOFT: a brand in the sender name, the three-part lure, a brand's name\n * beside a sign-in or payment call to action on a page (in one element,\n * or anywhere on a page that carries a lure), a call to action or a\n * redirect that leaves the site beside account or document-share wording,\n * the reader's address in a query beside account phrasing.\n * Each is shaped like phishing but also like a clumsy legitimate message,\n * so they hold\n * only for a workspace in its first {@link OUTBOUND_REVIEW_YOUNG_DAYS}\n * days — the incident's window — and NEVER for mail the recipient's own\n * act made owed ({@link OutboundScreenPolicy.owed}).\n *\n * A credential-harvest page (a password, card or one-time-code field that\n * is not one of the platform's own sign-in or checkout elements) is STRONG:\n * see `hosted-page-screen.ts`. So is a link to a host Google Web Risk lists\n * (`web-risk-link`, `link-reputation.ts`): it holds for every workspace, and\n * an account-subdomain host does not soften it, because the listing names\n * that host itself.\n *=========================================*/\n\n/** A workspace younger than this many days has the soft rules applied. */\nexport const OUTBOUND_REVIEW_YOUNG_DAYS = 14\n\n/** Which tier a signal belongs to. */\nexport type PhishingSignalTier = 'strong' | 'soft'\n\n/** The signal codes that hold for every workspace. */\nexport const STRONG_PHISHING_SIGNAL_CODES: ReadonlySet<string> = new Set([\n 'lookalike-link',\n 'credential-field',\n 'web-risk-link',\n])\n\n/**\n * Hosts that give each customer an account subdomain named after the\n * customer: `acme.zendesk.com` is Acme's own help desk. A brand's name there is usually the brand itself, so a\n * lookalike on one of these is SOFT — held for a young workspace, never a\n * takedown of an established one's page or mail. A lookalike on any other\n * host (`poshmark.id63835663.shop`) stays STRONG.\n */\nexport const ACCOUNT_SUBDOMAIN_HOSTS: ReadonlySet<string> = new Set([\n 'vimeo.com', 'vimeocdn.com', 'zendesk.com', 'freshdesk.com',\n 'helpscoutdocs.com', 'intercom.help', 'statuspage.io', 'atlassian.net', 'myshopify.com',\n 'squarespace.com', 'wixsite.com', 'webflow.io', 'hubspotpagebuilder.com', 'substack.com',\n 'typeform.com', 'calendly.com', 'gitbook.io', 'readme.io', 'notion.site', 'github.io',\n 'cloudfront.net', 'kajabi.com', 'thinkific.com', 'teachable.com', 'mailchimpsites.com',\n])\n\nexport function phishingSignalTier(signal: {\n code: string\n host?: string\n place?: string\n}): PhishingSignalTier {\n if (signal?.code === 'recipient-prefill-link') {\n return signal.place === 'fragment' ? 'strong' : 'soft'\n }\n if (!STRONG_PHISHING_SIGNAL_CODES.has(signal?.code)) return 'soft'\n if (\n signal.code === 'lookalike-link' &&\n typeof signal.host === 'string' &&\n ACCOUNT_SUBDOMAIN_HOSTS.has(registrableDomain(signal.host))\n ) {\n return 'soft'\n }\n return 'strong'\n}\n\n/** Is a workspace of this age (days, `null` = unreadable) screened by the soft rules? */\nexport function isYoungWorkspaceAge(ageDays: number | null | undefined): boolean {\n return typeof ageDays === 'number' && Number.isFinite(ageDays) && ageDays < OUTBOUND_REVIEW_YOUNG_DAYS\n}\n\nexport interface OutboundScreenPolicy {\n /**\n * The workspace's age in days, or `null` when its creation date cannot be\n * read — an org that predates the field, which is an EXISTING customer and\n * is not young.\n */\n ageDays: number | null\n /**\n * The recipient's own act made this message owed: a receipt for their\n * order, a confirmation of their booking, a reset of their password. The\n * soft rules never hold it. The lookalike rule still does — a receipt that\n * links to a Poshmark lookalike is the disguise, not the receipt.\n */\n owed?: boolean\n}\n\n/** The signals that HOLD under the tiers, for this workspace and message. */\nexport function signalsThatHold<T extends { code: string; host?: string }>(\n signals: readonly T[],\n policy: OutboundScreenPolicy,\n): T[] {\n const soft = isYoungWorkspaceAge(policy.ageDays) && !policy.owed\n return signals.filter((signal) => phishingSignalTier(signal) === 'strong' || soft)\n}\n\n/**\n * The same brand, lookalike and tier logic applied to a HOST NAME a workspace\n * asks for — a subdomain on the tenant apex, or a custom domain it attaches.\n *\n * Words a brand's impersonator hyphen-joins to its name. A subdomain that\n * joins a brand's word to one of these (`booking-review`, `apple-support`,\n * `amazon-account`) is the incident's shape even where the brand's word is\n * an ordinary one — which the lookalike rule alone deliberately lets pass,\n * so a salon can be `tanyas-booking` and a bakery `apple-pie-co`.\n */\nexport const BRAND_IMPERSONATION_WORDS: ReadonlySet<string> = new Set([\n 'account', 'accounts', 'auth', 'billing', 'help', 'helpdesk', 'id', 'login',\n 'logon', 'order', 'orders', 'pay', 'payment', 'payments', 'refund', 'resolution',\n 'review', 'reviews', 'secure', 'security', 'seller', 'service', 'signin',\n 'support', 'update', 'verify', 'verification', 'wallet',\n])\n\n/**\n * The brand a requested subdomain label wears, or null.\n *\n * Refused for EVERY workspace, at creation and at rename — the tier is\n * strong, because nothing is lost by asking a real bakery to pick\n * `apple-pie-co` instead of `apple-support`, and a brand's name on our apex\n * is a disguise that outlives every later screen. Two shapes:\n *\n * 1. the label is a lookalike host label ({@link lookalikeBrandForHost} on\n * `<label>.<apex>`): `poshmark`, `paypal-secure`, `paypa1`, `appleid`;\n * 2. a brand's word hyphen-joined to an impersonation word\n * ({@link BRAND_IMPERSONATION_WORDS}): `booking-review`, `apple-support`.\n */\nexport function brandForSubdomainLabel(\n label: string,\n apex = 'example.invalid',\n): PhishingScreenBrand | null {\n const normalized = String(label ?? '').trim().toLowerCase()\n if (!normalized) return null\n const byHost = lookalikeBrandForHost(`${normalized}.${apex}`)\n if (byHost) return byHost\n const parts = foldLeet(normalized).split('-').filter(Boolean)\n if (parts.length < 2 || !parts.some((part) => BRAND_IMPERSONATION_WORDS.has(part))) {\n return null\n }\n for (const brand of PHISHING_SCREEN_BRANDS) {\n const words = [brand.id, ...brand.hostTokens].filter((word) => !word.includes('-'))\n if (parts.some((part) => words.includes(part))) return brand\n }\n return null\n}\n\n/**\n * The platform's own entry in {@link PHISHING_SCREEN_BRANDS} (AGL-3365). A\n * workspace owns every other brand by carrying its name or domain; the\n * platform's is owned only by the platform's staff, because a workspace NAMED\n * for the platform is the cheapest disguise there is.\n */\nexport const PLATFORM_PHISHING_BRAND_ID = 'aglyn'\n\n/** The platform's brand entry. */\nexport function platformPhishingBrand(): PhishingScreenBrand {\n return PHISHING_SCREEN_BRANDS.find((brand) => brand.id === PLATFORM_PHISHING_BRAND_ID) as PhishingScreenBrand\n}\n\n/**\n * Words that make a name claim to SPEAK FOR a brand rather than mention it:\n * \"PayPal Support\", \"Aglyn Official\", \"Apple ID Security Team\".\n */\nconst OFFICIAL_CLAIM_PATTERN =\n /\\b(?:official|staff|team|verified|certified|support|helpdesk|admin|administrator|security|billing|trust|safety|compliance|core|headquarters|hq)\\b/i\n\n/**\n * The brand a display NAME claims to speak for (AGL-3365), or null.\n *\n * For names a stranger reads as an identity — a marketplace publisher, a\n * listing's title — rather than copy. A name that merely mentions a brand\n * (\"Sync for PayPal\", \"Bookings for Airbnb hosts\") passes: that is how an\n * integration is named. A name that pairs the brand with a claim of\n * officialness (\"PayPal Support\", \"Aglyn Official Plugins\") is the disguise.\n */\nexport function brandClaimedByName(name: string): PhishingScreenBrand | null {\n const text = String(name ?? '')\n if (!text.trim() || !OFFICIAL_CLAIM_PATTERN.test(text)) return null\n return PHISHING_SCREEN_BRANDS.find((brand) => brand.mention.test(text)) ?? null\n}\n"],"names":["PHISHING_SCREEN_BRANDS","id","label","mention","hostTokens","officialDomains","countryDomains","wordToken","hostedDomains","ACCOUNT_LURE_PATTERNS","DOCUMENT_SHARE_LURE_PATTERNS","SALE_AND_PARCEL_LURE_PATTERNS","PHISHING_LURE_PATTERNS","COMMON_LINK_DOMAINS","Set","TWO_LABEL_SUFFIXES","registrableDomain","host","labels","String","toLowerCase","replace","split","filter","Boolean","length","join","lastTwo","slice","has","splitRegistrable","registrable","dot","indexOf","suffix","isOfficialDomain","brand","includes","base","test","isBrandsOwnDomain","ownRegistrables","some","isAnyOfficialDomain","foldLeet","labelNamesBrand","token","candidate","parts","tokenParts","at","every","part","offset","MEDIA_EMBED_HOSTS","lookalikeBrandForHost","normalized","primary","startsWith","decodeEntities","text","_","hex","safeCodePoint","parseInt","dec","value","Number","isFinite","fromCodePoint","NAMED_ENTITIES","nbsp","ensp","emsp","thinsp","lt","gt","quot","apos","shy","zwnj","zwj","UNSEEN_ELEMENT_OPEN","BREAKING_TAG_NAME","INVISIBLE_CHARACTERS","stripMarkup","html","breaks","open","end","close","Math","min","dropUnseenElements","lower","RegExp","source","kept","found","Map","find","needle","from","known","get","undefined","position","set","match","exec","tagEnd","lastIndex","index","name","body","visibleTextOf","read","decodeVisibleEntities","trim","joined","broken","entity","URL_PATTERN","linkHostsIn","hosts","rest","lastIndexOf","disguise","add","linkTargetsIn","targets","hash","beforeHash","question","push","query","decodeUrlPart","fragment","decodeURIComponent","EMAIL_ADDRESS","EMAIL_ADDRESS_IN_TEXT","BASE64_TEXT","base64Text","decode","globalThis","atob","prefilledAddressIn","target","isOwnHost","matchAll","ADDRESS_HOST_PATTERN","addressHostsIn","squash","isOwnBrand","ownNames","map","squashScreenText","isWorkspaceOwnBrand","isAnyOfficialBrandDomain","isCommonLinkDomain","screenOutboundEmail","input","signals","ownHosts","ownDomains","domain","own","endsWith","subject","preheader","bodies","copy","visibleCopy","replyTo","Array","isArray","linkHosts","seenLookalike","fromAddress","code","fromName","isElsewhere","lure","pattern","foreign","namedInCopy","accountLure","prefill","place","hold","phishingScreenBrandLabel","LINK_THREAT_WORDS","SOCIAL_ENGINEERING","MALWARE","UNWANTED_SOFTWARE","describeLinkThreats","threats","words","threat","describePhishingScreenSignals","signal","field","action","OUTBOUND_REVIEW_YOUNG_DAYS","STRONG_PHISHING_SIGNAL_CODES","ACCOUNT_SUBDOMAIN_HOSTS","phishingSignalTier","isYoungWorkspaceAge","ageDays","signalsThatHold","policy","soft","owed","BRAND_IMPERSONATION_WORDS","brandForSubdomainLabel","apex","byHost","word","PLATFORM_PHISHING_BRAND_ID","platformPhishingBrand","OFFICIAL_CLAIM_PATTERN","brandClaimedByName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA2D2C,GAE3C,qCAAqC,GA2CrC,OAAO,MAAMA,yBAAyD;IACpE;QACEC,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;SAAW;QACxBC,iBAAiB;YAAC;YAAgB;SAAU;IAC9C;IACA;QACEJ,IAAI;QACJC,OAAO;QACP,qEAAqE;QACrEC,SAAS;QACTC,YAAY;YAAC;YAAc;SAAc;QACzCC,iBAAiB;YAAC;YAAe;SAAc;IACjD;IACA;QACEJ,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;SAAS;QACtBC,iBAAiB;YAAC;YAAc;YAAW;SAAe;QAC1DC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;SAAS;QACtBC,iBAAiB;YAAC;YAAc;YAAa;SAAoB;QACjEC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;YAAU;SAAO;QAC9BG,WAAW;QACXF,iBAAiB;YACf;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACP,yEAAyE;QACzEC,SAAS;QACTC,YAAY;YAAC;YAAS;YAAW;YAAU;SAAS;QACpDG,WAAW;QACXF,iBAAiB;YAAC;YAAa;YAAc;YAAY;YAAc;YAAU;SAAe;QAChGC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACP,sEAAsE;QACtE,cAAc;QACdC,SACE;QACFC,YAAY;YACV;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,iBAAiB;YACf;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACEJ,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;SAAW;QACxBC,iBAAiB;YAAC;YAAgB;SAAe;IACnD;IACA;QACEJ,IAAI;QACJC,OAAO;QACP,sEAAsE;QACtE,sDAAsD;QACtDC,SAAS;QACT,iEAAiE;QACjE,sEAAsE;QACtE,qEAAqE;QACrE,0CAA0C;QAC1CC,YAAY;YACV;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,iBAAiB;YACf;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACP,qEAAqE;QACrE,sCAAsC;QACtCC,SACE;QACFC,YAAY;YAAC;YAAS;YAAW;YAAa;YAAgB;SAAW;QACzEG,WAAW;QACXF,iBAAiB;YACf;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACEJ,IAAI;QACJC,OAAO;QACP,0DAA0D;QAC1DC,SAAS;QACTC,YAAY;YAAC;SAAU;QACvBC,iBAAiB;YAAC;YAAe;YAAS;YAA0B;YAAqB;SAAgB;IAC3G;IACA;QACE,wEAAwE;QACxE,uEAAuE;QACvEJ,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;Y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GC,GACD,MAAME,yBACJ;AAEF;;;;;;;;CAQC,GACD,OAAO,SAASC,mBAAmB5G,IAAY;QAGtCjH;IAFP,MAAM4D,OAAOzC,OAAO8F,eAAAA,OAAQ;IAC5B,IAAI,CAACrD,KAAK0D,IAAI,MAAM,CAACsG,uBAAuBrL,IAAI,CAACqB,OAAO,OAAO;IAC/D,QAAO5D,+BAAAA,uBAAuBoG,IAAI,CAAC,CAAChE,QAAUA,MAAMjC,OAAO,CAACoC,IAAI,CAACqB,kBAA1D5D,+BAAoE;AAC7E"}
1
+ {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/outbound-phishing-screen.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 OUTBOUND PHISHING SCREEN (AGL-3356).\n *\n * A fraud actor signed up, paid with a card that never met 3-D Secure, and\n * used a workspace to send two kinds of mail: a campaign of Booking.com-style\n * \"guest feedback regarding your property\" lures to hotels, and a workflow\n * that mailed \"Poshmark Order — one of the items from your Seller Account has\n * finally sold\", linking to `poshmark.id63835663.shop`.\n *\n * This module answers one question about a message a YOUNG workspace is\n * about to send: does its content carry a STRONG phishing signal? The caller\n * decides who is young and what happens to a positive answer — the answer is\n * a hold for staff review, never a drop.\n *\n * ## Conservative by construction\n *\n * A false positive costs a real merchant's first campaign a wait for a\n * human; a miss costs strangers their bank logins. Both are real, so only\n * four shapes hold, and each is one a legitimate merchant essentially never\n * produces:\n *\n * 1. **A lookalike link** — a link or reply address whose host carries a\n * brand's name without being the brand's own domain: the brand as a label\n * of an unrelated registrable domain (`poshmark.id63835663.shop`), hyphen-\n * joined to one (`paypal-secure.com`, `secure-paypal.net`), the brand's\n * real domain embedded in a longer host (`booking.com.guest-review.top`),\n * or leetspeak for it (`paypa1.com`). Holds on its own.\n * 2. **A brand in the sender's display name** that is not the workspace's\n * own name — mail that says it is FROM PayPal.\n * 3. **The three-part lure**: a brand named in the copy, AND credential or\n * account-action phrasing (\"verify your account\", \"has finally sold\",\n * \"feedback regarding your property\"), AND a link to a domain that is\n * neither the brand's, nor the workspace's, nor a common social or maps\n * link. Any two of the three are ordinary marketing — \"our book is on\n * Amazon\", \"sign in to your account\", a link to the shop — and pass.\n * 4. **A prefilled sign-in** (AGL-3453): account or password phrasing\n * (\"your password expires today\") beside a link to such a domain that\n * carries the reader's own address, so the harvester's form opens with\n * it filled in: `…/ss/c/…#victim@example.com`.\n *\n * Mentioning a brand, alone, never holds. Brands and lures are read from\n * what the reader SEES ({@link visibleTextOf}), never from the raw HTML, in\n * which a kit splits every letter with a tag; links are read from the raw\n * HTML, where an href lives.\n *\n * ## The brand list is small on purpose\n *\n * The brands phishing kits most often wear, plus the two in the incident, and\n * the file-share and mail-security names a document-share lure wears — a\n * \"Secure Document Access Portal\" under Proofpoint's or SharePoint's name\n * whose one button leaves for the kit (AGL-3447). A brand is added when it\n * has been seen impersonated, not because it is big: every entry is a set of\n * words that can now hold somebody's newsletter.\n * Each carries its REAL domains, so a link to the brand itself is never\n * suspicious, and host tokens chosen so a common word (`booking`, `apple`,\n * `outlook`, `box`, `adobe`) does not match an unrelated host by itself.\n *\n * Pure: no DNS, no store, no clock. Everything the caller knows about the\n * workspace arrives as input.\n *=========================================*/\n\n/** One brand the screen recognizes. */\nexport interface PhishingScreenBrand {\n /** Stable id, as stored on a hold. */\n id: string\n /** How staff read it. */\n label: string\n /** Copy that names the brand — subject, body, sender. Case-insensitive. */\n mention: RegExp\n /**\n * Host labels that name the brand. Matched against each dot-separated\n * label of a link's host, whole or hyphen-joined, after leetspeak is\n * folded — never as a bare substring, which is how `amazonaws` or\n * `bookingengine` would read as a brand.\n */\n hostTokens: readonly string[]\n /**\n * Registrable domains the brand genuinely links from. The FIRST is its\n * primary domain, the one a kit embeds in a longer host.\n */\n officialDomains: readonly string[]\n /**\n * The brand's name is an ordinary word (`apple`, `amazon`), so a host\n * label names the brand only when it IS the word — `apple.example.top` —\n * and never hyphen-joined or leet-folded, which `apple-orchard-farm.com`\n * would otherwise be.\n */\n wordToken?: boolean\n /**\n * Whether `<brand>.<country code>` (and `<brand>.co.<cc>`) is the brand's\n * too — true for the marketplaces that run a site per country.\n */\n countryDomains?: boolean\n /**\n * Registrable domains the brand runs but where OTHER people's content lives —\n * the platform's own tenant apex, where every site is `<name>.<apex>`. A\n * host there never wears the brand as a disguise, so the lookalike rule\n * skips it; but it is not the brand's own domain either, so a link to a\n * neighbor's site still counts as \"somewhere else\" to the lure rules, and a\n * workspace hosted there does not own the brand by being hosted there.\n */\n hostedDomains?: readonly string[]\n}\n\nexport const PHISHING_SCREEN_BRANDS: readonly PhishingScreenBrand[] = [\n {\n id: 'poshmark',\n label: 'Poshmark',\n mention: /\\bposhmark\\b/i,\n hostTokens: ['poshmark'],\n officialDomains: ['poshmark.com', 'posh.mk'],\n },\n {\n id: 'booking',\n label: 'Booking.com',\n // Never the bare word: \"booking\" is every hotel's and every salon's.\n mention: /\\bbooking\\.com\\b/i,\n hostTokens: ['bookingcom', 'booking-com'],\n officialDomains: ['booking.com', 'bstatic.com'],\n },\n {\n id: 'airbnb',\n label: 'Airbnb',\n mention: /\\bairbnb\\b/i,\n hostTokens: ['airbnb'],\n officialDomains: ['airbnb.com', 'abnb.me', 'muscache.com'],\n countryDomains: true,\n },\n {\n id: 'paypal',\n label: 'PayPal',\n mention: /\\bpay\\s?pal\\b/i,\n hostTokens: ['paypal'],\n officialDomains: ['paypal.com', 'paypal.me', 'paypalobjects.com'],\n countryDomains: true,\n },\n {\n id: 'amazon',\n label: 'Amazon',\n mention: /\\bamazon\\b/i,\n hostTokens: ['amazon', 'amzn'],\n wordToken: true,\n officialDomains: [\n 'amazon.com',\n 'amzn.to',\n 'amzn.com',\n 'amazonaws.com',\n 'media-amazon.com',\n 'ssl-images-amazon.com',\n ],\n countryDomains: true,\n },\n {\n id: 'apple',\n label: 'Apple',\n // The fruit is on every bakery's menu; the account is what gets phished.\n mention: /\\bapple\\s?(?:id|support|account)\\b|\\bicloud\\b|\\bitunes\\b/i,\n hostTokens: ['apple', 'appleid', 'icloud', 'itunes'],\n wordToken: true,\n officialDomains: ['apple.com', 'icloud.com', 'apple.co', 'itunes.com', 'me.com', 'mzstatic.com'],\n countryDomains: true,\n },\n {\n id: 'microsoft',\n label: 'Microsoft',\n // Outlook only as the product — \"our 2026 outlook\" is every advisor's\n // newsletter.\n mention:\n /\\bmicrosoft\\b|\\b(?:office|ms|m)\\s?365\\b|\\bonedrive\\b|\\bsharepoint\\b|\\boutlook(?:\\.com|\\s+(?:web\\s+app|web\\s+access|online|account|365))\\b/i,\n hostTokens: [\n 'microsoft',\n 'microsoft365',\n 'office365',\n 'office-365',\n 'outlook365',\n 'onedrive',\n 'sharepoint',\n 'microsoftonline',\n 'msonline',\n ],\n officialDomains: [\n 'microsoft.com',\n 'office.com',\n 'office365.com',\n 'microsoft365.com',\n 'live.com',\n 'outlook.com',\n 'microsoftonline.com',\n 'sharepoint.com',\n 'sharepointonline.com',\n 'onedrive.com',\n '1drv.ms',\n 'aka.ms',\n ],\n },\n {\n id: 'docusign',\n label: 'DocuSign',\n mention: /\\bdocu\\s?sign\\b/i,\n hostTokens: ['docusign'],\n officialDomains: ['docusign.com', 'docusign.net'],\n },\n {\n id: 'google',\n label: 'Google',\n // The account and the files, never the bare name: \"find us on Google\"\n // and \"Google Maps\" are on every shop's contact page.\n mention: /\\bgoogle\\s?(?:drive|docs?|sheets|slides|workspace|account)\\b|\\bgmail\\b|\\bg\\s?suite\\b/i,\n // The products and the account, never the bare name: Google runs\n // hyphenated hosts of its own that a page embeds, and a bare `google`\n // token would read each as its lookalike. `docs.google.com.<kit>` is\n // still read, by the primary-domain rule.\n hostTokens: [\n 'gmail',\n 'gsuite',\n 'googledocs',\n 'googledrive',\n 'google-docs',\n 'google-drive',\n 'google-workspace',\n 'google-account',\n 'google-login',\n 'google-mail',\n 'docs-google',\n 'drive-google',\n ],\n officialDomains: [\n 'google.com',\n 'goo.gl',\n 'g.co',\n 'g.page',\n 'forms.gle',\n 'gmail.com',\n 'googleapis.com',\n 'gstatic.com',\n 'googleusercontent.com',\n 'withgoogle.com',\n ],\n countryDomains: true,\n },\n {\n id: 'adobe',\n label: 'Adobe',\n // \"Adobe\" alone is a house, a grill and an inn across the Southwest;\n // the products are what a lure names.\n mention:\n /\\badobe\\s?(?:acrobat|sign|id|account|document\\s?cloud|reader|pdf|creative\\s?cloud)\\b|\\bacrobat\\s?(?:reader|sign|pro)\\b|\\bechosign\\b/i,\n hostTokens: ['adobe', 'adobeid', 'adobesign', 'adobeacrobat', 'echosign'],\n wordToken: true,\n officialDomains: [\n 'adobe.com',\n 'adobe.io',\n 'adobe.ly',\n 'adobelogin.com',\n 'adobesign.com',\n 'echosign.com',\n 'acrobat.com',\n 'typekit.net',\n 'adobedtm.com',\n ],\n },\n {\n id: 'dropbox',\n label: 'Dropbox',\n // One word only: a \"drop box\" is by every library's door.\n mention: /\\bdropbox\\b/i,\n hostTokens: ['dropbox'],\n officialDomains: ['dropbox.com', 'db.tt', 'dropboxusercontent.com', 'dropboxstatic.com', 'hellosign.com'],\n },\n {\n // Never the bare word, as an id either — `brandForSubdomainLabel` reads\n // ids as words, and \"box\" is every lunch box's and subscription box's.\n id: 'boxcom',\n label: 'Box',\n mention: /\\bbox\\.com\\b|\\bbox\\s+drive\\b/i,\n hostTokens: ['boxcom', 'box-com'],\n officialDomains: ['box.com', 'box.net', 'boxcdn.net', 'boxcloud.com'],\n },\n {\n id: 'wetransfer',\n label: 'WeTransfer',\n // One word only: \"we transfer\" is a moving company's sentence.\n mention: /\\bwetransfer\\b/i,\n hostTokens: ['wetransfer'],\n officialDomains: ['wetransfer.com', 'we.tl'],\n },\n {\n id: 'sharefile',\n label: 'ShareFile',\n mention: /\\bshare\\s?file\\b/i,\n hostTokens: ['sharefile'],\n officialDomains: ['sharefile.com', 'sharefile.eu', 'citrix.com'],\n },\n {\n // A secure-mail gateway's name is what makes a document lure read as\n // safe: \"Proofpoint Encryption for your sensitive documents\".\n id: 'proofpoint',\n label: 'Proofpoint',\n // One word only: a \"proof point\" is every pitch deck's.\n mention: /\\bproofpoint\\b/i,\n hostTokens: ['proofpoint'],\n officialDomains: ['proofpoint.com', 'urldefense.com', 'pphosted.com', 'ppe-hosted.com'],\n },\n {\n id: 'mimecast',\n label: 'Mimecast',\n mention: /\\bmimecast\\b/i,\n hostTokens: ['mimecast'],\n officialDomains: ['mimecast.com', 'mimecastprotect.com'],\n },\n {\n id: 'netflix',\n label: 'Netflix',\n mention: /\\bnetflix\\b/i,\n hostTokens: ['netflix'],\n officialDomains: ['netflix.com', 'nflxext.com', 'nflximg.net'],\n },\n {\n id: 'wellsfargo',\n label: 'Wells Fargo',\n mention: /\\bwells\\s?fargo\\b/i,\n hostTokens: ['wellsfargo', 'wells-fargo'],\n officialDomains: ['wellsfargo.com'],\n },\n {\n id: 'bankofamerica',\n label: 'Bank of America',\n mention: /\\bbank\\s+of\\s+america\\b/i,\n hostTokens: ['bankofamerica', 'bofa'],\n officialDomains: ['bankofamerica.com', 'bofa.com'],\n },\n {\n id: 'coinbase',\n label: 'Coinbase',\n mention: /\\bcoinbase\\b/i,\n hostTokens: ['coinbase'],\n officialDomains: ['coinbase.com'],\n },\n {\n id: 'usps',\n label: 'USPS',\n mention: /\\busps\\b/i,\n hostTokens: ['usps'],\n officialDomains: ['usps.com'],\n },\n {\n id: 'fedex',\n label: 'FedEx',\n mention: /\\bfed\\s?ex\\b/i,\n hostTokens: ['fedex'],\n officialDomains: ['fedex.com'],\n },\n {\n id: 'dhl',\n label: 'DHL',\n mention: /\\bdhl\\b/i,\n hostTokens: ['dhl'],\n officialDomains: ['dhl.com'],\n countryDomains: true,\n },\n {\n // The platform itself (AGL-3365). A marketplace listing, a page or an\n // email that wears the platform's name — \"Aglyn Support\", a link to\n // `aglyn-billing.com`, \"official Aglyn plugin\" — is the one impersonation\n // every customer is primed to trust. The workspace named for it (the\n // platform's own org) owns it by name, as any brand's own workspace does.\n id: 'aglyn',\n label: 'Aglyn',\n mention: /\\baglyn\\b/i,\n hostTokens: ['aglyn'],\n officialDomains: ['aglyn.com', 'aglyn.io', 'aglyn.dev'],\n hostedDomains: ['aglyn.app'],\n },\n]\n\n/**\n * Account and credential phrasing: the lure that asks the reader to DO\n * something with an account — verify it, confirm it, sign in to it.\n */\nexport const ACCOUNT_LURE_PATTERNS: readonly RegExp[] = [\n /\\bverify\\s+your\\s+(?:account|identity|information|details|payment|email)\\b/i,\n /\\bconfirm\\s+your\\s+(?:account|identity|details|payment|password|billing|information)\\b/i,\n /\\b(?:account|payment|card)\\s+(?:has\\s+been\\s+|is\\s+|was\\s+|will\\s+be\\s+)?(?:suspended|locked|limited|restricted|disabled|deactivated|terminated|on\\s+hold)\\b/i,\n /\\bunusual\\s+(?:sign[-\\s]?in|login|activity)\\b/i,\n /\\bupdate\\s+your\\s+(?:payment|billing|card|account)\\s*(?:details|information|method)?\\b/i,\n /\\b(?:sign|log)\\s?in\\s+to\\s+(?:your|view|confirm|claim|release)\\b/i,\n // \"Password Expired\", \"your password expires today\", \"will expire\".\n /\\bpassword\\s+(?:has\\s+|will\\s+)?expire/i,\n /\\bkeep\\s+(?:your|my|the)\\s+(?:current\\s+|active\\s+|existing\\s+|same\\s+)?password\\b/i,\n /\\bchange\\s+(?:your\\s+)?password\\s+settings?\\b/i,\n /\\bmailbox\\s+(?:storage\\s+|quota\\s+)?(?:is\\s+)?(?:almost\\s+|nearly\\s+)?(?:full|exceeded)\\b/i,\n /\\bsecurity\\s+alert\\b/i,\n]\n\n/**\n * Document-share phrasing (AGL-3447): the lure that says a file is waiting\n * behind a secure door — \"Secure Document Access Portal\", \"Continue to\n * Document\", \"shared a file with you\", \"encrypted message\". The credential\n * harvest is on the far side of the button, so these are the words the page\n * or the mail itself carries.\n */\nexport const DOCUMENT_SHARE_LURE_PATTERNS: readonly RegExp[] = [\n /\\b(?:document|invoice|agreement)s?\\s+(?:is\\s+|are\\s+)?(?:ready|waiting|pending)\\s+(?:for\\s+)?(?:your\\s+)?(?:review|signature|to\\s+sign)\\b/i,\n /\\b(?:view|access|open)\\s+(?:the\\s+|your\\s+)?secure\\s+(?:file|document|message)s?\\b/i,\n /\\bsecure\\s+(?:file|document|message)s?\\b/i,\n /\\bdocument\\s+access\\b/i,\n /\\baccess\\s+portal\\b/i,\n /\\b(?:continue|proceed)\\s+to\\s+(?:the\\s+|your\\s+)?(?:document|file)s?\\b/i,\n /\\bshared\\s+(?:a|an|the)\\s+(?:file|document|folder)\\s+with\\s+you\\b/i,\n /\\b(?:file|document|folder)s?\\s+(?:has\\s+been|have\\s+been|was|were)\\s+shared\\s+with\\s+you\\b/i,\n /\\bencrypted\\s+(?:message|document|file|email)s?\\b/i,\n]\n\n/**\n * Marketplace, booking and parcel phrasing: the lure that says a sale, a\n * guest or a delivery needs the reader. The incident's Poshmark and\n * Booking.com mail.\n */\nconst SALE_AND_PARCEL_LURE_PATTERNS: readonly RegExp[] = [\n /\\b(?:has|have)\\s+(?:finally\\s+)?sold\\b/i,\n /\\bseller\\s+account\\b/i,\n /\\b(?:guest|customer)\\s+(?:complaint|review|feedback)\\b/i,\n /\\bfeedback\\s+regarding\\s+your\\s+(?:property|listing|stay|booking|reservation)\\b/i,\n /\\bclaim\\s+your\\s+(?:refund|reward|prize|package|payment|funds)\\b/i,\n /\\b(?:delivery|shipment)\\s+(?:failed|attempt|suspended|on\\s+hold)\\b/i,\n /\\b(?:package|parcel)\\s+(?:is\\s+)?(?:on\\s+hold|held|awaiting|undeliverable)\\b/i,\n]\n\n/**\n * Every lure — the half of the three-part lure that asks the reader to act.\n * Only ever counted beside a brand AND a foreign link; alone, several of\n * these are ordinary transactional copy.\n */\nexport const PHISHING_LURE_PATTERNS: readonly RegExp[] = [\n ...ACCOUNT_LURE_PATTERNS,\n ...DOCUMENT_SHARE_LURE_PATTERNS,\n ...SALE_AND_PARCEL_LURE_PATTERNS,\n]\n\n/**\n * Link targets a merchant's mail ordinarily carries that are not theirs:\n * social profiles, maps, review sites, video. Counted as neither foreign nor\n * suspicious in the three-part lure, so \"leave us a review on Google\" with a\n * brand named elsewhere does not become a hold. Never consulted by the\n * lookalike check, which holds on the host's own shape.\n */\nconst COMMON_LINK_DOMAINS: ReadonlySet<string> = new Set([\n 'facebook.com',\n 'fb.com',\n 'instagram.com',\n 'x.com',\n 'twitter.com',\n 'linkedin.com',\n 'youtube.com',\n 'youtu.be',\n 'tiktok.com',\n 'pinterest.com',\n 'google.com',\n 'goo.gl',\n 'g.page',\n 'yelp.com',\n 'tripadvisor.com',\n 'wa.me',\n 'whatsapp.com',\n])\n\n/**\n * Two-label public suffixes, so `evil.co.uk` registers as `evil.co.uk` and\n * not as `co.uk`. Deliberately a short list of the ones mail actually\n * arrives from rather than the whole public suffix list: a suffix missing\n * here makes the registrable domain one label too short, which can only\n * widen what counts as \"the same domain\" for a link — never invent a brand\n * label that is not in the host.\n */\nconst TWO_LABEL_SUFFIXES: ReadonlySet<string> = new Set([\n 'co.uk', 'org.uk', 'ac.uk', 'gov.uk', 'me.uk',\n 'com.au', 'net.au', 'org.au',\n 'co.nz', 'co.jp', 'co.kr', 'co.in', 'co.za', 'co.il', 'co.id', 'co.th',\n 'com.br', 'com.mx', 'com.ar', 'com.tr', 'com.cn', 'com.hk', 'com.sg',\n 'com.tw', 'com.my', 'com.ph', 'com.co', 'com.pe', 'com.sa', 'com.eg',\n])\n\n/** A signal the screen found. */\nexport type PhishingScreenSignal =\n | { code: 'lookalike-link'; brand: string; host: string }\n | { code: 'brand-sender'; brand: string; fromName: string }\n | { code: 'brand-lure-link'; brand: string; lure: string; host: string }\n /**\n * A published page asks for a password, a card number or a one-time code\n * in a field that is not one of the platform's own sign-in or checkout\n * elements (`hosted-page-screen.ts`). Strong.\n */\n | { code: 'credential-field'; field: 'password' | 'card' | 'otp'; label: string }\n /**\n * A published page names a brand that is not the workspace's beside a\n * sign-in, verify or payment call to action (`hosted-page-screen.ts`).\n * Soft.\n */\n | { code: 'brand-action-page'; brand: string; action: string }\n /**\n * The same, read over the page as a WHOLE (AGL-3447): a brand that is not\n * the workspace's anywhere on a page that carries an account or\n * document-share lure anywhere, or whose call to action leaves the site\n * worded as one, and that links away (`hosted-page-screen.ts`). Soft.\n */\n | { code: 'brand-lure-page'; brand: string; lure: string; host: string }\n /**\n * A published page's call to action — its only one, or one worded as an\n * account or document action — sends visitors to a host that is not the\n * site's, a listed brand's or a common link, on a page that carries an\n * account or document-share lure (`hosted-page-screen.ts`, AGL-3447). No\n * brand needed. Soft.\n */\n | { code: 'offsite-action-page'; action: string; lure: string; host: string }\n /**\n * A site redirect whose path reads as an account or document-share lure\n * sends visitors to such a host (`screenSiteRedirect`, AGL-3447). Soft.\n */\n | { code: 'offsite-redirect'; source: string; lure: string; host: string }\n /**\n * Account or password phrasing beside a link elsewhere that carries the\n * reader's own address (AGL-3453). STRONG when the address is the whole\n * fragment (`#victim@example.com`), which only a landing page's script\n * reads; soft when it is a query parameter or part of a longer fragment.\n * The address itself is never stored.\n */\n | { code: 'recipient-prefill-link'; host: string; lure: string; place: 'fragment' | 'parameter' }\n /**\n * A link, embed, redirect or form action whose host Google Web Risk lists\n * as phishing, malware or unwanted software (AGL-3451,\n * `link-reputation.ts`). Strong: a harvester already known to be bad\n * anywhere is bad whatever page or message surrounds it. `url` is set\n * when the listing names one page on the host rather than the host\n * (AGL-3459, `platformSettings/webRisk.lookupMode: 'url'`): the address\n * as looked up, scheme, host and path, never a query string.\n */\n | { code: 'web-risk-link'; host: string; threats: string[]; url?: string }\n\nexport interface PhishingScreenInput {\n subject?: string | null\n /** The display name in front of the sending address. */\n fromName?: string | null\n /**\n * The ADDRESS the message leaves from (AGL-3362) — a `From:` domain is a\n * link the recipient never has to click, so its host is read by the\n * lookalike rule exactly like a link's: mail from `support@paypa1.com` is\n * the disguise whoever sends it. Not an own domain for the lure's \"is this\n * elsewhere\" test either way; it only ever adds a lookalike signal.\n */\n fromAddress?: string | null\n replyTo?: string | readonly string[] | null\n preheader?: string | null\n /**\n * Everything else the recipient reads or clicks: the body, the plain-text\n * part, a design's nodes serialized — any string. Links are found by\n * shape, so a JSON-encoded design is as readable here as HTML.\n */\n bodies?: readonly (string | null | undefined)[]\n /**\n * The workspace's own names — org, site, subdomain. A brand in one of them\n * is the workspace's own, and `brand-sender` / `brand-lure-link` do not\n * fire for it. The lookalike check does not consult names: a workspace\n * NAMED \"Poshmark\" linking to `poshmark.id63835663.shop` is the incident.\n */\n ownNames?: readonly (string | null | undefined)[]\n /**\n * The workspace's own hosts — its subdomain on the tenant apex, custom\n * domain, sending domain. A link to one of them, or below one, is never\n * the \"somewhere else\" of a lure. Matched by host, never by registrable\n * domain: every site's subdomain shares the tenant apex, and a link to a\n * NEIGHBOR's site is somewhere else.\n *\n * Not an exemption from the lookalike check. A host shaped like\n * `paypal-secure.com` is a lookalike whoever attached it, and a workspace\n * that attached it has attached the disguise.\n */\n ownDomains?: readonly (string | null | undefined)[]\n}\n\nexport interface PhishingScreenVerdict {\n /** True when the message should be held for staff review. */\n hold: boolean\n signals: PhishingScreenSignal[]\n}\n\n/** The registrable domain of a host: `a.b.evil.co.uk` → `evil.co.uk`. */\nexport function registrableDomain(host: string): string {\n const labels = String(host ?? '')\n .toLowerCase()\n .replace(/\\.+$/, '')\n .split('.')\n .filter(Boolean)\n if (labels.length <= 2) return labels.join('.')\n const lastTwo = labels.slice(-2).join('.')\n return TWO_LABEL_SUFFIXES.has(lastTwo)\n ? labels.slice(-3).join('.')\n : lastTwo\n}\n\n/** `<label>.<suffix>` of a registrable domain, split once. */\nfunction splitRegistrable(registrable: string): { label: string; suffix: string } {\n const dot = registrable.indexOf('.')\n return dot < 0\n ? { label: registrable, suffix: '' }\n : { label: registrable.slice(0, dot), suffix: registrable.slice(dot + 1) }\n}\n\nfunction isOfficialDomain(brand: PhishingScreenBrand, registrable: string): boolean {\n if (brand.officialDomains.includes(registrable)) return true\n if (!brand.countryDomains) return false\n const base = splitRegistrable(brand.officialDomains[0]).label\n const { label, suffix } = splitRegistrable(registrable)\n return label === base && (/^[a-z]{2}$/.test(suffix) || TWO_LABEL_SUFFIXES.has(suffix))\n}\n\n/**\n * Is the workspace the brand itself, by DOMAIN: one of its own domains is\n * one of the brand's official ones (Aglyn's site on aglyn.com linking to\n * its own account on a video or help-desk vendor). Deliberately not by name — a workspace can call itself\n * \"Poshmark\", but it cannot serve on poshmark.com.\n */\nexport function isBrandsOwnDomain(\n brand: PhishingScreenBrand,\n ownRegistrables: ReadonlySet<string>,\n): boolean {\n return [...ownRegistrables].some((registrable) => isOfficialDomain(brand, registrable))\n}\n\n/** Every brand's real domains, for \"is this link just the brand itself\". */\nfunction isAnyOfficialDomain(registrable: string): boolean {\n return PHISHING_SCREEN_BRANDS.some((brand) => isOfficialDomain(brand, registrable))\n}\n\n/** Leetspeak folded, so `paypa1` reads as `paypal`. */\nfunction foldLeet(label: string): string {\n return label\n .replace(/0/g, 'o')\n .replace(/1/g, 'l')\n .replace(/3/g, 'e')\n .replace(/4/g, 'a')\n .replace(/5/g, 's')\n .replace(/7/g, 't')\n}\n\n/** Does one host label name the brand — whole, or hyphen-joined? */\nfunction labelNamesBrand(label: string, token: string, wordToken: boolean): boolean {\n if (wordToken) return label === token\n for (const candidate of new Set([label, foldLeet(label)])) {\n if (candidate === token) return true\n const parts = candidate.split('-')\n // A hyphen-joined token (`booking-com`) spans parts, so it is matched\n // as a run of parts rather than one of them.\n const tokenParts = token.split('-')\n for (let at = 0; at + tokenParts.length <= parts.length; at += 1) {\n if (tokenParts.every((part, offset) => parts[at + offset] === part)) {\n return true\n }\n }\n }\n return false\n}\n\n/**\n * Video and audio platforms whose account subdomains and embed URLs a page\n * or email plays media from: `player.vimeo.com`, `www.youtube.com/embed/…`.\n * A video plugin's own hosts are the plugin's to declare, not listed here. Anyone may embed or link media from these, so a\n * host on one is never a lookalike, whatever name its subdomain carries.\n */\nexport const MEDIA_EMBED_HOSTS: ReadonlySet<string> = new Set([\n 'vimeo.com', 'vimeocdn.com', 'youtube.com', 'youtu.be',\n 'youtube-nocookie.com', 'ytimg.com', 'loom.com', 'vidyard.com', 'brightcove.net',\n 'brightcove.com', 'jwplayer.com', 'jwpcdn.com', 'mux.com', 'cloudflarestream.com',\n 'videodelivery.net', 'dailymotion.com', 'twitch.tv', 'spotify.com', 'soundcloud.com',\n 'podbean.com', 'buzzsprout.com', 'simplecast.com', 'transistor.fm', 'anchor.fm',\n])\n\n/** The brand a host impersonates, or null. */\nexport function lookalikeBrandForHost(host: string): PhishingScreenBrand | null {\n const normalized = String(host ?? '').toLowerCase().replace(/\\.+$/, '')\n if (!normalized.includes('.')) return null\n const registrable = registrableDomain(normalized)\n if (MEDIA_EMBED_HOSTS.has(registrable)) return null\n for (const brand of PHISHING_SCREEN_BRANDS) {\n if (isOfficialDomain(brand, registrable)) continue\n if (brand.hostedDomains?.includes(registrable)) continue\n const labels = normalized.split('.')\n if (\n labels.some((label) =>\n brand.hostTokens.some((token) => labelNamesBrand(label, token, brand.wordToken === true)),\n )\n ) {\n return brand\n }\n // The brand's primary domain embedded in a longer, different one:\n // `booking.com.guest-review.top`, `paypal.com-secure.net`. Only the\n // primary: a short secondary (`me.com`, `aka.ms`) would match too much.\n const primary = brand.officialDomains[0]\n if (\n normalized.startsWith(`${primary}.`) ||\n normalized.startsWith(`${primary}-`) ||\n normalized.includes(`.${primary}.`) ||\n normalized.includes(`.${primary}-`)\n ) {\n return brand\n }\n }\n return null\n}\n\n/**\n * The few entity forms a phishing kit uses to keep a URL away from a naive\n * scanner (`&#46;` for a dot, `&amp;` inside a query). Decoded before links\n * are read; everything else is left alone.\n */\nfunction decodeEntities(text: string): string {\n return text\n .replace(/&#x([0-9a-f]{1,6});/gi, (_, hex: string) => safeCodePoint(parseInt(hex, 16)))\n .replace(/&#(\\d{1,7});/g, (_, dec: string) => safeCodePoint(parseInt(dec, 10)))\n .replace(/&amp;/gi, '&')\n}\n\nfunction safeCodePoint(value: number): string {\n return Number.isFinite(value) && value > 0 && value <= 0x10ffff\n ? String.fromCodePoint(value)\n : ''\n}\n\n/** Named entities a body uses for spacing, quoting and invisible splitting. */\nconst NAMED_ENTITIES: Record<string, string> = {\n nbsp: ' ',\n ensp: ' ',\n emsp: ' ',\n thinsp: ' ',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n shy: '',\n zwnj: '',\n zwj: '',\n}\n\n/*\n * Markup is read in single forward passes, never with a pattern that can\n * rescan to the end of the body from every `<`: the screen reads every\n * tenant message, and the tenant writes the body, so a million unclosed\n * `<` must cost a linear read.\n */\n/** An element whose contents a reader never sees: the start of its opening tag. */\nconst UNSEEN_ELEMENT_OPEN = /<(style|script|head|template)\\b/gi\n/** The name at the start of a tag that breaks a line or a block: a reader sees a gap there. */\nconst BREAKING_TAG_NAME =\n /^\\/?(?:br|p|div|li|ul|ol|tr|td|th|table|tbody|thead|h[1-6]|section|article|header|footer|blockquote|hr|center)\\b/i\n/** Characters that render as nothing, used to split a word for a scanner. */\nconst INVISIBLE_CHARACTERS = /[\\u00ad\\u200b-\\u200d\\u2060\\ufeff]/g\n\n/**\n * The text between the tags, joined with NO separator — or, with `breaks`,\n * with a space where a line or block breaks. A comment is dropped; a `<`\n * with no `>` after it is text.\n */\nfunction stripMarkup(html: string, breaks: boolean): string {\n let text = ''\n let at = 0\n while (at < html.length) {\n const open = html.indexOf('<', at)\n if (open < 0) return text + html.slice(at)\n text += html.slice(at, open)\n if (html.startsWith('<!--', open)) {\n const end = html.indexOf('-->', open + 4)\n if (end < 0) return text\n at = end + 3\n continue\n }\n const close = html.indexOf('>', open + 1)\n if (close < 0) return text + html.slice(open)\n if (breaks && BREAKING_TAG_NAME.test(html.slice(open + 1, Math.min(close, open + 12)))) text += ' '\n at = close + 1\n }\n return text\n}\n\n/** The markup with every unseen element and its contents taken out, in one pass. */\nfunction dropUnseenElements(html: string): string {\n const lower = html.toLowerCase()\n const open = new RegExp(UNSEEN_ELEMENT_OPEN.source, 'gi')\n let kept = ''\n let at = 0\n // Each search starts at or after the last; what it found (or that it found\n // nothing) still answers the next one, so no stretch is scanned twice.\n const found = new Map<string, number>()\n const find = (needle: string, from: number) => {\n const known = found.get(needle)\n if (known !== undefined && (known < 0 || known >= from)) return known\n const position = lower.indexOf(needle, from)\n found.set(needle, position)\n return position\n }\n for (let match = open.exec(html); match; match = open.exec(html)) {\n // No `>` after it: neither this nor anything later is a tag.\n const tagEnd = find('>', open.lastIndex)\n if (tagEnd < 0) break\n kept += `${html.slice(at, match.index)} `\n const name = match[1].toLowerCase()\n const close = find(`</${name}`, tagEnd + 1)\n // A head nobody closed ends where the body starts, as a browser reads it.\n const body = name === 'head' ? find('<body', tagEnd + 1) : -1\n if (body >= 0 && (close < 0 || body < close)) {\n at = body\n } else {\n const end = close < 0 ? -1 : find('>', close)\n // Never closed: only the opening tag goes, and what follows is still\n // read, so an unclosed `<style>` cannot hide the lure after it.\n at = end < 0 ? tagEnd + 1 : end + 1\n }\n open.lastIndex = at\n }\n return kept + html.slice(at)\n}\n\n/**\n * What a reader SEES in a body (AGL-3453): its text with the markup taken\n * out, the way a mail client or a browser draws it.\n *\n * A kit splits every letter of a brand and a lure with a tag —\n * `G<SPAN class=…>o<SPAN …>o…gle`, `P<SPAN …>a<SPAN …>s…word E<SPAN …>x…pired`\n * — so the raw HTML never contains the word a reader reads. Tags are\n * therefore removed with NO separator, which rejoins the letters; `<style>`,\n * `<script>` and `<head>` are dropped with their contents; comments and\n * zero-width characters are dropped; entities are decoded; whitespace is\n * collapsed. A second reading that puts a space where a line or block\n * breaks is added when it differs, so two words in two paragraphs are still\n * two words. Links are NOT read from this: an href lives inside a tag.\n */\nexport function visibleTextOf(html: string | null | undefined): string {\n const text = String(html ?? '')\n const source = text.includes('<') ? dropUnseenElements(text) : text\n const read = (breaks: boolean) =>\n decodeVisibleEntities(stripMarkup(source, breaks))\n .replace(INVISIBLE_CHARACTERS, '')\n .replace(/\\s+/g, ' ')\n .trim()\n const joined = read(false)\n const broken = read(true)\n return broken === joined ? joined : `${joined}\\n${broken}`\n}\n\n/** {@link decodeEntities}, after the named entities a body reads with. */\nfunction decodeVisibleEntities(text: string): string {\n return decodeEntities(\n text.replace(/&([a-z]{2,8});/gi, (entity, name: string) => NAMED_ENTITIES[name.toLowerCase()] ?? entity),\n )\n}\n\nconst URL_PATTERN = /\\b(?:https?:\\/\\/|www\\.)[^\\s\"'<>()\\\\[\\]{}]+/gi\n\n/** The hosts every link in the text points at, lowercased. */\nexport function linkHostsIn(text: string): string[] {\n const hosts = new Set<string>()\n for (const match of decodeEntities(String(text ?? '')).match(URL_PATTERN) ?? []) {\n let rest = match.replace(/^https?:\\/\\//i, '')\n rest = rest.split(/[/?#]/)[0]\n // `https://paypal.com@evil.top/` resolves to evil.top — and the part\n // before the `@` is exactly the disguise, so it is kept as a host too.\n const at = rest.lastIndexOf('@')\n const disguise = at >= 0 ? rest.slice(0, at) : ''\n rest = at >= 0 ? rest.slice(at + 1) : rest\n for (const candidate of [rest, disguise]) {\n const host = candidate.replace(/:\\d+$/, '').replace(/\\.+$/, '').toLowerCase()\n // A merge tag inside a URL is not a host anybody can visit yet.\n if (host && host.includes('.') && !host.includes('{') && !host.includes('%7b')) {\n hosts.add(host)\n }\n }\n }\n return [...hosts]\n}\n\n/**\n * Every link in the text as written — `www.` read as `https://`, prose\n * punctuation after it dropped — in the order found, each once. Query\n * strings and fragments are still on them: read them through\n * `normalizeReputationLink` (`link-reputation.ts`) before they go anywhere.\n */\nexport function linkUrlsIn(text: string): string[] {\n const urls = new Set<string>()\n for (const match of decodeEntities(String(text ?? '')).match(URL_PATTERN) ?? []) {\n const url = match.replace(/[.,;:!]+$/, '')\n urls.add(/^www\\./i.test(url) ? `https://${url}` : url)\n }\n return [...urls]\n}\n\n/** One link: the host it goes to, and its query and fragment, URL-decoded. */\ninterface LinkTarget {\n host: string\n query: string\n fragment: string\n}\n\n/** Every link in the text, with what it carries after its path. */\nfunction linkTargetsIn(text: string): LinkTarget[] {\n const targets: LinkTarget[] = []\n for (const match of decodeEntities(String(text ?? '')).match(URL_PATTERN) ?? []) {\n // The first host is where the browser goes; a userinfo disguise is not.\n const [host] = linkHostsIn(match)\n if (!host) continue\n const hash = match.indexOf('#')\n const beforeHash = hash < 0 ? match : match.slice(0, hash)\n const question = beforeHash.indexOf('?')\n targets.push({\n host,\n query: question < 0 ? '' : decodeUrlPart(beforeHash.slice(question + 1)),\n fragment: hash < 0 ? '' : decodeUrlPart(match.slice(hash + 1)),\n })\n }\n return targets\n}\n\nfunction decodeUrlPart(part: string): string {\n try {\n return decodeURIComponent(part)\n } catch {\n return part\n }\n}\n\nconst EMAIL_ADDRESS = /^[a-z0-9._%+-]+@[a-z0-9-]+(?:\\.[a-z0-9-]+)+$/i\nconst EMAIL_ADDRESS_IN_TEXT = /[a-z0-9._%+-]+@([a-z0-9-]+(?:\\.[a-z0-9-]+)+)/gi\nconst BASE64_TEXT = /^[a-z0-9+/_-]{8,}={0,2}$/i\n\n/** A fragment read as base64, the other way a kit carries the address, or ''. */\nfunction base64Text(fragment: string): string {\n const decode = (globalThis as { atob?: (data: string) => string }).atob\n if (!decode || !BASE64_TEXT.test(fragment)) return ''\n try {\n return decode(fragment.replace(/-/g, '+').replace(/_/g, '/'))\n } catch {\n return ''\n }\n}\n\n/**\n * Where a link carries a reader's own address (AGL-3453), or null.\n *\n * - `fragment`: the WHOLE fragment is an address, plain or base64 —\n * `…#victim@example.com`. A fragment never reaches the server; the only\n * thing that reads it is the landing page's script, filling a sign-in\n * form so the reader sees their own address and types the password.\n * - `parameter`: an address that is not the workspace's own inside a query\n * or a longer fragment — `?email=victim@example.com`, a hash route's\n * `#/login?email=…`. Ordinary in a sign-up or a SaaS login link, so softer.\n */\nfunction prefilledAddressIn(\n target: LinkTarget,\n isOwnHost: (host: string) => boolean,\n): 'fragment' | 'parameter' | null {\n const fragment = target.fragment.trim()\n if (fragment && (EMAIL_ADDRESS.test(fragment) || EMAIL_ADDRESS.test(base64Text(fragment).trim()))) {\n return 'fragment'\n }\n for (const part of [target.query, target.fragment]) {\n // An address is short; a tracking token can be kilobytes of the\n // characters an address is made of, so only the head of one is read.\n if (!part.includes('@')) continue\n for (const match of part.slice(0, 4096).matchAll(EMAIL_ADDRESS_IN_TEXT)) {\n if (!isOwnHost(match[1].toLowerCase())) return 'parameter'\n }\n }\n return null\n}\n\nconst ADDRESS_HOST_PATTERN = /[a-z0-9._%+-]+@([a-z0-9-]+(?:\\.[a-z0-9-]+)+)/gi\n\n/** The host of every email address in the text — a reply-to, a `mailto:`. */\nfunction addressHostsIn(text: string): string[] {\n const hosts = new Set<string>()\n for (const match of decodeEntities(String(text ?? '')).matchAll(ADDRESS_HOST_PATTERN)) {\n hosts.add(match[1].toLowerCase().replace(/\\.+$/, ''))\n }\n return [...hosts]\n}\n\n/** Lowercased alphanumerics only, so \"Wells-Fargo Advisors\" contains `wellsfargo`. */\nfunction squash(text: string): string {\n return text.toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\n/** Is this brand the workspace's own, by name or by a domain it holds? */\nfunction isOwnBrand(\n brand: PhishingScreenBrand,\n ownNames: string,\n ownRegistrables: ReadonlySet<string>,\n): boolean {\n const labels = [brand.id, squash(brand.label), ...brand.hostTokens.map(squash)]\n if (labels.some((label) => label && ownNames.includes(label))) return true\n return [...ownRegistrables].some((registrable) => isOfficialDomain(brand, registrable))\n}\n\n/*\n * The same judgements, for the other surfaces that read content with this\n * screen's data (`hosted-page-screen.ts`). Exported under these names rather\n * than copied, so a page and an email can never disagree about what a\n * brand's own domain is or whose brand a name is.\n */\n\n/** `squash`: lowercased alphanumerics, the form own-name matching reads. */\nexport const squashScreenText = squash\n/** Is this brand the workspace's own, by name (squashed) or by a domain it holds? */\nexport const isWorkspaceOwnBrand = isOwnBrand\n/** Is this registrable domain one of any listed brand's own? */\nexport const isAnyOfficialBrandDomain = isAnyOfficialDomain\n/** Is this registrable domain a social, maps or review link merchants ordinarily carry? */\nexport function isCommonLinkDomain(registrable: string): boolean {\n return COMMON_LINK_DOMAINS.has(registrable)\n}\n\n/**\n * Screen one outbound message. See the module header for what holds and why.\n */\nexport function screenOutboundEmail(input: PhishingScreenInput): PhishingScreenVerdict {\n const signals: PhishingScreenSignal[] = []\n const ownNames = squash((input.ownNames ?? []).filter(Boolean).join(' '))\n const ownHosts = (input.ownDomains ?? [])\n .map((domain) => String(domain ?? '').trim().toLowerCase().replace(/\\.+$/, ''))\n .filter((domain) => domain.includes('.'))\n const ownRegistrables = new Set(ownHosts.map(registrableDomain))\n const isOwnHost = (host: string) =>\n ownHosts.some((own) => host === own || host.endsWith(`.${own}`))\n\n const parts = [input.subject, input.preheader, ...(input.bodies ?? [])].filter(\n (part): part is string => typeof part === 'string' && part.length > 0,\n )\n // Links are read from the raw copy, where an href lives; brands and lures\n // from what a reader sees, where a tag cannot split a word (AGL-3453).\n const copy = parts.join('\\n')\n const visibleCopy = parts.map(visibleTextOf).join('\\n')\n const replyTo = Array.isArray(input.replyTo)\n ? input.replyTo.join(' ')\n : String(input.replyTo ?? '')\n const linkHosts = linkHostsIn(copy)\n\n // 1. A lookalike host, anywhere a recipient could click, write back, or\n // read as the sender.\n const seenLookalike = new Set<string>()\n const fromAddress = String(input.fromAddress ?? '')\n for (const host of [...linkHosts, ...addressHostsIn(`${copy}\\n${replyTo}\\n${fromAddress}`)]) {\n if (seenLookalike.has(host)) continue\n const brand = lookalikeBrandForHost(host)\n if (brand && !isBrandsOwnDomain(brand, ownRegistrables)) {\n seenLookalike.add(host)\n signals.push({ code: 'lookalike-link', brand: brand.id, host })\n }\n }\n\n // 2. A brand in the sender's display name that is not the workspace's.\n const fromName = String(input.fromName ?? '').trim()\n if (fromName) {\n for (const brand of PHISHING_SCREEN_BRANDS) {\n if (brand.mention.test(fromName) && !isOwnBrand(brand, ownNames, ownRegistrables)) {\n signals.push({ code: 'brand-sender', brand: brand.id, fromName: fromName.slice(0, 120) })\n }\n }\n }\n\n // 3. Brand + lure + a link to somewhere that is nobody's we know.\n const isElsewhere = (host: string) => {\n if (isOwnHost(host)) return false\n const registrable = registrableDomain(host)\n return !isAnyOfficialDomain(registrable) && !COMMON_LINK_DOMAINS.has(registrable)\n }\n const lure = PHISHING_LURE_PATTERNS.map((pattern) => visibleCopy.match(pattern)?.[0])\n .find(Boolean)\n if (lure) {\n const foreign = linkHosts.find(isElsewhere)\n if (foreign) {\n const namedInCopy = `${visibleCopy}\\n${fromName}`\n for (const brand of PHISHING_SCREEN_BRANDS) {\n if (brand.mention.test(namedInCopy) && !isOwnBrand(brand, ownNames, ownRegistrables)) {\n signals.push({\n code: 'brand-lure-link',\n brand: brand.id,\n lure: lure.slice(0, 120),\n host: foreign,\n })\n break\n }\n }\n }\n }\n\n // 4. An account lure beside a link elsewhere that carries the reader's own\n // address, filled in for the sign-in form at the far end (AGL-3453).\n const accountLure = ACCOUNT_LURE_PATTERNS.map((pattern) => visibleCopy.match(pattern)?.[0]).find(Boolean)\n if (accountLure) {\n let prefill: { host: string; place: 'fragment' | 'parameter' } | null = null\n for (const target of linkTargetsIn(copy)) {\n if (!isElsewhere(target.host)) continue\n const place = prefilledAddressIn(target, isOwnHost)\n if (place && (!prefill || (place === 'fragment' && prefill.place !== 'fragment'))) {\n prefill = { host: target.host, place }\n }\n }\n if (prefill) {\n signals.push({\n code: 'recipient-prefill-link',\n host: prefill.host,\n lure: accountLure.slice(0, 120),\n place: prefill.place,\n })\n }\n }\n\n return { hold: signals.length > 0, signals }\n}\n\n/** The brand's label for a stored id, for the staff surface. */\nexport function phishingScreenBrandLabel(id: string): string {\n return PHISHING_SCREEN_BRANDS.find((brand) => brand.id === id)?.label ?? id\n}\n\n/** Web Risk's threat types, in the words staff read (AGL-3451). */\nconst LINK_THREAT_WORDS: Record<string, string> = {\n SOCIAL_ENGINEERING: 'phishing or social engineering',\n MALWARE: 'malware',\n UNWANTED_SOFTWARE: 'unwanted software',\n}\n\n/** \"phishing or social engineering and malware\", from Web Risk's threat types. */\nexport function describeLinkThreats(threats: readonly string[]): string {\n const words = [...new Set(threats)].map((threat) => LINK_THREAT_WORDS[threat] ?? threat.toLowerCase())\n if (!words.length) return 'unsafe'\n return words.length === 1 ? words[0] : `${words.slice(0, -1).join(', ')} and ${words[words.length - 1]}`\n}\n\n/** One line per signal, in words staff read on the review row. */\nexport function describePhishingScreenSignals(\n signals: readonly PhishingScreenSignal[],\n): string[] {\n return signals.map((signal) => {\n const brand = 'brand' in signal ? phishingScreenBrandLabel(signal.brand) : ''\n switch (signal.code) {\n case 'lookalike-link':\n return `Links to ${signal.host}, which wears the ${brand} name but is not ${brand}'s domain.`\n case 'brand-sender':\n return `Sends as \"${signal.fromName}\", naming ${brand}, which is not this workspace.`\n case 'brand-lure-link':\n return `Names ${brand}, asks the reader to act (\"${signal.lure}\"), and links to ${signal.host}.`\n case 'credential-field':\n return `Asks for a ${\n signal.field === 'card' ? 'card number' : signal.field === 'otp' ? 'one-time code' : 'password'\n } in its own field (\"${signal.label}\"), outside the platform's sign-in and checkout elements.`\n case 'brand-action-page':\n return `Names ${brand} beside a call to action (\"${signal.action}\"), and this workspace is not ${brand}.`\n case 'brand-lure-page':\n return `Names ${brand} on a page that asks visitors to act (\"${signal.lure}\") and links to ${signal.host}, and this workspace is not ${brand}.`\n case 'offsite-action-page':\n return `Its call to action (\"${signal.action}\") sends visitors off the site to ${signal.host}, on a page that reads \"${signal.lure}\".`\n case 'offsite-redirect':\n return `Redirects ${signal.source}, a path that reads \"${signal.lure}\", off the site to ${signal.host}.`\n case 'recipient-prefill-link':\n return `Links to ${signal.host} with the recipient's own address in the ${\n signal.place === 'fragment' ? 'fragment' : 'link'\n }, so a sign-in form there opens filled in, beside \"${signal.lure}\".`\n case 'web-risk-link':\n return `Links to ${signal.url ?? signal.host}, which Google Web Risk lists as ${describeLinkThreats(signal.threats)}.`\n default:\n return 'Phishing signal.'\n }\n })\n}\n\n/*==========================================\n * RISK TIERS: who a signal holds for (AGL-3356, widened to every surface).\n *\n * The screen above finds signals; this decides which of them hold, the same\n * way on every surface that asks — an email at the send seam, a campaign\n * before it is claimed, a page at publish, a subdomain at creation.\n *\n * - STRONG: a lookalike host. A link to `poshmark.id63835663.shop` or\n * `paypa1.com` is a disguise whoever wears it and however old the\n * workspace is, so it holds for EVERY workspace, on every message and\n * page, transactional mail included. A merchant has no ordinary reason to\n * link to a host shaped like somebody else's brand.\n * - STRONG, too: account or password phrasing beside a link elsewhere whose\n * whole FRAGMENT is the reader's address (AGL-3453). A fragment never\n * reaches a server, so the address there is for the landing page's script\n * to fill a sign-in form with; a merchant's own reset mail links to its\n * own domain, and a SaaS login link puts the address in its query, which\n * is soft.\n * - SOFT: a brand in the sender name, the three-part lure, a brand's name\n * beside a sign-in or payment call to action on a page (in one element,\n * or anywhere on a page that carries a lure), a call to action or a\n * redirect that leaves the site beside account or document-share wording,\n * the reader's address in a query beside account phrasing.\n * Each is shaped like phishing but also like a clumsy legitimate message,\n * so they hold\n * only for a workspace in its first {@link OUTBOUND_REVIEW_YOUNG_DAYS}\n * days — the incident's window — and NEVER for mail the recipient's own\n * act made owed ({@link OutboundScreenPolicy.owed}).\n *\n * A credential-harvest page (a password, card or one-time-code field that\n * is not one of the platform's own sign-in or checkout elements) is STRONG:\n * see `hosted-page-screen.ts`. So is a link to a host Google Web Risk lists\n * (`web-risk-link`, `link-reputation.ts`): it holds for every workspace, and\n * an account-subdomain host does not soften it, because the listing names\n * that host itself.\n *=========================================*/\n\n/** A workspace younger than this many days has the soft rules applied. */\nexport const OUTBOUND_REVIEW_YOUNG_DAYS = 14\n\n/** Which tier a signal belongs to. */\nexport type PhishingSignalTier = 'strong' | 'soft'\n\n/** The signal codes that hold for every workspace. */\nexport const STRONG_PHISHING_SIGNAL_CODES: ReadonlySet<string> = new Set([\n 'lookalike-link',\n 'credential-field',\n 'web-risk-link',\n])\n\n/**\n * Hosts that give each customer an account subdomain named after the\n * customer: `acme.zendesk.com` is Acme's own help desk. A brand's name there is usually the brand itself, so a\n * lookalike on one of these is SOFT — held for a young workspace, never a\n * takedown of an established one's page or mail. A lookalike on any other\n * host (`poshmark.id63835663.shop`) stays STRONG.\n */\nexport const ACCOUNT_SUBDOMAIN_HOSTS: ReadonlySet<string> = new Set([\n 'vimeo.com', 'vimeocdn.com', 'zendesk.com', 'freshdesk.com',\n 'helpscoutdocs.com', 'intercom.help', 'statuspage.io', 'atlassian.net', 'myshopify.com',\n 'squarespace.com', 'wixsite.com', 'webflow.io', 'hubspotpagebuilder.com', 'substack.com',\n 'typeform.com', 'calendly.com', 'gitbook.io', 'readme.io', 'notion.site', 'github.io',\n 'cloudfront.net', 'kajabi.com', 'thinkific.com', 'teachable.com', 'mailchimpsites.com',\n])\n\nexport function phishingSignalTier(signal: {\n code: string\n host?: string\n place?: string\n}): PhishingSignalTier {\n if (signal?.code === 'recipient-prefill-link') {\n return signal.place === 'fragment' ? 'strong' : 'soft'\n }\n if (!STRONG_PHISHING_SIGNAL_CODES.has(signal?.code)) return 'soft'\n if (\n signal.code === 'lookalike-link' &&\n typeof signal.host === 'string' &&\n ACCOUNT_SUBDOMAIN_HOSTS.has(registrableDomain(signal.host))\n ) {\n return 'soft'\n }\n return 'strong'\n}\n\n/** Is a workspace of this age (days, `null` = unreadable) screened by the soft rules? */\nexport function isYoungWorkspaceAge(ageDays: number | null | undefined): boolean {\n return typeof ageDays === 'number' && Number.isFinite(ageDays) && ageDays < OUTBOUND_REVIEW_YOUNG_DAYS\n}\n\nexport interface OutboundScreenPolicy {\n /**\n * The workspace's age in days, or `null` when its creation date cannot be\n * read — an org that predates the field, which is an EXISTING customer and\n * is not young.\n */\n ageDays: number | null\n /**\n * The recipient's own act made this message owed: a receipt for their\n * order, a confirmation of their booking, a reset of their password. The\n * soft rules never hold it. The lookalike rule still does — a receipt that\n * links to a Poshmark lookalike is the disguise, not the receipt.\n */\n owed?: boolean\n}\n\n/** The signals that HOLD under the tiers, for this workspace and message. */\nexport function signalsThatHold<T extends { code: string; host?: string }>(\n signals: readonly T[],\n policy: OutboundScreenPolicy,\n): T[] {\n const soft = isYoungWorkspaceAge(policy.ageDays) && !policy.owed\n return signals.filter((signal) => phishingSignalTier(signal) === 'strong' || soft)\n}\n\n/**\n * The same brand, lookalike and tier logic applied to a HOST NAME a workspace\n * asks for — a subdomain on the tenant apex, or a custom domain it attaches.\n *\n * Words a brand's impersonator hyphen-joins to its name. A subdomain that\n * joins a brand's word to one of these (`booking-review`, `apple-support`,\n * `amazon-account`) is the incident's shape even where the brand's word is\n * an ordinary one — which the lookalike rule alone deliberately lets pass,\n * so a salon can be `tanyas-booking` and a bakery `apple-pie-co`.\n */\nexport const BRAND_IMPERSONATION_WORDS: ReadonlySet<string> = new Set([\n 'account', 'accounts', 'auth', 'billing', 'help', 'helpdesk', 'id', 'login',\n 'logon', 'order', 'orders', 'pay', 'payment', 'payments', 'refund', 'resolution',\n 'review', 'reviews', 'secure', 'security', 'seller', 'service', 'signin',\n 'support', 'update', 'verify', 'verification', 'wallet',\n])\n\n/**\n * The brand a requested subdomain label wears, or null.\n *\n * Refused for EVERY workspace, at creation and at rename — the tier is\n * strong, because nothing is lost by asking a real bakery to pick\n * `apple-pie-co` instead of `apple-support`, and a brand's name on our apex\n * is a disguise that outlives every later screen. Two shapes:\n *\n * 1. the label is a lookalike host label ({@link lookalikeBrandForHost} on\n * `<label>.<apex>`): `poshmark`, `paypal-secure`, `paypa1`, `appleid`;\n * 2. a brand's word hyphen-joined to an impersonation word\n * ({@link BRAND_IMPERSONATION_WORDS}): `booking-review`, `apple-support`.\n */\nexport function brandForSubdomainLabel(\n label: string,\n apex = 'example.invalid',\n): PhishingScreenBrand | null {\n const normalized = String(label ?? '').trim().toLowerCase()\n if (!normalized) return null\n const byHost = lookalikeBrandForHost(`${normalized}.${apex}`)\n if (byHost) return byHost\n const parts = foldLeet(normalized).split('-').filter(Boolean)\n if (parts.length < 2 || !parts.some((part) => BRAND_IMPERSONATION_WORDS.has(part))) {\n return null\n }\n for (const brand of PHISHING_SCREEN_BRANDS) {\n const words = [brand.id, ...brand.hostTokens].filter((word) => !word.includes('-'))\n if (parts.some((part) => words.includes(part))) return brand\n }\n return null\n}\n\n/**\n * The platform's own entry in {@link PHISHING_SCREEN_BRANDS} (AGL-3365). A\n * workspace owns every other brand by carrying its name or domain; the\n * platform's is owned only by the platform's staff, because a workspace NAMED\n * for the platform is the cheapest disguise there is.\n */\nexport const PLATFORM_PHISHING_BRAND_ID = 'aglyn'\n\n/** The platform's brand entry. */\nexport function platformPhishingBrand(): PhishingScreenBrand {\n return PHISHING_SCREEN_BRANDS.find((brand) => brand.id === PLATFORM_PHISHING_BRAND_ID) as PhishingScreenBrand\n}\n\n/**\n * Words that make a name claim to SPEAK FOR a brand rather than mention it:\n * \"PayPal Support\", \"Aglyn Official\", \"Apple ID Security Team\".\n */\nconst OFFICIAL_CLAIM_PATTERN =\n /\\b(?:official|staff|team|verified|certified|support|helpdesk|admin|administrator|security|billing|trust|safety|compliance|core|headquarters|hq)\\b/i\n\n/**\n * The brand a display NAME claims to speak for (AGL-3365), or null.\n *\n * For names a stranger reads as an identity — a marketplace publisher, a\n * listing's title — rather than copy. A name that merely mentions a brand\n * (\"Sync for PayPal\", \"Bookings for Airbnb hosts\") passes: that is how an\n * integration is named. A name that pairs the brand with a claim of\n * officialness (\"PayPal Support\", \"Aglyn Official Plugins\") is the disguise.\n */\nexport function brandClaimedByName(name: string): PhishingScreenBrand | null {\n const text = String(name ?? '')\n if (!text.trim() || !OFFICIAL_CLAIM_PATTERN.test(text)) return null\n return PHISHING_SCREEN_BRANDS.find((brand) => brand.mention.test(text)) ?? null\n}\n"],"names":["PHISHING_SCREEN_BRANDS","id","label","mention","hostTokens","officialDomains","countryDomains","wordToken","hostedDomains","ACCOUNT_LURE_PATTERNS","DOCUMENT_SHARE_LURE_PATTERNS","SALE_AND_PARCEL_LURE_PATTERNS","PHISHING_LURE_PATTERNS","COMMON_LINK_DOMAINS","Set","TWO_LABEL_SUFFIXES","registrableDomain","host","labels","String","toLowerCase","replace","split","filter","Boolean","length","join","lastTwo","slice","has","splitRegistrable","registrable","dot","indexOf","suffix","isOfficialDomain","brand","includes","base","test","isBrandsOwnDomain","ownRegistrables","some","isAnyOfficialDomain","foldLeet","labelNamesBrand","token","candidate","parts","tokenParts","at","every","part","offset","MEDIA_EMBED_HOSTS","lookalikeBrandForHost","normalized","primary","startsWith","decodeEntities","text","_","hex","safeCodePoint","parseInt","dec","value","Number","isFinite","fromCodePoint","NAMED_ENTITIES","nbsp","ensp","emsp","thinsp","lt","gt","quot","apos","shy","zwnj","zwj","UNSEEN_ELEMENT_OPEN","BREAKING_TAG_NAME","INVISIBLE_CHARACTERS","stripMarkup","html","breaks","open","end","close","Math","min","dropUnseenElements","lower","RegExp","source","kept","found","Map","find","needle","from","known","get","undefined","position","set","match","exec","tagEnd","lastIndex","index","name","body","visibleTextOf","read","decodeVisibleEntities","trim","joined","broken","entity","URL_PATTERN","linkHostsIn","hosts","rest","lastIndexOf","disguise","add","linkUrlsIn","urls","url","linkTargetsIn","targets","hash","beforeHash","question","push","query","decodeUrlPart","fragment","decodeURIComponent","EMAIL_ADDRESS","EMAIL_ADDRESS_IN_TEXT","BASE64_TEXT","base64Text","decode","globalThis","atob","prefilledAddressIn","target","isOwnHost","matchAll","ADDRESS_HOST_PATTERN","addressHostsIn","squash","isOwnBrand","ownNames","map","squashScreenText","isWorkspaceOwnBrand","isAnyOfficialBrandDomain","isCommonLinkDomain","screenOutboundEmail","input","signals","ownHosts","ownDomains","domain","own","endsWith","subject","preheader","bodies","copy","visibleCopy","replyTo","Array","isArray","linkHosts","seenLookalike","fromAddress","code","fromName","isElsewhere","lure","pattern","foreign","namedInCopy","accountLure","prefill","place","hold","phishingScreenBrandLabel","LINK_THREAT_WORDS","SOCIAL_ENGINEERING","MALWARE","UNWANTED_SOFTWARE","describeLinkThreats","threats","words","threat","describePhishingScreenSignals","signal","field","action","OUTBOUND_REVIEW_YOUNG_DAYS","STRONG_PHISHING_SIGNAL_CODES","ACCOUNT_SUBDOMAIN_HOSTS","phishingSignalTier","isYoungWorkspaceAge","ageDays","signalsThatHold","policy","soft","owed","BRAND_IMPERSONATION_WORDS","brandForSubdomainLabel","apex","byHost","word","PLATFORM_PHISHING_BRAND_ID","platformPhishingBrand","OFFICIAL_CLAIM_PATTERN","brandClaimedByName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA2D2C,GAE3C,qCAAqC,GA2CrC,OAAO,MAAMA,yBAAyD;IACpE;QACEC,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;SAAW;QACxBC,iBAAiB;YAAC;YAAgB;SAAU;IAC9C;IACA;QACEJ,IAAI;QACJC,OAAO;QACP,qEAAqE;QACrEC,SAAS;QACTC,YAAY;YAAC;YAAc;SAAc;QACzCC,iBAAiB;YAAC;YAAe;SAAc;IACjD;IACA;QACEJ,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;SAAS;QACtBC,iBAAiB;YAAC;YAAc;YAAW;SAAe;QAC1DC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;SAAS;QACtBC,iBAAiB;YAAC;YAAc;YAAa;SAAoB;QACjEC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;YAAU;SAAO;QAC9BG,WAAW;QACXF,iBAAiB;YACf;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACP,yEAAyE;QACzEC,SAAS;QACTC,YAAY;YAAC;YAAS;YAAW;YAAU;SAAS;QACpDG,WAAW;QACXF,iBAAiB;YAAC;YAAa;YAAc;YAAY;YAAc;YAAU;SAAe;QAChGC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACP,sEAAsE;QACtE,cAAc;QACdC,SACE;QACFC,YAAY;YACV;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,iBAAiB;YACf;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACEJ,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;SAAW;QACxBC,iBAAiB;YAAC;YAAgB;SAAe;IACnD;IACA;QACEJ,IAAI;QACJC,OAAO;QACP,sEAAsE;QACtE,sDAAsD;QACtDC,SAAS;QACT,iEAAiE;QACjE,sEAAsE;QACtE,qEAAqE;QACrE,0CAA0C;QAC1CC,YAAY;YACV;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,iBAAiB;YACf;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,gBAAgB;IAClB;IACA;QACEL,IAAI;QACJC,OAAO;QACP,qEAAqE;QACrE,sCAAsC;QACtCC,SACE;QACFC,YAAY;YAAC;YAAS;YAAW;YAAa;YAAgB;SAAW;QACzEG,WAAW;QACXF,iBAAiB;YACf;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH;IACA;QACEJ,IAAI;QACJC,OAAO;QACP,0DAA0D;QAC1DC,SAAS;QACTC,YAAY;YAAC;SAAU;QACvBC,iBAAiB;YAAC;YAAe;YAAS;YAA0B;YAAqB;SAAgB;IAC3G;IACA;QACE,wEAAwE;QACxE,uEAAuE;QACvEJ,IAAI;QACJC,OAAO;QACPC,SAAS;QACTC,YAAY;YAAC;YAAU;SAAU;QACjCC,iBAAiB;YAAC;YAAW;YAAW;YAAc;SAAe;IACvE;IACA;QACEJ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AMhC,UAAU;SAAC,CAACmB,MAAM,CAAC,CAACqM,OAAS,CAACA,KAAKvL,QAAQ,CAAC;QAC9E,IAAIW,MAAMN,IAAI,CAAC,CAACU,OAASoJ,MAAMnK,QAAQ,CAACe,QAAQ,OAAOhB;IACzD;IACA,OAAO;AACT;AAEA;;;;;CAKC,GACD,OAAO,MAAMyL,6BAA6B,QAAO;AAEjD,gCAAgC,GAChC,OAAO,SAASC;IACd,OAAO9N,uBAAuBoG,IAAI,CAAC,CAAChE,QAAUA,MAAMnC,EAAE,KAAK4N;AAC7D;AAEA;;;CAGC,GACD,MAAME,yBACJ;AAEF;;;;;;;;CAQC,GACD,OAAO,SAASC,mBAAmB/G,IAAY;QAGtCjH;IAFP,MAAM4D,OAAOzC,OAAO8F,eAAAA,OAAQ;IAC5B,IAAI,CAACrD,KAAK0D,IAAI,MAAM,CAACyG,uBAAuBxL,IAAI,CAACqB,OAAO,OAAO;IAC/D,QAAO5D,+BAAAA,uBAAuBoG,IAAI,CAAC,CAAChE,QAAUA,MAAMjC,OAAO,CAACoC,IAAI,CAACqB,kBAA1D5D,+BAAoE;AAC7E"}
@@ -35,7 +35,7 @@
35
35
  * Nothing installed is UNGATED, the governor's posture: a deployment that
36
36
  * never installs the store must still send.
37
37
  *=========================================*/ import { linkReputationSignals } from "./link-reputation.js";
38
- import { linkHostsIn, screenOutboundEmail, signalsThatHold } from "./outbound-phishing-screen.js";
38
+ import { linkUrlsIn, screenOutboundEmail, signalsThatHold } from "./outbound-phishing-screen.js";
39
39
  let installedGate = null;
40
40
  /** Installs the durable gate. Called once, from `@aglyn/tenant-data-admin`. */ export function setOutboundScreenGate(gate) {
41
41
  installedGate = gate;
@@ -73,10 +73,11 @@ let installedGate = null;
73
73
  ownNames: workspace.ownNames,
74
74
  ownDomains: workspace.ownDomains
75
75
  });
76
- // Every foreign host the message links to, against the reputation list
77
- // (AGL-3451). A listed host is a strong signal; a lookup that fails is
78
- // none. Nothing installed looks nothing up.
79
- const reputation = await linkReputationSignals(linkHostsIn([
76
+ // Every foreign link the message carries, against the reputation list
77
+ // (AGL-3451): its host, and in 'url' mode its address (AGL-3459). A
78
+ // listing is a strong signal; a lookup that fails is none. Nothing
79
+ // installed looks nothing up.
80
+ const reputation = await linkReputationSignals(linkUrlsIn([
80
81
  input.subject,
81
82
  ...input.bodies
82
83
  ].filter(Boolean).join('\n')), {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/outbound-screen-gate.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 OUTBOUND SCREEN ON THE SEND SEAM (AGL-3362).\n *\n * Every tenant message leaves through `sendEmail`, and every tenant sender\n * but the campaign core resolves its identity through `hostSendingIdentity`,\n * which stamps the verdict with the {@link SendingWorkspace} it read. So the\n * screen is asked HERE, once, for the CRM's one-off mail, inbox replies,\n * newsletters, member posts, cart and restock sweeps, flow steps, receipts —\n * and any marketplace plugin that sends for a site — with no copy of it in\n * any of them.\n *\n * Split the way the governor, the marketing gate and the deliverability\n * preflight are: the DECISION is pure and lives in this library\n * (`screenOutboundEmail` finds signals, `signalsThatHold` applies the tiers);\n * what a hold WRITES — the abuse-queue row, the staff alert, the release\n * lookup — is a store, so it is injected by `@aglyn/tenant-data-admin`\n * through {@link setOutboundScreenGate}. The gate is only called when a\n * signal holds, so a clean message costs no read.\n *\n * Nothing installed is UNGATED, the governor's posture: a deployment that\n * never installs the store must still send.\n *=========================================*/\n\nimport { linkReputationSignals } from './link-reputation'\nimport {\n linkHostsIn,\n type PhishingScreenSignal,\n screenOutboundEmail,\n signalsThatHold,\n} from './outbound-phishing-screen'\n\n/**\n * The workspace a tenant message belongs to, as the screen needs it. Stamped\n * on the sending identity by `hostSendingIdentity` from the host and org\n * documents it already reads, so the screen costs no read of its own.\n */\nexport interface SendingWorkspace {\n hostId: string\n orgId: string | null\n /** Days since the org was created; `null` when unreadable (an existing customer). */\n ageDays: number | null\n /** The org's and site's names and the subdomain — a brand in one is its own. */\n ownNames: string[]\n /** The site's hosts — a link to one is never \"elsewhere\". */\n ownDomains: string[]\n}\n\nexport interface OutboundScreenGateRequest {\n workspace: SendingWorkspace\n /** The signals that HOLD, after the tiers. Never empty. */\n signals: PhishingScreenSignal[]\n subject: string\n fromName: string | null\n /** The sender's `context`, so the reviewer can tell which feature sent it. */\n context: string | null\n /**\n * A review row a caller's own screen held and staff RELEASED for this\n * content (a campaign, an automation step). The gate honors it only when\n * that row really is a release for this site — a caller cannot mint one.\n */\n releasedReviewId: string | null\n}\n\nexport interface OutboundScreenGateVerdict {\n outcome: 'send' | 'held' | 'rejected'\n /** The `HS-…` reference staff and the merchant quote. */\n reference?: string | null\n}\n\nexport type OutboundScreenGate = (\n request: OutboundScreenGateRequest,\n) => Promise<OutboundScreenGateVerdict>\n\nlet installedGate: OutboundScreenGate | null = null\n\n/** Installs the durable gate. Called once, from `@aglyn/tenant-data-admin`. */\nexport function setOutboundScreenGate(gate: OutboundScreenGate | null): void {\n installedGate = gate\n}\n\n/** The installed gate, or null when nothing has been installed. */\nexport function getOutboundScreenGate(): OutboundScreenGate | null {\n return installedGate\n}\n\n/** Test seam: forget any installed gate. */\nexport function resetOutboundScreenGateForTests(): void {\n installedGate = null\n}\n\nexport interface TenantMessageScreenInput {\n workspace: SendingWorkspace\n subject: string\n fromName?: string | null\n /** The address it leaves from — a lookalike `From:` domain holds for everyone. */\n fromAddress?: string | null\n replyTo?: string | readonly string[] | null\n /** Everything the recipient reads or clicks: the text part, the HTML. */\n bodies: readonly (string | null | undefined)[]\n /** The recipient's own act made this owed (see `SendEmailOptions.owedFor`). */\n owed?: boolean\n context?: string | null\n releasedReviewId?: string | null\n}\n\n/** Why a tenant message may not leave. */\nexport interface TenantMessageScreenRefusal {\n outcome: 'held' | 'rejected'\n reference: string | null\n /** The sentence a merchant reads. */\n detail: string\n}\n\n/**\n * Screen one tenant message: the pure screen, the reputation of every\n * foreign host it links to (AGL-3451), the tiers, then — only when a signal\n * holds — the installed gate, which files or reads the review row. `null`\n * when it may go.\n *\n * The ONE door for every transport. `sendEmail` asks it for every message a\n * site sends through the platform's provider, and a sender on another\n * transport (Outreach's connected mailboxes) asks it the same way, so a\n * second transport is not a second screen.\n *\n * Fails OPEN on a gate that is missing, throws or answers nothing, the\n * posture of every other control on the send path: an outage on the review\n * queue must not become an outage on every site's mail.\n */\nexport async function screenTenantMessage(\n input: TenantMessageScreenInput,\n label = 'email',\n): Promise<TenantMessageScreenRefusal | null> {\n const { workspace } = input\n if (!workspace?.hostId) return null\n const verdict = screenOutboundEmail({\n subject: input.subject,\n fromName: input.fromName ?? null,\n fromAddress: input.fromAddress ?? null,\n replyTo: input.replyTo ?? null,\n bodies: input.bodies,\n ownNames: workspace.ownNames,\n ownDomains: workspace.ownDomains,\n })\n // Every foreign host the message links to, against the reputation list\n // (AGL-3451). A listed host is a strong signal; a lookup that fails is\n // none. Nothing installed looks nothing up.\n const reputation = await linkReputationSignals(\n linkHostsIn([input.subject, ...input.bodies].filter(Boolean).join('\\n')),\n { ownDomains: workspace.ownDomains },\n )\n const holding = signalsThatHold([...verdict.signals, ...reputation], {\n ageDays: workspace.ageDays,\n owed: input.owed === true,\n })\n if (!holding.length) return null\n const gate = getOutboundScreenGate()\n if (!gate) {\n console.warn(`${label} matched the phishing screen, and no review store is installed — allowing`)\n return null\n }\n let answer: OutboundScreenGateVerdict | null\n try {\n answer = await gate({\n workspace,\n signals: holding,\n subject: String(input.subject ?? ''),\n fromName: input.fromName ?? null,\n context: input.context ?? null,\n releasedReviewId: input.releasedReviewId ?? null,\n })\n } catch (error) {\n console.error(`${label} phishing review failed — allowing`, error)\n answer = null\n }\n if (!answer || answer.outcome === 'send') return null\n const reference = answer.reference ?? null\n const cited = reference ? ` (${reference})` : ''\n return {\n outcome: answer.outcome,\n reference,\n detail:\n answer.outcome === 'rejected'\n ? `Staff review rejected email like this from this site${cited}, so it was not sent.`\n : 'This email is held for staff review because it may impersonate another ' +\n `business${cited}. Nothing was sent.`,\n }\n}\n"],"names":["linkReputationSignals","linkHostsIn","screenOutboundEmail","signalsThatHold","installedGate","setOutboundScreenGate","gate","getOutboundScreenGate","resetOutboundScreenGateForTests","screenTenantMessage","input","label","answer","workspace","hostId","verdict","subject","fromName","fromAddress","replyTo","bodies","ownNames","ownDomains","reputation","filter","Boolean","join","holding","signals","ageDays","owed","length","console","warn","String","context","releasedReviewId","error","outcome","reference","cited","detail"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,SAASA,qBAAqB,QAAQ,uBAAmB;AACzD,SACEC,WAAW,EAEXC,mBAAmB,EACnBC,eAAe,QACV,gCAA4B;AA4CnC,IAAIC,gBAA2C;AAE/C,6EAA6E,GAC7E,OAAO,SAASC,sBAAsBC,IAA+B;IACnEF,gBAAgBE;AAClB;AAEA,iEAAiE,GACjE,OAAO,SAASC;IACd,OAAOH;AACT;AAEA,0CAA0C,GAC1C,OAAO,SAASI;IACdJ,gBAAgB;AAClB;AAyBA;;;;;;;;;;;;;;CAcC,GACD,OAAO,eAAeK,oBACpBC,KAA+B,EAC/BC,QAAQ,OAAO;QAMHD,iBACGA,oBACJA,gBAqCOE;IA3ClB,MAAM,EAAEC,SAAS,EAAE,GAAGH;IACtB,IAAI,EAACG,6BAAAA,UAAWC,MAAM,GAAE,OAAO;IAC/B,MAAMC,UAAUb,oBAAoB;QAClCc,SAASN,MAAMM,OAAO;QACtBC,QAAQ,GAAEP,kBAAAA,MAAMO,QAAQ,YAAdP,kBAAk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AAK,QAAQ,OAAO;IACjD,MAAMC,aAAY3B,oBAAAA,OAAO2B,SAAS,YAAhB3B,oBAAoB;IACtC,MAAM4B,QAAQD,YAAY,CAAC,EAAE,EAAEA,UAAU,CAAC,CAAC,GAAG;IAC9C,OAAO;QACLD,SAAS1B,OAAO0B,OAAO;QACvBC;QACAE,QACE7B,OAAO0B,OAAO,KAAK,aACf,CAAC,oDAAoD,EAAEE,MAAM,qBAAqB,CAAC,GACnF,4EACA,CAAC,QAAQ,EAAEA,MAAM,mBAAmB,CAAC;IAC7C;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/outbound-screen-gate.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 OUTBOUND SCREEN ON THE SEND SEAM (AGL-3362).\n *\n * Every tenant message leaves through `sendEmail`, and every tenant sender\n * but the campaign core resolves its identity through `hostSendingIdentity`,\n * which stamps the verdict with the {@link SendingWorkspace} it read. So the\n * screen is asked HERE, once, for the CRM's one-off mail, inbox replies,\n * newsletters, member posts, cart and restock sweeps, flow steps, receipts —\n * and any marketplace plugin that sends for a site — with no copy of it in\n * any of them.\n *\n * Split the way the governor, the marketing gate and the deliverability\n * preflight are: the DECISION is pure and lives in this library\n * (`screenOutboundEmail` finds signals, `signalsThatHold` applies the tiers);\n * what a hold WRITES — the abuse-queue row, the staff alert, the release\n * lookup — is a store, so it is injected by `@aglyn/tenant-data-admin`\n * through {@link setOutboundScreenGate}. The gate is only called when a\n * signal holds, so a clean message costs no read.\n *\n * Nothing installed is UNGATED, the governor's posture: a deployment that\n * never installs the store must still send.\n *=========================================*/\n\nimport { linkReputationSignals } from './link-reputation'\nimport {\n linkUrlsIn,\n type PhishingScreenSignal,\n screenOutboundEmail,\n signalsThatHold,\n} from './outbound-phishing-screen'\n\n/**\n * The workspace a tenant message belongs to, as the screen needs it. Stamped\n * on the sending identity by `hostSendingIdentity` from the host and org\n * documents it already reads, so the screen costs no read of its own.\n */\nexport interface SendingWorkspace {\n hostId: string\n orgId: string | null\n /** Days since the org was created; `null` when unreadable (an existing customer). */\n ageDays: number | null\n /** The org's and site's names and the subdomain — a brand in one is its own. */\n ownNames: string[]\n /** The site's hosts — a link to one is never \"elsewhere\". */\n ownDomains: string[]\n}\n\nexport interface OutboundScreenGateRequest {\n workspace: SendingWorkspace\n /** The signals that HOLD, after the tiers. Never empty. */\n signals: PhishingScreenSignal[]\n subject: string\n fromName: string | null\n /** The sender's `context`, so the reviewer can tell which feature sent it. */\n context: string | null\n /**\n * A review row a caller's own screen held and staff RELEASED for this\n * content (a campaign, an automation step). The gate honors it only when\n * that row really is a release for this site — a caller cannot mint one.\n */\n releasedReviewId: string | null\n}\n\nexport interface OutboundScreenGateVerdict {\n outcome: 'send' | 'held' | 'rejected'\n /** The `HS-…` reference staff and the merchant quote. */\n reference?: string | null\n}\n\nexport type OutboundScreenGate = (\n request: OutboundScreenGateRequest,\n) => Promise<OutboundScreenGateVerdict>\n\nlet installedGate: OutboundScreenGate | null = null\n\n/** Installs the durable gate. Called once, from `@aglyn/tenant-data-admin`. */\nexport function setOutboundScreenGate(gate: OutboundScreenGate | null): void {\n installedGate = gate\n}\n\n/** The installed gate, or null when nothing has been installed. */\nexport function getOutboundScreenGate(): OutboundScreenGate | null {\n return installedGate\n}\n\n/** Test seam: forget any installed gate. */\nexport function resetOutboundScreenGateForTests(): void {\n installedGate = null\n}\n\nexport interface TenantMessageScreenInput {\n workspace: SendingWorkspace\n subject: string\n fromName?: string | null\n /** The address it leaves from — a lookalike `From:` domain holds for everyone. */\n fromAddress?: string | null\n replyTo?: string | readonly string[] | null\n /** Everything the recipient reads or clicks: the text part, the HTML. */\n bodies: readonly (string | null | undefined)[]\n /** The recipient's own act made this owed (see `SendEmailOptions.owedFor`). */\n owed?: boolean\n context?: string | null\n releasedReviewId?: string | null\n}\n\n/** Why a tenant message may not leave. */\nexport interface TenantMessageScreenRefusal {\n outcome: 'held' | 'rejected'\n reference: string | null\n /** The sentence a merchant reads. */\n detail: string\n}\n\n/**\n * Screen one tenant message: the pure screen, the reputation of every\n * foreign host it links to (AGL-3451), the tiers, then — only when a signal\n * holds — the installed gate, which files or reads the review row. `null`\n * when it may go.\n *\n * The ONE door for every transport. `sendEmail` asks it for every message a\n * site sends through the platform's provider, and a sender on another\n * transport (Outreach's connected mailboxes) asks it the same way, so a\n * second transport is not a second screen.\n *\n * Fails OPEN on a gate that is missing, throws or answers nothing, the\n * posture of every other control on the send path: an outage on the review\n * queue must not become an outage on every site's mail.\n */\nexport async function screenTenantMessage(\n input: TenantMessageScreenInput,\n label = 'email',\n): Promise<TenantMessageScreenRefusal | null> {\n const { workspace } = input\n if (!workspace?.hostId) return null\n const verdict = screenOutboundEmail({\n subject: input.subject,\n fromName: input.fromName ?? null,\n fromAddress: input.fromAddress ?? null,\n replyTo: input.replyTo ?? null,\n bodies: input.bodies,\n ownNames: workspace.ownNames,\n ownDomains: workspace.ownDomains,\n })\n // Every foreign link the message carries, against the reputation list\n // (AGL-3451): its host, and in 'url' mode its address (AGL-3459). A\n // listing is a strong signal; a lookup that fails is none. Nothing\n // installed looks nothing up.\n const reputation = await linkReputationSignals(\n linkUrlsIn([input.subject, ...input.bodies].filter(Boolean).join('\\n')),\n { ownDomains: workspace.ownDomains },\n )\n const holding = signalsThatHold([...verdict.signals, ...reputation], {\n ageDays: workspace.ageDays,\n owed: input.owed === true,\n })\n if (!holding.length) return null\n const gate = getOutboundScreenGate()\n if (!gate) {\n console.warn(`${label} matched the phishing screen, and no review store is installed — allowing`)\n return null\n }\n let answer: OutboundScreenGateVerdict | null\n try {\n answer = await gate({\n workspace,\n signals: holding,\n subject: String(input.subject ?? ''),\n fromName: input.fromName ?? null,\n context: input.context ?? null,\n releasedReviewId: input.releasedReviewId ?? null,\n })\n } catch (error) {\n console.error(`${label} phishing review failed — allowing`, error)\n answer = null\n }\n if (!answer || answer.outcome === 'send') return null\n const reference = answer.reference ?? null\n const cited = reference ? ` (${reference})` : ''\n return {\n outcome: answer.outcome,\n reference,\n detail:\n answer.outcome === 'rejected'\n ? `Staff review rejected email like this from this site${cited}, so it was not sent.`\n : 'This email is held for staff review because it may impersonate another ' +\n `business${cited}. Nothing was sent.`,\n }\n}\n"],"names":["linkReputationSignals","linkUrlsIn","screenOutboundEmail","signalsThatHold","installedGate","setOutboundScreenGate","gate","getOutboundScreenGate","resetOutboundScreenGateForTests","screenTenantMessage","input","label","answer","workspace","hostId","verdict","subject","fromName","fromAddress","replyTo","bodies","ownNames","ownDomains","reputation","filter","Boolean","join","holding","signals","ageDays","owed","length","console","warn","String","context","releasedReviewId","error","outcome","reference","cited","detail"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,SAASA,qBAAqB,QAAQ,uBAAmB;AACzD,SACEC,UAAU,EAEVC,mBAAmB,EACnBC,eAAe,QACV,gCAA4B;AA4CnC,IAAIC,gBAA2C;AAE/C,6EAA6E,GAC7E,OAAO,SAASC,sBAAsBC,IAA+B;IACnEF,gBAAgBE;AAClB;AAEA,iEAAiE,GACjE,OAAO,SAASC;IACd,OAAOH;AACT;AAEA,0CAA0C,GAC1C,OAAO,SAASI;IACdJ,gBAAgB;AAClB;AAyBA;;;;;;;;;;;;;;CAcC,GACD,OAAO,eAAeK,oBACpBC,KAA+B,EAC/BC,QAAQ,OAAO;QAMHD,iBACGA,oBACJA,gBAsCOE;IA5ClB,MAAM,EAAEC,SAAS,EAAE,GAAGH;IACtB,IAAI,EAACG,6BAAAA,UAAWC,M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F,EAAE,OAAO2B,OAAO;QACdL,QAAQK,KAAK,CAAC,GAAG1B,MAAM,kCAAkC,CAAC,EAAE0B;QAC5DzB,SAAS;IACX;IACA,IAAI,CAACA,UAAUA,OAAO0B,OAAO,KAAK,QAAQ,OAAO;IACjD,MAAMC,aAAY3B,oBAAAA,OAAO2B,SAAS,YAAhB3B,oBAAoB;IACtC,MAAM4B,QAAQD,YAAY,CAAC,EAAE,EAAEA,UAAU,CAAC,CAAC,GAAG;IAC9C,OAAO;QACLD,SAAS1B,OAAO0B,OAAO;QACvBC;QACAE,QACE7B,OAAO0B,OAAO,KAAK,aACf,CAAC,oDAAoD,EAAEE,MAAM,qBAAqB,CAAC,GACnF,4EACA,CAAC,QAAQ,EAAEA,MAAM,mBAAmB,CAAC;IAC7C;AACF"}
@@ -798,7 +798,7 @@ const CANNOT_SIGN_IN = 'If you cannot sign in, reply to this email or write to {
798
798
  },
799
799
  staff: {
800
800
  title: 'Platform billing fraud signal',
801
- summary: '{{staff.evidence}} Workspace {{workspace.name}}, {{amount}}, on {{occurredAt}}. Nothing has been refunded or canceled. Reference {{reference}}.',
801
+ summary: '{{staff.evidence}} Workspace {{workspace.name}}, {{amount}}, on {{occurredAt}}. This alert refunded and canceled nothing. Reference {{reference}}.',
802
802
  actions: [
803
803
  'staff-open-row',
804
804
  'staff-open-stripe',