#!/usr/bin/env python3
"""
alfred-supply-chain-audit — Sovereign Pre-Release & Webroot Leak Gate
Clean-room scanner preventing .js.map source-map leaks, .bak/.swp artifacts,
exposed .env/.git metadata, and accidental credential/PII exposure in webroots
and ISO build trees.
"""
import argparse
import json
import os
import re
import sys
from pathlib import Path

SKIP_DIRS = {
    "node_modules", ".git", "__pycache__", "vendor", ".venv", "venv",
    "chroot", "cache", ".cache", "proc", "sys", "dev"
}

BACKUP_SUFFIXES = (
    ".bak", ".orig", ".old", ".swp", ".swo", ".save", ".tmp"
)
SOURCEMAP_SUFFIXES = (
    ".js.map", ".mjs.map", ".cjs.map", ".css.map"
)
DANGEROUS_FILENAMES = {
    ".env", ".env.local", ".env.production", "id_rsa", "id_ed25519",
    "wp-config.php.bak", "config.php.bak"
}

SECRET_PATTERNS = [
    ("private_key_pem", re.compile(r"-----BEGIN (?:RSA |OPENSSH |EC |DSA )?PRIVATE KEY-----")),
    ("stripe_live_secret", re.compile(r"\bsk_live_[0-9a-zA-Z]{20,}\b")),
    ("aws_access_key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
    ("github_pat", re.compile(r"\bgh[pousr]_[0-9a-zA-Z]{30,}\b")),
    ("cloud_ai_secret", re.compile(r"\bsk-(?:proj-|ant-api03-)[0-9a-zA-Z_-]{20,}\b")),
    ("unowned_domain_leak", re.compile(r"\balfred" + r"\.com\b", re.I)),
]

PII_PATTERNS = [
    ("lan_ipv4", re.compile(r"\b192\.168\.\d{1,3}\.\d{1,3}\b")),
]

TEXT_EXTS = {
    ".php", ".js", ".mjs", ".ts", ".tsx", ".jsx", ".html", ".htm",
    ".css", ".json", ".yml", ".yaml", ".sh", ".py", ".md", ".txt", ".xml"
}


def parse_htaccess_protections(root: Path) -> dict:
    prot = {"maps": False, "backups": False, "git": False}
    candidates = [root / ".htaccess"]
    if os.path.isdir("/etc/nginx/sites-enabled"):
        for nf in os.listdir("/etc/nginx/sites-enabled"):
            p = Path("/etc/nginx/sites-enabled") / nf
            if p.is_file():
                try:
                    if str(root) in p.read_text(encoding="utf-8", errors="ignore"):
                        candidates.append(p)
                except Exception:
                    pass
    for cfg in candidates:
        if not cfg.is_file():
            continue
        try:
            txt = cfg.read_text(encoding="utf-8", errors="ignore")
            has_deny = bool(re.search(r"Require\s+all\s+denied|Deny\s+from\s+all|deny\s+all", txt, re.I))
            if has_deny:
                if re.search(r"\\\.map|\bmap\b", txt):
                    prot["maps"] = True
                if re.search(r"bak", txt) and re.search(r"old", txt):
                    prot["backups"] = True
                if re.search(r"git|\\\.\(\?!well-known\)", txt):
                    prot["git"] = True
        except Exception:
            pass
    return prot


def scan_target(target_dir: str, check_pii: bool = False):
    findings = []
    root = Path(target_dir)
    if not root.exists():
        return findings, 0

    prot = parse_htaccess_protections(root)
    scanned_files = 0

    for dirpath, dirnames, filenames in os.walk(root):
        rel_dir = os.path.relpath(dirpath, root)
        if ".git" in dirnames and rel_dir == ".":
            if any(seg in str(root) for seg in ("/var/www/", "/public_html", "/web")):
                sev = "LOW" if prot["git"] else "CRITICAL"
                findings.append({
                    "severity": sev,
                    "kind": "exposed_git_dir",
                    "path": str(Path(dirpath) / ".git"),
                    "detail": ".git in webroot (403-blocked by .htaccess)" if prot["git"] else ".git directory publicly readable in webroot"
                })
        dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]

        for fn in filenames:
            fp = Path(dirpath) / fn
            if fp.is_symlink():
                continue
            scanned_files += 1
            low = fn.lower()

            if fn in DANGEROUS_FILENAMES or low.startswith(".env."):
                findings.append({
                    "severity": "CRITICAL",
                    "kind": "exposed_secret_file",
                    "path": str(fp),
                    "detail": f"Sensitive dotfile/key in tree: {fn}"
                })
                continue

            if low.endswith(SOURCEMAP_SUFFIXES):
                sev = "LOW" if prot["maps"] else "HIGH"
                findings.append({
                    "severity": sev,
                    "kind": "exposed_sourcemap",
                    "path": str(fp),
                    "detail": "Source map in webroot (403-blocked by .htaccess)" if prot["maps"] else "Unblocked .map source map exposes original source tree"
                })
                continue

            if low.endswith(BACKUP_SUFFIXES) or fn.endswith("~") or re.search(r"\.bak[-_.]", low):
                sev = "LOW" if prot["backups"] else "HIGH"
                findings.append({
                    "severity": sev,
                    "kind": "backup_swap_artifact",
                    "path": str(fp),
                    "detail": f"Backup/swap file in webroot (403-blocked by .htaccess): {fn}" if prot["backups"] else f"Unblocked backup/swap file in webroot: {fn}"
                })
                continue

            ext = fp.suffix.lower()
            if ext in TEXT_EXTS:
                try:
                    if fp.stat().st_size > 2_000_000:
                        continue
                    content = fp.read_text(encoding="utf-8", errors="ignore")
                except Exception:
                    continue

                for kind, rx in SECRET_PATTERNS:
                    m = rx.search(content)
                    if m:
                        findings.append({
                            "severity": "CRITICAL",
                            "kind": kind,
                            "path": str(fp),
                            "detail": f"Matched secret pattern {kind}"
                        })

                if check_pii:
                    for kind, rx in PII_PATTERNS:
                        m = rx.search(content)
                        if m:
                            findings.append({
                                "severity": "MEDIUM",
                                "kind": kind,
                                "path": str(fp),
                                "detail": f"Matched private network literal: {m.group(0)}"
                            })

    return findings, scanned_files


