from __future__ import annotations import bleach from bs4 import BeautifulSoup ALLOWED_TAGS = [ "p", "br", "ul", "ol", "li", "strong", "b", "em", "i", "h2", "h3", "h4", "blockquote", "code", "pre", "a", ] ALLOWED_ATTRIBUTES = {"a": ["href", "title", "rel"]} def sanitize_job_html(value: str) -> str: cleaned = bleach.clean( value or "", tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, protocols=["http", "https", "mailto"], strip=True, strip_comments=True, ) soup = BeautifulSoup(cleaned, "lxml") for anchor in soup.find_all("a"): anchor["rel"] = "noopener noreferrer nofollow" body = soup.body return "".join(str(child) for child in body.children) if body else str(soup)