Block Secrets Before They're Committed

Runs before Claude Code's Bash tool executes. If the command is a `git commit`, it scans the staged diff for common secret shapes — AWS keys, private key headers, Anthropic/OpenAI/Stripe-style API keys, GitHub tokens, and generic `password=`/`secret=` assignments — and blocks the commit (exit code 2) if one matches, feeding the reason back to Claude so it can fix the file instead of just retrying blindly.

Secrets & Credentials Event: PreToolUse Claude Code Open source · Free

1. Save this as the hook script

#!/usr/bin/env python3
"""PreToolUse hook — blocks a git commit if the staged diff contains a likely secret.
Wire this to the Bash matcher so it runs before every shell command Claude Code executes."""
import json, re, subprocess, sys

data = json.load(sys.stdin)
command = (data.get("tool_input") or {}).get("command", "")

if not re.search(r"git\s+commit", command):
    sys.exit(0)  # not a commit — nothing to check

SECRET_PATTERNS = [
    r"AKIA[0-9A-Z]{16}",                        # AWS access key
    r"-----BEGIN (RSA|OPENSSH|EC) PRIVATE KEY-----",
    r"sk-(ant|proj|live)-[A-Za-z0-9_-]{20,}",   # Anthropic / OpenAI / Stripe-style secret keys
    r"ghp_[A-Za-z0-9]{36}",                      # GitHub personal access token
    r"(?i)(api[_-]?key|secret|password)\s*[=:]\s*['\"][^'\"]{8,}['\"]",
]

try:
    diff = subprocess.run(["git", "diff", "--cached"], capture_output=True, text=True, timeout=10).stdout
except Exception:
    sys.exit(0)  # fail open rather than block on an unrelated git error

for pattern in SECRET_PATTERNS:
    match = re.search(pattern, diff)
    if match:
        print(f"BLOCKED: staged diff matches secret pattern `{pattern}` near: {match.group()[:20]}...", file=sys.stderr)
        print("Unstage the file or remove the secret before committing.", file=sys.stderr)
        sys.exit(2)  # exit 2 = block the tool call, message goes back to Claude

sys.exit(0)

Save to a path inside your project, e.g. .claude/hooks/block-secrets-before-commit.sh, then chmod +x it.

2. Wire it into .claude/settings.json

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {"type": "command", "command": "python3 .claude/hooks/block-secrets-before-commit.py"}
        ]
      }
    ]
  }
}

Before you use this

A hook runs with your local shell's permissions — review the script above before adding it, the same way you'd review any script you didn't write yourself. See our guide on hook security risks for the specific CVEs this category of feature has already produced.

Related hooks

← All hooks
FEEDBACK