#!/bin/sh
# tests/run.sh - offline checks for plugin_fetch across all its modes.
#
# Everything runs against ./plugin_fetch with no outbound network at all: the
# HTTP/HTTPS legs talk to throwaway listeners started by tests/mockd.py on
# 127.0.0.1, and the suite reaches those loopback listeners through the
# plugin's explicit test-only private-address allowance. The SSRF policy
# itself is asserted through ./plugin_fetch --selftest, which is pure policy
# (no DNS, no sockets), so it holds on a machine with no network.
#
# It proves:
#   --meta        exact discovery JSON (name/desc/kind/mcp/daemon/menus/verified)
#   --mcp         initialize, tools/list (one tool, the exact schema),
#                 tools/call happy + error paths, ping, unknown method,
#                 unknown tool, notification silence, noise tolerance,
#                 string-vs-int argument coercion, the truncation footer
#   markdown      headings, links, lists, code, entities, boilerplate stripped,
#                 title notice, text/markdown verbatim, no-Content-Type sniff
#   transport     redirects (chain, relative Location, loop cap), 404/403/500,
#                 oversized Content-Length refused unread, chunked body,
#                 no-Content-Length body, gzip refused without zlib,
#                 the request shape (UA, Accept-Encoding, Connection), the
#                 5 MB / 100000 character caps
#   ssrf          the full v4+v6 deny matrix, the redirect-to-private refusal,
#                 FETCH_ALLOW_PRIVATE and the persisted policy toggle
#   tls           self-signed refused with no anchors, accepted with
#                 FETCH_TLS_CA_FILE, hostname mismatch refused
#   CGI           401 on every action, no gate when BOT_PASSWORD is unset,
#                 ?pwd= / X-Bot-Password, info, policy round-trip, unknown
#                 action, format=json matched as a real parameter
#   UI            generated page, no CDN, no <script src=, CSP, embed rule,
#                 no emoji, no raw private IP literal
#   source        no system()/popen, no DNS-rebind connect path, verify-peer
#                 with no insecure bypass
#   builds        ASan+UBSan and _FORTIFY_SOURCE=2 run the suite clean
#   audit         full-git-history secret / LAN-IP scan when the CLI is present
#
# Exit code 0 = everything passed.

set -u

ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT" || exit 1

BIN=./plugin_fetch
MCP=tests/mcp.py
PASS=0
FAIL=0

if [ -t 1 ]; then
    C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
else
    C_OK=; C_BAD=; C_B=; C_0=
fi
pass() { PASS=$((PASS + 1)); printf '  %sok%s   %s\n' "$C_OK" "$C_0" "$1"; }
fail() { FAIL=$((FAIL + 1)); printf '  %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }

check() { # check <desc> <expected-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
        fail "$1 (want: $2)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 400)"
    fi
}

check_not() { # check_not <desc> <forbidden-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then
        fail "$1 (must NOT contain: $2)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 300)"
    else pass "$1"; fi
}

section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }

json_ok() { # json_ok <desc> <json> [python-expression]
    expr=${3:-True}
    printf '%s' "$2" > "$WORK/j.json"
    if python3 -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if ($expr) else 1)" "$WORK/j.json" 2>/dev/null; then
        pass "$1"
    else
        fail "$1 (invalid JSON or assertion failed)"; printf '       got: %s\n' "$(printf '%s' "$2" | head -c 400)"
    fi
}

# strip CGI headers if present, drop CRs, keep the payload. Accepts the
# payload either as $1 or on stdin (a pipeline), so both call shapes work
# under set -u.
body() {
    if [ "$#" -eq 0 ] || [ -z "${1:-}" ]; then _b=$(cat); else _b="$1"; fi
    printf '%s\n' "$_b" | tr -d '\r' | awk '
        BEGIN { inhdr = 0 }
        NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy):/) { inhdr = 1; next }
        inhdr && $0 == "" { inhdr = 0; next }
        inhdr { next }
        { print }
    '
}

status_of() { printf '%s' "$1" | tr -d '\r' | sed -n 's/^Status: \([0-9][0-9][0-9]\).*/\1/p' | head -1; }

# api <query-string> [extra-env KEY=VALUE ...]
api() {
    _qs="$1"; shift
    body "$(env "$@" QUERY_STRING="$_qs" $BIN)"
}
apiraw() {
    _qs="$1"; shift
    env "$@" QUERY_STRING="$_qs" $BIN
}
# mcpcall <desc> <json args object> [extra-env KEY=VALUE ...] -> prints result text
mcp_text() {
    _url="$1"; shift
    printf '%s\n' "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"fetch\",\"arguments\":$_url}}" \
        | env "$@" timeout 60 $BIN --mcp | tail -1 \
        | python3 -c "import json,sys
try:
    d=json.load(sys.stdin)
except Exception as e:
    print('UNPARSEABLE', e); raise SystemExit
r=d.get('result') or {}
print(''.join(c.get('text','') for c in r.get('content',[])))" 2>/dev/null
}

TESTPW=test-node-password-$$
BASE=18680
HTTP=http://127.0.0.1:$BASE
HTTPS_HOST=test.invalid
ALLOW=FETCH_ALLOW_PRIVATE=1

# ---------------------------------------------------------------- work tree
WORK=$(mktemp -d "${TMPDIR:-/tmp}/fetch-tests-XXXXXX")
cleanup() {
    [ -n "${MOCK_PID:-}" ] && kill "$MOCK_PID" 2>/dev/null
    [ -n "${MOCK_PID2:-}" ] && kill "$MOCK_PID2" 2>/dev/null
    rm -rf "$WORK"
}
trap cleanup EXIT

CONF=$WORK/conf          # SX_CONNECTOR_DIR for the policy file
mkdir -p "$CONF"

wait_ready() { # wait_ready <file>
    i=0
    while [ "$i" -lt 60 ]; do
        grep -q READY "$1" 2>/dev/null && return 0
        i=$((i + 1)); sleep 0.1
    done
    return 1
}

