File size: 5,092 Bytes
d160eca | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | // Markdown + math + code -> safe DOM.
//
// Model output is untrusted text. Pipeline:
// 1. pull the TeX out (protocol.extractMath) so Markdown cannot mangle it
// 2. Markdown -> HTML (marked), code highlighted with highlight.js
// 3. sanitise with DOMPurify against a small allow-list
// 4. put KaTeX-rendered math back, into text positions only
import { Marked, DOMPurify, katex, hljs } from '../vendor/vendor.js';
import { extractMath, MATH_OPEN, MATH_CLOSE } from './protocol.js';
const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const marked = new Marked({
gfm: true,
breaks: true,
renderer: {
code({ text, lang }) {
const language = (lang || '').trim().split(/\s+/)[0].toLowerCase();
let body;
if (language && hljs.getLanguage(language)) {
try {
body = hljs.highlight(text, { language, ignoreIllegals: true }).value;
} catch {
body = escapeHtml(text);
}
} else {
body = escapeHtml(text);
}
const label = language ? ` data-lang="${escapeHtml(language)}"` : '';
return `<pre${label}><code class="hljs">${body}</code></pre>\n`;
},
},
});
const PURIFY = {
ALLOWED_TAGS: [
'p', 'br', 'strong', 'b', 'em', 'i', 'del', 's', 'code', 'pre', 'blockquote', 'ul', 'ol', 'li', 'a',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'span', 'sup', 'sub', 'kbd',
],
ALLOWED_ATTR: ['href', 'title', 'class', 'start', 'align', 'data-lang'],
ALLOWED_URI_REGEXP: /^(?:https?:|mailto:)/i,
RETURN_DOM_FRAGMENT: true,
};
// Only syntax-highlighting classes survive, so model output cannot borrow the app's own styles.
DOMPurify.addHook('uponSanitizeAttribute', (node, data) => {
if (data.attrName === 'class') {
const kept = data.attrValue.split(/\s+/).filter((c) => /^hljs(?:-[\w-]+)?$/.test(c) || /^language-[\w-]+$/.test(c));
if (kept.length) data.attrValue = kept.join(' ');
else data.keepAttr = false;
}
});
const mathCache = new Map();
function renderTex(tex, display) {
const key = `${display ? 'D' : 'I'}${tex}`;
let html = mathCache.get(key);
if (html === undefined) {
try {
html = katex.renderToString(tex, { displayMode: display, throwOnError: false, strict: 'ignore', trust: false, output: 'htmlAndMathml' });
} catch {
html = `<code>${escapeHtml(tex)}</code>`;
}
if (mathCache.size > 600) mathCache.clear();
mathCache.set(key, html);
}
return html;
}
const PLACEHOLDER = new RegExp(`${MATH_OPEN}(\\d+)${MATH_CLOSE}`, 'g');
function restoreMath(root, items) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const targets = [];
while (walker.nextNode()) {
if (walker.currentNode.nodeValue.includes(MATH_OPEN)) targets.push(walker.currentNode);
}
for (const node of targets) {
const parent = node.parentNode;
const inCode = parent.closest?.('code, pre');
const frag = document.createDocumentFragment();
let last = 0;
const value = node.nodeValue;
for (const m of value.matchAll(PLACEHOLDER)) {
const item = items[Number(m[1])];
if (m.index > last) frag.append(value.slice(last, m.index));
if (!item) {
// not one of ours: leave nothing behind
} else if (inCode) {
frag.append(item.display ? `$$${item.tex}$$` : `$${item.tex}$`);
} else {
const holder = document.createElement('span');
holder.className = item.display ? 'math math--display' : 'math';
holder.innerHTML = renderTex(item.tex, item.display); // KaTeX output, generated with trust:false
frag.append(holder);
}
last = m.index + m[0].length;
}
if (last < value.length) frag.append(value.slice(last));
parent.replaceChild(frag, node);
}
}
/** Renders one chat bubble's Markdown source to a DocumentFragment that is safe to insert. */
export function renderMarkdown(src) {
const { text, items } = extractMath(src);
const html = marked.parse(text, { async: false });
const frag = DOMPurify.sanitize(html, PURIFY);
for (const a of frag.querySelectorAll('a')) {
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener noreferrer');
}
if (items.length) restoreMath(frag, items);
// The private-use markers must never reach the page, whatever happened above.
const stray = document.createTreeWalker(frag, NodeFilter.SHOW_TEXT);
while (stray.nextNode()) {
const n = stray.currentNode;
if (n.nodeValue.includes(MATH_OPEN) || n.nodeValue.includes(MATH_CLOSE)) {
n.nodeValue = n.nodeValue.replace(/[]/g, '');
}
}
return frag;
}
/**
* Renders what the user typed: kept as plain text (so asterisks and underscores
* stay literal) but with any TeX math they wrote rendered.
*/
export function renderUserText(src) {
const { text, items } = extractMath(src);
const frag = document.createDocumentFragment();
frag.append(text);
if (items.length) restoreMath(frag, items);
return frag;
}
|