#!/bin/sh
# tests/run.sh - offline checks for plugin_netcheck across all 3 modes.
#
# Everything runs against ./plugin_netcheck with no network required: the
# resolver, the interface table and the outbound connect are replaced by the
# three environment hooks the plugin exposes for exactly this purpose
# (NETCHECK_MOCK_IFACES, NETCHECK_MOCK_DNS, NETCHECK_MOCK_TIMEOUT), and the
# TCP/HTTP legs talk to throwaway listeners started by tests/mockd.py on
# 127.0.0.1. It proves: --meta, node auth on every action, each action's JSON
# shape, host/port/url validation, the timeout path, redirect handling, the
# no-TLS contract, the generated page (no CDN, no <script src=>, no emoji),
# the MinGW PE header when present, a _FORTIFY_SOURCE=2 build that runs clean,
# and a full git-history secret audit.
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_netcheck
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)"; else pass "$1"
    fi
}

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

# strip CGI headers if present, drop CRs, keep the payload
body() {
    printf '%s\n' "$1" | 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 }
    '
}

json_ok() { # json_ok <desc> <json> [python-expression]
    expr=${3:-True}
    if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 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
}

# api <query-string> [extra-env-assignments...]
api() {
    _qs="$1"; shift
    body "$(env "$@" QUERY_STRING="$_qs" $BIN)"
}
apiraw() {
    _qs="$1"; shift
    env "$@" QUERY_STRING="$_qs" $BIN
}

# ---------------------------------------------------------------- fixtures
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"; kill "$MOCK_PID" 2>/dev/null; wait "$MOCK_PID" 2>/dev/null' EXIT

# TEST-NET ranges (RFC 5737) are used for every synthetic address so the suite
# never contains a private-range literal.
IF_FIX='lo|127.0.0.1|255.0.0.0|127.0.0.1|4|1,lo|::1|||6|1,tap0|198.51.100.7|255.255.255.0|198.51.100.255|4|1,wlan9|203.0.113.42|255.255.255.0|203.0.113.255|4|0'
DNS_FIX='example.com=93.184.216.34,2606:2800:220:1::34;target=127.0.0.1;two=198.51.100.9,198.51.100.10'

BASE=18080
python3 tests/mockd.py "$BASE" > "$WORK/mockd.out" 2>"$WORK/mockd.err" &
MOCK_PID=$!
i=0
while [ "$i" -lt 40 ]; do
    grep -q READY "$WORK/mockd.out" 2>/dev/null && break
    i=$((i + 1)); sleep 0.05
done
if grep -q READY "$WORK/mockd.out" 2>/dev/null; then
    pass "mock listeners are up on 127.0.0.1:$BASE..$((BASE + 4))"
else
    fail "mock listeners never came up"
    cat "$WORK/mockd.err" | sed 's/^/       /' | head -5
fi
OPEN_PORT=$((BASE + 1))
N404_PORT=$((BASE + 2))
N301_PORT=$((BASE + 3))
SILENT_PORT=$((BASE + 4))
TCPFIX="target=127.0.0.1"

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -o "$BIN" src/plugin_netcheck.c -lpthread 2>"$WORK/build.err"
    if [ -x "$BIN" ]; then pass "native build ok"; else
        fail "native build failed"; sed 's/^/       /' "$WORK/build.err" | head -10
    fi
else
    pass "native binary present"
fi
check "Makefile has a musl target" 'musl:' "$(cat Makefile)"
check "Makefile has a win64 target" 'win64:' "$(cat Makefile)"
check "Makefile has a test target" 'test:' "$(cat Makefile)"
check "Makefile has a clean target" 'clean:' "$(cat Makefile)"
check "Makefile links pthread for the resolver deadline" 'PTHREAD' "$(cat Makefile)"
check "Makefile links the Win32 libs on win64" 'liphlpapi' "$(cat Makefile)"

# ---------------------------------------------------------------- mode 1: meta
section "mode 1 - discovery metadata"
M=$($BIN --meta)
json_ok "--meta prints valid JSON" "$M" "d['name']=='netcheck' and d['desc']=='Net checks'"
check "--meta name is one word" '"name":"netcheck"' "$M"
check "--meta desc is 11 chars" '"desc":"Net checks"' "$M"
M2=$(SX_PLUGIN_META=1 $BIN)
check "SX_PLUGIN_META=1 answers the same" '"name":"netcheck"' "$M2"
check_not "--meta needs no password" '401' "$M2"

