#!/usr/bin/env python3
"""Pre-tool hook for Claude Code, Codex, and Gemini CLI.

Reads the tool-call JSON on stdin, asks aiproxy-supervisor, and denies the
call when the supervisor denies it. Tools with no file, command, or URL are
left alone.
"""
from __future__ import annotations

import json
import os
import re
import shlex
import subprocess
import sys
from pathlib import Path
from urllib.parse import urlparse

WRITE_TOOLS = {
    "write",
    "edit",
    "multiedit",
    "notebookedit",
    "write_file",
    "replace",
    "apply_patch",
    "search_replace",
}
PATH_KEYS = ("file_path", "path", "target_file", "notebook_path", "file")
# Search tools that take a root directory. With no root, they search the
# working directory, so that directory is what must be checked.
SEARCH_TOOLS = {"grep", "glob"}
# Bare program names resolve only inside these fixed system directories, never
# the agent's PATH, so a project cannot shadow a binary.
TRUSTED_DIRS = ("/usr/bin", "/bin", "/usr/sbin", "/sbin")


def home() -> Path:
    return Path(os.environ.get("HOME", str(Path.home())))


def supervisor() -> Path | None:
    env = os.environ.get("AIPROXY_SUPERVISOR")
    candidates = []
    if env:
        candidates.append(Path(env))
    candidates.extend(
        [
            home() / ".local/aiproxy/bin/aiproxy-supervisor",
            Path(__file__).resolve().parent / "aiproxy-supervisor",
        ]
    )
    for c in candidates:
        for path in (c, c.with_suffix(".exe") if c.suffix == "" else c):
            if path.is_file() and (os.access(path, os.X_OK) or os.name == "nt"):
                return path
    from shutil import which

    found = which("aiproxy-supervisor")
    return Path(found) if found else None


def policy_and_keys(root_hint: Path | None) -> tuple[Path, Path]:
    policy = os.environ.get("AIPROXY_POLICY")
    keys = os.environ.get("AIPROXY_KEYS")
    roots = []
    if root_hint:
        roots.append(root_hint)
    roots.append(home() / ".local/aiproxy")
    roots.append(Path.cwd())
    pol = Path(policy) if policy else None
    key = Path(keys) if keys else None
    if pol is None:
        for r in roots:
            cand = r / "policy/max-boundary.yaml"
            if cand.is_file():
                pol = cand
                break
    if pol is None:
        pol = home() / ".local/aiproxy/policy/max-boundary.yaml"
    if key is None:
        for r in roots:
            cand = r / "var/keys"
            if cand.is_dir():
                key = cand
                break
        if key is None:
            key = home() / ".local/aiproxy/var/keys"
    return pol, key


def ensure_keys(binary: Path, keys: Path) -> None:
    if (keys / "ed25519.sk").is_file() or (keys / "mode").is_file():
        return
    keys.mkdir(parents=True, exist_ok=True)
    subprocess.run([str(binary), "--keys", str(keys), "init-keys"], check=False, capture_output=True, text=True)


def run_check(binary: Path, policy: Path, keys: Path, args: list[str]) -> tuple[str, str]:
    proc = subprocess.run(
        [str(binary), "--policy", str(policy), "--keys", str(keys), *args],
        capture_output=True,
        text=True,
        timeout=20,
    )
    raw = (proc.stdout or "") + (proc.stderr or "")
    i = raw.find("{")
    if i < 0:
        return "deny", "supervisor returned no decision"
    try:
        doc = json.loads(raw[i:])
    except json.JSONDecodeError:
        return "deny", "supervisor returned unreadable output"
    decision = doc.get("decision") or "deny"
    reason = doc.get("reason") or doc.get("detail") or decision
    return decision, str(reason)


