27 lines
886 B
Python
27 lines
886 B
Python
import re
|
|
from html import escape
|
|
|
|
_UNSAFE_TAGS = re.compile(
|
|
r"<\s*(script|iframe|object|embed|form|base|meta|link)\b[^>]*>.*?</\s*\1\s*>",
|
|
re.IGNORECASE | re.DOTALL,
|
|
)
|
|
_UNSAFE_OPEN_TAGS = re.compile(
|
|
r"<\s*(script|iframe|object|embed|form|base)\b[^>]*/?>",
|
|
re.IGNORECASE,
|
|
)
|
|
_EVENT_HANDLERS = re.compile(r"\s+on[a-z]+\s*=\s*(['\"]).*?\1", re.IGNORECASE)
|
|
_JS_URLS = re.compile(r"""(href|src)\s*=\s*(['"])\s*javascript:.*?\2""", re.IGNORECASE)
|
|
|
|
|
|
def sanitize_email_html(html: str) -> str:
|
|
if not html:
|
|
return ""
|
|
cleaned = _UNSAFE_TAGS.sub("", html)
|
|
cleaned = _UNSAFE_OPEN_TAGS.sub("", cleaned)
|
|
cleaned = _EVENT_HANDLERS.sub("", cleaned)
|
|
cleaned = _JS_URLS.sub("", cleaned)
|
|
return cleaned.strip()
|
|
|
|
|
|
def plain_text_to_html(text: str) -> str:
|
|
return f'<pre style="margin:0;white-space:pre-wrap;font-family:inherit;">{escape(text)}</pre>'
|