forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

markdown.rs1085 lines, 36.4 KiBHistoryRawDownload
1//! comrak + ammonia markdown rendering.
2//!
3//! Pipeline: parse with comrak (GFM extensions, raw HTML passed through),
4//! optionally rewrite link and image URLs in the AST, render to HTML, then
5//! sanitize the whole output with a strict ammonia allowlist. Nothing that
6//! comrak emits reaches the page without going through ammonia.
7
8use std::borrow::Cow;
9use std::collections::{HashMap, HashSet};
10use std::ops::Range;
11use std::sync::LazyLock;
12
13use ammonia::{Builder, UrlRelative};
14use comrak::nodes::{Ast, AstNode, NodeLink, NodeValue};
15use comrak::{Arena, Options, format_html, parse_document};
16use forge_core::issue_refs;
17
18use crate::render::emoji::emojify;
19
20/// Prefix applied to heading ids (and to in-page `#anchor` links that target them).
21const ID_PREFIX: &str = "user-content-";
22
23/// Longest username an `@mention` can name.
24const MAX_MENTION_LEN: usize = 39;
25
26/// comrak cannot put a `class` on a link, so links made for issue refs and mentions carry one of
27/// these sentinel titles, which `apply_link_classes` turns into the class before sanitizing.
28const ISSUE_REF_TITLE: &str = "forge-issue-ref";
29const USER_MENTION_TITLE: &str = "forge-user-mention";
30
31/// `rel` added to every link, internal or external. The sanitizer sets it, so raw HTML links
32/// cannot skip it.
33const EXTERNAL_REL: &str = "nofollow noopener noreferrer";
34
35/// Base URLs used to resolve relative links in a rendered file.
36///
37/// Each base ends at the directory that contains the file being rendered,
38/// with no trailing slash, e.g. `https://host/o/r/blob/main/docs`.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct LinkContext {
41 pub tree_base: String,
42 pub blob_base: String,
43 pub raw_base: String,
44 /// Issues page of the repo, e.g. `/Tahinli/forge/issues`. When set, `#N` and `@user` in text
45 /// are linked. `None` leaves them as plain text.
46 pub issues_base: Option<String>,
47}
48
49/// Renders markdown to sanitized HTML.
50///
51/// With `ctx = None` no link rewriting happens: links and images keep their
52/// source URLs, and `#anchor` links are left alone.
53pub fn render_markdown(src: &str, ctx: Option<&LinkContext>) -> String {
54 let options = markdown_options();
55 let arena = Arena::new();
56 let root = parse_document(&arena, src, &options);
57
58 emojify_text(root);
59 if let Some(ctx) = ctx {
60 rewrite_links(root, &Resolver::new(ctx));
61 if let Some(issues_base) = &ctx.issues_base {
62 link_refs(&arena, root, issues_base);
63 }
64 }
65
66 let mut html = String::new();
67 if format_html(root, &options, &mut html).is_err() {
68 return String::new();
69 }
70 SANITIZER.clean(&apply_link_classes(&html)).to_string()
71}
72
73fn markdown_options() -> Options<'static> {
74 let mut options = Options::default();
75 options.extension.table = true;
76 options.extension.tasklist = true;
77 options.extension.strikethrough = true;
78 options.extension.autolink = true;
79 options.extension.footnotes = true;
80 options.extension.alerts = true;
81 options.extension.math_dollars = true;
82 options.extension.header_id_prefix = Some(ID_PREFIX.to_string());
83 // Raw HTML is passed through to ammonia, which removes anything not allowlisted.
84 options.render.r#unsafe = true;
85 options
86}
87
88/// Resolves relative URLs against the repo.
89///
90/// The bases in a [`LinkContext`] all carry the directory of the rendered
91/// file after the ref, e.g. `.../blob/main/docs/guide`. The directory is the
92/// part after the ref segment, so `dir` is `["docs", "guide"]` here, and the
93/// repo root for each kind is the base with those trailing segments removed.
94///
95/// Root-relative links (`/x`) resolve from the repo root, not from `dir`.
96/// Relative links (`x`, `../x`) resolve from `dir`. Both kinds clamp `..` at
97/// the root, so a link can never point above the repo.
98///
99/// Limitation: the ref is assumed to be a single path segment. A branch name
100/// with a `/` in it makes the directory split wrong.
101struct Resolver {
102 tree_root: String,
103 blob_root: String,
104 raw_root: String,
105 dir: Vec<String>,
106}
107
108impl Resolver {
109 fn new(ctx: &LinkContext) -> Self {
110 let blob = ctx.blob_base.trim_end_matches('/');
111 let depth = dir_depth(blob);
112 let dir = blob
113 .split('/')
114 .rev()
115 .take(depth)
116 .filter(|seg| !seg.is_empty())
117 .map(str::to_string)
118 .collect::<Vec<_>>()
119 .into_iter()
120 .rev()
121 .collect();
122 Self {
123 tree_root: strip_segments(&ctx.tree_base, depth),
124 blob_root: strip_segments(&ctx.blob_base, depth),
125 raw_root: strip_segments(&ctx.raw_base, depth),
126 dir,
127 }
128 }
129
130 /// Returns the rewritten URL, or `None` to keep the original.
131 fn rewrite(&self, url: &str, image: bool) -> Option<String> {
132 // Attachment URLs are site-absolute and independent of the rendered file's location.
133 if url.is_empty()
134 || url.starts_with("//")
135 || has_scheme(url)
136 || url.starts_with("/attachments/")
137 {
138 return None;
139 }
140 if let Some(fragment) = url.strip_prefix('#') {
141 if fragment.is_empty() {
142 return None;
143 }
144 return Some(format!("#{ID_PREFIX}{fragment}"));
145 }
146
147 let split = url.find(['?', '#']).unwrap_or(url.len());
148 let (path, suffix) = url.split_at(split);
149 let start: &[String] = if path.starts_with('/') {
150 &[]
151 } else {
152 &self.dir
153 };
154 let segments = normalize(start, path);
155
156 if image {
157 return Some(join(&self.raw_root, &segments, suffix));
158 }
159 if segments.is_empty() || path.ends_with('/') {
160 Some(join(&self.tree_root, &segments, suffix))
161 } else {
162 Some(join(&self.blob_root, &segments, suffix))
163 }
164 }
165}
166
167/// Number of path segments after the ref in a blob/tree base, or 0 if there is none.
168///
169/// The marker is searched from index 3 on so the scheme, host, owner and repo
170/// are skipped.
171fn dir_depth(base: &str) -> usize {
172 let segments: Vec<&str> = base.split('/').collect();
173 segments
174 .iter()
175 .enumerate()
176 .skip(3)
177 .find(|(i, seg)| (**seg == "blob" || **seg == "tree") && i + 1 < segments.len())
178 .map_or(0, |(i, _)| segments.len() - (i + 2))
179}
180
181/// Removes `n` trailing path segments from a base URL.
182fn strip_segments(base: &str, n: usize) -> String {
183 let mut out = base.trim_end_matches('/');
184 for _ in 0..n {
185 match out.rfind('/') {
186 Some(i) => out = &out[..i],
187 None => break,
188 }
189 }
190 out.to_string()
191}
192
193/// Applies `path` to `start`, resolving `.` and `..`. `..` past the root is dropped.
194fn normalize(start: &[String], path: &str) -> Vec<String> {
195 let mut out = start.to_vec();
196 for seg in path.split('/') {
197 match seg {
198 "" | "." => {}
199 ".." => {
200 out.pop();
201 }
202 other => out.push(other.to_string()),
203 }
204 }
205 out
206}
207
208fn join(root: &str, segments: &[String], suffix: &str) -> String {
209 if segments.is_empty() {
210 format!("{root}{suffix}")
211 } else {
212 format!("{root}/{}{suffix}", segments.join("/"))
213 }
214}
215
216/// True for `scheme:` prefixes such as `https:`, `mailto:` or `javascript:`.
217fn has_scheme(url: &str) -> bool {
218 match url.find(':') {
219 Some(i) if i > 0 => {
220 let scheme = &url[..i];
221 scheme.starts_with(|c: char| c.is_ascii_alphabetic())
222 && scheme
223 .chars()
224 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
225 }
226 _ => false,
227 }
228}
229
230/// Replaces `:shortcode:` in text nodes. Code spans and blocks keep their literals in their own
231/// node values, so they are never `Text`. Text inside a link (such as an autolink, whose
232/// visible text must match its href) is left alone.
233fn emojify_text<'a>(root: &'a AstNode<'a>) {
234 for node in root.descendants() {
235 let in_link = node
236 .parent()
237 .is_some_and(|parent| matches!(parent.data.borrow().value, NodeValue::Link(_)));
238 if in_link {
239 continue;
240 }
241 let mut ast = node.data.borrow_mut();
242 if let NodeValue::Text(text) = &mut ast.value {
243 let replaced = match emojify(text.as_ref()) {
244 Cow::Owned(s) => Some(s),
245 Cow::Borrowed(_) => None,
246 };
247 if let Some(s) = replaced {
248 *text = s.into();
249 }
250 }
251 }
252}
253
254fn rewrite_links<'a>(root: &'a AstNode<'a>, resolver: &Resolver) {
255 for node in root.descendants() {
256 let mut ast = node.data.borrow_mut();
257 match &mut ast.value {
258 NodeValue::Link(link) => {
259 if let Some(url) = resolver.rewrite(&link.url, false) {
260 link.url = url;
261 }
262 }
263 NodeValue::Image(link) => {
264 if let Some(url) = resolver.rewrite(&link.url, true) {
265 link.url = url;
266 }
267 }
268 _ => {}
269 }
270 }
271}
272
273/// Replaces the sentinel titles of issue-ref and mention links with their classes. `rel` is not
274/// handled here: the sanitizer adds it to every link. Text quotes are escaped by comrak, so the
275/// patterns can only occur in a tag.
276fn apply_link_classes(html: &str) -> String {
277 html.replace(
278 &format!("title=\"{ISSUE_REF_TITLE}\""),
279 "class=\"issue-ref\"",
280 )
281 .replace(
282 &format!("title=\"{USER_MENTION_TITLE}\""),
283 "class=\"user-mention\"",
284 )
285}
286
287/// Turns `#N` and `@user` in text nodes into link nodes. Text inside links and images is skipped.
288/// Code spans and blocks are not text nodes, so they are skipped too. Raw HTML blocks are split
289/// so that their plain text (outside tags, code, links and raw-text elements) is linked as well.
290fn link_refs<'a>(arena: &'a Arena<'a>, root: &'a AstNode<'a>, issues_base: &str) {
291 let targets: Vec<&'a AstNode<'a>> = root
292 .descendants()
293 .filter(|node| {
294 matches!(
295 node.data.borrow().value,
296 NodeValue::Text(_) | NodeValue::HtmlBlock(_)
297 ) && !node.ancestors().skip(1).any(|ancestor| {
298 matches!(
299 ancestor.data.borrow().value,
300 NodeValue::Link(_) | NodeValue::Image(_)
301 )
302 })
303 })
304 .collect();
305
306 for node in targets {
307 let (sourcepos, value) = {
308 let ast = node.data.borrow();
309 (ast.sourcepos, ast.value.clone())
310 };
311 match value {
312 NodeValue::Text(text) => {
313 if let Some(nodes) = text_with_links(arena, sourcepos, &text, issues_base) {
314 for new in nodes {
315 node.insert_before(new);
316 }
317 node.detach();
318 }
319 }
320 NodeValue::HtmlBlock(block) => {
321 let literal = block.literal.trim_end_matches('\n').to_string();
322 let mut children = Vec::new();
323 let mut linked = false;
324 for piece in split_html(&literal) {
325 match piece {
326 HtmlPiece::Html(html) => {
327 children.push(new_node(arena, sourcepos, NodeValue::HtmlInline(html)))
328 }
329 HtmlPiece::Text(raw) => {
330 // Raw text may hold entities; comrak escapes Text nodes again, so decode
331 // them first.
332 let text = decode_entities(&raw);
333 match text_with_links(arena, sourcepos, &text, issues_base) {
334 Some(nodes) => {
335 linked = true;
336 children.extend(nodes);
337 }
338 None => children.push(new_node(
339 arena,
340 sourcepos,
341 NodeValue::Text(text.into()),
342 )),
343 }
344 }
345 }
346 }
347 // Only rewrite the block when something was actually linked.
348 if linked {
349 node.data.borrow_mut().value = NodeValue::Paragraph;
350 for child in children {
351 node.append(child);
352 }
353 }
354 }
355 _ => {}
356 }
357 }
358}
359
360/// Splits `text` into link and text nodes for every `#N` and `@user` in it. Returns `None` when
361/// there is nothing to link.
362fn text_with_links<'a>(
363 arena: &'a Arena<'a>,
364 sourcepos: comrak::nodes::Sourcepos,
365 text: &str,
366 issues_base: &str,
367) -> Option<Vec<&'a AstNode<'a>>> {
368 let mut spans: Vec<(Range<usize>, Option<i64>)> = issue_refs::issue_ref_spans(text)
369 .into_iter()
370 .map(|(range, n)| (range, Some(n)))
371 .chain(mention_spans(text).into_iter().map(|range| (range, None)))
372 .collect();
373 if spans.is_empty() {
374 return None;
375 }
376 spans.sort_by_key(|(range, _)| range.start);
377
378 let mut out = Vec::new();
379 let mut cursor = 0;
380 for (range, issue) in spans {
381 if range.start > cursor {
382 out.push(new_node(
383 arena,
384 sourcepos,
385 NodeValue::Text(text[cursor..range.start].to_string().into()),
386 ));
387 }
388 let label = &text[range.clone()];
389 let link = match issue {
390 Some(n) => new_node(
391 arena,
392 sourcepos,
393 NodeValue::Link(Box::new(NodeLink::new(
394 format!("{issues_base}/{n}"),
395 ISSUE_REF_TITLE.to_string(),
396 ))),
397 ),
398 None => new_node(
399 arena,
400 sourcepos,
401 NodeValue::Link(Box::new(NodeLink::new(
402 format!("/{}", &label[1..]),
403 USER_MENTION_TITLE.to_string(),
404 ))),
405 ),
406 };
407 link.append(new_node(
408 arena,
409 sourcepos,
410 NodeValue::Text(label.to_string().into()),
411 ));
412 out.push(link);
413 cursor = range.end;
414 }
415 if cursor < text.len() {
416 out.push(new_node(
417 arena,
418 sourcepos,
419 NodeValue::Text(text[cursor..].to_string().into()),
420 ));
421 }
422 Some(out)
423}
424
425/// A piece of a raw HTML block: markup that must stay as written, or plain text that may be linked.
426#[derive(Debug, PartialEq, Eq)]
427enum HtmlPiece {
428 Html(String),
429 Text(String),
430}
431
432/// Tags whose content is raw text (not markup) and is removed by the sanitizer.
433const RAW_TEXT_TAGS: &[&str] = &["script", "style", "textarea", "title"];
434
435/// Tags inside which nothing may be linked.
436const NO_LINK_TAGS: &[&str] = &["a", "code", "pre"];
437
438/// Splits raw HTML into markup and text. Text outside tags is `Text`, unless it sits inside a
439/// link, code or pre element, in which case it is `Html`. Raw-text elements are kept whole as `Html`.
440fn split_html(src: &str) -> Vec<HtmlPiece> {
441 let lower = src.to_ascii_lowercase();
442 let mut segments: Vec<(bool, Range<usize>)> = Vec::new();
443 let mut prev = 0;
444 let mut depth = 0usize;
445 let mut i = 0;
446 while let Some(off) = src[i..].find('<') {
447 let lt = i + off;
448 let end = if src[lt..].starts_with("<!--") {
449 src[lt..].find("-->").map_or(src.len(), |p| lt + p + 3)
450 } else {
451 match src[lt..].find('>') {
452 Some(p) => lt + p + 1,
453 None => break,
454 }
455 };
456 let inner = src[lt + 1..end].trim_end_matches('>');
457 let closing = inner.starts_with('/');
458 let name: String = inner
459 .trim_start_matches('/')
460 .chars()
461 .take_while(|c| c.is_ascii_alphanumeric())
462 .collect::<String>()
463 .to_ascii_lowercase();
464
465 if lt > prev {
466 segments.push((depth == 0, prev..lt));
467 }
468 let mut tag_end = end;
469 if !closing && RAW_TEXT_TAGS.contains(&name.as_str()) {
470 let close = format!("</{name}");
471 if let Some(p) = lower[end..].find(&close) {
472 let close_start = end + p;
473 tag_end = lower[close_start..]
474 .find('>')
475 .map_or(src.len(), |g| close_start + g + 1);
476 }
477 }
478 segments.push((false, lt..tag_end));
479 if NO_LINK_TAGS.contains(&name.as_str()) {
480 if closing {
481 depth = depth.saturating_sub(1);
482 } else {
483 depth += 1;
484 }
485 }
486 prev = tag_end;
487 i = tag_end;
488 }
489 if prev < src.len() {
490 segments.push((depth == 0, prev..src.len()));
491 }
492
493 let mut out: Vec<HtmlPiece> = Vec::new();
494 for (is_text, range) in segments {
495 let piece = &src[range];
496 let next = if is_text {
497 HtmlPiece::Text(piece.to_string())
498 } else {
499 HtmlPiece::Html(piece.to_string())
500 };
501 match (out.last_mut(), next) {
502 (Some(HtmlPiece::Html(prev_html)), HtmlPiece::Html(html)) => prev_html.push_str(&html),
503 (Some(HtmlPiece::Text(prev_text)), HtmlPiece::Text(text)) => prev_text.push_str(&text),
504 (_, next) => out.push(next),
505 }
506 }
507 out
508}
509
510/// Decodes the character references that raw HTML text may contain: the named entities `&amp;`,
511/// `&lt;`, `&gt;`, `&quot;`, `&apos;`, `&nbsp;` and numeric `&#NN;` / `&#xHH;`. Anything else is
512/// kept literally.
513fn decode_entities(text: &str) -> String {
514 let mut out = String::with_capacity(text.len());
515 let mut rest = text;
516 while let Some(amp) = rest.find('&') {
517 out.push_str(&rest[..amp]);
518 let from_amp = &rest[amp..];
519 match decode_entity(from_amp) {
520 Some((ch, len)) => {
521 out.push(ch);
522 rest = &from_amp[len..];
523 }
524 None => {
525 out.push('&');
526 rest = &from_amp[1..];
527 }
528 }
529 }
530 out.push_str(rest);
531 out
532}
533
534/// Decodes the entity at the start of `s` (which begins with `&`). Returns the character and the
535/// number of bytes the entity spans.
536fn decode_entity(s: &str) -> Option<(char, usize)> {
537 let end = s.find(';')?;
538 if end > 12 {
539 return None;
540 }
541 let body = &s[1..end];
542 let ch = if let Some(hex) = body.strip_prefix("#x").or_else(|| body.strip_prefix("#X")) {
543 if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
544 return None;
545 }
546 char::from_u32(u32::from_str_radix(hex, 16).ok()?)?
547 } else if let Some(dec) = body.strip_prefix('#') {
548 if dec.is_empty() || !dec.bytes().all(|b| b.is_ascii_digit()) {
549 return None;
550 }
551 char::from_u32(dec.parse().ok()?)?
552 } else {
553 match body {
554 "amp" => '&',
555 "lt" => '<',
556 "gt" => '>',
557 "quot" => '"',
558 "apos" => '\'',
559 "nbsp" => '\u{a0}',
560 _ => return None,
561 }
562 };
563 Some((ch, end + 1))
564}
565
566fn new_node<'a>(
567 arena: &'a Arena<'a>,
568 sourcepos: comrak::nodes::Sourcepos,
569 value: NodeValue,
570) -> &'a AstNode<'a> {
571 arena.alloc(comrak::arena_tree::Node::new(std::cell::RefCell::new(
572 Ast::new_with_sourcepos(value, sourcepos),
573 )))
574}
575
576/// Byte ranges of `@username` mentions. The `@` must start the text or follow whitespace, and the
577/// name uses `[A-Za-z0-9._-]`, at most 39 chars, without trailing dots.
578fn mention_spans(text: &str) -> Vec<Range<usize>> {
579 let bytes = text.as_bytes();
580 let mut out = Vec::new();
581 for (at, _) in text.match_indices('@') {
582 if text[..at]
583 .chars()
584 .next_back()
585 .is_some_and(|c| !c.is_whitespace())
586 {
587 continue;
588 }
589 let run = bytes[at + 1..]
590 .iter()
591 .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
592 .count();
593 let name = text[at + 1..at + 1 + run].trim_end_matches('.');
594 if name.is_empty() || name.len() > MAX_MENTION_LEN {
595 continue;
596 }
597 out.push(at..at + 1 + name.len());
598 }
599 out
600}
601
602/// Usernames `@mention`ed in markdown `text`, lowercased and deduplicated in first-seen order.
603///
604/// Parses with the same options as [`render_markdown`] and walks the text nodes that the `@user`
605/// linking would touch: code spans and blocks, and text inside links and images, are skipped.
606/// Raw HTML blocks are split the same way the linker splits them.
607pub fn mentioned_usernames(text: &str) -> Vec<String> {
608 let options = markdown_options();
609 let arena = Arena::new();
610 let root = parse_document(&arena, text, &options);
611
612 let mut found: Vec<String> = Vec::new();
613 for node in root.descendants() {
614 let ast = node.data.borrow();
615 let inside_link = node.ancestors().skip(1).any(|ancestor| {
616 matches!(
617 ancestor.data.borrow().value,
618 NodeValue::Link(_) | NodeValue::Image(_)
619 )
620 });
621 if inside_link {
622 continue;
623 }
624 match &ast.value {
625 NodeValue::Text(literal) => collect_mentions(literal, &mut found),
626 NodeValue::HtmlBlock(block) => {
627 let literal = block.literal.trim_end_matches('\n');
628 for piece in split_html(literal) {
629 if let HtmlPiece::Text(raw) = piece {
630 collect_mentions(&decode_entities(&raw), &mut found);
631 }
632 }
633 }
634 _ => {}
635 }
636 }
637 found
638}
639
640/// The task items of `src` in document order, as `(byte offset of the mark, checked)`. The mark is
641/// the character between the brackets. Tasks inside code blocks are not task items, so they are
642/// not listed.
643fn task_marks(src: &str) -> Vec<(usize, bool)> {
644 let options = markdown_options();
645 let arena = Arena::new();
646 let root = parse_document(&arena, src, &options);
647 let mut line_starts = vec![0usize];
648 for (i, b) in src.bytes().enumerate() {
649 if b == b'\n' {
650 line_starts.push(i + 1);
651 }
652 }
653 let mut out = Vec::new();
654 for node in root.descendants() {
655 if let NodeValue::TaskItem(item) = &node.data.borrow().value {
656 let pos = item.symbol_sourcepos.start;
657 let Some(line) = line_starts.get(pos.line.wrapping_sub(1)) else {
658 continue;
659 };
660 let at = line + pos.column.saturating_sub(1);
661 if at < src.len() && src.is_char_boundary(at) {
662 out.push((at, item.symbol.is_some()));
663 }
664 }
665 }
666 out
667}
668
669/// `(done, total)` task items in markdown `src`.
670pub fn task_progress(src: &str) -> (usize, usize) {
671 let marks = task_marks(src);
672 (marks.iter().filter(|(_, done)| *done).count(), marks.len())
673}
674
675/// Sets the `index`th task item (document order) to `checked`. `None` when there is no such task.
676pub fn set_task(src: &str, index: usize, checked: bool) -> Option<String> {
677 let (at, _) = *task_marks(src).get(index)?;
678 let mark = src[at..].chars().next()?;
679 let before = src[..at].chars().next_back()?;
680 if before != '[' || !(mark == ' ' || mark == 'x' || mark == 'X') {
681 return None;
682 }
683 let mut out = String::with_capacity(src.len());
684 out.push_str(&src[..at]);
685 out.push(if checked { 'x' } else { ' ' });
686 out.push_str(&src[at + mark.len_utf8()..]);
687 Some(out)
688}
689
690/// Adds the lowercased names of the `@mention`s in one text run to `found`, skipping duplicates.
691fn collect_mentions(text: &str, found: &mut Vec<String>) {
692 for range in mention_spans(text) {
693 let name = text[range.start + 1..range.end].to_ascii_lowercase();
694 if !found.contains(&name) {
695 found.push(name);
696 }
697 }
698}
699
700const TAGS: &[&str] = &[
701 "h1",
702 "h2",
703 "h3",
704 "h4",
705 "h5",
706 "h6",
707 "p",
708 "a",
709 "img",
710 "ul",
711 "ol",
712 "li",
713 "input",
714 "table",
715 "thead",
716 "tbody",
717 "tr",
718 "th",
719 "td",
720 "pre",
721 "code",
722 "blockquote",
723 "hr",
724 "br",
725 "em",
726 "strong",
727 "del",
728 "sup",
729 "sub",
730 "details",
731 "summary",
732 "kbd",
733 "div",
734 "span",
735 "section",
736];
737
738const CLASSES: &[&str] = &[
739 "markdown-alert",
740 "markdown-alert-note",
741 "markdown-alert-tip",
742 "markdown-alert-important",
743 "markdown-alert-warning",
744 "markdown-alert-caution",
745 "markdown-alert-title",
746 "footnote-ref",
747 "footnote-backref",
748 "footnotes",
749 "task-list-item",
750 "sr-only",
751 "anchor",
752 "issue-ref",
753 "user-mention",
754];
755
756const SCRIPT_LIKE: &[&str] = &[
757 "script", "style", "iframe", "object", "embed", "noscript", "template", "textarea", "title",
758 "svg", "math", "form",
759];
760
761/// Built once: the allowlist is fixed, and rebuilding it per render allocated every set again.
762static SANITIZER: LazyLock<Builder<'static>> = LazyLock::new(sanitizer);
763
764/// The strict allowlist. Anything not listed here is removed, and so are all `style`
765/// and `on*` attributes, because they are not in any attribute list.
766fn sanitizer() -> Builder<'static> {
767 let tags: HashSet<&'static str> = TAGS.iter().copied().collect();
768 let clean_content: HashSet<&'static str> = SCRIPT_LIKE.iter().copied().collect();
769 let classes: HashSet<&'static str> = CLASSES.iter().copied().collect();
770 let allowed_classes: HashMap<&'static str, HashSet<&'static str>> =
771 TAGS.iter().map(|tag| (*tag, classes.clone())).collect();
772
773 let attrs: HashMap<&'static str, HashSet<&'static str>> = [
774 ("h1", &["id"][..]),
775 ("h2", &["id"]),
776 ("h3", &["id"]),
777 ("h4", &["id"]),
778 ("h5", &["id"]),
779 ("h6", &["id"]),
780 (
781 "a",
782 &[
783 "href",
784 "title",
785 "id",
786 "data-footnote-ref",
787 "data-footnote-backref",
788 ],
789 ),
790 ("img", &["src", "alt", "title", "width", "height"]),
791 ("ol", &["start"]),
792 ("li", &["id"]),
793 ("sup", &["id"]),
794 ("section", &["id", "data-footnotes"]),
795 ("pre", &["lang"]),
796 ("td", &["align"]),
797 ("th", &["align"]),
798 ("input", &["type", "checked", "disabled"]),
799 ("details", &["open"]),
800 ("span", &["data-math-style"]),
801 ]
802 .into_iter()
803 .map(|(tag, names)| (tag, names.iter().copied().collect()))
804 .collect();
805
806 let mut builder = Builder::empty();
807 builder
808 .tags(tags)
809 .clean_content_tags(clean_content)
810 .tag_attributes(attrs)
811 .generic_attributes(HashSet::from([
812 "aria-label",
813 "aria-describedby",
814 "aria-hidden",
815 ]))
816 .allowed_classes(allowed_classes)
817 .url_schemes(HashSet::from(["http", "https", "mailto"]))
818 .url_relative(UrlRelative::PassThrough)
819 .link_rel(Some(EXTERNAL_REL))
820 .set_tag_attribute_value("input", "type", "checkbox");
821 builder
822}
823
824#[cfg(test)]
825mod tests {
826 use super::*;
827
828 fn ctx() -> LinkContext {
829 LinkContext {
830 tree_base: "https://forge.test/o/r/tree/main/guide".to_string(),
831 blob_base: "https://forge.test/o/r/blob/main/guide".to_string(),
832 raw_base: "https://raw.test/o/r/main/guide".to_string(),
833 issues_base: None,
834 }
835 }
836
837 fn issue_ctx() -> LinkContext {
838 LinkContext {
839 issues_base: Some("/o/r/issues".to_string()),
840 ..ctx()
841 }
842 }
843
844 /// `(markdown, with_ctx, fragments that must appear in the rendered HTML)`.
845 const CONTAINS_CASES: &[(&str, bool, &[&str])] = &[
846 (
847 "$x^2$ and ![a](/attachments/abc/a.png)",
848 true,
849 &[
850 "data-math-style=\"inline\"",
851 "src=\"/attachments/abc/a.png\"",
852 ],
853 ),
854 (
855 "| a | b |\n|:-|-:|\n| 1 | 2 |\n\n- [x] done\n- [ ] todo\n",
856 false,
857 &["<table>", "<td", "type=\"checkbox\"", "checked"],
858 ),
859 (
860 "<details><summary>More</summary>\n\nHidden text\n\n</details>\n",
861 false,
862 &["<details>", "<summary>More</summary>"],
863 ),
864 ("# Hello World", false, &["id=\"user-content-hello-world\""]),
865 (
866 "[t](#hello-world)",
867 true,
868 &["href=\"#user-content-hello-world\""],
869 ),
870 (
871 "[x](docs/a.md)",
872 true,
873 &["href=\"https://forge.test/o/r/blob/main/guide/docs/a.md\""],
874 ),
875 (
876 "[d](../sub/)\n\n[e](../../../../x.md)",
877 true,
878 &[
879 "href=\"https://forge.test/o/r/tree/main/sub\"",
880 "href=\"https://forge.test/o/r/blob/main/x.md\"",
881 ],
882 ),
883 (
884 "![i](../img.png)",
885 true,
886 &["src=\"https://raw.test/o/r/main/img.png\""],
887 ),
888 // The fragment belongs to the target file (e.g. #L12 on code), so it is left as is.
889 (
890 "[r](/README.md#top) [s](/a/../b.md)",
891 true,
892 &[
893 "href=\"https://forge.test/o/r/blob/main/README.md#top\"",
894 "href=\"https://forge.test/o/r/blob/main/b.md\"",
895 ],
896 ),
897 (
898 "[g](https://example.com/a?b=1)",
899 true,
900 &[
901 "href=\"https://example.com/a?b=1\"",
902 "rel=\"nofollow noopener noreferrer\"",
903 ],
904 ),
905 ("[x](docs/a.md)", false, &["href=\"docs/a.md\""]),
906 ];
907
908 #[test]
909 fn rendered_html_contains_expected_fragments() {
910 for (src, with_ctx, needles) in CONTAINS_CASES {
911 let lc = ctx();
912 let html = render_markdown(src, with_ctx.then_some(&lc));
913 for needle in needles.iter() {
914 assert!(
915 html.contains(needle),
916 "case {src:?} missing {needle:?}: {html}"
917 );
918 }
919 }
920 }
921
922 #[test]
923 fn tasks_are_counted_and_toggled() {
924 let src = "- [ ] one\n- [x] two\n - [ ] nested\n\n```\n- [ ] code\n```\n";
925 assert_eq!(task_progress(src), (1, 3));
926 let on = set_task(src, 0, true).unwrap();
927 assert!(on.starts_with("- [x] one\n"), "{on}");
928 let off = set_task(&on, 1, false).unwrap();
929 assert!(off.contains("- [ ] two"), "{off}");
930 assert_eq!(set_task(src, 2, true).unwrap().matches("[x]").count(), 2);
931 assert!(set_task(src, 3, true).is_none());
932 assert!(set_task("no tasks", 0, true).is_none());
933 }
934
935 #[test]
936 fn issue_refs_and_mentions_are_linked() {
937 let html = render_markdown("fixes #12, see @tahinli.\n\n- #3", Some(&issue_ctx()));
938 assert!(html.contains("href=\"/o/r/issues/12\""), "{html}");
939 assert!(html.contains("class=\"issue-ref\""), "{html}");
940 assert!(html.contains(">#12</a>"), "{html}");
941 assert!(html.contains("href=\"/o/r/issues/3\""), "{html}");
942 assert!(html.contains(">#3</a>"), "{html}");
943 assert!(html.contains("href=\"/tahinli\""), "{html}");
944 assert!(html.contains("class=\"user-mention\""), "{html}");
945 assert!(html.contains(">@tahinli</a>."), "{html}");
946 assert!(!html.contains("title="), "{html}");
947 }
948
949 /// Every `<a` start tag in `html` must carry the external `rel`.
950 fn assert_all_links_have_rel(html: &str) {
951 let mut count = 0;
952 for (at, _) in html.match_indices("<a") {
953 if !matches!(html[at + 2..].chars().next(), Some(' ' | '>')) {
954 continue;
955 }
956 count += 1;
957 let tag_end = html[at..].find('>').expect("unclosed tag");
958 let tag = &html[at..at + tag_end];
959 assert!(
960 tag.contains("rel=\"nofollow noopener noreferrer\""),
961 "{html}"
962 );
963 }
964 assert!(count > 0, "{html}");
965 }
966
967 #[test]
968 fn raw_html_links_always_get_rel() {
969 let html = render_markdown(
970 "<a title=\"x\" href='https://spam.example'>s</a>\n\n\
971 <a href=\"https://x.example\">x</a>\n\n<a href=\"/internal\">i</a>\n",
972 Some(&ctx()),
973 );
974 assert_all_links_have_rel(&html);
975 assert!(html.contains("href=\"https://spam.example\""), "{html}");
976 assert_all_links_have_rel(&render_markdown(
977 "<a title=\"x\" href='https://spam.example'>s</a>\n\n<a href=\"https://x.example\">x</a>",
978 None,
979 ));
980 }
981
982 #[test]
983 fn html_block_entities_are_not_double_escaped() {
984 let html = render_markdown("<div>Tom &amp; Jerry #3</div>\n", Some(&issue_ctx()));
985 assert!(html.contains("Tom &amp; Jerry"), "{html}");
986 assert!(!html.contains("&amp;amp;"), "{html}");
987 assert!(html.contains("class=\"issue-ref\""), "{html}");
988 assert!(html.contains(">#3</a>"), "{html}");
989 }
990
991 #[test]
992 fn decode_entities_handles_known_and_unknown() {
993 assert_eq!(
994 decode_entities("a &amp; b &lt;&#39;&#x41;&gt;"),
995 "a & b <'A>"
996 );
997 assert_eq!(decode_entities("&nbsp;&quot;&apos;"), "\u{a0}\"'");
998 assert_eq!(
999 decode_entities("&bogus; & &#; &#xZZ; &"),
1000 "&bogus; & &#; &#xZZ; &"
1001 );
1002 assert_eq!(decode_entities("&#0;"), "\0");
1003 }
1004
1005 #[test]
1006 fn refs_in_code_are_not_linked() {
1007 let html = render_markdown(
1008 "`#12` and @bob\n\n```\n#13 @carol\n```\n",
1009 Some(&issue_ctx()),
1010 );
1011 // `@bob` is plain text and is linked; the refs inside code are not.
1012 assert!(!html.contains("issue-ref"), "{html}");
1013 assert_eq!(html.matches("user-mention").count(), 1, "{html}");
1014 assert!(html.contains(">@bob</a>"), "{html}");
1015 assert!(!html.contains("@carol</a>"), "{html}");
1016 assert!(html.contains("<code>#12</code>"), "{html}");
1017 }
1018
1019 #[test]
1020 fn refs_inside_existing_links_are_not_doubled() {
1021 let html = render_markdown("[see #5 and @dan](https://example.com)", Some(&issue_ctx()));
1022 assert!(!html.contains("issue-ref"), "{html}");
1023 assert!(!html.contains("user-mention"), "{html}");
1024 assert_eq!(html.matches("<a ").count(), 1, "{html}");
1025 }
1026
1027 #[test]
1028 fn script_is_still_stripped_with_linking_on() {
1029 let html = render_markdown("<script>alert(1)</script> #7", Some(&issue_ctx()));
1030 assert!(!html.contains("script"), "{html}");
1031 assert!(html.contains("class=\"issue-ref\""), "{html}");
1032 assert!(html.contains(">#7</a>"), "{html}");
1033 }
1034
1035 #[test]
1036 fn no_issues_base_means_no_linking() {
1037 let html = render_markdown("#12 @tahinli", Some(&ctx()));
1038 assert!(!html.contains("issue-ref"), "{html}");
1039 assert!(!html.contains("user-mention"), "{html}");
1040 assert!(html.contains("#12 @tahinli"), "{html}");
1041 }
1042
1043 #[test]
1044 fn email_is_not_a_mention() {
1045 let html = render_markdown("write to a@b.com or @ alone", Some(&issue_ctx()));
1046 assert!(!html.contains("user-mention"), "{html}");
1047 assert!(html.contains("a@b.com"), "{html}");
1048 }
1049
1050 #[test]
1051 fn mention_names_follow_the_rules() {
1052 assert_eq!(mention_spans("@bob."), vec![0..4]);
1053 assert!(mention_spans(&format!("@{}", "a".repeat(40))).is_empty());
1054 assert_eq!(mention_spans(&format!("@{}", "a".repeat(39))), vec![0..40]);
1055 assert!(mention_spans("@.").is_empty());
1056 assert_eq!(mention_spans("x @a, @b_c-d"), vec![2..4, 6..12]);
1057 }
1058
1059 #[test]
1060 fn dangerous_markup_is_stripped() {
1061 let html = render_markdown(
1062 "<script>alert(1)</script>\n\n[x](javascript:alert(1))\n\n\
1063 <img src=x onerror=alert(1)>\n\n<span style=\"color:red\">s</span>\n",
1064 None,
1065 );
1066 assert!(!html.contains("script"), "{html}");
1067 assert!(!html.contains("javascript:"), "{html}");
1068 assert!(!html.contains("onerror"), "{html}");
1069 assert!(!html.contains("style"), "{html}");
1070 assert!(html.contains(">x</a>"), "{html}");
1071 }
1072
1073 #[test]
1074 fn emoji_shortcodes_convert_outside_code() {
1075 let html = render_markdown(
1076 "party :tada: and `:tada:` and\n\n```\n:tada:\n```\n\n:spark:\n",
1077 None,
1078 );
1079 assert!(html.contains("party 🎉 and"), "{html}");
1080 assert!(html.contains("<code>:tada:</code>"), "{html}");
1081 assert!(html.contains("<pre"), "{html}");
1082 assert!(html.contains(":spark:"), "{html}");
1083 assert!(!html.contains("<code>🎉</code>"), "{html}");
1084 }
1085}