def resolve_program(name: str) -> str:
    """Return the absolute path of a bare program name in a trusted directory.

    Falls back to the bare name, which the checker refuses. Windows keeps the
    name as typed.
    """
    if not name or "/" in name or os.name == "nt":
        return name
    for directory in TRUSTED_DIRS:
        candidate = Path(directory) / name
        if candidate.is_file() and os.access(candidate, os.X_OK):
            return str(candidate)
    return name


def first_binary(command: str) -> str:
    try:
        parts = shlex.split(command)
    except ValueError:
        parts = command.split()
    if not parts:
        return ""
    if parts[0] in {"sudo", "command", "exec", "time"} and len(parts) > 1:
        return parts[1]
    return parts[0]


# These programs can open a file without the path appearing as text.
# The checker allows the program name. The hook still refuses the shell
# command, because it cannot see the file the program will open.
OPAQUE_PROGRAMS = {
    "python",
    "python3",
    "python.exe",
    "perl",
    "ruby",
    "node",
    "nodejs",
    "bash",
    "sh",
    "zsh",
    "pwsh",
    "powershell",
    "powershell.exe",
    "cmd",
    "cmd.exe",
}


def command_hides_paths(command: str) -> bool:
    try:
        tokens = shlex.split(command)
    except ValueError:
        tokens = command.split()
    names = {Path(t).name.lower() for t in tokens}
    if names & OPAQUE_PROGRAMS:
        return True
    # "-c" and "-e" only mean "run this code" for an interpreter. On their own
    # (grep -c) they are ordinary flags.
    return False


# git subcommands that only read the repository. Anything else is refused,
# including every network command (clone, fetch, pull, push, remote, ls-remote).
GIT_READ_ONLY = {"status", "diff", "log", "show", "rev-parse", "blame", "ls-files", "describe", "shortlog"}
GIT_REFUSED_FLAGS = {"-c", "--git-dir", "--work-tree", "--exec-path", "--ext-diff", "--textconv", "--output", "--config-env"}


def readonly_plan(name: str, tokens: list[str], cwd: str) -> list[tuple[str, list[str]]]:
    """Check a read-only program's arguments. Raise Deny for anything unexpected."""
    spec = READONLY_SPEC[name]
    paths: list[str] = []
    positional: list[str] = []
    explicit_pattern = False
    recursive = False
    i = 1
    end_of_options = False
    while i < len(tokens):
        tok = tokens[i]
        i += 1
        if end_of_options or tok == "-" or not tok.startswith("-"):
            positional.append(tok)
            continue
        if tok == "--":
            end_of_options = True
            continue
        if tok.startswith("--"):
            raise Deny(f"{name} option {tok.split('=')[0]} is not allowed by aiproxy")
        if name in ("head", "tail") and re.fullmatch(r"-\d+", tok):  # head -20 means head -n 20
            continue
        j = 1
        while j < len(tok):
            ch = tok[j]
            if ch in spec["value"]:
                rest = tok[j + 1:]
                if rest:
                    value = rest
                else:
                    if i >= len(tokens):
                        raise Deny(f"{name} -{ch} has no value")
                    value = tokens[i]
                    i += 1
                if name == "grep" and ch in ("e", "f"):
                    explicit_pattern = True
                if name == "grep" and ch == "f":
                    paths.append(value)
                break
            if ch in spec["bool"]:
                if ch in ("r", "R"):
                    recursive = True
                j += 1
                continue
            raise Deny(f"{name} -{ch} is not allowed by aiproxy")
    if name == "grep" and not explicit_pattern and positional:
        positional = positional[1:]  # the first word is the search pattern
    paths.extend(positional)
    checks: list[tuple[str, list[str]]] = []
    for raw in paths:
        p = str(home() / raw[1:].lstrip("/")) if raw.startswith("~") else raw
        if not os.path.isabs(p):
            p = os.path.join(cwd, p)
        checks.append(("fs", ["check-fs", os.path.normpath(p)]))
    if not paths and (name == "ls" or (name == "grep" and recursive)):
        checks.append(("fs", ["check-fs", cwd]))
    return checks


