aboutsummaryrefslogtreecommitdiff
path: root/utils/security.py
blob: 962422bd0a453d7938a5ba143e49d1d740685c6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""Minimal helpers for safely rendering external text and URLs."""
from html import escape
from urllib.parse import urlparse


def escape_html(value) -> str:
    """Escape a value for HTML text or attribute contexts."""
    if value is None:
        return ""
    return escape(str(value), quote=True)


def validate_outbound_url(url: str | None) -> str | None:
    """Allow only absolute http/https outbound URLs."""
    if not url:
        return None

    candidate = str(url).strip()
    if not candidate:
        return None

    parsed = urlparse(candidate)
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        return None

    return parsed.geturl()


def json_for_script(value) -> str:
    """Serialize JSON for safe embedding inside inline script tags."""
    import json

    return json.dumps(value).replace("</", "<\\/")