|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Cursor hook script: write a redacted JSONL audit record for hook events. |
| 4 | +
|
| 5 | +This script is designed to be called by Cursor hooks (e.g., preToolUse) and is: |
| 6 | +- dependency-free (stdlib only) |
| 7 | +- safe-by-default (redacts common secret-like fields) |
| 8 | +- resilient (always prints a JSON response) |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import json |
| 14 | +import os |
| 15 | +import re |
| 16 | +import sys |
| 17 | +from dataclasses import dataclass |
| 18 | +from datetime import datetime, timezone |
| 19 | +from pathlib import Path |
| 20 | +from typing import Any |
| 21 | + |
| 22 | + |
| 23 | +REDACT_KEY_RE = re.compile( |
| 24 | + r"(token|secret|password|passwd|authorization|api[_-]?key|private[_-]?key)", |
| 25 | + re.IGNORECASE, |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +def _now_iso() -> str: |
| 30 | + return datetime.now(timezone.utc).isoformat() |
| 31 | + |
| 32 | + |
| 33 | +def _safe_load_stdin() -> dict[str, Any]: |
| 34 | + raw = sys.stdin.read() |
| 35 | + if not raw.strip(): |
| 36 | + return {} |
| 37 | + try: |
| 38 | + data = json.loads(raw) |
| 39 | + if isinstance(data, dict): |
| 40 | + return data |
| 41 | + except Exception: |
| 42 | + pass |
| 43 | + return {"_raw": raw[:4096]} |
| 44 | + |
| 45 | + |
| 46 | +def _redact(value: Any) -> Any: |
| 47 | + if isinstance(value, dict): |
| 48 | + redacted: dict[str, Any] = {} |
| 49 | + for k, v in value.items(): |
| 50 | + if REDACT_KEY_RE.search(str(k)): |
| 51 | + redacted[k] = "***REDACTED***" |
| 52 | + else: |
| 53 | + redacted[k] = _redact(v) |
| 54 | + return redacted |
| 55 | + if isinstance(value, list): |
| 56 | + return [_redact(v) for v in value] |
| 57 | + if isinstance(value, str): |
| 58 | + if len(value) > 20000: |
| 59 | + return value[:20000] + "...<truncated>" |
| 60 | + return value |
| 61 | + return value |
| 62 | + |
| 63 | + |
| 64 | +@dataclass(frozen=True) |
| 65 | +class Output: |
| 66 | + # Cursor accepts a minimal output object. Returning {} is also OK. |
| 67 | + # We keep a stable shape to avoid accidental blocking. |
| 68 | + continue_: bool = True |
| 69 | + |
| 70 | + def to_json(self) -> str: |
| 71 | + return json.dumps({"continue": self.continue_}) |
| 72 | + |
| 73 | + |
| 74 | +def _default_log_path() -> Path: |
| 75 | + # User hooks run from ~/.cursor; project hooks run from repo root. |
| 76 | + # Prefer a local state directory if present, otherwise write under ~/.cursor. |
| 77 | + cwd = Path(os.getcwd()) |
| 78 | + local_state = cwd / ".cursor" / "hooks" / "state" |
| 79 | + if (cwd / ".cursor").exists(): |
| 80 | + return local_state / "hook-audit.jsonl" |
| 81 | + |
| 82 | + home = Path.home() |
| 83 | + return home / ".cursor" / "hooks" / "state" / "hook-audit.jsonl" |
| 84 | + |
| 85 | + |
| 86 | +def main() -> int: |
| 87 | + payload = _safe_load_stdin() |
| 88 | + record = { |
| 89 | + "ts_utc": _now_iso(), |
| 90 | + "hook_event_name": payload.get("hook_event_name"), |
| 91 | + "tool_name": payload.get("tool_name"), |
| 92 | + "file_path": payload.get("file_path") or (payload.get("tool_input") or {}).get("file_path"), |
| 93 | + "cwd": payload.get("cwd"), |
| 94 | + "conversation_id": payload.get("conversation_id"), |
| 95 | + "generation_id": payload.get("generation_id"), |
| 96 | + "model": payload.get("model"), |
| 97 | + "payload": _redact(payload), |
| 98 | + } |
| 99 | + |
| 100 | + log_path = _default_log_path() |
| 101 | + log_path.parent.mkdir(parents=True, exist_ok=True) |
| 102 | + with log_path.open("a", encoding="utf-8") as f: |
| 103 | + f.write(json.dumps(record, ensure_ascii=False) + "\n") |
| 104 | + |
| 105 | + sys.stdout.write(Output().to_json() + "\n") |
| 106 | + return 0 |
| 107 | + |
| 108 | + |
| 109 | +if __name__ == "__main__": |
| 110 | + raise SystemExit(main()) |
0 commit comments