def git_plan(tokens: list[str]) -> list[tuple[str, list[str]]]:
    """Allow only read-only git subcommands. Raise Deny otherwise."""
    checks: list[tuple[str, list[str]]] = []
    sub = None
    i = 1
    while i < len(tokens):
        tok = tokens[i]
        i += 1
        if tok in GIT_REFUSED_FLAGS or tok.startswith("--output=") or tok.startswith("--exec-path="):
            raise Deny(f"git option {tok.split('=')[0]} is not allowed by aiproxy")
        if tok == "-C":
            if i >= len(tokens):
                raise Deny("git -C has no directory")
            checks.append(("fs", ["check-fs", tokens[i]]))
            i += 1
            continue
        if tok.startswith("-"):
            continue
        sub = tok
        break
    if sub is None:
        raise Deny("git needs a read-only subcommand")
    if sub not in GIT_READ_ONLY:
        raise Deny(f"git {sub} is not allowed by aiproxy; only read-only commands are")
    # Options after the subcommand can also write or run code, so check them too.
    for tok in tokens[i:]:
        if any(tok == f or tok.startswith(f + "=") for f in GIT_REFUSED_FLAGS):
            raise Deny(f"git option {tok.split('=')[0]} is not allowed by aiproxy")
    return checks


# Read-only programs the policy may allow. Each flag is either boolean or takes
# a value. Anything else is refused, and every path argument is checked.
READONLY_SPEC = {
    "cat": {"bool": set("nbsvAeEtTu"), "value": set()},
    "ls": {"bool": set("alhR1FdtrSs"), "value": set()},
    "head": {"bool": set("qv"), "value": set("nc")},
    "tail": {"bool": set("qv"), "value": set("nc")},
    "wc": {"bool": set("lwcmL"), "value": set()},
    "grep": {"bool": set("ivnrRlcEFwxHhoqsz"), "value": set("eABCfm")},
}
SHELL_OPERATORS = re.compile(r"[;&|`\n<>]|\$\(")


class Deny(Exception):
    """Raised by a parser when a request must be refused."""


# curl flags we understand. Anything else is refused, so an unknown option can
# never hide a destination, a body, or a file.
CURL_BOOL_SHORT = set("sSvifkIN")  # silent, show-error, verbose, include, fail, insecure, head, no-buffer
CURL_BOOL_LONG = {"--silent", "--show-error", "--verbose", "--include", "--fail", "--head", "--no-buffer", "--compressed", "--globoff", "--http1.1", "--http2", "--tlsv1.2"}
CURL_VALUE_SHORT = set("XHodFTuAebcmwroDCzE")  # request, header, data, form, upload, user, agent, referer, cookie, cookie-jar, max-time, write-out, range, output, dump-header, continue, time-cond, cert
CURL_VALUE_LONG = {"--request", "--header", "--data", "--data-raw", "--data-binary", "--data-urlencode", "--data-ascii", "--json",
                   "--form", "--form-string", "--upload-file", "--user", "--user-agent", "--referer", "--cookie", "--cookie-jar",
                   "--max-time", "--write-out", "--range", "--output", "--dump-header", "--cert", "--cacert", "--key"}
CURL_REFUSED_LONG = {"--config", "--location", "--location-trusted", "--remote-name", "--remote-name-all", "--proxy", "--preproxy",
                     "--socks4", "--socks5", "--socks5-hostname", "--resolve", "--connect-to", "--next", "--get", "--unix-socket",
                     "--netrc", "--netrc-optional", "--url-query", "--create-dirs", "--ftp-port", "--interface"}
CURL_REFUSED_SHORT = set("KLOxGP:")


