"""Steward draws itself only with what it serves (#5091; rules 155 and 164). No template or stylesheet loads a script, stylesheet, font or image from another origin (a page would quietly lose htmx, its charts or its fonts on an instance with no outbound network, and tell a third party about every visitor), and every file a template asks url_for('static') for exists. Example URLs in placeholders and help text are fine: only loads count. """ import pathlib import re import steward _REPO = pathlib.Path(steward.__file__).parent.parent _STATIC = _REPO / "steward" / "static" _COMMENTS = re.compile(r"\{#.*?#\}||/\*.*?\*/", re.S) _REMOTE = r"""["']?\s*(?:https?:)?//""" _LOADS = [ re.compile(r"]*\bsrc\s*=\s*" + _REMOTE, re.I), re.compile(r"]*\bhref\s*=\s*" + _REMOTE, re.I), re.compile(r"]*\bsrc\s*=\s*" + _REMOTE, re.I), re.compile(r"@import\s+" + _REMOTE, re.I), # @import url(...) is the url( case below re.compile(r"\burl\(\s*" + _REMOTE, re.I), ] _STATIC_REF = re.compile(r"url_for\(\s*'static'\s*,\s*filename\s*=\s*'([^']+)'\s*\)") def remote_loads(text: str) -> list[str]: text = _COMMENTS.sub("", text) return [m.group(0) for rx in _LOADS for m in rx.finditer(text)] def _files(): roots = [_REPO / "steward" / "templates", _STATIC, *(_REPO / "plugins").glob("*/templates")] for root in roots: for path in root.rglob("*"): if path.suffix in (".html", ".css", ".js") and "vendor" not in path.parts: yield path def test_the_remote_asset_guard_can_fail(): page = """ {# #} a link is not a load """ assert len(remote_loads(page)) == 4 def test_nothing_is_loaded_from_another_origin(): found = {str(p.relative_to(_REPO)): hits for p in _files() if (hits := remote_loads(p.read_text()))} assert not found, f"loads from another origin (vendor it under steward/static): {found}" def test_every_static_file_a_template_names_exists(): refs = {(p, ref) for p in _files() for ref in _STATIC_REF.findall(p.read_text())} assert any(ref == "vendor/htmx-2.0.4.min.js" for _, ref in refs) missing = sorted(f"{p.relative_to(_REPO)}: {ref}" for p, ref in refs if not (_STATIC / ref).is_file()) assert not missing, missing def test_every_font_file_the_font_sheet_names_exists(): sheet = (_STATIC / "fonts" / "fonts.css").read_text() names = set(re.findall(r"url\(([^)]+\.woff2)\)", sheet)) assert len(names) >= 10 assert not [n for n in names if not (_STATIC / "fonts" / n).is_file()]