1#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum HNode {
17 Element { tag: String, attrs: Vec<(String, String)>, children: Vec<HNode> },
18 Text(String),
19}
20
21pub 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
27const VOID: &[&str] = &["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"];
29
30const DROPPED_WHOLE: &[&str] = &["script", "style", "iframe", "object", "embed", "noscript", "template", "svg", "math", "textarea", "title", "head", "frameset", "frame", "noembed", "xmp", "plaintext"];
32
33const RAW_TEXT: &[&str] = &["script", "style", "textarea", "title", "xmp", "noembed", "plaintext"];
35
36const URL_ATTRS: &[&str] = &["href", "src"];
38
39pub 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
57pub 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
66pub 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
75pub 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
81pub 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
88pub const PROP_PREFIX: &str = "data-prop-";
92
93pub 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
105const BOUND_MARK: &[&str] = &["data-slot", "data-component", "data-version", "data-layout"];
107
108pub 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
124fn 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
165struct Open {
167 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
199fn 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
209fn 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
263fn 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 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
304pub 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 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 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 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("&"),
409 '<' => out.push_str("<"),
410 '>' => out.push_str(">"),
411 '"' if attr => out.push_str("""),
412 c => out.push(c),
413 }
414 }
415 out
416}
417
418pub 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
441pub 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;