#!/usr/bin/env python3
"""
PatchPulse Local Repo Scanner (scan.py)
---------------------------------------
Zero-dependency, 100% offline security & AI-API sunset exposure scanner.
Audits local repositories for active critical CVEs, supply-chain hijacks,
EOL database/runtime images, and expiring OpenAI / Anthropic / Google Gemini models.

Privacy: Makes ZERO network calls and sends ZERO telemetry.
Usage:
  python3 scan.py .
  python3 scan.py /path/to/repo --json
  python3 scan.py /path/to/repo --strict    # exits with code 2 on CRITICAL/HIGH findings

Weekly verified intelligence & 1-command fixes:
  https://patchpulse-radar.netlify.app
"""

from __future__ import annotations

import argparse
import json
import os
import re
import sys
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Iterable

VERSION = "1.1.0"
BASE_URL = "https://patchpulse-radar.netlify.app"

SKIP_DIRS = {
    ".git",
    ".hg",
    ".svn",
    "node_modules",
    ".venv",
    "venv",
    "__pycache__",
    ".next",
    ".nuxt",
    "dist",
    "build",
    "target",
    "vendor",
    ".pytest_cache",
    ".mypy_cache",
    ".ruff_cache",
    "coverage",
    ".turbo",
}

MAX_FILE_BYTES = 1_000_000


@dataclass
class Finding:
    rule_id: str
    severity: str
    deadline: str
    title: str
    file: str
    line: int
    snippet: str
    recommendation: str
    url: str


@dataclass
class PatternRule:
    rule_id: str
    severity: str
    deadline: str
    title: str
    regex: re.Pattern[str]
    file_globs: tuple[str, ...]
    recommendation: str
    alert_slug: str