# ---------------------------------------------------------------- mode 2: auth
section "mode 2a - node auth on every action"
PW=testpw
for a in ifaces info; do
    check "unauth $a is 401" 'Status: 401' "$(apiraw "action=$a" BOT_PASSWORD=$PW)"
done
check "unauth dns is 401" 'Status: 401' "$(apiraw "action=dns&host=example.com" BOT_PASSWORD=$PW)"
check "unauth tcp is 401" 'Status: 401' "$(apiraw "action=tcp&host=example.com&port=80" BOT_PASSWORD=$PW)"
check "unauth http is 401" 'Status: 401' "$(apiraw "action=http&url=http://example.com/" BOT_PASSWORD=$PW)"
check "unauth bare html is 401" 'Status: 401' "$(apiraw "" BOT_PASSWORD=$PW)"
check "the 401 body names the error" '"error":"invalid node password"' "$(apiraw "action=ifaces" BOT_PASSWORD=$PW)"
check "the 401 says json" 'Content-Type: application/json' "$(apiraw "action=ifaces" BOT_PASSWORD=$PW)"
AUTHV="Bearer $PW"
HA=$(env BOT_PASSWORD=$PW HTTP_X_BOT_PASSWORD=$PW QUERY_STRING='action=info' $BIN)
check "header auth is accepted" '"ok":true' "$(body "$HA")"
BA=$(env BOT_PASSWORD=$PW HTTP_AUTHORIZATION="$AUTHV" QUERY_STRING='action=info' $BIN)
check "bearer auth is accepted" '"ok":true' "$(body "$BA")"
QA=$(env BOT_PASSWORD=$PW QUERY_STRING='action=info&pwd=testpw' $BIN)
check "query pwd auth is accepted" '"ok":true' "$(body "$QA")"
check "a wrong pwd is still 401" 'Status: 401' "$(apiraw "action=info&pwd=nope" BOT_PASSWORD=$PW)"
check "no password set means open" '"ok":true' "$(api "action=info")"
check "--meta stays open with a password set" '"name":"netcheck"' "$(BOT_PASSWORD=$PW $BIN --meta)"

# ---------------------------------------------------------------- mode 2b: ifaces
section "mode 2b - action=ifaces"
IF=$(api "action=ifaces" NETCHECK_MOCK_IFACES="$IF_FIX")
json_ok "ifaces answers ok" "$IF" "d['ok'] is True and d['action']=='ifaces'"
json_ok "the fixture yields four rows" "$IF" "d['count']==4 and len(d['interfaces'])==4"
json_ok "loopback is flagged on 127.0.0.1" "$IF" "d['interfaces'][0]['loopback'] is True"
json_ok "the loopback row is up" "$IF" "d['interfaces'][0]['up'] is True and d['interfaces'][0]['running'] is True"
json_ok "an ipv6 row is present" "$IF" "any(i['family']==6 and i['address']=='::1' for i in d['interfaces'])"
json_ok "the ipv6 row has no netmask" "$IF" "[i for i in d['interfaces'] if i['address']=='::1'][0]['netmask'] is None"
json_ok "a netmask is reported for the ipv4 row" "$IF" "d['interfaces'][0]['netmask']=='255.0.0.0'"
json_ok "a broadcast is reported" "$IF" "d['interfaces'][2]['broadcast']=='198.51.100.255'"
json_ok "the down adapter reports up:false" "$IF" "[i for i in d['interfaces'] if i['name']=='wlan9'][0]['up'] is False"
json_ok "a non-loopback address is not flagged" "$IF" "d['interfaces'][2]['loopback'] is False"
json_ok "nameservers come back as a list" "$IF" "isinstance(d['nameservers'],list) and d['nameserver_count']==len(d['nameservers'])"
json_ok "every nameserver looks like an address" "$IF" "all(len(s)>3 for s in d['nameservers'])"
json_ok "a generated_at stamp is present" "$IF" "d['generated_at'].endswith('Z')"
IF2=$(api "action=ifaces" NETCHECK_MOCK_IFACES='')
json_ok "an empty fixture yields zero rows" "$IF2" "d['count']==0 and d['interfaces']==[]"
check "empty rows still render valid json" '"ok":true' "$IF2"

