8.1 KiB · text History 7250478
//! Markdown rendering for post bodies.
//!
//! Posts are stored as raw markdown (`raw`) plus a cached, sanitized HTML
//! rendering (`cooked`). Rendering happens at write time via [`render`].
//! Off-site links are pointed at the `/out` interstitial when the post is
//! *shown* (`crate::links::display`), not here, so the stored HTML never
//! depends on the host name or `LINK_SECRET`.
//!
//! Beyond CommonMark: tables, strikethrough, task lists, footnotes, and bare
//! `http(s)://` URLs made into links.

use std::borrow::Cow;

use pulldown_cmark::{html, CowStr, Event, LinkType, Options, Parser, Tag, TagEnd, TextMergeStream};
use sha2::{Digest, Sha256};

/// The sanitizer every post body passes through, at write time and again
/// when shown. `ammonia`'s defaults (no scripts, event handlers, styles or
/// ids) plus the footnote markup: their classes, and an `id` on a footnote's
/// `div` only when it's one of ours (`fn-…`), so a post can't clobber the
/// page's own ids.
pub fn sanitizer() -> ammonia::Builder<'static> {
    let mut b = ammonia::Builder::default();
    b.add_tag_attributes("div", &["id"])
        .add_allowed_classes("sup", &["footnote-reference", "footnote-definition-label"])
        .add_allowed_classes("div", &["footnote-definition"]);
    b
}

/// Keep a `div`'s `id` only when it's a footnote's.
pub fn footnote_ids_only<'u>(element: &str, attribute: &str, value: &'u str) -> Option<Cow<'u, str>> {
    if element == "div" && attribute == "id" && !value.starts_with("fn-") {
        return None;
    }
    Some(Cow::Borrowed(value))
}

/// Render raw markdown to sanitized HTML safe to drop into a page.
pub fn render(raw: &str) -> String {
    let mut options = Options::empty();
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_TASKLISTS);
    options.insert(Options::ENABLE_FOOTNOTES);

    // Footnote ids are unique to the post's text, so two posts on one page
    // with a [^1] each don't jump to each other's notes.
    let prefix = {
        let digest = Sha256::digest(raw.as_bytes());
        format!("fn-{}-", hex8(&digest))
    };
    let note_id = |name: &str| -> CowStr<'static> {
        let clean: String =
            name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' }).collect();
        format!("{prefix}{clean}").into()
    };

    let mut in_link = 0usize;
    let mut in_code = 0usize;
    let mut events: Vec<Event> = Vec::new();
    for event in TextMergeStream::new(Parser::new_ext(raw, options)) {
        match event {
            Event::Start(Tag::Link { .. }) => {
                in_link += 1;
                events.push(event);
            }
            Event::End(TagEnd::Link) => {
                in_link = in_link.saturating_sub(1);
                events.push(event);
            }
            Event::Start(Tag::CodeBlock(_)) => {
                in_code += 1;
                events.push(event);
            }
            Event::End(TagEnd::CodeBlock) => {
                in_code = in_code.saturating_sub(1);
                events.push(event);
            }
            Event::Text(text) if in_link == 0 && in_code == 0 => autolink(&text, &mut events),
            Event::FootnoteReference(name) => events.push(Event::FootnoteReference(note_id(&name))),
            Event::Start(Tag::FootnoteDefinition(name)) => {
                events.push(Event::Start(Tag::FootnoteDefinition(note_id(&name))))
            }
            other => events.push(other),
        }
    }
    let mut unsafe_html = String::new();
    html::push_html(&mut unsafe_html, events.into_iter());

    sanitizer().attribute_filter(footnote_ids_only).clean(&unsafe_html).to_string()
}

fn hex8(bytes: &[u8]) -> String {
    bytes.iter().take(4).map(|b| format!("{b:02x}")).collect()
}

