77 lines
2.8 KiB
JavaScript
77 lines
2.8 KiB
JavaScript
import sanitizeHtml from 'sanitize-html'
|
|
import { safeHtml, escapeHtml } from './content.js'
|
|
|
|
function raster(mime, content) {
|
|
if (mime === 'image/png')
|
|
return content.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
|
|
if (mime === 'image/jpeg') return content[0] === 255 && content[1] === 216 && content[2] === 255
|
|
if (mime === 'image/gif') return ['GIF87a', 'GIF89a'].includes(content.subarray(0, 6).toString())
|
|
if (mime === 'image/webp')
|
|
return (
|
|
content.subarray(0, 4).toString() === 'RIFF' && content.subarray(8, 12).toString() === 'WEBP'
|
|
)
|
|
return false
|
|
}
|
|
export function messageView(s, m) {
|
|
const original = s.get(
|
|
'SELECT html,source IS NOT NULL has_source FROM message_originals WHERE message_id=?',
|
|
m.id,
|
|
)
|
|
const source =
|
|
original?.html || s.get('SELECT html FROM message_html WHERE message_id=?', m.id)?.html
|
|
const markup = source ? Buffer.from(source, 'utf8') : null
|
|
const truncated = !!markup && markup.length > 2 * 1024 * 1024
|
|
const clean = source
|
|
? safeHtml(markup.subarray(0, 2 * 1024 * 1024).toString('utf8'), { cid: true })
|
|
: `<div style="white-space:pre-wrap">${escapeHtml(m.body).replace(/\n/g, '<br>')}</div>`
|
|
const attachments = s.all(
|
|
'SELECT a.mime,a.content,i.content_id FROM attachment_inline i JOIN attachments a ON a.id=i.attachment_id WHERE a.message_id=?',
|
|
m.id,
|
|
)
|
|
let bytes = 0,
|
|
blockedInline = 0,
|
|
remoteImages = 0
|
|
const html = sanitizeHtml(clean, {
|
|
allowedTags: false,
|
|
allowedAttributes: false,
|
|
allowVulnerableTags: true,
|
|
allowedSchemes: ['https', 'http', 'mailto', 'tel', 'data'],
|
|
allowedSchemesByTag: { img: ['https', 'data'] },
|
|
allowProtocolRelative: false,
|
|
transformTags: {
|
|
img: (tag, attrs) => {
|
|
if (attrs.src?.startsWith('cid:')) {
|
|
let cid = attrs.src.slice(4)
|
|
try {
|
|
cid = decodeURIComponent(cid)
|
|
} catch {}
|
|
const matching = attachments.filter((a) => a.content_id === cid)
|
|
const a = matching.length === 1 ? matching[0] : null
|
|
if (a && raster(a.mime, a.content) && bytes + a.content.length <= 20 * 1024 * 1024) {
|
|
bytes += a.content.length
|
|
attrs.src = `data:${a.mime};base64,${a.content.toString('base64')}`
|
|
} else {
|
|
delete attrs.src
|
|
attrs.alt = attrs.alt || 'Eingebettetes Bild nicht verfügbar'
|
|
blockedInline++
|
|
}
|
|
} else if (attrs.src?.startsWith('https:')) remoteImages++
|
|
return { tagName: tag, attribs: attrs }
|
|
},
|
|
a: (tag, attrs) => ({
|
|
tagName: tag,
|
|
attribs: { ...attrs, target: '_blank', rel: 'noopener noreferrer' },
|
|
}),
|
|
},
|
|
})
|
|
return {
|
|
html,
|
|
text: m.body,
|
|
hasSource: !!original?.has_source,
|
|
hasHtml: !!source,
|
|
truncated,
|
|
blockedInline,
|
|
remoteImages,
|
|
}
|
|
}
|