import json
import sys
import os
def is_sensitive_file(file_path):
sensitive_patterns = [
'.env',
'package-lock.json',
'yarn.lock',
'Gemfile.lock',
'Cargo.lock',
'.git/',
'config/',
'secrets/',
'credentials',
'password',
'private',
'secret',
'token',
'key'
]
lower_path = file_path.lower()
for pattern in sensitive_patterns:
if pattern in lower_path:
if pattern == 'config/' and 'config/' in lower_path and 'config/' in os.path.dirname(file_path) + '/':
return True
elif pattern in ['password', 'secret', 'token', 'key']:
filename = os.path.basename(file_path)
if pattern in filename.lower():
return True
elif pattern in ['.env', 'package-lock.json', 'yarn.lock', 'Gemfile.lock', 'Cargo.lock']:
if os.path.basename(file_path).lower() == pattern:
return True
elif pattern == '.git/':
if '.git/' in lower_path:
return True
else:
return True
return False
try:
input_data = json.load(sys.stdin)
file_path = input_data.get('tool_input', {}).get('file_path', '')
if is_sensitive_file(file_path):
print(f"Blocked modification of sensitive file: {file_path}", file=sys.stderr)
sys.exit(2) else:
print(f"File {file_path} is not sensitive, allowing operation")
except Exception as e:
print(f"Error in file protection hook: {e}", file=sys.stderr)
sys.exit(0)