diff options
| author | Tyler <tyler@tylerhoang.xyz> | 2026-05-16 00:02:32 -0700 |
|---|---|---|
| committer | Tyler <tyler@tylerhoang.xyz> | 2026-05-16 00:02:32 -0700 |
| commit | 0d888203cbc4dc596d0c05cedfeabe8785b263fc (patch) | |
| tree | 7aa04a8b6b669fc8258e7e95905c07656c6f93f9 /utils/security.py | |
| parent | 870f8e6c8b88d61d0f7183b938b9a496c193b141 (diff) | |
Fix valuation and data robustness bugs
Diffstat (limited to 'utils/security.py')
| -rw-r--r-- | utils/security.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/utils/security.py b/utils/security.py new file mode 100644 index 0000000..962422b --- /dev/null +++ b/utils/security.py @@ -0,0 +1,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("</", "<\\/") |
