import html as html_module import json import random import re from datetime import datetime as dt from zoneinfo import ZoneInfo import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 ERROR_TEMPLATE = "ERROR: PreprocessEmail - {function_name}: {reason}" ALLOWED_EMAIL_TAGS = { "p", "br", "div", "span", "b", "i", "u", "a", "img", "table", "tr", "td", "th", "thead", "tbody", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "code", "blockquote", "strong", "em", "hr", "font", "center", "small", "big", "sub", "sup", "dl", "dt", "dd", "caption", } ALLOWED_EMAIL_ATTRIBUTES: dict[str, set[str]] = { "*": {"style", "class", "id", "dir", "align", "width", "height", "bgcolor", "valign"}, "a": {"href", "target"}, "img": {"src", "alt", "title"}, "td": {"colspan", "rowspan"}, "th": {"colspan", "rowspan", "scope"}, "font": {"color", "face", "size"}, "table": {"border", "cellpadding", "cellspacing"}, } def sanitize_html_body(html_body: str) -> str: """Sanitize email body HTML using an allowlist of tags and attributes. When nh3 is available, strips disallowed tags and attributes while preserving safe ones. When nh3 is not available, returns the HTML as-is since full escaping would break legitimate formatting in an HTML rendering context. """ try: import nh3 return nh3.clean(html_body, tags=ALLOWED_EMAIL_TAGS, attributes=ALLOWED_EMAIL_ATTRIBUTES) # pylint: disable=no-member except ImportError: demisto.debug("nh3 is not available; HTML sanitization skipped") return html_body # List of strings that mail clients use to separate new message content from previous thread messages when replying QUOTE_MARKERS = [ '