All source filestools/publish_source.py
Download raw file
#!/usr/bin/env python3
import argparse
from datetime import datetime, timezone
import fnmatch
import hashlib
import html
import json
import mimetypes
from pathlib import Path, PurePosixPath
import re
import shutil
import sys
from urllib.parse import quote
import zipfile
MAX_FILE_BYTES = 50 * 1024 * 1024
SECRET_RULES = [
("private-key", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |ENCRYPTED )?PRIVATE KEY-----")),
("certificate", re.compile(r"-----BEGIN CERTIFICATE" r"-----")),
("possible-customer-pii", re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")),
("payment-secret", re.compile(r"\bsk_(?:live|test)_[A-Za-z0-9]{16,}\b")),
("cloud-key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
("github-token", re.compile(r"\b(?:ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,})\b")),
("gitlab-token", re.compile(r"\bglpat-[A-Za-z0-9_-]{20,}\b")),
("webhook-secret", re.compile(r"\bwhsec_[A-Za-z0-9]{16,}\b")),
("openai-key", re.compile(r"\bsk-(?:proj|ant)-[A-Za-z0-9_-]{20,}\b")),
("google-key", re.compile(r"\bAIza[0-9A-Za-z_-]{30,}\b")),
("slack-token", re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{20,}\b")),
]
SENSITIVE_FILENAMES = {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "credentials.json", "service-account.json"}
SENSITIVE_SUFFIXES = {".key", ".p12", ".pfx", ".pem", ".crt", ".cer"}
def fail(message):
raise ValueError(message)
def normalize_build(value):
if isinstance(value, str) and value.strip():
return {"command": value.strip()}
if not isinstance(value, dict) or set(value) - {"command", "output"}:
fail("build must be a command string or an object with command/output")
if not isinstance(value.get("command"), str) or not value["command"].strip():
fail("build.command is required for a reproducible source package")
build = {"command": value["command"].strip()}
if "output" in value:
if not isinstance(value["output"], str):
fail("build.output must be a string")
build["output"] = value["output"]
return build
def load_config(root):
path = root / "source-files.json"
if not path.is_file():
fail("source-files.json is required")
config = json.loads(path.read_text(encoding="utf-8"))
allowed = {"version", "license", "include", "build", "exclude"}
if not isinstance(config, dict) or set(config) - allowed:
fail("config contains unknown keys")
if "version" in config and config["version"] != 1:
fail("only source-files version 1 is supported")
if not isinstance(config.get("license"), str) or not config["license"].strip():
fail("license must be a non-empty string; use All Rights Reserved when reuse is not granted")
include = config.get("include")
if not isinstance(include, list) or not include or not all(isinstance(item, str) for item in include):
fail("include must be a non-empty string array")
required = {"source-files.json", "README.md", "LICENSE", "tools/publish_source.py", "tools/verify_source.py"}
if not required.issubset(include):
fail(f"include must contain {sorted(required)}")
exclude = config.get("exclude", [])
if not isinstance(exclude, list) or not all(isinstance(item, str) for item in exclude):
fail("exclude must be a string array documenting non-public paths")
for pattern in exclude:
safe_exclude_pattern(pattern)
config["_build"] = normalize_build(config.get("build"))
config["_exclude"] = [safe_exclude_pattern(pattern) for pattern in exclude]
for required_path in required:
if excluded(required_path, config["_exclude"]):
fail(f"exclude must not remove required self-contained file: {required_path}")
return config
def safe_relative(value):
if not value or "\\" in value or value.startswith("/"):
fail(f"unsafe include path: {value!r}")
path = PurePosixPath(value)
if any(part in {"", ".", ".."} or part.startswith(".") for part in path.parts):
fail(f"dotfiles, hidden directories and traversal are denied: {value!r}")
if path.parts and ":" in path.parts[0]:
fail(f"drive-qualified paths are denied: {value!r}")
return path
def safe_exclude_pattern(value):
if not value or "\\" in value or value.startswith("/"):
fail(f"unsafe exclude pattern: {value!r}")
path = PurePosixPath(value)
if any(part in {"", ".", ".."} for part in path.parts):
fail(f"exclude traversal is denied: {value!r}")
if path.parts and ":" in path.parts[0]:
fail(f"drive-qualified exclude paths are denied: {value!r}")
return path.as_posix().rstrip("/")
def excluded(path, patterns):
for pattern in patterns:
if path == pattern or path.startswith(pattern + "/"):
return True
if 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"symlinks are not publishable: {current}")
if current.parent == current:
break
current = current.parent
resolved = candidate.resolve()
if resolved != root and root not in resolved.parents:
fail(f"included path resolves outside source root: {candidate}")
def collect_files(root, out, include, patterns):
files = {}
for value in include:
relative = safe_relative(value)
source = root.joinpath(*relative.parts)
assert_no_symlink(root, source)
if not source.exists():
fail(f"included path does not exist: {relative}")
if source.is_dir() and (out == source or out in source.parents or source in out.parents):
fail(f"output directory cannot be inside included path: {relative}")
candidates = [source] if source.is_file() else sorted(source.rglob("*")) if source.is_dir() else []
if not candidates:
fail(f"included path is not a file or non-empty directory: {relative}")
for candidate in candidates:
assert_no_symlink(root, candidate)
if candidate.is_dir():
continue
if not candidate.is_file():
fail(f"unsupported file type: {candidate}")
item = candidate.relative_to(root)
safe_relative(item.as_posix())
if excluded(item.as_posix(), patterns):
continue
if item.as_posix() in files:
fail(f"duplicate include path: {item}")
files[item.as_posix()] = candidate
return [files[key] for key in sorted(files)]
def inspect_file(relative, path):
if path.stat().st_size > MAX_FILE_BYTES:
fail(f"file exceeds the {MAX_FILE_BYTES}-byte safety limit: {relative}")
if path.name.lower() in SENSITIVE_FILENAMES or path.suffix.lower() in SENSITIVE_SUFFIXES:
fail(f"sensitive filename is not publishable: {relative}")
payload = path.read_bytes()
try:
text = payload.decode("utf-8")
except UnicodeDecodeError:
text = None
if text is not None:
for rule_id, pattern in SECRET_RULES:
if rule_id == "possible-customer-pii":
if re.search(r"(?:customer|order|invoice|subscriber|visitor|lead|payment)", relative, re.I) and pattern.search(text):
fail(f"possible customer data detected in {relative}; review it before publishing")
elif pattern.search(text):
fail(f"secret pattern {rule_id} detected in {relative}; remove it before publishing")
return payload, text
def viewer_path(relative):
return relative + ".viewer.html"
def render_index(entries, license_name):
rows = []
for path, is_text in entries:
view = viewer_path(path)
parent = PurePosixPath(path).parent.as_posix()
name = PurePosixPath(path).name
rows.append(
f'<tr data-name="{html.escape(path.lower())}"><td>{html.escape(parent)}</td>'
f'<td><a href="view/{quote(view)}">{html.escape(name)}</a></td>'
f'<td>{"text" if is_text else "binary"}</td><td><a href="../files/{quote(path)}" download>download</a></td></tr>'
)
return """<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
<title>Site source</title><style>body{font:16px/1.5 system-ui;max-width:1100px;margin:2rem auto;padding:0 1rem}input{width:100%;padding:.7rem;font:inherit}table{width:100%;border-collapse:collapse}td,th{padding:.5rem;border-bottom:1px solid #ddd;text-align:left}a{color:#0645ad}code{overflow-wrap:anywhere}</style></head>
<body><h1>Site source</h1><p>License: <strong>""" + html.escape(license_name) + """</strong>. Public readability does not grant reuse rights.</p>
<p><a href="../source.zip">Download source.zip</a> ยท <a href="../source-manifest.json">SHA-256 manifest</a></p>
<label for="query">Filter files</label><input id="query" type="search" placeholder="path or filename">
<table><thead><tr><th>Directory</th><th>File</th><th>Type</th><th>Raw file</th></tr></thead><tbody>""" + "".join(rows) + """</tbody></table>
<script>document.getElementById('query').addEventListener('input',function(){const q=this.value.toLowerCase();document.querySelectorAll('tr[data-name]').forEach(function(row){row.hidden=!row.dataset.name.includes(q);});});</script>
</body></html>"""
def render_viewer(path, payload, text):
depth = len(PurePosixPath(viewer_path(path)).parent.parts) + 1
raw_link = "../" * depth + "files/" + path
home_link = "../" * depth + "index.html"
if text is None:
body = f'<p>Binary asset ({len(payload)} bytes). <a href="{quote(raw_link)}" download>Download raw file</a>.</p>'
else:
body = f'<p><a href="{quote(raw_link)}" download>Download raw file</a></p><pre><code>{html.escape(text)}</code></pre>'
return f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>{html.escape(path)}</title>
<style>body{{font:16px/1.5 system-ui;margin:2rem;max-width:1200px}}pre{{white-space:pre-wrap;overflow-wrap:anywhere;background:#f6f8fa;padding:1rem}}code{{font:14px/1.5 ui-monospace,monospace}}</style></head>
<body><a href="{quote(home_link)}">All source files</a><h1>{html.escape(path)}</h1>{body}</body></html>"""
def prepare_output(out):
source_dir = out / "source"
if source_dir.is_symlink():
fail("output source directory cannot be a symlink")
if source_dir.exists():
marker = source_dir / ".source-publish-owned.json"
if not marker.is_file():
fail("refusing to replace an unowned source directory")
owned = json.loads(marker.read_text(encoding="utf-8"))
if owned.get("tool") != "site-source-publish" or owned.get("version") != 1:
fail("refusing to replace an unowned source directory")
shutil.rmtree(source_dir)
elif (out / "source.zip").exists() or (out / "source-manifest.json").exists():
fail("refusing to overwrite source artifacts without an ownership marker")
source_dir.mkdir(parents=True)
(source_dir / ".source-publish-owned.json").write_text('{"tool":"site-source-publish","version":1}\n', encoding="utf-8")
def publish(root, out):
if root == out or out in root.parents:
fail("output directory must be inside a separate build directory, not the source root or its ancestor")
config = load_config(root)
files = collect_files(root, out, config["include"], config["_exclude"])
inspected = [(path.relative_to(root).as_posix(), *inspect_file(path.relative_to(root).as_posix(), path)) for path in files]
out.mkdir(parents=True, exist_ok=True)
prepare_output(out)
manifest_files = []
entries = []
for relative, payload, text in inspected:
raw = out / "source/files" / relative
raw.parent.mkdir(parents=True, exist_ok=True)
raw.write_bytes(payload)
media_type = mimetypes.guess_type(relative)[0] or "application/octet-stream"
manifest_files.append({"path": relative, "bytes": len(payload), "sha256": hashlib.sha256(payload).hexdigest(), "media_type": media_type})
entries.append((relative, text is not None))
view = out / "source/view" / viewer_path(relative)
view.parent.mkdir(parents=True, exist_ok=True)
view.write_text(render_viewer(relative, payload, text), encoding="utf-8")
(out / "source/index.html").write_text(render_index(entries, config["license"]), encoding="utf-8")
manifest = {
"version": 1,
"schema_version": 1,
"generatedAt": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
"license": config["license"],
"build": config["_build"],
"entry": {"source": "/source/", "zip": "/source.zip"},
"excluded": [{"path": pattern, "reason": "declared non-public"} for pattern in config["_exclude"]],
"files": manifest_files,
}
(out / "source-manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
with zipfile.ZipFile(out / "source.zip", "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
for relative, payload, _ in inspected:
info = zipfile.ZipInfo(relative, date_time=(1980, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o100644 << 16
archive.writestr(info, payload)
return manifest
def main():
parser = argparse.ArgumentParser(description="Publish an allowlisted, reproducible static-site source package.")
parser.add_argument("--root", required=True, type=Path)
parser.add_argument("--out", required=True, type=Path)
args = parser.parse_args()
try:
manifest = publish(args.root.resolve(), args.out.resolve())
except (ValueError, OSError, json.JSONDecodeError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
print(f"Published {len(manifest['files'])} source files to {args.out}")
return 0
if __name__ == "__main__":
raise SystemExit(main())