#!/bin/bash
# PostToolUse hook: Detect potential secrets in written/edited files
# Prints warning to stderr if patterns matching API keys, passwords, or tokens are found
# Does NOT block the operation — just warns
# NOTE: This script needs chmod +x to be executable

PROJECT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"

# Read the tool input from stdin to get the modified file path
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',{}).get('file_path',''))" 2>/dev/null)

# Skip if we couldn't determine the file, or if it's a known safe file type
if [ -z "$FILE_PATH" ] || [ "$FILE_PATH" = "" ]; then
    exit 0
fi

# Skip binary files and known safe files
case "$FILE_PATH" in
    *.png|*.jpg|*.jpeg|*.gif|*.ico|*.woff|*.woff2|*.ttf|*.eot|*.svg)
        exit 0
        ;;
    */.env.example|*/CLAUDE.md|*/.gitignore)
        # These files may legitimately contain key names (not values)
        exit 0
        ;;
esac

# Only check if the file exists and is readable
if [ ! -f "$FILE_PATH" ] || [ ! -r "$FILE_PATH" ]; then
    exit 0
fi

# Check for common secret patterns
# Using grep with extended regex; -c counts matches
WARNINGS=""

# API keys (common formats: sk_, pk_, api_, key_, token_)
if grep -qE '(sk_live_|pk_live_|sk_test_|pk_test_)[a-zA-Z0-9]{20,}' "$FILE_PATH" 2>/dev/null; then
    WARNINGS="${WARNINGS}\n  - Possible Stripe key detected"
fi

if grep -qE '(AKIA|ASIA)[A-Z0-9]{16}' "$FILE_PATH" 2>/dev/null; then
    WARNINGS="${WARNINGS}\n  - Possible AWS access key detected"
fi

# Generic secret patterns (assignments like KEY = "value" or KEY: "value")
if grep -qE '(api[_-]?key|api[_-]?secret|auth[_-]?token|access[_-]?token|secret[_-]?key|private[_-]?key|password)\s*[:=]\s*["\x27][a-zA-Z0-9+/]{20,}' "$FILE_PATH" 2>/dev/null; then
    WARNINGS="${WARNINGS}\n  - Possible hardcoded secret (api_key/token/password assignment)"
fi

# .env file content outside of .env files
BASENAME=$(basename "$FILE_PATH")
if [[ "$BASENAME" != ".env"* ]] && [[ "$BASENAME" != "*.example" ]]; then
    if grep -qE '^[A-Z_]{3,}=.{10,}$' "$FILE_PATH" 2>/dev/null; then
        # Count how many lines match — if many, it's likely .env content pasted into a source file
        COUNT=$(grep -cE '^[A-Z_]{3,}=.{10,}$' "$FILE_PATH" 2>/dev/null)
        if [ "$COUNT" -ge 3 ]; then
            WARNINGS="${WARNINGS}\n  - File contains $COUNT lines that look like .env variable assignments"
        fi
    fi
fi

# Private keys
if grep -qE 'BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY' "$FILE_PATH" 2>/dev/null; then
    WARNINGS="${WARNINGS}\n  - Private key detected!"
fi

# Print warnings to stderr (does not block the operation)
if [ -n "$WARNINGS" ]; then
    echo "" >&2
    echo "WARNING: Potential secrets detected in $FILE_PATH:" >&2
    echo -e "$WARNINGS" >&2
    echo "  Review this file before committing." >&2
    echo "" >&2
fi

exit 0