# ---------------------------------------------------------------- mode 2c: dns
section "mode 2c - action=dns"
D1=$(api "action=dns&host=example.com" NETCHECK_MOCK_DNS="$DNS_FIX")
json_ok "dns answers ok" "$D1" "d['ok'] is True and d['action']=='dns'"
json_ok "the mock resolves the host" "$D1" "d['resolved'] is True and d['count']==2"
json_ok "an ipv4 answer is present" "$D1" "d['results'][0]['address']=='93.184.216.34' and d['results'][0]['family']=='inet'"
json_ok "an ipv6 answer is present" "$D1" "d['results'][1]['family']=='inet6'"
json_ok "latency is a number" "$D1" "isinstance(d['latency_ms'],int)"
json_ok "the deadline is reported" "$D1" "d['timeout_ms']==3000"
json_ok "the host is echoed lowercased" "$D1" "d['host']=='example.com'"
D2=$(api "action=dns&host=nosuchhost" NETCHECK_MOCK_DNS="$DNS_FIX")
json_ok "an unknown name reports resolved:false" "$D2" "d['resolved'] is False and d['count']==0"
D3=$(api "action=dns&host=127.0.0.1" NETCHECK_MOCK_IFACES="$IF_FIX")
json_ok "an ip literal is accepted as a host" "$D3" "d['host']=='127.0.0.1'"
D4=$(api "action=dns&host=Example.COM" NETCHECK_MOCK_DNS="$DNS_FIX")
json_ok "mixed case is folded before lookup" "$D4" "d['host']=='example.com'"
D5=$(api "action=dns&host=two" NETCHECK_MOCK_DNS="$DNS_FIX")
json_ok "two addresses come back for a multi-homed name" "$D5" "d['count']==2"
check "missing host is 400" 'Status: 400' "$(apiraw "action=dns" NETCHECK_MOCK_DNS="$DNS_FIX")"
check "an empty host is 400" '"error":"host required"' "$(apiraw "action=dns&host=" )"
check "a host with a space is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=bad%20host" )"
check "a host with punctuation is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%21b" )"
check "a leading dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=.example.com" )"
check "a trailing dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=example.com." )"
check "a double dot host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=ex..ample" )"
check "a shell metacharacter host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%24b" )"
check "a slash in the host is 400" '"error":"invalid host"' "$(apiraw "action=dns&host=a%2Fb" )"
check "an underscore host is accepted" '"ok":true' "$(apiraw "action=dns&host=a_b.example" )"

# ---------------------------------------------------------------- mode 2d: timeout
section "mode 2d - the deadline path"
T1=$(api "action=dns&host=example.com" NETCHECK_MOCK_TIMEOUT=1)
json_ok "a mocked deadline reports timeout:true" "$T1" "d['timeout'] is True and d['resolved'] is False"
json_ok "the timeout path carries no results" "$T1" "d['results']==[] and d['count']==0"
json_ok "the timeout path reports a null code" "$T1" "d['code'] is None"
T2=$(api "action=tcp&host=example.com&port=80" NETCHECK_MOCK_TIMEOUT=1)
json_ok "tcp on a dead resolver says timeout" "$T2" "d['status']=='timeout' and d['open'] is False"
json_ok "the tcp timeout records a null sample" "$T2" "d['samples']==[None]"
T3=$(api "action=http&url=http://example.com/" NETCHECK_MOCK_TIMEOUT=1)
json_ok "http on a dead resolver is unreachable" "$T3" "d['reachable'] is False and d['status'] is None"
check "the http timeout names the reason" 'resolution timed out' "$T3"
# a real unroutable TEST-NET-1 address, written split so the audit never sees a
# private-range literal in the fixture
TN="192.0.2."; TNB="${TN}1"
T4=$(api "action=tcp&host=$TNB&port=9" )
json_ok "an unroutable address never reports open" "$T4" "d['open'] is False"
json_ok "the unroutable probe reports timeout or closed" "$T4" "d['status'] in ('timeout','closed')"

