# Security Scan Hook

_Reference template. Adapt it to your environment before you use it._

A PostToolUse hook that fires after every file edit. Deterministic pattern detection, no AI judgment.

## Configuration

Add to your `.claude/settings.json`:

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "bash .claude/hooks/security-scan.sh"
          }
        ]
      }
    ]
  }
}
```

## Hook Script (`.claude/hooks/security-scan.sh`)

Hook input arrives as JSON on stdin. Exit code 2 feeds stderr back to the model.

```bash
#!/bin/bash
# Security scan: runs after every file edit
# Deterministic pattern detection, no AI judgment

FILE="$(jq -r '.tool_input.file_path // empty')"

if [ -z "$FILE" ] || [ ! -f "$FILE" ]; then
  exit 0
fi

ISSUES=""

# Hardcoded secrets
if grep -qiE "(api[_-]?key|secret|password|token)\s*[=:]\s*['\"][^'\"]{8,}" "$FILE"; then
  ISSUES="${ISSUES}[CRITICAL] Possible hardcoded secret detected\n"
fi

# Common token prefixes
if grep -qE "(sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{20,}|xox[bap]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{35})" "$FILE"; then
  ISSUES="${ISSUES}[CRITICAL] Known token prefix detected\n"
fi

# AWS keys
if grep -qE "AKIA[0-9A-Z]{16}" "$FILE"; then
  ISSUES="${ISSUES}[CRITICAL] AWS access key detected\n"
fi

# Private keys
if grep -q "BEGIN.*PRIVATE KEY" "$FILE"; then
  ISSUES="${ISSUES}[CRITICAL] Private key detected\n"
fi

# HTTP endpoints (should be HTTPS), ignoring localhost
if grep -E 'http://' "$FILE" | grep -vqE 'http://(localhost|127\.0\.0\.1)'; then
  ISSUES="${ISSUES}[WARNING] Non-HTTPS endpoint detected\n"
fi

# Connection strings
if grep -qiE "(mongodb|postgres|mysql|redis)://[^$]" "$FILE"; then
  ISSUES="${ISSUES}[CRITICAL] Hardcoded connection string detected\n"
fi

if [ -n "$ISSUES" ]; then
  {
    printf '=== SECURITY SCAN FAILED ===\n'
    printf '%b' "$ISSUES"
    printf 'File: %s\n' "$FILE"
    printf '===========================\n'
  } >&2
  exit 2
fi

exit 0
```

## Why Deterministic?
- No AI judgment means no hallucinated passes
- Runs 100% of the time, no skipping
- Catches structured patterns (keys, tokens, connection strings)
- Contextual analysis (names in prose, embedded terms) should be handled separately by a human or a dedicated review
- Pattern matching is a floor, not a scanner. Pair it with a dedicated secret scanner in CI.