def curl_plan(tokens: list[str], body: str) -> list[tuple[str, list[str]]]:
    """Turn curl arguments into policy checks, or raise Deny."""
    method = None
    has_body = False
    urls: list[str] = []
    checks: list[tuple[str, list[str]]] = []
    i = 0
    while i < len(tokens):
        tok = tokens[i]
        i += 1
        if tok == "--":
            urls.extend(tokens[i:])
            break
        if tok.startswith("--"):
            name, eq, value = tok.partition("=")
            if name in CURL_REFUSED_LONG:
                raise Deny(f"curl option {name} is not allowed by aiproxy")
            if name in CURL_BOOL_LONG and not eq:
                continue
            if name in CURL_VALUE_LONG:
                if not eq:
                    if i >= len(tokens):
                        raise Deny(f"curl option {name} has no value")
                    value = tokens[i]
                    i += 1
                v_method, v_body, v_checks = _curl_value(name, value)
                method = v_method or method
                has_body = has_body or v_body
                checks.extend(v_checks)
                continue
            raise Deny(f"curl option {name} is not recognized by aiproxy")
        if tok.startswith("-") and len(tok) > 1:
            j = 1
            while j < len(tok):
                ch = tok[j]
                if ch in CURL_REFUSED_SHORT:
                    raise Deny(f"curl option -{ch} is not allowed by aiproxy")
                if ch in CURL_BOOL_SHORT:
                    j += 1
                    continue
                if ch in CURL_VALUE_SHORT:
                    rest = tok[j + 1:]
                    if rest:
                        value = rest
                    else:
                        if i >= len(tokens):
                            raise Deny(f"curl option -{ch} has no value")
                        value = tokens[i]
                        i += 1
                    v_method, v_body, v_checks = _curl_value("-" + ch, value)
                    method = v_method or method
                    has_body = has_body or v_body
                    checks.extend(v_checks)
                    break
                raise Deny(f"curl option -{ch} is not recognized by aiproxy")
            continue
        urls.append(tok)
    if not urls:
        raise Deny("curl has no URL that aiproxy can check")
    if method is None:
        method = "POST" if has_body else "GET"
    for url in urls:
        parsed = urlparse(url)
        if parsed.scheme not in ("http", "https") or not parsed.hostname:
            raise Deny("curl URL must be an explicit http or https address")
        port = parsed.port or (443 if parsed.scheme == "https" else 80)
        checks.append(("net", ["check-net", parsed.hostname, method.upper(), "--port", str(port), "--path", parsed.path or "/", "--body", body[:4000]]))
    return checks


def _curl_value(flag: str, value: str) -> tuple[str | None, bool, list[tuple[str, list[str]]]]:
    """Return (method override, sends a body, file checks) for one curl option."""
    if flag in ("-X", "--request"):
        return value.upper(), False, []
    if flag in ("-d", "--data", "--data-raw", "--data-binary", "--data-urlencode", "--data-ascii", "--json"):
        checks = []
        if "@" in value:
            file_part = value.split("@", 1)[1]
            checks.append(("fs", ["check-fs", file_part]))
        return None, True, checks
    if flag in ("-F", "--form", "--form-string"):
        checks = []
        for marker in ("@", "<"):
            if marker in value:
                checks.append(("fs", ["check-fs", value.split(marker, 1)[1].split(";")[0]]))
        return "POST", True, checks
    if flag in ("-T", "--upload-file"):
        return "PUT", True, [("fs", ["check-fs", value])]
    if flag in ("-o", "--output"):
        return None, False, [("fs", ["check-fs", value, "--write"])]
    if flag in ("-c", "--cookie-jar", "-D", "--dump-header"):
        return None, False, [("fs", ["check-fs", value, "--write"])]
    if flag in ("-E", "--cert", "--cacert", "--key"):
        return None, False, [("fs", ["check-fs", value])]
    return None, False, []


def paths_in(command: str) -> list[str]:
    found = re.findall(r"(?:(?:~|/|\.\.?/)[^\s'\"|;<>]+)", command)
    out = []
    for p in found:
        if p.startswith("~"):
            p = str(home() / p[1:].lstrip("/"))
        out.append(p)
    return out


