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:
1 parent
d1b56d2c23
commit
7dd66ea138
7 files changed
+386
-13
No files matched your search
+52
-7
@@ -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,11 +676,33 @@ pub(crate) async fn session_chat(
|
||||
}
|
||||
});
|
||||
let events = UnboundedReceiverStream::new(rx)
|
||||
.map(|ev| match Event::default().json_data(&ev) {
|
||||
Ok(e) => Ok::<_, std::convert::Infallible>(e),
|
||||
Err(e) => {
|
||||
tracing::error!(error = %e, "failed to serialize agent event");
|
||||
Ok(Event::default().data("{}"))
|
||||
.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 {
|
||||
|
||||
@@ -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
@@ -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("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => 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("<script>"), "{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("");
|
||||
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("<div>"), "{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"), "");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user