#!/usr/bin/env python3 """Audit the entire exported candidate, not a handpicked endpoint sample. Run with .local-run/recovery-env/bin/python scripts/rebuild-v2/check-built.py. The crawler never fetches external destinations; exact page/anchor approvals are checked locally. Browser interaction remains a separate, explicitly named check. Unresolved archive inventory produces a blocked restoration result, even when all published-page checks succeed. No build, deployment or Git mutation occurs. """ from __future__ import annotations import argparse from collections import Counter, defaultdict from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import re import subprocess import sys from urllib.parse import unquote, urldefrag, urljoin, urlsplit, urlunsplit try: from bs4 import BeautifulSoup except ImportError: raise SystemExit("Use the pinned recovery Python, or set PYTHONPATH=scripts/rebuild-v2/vendor for offline verification") RASTER_DECODER = os.environ.get("VIDEOREG_RASTER_DECODER", "pillow") if RASTER_DECODER not in ("pillow", "sharp"): raise SystemExit("VIDEOREG_RASTER_DECODER must be pillow or sharp; raster validation cannot be disabled") if RASTER_DECODER == "pillow": try: from PIL import Image, ImageSequence except ImportError: raise SystemExit("Pillow is required for the default local decoder; use explicit VIDEOREG_RASTER_DECODER=sharp in offline CI") ROOT = Path(__file__).resolve().parents[2] INTERNAL_HOSTS = {"videoreg.ru", "www.videoreg.ru"} ATTRS = ("href", "src", "poster", "action", "formaction", "data", "cite", "background", "longdesc", "manifest", "xlink:href") CSS_URL = re.compile(r"url\(\s*(['\"]?)(.*?)\1\s*\)", re.I | re.S) CSS_IMPORT = re.compile(r"@import\s+(['\"])(.*?)\1", re.I) JS_STRING = re.compile(r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'') ABSOLUTE_URL = re.compile(r"(?:https?:)?//[^\s<>\"'`\\]+", re.I) SOURCE_ATTR = re.compile(r"\b(href|src|poster|action|formaction)\s*=\s*(?:\{\s*)?[\"']([^\"']+)[\"']", re.I) SPAM = re.compile(r"казино|покер|онлайн[ -]?ставк|ставки на спорт|payday loan|buy viagra|порно|букмекер", re.I) ERROR_BODY = re.compile(r"wayback machine (?:has not|hasn.t)|this url has been excluded|access denied|too many requests|just a moment\.\.\.|page cannot be crawled", re.I) SELF_REFERENCE = re.compile(r"(?:создан[аоы]?|нарисован[аоы]?|написан[аоы]?)\s+(?:в\s+)?2026|created by AI|сгенерирован[аоы]? (?:ИИ|AI)", re.I) def sha(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def read_json(path: Path, default): return json.loads(path.read_text()) if path.is_file() else default def confined(path: Path, root: Path) -> Path | None: try: resolved = path.resolve(strict=False) resolved.relative_to(root.resolve()) return resolved except (ValueError, OSError, RuntimeError): return None def tree_manifest(root: Path, predicate=lambda p: True): entries = [] rejected = [] if root.exists(): for path in sorted(root.rglob("*")): if not path.is_file() or not predicate(path): continue selected = confined(path, root) if selected is None: rejected.append(str(path.relative_to(root))) continue entries.append({"path": path.relative_to(root).as_posix(), "sha256": sha(selected.read_bytes()), "bytes": selected.stat().st_size}) return entries, rejected def manifest_hash(entries): return sha(json.dumps(entries, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()) def route_for(relative: str) -> str: if relative == "index.html": return "/" if relative.endswith("/index.html"): return "/" + relative[:-len("index.html")] return "/" + relative[:-len(".html")] def normalize_path(path: str) -> str: if path != "/" and path.endswith("/"): return path.rstrip("/") return path or "/" def split_srcset(value: str): # Data URI commas must not be mistaken for separate candidate URLs. for candidate in re.split(r",\s*(?![^\s]*;base64)", value): candidate = candidate.strip() if candidate: yield candidate.split()[0] def extract_html(data: bytes, source: str, stage: str): soup = BeautifulSoup(data, "html.parser") occurrences = [] for node in soup.find_all(True): context = node.get_text(" ", strip=True)[:240] or node.get("alt", "") or node.name for attribute in ATTRS: value = node.get(attribute) if isinstance(value, str) and value.strip(): occurrences.append(dict(stage=stage, sourcePage=source, element=node.name, attribute=attribute, context=context, destination=value.strip())) for attribute in ("srcset", "imagesrcset"): value = node.get(attribute) if isinstance(value, str): for candidate in split_srcset(value): occurrences.append(dict(stage=stage, sourcePage=source, element=node.name, attribute=attribute, context=context, destination=candidate)) if node.get("style"): for _, value in CSS_URL.findall(node["style"]): occurrences.append(dict(stage=stage, sourcePage=source, element=node.name, attribute="style:url", context=context, destination=value)) if node.name == "style": for _, value in CSS_URL.findall(node.get_text()): occurrences.append(dict(stage=stage, sourcePage=source, element="style", attribute="url", context="embedded stylesheet", destination=value)) if node.name == "meta" and str(node.get("http-equiv", "")).lower() == "refresh": refresh = re.search(r"url\s*=\s*(.+)", node.get("content", ""), re.I) if refresh: occurrences.append(dict(stage=stage, sourcePage=source, element="meta", attribute="refresh", context="automatic navigation", destination=refresh.group(1).strip(" '\""))) if node.name == "script" and not node.get("src"): for value in ABSOLUTE_URL.findall(node.get_text()): occurrences.append(dict(stage=stage, sourcePage=source, element="script", attribute="inline-url", context="embedded script string (may be inert serialized data)", destination=value.rstrip("),.;"))) return soup, occurrences def anchor_text(value): # The public template appends a decorative external-link arrow. return re.sub(r"\s+↗$", "", value).strip() def inert_script_constant(value, context): namespaces = {"http://www.w3.org/1999/xhtml", "http://www.w3.org/2000/svg", "http://www.w3.org/1998/Math/MathML", "http://www.w3.org/1999/xlink", "http://www.w3.org/XML/1998/namespace"} if value in namespaces: return "Exact DOM/XML namespace identifier, not a network request" if value in {"https://github.com/zloirock/core-js", "https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE"} and any(token in context for token in ("license:", "source:", "copyright:")): return "core-js source/license metadata in bundled polyfill" fixtures = {"https://a", "https://a/c%20d?a=1&c=3", "https://a@b", "https://тест", "https://a#б", "https://x"} if value in fixtures and "URL" in context: return "core-js local URL/URLSearchParams conformance fixture; no fetch" if value == "http://n" and ("URL" in context or "getLocationOrigin" in context): return "Next URL parser's local dummy base for server-side normalization" if value in {"https://react.dev/errors/", "https://nextjs.org/docs/messages/", "https://nextjs.org/docs/messages"}: return "Bundled framework error-message documentation prefix, not a resource load" return None def local_or_external(destination: str, owner: str, base: str): destination = destination.strip() if not destination: return "ignored", None if destination.startswith(("data:", "blob:")): return "embedded", destination if destination.lower().startswith(("javascript:", "vbscript:")): return "unsafe-scheme", destination if destination.startswith(("mailto:", "tel:", "ftp:")): return "external", destination parsed = urlsplit(urljoin(base.rstrip("/") + owner, destination)) base_host = urlsplit(base).hostname if parsed.scheme not in ("http", "https"): return "unsupported-scheme", destination if parsed.hostname in INTERNAL_HOSTS | {base_host}: return "local", urlunsplit(("", "", parsed.path or "/", parsed.query, parsed.fragment)) return "external", urlunsplit(parsed) def locate_export(out: Path, url: str): path = unquote(urlsplit(url).path) if "\\" in path or "\x00" in path or ".." in Path(path).parts: return None raw = out / path.lstrip("/") for selected in [raw, Path(str(raw) + ".html"), raw / "index.html"]: resolved = confined(selected, out) if resolved is not None and resolved.is_file(): return resolved return None def body_details(soup, route, error_document=False): title = soup.title.get_text(" ", strip=True) if soup.title else "" main = soup.find("article") or soup.find("main") or soup.body if main is None: return dict(title=title, bodyChars=0, words=0, bodySha256=sha(b""), findings=["missing-main-body"], ids=[]) text_soup = BeautifulSoup(str(main), "html.parser") for element in text_soup.select("script,style,nav,header,footer,.related-reading,.contents,[hidden],[aria-hidden=true]"): element.decompose() text = " ".join(text_soup.stripped_strings) normalized = re.sub(r"\s+", " ", text.lower()).strip() findings = [] is_article = soup.find("article") is not None if not error_document: if not title: findings.append("missing-title") if is_article and (len(text) < 300 or len(text.split()) < 40): findings.append("thin-article-needs-editorial-review") if ERROR_BODY.search(text): findings.append("possible-archive-or-antibot-error-body") if SPAM.search(text): findings.append("spam-keyword-needs-context-review") if SELF_REFERENCE.search(text): findings.append("self-referential-creation-copy") return dict(title=title, bodyChars=len(text), words=len(text.split()), bodySha256=sha(normalized.encode()), findings=findings, ids=sorted({n.get("id") for n in soup.find_all(id=True)}), article=is_article, images=len(soup.find_all("img")), tables=len(soup.find_all("table")), codeBlocks=len(soup.find_all("pre"))) def active_source_files(): src = ROOT / "web-front/src" pending = list((src / "app").rglob("*.tsx")) + list((src / "app").rglob("*.ts")) seen = set() while pending: path = pending.pop() safe = confined(path, src) if safe is None or not safe.is_file() or safe in seen: continue seen.add(safe) if safe.suffix not in (".ts", ".tsx", ".js", ".jsx", ".css"): continue text = safe.read_text() for target in re.findall(r"(?:import|export).*?(?:from\s*)?[\"']([^\"']+)[\"']", text): if target.startswith("@/"): stem = src / target[2:] elif target.startswith("."): stem = safe.parent / target else: continue candidates = [stem, *[Path(str(stem) + suffix) for suffix in (".ts", ".tsx", ".js", ".jsx", ".json", ".css")], stem / "index.ts", stem / "index.tsx"] pending.extend(p for p in candidates if p.is_file()) return sorted(seen) def source_occurrences(files): occurrences = [] for path in files: text = path.read_text() relative = path.relative_to(ROOT).as_posix() if path.suffix == ".json": try: data = json.loads(text) except json.JSONDecodeError: continue # Approval metadata is reviewed evidence, not an emitted destination. if path.name == "v2-link-approvals.json": continue def visit(value, context=""): if isinstance(value, dict): for key, item in value.items(): if key in ("href", "src", "poster", "action", "formaction", "url") and isinstance(item, str): occurrences.append(dict(stage="active-source", sourceFile=relative, attribute=key, context=str(value.get("label") or value.get("alt") or context)[:240], destination=item)) visit(item, str(value.get("title") or value.get("path") or context)) elif isinstance(value, list): for item in value: visit(item, context) visit(data) else: for match in SOURCE_ATTR.finditer(text): occurrences.append(dict(stage="active-source", sourceFile=relative, line=text[:match.start()].count("\n") + 1, attribute=match.group(1), context=text[max(0, match.start()-90):match.end()+90].strip()[:240], destination=match.group(2))) for _, value in CSS_URL.findall(text) + CSS_IMPORT.findall(text): occurrences.append(dict(stage="active-source", sourceFile=relative, attribute="css:url", context="stylesheet reference", destination=value)) return occurrences def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--base", help="Running local or public HTTP base; defaults to .local-run/server.json") parser.add_argument("--origin", help="Explicit diagnostic HTTPS origin IP (requires --insecure-origin for untrusted certificate)") parser.add_argument("--insecure-origin", action="store_true", help="Diagnostic only; never records TLS as verified") parser.add_argument("--out", type=Path, default=ROOT / "web-front/out") parser.add_argument("--inventory", type=Path, default=ROOT / "docs/rebuild-v2/url-inventory.json") parser.add_argument("--approvals", type=Path, default=ROOT / "web-front/src/content/v2-link-approvals.json") parser.add_argument("--report", type=Path, default=ROOT / "docs/rebuild-v2/evidence/built-crawl.json") args = parser.parse_args() base = (args.base or read_json(ROOT / ".local-run/server.json", {}).get("url", "")).rstrip("/") if urlsplit(base).scheme not in ("http", "https") or not urlsplit(base).hostname: parser.error("Provide an http(s) --base or start the local preview") if args.insecure_origin and not args.origin: parser.error("--insecure-origin is allowed only for an explicit diagnostic --origin") out = args.out.resolve() if not out.is_dir(): parser.error("Missing export; owner must build candidate first") before, unsafe_files = tree_manifest(out) source_files = active_source_files() source_before = [{"path": p.relative_to(ROOT).as_posix(), "sha256": sha(p.read_bytes())} for p in source_files] approvals = read_json(args.approvals, []) inventory = read_json(args.inventory, []) legacy = read_json(ROOT / "deploy/legacy-routes.json", {}) errors = [{"kind": "export-file-outside-root", "file": x} for x in unsafe_files] repository_git = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True) repository_head = repository_git.stdout.strip() built_health = {} try: built_health_path = confined(out / "health/ready", out) if built_health_path is not None: built_health = read_json(built_health_path, {}) except (ValueError, OSError) as exc: errors.append(dict(kind="invalid-built-health-metadata", error=str(exc))) metadata = built_health.get("metadata", {}) if isinstance(built_health, dict) else {} built_revision = metadata.get("commitSha") if isinstance(metadata, dict) else None built_source_files = [] built_source_manifest = None if not isinstance(built_revision, str) or not re.fullmatch(r"[0-9a-f]{40}", built_revision): errors.append(dict(kind="missing-built-source-revision", value=built_revision)) else: # A later docs/tooling commit is not the source revision of an already # built candidate. Compare actual active sources to that Git snapshot. for source in source_before: result = subprocess.run(["git", "show", built_revision + ":" + source["path"]], cwd=ROOT, capture_output=True) if result.returncode: errors.append(dict(kind="built-source-unavailable-in-git", revision=built_revision, file=source["path"])) else: built_source_files.append(dict(path=source["path"], sha256=sha(result.stdout))) if len(built_source_files) == len(source_before): built_source_manifest = manifest_hash(built_source_files) if built_source_manifest != manifest_hash(source_before): errors.append(dict(kind="current-app-source-differs-from-built-revision", builtRevision=built_revision, builtSourceManifestSha256=built_source_manifest, actualSourceManifestSha256=manifest_hash(source_before))) warnings = [] responses = {} http_checks = [] request_urls = set() def request(url, method="GET"): url = urldefrag(url)[0] key = method, url if key in responses: return responses[key] cmd = ["curl", "-sS", "--max-time", "20", "--path-as-is", "-D", "-", "-w", "\n__VIDEOREG_STATUS__:%{http_code}"] cmd += ["--head"] if method == "HEAD" else ["-X", method] if args.origin: cmd += ["--resolve", f"{urlsplit(base).hostname}:443:{args.origin}"] if args.insecure_origin: cmd += ["-k"] cmd += [base + url] result = subprocess.run(cmd, capture_output=True) status_marker = b"\n__VIDEOREG_STATUS__:" prefix, _, raw_status = result.stdout.rpartition(status_marker) status = int(raw_status) if raw_status.isdigit() else 0 # curl can prepend HTTP CONNECT/interim headers; choose final header block. content = prefix headers = {} while content.startswith(b"HTTP/"): boundary = content.find(b"\r\n\r\n") length = 4 if boundary < 0: boundary = content.find(b"\n\n"); length = 2 if boundary < 0: break header_block, content = content[:boundary], content[boundary+length:] headers = {} for line in header_block.splitlines()[1:]: if b":" in line: name, value = line.split(b":", 1) headers[name.decode().lower()] = value.decode(errors="replace").strip() value = dict(status=status, headers=headers, body=content, returncode=result.returncode, error=result.stderr.decode(errors="replace")[:1000]) responses[key] = value request_urls.add(url) http_checks.append(dict(url=url, method=method, status=status, curlReturncode=result.returncode, bytes=len(content), location=headers.get("location"), contentType=headers.get("content-type"))) return value live_health_response = request("/health/ready") live_health = None try: live_health = json.loads(live_health_response["body"]) except (ValueError, TypeError): pass if live_health_response["status"] != 200 or live_health != built_health: errors.append(dict(kind="live-built-health-identity-mismatch", status=live_health_response["status"], expected=built_health, actual=live_health)) pages = [] occurrences = [] script_constants = [] asset_checks = [] page_by_file = {} for entry in before: relative = entry["path"] if not relative.endswith(".html"): continue path = out / relative data = path.read_bytes() route = route_for(relative) error_document = relative in ("404.html", "_not-found.html") soup, found = extract_html(data, route, "generated-html") detail = body_details(soup, route, error_document) row = dict(file=relative, route=route, sha256=entry["sha256"], bytes=entry["bytes"], errorDocument=error_document, **detail) response = request("/" + relative if error_document else route) row["httpStatus"] = response["status"] row["httpSha256"] = sha(response["body"]) if not error_document and response["status"] != 200: errors.append(dict(kind="published-page-http-status", route=route, status=response["status"])) if not error_document and response["status"] == 200 and response["body"] != data: errors.append(dict(kind="http-build-body-mismatch", route=route, file=relative)) pages.append(row) page_by_file[path.resolve()] = row occurrences.extend(found) for finding in row["findings"]: warnings.append(dict(kind=finding, route=route)) if not pages: errors.append(dict(kind="empty-export-no-html")) # Decode every exported raster asset, including unlinked public files. # Both explicit decoders fail closed; there is no "skip images" fallback. raster_entries = [entry for entry in before if Path(entry["path"]).suffix.lower() in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico")] if RASTER_DECODER == "sharp": result = subprocess.run(["node", str(ROOT / "scripts/rebuild-v2/decode-raster-sharp.mjs")], cwd=ROOT, input=json.dumps(dict(root=str(out), files=[e["path"] for e in raster_entries])).encode(), capture_output=True) try: decoded = json.loads(result.stdout) decoded_rows = decoded["results"] if [item.get("file") for item in decoded_rows] != [e["path"] for e in raster_entries]: raise ValueError("Sharp did not return every requested raster in order") for entry, item in zip(raster_entries, decoded_rows): item["sha256"] = entry["sha256"] asset_checks.append(item) if not item.get("valid"): errors.append(dict(kind="invalid-raster-image", file=entry["path"], error=item.get("error"), decoder="sharp")) if result.returncode and not any(not item.get("valid") for item in decoded_rows): errors.append(dict(kind="raster-decoder-process-failed", decoder="sharp", returncode=result.returncode, error=result.stderr.decode(errors="replace")[:2000])) except (ValueError, KeyError, TypeError) as exc: errors.append(dict(kind="raster-decoder-failed", decoder="sharp", error=str(exc), stderr=result.stderr.decode(errors="replace")[:2000])) else: for entry in raster_entries: path = out / entry["path"] try: with Image.open(path) as image: width, height = image.size image.verify() with Image.open(path) as image: for frame in ImageSequence.Iterator(image): frame.load() asset_checks.append(dict(file=entry["path"], type="raster", valid=True, width=width, height=height, sha256=entry["sha256"], decoder="pillow-verify-and-full-load")) except Exception as exc: asset_checks.append(dict(file=entry["path"], type="raster", valid=False, error=str(exc), decoder="pillow")) errors.append(dict(kind="invalid-raster-image", file=entry["path"], error=str(exc))) for entry in before: path = out / entry["path"] if path.suffix.lower() == ".pdf": data = path.read_bytes() valid = b"%PDF-" in data[:1024] and b"%%EOF" in data[-2048:] asset_checks.append(dict(file=entry["path"], type="pdf-signature-and-eof", valid=valid, sha256=entry["sha256"])) if not valid: errors.append(dict(kind="invalid-pdf-signature", file=entry["path"])) # Scan every emitted CSS/JS/SVG, not only those linked from the homepage. for entry in before: path = out / entry["path"] if path.suffix == ".svg": _, found = extract_html(path.read_bytes(), "/" + entry["path"], "generated-svg") occurrences.extend(found) elif path.suffix in (".css", ".js", ".mjs"): text = path.read_text(errors="replace") for _, value in (CSS_URL.findall(text) if path.suffix == ".css" else []): occurrences.append(dict(stage="generated-resource", sourcePage="/" + entry["path"], sourceFile=entry["path"], attribute="css:url", context="emitted resource", destination=value)) for _, value in CSS_IMPORT.findall(text): occurrences.append(dict(stage="generated-resource", sourcePage="/" + entry["path"], sourceFile=entry["path"], attribute="css:import", context="emitted stylesheet import", destination=value)) if path.suffix in (".js", ".mjs"): for match in JS_STRING.finditer(text): value = match.group(0)[1:-1].replace("\\/", "/") if not re.fullmatch(r"(?:https?:)?//[^\s<>\"'`]+", value): continue context = text[max(0, match.start()-180):match.end()+180] reason = inert_script_constant(value, context) if reason: script_constants.append(dict(sourceFile=entry["path"], destination=value, context=context, classification="inert-code-constant", reviewed=True, reviewer="programmer-code-context", reason=reason)) else: occurrences.append(dict(stage="generated-script-string", sourcePage="/" + entry["path"], sourceFile=entry["path"], attribute="inline-url", context=context, destination=value)) local_refs = [] outbound = [] for occurrence in occurrences: owner = occurrence.get("sourcePage", "/") kind, destination = local_or_external(occurrence["destination"], owner, base) occurrence["classification"] = kind occurrence["resolvedDestination"] = destination if kind in ("unsafe-scheme", "unsupported-scheme"): errors.append(dict(kind="unsafe-or-unsupported-reference", **occurrence)) elif kind == "external": matching = [a for a in approvals if a.get("sourcePage") == owner and a.get("destination") == destination and a.get("anchor") == anchor_text(occurrence.get("context", "")) and a.get("reviewed") is True and a.get("decision") == "keep" and a.get("reason")] if not matching and occurrence["attribute"] == "inline-url": # Next serializes already emitted link props for hydration. This # is approved only when the exact page/URL/anchor was emitted. matching = [a for a in approvals if a.get("sourcePage") == owner and a.get("destination") == destination and a.get("reviewed") is True and a.get("decision") == "keep" and a.get("reason") and any(x.get("sourcePage") == owner and x.get("destination") == destination and anchor_text(x.get("context", "")) == a.get("anchor") and x.get("attribute") == "href" for x in occurrences)] if matching: occurrence["classification"] = "serialized-reference-of-approved-link" occurrence["reviewed"] = bool(matching) occurrence["approvalReason"] = matching[0]["reason"] if matching else None outbound.append(occurrence) if not matching: errors.append(dict(kind="unapproved-external-occurrence", sourcePage=owner, destination=destination, context=occurrence.get("context"), stage=occurrence["stage"])) elif kind == "local": local_refs.append(occurrence) url, fragment = urldefrag(destination) selected = locate_export(out, url) response = request(url) if url in legacy: expected = legacy[url] if response["status"] != 308 or response["headers"].get("location") != expected: errors.append(dict(kind="legacy-reference-mismatch", url=url, expected=expected, status=response["status"], location=response["headers"].get("location"))) target_url, target_fragment = urldefrag(expected) selected = locate_export(out, target_url) fragment = target_fragment or fragment elif response["status"] != 200: errors.append(dict(kind="missing-local-reference", sourcePage=owner, destination=destination, status=response["status"], attribute=occurrence["attribute"])) elif selected is None: errors.append(dict(kind="local-reference-not-in-export", sourcePage=owner, destination=destination)) if fragment and selected is not None: target = page_by_file.get(selected) if target and unquote(fragment) not in target["ids"]: errors.append(dict(kind="missing-fragment", sourcePage=owner, destination=destination)) if selected is not None and response["status"] == 200 and selected not in page_by_file and response["body"] != selected.read_bytes(): errors.append(dict(kind="http-asset-body-mismatch", sourcePage=owner, destination=destination)) if occurrence.get("element") == "img" and selected is not None and selected.stat().st_size == 0: errors.append(dict(kind="empty-image", sourcePage=owner, destination=destination)) active_occurrences = source_occurrences(source_files) for occurrence in active_occurrences: kind, destination = local_or_external(occurrence["destination"], "/", base) occurrence["classification"] = kind if kind == "external": occurrence["appearsInExport"] = any(x["resolvedDestination"] == destination for x in outbound) occurrence["exactDestinationApproved"] = any(a.get("destination") == destination and a.get("reviewed") is True and a.get("decision") == "keep" for a in approvals) if not occurrence["appearsInExport"] and not occurrence["exactDestinationApproved"]: errors.append(dict(kind="source-external-not-reviewed", **occurrence)) elif kind in ("unsafe-scheme", "unsupported-scheme"): errors.append(dict(kind="unsafe-source-reference", **occurrence)) duplicates = [] grouped = defaultdict(list) for page in pages: if page.get("article") and not page["errorDocument"]: grouped[page["bodySha256"]].append(page["route"]) for digest, routes in grouped.items(): if len(routes) > 1: duplicates.append(dict(bodySha256=digest, routes=routes)) errors.append(dict(kind="duplicate-article-body", routes=routes)) source_publications = [] generated_routes = {normalize_path(p["route"]) for p in pages if not p["errorDocument"]} for source_file in source_files: if source_file.name not in ("v2-articles.json", "v2-community.json"): continue for article in read_json(source_file, []): route = article.get("path") present = normalize_path(route or "") in generated_routes source_publications.append(dict(path=route, title=article.get("title"), sourceFile=source_file.relative_to(ROOT).as_posix(), generated=present)) if not present: errors.append(dict(kind="typed-article-not-exported", route=route, sourceFile=source_file.relative_to(ROOT).as_posix())) legacy_results = [] for original, destination in legacy.items(): response = request(original) target, fragment = urldefrag(destination) target_response = request(target) selected = locate_export(out, target) passed = response["status"] == 308 and response["headers"].get("location") == destination and target_response["status"] == 200 and selected is not None if fragment: target_page = page_by_file.get(selected) passed = passed and target_page is not None and fragment in target_page["ids"] legacy_results.append(dict(original=original, destination=destination, status=response["status"], location=response["headers"].get("location"), targetStatus=target_response["status"], passed=bool(passed))) if not passed: errors.append(dict(kind="legacy-route-failed", **legacy_results[-1])) behavior = [] for path, method, expected in [("/videoreg-v2-definitely-missing-page", "GET", 404), ("/api/videos", "GET", 404), ("/api/videos", "POST", 404), ("/_dev/showcase", "GET", 404), ("/", "HEAD", 200), ("/health/ready", "HEAD", 200), ("/forum/viewtopic.php?t=184&start=20", "GET", 404), ("/forum/viewtopic.php?t=184&highlight=word", "GET", 404), ("/forum/viewtopic.php?t=184&postorder=desc", "GET", 404)]: response = request(path, method) passed = response["status"] == expected behavior.append(dict(path=path, method=method, expected=expected, status=response["status"], passed=passed)) if not passed: errors.append(dict(kind="http-behavior-failed", **behavior[-1])) inventory_results = [] unresolved = [] for item in inventory: status = item.get("publicationStatus", "missing-status") destination = item.get("currentDestination") raw = item.get("rawFile") raw_integrity = None if raw and item.get("rawSha256"): raw_path = confined(ROOT / raw, ROOT) raw_integrity = raw_path is not None and raw_path.is_file() and sha(raw_path.read_bytes()) == item["rawSha256"] if not raw_integrity: errors.append(dict(kind="inventory-raw-hash-mismatch", originalUrl=item.get("originalUrl"), file=raw)) row = dict(originalUrl=item.get("originalUrl"), type=item.get("type"), status=status, destination=destination, rawHashVerified=raw_integrity, reason=item.get("exclusionOrUnresolvedReason")) if status.startswith("unresolved") or status == "missing-status": unresolved.append(row) elif status.startswith("excluded"): if not item.get("exclusionOrUnresolvedReason"): errors.append(dict(kind="inventory-exclusion-without-reason", originalUrl=item.get("originalUrl"))) elif destination: kind, url = local_or_external(destination, "/", base) if kind != "local" or locate_export(out, url) is None: errors.append(dict(kind="inventory-destination-missing", **row)) else: row["targetExists"] = True selected = locate_export(out, url) fragment = urlsplit(url).fragment target_page = page_by_file.get(selected) if fragment and target_page and unquote(fragment) not in target_page["ids"]: errors.append(dict(kind="inventory-destination-fragment-missing", **row)) else: errors.append(dict(kind="inventory-published-without-destination", **row)) inventory_results.append(row) after, _ = tree_manifest(out) source_after = [{"path": p.relative_to(ROOT).as_posix(), "sha256": sha(p.read_bytes())} for p in source_files if p.is_file()] if before != after: errors.append(dict(kind="build-mutated-during-check")) if source_before != source_after: errors.append(dict(kind="source-mutated-during-check")) report = dict(schemaVersion=1, domain="videoreg.ru", generatedAt=datetime.now(timezone.utc).isoformat(), sourceCommit=built_revision, repositoryHead=repository_head, builtHealthMetadata=built_health, builtSourceManifestSha256=built_source_manifest, rasterDecoder=RASTER_DECODER, sourceManifestSha256=manifest_hash(source_before), sourceFiles=source_before, exportManifestSha256=manifest_hash(before), exportFileCount=len(before), base=base, origin=args.origin, tlsVerified=False if args.insecure_origin else (True if base.startswith("https://") and all(x["curlReturncode"] == 0 for x in http_checks) else None), browserDOMInspection="not performed by this script; use separate exact-candidate browser evidence", summary=dict(technicalStatus="failed" if errors else "passed", restorationStatus="blocked-unresolved-inventory" if unresolved else "reconciled", acceptance="blocked" if errors or unresolved else "mechanical-checks-only-not-role-approval", htmlFiles=len(pages), contentPages=sum(not p["errorDocument"] for p in pages), HTTPRequests=len(http_checks), localReferences=len(local_refs), emittedExternalOccurrences=len(outbound), activeSourceFiles=len(source_files), inventoryItems=len(inventory), unresolvedInventoryItems=len(unresolved), suspiciousPages=len(warnings), errors=len(errors), decodedRasterAssets=sum(x["type"] == "raster" for x in asset_checks)), pages=pages, assetChecks=asset_checks, duplicateBodies=duplicates, suspiciousCandidates=warnings, errors=errors, localReferences=local_refs, outboundOccurrences=outbound, inertScriptConstants=script_constants, activeSourceReferences=active_occurrences, HTTPChecks=http_checks, legacyRoutes=legacy_results, sourcePublications=source_publications, behavior=behavior, coverage=dict(statusCounts=dict(Counter(x["status"] for x in inventory_results)), items=inventory_results, unresolved=unresolved), limitations=["No external page is fetched by this checker; approvals must contain independent editorial verification.", "HTML/CSS/script-string extraction detects static references. Live JavaScript interactions, crops and browser DOM are checked separately.", "Suspicious thin/spam/error flags require per-page editorial assessment; they are not automatically treated as spam exclusions.", "A reconciled inventory does not establish that the external discovery denominator is complete."]) args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") print(json.dumps(dict(report=str(args.report.relative_to(ROOT) if args.report.is_relative_to(ROOT) else args.report), **report["summary"]), ensure_ascii=False)) return 1 if errors or unresolved else 0 if __name__ == "__main__": sys.exit(main())