#!/usr/bin/env python3 """Install hook for Claude Code, Cursor, Windsurf and Antigravity: checks the packages of an install command with Vordix Security before it runs. malware -> denied. vulnerable or nonexistent -> you are asked, with the version to take instead (Windsurf cannot ask: a note). Anything else -> your normal permissions, with a note (Cursor: nothing, a note there needs a permission). Service not reachable within 3 seconds -> the same: this hook never stops your work for that, and it never approves a command. The command is only read, never run. Sent: ecosystem, package name and version, nothing else (no paths, URLs, options). Python 3 standard library only. It reads a command as a shell would in simple cases; it is a safety net, no sandbox. """ import json import os import re import shlex import sys import threading import urllib.request URL = os.environ.get("VORDIX_SECURITY_URL", "https://security.vordix.ai") + "/mcp" TIMEOUT = 3 MAX_PACKAGES = 20 PREFIXES = {"sudo", "command", "env", "time", "nohup", "exec", "then", "do", "else", "if", "!", "{"} PREFIX_VALUED = {"sudo": {"-u", "-g", "-C", "-D", "-h", "-p", "-r", "-t", "-T", "-U", "--user", "--group", "--chdir", "--host", "--prompt"}, "env": {"-u", "-C", "--unset", "--chdir"}} # the options of a prefix that take a value NPM = ("npm", {"install", "i", "add", "in", "update", "upgrade", "up", "dlx"}, "--prefix --workspace --registry --tag --cache --omit --include --loglevel --userconfig --filter --cwd -C -F") PIP = ("pypi", {"install", "add"}, "-r -c -i -f -t -e -G -E -p --requirement --requirements --constraint --index-url --extra-index-url --find-links --target --prefix --root " "--editable --python --group --extra --optional --package --index --default-index --source --tag --branch --rev --directory --project --script " "--timeout --retries --platform --python-version --implementation --abi --upgrade-strategy --progress-bar") MANAGERS = { "npm": NPM, "pnpm": NPM, "yarn": NPM, "bun": NPM, "pip": PIP, "uv": PIP, "poetry": PIP, "pipx": PIP, "cargo": ("crates.io", {"add", "install"}, "-F -p --features --package --git --path --branch --tag --rev --registry --target --rename --manifest-path --root"), "go": ("go", {"get", "install"}, "-C -mod -modfile -tags -ldflags"), "gem": ("rubygems", {"install", "i"}, "-s -i -n --source --install-dir --bindir --platform"), "composer": ("packagist", {"require"}, "-d --working-dir"), "dotnet": ("nuget", {"add"}, "-s -f --source --framework --package-directory"), } def commands(text): """The simple commands of a shell line, as lists of words.""" lexer = shlex.shlex(text.replace("\\\n", " "), posix=True, punctuation_chars=";&|()<>\n") lexer.whitespace, lexer.whitespace_split, lexer.commenters = " \t\r", True, "#" words, skip = [], False for token in [*lexer, ";"]: if token and set(token) <= set("<>&") and set(token) & set("<>"): skip = True # the next word is a file if words and words[-1].isdigit(): words.pop() # 2>&1 elif token and set(token) <= set(";&|()\n"): if words: yield words words, skip = [], False elif skip: skip = False else: words.append(token) def spec(eco, text): """(name, version or None) of one argument; None when it is a path, a URL or a repository.""" if re.search(r"://|^git[+@:]|^(?:file|link|github|gitlab|workspace|path):|^[./~]|\.(?:tgz|whl|gz|zip|gem)$|[$`\\]", text): return None if eco == "npm": text = re.sub(r"^.+@npm:", "", text) m = re.fullmatch(r"((?:@[\w.~-]+/)?[\w.~-]+)(?:@(.+))?", text) elif eco == "pypi": m = re.fullmatch(r"([\w.-]+)(?:\[[^\]]*\])?\s*(?:(?:===?|@)\s*([\w.!+^~<>=].*)|([<>=~!].*))?", text.split(";")[0].strip()) return m and (m[1], m[2] or m[3]) elif eco in ("packagist", "rubygems"): m = re.fullmatch(r"([\w./-]+)(?:[:=](.+))?", text) else: m = re.fullmatch(r"([\w./~-]+)(?:@(.+))?", text) if not m or eco == "go" and "." not in m[1].split("/")[0] or eco == "packagist" and "/" not in m[1]: return None version = m[2] and m[2].strip() if eco == "crates.io" and version and version[0].isdigit(): version = "^" + version # cargo add foo@1.2.3 is a requirement return m[1], None if version in ("latest", "*", "") else version def strip_prefixes(words): """The command after `sudo -u root`, `env -u X FOO=1`, `time` and the like.""" valued = set() while words and (os.path.basename(words[0]) in PREFIXES or re.match(r"[A-Za-z_]\w*=|-", words[0])): word = words[0] if os.path.basename(word) in PREFIXES: valued = PREFIX_VALUED.get(os.path.basename(word), set()) words = words[2:] if word in valued else words[1:] return words def packages(text, depth=0): """The packages an install command names: [{"ecosystem", "name", "version"?}].""" found = [] for words in commands(text): words = strip_prefixes(words) if not words: continue tool, args = os.path.basename(words[0]), words[1:] if tool in ("sh", "bash", "zsh") and depth < 2: script = next((b for a, b in zip(args, args[1:]) if re.fullmatch(r"-\w*c", a)), None) found += packages(script, depth + 1) if script else [] continue if re.fullmatch(r"python[\d.]*|py", tool) and "-m" in args[:-1] and args[args.index("-m") + 1] == "pip": tool, args = "pip", args[args.index("-m") + 2:] tool = "pip" if re.fullmatch(r"pip[\d.]*", tool) else tool if tool not in MANAGERS: continue eco, verbs, valued = MANAGERS[tool] valued, plain, version, i = set(valued.split()), [], None, 0 if tool in ("npm", "yarn"): valued.add("-w") # of pnpm it takes no value while i < len(args): arg = args[i] name, eq, value = arg.partition("=") if tool in ("gem", "dotnet", "cargo") and name in ("-v", "--version", "--vers"): version, i = (value, i) if eq else (next(iter(args[i + 1:]), None), i + 1) elif arg in valued: i += 1 elif arg and not arg.startswith("-"): plain.append(arg) i += 1 if plain[:1] in (["global"], ["workspace"], ["pip"], ["tool"], ["package"]): # yarn global add, uv pip install, dotnet package add plain = plain[2:] if plain[0] == "workspace" else plain[1:] if not plain or plain[0] not in verbs: continue plain = plain[1:] if tool == "dotnet" and "package" in plain: plain = plain[plain.index("package") + 1:] elif tool == "dotnet" and "package" not in args: continue # dotnet add reference if tool == "composer": # composer require vendor/name "^1.0" plain = [f"{a}:{b}" if b[:1] in "^~<>=*" or b[:1].isdigit() else a for a, b in zip(plain, [*plain[1:], "x"]) if "/" in a] for arg in plain: if got := spec(eco, arg): got_version = got[1] or version found.append({"ecosystem": eco, "name": got[0], **({"version": got_version} if got_version else {})}) return found def ask_service(wanted): body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "check_packages", "arguments": {"packages": wanted}}}) request = urllib.request.Request(URL, body.encode(), { "content-type": "application/json", "accept": "application/json, text/event-stream", "user-agent": "vordix-install-check"}) answer = {} def call(): try: with urllib.request.urlopen(request, timeout=TIMEOUT) as response: result = json.loads(response.read(200_000))["result"] text = result["content"][0]["text"] answer.update({"error": text} if result.get("isError") else {"verdicts": json.loads(text)["verdicts"]}) except Exception as exc: # whatever is wrong with the service, the command goes on answer["error"] = str(exc) or type(exc).__name__ thread = threading.Thread(target=call, daemon=True) # a timeout over all of it, not per read thread.start() thread.join(TIMEOUT) return answer.get("verdicts"), answer.get("error") or "no answer within 3 seconds" def line(v): word = {"use_instead": "vulnerable"}.get(v["verdict"], v["verdict"].replace("_", " ")) parts = [f"{v['package']}: {word}", v.get("reason") or "", f"use {v['use']}" if v.get("use") else ""] return re.sub(r"[^\x20-\x7e]", " ", "; ".join(p for p in parts if p))[:400] def extract_command(payload): """Auto-detect client hook schema and return (command_str_or_None, client_name). Supports Claude Code (`tool_input.command`), Antigravity (`toolCall.args.CommandLine` or `tool_input.CommandLine`), and Cursor/Windsurf (`command` or `tool_info.command_line`). """ if not isinstance(payload, dict): return None, "claude" tool_input = payload.get("tool_input") if isinstance(tool_input, dict): if "command" in tool_input: cmd = tool_input.get("command") return (cmd if isinstance(cmd, str) else None), "claude" if "CommandLine" in tool_input: cmd = tool_input.get("CommandLine") return (cmd if isinstance(cmd, str) else None), "antigravity" tool_call = payload.get("toolCall") if isinstance(tool_call, dict): args = tool_call.get("args") if isinstance(args, dict) and "CommandLine" in args: cmd = args.get("CommandLine") return (cmd if isinstance(cmd, str) else None), "antigravity" tool_info = payload.get("tool_info") if isinstance(tool_info, dict) and "command_line" in tool_info: cmd = tool_info.get("command_line") return (cmd if isinstance(cmd, str) else None), "windsurf" if isinstance(payload.get("command"), str): return payload["command"], "cursor" return None, "claude" def note_for(client, note): """A note in the agent's format; it leaves the decision to the user's own rules. Cursor gets nothing: its output needs a permission, and "allow" could approve the command. Antigravity's "allow" delegates to the next hook or the default policy (https://antigravity.google/docs/hooks).""" if client == "cursor": return {} if client == "antigravity": return {"decision": "allow", "reason": note} if client == "windsurf": return {"_stdout": note} return {"systemMessage": note, "hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": note}} def decide(verdicts, client="claude"): """The hook's answer. Never an approval: that would skip the user's own permission rules.""" by = {} for v in verdicts: by.setdefault(v["verdict"], []).append(line(v)) stop = by.get("do_not_install", []) warn = by.get("does_not_exist", []) + by.get("use_instead", []) + by.get("vulnerable", []) # A current release that is clear is a note too: the project's manifest or lockfile may resolve an older one. rest = [line(v) for v in verdicts if v["verdict"] not in ("do_not_install", "does_not_exist", "use_instead", "vulnerable") and (v["verdict"] != "no_known_problem" or v.get("latest"))] if client == "antigravity": if stop or warn: return {"decision": "deny" if stop else "ask", "reason": "Vordix Security: " + " | ".join(stop + warn)} return note_for(client, "Vordix Security: " + " | ".join(rest)[:1500]) if rest else {} if client == "windsurf": # pre_run_command blocks on exit code 2, the reason on stderr; it cannot ask, so a warning is a note on stdout. if stop: return {"_exit_code": 2, "_stderr": "Vordix Security: " + " | ".join(stop + warn)} return {"_stdout": "Vordix Security: " + " | ".join(warn + rest)[:1500]} if warn or rest else {} if client == "cursor": if stop or warn: msg = "Vordix Security: " + " | ".join(stop + warn) return {"permission": "deny" if stop else "ask", "user_message": msg, "agent_message": msg} return {} # a note needs a permission, and "allow" would approve the command over the user's own rules out = {"hookEventName": "PreToolUse"} if stop or warn: out["permissionDecision"] = "deny" if stop else "ask" out["permissionDecisionReason"] = "Vordix Security: " + " | ".join(stop + warn) elif rest: out["additionalContext"] = "Vordix Security, before this install: " + " | ".join(rest) else: return {} return {"hookSpecificOutput": out, **({"systemMessage": "Vordix Security: " + " | ".join(rest)[:1500]} if rest else {})} def main(): client = "claude" try: payload = json.load(sys.stdin) command, client = extract_command(payload) if not command: return wanted = [dict(t) for t in dict.fromkeys(tuple(p.items()) for p in packages(command))] except Exception: # not a command we can read return if not wanted: return verdicts, error = ask_service(wanted[:MAX_PACKAGES]) try: if verdicts is None: out = note_for(client, re.sub(r"[^\x20-\x7e]", " ", f"Vordix Security did not check this install ({error[:200]}). Nothing is known about these packages.")) else: extra = [{"package": f"{len(wanted) - MAX_PACKAGES} more packages", "verdict": "not_checked"}] if len(wanted) > MAX_PACKAGES else [] out = decide(verdicts + extra, client=client) except Exception: out = note_for(client, "Vordix Security did not check this install: an answer it could not read.") exit_code, stderr, stdout = out.pop("_exit_code", 0), out.pop("_stderr", ""), out.pop("_stdout", "") if stderr: print(stderr, file=sys.stderr, flush=True) if stdout: print(stdout, flush=True) elif out: print(json.dumps(out), flush=True) os._exit(exit_code) # do not wait for a hanging connection if __name__ == "__main__": main()