Safe Claude Code settings: permissions and a guard hook

Project settings that stop Claude Code from force-pushing, wiping work, reading secrets, or piping downloads into a shell, while leaving everyday commands alone. Two files, copy and commit.

What is in this template

File What it does
.claude/settings.json Permission rules: read-only git runs without asking; pushes, commits, publishing, and infrastructure tools ask first; secrets, force-pushes, hard resets, rm -rf, and sudo are denied. Edits through the Write and Edit tools to git hooks, Claude Code's settings files, shell startup files, and ~/Library/LaunchAgents are denied too. Also turns off bypass mode for this project.
.claude/hooks/guard.sh A PreToolUse hook that checks every shell command before it runs, including chained ones such as npm test && git push --force. It blocks with exit code 2, and Claude sees the reason.

Why both

Permission rules match the start of a command, and Claude Code's own docs warn that argument patterns are fragile. Read and Edit deny rules do reach into the shell: they apply to file commands Claude Code recognizes, such as cat, head, tail, sed, and tee, and to redirections such as > file and < file. So Read(.env) already stops cat .env. The same page names what deny rules miss: a command that reads files without naming them, such as grep -r pattern ., and a script that opens files itself, such as a Python or Node program (docs).

Those gaps are the hook's job. It reads the whole command line, so it catches chained commands, flags in any order, and one-line scripts that name a secret file, such as python3 -c "print(open('.env').read())". It cannot look inside a script file or know which files a recursive grep will open (see Limits). Hooks cannot loosen the rules: a deny rule still wins even if the hook allows the call (docs). Each layer only adds limits.

