Bảo vệ file .env
Hai lớp giữ bí mật trong .env khỏi Claude. Quy tắc deny trong permissions chặn các công cụ đọc và sửa những file bí mật thường gặp (.env, .env.local, .env.production…); hook chặn thêm các lệnh Bash nhắc tới chúng như cat hay source. File .env.example vẫn đọc được.
Đã thử với Claude Code 2.1.329
.claude/hooks/protect-env.sh
#!/bin/bash
# Blocks Bash commands that touch a .env file (but not .env.example). Exit 2 = block.
cmd=$(jq -r '.tool_input.command // empty')
[ -z "$cmd" ] && exit 0
cleaned=$(echo "$cmd" | sed -E 's/\.env\.(example|sample|template)//g')
if echo "$cleaned" | grep -Eq '(^|[[:space:]/"'\''=<>])\.env([.][A-Za-z0-9_-]+)?([[:space:]"'\'';|&>]|$)'; then
echo "Blocked: this command touches a .env file, which holds secrets. Use .env.example to see which variables exist." >&2
exit 2
fi
exit 0
.claude/settings.json
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./**/.env)",
"Read(./.env.local)",
"Read(./.env.*.local)",
"Read(./.env.production)",
"Read(./.env.development)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-env.sh"
}
]
}
]
}
}
Lưu ý
- Cần cài jq. Chạy `chmod +x .claude/hooks/protect-env.sh` một lần.
- Không lớp nào chặn được tuyệt đối, ví dụ một script tự đọc .env bên trong. Đừng để bí mật thật của production trên máy dev.
- Nếu `.claude/settings.json` đã có `permissions` hoặc `hooks`, hãy gộp vào thay vì ghi đè.
- Quy tắc deny luôn thắng allow, nên không dùng `Read(./.env.*)`: nó chặn cả .env.example. Thêm tên file bí mật khác của bạn vào danh sách deny.