#!/usr/bin/env bash
# LumozAI Pre-Install Supply-Chain Guard — Claude Code PreToolUse Hook
# Intercepts npm/pnpm/yarn/bun/pip/composer install commands BEFORE execution
# and blocks hallucinated, typosquatted, removed, or malicious packages (exit 2).
#
# Docs & MCP: https://lumozai.com/mcp
# Env:
#   LUMOZ_GUARD_API   Override endpoint (default: https://lumozai.com/api/security/package-trust)
#   LUMOZ_STRICT=1    Fail-closed on network timeout (default: 0 / fail-open)

set -u

command -v python3 >/dev/null 2>&1 || exit 0

exec python3 -c '
import json
import os
import re
import shlex
import sys
import urllib.error
import urllib.request

API_URL = os.environ.get("LUMOZ_GUARD_API", "https://lumozai.com/api/security/package-trust")
STRICT = os.environ.get("LUMOZ_STRICT", "0") == "1"

raw_stdin = sys.stdin.read().strip()
if not raw_stdin:
    sys.exit(0)

try:
    event = json.loads(raw_stdin)
except Exception:
    sys.exit(0)

tool_input = event.get("tool_input") or {}
cmd = tool_input.get("command") or ""
if not isinstance(cmd, str) or not cmd.strip():
    sys.exit(0)

# Quick pre-filter so non-install Bash commands exit in <1ms
if not re.search(r"\b(npm|pnpm|yarn|bun|pip|pip3|uv|composer)\b", cmd):
    sys.exit(0)

def split_npm_spec(spec: str):
    if spec.startswith("@"):
        idx = spec.find("@", 1)
        if idx != -1:
            return spec[:idx], spec[idx + 1:]
        return spec, None
    if "@" in spec:
        name, ver = spec.split("@", 1)
        return name, ver
    return spec, None

def split_pip_spec(spec: str):
    m = re.match(r"^([A-Za-z0-9_.-]+)(?:\[[^\]]+\])?(?:(==|>=|<=|~=|!=|>|<)([0-9][0-9A-Za-z._-]*))?$", spec)
    if not m:
        return None, None
    return m.group(1), m.group(3)

def split_composer_spec(spec: str):
    if "/" not in spec:
        return None, None
    if ":" in spec:
        name, ver = spec.split(":", 1)
        ver = ver.lstrip("^~>=<vV")
        return name, ver or None
    return spec, None

def is_local_or_url(token: str) -> bool:
    return (
        token.startswith((".", "/", "~", "http://", "https://", "git+", "file:", "github:"))
        or token.endswith((".tgz", ".tar.gz", ".whl", ".zip"))
    )

def extract_packages(command: str):
    found = []
    segments = re.split(r"\s*(?:&&|\|\||;)\s*", command)
    for seg in segments:
        try:
            tokens = shlex.split(seg)
        except Exception:
            tokens = seg.split()
        if len(tokens) < 2:
            continue

        while tokens and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", tokens[0]):
            tokens.pop(0)
        if len(tokens) < 2:
            continue

        exe = os.path.basename(tokens[0]).lower()
        sub = tokens[1].lower() if len(tokens) > 1 else ""
        eco = None
        arg_start = 2

        if exe == "npm" and sub in ("i", "install", "add"):
            eco = "npm"
        elif exe in ("pnpm", "yarn", "bun") and sub in ("add", "install", "i"):
            eco = "npm"
        elif exe in ("pip", "pip3") and sub == "install":
            eco = "pip"
        elif exe == "uv" and len(tokens) >= 3 and sub == "pip" and tokens[2].lower() == "install":
            eco = "pip"
            arg_start = 3
        elif exe == "composer" and sub == "require":
            eco = "composer"

        if not eco:
            continue

        skip_next = False
        for tok in tokens[arg_start:]:
            if skip_next:
                skip_next = False
                continue
            if tok in ("-r", "--requirement", "-c", "--constraint", "-e", "--editable", "--registry", "--prefix", "-C", "--dir", "--working-dir", "-d"):
                skip_next = True
                continue
            if tok.startswith("-") or is_local_or_url(tok):
                continue

            if eco == "npm":
                name, ver = split_npm_spec(tok)
                if name and not name.startswith("-"):
                    if ver in ("latest", "next", "beta", "canary", "*"):
                        ver = None
                    found.append({"ecosystem": "npm", "name": name, "version": ver})
            elif eco == "pip":
                name, ver = split_pip_spec(tok)
                if name:
                    found.append({"ecosystem": "pip", "name": name, "version": ver})
            elif eco == "composer":
                name, ver = split_composer_spec(tok)
                if name:
                    found.append({"ecosystem": "composer", "name": name, "version": ver})
    return found

packages = extract_packages(cmd)
if not packages:
    sys.exit(0)

payload = json.dumps({"packages": packages}).encode("utf-8")
req = urllib.request.Request(
    API_URL,
    data=payload,
    headers={
        "Content-Type": "application/json",
        "Accept": "application/json",
        "User-Agent": "LumozAI-PreInstallGuard/1.0",
    },
    method="POST",
)

try:
    with urllib.request.urlopen(req, timeout=5) as resp:
        data = json.loads(resp.read().decode("utf-8"))
except Exception as e:
    if STRICT:
        sys.stderr.write(f"[LumozAI Guard] Blocked (LUMOZ_STRICT=1): could not reach {API_URL} ({e})\n")
        sys.exit(2)
    sys.exit(0)

blocked_items = [r for r in (data.get("results") or []) if r.get("blocked")]
if not blocked_items:
    sys.exit(0)

lines = [
    "",
    "🚨 [LumozAI Pre-Install Guard] BLOCKED package installation!",
    "",
]
for item in blocked_items:
    pkg = item.get("package", "unknown")
    eco = item.get("ecosystem", "")
    verdict = item.get("verdict", "DO_NOT_INSTALL")
    score = item.get("risk_score", 100)
    lines.append(f"  • {pkg} ({eco}) — {verdict} (Risk: {score}/100)")
    sug = item.get("typosquat_suggestion")
    if isinstance(sug, dict) and sug.get("target"):
        sug_target = sug.get("target")
        lines.append(f"    Did you mean: `{sug_target}`?")
    for sig in (item.get("signals") or [])[:4]:
        sev = str(sig.get("severity", "high")).upper()
        code = sig.get("code", "")
        detail = sig.get("detail", "")
        lines.append(f"    [{sev}] {code}: {detail}")

lines.append("")
lines.append("Fix the package name/version above and retry. Powered by LumozAI MCP (https://lumozai.com/mcp).")
sys.stderr.write("\n".join(lines) + "\n")
sys.exit(2)
'
