#!/bin/bash
# tests/run.sh - offline checks for plugin_ntfy across all five modes.
#
# Everything runs against ./plugin_ntfy and tests/mockd.py on loopback with no
# internet required. The mock ntfy server echoes our own publishes back on the
# subscription exactly like the real server, so the anti-self-loop rule is
# proven against real behaviour and not against a fixture that hides it.
#
# It proves:
#   * --meta (hybrid, mcp, daemon, menus false, verified mock) on one line
#   * the MCP stdio server: initialize, tools/list, tools/call ntfy_send,
#     priority clamp, missing message, unknown tool, --schema
#   * node auth on every action + the 401 shape
#   * the config save/validation matrix and write-only secrets
#   * the default-deny pairing gate: an unknown sender is challenged and
#     never reaches /inbox; approve -> bridge -> /inbox; the assistant reply
#     is published back once (never on later keepalives) and its own echo is
#     never forwarded; PAIR <code> self-pairing; deny / unapprove
#   * a wrong node password blocks the bridge
#   * daemon pidfile, supervised start/stop
#   * the generated page: no CDN, no <script src=, no emoji, CSP, tabs
#   * ASan + _FORTIFY_SOURCE=2 builds, PE header when present
#   * a secret audit of the tree (and of git history when .git exists)
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_ntfy
PASS=0
FAIL=0
PORT=${PORT:-18199}
MOCK_PID=""
DAEMON_PID=""

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 }
    '
}

jget() { # jget <json> <python-expr on d>  -> prints value or ERR
    printf '%s' "$1" | python3 -c "
import json,sys
try:
    d=json.loads(sys.stdin.read())
except Exception:
    print('ERR'); raise SystemExit
try:
    print($2)
except Exception:
    print('ERR')" 2>/dev/null
}

json_ok() { # json_ok <desc> <json> <python-expression on d>
    if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($3) 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...]   (state dir pinned to $CONN)
api() {
    _qs="$1"; shift
    body "$(env SX_CONNECTORS_DIR="$CONN" "$@" QUERY_STRING="$_qs" $BIN)"
}
# post <query-string> <json-body> [extra env...]
post() {
    _qs="$1"; _b="$2"; shift 2
    _blen=$(printf '%s' "$_b" | wc -c)
    body "$(printf '%s' "$_b" | env SX_CONNECTORS_DIR="$CONN" "$@" \
        REQUEST_METHOD=POST CONTENT_LENGTH=$_blen QUERY_STRING="$_qs" $BIN)"
}

wait_for() { # wait_for <seconds> <desc> <cmd...>
    _end=$(( $(date +%s) + $1 ))
    while [ "$(date +%s)" -lt "$_end" ]; do
        if "${@:3}" >/dev/null 2>&1; then pass "$2"; return 0; fi
        sleep 0.2
    done
    fail "$2 (timeout after ${1}s)"; return 1
}

mock_has() { # published capture contains substring
    curl -s -m 3 "http://127.0.0.1:$PORT/__publishes" 2>/dev/null | grep -F -q -- "$1"
}
mock_inbox_has() {
    curl -s -m 3 "http://127.0.0.1:$PORT/__inbox" 2>/dev/null | grep -F -q -- "$1"
}
mock_count() {
    curl -s -m 3 "http://127.0.0.1:$PORT/__publishes" 2>/dev/null \
        | python3 -c "import json,sys;print(len(json.load(sys.stdin)['published']))" 2>/dev/null
}

# ---------------------------------------------------------------- fixtures
WORK=$(mktemp -d)
CONN=$WORK/connectors
ROOTM=$WORK/mock
cleanup() {
    if [ -n "$DAEMON_PID" ] && kill -0 "$DAEMON_PID" 2>/dev/null; then
        kill "$DAEMON_PID" 2>/dev/null; wait "$DAEMON_PID" 2>/dev/null || true
    fi
    if [ -n "$MOCK_PID" ]; then kill "$MOCK_PID" 2>/dev/null; wait "$MOCK_PID" 2>/dev/null || true; fi
    rm -rf "$WORK"
}
trap cleanup EXIT

python3 tests/mockd.py --port "$PORT" --root "$ROOTM" > "$WORK/mockd.out" 2>&1 &
MOCK_PID=$!
i=0
while [ "$i" -lt 60 ]; do
    grep -q "listening" "$WORK/mockd.out" 2>/dev/null && break
    i=$((i + 1)); sleep 0.1
done
if grep -q "listening" "$WORK/mockd.out" 2>/dev/null; then
    pass "mock ntfy + node API is up on 127.0.0.1:$PORT"
else
    fail "mockd never came up"; sed 's/^/       /' "$WORK/mockd.out" | head -5
    printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0"
    exit 1
fi

CFG_OK='{"server_url":"http://127.0.0.1:'"$PORT"'","topic":"tin","publish_topic":"tout","bot_api_url":"http://127.0.0.1:'"$PORT"'","target_session":"mock-session","pairing_code_enabled":1,"reply_poll_ms":200,"idle_timeout_ms":2500}'

