Skip to content

Instantly share code, notes, and snippets.

@tebeka
Last active June 1, 2026 13:53
Show Gist options
  • Select an option

  • Save tebeka/b9c197ad5393e348e938498e7984fb26 to your computer and use it in GitHub Desktop.

Select an option

Save tebeka/b9c197ad5393e348e938498e7984fb26 to your computer and use it in GitHub Desktop.
Disallow Claude from Reading Secrets

Disallowing Claude from Reading Secrets

There are files you don't want your agnet to read, especially ones with secrets in them. Here's how you can prevent it:

PreToolUse Hook

In ~/.claude/settings.json (or in the project directory .claude/settings.json)

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read|Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "python ~/.claude/hooks/block_env_files.py"
          }
        ]
      }
    ],
...

block_env_files.py

You can probably do it with shell and jq, but I find this nicer. Claude passes the data to the hook in JSON over stdin.

#!/usr/bin/env python

import json
import sys
from pathlib import Path


def is_secret(file_path: Path):
    path = Path(file_path)
    if path.name in {'.env', '.envrc'}:
        return True

    return path.match('.env.*')


data = json.load(sys.stdin)
file_path = data.get('tool_input', {}).get('file_path', '')
if file_path and is_secret(file_path):
    msg = {
        'continue': False,
        'stopReason': f'Blocked: reading {file_path} is not allowed',
    }
    print(json.dumps(msg))
@alexandear

Copy link
Copy Markdown

The script has a few gaps:

  • Does not block common variants .env.local, .env.dev, .env.prod, etc.
  • Does not block *.env patterns (e.g., backend.env)

We could extend the check to fix the issues:

name = Path(file_path).name
if name in {'.env', '.envrc'} or name.startswith('.env.') or name.endswith('.env'):

@tebeka

tebeka commented Jun 1, 2026

Copy link
Copy Markdown
Author

Thanks @alexandear ! Updated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment