Skip to main content
hooksSource-backed

Pre-Write Secret Scanner - Claude Code Hook

PreToolUse hook that scans the exact text Claude Code is about to write or edit for high-confidence secret formats (AWS access keys, GitHub tokens, OpenAI keys, Slack tokens, Google API keys, Stripe keys, and private key blocks) and blocks the write with a non-zero exit before the secret ever reaches disk.

by jony376·added 2026-06-04·
Trigger:PreToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/hooks, https://github.com/gitleaks/gitleaks
Safety notes
Runs before every Write, Edit, and MultiEdit and reads the pending content from the tool input on stdin., Blocks the write with exit code 2 when a high-confidence secret pattern matches; no files are created, deleted, or modified by the hook itself., Uses regex heuristics, so it can produce false positives (block a non-secret) or false negatives (miss an obfuscated secret); treat it as a guardrail, not proof of safety., Makes no network calls and runs entirely locally., Safe for user-level settings only when the command points to a trusted script you installed under your home directory; do not configure global hooks to execute scripts from `$CLAUDE_PROJECT_DIR`.
Privacy notes
Reads the text about to be written but never prints the matched secret value; only the detected secret type and the target file path are written to stderr., Writes nothing to disk and retains no logs., The target file path shown in the message may reveal local directory structure in your terminal output.
Author
jony376
Submitted by
jony376
Claim status
unclaimed
Last verified
2026-06-04

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Prerequisite readiness

Prerequisite readiness

2 prerequisites to line up before setup.

0/2 ready
Install & runtime1General1

Safety & privacy surface

Safety & privacy surface

5 safety and 3 privacy notes across 4 risk areas. Review closely: credentials & tokens, network access.

4 areas
  • SafetyExecution & processesRuns before every Write, Edit, and MultiEdit and reads the pending content from the tool input on stdin.
  • SafetyCredentials & tokensBlocks the write with exit code 2 when a high-confidence secret pattern matches; no files are created, deleted, or modified by the hook itself.
  • SafetyCredentials & tokensUses regex heuristics, so it can produce false positives (block a non-secret) or false negatives (miss an obfuscated secret); treat it as a guardrail, not proof of safety.
  • SafetyNetwork accessMakes no network calls and runs entirely locally.
  • SafetyLocal filesSafe for user-level settings only when the command points to a trusted script you installed under your home directory; do not configure global hooks to execute scripts from `$CLAUDE_PROJECT_DIR`.
  • PrivacyCredentials & tokensReads the text about to be written but never prints the matched secret value; only the detected secret type and the target file path are written to stderr.
  • PrivacyLocal filesWrites nothing to disk and retains no logs.
  • PrivacyLocal filesThe target file path shown in the message may reveal local directory structure in your terminal output.

Safety notes

  • Runs before every Write, Edit, and MultiEdit and reads the pending content from the tool input on stdin.
  • Blocks the write with exit code 2 when a high-confidence secret pattern matches; no files are created, deleted, or modified by the hook itself.
  • Uses regex heuristics, so it can produce false positives (block a non-secret) or false negatives (miss an obfuscated secret); treat it as a guardrail, not proof of safety.
  • Makes no network calls and runs entirely locally.
  • Safe for user-level settings only when the command points to a trusted script you installed under your home directory; do not configure global hooks to execute scripts from `$CLAUDE_PROJECT_DIR`.

Privacy notes

  • Reads the text about to be written but never prints the matched secret value; only the detected secret type and the target file path are written to stderr.
  • Writes nothing to disk and retains no logs.
  • The target file path shown in the message may reveal local directory structure in your terminal output.

Prerequisites

  • Claude Code CLI with hooks enabled.
  • bash and jq available on PATH (the hook fails open and does not block if jq is missing).

Schema details

Install type
cli
Troubleshooting
No
Source repository stats
Scope
Source repo
Runtime and command metadata
Trigger
PreToolUse
Script language
bash
Script body
#!/usr/bin/env bash
set -u

# Claude Code PreToolUse hook. Scans the text a Write/Edit/MultiEdit call is
# about to persist for high-confidence secret formats and blocks the call
# (exit code 2) before the secret reaches disk. The stderr message is fed
# back to Claude so it can redact and retry. Fails open: any inability to
# inspect the input leaves the write unblocked.

if ! command -v jq >/dev/null 2>&1; then
  exit 0
fi

INPUT=$(cat)
FILE=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

# Only the NEW text this tool would write, across Write/Edit/MultiEdit.
CONTENT=$(printf '%s' "$INPUT" | jq -r '
  [ .tool_input.content,
    .tool_input.new_string,
    (.tool_input.edits[]?.new_string) ]
  | map(select(. != null)) | join("\n")
')

if [ -z "$CONTENT" ]; then
  exit 0
fi

# name|ERE pairs for high-confidence secret formats (mirrors gitleaks rules).
PATTERNS=(
  "AWS access key|AKIA[0-9A-Z]{16}"
  "GitHub token|gh[pousr]_[A-Za-z0-9]{36,}"
  "GitHub fine-grained token|github_pat_[A-Za-z0-9_]{82}"
  "OpenAI API key|sk-(proj-)?[A-Za-z0-9_-]{20,}"
  "Slack token|xox[baprs]-[A-Za-z0-9-]{10,}"
  "Google API key|AIza[0-9A-Za-z_-]{35}"
  "Stripe secret key|sk_live_[0-9a-zA-Z]{24,}"
  "Private key block|-----BEGIN [A-Z ]*PRIVATE KEY-----"
)

FOUND=0
for entry in "${PATTERNS[@]}"; do
  name=${entry%%|*}
  regex=${entry#*|}
  if printf '%s' "$CONTENT" | grep -Eq -- "$regex"; then
    echo "🔒 Secret blocked: possible ${name} in ${FILE:-pending write}." >&2
    FOUND=1
  fi
done

if [ "$FOUND" -ne 0 ]; then
  echo "Replace the secret with an environment variable or secret-manager reference, then retry." >&2
  exit 2
fi

exit 0
Full copyable content
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "$HOME/.claude/hooks/pre-write-secret-scanner.sh"
          }
        ]
      }
    ]
  }
}

About this resource

Features

  • Scans the exact text a Write, Edit, or MultiEdit call would persist — before it reaches disk — and blocks it on a match (exit code 2).
  • Detects high-confidence secret formats whose patterns mirror the canonical gitleaks rule set, so detections map to real provider key shapes rather than ad-hoc guesses.
  • Reports the detected secret type and target file without ever echoing the secret value.
  • Fails open: if jq is unavailable or the tool input carries no new text, the write proceeds untouched.
  • Pure local bash + jq, no network access, no persisted logs.

How it works

Claude Code passes the pending tool call to the hook as JSON on stdin. The hook extracts only the new text the call would write (tool_input.content for Write, new_string for Edit, and each edits[].new_string for MultiEdit), then tests it against a list of named secret patterns. If any match, it prints a redacted message to stderr and exits 2, which instructs Claude Code to block the call so the secret is never saved.

Detected secret types

  • AWS access key IDs (AKIA…)
  • GitHub personal access and OAuth tokens (ghp_, gho_, ghu_, ghs_, ghr_) and fine-grained tokens (github_pat_…)
  • OpenAI API keys (sk-…, sk-proj-…)
  • Slack tokens (xox[baprs]-…)
  • Google API keys (AIza…)
  • Stripe secret keys (sk_live_…)
  • PEM private key blocks (-----BEGIN … PRIVATE KEY-----)

Use cases

  • Stop Claude from hardcoding a leaked credential into source, config, or test fixtures during an agentic session.
  • Add a defense-in-depth layer ahead of (not instead of) commit-time scanners like gitleaks in CI.
  • Keep .env-style values out of files that are about to be written to a tracked directory.

Installation

  1. Create a trusted user hooks directory: mkdir -p "$HOME/.claude/hooks"
  2. Create the hook file: touch "$HOME/.claude/hooks/pre-write-secret-scanner.sh"
  3. Paste the script body into that file and make it executable: chmod +x "$HOME/.claude/hooks/pre-write-secret-scanner.sh"
  4. Add the configuration below to ~/.claude/settings.json (user) or .claude/settings.json (project). Keep user-level hooks pointed at this trusted $HOME script; do not use $CLAUDE_PROJECT_DIR in global settings because untrusted projects can control that path.

