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/// COMPS-4: where a house mark's or a custom tag's other attributes go — a
89/// tag in a body names a component, its attributes its props: kept inert
90/// under this prefix (`<x-counter start="3">` → `data-prop-start="3"`).
91pub const PROP_PREFIX: &str = "data-prop-";
92
93/// COMPS-4: an attribute kept as a prop ([`PROP_PREFIX`]) — letters, digits
94/// and `-`, beginning with a letter; never a handler (`on…`), a style, a
95/// URL (`href`, `src`) or a `data-*` (those are [`house_attr`]'s, the bound
96/// mark's dropped).
97pub fn prop_attr(attr: &str) -> bool {
98    attr.as_bytes().first().is_some_and(u8::is_ascii_lowercase)
99        && attr.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
100        && !attr.starts_with("on")
101        && !attr.starts_with("data-")
102        && !matches!(attr, "style" | "href" | "src" | "id")
103}
104
105/// FRAME-29's bound mark: never planted by untrusted text, on any tag.
106const BOUND_MARK: &[&str] = &["data-slot", "data-component", "data-version", "data-layout"];
107
108/// Whether a house mark keeps `attr`: a `data-*` (letters, digits, `-`) but
109/// the bound mark's four, or one of [`HOUSE_ATTRS`]. No handler, no style, no
110/// URL.
111pub fn house_attr(attr: &str) -> bool {
112    let data = attr.len() > 5
113        && attr.starts_with("data-")
114        && attr[5..].bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
115        && !BOUND_MARK.contains(&attr);
116    data || HOUSE_ATTRS.contains(&attr)
117}
118
119fn url_ok(value: &str) -> bool {
120    let v = value.trim().to_ascii_lowercase();
121    v.starts_with("https://") || v.starts_with("http://") || v.starts_with("mailto:") || v.starts_with('#')
122}
123
124/// `&amp;`, `&lt;`, `&#39;`, `&#x27;`, … decoded; an unknown entity kept as written.
125fn decode(text: &str) -> String {
126    let mut out = String::with_capacity(text.len());
127    let mut rest = text;
128    while let Some(i) = rest.find('&') {
129        out.push_str(&rest[..i]);
130        rest = &rest[i..];
131        let end = rest[1..].find(|c: char| c == ';' || c == '&' || c.is_whitespace() || c == '<').map(|j| j + 1);
132        let decoded = match end.filter(|e| rest.as_bytes().get(*e) == Some(&b';')) {
133            Some(e) => {
134                let name = &rest[1..e];
135                let ch = match name {
136                    "amp" => Some('&'),
137                    "lt" => Some('<'),
138                    "gt" => Some('>'),
139                    "quot" => Some('"'),
140                    "apos" => Some('\''),
141                    "nbsp" => Some('\u{a0}'),
142                    n if n.starts_with("#x") || n.starts_with("#X") => u32::from_str_radix(&n[2..], 16).ok().and_then(char::from_u32),
143                    n if n.starts_with('#') => n[1..].parse::<u32>().ok().and_then(char::from_u32),
144                    _ => None,
145                };
146                ch.map(|c| (c, e + 1))
147            }
148            None => None,
149        };
150        match decoded {
151            Some((c, len)) => {
152                out.push(c);
153                rest = &rest[len..];
154            }
155            None => {
156                out.push('&');
157                rest = &rest[1..];
158            }
159        }
160    }
161    out.push_str(rest);
162    out
163}
164
165/// An open element while parsing.
166struct Open {
167    /// The name its end tag says (EDITOR-9: a custom tag's own, kept as `m-el`).
168    name: String,
169    tag: String,
170    attrs: Vec<(String, String)>,
171    children: Vec<HNode>,
172}
173
174fn push_text(stack: &mut [Open], root: &mut Vec<HNode>, text: String) {
175    if text.is_empty() {
176        return;
177    }
178    let into = match stack.last_mut() {
179        Some(o) => &mut o.children,
180        None => root,
181    };
182    if let Some(HNode::Text(t)) = into.last_mut() {
183        t.push_str(&text);
184    } else {
185        into.push(HNode::Text(text));
186    }
187}
188
189fn close(stack: &mut Vec<Open>, root: &mut Vec<HNode>) {
190    if let Some(o) = stack.pop() {
191        let node = HNode::Element { tag: o.tag, attrs: o.attrs, children: o.children };
192        match stack.last_mut() {
193            Some(p) => p.children.push(node),
194            None => root.push(node),
195        }
196    }
197}
198
199/// A tag's name at `s` (letters, digits, `-`), lower-cased.
200fn tag_name(s: &str) -> Option<(String, usize)> {
201    let b = s.as_bytes();
202    if !b.first()?.is_ascii_alphabetic() {
203        return None;
204    }
205    let n = b.iter().position(|c| !(c.is_ascii_alphanumeric() || *c == b'-' || *c == b':')).unwrap_or(b.len());
206    Some((s[..n].to_ascii_lowercase(), n))
207}
208
209/// The attributes of a start tag from `s` (after its name) to its `>`:
210/// the attributes, whether it closed itself, and how far it went.
211fn attributes(s: &str) -> (Vec<(String, String)>, bool, usize) {
212    let b = s.as_bytes();
213    let mut i = 0;
214    let mut attrs = Vec::new();
215    loop {
216        while i < b.len() && (b[i].is_ascii_whitespace() || b[i] == b'/') {
217            if b[i] == b'/' && b.get(i + 1) == Some(&b'>') {
218                return (attrs, true, i + 2);
219            }
220            i += 1;
221        }
222        if i >= b.len() {
223            return (attrs, false, i);
224        }
225        if b[i] == b'>' {
226            return (attrs, false, i + 1);
227        }
228        let start = i;
229        while i < b.len() && !(b[i].is_ascii_whitespace() || b[i] == b'=' || b[i] == b'>' || b[i] == b'/') {
230            i += 1;
231        }
232        let name = s[start..i].to_ascii_lowercase();
233        while i < b.len() && b[i].is_ascii_whitespace() {
234            i += 1;
235        }
236        let mut value = String::new();
237        if b.get(i) == Some(&b'=') {
238            i += 1;
239            while i < b.len() && b[i].is_ascii_whitespace() {
240                i += 1;
241            }
242            match b.get(i) {
243                Some(&q) if q == b'"' || q == b'\'' => {
244                    let end = s[i + 1..].find(q as char).map(|e| i + 1 + e).unwrap_or(b.len());
245                    value = decode(&s[i + 1..end]);
246                    i = (end + 1).min(b.len());
247                }
248                _ => {
249                    let vs = i;
250                    while i < b.len() && !(b[i].is_ascii_whitespace() || b[i] == b'>') {
251                        i += 1;
252                    }
253                    value = decode(&s[vs..i]);
254                }
255            }
256        }
257        if !name.is_empty() {
258            attrs.push((name, value));
259        }
260    }
261}
262
263/// Where the end tag `</tag` closing a dropped element is, counting the
264/// same tag opened inside it (raw text: the first end tag); none: the end.
265fn skip_to_end(s: &str, tag: &str) -> usize {
266    let lower = s.to_ascii_lowercase();
267    let (open, close) = (format!("<{tag}"), format!("</{tag}"));
268    let raw = RAW_TEXT.contains(&tag);
269    // `<svg` names svg only when the name ends there (`<svgx` does not).
270    let find = |from: usize, pat: &str| -> Option<usize> {
271        let mut at = from;
272        while let Some(j) = lower[at..].find(pat) {
273            let k = at + j;
274            match lower.as_bytes().get(k + pat.len()) {
275                Some(c) if c.is_ascii_alphanumeric() || *c == b'-' || *c == b':' => at = k + pat.len(),
276                _ => return Some(k),
277            }
278        }
279        None
280    };
281    let mut depth = 1;
282    let mut i = 0;
283    loop {
284        let next_close = find(i, &close);
285        let next_open = if raw { None } else { find(i, &open) };
286        match (next_open, next_close) {
287            (Some(o), Some(c)) if o < c => {
288                depth += 1;
289                i = o + open.len();
290            }
291            (_, Some(c)) => {
292                depth -= 1;
293                let gt = lower[c..].find('>').map(|g| c + g + 1).unwrap_or(s.len());
294                if depth == 0 {
295                    return gt;
296                }
297                i = gt;
298            }
299            (_, None) => return s.len(),
300        }
301    }
302}
303
304/// `html`, parsed and kept to the allow-list.
305pub fn sanitize(html: &str) -> Vec<HNode> {
306    let mut root = Vec::new();
307    let mut stack: Vec<Open> = Vec::new();
308    let mut text = String::new();
309    let mut i = 0;
310    let s = html;
311    while i < s.len() {
312        let rest = &s[i..];
313        let Some(lt) = rest.find('<') else {
314            text.push_str(rest);
315            break;
316        };
317        text.push_str(&rest[..lt]);
318        i += lt;
319        let rest = &s[i..];
320        if rest.starts_with("<!--") {
321            push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
322            i += rest.find("-->").map(|e| e + 3).unwrap_or(rest.len());
323            continue;
324        }
325        if rest.starts_with("<!") || rest.starts_with("<?") {
326            push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
327            i += rest.find('>').map(|e| e + 1).unwrap_or(rest.len());
328            continue;
329        }
330        if let Some((name, n)) = rest.strip_prefix("</").and_then(tag_name) {
331            push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
332            i += 2 + n + rest[2 + n..].find('>').map(|e| e + 1).unwrap_or(rest.len() - 2 - n);
333            if let Some(at) = stack.iter().rposition(|o| o.name == name) {
334                while stack.len() > at {
335                    close(&mut stack, &mut root);
336                }
337            }
338            continue;
339        }
340        let Some((name, n)) = tag_name(&rest[1..]) else {
341            text.push('<');
342            i += 1;
343            continue;
344        };
345        push_text(&mut stack, &mut root, decode(&std::mem::take(&mut text)));
346        let (attrs, self_closed, used) = attributes(&rest[1 + n..]);
347        i += 1 + n + used;
348        if DROPPED_WHOLE.contains(&name.as_str()) {
349            if !VOID.contains(&name.as_str()) && !self_closed {
350                i += skip_to_end(&s[i..], &name);
351            }
352            continue;
353        }
354        // EDITOR-9: any other custom element's tag (a `-` in its name: `volt-poll`) is kept inert as
355        // `m-el`, its own name as `data-tag` — a name a page may define is never planted, and the
356        // body's words inside it still draw, in a neutral box the tenant styles.
357        let custom = !house_tag(&name) && !ALLOWED_TAGS.contains(&name.as_str()) && custom_tag(&name);
358        let (name, tag) = if custom { (name.clone(), "m-el".to_string()) } else { (name.clone(), name) };
359        let house = house_tag(&tag);
360        if !ALLOWED_TAGS.contains(&tag.as_str()) && !house {
361            continue;
362        }
363        let attrs: Vec<(String, String)> = if house {
364            // EDITOR-8: `id` as `data-id` (unless the mark says one itself), then the house's list.
365            let named = attrs.iter().any(|(a, _)| a == "data-id");
366            let mut kept: Vec<(String, String)> = Vec::new();
367            if custom {
368                kept.push(("data-tag".to_string(), name.clone()));
369            }
370            for (a, v) in attrs {
371                let a = if a == "id" && !named { "data-id".to_string() } else { a };
372                if house_attr(&a) && !kept.iter().any(|(k, _)| *k == a) && !(custom && a == "data-tag") {
373                    kept.push((a, v));
374                } else if prop_attr(&a) {
375                    // COMPS-4: any other plain attribute is a prop of the component the tag may
376                    // name, kept inert as `data-prop-<name>`.
377                    let named = format!("{PROP_PREFIX}{a}");
378                    if !kept.iter().any(|(k, _)| *k == named) {
379                        kept.push((named, v));
380                    }
381                }
382            }
383            kept
384        } else {
385            attrs.into_iter().filter(|(a, v)| allowed_attr(&name, a) && (!URL_ATTRS.contains(&a.as_str()) || url_ok(v))).collect()
386        };
387        if VOID.contains(&tag.as_str()) || self_closed {
388            let node = HNode::Element { tag, attrs, children: Vec::new() };
389            match stack.last_mut() {
390                Some(p) => p.children.push(node),
391                None => root.push(node),
392            }
393        } else {
394            stack.push(Open { name, tag, attrs, children: Vec::new() });
395        }
396    }
397    push_text(&mut stack, &mut root, decode(&text));
398    while !stack.is_empty() {
399        close(&mut stack, &mut root);
400    }
401    root
402}
403
404fn escape(text: &str, attr: bool) -> String {
405    let mut out = String::with_capacity(text.len());
406    for c in text.chars() {
407        match c {
408            '&' => out.push_str("&amp;"),
409            '<' => out.push_str("&lt;"),
410            '>' => out.push_str("&gt;"),
411            '"' if attr => out.push_str("&quot;"),
412            c => out.push(c),
413        }
414    }
415    out
416}
417
418/// The nodes as HTML text (escaped), for the tests and the console.
419pub fn to_html(nodes: &[HNode]) -> String {
420    let mut out = String::new();
421    for n in nodes {
422        match n {
423            HNode::Text(t) => out.push_str(&escape(t, false)),
424            HNode::Element { tag, attrs, children } => {
425                out.push('<');
426                out.push_str(tag);
427                for (k, v) in attrs {
428                    out.push_str(&format!(" {k}=\"{}\"", escape(v, true)));
429                }
430                out.push('>');
431                if !VOID.contains(&tag.as_str()) {
432                    out.push_str(&to_html(children));
433                    out.push_str(&format!("</{tag}>"));
434                }
435            }
436        }
437    }
438    out
439}
440
441/// Markdown as HTML (CommonMark with tables and strikethrough); raw HTML in
442/// it passes through, to be sanitized where it is drawn.
443pub fn markdown(text: &str) -> String {
444    use pulldown_cmark::{html, Options, Parser};
445    let mut out = String::new();
446    html::push_html(&mut out, Parser::new_ext(text, Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH));
447    out
448}
449
450#[cfg(test)]
451mod tests;