syncova-ticket/server/content.js
Weapie c72c72e41e
Some checks failed
Tests und Docker-Image / Tests und Frontend-Build (push) Successful in 51s
Tests und Docker-Image / Leeres Produktionsimage bauen und veröffentlichen (push) Has been cancelled
Preserve HTML email layouts and adapt dark mode with Dark Reader
2026-11-05 17:54:57 +01:00

159 lines
4.6 KiB
JavaScript

import sanitizeHtml from 'sanitize-html'
import { convert } from 'html-to-text'
import { HttpError } from './service.js'
import { expandSignature } from './signature-placeholders.js'
import { inlineMailCss } from './mail-css.js'
import { safeImageUrl } from './mail-html.js'
export const escapeHtml = (value) =>
String(value).replace(
/[&<>"']/g,
(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
)
export function safeHtml(html, options = {}) {
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',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote',
'pre',
'code',
'dl',
'dt',
'dd',
'tfoot',
'font',
],
allowedAttributes: {
'*': ['style', 'class', 'title', 'align', 'valign', 'bgcolor', 'width', 'height', 'dir'],
a: ['href', 'title'],
img: ['src', 'alt', 'width', 'height'],
td: ['colspan', 'rowspan'],
th: ['colspan', 'rowspan'],
table: ['width', 'cellpadding', 'cellspacing', 'border'],
font: ['color', 'face', 'size'],
},
allowedSchemes: ['https', 'http', 'mailto', 'tel'],
allowedSchemesByTag: { img: options.cid ? ['https', 'data', 'cid'] : ['https', 'data'] },
allowProtocolRelative: false,
parseStyleAttributes: false,
transformTags: {
'*': (tag, attrs) => ({
tagName: tag,
attribs: {
...attrs,
...(attrs.style ? { style: inlineMailCss(attrs.style, safeImageUrl) } : {}),
},
}),
img: (tag, attribs) => {
if (attribs.style) attribs.style = inlineMailCss(attribs.style, safeImageUrl)
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
? `<div style="white-space:pre-wrap">${escapeHtml(base).replace(/\n/g, '<br>')}</div><br>${sig.html}`
: null,
}
}
export function normaliseAttachments(
values = [],
{ maxFileBytes = 10 * 1024 * 1024, maxTotalBytes = 20 * 1024 * 1024 } = {},
) {
if (!Array.isArray(values) || values.length > 20)
throw new HttpError(400, 'Höchstens 20 Anhänge pro Nachricht.')
let total = 0
return values.map((a) => {
if (
!a ||
typeof a.content !== 'string' ||
a.content.length > Math.ceil(maxFileBytes / 3) * 4 ||
a.content.length % 4 !== 0 ||
/[^a-z\d+/=]/i.test(a.content)
)
throw new HttpError(
400,
`Ungültiger Anhang (maximal ${maxFileBytes / 1024 / 1024} MiB pro Datei).`,
)
const content = Buffer.from(a.content, 'base64')
if (content.length > maxFileBytes || content.toString('base64') !== a.content)
throw new HttpError(413, 'Anhang ist zu groß oder ungültig.')
total += content.length
if (total > maxTotalBytes)
throw new HttpError(
413,
`Anhänge dürfen zusammen höchstens ${maxTotalBytes / 1024 / 1024} MiB groß sein.`,
)
return {
name: String(a.name || 'Anhang')
.replace(/[\x00-\x1f\x7f/\\]/g, '_')
.slice(0, 200),
mime:
typeof a.mime === 'string' && /^[a-z\d!#$&^_.+-]+\/[a-z\d!#$&^_.+-]+$/i.test(a.mime)
? a.mime
: 'application/octet-stream',
content,
contentId:
typeof a.contentId === 'string' &&
a.contentId.length <= 998 &&
!/[\r\n\0]/.test(a.contentId)
? a.contentId.trim().replace(/^<|>$/g, '')
: '',
}
})
}