Upgrade code

This commit is contained in:
2026-03-30 14:04:58 -04:00
parent bf29ccb287
commit 53eaf1c76d
12 changed files with 390 additions and 58 deletions
+49
View File
@@ -6,6 +6,7 @@ copy-pasting validation code into auth.py, admin.py, and future modules.
"""
import logging
import mistune
logger = logging.getLogger(__name__)
@@ -177,3 +178,51 @@ def _group_by_alternative(
else:
groups.append([(offset, magic)])
return groups if groups else [[]]
# ─── Comment Body Markdown Rendering ─────────────────────────────────────────
# Comments support a safe subset of Markdown (bold, italic, code, lists,
# blockquotes, links). We render to HTML at write time and sanitize with a
# strict allowlist so stored bodies are always safe to render with | safe.
#
# Intentionally excluded from comments (present in KB allowlist):
# img, table, div, h1-h6, figure — keep comment rendering lightweight.
import bleach as _bleach
_COMMENT_ALLOWED_TAGS = {
'p', 'br',
'strong', 'em', 'u', 's', 'code', 'pre',
'ul', 'ol', 'li',
'blockquote',
'a',
'hr',
}
_COMMENT_ALLOWED_ATTRS = {
'a': ['href', 'title', 'rel'],
}
_md = mistune.create_markdown(escape=True)
def render_comment_body(raw_text: str) -> str:
"""Convert plain-text Markdown comment to sanitized HTML.
Renders Markdown to HTML with mistune, then strips any tags/attributes
not in the comment allowlist via bleach. The result is safe to render
with Jinja2's ``| safe`` filter without further escaping.
Parameters
----------
raw_text : str the raw plain-text comment body submitted by the user
"""
if not raw_text:
return ''
html = _md(raw_text)
cleaned = _bleach.clean(
html,
tags = _COMMENT_ALLOWED_TAGS,
attributes = _COMMENT_ALLOWED_ATTRS,
strip = True,
)
return cleaned