import sanitizeHtml from 'sanitize-html' import { parseDocument } from 'htmlparser2' import render from 'dom-serializer' import parseSrcset from 'parse-srcset' import { inlineMailCss, stylesheetMailCss } from './mail-css.js' const tags = `a abbr acronym address b bdi bdo big blockquote br caption center cite code col colgroup dd del dfn div dl dt em font h1 h2 h3 h4 h5 h6 hr i img ins kbd li mark nobr ol p pre q s samp small span strike strong sub sup table tbody td tfoot th thead tr tt u ul var wbr`.split(/\s+/) const globalAttrs = [ 'style', 'class', 'id', 'title', 'dir', 'lang', 'align', 'valign', 'bgcolor', 'background', 'width', 'height', 'role', 'aria-label', ] const attributes = { '*': globalAttrs, a: ['href', 'name', 'target', 'rel'], img: ['src', 'srcset', 'sizes', 'alt', 'border', 'hspace', 'vspace', 'loading', 'referrerpolicy'], td: ['colspan', 'rowspan', 'nowrap'], th: ['colspan', 'rowspan', 'nowrap', 'scope'], table: ['cellpadding', 'cellspacing', 'border', 'summary'], col: ['span'], colgroup: ['span'], ol: ['start', 'type', 'reversed'], li: ['value', 'type'], font: ['face', 'color', 'size'], hr: ['size', 'noshade'], } export function safeImageUrl(value) { const url = String(value || '').trim() if (/^data:image\/(png|jpeg|gif|webp);base64,[a-z\d+/=]+$/i.test(url)) return url if (!/^(https?:\/\/|\/\/)/i.test(url)) return null try { const parsed = new URL(url.startsWith('//') ? 'https:' + url : url.replace(/^http:/i, 'https:')) if (parsed.protocol !== 'https:' || parsed.username || parsed.password) return null return parsed.href } catch { return null } } export function mailHtml(html, { resolveImage = safeImageUrl } = {}) { const doc = parseDocument(html, { decodeEntities: true }) let body, htmlNode const sheets = [] function walk(nodes) { const pending = [...nodes].reverse().map((node) => ({ node, depth: 0 })) while (pending.length) { const { node, depth } = pending.pop() if (depth > 100) { node.children = [] continue } if (node.name === 'style') { sheets.push( stylesheetMailCss( (node.children || []).map((child) => child.data || '').join(''), resolveImage, ), ) node.children = [] } if (node.name === 'body') body = node if (node.name === 'html') htmlNode = node for (const child of [...(node.children || [])].reverse()) pending.push({ node: child, depth: depth + 1 }) } } walk(doc.children) const transform = (tag, attrs) => { if (attrs.id) attrs.id = 'email-' + attrs.id if (attrs.class) attrs.class = attrs.class .split(/\s+/) .filter((name) => !name.startsWith('syncova-') && !name.startsWith('darkreader')) .join(' ') if (attrs.style) attrs.style = inlineMailCss(attrs.style, resolveImage) if (attrs.background) { const image = resolveImage(attrs.background) if (image) attrs.background = image else delete attrs.background } if (tag === 'img') { const src = resolveImage(attrs.src) if (src) attrs.src = src else { delete attrs.src attrs.alt ||= 'Bild nicht verfügbar' } if (attrs.srcset) { try { attrs.srcset = parseSrcset(attrs.srcset) .map((item) => { const url = resolveImage(item.url) return url ? url + (item.w ? ` ${item.w}w` : item.d ? ` ${item.d}x` : '') : '' }) .filter(Boolean) .join(', ') } catch { delete attrs.srcset } } attrs.referrerpolicy = 'no-referrer' attrs.loading = 'eager' } if (tag === 'a') { if (attrs.href?.startsWith('//')) attrs.href = 'https:' + attrs.href attrs.target = '_blank' attrs.rel = 'noopener noreferrer' } if (tag === 'o:p') tag = 'span' return { tagName: tag, attribs: attrs } } const options = { allowedTags: tags, allowedAttributes: attributes, allowProtocolRelative: false, allowedSchemes: ['https', 'http', 'mailto', 'tel'], allowedSchemesByTag: { img: ['https', 'data'] }, parseStyleAttributes: false, transformTags: { '*': transform }, nonTextTags: [ 'style', 'script', 'textarea', 'option', 'noscript', 'title', 'iframe', 'object', 'template', ], enforceHtmlBoundary: false, } const clean = sanitizeHtml( render(body?.children || doc.children.filter((node) => !['head'].includes(node.name))), options, ) const wrapper = (node, kind, content) => { const attrs = { ...(node?.attribs || {}) } const serialized = Object.entries(attrs) .map( ([name, value]) => ` ${name}="${String(value).replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<')}"`, ) .join('') const shell = sanitizeHtml(``, options) return shell.replace(/^
', content + '
') } const styled = sheets .filter(Boolean) .map((css) => ``) .join('') return styled + wrapper(htmlNode, 'html', wrapper(body, 'body', clean)) }