#!/usr/bin/env python3 """The deploy gate. Run after build.py; any problem stops the deploy. python3 scripts/check_dist.py [DIST_DIR] It checks the promises the site makes to visitors: - the script sends nothing and stores nothing; - no page loads a script from another site, or submits a form, except the "Report an error" form on /report/, which posts only to this site's /api/report; - no draft (unverified) page goes live; - every page says "Not legal advice", and every internal link works; - a letter tool appears only for an entry whose `opt_out.letter` covers every item the agreement requires, and never where the company requires its own form. """ import html.parser import json import pathlib import re import sys import urllib.parse ROOT = pathlib.Path(__file__).resolve().parent.parent REQUIRED_FILES = [ "index.html", "404.html", "about/index.html", "methodology/index.html", "arbitration/index.html", "code/index.html", "code/research-brief.md.txt", "code/validate.py.txt", "code/verify_sources.py.txt", "capital-one/index.html", "capital-one/reminder.ics", "data/entries.json", "sitemap.xml", "robots.txt", "_headers", "_redirects", ] # Browser APIs that send data or store it. The script must use none of them. FORBIDDEN_JS = [ "fetch", "XMLHttpRequest", "sendBeacon", "WebSocket", "EventSource", "importScripts", "localStorage", "sessionStorage", "indexedDB", "cookie", "caches", "serviceWorker", "postMessage", "BroadcastChannel", "RTCPeerConnection", "eval", "Function(", ] # Things that look like credentials. Assembled from parts, so this file's own published # copy doesn't match them. _u = "_" SECRET_PATTERN = "|".join([ "gh" + "[pousr]" + _u + "[A-Za-z0-9]{30,}", # GitHub tokens "github" + _u + "pat" + _u + "[A-Za-z0-9_]{30,}", "AK" + "IA[0-9A-Z]{16}", # AWS access key "AI" + "za[0-9A-Za-z_-]{35}", # Google API key "xox" + "[abprs]-[A-Za-z0-9-]{10,}", # Slack "sk-" + "(?:ant-|proj-)?[A-Za-z0-9_-]{32,}", # Anthropic / OpenAI style "-----BEGIN " + "[A-Z ]*PRIVATE KEY-----", # private keys "(?i:api[_-]?key|secret|token|password)" + r"\s*[:=]\s*['\"][A-Za-z0-9_\-]{20,}['\"]", ]) class PageScanner(html.parser.HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.ids = set() self.links = [] # (attribute, value) self.scripts = [] # (src or None, type) self.forms = [] # (action, method) self.style_attrs = 0 self.draft_banner = False self.text = [] def handle_starttag(self, tag, attrs): attrs = dict(attrs) if "id" in attrs: self.ids.add(attrs["id"]) if "style" in attrs: self.style_attrs += 1 if "draft-banner" in (attrs.get("class") or "").split(): self.draft_banner = True if tag == "script": self.scripts.append((attrs.get("src"), attrs.get("type"))) if tag == "form": self.forms.append((attrs.get("action"), (attrs.get("method") or "get").lower())) for name in ("href", "src"): if attrs.get(name): self.links.append((name, attrs[name])) def handle_data(self, data): self.text.append(data) def strip_js_comments(source): source = re.sub(r"/\*.*?\*/", "", source, flags=re.S) return re.sub(r"(^|\s)//[^\n]*", r"\1", source) def target_exists(dist, path): path = urllib.parse.unquote(path) candidate = dist / path.lstrip("/") if path.endswith("/"): return (candidate / "index.html").is_file() return candidate.is_file() or (candidate / "index.html").is_file() def check_citations(dist): """A cited number must be the number of the quote it links to, and quotes are numbered 1, 2, 3 in the order they're listed.""" problems = [] for page in sorted(dist.rglob("*.html")): text = page.read_text(encoding="utf-8") if 'class="cite"' not in text: continue figures = re.findall(r'
', text) numbers = [int(n) for n in re.findall(r'(\d+)', text)] rel = page.relative_to(dist) if numbers != list(range(1, len(figures) + 1)): problems.append(f"{rel}: sources aren't numbered 1 to {len(figures)} in order") for name, num in re.findall(r']*>(\d+)', text): if name not in figures or figures.index(name) + 1 != int(num): problems.append(f"{rel}: citation {num} doesn't match the quote it links to ({name})") return problems def check_letters(dist, entries): """Every printed letter must contain what the agreement requires (validate.py's rule, checked again on the built pages).""" problems = [] for page in sorted(dist.rglob("*.html")): match = re.search(r'id="letter-tool" data-entry="([a-z0-9-]+)"', page.read_text(encoding="utf-8")) if not match: continue rel, entry = page.relative_to(dist), entries.get(match.group(1)) opt_out = (entry or {}).get("opt_out") or {} letter = opt_out.get("letter") or {} required, covers = opt_out.get("required") or [], letter.get("covers") or [] fields = set(letter.get("fields") or []) if not entry or not letter or letter.get("form"): problems.append(f"{rel} shows a letter tool, but its entry has no letter (or needs a form)") elif len(covers) != len(required): problems.append(f"{rel}: the letter covers {len(covers)} of {len(required)} required items") else: for item, cover in zip(required, covers): for part in str(cover).split("+"): if part in {"name", "address", "phone", "email", "account", "account_name", "vin", "username", "agreement_date", "ssn"} and part not in fields: problems.append(f"{rel}: {item!r} needs the letter field {part!r}") return problems def main(argv): dist = pathlib.Path(argv[1]) if len(argv) > 1 else ROOT / "dist" problems = [] for name in REQUIRED_FILES: if not (dist / name).is_file(): problems.append(f"missing {name}") for js in sorted((dist / "static").glob("*.js")): code = strip_js_comments(js.read_text(encoding="utf-8")) for token in FORBIDDEN_JS: pattern = re.escape(token) if not token[-1].isalnum() else rf"\b{re.escape(token)}\b" if re.search(pattern, code): problems.append(f"static/{js.name} uses `{token}`, which could send or store data") pages = sorted(dist.rglob("*.html")) scanned = {} for page in pages: scanner = PageScanner() scanner.feed(page.read_text(encoding="utf-8")) scanned[page] = scanner rel = page.relative_to(dist) if scanner.draft_banner: problems.append(f"{rel} is a draft preview (built with --drafts); rebuild without it") report_page = rel.as_posix() in ("report/index.html", "report/request/index.html") if scanner.forms and not (report_page and scanner.forms == [("/api/report", "post")]): problems.append(f"{rel} has a
; only /report/ may have one, posting to /api/report") if scanner.style_attrs: problems.append(f"{rel} has style=\"\" attributes, which the Content-Security-Policy blocks") page_text = "".join(scanner.text) if "Not legal advice" not in page_text: problems.append(f"{rel} doesn't say \"Not legal advice\"") if "Researched by AI agents" not in page_text: problems.append(f"{rel} lacks the AI disclosure in the footer") for src, kind in scanner.scripts: if src is None and kind != "application/ld+json": problems.append(f"{rel} has an inline