Progress will not be saved. This browser is blocking storage (often private browsing). You can still learn, but closing the tab loses your progress.
Practice needs JavaScript. The reading works without it.Back to the reading
The main tool is PreToolUse: the hook runs before the tool does, and can refuse. There are two ways to refuse:
- Exit 2, with the reason on stderr (as in lesson 6.2).
- Exit 0 and print JSON with
permissionDecision: "deny"and apermissionDecisionReason. Claude Code cancels the call and passes the reason to Claude.
What makes protective hooks stronger than anything so far:
- When a hook refuses, an allow rule can't rescue the call. In our test we pre-approved
Bash(rm *), andrm -rfwas still blocked. - The docs say a hook's
denyholds in every permission mode, includingbypassPermissions, becausePreToolUseruns before any mode check. We didn't test this part: the safety tooling of our test session itself refused to run Claude with permissions bypassed, and we didn't look for a way around it.
Create .claude/hooks/block-rm.sh:
#!/bin/bash
# PreToolUse (Bash): refuse recursive force deletes such as rm -rf, rm -fr, rm -r -f
CMD=$(jq -r '.tool_input.command // empty')
if echo "$CMD" | grep -Eq '(^|[;&|(`[:space:]])rm[[:space:]]+([^;&|]*[[:space:]])?(-[[:alnum:]]*[rR][[:alnum:]]*f|-[[:alnum:]]*f[[:alnum:]]*[rR]|(-[rR]|--recursive)[[:space:]]+([^;&|]*[[:space:]])?(-f|--force)|(-f|--force)[[:space:]]+([^;&|]*[[:space:]])?(-[rR]|--recursive))([[:space:]]|$)'; then
jq -n '{hookSpecificOutput: {hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: "rm -rf is blocked in this project. Delete specific files, or ask the user to run it."}}'
fi
exit 0The pattern is long because rm -rf can be written many ways. We tested each form by hand with sample JSON:
- Blocked:
rm -rf,rm -fr,rm -Rf,rm -r -f,rm --recursive --force,cd x && rm -rf . - Allowed:
rm -r build,rm file.txt,npm test,echo 'rm -rf' > notes.txt - Over-blocked:
git rm -rf --cached x. Blocking a rare command too many is better than letting a dangerous one through.
Notice the reason text: it points Claude to the right path. When we asked "delete tmp-build with rm -rf", the hook blocked it, and Claude did exactly what the reason said: it deleted the files by name and didn't look for a way around. A good reason turns a block into guidance.
The docs have a protect-files.sh example that blocks Edit and Write on .env, and they say plainly that Claude can still write it with shell commands. So todo-api's script checks Bash too. Create .claude/hooks/protect-env.sh:
#!/bin/bash
# PreToolUse (Edit|Write|Bash): never write to .env files; .env.example is fine
INPUT=$(cat)
is_secret() {
local name; name=$(basename "$1")
[[ "$name" == .env || ( "$name" == .env.* && "$name" != .env.example ) ]]
}
block() {
echo "Blocked: $1 holds secrets and is never written by Claude. Tell the user which variable to set instead." >&2
exit 2
}
if [ "$(echo "$INPUT" | jq -r '.tool_name')" = "Bash" ]; then
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
# the target of >, >>, tee, sed -i, cp or mv, when it looks like a .env file
for T in $(echo "$CMD" | grep -Eo '(>>?|tee( -a)?|sed -i[^ ]*|cp|mv)[[:space:]]*([^;&|]*[[:space:]])?[^[:space:];&|]*\.env[[:alnum:]._-]*' | awk '{print $NF}'); do
is_secret "${T##*>}" && block "${T##*>}"
done
exit 0
fi
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
is_secret "$FILE" && block "$(basename "$FILE")"
exit 0Our first version had a bug: the exception for .env.example applied to the whole command, so cp .env.example .env slipped through, because the command contained .env.example. The version above checks the name of each write target, blocking >> .env, tee -a .env, sed -i … .env and cp … .env, while still allowing writes to .env.example. The lesson: test scripts with near misses, not just the obvious cases.
When we tried it with Claude, the Edit to .env was blocked, and Claude told the user which line to add instead of trying the shell.
That same test showed something important: before trying to edit, Claude had read .env twice, once with cat and once with Read, and the key's value was already in its context. The hook only blocks writes; reading is a different matter.
Blocking reads doesn't need a hook: use deny rules in .claude/settings.json:
"permissions": {
"deny": ["Read(./.env)", "Read(./.env.*)", "Read(!.env.example)"]
}Read(./.env)blocks Claude's file-reading tools. According to the docs it also covers Bash commands Claude Code can analyse, such ascat,head,tailandsed, and it blocks Edit and Write on the same file too.Read(!.env.example)is a.gitignore-style exception: the sample file stays readable.
In our test, Read on .env was refused while .env.example stayed readable. Asked directly to "run cat .env", Claude Code refused even with an allow rule for Bash(cat *), because deny always beats allow. The secret value appeared zero times in the session log.
Both the hooks and the rules above look at the command text, so there are routes they can't see:
- A Python or Node script that opens the file itself, such as
node -e "fs.writeFileSync('.env', …)". - A read that never names the file:
grep -r KEY .run in the folder that holds.env. - Deleting another way:
find . -delete, or a command that's encoded and decoded at run time.
The docs are clear: Read/Edit rules don't apply to subprocesses that read or write files themselves; for enforcement at the operating-system level, turn on the sandbox. They also note that the if field is only a best-effort filter.
So what are protective hooks for? They stop common mistakes: Claude in a hurry, Claude misreading a request, Claude following an issue with malicious text as in lesson 5.3. They are not a wall against someone determined. Stack your layers: a minimal token (level 5), deny rules, hooks, the sandbox when needed, and you reading carefully before you approve.
Put together in .claude/settings.json, next to the hooks from lesson 6.2:
{
"permissions": {
"deny": ["Read(./.env)", "Read(./.env.*)", "Read(!.env.example)"]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm.sh" }
]
},
{
"matcher": "Edit|Write|Bash",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-env.sh" }
]
}
]
}
}Before committing: chmod +x both scripts, test each with sample JSON covering cases that must be blocked and cases that must pass, then open /hooks to check they're loaded.
That closes level 6. You now have three kinds of hook: recording (6.1), checking after (6.2) and blocking before (6.3), all rules that run every time without Claude having to remember. Level 7 builds on them to take on bigger work safely: plan mode, checkpoints and long sessions.