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
88const BOUND_MARK: &[&str] = &["data-slot", "data-component", "data-version", "data-layout"];
90
91pub 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
107fn 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
148struct Open {
150 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
182fn 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
192fn 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
246fn 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 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
287pub 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 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 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("&"),
385 '<' => out.push_str("<"),
386 '>' => out.push_str(">"),
387 '"' if attr => out.push_str("""),
388 c => out.push(c),
389 }
390 }
391 out
392}
393
394pub 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
417pub 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;