Skip to main content
hooksSource-backedReview first Safety Privacy

Sensitive Data Alert Scanner - Hooks

Scans for potential sensitive data exposure and alerts immediately.

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:Notification
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://github.com/gitleaks/gitleaks, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/sensitive-data-alert-scanner.mdx
Safety notes
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.
Privacy notes
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.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

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.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

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.

Safety & privacy surface

Safety & privacy surface

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

4 areas
  • SafetyCredentials & tokensRuns on notification events and scans recent tool input for patterns that resemble secrets or sensitive data.
  • SafetyCredentials & tokensProduces alerts only and does not redact files, rotate credentials, or block the original tool action.
  • SafetyCredentials & tokensPattern-based detection can miss real secrets or flag harmless placeholders.
  • PrivacyLocal filesReads hook input fields such as tool names, file paths, commands, and text snippets supplied to the notification event.
  • PrivacyGeneralMay print matched sensitive-looking strings or surrounding context to local hook output.
  • PrivacyNetwork accessDoes not send findings to a remote service in the bundled script.

Safety notes

  • 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.

Privacy notes

  • 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.

Schema details

Install type
cli
Reading time
4 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://github.com/gitleaks/gitleakshttps://code.claude.com/docs/en/hooks
Runtime and command metadata
Trigger
Notification
Script language
bash
Script body
#!/bin/bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

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

# Only scan for Write and Edit operations
if [[ "$TOOL_NAME" != "Write" && "$TOOL_NAME" != "Edit" ]]; then
  exit 0
fi

echo "🔒 Sensitive Data Alert Scanner - Analyzing file for security risks..."
echo "📄 File: $FILE_PATH"

# Check if file exists and is readable
if [ ! -f "$FILE_PATH" ]; then
    echo "⚠️ File not found: $FILE_PATH"
    exit 0
fi

# Skip binary files
if file "$FILE_PATH" | grep -q binary; then
    echo "ℹ️ Skipping binary file"
    exit 0
fi

SECURITY_ISSUES=0
WARNINGS=0

echo "🔍 Scanning for sensitive data patterns..."

# 1. API Keys and Secrets
echo "🔑 Checking for API keys and secrets..."
API_PATTERNS=(
    "api[_-]?key\s*[:=]\s*[\"'][^\"']{8,}[\"']"
    "secret[_-]?key\s*[:=]\s*[\"'][^\"']{8,}[\"']"
    "access[_-]?token\s*[:=]\s*[\"'][^\"']{10,}[\"']"
    "private[_-]?key\s*[:=]\s*[\"'][^\"']{20,}[\"']"
    "client[_-]?secret\s*[:=]\s*[\"'][^\"']{8,}[\"']"
)

for pattern in "${API_PATTERNS[@]}"; do
    if grep -iE "$pattern" "$FILE_PATH" 2>/dev/null | grep -v -iE "(\*\*\*|example|placeholder|your[_-]|demo|test|fake|dummy)"; then
        echo "🚨 SECURITY ALERT: Potential API key/secret detected!"
        SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
    fi
done

# 2. Password patterns
echo "🔐 Checking for password exposure..."
PASSWORD_PATTERNS=(
    "password\s*[:=]\s*[\"'][^\"']{6,}[\"']"
    "passwd\s*[:=]\s*[\"'][^\"']{6,}[\"']"
    "pwd\s*[:=]\s*[\"'][^\"']{6,}[\"']"
)

for pattern in "${PASSWORD_PATTERNS[@]}"; do
    if grep -iE "$pattern" "$FILE_PATH" 2>/dev/null | grep -v -iE "(\*\*\*|example|placeholder|your[_-]|demo|test|123456|password)"; then
        echo "🚨 SECURITY ALERT: Potential password detected!"
        SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
    fi
done

# 3. Database connection strings
echo "🗄️ Checking for database credentials..."
if grep -iE "(mysql://|postgresql://|mongodb://|redis://).*:.*@" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: Database connection string with credentials detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 4. JWT tokens
echo "🎫 Checking for JWT tokens..."
if grep -E "eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: JWT token detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 5. SSH private keys
echo "🔑 Checking for SSH private keys..."
if grep -q "BEGIN.*PRIVATE KEY" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: SSH private key detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 6. Email addresses (warning, not critical)
echo "📧 Checking for email addresses..."
if grep -E "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}" "$FILE_PATH" 2>/dev/null | head -3; then
    echo "⚠️ Email addresses detected - ensure this is intentional"
    WARNINGS=$((WARNINGS + 1))