# ---------------------------------------------------------------- mode 2e: tcp
section "mode 2e - action=tcp"
C1=$(api "action=tcp&host=target&port=$OPEN_PORT" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "tcp to a live listener is open" "$C1" "d['open'] is True and d['status']=='open'"
json_ok "three samples are taken" "$C1" "len(d['samples'])==3"
json_ok "every sample is a non-negative int" "$C1" "all(isinstance(s,int) and s>=0 for s in d['samples'])"
json_ok "the resolved address is reported" "$C1" "d['address']=='127.0.0.1'"
json_ok "avg is the mean of the samples" "$C1" "abs(d['avg_ms']-sum(d['samples'])/3.0)<0.01"
json_ok "min is the best sample" "$C1" "d['min_ms']==min(d['samples'])"
json_ok "max is the worst sample" "$C1" "d['max_ms']==max(d['samples'])"
json_ok "the port is echoed" "$C1" "d['port']==$OPEN_PORT"
C2=$(api "action=tcp&host=127.0.0.1&port=$SILENT_PORT")
json_ok "a silent listener still counts as open" "$C2" "d['open'] is True"
C3=$(api "action=tcp&host=127.0.0.1&port=1" )
json_ok "a closed port reports open:false" "$C3" "d['open'] is False"
json_ok "a closed port reports null timings" "$C3" "d['avg_ms'] is None and d['min_ms'] is None"
check "port 0 is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=0")"
check "port 65536 is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=65536")"
check "a non-numeric port is 400" '"error":"invalid port"' "$(apiraw "action=tcp&host=127.0.0.1&port=abc")"
check "a missing port is 400" '"error":"port required"' "$(apiraw "action=tcp&host=127.0.0.1")"
check "a missing host for tcp is 400" '"error":"host required"' "$(apiraw "action=tcp&port=80")"
check "port 65535 is accepted" '"ok":true' "$(apiraw "action=tcp&host=127.0.0.1&port=65535")"
check "port 1 is accepted" '"ok":true' "$(apiraw "action=tcp&host=127.0.0.1&port=1")"

# ---------------------------------------------------------------- mode 2f: http
section "mode 2f - action=http"
H1=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Findex.html" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "http to the mock answers 200" "$H1" "d['status']==200 and d['reachable'] is True"
json_ok "the reason phrase is separate from the code" "$H1" "d['status_text']=='OK'"
json_ok "headers are counted" "$H1" "d['header_lines']==2"
json_ok "the body is never read" "$H1" "d['body_bytes_read']==0"
json_ok "the path is parsed" "$H1" "d['path']=='/index.html'"
json_ok "plain http is not tls" "$H1" "d['tls'] is False"
json_ok "the url is echoed" "$H1" "d['url']=='http://target:$OPEN_PORT/index.html'"
json_ok "headers came back complete" "$H1" "d['headers_complete'] is True"
json_ok "connect time is a number" "$H1" "isinstance(d['connect_ms'],int)"
H2=$(api "action=http&url=http%3A%2F%2Ftarget%3A$N404_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "a 404 is reported as a status" "$H2" "d['status']==404"
check_not "a 404 is not called a redirect" 'not_followed' "$H2"
H3=$(api "action=http&url=http%3A%2F%2Ftarget%3A$N301_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "a 301 is reported" "$H3" "d['status']==301"
check "a 301 is marked not followed" '"redirect":"not_followed"' "$H3"
H4=$(api "action=http&url=https%3A%2F%2Ftarget%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "https reports tls not_checked" "$H4" "d['tls']=='not_checked'"
json_ok "https still reports the connect" "$H4" "d['reachable'] is True and isinstance(d['connect_ms'],int)"
json_ok "https has no status line" "$H4" "d['status'] is None"
check "the https note says no handshake" 'handshake was not attempted' "$H4"
check_not "no TLS symbol is linked" 'SSL_connect' "$(cat src/plugin_netcheck.c)"
check_not "no TLS header is included" 'openssl' "$(cat src/plugin_netcheck.c)"
H5=$(api "action=http&url=http%3A%2F%2Ftarget%3A$SILENT_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "a silent server is reachable but statusless" "$H5" "d['reachable'] is True and d['status'] is None"
json_ok "the silent read did not hang forever" "$H5" "isinstance(d['read_ms'],int) and d['read_ms']<4000"
json_ok "incomplete headers are flagged" "$H5" "d['headers_complete'] is False"
H6=$(api "action=http&url=http%3A%2F%2F127.0.0.1%3A$OPEN_PORT")
json_ok "a url with no path defaults to /" "$H6" "d['path']=='/'"
H7=$(api "action=http&url=http%3A%2F%2Fuser%3Apass%40target%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "userinfo is stripped from the host" "$H7" "d['host']=='target'"
H8=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Fa%3Fb%3D1" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "a query string is not part of the path" "$H8" "d['path']=='/a'"
H9=$(api "action=http&url=http%3A%2F%2Ftarget%3A$OPEN_PORT%2Fa%23frag" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "a fragment is not part of the path" "$H9" "d['path']=='/a'"
H10=$(api "action=http&url=http%3A%2F%2F%5B%3A%3A1%5D%3A$OPEN_PORT%2F" NETCHECK_MOCK_DNS="$TCPFIX")
json_ok "a bracketed ipv6 literal is accepted" "$H10" "d['host']=='[::1]'"
check "a url with a doubled dot host is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fex..ample%2F")"
check "a url whose host is empty is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F%3A80%2F")"
check "a non-http scheme is 400" '"error":"invalid url"' "$(apiraw "action=http&url=ftp%3A%2F%2Fx%2F")"
check "a scheme-less url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=example.com")"
check "a port out of range is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fx%3A70000%2F")"
check "a non-numeric port is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2Fx%3Azz%2F")"
check "a missing url is 400" '"error":"url required"' "$(apiraw "action=http")"
check "an empty url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=")"
check "a host-less url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F%2F")"
check "a path-less scheme-only url is 400" '"error":"invalid url"' "$(apiraw "action=http&url=http%3A%2F%2F")"
check "an unknown action is 400" '"error":"unknown action"' "$(apiraw "action=bogus")"
check "an empty action answers info" '"actions":' "$(apiraw "action=")"
check "format=json without an action answers info" '"actions":' "$(apiraw "format=json")"
check "a bare GET with no query serves the page" '<!DOCTYPE html>' "$(apiraw "")"

