//! Minimal safe Markdown renderer for agent-authored text.
//!
//! Agent output (`assistant` / `plan` / `question` events, pending payloads)
//! is untrusted: it may contain raw HTML or `javascript:` links. This module
//! parses with `pulldown-cmark` but renders its own HTML subset, so nothing
//! reaches the page unescaped:
//!
//! * emitted tags: `p`, `strong` (also for headings), `em`, `code`,
//! `pre>code`, `ul`/`ol`/`li`, `br`, `hr`, `div.md-quote`, and `a[href]`
//! for `http(s)` URLs only;
//! * raw HTML blocks and inline HTML are ESCAPED and shown as text;
//! * links with any other scheme render as plain text (no ``);
//! * images render as their alt text (no external fetch under CSP `self`);
//! * everything else (tables, footnotes, metadata, …) renders as plain
//! escaped text without its wrapper tags.
use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
/// Escape `&<>"` for HTML text/attribute contexts.
fn esc(out: &mut String, s: &str) {
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
_ => out.push(c),
}
}
}
/// Only `http://` and `https://` links become ``; anything else
/// (`javascript:`, `data:`, relative, …) renders as plain text.
fn is_safe_url(url: &str) -> bool {
let u = url.trim_start();
if u.chars().any(|c| c.is_control()) {
return false;
}
let lower = u.to_ascii_lowercase();
lower.starts_with("http://") || lower.starts_with("https://")
}
/// Render the safe subset of `md` to an HTML fragment (already escaped —
/// embed with [`maud::PreEscaped`]).
pub fn render_markdown(md: &str) -> String {
let mut out = String::new();
let parser = Parser::new_ext(md, Options::empty());
// Whether each open `Link` emitted an `` (matters only at `End`).
let mut link_stack: Vec "),
Tag::Heading { .. } => out.push_str(" "),
Tag::BlockQuote(_) => out.push_str(""),
Tag::List(ordered) => {
if ordered.is_some() {
out.push_str("");
} else {
out.push_str("
");
}
}
Tag::Item => out.push_str("
`.
// Tables/footnotes/metadata/definition lists/HTML blocks:
// wrappers dropped, text children still render (escaped).
_ => {}
},
Event::End(tag) => match tag {
TagEnd::Paragraph => out.push_str(""),
TagEnd::Heading(_) => out.push_str(""),
TagEnd::BlockQuote(_) => out.push_str("
");
esc(&mut out, &t);
out.push_str("");
}
Event::Html(t) | Event::InlineHtml(t) => esc(&mut out, &t),
Event::InlineMath(t) | Event::DisplayMath(t) => esc(&mut out, &t),
Event::FootnoteReference(name) => {
out.push_str("[^");
esc(&mut out, &name);
out.push(']');
}
Event::SoftBreak => out.push('\n'),
Event::HardBreak => out.push_str("
"),
Event::Rule => out.push_str("