fi

# 7. Credit card patterns (basic check)
echo "💳 Checking for credit card numbers..."
if grep -E "[0-9]{4}[\s-]?[0-9]{4}[\s-]?[0-9]{4}[\s-]?[0-9]{4}" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: Potential credit card number detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 8. Social Security Numbers (US format)
echo "🆔 Checking for SSN patterns..."
if grep -E "[0-9]{3}-[0-9]{2}-[0-9]{4}" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: Potential SSN detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 9. Phone numbers
echo "📞 Checking for phone numbers..."
if grep -E "\+?[1-9][0-9]{1,3}[\s-]?\(?[0-9]{3}\)?[\s-]?[0-9]{3}[\s-]?[0-9]{4}" "$FILE_PATH" 2>/dev/null; then
    echo "⚠️ Phone numbers detected - verify if intentional"
    WARNINGS=$((WARNINGS + 1))
fi

# Summary
echo ""
echo "📊 Security Scan Results:"
echo "  • Critical Issues: $SECURITY_ISSUES"
echo "  • Warnings: $WARNINGS"

if [ $SECURITY_ISSUES -gt 0 ]; then
    echo ""
    echo "🚨 CRITICAL SECURITY ALERT!"
    echo "🛡️ Action Required:"
    echo "  • Review detected sensitive data immediately"
    echo "  • Remove or mask sensitive information"
    echo "  • Use environment variables for secrets"
    echo "  • Consider using a secrets management service"
    echo "  • Check if file should be added to .gitignore"
fi

if [ $WARNINGS -gt 0 ]; then
    echo ""
    echo "⚠️ Security Warnings:"
    echo "  • Review detected information for necessity"
    echo "  • Consider data privacy implications"
    echo "  • Verify compliance with data protection regulations"
fi

echo ""
echo "💡 Security Best Practices:"
echo "  • Use environment variables for sensitive data"
echo "  • Implement proper secrets management"
echo "  • Add sensitive files to .gitignore"
echo "  • Regular security audits of codebase"
echo "  • Use code scanning tools in CI/CD"

echo ""
echo "🎯 Security scan complete!"

exit 0
Full copyable content
{
  "hooks": {
    "notification": {
      "script": "./.claude/hooks/sensitive-data-alert-scanner.sh",
      "matchers": [
        "*"
      ]
    }
  }
}

About this resource

Features

  • Real-time sensitive data detection including sensitive data detection integration (real-time sensitive data scanning on file changes, immediate security alerts with alert notifications, sensitive data pattern detection with pattern matching, sensitive data validation with data validation), detection optimization (detection performance with fast scanning, detection accuracy with accurate pattern matching, detection efficiency with efficient processing, detection coverage with comprehensive patterns), detection validation (sensitive data validation with data verification, false positive reduction with filtering, sensitive data classification with classification, sensitive data severity assessment with severity levels), and detection reporting (sensitive data detection reporting with detection results, sensitive data location reporting with file locations, sensitive data severity reporting with severity levels, sensitive data remediation reporting with remediation suggestions)
  • API key and token scanning including API key detection (API key pattern detection with comprehensive patterns, API key validation with key verification, API key classification with key classification, API key severity assessment with severity levels), token detection (access token detection with token patterns, refresh token detection with refresh patterns, JWT token detection with JWT patterns, OAuth token detection with OAuth patterns), API key management (API key exclusion configuration with exclusion patterns, API key ignore file configuration with ignore files, API key scanning optimization with optimization, API key scanning performance with performance tuning), and API key reporting (API key detection reporting with detection results, API key location reporting with file locations, API key severity reporting with severity levels, API key remediation reporting with remediation suggestions)
  • Password exposure prevention including password detection (password pattern detection with password patterns, hardcoded password detection with hardcoded patterns, password hash detection with hash patterns, password placeholder detection with placeholder filtering), password validation (password validation with verification, false positive reduction with filtering, password classification with classification, password severity assessment with severity levels), password management (password exclusion configuration with exclusion patterns, password ignore file configuration with ignore files, password scanning optimization with optimization, password scanning performance with performance tuning), and password reporting (password detection reporting with detection results, password location reporting with file locations, password severity reporting with severity levels, password remediation reporting with remediation suggestions)
  • Email address detection including email detection (email address pattern detection with email patterns, email validation with email verification, email classification with email classification, email severity assessment with severity levels), email management (email exclusion configuration with exclusion patterns, email ignore file configuration with ignore files, email scanning optimization with optimization, email scanning performance with performance tuning), and email reporting (email detection reporting with detection results, email location reporting with file locations, email severity reporting with severity levels, email remediation reporting with remediation suggestions)
  • Personal information monitoring including PII detection (personally identifiable information detection with PII patterns, SSN detection with SSN patterns, credit card detection with credit card patterns, phone number detection with phone patterns), PII validation (PII validation with verification, false positive reduction with filtering, PII classification with classification, PII severity assessment with severity levels), PII management (PII exclusion configuration with exclusion patterns, PII ignore file configuration with ignore files, PII scanning optimization with optimization, PII scanning performance with performance tuning), and PII reporting (PII detection reporting with detection results, PII location reporting with file locations, PII severity reporting with severity levels, PII remediation reporting with remediation suggestions)
  • Immediate security alerts including alert generation (immediate security alert generation with real-time alerts, security alert notification with alert notifications, security alert prioritization with alert priorities, security alert routing with alert routing), alert configuration (alert threshold configuration with threshold settings, alert severity configuration with severity levels, alert notification configuration with notification settings, alert routing configuration with routing settings), alert management (alert suppression configuration with suppression rules, alert deduplication with duplicate detection, alert aggregation with alert aggregation, alert escalation with escalation rules), and alert reporting (alert generation reporting with alert status, alert notification reporting with notification status, alert resolution reporting with resolution status, alert statistics with alert metrics)
  • Database and credential scanning including database credential detection (database connection string detection with connection patterns, database credential validation with credential verification, database password detection with password patterns, database URL detection with URL patterns), credential management (credential exclusion configuration with exclusion patterns, credential ignore file configuration with ignore files, credential scanning optimization with optimization, credential scanning performance with performance tuning), and credential reporting (credential detection reporting with detection results, credential location reporting with file locations, credential severity reporting with severity levels, credential remediation reporting with remediation suggestions)
  • Development workflow integration including continuous monitoring (real-time sensitive data monitoring on file changes, immediate security alerts on data exposure, automatic data detection on file modifications, seamless security integration with development workflow), workflow automation (automated sensitive data detection without manual intervention, detection automation with automatic detection, alert automation with automatic alerts), and workflow optimization (sensitive data change detection with change tracking, detection optimization with optimization, sensitive data consistency maintenance with consistency checks)

Use Cases

  • Prevent accidental commits of API keys and secrets automatically detecting API keys and secrets in code, alerting immediately, and preventing sensitive data exposure
  • Detect exposed passwords in code files automatically scanning for password patterns, detecting hardcoded passwords, and alerting on password exposure
  • Monitor for personal information leaks automatically detecting PII patterns (SSN, credit cards, phone numbers), alerting on PII exposure, and maintaining privacy compliance
  • Alert on potential security vulnerabilities automatically detecting security-sensitive patterns, providing immediate alerts, and preventing security issues
  • Scan for hardcoded credentials automatically detecting hardcoded credentials, database connection strings, and authentication tokens, and alerting on credential exposure
  • Development workflow integration seamlessly integrating sensitive data detection into development workflows without manual security checks or data scanning

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/sensitive-data-alert-scanner.sh
  3. Make executable: chmod +x .claude/hooks/sensitive-data-alert-scanner.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • grep command (standard Unix tool)
  • jq (optional, for JSON parsing)
  • file command (optional, for binary file detection)
  • awk (optional, for comment filtering)

Hook Configuration

{
  "hooks": {
    "notification": {
      "script": "./.claude/hooks/sensitive-data-alert-scanner.sh",
      "matchers": ["*"]
    }
  }
}

Hook Script

#!/bin/bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

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

