Skip to main content

plexus_ui_engine/html/
mod.rs

1//! UI-10: **HTML the page may hold** — `{@html expr}` draws the
2//! expression's text as HTML, and `markdown(text)` makes HTML of
3//! markdown; both go through [`sanitize`] first.
4//!
5//! The sanitizer is an allow-list: it parses the text into elements and
6//! text, keeps a tag only when it is listed ([`ALLOWED_TAGS`]) and an
7//! attribute only when it is listed for its tag ([`allowed_attr`]); a URL
8//! attribute keeps only `http:`, `https:`, `#…` and `mailto:` values. A tag
9//! not listed is dropped and its text kept — except `script`, `style`,
10//! `iframe`, `object`, `embed`, `noscript`, `template`, `svg` and `math`,
11//! dropped with everything inside. What it answers is a tree the engine
12//! draws through the renderer: no HTML string reaches the page.
13
14/// A sanitized node.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum HNode {
17    Element { tag: String, attrs: Vec<(String, String)>, children: Vec<HNode> },
18    Text(String),
19}
20
21/// The tags kept.
22pub const ALLOWED_TAGS: &[&str] = &[
23    "a", "abbr", "b", "blockquote", "br", "code", "dd", "del", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "img", "kbd", "li",
24    "mark", "ol", "p", "pre", "q", "s", "small", "span", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u", "ul",
25];
26
27/// Elements with no content and no end tag.
28const VOID: &[&str] = &["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"];
29
30/// Dropped with everything inside them.
31const DROPPED_WHOLE: &[&str] = &["script", "style", "iframe", "object", "embed", "noscript", "template", "svg", "math", "textarea", "title", "head", "frameset", "frame", "noembed", "xmp", "plaintext"];
32
33/// Whose content is raw text (no tags inside, up to the end tag).
34const RAW_TEXT: &[&str] = &["script", "style", "textarea", "title", "xmp", "noembed", "plaintext"];
35
36/// Attributes that hold a URL: kept only for `http:`, `https:`, `#…`, `mailto:`.
37const URL_ATTRS: &[&str] = &["href", "src"];
38
39/// Every `(tag, attribute)` kept; `*` is any allowed tag. Widening it is a
40/// deliberate edit (html/tests.rs pins it).
41pub const ALLOWED_ATTRS: &[(&str, &str)] = &[
42    ("*", "title"),
43    ("a", "href"),
44    ("code", "class"),
45    ("img", "alt"),
46    ("img", "height"),
47    ("img", "src"),
48    ("img", "width"),
49    ("ol", "start"),
50    ("pre", "class"),
51    ("td", "colspan"),
52    ("td", "rowspan"),
53    ("th", "colspan"),
54    ("th", "rowspan"),
55];
56
57/// Whether `attr` is kept on `tag` ([`ALLOWED_ATTRS`]; on a house mark,
58/// [`house_attr`]).
59pub fn allowed_attr(tag: &str, attr: &str) -> bool {
60    if house_tag(tag) {
61        return house_attr(attr);
62    }
63    ALLOWED_TAGS.contains(&tag) && ALLOWED_ATTRS.iter().any(|(t, a)| (*t == "*" || *t == tag) && *a == attr)
64}
65
66/// EDITOR-8: **a house mark** — `m-<name>` (`m-summary`, `m-field`,
67/// `m-decision`, …), letters, digits and `-` after the `m-`. A tenant's body
68/// draws its marks as cards in CSS (the element is inert: no script defines
69/// it here, and nothing on it loads or runs), so the tag is kept with the
70/// plain-text attributes its card reads ([`house_attr`]) and nothing else.
71pub fn house_tag(tag: &str) -> bool {
72    tag.len() > 2 && tag.starts_with("m-") && tag[2..].bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
73}
74
75/// EDITOR-9: a custom element's name — letters, digits and `-`, with a `-`, beginning with a letter
76/// (`volt-poll`, `x-new`); not a house mark's (those stay themselves).
77pub fn custom_tag(tag: &str) -> bool {
78    tag.contains('-') && tag.as_bytes().first().is_some_and(|c| c.is_ascii_lowercase()) && tag.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
79}
80
81/// The plain-text attributes a house mark keeps beside `data-*` (and `id`,
82/// kept as `data-id`: an element's `id` names a global on `window`).
83pub const HOUSE_ATTRS: &[&str] = &[
84    "benefit", "by", "commits", "cost", "date", "description", "heading", "kicker", "kind", "label", "labels", "lang", "name", "path", "picked",
85    "recommended", "ref", "size", "status", "ticket", "title", "tone", "value", "why",
86];
87
88/// FRAME-29's bound mark: never planted by untrusted text, on any tag.
89const BOUND_MARK: &[&str] = &["data-slot", "data-component", "data-version", "data-layout"];
90
91/// Whether a house mark keeps `attr`: a `data-*` (letters, digits, `-`) but
92/// the bound mark's four, or one of [`HOUSE_ATTRS`]. No handler, no style, no
93/// URL.
94pub fn house_attr(attr: &str) -> bool {
95    let data = attr.len() > 5
96        && attr.starts_with("data-")
97        && attr[5..].bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
98        && !BOUND_MARK.contains(&attr);
99    data || HOUSE_ATTRS.contains(&attr)
100}
101
102fn url_ok(value: &str) -> bool {
103    let v = value.trim().to_ascii_lowercase();
104    v.starts_with("https://") || v.starts_with("http://") || v.starts_with("mailto:") || v.starts_with('#')
105}
106
107/// `&amp;`, `&lt;`, `&#39;`, `&#x27;`, … decoded; an unknown entity kept as written.
108fn decode(text: &str) -> String {
109    let mut out = String::with_capacity(text.len());
110    let mut rest = text;
111    while let Some(i) = rest.find('&') {
112        out.push_str(&rest[..i]);
113        rest = &rest[i..];
114        let end = rest[1..].find(|c: char| c == ';' || c == '&' || c.is_whitespace() || c == '<').map(|j| j + 1);
115        let decoded = match end.filter(|e| rest.as_bytes().get(*e) == Some(&b';')) {
116            Some(e) => {
117                let name = &rest[1..e];
118                let ch = match name {
119                    "amp" => Some('&'),
120                    "lt" => Some('<'),
121                    "gt" => Some('>'),
122                    "quot" => Some('"'),
123                    "apos" => Some('\''),
124                    "nbsp" => Some('\u{a0}'),
125                    n if n.starts_with("#x") || n.starts_with("#X") => u32::from_str_radix(&n[2..], 16).ok().and_then(char::from_u32),
126                    n if n.starts_with('#') => n[1..].parse::<u32>().ok().and_then(char::from_u32),
127                    _ => None,
128                };
129                ch.map(|c| (c, e + 1))
130            }
131            None => None,
132        };
133        match decoded {
134            Some((c, len)) => {
135                out.push(c);
136                rest = &rest[len..];
137            }
138            None => {
139                out.push('&');
140                rest = &rest[1..];
141            }
142        }
143    }
144    out.push_str(rest);
145    out
146}
147
148/// An open element while parsing.
149struct Open {
150    /// The name its end tag says (EDITOR-9: a custom tag's own, kept as `m-el`).
151    name: String,
152    tag: String,
153    attrs: Vec<(String, String)>,
154    children: Vec<HNode>,
155}
156
157fn push_text(stack: &mut [Open], root: &mut Vec<HNode>, text: String) {
158    if text.is_empty() {
159        return;
160    }
161    let into = match stack.last_mut() {
162        Some(o) => &mut o.children,
163        None => root,
164    };
165    if let Some(HNode::Text(t)) = into.last_mut() {
166        t.push_str(&text);
167    } else {
168        into.push(HNode::Text(text));
169    }
170}
171
172fn close(stack: &mut Vec<Open>, root: &mut Vec<HNode>) {
173    if let Some(o) = stack.pop() {
174        let node = HNode::Element { tag: o.tag, attrs: o.attrs, children: o.children };
175        match stack.last_mut() {
176            Some(p) => p.children.push(node),
177            None => root.push(node),
178        }
179    }
180}
181
182/// A tag's name at `s` (letters, digits, `-`), lower-cased.
183fn tag_name(s: &str) -> Option<(String, usize)> {
184    let b = s.as_bytes();
185    if !b.first()?.is_ascii_alphabetic() {
186        return None;
187    }
188    let n = b.iter().position(|c| !(c.is_ascii_alphanumeric() || *c == b'-' || *c == b':')).unwrap_or(b.len());
189    Some((s[..n].to_ascii_lowercase(), n))
190}
191
192/// The attributes of a start tag from `s` (after its name) to its `>`:
193/// the attributes, whether it closed itself, and how far it went.
194fn attributes(s: &str) -> (Vec<(String, String)>, bool, usize) {
195    let b = s.as_bytes();
196    let mut i = 0;
197    let mut attrs = Vec::new();
198    loop {
199        while i < b.len() && (b[i].is_ascii_whitespace() || b[i] == b'/') {
200            if b[i] == b'/' && b.get(i + 1) == Some(&b'>') {
201                return (attrs, true, i + 2);
202            }
203            i += 1;
204        }
205        if i >= b.len() {
206            return (attrs, false, i);
207        }
208        if b[i] == b'>' {
209            return (attrs, false, i + 1);
210        }
211        let start = i;
212        while i < b.len() && !(b[i].is_ascii_whitespace() || b[i] == b'=' || b[i] == b'>' || b[i] == b'/') {
213            i += 1;
214        }
215        let name = s[start..i].to_ascii_lowercase();
216        while i < b.len() && b[i].is_ascii_whitespace() {
217            i += 1;
218        }
219        let mut value = String::new();
220        if b.get(i) == Some(&b'=') {
221            i += 1;
222            while i < b.len() && b[i].is_ascii_whitespace() {
223                i += 1;
224            }
225            match b.get(i) {
226                Some(&q) if q == b'"' || q == b'\'' => {
227                    let end = s[i + 1..].find(q as char).map(|e| i + 1 + e).unwrap_or(b.len());
228                    value = decode(&s[i + 1..end]);
229                    i = (end + 1).min(b.len());
230                }
231                _ => {
232                    let vs = i;
233                    while i < b.len() && !(b[i].is_ascii_whitespace() || b[i] == b'>') {
234                        i += 1;
235                    }
236                    value = decode(&s[vs..i]);
237                }
238            }
239        }
240        if !name.is_empty() {
241            attrs.push((name, value));
242        }
243    }
244}
245
246/// Where the end tag `</tag` closing a dropped element is, counting the
247/// same tag opened inside it (raw text: the first end tag); none: the end.
248fn skip_to_end(s: &str, tag: &str) -> usize {
249    let lower = s.to_ascii_lowercase();
250    let (open, close) = (format!("<{tag}"), format!("</{tag}"));
251    let raw = RAW_TEXT.contains(&tag);
252    // `<svg` names svg only when the name ends there (`<svgx` does not).
253    let find = |from: usize, pat: &str| -> Option<usize> {
254        let mut at = from;
255        while let Some(j) = lower[at..].find(pat) {
256            let k = at + j;
257            match lower.as_bytes().get(k + pat.len()) {
258                Some(c) if c.is_ascii_alphanumeric() || *c == b'-' || *c == b':' => at = k + pat.len(),
259                _ => return Some(k),
260            }
261        }
262        None
263    };
264    let mut depth = 1;
265    let mut i = 0;
266    loop {
267        let next_close = find(i, &close);
268        let next_open = if raw { None } else { find(i, &open) };
269        match (next_open, next_close) {
270            (Some(o), Some(c)) if o < c => {
271                depth += 1;
272                i = o + open.len();
273            }
274            (_, Some(c)) => {
275                depth -= 1;
276                let gt = lower[c..].find('>').map(|g| c + g + 1).unwrap_or(s.len());
277                if depth == 0 {
278                    return gt;
279                }
280                i = gt;
281            }
282            (_, None) => return s.len(),
283        }
284    }
285}
286
287/// `html`, parsed and kept to the allow-list.
288pub fn sanitize(html: &str) -> Vec<HNode> {
289    let mut root = Vec::new();
290    let mut stack: Vec<Open> = Vec::new();
291    let mut text = String::new();
292    let mut i = 0;
293    let s = html;
294    while i < s.len() {
295        let rest = &s[i..];
296        let Some(lt) = rest.find('<') else {
297            text.push_str(rest);
298            break;
299        };
300        text.push_str(&rest[..lt]);
301        i += lt;
302        let rest = &s[i..];
303        if rest.starts_with("<!--") {
304            push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
305            i += rest.find("-->").map(|e| e + 3).unwrap_or(rest.len());
306            continue;
307        }
308        if rest.starts_with("<!") || rest.starts_with("<?") {
309            push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
310            i += rest.find('>').map(|e| e + 1).unwrap_or(rest.len());
311            continue;
312        }
313        if let Some((name, n)) = rest.strip_prefix("</").and_then(tag_name) {
314            push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
315            i += 2 + n + rest[2 + n..].find('>').map(|e| e + 1).unwrap_or(rest.len() - 2 - n);
316            if let Some(at) = stack.iter().rposition(|o| o.name == name) {
317                while stack.len() > at {
318                    close(&mut stack, &mut root);
319                }
320            }
321            continue;
322        }
323        let Some((name, n)) = tag_name(&rest[1..]) else {
324            text.push('<');
325            i += 1;
326            continue;
327        };
328        push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
329        let (attrs, self_closed, used) = attributes(&rest[1 + n..]);
330        i += 1 + n + used;
331        if DROPPED_WHOLE.contains(&name.as_str()) {
332            if !VOID.contains(&name.as_str()) && !self_closed {
333                i += skip_to_end(&s[i..], &name);
334            }
335            continue;
336        }
337        // EDITOR-9: any other custom element's tag (a `-` in its name: `volt-poll`) is kept inert as
338        // `m-el`, its own name as `data-tag` — a name a page may define is never planted, and the
339        // body's words inside it still draw, in a neutral box the tenant styles.
340        let custom = !house_tag(&name) && !ALLOWED_TAGS.contains(&name.as_str()) && custom_tag(&name);
341        let (name, tag) = if custom { (name.clone(), "m-el".to_string()) } else { (name.clone(), name) };
342        let house = house_tag(&tag);
343        if !ALLOWED_TAGS.contains(&tag.as_str()) && !house {
344            continue;
345        }
346        let attrs: Vec<(String, String)> = if house {
347            // EDITOR-8: `id` as `data-id` (unless the mark says one itself), then the house's list.
348            let named = attrs.iter().any(|(a, _)| a == "data-id");
349            let mut kept: Vec<(String, String)> = Vec::new();
350            if custom {
351                kept.push(("data-tag".to_string(), name.clone()));
352            }
353            for (a, v) in attrs {
354                let a = if a == "id" && !named { "data-id".to_string() } else { a };
355                if house_attr(&a) && !kept.iter().any(|(k, _)| *k == a) && !(custom && a == "data-tag") {
356                    kept.push((a, v));
357                }
358            }
359            kept
360        } else {
361            attrs.into_iter().filter(|(a, v)| allowed_attr(&name, a) && (!URL_ATTRS.contains(&a.as_str()) || url_ok(v))).collect()
362        };
363        if VOID.contains(&tag.as_str()) || self_closed {
364            let node = HNode::Element { tag, attrs, children: Vec::new() };
365            match stack.last_mut() {
366                Some(p) => p.children.push(node),
367                None => root.push(node),
368            }
369        } else {
370            stack.push(Open { name, tag, attrs, children: Vec::new() });
371        }
372    }
373    push_text(&mut stack, &mut root, decode(&text));
374    while !stack.is_empty() {
375        close(&mut stack, &mut root);
376    }
377    root
378}
379
380fn escape(text: &str, attr: bool) -> String {
381    let mut out = String::with_capacity(text.len());
382    for c in text.chars() {
383        match c {
384            '&' => out.push_str("&amp;"),
385            '<' => out.push_str("&lt;"),
386            '>' => out.push_str("&gt;"),
387            '"' if attr => out.push_str("&quot;"),
388            c => out.push(c),
389        }
390    }
391    out
392}
393
394/// The nodes as HTML text (escaped), for the tests and the console.
395pub fn to_html(nodes: &[HNode]) -> String {
396    let mut out = String::new();
397    for n in nodes {
398        match n {
399            HNode::Text(t) => out.push_str(&escape(t, false)),
400            HNode::Element { tag, attrs, children } => {
401                out.push('<');
402                out.push_str(tag);
403                for (k, v) in attrs {
404                    out.push_str(&format!(" {k}=\"{}\"", escape(v, true)));
405                }
406                out.push('>');
407                if !VOID.contains(&tag.as_str()) {
408                    out.push_str(&to_html(children));
409                    out.push_str(&format!("</{tag}>"));
410                }
411            }
412        }
413    }
414    out
415}
416
417/// Markdown as HTML (CommonMark with tables and strikethrough); raw HTML in
418/// it passes through, to be sanitized where it is drawn.
419pub fn markdown(text: &str) -> String {
420    use pulldown_cmark::{html, Options, Parser};
421    let mut out = String::new();
422    html::push_html(&mut out, Parser::new_ext(text, Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH));
423    out
424}
425
426#[cfg(test)]
427mod tests;