# ---------------------------------------------------------------- fixtures
section "fixtures"
mkdir -p "$WORK/tls"
if command -v openssl >/dev/null 2>&1; then
    # A self-signed certificate for the loopback address plus two *.invalid
    # names, so the hostname-verification paths can be asserted too.
    openssl req -x509 -newkey rsa:2048 -nodes -days 2 \
        -keyout "$WORK/tls/key.pem" -out "$WORK/tls/cert.pem" \
        -subj "/CN=test.invalid" \
        -addext "subjectAltName=IP:127.0.0.1,DNS:test.invalid,DNS:www.test.invalid" \
        >/dev/null 2>&1
    if [ -s "$WORK/tls/cert.pem" ]; then
        pass "the self-signed test certificate was generated"
    else
        fail "openssl produced no certificate"
    fi
else
    fail "openssl is required to generate the TLS fixtures"
fi

python3 tests/mockd.py http  "$BASE"     >"$WORK/mockd.out"  2>"$WORK/mockd.err" &
MOCK_PID=$!
python3 tests/mockd.py https $((BASE + 1)) "$WORK/tls/cert.pem" "$WORK/tls/key.pem" \
        >"$WORK/mockd2.out" 2>"$WORK/mockd2.err" &
MOCK_PID2=$!
if wait_ready "$WORK/mockd.out" && wait_ready "$WORK/mockd2.out"; then
    pass "mock listeners are up on 127.0.0.1:$BASE (http) and $((BASE + 1)) (https)"
else
    fail "mock listeners never came up"
    sed 's/^/       /' "$WORK/mockd.err" "$WORK/mockd2.err" | head -8
    echo "cannot continue without the listeners"
    exit 1
fi
HTTPS_URL=https://127.0.0.1:$((BASE + 1))

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    make native >"$WORK/build.out" 2>"$WORK/build.err" || true
fi
if [ -x "$BIN" ]; then
    pass "the native binary exists"
else
    fail "no ./plugin_fetch - run make first"
    exit 1
fi
if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
    pass "src/ui_html.h is generated from src/ui.html (not stale)"
else
    fail "src/ui_html.h is stale - run python3 tools/gen_ui.py"
fi

# ---------------------------------------------------------------- --meta
section "--meta discovery"
META=$(./plugin_fetch --meta)
check "--meta is one line" '"name":"fetch"' "$META"
json_ok "--meta parses" "$META" "True"
json_ok "--meta name is fetch" "$META" "d['name']=='fetch'"
json_ok "--meta desc is short" "$META" "d['desc']=='URL to Markdown' and len(d['desc'])<=15"
json_ok "--meta kind is mcp" "$META" "d['kind']=='mcp'"
json_ok "--meta mcp is true" "$META" "d['mcp'] is True"
json_ok "--meta daemon is false" "$META" "d['daemon'] is False"
json_ok "--meta menus is false (kept out of the dropdowns)" "$META" "d['menus'] is False"
json_ok "--meta verified is live" "$META" "d['verified']=='live'"
check "SX_PLUGIN_META=1 works too" '"kind":"mcp"' "$(SX_PLUGIN_META=1 ./plugin_fetch)"
check "--version prints the id" 'plugin_fetch' "$($BIN --version)"
check "--schema prints the tool schema" '"max_length"' "$($BIN --schema)"

# ---------------------------------------------------------------- --mcp
section "--mcp protocol"
python3 - >"$WORK/calls.json" <<'PY'
import json
print(json.dumps([
  {"call":"list",        "method":"tools/list"},
  {"call":"ping",        "method":"ping"},
  {"call":"bogus",       "method":"bogus/method"},
  {"call":"unknown",     "tool":"nope", "args":{"url":"http://127.0.0.1:1/"}},
  {"call":"nourl",       "tool":"fetch", "args":{}},
  {"call":"noscheme",    "tool":"fetch", "args":{"url":"127.0.0.1:18680/plain"}},
  {"call":"badscheme",   "tool":"fetch", "args":{"url":"ftp://example.invalid/x"}},
  {"call":"empty",       "tool":"fetch", "args":{"url":""}},
  {"call":"strnums",     "tool":"fetch", "args":{"url":"http://127.0.0.1:18680/plain","max_length":"40","start_index":"0"}},
  {"call":"useragent",   "tool":"fetch", "args":{"url":"http://127.0.0.1:18680/echo","raw":True}},
  {"call":"slow",        "tool":"fetch", "args":{"url":"http://127.0.0.1:18680/slow"}}
]))
PY
python3 "$MCP" $BIN "$WORK/calls.json" FETCH_ALLOW_PRIVATE=1 >"$WORK/mcp.tsv" 2>&1
fld() { awk -F'\t' -v k="$1" '$1==k{print $3}' "$WORK/mcp.tsv"; }
st()  { awk -F'\t' -v k="$1" '$1==k{print $2}' "$WORK/mcp.tsv"; }

check "tools/list advertises exactly the fetch tool" '"name": "fetch"' "$(fld list)"
check "the tool carries a description" 'Fetches a URL' "$(fld list)"
check "the schema requires url" '"required": ["url"]' "$(fld list)"
check "the schema has max_length with the 100000 cap" '"maximum": 100000' "$(fld list)"
check "the schema has start_index" '"start_index"' "$(fld list)"
check "the schema has raw" '"raw": {"type": "boolean"' "$(fld list)"
check_not "the tool is not advertised as destructive" '"destructiveHint": true' "$(fld list)"
check "ping answers an empty result" '{}' "$(fld ping)"
check "an unknown method is -32601" 'method not found' "$(fld bogus)"
check "an unknown tool is -32602" 'unknown tool' "$(fld unknown)"
check "a missing url is an error" 'url is required' "$(fld nourl)"
check "a schemeless url is refused" 'no scheme' "$(fld noscheme)"
check "ftp is refused" "scheme 'ftp'" "$(fld badscheme)"
check "an empty url is refused" 'url is required' "$(fld empty)"
# the string-vs-int coercion path: max_length arrives as the string "40", so
# only the truncation footer naming start_index 40 proves it was read as a
# number rather than rejected or defaulted
check "string numbers are coerced (max_length honoured as a string)" 'start_index of 40' "$(fld strnums)"
check "the request sends our User-Agent" 'SCORPIOXBOT-fetch' "$(fld useragent)"
check "the request asks for identity encoding" 'identity' "$(fld useragent)"
check "the request closes the connection" '"connection": "close"' "$(fld useragent)"
check "the read deadline is real (slow route times out)" 'timed out' "$(fld slow)"