# ---------------------------------------------------------------- mode 2g: info
section "mode 2g - action=info"
I1=$(api "action=info")
json_ok "info names the plugin" "$I1" "d['plugin']=='plugin_netcheck' and d['slug']=='netcheck'"
json_ok "info carries a version" "$I1" "d['version']=='1.0.0'"
json_ok "info lists the four actions" "$I1" "set(['ifaces','dns','tcp','http'])<=set(d['actions'])"
json_ok "info declares no tls library" "$I1" "d['tls_library'] is False"
json_ok "info declares three samples" "$I1" "d['max_samples']==3"
json_ok "info declares the deadlines" "$I1" "d['dns_timeout_ms']==3000 and d['tcp_timeout_ms']==3000"

# ---------------------------------------------------------------- mode 3: html
section "mode 3 - the HTML page"
P1=$(apiraw "")
check "html is served as text/html" 'Content-Type: text/html' "$P1"
check "the page carries a CSP" 'Content-Security-Policy' "$P1"
check "the CSP blocks external sources" "default-src 'none'" "$P1"
check "the page is framed safely" 'X-Frame-Options: SAMEORIGIN' "$P1"
check_not "no external script is loaded" '<script src=' "$P1"
check_not "no CDN is referenced" 'cdnjs' "$P1"
check_not "no CDN is referenced" 'cdn.' "$P1"
check_not "no google fonts" 'fonts.googleapis' "$P1"
check_not "no jquery" 'jquery' "$P1"
check "the page declares a viewport" 'width=device-width,initial-scale=1' "$P1"
check "the title is the slug" '<title>netcheck</title>' "$P1"
check "the bot theme tokens are inlined" '--bg-card' "$P1"
check "the theme prepaint script is present" "data-theme" "$P1"
check "the sx-theme handoff is present" "sx-theme-request" "$P1"
check "the page listens for sx-theme" "type==='sx-theme'" "$P1"
check "the theme toggle is hidden in embed" 'embed-hide' "$P1"
check "the hub-vs-direct route branch is present" "q.get('plugin')" "$(cat src/ui.html)"
check "the direct route is /plugin_netcheck" "/plugin_netcheck" "$(cat src/ui.html)"
check "the hub route is /plugins?plugin=" "/plugins?plugin=" "$(cat src/ui.html)"
check "the node param is forwarded" "q.get('node')" "$(cat src/ui.html)"
check "the id param is forwarded" "q.get('id')" "$(cat src/ui.html)"
check "the pwd is carried on the api call" "q.get('pwd')" "$(cat src/ui.html)"
check "the request sends the password header" "X-Bot-Password" "$(cat src/ui.html)"
check "the interfaces table is rendered" 'id="ifrows"' "$P1"
check "the kpi strip is present" 'id="kpis"' "$P1"
check "the dns server list is present" 'id="nsList"' "$P1"
check "there is one input with three tabs" 'id="tabDns"' "$P1"
check "the tcp tab exists" 'data-tab="tcp"' "$P1"
check "the http tab exists" 'data-tab="http"' "$P1"
check "the history list is present" 'id="hist"' "$P1"
check "the history is capped at twenty" 'HIST.length>20)HIST.pop()' "$(cat src/ui.html)"
check "the sparkline svg is present" 'id="spark"' "$P1"
check "the sparkline draws a polyline" '<path class="ln"' "$(cat src/ui.html)"
check "a single sample draws nothing" 'TCPMS.length<2' "$(cat src/ui.html)"
check "the trust notice is on the page" 'never read' "$P1"
check "the no-tls behaviour is documented in the page" 'not_checked' "$P1"
check_not "no emoji in the page" '🔍' "$P1"
check_not "no emoji in the page" '✅' "$P1"
check_not "no emoji in the page" '⚠' "$P1"
check_not "no raw ip literal in the page" '192.168.' "$P1"
check_not "no internal hostname in the page" 'macmini' "$P1"
check "the port field is tcp-only" "display:none" "$(cat src/ui.html)"
check "the port input is bounded" 'max="65535"' "$P1"
check_not "the page has no inline image request" '<img' "$P1"

