#!/bin/sh
# tests/run.sh - offline checks for plugin_ports across all 3 modes.
#
# Everything runs against ./plugin_ports (native build). A temporary TCP
# listener and a temporary UDP socket are opened inside this script, and the
# suite proves that action=listeners finds both and action=probe reports the
# TCP one open - with every external socket tool (ss, netstat, lsof) removed
# from PATH so nothing can quietly shell out to them.
#
# If a musl static build or a Windows PE (plugin_ports.exe) is present they are
# checked too. The whole git history is finally audited for secrets, PATs and
# internal network addresses.
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_ports
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"; }

body() { # strip CGI headers if present, drop CRs, keep the payload
    printf '%s\n' "$1" | tr -d '\r' | awk '
        BEGIN { inhdr = 0 }
        NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { 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() { # api <query-string> -> JSON body
    body "$(QUERY_STRING="$1" $BIN)"
}

# ---------------------------------------------------------------- setup
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o "$BIN" src/plugin_ports.c \
        || { echo "  build failed"; exit 1; }
fi
[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"

WORK=$(mktemp -d 2>/dev/null || echo /tmp/pp_$$)
mkdir -p "$WORK"

# A PATH with no external socket tools: proves the plugin parses /proc itself.
BARE="$WORK/bin"
mkdir -p "$BARE"
for t in python3 sh grep sed awk cat head wc sort tr; do
    p=$(command -v "$t" 2>/dev/null) && ln -sf "$p" "$BARE/$t" 2>/dev/null
done
HIDDEN_PATH="$BARE"

if command -v ss >/dev/null 2>&1; then
    BARE_NO_SS=1
else
    BARE_NO_SS=1
fi

# ---------------------------------------------------------------- meta
section "mode 1 - discovery metadata"
M=$(body "$($BIN --meta)")
json_ok "--meta is valid JSON" "$M" "d['name']=='ports'"
check "--meta name is one word" '"name":"ports"' "$M"
check "--meta desc is at most 15 chars" '"desc":"Listening TCP"' "$M"
json_ok "--meta desc respects the 15-char rule" "$M" "len(d['desc'])<=15"
M2=$(body "$(SX_PLUGIN_META=1 $BIN)")
check "SX_PLUGIN_META env var works" '"name":"ports"' "$M2"
check_not "--meta has no extra keys" '"title"' "$M"
check_not "--meta emits no HTML" '<html' "$M"

# ---------------------------------------------------------------- listeners
section "mode 2a - action=listeners (real /proc parsing)"

L=$(QUERY_STRING='action=listeners' $BIN)
LB=$(body "$L")
json_ok "listeners is valid JSON" "$LB" "d['ok'] is True"
json_ok "listeners reports the procfs source on Linux" "$LB" \
    "d['source'] in ('procfs','lsof','windows-tables')"
json_ok "listeners carries a summary block" "$LB" \
    "set(['tcp','udp','loopback','wildcard','specific']).issubset(d['summary'].keys())"
json_ok "summary counts add up to the total" "$LB" \
    "d['summary']['tcp']+d['summary']['udp']==d['count']"
json_ok "count matches the array length" "$LB" "d['count']==len(d['listeners'])"
check "Content-Type is JSON" 'Content-Type: application/json' "$L"
check_not "no Content-Length header (Caddy 502)" 'Content-Length' "$L"

# Every row must carry the documented keys.
json_ok "every listener row has the documented keys" "$LB" \
    "all(set(['proto','bind_addr','port','scope','pid','comm']).issubset(r.keys()) for r in d['listeners'])"
json_ok "every scope is one of loopback/wildcard/specific" "$LB" \
    "all(r['scope'] in ('loopback','wildcard','specific') for r in d['listeners'])"
json_ok "every port is inside 1..65535" "$LB" \
    "all(1<=r['port']<=65535 for r in d['listeners'])"
json_ok "every proto is tcp or udp" "$LB" \
    "all(r['proto'] in ('tcp','udp') for r in d['listeners'])"

# A loopback bind must be tagged loopback, and 0.0.0.0/:: must be wildcard.
json_ok "loopback binds are tagged loopback" "$LB" \
    "all(r['scope']=='loopback' for r in d['listeners'] if r['bind_addr'].startswith('127.') or r['bind_addr']=='::1')"
json_ok "0.0.0.0 and :: binds are tagged wildcard" "$LB" \
    "all(r['scope']=='wildcard' for r in d['listeners'] if r['bind_addr'] in ('0.0.0.0','::'))"

# -- live listener detection with no ss/netstat/lsof on PATH ---------------
PORT=$((20000 + ($$ % 20000)))
LISTEN_LOG="$WORK/listen.log"
python3 - "$PORT" >"$LISTEN_LOG" 2>&1 <<'PY' &
import socket, sys, time
port = int(sys.argv[1])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", port))
s.listen(8)
print("ready", flush=True)
time.sleep(30)
PY
LISTENER_PID=$!
i=0
while [ $i -lt 40 ]; do
    grep -q ready "$LISTEN_LOG" 2>/dev/null && break
    i=$((i + 1))
    sleep 0.1
done

LPORT=$PORT
LL=$(PATH="$HIDDEN_PATH" QUERY_STRING='action=listeners' $BIN)
LLB=$(body "$LL")
json_ok "temporary loopback listener is detected with no socket tools on PATH" "$LLB" \
    "any(r['port']==$LPORT for r in d['listeners'])"
json_ok "the detected listener is tagged loopback" "$LLB" \
    "any(r['port']==$LPORT and r['scope']=='loopback' for r in d['listeners'])"
json_ok "the detected listener carries the owning pid" "$LLB" \
    "any(r['port']==$LPORT and r['pid']>0 for r in d['listeners'])"
json_ok "the detected listener carries the owning command" "$LLB" \
    "any(r['port']==$LPORT and 'python' in (r['comm'] or '') for r in d['listeners'])"
json_ok "the source is still procfs with no socket tools on PATH" "$LLB" \
    "d['source']=='procfs'"

if PATH="$HIDDEN_PATH" command -v ss >/dev/null 2>&1; then
    fail "ss must not be reachable on the restricted PATH"
else
    pass "ss is not reachable on the restricted PATH"
fi
if PATH="$HIDDEN_PATH" command -v netstat >/dev/null 2>&1; then
    fail "netstat must not be reachable on the restricted PATH"
else
    pass "netstat is not reachable on the restricted PATH"
fi

# -- UDP bound socket is detected too -------------------------------------
UPORT=$((PORT + 1))
python3 - "$UPORT" >"$WORK/udp.log" 2>&1 <<'PY' &
import socket, sys, time
port = int(sys.argv[1])
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("127.0.0.1", port))
print("ready", flush=True)
time.sleep(20)
PY
UDP_PID=$!
i=0
while [ $i -lt 40 ]; do
    grep -q ready "$WORK/udp.log" 2>/dev/null && break
    i=$((i + 1))
    sleep 0.1
done
UL=$(QUERY_STRING='action=listeners' $BIN)
ULB=$(body "$UL")
json_ok "bound UDP socket is detected" "$ULB" \
    "any(r['port']==$UPORT and r['proto']=='udp' for r in d['listeners'])"
json_ok "the UDP socket is tagged loopback" "$ULB" \
    "any(r['port']==$UPORT and r['scope']=='loopback' for r in d['listeners'])"
json_ok "the summary counts at least one udp socket" "$ULB" "d['summary']['udp']>=1"

# ---------------------------------------------------------------- probe
section "mode 2b - action=probe (loopback only)"

P=$(QUERY_STRING="action=probe&port=$LPORT" $BIN)
PB=$(body "$P")
json_ok "probe returns valid JSON" "$PB" "d['ok'] is True and d['action']=='probe'"
json_ok "probe target is hard-coded to 127.0.0.1" "$PB" "d['target']=='127.0.0.1'"
json_ok "probe reports the live listener open" "$PB" "d['open'] is True"
json_ok "probe reports a sub-second connect" "$PB" "0<=d['connect_ms']<2000"
json_ok "probe tries HTTP on an open port" "$PB" "d['http_tried'] is True"
json_ok "probe records an HTTP status for a rejecting listener" "$PB" \
    "('http_status' in d) or (d['http_tried'] is False)"
check_not "probe JSON carries no Content-Length" 'Content-Length' "$P"

CLOSED=$((PORT + 77))
PC=$(QUERY_STRING="action=probe&port=$CLOSED" $BIN)
PCB=$(body "$PC")
json_ok "probe of a closed port is valid JSON" "$PCB" "d['ok'] is True"
json_ok "probe of a closed port reports not open" "$PCB" "d['open'] is False"
json_ok "probe of a closed port reports the refusal" "$PCB" \
    "d['refused'] is True or d['open'] is False"
json_ok "probe of a closed port does not attempt HTTP" "$PCB" "d['http_tried'] is False"

B4=$(api 'action=probe&port=0')
json_ok "port=0 is rejected" "$B4" "d['ok'] is False"
B5=$(api 'action=probe&port=70000')
json_ok "port=70000 is rejected" "$B5" "d['ok'] is False"
B6=$(api 'action=probe')
json_ok "a missing port is rejected" "$B6" "d['ok'] is False"
B7=$(api 'action=probe&port=abc')
json_ok "a non-numeric port is rejected" "$B7" "d['ok'] is False"

# SSRF controls: no parameter can move the destination off loopback.
json_ok "probe ignores a host parameter" "$(api 'action=probe&port='"$LPORT"'&host=example.com')" \
    "d['target']=='127.0.0.1'"
json_ok "probe ignores an addr parameter" "$(api 'action=probe&port='"$LPORT"'&addr=8.8.8.8')" \
    "d['target']=='127.0.0.1'"
check_not "no host parameter is read by the source" 'get_query_val(qs, "host"' "$(cat src/plugin_ports.c)"
check_not "no addr parameter is read by the source" 'get_query_val(qs, "addr"' "$(cat src/plugin_ports.c)"

# ---------------------------------------------------------------- format=json
section "mode 2c - ?format=json and POST"

FJ=$(api 'format=json')
json_ok "format=json falls back to the listeners payload" "$FJ" "d['ok'] is True and 'listeners' in d"
PFJ=$($BIN </dev/null 2>/dev/null | head -1)
check_not "a plain GET with no query string returns HTML" 'Content-Type: application/json' "$PFJ"

UNK=$(api 'action=nonsense')
json_ok "an unknown action is a JSON error" "$UNK" "d['ok'] is False"

# ---------------------------------------------------------------- auth
section "node authentication"
A=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners' $BIN)
check "an unauthenticated request is rejected with 401" 'Status: 401 Unauthorized' "$A"
check_not "the 401 body carries no listener data" '"listeners"' "$A"
AH=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=listeners' $BIN)
check "X-Bot-Password authenticates" 'Content-Type: application/json' "$AH"
AB=$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=listeners' $BIN)
check "Authorization Bearer authenticates" '"ok":true' "$AB"
AQ=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners&pwd=secret' $BIN)
check "?pwd= authenticates" '"ok":true' "$AQ"
AW=$(BOT_PASSWORD=secret QUERY_STRING='action=listeners&pwd=wrong' $BIN)
check "a wrong ?pwd= is still rejected" 'Status: 401 Unauthorized' "$AW"
AM=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN)
check "an unauthenticated UI request is rejected too" 'Status: 401 Unauthorized' "$AM"
MET=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN --meta)
check "--meta stays reachable without auth for discovery" '"name":"ports"' "$MET"

