Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / markdown.rs

markdown.rs125 lines · 5.1 KiBRaw
1//! Minimal safe Markdown renderer for agent-authored text.
2//!
3//! Agent output (`assistant` / `plan` / `question` events, pending payloads)
4//! is untrusted: it may contain raw HTML or `javascript:` links. This module
5//! parses with `pulldown-cmark` but renders its own HTML subset, so nothing
6//! reaches the page unescaped:
7//!
8//! * emitted tags: `p`, `strong` (also for headings), `em`, `code`,
9//! `pre>code`, `ul`/`ol`/`li`, `br`, `hr`, `div.md-quote`, and `a[href]`
10//! for `http(s)` URLs only;
11//! * raw HTML blocks and inline HTML are ESCAPED and shown as text;
12//! * links with any other scheme render as plain text (no `<a>`);
13//! * images render as their alt text (no external fetch under CSP `self`);
14//! * everything else (tables, footnotes, metadata, …) renders as plain
15//! escaped text without its wrapper tags.
16
17use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
18
19/// Escape `&<>"` for HTML text/attribute contexts.
20fn esc(out: &mut String, s: &str) {
21 for c in s.chars() {
22 match c {
23 '&' => out.push_str("&amp;"),
24 '<' => out.push_str("&lt;"),
25 '>' => out.push_str("&gt;"),
26 '"' => out.push_str("&quot;"),
27 _ => out.push(c),
28 }
29 }
30}
31
32/// Only `http://` and `https://` links become `<a>`; anything else
33/// (`javascript:`, `data:`, relative, …) renders as plain text.
34fn is_safe_url(url: &str) -> bool {
35 let u = url.trim_start();
36 if u.chars().any(|c| c.is_control()) {
37 return false;
38 }
39 let lower = u.to_ascii_lowercase();
40 lower.starts_with("http://") || lower.starts_with("https://")
41}
42
43/// Render the safe subset of `md` to an HTML fragment (already escaped —
44/// embed with [`maud::PreEscaped`]).
45pub fn render_markdown(md: &str) -> String {
46 let mut out = String::new();
47 let parser = Parser::new_ext(md, Options::empty());
48 // Whether each open `Link` emitted an `<a>` (matters only at `End`).
49 let mut link_stack: Vec<bool> = Vec::new();
50 for ev in parser {
51 match ev {
52 Event::Start(tag) => match tag {
53 Tag::Paragraph => out.push_str("<p>"),
54 Tag::Heading { .. } => out.push_str("<p><strong>"),
55 Tag::BlockQuote(_) => out.push_str("<div class=\"md-quote\">"),
56 Tag::CodeBlock(_) => out.push_str("<pre class=\"md-code\"><code>"),
57 Tag::List(ordered) => {
58 if ordered.is_some() {
59 out.push_str("<ol>");
60 } else {
61 out.push_str("<ul>");
62 }
63 }
64 Tag::Item => out.push_str("<li>"),
65 Tag::Emphasis => out.push_str("<em>"),
66 Tag::Strong => out.push_str("<strong>"),
67 Tag::Strikethrough => {}
68 Tag::Link { dest_url, .. } => {
69 if is_safe_url(&dest_url) {
70 out.push_str("<a href=\"");
71 esc(&mut out, &dest_url);
72 out.push_str("\" rel=\"noopener\">");
73 link_stack.push(true);
74 } else {
75 link_stack.push(false);
76 }
77 }
78 // Images: alt-text children render as text; no `<img>`.
79 // Tables/footnotes/metadata/definition lists/HTML blocks:
80 // wrappers dropped, text children still render (escaped).
81 _ => {}
82 },
83 Event::End(tag) => match tag {
84 TagEnd::Paragraph => out.push_str("</p>"),
85 TagEnd::Heading(_) => out.push_str("</strong></p>"),
86 TagEnd::BlockQuote(_) => out.push_str("</div>"),
87 TagEnd::CodeBlock => out.push_str("</code></pre>"),
88 TagEnd::List(ordered) => {
89 if ordered {
90 out.push_str("</ol>");
91 } else {
92 out.push_str("</ul>");
93 }
94 }
95 TagEnd::Item => out.push_str("</li>"),
96 TagEnd::Emphasis => out.push_str("</em>"),
97 TagEnd::Strong => out.push_str("</strong>"),
98 TagEnd::Link if link_stack.pop().unwrap_or(false) => {
99 out.push_str("</a>");
100 }
101 _ => {}
102 },
103 Event::Text(t) => esc(&mut out, &t),
104 Event::Code(t) => {
105 out.push_str("<code>");
106 esc(&mut out, &t);
107 out.push_str("</code>");
108 }
109 Event::Html(t) | Event::InlineHtml(t) => esc(&mut out, &t),
110 Event::InlineMath(t) | Event::DisplayMath(t) => esc(&mut out, &t),
111 Event::FootnoteReference(name) => {
112 out.push_str("[^");
113 esc(&mut out, &name);
114 out.push(']');
115 }
116 Event::SoftBreak => out.push('\n'),
117 Event::HardBreak => out.push_str("<br>"),
118 Event::Rule => out.push_str("<hr>"),
119 Event::TaskListMarker(checked) => {
120 out.push_str(if checked { "☑ " } else { "☐ " });
121 }
122 }
123 }
124 out
125}