Protected Files Guard Hook
Prevents Claude from modifying sensitive files like .env, lock files, and .git/ directories. Uses a PreToolUse hook that intercepts Edit and Write operations and blocks them with exit code 2 if the target matches any protected pattern. Essential for production safety.
Hook Type
PreToolUse -- Fires before Claude executes Edit, Write, or Bash tools.
Description
This hook acts as a file-level access control layer. Before any file modification, it checks the target path against a configurable list of protected patterns. If a match is found, the operation is blocked (exit code 2) and Claude is informed why. This prevents accidental modification of environment files, lock files, CI configs, and version control internals.
Patterns/Rules
Default protected patterns:
.env/.env.*-- Environment variables and secretspackage-lock.json/yarn.lock/pnpm-lock.yaml-- Dependency lock files.git/-- Git internals*.pem/*.key-- SSL certificates and private keys.github/workflows/-- CI/CD pipeline definitions
You can customize the PROTECTED_PATTERNS array in the script.
Configuration
Hook Script (scripts/protect-files.sh)
#!/bin/bash # protect-files.sh -- Block modifications to sensitive files # Exit code 2 = block the tool use INPUT=$(cat) FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.command // empty') # Skip if no file path detected [ -z "$FILE_PATH" ] && exit 0 # Configurable protected patterns PROTECTED_PATTERNS=( ".env" ".env.*" "package-lock.json" "yarn.lock" "pnpm-lock.yaml" ".git/" ".pem" ".key" ".github/workflows/" ) for pattern in "${PROTECTED_PATTERNS[@]}"; do if [[ "$FILE_PATH" == *"$pattern"* ]]; then echo "BLOCKED: Cannot modify '$FILE_PATH' -- matches protected pattern '$pattern'" >&2 echo "To override, temporarily remove this pattern from scripts/protect-files.sh" >&2 exit 2 fi done exit 0
Settings Configuration
{ "hooks": { "PreToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "bash ./scripts/protect-files.sh" } ] } ] } }
Action
Before any Edit or Write tool call:
- The hook receives the tool input as JSON on stdin
- Extracts the
file_pathfield - Checks against all protected patterns
- If matched: prints a descriptive message to stderr and exits with code 2 (blocks the operation)
- If no match: exits with code 0 (allows the operation)
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Pre-Commit Security Scanner
Pre-commit hook that scans staged files for hardcoded secrets, API keys, passwords, and sensitive data patterns before allowing commits.
Agents Md Watcher
Streamline your workflow with this automatically, loads, agents, configuration. Includes structured workflows, validation checks, and reusable patterns for automation.
Automated Build Inspector
Boost productivity using this automatically, trigger, build, processes. Includes structured workflows, validation checks, and reusable patterns for automation.