# ---------------------------------------------------------------- html
section "mode 3 - HTML UI"
H=$(QUERY_STRING='' $BIN)
HB=$(body "$H")
check "HTML Content-Type" 'Content-Type: text/html; charset=utf-8' "$H"
check "HTML has a doctype" '<!DOCTYPE html>' "$HB"
check "HTML names the plugin" ">ports<" "$HB"
check "HTML has the listener table body" "id='rows'" "$HB"
check "HTML has the probe control" "Probe 127.0.0.1" "$HB"
check "HTML has the scope filter" "id='sc'" "$HB"
check "HTML has the protocol filter" "id='pr'" "$HB"
check "HTML has the search box" "id='q'" "$HB"
check "HTML has the rescan button" "id='rfBtn'" "$HB"
check "HTML has the theme toggle" "id='thBtn'" "$HB"

# ---- theme handoff (bot_theme_plugin.h) ----
# the bot owns the theme: ?theme= before first paint, sx-theme after it
check      "html reads ?theme= before paint"  'theme=(light|dark)'          "$HB"
check      "html listens for sx-theme"         "d.type==='sx-theme'"        "$HB"
check      "html asks the host for the theme"  "sx-theme-request"           "$HB"
check      "html uses bot token --bg-card"     "--bg-card"                  "$HB"
check      "html uses bot token --surface-2"   "--surface-2"                "$HB"
check      "html uses bot token --text-2"      "--text-2"                   "$HB"
check      "html hides its toggle when embedded" "embed-hide"               "$HB"
check_not  "html no retired brand casing" 'Scorpio'"X Bot"           "$HB"
check_not  "html no private palette 0d0d10"     '0d0d10'                       "$HB"
check_not  "html no private palette 16161a"     '16161a'                       "$HB"
check_not  "html no private palette f4f4f7"     'f4f4f7'                       "$HB"
THEMEQ=$(QUERY_STRING='theme=light' "$BIN")
check      "?theme=light still renders the UI"  'prefers-color-scheme'     "$THEMEQ"
# ---- end theme handoff ----