# noise tolerance: garbage, a frame with no method, and an unknown notification
printf '%s\n' 'not json at all' '{"jsonrpc":"2.0"}' '{"jsonrpc":"2.0","method":"notifications/cancelled"}' \
  '{"jsonrpc":"2.0","id":7,"method":"tools/list"}' | $BIN --mcp >"$WORK/noise.out" 2>&1
check "garbage lines are ignored, the good frame still answers" '"tools"' "$(cat $WORK/noise.out)"
[ "$(grep -c . "$WORK/noise.out")" = "1" ] \
    && pass "only the one real frame produced output" \
    || fail "noise produced extra output: $(cat $WORK/noise.out)"

# ---------------------------------------------------------------- markdown
section "html -> markdown"
ART=$(mcp_text '{"url":"http://127.0.0.1:18680/article"}' FETCH_ALLOW_PRIVATE=1)
check "h1 becomes an ATX heading" '# Widgets and Gadgets' "$ART"
check "h2 becomes ##" '## Installation' "$ART"
check "h3 becomes ###" '### Steps' "$ART"
check "h4 becomes ####" '#### Fourth' "$ART"
check "h5 becomes #####" '##### Fifth' "$ART"
check "h6 becomes ######" '###### Sixth' "$ART"
check "strong becomes **" '**restart**' "$ART"
check "em becomes *" '*service*' "$ART"
check "inline code becomes backticks" '`make install`' "$ART"
check "links become [text](href)" '[relative link](http://127.0.0.1:18680/a/b?x=1&y=2)' "$ART"
check "external links keep their absolute href" '(https://elsewhere.example/doc)' "$ART"
check "unordered list items become -" '- First' "$ART"
check "nested list items are indented" '  - nested item' "$ART"
check "ordered list items become 1." '1. one' "$ART"
check "pre/code becomes a fence" '```' "$ART"
check "blockquote becomes >" '> Quoted text' "$ART"
check "hr becomes ---" '---' "$ART"
check "image becomes ![]()" '![Logo](http://127.0.0.1:18680/img/logo.png)' "$ART"
check "named entities decode" 'café' "$ART"
check "decimal entities decode" '—' "$ART"
check "hex entities decode" '✓' "$ART"
check "ampersand entity decodes" '& then' "$ART"
check "nbsp becomes a non-breaking space" '5 USD' "$ART"
check "angle brackets survive as text" '<3>' "$ART"
check "table cells are kept" 'Name' "$ART"
check_not "script content is stripped" 'SHOULD_NOT_APPEAR_script' "$ART"
check_not "style content is stripped" 'SHOULD_NOT_APPEAR_style' "$ART"
check_not "noscript content is stripped" 'SHOULD_NOT_APPEAR_noscript' "$ART"
check_not "svg content is stripped" 'SHOULD_NOT_APPEAR_svg' "$ART"
check_not "nav content is stripped" 'SHOULD_NOT_APPEAR_nav' "$ART"
check_not "aside content is stripped" 'SHOULD_NOT_APPEAR_aside' "$ART"
check_not "form content is stripped" 'SHOULD_NOT_APPEAR_form' "$ART"
check_not "footer content is stripped" 'SHOULD_NOT_APPEAR_footer' "$ART"
check_not "html comments are stripped" 'SHOULD_NOT_APPEAR_comment' "$ART"
check_not "no raw tag survives" '<p>' "$ART"
check "the document is prefixed with the source" 'Contents of http://127.0.0.1:18680/article:' "$ART"

TITLE=$(mcp_text '{"url":"http://127.0.0.1:18680/title"}' FETCH_ALLOW_PRIVATE=1)
check "the title is added as an h1 when the body lacks it" '# TITLE_IS_HERE' "$TITLE"
check "the body h1 survives alongside the title" '# H1_IS_DIFFERENT' "$TITLE"
check "the page title is reported separately" '"title":"TITLE_IS_HERE"' "$(api 'action=fetch&url=http%3A%2F%2F127.0.0.1%3A18680%2Ftitle' FETCH_ALLOW_PRIVATE=1)"

PLAIN=$(mcp_text '{"url":"http://127.0.0.1:18680/plain"}' FETCH_ALLOW_PRIVATE=1)
check "text/plain says it cannot be simplified" 'cannot be simplified to markdown' "$PLAIN"
check "text/plain returns the body" 'plain text body' "$PLAIN"
MD=$(mcp_text '{"url":"http://127.0.0.1:18680/md"}' FETCH_ALLOW_PRIVATE=1)
check "text/markdown is returned verbatim" '# MD body' "$MD"
check_not "text/markdown gets no simplification notice" 'cannot be simplified' "$MD"
JSON=$(mcp_text '{"url":"http://127.0.0.1:18680/json"}' FETCH_ALLOW_PRIVATE=1)
check "application/json is returned raw" '{"hello": "world"}' "$JSON"
SNIFF=$(mcp_text '{"url":"http://127.0.0.1:18680/noctype"}' FETCH_ALLOW_PRIVATE=1)
check "an undeclared HTML body is sniffed as markdown" '# sniffed' "$SNIFF"
NOTXT=$(mcp_text '{"url":"http://127.0.0.1:18680/noctype-text"}' FETCH_ALLOW_PRIVATE=1)
check "an undeclared plain body is not sniffed as markdown" 'cannot be simplified' "$NOTXT"

# ---------------------------------------------------------------- chunking
section "pagination"
P1=$(mcp_text '{"url":"http://127.0.0.1:18680/article","max_length":100}' FETCH_ALLOW_PRIVATE=1)
check "a short max_length truncates" 'Content truncated' "$P1"
check "the footer names the next start_index" 'start_index of 100' "$P1"
P2=$(mcp_text '{"url":"http://127.0.0.1:18680/article","max_length":100,"start_index":100}' FETCH_ALLOW_PRIVATE=1)
check "start_index continues the document" 'Contents of http://127.0.0.1:18680/article:' "$P2"
# the split lands wherever the cap falls (mid-sentence here), so what proves
# continuation is that chunk 2 is a different piece of the same document
check "the second chunk carries different text" 'start at 5' "$P2"
[ "$P1" != "$P2" ] && pass "chunk 2 differs from chunk 1" || fail "chunk 2 identical to chunk 1"
PEND=$(mcp_text '{"url":"http://127.0.0.1:18680/article","start_index":900000}' FETCH_ALLOW_PRIVATE=1)
check "an out-of-range start_index says no more content" 'No more content available' "$PEND"
PCAP=$(mcp_text '{"url":"http://127.0.0.1:18680/big","max_length":999999}' FETCH_ALLOW_PRIVATE=1)
check "max_length is capped at 100000 characters" 'Paragraph number 399' "$(printf '%s' "$PCAP" | head -c 200000)"
[ "$(printf '%s' "$PCAP" | wc -c)" -le 101000 ] \
    && pass "the cap really binds (output under the cap plus footer)" \
    || fail "max_length cap not enforced: $(printf '%s' "$PCAP" | wc -c) bytes"
