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