validate-write.sh 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/bin/bash
  2. # Example PreToolUse hook for validating Write/Edit operations
  3. # This script demonstrates file write validation patterns
  4. set -euo pipefail
  5. # Read input from stdin
  6. input=$(cat)
  7. # Extract file path and content
  8. file_path=$(echo "$input" | jq -r '.tool_input.file_path // empty')
  9. # Validate path exists
  10. if [ -z "$file_path" ]; then
  11. echo '{"continue": true}' # No path to validate
  12. exit 0
  13. fi
  14. # Check for path traversal
  15. if [[ "$file_path" == *".."* ]]; then
  16. echo '{"hookSpecificOutput": {"permissionDecision": "deny"}, "systemMessage": "Path traversal detected in: '"$file_path"'"}' >&2
  17. exit 2
  18. fi
  19. # Check for system directories
  20. if [[ "$file_path" == /etc/* ]] || [[ "$file_path" == /sys/* ]] || [[ "$file_path" == /usr/* ]]; then
  21. echo '{"hookSpecificOutput": {"permissionDecision": "deny"}, "systemMessage": "Cannot write to system directory: '"$file_path"'"}' >&2
  22. exit 2
  23. fi
  24. # Check for sensitive files
  25. if [[ "$file_path" == *.env ]] || [[ "$file_path" == *secret* ]] || [[ "$file_path" == *credentials* ]]; then
  26. echo '{"hookSpecificOutput": {"permissionDecision": "ask"}, "systemMessage": "Writing to potentially sensitive file: '"$file_path"'"}' >&2
  27. exit 2
  28. fi
  29. # Approve the operation
  30. exit 0