# Only scan for Write and Edit operations
if [[ "$TOOL_NAME" != "Write" && "$TOOL_NAME" != "Edit" ]]; then
  exit 0
fi

echo "🔒 Sensitive Data Alert Scanner - Analyzing file for security risks..."
echo "📄 File: $FILE_PATH"

# Check if file exists and is readable
if [ ! -f "$FILE_PATH" ]; then
    echo "⚠️ File not found: $FILE_PATH"
    exit 0
fi

# Skip binary files
if file "$FILE_PATH" | grep -q binary; then
    echo "ℹ️ Skipping binary file"
    exit 0
fi

SECURITY_ISSUES=0
WARNINGS=0

echo "🔍 Scanning for sensitive data patterns..."

# 1. API Keys and Secrets
echo "🔑 Checking for API keys and secrets..."
API_PATTERNS=(
    "api[_-]?key\s*[:=]\s*[\"'][^\"']{8,}[\"']"
    "secret[_-]?key\s*[:=]\s*[\"'][^\"']{8,}[\"']"
    "access[_-]?token\s*[:=]\s*[\"'][^\"']{10,}[\"']"
    "private[_-]?key\s*[:=]\s*[\"'][^\"']{20,}[\"']"
    "client[_-]?secret\s*[:=]\s*[\"'][^\"']{8,}[\"']"
)

for pattern in "${API_PATTERNS[@]}"; do
    if grep -iE "$pattern" "$FILE_PATH" 2>/dev/null | grep -v -iE "(\*\*\*|example|placeholder|your[_-]|demo|test|fake|dummy)"; then
        echo "🚨 SECURITY ALERT: Potential API key/secret detected!"
        SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
    fi
done

# 2. Password patterns
echo "🔐 Checking for password exposure..."
PASSWORD_PATTERNS=(
    "password\s*[:=]\s*[\"'][^\"']{6,}[\"']"
    "passwd\s*[:=]\s*[\"'][^\"']{6,}[\"']"
    "pwd\s*[:=]\s*[\"'][^\"']{6,}[\"']"
)

for pattern in "${PASSWORD_PATTERNS[@]}"; do
    if grep -iE "$pattern" "$FILE_PATH" 2>/dev/null | grep -v -iE "(\*\*\*|example|placeholder|your[_-]|demo|test|123456|password)"; then
        echo "🚨 SECURITY ALERT: Potential password detected!"
        SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
    fi
done

# 3. Database connection strings
echo "🗄️ Checking for database credentials..."
if grep -iE "(mysql://|postgresql://|mongodb://|redis://).*:.*@" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: Database connection string with credentials detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 4. JWT tokens
echo "🎫 Checking for JWT tokens..."
if grep -E "eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: JWT token detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 5. SSH private keys
echo "🔑 Checking for SSH private keys..."
if grep -q "BEGIN.*PRIVATE KEY" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: SSH private key detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 6. Email addresses (warning, not critical)
echo "📧 Checking for email addresses..."
if grep -E "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}" "$FILE_PATH" 2>/dev/null | head -3; then
    echo "⚠️ Email addresses detected - ensure this is intentional"
    WARNINGS=$((WARNINGS + 1))
fi

# 7. Credit card patterns (basic check)
echo "💳 Checking for credit card numbers..."
if grep -E "[0-9]{4}[\s-]?[0-9]{4}[\s-]?[0-9]{4}[\s-]?[0-9]{4}" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: Potential credit card number detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 8. Social Security Numbers (US format)
echo "🆔 Checking for SSN patterns..."
if grep -E "[0-9]{3}-[0-9]{2}-[0-9]{4}" "$FILE_PATH" 2>/dev/null; then
    echo "🚨 SECURITY ALERT: Potential SSN detected!"
    SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi

# 9. Phone numbers
echo "📞 Checking for phone numbers..."
if grep -E "\+?[1-9][0-9]{1,3}[\s-]?\(?[0-9]{3}\)?[\s-]?[0-9]{3}[\s-]?[0-9]{4}" "$FILE_PATH" 2>/dev/null; then
    echo "⚠️ Phone numbers detected - verify if intentional"
    WARNINGS=$((WARNINGS + 1))
fi