/// Split a text run at bare `http://` / `https://` URLs, emitting each as a
/// link. A URL ends at whitespace or `<>"`; trailing sentence punctuation
/// and an unbalanced `)` are left outside it.
fn autolink(text: &str, out: &mut Vec<Event<'_>>) {
    let mut rest = text;
    while let Some(start) = find_url(rest) {
        if start > 0 {
            out.push(Event::Text(rest[..start].to_string().into()));
        }
        let tail = &rest[start..];
        let mut end = tail.find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"')).unwrap_or(tail.len());
        loop {
            let candidate = &tail[..end];
            let Some(last) = candidate.chars().last() else { break };
            let unbalanced_paren = last == ')' && candidate.matches('(').count() < candidate.matches(')').count();
            if matches!(last, '.' | ',' | ';' | ':' | '!' | '?' | '\'' | '*' | '_') || unbalanced_paren {
                end -= last.len_utf8();
            } else {
                break;
            }
        }
        let url = &tail[..end];
        let scheme_only = url.trim_start_matches("https://").trim_start_matches("http://").is_empty();
        if scheme_only {
            out.push(Event::Text(url.to_string().into()));
        } else {
            out.push(Event::Start(Tag::Link {
                link_type: LinkType::Autolink,
                dest_url: url.to_string().into(),
                title: "".into(),
                id: "".into(),
            }));
            out.push(Event::Text(url.to_string().into()));
            out.push(Event::End(TagEnd::Link));
        }
        rest = &tail[end..];
    }
    if !rest.is_empty() {
        out.push(Event::Text(rest.to_string().into()));
    }
}

/// Where the next bare URL starts, at a word boundary.
fn find_url(s: &str) -> Option<usize> {
    let lower = s.to_ascii_lowercase();
    let mut from = 0;
    while let Some(i) = lower[from..].find("http").map(|i| i + from) {
        let rest = &lower[i..];
        let boundary = i == 0 || !s[..i].chars().last().is_some_and(|c| c.is_alphanumeric());
        if boundary && (rest.starts_with("https://") || rest.starts_with("http://")) {
            return Some(i);
        }
        from = i + 4;
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn renders_basic_markdown() {
        let out = render("**bold** and *italic*");
        assert!(out.contains("<strong>bold</strong>"));
        assert!(out.contains("<em>italic</em>"));
    }

    #[test]
    fn strips_dangerous_html() {
        let out = render("<script>alert(1)</script> hi");
        assert!(!out.contains("<script>"));
        assert!(out.contains("hi"));
    }

    #[test]
    fn bare_urls_become_links() {
        let out = render("See https://example.com/a_b?c=1. And (http://x.org/wiki/Foo_(bar)), done.");
        assert!(out.contains(r#"href="https://example.com/a_b?c=1""#), "{out}");
        assert!(out.contains("https://example.com/a_b?c=1</a>."), "{out}");
        assert!(out.contains(r#"href="http://x.org/wiki/Foo_(bar)""#), "{out}");
        assert!(out.contains("</a>), done."), "{out}");
        // Not inside code, nor twice inside an existing link, nor mid-word.
        let out = render("`https://a.example` and [x](https://b.example) and xhttps://c.example\n\n    https://d.example");
        assert!(!out.contains(r#"href="https://a.example""#));
        assert_eq!(out.matches(r#"href="https://b.example""#).count(), 1);
        assert!(!out.contains(r#"href="https://c.example""#));
        assert!(!out.contains(r#"href="https://d.example""#));
        assert!(!render("just https:// alone").contains("<a"));
    }

    #[test]
    fn footnotes_link_to_their_note_and_only_their_ids_survive() {
        let out = render("Claim.[^1]\n\n[^1]: Source.");
        let id = out.split(r#"id=""#).nth(1).unwrap().split('"').next().unwrap().to_string();
        assert!(id.starts_with("fn-") && id.ends_with("-1"), "{out}");
        assert!(out.contains(&format!(r##"href="#{id}""##)), "{out}");
        assert!(out.contains(r#"class="footnote-definition""#));
        // Another post's [^1] gets another id.
        let other = render("Different.[^1]\n\n[^1]: Elsewhere.");
        assert!(!other.contains(&id));
        // A post can't set arbitrary ids.
        let out = render(r#"<div id="content">x</div>"#);
        assert!(!out.contains("id="), "{out}");
    }
}