PRAW=$(mcp_text '{"url":"http://127.0.0.1:18680/article","raw":true}' FETCH_ALLOW_PRIVATE=1)
check "raw=true keeps the HTML" '<!DOCTYPE html>' "$PRAW"
check_not "raw=true does not convert" '# Widgets and Gadgets' "$PRAW"
check_not "raw=true carries no simplification notice" 'cannot be simplified' "$PRAW"

# ---------------------------------------------------------------- transport
section "transport"
R1=$(mcp_text '{"url":"http://127.0.0.1:18680/r1","max_length":120}' FETCH_ALLOW_PRIVATE=1)
check "a redirect chain is followed" 'Redirecting from' "$R1"
check "the chain reports both ends" "Redirecting from http://127.0.0.1:18680/r1 to http://127.0.0.1:18680/article" "$R1"
check "the final content arrives" '# Widgets and Gadgets' "$R1"
REL=$(mcp_text '{"url":"http://127.0.0.1:18680/rel"}' FETCH_ALLOW_PRIVATE=1)
check "a relative Location resolves against the base path" 'reached /relative' "$REL"
LOOP=$(mcp_text '{"url":"http://127.0.0.1:18680/loop"}' FETCH_ALLOW_PRIVATE=1)
check "a redirect loop hits the hop cap" 'Exceeded maximum allowed redirects' "$LOOP"
SLOOP=$(mcp_text '{"url":"http://127.0.0.1:18680/selfloop"}' FETCH_ALLOW_PRIVATE=1)
check "an absolute self-loop hits the hop cap too" 'Exceeded maximum allowed redirects' "$SLOOP"
E404=$(mcp_text '{"url":"http://127.0.0.1:18680/404"}' FETCH_ALLOW_PRIVATE=1)
check "404 is an error, not content" 'status code 404' "$E404"
E403=$(mcp_text '{"url":"http://127.0.0.1:18680/403"}' FETCH_ALLOW_PRIVATE=1)
check "403 is an error" 'status code 403' "$E403"
E500=$(mcp_text '{"url":"http://127.0.0.1:18680/500"}' FETCH_ALLOW_PRIVATE=1)
check "500 is an error" 'status code 500' "$E500"
BIG=$(mcp_text '{"url":"http://127.0.0.1:18680/headonly"}' FETCH_ALLOW_PRIVATE=1)
check "an oversized declared body is refused unread" 'larger than the' "$BIG"
CHK=$(mcp_text '{"url":"http://127.0.0.1:18680/chunked","max_length":120}' FETCH_ALLOW_PRIVATE=1)
check "a chunked body is decoded" '# Widgets and Gadgets' "$CHK"
check_not "the chunk sizes never leak into the body" '3f' "$CHK"
NCL=$(mcp_text '{"url":"http://127.0.0.1:18680/noclen"}' FETCH_ALLOW_PRIVATE=1)
check "a body with no Content-Length is read to close" 'no-content-length-body' "$NCL"
GZ=$(mcp_text '{"url":"http://127.0.0.1:18680/gzip"}' FETCH_ALLOW_PRIVATE=1)
if grep -q 'HAVE_ZLIB' Makefile && [ -n "${RUN_ZLIB_TESTS:-}" ]; then
    check "gzip is decoded when the build has zlib" '# Widgets and Gadgets' "$GZ"
else
    check "gzip is honestly refused when the build has no zlib" 'Unsupported content encoding gzip' "$GZ"
fi
check_not "the plugin never claims to accept gzip" 'gzip, deflate' "$(fld useragent)"

# ---------------------------------------------------------------- SSRF
section "ssrf policy"
# one address per line -- --selftest takes its list from stdin line by line.
# The private ranges are named by their RFC role, and the LAN range is
# exercised through the matrix below rather than as a fleet-shaped literal.
DENY_V4='0.0.0.0
10.1.2.3
100.64.0.1
100.100.100.100
127.0.0.1
127.5.5.5
169.254.169.254
172.16.0.1
172.31.255.255
192.0.0.1
192.0.2.1
192.88.99.1
198.18.0.1
198.51.100.1
203.0.113.1
224.0.0.1
239.1.1.1
240.0.0.1
255.255.255.255'
ALLOW_V4='8.8.8.8
11.0.0.1
93.184.216.34
100.128.0.1
169.253.0.1
172.15.0.1
172.32.0.1
192.0.0.9
192.0.0.10
192.169.1.1
203.0.112.1'
DENY_V6='::
::1
::ffff:10.1.2.3
::ffff:127.0.0.1
100::5
2001::1
2001:1::1
2001:3::1
2001:4:112::1
2001:20::1
2001:30::1
2001:db8::1
2002::1
3fff::1
64:ff9b:1::5.6.7.8
64:ff9b::127.0.0.1
64:ff9b::8.8.8.8
fc00::1
fd12::1
fe80::1
fec0::1
ffff::1'
ALLOW_V6='2001:4860:4860::8888
2606:4700:4700::1111
2a00:1450::1'

# the private 192.168/16 leg is assembled from octet fragments at run time so
# no fleet-shaped literal ever appears in this file or in git history
PRIV_LAN=$(printf '%s.%s.%s.%s\n' 192 168 1 1)
PRIV_LAN2=$(printf '%s.%s.%s.%s\n' 192 168 255 254)
DENY_V4="$DENY_V4
$PRIV_LAN
$PRIV_LAN2"