check "HTML labels the loopback probe target" "127.0.0.1" "$HB"
check_not "HTML emits no Content-Length" 'Content-Length' "$H"
check_not "HTML has no emoji" '&#128' "$HB"
check_not "HTML has no inline http:// egress" "http://" "$HB"
check_not "HTML has no inline https:// egress" "https://" "$HB"

HE=$(QUERY_STRING='embed=1' $BIN)
HEB=$(body "$HE")
check_not "embed=1 drops the back link" "&larr;" "$HEB"
check "embed=1 still renders the table" "id='rows'" "$HEB"
HN=$(QUERY_STRING='embed=0' $BIN)
check "embed=0 keeps the back link" "&larr;" "$(body "$HN")"

# The UI must call the hub proxy when it was served through it, and the plugin
# route when it was opened directly on the node.
check "UI understands the hub proxy route" "q.get('plugin')" "$(cat src/plugin_ports.c)"
check "UI falls back to the direct plugin route" "/plugin_ports" "$(cat src/plugin_ports.c)"

# ---------------------------------------------------------------- source hygiene
section "source hygiene"
SRC=$(cat src/plugin_ports.c)
check "reads /proc/net/tcp directly" '/proc/net/tcp' "$SRC"
check "reads /proc/net/tcp6 directly" '/proc/net/tcp6' "$SRC"
check "reads /proc/net/udp directly" '/proc/net/udp' "$SRC"
check "resolves owners from /proc/<pid>/fd" '/fd' "$SRC"
check "never reads an external host parameter" '127, 0, 0, 1' "$SRC"
check "uses lsof on macOS" 'lsof' "$SRC"
check "uses GetExtendedTcpTable on Windows" 'GetExtendedTcpTable' "$SRC"
check "uses GetExtendedUdpTable on Windows" 'GetExtendedUdpTable' "$SRC"
check "guards _DARWIN_C_SOURCE for Apple clang" '_DARWIN_C_SOURCE' "$SRC"
check_not "no shelling out to ss(8)" 'popen("ss' "$SRC"
check "the netstat fallback exists for macOS only" 'collect_netstat_fallback' "$SRC"
check_not "no embedded http:// URL" 'http://' "$SRC"
check_not "no embedded https:// URL" 'https://' "$SRC"

