"""Verification you don't have to take our word for: the running source of the integrity modules, third-party (Internet Archive) copies of the public logs, the marketing-entity disclosure, and the auditor packet.""" import hashlib import logging import os from datetime import datetime, timedelta, timezone from pathlib import Path import httpx from fastapi import APIRouter, HTTPException from fastapi.responses import PlainTextResponse from deps import db logger = logging.getLogger("verification") router = APIRouter(prefix="/api/public") HERE = Path(__file__).parent # Only integrity modules are exposed; they contain no secrets (environment variable NAMES only). PUBLIC_CODE = { "firewall.py": "Runtime billing firewall — refuses any billing request carrying score/rank/record/expedite fields.", "conflicts.py": "Conflicts & revenue endpoint — live counts, import-scan separation check, source roster.", "corrections.py": "Corrections desk — free tickets, hash-chained public log, operator resolve.", "covenantscore.py": "Covenant Index engine — formula, reproduce steps, score change log, report purchase (Stripe key read by NAME only).", "stateregistry.py": "State registry connector — verbatim rows, official links, no invented values.", "verification.py": "This module.", "cite.py": "Citable figures — permalink receipts (source, pull time, hash, accuracy history) for any published number; source-moved feed.", "platform_seal.py": "Platform seal — API allowlist (410 for everything else), sealed background jobs, sealed payment sources, and the public manifest at /api/public/sealed.", "scorerefresh.py": "Scheduled 12-hourly re-pull of every published Covenant Index figure so copies stay inside the 24 h window; publicly resolves accuracy-opened tickets with the re-pulled value.", "accuracy.py": "Continuous accuracy check — re-fetches published figures from their sources and publishes matches and misses as plain counts (self-check, not an independent audit).", "replay.py": "Independent replay — standard-library script anyone can run to re-issue every published check's exact public request and compare with the published figure. Reproducibility tool, not an audit.", "tests/test_separation.py": "Build test: scoring modules must not import billing modules.", } ARCHIVE_TARGETS = ["/api/corrections", "/api/public/conflicts", "/api/public/accuracy", "/api/record/trust", "/api/public/trust", "/api/record/reviewer-packet", "/methodology", "/conflicts", "/corrections", "/accuracy", "/api/public/code"] JOB = "archive_public_logs" def _sha(b: bytes) -> str: return hashlib.sha256(b).hexdigest() def entity_disclosure() -> dict: name, url = os.environ.get("MARKETING_ENTITY_NAME", "").strip(), os.environ.get("MARKETING_ENTITY_URL", "").strip() return {"records_platform_entity": "Alpha Covenant Holdings, a trade name (DBA) of Build Break Build Fitness and Promo (Cincinnati, Ohio; entity details on file with the Ohio Secretary of State).", "marketing_business": {"named": bool(name), "name": name or None, "website": url or None, "status": "Operating under its own name and website." if name else "Being formed. Its legal name and website will be published here the day they exist; until then no marketing, affiliate or growth service is sold anywhere under the Alpha Covenant name."}, "common_ownership": True, "common_ownership_statement": "Both businesses are owned by the same person. The separation is structural, not an ownership divestiture: separate name, separate website, separate database, no shared code, no data flow in either direction, and no record page links to the marketing business. Anyone evaluating the platform should weigh that fact directly.", "what_would_change_it": "A sale of the marketing business to an unrelated party, or an independent audit confirming the structural controls, would be published here."} @router.get("/code") async def code_index(): files = [] for rel, what in PUBLIC_CODE.items(): p = HERE / rel if p.exists(): b = p.read_bytes() files.append({"file": rel, "what": what, "bytes": len(b), "sha256": _sha(b), "url": f"/api/public/code/{rel}"}) return {"note": "This is the source code running on this server right now, read from disk on each request — not a copy in a repository. Hash it yourself and compare.", "files": files, "generated_at": datetime.now(timezone.utc).isoformat()} @router.get("/code/{path:path}", response_class=PlainTextResponse) async def code_file(path: str): if path not in PUBLIC_CODE: raise HTTPException(status_code=404, detail="Only the integrity modules are published.") b = (HERE / path).read_bytes() return PlainTextResponse(b, headers={"X-Content-SHA256": _sha(b), "Cache-Control": "no-store"}) @router.get("/verification") async def verification(): snaps = await db.archive_snapshots.find({}, {"_id": 0}).sort("at", -1).to_list(60) host = (os.environ.get("PUBLIC_BASE_URL") or "https://alphacovenantholdings.com").replace("https://", "").replace("http://", "").rstrip("/") return {"entity_disclosure": entity_disclosure(), "running_code": {"index": "/api/public/code", "files": list(PUBLIC_CODE)}, "third_party_copies": {"holder": "Internet Archive (Wayback Machine) — an independent non-profit; copies cannot be edited by us after capture.", "targets": ARCHIVE_TARGETS, "browse": [f"https://web.archive.org/web/*/{host}{t}" for t in ARCHIVE_TARGETS], "recent_captures": snaps}, "self_tests": [{"what": "Runtime billing firewall", "how": "POST /api/carrier-monitor/checkout with JSON {\"plan\":\"fleet25\",\"email\":\"you@example.com\",\"targets\":[],\"target_score\":95} — expect HTTP 403 naming the field; the attempt is counted on /conflicts."}, {"what": "Score reproducibility", "how": "GET /api/score?company=mohela → open reproduce.steps[0].url on consumerfinance.gov and compare hits.total.value."}, {"what": "Corrections log integrity", "how": "GET /api/corrections → for any entry, SHA-256 the sorted-JSON of {seq, ts, event, ticket_id, details, prev_hash} and compare to hash; prev_hash must equal the previous entry's hash."}, {"what": "Scoring ↔ billing separation", "how": "Read /api/public/code/conflicts.py (separation_check) and /api/public/code/tests/test_separation.py, then GET /api/public/conflicts → separation_check.pass."}], "independent_audit": {"status": "none yet", "packet": "/api/public/auditor-packet"}} @router.get("/auditor-packet") async def auditor_packet(): import covenantscore cols = {"records (written only by source pulls)": ["watchdog_snapshots", "covenant_scores", "score_changes", "ledger", "carrier_cache", "carrier_history", "registry_snapshots", "public_record_cache"], "corrections desk": ["corrections", "corrections_log"], "firewall": ["firewall_events"], "third-party copies": ["archive_snapshots"], "billing (never read by scoring code)": ["sponsors", "carrier_watchlists", "carrier_subscriptions", "payment_transactions", "covenant_reports"]} counts = {} for group in cols.values(): for c in group: counts[c] = await db[c].estimated_document_count() return {"purpose": "Everything an independent auditor needs to test the platform's integrity claims. Read access to the named collections is granted on request via /press.", "claims_to_test": ["Every displayed figure equals its named source at the recorded pull time (spot-check via 'View official source' links and reproduce steps).", "No billing code path writes to any record collection (collection ownership + import scan + firewall).", "Score changes occur only when a public input or the published formula version changes (score_changes vs covenant_scores history).", "Corrections log is append-only and hash-chained; no entry altered after capture (compare with Internet Archive copies)."], "collections": cols, "document_counts": counts, "formula": {"current_version": "2026-09-14c", "methodology": covenantscore.METHODOLOGY}, "endpoints": ["/api/public/conflicts", "/api/public/verification", "/api/public/code", "/api/corrections", "/api/score?company=", "/api/score/changes?company=", "/api/record/company?q=", "/api/carriers/{usdot}/history"], "generated_at": datetime.now(timezone.utc).isoformat()} async def archive_job(db_=None, payload: dict | None = None): """Daily: ask the Internet Archive to capture the public logs so an independent party holds every day's copy.""" import scheduler as scheduler_mod base = (os.environ.get("PUBLIC_BASE_URL") or "https://alphacovenantholdings.com").rstrip("/") results = [] async with httpx.AsyncClient(timeout=60, follow_redirects=True, headers={"User-Agent": "AlphaCovenantArchiver/1.0 (+https://alphacovenantholdings.com/conflicts)"}) as client: for t in ARCHIVE_TARGETS: try: r = await client.get(f"https://web.archive.org/save/{base}{t}") a = await client.get("https://archive.org/wayback/available", params={"url": f"{base.split('://', 1)[-1]}{t}"}) closest = ((a.json() if a.status_code == 200 else {}).get("archived_snapshots") or {}).get("closest") or {} results.append({"target": t, "save_status": r.status_code, "captured": bool(closest.get("available")), "capture_timestamp": closest.get("timestamp"), "archived_url": closest.get("url")}) except Exception as e: results.append({"target": t, "save_status": None, "captured": False, "error": type(e).__name__}) db_ = db if db_ is None else db_ await db_.archive_snapshots.insert_one({"at": datetime.now(timezone.utc).isoformat(), "results": results}) logger.info(f"archive_public_logs: {[(x['target'], x.get('captured')) for x in results]}") await scheduler_mod.enqueue(db_, JOB, {}, run_at=datetime.now(timezone.utc) + timedelta(hours=24)) return {"results": results}