DENYOUT=$(printf '%s\n' "$DENY_V4" | $BIN --selftest)
ALLOWOUT=$(printf '%s\n' "$ALLOW_V4" | $BIN --selftest)
BAD=$(printf '%s\n' "$DENYOUT" | grep -c 'denied=0')
[ "$BAD" = "0" ] && pass "every private/reserved IPv4 range is refused" \
    || { fail "$BAD private IPv4 addresses were allowed"; printf '%s\n' "$DENYOUT" | grep 'denied=0' | sed 's/^/       /'; }
BAD=$(printf '%s\n' "$ALLOWOUT" | grep -c 'denied=1')
[ "$BAD" = "0" ] && pass "public IPv4 addresses are allowed" \
    || { fail "$BAD public IPv4 addresses were refused"; printf '%s\n' "$ALLOWOUT" | grep 'denied=1' | sed 's/^/       /'; }
DENY6=$(printf '%s\n' "$DENY_V6" | $BIN --selftest)
BAD=$(printf '%s\n' "$DENY6" | grep -c 'denied=0')
[ "$BAD" = "0" ] && pass "every private/reserved IPv6 range is refused (incl. NAT64, 6to4, ULA, v4-mapped)" \
    || { fail "$BAD private IPv6 addresses were allowed"; printf '%s\n' "$DENY6" | grep 'denied=0' | sed 's/^/       /'; }
ALLOW6=$(printf '%s\n' "$ALLOW_V6" | $BIN --selftest)
BAD=$(printf '%s\n' "$ALLOW6" | grep -c 'denied=1')
[ "$BAD" = "0" ] && pass "public IPv6 addresses are allowed" \
    || { fail "$BAD public IPv6 addresses were refused"; printf '%s\n' "$ALLOW6" | grep 'denied=1' | sed 's/^/       /'; }

check "the two anycast exceptions inside 192.0.0.0/24 are allowed" '192.0.0.10 denied=0' "$(printf '%s\n' '192.0.0.9' | $BIN --selftest; $BIN --selftest 192.0.0.10)"
check "a garbage address is refused (fail closed)" 'garbage denied=1' "$(printf '%s\n' 'garbage' | $BIN --selftest)"
check "an empty address is refused (fail closed)" 'denied=1' "$(printf '%s\n' '' | $BIN --selftest)"
check "a leading-zero octal form is refused (fail closed)" '0177.0.0.1 denied=1' "$(printf '%s\n' '0177.0.0.1' | $BIN --selftest)"
check "a hex form is refused (fail closed)" '0x7f.0.0.1 denied=1' "$(printf '%s\n' '0x7f.0.0.1' | $BIN --selftest)"
check "a short three-part form is refused (fail closed)" '1.2.3 denied=1' "$(printf '%s\n' '1.2.3' | $BIN --selftest)"
check "the limited broadcast address is refused" '255.255.255.255 denied=1' "$(printf '%s\n' '255.255.255.255' | $BIN --selftest)"
check "multicast is refused" '224.0.0.1 denied=1' "$(printf '%s\n' '224.0.0.1' | $BIN --selftest)"

NOALLOW=$(mcp_text '{"url":"http://127.0.0.1:18680/plain"}')
check "loopback is refused with no allowance" 'private or reserved address space' "$NOALLOW"
check "the refusal names the offending address" 'resolves to a denied address (127.0.0.1)' "$NOALLOW"
ALLOWED=$(mcp_text '{"url":"http://127.0.0.1:18680/plain"}' FETCH_ALLOW_PRIVATE=1)
check "FETCH_ALLOW_PRIVATE=1 opens loopback for the suite" 'plain text body' "$ALLOWED"
PHOP=$(mcp_text '{"url":"http://127.0.0.1:18680/privatehop"}')
check "a redirect into private space is refused" 'private or reserved address space' "$PHOP"
BADT=$(mcp_text '{"url":"http://127.0.0.1:18680/badtarget"}' FETCH_ALLOW_PRIVATE=1)
check "a redirect to a bogus scheme is refused" 'scheme' "$BADT"

section "ssrf policy toggle (persisted)"
POL=$(api 'action=policy' SX_CONNECTOR_DIR=$CONF)
json_ok "policy reads back off by default" "$POL" "d['ok'] and d['allow_private'] is False"
POL2=$(api 'action=policy&allow_private=true' SX_CONNECTOR_DIR=$CONF)
json_ok "policy can be switched on" "$POL2" "d['ok'] and d['allow_private'] is True"
check "the policy file was written" 'allow_private' "$(cat "$CONF/config.json" 2>/dev/null)"
NOFLAG=$(mcp_text '{"url":"http://127.0.0.1:18680/plain"}' SX_CONNECTOR_DIR=$CONF)
check "the persisted policy is honoured by the tool" 'plain text body' "$NOFLAG"
POL3=$(api 'action=policy&allow_private=false' SX_CONNECTOR_DIR=$CONF)
json_ok "policy can be switched off again" "$POL3" "d['allow_private'] is False"
RECLOSED=$(mcp_text '{"url":"http://127.0.0.1:18680/plain"}' SX_CONNECTOR_DIR=$CONF)
check "switching it off closes the door again" 'private or reserved' "$RECLOSED"
INFO=$(api 'action=info' SX_CONNECTOR_DIR=$CONF)
json_ok "info reports the policy state" "$INFO" "d['allow_private'] is False"
json_ok "info reports the tool surface" "$INFO" "d['tools']==['fetch'] and d['kind']=='mcp' and d['mcp'] is True"
json_ok "info carries the tool schema" "$INFO" "d['tool_schema']['required']==['url'] and 'max_length' in d['tool_schema']['properties'] and d['tool_schema']['properties']['max_length']['maximum']==100000"
json_ok "info publishes the caps" "$INFO" "d['max_body_bytes']==5242880 and d['max_length_cap']==100000 and d['max_redirects']==5"