Requirements

  • Claude Code CLI with hooks enabled
  • bash shell
  • jq (for parsing the tool input)

Hook configuration

This configuration references the trusted script installed under your home directory, so it is safe to use from user-level settings across projects. If you instead keep a project-local copy under .claude/hooks, only reference that project-local path from that same project's .claude/settings.json, never from ~/.claude/settings.json.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "$HOME/.claude/hooks/pre-write-secret-scanner.sh"
          }
        ]
      }
    ]
  }
}

Limitations

  • Regex detection cannot catch every secret format and may flag a non-secret that happens to match a shape; tune the PATTERNS list for your stack.
  • It inspects only the content of the pending write, not files already on disk — pair it with a repository-wide scanner for full coverage.

Source and references

Source citations

Add this badge to your README

Show that Pre-Write Secret Scanner - Claude Code Hook is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/pre-write-secret-scanner.svg)](https://heyclau.de/entry/hooks/pre-write-secret-scanner)

How it compares

Pre-Write Secret Scanner - Claude Code Hook side by side with 2 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

1 trust signal differ across this comparison (Submitter).

Field

PreToolUse hook that scans the exact text Claude Code is about to write or edit for high-confidence secret formats (AWS access keys, GitHub tokens, OpenAI keys, Slack tokens, Google API keys, Stripe keys, and private key blocks) and blocks the write with a non-zero exit before the secret ever reaches disk.

Open dossier

Scans for potential sensitive data exposure and alerts immediately.

Open dossier

Comprehensive Docker image vulnerability scanning with layer analysis, base image recommendations, and security best practices enforcement. This PostToolUse hook automatically scans Docker images for vulnerabilities when Dockerfiles are modified, providing real-time security validation during development.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backed
SubmitterDiffersjony376
Install riskReview firstReview firstReview first
Notes Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓
BrandDocker logoDocker
Categoryhookshookshooks
SourceSource-backedSource-backedSource-backed
Authorjony376JSONboredJSONbored
Added2026-06-042025-09-192025-10-19
Platforms
Harness
Source repo
Safety notesRuns before every Write, Edit, and MultiEdit and reads the pending content from the tool input on stdin. Blocks the write with exit code 2 when a high-confidence secret pattern matches; no files are created, deleted, or modified by the hook itself. Uses regex heuristics, so it can produce false positives (block a non-secret) or false negatives (miss an obfuscated secret); treat it as a guardrail, not proof of safety. Makes no network calls and runs entirely locally. Safe for user-level settings only when the command points to a trusted script you installed under your home directory; do not configure global hooks to execute scripts from `$CLAUDE_PROJECT_DIR`.Runs on notification events and scans recent tool input for patterns that resemble secrets or sensitive data. Produces alerts only and does not redact files, rotate credentials, or block the original tool action. Pattern-based detection can miss real secrets or flag harmless placeholders.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notesReads the text about to be written but never prints the matched secret value; only the detected secret type and the target file path are written to stderr. Writes nothing to disk and retains no logs. The target file path shown in the message may reveal local directory structure in your terminal output.Reads hook input fields such as tool names, file paths, commands, and text snippets supplied to the notification event. May print matched sensitive-looking strings or surrounding context to local hook output. Does not send findings to a remote service in the bundled script.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Prerequisites
  • Claude Code CLI with hooks enabled.
  • bash and jq available on PATH (the hook fails open and does not block if jq is missing).
— none listed— none listed
Install
mkdir -p "$HOME/.claude/hooks" && touch "$HOME/.claude/hooks/pre-write-secret-scanner.sh" && chmod +x "$HOME/.claude/hooks/pre-write-secret-scanner.sh"
mkdir -p .claude/hooks && touch .claude/hooks/sensitive-data-alert-scanner.sh && chmod +x .claude/hooks/sensitive-data-alert-scanner.sh
mkdir -p .claude/hooks && touch .claude/hooks/docker-image-security-scanner.sh && chmod +x .claude/hooks/docker-image-security-scanner.sh
Config
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "$HOME/.claude/hooks/pre-write-secret-scanner.sh"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "notification": {
      "script": "./.claude/hooks/sensitive-data-alert-scanner.sh",
      "matchers": [
        "*"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/docker-image-security-scanner.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimed
Open 3 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.