DEV Community

Vildanden
Vildanden

Posted on

Stop yourself from pasting a private key into Claude Code with a UserPromptSubmit hook

Deny rules and write guards protect files on disk. They do nothing if you paste a private key, seed phrase, or API token into the prompt itself. A UserPromptSubmit hook can catch that shape before the model ever sees it.

The hook

Save this as .claude/hooks/block-secret-prompts.sh and make it executable (chmod +x):

#!/usr/bin/env bash
# Reads the hook event as JSON on stdin; exit code 2 blocks the prompt.
text=$(jq -r '.prompt // .user_prompt // .content // empty')

if echo "$text" | grep -Eq '-----BEGIN .*PRIVATE KEY-----'; then
  echo "Blocked: that prompt looks like it contains a PEM private key. Use a redacted fixture or a secret manager instead." >&2
  exit 2
fi

if echo "$text" | grep -Eiq '\b(seed phrase|mnemonic|private key)\b.{0,80}\b(is|here|below|follows|:)\b|\b(api[_-]?key|access[_-]?token|secret[_-]?key)\s*[:=]\s*\S{16,}'; then
  echo "Blocked: that prompt looks like it may contain a credential or wallet secret. Redact it before retrying." >&2
  exit 2
fi
exit 0
Enter fullscreen mode Exit fullscreen mode

Register it in .claude/settings.json:

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [{ "type": "command", "command": ".claude/hooks/block-secret-prompts.sh" }]
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

What happens

When the hook exits with code 2, Claude Code should reject the prompt and show the stderr message. The model never receives the pasted material, so it cannot repeat or store it in the transcript.

Tips

  • This is a pattern match, not a vault. It will miss unusual encodings, and it may flag a sentence that only talks about a private key. Tune the patterns for your team.
  • Pair it with Read deny rules and a PreToolUse write guard so secrets stay out of files as well as prompts.
  • Test with a fake -----BEGIN EXAMPLE PRIVATE KEY----- block or a dummy API_KEY=aaaaaaaaaaaaaaaa, never a real secret.
  • Commit the hook so every teammate gets the same guardrail.

Want the rest of the setup?

I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/

Top comments (0)