aboutsummaryrefslogtreecommitdiff
path: root/utils/security.py
diff options
context:
space:
mode:
Diffstat (limited to 'utils/security.py')
-rw-r--r--utils/security.py33
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("</", "<\\/")