def main():
    ap = argparse.ArgumentParser(description="Alfred Supply-Chain & Webroot Leak Gate")
    ap.add_argument("paths", nargs="*", default=["/var/www"], help="Directories to audit")
    ap.add_argument("--check-pii", action="store_true", help="Also flag RFC1918 LAN IPs")
    ap.add_argument("--json", action="store_true", help="Emit JSON report")
    ap.add_argument("--strict", action="store_true", help="Exit non-zero on HIGH or CRITICAL findings")
    args = ap.parse_args()

    all_findings = []
    total_scanned = 0
    for p in args.paths:
        if not os.path.exists(p):
            continue
        res = scan_target(p, check_pii=args.check_pii)
        if isinstance(res, tuple):
            fnds, cnt = res
            all_findings.extend(fnds)
            total_scanned += cnt

    high_crit = [f for f in all_findings if f["severity"] in ("HIGH", "CRITICAL")]
    report = {
        "ok": len(high_crit) == 0,
        "scanned_files": total_scanned,
        "total_findings": len(all_findings),
        "blocking_findings": len(high_crit),
        "findings": all_findings[:100],
    }

    if args.json:
        print(json.dumps(report, indent=2))
    else:
        status = "PASS" if report["ok"] else "FAIL"
        print(f"[alfred-supply-chain-audit] {status} — scanned {total_scanned} files, {len(high_crit)} blocking ({len(all_findings)} total)")
        for f in all_findings[:40]:
            print(f"  [{f['severity']}] {f['kind']}: {f['path']} — {f['detail']}")

    if args.strict and not report["ok"]:
        sys.exit(1)


if __name__ == "__main__":
    main()