# Identities: sha256("v1|<topic>|<user>|<tags lowercased verbatim>"). The mock
# re-serialises a JSON tags array into its ndjson record, so ["phish"] arrives
# as the string "['phish']" -- the expected key is computed here
# independently of the plugin, not scraped from it.
KEY_MAL=$(python3 -c "import hashlib;print(hashlib.sha256(b\"v1|tin|mallory|['phish']\").hexdigest())")
KEY_ALI=$(python3 -c "import hashlib;print(hashlib.sha256(b'v1|tin|alice|').hexdigest())")

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    make native >"$WORK/build.out" 2>"$WORK/build.err"
fi
if [ -x "$BIN" ]; then pass "native binary present"; else
    fail "native build failed"; sed 's/^/       /' "$WORK/build.err" | head -20
    printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0"
    exit 1
fi
MAKEM=$(cat Makefile)
check "Makefile has a musl target" 'musl:' "$MAKEM"
check "Makefile has an arm64 target" 'arm64:' "$MAKEM"
check "Makefile has a win64 target" 'win64:' "$MAKEM"
check "Makefile has a macos target" 'macos:' "$MAKEM"
check "Makefile has an asan target" 'asan:' "$MAKEM"
check "Makefile has a fortify target" 'fortify:' "$MAKEM"
check "Makefile vendors mbedTLS" 'vendor/mbedtls' "$MAKEM"
check "Makefile vendors yyjson" 'vendor/yyjson.c' "$MAKEM"
PJ=$(cat plugin.json)
json_ok "plugin.json is valid JSON" "$PJ" "d['slug']=='ntfy' and d['id']=='plugin_ntfy'"
check "plugin.json declares kind hybrid" '"kind": "hybrid"' "$PJ"
check "plugin.json declares the mcp face" '"mcp": true' "$PJ"
check "plugin.json declares the daemon face" '"daemon": true' "$PJ"
check "plugin.json says mock-verified" '"verified": "mock"' "$PJ"
check "plugin.json sets menus false" '"menus": false' "$PJ"
check "README documents --daemon" -- '--daemon' "$(cat README.md 2>/dev/null)"
check "README documents --mcp" 'ntfy_send' "$(cat README.md 2>/dev/null)"

# ---------------------------------------------------------------- mode 1: meta
section "mode 1 - discovery metadata"
M=$($BIN --meta)
if [ "$(printf '%s\n' "$M" | wc -l)" -eq 1 ]; then pass "--meta is one line"; else fail "--meta must be one line"; fi
json_ok "--meta prints valid JSON with the short label" "$M" "d['name']=='ntfy' and d['desc']=='Push channel'"
check "--meta kind hybrid" '"kind":"hybrid"' "$M"
check "--meta mcp true" '"mcp":true' "$M"
check "--meta daemon true" '"daemon":true' "$M"
check "--meta menus false (connector stays out of dropdowns)" '"menus":false' "$M"
check "--meta verified mock" '"verified":"mock"' "$M"
check "--meta advertises ntfy_send" 'ntfy_send' "$M"
M2=$(SX_PLUGIN_META=1 $BIN)
check "SX_PLUGIN_META=1 answers the same" '"name":"ntfy"' "$M2"
check_not "--meta needs no password" '401' "$(BOT_PASSWORD=letmein $BIN --meta)"

# ---------------------------------------------------------------- auth
section "mode 2 - node auth on every action"
PW=testpw
for a in status config pending approved info logs; do
    check "unauth $a is 401" 'Status: 401' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING="action=$a" $BIN | head -1)"
