spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

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