OmniscioGuidesAn .env protection hook
A Claude Code hook that blocks .env reads and edits
A .env file is the one file in a project where a helpful read is a real leak: the whole file ends up in the model’s context, in the transcript, and in any log that copies it. Blocking the file tools is the cheap half of the answer, and knowing where that half ends is the rest of it.
Checked against Anthropic’s Claude Code hooks documentation on November 25, 2026. By the Omniscio team. Updated .
The hook, complete
Save the script to .claude/hooks/block-env.sh in the project and make it executable. It handles both cases: the file tools, where the path is in tool_input.file_path, and Bash, where the command is in tool_input.command.
It needs jq: brew install jq on macOS, sudo apt-get install jq on Debian and Ubuntu, or winget install jqlang.jq on Windows. Install it before you switch the hook on. The command -v jq line exits 2 when it is missing, and with onFailure: "block" that means every Read, Edit, Write and Bash call is refused until you do.
#!/bin/bash
set -u
command -v jq >/dev/null 2>&1 || { echo "block-env: jq is not installed." >&2; exit 2; }
input=$(cat)
tool=$(jq -r '.tool_name // empty' <<<"$input")
if [ "$tool" = "Bash" ]; then
cmd=$(jq -r '.tool_input.command // empty' <<<"$input")
scan="${cmd//.env.example/}"
scan="${scan//.env.sample/}"
scan="${scan//.env.template/}"
if [[ "$scan" =~ (^|[^A-Za-z0-9_.-])\.env(\.[A-Za-z0-9_-]+)?([^A-Za-z0-9_-]|$) ]]; then
echo "Blocked: .env files hold secrets. Ask the user for the values you need." >&2
exit 2
fi
exit 0
fi
file=$(jq -r '.tool_input.file_path // empty' <<<"$input")
file="${file//\\//}"
case "$file" in
*.env.example|*.env.sample|*.env.template) exit 0 ;;
esac
case "${file##*/}" in
.env|.env.*)
echo "Blocked: $file holds secrets. Ask the user for the values you need." >&2
exit 2
;;
esac
exit 0Put the block in .claude/settings.json at the project root. If that file already exists, merge the two PreToolUse entries into its hooks object rather than replacing it. $CLAUDE_PROJECT_DIR is the project root where the session started, so write the hook into the project rather than into your user settings — otherwise the script path will not resolve.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Read|Edit|Write",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-env.sh",
"onFailure": "block"
}
]
},
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-env.sh",
"onFailure": "block"
}
]
}
]
}
}Then chmod +x .claude/hooks/block-env.sh. Without the execute bit the hook never starts, and with onFailure: "block" that failure now blocks every matching tool call instead of being ignored.
This is a Bash script, so on Windows it needs Git Bash. Without Git for Windows the shell is PowerShell, the file-tool script cannot start, and with onFailure: "block" that blocks every Read, Edit and Write; the Bash block never fires at all, because Claude Code does not register that tool there. Either install Git for Windows or leave this hook off on that machine.
The problem it solves
Claude reads a file to answer a question about it. The question is usually reasonable — what key name does this service expect, is the database URL already set — and the answer arrives as the whole file, secrets included, into a context window and a transcript you may share.
The protection you want is not “Claude never learns the shape of the config”. It is “Claude never receives the values”. A hook that blocks the read entirely gives you that at the cost of the helpful part, so the block message matters: it should tell Claude what to ask for instead.
What each line does
| Part | Job |
|---|---|
"PreToolUse" | The event: it runs after Claude builds the tool’s parameters and before the tool call is processed, so it is the place a tool call can be stopped. |
"matcher": "Read|Edit|Write" | Filters by tool name. A value of only letters, digits, _, -, spaces, commas and | is read as a list of exact names, so this matches those three tools and nothing else. |
"matcher": "Bash" | The second block covers shell commands. It needs its own entry because a matcher is a filter, not a fallback. |
command -v jq | Exits 2 when jq is missing. Without it the script would carry on with empty variables and exit 0, which Claude Code reads as success and a protection that is silently off. |
tool_name | One field tells the script which shape the input has, so a single script can serve both blocks. |
${file//\\//} | Normalises Windows backslashes. Anthropic states the path arrives with backslash separators on Windows even under Git Bash, so a forward-slash pattern silently never matches without this. |
${scan//.env.example/} | Removes the template names before the shell check, so reading a committed example file is allowed while cat .env.example .env is still caught. |
the Bash regex | Matches .env as its own path segment, so cat ./.env, cat /app/.env and cat .env; all match while environment.ts does not. |
${file##*/} | Compares the file’s own name, so /app/.env.local matches and /app/environment.ts does not. |
.env.example allow-list | Keeps the committed template readable. Claude usually needs it, and it holds no values. |
exit 2 | Blocks the call. Your stderr becomes the reason Claude receives, which is why the message asks for what it needs instead. |
onFailure: "block" | Makes a hook that fails to start or times out block instead of letting the call through. It is the second net, after the jq check. |
Everything else exits 0, which on PreToolUse leaves the normal permission flow to decide. A hook is not a permission rule: returning nothing is not an approval, and returning allow cannot override a deny rule that already matches.
The five things this hook does not stop
This is the section that decides whether you should rely on the hook. One of the five is a limit of what a PreToolUse hook can see at all; the others are limits of this recipe, and four of them can be closed with something else.
- An
@mention in the prompt. Anthropic documents that files you reference with@are added to the prompt without any tool call, so noPreToolUsehook fires for them, including hooks matchingRead. This one is not a recipe flaw and no matcher fixes it. Anthropic’s documented fix is aReaddeny rule on those paths, which is a permission rule rather than a hook.CLAUDE_CODE_DISABLE_FILE_MENTIONS=1is the other documented route, and it is weaker than it sounds: it does not force a read, it only gives Claude the paths with a note to use its file tools, so your hook runs only if Claude does. The variable also needs Claude Code v2.1.299 or later and is ignored in project and local settings, so it has to go in your user settings or the shell. - A shell command that reads it. The
Bashblock catches a.envtoken in the command, and nothing more. Anthropic’s guide says plainly that Claude can still change protected files with shell commands, and that covers more than a pattern can: a script that opens the file, an env loader, a command assembled from variables at run time. - Another tool. MCP tools and plugin tools are separate tool names. A filesystem MCP server that reads a path is not
Read, so theRead|Edit|Writematcher does not see it. The docs say to match MCP tools the same way as any other tool name, so this is a matcher you add, not a gap you live with. - A cloud session. Hooks from settings files also run inside subagents, so that part is covered. Cloud sessions do not read your local
~/.claude/settings.json, so a hook defined there is not present in one; a hook committed in the project’s.claude/settings.jsonis a different question, and worth checking in your own setup rather than assuming. - A differently named secrets file. Both checks look for the name
.envor.env.something. A repository that keepsproduction.envorconfig.envis not protected by either, and theGrepandGlobtools are not in the matcher at all, so a search can still surface the contents. Add those names to the pattern, andGrep|Globto the matcher, if your repository uses them.
The documented next layer is a deny rule in permissions.deny, for example Edit(/.env) for the project root’s .env, which Anthropic’s guide shows, and the same rule shape for Read; then sandboxing to limit which files commands can write at all. The guide names both after its own protect-files example, which suggests treating the hook as the first layer rather than the last.
Why not just copy Anthropic’s protect-files script
Anthropic’s own example is a good starting point and its shape is the same: read file_path, check patterns, exit 2. Two details in it are worth knowing before you rely on it for secrets.
Its pattern list includes .env and it tests with a substring match, so any path containing those four characters matches — app.environment.ts included. And its matcher is Edit|Write, so it stops changes and leaves Read open. That is the right call for its stated job, protecting package-lock.json and .git/ from edits. For a secret you are trying to keep out of the context window, the read is the part that matters.
How to test that it fires
- Run the script by hand, from the project root, with both shapes of input. This is the check that separates a broken script from a hook that never ran:
H=.claude/hooks/block-env.sh echo '{"tool_name":"Read","tool_input":{"file_path":"/app/.env"}}' | $H; echo $? echo '{"tool_name":"Read","tool_input":{"file_path":"/app/.env.example"}}' | $H; echo $? echo '{"tool_name":"Bash","tool_input":{"command":"cat .env"}}' | $H; echo $? echo '{"tool_name":"Bash","tool_input":{"command":"cat ./.env;"}}' | $H; echo $?The first, third and fourth should print the blocked message on stderr and exit 2. The second should print nothing and exit 0. - Check the hook is registered. Type
/hooks: a read-only browser that lists each hook under its event and says where it comes from. - Trigger it for real. Ask Claude to open
.env. The call is refused and Claude receives your stderr as the reason, so it should come back asking you for the value instead — that reply is the proof the message did its job. - Read the debug log when it does not. Run
/debugmid-session, or restart withclaude --debug-file /tmp/claude.log(use a Windows path such asC:\Temp\claude.logthere) and read the file. The log records each hook run and its outcome, which is where a script that exited early shows up.
What makes this hook fail
1. The script swallows its own errors
The dangerous version of this hook reads the path with jq, gets nothing back because jq is missing or the settings say something unexpected, and still reaches exit 0. Claude Code reads exit 0 as success, so onFailure never fires and the protection is off while everything looks fine. The command -v jq line at the top is the fix: a missing tool becomes exit 2, which blocks. Anything else your script depends on deserves the same treatment.
2. The Windows path never matches
A pattern written for forward slashes meets backslashes and matches nothing, and the tool call proceeds as if the hook had nothing to block. That is the failure the backslash-normalising line exists to prevent, and it is silent: no error, no notice, just the file open.
3. It blocks the edit and not the read
The most common version of this hook is Anthropic’s Edit|Write matcher. It stops Claude changing .env and does nothing about Claude reading it, which is the case that leaks. If a copied script seems to work and secrets still reach the transcript, check the matcher first.
4. It blocks too much
The Bash check matches a .env token anywhere in the command, so git commit -m "edit .env" is refused even though it touches no file. That is deliberate — a check that guesses is worth more than one that misses — but if it costs you more than it saves, narrow the regex to the commands you care about, or move the check to if patterns such as Bash(cat .env), rather than deleting the block.
5. It never runs at all
A mistyped path in the settings file, a script without the execute bit, or a Windows machine without Git Bash all stop the hook starting. With onFailure: "block" the first two block every matching call, which is loud and easy to notice; the third means the Bash block simply never fires. /hooks is the fastest check: if the block is not listed under PreToolUse, nothing below it matters.
Where Omniscio fits
This belongs in the project. Commit .claude/settings.json and the whole team gets the same protection, which is the point of putting it there rather than in a personal folder. Omniscio takes the other angle: its Hooks panel composes the hooks it ships, and any you define, into every session it spawns, keeping them in its own database rather than writing into your global Claude configuration, with a global switch and per-project overrides.
The hooks examples hub collects the other recipes, the Claude Code hooks guide covers every event, and the hooks builder assembles a block like this one. Omniscio runs on Windows, macOS and Linux, and the pricing page covers the plans.
How this page was written
Everything about events, matcher rules, input fields, exit codes, onFailure, Windows path handling, @ mentions and their settings limits, MCP tool names, hook locations and the security guidance was read from Anthropic’s Claude Code hooks reference and its hooks guide on November 25, 2026, quoted from those pages as they read today.
The script was run on this machine with fourteen sample inputs, covering both tool shapes, the template allow-list, a Windows backslash path and a run with jq removed from the path. No live Claude Code session was configured to run it, so the page describes the documented behaviour of the block and the measured behaviour of the script.
Sources
- Anthropic’s Hooks reference, for
PreToolUse, matcher rules, input fields, exit codes,onFailure, the@mention warning, MCP naming, hook locations and the security guidance, read November 25, 2026. - Anthropic’s Automate actions with hooks, for the protect-files example, its stated limits and the deny-rule and sandboxing advice, read November 25, 2026.
Common questions
How do I stop Claude Code reading my .env file?
Register a PreToolUse hook on Read, Edit and Write that exits 2 when the path names a .env file. Exit 2 blocks the call, and the script’s stderr becomes the reason Claude sees. Add a deny rule under permissions.deny for the same path as well, because a hook is not the only way a file is opened.
Does it stop an @ mention?
No. Anthropic documents that files you reference with @ in a prompt are added without any tool call, so no PreToolUse hook fires for them, including hooks matching Read. Use a Read deny rule for those paths. CLAUDE_CODE_DISABLE_FILE_MENTIONS=1 is the other route: it stops the insertion and gives Claude the paths with a note to read them with its file tools, so your hook runs only if Claude does. It needs v2.1.299 or later and is ignored in project and local settings.
What does onFailure: "block" do here?
It makes a hook that fails to start or times out block the action instead of letting it through, so a mistyped script path fails closed. It needs Claude Code v2.1.295 or later, and it has no effect on Stop, SubagentStop, TaskCompleted or TeammateIdle hooks. A script that catches its own errors and exits 0 is not a failure, which is why the jq check is in the script as well.
Is a hook enough to protect secrets?
No. Anthropic’s guide says Claude can still change protected files with shell commands even with the hook in place, and points at deny rules and sandboxing for a harder boundary. Treat the hook as one layer that catches the obvious paths.
Does it cover a filesystem MCP server?
Not as written. MCP tools appear under their own names, such as mcp__filesystem__read_file, so a Read|Edit|Write matcher never sees them. Add the server’s tool names to a matcher of their own if you run one.
The same guard in every session
Omniscio runs your Claude Code sessions side by side and composes the hooks it ships, and any you define, into every one it spawns, so a secrets rule does not depend on which folder you opened.
The features page covers what else it does, pricing covers the plans, and you can download it for Windows, macOS or Linux.