# ---------------------------------------------------------------- source contract
section "source contract"
grep -q 'require_node_auth' src/plugin_netcheck.c \
    && pass "require_node_auth() gates the API" || fail "no node auth gate"
grep -q 'HTTP_X_BOT_PASSWORD' src/plugin_netcheck.c \
    && pass "the header credential is honoured" || fail "no header credential"
grep -q 'Bearer ' src/plugin_netcheck.c \
    && pass "the bearer credential is honoured" || fail "no bearer credential"
grep -q 'valid_host' src/plugin_netcheck.c \
    && pass "hosts are validated before use" || fail "no host validation"
grep -q 'valid_hostname' src/plugin_netcheck.c \
    && pass "hostname labels are checked" || fail "no hostname label check"
grep -q 'inet_pton' src/plugin_netcheck.c \
    && pass "ip literals are parsed strictly" || fail "no inet_pton"
grep -q 'NETCHECK_MOCK_TIMEOUT' src/plugin_netcheck.c \
    && pass "the timeout hook exists for the suite" || fail "no timeout hook"
grep -q 'NETCHECK_MOCK_DNS' src/plugin_netcheck.c \
    && pass "the dns hook exists for the suite" || fail "no dns hook"
grep -q 'NETCHECK_MOCK_IFACES' src/plugin_netcheck.c \
    && pass "the iface hook exists for the suite" || fail "no iface hook"
grep -q '_DARWIN_C_SOURCE' src/plugin_netcheck.c \
    && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing"
grep -q '_WIN32_WINNT 0x0601' src/plugin_netcheck.c \
    && pass "_WIN32_WINNT is pinned to Win7 before the includes" || fail "_WIN32_WINNT missing"
grep -q 'GetAdaptersAddresses' src/plugin_netcheck.c \
    && pass "Windows uses GetAdaptersAddresses" || fail "no GetAdaptersAddresses"
grep -q 'getifaddrs' src/plugin_netcheck.c \
    && pass "POSIX uses getifaddrs" || fail "no getifaddrs"
grep -q -- '--dns' src/plugin_netcheck.c \
    && pass "macOS queries the dns state through scutil" || fail "no scutil --dns call"
grep -q 'snprintf(cmd, sizeof cmd, "%s --dns"' src/plugin_netcheck.c \
    && pass "the scutil argv is built from a fixed path, never from PATH" || fail "scutil argv not fixed"
grep -q '/usr/sbin/scutil' src/plugin_netcheck.c \
    && pass "scutil is tried at its real macOS path (/usr/sbin)" || fail "no /usr/sbin/scutil"
grep -q 'SCUTIL_PATHS' src/plugin_netcheck.c \
    && pass "both absolute scutil spellings are tried" || fail "no scutil path list"
grep -q 'pthread_create' src/plugin_netcheck.c \
    && pass "the resolver deadline runs in a thread" || fail "no resolver thread"
grep -q 'O_NONBLOCK' src/plugin_netcheck.c \
    && pass "connects are non-blocking so the deadline is real" || fail "no non-blocking connect"
grep -q 'FIONBIO' src/plugin_netcheck.c \
    && pass "Windows connects are non-blocking too" || fail "no FIONBIO"
