Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions .github/scripts/test-validate-static.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Check accepted script modes and rejection of broken local pages/assets."""
import importlib.util
from pathlib import Path
import subprocess
import tempfile
import unittest

spec = importlib.util.spec_from_file_location("validation", Path(__file__).with_name("validate-static.py"))
validation = importlib.util.module_from_spec(spec)
spec.loader.exec_module(validation)


class StaticValidationTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name)
self.root.joinpath("package.json").write_text('{"type":"commonjs"}')

def page(self, content):
self.root.joinpath("index.html").write_text(
'<!DOCTYPE html><html><head><title>Fixture</title></head><body>' + content + '</body></html>'
)

def test_classic_and_module_scripts(self):
self.root.joinpath("app.js").write_text('export const value = 1;')
self.page('<script type="module" src="app.js"></script><script type="module">export const inline = 2;</script>')
validation.validate(self.root)
self.page('<script src="app.js"></script>')
with self.assertRaises(subprocess.CalledProcessError):
validation.validate(self.root)

def test_invalid_inline_javascript(self):
self.page('<script>const broken = ;</script>')
with self.assertRaises(subprocess.CalledProcessError):
validation.validate(self.root)

def test_unterminated_inline_script(self):
self.page('<script>const broken = ;')
with self.assertRaisesRegex(ValueError, 'unterminated script'):
validation.validate(self.root)

def test_missing_and_outside_assets(self):
for reference, error in [('missing.png', 'missing local asset'), ('../outside.png', 'escapes site root')]:
with self.subTest(reference=reference):
self.page(f'<img src="{reference}">')
with self.assertRaisesRegex(ValueError, error):
validation.validate(self.root)

def test_css_and_manifest_assets(self):
self.page('<link rel="stylesheet" href="style.css"><link rel="manifest" href="site.webmanifest">')
self.root.joinpath('style.css').write_text('body { background: url(missing.png); }')
self.root.joinpath('site.webmanifest').write_text('{"icons":[{"src":"icon.png"}]}')
with self.assertRaisesRegex(ValueError, 'missing.png'):
validation.validate(self.root)
self.root.joinpath('missing.png').touch()
with self.assertRaisesRegex(ValueError, 'icon.png'):
validation.validate(self.root)
self.root.joinpath('icon.png').touch()
validation.validate(self.root)


if __name__ == '__main__':
unittest.main()
37 changes: 27 additions & 10 deletions .github/scripts/validate-static.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ def __init__(self):
self.references = []
self.scripts = []
self.script = None
self.open_script = False
self.external_scripts = []
self.doctype = False
self.title = ""
self.in_title = False
Expand All @@ -34,17 +36,23 @@ def handle_starttag(self, tag, attributes):
self.references.append(attributes[key])
if tag == "title":
self.in_title = True
if tag == "script" and not attributes.get("src"):
if tag == "script":
self.open_script = True
script_type = attributes.get("type", "text/javascript")
if script_type in ("module", "text/javascript", "application/javascript", ""):
self.script = (script_type == "module", [])
if attributes.get("src"):
self.external_scripts.append((attributes["src"], script_type == "module"))
else:
self.script = (script_type == "module", [])

def handle_endtag(self, tag):
if tag == "title":
self.in_title = False
if tag == "script" and self.script is not None:
self.scripts.append(self.script)
self.script = None
if tag == "script":
self.open_script = False
if self.script is not None:
self.scripts.append(self.script)
self.script = None

def handle_data(self, data):
if self.script is not None:
Expand All @@ -56,19 +64,18 @@ def handle_data(self, data):
def local_reference(root, source, reference):
url = urlsplit(reference)
if url.scheme or url.netloc or not url.path:
return
return None
decoded = unquote(url.path)
destination = (root / decoded.lstrip("/") if decoded.startswith("/") else source.parent / decoded).resolve()
if not destination.is_relative_to(root):
raise ValueError(f"{source}: asset escapes site root: {reference}")
if not destination.exists():
raise ValueError(f"{source}: missing local asset: {reference}")
return destination


def check_javascript(code, module=False):
command = ["node", "--check"]
if module:
command.append("--input-type=module")
command = ["node", "--check", "--input-type=" + ("module" if module else "commonjs")]
subprocess.run(command, input=code, text=True, check=True)


Expand All @@ -77,17 +84,27 @@ def validate(root):
pages = sorted(root.rglob("*.html"))
if not pages:
raise ValueError(f"No HTML pages in {root}")
checked_external = set()
for path in pages:
page = Page()
page.feed(path.read_text())
page.close()
if page.open_script:
raise ValueError(f"{path}: unterminated script element")
if not page.doctype or not {"html", "head", "body", "title"} <= page.tags or not page.title.strip():
raise ValueError(f"{path}: expected HTML document with doctype, head, body and title")
for reference in page.references:
local_reference(root, path, reference)
for reference, module in page.external_scripts:
destination = local_reference(root, path, reference)
if destination is not None:
check_javascript(destination.read_text(), module)
checked_external.add(destination)
for module, script in page.scripts:
check_javascript("".join(script), module)
for path in root.rglob("*.js"):
subprocess.run(["node", "--check", str(path)], check=True)
if path.resolve() not in checked_external:
subprocess.run(["node", "--check", str(path)], check=True)
for path in root.rglob("*.css"):
css = re.sub(r"/\*.*?\*/", "", path.read_text(), flags=re.S)
for reference in re.findall(r"url\(\s*['\"]?([^)'\"]+)['\"]?\s*\)", css):
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,5 @@ jobs:
node-version: "24"
- name: Validate HTML, JavaScript and local assets
run: python .github/scripts/validate-static.py .
- name: Test static validation regressions
run: python .github/scripts/test-validate-static.py
Loading