All source filestools/verify_source.py
Download raw file
#!/usr/bin/env python3
import argparse
import fnmatch
import hashlib
import json
from pathlib import Path, PurePosixPath
import sys
import zipfile
def fail(message):
raise ValueError(message)
def sha256(payload):
return hashlib.sha256(payload).hexdigest()
def safe_relative(value):
if not value or "\\" in value or value.startswith(("/", ".")):
fail(f"unsafe manifest path: {value!r}")
path = PurePosixPath(value)
if any(part in {"", ".", ".."} for part in path.parts):
fail(f"unsafe manifest path: {value!r}")
if path.parts and ":" in path.parts[0]:
fail(f"drive-qualified manifest path: {value!r}")
return path
def excluded(path, patterns):
for pattern in patterns:
if path == pattern or path.startswith(pattern + "/") or fnmatch.fnmatchcase(path, pattern):
return True
return False
def assert_no_symlink(root, candidate):
current = candidate
while current != root:
if current.is_symlink():
fail(f"symlink is not accepted: {current}")
if current.parent == current:
break
current = current.parent
resolved = candidate.resolve()
if resolved != root and root not in resolved.parents:
fail(f"path resolves outside expected root: {candidate}")
def viewer_path(relative):
return relative + ".viewer.html"
def verify(root, dist):
manifest = json.loads((dist / "source-manifest.json").read_text(encoding="utf-8"))
if manifest.get("version") != 1 or manifest.get("schema_version") != 1 or not isinstance(manifest.get("files"), list):
fail("unsupported or missing manifest")
if not isinstance(manifest.get("license"), str) or not manifest["license"].strip():
fail("manifest license is missing")
if not isinstance(manifest.get("generatedAt"), str) or not manifest["generatedAt"]:
fail("manifest generatedAt is missing")
if manifest.get("entry") != {"source": "/source/", "zip": "/source.zip"}:
fail("manifest entry is invalid")
build = manifest.get("build")
if not isinstance(build, dict) or not isinstance(build.get("command"), str) or not build["command"].strip():
fail("manifest build.command is missing")
excluded_patterns = manifest.get("excluded")
if not isinstance(excluded_patterns, list) or not all(isinstance(item, dict) and isinstance(item.get("path"), str) for item in excluded_patterns):
fail("manifest excluded[] is invalid")
patterns = [item["path"].rstrip("/") for item in excluded_patterns]
required = {"source-files.json", "README.md", "LICENSE", "tools/publish_source.py", "tools/verify_source.py"}
expected = {}
for item in manifest["files"]:
path = item["path"]
safe_relative(path)
if path in expected or path.startswith(("source/", "dist/")) or excluded(path, patterns):
fail(f"duplicate or excluded manifest path: {path}")
if not isinstance(item.get("bytes"), int) or not isinstance(item.get("sha256"), str):
fail(f"manifest hash metadata is invalid: {path}")
expected[path] = item
source = root / path
assert_no_symlink(root, source)
if not source.is_file():
fail(f"missing safe source file: {path}")
payload = source.read_bytes()
if item["bytes"] != len(payload) or item["sha256"] != sha256(payload):
fail(f"source changed after publication: {path}")
raw = dist / "source/files" / path
assert_no_symlink(dist, raw)
if not raw.is_file() or raw.read_bytes() != payload:
fail(f"published raw file differs: {path}")
viewer = dist / "source/view" / viewer_path(path)
if not viewer.is_file():
fail(f"source viewer is missing: {path}")
if not required.issubset(expected):
fail(f"source package is not self-contained; missing {sorted(required - set(expected))}")
raw_root = dist / "source/files"
actual = {path.relative_to(raw_root).as_posix() for path in raw_root.rglob("*") if path.is_file()}
if actual != set(expected):
fail(f"raw file set differs from manifest: {sorted(actual - set(expected))}")
browser = dist / "source/index.html"
if not browser.is_file() or 'name="robots" content="noindex"' not in browser.read_text(encoding="utf-8"):
fail("source browser or noindex marker is missing")
with zipfile.ZipFile(dist / "source.zip") as archive:
names = archive.namelist()
if len(names) != len(set(names)) or set(names) != set(expected):
fail("ZIP members differ from the manifest")
for path, item in expected.items():
payload = archive.read(path)
if len(payload) != item["bytes"] or sha256(payload) != item["sha256"]:
fail(f"ZIP payload differs: {path}")
return len(expected)
def main():
parser = argparse.ArgumentParser(description="Verify source, raw files, manifest hashes and ZIP payloads.")
parser.add_argument("--root", required=True, type=Path)
parser.add_argument("--dist", required=True, type=Path)
args = parser.parse_args()
try:
count = verify(args.root.resolve(), args.dist.resolve())
except (ValueError, OSError, json.JSONDecodeError, zipfile.BadZipFile) as exc:
print(f"FAIL: {exc}", file=sys.stderr)
return 1
print(f"PASS: {count} source files match the manifest and ZIP")
return 0
if __name__ == "__main__":
raise SystemExit(main())