Files
client/app/renderer/js/markdown/render.js
T
omar f618d8bce9
ci / linux-arm64-cross (push) Successful in 3m22s
ci / linux-x64 (push) Successful in 3m32s
chat: add safe hybrid Markdown editing with strict CSP
2026-11-02 11:32:31 +03:00

414 lines
15 KiB
JavaScript

// Renders the chat-markdown tree (parse.js) into DOM nodes with the official class names
// (html render profile of main.js module 37702). Only createElement / textContent / CSSOM are
// used: no HTML string is parsed, no script, iframe or form is ever created, and nothing loads
// from the network while rendering. Behaviour (links, spoilers, server images, server files) is
// attached by chat.js through delegated listeners on the data attributes set here.
import { parseMarkdown } from './parse.js';
import { hydrateMath } from './math.js';
import { hydrateMermaid } from './mermaid.js';
import { t } from '../i18n.js';
import { setText } from '../dom.js';
const ALLOWED_LINK_SCHEMES = new Set(['https', 'http', 'mailto']);
// Official image options: TS overrides maxPx 1000 and defaultMaxHeight 300 (module 77246);
// remaining limits are the engine defaults `W_`.
const IMAGE_LIMITS = { maxPx: 1000, maxPct: 100, minPx: 16, minPct: 5, defaultMaxHeight: 300, defaultMinHeight: 50 };
/** Resolve user-visible links without ever manufacturing an executable URL from an unsafe scheme. */
export function linkHref(href, email) {
if (typeof href !== 'string' || /[\u0000-\u0020\u007f]/.test(href)) return null;
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(href)?.[1]?.toLowerCase();
if (scheme && !ALLOWED_LINK_SCHEMES.has(scheme)) return null;
const value = scheme ? href : email ? `mailto:${href}` : `https://${href.replace(/^\/\//, '')}`;
try {
const url = new URL(value);
return url.username || url.password ? null : url.href;
} catch { return null; }
}
/** `ts3image://<name>?channel=<cid>&path=<dir>` → file reference, or null. */
export function parseTs3Image(src) {
if (!/^ts3image:\/\//i.test(src)) return null;
const q = src.indexOf('?');
if (q < 0) return null;
let name;
try {
name = decodeURIComponent(src.slice(11, q));
} catch {
return null;
}
const params = new URLSearchParams(src.slice(q + 1));
const channelId = Number(params.get('channel'));
const path = params.get('path') || '/';
if (!name || /[\/\\\u0000-\u001f]/.test(name) || !Number.isSafeInteger(channelId) || channelId <= 0 || !path.startsWith('/') || path.split('/').includes('..')) return null;
return { name, channelId, path: path.endsWith('/') ? path : `${path}/` };
}
/** Official `ts3file://` URL (file browser "Copy URL"): host?port&serverUID&channel&path&filename&isDir&size. */
export function parseTs3File(url) {
if (!/^ts3file:\/\//i.test(url)) return null;
const q = url.indexOf('?');
if (q < 0) return null;
const params = new URLSearchParams(url.slice(q + 1));
const filename = params.get('filename');
const channelId = Number(params.get('channel') ?? '0');
const path = params.get('path') || '/';
if (!filename || /[\/\\\u0000-\u001f]/.test(filename) || !Number.isSafeInteger(channelId) || channelId <= 0 || !path.startsWith('/') || path.split('/').includes('..')) return null;
return {
address: url.slice(10, q),
port: Number.parseInt(params.get('port') ?? '0', 10) || 0,
serverUid: params.get('serverUID') ?? '',
channelId,
path: path.endsWith('/') ? path : `${path}/`,
name: filename,
isDir: params.get('isDir') === '1' || params.get('isDir') === 'true',
size: Number.parseInt(params.get('size') ?? '0', 10) || 0,
};
}
function clampSize(value, limits) {
if (value.endsWith('%')) {
const n = Number.parseFloat(value);
return `${Math.min(limits.maxPct, Math.max(limits.minPct, n))}%`;
}
const n = Number.parseInt(value, 10);
return String(Math.min(limits.maxPx, Math.max(limits.minPx, n)));
}
export function applyImageSize(img, width, height) {
if (!width && !height) {
img.style.maxHeight = `${IMAGE_LIMITS.defaultMaxHeight}px`;
img.style.minHeight = `${IMAGE_LIMITS.defaultMinHeight}px`;
return;
}
img.classList.add('md-img-sized');
let w = width;
let h = height;
if (w && h && !w.endsWith('%') && !h.endsWith('%')) {
const wi = Number.parseInt(w, 10);
const hi = Number.parseInt(h, 10);
if (wi > 0 && hi > 0) {
let scale = Math.min(1, IMAGE_LIMITS.maxPx / wi, IMAGE_LIMITS.maxPx / hi);
scale = Math.max(scale, IMAGE_LIMITS.minPx / wi, IMAGE_LIMITS.minPx / hi);
w = String(Math.round(wi * scale));
h = String(Math.round(hi * scale));
}
} else {
if (w) w = clampSize(w, IMAGE_LIMITS);
if (h) h = clampSize(h, IMAGE_LIMITS);
}
if (w) {
if (w.endsWith('%')) img.style.width = w;
else img.width = Number(w);
}
if (h) {
if (h.endsWith('%')) img.style.height = h;
else img.height = Number(h);
}
}
function el(tag, className, children) {
const node = document.createElement(tag);
if (className) node.className = className;
if (children) for (const child of children) if (child) node.appendChild(child);
return node;
}
class DomRenderer {
constructor(options) {
this.options = options;
}
inline(nodes) {
const out = [];
for (const n of nodes) {
const node = this.inlineNode(n);
if (node) out.push(node);
}
return out;
}
inlineNode(n) {
switch (n.type) {
case 'text': return document.createTextNode(n.value);
case 'em': return el('em', null, this.inline(n.children));
case 'strong': return el('strong', null, this.inline(n.children));
case 'del': return el('del', null, this.inline(n.children));
case 'u': return el('u', null, this.inline(n.children));
case 'sup': return el('sup', null, this.inline(n.children));
case 'sub': return el('sub', null, this.inline(n.children));
case 'mark': return el('mark', 'md-highlight', this.inline(n.children));
case 'spoiler': {
const s = el('span', 'md-spoiler', this.inline(n.children));
s.tabIndex = 0;
s.setAttribute('role', 'button');
s.setAttribute('aria-expanded', 'false');
s.title = t('chat.message.spoiler.reveal');
return s;
}
case 'code': {
const c = el('code');
c.textContent = n.value;
return c;
}
case 'math': {
const s = el('span', 'md-inline-math');
hydrateMath(s, n.value, false);
return s;
}
case 'emoji': {
const s = el('span', 'md-emoji');
s.title = `:${n.shortcode}:`;
s.textContent = n.unicode;
return s;
}
case 'fnref': {
const sup = el('sup', 'footnote-ref');
sup.dataset.footnote = n.label;
sup.textContent = String(n.number);
return sup;
}
case 'link': return this.link(n);
case 'image': return this.image(n);
case 'color': {
const s = el('span', null, this.inline(n.children));
if (n.color) s.style.color = n.color;
return s;
}
case 'size': {
const s = el('span', null, this.inline(n.children));
if (n.size) s.style.fontSize = n.size;
return s;
}
case 'bb_align': {
const s = el('span', 'md-bb-align', this.inline(n.children));
s.style.display = 'block';
s.style.textAlign = n.align;
return s;
}
default: return null;
}
}
link(n) {
const href = linkHref(n.href, n.email);
const a = el('a', 'ts-parsed-link', this.inline(n.children));
if (href) { a.dataset.href = href; a.href = href; }
else { a.dataset.invalid = ''; }
a.rel = 'noreferrer noopener';
if (n.title) a.dataset.title = n.title;
a.title = n.title ? `${n.title}\n${href ?? n.href}` : t('chat.message.link.links_to', { url: href ?? n.href });
return a;
}
/** Official behaviour: only server images (ts3image://) become <img>; any other source shows as text. */
image(n) {
const ref = parseTs3Image(n.src);
if (!ref) {
const s = el('span', 'md-image-source');
s.textContent = n.src;
if (n.alt) s.title = n.alt;
return s;
}
const wrap = el('span', 'md-ts3image');
wrap.dataset.channelId = String(ref.channelId);
wrap.dataset.path = ref.path;
wrap.dataset.name = ref.name;
wrap.dataset.alt = n.alt ?? '';
if (n.title) wrap.dataset.title = n.title;
if (n.width) wrap.dataset.width = n.width;
if (n.height) wrap.dataset.height = n.height;
const load = el('button', 'md-ts3image-load');
load.type = 'button';
setText(load, () => t('chat.image.load', { name: ref.name }));
wrap.appendChild(load);
return wrap;
}
blocks(nodes) {
const out = [];
for (const n of nodes) {
const node = this.block(n);
if (node) out.push(node);
}
return out;
}
block(n) {
switch (n.type) {
case 'paragraph': return el('p', null, this.inline(n.children));
case 'heading': return el(`h${n.level}`, null, this.inline(n.children));
case 'hr': return el('hr');
case 'blockquote': {
if (!n.callout) return el('blockquote', null, this.blocks(n.children));
const title = el('div', 'md-callout-title');
title.textContent = n.callout.title;
const q = el('blockquote', `md-callout md-callout-${n.callout.type}`, [title, ...this.blocks(n.children)]);
q.dataset.callout = n.callout.type;
return q;
}
case 'list': return this.list(n);
case 'code': {
const code = el('code', 'cm-no-highlight');
code.textContent = n.text;
if (n.lang) code.dataset.lang = n.lang;
const pre = el('pre');
if (n.lang) {
const label = el('span', 'md-code-lang');
label.textContent = n.lang;
pre.appendChild(label);
}
pre.appendChild(code);
return pre;
}
case 'math_block': {
const d = el('div', 'md-offline-math-preview');
hydrateMath(d, n.text, true);
return d;
}
case 'mermaid': {
const d = el('div', 'md-offline-mermaid-preview');
hydrateMermaid(d, n.text);
return d;
}
case 'table': return this.table(n);
case 'details': {
const summary = el('summary', null, n.summary.length ? this.inline(n.summary) : [document.createTextNode('Details')]);
return el('details', 'md-details-preview', [summary, el('div', 'md-details-content', this.blocks(n.children))]);
}
case 'align': {
if (n.align === 'center') return el('center', 'md-align-block', this.blocks(n.children));
const d = el('div', n.align === 'right' ? 'md-align-block md-align-right' : 'md-align-block', this.blocks(n.children));
if (n.align !== 'right') d.style.textAlign = n.align;
return d;
}
case 'bb_block': {
const s = el('span', `md-bb-block-${n.style}`, this.blocks(n.children));
s.style.display = 'block';
if (n.style === 'strong') s.style.fontWeight = 'bold';
if (n.style === 'emphasis') s.style.fontStyle = 'italic';
if (n.style === 'underline') s.style.textDecoration = 'underline';
if (n.style === 'strikethrough') s.style.textDecoration = 'line-through';
if (n.style === 'color' && n.color) s.style.color = n.color;
if (n.style === 'size' && n.size) s.style.fontSize = n.size;
return s;
}
case 'bb_align': {
const d = el('div', 'md-bb-align', this.blocks(n.children));
d.style.textAlign = n.align;
return d;
}
default: return null;
}
}
list(n) {
const list = el(n.ordered ? 'ol' : 'ul');
if (n.ordered && n.start !== 1) list.start = n.start;
for (const item of n.items) {
const li = el('li');
if (item.task !== null) {
li.className = 'md-task';
const box = el('span', 'ts-checkbox inline');
box.dataset.checked = String(item.task);
box.setAttribute('role', 'img');
box.setAttribute('aria-label', item.task ? '☑' : '☐');
li.appendChild(box);
}
const onlyRule = item.children.length === 1 && item.children[0].type === 'hr';
for (const child of onlyRule ? [el('hr')] : this.inline(item.children)) li.appendChild(child);
if (item.sub) li.appendChild(this.list(item.sub));
list.appendChild(li);
}
return list;
}
table(n) {
const table = el('table', 'md-table');
const row = (cells, tag) => {
const tr = el('tr');
cells.forEach((cell, idx) => {
const c = el(tag, null, this.inline(cell));
if (n.align[idx]) c.style.textAlign = n.align[idx];
tr.appendChild(c);
});
return tr;
};
table.appendChild(el('thead', null, [row(n.header, 'th')]));
table.appendChild(el('tbody', null, n.rows.map((r) => row(r, 'td'))));
return table;
}
footnotes(notes) {
if (!notes.length) return null;
const ol = el('ol');
for (const note of notes) {
const li = el('li', null, this.inline(note.children));
li.dataset.footnote = note.label;
ol.appendChild(li);
}
return el('section', 'md-footnotes', [ol]);
}
}
/**
* Server-file attachments, found the way the official client does (`k9`, module 96121): URLs in
* markdown links plus bare `scheme://…` / `www.` runs; only ts3file:// ones are kept here.
* `hideText` mirrors `hide_message_parts`: a message consisting of just the link shows only the card.
*/
export function findTs3Files(source) {
const found = [];
const ranges = [];
const linkRe = /\[((?:\[[^\]]*\]|[^[\]]|\](?=[^[]*\]))*)\]\(\s*<?((?:[^\s\\]|\\.)*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*\)/g;
let m;
while ((m = linkRe.exec(source))) {
const from = m.index + (m[1] ?? '').length + 3;
const url = (m[2] ?? '').trim();
ranges.push({ from, to: from + url.length, url });
}
const bareRe = /((?:(?:(?:https?|ts3file|ts3server|teamspeak):\/\/)|(?:www\.))[^\s<>[\]]+[^<>.,:;"')[\]\s])/g;
while ((m = bareRe.exec(source))) {
const from = m.index;
const to = from + m[0].length;
if (!ranges.some((r) => !(to <= r.from || from >= r.to))) ranges.push({ from, to, url: m[0] });
}
let hideText = false;
for (const r of ranges) {
const file = parseTs3File(r.url);
if (!file) continue;
found.push({ ...file, url: r.url });
if (source.trim() === r.url) hideText = true;
}
return { files: found, hideText };
}
/** Renders message text into `target` (replacing its children). */
export function renderMarkdownInto(target, source, options = {}) {
const doc = parseMarkdown(source);
const r = new DomRenderer(options);
const nodes = r.blocks(doc.children);
const notes = r.footnotes(doc.footnotes);
if (notes) nodes.push(notes);
target.replaceChildren(...nodes);
// Emoji-only messages are shown large (official `apparently-people-like-huge-faces`).
const onlyEmoji = doc.children.length === 1 && doc.children[0].type === 'paragraph'
&& doc.children[0].children.length > 0
&& doc.children[0].children.every((c) => c.type === 'emoji' || (c.type === 'text' && !c.value.trim()));
return { onlyEmoji };
}
/**
* Renders one top-level block of a `parseMarkdown` tree (chat editor preview). Reference links and
* footnote numbers are resolved document-wide by the parser, so a block looks as it will in the message.
*/
export function renderMarkdownBlock(node, options = {}) {
return new DomRenderer(options).block(node);
}
/** Renders footnote definitions as the message's footnote section, numbered from the first note. */
export function renderMarkdownFootnotes(notes, options = {}) {
const section = new DomRenderer(options).footnotes(notes);
if (section && notes[0].number !== 1) section.firstChild.start = notes[0].number;
return section;
}