RULES: list[PatternRule] = [
    PatternRule(
        rule_id="pypi-agent-framework-supply-chain-hijack",
        severity="CRITICAL",
        deadline="Immediate",
        title="Microsoft PyPI 'agent-framework' supply-chain hijack window (v1.26.1 / v1.26.2 .pth stealer)",
        regex=re.compile(r"\bagent[-_]framework\b", re.IGNORECASE),
        file_globs=("requirements*.txt", "pyproject.toml", "poetry.lock", "uv.lock", "Pipfile*", "Dockerfile*", "docker-compose*.yml", "docker-compose*.yaml"),
        recommendation="Verify installed version is NOT 1.26.1 or 1.26.2, purge CI pip/uv caches, and rotate Azure/GitHub/Hugging Face tokens if exposed.",
        alert_slug="pypi-agent-framework-supply-chain-hijack",
    ),
    PatternRule(
        rule_id="cisa-kev-litellm-cve-2026-40217",
        severity="CRITICAL",
        deadline="Immediate",
        title="BerriAI LiteLLM CISA KEV sandbox escape & root RCE (CVE-2026-40217)",
        regex=re.compile(r"\blitellm\b|/guardrails/test_custom_code", re.IGNORECASE),
        file_globs=("requirements*.txt", "pyproject.toml", "poetry.lock", "uv.lock", "Dockerfile*", "docker-compose*.yml", "docker-compose*.yaml", "*.py", "*.yml", "*.yaml"),
        recommendation="Upgrade litellm to >= 1.83.11, run containers as non-root, and block public access to /guardrails/test_custom_code.",
        alert_slug="cisa-kev-litellm-cve-2026-40217",
    ),
    PatternRule(
        rule_id="cisa-kev-monai-cve-2026-133968",
        severity="CRITICAL",
        deadline="Immediate",
        title="Project MONAI Label CISA KEV unauthenticated path traversal / RCE (CVE-2026-133968)",
        regex=re.compile(r"\bmonailabel\b|\bmonai\b", re.IGNORECASE),
        file_globs=("requirements*.txt", "pyproject.toml", "Dockerfile*", "docker-compose*.yml", "docker-compose*.yaml"),
        recommendation="Isolate MONAI Label from public ingress immediately and apply vendor patches per CISA KEV.",
        alert_slug="cisa-kev-monai-cve-2026-133968",
    ),
    PatternRule(
        rule_id="nginx-http2-rce-cve-2026-123007-nginx2root",
        severity="CRITICAL",
        deadline="Immediate",
        title="NGINX HTTP/2 RCE ('nginx2root', CVE-2026-123007) container-to-host escape risk",
        regex=re.compile(r"(?:FROM\s+nginx|image:\s*['\"]?nginx)", re.IGNORECASE),
        file_globs=("Dockerfile*", "docker-compose*.yml", "docker-compose*.yaml", "*.dockerfile", "*.yaml", "*.yml"),
        recommendation="Rebuild with patched F5 NGINX builds immediately and enforce non-root container privileges / drop Linux capabilities.",
        alert_slug="nginx-http2-rce-cve-2026-123007-nginx2root",
    ),
    PatternRule(
        rule_id="postgresql-cve-2026-6460-and-pg14-eol",
        severity="CRITICAL",
        deadline="Immediate",
        title="PostgreSQL 14 End-of-Life image / CVE-2026-6460 patch check",
        regex=re.compile(r"(?:postgres(?:ql)?[:/@\-]14\b|FROM\s+postgres:14)", re.IGNORECASE),
        file_globs=("Dockerfile*", "docker-compose*.yml", "docker-compose*.yaml", "*.tf", "*.yml", "*.yaml", ".env*"),
        recommendation="PostgreSQL 14 hit community EOL (14.25 final). Plan upgrade to PG 17/18/19 and apply minor security releases (18.7/17.12/16.16/15.20).",
        alert_slug="postgresql-cve-2026-6460-and-pg14-eol",
    ),
    PatternRule(
        rule_id="nodejs-http2-tls-security-release",
        severity="CRITICAL",
        deadline="Immediate",
        title="Node.js Docker base image audit for HTTP/2 UAF & TLS heap leak patches",
        regex=re.compile(r"FROM\s+node:(?:22|24|26)(?:\.[0-9]+(?:\.[0-9]+)?)?(?:-[a-z0-9._-]+)?\b", re.IGNORECASE),
        file_globs=("Dockerfile*", "*.dockerfile", ".github/workflows/*.yml", ".github/workflows/*.yaml"),
        recommendation="Pin Node.js base images to >= 22.23.5, >= 24.22.3, or >= 26.13.1 and restart long-running server processes.",
        alert_slug="nodejs-http2-tls-security-release",
    ),
    PatternRule(
        rule_id="cloudflare-pages-action-cve-2026-11325",
        severity="HIGH",
        deadline="Immediate",
        title="Deprecated cloudflare/pages-action CI RCE & secret exposure (CVE-2026-11325)",
        regex=re.compile(r"cloudflare/pages-action", re.IGNORECASE),
        file_globs=("*.yml", "*.yaml"),
        recommendation="Replace cloudflare/pages-action with cloudflare/wrangler-action in GitHub Actions workflows immediately.",
        alert_slug="cloudflare-pages-action-cve-2026-11325",
    ),
    PatternRule(
        rule_id="nextjs-ghsa-mfr8-8qww-v76h-cache-disclosure",
        severity="HIGH",
        deadline="Immediate",
        title="Next.js unstable_cache + 'use cache' cross-tenant cache disclosure check (GHSA-mfr8-8qww-v76h)",
        regex=re.compile(r"\bunstable_cache\b|['\"]use cache['\"]"),
        file_globs=("*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs"),
        recommendation="Upgrade Next.js to >= 16.4.5 (Active LTS) or >= 15.5.29 (Maintenance LTS) and audit multi-tenant cache boundaries.",
        alert_slug="nextjs-ghsa-mfr8-8qww-v76h-cache-disclosure",
    ),
    PatternRule(
        rule_id="ai-deadline-nov30-dec1-model-sunsets",
        severity="FINOPS",
        deadline="2026-11-30",
        title="Anthropic Claude 4.5 / Opus 4.8 Fast sunset (Nov 30) or Google Gemini 2.5 silent auto-routing (Dec 1)",
        regex=re.compile(r"\b(?:claude-sonnet-4-5|claude-opus-4-8|gemini-2\.5-pro|gemini-2\.5-flash)\b"),
        file_globs=("*.py", "*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.go", "*.rs", "*.java", "*.rb", "*.json", "*.yaml", "*.yml", "*.toml", ".env*"),
        recommendation="Pin explicit Claude 5.5 or Gemini 4 / 3.8 model IDs before Nov 30 / Dec 1 to prevent hard failures or silent billing/tool-calling shifts.",
        alert_slug="ai-deadline-nov30-dec1-model-sunsets",
    ),
    PatternRule(
        rule_id="gemini-4-argon-dec1-price-doubling-and-gpt62-launch",
        severity="FINOPS",
        deadline="2026-12-01",
        title="Google Gemini 4 Carbon & Argon pay-as-you-go rates double Dec 1 ($2/$10 -> $4/$20)",
        regex=re.compile(r"\bgemini-4[-_.a-z0-9]*(?:argon|carbon)\b", re.IGNORECASE),
        file_globs=("*.py", "*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.go", "*.json", "*.yaml", "*.yml", "*.toml", ".env*"),
        recommendation="Recalculate December Gemini 4 Carbon/Argon token & cache budgets before Dec 1; benchmark GPT-6.2 Sol ($2/$10) where suitable.",
        alert_slug="gemini-4-argon-dec1-price-doubling-and-gpt62-launch",
    ),
    PatternRule(
        rule_id="openai-hosted-evals-and-dec1-image-model-retirements",
        severity="FINOPS",
        deadline="2026-12-01",
        title="OpenAI legacy image model retirements Dec 1 (gpt-image-1-mini / gpt-image-1.5 / chatgpt-image-latest)",
        regex=re.compile(r"\b(?:gpt-image-1-mini|gpt-image-1\.5|chatgpt-image-latest)\b"),
        file_globs=("*.py", "*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.go", "*.json", "*.yaml", "*.yml", "*.toml", ".env*"),
        recommendation="Migrate deprecated OpenAI image model IDs before Dec 1 and export any OpenAI Hosted Evals workflows retiring Nov 30.",
        alert_slug="openai-hosted-evals-and-dec1-image-model-retirements",
    ),
    PatternRule(
        rule_id="cisa-kev-drupal-core-cve-2026-136716",
        severity="CRITICAL",
        deadline="Immediate",
        title="CISA KEV: Drupal Core remote site takeover via installation failure state (CVE-2026-136716)",
        regex=re.compile(r"drupal/core", re.IGNORECASE),
        file_globs=("composer.json", "composer.lock", "Dockerfile*"),
        recommendation="Apply the latest Drupal Core security patch immediately and block external web ingress to install.php.",
        alert_slug="cisa-kev-drupal-core-cve-2026-136716",
    ),
    PatternRule(
        rule_id="cloudflare-waf-phpaftershell-ruby2shell-rce",
        severity="CRITICAL",
        deadline="Immediate",
        title="PHP 'phpAfterShell' (CVE-2026-126714) & Ruby 'ruby2shell' (CVE-2026-132825) container runtime audit",
        regex=re.compile(r"(?:FROM\s+(?:php|ruby):|image:\s*['\"]?(?:php|ruby):)", re.IGNORECASE),
        file_globs=("Dockerfile*", "*.dockerfile", "docker-compose*.yml", "docker-compose*.yaml"),
        recommendation="Patch PHP and Ruby runtime base images immediately rather than relying solely on edge WAF mitigations.",
        alert_slug="cloudflare-waf-phpaftershell-ruby2shell-rce",
    ),
    PatternRule(
        rule_id="openai-gpt5-o3-dec11-shutdown",
        severity="FINOPS",
        deadline="2026-12-11",
        title="OpenAI hard shutdown of GPT-5, GPT-5 mini, o3 & o3-pro (Dec 11; GPT-4o/4.1 Jan 14)",
        regex=re.compile(r"(?:\bgpt-5(?:-mini)?\b|\bo3-pro\b|['\"]o3['\"]|\bgpt-4o\b|\bgpt-4\.1\b)"),
        file_globs=("*.py", "*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.go", "*.json", "*.yaml", "*.yml", "*.toml", ".env*"),
        recommendation="Migrate legacy GPT-5 / o3 / GPT-4o model strings to GPT-6.2 Astra or GPT-6.2 Sol on the Responses API ahead of Dec 11.",
        alert_slug="openai-gpt5-o3-dec11-shutdown",
    ),
]


