#!/usr/bin/env bash
# .claude/hooks/guard.sh: a PreToolUse hook for the few things that must never happen. CLAUDE.md can only ask; this
# denies, whatever the model decides. Keep it to these four, or nothing gets done:
#   1. secret files (.env, credentials, keys): never read, searched, edited, written, or named in a shell command
#   2. force push, push to main or master (named, or a bare push while on it), and --no-verify (or commit -n)
#   3. deleting a folder (rm -r in any form, find -delete): the human deletes folders
#   4. writing a kill-listed key or address (one per line in .claude/kill-list.txt, if it exists) into any file
# Every deny says what to do instead. Needs jq. A hook that crashes is skipped silently (fail-open), so this one never
# exits non-zero and denies when it cannot read its input; run .claude/hooks/guard.test.sh in CI to know it still works.
# The rule lines are the ones web/src/lib/hook-preview.mjs (SH) prints; scripts/hook-preview.test.mjs checks they match.
input=$(cat)
deny() { jq -cn --arg r "$1" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$r}}'; exit 0; }
if ! command -v jq >/dev/null 2>&1; then
  echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"guard.sh needs jq: install it, then retry"}}'
  exit 0
fi
jq -e . >/dev/null 2>&1 <<<"$input" || deny "guard.sh could not read its input, so the call is denied"
path=$(jq -r '.tool_input.file_path // .tool_input.notebook_path // .tool_input.path // empty' <<<"$input")
glob=$(jq -r '[.tool_input.glob, (if .tool_name == "Glob" then .tool_input.pattern else null end)] | map(select(. != null)) | join("\n")' <<<"$input")
cmd=$(jq -r '.tool_input.command // empty' <<<"$input")
body=$(jq -r '[.tool_input.content, .tool_input.new_string, .tool_input.new_source, (.tool_input.edits // [] | .[].new_string)] | map(select(. != null)) | join("\n")' <<<"$input")
# a shell command that writes a file (a redirect, tee, sed -i) counts as a body too; a plain query that only names a value,
# or throws its output away (>/dev/null), does not; => and -> are not redirects
[[ -n $cmd ]] && grep -qE '(^|[^0-9&>=-])>|(^|[^[:alnum:]_])(tee|sed[[:space:]]+-i)' <<<"$(sed -E 's#[0-9&]?>[[:space:]]*/dev/null##g' <<<"$cmd")" && body+=$'\n'"$cmd"

# 1. secret files; the committed templates (.env.example, .env.sample) are fine
secret='(^|[^[:alnum:]_])\.env($|[^[:alnum:]_])|credentials|id_rsa|id_ed25519|\.pem($|[^[:alnum:]_])'
strip() { sed -E 's/\.env\.(example|sample)//g' <<<"$1"; }
why="secret file: never read or change it. Need a variable's name? Read the code that references it."
[[ -n $path ]] && grep -qE "$secret" <<<"$(strip "$path")" && deny "$why"
[[ -n $glob ]] && grep -qE "$secret" <<<"$(strip "$glob")" && deny "$why"
[[ -n $cmd ]] && grep -qE "$secret" <<<"$(strip "$cmd")" && deny "$why"

# 2. git that rewrites or skips: print the command instead, the human runs it
if [[ -n $cmd ]] && grep -qE '(^|[^[:alnum:]_])git[[:space:]]' <<<"$cmd"; then
  grep -qE 'push[^;&|]*(--force|[[:space:]]-[[:alpha:]]*f[[:alpha:]]*([[:space:]]|$)|[[:space:]]\+)' <<<"$cmd" && deny "force push: print the command for the human to run"
  grep -qE 'push[^;&|]*([[:space:]:]|/)(main|master)([^[:alnum:]_./-]|$)|push[^;&|]*[[:space:]](--all|--mirror)' <<<"$cmd" && deny "push to main: push a feature branch and open a PR, or print the command for the human"
  branch=$(git -C "${CLAUDE_PROJECT_DIR:-.}" branch --show-current 2>/dev/null)
  [[ $branch == main || $branch == master ]] && grep -qE 'git([[:space:]]+-C[[:space:]]+[^[:space:]]+)?[[:space:]]+push([[:space:]]+-[^[:space:]]+)*([[:space:]]+[^-[:space:];&|][^[:space:];&|]*)?([[:space:]]+-[^[:space:]]+)*[[:space:]]*($|[;&|])|push[^;&|]*[[:space:]](HEAD|@)([[:space:]]|$)' <<<"$cmd" && deny "push while on $branch pushes $branch: switch to a feature branch, or print the command for the human"
  unq=$(sed -E "s/\"[^\"]*\"|'[^']*'//g" <<<"$cmd")
  grep -qE -- '--no-verify|commit[^;&|]*[[:space:]]-[[:alpha:]]*n[[:alpha:]]*([[:space:]]|$)' <<<"$unq" && deny "--no-verify skips the git hooks that are there to run: fix what they report"
fi

# 3. folder deletes
[[ -n $cmd ]] && grep -qE '(^|[;&|(`[:space:]/\])rm([[:space:]]+-[^[:space:]]*)*[[:space:]]+(-[[:alpha:]]*[rR]|--recursive)|(^|[^[:alnum:]_])find[[:space:]][^;&|]*[[:space:]]-delete' <<<"$cmd" && deny "deleting a folder: print the command for the human to run"

# 4. kill-listed keys and addresses never go into a file
list="${CLAUDE_PROJECT_DIR:-.}/.claude/kill-list.txt"
if [[ -n $body && -f $list ]]; then
  # || [[ -n $k ]]: the last line counts even with no newline after it
  while IFS= read -r k || [[ -n $k ]]; do
    k=${k%%#*}; k=${k//[[:space:]]/}
    [[ -n $k ]] && grep -qiF -- "$k" <<<"$body" && deny "kill-listed value ($k): never wire it into a file; ask which value replaces it"
  done < "$list"
fi
exit 0
