Detect a Pasted Credential in a Prompt

A surprisingly common real leak path: a human pastes an error message or a config snippet into chat to ask for help, and it still has a live API key in it. This catches it before the prompt (and the secret inside it) ever reaches the model or gets written into the transcript file.

Prompt & Input Safety Event: UserPromptSubmit Claude Code Open source · Free

1. Save this as the hook script

#!/usr/bin/env python3
"""UserPromptSubmit hook — blocks a prompt containing a secret-shaped
string."""
import json, re, sys

data = json.load(sys.stdin)
prompt = data.get("user_prompt", "")

PATTERNS = [r"AKIA[0-9A-Z]{16}", r"sk-(ant|proj|live)-[A-Za-z0-9_-]{20,}",
            r"ghp_[A-Za-z0-9]{36}", r"-----BEGIN (RSA|OPENSSH|EC) PRIVATE KEY-----"]

for p in PATTERNS:
    if re.search(p, prompt):
        print(f"BLOCKED: your prompt matches secret pattern `{p}`. Remove it "
              f"and resubmit — it would otherwise be written into the transcript.", file=sys.stderr)
        sys.exit(2)

sys.exit(0)

Save to a path inside your project, e.g. .claude/hooks/detect-pasted-credential-in-prompt.sh, then chmod +x it.

2. Wire it into .claude/settings.json

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {"type": "command", "command": "python3 .claude/hooks/detect-pasted-credential-in-prompt.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