zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///
"""Check that HTML pages run and apply only the inline code their policy names by hash."""
import base64
import hashlib
import re
import sys
import urllib.request
def allowed(policy, directive, bodies):
sources = re.search(directive + r"([^;]*)", policy)[1].split()
assert "'unsafe-inline'" not in sources and "'self'" not in sources, policy
hashes = {source[len("'sha256-"):-1] for source in sources if source.startswith("'sha256-")}
for body in bodies:
digest = base64.b64encode(hashlib.sha256(body.encode()).digest()).decode()
assert digest in hashes, f'inline {directive} body not in policy: {body[:60]!r}'
if not bodies:
assert sources == ["'none'"], policy
def check(policy, html):
assert '<script ' not in html, 'script element with attributes'
assert '<style ' not in html, 'style element with attributes'
assert not re.search(r"<[^>]*\sstyle=", html), 'style attribute'
scripts = re.findall(r"<script>(.*?)</script>", html, re.S)
styles = re.findall(r"<style>(.*?)</style>", html, re.S)
allowed(policy, 'script-src', scripts)
allowed(policy, 'style-src', styles)
return len(scripts), len(styles)
if __name__ == '__main__':
base, *pages = sys.argv[1:]
for page in pages:
with urllib.request.urlopen(base + page) as response:
scripts, styles = check(response.headers['content-security-policy'], response.read().decode())
print(f'{page}: {scripts} inline scripts and {styles} inline styles allowed by hash')