The hook has a gap of its own: it checks shell commands only, so it never sees a file that Claude writes with the Write or Edit tool. The Edit deny rules in settings.json cover that path for git hooks (.git/hooks/**), .claude/settings.json, .claude/settings.local.json, the hook itself (.claude/hooks/**), ~/.zshrc, ~/.bashrc, ~/.profile, and ~/Library/LaunchAgents/**.

What the hook blocks:

Install

From the root of your repo:

mkdir -p .claude/hooks
curl -fsSL https://raw.githubusercontent.com/RyanAlberts/best-of-Agent-Harnesses/main/templates/claude-code-safe-settings/.claude/settings.json -o .claude/settings.json
curl -fsSL https://raw.githubusercontent.com/RyanAlberts/best-of-Agent-Harnesses/main/templates/claude-code-safe-settings/.claude/hooks/guard.sh -o .claude/hooks/guard.sh
chmod +x .claude/hooks/guard.sh

If you already have a .claude/settings.json, merge the permissions and hooks blocks by hand instead of overwriting it. The hook needs jq or python3.

Open Claude Code in the repo once and accept the trust prompt. Until you do, Claude Code ignores the project's allow rules.

Check that it works

Test the hook without starting a session:

echo '{"tool_name":"Bash","tool_input":{"command":"npm test && git push --force"}}' | .claude/hooks/guard.sh; echo "exit $?"

You should see a Blocked by .claude/hooks/guard.sh message and exit 2. Then, in a session, run /permissions to see the rules Claude Code loaded and /hooks to see the hook.

Adjust it

Limits

Pattern checks catch mistakes and obvious prompt injection, not a determined attacker: a script file the agent writes and then runs is not inspected. For real isolation, run the agent in a container or turn on Claude Code's sandbox; the sandboxing guide compares options.

Go further

.claude/hooks/guard.sh

Raw file

#!/usr/bin/env bash
# PreToolUse hook for Claude Code: blocks dangerous shell commands anywhere in
# the command line, including chained ones (`ls && git push --force`), which
# permission rules can miss. Exit 2 blocks the call and shows stderr to Claude.
# Needs jq or python3 to read the hook's JSON input.

input="$(cat)"
if command -v jq >/dev/null 2>&1; then
  cmd="$(printf '%s' "$input" | jq -r '.tool_input.command // ""')"
else
  cmd="$(printf '%s' "$input" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("tool_input",{}).get("command",""))')"
fi

block() {
  echo "Blocked by .claude/hooks/guard.sh: $1. Ask the user to run it themselves if it is really needed." >&2
  exit 2
}

# Destructive git
# git, then global options such as -C <dir> or -c <key=value>, then a subcommand that may be quoted.
git_cmd='git([[:space:]]+-[^[:space:];&|]+([[:space:]]+("[^"]*"|'"'"'[^'"'"']*'"'"'|[^-[:space:];&|"'"'"'][^[:space:];&|]*))?)*[[:space:]]+["'"'"']?'
printf '%s' "$cmd" | grep -Eq "$git_cmd"'push["'"'"']?([[:space:]][^;&|]*)?(--force|[[:space:]]-f([[:space:]]|$)|--mirror|--delete|[[:space:]]:[^[:space:]]|[[:space:]]["'"'"']?[+][^[:space:]])' && block "force-push or remote delete"
printf '%s' "$cmd" | grep -Eq "$git_cmd"'reset["'"'"']?[[:space:]]+--hard' && block "git reset --hard discards work"
printf '%s' "$cmd" | grep -Eq "$git_cmd"'clean["'"'"']?[[:space:]]+-[a-zA-Z]*f' && block "git clean deletes untracked files"
printf '%s' "$cmd" | grep -Eq "$git_cmd"'(checkout|restore)["'"'"']?([[:space:]]+[^-[:space:];&|][^[:space:];&|]*)?[[:space:]]+(--[[:space:]]+)?\.([[:space:]]|$)' && block "discarding all local changes"
printf '%s' "$cmd" | grep -Eq "$git_cmd"'branch["'"'"']?[[:space:]]+-D' && block "force-deleting a branch"

# Destructive files and privilege
# rm: -r and -f in one flag (-rf, -fr) or split (-r -f, -R --force), in any order.
printf '%s' "$cmd" | grep -Eq '(^|[^[:alnum:]_.-])rm[[:space:]]([^;&|]*[[:space:]])?(-[a-zA-Z]*([rR][a-zA-Z]*f|f[a-zA-Z]*[rR])|(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)[[:space:]]([^;&|]*[[:space:]])?(-[a-zA-Z]*f|--force)|(-[a-zA-Z]*f[a-zA-Z]*|--force)[[:space:]]([^;&|]*[[:space:]])?(-[a-zA-Z]*[rR]|--recursive))' && block "recursive forced delete"
printf '%s' "$cmd" | grep -Eq '(^|[^[:alnum:]_.-])find[[:space:]]([^;&|]*[[:space:]])?(-delete([^[:alnum:]_-]|$)|-(exec|execdir|ok|okdir)[[:space:]]+([^[:space:];&|]*/)?rm[[:space:]])' && block "find that deletes files"
# sudo only where a command starts: after a separator, a find -exec, or wrappers such as env, nohup, or xargs.
printf '%s' "$cmd" | grep -Eq '(^|[;&|({!`]|[[:space:]]-(exec|execdir|ok|okdir))[[:space:]]*(([[:alpha:]_][[:alnum:]_]*=[^[:space:]]*|env|command|builtin|exec|nohup|time|nice|timeout|stdbuf|xargs|then|do|else|elif|-[^[:space:];&|]*|[0-9][^[:space:];&|]*)[[:space:]]+)*([^[:space:];&|]*/)?sudo[[:space:]]' && block "sudo"

# Secrets: Read() deny rules cover cat, head, tail, sed, and tee, but not every
# reader, and not a script that opens the file itself.
# Example files (.env.example, .env.sample, .env.template) are not secrets.
scan="$(printf '%s' "$cmd" | sed -E 's/\.env\.(example|sample|template)//g')"
printf '%s' "$scan" | grep -Eq '(cat|less|more|head|tail|grep|awk|sed|scp|base64|xxd)[^;&|]*(\.env([.[:space:]]|$)|\.pem|id_rsa|id_ed25519|\.aws/credentials|\.ssh/)' && block "reading secrets through the shell"
printf '%s' "$scan" | grep -Eq '(^|[^[:alnum:]_.-])(python[0-9.]*|node|ruby|perl)[[:space:]].*(\.env([^[:alnum:]_-]|$)|\.pem|id_rsa|id_ed25519|\.aws/credentials|\.ssh/)' && block "reading secrets with a one-line script"
printf '%s' "$cmd" | grep -Eq '(^|[;&|[:space:]])(printenv|env)([[:space:]]*$|[[:space:]]*[;&|])' && block "dumping environment variables"