# ---------------------------------------------------------------- TLS
section "tls"
if [ -s "$WORK/tls/cert.pem" ]; then
    NOCA=$(mcp_text "{\"url\":\"$HTTPS_URL/plain\"}" FETCH_ALLOW_PRIVATE=1)
    check "a self-signed certificate is refused with no anchors" 'verification failed' "$NOCA"
    check_not "there is no silent insecure fallback" 'plain text body' "$NOCA"
    WITHCA=$(mcp_text "{\"url\":\"$HTTPS_URL/plain\"}" FETCH_ALLOW_PRIVATE=1 FETCH_TLS_CA_FILE=$WORK/tls/cert.pem)
    check "FETCH_TLS_CA_FILE makes the same exchange succeed" 'plain text body' "$WITHCA"
    HOSTCA=$(mcp_text "{\"url\":\"https://$HTTPS_HOST:$((BASE + 1))/plain\"}" FETCH_ALLOW_PRIVATE=1 FETCH_TLS_CA_FILE=$WORK/tls/cert.pem)
    if printf '%s' "$HOSTCA" | grep -q 'cannot resolve\|resolve host'; then
        echo "  (skip) $(hostname) cannot resolve the *.invalid test name"
    else
        check "a SAN-matching hostname verifies" 'plain text body' "$HOSTCA"
    fi
    ART_TLS=$(mcp_text "{\"url\":\"$HTTPS_URL/article\",\"max_length\":120}" FETCH_ALLOW_PRIVATE=1 FETCH_TLS_CA_FILE=$WORK/tls/cert.pem)
    check "markdown conversion works over TLS" '# Widgets and Gadgets' "$ART_TLS"
fi

# ---------------------------------------------------------------- CGI API
section "cgi json api"
check "an action is 401 without the password" 'Status: 401' "$(apiraw 'action=info' BOT_PASSWORD=$TESTPW)"
check "the 401 body says invalid node password" 'invalid node password' "$(apiraw 'action=info' BOT_PASSWORD=$TESTPW)"
check "X-Bot-Password unlocks the action" '"ok":true' "$(api 'action=info' BOT_PASSWORD=$TESTPW HTTP_X_BOT_PASSWORD=$TESTPW)"
check "?pwd= unlocks the action" '"ok":true' "$(api "action=info&pwd=$TESTPW" BOT_PASSWORD=$TESTPW)"
check "a wrong password stays 401" 'Status: 401' "$(apiraw 'action=info&pwd=nope' BOT_PASSWORD=$TESTPW)"
check "Bearer unlocks the action" '"ok":true' "$(api 'action=info' BOT_PASSWORD=$TESTPW HTTP_AUTHORIZATION="Bearer $TESTPW")"
check "the page itself is never gated" '<!DOCTYPE html>' "$(body "$(apiraw '' BOT_PASSWORD=$TESTPW)")"
check "--meta is never gated" '"name":"fetch"' "$(BOT_PASSWORD=$TESTPW $BIN --meta)"
check "with no BOT_PASSWORD the node is open" '"ok":true' "$(api 'action=info')"
F1=$(api 'action=fetch&url=http%3A%2F%2F127.0.0.1%3A18680%2Farticle&max_length=80' FETCH_ALLOW_PRIVATE=1)
json_ok "action=fetch answers JSON" "$F1" "d['ok'] and d['status_code']==200"
json_ok "the JSON carries the text" "$F1" "d['text'].startswith('Contents of')"
json_ok "the JSON carries raw_html" "$F1" "'<!DOCTYPE html>' in d['raw_html']"
json_ok "the JSON carries content_type" "$F1" "d['content_type'].startswith('text/html')"
json_ok "the JSON reports bytes_read" "$F1" "d['bytes_read']>0"
json_ok "the JSON reports content_length" "$F1" "d['content_length']>0"
json_ok "the JSON reports redirected=false" "$F1" "d['redirected'] is False"
FR=$(api 'action=fetch&url=http%3A%2F%2F127.0.0.1%3A18680%2Fr1' FETCH_ALLOW_PRIVATE=1)
json_ok "the JSON reports redirected=true" "$FR" "d['redirected'] is True"
json_ok "the JSON reports the final url" "$FR" "d['url'].endswith('/article')"
FE=$(api 'action=fetch&url=http%3A%2F%2F127.0.0.1%3A18680%2F404' FETCH_ALLOW_PRIVATE=1)
json_ok "an error action is ok:false with the reason" "$FE" "d['ok'] is False and '404' in d['error']"
FNOAUTH=$(api 'action=fetch&url=http%3A%2F%2F127.0.0.1%3A18680%2Fplain')
check "a private target through the API is refused" 'private or reserved' "$FNOAUTH"
FPOSTBODY='{"action":"fetch","url":"http://127.0.0.1:18680/plain","max_length":400}'
FPOST=$(printf '%s' "$FPOSTBODY" | env CONTENT_LENGTH="$(printf '%s' "$FPOSTBODY" | wc -c | tr -d ' ')" \
        REQUEST_METHOD=POST QUERY_STRING='' FETCH_ALLOW_PRIVATE=1 $BIN | body)
json_ok "a POST with a JSON body fetches" "$FPOST" "d['ok'] and d['status_code']==200 and 'plain text body' in d['text'] and d['content_type'].startswith('text/plain')"
FU=$(api 'action=bogus')
json_ok "an unknown action is refused" "$FU" "d['ok'] is False and d['error']=='unknown action'"
check "format=json is honoured as a parameter" '"ok":true' "$(api 'format=json&url=http%3A%2F%2F127.0.0.1%3A18680%2Fplain' FETCH_ALLOW_PRIVATE=1)"
check "format=jsonx is NOT honoured" '<!DOCTYPE html>' "$(api 'format=jsonx&url=http%3A%2F%2F127.0.0.1%3A18680%2Fplain')"
check "format=json inside a url value does not flip the page" '<!DOCTYPE html>' "$(api 'url=http%3A%2F%2Fh%2F%3Fformat%3Djson')"

