#!/usr/bin/env bash
# SPDX-License-Identifier: MPL-2.0
#
# Ianitor pre-commit hook. Rejects staged files that must never be in git:
#   - binaries: any NUL byte anywhere in the staged blob (git attributes do not matter)
#   - private keys: PEM/PKCS#8/OpenSSH/PGP blocks, SSH2 (RFC 4716) keys, PuTTY .ppk,
#     age secret keys, JWK private keys (an object with "kty" RSA/EC/OKP and "d"),
#     WireGuard private keys (wg-quick `PrivateKey =` or YAML `private_key:`), and
#     key-store file names
#   - files over 5 MB (5,000,000 bytes, as CLAUDE.md says)
#   - build output and dependencies: target/, node_modules/, dist/, .svelte-kit/ anywhere;
#     build/ at the repository root, in apps/<app>/, or next to a package.json
# Name checks are case-insensitive. Paths are read NUL-separated, so quotes, tabs,
# backslashes or newlines in file names cannot slip past. A staged file that cannot be read,
# or any git command that fails, blocks the commit.
#
# Contents are checked in a few batch passes over the index (one `git cat-file`, two
# `git grep`), not with processes per file.
#
# Enable once per clone:   git config core.hooksPath .githooks
# Test it:                 bash .githooks/test-pre-commit.sh

if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
    echo "pre-commit: needs bash 4 or newer (this is ${BASH_VERSION:-not bash}); commit blocked." >&2
    echo "pre-commit: use Git Bash on Windows, any Linux, or a newer bash on macOS." >&2
    exit 1
fi

set -u
LIMIT=5000000

# Patterns are written so that this file does not match them itself. They are matched
# case-insensitively.
KEY_PATTERNS=(
    '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----'
    '---- BEGIN SSH2 ENCRYPTED PRIVATE KEY[ ]----'
    '---- BEGIN SSH2 PRIVATE KEY[ ]----'
    'PuTTY-User-Key-File-[0-9]+:'
    'AGE-SECRET-KEY-[1][0-9A-Z]+'
    '^[[:space:]]*(-[[:space:]]*)?["'\'']?private_?key["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9+/]{42,43}=?["'\'']?[[:space:]]*,?[[:space:]]*$'
)
# One flat JSON object (JWK members are flat) holding a private-key parameter set.
JWK_OBJECT='\{[^{}]*\}'
JWK_KTY='"kt[y]"[[:space:]]*:[[:space:]]*"(RSA|EC|OKP)"'
JWK_D='"[d]"[[:space:]]*:[[:space:]]*"'

failed=0
reject() {
    # %q keeps odd characters in names visible and harmless.
    printf 'pre-commit: rejected %q: %s\n' "$1" "$2" >&2
    failed=1
}
die() {
    echo "pre-commit: $1; commit blocked." >&2
    exit 1
}

tmp=$(mktemp -d 2>/dev/null || { d="${TMPDIR:-/tmp}/ianitor-pre-commit.$$"; mkdir -p "$d" && echo "$d"; }) ||
    die "cannot create a temporary directory"
trap 'rm -rf "$tmp"' EXIT

git diff --cached --raw -z --no-abbrev --no-renames --diff-filter=ACMT >"$tmp/list" ||
    die "cannot list the staged files"
git ls-files -z -- ':(glob)**/package.json' >"$tmp/packages" ||
    die "cannot list package.json files"

declare -A staged=() pkgdir=()
paths=() shas=()

while IFS= read -r -d '' p; do
    d=${p%package.json}
    d=${d%/}
    # The root package.json needs no entry: build/ at the root is always output.
    [ -n "$d" ] && pkgdir[${d,,}]=1
done <"$tmp/packages"

# build/ is output only at the root, in apps/<app>/ or beside a package.json.
is_build_output() {
    local lower=$1 prefix=
    [[ $lower == build/* || $lower =~ ^apps/[^/]+/build/ ]] && return 0
    local rest=$lower part
    while [[ $rest == */* ]]; do
        part=${rest%%/*}
        rest=${rest#*/}
        if [[ $part == build && -n $prefix && -n ${pkgdir[${prefix%/}]+x} ]]; then
            return 0
        fi
        prefix+="$part/"
    done
    return 1
}

