ifixkart-backend/app/utils/html_utils.py

31 lines
1.2 KiB
Python

import re
from typing import Any, Optional
def strip_html(value: Any) -> Optional[str]:
"""Remove HTML tags from a string, returning plain text for SEO fields."""
if not value:
return None
val_str = str(value).strip()
if not val_str:
return None
return re.sub(r"<[^>]+>", "", val_str).strip()
def sanitize_html(html_content: Optional[str]) -> Optional[str]:
"""
Sanitize HTML content by stripping dangerous executable elements
(script, iframe, object, embed) and inline event handlers (onerror, onload, onclick)
to prevent Stored XSS attacks in rich text fields.
"""
if not html_content:
return html_content
# Strip dangerous tags and their contents
clean = re.sub(r"<(script|iframe|object|embed|applet|meta)[^>]*>.*?</\1>", "", html_content, flags=re.DOTALL | re.IGNORECASE)
clean = re.sub(r"<(script|iframe|object|embed|applet|meta)[^>]*>", "", clean, flags=re.IGNORECASE)
# Strip event handler attributes (on*)
clean = re.sub(r"\s+on[a-zA-Z]+\s*=\s*(?:'[^']*'|\"[^\"]*\"|[^\s>]+)", "", clean, flags=re.IGNORECASE)
# Neutralize javascript: pseudoprotocol URLs
clean = re.sub(r"href\s*=\s*['\"]javascript:[^'\"]*['\"]", 'href="#"', clean, flags=re.IGNORECASE)
return clean