#!/usr/bin/env bash
# hook-utils.sh -- Shared validation for all governance hooks.
#
# Source this file at the top of every hook script:
#   SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
#   source "$SCRIPT_DIR/hook-utils.sh"
#
# Provides:
#   validate_input()  - Read and validate stdin JSON
#   $HOOK_INPUT       - Validated JSON string
#   $HOOK_TOOL_NAME   - Extracted tool_name
#   $HOOK_TOOL_INPUT  - Extracted tool_input
#
# @connexum/ai-governance

# Maximum input size (1MB). Larger inputs are rejected to prevent
# resource exhaustion and buffer overflow in jq processing.
MAX_INPUT_BYTES=1048576

validate_input() {
  # Read all stdin
  HOOK_INPUT=$(cat)

  # Check input size
  INPUT_SIZE=${#HOOK_INPUT}
  if [ "$INPUT_SIZE" -gt "$MAX_INPUT_BYTES" ]; then
    echo "BLOCKED: Hook input exceeds maximum size (${INPUT_SIZE} bytes > ${MAX_INPUT_BYTES} bytes). Possible injection attempt." >&2
    exit 2
  fi

  # Check for empty input
  if [ -z "$HOOK_INPUT" ]; then
    # No input = nothing to gate
    exit 0
  fi

  # Validate JSON structure (jq will fail on non-JSON)
  if ! echo "$HOOK_INPUT" | jq empty 2>/dev/null; then
    echo "BLOCKED: Hook input is not valid JSON. Possible injection attempt." >&2
    exit 2
  fi

  # Validate expected top-level fields exist
  HOOK_TOOL_NAME=$(echo "$HOOK_INPUT" | jq -r '.tool_name // empty' 2>/dev/null)
  HOOK_TOOL_INPUT=$(echo "$HOOK_INPUT" | jq -r '.tool_input // empty' 2>/dev/null)

  # Export for use in calling script
  export HOOK_INPUT
  export HOOK_TOOL_NAME
  export HOOK_TOOL_INPUT
}