# Remote code
printf '%s' "$cmd" | grep -Eq '(curl|wget)[^;&]*\|[[:space:]]*(sudo[[:space:]]+)?(ba|z)?sh([^[:alnum:]_.-]|$)' && block "piping a download into a shell"
printf '%s' "$cmd" | grep -Eq 'base64[[:space:]][^;&|]*-(d|D|-decode)[^;&]*\|[[:space:]]*(sudo[[:space:]]+)?(ba|z|da)?sh([[:space:]]|$)' && block "piping decoded text into a shell"
printf '%s' "$cmd" | grep -Eq '(curl|wget)[[:space:]][^|]*(;|&&|\|\|)[[:space:]]*(sudo[[:space:]]+)?(((ba|z|da)?sh|source|\.)[[:space:]]+[^-[:space:]]|chmod[[:space:]][^;&|]*[+]x)' && block "downloading a file and then running it"

# Files that run later or loosen these settings: git hooks, shell startup files,
# launch agents, and Claude Code's own settings and hooks. Reading them is fine.
protected='(\.git/hooks|Library/Launch(Agents|Daemons)|\.claude/(settings[^/[:space:]]*\.json|hooks)|\.(zshrc|zshenv|zprofile|zlogin|bashrc|bash_profile|bash_login|profile))'
printf '%s' "$cmd" | grep -Eq '>[[:space:]]*[^[:space:];&|]*'"$protected"'([^[:alnum:]_.-]|$)' && block "redirecting into a git hook, shell startup file, launch agent, or Claude Code setting"
printf '%s' "$cmd" | grep -Eq '(^|[^[:alnum:]_.-])(tee|touch|chmod|chown|truncate|dd|mv|rm|unlink)[[:space:]][^;&|]*'"$protected"'([^[:alnum:]_.-]|$)' && block "changing a git hook, shell startup file, launch agent, or Claude Code setting"
printf '%s' "$cmd" | grep -Eq '(^|[^[:alnum:]_.-])(cp|ln|install|rsync)[[:space:]][^;&|]*[[:space:]]["'"'"']?[^[:space:];&|]*'"$protected"'(/[^[:space:];&|]*)?["'"'"']?[[:space:]]*($|[;&|)])' && block "copying into a git hook, shell startup file, launch agent, or Claude Code setting"
printf '%s' "$cmd" | grep -Eq '(^|[^[:alnum:]_.-])sed[[:space:]]([^;&|]*[[:space:]])?(-[a-zA-Z]*[iI]|--in-place)[^;&|]*'"$protected"'([^[:alnum:]_.-]|$)' && block "editing a git hook, shell startup file, launch agent, or Claude Code setting"

exit 0

.claude/settings.json

Raw file

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "permissions": {
    "allow": [
      "Bash(git status *)",
      "Bash(git diff *)",
      "Bash(git log *)",
      "Bash(git show *)"
    ],
    "ask": [
      "Bash(git push *)",
      "Bash(git commit *)",
      "Bash(npm publish *)",
      "Bash(docker *)",
      "Bash(kubectl *)",
      "Bash(terraform *)"
    ],
    "deny": [
      "Read(.env)",
      "Read(.env.*)",
      "Read(**/*.pem)",
      "Read(**/*.key)",
      "Read(**/id_rsa*)",
      "Read(**/id_ed25519*)",
      "Read(./secrets/**)",
      "Read(~/.ssh/**)",
      "Read(~/.aws/**)",
      "Edit(.env)",
      "Edit(.env.*)",
      "Edit(.git/hooks/**)",
      "Edit(.claude/settings.json)",
      "Edit(.claude/settings.local.json)",
      "Edit(.claude/hooks/**)",
      "Edit(~/.zshrc)",
      "Edit(~/.bashrc)",
      "Edit(~/.profile)",
      "Edit(~/Library/LaunchAgents/**)",
      "Bash(git push --force *)",
      "Bash(git push -f *)",
      "Bash(git reset --hard *)",
      "Bash(git clean *)",
      "Bash(rm -rf *)",
      "Bash(sudo *)"
    ],
    "disableBypassPermissionsMode": "disable"
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard.sh"
          }
        ]
      }
    ]
  }
}