import sanitizeHtml from 'sanitize-html' import { convert } from 'html-to-text' import { HttpError } from './service.js' import { expandSignature } from './signature-placeholders.js' export const escapeHtml = (value) => String(value).replace( /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c], ) export function safeHtml(html) { return sanitizeHtml(html, { allowedTags: [ 'p', 'br', 'b', 'strong', 'i', 'em', 'u', 's', 'div', 'span', 'a', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'img', 'hr', ], allowedAttributes: { '*': ['style'], a: ['href', 'title'], img: ['src', 'alt', 'width', 'height'], td: ['colspan', 'rowspan'], th: ['colspan', 'rowspan'], }, allowedSchemes: ['https', 'http', 'mailto', 'tel'], allowedSchemesByTag: { img: ['https', 'data'] }, allowProtocolRelative: false, allowedStyles: { '*': { color: [/^#[0-9a-f]{3,8}$/i, /^[a-z]+$/i, /^rgb\([\d\s,]+\)$/i], 'background-color': [/^#[0-9a-f]{3,8}$/i, /^[a-z]+$/i], 'font-family': [/^[a-z\s,\-']+$/i], 'font-size': [/^\d{1,2}(px|pt)$/], 'font-weight': [/^(normal|bold|[1-9]00)$/], 'text-align': [/^(left|right|center|justify)$/], 'text-decoration': [/^(none|underline|line-through)$/], 'line-height': [/^[\d.]+(px|em|%)?$/], padding: [/^[\d\s.]+(px|pt)$/], 'border-collapse': [/^(collapse|separate)$/], }, }, transformTags: { img: (tag, attribs) => { if ( attribs.src?.startsWith('data:') && !/^data:image\/(png|jpeg|gif|webp);base64,[a-z\d+/=]+$/i.test(attribs.src) ) delete attribs.src return { tagName: tag, attribs } }, }, }) } export function plainHtml(html) { return convert(html, { wordwrap: false, selectors: [ { selector: 'img', format: 'skip' }, { selector: 'a', options: { hideLinkHrefIfSameAsText: true } }, ], }).trim() } export function signatureValue(s, context) { return s?.format === 'html' ? (() => { const html = safeHtml(expandSignature(safeHtml(s.body), context, escapeHtml)) return { html, text: plainHtml(html) } })() : { html: null, text: expandSignature(s?.body || '', context) } } export function composeContent(body, signature, context) { const sig = signatureValue(signature, context) let base = body.trimEnd() if (sig.text && base.endsWith(sig.text)) base = base.slice(0, -sig.text.length).trimEnd() return { text: base + (sig.text ? '\n\n' + sig.text : ''), html: sig.html ? `