# Summary
echo ""
echo "📊 Security Scan Results:"
echo "  • Critical Issues: $SECURITY_ISSUES"
echo "  • Warnings: $WARNINGS"

if [ $SECURITY_ISSUES -gt 0 ]; then
    echo ""
    echo "🚨 CRITICAL SECURITY ALERT!"
    echo "🛡️ Action Required:"
    echo "  • Review detected sensitive data immediately"
    echo "  • Remove or mask sensitive information"
    echo "  • Use environment variables for secrets"
    echo "  • Consider using a secrets management service"
    echo "  • Check if file should be added to .gitignore"
fi

if [ $WARNINGS -gt 0 ]; then
    echo ""
    echo "⚠️ Security Warnings:"
    echo "  • Review detected information for necessity"
    echo "  • Consider data privacy implications"
    echo "  • Verify compliance with data protection regulations"
fi

echo ""
echo "💡 Security Best Practices:"
echo "  • Use environment variables for sensitive data"
echo "  • Implement proper secrets management"
echo "  • Add sensitive files to .gitignore"
echo "  • Regular security audits of codebase"
echo "  • Use code scanning tools in CI/CD"

echo ""
echo "🎯 Security scan complete!"

exit 0

Examples

Sensitive Data Alert Scanner Hook Script

Complete hook script that scans for sensitive data and alerts immediately

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
  exit 0
fi
if [[ "$FILE_PATH" == *.test.* ]] || [[ "$FILE_PATH" == *fixture* ]]; then
  exit 0
fi
SECURITY_ISSUES=0
if grep -iE "api[_-]?key\s*[:=]\s*[\"'][^\"']{8,}[\"']" "$FILE_PATH" 2>/dev/null | grep -v -iE "(example|placeholder|your[_-]|demo|test)"; then
  echo "🚨 SECURITY ALERT: Potential API key detected!"
  SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi
if [ $SECURITY_ISSUES -gt 0 ]; then
  exit 1
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable sensitive data scanning

{
  "hooks": {
    "notification": {
      "script": "./.claude/hooks/sensitive-data-alert-scanner.sh",
      "matchers": ["*"]
    }
  }
}

Enhanced Scanner with File Wait and Ignore Support

Enhanced hook script with file wait retry loop and .securityignore file support

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -f ".securityignore" ] && grep -qF "$FILE_PATH" .securityignore; then
  exit 0
fi
for i in {1..5}; do
  [ -f "$FILE_PATH" ] && break
  sleep 0.1
done
if [ ! -f "$FILE_PATH" ]; then
  exit 0
fi
SECURITY_ISSUES=0
if grep -iE "password\s*[:=]\s*[\"'][^\"']{6,}[\"']" "$FILE_PATH" 2>/dev/null | grep -v -iE "(example|placeholder|your[_-]|demo|test|123456|password)"; then
  echo "🚨 SECURITY ALERT: Potential password detected!"
  SECURITY_ISSUES=$((SECURITY_ISSUES + 1))
fi
if [ $SECURITY_ISSUES -gt 0 ]; then
  exit 1
fi
exit 0

Comment-Aware Sensitive Data Scanning

Enhanced hook script that filters out commented lines before scanning for sensitive data

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if grep -qE "^\s*[#/]" "$FILE_PATH" 2>/dev/null; then
  CONTENT=$(awk '!/^\s*[#/]/' "$FILE_PATH" 2>/dev/null)
else
  CONTENT=$(cat "$FILE_PATH" 2>/dev/null)
fi
if echo "$CONTENT" | grep -iE "api[_-]?key\s*[:=]\s*[\"'][^\"']{8,}[\"']" | grep -v -iE "(example|placeholder|your[_-]|demo|test)"; then
  echo "🚨 SECURITY ALERT: Potential API key detected!"
  exit 1
fi
exit 0

Sensitive Data Scanner Configuration Example

Example sensitive data scanner configuration for customizing scan behavior

{
  "sensitive_data": {
    "exclude_patterns": ["test/**", "**/fixtures/*", "*.test.*"],
    "ignore_file": ".securityignore",
    "alert_threshold": "high",
    "patterns": {
      "api_keys": true,
      "passwords": true,
      "tokens": true,
      "credentials": true,
      "pii": true
    }
  }
}