def checks_for(event: dict) -> list[tuple[str, list[str]]]:
    tool = str(event.get("tool_name") or event.get("toolName") or "")
    inp = event.get("tool_input") or event.get("toolInput") or {}
    if not isinstance(inp, dict):
        inp = {}
    write = tool.lower() in WRITE_TOOLS or any(w in tool.lower() for w in ("write", "edit", "patch", "replace"))
    checks: list[tuple[str, list[str]]] = []
    has_root = False
    for key in PATH_KEYS:
        val = inp.get(key)
        if isinstance(val, str) and val.strip():
            has_root = True
            checks.append(("fs", ["check-fs", val, *(["--write"] if write else [])]))
    base = event.get("cwd") if isinstance(event.get("cwd"), str) and event.get("cwd") else str(Path.cwd())
    if tool.lower() == "read":
        for key in PATH_KEYS:
            val = inp.get(key)
            if isinstance(val, str) and val.strip():
                checks.append(("content", [val]))
    if tool.lower() in SEARCH_TOOLS:
        pattern = inp.get("pattern")
        # Glob patterns are paths. Grep patterns are regular expressions, so they are not checked here.
        if tool.lower() == "glob" and isinstance(pattern, str) and pattern.strip():
            # Check the literal part of the glob, up to the first wildcard, against the real location.
            prefix = re.split(r"[*?\[{]", pattern, maxsplit=1)[0]
            if prefix.startswith("~"):
                prefix = str(home() / prefix[1:].lstrip("/"))
            elif not prefix.startswith("/"):
                prefix = os.path.join(base, prefix)
            checks.append(("fs", ["check-fs", os.path.normpath(prefix)]))
        if not has_root:
            checks.append(("fs", ["check-fs", base]))
    command = inp.get("command") or inp.get("cmd") or ""
    urls: list[str] = []
    if isinstance(command, str) and command.strip() and SHELL_OPERATORS.search(command):
        # One program per call. Pipes, chains, redirects and substitutions would run
        # programs the hook never checks.
        checks.append(("deny", ["compound or redirected shell commands are not allowed by aiproxy"]))
        command = ""
    if isinstance(command, str) and command.strip():
        binary = resolve_program(first_binary(command))
        if command_hides_paths(command):
            checks.append(("opaque", []))
        elif binary:
            checks.append(("exec", ["check-exec", binary]))
        if not command_hides_paths(command) and Path(binary).name in READONLY_SPEC:
            try:
                tokens = shlex.split(command)
                checks.extend(readonly_plan(Path(binary).name, tokens, base))
            except ValueError:
                checks.append(("deny", ["command could not be read"]))
            except Deny as exc:
                checks.append(("deny", [str(exc)]))
        elif not command_hides_paths(command) and Path(binary).name == "git":
            try:
                tokens = shlex.split(command)
                checks.extend(git_plan(tokens))
            except ValueError:
                checks.append(("deny", ["git command could not be read"]))
            except Deny as exc:
                checks.append(("deny", [str(exc)]))
            # Files named on the command line are still checked.
            for path in paths_in(re.sub(r"https?://[^\s'\"|;]+", " ", command)):
                checks.append(("fs", ["check-fs", path]))
        elif not command_hides_paths(command) and Path(binary).name == "curl":
            try:
                tokens = shlex.split(command)
            except ValueError:
                checks.append(("deny", ["curl command could not be read"]))
                tokens = []
            if tokens:
                try:
                    checks.extend(curl_plan(tokens[1:] if Path(tokens[0]).name == "curl" else tokens, command))
                except Deny as exc:
                    checks.append(("deny", [str(exc)]))
        elif not command_hides_paths(command):
            # URLs are checked as network endpoints below, not as file paths.
            path_text = re.sub(r"https?://[^\s'\"|;]+", " ", command)
            for path in paths_in(path_text):
                destructive = bool(re.search(r"\b(rm|mv|cp|tee|dd|truncate)\b", command)) or ">" in command
                checks.append(("fs", ["check-fs", path, *(["--write"] if destructive else [])]))
            urls = re.findall(r"https?://[^\s'\"|;]+", command)
    url = inp.get("url") or inp.get("uri") or ""
    if isinstance(url, str) and url:
        urls.append(url)
    for url in urls:
        parsed = urlparse(url)
        if not parsed.hostname:
            continue
        port = parsed.port or (443 if parsed.scheme == "https" else 80)
        method = str(inp.get("method") or "GET")
        body = command if isinstance(command, str) else ""
        checks.append(
            (
                "net",
                [
                    "check-net",
                    parsed.hostname,
                    method,
                    "--port",
                    str(port),
                    "--path",
                    parsed.path or "/",
                    "--body",
                    body[:4000],
                ],
            )
        )
    return checks


