#!/bin/bash
# Reads the bash command Claude is about to run.
# If it's a package install, checks Socket.dev for security risks.
# Exit 2 blocks the install and sends findings to Claude.

INPUT=$(cat)
CMD=$(echo "$INPUT" | python3 -c "
import sys, json
try:
    d = json.load(sys.stdin)
    print(d.get('tool_input', {}).get('command', ''))
except:
    print('')
" 2>/dev/null)

# Claude Code's Bash tool typically wraps the real command as
# `cd "<dir>" && <command>`, so the install keyword usually isn't at the
# very start of $CMD. Split on chaining operators (&&, ||, ;, |) and check
# each sub-command individually against the anchored pattern below.
INSTALL_RE='^[[:space:]]*(npm install|npm i|pnpm add|pnpm install|pnpm i|yarn add|pip install|pip3 install)[[:space:]]+[a-zA-Z@-]'
SUBCMD=""
while IFS= read -r part; do
    if echo "$part" | grep -qE "$INSTALL_RE"; then
        SUBCMD="$part"
        break
    fi
done <<EOF
$(echo "$CMD" | sed -E 's/(&&|\|\||;|\|)/\n/g')
EOF

if [ -z "$SUBCMD" ]; then
    exit 0  # Not an install command — let it proceed
fi

# Extract the package name: drop the keyword, then take the first token
# that isn't a flag (so `pnpm add -D lodash` correctly yields "lodash").
# Uses [[:space:]] rather than \s — macOS's BSD sed doesn't support \s.
PKG=$(echo "$SUBCMD" | sed -E 's/^[[:space:]]*(npm install|npm i|pnpm add|pnpm install|pnpm i|yarn add|pip install|pip3 install)[[:space:]]+//' | tr ' ' '\n' | grep -vE '^-' | head -1)

if [ -z "$PKG" ]; then
    exit 0  # Couldn't parse package name — let it through
fi

# Determine package manager and check Socket.dev
# npm, pnpm, and yarn all pull from the npm registry; only pip/pip3 use PyPI
if echo "$SUBCMD" | grep -qE '^[[:space:]]*(npm|pnpm|yarn)[[:space:]]'; then
    REGISTRY="npm"
    URL="https://socket.dev/npm/package/$PKG"
else
    REGISTRY="pypi"
    URL="https://socket.dev/pypi/package/$PKG"
fi

# Run the Socket.dev check
RESULT=$(curl -sL --max-time 10 "$URL" 2>/dev/null | \
    grep -iE "supply chain|malware|critical|high risk|typosquat|score|alert" | \
    head -5)

# Block the install and send findings to Claude
{
    echo "SOCKET.DEV SECURITY CHECK — $REGISTRY package: $PKG"
    echo "URL checked: $URL"
    if [ -n "$RESULT" ]; then
        echo "FINDINGS:"
        echo "$RESULT"
    else
        echo "No risk flags detected (or Socket.dev returned no matching data)."
        echo "Note: If the page was unreachable, treat this as UNVERIFIED — do not install without telling Jonathan."
    fi
    echo ""
    echo "INSTRUCTION: Report these findings to Jonathan in plain English before proceeding."
    echo "Use the reporting format in CLAUDE.md. Wait for Jonathan to type 'yes, install it' or 'go ahead' before retrying."
} >&2

exit 2  # Block the install
