Details
For comparison, the four schemes already in the denylist are correctly blocked: javascript:, vbscript:, file:, data:text/html all return <a href="#harmful-link">.
The same gap applies to reference links ([click][ref]\n\n[ref]: feed:javascript:alert(1) → <a href="feed:javascript:alert(1)">) and to autolinks (<feed:javascript:alert(1)> → <a href="feed:javascript:alert(1)">).
Suggested Fix
Switch from denylist to allowlist. The set of schemes a markdown renderer needs to allow is small and well-known; the set of schemes that might trigger handler chains is unbounded.
--- a/src/mistune/renderers/html.py
+++ b/src/mistune/renderers/html.py
@@ -7,21 +7,28 @@ class HTMLRenderer(BaseRenderer):
_escape: bool
NAME: ClassVar[Literal["html"]] = "html"
- HARMFUL_PROTOCOLS: ClassVar[Tuple[str, ...]] = (
- "javascript:",
- "vbscript:",
- "file:",
- "data:",
- )
+ SAFE_PROTOCOLS: ClassVar[Tuple[str, ...]] = (
+ "http:",
+ "https:",
+ "mailto:",
+ "tel:",
+ "ftp:",
+ "ftps:",
+ "irc:",
+ "ircs:",
+ )
GOOD_DATA_PROTOCOLS: ClassVar[Tuple[str, ...]] = (
"data:image/gif;",
"data:image/png;",
"data:image/jpeg;",
"data:image/webp;",
)
@@ -49,15 +56,21 @@ class HTMLRenderer(BaseRenderer):
def safe_url(self, url: str) -> str:
- if self._allow_harmful_protocols is True:
- return escape_text(url)
-
- _url = url.lower()
- if self._allow_harmful_protocols and _url.startswith(tuple(self._allow_harmful_protocols)):
- return escape_text(url)
-
- if _url.startswith(self.HARMFUL_PROTOCOLS) and not _url.startswith(self.GOOD_DATA_PROTOCOLS):
- return "#harmful-link"
- return escape_text(url)
+ # Allow-list: only schemes in SAFE_PROTOCOLS, image-only data: URLs in
+ # GOOD_DATA_PROTOCOLS, scheme-relative URLs (//host/path), absolute
+ # paths (/path), and anchor-only references (#fragment) reach the
+ # rendered output. Everything else is replaced with '#harmful-link'.
+ if self._allow_harmful_protocols is True:
+ return escape_text(url)
+ _url = url.lower().lstrip()
+ if (
+ _url.startswith(self.SAFE_PROTOCOLS)
+ or _url.startswith(self.GOOD_DATA_PROTOCOLS)
+ or _url.startswith(("/", "#", "?"))
+ or ":" not in _url.split("/", 1)[0] # bare relative path
+ ):
+ return escape_text(url)
+ if self._allow_harmful_protocols and _url.startswith(tuple(self._allow_harmful_protocols)):
+ return escape_text(url)
+ return "#harmful-link"
The allow_harmful_protocols option is preserved, so callers who genuinely want to allow a custom scheme can still opt in. The lower().lstrip() also closes the leading-whitespace evasion sub-case (e.g., javascript: is already blocked by the current code via lower().startswith, but the same pattern needs to apply on the new allowlist branch). Add regression tests for each scheme listed in the PoC above asserting they resolve to #harmful-link.