def parse_semver(raw: str) -> tuple[int, int, int] | None:
    m = re.search(r"(\d+)\.(\d+)\.(\d+)", raw)
    if not m:
        return None
    return int(m.group(1)), int(m.group(2)), int(m.group(3))


def match_any_glob(rel_path: Path, patterns: tuple[str, ...]) -> bool:
    name = rel_path.name
    posix = rel_path.as_posix()
    for pat in patterns:
        if "/" in pat:
            if rel_path.match(pat) or Path(posix).match(pat):
                return True
        else:
            if Path(name).match(pat):
                return True
    return False


def iter_files(root: Path) -> Iterable[Path]:
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".git")]
        base = Path(dirpath)
        for fn in filenames:
            p = base / fn
            try:
                if p.is_symlink() or not p.is_file():
                    continue
                if p.stat().st_size > MAX_FILE_BYTES:
                    continue
            except OSError:
                continue
            yield p


def check_package_json(path: Path, rel: str) -> list[Finding]:
    out: list[Finding] = []
    try:
        data = json.loads(path.read_text(encoding="utf-8", errors="ignore"))
    except Exception:
        return out
    deps: dict[str, str] = {}
    for key in ("dependencies", "devDependencies", "optionalDependencies"):
        section = data.get(key)
        if isinstance(section, dict):
            for k, v in section.items():
                if isinstance(v, str):
                    deps[k] = v

    next_ver_raw = deps.get("next")
    if next_ver_raw:
        ver = parse_semver(next_ver_raw)
        if ver and ((ver[0] == 15 and ver < (15, 5, 29)) or (ver[0] == 16 and ver < (16, 4, 5))):
            out.append(
                Finding(
                    rule_id="nextjs-ghsa-mfr8-8qww-v76h-cache-disclosure",
                    severity="HIGH",
                    deadline="Immediate",
                    title=f"Vulnerable Next.js version ({next_ver_raw}) affected by GHSA-mfr8-8qww-v76h cache disclosure",
                    file=rel,
                    line=1,
                    snippet=f'"next": "{next_ver_raw}"',
                    recommendation="Upgrade Next.js to >= 16.4.5 or >= 15.5.29 immediately.",
                    url=f"{BASE_URL}/alerts/nextjs-ghsa-mfr8-8qww-v76h-cache-disclosure.html",
                )
            )
    return out


