| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- from __future__ import annotations
- from django.utils.safestring import mark_safe
- import nh3
- _ALLOWED_TAGS = {
- "p", "br", "strong", "b", "em", "i", "u", "s",
- "ul", "ol", "li", "blockquote", "pre", "code",
- "h1", "h2", "h3", "h4", "h5", "h6",
- "a", "img", "div", "span",
- }
- _ALLOWED_ATTRIBUTES = {
- "a": {"href", "title"},
- "img": {"src", "alt", "title", "width", "height"},
- "p": {"style"},
- "div": {"style"},
- "span": {"style"},
- }
- _CLEAN_CONTENT_TAGS = {"script", "style", "iframe", "object", "embed", "svg", "math"}
- _ALLOWED_URL_SCHEMES = {"http", "https", "mailto", "tel"}
- _ALLOWED_STYLE_PROPERTIES = {"text-align"}
- _CLEANER = nh3.Cleaner(
- tags=_ALLOWED_TAGS,
- attributes=_ALLOWED_ATTRIBUTES,
- clean_content_tags=_CLEAN_CONTENT_TAGS,
- url_schemes=_ALLOWED_URL_SCHEMES,
- filter_style_properties=_ALLOWED_STYLE_PROPERTIES,
- link_rel="noopener noreferrer",
- url_relative="pass_through",
- )
- def sanitize_rich_html(value: str | None) -> str | None:
- """Return safe persisted HTML while preserving the field's None semantics."""
- if value is None:
- return None
- return _CLEANER.clean(str(value))
- def render_rich_html(value: str | None):
- """Return a SafeString only after the same server-side allowlist sanitizer."""
- return mark_safe(sanitize_rich_html(value) or "")
|