@aglyn/shared-util-email 1.0.0-beta.200 → 1.0.0-beta.201
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/src/index.d.ts +6 -0
- package/src/index.js +16 -0
- package/src/index.js.map +1 -1
- package/src/lib/email-deliverability.d.ts +200 -0
- package/src/lib/email-deliverability.js +461 -0
- package/src/lib/email-deliverability.js.map +1 -0
- package/src/lib/email-delivery-events.d.ts +16 -39
- package/src/lib/email-delivery-events.js +28 -12
- package/src/lib/email-delivery-events.js.map +1 -1
- package/src/lib/hosted-page-screen.d.ts +60 -0
- package/src/lib/hosted-page-screen.js +314 -0
- package/src/lib/hosted-page-screen.js.map +1 -0
- package/src/lib/mail-bounce.d.ts +42 -0
- package/src/lib/mail-bounce.js +108 -0
- package/src/lib/mail-bounce.js.map +1 -0
- package/src/lib/mail-gateway.d.ts +161 -0
- package/src/lib/mail-gateway.js +330 -0
- package/src/lib/mail-gateway.js.map +1 -0
- package/src/lib/outbound-phishing-screen.d.ts +220 -0
- package/src/lib/outbound-phishing-screen.js +719 -0
- package/src/lib/outbound-phishing-screen.js.map +1 -0
- package/src/lib/outbound-screen-gate.d.ts +95 -0
- package/src/lib/outbound-screen-gate.js +109 -0
- package/src/lib/outbound-screen-gate.js.map +1 -0
- package/src/lib/send-email.d.ts +79 -1
- package/src/lib/send-email.js +153 -10
- package/src/lib/send-email.js.map +1 -1
- package/src/lib/sending-domain.d.ts +22 -1
- package/src/lib/sending-domain.js +0 -95
- package/src/lib/sending-domain.js.map +1 -1
|
@@ -0,0 +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 * three 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 *\n * Mentioning a brand, alone, never holds.\n *\n * ## The brand list is small on purpose\n *\n * The brands phishing kits most often wear, plus the two in the incident. A\n * brand is added when it has been seen impersonated, not because it is big:\n * every entry is a set of 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`) 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\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 mention: /\\bmicrosoft\\b|\\boffice\\s?365\\b|\\bonedrive\\b|\\bsharepoint\\b/i,\n hostTokens: ['microsoft', 'office365', 'onedrive', 'sharepoint', 'microsoftonline', 'msonline'],\n officialDomains: [\n 'microsoft.com',\n 'office.com',\n 'office365.com',\n 'live.com',\n 'outlook.com',\n 'microsoftonline.com',\n 'sharepoint.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: '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\n/**\n * Account-action and credential phrasing — the half of a lure that asks the\n * reader to DO something with an account. Only ever counted beside a brand\n * AND a foreign link; alone, several of these are ordinary transactional copy.\n */\nexport const PHISHING_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+)?(?:suspended|locked|limited|restricted|disabled|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 /\\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 /\\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 /\\bpassword\\s+(?:will\\s+)?expire/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 /\\bsecurity\\s+alert\\b/i,\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\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/** 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/** 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 for (const brand of PHISHING_SCREEN_BRANDS) {\n if (isOfficialDomain(brand, 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 (`.` for a dot, `&` 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(/&/gi, '&')\n}\n\nfunction safeCodePoint(value: number): string {\n return Number.isFinite(value) && value > 0 && value <= 0x10ffff\n ? String.fromCodePoint(value)\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\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 copy = [input.subject, input.preheader, ...(input.bodies ?? [])]\n .filter((part): part is string => typeof part === 'string' && part.length > 0)\n .join('\\n')\n const decodedCopy = decodeEntities(copy)\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) {\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 lure = PHISHING_LURE_PATTERNS.map((pattern) => decodedCopy.match(pattern)?.[0])\n .find(Boolean)\n if (lure) {\n const foreign = linkHosts.find((host) => {\n if (isOwnHost(host)) return false\n const registrable = registrableDomain(host)\n return !isAnyOfficialDomain(registrable) && !COMMON_LINK_DOMAINS.has(registrable)\n })\n if (foreign) {\n const namedInCopy = `${decodedCopy}\\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 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/** 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 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 * - 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. Each is shaped\n * like phishing but also like a clumsy legitimate message, 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`.\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])\n\nexport function phishingSignalTier(signal: { code: string }): PhishingSignalTier {\n return STRONG_PHISHING_SIGNAL_CODES.has(signal?.code) ? 'strong' : 'soft'\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 }>(\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"],"names":["PHISHING_SCREEN_BRANDS","id","label","mention","hostTokens","officialDomains","countryDomains","wordToken","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","isAnyOfficialDomain","some","foldLeet","labelNamesBrand","token","candidate","parts","tokenParts","at","every","part","offset","lookalikeBrandForHost","normalized","primary","startsWith","decodeEntities","text","_","hex","safeCodePoint","parseInt","dec","value","Number","isFinite","fromCodePoint","URL_PATTERN","linkHostsIn","hosts","match","rest","lastIndexOf","disguise","add","ADDRESS_HOST_PATTERN","addressHostsIn","matchAll","squash","isOwnBrand","ownNames","ownRegistrables","map","squashScreenText","isWorkspaceOwnBrand","isAnyOfficialBrandDomain","isCommonLinkDomain","screenOutboundEmail","input","signals","ownHosts","ownDomains","domain","trim","isOwnHost","own","endsWith","copy","subject","preheader","bodies","decodedCopy","replyTo","Array","isArray","linkHosts","seenLookalike","fromAddress","push","code","fromName","lure","pattern","find","foreign","namedInCopy","hold","phishingScreenBrandLabel","describePhishingScreenSignals","signal","field","action","OUTBOUND_REVIEW_YOUNG_DAYS","STRONG_PHISHING_SIGNAL_CODES","phishingSignalTier","isYoungWorkspaceAge","ageDays","signalsThatHold","policy","soft","owed","BRAND_IMPERSONATION_WORDS","brandForSubdomainLabel","apex","byHost","words","word"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,KAAa,EACb+H,OAAO,iBAAiB;IAExB,MAAMhF,aAAalC,OAAOb,gBAAAA,QAAS,IAAIuF,IAAI,GAAGzE,WAAW;IACzD,IAAI,CAACiC,YAAY,OAAO;IACxB,MAAMiF,SAASlF,sBAAsB,GAAGC,WAAW,CAAC,EAAEgF,MAAM;IAC5D,IAAIC,QAAQ,OAAOA;IACnB,MAAMxF,QAAQJ,SAASW,YAAY/B,KAAK,CAAC,KAAKC,MAAM,CAACC;IACrD,IAAIsB,MAAMrB,MAAM,GAAG,KAAK,CAACqB,MAAML,IAAI,CAAC,CAACS,OAASiF,0BAA0BtG,GAAG,CAACqB,QAAQ;QAClF,OAAO;IACT;IACA,KAAK,MAAMd,SAAShC,uBAAwB;QAC1C,MAAMmI,QAAQ;YAACnG,MAAM/B,EAAE;eAAK+B,MAAM5B,UAAU;SAAC,CAACe,MAAM,CAAC,CAACiH,OAAS,CAACA,KAAKnG,QAAQ,CAAC;QAC9E,IAAIS,MAAML,IAAI,CAAC,CAACS,OAASqF,MAAMlG,QAAQ,CAACa,QAAQ,OAAOd;IACzD;IACA,OAAO;AACT"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { type PhishingScreenSignal } from './outbound-phishing-screen';
|
|
18
|
+
/**
|
|
19
|
+
* The workspace a tenant message belongs to, as the screen needs it. Stamped
|
|
20
|
+
* on the sending identity by `hostSendingIdentity` from the host and org
|
|
21
|
+
* documents it already reads, so the screen costs no read of its own.
|
|
22
|
+
*/
|
|
23
|
+
export interface SendingWorkspace {
|
|
24
|
+
hostId: string;
|
|
25
|
+
orgId: string | null;
|
|
26
|
+
/** Days since the org was created; `null` when unreadable (an existing customer). */
|
|
27
|
+
ageDays: number | null;
|
|
28
|
+
/** The org's and site's names and the subdomain — a brand in one is its own. */
|
|
29
|
+
ownNames: string[];
|
|
30
|
+
/** The site's hosts — a link to one is never "elsewhere". */
|
|
31
|
+
ownDomains: string[];
|
|
32
|
+
}
|
|
33
|
+
export interface OutboundScreenGateRequest {
|
|
34
|
+
workspace: SendingWorkspace;
|
|
35
|
+
/** The signals that HOLD, after the tiers. Never empty. */
|
|
36
|
+
signals: PhishingScreenSignal[];
|
|
37
|
+
subject: string;
|
|
38
|
+
fromName: string | null;
|
|
39
|
+
/** The sender's `context`, so the reviewer can tell which feature sent it. */
|
|
40
|
+
context: string | null;
|
|
41
|
+
/**
|
|
42
|
+
* A review row a caller's own screen held and staff RELEASED for this
|
|
43
|
+
* content (a campaign, an automation step). The gate honors it only when
|
|
44
|
+
* that row really is a release for this site — a caller cannot mint one.
|
|
45
|
+
*/
|
|
46
|
+
releasedReviewId: string | null;
|
|
47
|
+
}
|
|
48
|
+
export interface OutboundScreenGateVerdict {
|
|
49
|
+
outcome: 'send' | 'held' | 'rejected';
|
|
50
|
+
/** The `HS-…` reference staff and the merchant quote. */
|
|
51
|
+
reference?: string | null;
|
|
52
|
+
}
|
|
53
|
+
export type OutboundScreenGate = (request: OutboundScreenGateRequest) => Promise<OutboundScreenGateVerdict>;
|
|
54
|
+
/** Installs the durable gate. Called once, from `@aglyn/tenant-data-admin`. */
|
|
55
|
+
export declare function setOutboundScreenGate(gate: OutboundScreenGate | null): void;
|
|
56
|
+
/** The installed gate, or null when nothing has been installed. */
|
|
57
|
+
export declare function getOutboundScreenGate(): OutboundScreenGate | null;
|
|
58
|
+
/** Test seam: forget any installed gate. */
|
|
59
|
+
export declare function resetOutboundScreenGateForTests(): void;
|
|
60
|
+
export interface TenantMessageScreenInput {
|
|
61
|
+
workspace: SendingWorkspace;
|
|
62
|
+
subject: string;
|
|
63
|
+
fromName?: string | null;
|
|
64
|
+
/** The address it leaves from — a lookalike `From:` domain holds for everyone. */
|
|
65
|
+
fromAddress?: string | null;
|
|
66
|
+
replyTo?: string | readonly string[] | null;
|
|
67
|
+
/** Everything the recipient reads or clicks: the text part, the HTML. */
|
|
68
|
+
bodies: readonly (string | null | undefined)[];
|
|
69
|
+
/** The recipient's own act made this owed (see `SendEmailOptions.owedFor`). */
|
|
70
|
+
owed?: boolean;
|
|
71
|
+
context?: string | null;
|
|
72
|
+
releasedReviewId?: string | null;
|
|
73
|
+
}
|
|
74
|
+
/** Why a tenant message may not leave. */
|
|
75
|
+
export interface TenantMessageScreenRefusal {
|
|
76
|
+
outcome: 'held' | 'rejected';
|
|
77
|
+
reference: string | null;
|
|
78
|
+
/** The sentence a merchant reads. */
|
|
79
|
+
detail: string;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Screen one tenant message: the pure screen, its tiers, then — only when a
|
|
83
|
+
* signal holds — the installed gate, which files or reads the review row.
|
|
84
|
+
* `null` when it may go.
|
|
85
|
+
*
|
|
86
|
+
* The ONE door for every transport. `sendEmail` asks it for every message a
|
|
87
|
+
* site sends through the platform's provider, and a sender on another
|
|
88
|
+
* transport (Outreach's connected mailboxes) asks it the same way, so a
|
|
89
|
+
* second transport is not a second screen.
|
|
90
|
+
*
|
|
91
|
+
* Fails OPEN on a gate that is missing, throws or answers nothing, the
|
|
92
|
+
* posture of every other control on the send path: an outage on the review
|
|
93
|
+
* queue must not become an outage on every site's mail.
|
|
94
|
+
*/
|
|
95
|
+
export declare function screenTenantMessage(input: TenantMessageScreenInput, label?: string): Promise<TenantMessageScreenRefusal | null>;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ /*==========================================
|
|
17
|
+
* THE OUTBOUND SCREEN ON THE SEND SEAM (AGL-3362).
|
|
18
|
+
*
|
|
19
|
+
* Every tenant message leaves through `sendEmail`, and every tenant sender
|
|
20
|
+
* but the campaign core resolves its identity through `hostSendingIdentity`,
|
|
21
|
+
* which stamps the verdict with the {@link SendingWorkspace} it read. So the
|
|
22
|
+
* screen is asked HERE, once, for the CRM's one-off mail, inbox replies,
|
|
23
|
+
* newsletters, member posts, cart and restock sweeps, flow steps, receipts —
|
|
24
|
+
* and any marketplace plugin that sends for a site — with no copy of it in
|
|
25
|
+
* any of them.
|
|
26
|
+
*
|
|
27
|
+
* Split the way the governor, the marketing gate and the deliverability
|
|
28
|
+
* preflight are: the DECISION is pure and lives in this library
|
|
29
|
+
* (`screenOutboundEmail` finds signals, `signalsThatHold` applies the tiers);
|
|
30
|
+
* what a hold WRITES — the abuse-queue row, the staff alert, the release
|
|
31
|
+
* lookup — is a store, so it is injected by `@aglyn/tenant-data-admin`
|
|
32
|
+
* through {@link setOutboundScreenGate}. The gate is only called when a
|
|
33
|
+
* signal holds, so a clean message costs no read.
|
|
34
|
+
*
|
|
35
|
+
* Nothing installed is UNGATED, the governor's posture: a deployment that
|
|
36
|
+
* never installs the store must still send.
|
|
37
|
+
*=========================================*/ import { screenOutboundEmail, signalsThatHold } from "./outbound-phishing-screen.js";
|
|
38
|
+
let installedGate = null;
|
|
39
|
+
/** Installs the durable gate. Called once, from `@aglyn/tenant-data-admin`. */ export function setOutboundScreenGate(gate) {
|
|
40
|
+
installedGate = gate;
|
|
41
|
+
}
|
|
42
|
+
/** The installed gate, or null when nothing has been installed. */ export function getOutboundScreenGate() {
|
|
43
|
+
return installedGate;
|
|
44
|
+
}
|
|
45
|
+
/** Test seam: forget any installed gate. */ export function resetOutboundScreenGateForTests() {
|
|
46
|
+
installedGate = null;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Screen one tenant message: the pure screen, its tiers, then — only when a
|
|
50
|
+
* signal holds — the installed gate, which files or reads the review row.
|
|
51
|
+
* `null` when it may go.
|
|
52
|
+
*
|
|
53
|
+
* The ONE door for every transport. `sendEmail` asks it for every message a
|
|
54
|
+
* site sends through the platform's provider, and a sender on another
|
|
55
|
+
* transport (Outreach's connected mailboxes) asks it the same way, so a
|
|
56
|
+
* second transport is not a second screen.
|
|
57
|
+
*
|
|
58
|
+
* Fails OPEN on a gate that is missing, throws or answers nothing, the
|
|
59
|
+
* posture of every other control on the send path: an outage on the review
|
|
60
|
+
* queue must not become an outage on every site's mail.
|
|
61
|
+
*/ export async function screenTenantMessage(input, label = 'email') {
|
|
62
|
+
var _input_fromName, _input_fromAddress, _input_replyTo, _answer_reference;
|
|
63
|
+
const { workspace } = input;
|
|
64
|
+
if (!(workspace == null ? void 0 : workspace.hostId)) return null;
|
|
65
|
+
const verdict = screenOutboundEmail({
|
|
66
|
+
subject: input.subject,
|
|
67
|
+
fromName: (_input_fromName = input.fromName) != null ? _input_fromName : null,
|
|
68
|
+
fromAddress: (_input_fromAddress = input.fromAddress) != null ? _input_fromAddress : null,
|
|
69
|
+
replyTo: (_input_replyTo = input.replyTo) != null ? _input_replyTo : null,
|
|
70
|
+
bodies: input.bodies,
|
|
71
|
+
ownNames: workspace.ownNames,
|
|
72
|
+
ownDomains: workspace.ownDomains
|
|
73
|
+
});
|
|
74
|
+
const holding = signalsThatHold(verdict.signals, {
|
|
75
|
+
ageDays: workspace.ageDays,
|
|
76
|
+
owed: input.owed === true
|
|
77
|
+
});
|
|
78
|
+
if (!holding.length) return null;
|
|
79
|
+
const gate = getOutboundScreenGate();
|
|
80
|
+
if (!gate) {
|
|
81
|
+
console.warn(`${label} matched the phishing screen, and no review store is installed — allowing`);
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
let answer;
|
|
85
|
+
try {
|
|
86
|
+
var _input_subject, _input_fromName1, _input_context, _input_releasedReviewId;
|
|
87
|
+
answer = await gate({
|
|
88
|
+
workspace,
|
|
89
|
+
signals: holding,
|
|
90
|
+
subject: String((_input_subject = input.subject) != null ? _input_subject : ''),
|
|
91
|
+
fromName: (_input_fromName1 = input.fromName) != null ? _input_fromName1 : null,
|
|
92
|
+
context: (_input_context = input.context) != null ? _input_context : null,
|
|
93
|
+
releasedReviewId: (_input_releasedReviewId = input.releasedReviewId) != null ? _input_releasedReviewId : null
|
|
94
|
+
});
|
|
95
|
+
} catch (error) {
|
|
96
|
+
console.error(`${label} phishing review failed — allowing`, error);
|
|
97
|
+
answer = null;
|
|
98
|
+
}
|
|
99
|
+
if (!answer || answer.outcome === 'send') return null;
|
|
100
|
+
const reference = (_answer_reference = answer.reference) != null ? _answer_reference : null;
|
|
101
|
+
const cited = reference ? ` (${reference})` : '';
|
|
102
|
+
return {
|
|
103
|
+
outcome: answer.outcome,
|
|
104
|
+
reference,
|
|
105
|
+
detail: answer.outcome === 'rejected' ? `Staff review rejected email like this from this site${cited}, so it was not sent.` : 'This email is held for staff review because it may impersonate another ' + `business${cited}. Nothing was sent.`
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
//# sourceMappingURL=outbound-screen-gate.js.map
|
|
@@ -0,0 +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 {\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, its tiers, then — only when a\n * signal holds — the installed gate, which files or reads the review row.\n * `null` 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 const holding = signalsThatHold(verdict.signals, {\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":["screenOutboundEmail","signalsThatHold","installedGate","setOutboundScreenGate","gate","getOutboundScreenGate","resetOutboundScreenGateForTests","screenTenantMessage","input","label","answer","workspace","hostId","verdict","subject","fromName","fromAddress","replyTo","bodies","ownNames","ownDomains","holding","signals","ageDays","owed","length","console","warn","String","context","releasedReviewId","error","outcome","reference","cited","detail"],"mapp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SAASD;YACTP,SAASc,QAAOpB,iBAAAA,MAAMM,OAAO,YAAbN,iBAAiB;YACjCO,QAAQ,GAAEP,mBAAAA,MAAMO,QAAQ,YAAdP,mBAAkB;YAC5BqB,OAAO,GAAErB,iBAAAA,MAAMqB,OAAO,YAAbrB,iBAAiB;YAC1BsB,gBAAgB,GAAEtB,0BAAAA,MAAMsB,gBAAgB,YAAtBtB,0BAA0B;QAC9C;IACF,EAAE,OAAOuB,OAAO;QACdL,QAAQK,KAAK,CAAC,GAAGtB,MAAM,kCAAkC,CAAC,EAAEsB;QAC5DrB,SAAS;IACX;IACA,IAAI,CAACA,UAAUA,OAAOsB,OAAO,KAAK,QAAQ,OAAO;IACjD,MAAMC,aAAYvB,oBAAAA,OAAOuB,SAAS,YAAhBvB,oBAAoB;IACtC,MAAMwB,QAAQD,YAAY,CAAC,EAAE,EAAEA,UAAU,CAAC,CAAC,GAAG;IAC9C,OAAO;QACLD,SAAStB,OAAOsB,OAAO;QACvBC;QACAE,QACEzB,OAAOsB,OAAO,KAAK,aACf,CAAC,oDAAoD,EAAEE,MAAM,qBAAqB,CAAC,GACnF,4EACA,CAAC,QAAQ,EAAEA,MAAM,mBAAmB,CAAC;IAC7C;AACF"}
|
package/src/lib/send-email.d.ts
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
import { type EmailSendPriority } from './send-rate';
|
|
25
25
|
import { type SendingIdentityAudience, type SendingIdentityVerdict } from './sending-domain';
|
|
26
26
|
import { type MarketingSendContext } from './marketing-send';
|
|
27
|
+
import { type EmailSendPurpose } from './email-deliverability';
|
|
27
28
|
export declare const RESEND_SEND_ENDPOINT = "https://api.resend.com/emails";
|
|
28
29
|
/** A Resend delivery tag, used for webhook attribution (AGL-268). */
|
|
29
30
|
export interface EmailTag {
|
|
@@ -123,6 +124,27 @@ export interface SendEmailOptions {
|
|
|
123
124
|
* first, and would ask the gate about one of them. Callers fan out.
|
|
124
125
|
*/
|
|
125
126
|
marketing?: MarketingSendContext;
|
|
127
|
+
/**
|
|
128
|
+
* What the RECIPIENT did that makes this message owed to them (AGL-3356):
|
|
129
|
+
* `order` — a receipt, a gift card, a shipping notice for something they
|
|
130
|
+
* bought; `booking` — a confirmation, reminder or change to something they
|
|
131
|
+
* booked; `account` — a password reset or sign-in link they asked for.
|
|
132
|
+
*
|
|
133
|
+
* The outbound phishing screen's SOFT rules never hold an owed message; a
|
|
134
|
+
* lookalike link still does, because a receipt that links to a brand's
|
|
135
|
+
* disguise is the disguise. Omitted — the default, and the one a forgotten
|
|
136
|
+
* caller gets — the message is treated as merchant-authored and every
|
|
137
|
+
* tier applies. A MARKETING message is never owed, whatever it declares.
|
|
138
|
+
*/
|
|
139
|
+
owedFor?: 'order' | 'booking' | 'account';
|
|
140
|
+
/**
|
|
141
|
+
* A review row that the caller's own screen held and staff RELEASED for
|
|
142
|
+
* exactly this content — a campaign put back on the clock, an automation
|
|
143
|
+
* step whose hold was dismissed. The send seam's screen honors it only
|
|
144
|
+
* after confirming, through the installed gate, that it is a release for
|
|
145
|
+
* this site; naming a row is not a way past the screen.
|
|
146
|
+
*/
|
|
147
|
+
releasedReviewId?: string | null;
|
|
126
148
|
}
|
|
127
149
|
/**
|
|
128
150
|
* The `context` tag, attached to every send (AGL-2407).
|
|
@@ -239,7 +261,41 @@ export type SendEmailFailureReason = 'unconfigured' | 'no-recipient'
|
|
|
239
261
|
* forever. Nothing about the recipient has been reduced; the next message
|
|
240
262
|
* after they open anything goes.
|
|
241
263
|
*/
|
|
242
|
-
| 'unengaged'
|
|
264
|
+
| 'unengaged'
|
|
265
|
+
/**
|
|
266
|
+
* The recipient's domain takes no mail — no MX and no address record, or
|
|
267
|
+
* an RFC 7505 null MX — so the message would only have bounced
|
|
268
|
+
* (AGL-3328). Refused for every purpose, transactional included, before
|
|
269
|
+
* the provider was called; the address is suppressed with a reason of its
|
|
270
|
+
* own. Terminal: the preflight answers the same until the domain's DNS
|
|
271
|
+
* changes, which it re-reads daily.
|
|
272
|
+
*/
|
|
273
|
+
| 'undeliverable'
|
|
274
|
+
/**
|
|
275
|
+
* A BULK or cold message whose recipient sits behind a mail gateway that
|
|
276
|
+
* refused this sending domain twice in thirty days and delivered nothing
|
|
277
|
+
* (AGL-3328). Terminal for this message rather than deferrable: the hold
|
|
278
|
+
* lifts when the gateway delivers again or the refusals age out, which is
|
|
279
|
+
* not something a sweep's next beat can wait out. Mail the recipient asked
|
|
280
|
+
* for is never held.
|
|
281
|
+
*/
|
|
282
|
+
| 'gateway-held'
|
|
283
|
+
/**
|
|
284
|
+
* The site or workspace this message belongs to is under a full lockdown
|
|
285
|
+
* (AGL-3356), carried in on its sending identity. Terminal for this
|
|
286
|
+
* message: a sweep that holds work across a suspension skips the host
|
|
287
|
+
* before it gets here, so a caller that reaches this refusal is one with
|
|
288
|
+
* no way to come back, and retrying would only ask the same question.
|
|
289
|
+
*/
|
|
290
|
+
| 'suspended'
|
|
291
|
+
/**
|
|
292
|
+
* The outbound phishing screen held this message for staff review, or
|
|
293
|
+
* staff already rejected a message carrying the same signals from this
|
|
294
|
+
* site (AGL-3356). Nothing was attempted. Terminal for this message:
|
|
295
|
+
* `detail` names the `HS-…` reference, and once staff release the review
|
|
296
|
+
* the site's next message carrying the same signals sends.
|
|
297
|
+
*/
|
|
298
|
+
| 'held-for-review';
|
|
243
299
|
export type SendEmailResult = {
|
|
244
300
|
sent: true;
|
|
245
301
|
id: string | null;
|
|
@@ -312,6 +368,28 @@ export declare function sendFailureReason(result: SendEmailResult | null | undef
|
|
|
312
368
|
* {@link rateLimitedRetryAtMs} beside it is one.
|
|
313
369
|
*/
|
|
314
370
|
export declare function isDeferrableSendResult(result: SendEmailResult | null | undefined): boolean;
|
|
371
|
+
/**
|
|
372
|
+
* Who a message is for, as the deliverability preflight reads it
|
|
373
|
+
* (AGL-3328): `bulk` for anything a control may already refuse — marketing
|
|
374
|
+
* by either of its two marks, a campaign, a resumable sweep — and
|
|
375
|
+
* `transactional` for the rest, which a gateway hold never touches.
|
|
376
|
+
*
|
|
377
|
+
* Derived from what a sender already declares, for the reason
|
|
378
|
+
* `isMarketingMessage` is: a label callers had to remember would be
|
|
379
|
+
* forgotten by the one that matters, and the permissive answer is the one a
|
|
380
|
+
* forgotten caller gets.
|
|
381
|
+
*/
|
|
382
|
+
export declare function emailSendPurpose(options: Pick<SendEmailOptions, 'priority' | 'context' | 'headers'> & {
|
|
383
|
+
marketing?: unknown;
|
|
384
|
+
}): EmailSendPurpose;
|
|
385
|
+
/**
|
|
386
|
+
* The send seam's half of the outbound phishing screen (AGL-3356): every
|
|
387
|
+
* message a SITE sends whose identity carries the workspace
|
|
388
|
+
* `hostSendingIdentity` stamped, through {@link screenTenantMessage} — the
|
|
389
|
+
* pure screen, its tiers, and the installed review store. `null` when the
|
|
390
|
+
* message may go; fails open, as that function documents.
|
|
391
|
+
*/
|
|
392
|
+
export declare function askOutboundScreen(options: SendEmailOptions, label?: string): Promise<SendEmailResult | null>;
|
|
315
393
|
export interface EmailConfig {
|
|
316
394
|
apiKey: string | undefined;
|
|
317
395
|
from: string | undefined;
|