P

Protected Files Guard Hook

Prevents Claude from writing to sensitive files like .env, credentials, lock files, and CI configs. Acts as a safety net that blocks writes to protected paths before they happen.

HookCommunitysecurityv1.0.0MIT
0 views0 copies

Hook Type

PreToolUse -- Runs before Write and Edit tool calls to validate the target file path.

Description

This hook intercepts file write operations and blocks them if the target path matches a protected pattern. It prevents accidental modification of environment files, credentials, lock files, CI configurations, and other sensitive files that should only be edited manually.

Patterns/Rules

Protected by Default

PatternReason
.env*Environment variables and secrets
*.pem, *.key, *.certTLS certificates and private keys
credentials.*, secrets.*Credential files
package-lock.json, yarn.lock, pnpm-lock.yamlLock files (should be generated, not edited)
.github/workflows/*CI/CD pipelines
docker-compose.prod.*Production deployment configs
.claude/settings.jsonClaude's own configuration

Configurable

  • Add custom patterns in the script's PROTECTED_PATTERNS array
  • Use glob patterns for flexible matching
  • Supports allowlisting specific files within protected directories

Configuration

Add to .claude/settings.json:

{ "hooks": { "PreToolUse": [ { "matcher": "(Write|Edit)", "hooks": [ { "type": "command", "command": ".claude/hooks/protect-files.sh \"$CLAUDE_FILE_PATH\"" } ] } ] } }

Action

Guard script (.claude/hooks/protect-files.sh):

#!/bin/bash # Block writes to sensitive files FILE_PATH="$1" if [ -z "$FILE_PATH" ]; then exit 0 fi # Protected patterns -- customize as needed PROTECTED_PATTERNS=( ".env" ".env.*" "*.pem" "*.key" "*.cert" "*.p12" "credentials.*" "secrets.*" "**/secrets/**" "package-lock.json" "yarn.lock" "pnpm-lock.yaml" "Gemfile.lock" "poetry.lock" "composer.lock" ".github/workflows/*" ".gitlab-ci.yml" "docker-compose.prod.*" ".claude/settings.json" "id_rsa*" "id_ed25519*" ) BASENAME=$(basename "$FILE_PATH") for pattern in "${PROTECTED_PATTERNS[@]}"; do # Check against full path and basename if [[ "$FILE_PATH" == $pattern ]] || [[ "$BASENAME" == $pattern ]]; then echo "BLOCKED: Cannot write to protected file: $FILE_PATH" echo "Pattern matched: $pattern" echo "Edit this file manually if changes are needed." exit 2 # Non-zero exit blocks the tool call fi done exit 0

Behavior

  • Exit 0: File is not protected, write proceeds normally
  • Exit 2: File is protected, write is blocked with an explanation
  • Claude sees the block message and can explain why the file is protected
Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates