Files

114 lines
4.7 KiB
TypeScript

// VA-P23 · safe email-HTML rendering (M09 Block F — CSP-hardened container).
//
// Email bodies are UNTRUSTED third-party HTML — the classic stored-XSS vector.
// Sanitization = DOMPurify (isomorphic build: jsdom on the server, native DOM
// in the browser; team decision 2026-07-02) + an email-specific layer on top:
// - external images are BLOCKED by default (`src` moved to `data-hg-blocked-src`,
// the UI re-enables them via the "Bilder laden" opt-in → allowExternalImages)
// - inline `cid:`/`data:` images stay (no network fetch)
// - all sender-controlled CSS is removed (CSS is a network-capable language)
// - links are forced to target="_blank" rel="noopener noreferrer nofollow"
// - forms/inputs are removed entirely (no credential phishing surface)
export interface SanitizedEmailHtml {
readonly html: string;
/** Number of external images that were blocked (drives the opt-in banner). */
readonly blockedImageCount: number;
}
const FORBIDDEN_TAGS = [
"form",
"input",
"select",
"textarea",
"button",
"iframe",
"frame",
"object",
"embed",
"base",
"meta",
"link",
"style",
"video",
"audio",
"source",
"track",
"picture",
];
const INLINE_IMAGE_SRC = /^(?:cid:|data:)/i;
let hooksInstalled = false;
let hookState: { allowExternalImages: boolean; blockedImageCount: number } = { allowExternalImages: false, blockedImageCount: 0 };
let domPurifyPromise: Promise<(typeof import("isomorphic-dompurify"))["default"]> | undefined;
function getDOMPurify() {
// `isomorphic-dompurify` creates a jsdom window in Node. Loading it eagerly
// adds hundreds of milliseconds and well over 100 MiB RSS to every web
// process, even when no email is viewed. Keep one shared lazy instance and
// pay that cost only on the first HTML-email request.
domPurifyPromise ??= import("isomorphic-dompurify").then(({ default: DOMPurify }) => DOMPurify);
return domPurifyPromise;
}
function ensureHooks(DOMPurify: Awaited<ReturnType<typeof getDOMPurify>>): void {
if (hooksInstalled) return;
hooksInstalled = true;
DOMPurify.addHook("afterSanitizeAttributes", (node) => {
const tag = node.tagName?.toLowerCase();
// Block external image loads unless the user opted in ("Bilder laden").
if (tag === "img") {
const src = node.getAttribute("src") ?? "";
// Browsers normalize backslashes and one-slash HTTP forms into network
// URLs. A narrow inline allowlist is safer than trying to enumerate all
// URL spellings that can trigger a request (including relative URLs).
if (src.trim() !== "" && !INLINE_IMAGE_SRC.test(src.trim()) && !hookState.allowExternalImages) {
node.setAttribute("data-hg-blocked-src", src);
node.removeAttribute("src");
node.setAttribute("alt", node.getAttribute("alt") ?? "");
hookState.blockedImageCount += 1;
}
node.removeAttribute("srcset");
node.removeAttribute("loading");
}
// CSS can fetch resources through url(), @import, image-set(), escaped
// identifiers and future browser features. A regex cannot safely parse
// that language, so email-provided CSS is removed wholesale. HiveGrid's
// surrounding reader UI owns presentation instead.
node.removeAttribute?.("style");
if (node.hasAttribute?.("background")) {
node.removeAttribute("background");
}
// Links open sandboxed in a new tab.
if (tag === "a") {
node.setAttribute("target", "_blank");
node.setAttribute("rel", "noopener noreferrer nofollow");
}
});
}
/**
* Sanitize an email HTML body for rendering. NOT idempotent state-wise — the
* blocked-image counter is per call (module-level hook state, single-threaded
* per request in Node).
*/
export async function sanitizeEmailHtml(html: string, options: { allowExternalImages?: boolean } = {}): Promise<SanitizedEmailHtml> {
const DOMPurify = await getDOMPurify();
ensureHooks(DOMPurify);
hookState = { allowExternalImages: options.allowExternalImages ?? false, blockedImageCount: 0 };
const clean = DOMPurify.sanitize(html, {
USE_PROFILES: { html: true },
FORBID_TAGS: FORBIDDEN_TAGS,
FORBID_ATTR: ["onerror", "onload", "onclick", "formaction", "ping", "style"],
ALLOW_DATA_ATTR: false,
ADD_ATTR: ["data-hg-blocked-src", "target", "rel"],
});
return { html: clean, blockedImageCount: hookState.blockedImageCount };
}
/** Plain-text fallback rendering (bodyText mails) — escaped, newlines kept. */
export function renderPlainTextAsHtml(text: string): string {
const escaped = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
return `<pre style="white-space:pre-wrap;font-family:inherit">${escaped}</pre>`;
}