72 lines
2.7 KiB
Python
72 lines
2.7 KiB
Python
"""Markdown rendering with XSS protection."""
|
|
|
|
import bleach
|
|
from markupsafe import Markup
|
|
from markdown import markdown
|
|
|
|
|
|
# Convert stored content to raw HTML for the editor (edit-load path).
|
|
# Rich-text editors store clean HTML; Markdown is converted on save. We detect
|
|
# which the caller stored and only run the Markdown parser on Markdown, so
|
|
# storing HTML never gets mangled.
|
|
# This is NOT bleach-sanitised — the editor receives the author's own content.
|
|
# Public rendering (render_markdown) is what applies XSS protection.
|
|
def _looks_like_html(text):
|
|
"""True if `text` is clean HTML rather than Markdown source."""
|
|
stripped = text.lstrip()
|
|
return bool(stripped) and stripped[0] == "<"
|
|
|
|
def to_html(text):
|
|
if not text:
|
|
return ""
|
|
if _looks_like_html(text):
|
|
# Already clean HTML from the rich-text editor — hand it straight
|
|
# through so it reaches the editor un-mangled.
|
|
return Markup(text)
|
|
html = markdown(text, extensions=["fenced_code", "tables", "nl2br"])
|
|
# The markdown library only ever emits its own known tags, so this is safe
|
|
# to hand to the editor. Wrap in Markup so Jinja does NOT HTML-escape the
|
|
# tags when the template renders this value into the Quill container.
|
|
return Markup(html)
|
|
|
|
|
|
# Tags we allow through. Markdown already produces safe HTML; bleach strips
|
|
# anything else to prevent stored XSS from editor input.
|
|
ALLOWED_TAGS = {
|
|
"a", "p", "br", "strong", "em", "b", "i", "code", "pre", "blockquote",
|
|
"h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "table", "thead",
|
|
"tbody", "tr", "th", "td", "hr", "img", "figure", "figcaption",
|
|
}
|
|
ALLOWED_ATTR = {
|
|
"a": ["href", "title", "target", "rel"],
|
|
"img": ["src", "alt", "title", "width", "height"],
|
|
}
|
|
ALLOWED_PROTOCOLS = ["http", "https", "mailto"]
|
|
|
|
|
|
def render_markdown(text):
|
|
"""Render stored content to safely-sanitised HTML for public display.
|
|
|
|
Handles both inputs:
|
|
* Markdown (the legacy Quill editor's format) -> markdown() + bleach.
|
|
* Clean HTML (the TipTap rich-text editor's format) -> bleach only,
|
|
so images/links render as-is instead of being mangled by the Markdown
|
|
parser. Either way, bleach strips anything outside ALLOWED_TAGS to
|
|
prevent stored XSS.
|
|
"""
|
|
if not text:
|
|
return ""
|
|
if _looks_like_html(text):
|
|
html = text
|
|
else:
|
|
html = markdown(text, extensions=["fenced_code", "tables", "nl2br"])
|
|
safe = bleach.clean(
|
|
html,
|
|
tags=ALLOWED_TAGS,
|
|
attributes=ALLOWED_ATTR,
|
|
protocols=ALLOWED_PROTOCOLS,
|
|
)
|
|
# bleach 6.x returns a plain str; wrap in Markup so Flask/Jinja does not
|
|
# HTML-escape the generated tags when the template renders this value.
|
|
return Markup(safe)
|