Render assistant Markdown and LaTeX as sanitized HTML with native MathML

Server-side rendering keeps the browser free of any Markdown/MathJax toolchain (single-binary). New src/render.rs: pulldown-cmark (tables/strikethrough/math) + pulldown-latex -> MathML Core. Safety: raw HTML events are escaped to text (pulldown-cmark 0.13 has no ENABLE_HTML opt-out) and link/image URLs pass a scheme allowlist (javascript:/data:/vbscript: stripped, control chars removed). content_html is added to get_messages (assistant only) and to the agent Final SSE event; the GUI injects it via innerHTML for assistant bubbles (history + live) while user text stays textContent. CSS styles Markdown and native MathML; block math must not override display (UA block math layout) or it collapses to vertical stacks. 10 render unit tests incl. XSS; 136 tests green, clippy/fmt clean; verified live + visually.
This commit is contained in:
adm committed 2026-11-25 20:58:20 +01:00
1 parent d1b56d2c23
commit 7dd66ea138
7 files changed
+382 -9

No files matched your search

Generated
+39
View File
@@ -696,6 +696,15 @@ dependencies = [
"slab",
]
[[package]]
name = "getopts"
version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
dependencies = [
"unicode-width",
]
[[package]]
name = "getrandom"
version = "0.2.17"
@@ -1433,6 +1442,34 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "pulldown-cmark"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b"
dependencies = [
"bitflags",
"getopts",
"memchr",
"pulldown-cmark-escape",
"unicase",
]
[[package]]
name = "pulldown-cmark-escape"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
[[package]]
name = "pulldown-latex"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cf850381ae0dbb131f36e31d6090f55363d079ab3e518ad0323b9cb6a96d115"
dependencies = [
"bumpalo",
]
[[package]]
name = "pxfm"
version = "0.1.30"
@@ -1928,6 +1965,8 @@ dependencies = [
"http-body-util",
"image",
"minijinja",
"pulldown-cmark",
"pulldown-latex",
"rusqlite",
"rust-embed",
"serde",
+2
View File
@@ -26,6 +26,8 @@ tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
rusqlite = { version = "0.32", features = ["bundled"] }
# Embeds the web/ GUI assets into the binary (single-binary, offline-capable).
rust-embed = "8"
pulldown-cmark = "0.13.6"
pulldown-latex = "0.8.0"
[dev-dependencies]
http-body-util = "0.1.5"
+48 -3
View File
@@ -26,6 +26,7 @@ use crate::agent::shell::{HostShell, ShellRunner};
use crate::agent::{self, AgentEvent};
use crate::i18n::t;
use crate::name;
use crate::render;
use crate::store::{NewMessage, Session, SessionSettings, Stats, Store, StoredMessage};
use tokio_stream::wrappers::UnboundedReceiverStream;
@@ -183,11 +184,33 @@ pub(crate) async fn put_defaults(
Ok(StatusCode::OK)
}
/// A stored message plus, for assistant turns, server-rendered safe HTML
/// (`content_html`) so the GUI can show Markdown/LaTeX without a JS toolchain.
#[derive(Serialize)]
pub(crate) struct MessageView {
#[serde(flatten)]
msg: StoredMessage,
#[serde(skip_serializing_if = "Option::is_none")]
content_html: Option<String>,
}
pub(crate) async fn get_messages(
State(st): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<Vec<StoredMessage>>, Error> {
Ok(Json(with_store(&st, move |s| s.messages(&id)).await?))
) -> Result<Json<Vec<MessageView>>, Error> {
let msgs = with_store(&st, move |s| s.messages(&id)).await?;
let views = msgs
.into_iter()
.map(|m| {
let content_html = (m.role == "assistant" && !m.content.is_empty())
.then(|| render::markdown_to_safe_html(&m.content));
MessageView {
msg: m,
content_html,
}
})
.collect();
Ok(Json(views))
}
/// The stats dashboard payload: persistent history aggregates (from the store)
@@ -653,12 +676,34 @@ pub(crate) async fn session_chat(
}
});
let events = UnboundedReceiverStream::new(rx)
.map(|ev| match Event::default().json_data(&ev) {
.map(|ev| {
let mut val = match serde_json::to_value(&ev) {
Ok(v) => v,
Err(e) => {
tracing::error!(error = %e, "failed to serialize agent event");
return Ok(Event::default().data("{}"));
}
};
// The final answer carries server-rendered safe HTML so the GUI
// can swap the streamed plain text for Markdown/LaTeX at the end.
if let AgentEvent::Final { response } = &ev {
let html = response
.choices
.first()
.and_then(|c| c.message.text())
.filter(|t| !t.is_empty())
.map(render::markdown_to_safe_html);
if let (Some(html), Some(obj)) = (html, val.as_object_mut()) {
obj.insert("content_html".to_string(), serde_json::Value::String(html));
}
}
match Event::default().json_data(&val) {
Ok(e) => Ok::<_, std::convert::Infallible>(e),
Err(e) => {
tracing::error!(error = %e, "failed to serialize agent event");
Ok(Event::default().data("{}"))
}
}
})
.chain(futures::stream::once(async {
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
+2
View File
@@ -5,6 +5,7 @@
//! completion service, axum routes).
//! - [`store`]: persistent session/context store for the web GUI (SQLite behind
//! a swappable `Store` trait).
//! - [`render`]: safe Markdown + LaTeX → HTML for assistant messages.
pub mod agent;
pub mod api;
@@ -13,4 +14,5 @@ pub mod engine;
pub mod i18n;
pub mod inkling;
pub mod name;
pub mod render;
pub mod store;
+211
View File
@@ -0,0 +1,211 @@
//! Safe Markdown + LaTeX rendering for assistant messages.
//!
//! The model writes Markdown with `$…$` / `$$…$$` math. We turn it into HTML on
//! the server so the GUI can inject it directly, keeping the browser free of any
//! Markdown/MathJax toolchain (single-binary philosophy). Two safety guarantees:
//!
//! - **No raw HTML**: pulldown-cmark always parses raw HTML (it is core
//! CommonMark, with no opt-out flag), so we rewrite every `Html`/`InlineHtml`
//! event into escaped text — the model's HTML is shown literally, never run.
//! - **No dangerous URLs**: link/image destinations pass a scheme allowlist, so
//! `javascript:`, `data:`, `vbscript:` (and friends) are stripped.
//!
//! Math becomes native **MathML Core** via `pulldown-latex` — no JavaScript and
//! no web fonts needed for correctness (optional CSS only refines the look).
use pulldown_cmark::{html, Event, Options, Parser, Tag};
use pulldown_latex::{config::DisplayMode, push_mathml, RenderConfig, Storage};
/// Convert model Markdown (with LaTeX math) into sanitized HTML ready for
/// `innerHTML`. Only assistant output is rendered this way; user text stays
/// plain (`textContent`) on the frontend.
pub fn markdown_to_safe_html(text: &str) -> String {
let mut opts = Options::empty();
opts.insert(Options::ENABLE_TABLES);
opts.insert(Options::ENABLE_STRIKETHROUGH);
opts.insert(Options::ENABLE_MATH);
let events = Parser::new_ext(text, opts).map(|ev| match ev {
Event::InlineMath(src) => Event::Html(render_math(&src, false).into()),
Event::DisplayMath(src) => Event::Html(render_math(&src, true).into()),
Event::Start(Tag::Link {
link_type,
dest_url,
title,
id,
}) => Event::Start(Tag::Link {
link_type,
dest_url: safe_url(&dest_url).into(),
title,
id,
}),
Event::Start(Tag::Image {
link_type,
dest_url,
title,
id,
}) => Event::Start(Tag::Image {
link_type,
dest_url: safe_url(&dest_url).into(),
title,
id,
}),
// Raw HTML is core CommonMark (no opt-out flag): escape it to text so
// nothing the model writes can inject live markup.
Event::Html(s) | Event::InlineHtml(s) => Event::Text(s),
other => other,
});
let mut out = String::new();
html::push_html(&mut out, events);
out
}
/// Render a LaTeX fragment to MathML. `display` selects block (`$$…$$`) vs inline
/// (`$…$`) mode. On the rare writer error we fall back to escaped source in a
/// `<code>` so nothing is lost; invalid LaTeX is flagged inline by the crate.
fn render_math(latex: &str, display: bool) -> String {
let storage = Storage::new();
let parser = pulldown_latex::Parser::new(latex, &storage);
let config = RenderConfig {
display_mode: if display {
DisplayMode::Block
} else {
DisplayMode::Inline
},
..RenderConfig::default()
};
let mut out = String::new();
match push_mathml(&mut out, parser, config) {
Ok(()) => out,
Err(_) => format!("<code>{}</code>", escape_html(latex)),
}
}
/// Filter a link/image destination to a safe scheme. Scheme-less URLs (relative
/// paths, `#anchors`, queries) are allowed; a present scheme must be http/https/
/// mailto. ASCII control chars are stripped first because browsers ignore them
/// inside URLs, so `java\tscript:` can't smuggle a blocked scheme past the check.
fn safe_url(url: &str) -> String {
let cleaned: String = url.chars().filter(|c| !c.is_control()).collect();
let trimmed = cleaned.trim();
if let Some(colon) = trimmed.find(':') {
let scheme = &trimmed[..colon];
let looks_like_scheme = scheme
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic())
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
if looks_like_scheme {
return match scheme.to_ascii_lowercase().as_str() {
"http" | "https" | "mailto" => trimmed.to_string(),
_ => String::new(),
};
}
}
trimmed.to_string()
}
/// Minimal HTML escaping for the math fallback path.
fn escape_html(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
_ => out.push(c),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn markdown_basics() {
let html = markdown_to_safe_html("# Title\n\n**bold** and *italic*");
assert!(html.contains("<h1>"), "{html}");
assert!(html.contains("<strong>bold</strong>"), "{html}");
assert!(html.contains("<em>italic</em>"), "{html}");
}
#[test]
fn inline_math_becomes_mathml() {
let html = markdown_to_safe_html("Energy is $E=mc^2$ here.");
assert!(html.contains("<math"), "{html}");
assert!(html.contains("</math>"), "{html}");
assert!(
!html.contains('$'),
"math delimiters should be gone: {html}"
);
}
#[test]
fn display_math_is_block() {
let html = markdown_to_safe_html("$$\\int_0^1 x\\,dx$$");
assert!(html.contains("display=\"block\""), "{html}");
}
#[test]
fn raw_html_is_escaped() {
let html = markdown_to_safe_html("<script>alert(1)</script>");
assert!(!html.contains("<script>"), "{html}");
assert!(html.contains("&lt;script&gt;"), "{html}");
}
#[test]
fn javascript_link_is_stripped() {
let html = markdown_to_safe_html("[click](javascript:alert(1))");
assert!(!html.to_lowercase().contains("javascript:"), "{html}");
}
#[test]
fn data_image_is_stripped() {
let html = markdown_to_safe_html("![x](data:text/html;base64,PHNjcmlwdD4=)");
assert!(!html.to_lowercase().contains("data:"), "{html}");
}
#[test]
fn safe_link_is_preserved() {
let html = markdown_to_safe_html("[ok](https://example.com)");
assert!(html.contains("href=\"https://example.com\""), "{html}");
}
#[test]
fn code_block_html_is_escaped() {
let html = markdown_to_safe_html("```\n<div>x</div>\n```");
assert!(html.contains("<pre><code>"), "{html}");
assert!(!html.contains("<div>"), "{html}");
assert!(html.contains("&lt;div&gt;"), "{html}");
}
#[test]
fn gfm_table_renders() {
let html = markdown_to_safe_html("| a | b |\n|---|---|\n| 1 | 2 |");
assert!(html.contains("<table>"), "{html}");
assert!(html.contains("<th>"), "{html}");
}
#[test]
fn safe_url_allowlist() {
assert_eq!(safe_url("https://ok.com"), "https://ok.com");
assert_eq!(safe_url("mailto:a@b.com"), "mailto:a@b.com");
assert_eq!(safe_url("/relative/path"), "/relative/path");
assert_eq!(safe_url("#anchor"), "#anchor");
assert_eq!(safe_url("page.html?q=1"), "page.html?q=1");
// Blocked schemes, including case and control-char obfuscation.
assert_eq!(safe_url("javascript:alert(1)"), "");
assert_eq!(safe_url("JaVaScRiPt:alert(1)"), "");
assert_eq!(safe_url("java\tscript:alert(1)"), "");
assert_eq!(safe_url("data:text/html,x"), "");
assert_eq!(safe_url("vbscript:x"), "");
assert_eq!(safe_url("file:///etc/passwd"), "");
}
}
+60
View File
@@ -138,6 +138,66 @@ body.resizing { cursor: col-resize; user-select: none; }
.bubble .content { white-space: pre-wrap; word-wrap: break-word; }
.bubble .content:empty::after { content: "…"; color: var(--muted); }
/* Rendered assistant Markdown/LaTeX (server-sanitized content_html). Normal
flow instead of pre-wrap so paragraphs, lists and tables lay out correctly.
Scoped to .rendered so user bubbles and tool output are untouched. */
.bubble .content.rendered { white-space: normal; }
.content.rendered > :first-child { margin-top: 0; }
.content.rendered > :last-child { margin-bottom: 0; }
.content.rendered p { margin: 0 0 0.6em; }
.content.rendered h1, .content.rendered h2, .content.rendered h3,
.content.rendered h4, .content.rendered h5, .content.rendered h6 {
margin: 0.8em 0 0.4em; line-height: 1.25; font-weight: 600;
}
.content.rendered h1 { font-size: 1.3rem; }
.content.rendered h2 { font-size: 1.2rem; }
.content.rendered h3 { font-size: 1.1rem; }
.content.rendered h4, .content.rendered h5, .content.rendered h6 { font-size: 1rem; }
.content.rendered ul, .content.rendered ol { margin: 0 0 0.6em; padding-left: 1.4em; }
.content.rendered li { margin: 0.2em 0; }
.content.rendered li > ul, .content.rendered li > ol { margin: 0.2em 0; }
.content.rendered a { color: var(--accent); text-decoration: none; }
.content.rendered a:hover { text-decoration: underline; }
.content.rendered blockquote {
margin: 0 0 0.6em; padding: 0.2em 0 0.2em 0.9em;
border-left: 3px solid var(--border); color: var(--muted);
}
.content.rendered code {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.88em; background: var(--panel-2);
border: 1px solid var(--border); border-radius: 5px; padding: 0.1em 0.35em;
}
.content.rendered pre {
margin: 0 0 0.6em; padding: 10px 12px; overflow-x: auto;
background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
}
.content.rendered pre code {
background: none; border: none; padding: 0; font-size: 0.85rem;
white-space: pre; color: var(--text);
}
.content.rendered hr { border: none; border-top: 1px solid var(--border); margin: 0.9em 0; }
/* Tables scroll horizontally on narrow screens instead of overflowing. */
.content.rendered table {
border-collapse: collapse; margin: 0 0 0.6em; display: block;
max-width: 100%; overflow-x: auto; font-size: 0.9rem;
}
.content.rendered th, .content.rendered td {
border: 1px solid var(--border); padding: 5px 9px; text-align: left;
}
.content.rendered th { background: var(--panel-2); font-weight: 600; }
.content.rendered img { max-width: 100%; height: auto; border-radius: 8px; }
.content.rendered del { color: var(--muted); }
/* Native MathML (pulldown-latex): no JS, no web fonts needed for correctness.
Do NOT override `display` on <math>: the UA uses `block math` / `inline math`
and a plain `display:block` would destroy MathML layout (vertical stacking).
Block equations keep their native centered block layout and scroll if wide. */
.content.rendered math { font-size: 1.05em; }
.content.rendered math[display="block"] {
margin: 0.6em 0; padding: 2px 0;
overflow-x: auto; overflow-y: hidden;
}
details.thinking { margin-bottom: 8px; }
details.thinking summary {
cursor: pointer; color: var(--muted); font-size: 0.85rem; user-select: none;
+20 -6
View File
@@ -1,7 +1,8 @@
// strata-ctl web GUI — vanilla ES module, no build step, no dependencies.
// Talks to the session-aware API (/api/sessions...); the server owns context.
// Model output is always inserted via textContent (never innerHTML) to avoid
// injection. Mobile-first: the session list is an off-canvas drawer on phones.
// User text is inserted via textContent; assistant Markdown/LaTeX arrives as
// server-sanitized HTML (content_html) injected via innerHTML. Mobile-first:
// the session list is an off-canvas drawer on phones.
const $ = (sel) => document.querySelector(sel);
@@ -59,7 +60,7 @@ function el(tag, cls, text) {
return n;
}
function messageNode(role, content, reasoning, usage, ts) {
function messageNode(role, content, reasoning, usage, ts, html) {
const wrap = el("div", `msg ${role}`);
const roleNode = el("div", "role", role === "user" ? "Tu" : "Assistente");
if (ts) roleNode.appendChild(el("span", "when", " · " + stampLabel(ts)));
@@ -71,7 +72,15 @@ function messageNode(role, content, reasoning, usage, ts) {
det.appendChild(el("div", "reasoning", reasoning));
bubble.appendChild(det);
}
bubble.appendChild(el("div", "content", content || ""));
const contentNode = el("div", "content");
if (html != null) {
// Server-sanitized Markdown/LaTeX (assistant only): safe to inject.
contentNode.classList.add("rendered");
contentNode.innerHTML = html;
} else {
contentNode.textContent = content || "";
}
bubble.appendChild(contentNode);
if (usage) bubble.appendChild(el("div", "usage", usage));
wrap.appendChild(bubble);
return wrap;
@@ -179,7 +188,7 @@ function renderTranscript(messages) {
const usage = m.completion_tokens
? usageText({ prompt_tokens: m.prompt_tokens, completion_tokens: m.completion_tokens })
: null;
t.appendChild(messageNode("assistant", m.content, m.reasoning_content, usage, m.created_at));
t.appendChild(messageNode("assistant", m.content, m.reasoning_content, usage, m.created_at, m.content_html));
}
}
}
@@ -420,9 +429,14 @@ async function agentTurn(content, t, attachments) {
if (!L.text && m.content) { L.text = m.content; L.contentNode.textContent = m.content; }
if (!L.reasoning && m.reasoning_content) {
L.reasoning = m.reasoning_content;
L.reasoningNode.textContent = m.reasoning;
L.reasoningNode.textContent = L.reasoning;
L.det.hidden = false;
}
// Swap the streamed plain text for server-rendered Markdown/LaTeX.
if (ev.content_html != null) {
L.contentNode.classList.add("rendered");
L.contentNode.innerHTML = ev.content_html;
}
L.det.open = false;
if (ev.response.usage) L.bubble.appendChild(el("div", "usage", usageText(ev.response.usage)));
live = null;