DEV Community

Vildanden
Vildanden

Posted on

Flag a sensitive permission ask in Claude Code with a PermissionRequest hook

A shell allow-list and a PreToolUse write guard can already keep Claude Code off .env files and private keys. Permission prompts are a second path. When the model asks to read or edit a sensitive path, a tired "always allow" click can bypass those guards. A small PermissionRequest hook can flag those asks so they stay a human decision.

The hook should name the sensitive path class and exit 2.

The hook

Save this as .claude/hooks/flag_sensitive_permission.py and make it executable:

#!/usr/bin/env python3
import json
import re
import sys

try:
    event = json.load(sys.stdin)
except json.JSONDecodeError:
    sys.exit(0)

def collect(value, parts):
    if isinstance(value, dict):
        for item in value.values():
            collect(item, parts)
    elif isinstance(value, list):
        for item in value:
            collect(item, parts)
    elif value is not None:
        parts.append(str(value))

parts = []
collect(event, parts)
text = "\n".join(parts)

# .env, private keys, wallets, and common credential filenames
if re.search(
    r"(?i)(\.env(?:\.|\b)|private.?key|wallet|seed phrase|mnemonic|id_rsa|credentials?|\.pem\b|\.p12\b|\.pfx\b)",
    text,
):
    print("PermissionRequest: this ask touches a sensitive-looking path. Review it yourself and offer a redacted alternative.")
    sys.exit(2)
Enter fullscreen mode Exit fullscreen mode

Wire it in .claude/settings.json under PermissionRequest with command set to python3 .claude/hooks/flag_sensitive_permission.py. Check the hooks page for your installed Claude Code version; payload fields can change between releases. The script walks the JSON rather than assuming one field name.

Why this beats a pasted prompt

"Ask me before touching .env" in CLAUDE.md only works when the model remembers it, and when you are paying attention to the prompt. A PermissionRequest hook runs when Claude Code is already asking for access, so a sensitive path cannot slip through as a habitual approval. If the file really must be read, open it yourself and paste a redacted excerpt — do not let the agent load the secret file.

Tips

  • Keep the hook local, fast, and free of network calls.
  • Pair it with PreToolUse write and Bash guards so secret-file reads, writes, and permission asks are all blocked.
  • Do not print the event payload or the matched path. The message above names the class of file, not the value.
  • If a docs fixture or an example filename trips the hook, tighten the regex rather than deleting it.

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)