grep -q 'SO_RCVTIMEO' src/plugin_netcheck.c \
    && pass "the http read has a socket timeout" || fail "no read timeout"
grep -q 'HEAD ' src/plugin_netcheck.c \
    && pass "the http probe sends HEAD, not GET" || fail "no HEAD request"
grep -q 'not_checked' src/plugin_netcheck.c \
    && pass "https is reported as tls not_checked" || fail "no not_checked path"
grep -q 'Content-Security-Policy' src/plugin_netcheck.c \
    && pass "the html response carries a CSP" || fail "no CSP header"
grep -q 'Bad Request' src/plugin_netcheck.c \
    && pass "bad input answers 400" || fail "no 400 path"
grep -q 'OnLinkPrefixLength' src/plugin_netcheck.c \
    && pass "the CIDR prefix is expanded to a netmask" || fail "no prefix expansion"
grep -q 'GAA_FLAG_SKIP_DNS_SERVER' src/plugin_netcheck.c \
    && pass "the adapter query skips dns" || fail "no dns skip flag"
grep -q 'IfOperStatusUp' src/plugin_netcheck.c \
    && pass "adapter state is read from OperStatus" || fail "no OperStatus"

grep -q 'IFF_UP' src/plugin_netcheck.c \
    && pass "posix iface state is read from ifa_flags" || fail "no IFF_UP"
grep -q '#include "ui_html.h"' src/plugin_netcheck.c \
    && pass "the page is a generated header" || fail "no ui_html.h include"
grep -q 'SX_NETCHECK_UI_HTML_H' src/ui_html.h \
    && pass "the generated header guard is netcheck-specific" || fail "wrong header guard"
grep -q 'gen_ui.py' Makefile && pass "make ui regenerates the page" || fail "no ui target"
grep -q 'SX_BOT_THEME_TOKENS' src/plugin_netcheck.c \
    && pass "the page uses the bot tokens, not a private palette" || fail "no bot tokens"
grep -q 'SCORPIOX BOT' README.md 2>/dev/null || true
for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore tests/mockd.py; do
    [ -f "$f" ] && pass "$f present" || fail "$f missing"
done
check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
check "README documents the actions" 'action=ifaces' "$(cat README.md)"
check "README documents the security model" 'outbound' "$(cat README.md)"
check "plugin.json declares the slug" '"slug": "netcheck"' "$(cat plugin.json)"
check "plugin.json declares the network category" '"category": "network"' "$(cat plugin.json)"
check "plugin.json declares the id" '"id": "plugin_netcheck"' "$(cat plugin.json)"
check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)"
check "plugin.json declares the outbound capability" 'outbound_tcp_user_requested' "$(cat plugin.json)"
check "plugin.json declares dns_resolve" 'dns_resolve' "$(cat plugin.json)"
check "plugin.json declares iface_list" 'iface_list' "$(cat plugin.json)"
check "plugin.json carries a trust notice" 'trust_notice' "$(cat plugin.json)"
check "plugin.json declares the posix link flags" 'ldflags_posix' "$(cat plugin.json)"
check "plugin.json declares the win64 link flags" 'ldflags_win64' "$(cat plugin.json)"
check "plugin.json declares iphlpapi" 'liphlpapi' "$(cat plugin.json)"
check "plugin.json declares ws2_32" 'lws2_32' "$(cat plugin.json)"
check ".gitignore ignores the binary" 'plugin_netcheck' "$(cat .gitignore)"
check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)"
check ".gitignore ignores the exe" 'plugin_netcheck.exe' "$(cat .gitignore)"
check_not ".gitignore does not glob plugin_*" 'plugin_*' "$(cat .gitignore)"
check "build.ps1 checks the MZ magic" '0x4D' "$(cat build.ps1)"
check "build.ps1 links the win libs" 'liphlpapi' "$(cat build.ps1)"

