claude-code-hooks
Production-ready Claude Code hooks, each installable on its own as a plugin.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/karanb192-claude-code-hooks)HTML
<a href="/listings/karanb192-claude-code-hooks"><img src="/api/listings/karanb192-claude-code-hooks/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
This repo is a **Claude Code plugin marketplace**, so you can install a single hook: no copying scripts, no editing `settings.json` by hand.
**1. Add the marketplace (once):**
/plugin marketplace add karanb192/claude-code-hooks
**2. Install just the hook you want:**
/plugin install context-hogs@claude-code-hooks
**3. Restart Claude Code**: the hook is active.
| Plugin | What it does | Command / config | | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | | [context-hogs](plugins/context-hogs) | Per-file context-cost leaderboard: attributes each tool result's tokens to the files it loaded, so you see which files cost you the most | `/context-hogs:leaderboard` renders the board on demand | | [cache-tax](plugins/cache-tax) | The comeback price of a cold prompt cache, before you pay it: warns (or refuses once) when your next message re-writes a lapsed 1-hour cache at up to 80x the read rate, prices a stale `--resume`, and doubles as a status line segment with minutes left and the cold cost. A Mod form with keep-warm lives in [claude-code-mods](https://github.com/karanb192/claude-code-mods/tree/main/plugins/cache-tax) | `/cache-tax:status` renders the card; `CACHE_TAX_BLOCK=1` refuses instead of warning; `cache-tax.js --statusline` for the segment | | [nerf-receipts](plugins/nerf-receipts) | Personal flight recorder: records your own failure rate, edit churn & tokens/task by model version, and flags real shifts when a model changes | `/nerf-receipts:receipts` renders the trend card on demand | | [dead-rules-audit](plugins/dead-rules-audit) | CLAUDE.md compliance scorecard: tallies which rules Claude follows vs ignores as you edit (SessionStart + PostToolUse + SessionEnd), and flags chronically-ignored rules to promote into a deterministic hook | `/dead-rules-audit:scorecard` renders the scorecard on demand | | [pr-provenance-stamp](plugins/pr-provenance-stamp) | Stamps a provenance receipt (prompts, est. spend, tests run, agent-authored lines) into your PR body when Claude runs `gh pr create` | `/pr-provenance-stamp:provenance` renders the receipt on demand | | [standup-autopilot](plugins/standup-autopilot) | Writes your daily standup from what your agents actually did across repos: captures tasks, tests, PRs, and blockers from session transcripts and re-injects yesterday's open blockers next session | `/standup-autopilot:standup` renders today's card on demand | | [dead-end-registry](plugins/dead-end-registry) | Remembers approaches you tried and reverted (reason + estimated token cost) and warns before you retry them: a prompt-submit card plus an ask-before-edit guard | `/dead-end-registry:dead-ends` renders the registry on demand | | [bounty-board](plugins/bounty-board) | Prices your repo's TODO/FIXME/HACK/skip debt as aging XP bounties, injects the top 3 as opportunistic side quests, and verifies + pays out bounties you genuinely clear | `/bounty-board:board` renders the board on demand | | [guard-pack](plugins/guard-pack) | **All seven guards below in one Node process**: one ~35 ms startup per tool call instead of seven. The first deny wins and a later deny outranks an earlier ask, in that guard's own format. Do not install alongside the individual guards. Also runs in Codex CLI from 1.3.0, edits included; see [its README](plugins/guard-pack#codex-cli). | `HOOK_SAFETY_LEVEL` applies to the six pattern guards uniformly; `HOOK_ASK_*`, `CONFIG_GUARD_ALLOW`, and `SPAWN_CAP_*` pass through |
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 320 lines
- {
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "claude-code-hooks",
- "description": "Production-ready Claude Code hooks, each installable on its own as a plugin.",
- "owner": {
- "name": "Karan Bansal",
- "url": "https://github.com/karanb192"
- },
- "plugins": [
- {
- "name": "context-hogs",
- "source": "./plugins/context-hogs",
- "description": "Per-file context-cost leaderboard: attributes every tool result's tokens to the files it loaded, so you know which files cost you the most.",
- "category": "cost",
- "tags": [
- "cost",
- "observability",
- "context",
- "hooks",
- "posttooluse"
- ]
- },
- {
- "name": "cache-tax",
- "source": "./plugins/cache-tax",
- "description": "The comeback price of a cold prompt cache, shown before you pay it: a UserPromptSubmit guard that warns (or refuses once) when your next message re-writes a lapsed 1-hour cache at up to 80x the read rate, a SessionStart hook that prices a stale resume, and a one-line status line segment with minutes left and the cold-comeback cost.",
- "category": "cost",
- "tags": [
- "cost",
- "prompt-cache",
- "observability",
- "statusline",
- "hooks",
- "userpromptsubmit",
- "sessionstart"
- ]
- },
- {
- "name": "nerf-receipts",
- "source": "./plugins/nerf-receipts",
- "description": "A personal flight recorder for Claude Code quality: records your own per-session failure rate, edit churn, and tokens/task by model version, and flags real shifts when a model changes.",
- "category": "observability",
- "tags": [
- "quality",
- "observability",
- "model-drift",
- "hooks",
- "sessionend"
- ]
- },
- {
- "name": "dead-rules-audit",
- "source": "./plugins/dead-rules-audit",
- "description": "CLAUDE.md compliance scorecard: tallies which rules Claude actually follows vs ignores as you edit, and flags chronically-ignored rules to promote into a deterministic hook.",
- "category": "observability",
- "tags": [
- "compliance",
- "claude-md",
- "observability",
- "hooks",
- "posttooluse",
- "sessionstart",
- "sessionend"
- ]
- },
- {
- "name": "pr-provenance-stamp",
- "source": "./plugins/pr-provenance-stamp",
- "description": "Stamps a provenance receipt (prompts, estimated spend, tests run with exit codes, and a truthful agent-authored line split) into your PR body on `gh pr create`.",
- "category": "git",
- "tags": [
- "pr",
- "provenance",
- "github",
- "hooks",
- "pretooluse",
- "posttooluse"
- ]
- },
- {
- "name": "standup-autopilot",
- "source": "./plugins/standup-autopilot",
- "description": "Writes your daily standup from what your agents actually did across repos: captures tasks, tests, PRs, and blockers from session transcripts and re-injects yesterday's open blockers next session.",
- "category": "productivity",
- "tags": [
- "standup",
- "productivity",
- "sessionstart",
- "sessionend",
- "hooks",
- "stop"
- ]
- },
- {
- "name": "dead-end-registry",
- "source": "./plugins/dead-end-registry",
- "description": "Remembers approaches you tried and reverted (with reason and estimated token cost) and warns before you retry them, via a prompt-submit card and an ask-before-edit guard.",
- "category": "memory",
- "tags": [
- "memory",
- "context",
- "negative-knowledge",
- "hooks",
- "userpromptsubmit",
- "pretooluse",
- "stop",
- "subagentstop",
- "precompact"
- ]
- },
- {
- "name": "bounty-board",
- "source": "./plugins/bounty-board",
- "description": "Prices your repo's TODO/FIXME/HACK debt as aging XP bounties, injects the top 3 as opportunistic side quests, and verifies + pays out bounties you genuinely clear.",
- "category": "productivity",
- "tags": [
- "tech-debt",
- "todo",
- "gamification",
- "hooks",
- "sessionstart",
- "posttooluse"
- ]
- },
- {
- "name": "block-dangerous-commands",
- "source": "./plugins/block-dangerous-commands",
- "description": "PreToolUse guard for Bash: blocks dangerous shell commands (rm -rf ~, fork bombs, curl|sh, force push to main) before they run, with three safety levels and opt-in per-level ask mode.",
- "category": "safety",
- "tags": [
- "safety",
- "security",
- "guardrails",
- "bash",
- "hooks",
- "pretooluse"
- ]
- },
- {
- "name": "protect-secrets",
- "source": "./plugins/protect-secrets",
- "description": "Secrets firewall for tool calls: denies (or asks, per level) any Read/Edit/Write/Bash/Grep that would read, search, modify, or exfiltrate .env files, SSH keys, cloud credentials, or keystores, with tiered safety levels tunable via HOOK_SAFETY_LEVEL.",
- "category": "security",
- "tags": [
- "security",
- "secrets",
- "guardrails",
- "hooks",
- "pretooluse"
- ]
- },
- {
- "name": "git-safety",
- "source": "./plugins/git-safety",
- "description": "Branch-aware git guardrails plus destructive gh CLI protection: denies pushes to main/master, protected-branch deletion, direct commit/merge/rebase/reset/push on a protected branch, and gh pr merge/close, issue close, release and repo delete.",
- "category": "safety",
- "tags": [
- "git",
- "github",
- "safety",
- "guardrails",
- "hooks",
- "pretooluse"
- ]
- },
- {
- "name": "protect-tests",
- "source": "./plugins/protect-tests",
- "description": "Stops \"fake green\" test-gaming: blocks the agent from deleting, renaming-away, or skip/xfail-disabling tests so it fixes the code instead, across pytest, jest, Go, JUnit, RSpec, and more.",
- "category": "safety",
- "tags": [
- "safety",
- "tests",
- "guardrails",
- "hooks",
- "pretooluse"
- ]
- },
- {
- "name": "case-insensitive-guard",
- "source": "./plugins/case-insensitive-guard",
- "description": "Stops `rm -rf content` destroying `Content` on case-insensitive filesystems (APFS/exFAT/NTFS): resolves the real target of destructive commands through cd chains, quotes, and subshells, and denies provable case collisions.",
- "category": "safety",
- "tags": [
- "safety",
- "filesystem",
- "data-loss",
- "hooks",
- "pretooluse"
- ]
- },
- {
- "name": "config-guard",
- "source": "./plugins/config-guard",
- "description": "Who guards the guards: blocks the agent from tampering with its own guardrail config (settings.json, hook scripts, hooks.json, .mcp.json, plugin manifests, claude CLI config writes); reads always pass.",
- "category": "safety",
- "tags": [
- "security",
- "guardrails",
- "config",
- "supply-chain",
- "hooks",
- "pretooluse"
- ]
- },
- {
- "name": "subagent-spawn-cap",
- "source": "./plugins/subagent-spawn-cap",
- "description": "Per-session subagent spawn budget: a PreToolUse guard on the Agent tool that counts every spawn (nested fan-outs included) in an append-only ledger, asks at SPAWN_CAP_ASK (default 20) and every SPAWN_CAP_ASK_STEP after it (default 10), and denies at SPAWN_CAP_DENY (default 60). The total cap Claude Code 2.1.224 removed, back under the user's control.",
- "category": "safety",
- "tags": [
- "safety",
- "cost",
- "subagents",
- "guardrails",
- "hooks",
- "pretooluse"
- ]
- },
- {
- "name": "config-watch",
- "source": "./plugins/config-watch",
- "description": "Tripwire for out-of-band config changes: warns on every mid-session settings/skills change (or blocks it with CONFIG_WATCH_BLOCK=true) to catch installer scripts and npm payloads rewriting settings behind Claude Code's back.",
- "category": "safety",
- "tags": [
- "security",
- "config",
- "supply-chain",
- "hooks",
- "configchange"
- ]
- },
- {
- "name": "auto-stage",
- "source": "./plugins/auto-stage",
- "description": "Stage files after Claude edits or writes them, or after successful native Codex patches. Stages whole files, including pre-existing edits; review the index before committing.",
- "category": "git",
- "tags": [
- "git",
- "automation",
- "staging",
- "hooks",
- "posttooluse"
- ]
- },
- {
- "name": "format-code",
- "source": "./plugins/format-code",
- "description": "Format Claude edits and native Codex patches with ruff and prettier. Codex uses installed tools, skips project formatter settings and ignore files, and never runs lint autofixes or downloads tools.",
- "category": "automation",
- "tags": [
- "formatting",
- "prettier",
- "ruff",
- "automation",
- "hooks",
- "posttooluse"
- ]
- },
- {
- "name": "session-logger",
- "source": "./plugins/session-logger",
- "description": "Local Markdown session notes with best-effort command redaction. Async in Claude Code; synchronous Codex hooks record lifecycle events, native patch paths and shell commands.",
- "category": "observability",
- "tags": [
- "logging",
- "sessions",
- "observability",
- "obsidian",
- "hooks",
- "sessionstart",
- "posttooluse",
- "sessionend"
- ]
- },
- {
- "name": "instructions-audit",
- "source": "./plugins/instructions-audit",
- "description": "Prompt-injection tripwire for CLAUDE.md and .claude/rules files: flags invisible-Unicode smuggling, secret read/exfil directives, curl|sh, decode-and-execute, and hook/settings tampering as instructions load, then locks the session (every prompt and tool call denied) until a human clears it.",
- "category": "security",
- "tags": [
- "security",
- "prompt-injection",
- "claude-md",
- "hooks",
- "instructionsloaded",
- "userpromptsubmit",
- "pretooluse"
- ]
- },
- {
- "name": "notify-permission",
- "source": "./plugins/notify-permission",
- "description": "Slack alerts when Claude Code needs you: posts a rich card (project, session, and what needs approval) to your webhook on permission, idle, and choice prompts.",
- "category": "notifications",
- "tags": [
- "notifications",
- "slack",
- "alerts",
- "hooks",
- "notification"
- ]
- },
- {
- "name": "guard-pack",
- "source": "./plugins/guard-pack",
- "description": "All seven guard hooks in one Node process: subagent-spawn-cap, config-guard, block-dangerous-commands, protect-secrets, protect-tests, git-safety, and case-insensitive-guard, first blocking verdict wins. One ~35 ms Node startup per tool call instead of seven. Do not install alongside the individual guard plugins. Also runs in Codex CLI, file edits included.",
- "category": "security",
- "tags": [
- "security",
- "safety",
- "guardrails",
- "pretooluse",
- "latency",
- "subagents",
- "codex"
- ]
- }
- ]
- }
README.md · README · 436 lines
- # claude-code-hooks
- 🪝 Guardrails for Claude Code and Codex CLI. Browse the 22-plugin marketplace and check [host compatibility](#-using-codex).
- [](https://github.com/karanb192/claude-code-hooks)
- [](https://opensource.org/licenses/MIT)
- [](https://github.com/karanb192/claude-code-hooks/actions/workflows/test.yml)
- [](https://github.com/karanb192/claude-code-hooks/actions/workflows/test.yml)
- **🌐 [Live site & catalog](https://karanb192.github.io/claude-code-hooks/)**
- Before an agent runs a shell command or edits a file, these hooks check the action against rules outside the model. The [guard pack](plugins/guard-pack) blocks matched secret reads, dangerous commands, test disabling and destructive Git operations. A blocked call returns a reason to the agent. The [coverage limits](plugins/guard-pack#codex-cli) matter: hooks only see the events their host sends, and pattern checks are not a sandbox. The catalog also includes Claude Code automation, notifications and observability, with an [OWASP mapping](docs/owasp-llm-top-10-2026.md).
- **Start with guard-pack. Choose your agent:**
- Claude Code, inside a session:
- ```text
- /plugin marketplace add karanb192/claude-code-hooks
- /plugin install guard-pack@claude-code-hooks
- ```
- Restart Claude Code after installing.
- Codex CLI, from a shell:
- ```sh
- codex plugin marketplace add karanb192/claude-code-hooks
- codex plugin add guard-pack@claude-code-hooks
- ```
- Open `/hooks` in Codex and approve the pack. Approve it again after updates; Codex skips unapproved or changed hooks. Do not install the pack alongside its individual guards. See the [Codex compatibility table](#-using-codex) before choosing other plugins.
- ### 🎬 Quick Demo
- <table>
- <tr>
- <th align="center">Protecting Secrets</th>
- <th align="center">Blocking Dangerous Commands</th>
- </tr>
- <tr>
- <td valign="bottom" align="center"><img src="assets/block-secrets.png" alt="Hook blocking .env read" width="400"></td>
- <td valign="bottom" align="center"><img src="assets/block-dangerous-commands.png" alt="Hook blocking dangerous commands" width="400"></td>
- </tr>
- </table>
- A growing collection of tested, documented hooks. Every one installs as a one-command Claude Code plugin: run `/plugin marketplace add karanb192/claude-code-hooks`, then `/plugin install <name>@claude-code-hooks`; see [Install as a plugin](#-install-as-a-plugin) for the 22-plugin catalog. Prefer to own the file? Every plugin's script also works standalone: copy `plugins/<name>/<name>.js` and wire it into `settings.json` yourself ([Quick Start](#-quick-start)).
- ---
- ## 📑 Table of Contents
- - [Hooks](#-hooks)
- - [Install as a plugin](#-install-as-a-plugin)
- - [Using Codex?](#-using-codex)
- - [Quick Start](#-quick-start)
- - [Safety Levels](#-safety-levels)
- - [Testing](#-testing)
- - [Token Diet](#-token-diet)
- - [Configuration Reference](#-configuration-reference)
- - [Looking for mods?](#-looking-for-mods)
- - [Contributing](#-contributing)
- - [License](#-license)
- ---
- ## 🪝 Hooks
- Every hook below is an installable plugin; each link goes to the plugin's directory, which holds the script, its tests, and a README. They're grouped by the event that fires them, because the event model is the thing worth learning.
- ### Session Lifecycle
- Runs at session boundaries: inject context at **SessionStart** and capture outcomes at **Stop / SessionEnd**.
- | Hook | Events | Description |
- |------|---------|-------------|
- | [session-logger](plugins/session-logger) | `SessionStart` + `PostToolUse` + `SessionEnd` | Writes a durable markdown log of every session (cwd, git repo, files touched, bash commands). `PostToolUse` registers with `"async": true` so logging never blocks Claude; concurrent writes are serialized with a file lock. Bash commands get best-effort secret redaction. Drop-in for Obsidian vaults via `CC_SESSION_LOG_DIR`. |
- | [standup-autopilot](plugins/standup-autopilot) | `SessionStart` (`startup`) + `Stop` + `SessionEnd` | Writes your daily standup from what your agents actually did across repos: captures tasks, tests, PRs, and blockers from session transcripts and re-injects yesterday's open blockers next session |
- | [nerf-receipts](plugins/nerf-receipts) | `SessionStart` + `PostToolUse` + `PostToolUseFailure` + `Stop` + `SubagentStop` + `SessionEnd` | Personal flight recorder: records your own failure rate, edit churn & tokens/task by model version, and flags real shifts when a model changes |
- | [bounty-board](plugins/bounty-board) | `SessionStart` + `PostToolUse` + `SessionEnd` | Prices your repo's TODO/FIXME/HACK/skip debt as aging XP bounties, injects the top 3 as opportunistic side quests, and verifies + pays out bounties you genuinely clear |
- ### Instructions-Loaded
- Fires when a CLAUDE.md or `.claude/rules/*.md` file is loaded into context. The event has no decision control, its exit code is ignored, and current Claude Code builds ignore even the universal `continue: false` on it (verified live), so detection and enforcement are split: the InstructionsLoaded registration records a per-session lock on a finding (and still emits `continue: false` for builds that honor it), and the same script registered on UserPromptSubmit and PreToolUse blocks every prompt and tool call for that session until a human fixes the file or deletes the named lock file. The plugin wires all three arms in one install.
- | Hook | Matcher | Description |
- |------|---------|-------------|
- | [instructions-audit](plugins/instructions-audit) | all load reasons (narrow with `session_start\|nested_traversal\|path_glob_match\|include\|compact`) | Locks the session when a loaded instruction file carries hidden directives: invisible-Unicode smuggling (zero-width, tag characters, variation-selector runs; the TrapDoor supply-chain signature), bidi overrides, directives to read or exfiltrate secrets, curl\|sh, decode-and-execute, and hook/settings tampering. Names the rule and line number so you can inspect the file; one install wires the detection arm plus both enforcement arms; `HOOK_AUDIT_LEVEL` tunes critical/high/strict, `HOOK_AUDIT_WARN_ONLY=true` warns without locking. |
- ### User-Prompt-Submit
- Runs when the user submits a prompt, before Claude processes it. Can inject context or block the prompt.
- | Hook | Events | Description |
- |------|---------|-------------|
- | [dead-end-registry](plugins/dead-end-registry) | `UserPromptSubmit` + `PreToolUse` (`Edit\|Write`) + `Stop` + `SubagentStop` + `PreCompact` | Remembers approaches you tried and reverted (reason + estimated token cost) and warns before you retry them: a prompt-submit card plus an ask-before-edit guard |
- ### Pre-Tool-Use
- Runs **before** Claude executes a tool. Can block or modify the operation.
- | Hook | Matcher | Description |
- | ------------------------------------------------------------- | ------------------------- | ---------------------------------------------------------------- |
- | [block-dangerous-commands](plugins/block-dangerous-commands) | `Bash` | Blocks dangerous shell commands (rm -rf ~, fork bombs, curl\|sh, force push to main) before they run |
- | [protect-secrets](plugins/protect-secrets) | `Read\|Edit\|Write\|Bash\|Grep` | Prevents reading/modifying/exfiltrating sensitive files |
- | [git-safety](plugins/git-safety) | `Bash` | Branch-aware git guardrails + destructive gh CLI protection |
- | [protect-tests](plugins/protect-tests) | `Bash\|Edit\|MultiEdit\|Write` | Stops "fake green": blocks deleting, renaming-away, or skip/xfail-disabling tests |
- | [case-insensitive-guard](plugins/case-insensitive-guard) | `Bash` | Stops `rm -rf content` destroying `Content` on case-insensitive filesystems (APFS/exFAT/NTFS): resolves real targets through `cd` chains and quotes |
- | [config-guard](plugins/config-guard) | `Bash\|Edit\|MultiEdit\|Write` | Who guards the guards: blocks the agent from tampering with its own guardrail config (settings.json, `.claude/hooks/`, hooks.json, `.mcp.json`, plugin manifests). Reads always pass. See [Config-Change](#config-change) for why and for its out-of-band sibling. |
- | [subagent-spawn-cap](plugins/subagent-spawn-cap) | `Agent\|Task` | Per-session subagent spawn budget: asks at spawn 20 and every 10 after, denies at 60, nested fan-outs included. The total cap Claude Code 2.1.224 removed, back under your control. |
- ### Post-Tool-Use
- Runs **after** Claude executes a tool. Can react to results.
- | Hook | Matcher | Description |
- | -------------------------------------------------------- | ------------- | ----------------------------------------------------------------------------- |
- | [auto-stage](plugins/auto-stage) | `Edit\|Write` | Automatically git stages files after Claude modifies them |
- | [format-code](plugins/format-code) | `Write\|Edit` | Auto-formats Python (ruff) and JS/TS/HTML/JSON/MD/YAML (prettier) after edits |
- | [context-hogs](plugins/context-hogs) | `Read\|Grep\|Glob\|Bash` (async) + `SessionEnd` | Per-file context-cost leaderboard: attributes each tool result's tokens to the files it loaded, so you see which files cost you the most |
- | [pr-provenance-stamp](plugins/pr-provenance-stamp) | `Edit\|MultiEdit\|Write\|Bash` (async) + `PreToolUse` on `Bash` | Stamps a provenance receipt (prompts, est. spend, tests run, agent-authored lines) into your PR body when Claude runs `gh pr create` |
- | [dead-rules-audit](plugins/dead-rules-audit) | `Edit\|MultiEdit\|Write` (async) + `SessionStart` + `SessionEnd` | CLAUDE.md compliance scorecard: tallies which rules Claude follows vs ignores as you edit, and flags chronically-ignored rules to promote into a deterministic hook |
- ### Notification
- Fires when Claude needs user attention.
- | Hook | Matcher | Description |
- | ------------------------------------------------------------------- | -------------------------------- | ------------------------------------------ |
- | [notify-permission](plugins/notify-permission) | `permission_prompt\|idle_prompt\|elicitation_dialog` | Sends Slack alerts when Claude needs input |
- ### Config-Change
- Fires when a configuration file changes during a session. Can block the change (exit 2), except for `policy_settings`.
- | Hook | Matcher | Description |
- | ---------------------------------------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------ |
- | [config-watch](plugins/config-watch) | `user_settings\|project_settings\|local_settings\|policy_settings\|skills` | Makes every mid-session config change loudly visible (default), or blocks it outright with `CONFIG_WATCH_BLOCK=true`. Note: the docs guarantee ConfigChange can block via exit 2 but do not document its payload schema, so the hook parses defensively and logs the raw payload. |
- **Why config-guard + config-watch exist:** the Aug 2026 [CHAINDROP npm worm](https://www.elastic.co/security-labs/shai-hulud-chaindrop-npm-supply-chain) hid its payload in `.claude/settings.json`, turning the agent's own config into its persistence mechanism. And [CVE-2026-25725](https://advisories.gitlab.com/pkg/npm/@anthropic-ai/claude-code/CVE-2026-25725) let sandboxed code escape by injecting hooks into a `settings.json` that did not exist yet, which is why `config-guard` treats creating a protected file as mutation. `config-guard` (PreToolUse) blocks the agent itself from rewriting its guardrails before damage happens; `config-watch` (ConfigChange) covers changes made by anything else while a session runs. For intentional config edits, set `CONFIG_GUARD_ALLOW=true` for that call, or use [ask mode](#-ask-mode-prompt-instead-of-block) to get a prompt instead of a hard wall.
- Install them as a pair:
- ```
- /plugin install config-guard@claude-code-hooks
- /plugin install config-watch@claude-code-hooks
- ```
- > ⚠️ **Heads-up:** once `config-guard` is active it also blocks `claude plugin install/uninstall/disable` at its default `high` level (the plugin manager rewrites config too, including config-guard's own manifest). Install your other plugins first, or set `CONFIG_GUARD_ALLOW=true` for that one call.
- ### Utils
- Tools to help you build and debug hooks.
- | Tool | Language | Description |
- | -------------------------------------------------- | -------- | -------------------------------------------------- |
- | [event-logger](utils/event-logger.py) | Python | Logs all hook events to inspect payload structures |
- > 💡 **Building a new hook?** Use `event-logger.py` to discover what data Claude Code provides for each event before writing your own hooks.
- ---
- ## 🔌 Install as a plugin
- This repo is a **Claude Code plugin marketplace**, so you can install a single hook: no copying scripts, no editing `settings.json` by hand.
- **1. Add the marketplace (once):**
- ```
- /plugin marketplace add karanb192/claude-code-hooks
- ```
- **2. Install just the hook you want:**
- ```
- /plugin install context-hogs@claude-code-hooks
- ```
- **3. Restart Claude Code**: the hook is active.
- | Plugin | What it does | Command / config |
- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
- | [context-hogs](plugins/context-hogs) | Per-file context-cost leaderboard: attributes each tool result's tokens to the files it loaded, so you see which files cost you the most | `/context-hogs:leaderboard` renders the board on demand |
- | [cache-tax](plugins/cache-tax) | The comeback price of a cold prompt cache, before you pay it: warns (or refuses once) when your next message re-writes a lapsed 1-hour cache at up to 80x the read rate, prices a stale `--resume`, and doubles as a status line segment with minutes left and the cold cost. A Mod form with keep-warm lives in [claude-code-mods](https://github.com/karanb192/claude-code-mods/tree/main/plugins/cache-tax) | `/cache-tax:status` renders the card; `CACHE_TAX_BLOCK=1` refuses instead of warning; `cache-tax.js --statusline` for the segment |
- | [nerf-receipts](plugins/nerf-receipts) | Personal flight recorder: records your own failure rate, edit churn & tokens/task by model version, and flags real shifts when a model changes | `/nerf-receipts:receipts` renders the trend card on demand |
- | [dead-rules-audit](plugins/dead-rules-audit) | CLAUDE.md compliance scorecard: tallies which rules Claude follows vs ignores as you edit (SessionStart + PostToolUse + SessionEnd), and flags chronically-ignored rules to promote into a deterministic hook | `/dead-rules-audit:scorecard` renders the scorecard on demand |
- | [pr-provenance-stamp](plugins/pr-provenance-stamp) | Stamps a provenance receipt (prompts, est. spend, tests run, agent-authored lines) into your PR body when Claude runs `gh pr create` | `/pr-provenance-stamp:provenance` renders the receipt on demand |
- | [standup-autopilot](plugins/standup-autopilot) | Writes your daily standup from what your agents actually did across repos: captures tasks, tests, PRs, and blockers from session transcripts and re-injects yesterday's open blockers next session | `/standup-autopilot:standup` renders today's card on demand |
- | [dead-end-registry](plugins/dead-end-registry) | Remembers approaches you tried and reverted (reason + estimated token cost) and warns before you retry them: a prompt-submit card plus an ask-before-edit guard | `/dead-end-registry:dead-ends` renders the registry on demand |
- | [bounty-board](plugins/bounty-board) | Prices your repo's TODO/FIXME/HACK/skip debt as aging XP bounties, injects the top 3 as opportunistic side quests, and verifies + pays out bounties you genuinely clear | `/bounty-board:board` renders the board on demand |
- | [guard-pack](plugins/guard-pack) | **All seven guards below in one Node process**: one ~35 ms startup per tool call instead of seven. The first deny wins and a later deny outranks an earlier ask, in that guard's own format. Do not install alongside the individual guards. Also runs in Codex CLI from 1.3.0, edits included; see [its README](plugins/guard-pack#codex-cli). | `HOOK_SAFETY_LEVEL` applies to the six pattern guards uniformly; `HOOK_ASK_*`, `CONFIG_GUARD_ALLOW`, and `SPAWN_CAP_*` pass through |
- | [block-dangerous-commands](plugins/block-dangerous-commands) | Blocks dangerous shell commands (rm -rf ~, fork bombs, curl\|sh, force push to main) before they run | `HOOK_SAFETY_LEVEL` picks critical/high/strict (default high); `HOOK_ASK_*` prompts instead of denying |
- | [protect-secrets](plugins/protect-secrets) | Prevents reading, modifying, or exfiltrating sensitive files (.env, SSH keys, cloud creds, keystores), including feeding them to an external model CLI or model API, by denying or asking before the tool call runs | `HOOK_SAFETY_LEVEL` (critical/high/strict, default high), `HOOK_ASK_CRITICAL/HIGH/STRICT` ask mode; `/plugin install protect-secrets@claude-code-hooks` |
- | [git-safety](plugins/git-safety) | Branch-aware git guardrails + destructive gh CLI protection: blocks pushes to main/master, protected-branch deletion, direct changes on a protected branch, and gh pr merge/close, issue close, release/repo delete | `HOOK_SAFETY_LEVEL` = `critical`/`high`/`strict` (default `high`); `/plugin install git-safety@claude-code-hooks` |
- | [protect-tests](plugins/protect-tests) | Stops "fake green": blocks deleting, renaming-away, or skip/xfail-disabling tests instead of fixing the code (PreToolUse on `Bash\|Edit\|MultiEdit\|Write`) | `HOOK_SAFETY_LEVEL=critical\|high\|strict` (default `high`); `/plugin install protect-tests@claude-code-hooks` |
- | [case-insensitive-guard](plugins/case-insensitive-guard) | Stops `rm -rf content` destroying `Content` on case-insensitive filesystems (APFS/exFAT/NTFS): resolves real targets through `cd` chains, quotes, and subshells | `HOOK_SAFETY_LEVEL=critical\|high\|strict` (default `high`); ask mode via `HOOK_ASK_CRITICAL/HIGH/STRICT=true` |
- | [config-guard](plugins/config-guard) | Who guards the guards: blocks the agent from tampering with its own guardrail config (settings files, `.claude/hooks/`, hooks.json, `.mcp.json`, plugin manifests, `claude config/mcp/plugin` CLI writes); reads always pass, creating a protected file counts as mutation. | `HOOK_SAFETY_LEVEL` (critical/high/strict, default high), `CONFIG_GUARD_ALLOW=true` escape hatch, `HOOK_ASK_*` ask mode |
- | [subagent-spawn-cap](plugins/subagent-spawn-cap) | Per-session subagent spawn budget: counts every `Agent` call (nested spawns included) in an append-only ledger, asks at 20, 30, 40, 50 and denies at 60. The total cap Claude Code 2.1.224 removed, back under your control; the native concurrency and depth caps bound the rate, not the total. | `SPAWN_CAP_ASK` (default 20), `SPAWN_CAP_ASK_STEP` (default 10), `SPAWN_CAP_DENY` (default 60), `SPAWN_CAP_ALLOW=true` bypass while set; unattended runs: set ASK equal to DENY |
- | [config-watch](plugins/config-watch) | Makes every mid-session config change loudly visible (default) or blocks it outright, catching out-of-band settings.json writes like the CHAINDROP worm's persistence trick. | `CONFIG_WATCH_BLOCK=true` to block (exit 2); `policy_settings` always warns; or `/plugin install config-watch@claude-code-hooks` |
- | [auto-stage](plugins/auto-stage) | Automatically git stages files after Claude modifies them, so `git status` shows exactly what Claude touched | No config needed; `/plugin install auto-stage@claude-code-hooks`; logs to `~/.claude/hooks-logs/` |
- | [format-code](plugins/format-code) | Auto-formats Python (ruff) and JS/TS/HTML/JSON/MD/YAML (prettier) after every Write/Edit | `/plugin install format-code@claude-code-hooks`; needs `uv` and `npx` on PATH, no env vars |
- | [session-logger](plugins/session-logger) | Writes a durable markdown log of every session (cwd, git repo/branch, files touched, bash commands with best-effort secret redaction); `PostToolUse` runs async so logging never blocks Claude, and concurrent writes are serialized with a file lock. | `CC_SESSION_LOG_DIR` (point at an Obsidian vault for sync), `CC_SESSION_BASH_TRUNCATE`; `/plugin install session-logger@claude-code-hooks` |
- | [instructions-audit](plugins/instructions-audit) | Audits CLAUDE.md / `.claude/rules/*.md` as they load and locks the session on hidden or hostile directives (invisible-Unicode smuggling, secret read/exfil, curl\|sh, decode-and-execute, hook/settings tampering); one install wires the detection arm plus both enforcement arms | `HOOK_AUDIT_LEVEL` tunes critical/high/strict; `HOOK_AUDIT_WARN_ONLY=true` warns without locking |
- | [notify-permission](plugins/notify-permission) | Sends Slack alerts when Claude needs input (permission, idle, or choice prompts): a rich card with project, session, and what needs approval | Requires `CCH_SLA_WEBHOOK` (Slack webhook URL); or `/plugin install notify-permission@claude-code-hooks` |
- > ⚡ The pure recorder events in these plugins run **async**: they record in the background and add **~zero latency** to a tool call. Guard hooks stay synchronous on purpose: a deny has to land before the tool runs. Plugins with a card render it on demand via their own command (e.g. `/context-hogs:leaderboard`) and at SessionEnd.
- Prefer the classic route? Every plugin's script is self-contained: copy `plugins/<name>/<name>.js` and register it in `settings.json` yourself; see [Quick Start](#-quick-start).
- ### Migrating from hook-scripts/
- Earlier versions shipped the standalone scripts under `hook-scripts/`; that directory is gone and every script now lives in its plugin dir as `plugins/<name>/<name>.js`. Two situations need action:
- - **Your `settings.json` points into a clone of this repo** (for example `node ~/repos/claude-code-hooks/hook-scripts/pre-tool-use/block-dangerous-commands.js`). After you pull, that path no longer exists, and Claude Code treats a failing hook command as a non-blocking error: the guard stops enforcing without any visible sign. Fix it now, not later: install the plugin, or repoint the command at `plugins/<name>/<name>.js`.
- - **You copied a script to a stable location** (like `~/.claude/hooks/`). Your copy keeps working untouched. If you install the plugin version, remove the manual `settings.json` registration first, or the hook runs twice on every matching event: double latency, double log entries, double denials.
- ---
- ## 🤖 Using Codex?
- These plugins were written for Claude Code. Codex CLI reads the same marketplace, so they install there too, but most of them only partly work. Unless a plugin's own README says it supports Codex, expect the behaviour below. It was measured live on Codex CLI 0.167.1 for block-dangerous-commands, protect-secrets and protect-tests, and the other rows follow from what each plugin reads. The Codex side was rechecked against the 0.169.0 source.
- ```
- codex plugin marketplace add karanb192/claude-code-hooks
- codex plugin add <name>@claude-code-hooks
- ```
- Then open `/hooks` in Codex and approve the plugin's hooks. Codex skips any hook you have not approved, and it stops running them again whenever the plugin's files change, so approve again after each update.
- | On Codex | Plugins | Why |
- | --- | --- | --- |
- | Native support | [guard-pack](plugins/guard-pack#codex-cli) 1.4.0 and all seven current standalone guards | Shell and native patch checks; asks become blocks. The pack also includes Codex config protection and a deny-only, per-thread spawn budget. Install the pack or individual guards, not both |
- | Native workflow support | [auto-stage](plugins/auto-stage#codex-cli), [format-code](plugins/format-code#codex-cli), [session-logger](plugins/session-logger#codex-cli) 1.1.0 | Stage or format successful native patches; record lifecycle, patch paths and shell commands. Formatting skips project settings and ignore files; unconfigured files use installed Ruff/Prettier 3 defaults without lint autofixes. Shell-edited paths are not tracked, and formatting/staging order is not guaranteed |
- | Older versions | guard-pack 1.3.x | Shell and native patches, without the Codex spawn cap or full config-path coverage. Older standalone guards have no native patch adapter and do not safely support ask mode |
- | Claude Code only for now | Every other plugin | They rely on Claude Code transcripts, its edit events, or events Codex doesn't have (`Notification`, `ConfigChange`, `InstructionsLoaded`, the status line) |
- Codex workflow diagnostics are in `$CODEX_HOME/hooks-logs` (default `~/.codex/hooks-logs`). Guard diagnostics remain in `~/.claude/hooks-logs` with `host: "codex"`. Session notes use `$CODEX_HOME/session-notes`, or `CC_SESSION_LOG_DIR` when set.
- Two more things change under Codex.
- - **Ask becomes block.** The current pack and standalone guards convert ask-mode matches into blocks. The spawn cap ignores ask settings and uses `SPAWN_CAP_DENY`; see [its Codex policy](plugins/subagent-spawn-cap#codex-cli).
- - **Reads are shell commands.** Codex has no Read or Grep tool. It reads files with `cat`, `rg` and the like, so protect-secrets catches a read only when the command names the file.
- ---
- ## 🚀 Quick Start
- **1. Add the marketplace and install a hook:**
- ```
- /plugin marketplace add karanb192/claude-code-hooks
- /plugin install block-dangerous-commands@claude-code-hooks
- ```
- **2. Restart Claude Code**: the hook is now active.
- ### The classic way (copy the script)
- Every plugin's script works standalone, so you can skip the marketplace and own the file:
- **1. Copy the hook script:**
- ```bash
- mkdir -p ~/.claude/hooks
- cp plugins/block-dangerous-commands/block-dangerous-commands.js ~/.claude/hooks/
- ```
- **2. Add to `.claude/settings.json`:**
- ```json
- {
- "hooks": {
- "PreToolUse": [
- {
- "matcher": "Bash",
- "hooks": [
- {
- "type": "command",
- "command": "node ~/.claude/hooks/block-dangerous-commands.js"
- }
- ]
- }
- ]
- }
- }
- ```
- **3. Restart Claude Code**: the hook is now active.
- > 💡 **Tip:** Use multiple hooks together. Combine `block-dangerous-commands` + `protect-secrets` for comprehensive safety.
- ---
- ## 🛡️ Safety Levels
- Security hooks support configurable safety levels:
- | Level | What's Blocked | Use Case |
- | ---------- | ------------------------------------------------------------- | ------------------- |
- | `critical` | Catastrophic only (rm -rf ~, fork bombs, dd to disk) | Maximum flexibility |
- | `high` | + Risky (force push main, secrets exposure, git reset --hard) | **Recommended** |
- | `strict` | + Cautionary (any force push, sudo rm, docker prune) | Maximum safety |
- **To change:** set the `HOOK_SAFETY_LEVEL` environment variable to `critical`, `high`, or `strict` (anything else falls back to `high`). All six pattern guards read it: `block-dangerous-commands`, `protect-secrets`, `git-safety`, `protect-tests`, `case-insensitive-guard`, and `config-guard`. (`instructions-audit` uses `HOOK_AUDIT_LEVEL` for the same three levels; `subagent-spawn-cap` is a budget, not a pattern set, so it has its own `SPAWN_CAP_ASK` / `SPAWN_CAP_DENY`.) The `env` block in `settings.json` applies it to every session:
- ```json
- {
- "env": {
- "HOOK_SAFETY_LEVEL": "strict"
- }
- }
- ```
- Running a copied script the classic way? You can still edit the `SAFETY_LEVEL` default at the top of the hook instead; for installed plugins prefer the env var, since plugin updates overwrite edited files.
- ```javascript
- const SAFETY_LEVEL = "strict"; // or 'critical', 'high'
- ```
- ### 🙋 Ask mode (prompt instead of block)
- `block-dangerous-commands`, `protect-secrets`, `case-insensitive-guard`, and `config-guard` can **ask** instead of denying outright. When ask mode is on for a level, matching operations return `permissionDecision: "ask"`; Claude Code shows the reason and lets you approve or reject, instead of hard-blocking.
- Enable per level via environment variables (the literal string `true`; anything else means deny):
- | Variable | Affects |
- | ------------------- | ---------------------------------------------- |
- | `HOOK_ASK_CRITICAL` | `critical`-level patterns (rm -rf ~, .env, …) |
- | `HOOK_ASK_HIGH` | `high`-level patterns (git reset --hard, …) |
- | `HOOK_ASK_STRICT` | `strict`-level patterns (any force push, …) |
- Set them in the `env` block of `settings.json` (works for plugins and classic copies alike):
- ```json
- {
- "env": {
- "HOOK_ASK_STRICT": "true"
- }
- }
- ```
- Classic copies can also take them inline in the hook command: `"command": "HOOK_ASK_STRICT=true node ~/.claude/hooks/block-dangerous-commands.js"`.
- Everything defaults to **deny**: ask mode is strictly opt-in. A common setup: keep `critical` on deny, set `HOOK_ASK_STRICT=true` so cautionary patterns prompt instead of blocking.
- ---
- ## 🗺️ OWASP mapping
- [docs/owasp-llm-top-10-2026.md](docs/owasp-llm-top-10-2026.md) maps every hook in this repo against the [OWASP LLM Top 10 2026](https://genai.owasp.org/resource/owasp-genai-llm-top-10-2026/), risk by risk.
- The verdicts are honest: risks a runtime hook genuinely covers are marked covered, risks it cannot touch are marked N/A, and the gaps (rate limiting, output scanning, dependency validation) are listed as wanted contributions.
- It also points agent-specific risks at the OWASP Top 10 for Agentic Applications and names the four ASI risks these hooks land on.
- ---
- ## 🧪 Testing
- Requires **Node ≥ 18** (no npm dependencies). The `format-code` tests exercise the real formatters, so have Prettier 3 (`prettier`), `ruff`, and `uv` on your PATH (CI installs them) or expect those few tests to fail. All hooks include comprehensive tests, run in CI on Node 18, 20, and 22:
- ```bash
- # Run all tests
- npm test
- # Run a single plugin's tests
- node --test plugins/block-dangerous-commands/tests/block-dangerous-commands.test.js
- ```
- **Test coverage:**
- - ✅ Unit tests for core functions
- - ✅ Integration tests for stdin/stdout flow
- - ✅ Config validation tests
- ---
- ## ⚡ Performance
- A synchronous hook adds its full runtime to every matching tool call. Measured with a fresh Node process per call and a realistic event on stdin, every guard hook here holds a 34-38 ms median on an Apple M3 Pro (Node v26). The two PostToolUse hooks that spawn real subprocesses cost more: auto-stage 68 ms with two git calls, format-code 114 ms with two ruff runs. The harness and committed numbers for all seven hooks live in [`bench/`](bench/); reproduce with `node bench/run.mjs`.
- ---
- ## 🍃 Token Diet
- Not every context problem needs a hook. [docs/token-diet.md](docs/token-diet.md) is three presets (light, lean, strict) built from settings Claude Code already ships: the per-Read token cap, the subagent model and concurrency knobs, the auto-compact window, and `bashOutputMaxChars`, each linked to where it is documented, with a table of what they replace from [Spotify's shunt](https://github.com/spotify/portal-ai-plugins/tree/main/plugins/shunt) plugin.
- Measure before you change anything: [`bench/read-replay`](bench/read-replay/) replays your own transcripts and prints how many Read calls a 350-line gate would have caught and what share of your context tokens they were. One command, nothing leaves your machine.
- ---
- ## 📖 Configuration Reference
- See the [official Claude Code hooks documentation](https://code.claude.com/docs/en/hooks) for:
- - All hook events and their lifecycles
- - Input/output JSON formats
- - Matcher patterns
- - Environment variables
- ---
- ## 🧩 Looking for mods?
- The hooks here are scripts that run on Claude Code's hook events. Mods are the newer plugin form: JavaScript or TypeScript functions that can also change the interface, from Claude Code 2.1.287.
- [Awesome Claude Code Mods](https://github.com/karanb192/awesome-claude-code-mods) catalogues thousands of them and records what each one can read, write, run or send over the network. Browse it at [mods.aidojo.si](https://mods.aidojo.si/). The mod form of cache-tax lives at [karanb192/cache-tax](https://github.com/karanb192/cache-tax).
- ---
- ## 🤝 Contributing
- Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
- **Ideas for new hooks:**
- | Hook | Event | Description |
- | ------------------ | ---------------- | ----------------------------------------------- |
- | `context-snapshot` | PreCompact | Preserve context before compaction |
- | `ntfy-notify` | Notification | Free mobile push via [ntfy.sh](https://ntfy.sh) |
- | `discord-notify` | Notification | Discord webhook alerts |
- | `tts-alerts` | Notification | Voice notifications via say/espeak |
- | `rules-injector` | UserPromptSubmit | Auto-inject CLAUDE.md rules |
- | `rate-limiter` | PreToolUse | Limit tool calls per minute |
- | `context-injector` | SessionStart | Inject project context on session start |
- ---
- ## 👤 Author
- Built by [Karan Bansal](https://karanbansal.in), Head of AI at ArmorCode. These hooks are the basis of my OWASP GenAI Summit talk, [Hardening AI Coding Agents with Hooks](https://karanbansal.in/talks/) (slides and recording there).
- I write about Claude Code, MCP, and production agentic AI at [karanbansal.in/blog](https://karanbansal.in/blog/).
- ---
- ## 📄 License
- MIT © [karanb192](https://github.com/karanb192)
plugins/guard-pack/lib/protect-secrets.js · Bundled script · 363 lines · 6 findings marked
- #!/usr/bin/env node
- /**
- * Protect Secrets - PreToolUse Hook for Read|Edit|Write|Bash|Grep
- * Prevents reading, modifying, or exfiltrating sensitive files.
- * Logs to: ~/.claude/hooks-logs/
- *
- * SAFETY_LEVEL: 'critical' | 'high' | 'strict' (default: 'high')
- * critical - SSH keys, AWS creds, .env files only
- * high - + secrets files, env dumps, exfiltration attempts
- * strict - + database configs, any config that might contain secrets
- * Override via HOOK_SAFETY_LEVEL instead of editing this file (plugin updates
- * overwrite installed files). Invalid values fall back to 'high'.
- *
- * Ask mode (opt-in, per level): set HOOK_ASK_CRITICAL / HOOK_ASK_HIGH /
- * HOOK_ASK_STRICT to the literal string "true" in the hook command to have
- * that level prompt the user ("ask") instead of blocking outright ("deny").
- * e.g. "command": "HOOK_ASK_STRICT=true node /path/to/protect-secrets.js"
- *
- * Setup (plugin, recommended):
- * /plugin marketplace add karanb192/claude-code-hooks # once per machine
- * /plugin install protect-secrets@claude-code-hooks
- * The plugin registers this hook automatically; restart Claude Code after install.
- *
- * Classic setup (copy this script somewhere stable) still works, via
- * .claude/settings.json:
- * {
- * "hooks": {
- * "PreToolUse": [{
- * "matcher": "Read|Edit|Write|Bash|Grep",
- * "hooks": [{ "type": "command", "command": "node /path/to/protect-secrets.js" }]
- * }]
- * }
- * }
- */
- const fs = require('fs');
- const path = require('path');
- const os = require('os');
- // A handled tool missing from hooks.json never reaches this guard.
- const HANDLED_TOOLS = ['Read', 'Edit', 'Write', 'Bash', 'Grep'];
- // Safety level: override via HOOK_SAFETY_LEVEL ('critical' | 'high' | 'strict').
- // Anything else (or unset) falls back to the default so a typo can never
- // silently disable the guard.
- const DEFAULT_SAFETY_LEVEL = 'high';
- const SAFETY_LEVEL = ['critical', 'high', 'strict'].includes(process.env.HOOK_SAFETY_LEVEL)
- ? process.env.HOOK_SAFETY_LEVEL
- : DEFAULT_SAFETY_LEVEL;
- // Ask mode per level: if true, prompts the user instead of blocking outright.
- // When ask=true, the hook returns decision "ask" so Claude Code shows the
- // reason and lets the user decide. When ask=false (default), the hook denies.
- // Env overrides: HOOK_ASK_CRITICAL, HOOK_ASK_HIGH, HOOK_ASK_STRICT
- const envBool = (key, fallback) => key in process.env ? process.env[key] === 'true' : fallback;
- Dismissed after review: Copies every environment variable, where API keys and tokens live, in a file that sends data
- Line 55 on GitHub
- const ASK = {
- critical: envBool('HOOK_ASK_CRITICAL', false),
- high: envBool('HOOK_ASK_HIGH', false),
- strict: envBool('HOOK_ASK_STRICT', false),
- };
- // Files explicitly safe to access (templates, examples)
- const ALLOWLIST = [
- /\.env\.example$/i, /\.env\.sample$/i, /\.env\.template$/i,
- /\.env\.schema$/i, /\.env\.defaults$/i, /env\.example$/i, /example\.env$/i,
- ];
- // Sensitive file patterns for Read, Edit, Write tools
- const SENSITIVE_FILES = [
- // CRITICAL
- { level: 'critical', id: 'env-file', regex: /(?:^|\/)\.env(?:\.[^/]*)?$/, reason: '.env file contains secrets' },
- { level: 'critical', id: 'envrc', regex: /(?:^|\/)\.envrc$/, reason: '.envrc (direnv) contains secrets' },
- { level: 'critical', id: 'ssh-private-key', regex: /(?:^|\/)\.ssh\/id_[^/]+$/, reason: 'SSH private key' },
- { level: 'critical', id: 'ssh-private-key-2', regex: /(?:^|\/)(id_rsa|id_ed25519|id_ecdsa|id_dsa)$/, reason: 'SSH private key' },
- { level: 'critical', id: 'ssh-authorized', regex: /(?:^|\/)\.ssh\/authorized_keys$/, reason: 'SSH authorized_keys' },
- { level: 'critical', id: 'aws-credentials', regex: /(?:^|\/)\.aws\/credentials$/, reason: 'AWS credentials file' },
- { level: 'critical', id: 'aws-config', regex: /(?:^|\/)\.aws\/config$/, reason: 'AWS config may contain secrets' },
- { level: 'critical', id: 'kube-config', regex: /(?:^|\/)\.kube\/config$/, reason: 'Kubernetes config contains credentials' },
- { level: 'critical', id: 'pem-key', regex: /\.pem$/i, reason: 'PEM key file' },
- { level: 'critical', id: 'key-file', regex: /\.key$/i, reason: 'Key file' },
- { level: 'critical', id: 'p12-key', regex: /\.(p12|pfx)$/i, reason: 'PKCS12 key file' },
- // HIGH
- { level: 'high', id: 'credentials-json', regex: /(?:^|\/)credentials\.json$/i, reason: 'Credentials file' },
- { level: 'high', id: 'secrets-file', regex: /(?:^|\/)(secrets?|credentials?)\.(json|ya?ml|toml)$/i, reason: 'Secrets configuration file' },
- { level: 'high', id: 'service-account', regex: /service[_-]?account.*\.json$/i, reason: 'GCP service account key' },
- { level: 'high', id: 'gcloud-creds', regex: /(?:^|\/)\.config\/gcloud\/.*(credentials|tokens)/i, reason: 'GCloud credentials' },
- { level: 'high', id: 'azure-creds', regex: /(?:^|\/)\.azure\/(credentials|accessTokens)/i, reason: 'Azure credentials' },
- { level: 'high', id: 'docker-config', regex: /(?:^|\/)\.docker\/config\.json$/, reason: 'Docker config may contain registry auth' },
- { level: 'high', id: 'netrc', regex: /(?:^|\/)\.netrc$/, reason: '.netrc contains credentials' },
- Dismissed after review: Reads a credential file in a script that also sends data over the network
- Line 90 on GitHub
- { level: 'high', id: 'git-credentials', regex: /(?:^|\/)\.git-credentials$/, reason: '.git-credentials stores plaintext tokens' },
- Dismissed after review: Reads a credential file in a script that also sends data over the network
- Line 91 on GitHub
- { level: 'high', id: 'npmrc', regex: /(?:^|\/)\.npmrc$/, reason: '.npmrc may contain auth tokens' },
- Dismissed after review: Reads a credential file in a script that also sends data over the network
- Line 92 on GitHub
- { level: 'high', id: 'pypirc', regex: /(?:^|\/)\.pypirc$/, reason: '.pypirc contains PyPI credentials' },
- Dismissed after review: Reads a credential file in a script that also sends data over the network
- Line 93 on GitHub
- { level: 'high', id: 'gem-creds', regex: /(?:^|\/)\.gem\/credentials$/, reason: 'RubyGems credentials' },
- { level: 'high', id: 'vault-token', regex: /(?:^|\/)(\.vault-token|vault-token)$/, reason: 'Vault token file' },
- { level: 'high', id: 'keystore', regex: /\.(keystore|jks)$/i, reason: 'Java keystore' },
- { level: 'high', id: 'htpasswd', regex: /(?:^|\/)\.?htpasswd$/, reason: 'htpasswd contains hashed passwords' },
- { level: 'high', id: 'pgpass', regex: /(?:^|\/)\.pgpass$/, reason: 'PostgreSQL password file' },
- { level: 'high', id: 'my-cnf', regex: /(?:^|\/)\.my\.cnf$/, reason: 'MySQL config may contain password' },
- // STRICT
- { level: 'strict', id: 'database-config', regex: /(?:^|\/)(?:config\/)?database\.(json|ya?ml)$/i, reason: 'Database config may contain passwords' },
- { level: 'strict', id: 'ssh-known-hosts', regex: /(?:^|\/)\.ssh\/known_hosts$/, reason: 'SSH known_hosts reveals infrastructure' },
- { level: 'strict', id: 'gitconfig', regex: /(?:^|\/)\.gitconfig$/, reason: '.gitconfig may contain credentials' },
- { level: 'strict', id: 'curlrc', regex: /(?:^|\/)\.curlrc$/, reason: '.curlrc may contain auth' },
- ];
- // Delegation sinks: file contents or secret env vars fed to an external model CLI or API host.
- const SINK_CLI = '(?:gemini(?:-cli)?|codex|llm|sgpt|aichat|openai|mods|fabric)';
- // A sink CLI behind env assignments, wrappers (sudo, npx, env, timeout, xargs ...), a path or an npm scope.
- // One lazy run after the first wrapper already spans any later wrappers and
- // assignments; repeating it made `| sudo -n sudo -n ...` exponential.
- const SINK_PREFIX = '(?:^|[|;&(`"\'!\\n]|\\b(?:do|then|else)\\b)\\s*'
- + '(?:[A-Za-z_][A-Za-z0-9_]*=\\S*\\s+)*'
- + '(?:(?:sudo|npx|uvx|bunx|pnpm\\s+dlx|command|time|exec|nice|nohup|env|timeout|xargs)\\b[^;|&\\n]*?\\s+)?'
- + '(?:[^\\s"\';|&]*\\/)?';
- const SINK_END = '(?=[\\s<]|$)';
- const SINK_CMD = SINK_PREFIX + SINK_CLI + SINK_END;
- const sinkCmd = (cli) => SINK_PREFIX + cli + SINK_END;
- // A segment with balanced quotes as opaque units: a name inside a quoted prompt is prose, not an operand.
- const SEG_QA = '(?:[^;|&\\n"\']|"[^"\\n]*"|\'[^\'\\n]*\')*?';
- // Commands whose stdout is the file they are given (ssh -i and kubectl --kubeconfig are not).
- const CONTENT_CMD = '\\b(?:cat|tac|head|tail|bat|more|less|sops|gpg|age|base64|xxd|od|rev|sed|awk|grep|jq|yq|strings|openssl\\s+enc|python3?|node|ruby|perl)\\b';
- const SINK_HOST = '(?:generativelanguage\\.googleapis\\.com|aiplatform\\.googleapis\\.com|api\\.openai\\.com|[\\w.-]+\\.openai\\.azure\\.com|api\\.anthropic\\.com|openrouter\\.ai|api\\.mistral\\.ai|api\\.groq\\.com|api\\.together\\.xyz|api\\.deepseek\\.com|api\\.x\\.ai|api\\.cohere\\.com|api\\.perplexity\\.ai|api\\.fireworks\\.ai|api\\.cerebras\\.ai|router\\.huggingface\\.co|bedrock-runtime(?:-fips)?\\.[\\w-]+\\.amazonaws\\.com|integrate\\.api\\.nvidia\\.com|api\\.deepinfra\\.com)';
- // HTTP clients as a command word, never the https inside a URL.
- const HTTP_CMD = '(?<![\\w:/.-])(?:curl|curlie|wget|https?|xh)(?=\\s)';
- const HTTPIE_CMD = '(?<![\\w:/.-])(?:https?|xh)(?=\\s)';
- // Secret file names come from the critical and high SENSITIVE_FILES entries; .env swaps in a template-excluding variant.
- const FILE_DIR = '["\']?(?:[^\\s"\';|&<>()]*\\/)?';
- const FILE_ANY = '["\']?[^\\s"\';|&<>()]*?';
- const ENV_FILE_NAME = '\\.env(?!\\.(?:example|sample|template|schema|defaults)\\b)(?:\\.[^/\\s"\']*)?(?![\\w.])';
- const PATH_ANCHOR = '(?:^|\\/)';
- function fileNameSource(p) {
- if (p.id === 'env-file') return ENV_FILE_NAME;
- return p.regex.source
- .replace(/^\(\?:\^\|\\\/\)/, '')
- .replace(/\$$/, '')
- .replace(/\((?!\?)/g, '(?:')
- .replace(/\[\^\/\]/g, '[^/\\s"\']')
- .replace(/\.\*/g, '[^\\s"\']*');
- }
- const secretFiles = SENSITIVE_FILES.filter(p => p.level !== 'strict');
- const anchoredNames = secretFiles.filter(p => p.regex.source.startsWith(PATH_ANCHOR)).map(fileNameSource);
- const floatingNames = secretFiles.filter(p => !p.regex.source.startsWith(PATH_ANCHOR)).map(fileNameSource);
- const SECRET_GLOB = '(?:\\.[A-Za-z]{0,3}[*?]|\\.(?:ssh|aws|kube|gnupg|azure|docker|config\\/gcloud)\\/[^\\s"\']*[*?])';
- const SECRET_NAME = '(?:' + FILE_DIR + '(?:' + anchoredNames.join('|') + '|' + SECRET_GLOB + ')|' + FILE_ANY + '(?:' + floatingNames.join('|') + '))(?![A-Za-z0-9])';
- const SECRET_FILE = '(?:^|[\\s"\'=<@(])\\s*' + SECRET_NAME;
- const SECRET_WORD = '(?:SECRETS?|KEY|TOKEN|PASSWORD|PASSWD|PASSW|PASSPHRASE|PASS|CREDENTIALS?|API_KEY|APIKEY|PAT)';
- // Whole name segments, so $AUTHOR and $TOKENS_USED stay clean; AUTH and PRIVATE only as the last segment.
- const SECRET_TAIL = '(?:_(?:ID|FILE|PATH|VALUE|VAL|STR|STRING|B64|BASE64|JSON|PEM|DATA|CONTENT|TEXT|RAW|HEX|PROD|PRODUCTION|DEV|STAGING|TEST|OLD|NEW|[0-9]+))*';
- const SECRET_VAR = '\\$\\{?!?(?:(?:[A-Z0-9]+_)*' + SECRET_WORD + SECRET_TAIL + '|(?:[A-Z0-9]+_)*(?:AUTH|PRIVATE))\\}?(?![A-Za-z0-9_])';
- // Not a heredoc, herestring, process substitution or /dev/*.
- const REDIRECT_IN = '(?<!<)<(?![<(])\\s*(?!\\/dev\\/)';
- // -T as a whole flag: the patterns run case-insensitive, so a bare -T also matches --max-time.
- const UPLOAD_FLAG = '(?:(?<![\\w-])-T(?![A-Za-z0-9-])\\s*|--(?:upload|post|body)-file[=\\s]+)';
- const FILE_BODY = '(?:@|' + REDIRECT_IN + '|\\$\\(\\s*(?:cat|head|tail|<)\\s+|`\\s*(?:cat|head|tail)\\s+|' + UPLOAD_FLAG + ')';
- const SUBST_FILE = '(?:\\$\\(\\s*(?:cat|head|tail|<)\\s+|`\\s*(?:cat|head|tail)\\s+)["\']?[^\\s"\';|&<>()-]';
- const BODY_FLAG = '(?:-d|--data(?:-binary|-raw|-urlencode|-ascii)?|--json|-F|--form(?:-string)?)';
- const API_BODY = '(?:' + BODY_FLAG + '\\s*=?\\s*["\']?(?:[\\w-]+=?)?(?:@|\\$\\(\\s*(?:cat|head|tail|<)\\s+|`\\s*cat\\s+)|' + REDIRECT_IN + '|' + UPLOAD_FLAG + ')';
- const HTTPIE_FILE_ITEM = '\\s(?:[\\w-]+:?=?)?@';
- const HTTPIE_FIELD = '\\s[\\w-]+:?=';
- // Stops at the first $ inside double quotes; a var in a later -H header sits outside the token.
- const BODY_TOKEN = '(?:"[^"$]*|\'[^\']*\'|[^\\s"\'$])*"?';
- // Per CLI: gemini -i is --prompt-interactive and mods -f is --format, so neither is a file flag.
- const CLI_FILE_FLAGS = {
- llm: '-a|--attachment|-f|--fragment|--sf|--system-fragment',
- aichat: '-f|--file',
- codex: '-i|--image',
- fabric: '-a|--attachment',
- openai: '--file',
- };
- const FLAG_ARG = '[\\s=]+["\']?[^\\s"\'-]';
- const FILE_TOKEN = '["\']?[^\\s"\';|&<>()-]';
- const AT_PATH = '(?<![\\w.])@(?=[\\w.~\\/])';
- const SINK_FILE_FLAG = Object.entries(CLI_FILE_FLAGS)
- .map(([cli, flags]) => sinkCmd(cli) + SEG_QA + '\\s(?:' + flags + ')' + FLAG_ARG)
- .concat([sinkCmd('(?:gemini(?:-cli)?|openai)') + '[^;|&\\n]*' + AT_PATH])
- .join('|');
- // A reader with a file operand, so `ps aux | head | llm` is a filter, not a read.
- const READER_CMD = '(?:\\b(?:cat|head|tail|bat|tac|more|less)\\b(?:\\s+-\\S+)*\\s+[^\\s|;&<>-]|\\bgit\\s+(?:diff|show)\\b)';
- // Bash patterns that expose or exfiltrate secrets
- const BASH_PATTERNS = [
- // CRITICAL
- // A word is a run of pieces (quoted span, escape, plain char). Each kind starts with a
- // different character, so a non-match stays linear, and `-F'='` or `".env"` still match.
- { level: 'critical', id: 'grep-env', regex: /\b(grep|rg|egrep|fgrep|ag|awk|gawk)\b(?:\s+(?:'[^']*'|"(?:[^"\\]|\\[\s\S])*"|\\[\s\S]|[^\s|;&"'\\])+)*\s+(?:'[^']*'|"(?:[^"\\]|\\[\s\S])*"|\\[\s\S]|[^\s|;&"'\\])*?(?:'[^']*|"[^"]*)?\.env\b/i, reason: 'Reading .env via text tools exposes secrets' },
- { level: 'critical', id: 'cat-env', regex: /\b(cat|less|head|tail|more|bat|view)\s+[^|;]*\.env\b/i, reason: 'Reading .env file exposes secrets' },
- { level: 'critical', id: 'cat-ssh-key', regex: /\b(cat|less|head|tail|more|bat)\s+[^|;]*(id_rsa|id_ed25519|id_ecdsa|id_dsa|\.pem|\.key)\b/i, reason: 'Reading private key' },
- { level: 'critical', id: 'cat-aws-creds', regex: /\b(cat|less|head|tail|more)\s+[^|;]*\.aws\/credentials/i, reason: 'Reading AWS credentials' },
- // HIGH - Environment exposure
- { level: 'high', id: 'env-dump', regex: /\bprintenv\b|(?:^|[;&|(]\s*)(?:env|set|export|declare\s+-x)\s*(?:$|[;&|)])/, reason: 'Environment dump may expose secrets' },
- { level: 'high', id: 'echo-secret-var', regex: /\becho\b[^;|&]*\$\{?[A-Za-z_]*(?:SECRET|KEY|TOKEN|PASSWORD|PASSW|CREDENTIAL|API_KEY|AUTH|PRIVATE)[A-Za-z_]*\}?/i, reason: 'Echoing secret variable' },
- { level: 'high', id: 'printf-secret-var', regex: /\bprintf\b[^;|&]*\$\{?[A-Za-z_]*(?:SECRET|KEY|TOKEN|PASSWORD|CREDENTIAL|API_KEY|AUTH|PRIVATE)[A-Za-z_]*\}?/i, reason: 'Printing secret variable' },
- { level: 'high', id: 'cat-secrets-file', regex: /\b(cat|less|head|tail|more)\s+[^|;]*(credentials?|secrets?)\.(json|ya?ml|toml)/i, reason: 'Reading secrets file' },
- { level: 'high', id: 'cat-netrc', regex: /\b(cat|less|head|tail|more)\s+[^|;]*\.netrc/i, reason: 'Reading .netrc credentials' },
- Dismissed after review: Reads a credential file in a script that also sends data over the network
- Line 198 on GitHub
- { level: 'high', id: 'source-env', regex: /\bsource\s+[^|;]*\.env\b|(?:^|[;&|]\s*)\.\s+[^|;]*\.env\b|^\.\s+[^|;]*\.env\b/i, reason: 'Sourcing .env loads secrets' },
- { level: 'high', id: 'export-cat-env', regex: /export\s+.*\$\(cat\s+[^)]*\.env/i, reason: 'Exporting secrets from .env' },
- // HIGH - Exfiltration
- { level: 'high', id: 'curl-upload-env', regex: /\bcurl\b[^;|&]*(-d\s*@|-F\s*[^=]+=@|--data[^=]*=@|--data[-a-z]*\s+@|(?<![\w-])-T(?![A-Za-z0-9-])\s*|--upload-file[=\s]+)[^;|&]*(\.env|credentials|secrets|id_rsa|\.pem|\.key)/i, reason: 'Uploading secrets via curl' },
- { level: 'high', id: 'curl-post-secrets', regex: /\bcurl\b[^;|&]*-X\s*POST[^;|&]*[^;|&]*(\.env|credentials|secrets)/i, reason: 'POSTing secrets via curl' },
- { level: 'high', id: 'wget-post-secrets', regex: /\bwget\b[^;|&]*--post-file[^;|&]*(\.env|credentials|secrets)/i, reason: 'POSTing secrets via wget' },
- { level: 'high', id: 'scp-secrets', regex: /\bscp\b[^;|&]*(\.env|credentials|secrets|id_rsa|\.pem|\.key)[^;|&]+:/i, reason: 'Copying secrets via scp' },
- { level: 'high', id: 'rsync-secrets', regex: /\brsync\b[^;|&]*(\.env|credentials|secrets|id_rsa)[^;|&]+:/i, reason: 'Syncing secrets via rsync' },
- { level: 'high', id: 'nc-secrets', regex: /\bnc\b[^;|&]*<[^;|&]*(\.env|credentials|secrets|id_rsa)/i, reason: 'Exfiltrating secrets via netcat' },
- // HIGH - Delegation sinks (secret material into an external model)
- { level: 'high', id: 'model-cli-secret-file', regex: new RegExp(SINK_CMD + SEG_QA + '[\\s<@=(]\\s*' + SECRET_NAME + '|' + SINK_CMD + '[^;|&\\n]*(?:\\$\\(|`)[^`\\n]*?[\\s"\'=<@(]\\s*' + SECRET_NAME + '|' + CONTENT_CMD + '[^;|&\\n]*' + SECRET_FILE + '[^;&\\n]*' + SINK_CMD, 'i'), reason: 'Feeding a secrets file to an external model CLI' },
- { level: 'high', id: 'model-cli-secret-var', regex: new RegExp(SINK_CMD + '[^;|&\\n]*' + SECRET_VAR, 'i'), reason: 'Passing a secret variable to an external model CLI' },
- { level: 'high', id: 'model-api-secret-body', regex: new RegExp(HTTP_CMD + '(?=[^;|&\\n]*' + SINK_HOST + ')' + SEG_QA + '(?:' + API_BODY + SECRET_NAME + '|' + BODY_FLAG + '\\s*=?\\s*' + BODY_TOKEN + SECRET_VAR + ')|' + HTTPIE_CMD + '(?=[^;|&\\n]*' + SINK_HOST + ')' + SEG_QA + '(?:' + HTTPIE_FILE_ITEM + SECRET_NAME + '|' + HTTPIE_FIELD + BODY_TOKEN + SECRET_VAR + ')', 'i'), reason: 'Sending secrets to a model API endpoint' },
- // HIGH - Copy/move/delete secrets
- { level: 'high', id: 'cp-env', regex: /\bcp\b[^;|&]*\.env\b/i, reason: 'Copying .env file' },
- { level: 'high', id: 'cp-ssh-key', regex: /\bcp\b[^;|&]*(id_rsa|id_ed25519|\.pem|\.key)\b/i, reason: 'Copying private key' },
- { level: 'high', id: 'mv-env', regex: /\bmv\b[^;|&]*\.env\b/i, reason: 'Moving .env file' },
- { level: 'high', id: 'rm-ssh-key', regex: /\brm\b[^;|&]*(id_rsa|id_ed25519|id_ecdsa|authorized_keys)/i, reason: 'Deleting SSH key' },
- { level: 'high', id: 'rm-env', regex: /\brm\b.*\.env\b/i, reason: 'Deleting .env file' },
- { level: 'high', id: 'rm-aws-creds', regex: /\brm\b[^;|&]*\.aws\/credentials/i, reason: 'Deleting AWS credentials' },
- { level: 'high', id: 'truncate-secrets', regex: /\btruncate\b.*\.(env|pem|key)\b|(?:^|[;&|]\s*)>\s*\.env\b/i, reason: 'Truncating secrets file' },
- // HIGH - Process environ
- { level: 'high', id: 'proc-environ', regex: /\/proc\/[^/]*\/environ/, reason: 'Reading process environment' },
- { level: 'high', id: 'xargs-cat-env', regex: /xargs.*cat|\.env.*xargs/i, reason: 'Reading .env via xargs' },
- { level: 'high', id: 'find-exec-cat-env', regex: /find\b.*\.env.*-exec|find\b.*-exec.*(cat|less)/i, reason: 'Finding and reading .env files' },
- // STRICT
- { level: 'strict', id: 'grep-password', regex: /\bgrep\b[^|;]*(-r|--recursive)[^|;]*(password|secret|api.?key|token|credential)/i, reason: 'Grep for secrets may expose them' },
- { level: 'strict', id: 'base64-secrets', regex: /\bbase64\b[^|;]*(\.env|credentials|secrets|id_rsa|\.pem)/i, reason: 'Base64 encoding secrets' },
- // STRICT - Delegation sinks (any file contents into an external model)
- { level: 'strict', id: 'model-cli-file-input', regex: new RegExp(READER_CMD + '[^;&\\n]*' + SINK_CMD + '|' + SINK_CMD + SEG_QA + REDIRECT_IN + FILE_TOKEN + '|' + SINK_CMD + '[^;|&\\n]*' + SUBST_FILE + '|' + SINK_FILE_FLAG, 'i'), reason: 'Piping file contents to an external model CLI' },
- { level: 'strict', id: 'model-api-file-body', regex: new RegExp(HTTP_CMD + '(?=[^;|&\\n]*' + SINK_HOST + ')' + SEG_QA + API_BODY + FILE_TOKEN + '|' + HTTPIE_CMD + '(?=[^;|&\\n]*' + SINK_HOST + ')' + SEG_QA + HTTPIE_FILE_ITEM + '[\\w.~\\/]|' + READER_CMD + '[^;&\\n]*' + HTTP_CMD + '(?=[^;|&\\n]*' + SINK_HOST + ')', 'i'), reason: 'Sending file contents to a model API endpoint' },
- ];
- const LEVELS = { critical: 1, high: 2, strict: 3 };
- const EMOJIS = { critical: '🔐', high: '🛡️', strict: '⚠️' };
- const LOG_DIR = path.join(process.env.HOME || process.env.USERPROFILE || os.homedir(), '.claude', 'hooks-logs');
- function log(data) {
- try {
- if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
- const file = path.join(LOG_DIR, `${new Date().toISOString().slice(0, 10)}.jsonl`);
- fs.appendFileSync(file, JSON.stringify({ ts: new Date().toISOString(), hook: 'protect-secrets', ...data }) + '\n');
- } catch {}
- }
- // Normalize tool paths only; backslashes in Bash commands can be shell escapes.
- function toPosixPath(filePath) {
- return typeof filePath === 'string' ? filePath.replace(/\\/g, '/') : filePath;
- }
- function isAllowlisted(filePath) {
- const target = toPosixPath(filePath);
- return target && ALLOWLIST.some(p => p.test(target));
- }
- function checkFilePath(filePath, safetyLevel = SAFETY_LEVEL) {
- const target = toPosixPath(filePath);
- if (!target || isAllowlisted(target)) return { blocked: false, pattern: null };
- const threshold = LEVELS[safetyLevel] || 2;
- for (const p of SENSITIVE_FILES) {
- if (LEVELS[p.level] <= threshold && p.regex.test(target)) {
- return { blocked: true, pattern: p };
- }
- }
- return { blocked: false, pattern: null };
- }
- function checkBashCommand(cmd, safetyLevel = SAFETY_LEVEL) {
- if (!cmd) return { blocked: false, pattern: null };
- cmd = cmd.replace(/\\\r?\n\s*/g, ' ');
- // Mask each allowlisted file name on its own; matching the allowlist against
- // the whole string let `cat .env # .env.example` through. The directory is
- // kept, so $SECRET_KEY/.env.example is still seen, except that a plain
- // segment's `.env` (my.env/) is defused; a $ in the name is not a template.
- cmd = cmd.replace(/[^\s"'`=@<>;|&()]+/g, token => {
- // An scp remote with no slash (host:.env.example) keeps its colon in the directory part.
- const dir = token.slice(0, Math.max(token.lastIndexOf('/'), token.lastIndexOf(':')) + 1);
- if (token.slice(dir.length).includes('$') || !isAllowlisted(token)) return token;
- // Only `.env` in a plain segment is defused; hosts (api.openai.com/), scp
- // remotes (host:) and variables stay visible to the other rules.
- return dir.split('/').map(seg => seg.includes('$') ? seg : seg.replace(/\.env/gi, '_env')).join('/') + 'allowlisted-template';
- });
- const threshold = LEVELS[safetyLevel] || 2;
- for (const p of BASH_PATTERNS) {
- if (LEVELS[p.level] <= threshold && p.regex.test(cmd)) {
- return { blocked: true, pattern: p };
- }
- }
- return { blocked: false, pattern: null };
- }
- function check(toolName, toolInput, safetyLevel = SAFETY_LEVEL) {
- if (toolName === 'Grep') {
- const searchPath = typeof toolInput?.path === 'string' ? toPosixPath(toolInput.path) : '';
- const filters = [toolInput?.glob, toolInput?.include]
- .filter(value => typeof value === 'string' && value.length > 0)
- .map(toPosixPath);
- // A directory and filter can form a sensitive path, such as .aws + credentials.
- const candidates = [searchPath, ...filters, ...filters.map(filter => searchPath.replace(/\/+$/, '') + '/' + filter)];
- const matches = candidates.map(candidate => checkFilePath(candidate, safetyLevel))
- .filter(result => result.blocked);
- matches.sort((a, b) => LEVELS[a.pattern.level] - LEVELS[b.pattern.level]);
- return matches[0] || { blocked: false, pattern: null };
- }
- if (['Read', 'Edit', 'Write'].includes(toolName)) {
- return checkFilePath(toolInput?.file_path, safetyLevel);
- }
- if (toolName === 'Bash') {
- return checkBashCommand(toolInput?.command, safetyLevel);
- }
- return { blocked: false, pattern: null };
- }
- async function main() {
- let input = '';
- for await (const chunk of process.stdin) input += chunk;
- try {
- const data = JSON.parse(input);
- const { tool_name, tool_input, session_id, cwd, permission_mode } = data;
- if (!HANDLED_TOOLS.includes(tool_name)) {
- return console.log('{}');
- }
- const result = check(tool_name, tool_input);
- if (result.blocked) {
- const p = result.pattern;
- const shouldAsk = ASK[p.level] === true;
- const decision = shouldAsk ? 'ask' : 'deny';
- const target = tool_input?.file_path || tool_input?.command?.slice(0, 100);
- log({ level: shouldAsk ? 'ASK' : 'BLOCKED', id: p.id, priority: p.level, decision, tool: tool_name, target, session_id, cwd, permission_mode });
- const action = { Read: 'read', Edit: 'modify', Write: 'write to', Bash: 'execute', Grep: 'search' }[tool_name];
- return console.log(JSON.stringify({
- hookSpecificOutput: {
- hookEventName: 'PreToolUse',
- permissionDecision: decision,
- permissionDecisionReason: `${EMOJIS[p.level]} [${p.id}] Cannot ${action}: ${p.reason}`
- }
- }));
- }
- console.log('{}');
- } catch (e) {
- log({ level: 'ERROR', error: e.message });
- console.log('{}');
- }
- }
- if (require.main === module) {
- main();
- } else {
- module.exports = {
- SENSITIVE_FILES, BASH_PATTERNS, ALLOWLIST, LEVELS, SAFETY_LEVEL, ASK,
- HANDLED_TOOLS,
- check, checkFilePath, checkBashCommand, isAllowlisted, toPosixPath,
- };
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.