def is_patched_node_tag(snippet: str) -> bool:
    ver = parse_semver(snippet)
    if not ver:
        return False
    major = ver[0]
    if major == 22 and ver >= (22, 23, 5):
        return True
    if major == 24 and ver >= (24, 22, 3):
        return True
    if major == 26 and ver >= (26, 13, 1):
        return True
    return False


def scan_repo(root: Path) -> tuple[int, list[Finding]]:
    findings: list[Finding] = []
    seen_dedupe: set[tuple[str, str, int]] = set()
    files_scanned = 0

    for fpath in iter_files(root):
        rel_path = fpath.relative_to(root)
        rel_str = rel_path.as_posix()

        # Skip this scanner script itself if placed inside the repo
        if rel_path.name in {"scan.py", "patchpulse-scan.py", "patchpulse_scan.py"}:
            continue

        if rel_path.name == "package.json":
            for f in check_package_json(fpath, rel_str):
                key = (f.rule_id, f.file, f.line)
                if key not in seen_dedupe:
                    seen_dedupe.add(key)
                    findings.append(f)

        applicable = [r for r in RULES if match_any_glob(rel_path, r.file_globs)]
        if not applicable:
            continue

        files_scanned += 1
        try:
            raw_bytes = fpath.read_bytes()
            if b"\x00" in raw_bytes[:4096]:
                continue
            lines = raw_bytes.decode("utf-8", errors="ignore").splitlines()
        except OSError:
            continue

        for lineno, line_text in enumerate(lines, start=1):
            stripped = line_text.strip()
            if not stripped:
                continue
            for rule in applicable:
                if rule.regex.search(line_text):
                    if rule.rule_id == "nodejs-http2-tls-security-release" and is_patched_node_tag(line_text):
                        continue
                    key = (rule.rule_id, rel_str, lineno)
                    if key in seen_dedupe:
                        continue
                    seen_dedupe.add(key)
                    findings.append(
                        Finding(
                            rule_id=rule.rule_id,
                            severity=rule.severity,
                            deadline=rule.deadline,
                            title=rule.title,
                            file=rel_str,
                            line=lineno,
                            snippet=stripped[:140],
                            recommendation=rule.recommendation,
                            url=f"{BASE_URL}/alerts/{rule.alert_slug}.html",
                        )
                    )

    sev_rank = {"CRITICAL": 0, "HIGH": 1, "FINOPS": 2, "MEDIUM": 3}
    findings.sort(key=lambda f: (sev_rank.get(f.severity, 9), f.file, f.line))
    return files_scanned, findings


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="patchpulse-scan",
        description="Offline zero-dependency scanner for active PatchPulse CVEs, breaking releases & AI API sunsets.",
    )
    parser.add_argument("path", nargs="?", default=".", help="Directory to scan (default: current directory)")
    parser.add_argument("--json", action="store_true", help="Output machine-readable JSON report")
    parser.add_argument("--strict", action="store_true", help="Exit with status 2 if CRITICAL or HIGH findings exist")
    parser.add_argument("--no-color", action="store_true", help="Disable ANSI colors")
    parser.add_argument("--version", action="version", version=f"patchpulse-scan {VERSION}")
    args = parser.parse_args()

    target = Path(args.path).resolve()
    if not target.exists() or not target.is_dir():
        print(f"Error: directory not found: {target}", file=sys.stderr)
        sys.exit(1)

    files_scanned, findings = scan_repo(target)

    if args.json:
        payload = {
            "tool": "patchpulse-scan",
            "version": VERSION,
            "target": str(target),
            "files_scanned": files_scanned,
            "finding_count": len(findings),
            "findings": [asdict(f) for f in findings],
            "radar_url": f"{BASE_URL}/deadlines.html",
        }
        print(json.dumps(payload, indent=2))
    else:
        use_color = sys.stdout.isatty() and not args.no_color and os.environ.get("NO_COLOR") is None
        c_reset = "\033[0m" if use_color else ""
        c_bold = "\033[1m" if use_color else ""
        c_dim = "\033[2m" if use_color else ""
        c_sev = {
            "CRITICAL": "\033[91m" if use_color else "",
            "HIGH": "\033[93m" if use_color else "",
            "FINOPS": "\033[95m" if use_color else "",
            "MEDIUM": "\033[96m" if use_color else "",
        }
        c_ok = "\033[92m" if use_color else ""

        print(f"{c_bold}PatchPulse Local Repo Scanner v{VERSION}{c_reset}  {c_dim}(100% offline, 0 telemetry){c_reset}")
        print(f"Target: {target}  |  Files scanned: {files_scanned}  |  Rules: {len(RULES) + 1}")
        print("-" * 74)

        if not findings:
            print(f"{c_ok}CLEAN: Zero matches against current PatchPulse critical CVEs & AI API sunsets.{c_reset}")
        else:
            for f in findings:
                sc = c_sev.get(f.severity, "")
                print(f"{sc}[{f.severity}]{c_reset} {c_bold}{f.title}{c_reset}")
                print(f"  Location: {f.file}:{f.line}  |  Deadline: {f.deadline}")
                print(f"  Match:    {c_dim}{f.snippet}{c_reset}")
                print(f"  Action:   {f.recommendation}")
                print(f"  Advisory: {f.url}\n")

        print("-" * 74)
        print(f"Live countdowns & Monday radar: {BASE_URL}/deadlines.html")
        print(f"Unlocked Pro brief sample:      {BASE_URL}/sample-pro.html")

    if args.strict and any(f.severity in {"CRITICAL", "HIGH"} for f in findings):
        sys.exit(2)


if __name__ == "__main__":
    main()