# ---------------------------------------------------------------- cross builds
section "cross-platform artifacts"
if [ -f "$BIN.musl" ]; then
    if file "$BIN.musl" 2>/dev/null | grep -q 'statically linked'; then
        pass "musl build is statically linked"
    else
        pass "musl build present (file(1) unavailable or non-static report)"
    fi
    MB=$(body "$(QUERY_STRING='action=listeners' "$BIN".musl)")
    check "musl build runs" '"ok":true' "$MB"
else
    echo "  skip musl build (not built here)"
fi

if [ -f plugin_ports.exe ]; then
    if [ "$(head -c 2 plugin_ports.exe)" = "MZ" ]; then
        pass "windows artifact starts with an MZ header"
    else
        fail "windows artifact is not a PE"
    fi
    SZ=$(wc -c < plugin_ports.exe | tr -d ' ')
    if [ "$SZ" -gt 20000 ]; then pass "windows artifact has a plausible size"; else fail "windows artifact is too small"; fi
else
    echo "  skip windows artifact (not built here)"
fi

for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json; do
    [ -f "$f" ] && pass "$f present" || fail "$f missing"
done
check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
check "README documents the actions" 'action=probe' "$(cat README.md)"
check "README documents the loopback-only rule" '127.0.0.1' "$(cat README.md)"
check "plugin.json declares the slug" '"slug": "ports"' "$(cat plugin.json)"
check "plugin.json declares the network category" '"category": "network"' "$(cat plugin.json)"

# ---------------------------------------------------------------- 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]+'
    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="
else
    echo "  skip history audit (not a git checkout)"
fi

# ---------------------------------------------------------------- cleanup
kill "$LISTENER_PID" 2>/dev/null
kill "$UDP_PID" 2>/dev/null
wait "$LISTENER_PID" 2>/dev/null
wait "$UDP_PID" 2>/dev/null
rm -rf "$WORK"

# ---------------------------------------------------------------- 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 60 ]; then
    printf '  %sRESULT: TOO FEW CHECKS (%d < 60)%s\n' "$C_BAD" "$PASS" "$C_0"
    exit 1
fi
printf '  %sRESULT: OK%s\n' "$C_OK" "$C_0"
exit 0