# Same secret patterns the supervisor's DLP uses on outbound bodies.
SECRET_PATTERNS = [
    ("aws_access_key", re.compile(r"AKIA[0-9A-Z]{16}")),
    ("generic_api_key", re.compile(r"(?i)(api[_-]?key|secret|token)\s*[:=]\s*['\"]?[A-Za-z0-9_\-]{16,}")),
    ("private_key_header", re.compile(r"-----BEGIN (RSA |OPENSSH |EC )?PRIVATE KEY-----")),
    ("github_pat", re.compile(r"ghp_[A-Za-z0-9]{20,}")),
]
READ_SCAN_LIMIT = 2 * 1024 * 1024


def secret_in_file(path: str) -> str | None:
    """Return the name of a secret pattern found in the file, or None.

    Files over the limit are not scanned here. Unreadable files are refused.
    """
    try:
        p = Path(path).expanduser()
        if not p.is_file():
            return None
        if p.stat().st_size > READ_SCAN_LIMIT:
            return None
        text = p.read_bytes().decode("utf-8", errors="ignore")
    except OSError:
        return "unreadable"
    for name, pattern in SECRET_PATTERNS:
        if pattern.search(text):
            return name
    return None


def emit(decision: str, reason: str) -> int:
    if decision != "deny":
        return 0
    payload = {
        "decision": "deny",
        "reason": reason,
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": reason,
        },
    }
    sys.stdout.write(json.dumps(payload) + "\n")
    sys.stderr.write(reason + "\n")
    return 2


def main() -> int:
    raw = sys.stdin.read()
    try:
        event = json.loads(raw) if raw.strip() else {}
    except json.JSONDecodeError:
        event = {}
    binary = supervisor()
    if binary is None:
        return emit("deny", "ai-proxy supervisor is not installed on this computer")
    policy, keys = policy_and_keys(binary.parent.parent if binary.parent.name == "bin" else None)
    if not policy.is_file():
        return emit("deny", f"ai-proxy policy is missing at {policy}")
    ensure_keys(binary, keys)
    for kind, args in checks_for(event):
        if kind == "opaque":
            return emit("deny", "ai-proxy denied a shell program that can open files without showing the path")
        if kind == "deny":
            return emit("deny", f"ai-proxy denied this action ({args[0]})")
        if kind == "content":
            found = secret_in_file(args[0])
            if found == "unreadable":
                return emit("deny", "ai-proxy could not read this file to check it")
            if found:
                return emit("deny", f"ai-proxy blocked this file: it contains a {found.replace('_', ' ')}")
            continue
        try:
            decision, reason = run_check(binary, policy, keys, args)
        except Exception as exc:
            return emit("deny", f"ai-proxy supervisor failed: {exc}")
        if decision == "deny":
            return emit("deny", f"ai-proxy denied this action ({reason})")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except BrokenPipeError:
        raise SystemExit(0)
    except Exception as exc:
        raise SystemExit(emit("deny", f"ai-proxy supervisor failed: {exc}"))