Troubleshooting

False positives on example code and test fixtures with dummy keys

Exclusion patterns filter common placeholders but miss context-specific ones. Add .securityignore file and check: grep -qF "$FILE_PATH" .securityignore && exit 0 to whitelist specific files or patterns. Verify exclusion patterns. Test with various test file configurations.

Notification hook timing runs before file write completes causing empty scans

Notification hooks fire during operation, not after. File may not exist yet. Add retry loop: for i in {1..5}; do [ -f "$FILE_PATH" ] && break; sleep 0.1; done before scanning to ensure file availability. Verify file existence. Test with various file write scenarios.

Notification hook receives different INPUT schema than PostToolUse

Notification hooks fire mid-operation with partial data. Input may lack file_path or use alternative fields. Extend jq filter: '.file_path // .tool_input.file_path // .path // ""' to handle schema variations across hook types. Verify input schema. Test with various hook types.

Grep patterns match commented-out secrets in code documentation

Current regex doesn't exclude comments. Add language-aware filtering: grep -v '^\s*[#/]' for basic comment detection, or use awk to skip comment blocks before pattern matching for comprehensive filtering. Verify comment filtering. Test with various comment styles.

Security scan exits zero even when critical issues detected

Script always exits 0 regardless of SECURITY_ISSUES count. Change final exit: [ $SECURITY_ISSUES -gt 0 ] && exit 1 || exit 0 to fail hook on findings, forcing Claude to acknowledge security alerts before proceeding. Verify exit codes. Test with various security issue scenarios.

Pattern matching is too broad and flags legitimate code

Refine regex patterns to be more specific. Add context-aware filtering: check for surrounding code context, variable names, or function signatures. Use negative lookahead patterns to exclude common false positives. Verify pattern specificity. Test with various code patterns.

Binary files cause grep errors or false positives

Add binary file detection: if file "$FILE_PATH" | grep -q binary; then exit 0; fi before scanning. Use file command to detect binary files and skip them. Verify binary detection. Test with various file types.

Multiple sensitive data patterns detected but only one alert shown

Script may exit early on first match. Remove early exits and collect all matches before reporting. Use array to store all findings, then report all at once. Verify match collection. Test with multiple pattern matches.

Source citations

Add this badge to your README

Show that Sensitive Data Alert Scanner - Hooks 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/sensitive-data-alert-scanner.svg)](https://heyclau.de/entry/hooks/sensitive-data-alert-scanner)

How it compares

Sensitive Data Alert Scanner - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

1 trust signal differ across this comparison (Submitter).

Field

Scans for potential sensitive data exposure and alerts immediately.

Open dossier

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

A Claude Code hook that flags files exceeding complexity thresholds after you edit them — estimating cyclomatic complexity, line and function counts, and nesting depth (via ESLint's complexity rule and Radon).

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 reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
SubmitterDiffersjony376
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
BrandDocker logoDocker
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredjony376JSONboredJSONbored
Added2025-09-192026-06-042025-09-192025-10-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns 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 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 after edits to JS/TS/Python files and prints advisory warnings only; the line/function/brace counts are heuristics, not a substitute for ESLint or Radon run on the full project.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 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.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.Reads the contents of files you edit to compute complexity locally; it prints warnings to hook output and does not transmit code, but those messages can reveal file structure.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— none listed
  • 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 .claude/hooks && touch .claude/hooks/sensitive-data-alert-scanner.sh && chmod +x .claude/hooks/sensitive-data-alert-scanner.sh
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/code-complexity-alert-monitor.sh && chmod +x .claude/hooks/code-complexity-alert-monitor.sh
mkdir -p .claude/hooks && touch .claude/hooks/docker-image-security-scanner.sh && chmod +x .claude/hooks/docker-image-security-scanner.sh
Config
{
  "hooks": {
    "notification": {
      "script": "./.claude/hooks/sensitive-data-alert-scanner.sh",
      "matchers": [
        "*"
      ]
    }
  }
}
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "$HOME/.claude/hooks/pre-write-secret-scanner.sh"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "notification": {
      "script": "./.claude/hooks/code-complexity-alert-monitor.sh"
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/docker-image-security-scanner.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 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.