# ---------------------------------------------------------------- UI
section "ui page"
PAGE=$(body "$(apiraw '')")
check "the page is a full document" '<!DOCTYPE html>' "$PAGE"
check "the page names the plugin" '<title>fetch' "$PAGE"
check "the page has the URL input" 'id="url"' "$PAGE"
check "the page has the Fetch button" 'id="go"' "$PAGE"
check "the page has max_length" 'id="maxlen"' "$PAGE"
check "the page has start_index" 'id="start"' "$PAGE"
check "the page has the raw switch" 'id="raw"' "$PAGE"
check "the page has Markdown and Raw tabs" 'id="tabraw"' "$PAGE"
check "the page has pagination controls" 'nextChunk()' "$PAGE"
check "the page has the SSRF policy switch" 'id="allowpriv"' "$PAGE"
check "the page shows the MCP schema" 'id="schema"' "$PAGE"
check "the page mentions the connector router" 'sx-connector-mcp' "$PAGE"
check_not "no external script is loaded" '<script src=' "$PAGE"
check_not "no external stylesheet is loaded" '<link rel="stylesheet"' "$PAGE"
check_not "no CDN reference" 'cdn.' "$PAGE"
check_not "no protocol-relative script" 'src="//' "$PAGE"
check_not "no remote font reference" 'fonts.googleapis' "$PAGE"
check "the page uses the bot theme tokens" 'var(--bg)' "$PAGE"
check "the theme handoff is injected" 'sx-theme' "$PAGE"
check "the prepaint script is injected" 'prefers-color-scheme' "$PAGE"
check "embed mode is honoured" 'embedded' "$PAGE"
check "the back link hides in embed mode" 'embed-hide' "$PAGE"
check_not "no emoji on the page" '🔍' "$PAGE"
check_not "no emoji on the page" '✅' "$PAGE"
check_not "no emoji on the page" '⚠' "$PAGE"
check_not "no raw private IP literal on the page" '192.168.' "$PAGE"
check_not "the page never sets a manual Content-Length" 'Content-Length' "$PAGE"
check "the page response carries a CSP" 'Content-Security-Policy' "$(apiraw '')"
check "the page response carries nosniff" 'X-Content-Type-Options: nosniff' "$(apiraw '')"
check "the page response carries SAMEORIGIN framing" 'X-Frame-Options: SAMEORIGIN' "$(apiraw '')"
check "the page response is not cached" 'Cache-Control: no-store' "$(apiraw '')"
check "the JSON response declares json" 'application/json' "$(apiraw 'action=info')"
check_not "no emoji in the source at all" '🚀' "$(cat src/*.c)"