done
check "unauth save is 401" 'Status: 401' "$(printf '%s' '{}' | env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING='action=save' $BIN | head -1)"
check "unauth bare html is 401" 'Status: 401' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING="" $BIN | head -1)"
check "the 401 body names the error" '"error":"invalid node password"' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)"
check "the 401 says json" 'Content-Type: application/json' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)"
HA=$(env BOT_PASSWORD=$PW HTTP_X_BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)
check "header auth is accepted" '"ok":true' "$(body "$HA")"
BA=$(env BOT_PASSWORD=$PW HTTP_AUTHORIZATION="Bearer $PW" SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status' $BIN)
check "bearer auth is accepted" '"ok":true' "$(body "$BA")"
QA=$(env BOT_PASSWORD=$PW QUERY_STRING='action=status&pwd=testpw' SX_CONNECTORS_DIR=$CONN $BIN)
check "query pwd auth is accepted" '"ok":true' "$(body "$QA")"
check "a wrong pwd is still 401" 'Status: 401' "$(env BOT_PASSWORD=$PW SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status&pwd=nope' $BIN | head -1)"
check "--meta stays open with a password set" '"name":"ntfy"' "$(BOT_PASSWORD=$PW $BIN --meta)"

# ---------------------------------------------------------------- config
section "mode 3 - config save + validation"
R=$(post "action=save" '{"server_url":"http://127.0.0.1:'"$PORT"'"}')
json_ok "save stores server_url" "$R" "d['config']['server_url']=='http://127.0.0.1:$PORT'"
check "an incomplete config is not valid" '"valid":false' "$R"
R=$(post "action=save" '{"server_url":"javascript:alert(1)","topic":"t","target_session":"s"}')
check "a javascript: server_url is refused" '"validation":"url must start with http:// or https://"' "$R"
R=$(post "action=save" '{"server_url":"http://192.0.2.9/x","topic":"t","target_session":"s"}')
check "plain http to a non-loopback server is refused" 'plain http:// is refused' "$R"
R=$(post "action=save" '{"server_url":"https://ntfy.sh","topic":"bad topic!","target_session":"s"}')
check "a bad topic is refused" 'topic contains forbidden characters' "$R"
R=$(post "action=save" '{"server_url":"https://ntfy.sh","topic":"ok","target_session":"s","bot_api_url":"http://example.com"}')
check "a non-loopback plain-http bot_api_url is refused" 'bot_api_url must point at 127.0.0.1 or localhost' "$R"
R=$(post "action=save" '{"server_url":"https://ntfy.sh","topic":"ok","target_session":"s","bot_api_url":"https://127.0.0.1:8150"}')
check "an https bot_api_url is refused (loopback API is plain)" 'bot_api_url must be plain http' "$R"
R=$(post "action=save" "$CFG_OK")
json_ok "the good config saves" "$R" "d['ok'] and d['valid']"
check "publish_topic defaults when blank" '"publish_topic":"tout"' "$R"
C=$(api "action=config&format=json")
check_not "config never echoes bearer_token" '"bearer_token"' "$C"
check_not "config never echoes bot_password" '"bot_password"' "$C"
check_not "config never echoes allowed_pins" '"allowed_pins"' "$C"
post "action=save" '{"bearer_token":"sekret-token"}' >/dev/null
check "the bearer token is stored on disk" 'sekret-token' "$(cat "$CONN/plugin_ntfy/config.json")"
C=$(api "action=config&format=json")
check_not "but never returned by the API" 'sekret-token' "$C"
ST=$(api "action=status&format=json")
check "status reports has_bearer only" '"has_bearer":true' "$ST"
check_not "status never leaks the token" 'sekret-token' "$ST"
post "action=save" '{"bearer_token":"__clear__"}' >/dev/null
check "__clear__ wipes the token" '"has_bearer":false' "$(api 'action=status&format=json')"
ST=$(api "action=status&format=json")
json_ok "status shape" "$ST" "d['status']['running']==0 and 'inbound_count' in d['status'] and d['status']['configured']==True"
I=$(api "action=info&format=json")
json_ok "info reports the five-mode facts" "$I" "d['kind']=='hybrid' and d['mcp'] and d['daemon'] and not d['menus'] and d['verified']=='mock'"

# ---------------------------------------------------------------- mcp
section "mode 4 - MCP stdio server"
MOUT=$(printf '%s\n%s\n%s\n' \
  '{"jsonrpc":"2.0","id":1,"method":"initialize"}' \
  '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
  '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | $BIN --mcp)
INIT=$(printf '%s\n' "$MOUT" | head -1)
json_ok "initialize answers" "$INIT" "d['result']['serverInfo']['name']=='plugin_ntfy' and 'protocolVersion' in d['result']"
# Every frame the MCP server prints must be parseable JSON. This is not
# pedantry: scorpiox-connector-mcp's proc_request() treats an unparseable line
# as "noise on stdout", keeps reading, hits EOF and reports
# `tools/list failed for ntfy: no response` - a connector whose tools the
# agent can simply never see. A substring grep passes happily on a frame no
# parser will accept, so the tools/list frame is validated the way the router
# will actually consume it (the first cut of this handler emitted the result
# object without its closing brace and passed every grep).
MJSON=$(printf '%s\n' "$MOUT" | python3 -c '
import sys, json
lines = [l for l in sys.stdin.read().splitlines() if l.strip()]
assert lines, "no frames at all"
parsed = [json.loads(l) for l in lines]
tl = [p for p in parsed if "result" in p and "tools" in p["result"]]
assert tl, "no tools/list response among %d frames" % len(parsed)
tools = tl[0]["result"]["tools"]
assert tools, "tools/list returned an empty list"
assert any(t.get("name") == "ntfy_send" for t in tools), [t.get("name") for t in tools]
for t in tools:
    assert t.get("description"), "tool without a description"
    assert isinstance(t.get("inputSchema"), dict), "tool without an inputSchema"
    assert t["inputSchema"].get("type") == "object", t["inputSchema"].get("type")
    assert "message" in t["inputSchema"].get("properties", {}), "no message param"
    assert "message" in t["inputSchema"].get("required", []), "message not required"
print("ok")
' 2>&1)
[ "$MJSON" = "ok" ] && pass "every --mcp frame parses and the tool schema is complete" \
  || fail "every --mcp frame parses and the tool schema is complete" "$MJSON"
check "tools/list offers ntfy_send" 'ntfy_send' "$MOUT"
check "the tool schema has message" '"message"' "$MOUT"
check "the tool schema has priority" '"priority"' "$MOUT"
SOUT=$(echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"ntfy_send","arguments":{"message":"suite alert","title":"Suite","priority":4,"tags":"warning"}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp)
json_ok "tools/call publishes" "$SOUT" "d['result']['isError']==False"
wait_for 5 "the alert reached the (mock) ntfy server" mock_has '"message": "suite alert"'
wait_for 5 "with the requested priority" mock_has '"priority": 4'
SOUT2=$(echo '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"ntfy_send","arguments":{"message":"no priority given"}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp)
json_ok "priority defaults without an error" "$SOUT2" "d['result']['isError']==False"
SOUT3=$(echo '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"ntfy_send","arguments":{}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp)
check "a missing message is rejected, not a crash" 'requires a non-empty' "$SOUT3"
SOUT4=$(echo '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"nope","arguments":{}}}' | env SX_CONNECTORS_DIR=$CONN $BIN --mcp)
check "an unknown tool is rejected" 'unknown tool' "$SOUT4"
SCH=$($BIN --schema)
json_ok "--schema is the bare tool schema" "$SCH" "d['tools'][0]['name']=='ntfy_send' and 'inputSchema' in d['tools'][0]"

# ---------------------------------------------------------------- publish UI
section "mode 3 - test + send actions"
T=$(api "action=test&format=json")
json_ok "action=test publishes" "$T" "d['ok'] and str(d['published_id']).startswith('m')"
wait_for 5 "the test notification landed" mock_has 'plugin_ntfy test notification'
SN=$(post "action=send" '{"message":"from the suite","title":"Suite UI","tags":"robot","priority":2}')
json_ok "action=send publishes" "$SN" "d['ok'] and str(d['published_id']).startswith('m')"
wait_for 5 "the UI send landed" mock_has '"message": "from the suite"'
check "action=send without a message is refused" '"error"' "$(api 'action=send&message=&format=json')"
MB=$(body "$(printf '%s' '{badjson' | env SX_CONNECTORS_DIR=$CONN REQUEST_METHOD=POST CONTENT_LENGTH=8 QUERY_STRING='action=send&message=' $BIN 2>&1)")
check "a malformed body is handled, not a crash" '"error"' "$MB"

# ---------------------------------------------------------------- pairing
section "mode 5 - daemon bridge (default-deny, inbox, reply, no self-loop)"
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__reset" -d '{}' >/dev/null
post "action=save" "$CFG_OK" >/dev/null

env SX_CONNECTORS_DIR=$CONN $BIN --daemon > "$WORK/daemon.out" 2>&1 &
DAEMON_PID=$!
wait_for 8 "the daemon subscribed" grep -q "subscribed to" "$WORK/daemon.out"

# 1. unknown sender: held, challenged, never delivered
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
     -d '{"topic":"tin","message":"hey there bot","user":"mallory","tags":["phish"]}' >/dev/null
wait_for 8 "unapproved sender blocked" grep -q "blocked unapproved sender" "$WORK/daemon.out"
sleep 1
check_not "the unapproved message never reached /inbox" 'hey there bot' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)"
P=$(api "action=pending&format=json")
json_ok "the sender landed in the pairing queue" "$P" "any(p['sample']=='hey there bot' for p in d['pending'])"
check "the pending key is mallory's fingerprint" "$KEY_MAL" "$P"
wait_for 8 "a pairing challenge was published" mock_has 'PAIR '

# 2. approve -> bridge delivers to /inbox
A=$(api "action=approve&key=$KEY_MAL&format=json")
json_ok "approve accepts the 64-hex key" "$A" "d['ok'] and d['key']=='$KEY_MAL'"
check "the identity is now approved" "$KEY_MAL" "$(api 'action=approved&format=json')"
json_ok "approve removed it from pending" "$(api 'action=pending&format=json')" "not any(p['sample']=='hey there bot' for p in d['pending'])"
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
     -d '{"topic":"tin","message":"what is 2+2","user":"mallory","tags":["phish"]}' >/dev/null
wait_for 8 "the approved message reached /inbox" mock_inbox_has 'what is 2+2'
check "the inbox text names the sender + channel" 'mallory via ntfy' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)"

# 3. the assistant reply is published back exactly once, no self-echo loop
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__reply" -d '{"content":"2 plus 2 is 4"}' >/dev/null
wait_for 8 "the assistant reply was published back" mock_has '2 plus 2 is 4'
N1=$(mock_count)
sleep 3
N2=$(mock_count)
if [ "$N1" = "$N2" ] && [ -n "$N1" ]; then pass "the reply was NOT republished on later keepalives"; else
    fail "the reply got republished ($N1 -> $N2)"
fi
check "our publish carries the reply tag" '"robot"' "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)"
check "every publish carries our source id" 'scorpiox-bot-plugin-ntfy' "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)"
check "replies go to the publish topic" '"topic": "tout"' "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)"
check_not "the echoed own reply never became an inbox message" '2 plus 2 is 4' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)"

# 4. self-pairing with PAIR <code>
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
     -d '{"topic":"tin","message":"hi, pairing request","user":"alice"}' >/dev/null
wait_for 8 "alice was held" grep -q "blocked unapproved sender $KEY_ALI" "$WORK/daemon.out"
CODE=$(jget "$(cat "$CONN/plugin_ntfy/pending.json")" "[p['code'] for p in d if p['key']=='$KEY_ALI'][0]")
if [ ${#CODE} -eq 8 ]; then pass "the pairing code is 8 chars ($CODE)"; else fail "bad pairing code '$CODE'"; fi
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
     -d "{\"topic\":\"tin\",\"message\":\"PAIR $CODE\",\"user\":\"alice\"}" >/dev/null
wait_for 8 "the PAIR command self-paired alice" grep -q "paired via code" "$WORK/daemon.out"
check "alice is approved now" "$KEY_ALI" "$(api 'action=approved&format=json')"
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
     -d '{"topic":"tin","message":"alice speaks","user":"alice"}' >/dev/null
wait_for 8 "alice reaches /inbox now" mock_inbox_has 'alice speaks'
WRONGCODE='{"topic":"tin","message":"PAIR ZZZZZZZZ","user":"bob"}'
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" -d "$WRONGCODE" >/dev/null
sleep 1
check "a wrong pairing code is refused, not accepted" "wrong pairing code" "$(tail -60 "$WORK/daemon.out")"

# 5. deny + unapprove + key validation
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
     -d '{"topic":"tin","message":"spam","user":"bob","tags":["junk"]}' >/dev/null
wait_for 8 "bob was held" grep -q "blocked unapproved sender $(python3 -c "import hashlib;print(hashlib.sha256(b\"v1|tin|bob|['junk']\").hexdigest())")" "$WORK/daemon.out"
BOBKEY=$(python3 -c "import hashlib;print(hashlib.sha256(b\"v1|tin|bob|['junk']\").hexdigest())")
D=$(api "action=deny&key=$BOBKEY&format=json")
json_ok "deny removes the pending entry" "$D" "d['ok'] and d['key']=='$BOBKEY'"
check_not "bob is gone from pending" '"sample": "spam"' "$(api 'action=pending&format=json')"
U=$(api "action=unapprove&key=$KEY_ALI&format=json")
json_ok "unapprove works" "$U" "d['ok'] and d['key']=='$KEY_ALI'"
check_not "unapproved identity gone from approved list" "$KEY_ALI" "$(api 'action=approved&format=json')"
BAD=$(api "action=approve&key=deadbeef&format=json")
check "a malformed key is rejected" 'key must be the 64-hex identity' "$BAD"

# 6. counters
ST=$(api "action=status&format=json")
json_ok "status counted inbound" "$ST" "d['status']['inbound_count']>=2"
json_ok "status counted outbound" "$ST" "d['status']['outbound_count']>=1"
json_ok "status counted blocked" "$ST" "d['status']['blocked_count']>=2"
json_ok "status says the daemon is running" "$ST" "d['status']['running']==True and d['status']['connected']==True"

# 7. pidfile, duplicate refusal, stop
if [ -f "$CONN/plugin_ntfy/daemon.pid" ]; then pass "daemon wrote its pidfile"; else fail "no pidfile"; fi
DUP=$(env SX_CONNECTORS_DIR=$CONN $BIN --daemon 2>&1 || true)
check "a second daemon refuses to start" "another daemon is already running" "$DUP"
STOP=$(api "action=stop&format=json")
json_ok "action=stop stops the daemon" "$STOP" "d['ok'] and d['stopped']"
wait_for 8 "the daemon exited" sh -c "! kill -0 $DAEMON_PID 2>/dev/null"
DAEMON_PID=""
rm -f "$CONN/plugin_ntfy/daemon.pid"

# 8. supervised start through the API
GO=$(api "action=start&format=json")
json_ok "action=start launches the daemon" "$GO" "d['ok'] and d['started']"
wait_for 8 "the supervised daemon reports running" sh -c "SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status&format=json' $BIN | grep -q '\"running\":1'"
DUP2=$(api "action=start&format=json")
check "a supervised second start is refused with 409-shape" "already running" "$DUP2"
api "action=stop&format=json" >/dev/null
wait_for 8 "the supervised daemon exited" sh -c "! SX_CONNECTORS_DIR=$CONN QUERY_STRING='action=status&format=json' $BIN | grep -q '\"running\":1'"
rm -f "$CONN/plugin_ntfy/daemon.pid"

# 9. a wrong node password blocks the bridge
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__config" -d '{"password":"nodepw"}' >/dev/null
post "action=save" '{"bot_password":"wrongpw"}' >/dev/null
env SX_CONNECTORS_DIR=$CONN $BIN --daemon > "$WORK/daemon2.out" 2>&1 &
DAEMON_PID=$!
wait_for 8 "daemon #2 subscribed" grep -q "subscribed to" "$WORK/daemon2.out"
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__inject" \
     -d '{"topic":"tin","message":"secret leak check","user":"mallory","tags":["phish"]}' >/dev/null
wait_for 8 "the bridge logged an inbox failure" grep -q "inbox post failed" "$WORK/daemon2.out"
check "the failure names the 401" "401" "$(grep -m1 'inbox post failed' "$WORK/daemon2.out")"
sleep 1
check_not "nothing was delivered with a bad password" 'secret leak check' "$(curl -s -m3 http://127.0.0.1:$PORT/__inbox)"
api "action=stop&format=json" >/dev/null
wait_for 8 "daemon #2 exited" sh -c "! kill -0 $DAEMON_PID 2>/dev/null"
DAEMON_PID=""
rm -f "$CONN/plugin_ntfy/daemon.pid"
curl -s -m 3 -X POST "http://127.0.0.1:$PORT/__config" -d '{"password":""}' >/dev/null
post "action=save" '{"bot_password":"__clear__"}' >/dev/null

# ---------------------------------------------------------------- html ui
section "mode 2 - the generated page"
H=$(env SX_CONNECTORS_DIR=$CONN QUERY_STRING="" $BIN)
check "the page is html" 'Content-Type: text/html' "$H"
check_not "no <script src=" '<script src=' "$H"
check_not "no CDN references" 'cdnjs' "$H"
check_not "no jsdelivr" 'jsdelivr' "$H"
check_not "no unpkg" 'unpkg' "$H"
check "a CSP is emitted" 'Content-Security-Policy:' "$H"
check "X-Frame-Options SAMEORIGIN" 'X-Frame-Options: SAMEORIGIN' "$H"
check "nosniff" 'X-Content-Type-Options: nosniff' "$H"
check "the page has the setup form" 'f_server' "$H"
check "the page has the pairing tab" 'tabPair' "$H"
check "the page has the daemon log tab" 'tabLog' "$H"
check "the page has the test-send tab" 'tabSend' "$H"
check "the page respects the theme handoff" 'sx-theme' "$H"
HE=$(env SX_CONNECTORS_DIR=$CONN QUERY_STRING="embed=1&theme=light" $BIN)
check "embed=1 still renders" 'f_server' "$HE"
check "theme=light still renders" 'f_server' "$HE"
check_not "no emoji in the markup" '&#x1F' "$H"
if python3 -c "
import sys,re
s=open('src/ui.html',encoding='utf-8').read()
sys.exit(1 if re.search('[\U0001F000-\U0001FAFF\u2600-\u27BF]',s) else 0)"; then pass "no unicode emoji in ui.html"; else fail "unicode emoji in ui.html"; fi

# ---------------------------------------------------------------- transport security
section "transport security - HTTPS, the bundled root store, SPKI pinning"
# sx_http.c is the highest-stakes code in the binary: it is the only thing
# standing between somebody else's ntfy topic and this node's /inbox. The
# offline mock can speak TLS as well, with a leaf the bundled root store will
# NEVER trust -- so the only way HTTPS can succeed at all here is an explicit
# SPKI pin. That makes both halves of the promise testable with zero internet:
# "it fails closed" and "a private CA works when pinned".
TLSPORT=$((PORT + 1))
TLSPLAIN=$((PORT + 2))
TLSMMSMPORT=$((PORT + 3))
TLSPID=""
tls_cleanup() { if [ -n "$TLSPID" ] && kill -0 "$TLSPID" 2>/dev/null; then kill "$TLSPID" 2>/dev/null; wait "$TLSPID" 2>/dev/null; fi; return 0; }
trap 'tls_cleanup' EXIT
python3 tests/mockd.py --port "$TLSPLAIN" --tls-port "$TLSPORT" \
    --tls-mismatch-port "$TLSMMSMPORT" --root "$WORK/mocktls" \
    > "$WORK/mockd.tls.out" 2>&1 &
TLSPID=$!
i=0
while [ "$i" -lt 60 ]; do
    grep -q "tls-mismatch=127.0.0.2:$TLSMMSMPORT" "$WORK/mockd.tls.out" 2>/dev/null && break
    i=$((i + 1)); sleep 0.1
done
if grep -q "tls-mismatch=" "$WORK/mockd.tls.out" 2>/dev/null; then
    pass "mock ntfy also speaks TLS on 127.0.0.1:$TLSPORT (+ mismatch front :$TLSMMSMPORT)"
else
    fail "mock TLS front never came up"
    sed 's/^/       /' "$WORK/mockd.tls.out" | head -5
fi
# Read the TLS mock's own capture: a publish that silently fell back to plain
# http would land on $PORT instead, which is what the downgrade check sees.
tls_published_has() {
    curl -s -m 3 "http://127.0.0.1:$TLSPLAIN/__publishes" 2>/dev/null | grep -F -q -- "$1"
}
pin_of() {
    openssl x509 -in "$1" -pubkey -noout 2>/dev/null \
        | openssl pkey -pubin -outform der 2>/dev/null \
        | openssl dgst -sha256 -hex 2>/dev/null | awk '{print $NF}'
}
PIN_REAL=$(pin_of "$WORK/mocktls/tls/mock-cert.pem")
if [ -n "$PIN_REAL" ] && [ "${#PIN_REAL}" -eq 64 ]; then
    pass "computed the leaf SPKI pin with openssl"
else
    fail "could not compute the leaf SPKI pin"
    PIN_REAL="0000000000000000000000000000000000000000000000000000000000000000"
fi

HTTPS_URL="https://127.0.0.1:$TLSPORT"
post "action=save" "{\"server_url\":\"$HTTPS_URL\",\"topic\":\"stin\",\"publish_topic\":\"stout\",\"allowed_pins\":\"\"}" >/dev/null

# 1) An untrusted leaf and no pin must be REFUSED -- not accepted, and above
#    all not quietly retried over plain http.
R=$(post "action=send" '{"message":"should never publish unauthenticated"}')
json_ok "https to an untrusted certificate is refused" "$R" "d['ok']==False"
check "the refusal names the certificate" 'certificate' "$R"
check_not "it did not reach the TLS mock" 'should never publish unauthenticated' \
    "$(curl -s -m3 http://127.0.0.1:$TLSPLAIN/__publishes)"
check_not "and it did not downgrade to the plain mock" 'should never publish unauthenticated' \
    "$(curl -s -m3 http://127.0.0.1:$PORT/__publishes)"

# 2) A pin that does not match is still a refusal.
post "action=save" "{\"allowed_pins\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"}" >/dev/null
R=$(post "action=send" '{"message":"wrong pin"}')
json_ok "a non-matching pin is refused" "$R" "d['ok']==False"

# 3) The right pin is accepted -- the path a self-hosted relay on a private CA
#    takes, so it has to work, and the pin the plugin derives from its own
#    peer certificate has to agree with the one openssl derives.
post "action=save" "{\"allowed_pins\":\"$PIN_REAL\"}" >/dev/null
R=$(post "action=send" '{"message":"pinned publish ok","title":"PinTest"}')
json_ok "the correct SPKI pin is accepted" "$R" "d['ok']==True"
wait_for 5 "the pinned publish reached the TLS mock" tls_published_has 'pinned publish ok'

# 4) A pin never becomes a bypass for hostname checking. The same leaf,
#    reached on 127.0.0.2 (outside its only IP SAN), must be refused even with
#    its own correct pin. 127.0.0.2 rather than a hostname because this
#    container resolves nothing -- a name only exercises the resolver error.
post "action=save" "{\"server_url\":\"https://127.0.0.2:$TLSMMSMPORT\",\"allowed_pins\":\"$PIN_REAL\"}" >/dev/null
R=$(post "action=send" '{"message":"hostname mismatch"}')
json_ok "a pin cannot override a hostname mismatch" "$R" "d['ok']==False"
check "and says so" 'hostname' "$R"
post "action=save" "{\"server_url\":\"$HTTPS_URL\"}" >/dev/null

# 5) The only no-verify mode is the explicit, loud environment opt-in.
R=$(post "action=send" '{"message":"insecure mode opt-in"}' NTFY_TLS_INSECURE=1)
json_ok "NTFY_TLS_INSECURE=1 is the documented explicit opt-in" "$R" "d['ok']==True"

# 6) Plain http to a non-loopback server is refused: a bearer token would ride
#    in the clear. save reports ok (forms fill in stages) plus the verdict --
#    the verdict is the refusal.
R=$(post "action=save" '{"server_url":"http://ntfy.example.invalid","topic":"tin"}')
json_ok "plain http to a non-loopback server is refused" "$R" \
    "d['valid']==False and 'plain http' in d.get('validation','')"

# put the transport back to the offline plain mock for anything that follows
post "action=save" "{\"server_url\":\"http://127.0.0.1:$PORT\",\"topic\":\"tin\",\"publish_topic\":\"tout\",\"allowed_pins\":\"\"}" >/dev/null
tls_cleanup; TLSPID=""

# ---------------------------------------------------------------- hardening
section "builds - ASan + fortify + PE header"
if [ ! -x tests/asan/plugin_ntfy_asan ]; then make asan >"$WORK/asan.build" 2>&1 || true; fi
if [ -x tests/asan/plugin_ntfy_asan ]; then
    AOUT=$(env SX_CONNECTORS_DIR=$WORK/asan-conn QUERY_STRING='action=status&format=json' tests/asan/plugin_ntfy_asan 2>&1)
    check "ASan build answers a CGI request clean" '"ok":true' "$AOUT"
    check_not "ASan saw no error" 'ERROR: AddressSanitizer' "$AOUT"
    MOUTA=$(printf '%s\n%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize"}' '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | env SX_CONNECTORS_DIR=$WORK/asan-conn ASAN_OPTIONS=detect_leaks=0 tests/asan/plugin_ntfy_asan --mcp 2>&1)
    check_not "ASan clean over the MCP round trip" 'runtime error' "$MOUTA"
    check "the MCP round trip answered under ASan" 'ntfy_send' "$MOUTA"
else
    fail "asan build missing"
fi
if [ ! -x tests/fortify/plugin_ntfy_fortify ]; then make fortify >"$WORK/fort.build" 2>&1 || true; fi
if [ -x tests/fortify/plugin_ntfy_fortify ]; then
    FOUT=$(env SX_CONNECTORS_DIR=$WORK/fort-conn QUERY_STRING='action=status&format=json' tests/fortify/plugin_ntfy_fortify 2>&1)
    check "_FORTIFY build answers a CGI request" '"ok":true' "$FOUT"
else
    fail "fortify build missing"
fi
if [ -f plugin_ntfy.exe ]; then
    MAGIC=$(head -c 2 plugin_ntfy.exe)
    if [ "$MAGIC" = "MZ" ]; then pass "the windows artifact has a PE header"; else fail "plugin_ntfy.exe is not a PE"; fi
fi

# ---------------------------------------------------------------- win32 guards
section "windows guards (static)"
# Neither of these can be RUN offline, and both have already shipped broken
# once, so the source itself carries the assertion.
SRC=$(cat src/plugin_ntfy.c)
# WSAStartup must sit in main(), before the mode dispatch -- not inside the
# CGI branch. It used to live only there, so plugin_ntfy.exe --mcp ran with a
# cold winsock and every ntfy_send died at "cannot resolve ntfy.sh:443" on a
# real Windows box while --meta looked fine.
WSA_MAIN=$(awk '/^int main\(/{f=1} f && /WSAStartup/{print NR; exit}' src/plugin_ntfy.c)
DISPATCH=$(awk '/^int main\(/{f=1} f && /mode_mcp\(\)/{print NR; exit}' src/plugin_ntfy.c)
if [ -n "$WSA_MAIN" ] && [ -n "$DISPATCH" ] && [ "$WSA_MAIN" -lt "$DISPATCH" ]; then
    pass "winsock starts in main() before any mode dispatch"
else
    fail "winsock must be started in main() before the mode dispatch"
fi
check "the --mcp face is dispatched from main, not only the env" 'if (!strcmp(argv[i], "--mcp"))' "$SRC"
# stdout must be binary on Windows: text mode turns our \n into \r\n and
# double-terminates the CGI headers.
check "_setmode(_fileno(stdout), _O_BINARY) on the windows path" '_O_BINARY' "$SRC"

# ---------------------------------------------------------------- secrets
section "git history secret audit"
if git rev-parse --git-dir >/dev/null 2>&1; then
    ALL="$WORK/history.txt"
    # --pretty= drops the commit-message bodies from the patch stream. The
    # messages of this very suite describe the detectors in prose and quote the
    # mbedTLS citations they exclude, so reading them back would make the audit
    # fail on its own documentation. Messages are still checked - by the secret
    # detectors, which are the ones a commit message can actually leak.
    git log -p --all --pretty=format:commit_%%H 2>/dev/null \
      | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|scan "|probe_cite|DOTS' \
      > "$ALL" || : > "$ALL"
    MSGS="$WORK/messages.txt"
    git log --all --pretty=format:%%B 2>/dev/null \
      | grep -vE 'scan_hist|audit "' > "$MSGS" || : > "$MSGS"

    # The vendored mbedTLS tree cites NIST SP 800-90A section numbers in
    # comments (the HMAC_DRBG reseeding note is one). DOTS below is the
    # four-part dotted form, built from fragments so this file never carries
    # an IP-shaped literal: those citations are indistinguishable from a
    # private IPv4 to a regex. The IP detectors therefore run against
    # $ALL_CODE (comment lines removed); every other detector still reads the
    # whole history, so a secret hidden in a comment is still caught. The two
    # self-tests below prove the IP detector still fires on a real address.
    ALL_CODE="$WORK/history-code.txt"
    grep -vE '^(\+|-)?[[:space:]]*(\*|//|/\*|#)' "$ALL" > "$ALL_CODE" 2>/dev/null \
      || : > "$ALL_CODE"

    audit() { # audit <label> <regex> [file]
        SRC="${3:-$ALL}"
        H=$(grep -Eo "$2" "$SRC" 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"        '(^|[^0-9.])192\.168\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$ALL_CODE"
    audit "private 10.x"         '(^|[^0-9.])10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$ALL_CODE"
    audit "private 172.16-31.x"  '(^|[^0-9.])172\.(1[6-9]|2[0-9]|3[01])\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$ALL_CODE"
    # A commit message is where a secret actually gets pasted, so these run
    # against the code history AND the message bodies.
    audit "GitHub PAT"            'ghp_[A-Za-z0-9]{36}'
    audit "GitHub PAT in messages" 'ghp_[A-Za-z0-9]{36}' "$MSGS"
    audit "HuggingFace token"     'hf_[A-Za-z0-9]{30,}'
    audit "HuggingFace token in messages" 'hf_[A-Za-z0-9]{30,}' "$MSGS"
    audit "embedded git creds"    'scorpioxinc:[A-Za-z0-9]{20,}'
    audit "embedded git creds in messages" 'scorpioxinc:[A-Za-z0-9]{20,}' "$MSGS"
    # the token is split so this public repo never contains the string it hunts
    audit "plugingit write token" '3ef2c00c''b68eb9a0f42610d17026839094642006'
    audit "plugingit token in messages" '3ef2c00c''b68eb9a0f42610d17026839094642006' "$MSGS"
    PK="pico""bot"; WT=".work""trees"
    audit "internal fleet path"   "/codebases/${PK}|${WT}"
    audit "internal fleet path in messages" "/codebases/${PK}|${WT}" "$MSGS"
    audit "fleet default pass"    'xbo''xone'
    audit "fleet default pass in messages" 'xbo''xone' "$MSGS"
    audit "nas password"          'Xbo''xone0909'
    audit "internal hostname"     'intel-ultra''2|mac''mini|laza''rus'
    audit "azure devops PAT"      'CAsH4l2cGeOmcxbnVaAqggJYibBCFREpGBcERAhkBEM4'

    # self-tests for the two exclusions above: an IP detector that has been
    # narrowed until it never fires is worse than no detector at all. The
    # probe address is assembled from fragments so this file carries no
    # complete LAN-IP literal of its own (the tree scan below reads raw text).
    O1="192"".""168"; O2="10"".""20"
    printf 'x = "%s.9.9"; y = %s.30.40;\n' "$O1" "$O2" > "$WORK/probe_hit"
    if grep -qEo '(^|[^0-9.])192\.168\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$WORK/probe_hit" \
       && grep -qEo '(^|[^0-9.])10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)' "$WORK/probe_hit"; then
        pass "history audit self-test: a real private IPv4 still fires"
    else
        fail "history audit self-test: the IP detector has been narrowed into silence"
    fi
    DOTS="1""0"".""1"".""2"".""4"
    printf ' * DRBG reseeding: %s + 9.2 (NIST section citation)\n' "$DOTS" > "$WORK/probe_cite"
    if grep -vE '^(\+|-)?[[:space:]]*(\*|//|/\*|#)' "$WORK/probe_cite" \
         | grep -qEo '(^|[^0-9.])10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}([^0-9.]|$)'; then
        fail "history audit self-test: a NIST section citation still reads as an IP"
    else
        pass "history audit self-test: a comment-only section citation is not a finding"
    fi

    if grep -rqE '192\.168\.[0-9]+\.[0-9]+' src tests tools README.md plugin.json Makefile --exclude-dir=asan --exclude-dir=fortify 2>/dev/null; then
        fail "tree: a LAN ip literal survived"; else pass "tree clean: LAN ips"; fi
else
    echo "  skip history audit (not a git checkout)"
fi

# ---------------------------------------------------------------- summary
printf '\n%s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0"
[ "$FAIL" -eq 0 ] || exit 1
exit 0
