From 549c7cfccb092c1c03048fde3b14e77f566db778 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Fri, 4 Dec 2026 13:29:24 +0300 Subject: [PATCH] Text: bounded CommonMark-subset Markdown parser and safe HTML renderer Add Void/Text/Markdown.hpp: a bounded CommonMark-subset parser with a safe HTML renderer. Raw HTML is always escaped, link/image destinations are allow-listed (http, https, mailto or relative), and unsafe schemes such as javascript: and data: are dropped, including entity-smuggled variants. Add html_escape to Void/Text/Html.hpp. Closes #58 --- include/Void/Text/Html.hpp | 20 + include/Void/Text/Markdown.hpp | 1129 ++++++++++++++++++++++++++++ tests/standalone/Text/Markdown.cpp | 310 ++++++++ 3 files changed, 1459 insertions(+) create mode 100644 include/Void/Text/Markdown.hpp create mode 100644 tests/standalone/Text/Markdown.cpp diff --git a/include/Void/Text/Html.hpp b/include/Void/Text/Html.hpp index 9da3c62..d666edf 100644 --- a/include/Void/Text/Html.hpp +++ b/include/Void/Text/Html.hpp @@ -42,6 +42,26 @@ inline constexpr std::array named_entities{{ }}; } // namespace Detail +/// Escape `s` for safe interpolation into HTML text or a quoted attribute: +/// `&` -> `&`, `<` -> `<`, `>` -> `>`, `"` -> `"`, `'` -> `'`. +/// Everything else is passed through byte-for-byte. +[[nodiscard]] inline std::string html_escape(std::string_view s) +{ + std::string out; + out.reserve(s.size()); + for (const char c : s) { + switch (c) { + case '&': out += "&"; break; + case '<': out += "<"; break; + case '>': out += ">"; break; + case '"': out += """; break; + case '\'': out += "'"; break; + default: out += c; break; + } + } + return out; +} + /// Decode HTML character references in `s` to UTF-8: numeric (`Ӓ`, /// `😀`) and the common named entities (& < > " ' ///   © …). Unknown or malformed references are left verbatim. diff --git a/include/Void/Text/Markdown.hpp b/include/Void/Text/Markdown.hpp new file mode 100644 index 0000000..c2676e7 --- /dev/null +++ b/include/Void/Text/Markdown.hpp @@ -0,0 +1,1129 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace Void::Text +{ + +// ── Bounded CommonMark-subset parser + safe HTML renderer ──────────────────── +// +// Supported block constructs: ATX headings, setext headings, paragraphs, +// fenced code blocks (``` and ~~~), thematic breaks, block quotes and tight or +// loose bullet/ordered lists. +// +// Supported inline constructs: emphasis/strong (* _ ** __), code spans, +// inline links and images ([text](url "title"), ![alt](url)), autolinks +// (), backslash escapes and hard line breaks. +// +// Everything else is treated as literal text: raw HTML is never passed +// through, it is escaped. Link/image destinations are allow-listed (http, +// https, mailto, or a relative URL); unsafe schemes such as javascript: and +// data: are dropped, keeping only the label text. +// +// All work is bounded by MarkdownLimits: input size, output size, block count +// and nesting depth. + +struct MarkdownLimits +{ + std::size_t max_input = 1024 * 1024; + std::size_t max_output = 8 * 1024 * 1024; + std::size_t max_blocks = 16384; + std::size_t max_depth = 32; +}; + +struct MarkdownError +{ + enum class Code : std::uint8_t + { + input_limit, + output_limit, + block_limit, + depth_limit, + }; + + Code code{Code::block_limit}; + std::size_t offset{0}; + + [[nodiscard]] constexpr bool operator==(const MarkdownError&) const noexcept = default; +}; + +struct MarkdownOptions +{ + MarkdownLimits limits{}; + bool allow_images = true; +}; + +namespace Detail +{ +inline constexpr std::size_t npos = std::string_view::npos; + +// ── ASCII helpers ───────────────────────────────────────────────────────────── + +[[nodiscard]] inline bool is_space_or_tab(char c) noexcept +{ + return c == ' ' || c == '\t'; +} + +[[nodiscard]] inline bool is_blank(std::string_view s) noexcept +{ + for (const char c : s) { + if (!is_space_or_tab(c) && c != '\r') { + return false; + } + } + return true; +} + +[[nodiscard]] inline bool is_alnum_ascii(char c) noexcept +{ + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); +} + +[[nodiscard]] inline char ascii_lower(char c) noexcept +{ + return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; +} + +[[nodiscard]] inline bool ascii_iequals(std::string_view a, std::string_view b) noexcept +{ + if (a.size() != b.size()) { + return false; + } + for (std::size_t i = 0; i < a.size(); ++i) { + if (ascii_lower(a[i]) != ascii_lower(b[i])) { + return false; + } + } + return true; +} + +[[nodiscard]] inline bool is_ascii_punct(char c) noexcept +{ + const auto u = static_cast(c); + return (u >= 33 && u <= 47) || (u >= 58 && u <= 64) || (u >= 91 && u <= 96) || + (u >= 123 && u <= 126); +} + +[[nodiscard]] inline std::string_view trim_left(std::string_view s) noexcept +{ + while (!s.empty() && is_space_or_tab(s.front())) { + s.remove_prefix(1); + } + return s; +} + +[[nodiscard]] inline std::string_view trim_right(std::string_view s) noexcept +{ + while (!s.empty() && is_space_or_tab(s.back())) { + s.remove_suffix(1); + } + return s; +} + +[[nodiscard]] inline std::string_view trim(std::string_view s) noexcept +{ + return trim_right(trim_left(s)); +} + +// Column width of leading whitespace (tab = 4). +[[nodiscard]] inline std::size_t indent_of(std::string_view s) noexcept +{ + std::size_t col = 0; + for (const char c : s) { + if (c == ' ') { + ++col; + } else if (c == '\t') { + col += 4; + } else { + break; + } + } + return col; +} + +// ── Line helpers ───────────────────────────────────────────────────────────── + +[[nodiscard]] inline std::string_view first_line(std::string_view rest) noexcept +{ + const std::size_t nl = rest.find('\n'); + std::string_view line = (nl == npos) ? rest : rest.substr(0, nl); + if (!line.empty() && line.back() == '\r') { + line.remove_suffix(1); + } + return line; +} + +inline void consume_line(std::string_view& rest) noexcept +{ + const std::size_t nl = rest.find('\n'); + if (nl == npos) { + rest = {}; + } else { + rest.remove_prefix(nl + 1); + } +} + +// ── Bounded writer ─────────────────────────────────────────────────────────── + +struct MarkdownWriter +{ + std::string out; + std::size_t limit = 0; + bool failed = false; + MarkdownError error{}; + + void fail(MarkdownError::Code code, std::size_t offset) noexcept + { + if (!failed) { + failed = true; + error = MarkdownError{code, offset}; + } + } + + void append(std::string_view s) + { + if (failed) { + return; + } + if (s.size() > limit || out.size() > limit - s.size()) { + fail(MarkdownError::Code::output_limit, out.size()); + return; + } + out.append(s); + } + + void append(char c) + { + if (failed) { + return; + } + if (out.size() >= limit) { + fail(MarkdownError::Code::output_limit, out.size()); + return; + } + out.push_back(c); + } +}; + +inline void append_escaped(MarkdownWriter& w, std::string_view s) +{ + for (const char c : s) { + switch (c) { + case '&': w.append("&"); break; + case '<': w.append("<"); break; + case '>': w.append(">"); break; + case '"': w.append("""); break; + case '\'': w.append("'"); break; + default: w.append(c); break; + } + } +} + +// ── URL allow-listing ──────────────────────────────────────────────────────── + +// Decode the handful of entity spellings that can smuggle a ':' past a naive +// scheme check (e.g. `javascript:alert(1)`). +[[nodiscard]] inline std::string decode_scheme_entities(std::string_view s) +{ + std::string out; + out.reserve(s.size()); + for (std::size_t i = 0; i < s.size();) { + if (s[i] == '&') { + const std::size_t semi = s.find(';', i + 1); + if (semi != npos && semi - i <= 8) { + const std::string_view body = s.substr(i + 1, semi - i - 1); + if (ascii_iequals(body, "colon") || body == "#58" || ascii_iequals(body, "#x3a")) { + out += ':'; + i = semi + 1; + continue; + } + } + } + out += s[i++]; + } + return out; +} + +[[nodiscard]] inline bool url_is_safe(std::string_view url) +{ + if (url.empty()) { + return true; + } + for (const char c : url) { + const auto u = static_cast(c); + if (u < 0x20 || u == 0x7F || c == ' ') { + return false; + } + } + const std::string normalized = decode_scheme_entities(url); + const std::size_t colon = normalized.find(':'); + const std::size_t sep = normalized.find_first_of("/?#"); + if (colon != std::string::npos && (sep == std::string::npos || colon < sep)) { + const std::string_view scheme = std::string_view{normalized}.substr(0, colon); + return ascii_iequals(scheme, "http") || ascii_iequals(scheme, "https") || + ascii_iequals(scheme, "mailto"); + } + return true; +} + +// ── Block line classifiers ────────────────────────────────────────────────── + +[[nodiscard]] inline bool is_fence_open(std::string_view line, + char& fence_char, + std::size_t& fence_len, + std::string_view& info) +{ + std::size_t i = 0; + while (i < line.size() && i < 3 && line[i] == ' ') { + ++i; + } + if (i >= line.size()) { + return false; + } + const char c = line[i]; + if (c != '`' && c != '~') { + return false; + } + std::size_t n = 0; + while (i + n < line.size() && line[i + n] == c) { + ++n; + } + if (n < 3) { + return false; + } + const std::string_view rest = line.substr(i + n); + if (c == '`' && rest.find('`') != npos) { + return false; + } + fence_char = c; + fence_len = n; + info = rest; + return true; +} + +[[nodiscard]] inline bool is_fence_close(std::string_view line, char c, std::size_t len) +{ + std::size_t i = 0; + while (i < line.size() && i < 3 && line[i] == ' ') { + ++i; + } + std::size_t n = 0; + while (i + n < line.size() && line[i + n] == c) { + ++n; + } + if (n < len) { + return false; + } + return is_blank(line.substr(i + n)); +} + +// Returns 1..6 for an ATX heading, else 0. +[[nodiscard]] inline int atx_heading(std::string_view line) noexcept +{ + std::size_t i = 0; + while (i < line.size() && i < 3 && line[i] == ' ') { + ++i; + } + std::size_t n = 0; + while (i + n < line.size() && line[i + n] == '#') { + ++n; + } + if (n == 0 || n > 6) { + return 0; + } + if (i + n < line.size() && line[i + n] != ' ') { + return 0; + } + return static_cast(n); +} + +[[nodiscard]] inline std::string_view heading_content(std::string_view line, int level) +{ + std::size_t i = 0; + while (i < line.size() && i < 3 && line[i] == ' ') { + ++i; + } + i += static_cast(level); + if (i < line.size() && line[i] == ' ') { + ++i; + } + std::string_view content = trim_right(line.substr(i)); + std::size_t end = content.size(); + while (end > 0 && content[end - 1] == '#') { + --end; + } + if (end < content.size() && (end == 0 || content[end - 1] == ' ')) { + content = trim_right(content.substr(0, end)); + } + return content; +} + +[[nodiscard]] inline bool is_thematic_break(std::string_view line) noexcept +{ + std::size_t i = 0; + while (i < line.size() && i < 3 && line[i] == ' ') { + ++i; + } + char marker = 0; + std::size_t count = 0; + for (; i < line.size(); ++i) { + const char c = line[i]; + if (is_space_or_tab(c)) { + continue; + } + if (c != '-' && c != '*' && c != '_') { + return false; + } + if (marker == 0) { + marker = c; + } else if (c != marker) { + return false; + } + ++count; + } + return count >= 3; +} + +[[nodiscard]] inline bool is_blockquote_line(std::string_view line) noexcept +{ + std::size_t i = 0; + while (i < line.size() && i < 3 && line[i] == ' ') { + ++i; + } + return i < line.size() && line[i] == '>'; +} + +[[nodiscard]] inline std::string_view strip_blockquote(std::string_view line) noexcept +{ + std::size_t i = 0; + while (i < line.size() && i < 3 && line[i] == ' ') { + ++i; + } + ++i; // the '>' + if (i < line.size() && line[i] == ' ') { + ++i; + } + return line.substr(i); +} + +[[nodiscard]] inline bool parse_list_marker(std::string_view line, + bool& ordered, + int& start, + std::size_t& content_offset) noexcept +{ + std::size_t i = 0; + while (i < line.size() && i < 3 && line[i] == ' ') { + ++i; + } + if (i >= line.size()) { + return false; + } + const char c = line[i]; + if (c == '-' || c == '*' || c == '+') { + if (i + 1 >= line.size() || line[i + 1] != ' ') { + return false; + } + ordered = false; + start = 1; + content_offset = i + 2; + return true; + } + if (c >= '0' && c <= '9') { + std::size_t n = 0; + long value = 0; + while (i + n < line.size() && line[i + n] >= '0' && line[i + n] <= '9' && n < 9) { + value = value * 10 + (line[i + n] - '0'); + ++n; + } + if (n == 0 || i + n >= line.size()) { + return false; + } + const char delim = line[i + n]; + if (delim != '.' && delim != ')') { + return false; + } + if (i + n + 1 < line.size() && line[i + n + 1] != ' ') { + return false; + } + ordered = true; + start = static_cast(value); + content_offset = i + n + 1; + if (content_offset < line.size()) { + ++content_offset; + } + return true; + } + return false; +} + +// Returns 1 for '=', 2 for '-', else 0. +[[nodiscard]] inline int setext_underline_level(std::string_view line) noexcept +{ + std::size_t i = 0; + while (i < line.size() && i < 3 && line[i] == ' ') { + ++i; + } + if (i >= line.size()) { + return 0; + } + const char c = line[i]; + if (c != '=' && c != '-') { + return 0; + } + std::size_t n = 0; + while (i + n < line.size() && line[i + n] == c) { + ++n; + } + if (n == 0 || !is_blank(line.substr(i + n))) { + return 0; + } + return c == '=' ? 1 : 2; +} + +[[nodiscard]] inline bool starts_block(std::string_view line) +{ + char fc = 0; + std::size_t fl = 0; + std::string_view fi; + if (is_fence_open(line, fc, fl, fi)) { + return true; + } + if (atx_heading(line) != 0) { + return true; + } + if (is_thematic_break(line)) { + return true; + } + if (is_blockquote_line(line)) { + return true; + } + bool ordered = false; + int start = 1; + std::size_t offset = 0; + return parse_list_marker(line, ordered, start, offset); +} + +[[nodiscard]] inline std::string_view first_word(std::string_view s) noexcept +{ + std::size_t i = 0; + while (i < s.size() && is_space_or_tab(s[i])) { + ++i; + } + std::size_t n = 0; + while (i + n < s.size() && !is_space_or_tab(s[i + n]) && s[i + n] != '\r') { + ++n; + } + return s.substr(i, n); +} + +// ── Inline parser ─────────────────────────────────────────────────────────── + +inline void render_inline(std::string_view s, + MarkdownWriter& w, + const MarkdownOptions& opt, + std::size_t depth); + +[[nodiscard]] inline std::size_t run_length(std::string_view s, std::size_t pos, char c) noexcept +{ + std::size_t n = 0; + while (pos + n < s.size() && s[pos + n] == c) { + ++n; + } + return n; +} + +[[nodiscard]] inline std::size_t find_closing_bracket(std::string_view s, std::size_t open) noexcept +{ + int level = 0; + for (std::size_t i = open; i < s.size(); ++i) { + const char c = s[i]; + if (c == '\\') { + ++i; + continue; + } + if (c == '[') { + ++level; + } else if (c == ']') { + --level; + if (level == 0) { + return i; + } + } + } + return npos; +} + +[[nodiscard]] inline std::size_t find_closing_paren(std::string_view s, std::size_t open) noexcept +{ + int level = 0; + for (std::size_t i = open + 1; i < s.size(); ++i) { + const char c = s[i]; + if (c == '\\') { + ++i; + continue; + } + if (c == '<') { + const std::size_t close = s.find('>', i + 1); + if (close == npos) { + return npos; + } + i = close; + continue; + } + if (c == '(') { + ++level; + } else if (c == ')') { + if (level == 0) { + return i; + } + --level; + } + } + return npos; +} + +[[nodiscard]] inline bool parse_link_target(std::string_view inside, + std::string& dest, + std::string& title) +{ + inside = trim(inside); + if (inside.empty()) { + dest.clear(); + return true; + } + std::size_t pos = 0; + if (inside.front() == '<') { + const std::size_t close = inside.find('>', 1); + if (close == npos) { + return false; + } + dest = std::string{inside.substr(1, close - 1)}; + pos = close + 1; + } else { + std::size_t level = 0; + std::size_t p = 0; + for (; p < inside.size(); ++p) { + const char c = inside[p]; + if (c == '\\' && p + 1 < inside.size()) { + ++p; + continue; + } + if (c == '(') { + ++level; + } else if (c == ')') { + if (level == 0) { + break; + } + --level; + } else if (is_space_or_tab(c) && level == 0) { + break; + } + } + dest = std::string{inside.substr(0, p)}; + pos = p; + } + inside = trim(inside.substr(pos)); + if (inside.empty()) { + return true; + } + const char open = inside.front(); + char close = open; + if (open == '(') { + close = ')'; + } else if (open != '"' && open != '\'') { + return false; + } + if (inside.size() < 2 || inside.back() != close) { + return false; + } + title = std::string{inside.substr(1, inside.size() - 2)}; + return true; +} + +[[nodiscard]] inline bool is_autolink(std::string_view s) +{ + if (s.empty() || s.size() > 255) { + return false; + } + for (const char c : s) { + if (c == ' ' || c == '<' || c == '>' || c == '"') { + return false; + } + } + const std::size_t colon = s.find(':'); + if (colon == npos) { + return false; + } + const std::string_view scheme = s.substr(0, colon); + if (!ascii_iequals(scheme, "http") && !ascii_iequals(scheme, "https") && + !ascii_iequals(scheme, "mailto")) { + return false; + } + return url_is_safe(s); +} + +[[nodiscard]] inline bool try_emphasis(std::string_view s, + std::size_t& i, + MarkdownWriter& w, + const MarkdownOptions& opt, + std::size_t depth) +{ + const char d = s[i]; + const std::size_t run = run_length(s, i, d); + if (d == '_' && i > 0 && is_alnum_ascii(s[i - 1])) { + return false; + } + if (i + run < s.size() && is_space_or_tab(s[i + run])) { + return false; + } + const std::size_t use = run >= 2 ? 2 : 1; + std::size_t j = i + use; + while (j < s.size()) { + if (s[j] == '\\') { + j += 2; + continue; + } + if (s[j] != d) { + ++j; + continue; + } + const std::size_t close_run = run_length(s, j, d); + const bool boundary_ok = + (d != '_' || j + close_run >= s.size() || !is_alnum_ascii(s[j + close_run])) && + (j == 0 || !is_space_or_tab(s[j - 1])); + if (close_run >= use && boundary_ok && j > i + use) { + // For `**…***` (and `***…***`) the extra closing delimiter closes + // an inner emphasis run, so fold it into the inner span. + const std::size_t extra = (use == 2 && close_run >= 3) ? close_run - use : 0; + const std::string_view inner = s.substr(i + use, (j + extra) - (i + use)); + w.append(use == 2 ? "" : ""); + render_inline(inner, w, opt, depth + 1); + w.append(use == 2 ? "" : ""); + i = j + use + extra; + return true; + } + j += close_run; + } + return false; +} + +[[nodiscard]] inline std::size_t try_link(std::string_view s, + std::size_t open, + MarkdownWriter& w, + const MarkdownOptions& opt, + std::size_t depth, + bool image) +{ + const std::size_t close = find_closing_bracket(s, open); + if (close == npos || close + 1 >= s.size() || s[close + 1] != '(') { + return npos; + } + const std::size_t paren = find_closing_paren(s, close + 1); + if (paren == npos) { + return npos; + } + const std::string_view label = s.substr(open + 1, close - open - 1); + std::string dest; + std::string title; + if (!parse_link_target(s.substr(close + 2, paren - close - 2), dest, title)) { + return npos; + } + if (!url_is_safe(dest)) { + render_inline(label, w, opt, depth + 1); + return paren + 1; + } + if (image) { + if (opt.allow_images) { + w.append("\"");"); + } else { + render_inline(label, w, opt, depth + 1); + } + } else { + w.append(""); + render_inline(label, w, opt, depth + 1); + w.append(""); + } + return paren + 1; +} + +inline void render_inline(std::string_view s, + MarkdownWriter& w, + const MarkdownOptions& opt, + std::size_t depth) +{ + if (w.failed) { + return; + } + if (depth > opt.limits.max_depth) { + w.fail(MarkdownError::Code::depth_limit, 0); + return; + } + std::size_t i = 0; + while (i < s.size() && !w.failed) { + const char c = s[i]; + + if (c == '\\' && i + 1 < s.size()) { + if (s[i + 1] == '\n') { + w.append("
\n"); + i += 2; + continue; + } + if (is_ascii_punct(s[i + 1])) { + append_escaped(w, s.substr(i + 1, 1)); + i += 2; + continue; + } + } + + if (c == '`') { + const std::size_t run = run_length(s, i, '`'); + std::size_t j = i + run; + std::size_t close = npos; + while (j < s.size()) { + if (s[j] == '`') { + const std::size_t m = run_length(s, j, '`'); + if (m == run) { + close = j; + break; + } + j += m; + } else { + ++j; + } + } + if (close != npos) { + std::string_view code = s.substr(i + run, close - i - run); + if (code.size() >= 2 && code.front() == ' ' && code.back() == ' ' && + code.find_first_not_of(' ') != npos) { + code.remove_prefix(1); + code.remove_suffix(1); + } + w.append(""); + append_escaped(w, code); + w.append(""); + i = close + run; + } else { + append_escaped(w, s.substr(i, run)); + i += run; + } + continue; + } + + if (c == '*' || c == '_') { + if (try_emphasis(s, i, w, opt, depth)) { + continue; + } + append_escaped(w, s.substr(i, 1)); + ++i; + continue; + } + + if (c == '[') { + const std::size_t end = try_link(s, i, w, opt, depth, false); + if (end != npos) { + i = end; + continue; + } + append_escaped(w, s.substr(i, 1)); + ++i; + continue; + } + + if (c == '!' && i + 1 < s.size() && s[i + 1] == '[') { + const std::size_t end = try_link(s, i + 1, w, opt, depth, true); + if (end != npos) { + i = end; + continue; + } + append_escaped(w, s.substr(i, 1)); + ++i; + continue; + } + + if (c == '<') { + const std::size_t close = s.find('>', i + 1); + if (close != npos) { + const std::string_view inner = s.substr(i + 1, close - i - 1); + if (is_autolink(inner)) { + w.append(""); + append_escaped(w, inner); + w.append(""); + i = close + 1; + continue; + } + } + append_escaped(w, s.substr(i, 1)); + ++i; + continue; + } + + if (c == '\n') { + if (w.out.size() >= 2 && w.out[w.out.size() - 1] == ' ' && + w.out[w.out.size() - 2] == ' ') { + w.out.resize(w.out.size() - 2); + w.append("
\n"); + } else { + w.append('\n'); + } + ++i; + continue; + } + + append_escaped(w, s.substr(i, 1)); + ++i; + } +} + +// ── Block parser ──────────────────────────────────────────────────────────── + +inline void render_blocks(std::string_view text, + MarkdownWriter& w, + const MarkdownOptions& opt, + std::size_t depth, + std::size_t& blocks, + bool tight = false); + +inline void render_blocks(std::string_view text, + MarkdownWriter& w, + const MarkdownOptions& opt, + std::size_t depth, + std::size_t& blocks, + bool tight) +{ + if (w.failed) { + return; + } + if (depth > opt.limits.max_depth) { + w.fail(MarkdownError::Code::depth_limit, 0); + return; + } + std::string_view rest = text; + while (!rest.empty() && !w.failed) { + const std::string_view line = first_line(rest); + if (is_blank(line)) { + consume_line(rest); + continue; + } + if (blocks >= opt.limits.max_blocks) { + w.fail(MarkdownError::Code::block_limit, 0); + return; + } + ++blocks; + + char fence_char = 0; + std::size_t fence_len = 0; + std::string_view info; + if (is_fence_open(line, fence_char, fence_len, info)) { + consume_line(rest); + std::string code; + while (!rest.empty()) { + const std::string_view l = first_line(rest); + if (is_fence_close(l, fence_char, fence_len)) { + consume_line(rest); + break; + } + if (!code.empty()) { + code += '\n'; + } + code.append(l); + consume_line(rest); + } + w.append("
");
+            append_escaped(w, code);
+            w.append("\n
\n"); + continue; + } + + const int level = atx_heading(line); + if (level != 0) { + consume_line(rest); + const std::string_view content = heading_content(line, level); + const char digit = static_cast('0' + level); + w.append(""); + render_inline(content, w, opt, depth + 1); + w.append("\n"); + continue; + } + + if (is_thematic_break(line)) { + consume_line(rest); + w.append("
\n"); + continue; + } + + if (is_blockquote_line(line)) { + std::string inner; + while (!rest.empty()) { + const std::string_view l = first_line(rest); + if (is_blockquote_line(l)) { + inner.append(strip_blockquote(l)); + inner += '\n'; + consume_line(rest); + } else if (is_blank(l)) { + std::string_view ahead = rest; + consume_line(ahead); + if (!ahead.empty() && is_blockquote_line(first_line(ahead))) { + inner += '\n'; + consume_line(rest); + } else { + break; + } + } else { + break; + } + } + w.append("
\n"); + render_blocks(inner, w, opt, depth + 1, blocks, false); + w.append("
\n"); + continue; + } + + bool ordered = false; + int start = 1; + std::size_t offset = 0; + if (parse_list_marker(line, ordered, start, offset)) { + w.append(ordered ? "\n"); + while (!rest.empty()) { + const std::string_view l = first_line(rest); + bool o2 = false; + int s2 = 1; + std::size_t off2 = 0; + if (!parse_list_marker(l, o2, s2, off2) || o2 != ordered) { + break; + } + consume_line(rest); + std::string item{l.substr(off2)}; + while (!rest.empty()) { + const std::string_view cont = first_line(rest); + if (is_blank(cont)) { + break; + } + bool o3 = false; + int s3 = 1; + std::size_t off3 = 0; + if (parse_list_marker(cont, o3, s3, off3)) { + break; + } + if (indent_of(cont) < 2) { + break; + } + item += '\n'; + item.append(trim_left(cont)); + consume_line(rest); + } + w.append("
  • "); + render_blocks(item, w, opt, depth + 1, blocks, true); + if (!w.failed && !w.out.empty() && w.out.back() == '\n') { + w.out.pop_back(); + } + w.append("
  • \n"); + } + w.append(ordered ? "\n" : "\n"); + continue; + } + + // Paragraph (possibly promoted to a setext heading). + std::string para; + int setext = 0; + while (!rest.empty()) { + const std::string_view l = first_line(rest); + if (is_blank(l)) { + break; + } + if (!para.empty()) { + const int lvl = setext_underline_level(l); + if (lvl != 0) { + setext = lvl; + consume_line(rest); + break; + } + if (starts_block(l)) { + break; + } + } + if (!para.empty()) { + para += '\n'; + } + para.append(l); + consume_line(rest); + } + + if (setext != 0) { + const char digit = static_cast('0' + setext); + w.append(""); + render_inline(para, w, opt, depth + 1); + w.append("\n"); + } else if (tight) { + render_inline(para, w, opt, depth + 1); + w.append('\n'); + } else { + w.append("

    "); + render_inline(para, w, opt, depth + 1); + w.append("

    \n"); + } + } +} +} // namespace Detail + +/// Parse a bounded CommonMark subset from `input` and render it to safe HTML. +/// Raw HTML is escaped, never passed through; unsafe link destinations are +/// dropped. Returns a `MarkdownError` when a configured limit is exceeded. +[[nodiscard]] inline std::expected +markdown_to_html(std::string_view input, MarkdownOptions options = {}) +{ + if (input.size() > options.limits.max_input) { + return std::unexpected{ + MarkdownError{MarkdownError::Code::input_limit, options.limits.max_input}}; + } + Detail::MarkdownWriter w; + w.limit = options.limits.max_output; + std::size_t blocks = 0; + Detail::render_blocks(input, w, options, 0, blocks, false); + if (w.failed) { + return std::unexpected{w.error}; + } + return std::move(w.out); +} + +} // namespace Void::Text diff --git a/tests/standalone/Text/Markdown.cpp b/tests/standalone/Text/Markdown.cpp new file mode 100644 index 0000000..e3e7ff0 --- /dev/null +++ b/tests/standalone/Text/Markdown.cpp @@ -0,0 +1,310 @@ +#include +#include +#include +#include + +#include +#include +#include + +namespace +{ +using Void::Text::MarkdownError; +using Void::Text::MarkdownLimits; +using Void::Text::MarkdownOptions; +using Void::Text::markdown_to_html; + +std::string render(std::string_view input) +{ + const auto r = markdown_to_html(input); + Void::Testing::expect(r.has_value()); + return r ? *r : std::string{}; +} + +MarkdownError render_error(std::string_view input, MarkdownOptions options) +{ + const auto r = markdown_to_html(input, options); + Void::Testing::expect(!r.has_value()); + return r ? MarkdownError{} : r.error(); +} +} // namespace + +// ── HTML escaping ──────────────────────────────────────────────────────────── + +Void::Testing::Test html_escape_special_characters() +{ + Void::Testing::expect_eq(Void::Text::html_escape("&'"), + std::string{"<a href="x">&'</a>"}); +} + +Void::Testing::Test html_escape_passthrough() +{ + Void::Testing::expect_eq(Void::Text::html_escape("plain text 123"), + std::string{"plain text 123"}); + Void::Testing::expect(Void::Text::html_escape("").empty()); +} + +// ── Headings and paragraphs ────────────────────────────────────────────────── + +Void::Testing::Test markdown_atx_headings() +{ + Void::Testing::expect_eq(render("# one"), std::string{"

    one

    \n"}); + Void::Testing::expect_eq(render("### three"), std::string{"

    three

    \n"}); + Void::Testing::expect_eq(render("###### six"), std::string{"
    six
    \n"}); + // Seven hashes is not a heading. + Void::Testing::expect_eq(render("####### seven"), + std::string{"

    ####### seven

    \n"}); +} + +Void::Testing::Test markdown_atx_closing_sequence() +{ + Void::Testing::expect_eq(render("## title ##"), std::string{"

    title

    \n"}); + Void::Testing::expect_eq(render("## title#"), std::string{"

    title#

    \n"}); +} + +Void::Testing::Test markdown_setext_headings() +{ + Void::Testing::expect_eq(render("Title\n====="), std::string{"

    Title

    \n"}); + Void::Testing::expect_eq(render("Title\n-----"), std::string{"

    Title

    \n"}); +} + +Void::Testing::Test markdown_paragraphs_and_soft_break() +{ + Void::Testing::expect_eq(render("one\ntwo\n\nthree"), + std::string{"

    one\ntwo

    \n

    three

    \n"}); +} + +Void::Testing::Test markdown_empty_input() +{ + Void::Testing::expect_eq(render(""), std::string{}); + Void::Testing::expect_eq(render("\n\n \n"), std::string{}); +} + +// ── Inline constructs ─────────────────────────────────────────────────────── + +Void::Testing::Test markdown_emphasis_and_strong() +{ + Void::Testing::expect_eq(render("*em*"), std::string{"

    em

    \n"}); + Void::Testing::expect_eq(render("_em_"), std::string{"

    em

    \n"}); + Void::Testing::expect_eq(render("**strong**"), + std::string{"

    strong

    \n"}); + Void::Testing::expect_eq(render("__strong__"), + std::string{"

    strong

    \n"}); + Void::Testing::expect_eq(render("**bold *and em***"), + std::string{"

    bold and em

    \n"}); +} + +Void::Testing::Test markdown_underscore_intraword_is_literal() +{ + Void::Testing::expect_eq(render("snake_case_name"), + std::string{"

    snake_case_name

    \n"}); +} + +Void::Testing::Test markdown_unmatched_delimiters_are_literal() +{ + Void::Testing::expect_eq(render("*unclosed"), std::string{"

    *unclosed

    \n"}); + Void::Testing::expect_eq(render("a * b"), std::string{"

    a * b

    \n"}); +} + +Void::Testing::Test markdown_code_spans() +{ + Void::Testing::expect_eq(render("`a < b`"), std::string{"

    a < b

    \n"}); + // A run of two backticks can contain a single backtick. + Void::Testing::expect_eq(render("``a ` b``"), + std::string{"

    a ` b

    \n"}); + // One space is trimmed from each side when both sides have one. + Void::Testing::expect_eq(render("` code `"), std::string{"

    code

    \n"}); +} + +Void::Testing::Test markdown_backslash_escapes() +{ + Void::Testing::expect_eq(render("\\*not em\\*"), std::string{"

    *not em*

    \n"}); + Void::Testing::expect_eq(render("\\[not a link\\]"), + std::string{"

    [not a link]

    \n"}); +} + +Void::Testing::Test markdown_hard_breaks() +{ + Void::Testing::expect_eq(render("one \ntwo"), + std::string{"

    one
    \ntwo

    \n"}); + Void::Testing::expect_eq(render("one\\\ntwo"), + std::string{"

    one
    \ntwo

    \n"}); +} + +// ── Links, images, autolinks ──────────────────────────────────────────────── + +Void::Testing::Test markdown_inline_link() +{ + Void::Testing::expect_eq( + render("[text](https://example.com)"), + std::string{"

    text

    \n"}); +} + +Void::Testing::Test markdown_inline_link_with_title() +{ + Void::Testing::expect_eq( + render("[text](https://example.com \"a title\")"), + std::string{"

    text

    \n"}); +} + +Void::Testing::Test markdown_relative_and_mailto_links_allowed() +{ + Void::Testing::expect(render("[/x](/x)").find("href=\"/x\"") != std::string::npos); + Void::Testing::expect(render("[#a](#a)").find("href=\"#a\"") != std::string::npos); + Void::Testing::expect(render("[m](mailto:a@b.c)").find("href=\"mailto:a@b.c\"") != + std::string::npos); +} + +Void::Testing::Test markdown_image() +{ + Void::Testing::expect_eq( + render("![alt text](https://example.com/x.png)"), + std::string{"

    \"alt

    \n"}); +} + +Void::Testing::Test markdown_image_disallowed_renders_alt() +{ + MarkdownOptions options; + options.allow_images = false; + const auto r = markdown_to_html("![alt text](https://example.com/x.png)", options); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(*r, std::string{"

    alt text

    \n"}); +} + +Void::Testing::Test markdown_autolink() +{ + Void::Testing::expect_eq( + render(""), + std::string{"

    https://example.com/a?b=1

    \n"}); +} + +// ── Blocks ────────────────────────────────────────────────────────────────── + +Void::Testing::Test markdown_thematic_break() +{ + Void::Testing::expect_eq(render("---"), std::string{"
    \n"}); + Void::Testing::expect_eq(render("***"), std::string{"
    \n"}); + Void::Testing::expect_eq(render("___"), std::string{"
    \n"}); +} + +Void::Testing::Test markdown_fenced_code_block() +{ + Void::Testing::expect_eq(render("```\nint x = 1;\n```"), + std::string{"
    int x = 1;\n
    \n"}); + Void::Testing::expect_eq( + render("```cpp\nif (a < b) {}\n```"), + std::string{"
    if (a < b) {}\n
    \n"}); + // Tilde fences work too. + Void::Testing::expect_eq(render("~~~\nx\n~~~"), + std::string{"
    x\n
    \n"}); +} + +Void::Testing::Test markdown_unclosed_fence_renders_to_end() +{ + Void::Testing::expect_eq(render("```\nabc"), + std::string{"
    abc\n
    \n"}); +} + +Void::Testing::Test markdown_unordered_list() +{ + Void::Testing::expect_eq(render("- one\n- two"), + std::string{"
      \n
    • one
    • \n
    • two
    • \n
    \n"}); + Void::Testing::expect_eq(render("* a\n* b"), + std::string{"
      \n
    • a
    • \n
    • b
    • \n
    \n"}); +} + +Void::Testing::Test markdown_ordered_list_and_start() +{ + Void::Testing::expect_eq(render("1. one\n2. two"), + std::string{"
      \n
    1. one
    2. \n
    3. two
    4. \n
    \n"}); + Void::Testing::expect_eq(render("3. three\n4. four"), + std::string{"
      \n
    1. three
    2. \n
    3. four
    4. \n
    \n"}); +} + +Void::Testing::Test markdown_blockquote() +{ + Void::Testing::expect_eq(render("> quoted"), + std::string{"
    \n

    quoted

    \n
    \n"}); + Void::Testing::expect_eq(render("> a\n> b"), + std::string{"
    \n

    a\nb

    \n
    \n"}); +} + +// ── Hostile input ────────────────────────────────────────────────────────── + +Void::Testing::Test markdown_raw_html_is_escaped() +{ + Void::Testing::expect_eq(render(""), + std::string{"

    <script>alert(1)</script>

    \n"}); + Void::Testing::expect_eq( + render(""), + std::string{"

    <img src=x onerror=alert(1)>

    \n"}); +} + +Void::Testing::Test markdown_javascript_links_dropped() +{ + Void::Testing::expect_eq(render("[x](javascript:alert(1))"), + std::string{"

    x

    \n"}); + Void::Testing::expect_eq(render("[x](JaVaScRiPt:alert(1))"), + std::string{"

    x

    \n"}); + Void::Testing::expect_eq(render("[x](data:text/html;base64,AAAA)"), + std::string{"

    x

    \n"}); + Void::Testing::expect_eq(render("[x](vbscript:msgbox(1))"), + std::string{"

    x

    \n"}); +} + +Void::Testing::Test markdown_entity_smuggled_scheme_dropped() +{ + Void::Testing::expect_eq(render("[x](javascript:alert(1))"), + std::string{"

    x

    \n"}); + Void::Testing::expect_eq(render("[x](javascript:alert(1))"), + std::string{"

    x

    \n"}); + Void::Testing::expect_eq(render("[x](javascript:alert(1))"), + std::string{"

    x

    \n"}); +} + +Void::Testing::Test markdown_attribute_injection_is_escaped() +{ + const std::string out = render("[x](https://e.com/\" onmouseover=\"alert(1))"); + Void::Testing::expect(out.find("onmouseover=\"") == std::string::npos); + Void::Testing::expect(out.find(""") != std::string::npos); +} + +Void::Testing::Test markdown_code_block_content_is_escaped() +{ + Void::Testing::expect_eq(render("```\n\n```"), + std::string{"
    </code><script>x</script>\n
    \n"}); +} + +// ── Bounds ───────────────────────────────────────────────────────────────── + +Void::Testing::Test markdown_input_limit() +{ + MarkdownOptions options; + options.limits.max_input = 4; + const auto err = render_error("12345", options); + Void::Testing::expect(err.code == MarkdownError::Code::input_limit); +} + +Void::Testing::Test markdown_output_limit() +{ + MarkdownOptions options; + options.limits.max_output = 8; + const auto err = render_error("# a long heading", options); + Void::Testing::expect(err.code == MarkdownError::Code::output_limit); +} + +Void::Testing::Test markdown_block_limit() +{ + MarkdownOptions options; + options.limits.max_blocks = 1; + const auto err = render_error("one\n\ntwo", options); + Void::Testing::expect(err.code == MarkdownError::Code::block_limit); +} + +Void::Testing::Test markdown_depth_limit() +{ + MarkdownOptions options; + options.limits.max_depth = 1; + const auto err = render_error("**a *b* c**", options); + Void::Testing::expect(err.code == MarkdownError::Code::depth_limit); +}