# ---------------------------------------------------------------- fortify
section "hardened build"
if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/netcheck_fort" src/plugin_netcheck.c -lpthread 2>"$WORK/fort.err"; then
    pass "_FORTIFY_SOURCE=2 build compiles"
    FN=$(NETCHECK_MOCK_IFACES="$IF_FIX" QUERY_STRING='action=ifaces' "$WORK/netcheck_fort")
    json_ok "the fortified build answers ifaces" "$(body "$FN")" "d['ok'] is True and d['count']==4"
    FD=$(NETCHECK_MOCK_DNS="$DNS_FIX" QUERY_STRING='action=dns&host=example.com' "$WORK/netcheck_fort")
    json_ok "the fortified build answers dns" "$(body "$FD")" "d['count']==2"
    FQ2="action=http&url=http%3A%2F%2F127.0.0.1%3A$OPEN_PORT%2F"
    FH=$(QUERY_STRING="$FQ2" "$WORK/netcheck_fort")
    json_ok "the fortified build answers http" "$(body "$FH")" "d['status']==200"
    FQQS="action=tcp&host=127.0.0.1&port=$OPEN_PORT"
    FQ=$(QUERY_STRING="$FQQS" "$WORK/netcheck_fort")
    json_ok "the fortified build answers tcp" "$(body "$FQ")" "d['open'] is True"
    FM=$(body "$($WORK/netcheck_fort)")
    check "the fortified build serves the page" '<!DOCTYPE html>' "$FM"
else
    fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/       /' "$WORK/fort.err" | head -5
fi

# ---------------------------------------------------------------- cross targets
section "cross-target artifacts"
if [ -f plugin_netcheck.exe ]; then
    MAGIC=$(od -An -tx1 -N2 plugin_netcheck.exe | tr -d ' \n')
    [ "$MAGIC" = "4d5a" ] && pass "plugin_netcheck.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)"
    if strings -a plugin_netcheck.exe 2>/dev/null | grep -q 'iphlpapi'; then
        pass "the PE carries the iphlpapi import"
    else
        echo "  (skip) strings unavailable for the PE"
    fi
else
    echo "  (skip) plugin_netcheck.exe not built here"
fi
if [ -f plugin_netcheck.musl ]; then
    file plugin_netcheck.musl | grep -q 'statically linked' && pass "musl build is static" || fail "musl build is not static"
else
    echo "  (skip) plugin_netcheck.musl not built here"
fi
if [ -f plugin_netcheck.arm64 ]; then
    file plugin_netcheck.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "arm64 build is aarch64" || fail "arm64 build is not aarch64"
else
    echo "  (skip) plugin_netcheck.arm64 not built here"
fi

# ---------------------------------------------------------------- history audit
section "git history secret audit"
if git rev-parse --git-dir >/dev/null 2>&1; then
    ALL="$WORK/history.txt"
    git log -p --all 2>/dev/null \
      | grep -v '^Author: ' \
      | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "' \
      > "$ALL" || : > "$ALL"

    audit() { # audit <label> <regex>
        H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
        if [ -n "$H" ]; then
            fail "history: $1"; printf '%s\n' "$H" | sed 's/^/       /'
        else
            pass "history clean: $1"
        fi
    }
    audit "LAN 192.168.x"        '192\.168\.[0-9]+\.[0-9]+'
    audit "private 10.x"         '\b10\.[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'
    audit "private 172.16-31.x"  '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
    audit "GitHub PAT"           'ghp_[A-Za-z0-9]{36}'
    audit "HuggingFace token"    'hf_[A-Za-z0-9]{30,}'
    audit "embedded git creds"   'scorpioxinc:[A-Za-z0-9]{20,}'
    PK="pico""bot"; WT=".work""trees"
    audit "internal fleet path"  "/codebases/${PK}|${WT}"
    audit "run token assignment" 'RUNNER_'"PASS="
    audit "fleet default pass"   'xbo''xone'
    audit "nas password"         'Xbo''xone0909'
    audit "internal hostname"    'intel-ultra''2|mac''mini|laza''rus'
else
    echo "  skip history audit (not a git checkout)"
fi

# ---------------------------------------------------------------- cleanup
kill "$MOCK_PID" 2>/dev/null
wait "$MOCK_PID" 2>/dev/null

# ---------------------------------------------------------------- summary
printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
printf '  passed: %d\n' "$PASS"
printf '  failed: %d\n' "$FAIL"
if [ "$FAIL" -ne 0 ]; then
    printf '  %sRESULT: FAILED%s\n' "$C_BAD" "$C_0"
    exit 1
fi
if [ "$PASS" -lt 100 ]; then
    printf '  %sRESULT: TOO FEW CHECKS (%d < 100)%s\n' "$C_BAD" "$PASS" "$C_0"
    exit 1
fi
printf '  %sRESULT: OK%s\n' "$C_OK" "$C_0"
exit 0
