Prevent Claude Code from Leaking Secrets

Claude Code can run git add . and commit your .env file, API keys, SSH keys, and other credentials to a public repository. This happens silently during autonomous sessions.

How It Happens

Claude Code frequently uses git add . or git add -A to stage all changes. If your .gitignore is incomplete — or if Claude created a new file with credentials — secrets get staged and committed.

API keys committed via git add .

During a refactoring session, Claude ran git add . which included a newly created config file containing API keys. The commit was pushed to a public repository.

#16561

The Fix: secret-guard Hook

secret-guard.sh — blocks staging of sensitive files:

#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

# Detect git add of sensitive files
if echo "$COMMAND" | grep -qE 'git\s+add.*\.(env|pem|key|p12|pfx|jks)'; then
  echo "BLOCKED: Staging sensitive file" >&2
  exit 2
fi

# Detect git add . or git add -A (catch-all staging)
if echo "$COMMAND" | grep -qE 'git\s+add\s+(-A|\.)'; then
  echo "BLOCKED: Use specific file names instead of git add ." >&2
  exit 2
fi

exit 0

The hook blocks both direct staging of sensitive files and the catch-all git add . pattern. Claude is forced to stage files individually, making accidental secret inclusion much less likely.

Install Secret Protection + 7 More Safety Hooks

npx cc-safe-setup

Blocks secret leaks, rm -rf, force-push, syntax errors, and more. 9,677 tests 605 examples

GitHub · npm · Getting Started

Also Prevents

Check Your Safety Score

npx cc-health-check

Free 20-point diagnostic for your Claude Code setup.

Open source, zero dependencies. View source.

New: Hook if field — reduce overhead (v2.1.85)

Learn more: Production Guide · All Tools