P

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.

HookAnthropicsecurityv1.0.0MIT
0 views0 copies

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 secrets
  • package-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:

  1. The hook receives the tool input as JSON on stdin
  2. Extracts the file_path field
  3. Checks against all protected patterns
  4. If matched: prints a descriptive message to stderr and exits with code 2 (blocks the operation)
  5. If no match: exits with code 0 (allows the operation)
Community

Reviews

Write a review

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

Similar Templates