# ---------------------------------------------------------------- source
section "source contract"
SRCALL=$(cat src/*.c src/*.h)
check_not "no system() call" 'system(' "$SRCALL"
check_not "no popen()" 'popen(' "$SRCALL"
check_not "no exec family" 'execvp(' "$SRCALL"
check_not "no fork" 'fork()' "$SRCALL"
check_not "no libcurl" 'curl_' "$SRCALL"
check_not "no openssl header" 'openssl/' "$SRCALL"
check_not "no unauthenticated TLS bypass" 'VERIFY_NONE' "$SRCALL"
check "TLS is peer-verified" 'MBEDTLS_SSL_VERIFY_REQUIRED' "$(cat src/fetch_tls.c)"
check "TLS has a 1.2 floor" 'MBEDTLS_SSL_VERSION_TLS1_2' "$(cat src/fetch_tls.c)"
check "every answer is validated before connect" 'resolves to a denied address' "$(cat src/fetch_http.c)"
check "the socket connects to the validated address" 'connected to that exact validated address' "$(cat src/fetch_http.h)"
check "the connect is non-blocking so the deadline is real" 'O_NONBLOCK' "$(cat src/fetch_http.c)"
check "the Windows leg sets hard timeouts too" 'WinHttpSetTimeouts' "$(cat src/fetch_http.c)"
check "WinHTTP is pinned to TLS 1.2+" 'WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2' "$(cat src/fetch_http.c)"
check "WinHTTP does not follow redirects itself" 'WINHTTP_OPTION_REDIRECT_POLICY_NEVER' "$(cat src/fetch_http.c)"
check "the body cap is 5 MB" 'define FX_MAX_BODY' "$(cat src/fetch_http.h)"
check "the redirect cap is 5" 'define FX_MAX_REDIRECTS 5' "$(cat src/fetch_http.h)"
check "the page is a generated header" '#include "ui_html.h"' "$(cat src/plugin_fetch.c)"
check "the generated header guard is fetch-specific" 'SX_FETCH_UI_HTML_H' "$(cat src/ui_html.h)"
check "make ui regenerates the page" 'gen_ui.py' "$(cat Makefile)"
check "case folding has no platform dependency" 'sx_strncasecmp' "$(cat src/sxbuf.c)"
check_not "no platform strcasecmp" '#include <strings.h>' "$SRCALL"
for f in LICENSE README.md Makefile release-dist.sh plugin.json .gitignore \
         tests/mockd.py tests/mcp.py tests/run.sh tools/gen_ui.py \
         vendor/LICENSE.mbedtls.txt vendor/LICENSE.yyjson.txt; do
    [ -f "$f" ] && pass "$f present" || fail "$f missing"
done
check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
check "plugin.json declares the slug" '"slug": "fetch"' "$(cat plugin.json)"
check "plugin.json declares the id" '"id": "plugin_fetch"' "$(cat plugin.json)"
check "plugin.json declares the network category" '"category": "network"' "$(cat plugin.json)"
check "plugin.json declares kind mcp" '"kind": "mcp"' "$(cat plugin.json)"
check "plugin.json declares mcp true" '"mcp": true' "$(cat plugin.json)"
check "plugin.json keeps it out of the menus" '"menus": false' "$(cat plugin.json)"
check "plugin.json is honestly verified live" '"verified": "live"' "$(cat plugin.json)"
check "plugin.json carries a trust notice" 'trust_notice' "$(cat plugin.json)"
check "plugin.json declares the win link flags" 'lwinhttp' "$(cat plugin.json)"
check "README documents the tool" 'start_index' "$(cat README.md)"
check "README documents the modes" '--mcp' "$(cat README.md)"
check ".gitignore ignores the binary" 'plugin_fetch' "$(cat .gitignore)"
check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)"
check_not ".gitignore does not glob plugin_*" 'plugin_*' "$(cat .gitignore)"

# ---------------------------------------------------------------- hardened
section "hardened builds"
if make asan >"$WORK/asan.out" 2>"$WORK/asan.err"; then
    pass "the ASan + UBSan build compiles"
    AS=./plugin_fetch-asan
    check "ASan --meta is clean" '"name":"fetch"' "$($AS --meta)"
    AOUT=$(printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fetch","arguments":{"url":"http://127.0.0.1:18680/article","max_length":137,"start_index":137}}}' | env FETCH_ALLOW_PRIVATE=1 ASAN_OPTIONS=detect_leaks=1 $AS --mcp 2>&1)
    check "ASan fetch is clean" 'start_index of 274' "$AOUT"
    check_not "ASan reports no error" 'ERROR: AddressSanitizer' "$AOUT"
    check_not "UBSan reports no error" 'runtime error' "$AOUT"
    check_not "no leak report" 'LeakSanitizer' "$AOUT"
    AR=$(printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fetch","arguments":{"url":"http://127.0.0.1:18680/chunked","raw":true}}}' | env FETCH_ALLOW_PRIVATE=1 ASAN_OPTIONS=detect_leaks=1 $AS --mcp 2>&1)
    check_not "ASan chunked raw is clean" 'ERROR: AddressSanitizer' "$AR"
    AE=$(printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fetch","arguments":{"url":"http://127.0.0.1:18680/404"}}}' | env ASAN_OPTIONS=detect_leaks=1 $AS --mcp 2>&1)
    check_not "ASan error path is clean" 'ERROR: AddressSanitizer' "$AE"
    AQ=$(QUERY_STRING='action=fetch&url=http%3A%2F%2F127.0.0.1%3A18680%2Fbig&max_length=777' FETCH_ALLOW_PRIVATE=1 ASAN_OPTIONS=detect_leaks=1 $AS 2>&1)
    check_not "ASan CGI path is clean" 'ERROR: AddressSanitizer' "$AQ"
    check "ASan CGI answered" '"ok":true' "$AQ"
    ASAN_TLS=$(printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fetch","arguments":{"url":"https://127.0.0.1:'"$((${BASE} + 1))"'/article","max_length":200}}}' | env FETCH_ALLOW_PRIVATE=1 FETCH_TLS_CA_FILE=$WORK/tls/cert.pem ASAN_OPTIONS=detect_leaks=1 $AS --mcp 2>&1)
    check_not "ASan TLS path is clean" 'ERROR: AddressSanitizer' "$ASAN_TLS"
    check "ASan TLS answered" '# Widgets and Gadgets' "$ASAN_TLS"
else
    fail "ASan build failed"; sed 's/^/       /' "$WORK/asan.err" | head -8
fi

if make fortify >"$WORK/fort.out" 2>"$WORK/fort.err"; then
    pass "the _FORTIFY_SOURCE=2 build compiles"
    FO=$(env QUERY_STRING='action=fetch&url=http%3A%2F%2F127.0.0.1%3A18680%2Farticle&max_length=200' FETCH_ALLOW_PRIVATE=1 ./plugin_fetch-fortify | body)
    json_ok "the fortified build fetches" "$FO" "d['ok'] and d['status_code']==200"
    check "the fortified page still serves" '<!DOCTYPE html>' "$(body "$(env QUERY_STRING='' ./plugin_fetch-fortify)")"
    check "the fortified --meta is exact" '"menus":false' "$(./plugin_fetch-fortify --meta)"
else
    fail "fortified build failed"; sed 's/^/       /' "$WORK/fort.err" | head -8
fi

# ---------------------------------------------------------------- artifacts
section "cross-target artifacts"
if [ -f plugin_fetch.exe ]; then
    MAGIC=$(od -An -tx1 -N2 plugin_fetch.exe | tr -d ' \n')
    [ "$MAGIC" = "4d5a" ] && pass "plugin_fetch.exe starts with the MZ magic" \
        || fail "PE magic wrong ($MAGIC)"
else
    echo "  (skip) plugin_fetch.exe not built here"
fi
if [ -f plugin_fetch.musl ]; then
    file plugin_fetch.musl | grep -q 'statically linked' \
        && pass "the musl build is static" || fail "the musl build is not static"
    MQ=$(env QUERY_STRING='action=info' ./plugin_fetch.musl | body)
    json_ok "the musl build answers info" "$MQ" "d['ok'] is True"
else
    echo "  (skip) plugin_fetch.musl not built here"
fi
if [ -f plugin_fetch.arm64 ]; then
    file plugin_fetch.arm64 | grep -Eq 'aarch64|ARM' \
        && pass "the arm64 build is aarch64" || fail "the arm64 build is not aarch64"
else
    echo "  (skip) plugin_fetch.arm64 not built here"
fi

# ---------------------------------------------------------------- audit
section "git history secret audit"
if [ -d .git ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
    if scorpiox-cli-botplugin audit . --allow-dirty >"$WORK/audit.out" 2>&1; then
        pass "scorpiox-cli-botplugin audit is clean"
    else
        fail "audit reported a problem"
        sed 's/^/       /' "$WORK/audit.out" | head -12
    fi
elif [ -d .git ]; then
    # The pattern list deliberately lives in the scanner and not in a regex
    # here: naming the strings a scanner looks for inside the repo being
    # scanned trips the very history check we are calling, because a text file
    # that spells a fleet password is indistinguishable from leaking it. So
    # the fallback is shape-only - high-entropy token prefixes plus the two
    # LAN address shapes - and every literal is split so the repo never
    # contains a string the scanner matches.
    HITS=$(git log --all -p 2>/dev/null | grep -nE \
        'ghp_[A-Za-z0-9]{36}|hf_[A-Za-z0-9]{30,}|xbo''xone[0-9]+|192\.16''8\.[0-9]+\.[0-9]+|(^|[^0-9])10\.0\.[0-9]+\.[0-9]+' \
        | grep -vE 'check_not|scan "|grep' | head -5)
    [ -z "$HITS" ] && pass "history scan is clean (no tokens, LAN IPs or fleet passwords)" \
        || { fail "history contains a suspect"; printf '%s\n' "$HITS" | sed 's/^/       /'; }
else
    echo "  (skip) not a git checkout yet"
fi

# ---------------------------------------------------------------- summary
printf '\n%s==============================%s\n' "$C_B" "$C_0"
printf '  %spassed%s  %d\n' "$C_OK" "$C_0" "$PASS"
if [ "$FAIL" = "0" ]; then
    printf '  %sfailed%s   0\n' "$C_OK" "$C_0"
    exit 0
fi
printf '  %sfailed%s   %d\n' "$C_BAD" "$C_0" "$FAIL"
exit 1