# --raw -z gives ":<old mode> <new mode> <old sha> <new sha> <status>" NUL "<path>" NUL.
while IFS= read -r -d '' meta && IFS= read -r -d '' path; do
    read -r -a f <<<"${meta#:}"
    mode=${f[1]} sha=${f[3]}
    lower=${path,,}

    case "/$lower" in
        */target/*|*/node_modules/*|*/dist/*|*/.svelte-kit/*)
            reject "$path" "build output or dependency directory" ;;
    esac
    if is_build_output "$lower"; then
        reject "$path" "build output directory"
    fi

    base=${lower##*/}
    case "$base" in
        *.pub) ;;
        *.key|*.p12|*.pfx|*.jks|*.keystore|*.ppk|id_rsa|id_dsa|id_ecdsa|id_ed25519|id_rsa.*|id_dsa.*|id_ecdsa.*|id_ed25519.*)
            reject "$path" "private key file name" ;;
    esac

    # Submodule entries have no blob to inspect.
    [ "$mode" = 160000 ] && continue
    staged[$path]=$sha
    paths+=("$path")
    shas+=("$sha")
done <"$tmp/list"

if [ "${#paths[@]}" -gt 0 ]; then
    # Sizes: one batch for every blob, in order.
    printf '%s\n' "${shas[@]}" | git cat-file --batch-check='%(objectname) %(objecttype) %(objectsize)' >"$tmp/sizes" ||
        die "cannot read the staged blobs"
    i=0
    while read -r _ type size; do
        p=${paths[$i]}
        if [ "$type" != blob ] || ! [[ $size =~ ^[0-9]+$ ]]; then
            reject "$p" "the staged content cannot be read"
        elif (( size > LIMIT )); then
            reject "$p" "$size bytes is over the 5 MB limit (5,000,000 bytes)"
        fi
        i=$((i + 1))
    done <"$tmp/sizes"
    [ "$i" -eq "${#paths[@]}" ] || die "cannot read the size of every staged blob"

    # Contents: git grep over the index, every file read as text (-a), names NUL-separated,
    # then kept only when staged. Exit 1 means no match; anything above blocks the commit.
    search() {
        local out=$1 rc
        shift
        git -c grep.fullName=true -c color.grep=never grep --cached --no-recurse-submodules \
            -a -l -z "$@" >"$out"
        rc=$?
        [ "$rc" -le 1 ] || die "git grep failed (exit $rc)"
    }

    search "$tmp/nul" -P '\x00'
    while IFS= read -r -d '' p; do
        [ -n "${staged[$p]+x}" ] && reject "$p" "binary file (contains NUL bytes)"
    done <"$tmp/nul"

    args=()
    for pattern in "${KEY_PATTERNS[@]}"; do args+=(-e "$pattern"); done
    search "$tmp/keys" -i -E "${args[@]}"
    while IFS= read -r -d '' p; do
        [ -n "${staged[$p]+x}" ] && reject "$p" "contains a private key"
    done <"$tmp/keys"

    # JWK members may span lines, so candidates are flattened and split into objects.
    search "$tmp/jwk" -F -e '"kt''y"'
    while IFS= read -r -d '' p; do
        [ -n "${staged[$p]+x}" ] || continue
        if git cat-file blob "${staged[$p]}" | tr '\r\n\t' '   ' | grep -a -o -E "$JWK_OBJECT" |
            grep -a -E "$JWK_KTY" | grep -a -q -E "$JWK_D"; then
            reject "$p" "contains a JWK private key"
        fi
    done <"$tmp/jwk"
fi

if [ "$failed" -ne 0 ]; then
    echo 'pre-commit: commit blocked. Unstage the files above (git rm --cached <file>).' >&2
    exit 1
fi
exit 0
