#!/bin/sh
# tests/run.sh - offline checks for plugin_codex_login across all 3 modes.
#
# Every check runs against ./plugin_codex_login with the credential paths and
# both CLIs redirected at throwaway fixtures, so the suite proves the public
# contract without touching a real Codex session and without a network.
#
# What it proves:
#   - --meta is exactly {"name":"codex","desc":"Codex login"} and is reachable
#     with no password (discovery must never be gated)
#   - every action 401s without the node password, and 401 is a real CGI Status
#   - status reads the tokens block, decodes the JWT exp claim for the expiry
#     (auth.json has no expiry field of its own), reads last_refresh, lists the
#     named account directory, and NEVER emits a token
#   - start returns the CLI's verify_url and user_code, reports "already logged
#     in" when the CLI says exists, and survives a CLI answer with no user code
#   - poll reports pending, reports done after the CLI writes the file, and
#     turns a denied device code into a terminal failed state
#   - refresh performs the grant, drops the CLI's payload, and surfaces failure
#   - the HTML page carries the bot theme handoff, no CDN and no <script src=>
#   - the source has no hard-coded secret, no internal address and no emoji
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_codex_login
ID=plugin_codex_login
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
}

found() { # found <desc> <needle> <file...> - the needle must appear somewhere
    _d=$1; _n=$2; shift 2
    if grep -F -q -- "$_n" "$@" 2>/dev/null; then pass "$_d"; else
        fail "$_d (missing: $_n)"
    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 = 1 }
        inhdr && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/ || $0 == "") { next }
        { inhdr = 0; 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() { body "$(QUERY_STRING="$1" $BIN)"; }
apiraw() { QUERY_STRING="$1" $BIN; }

# Build a JWT whose payload carries exp=<seconds>. The real access tokens are
# RS256 JWTs of the same shape, so the fixture is faithful in the only field the
# plugin reads.
mkjwt() { # mkjwt <exp-seconds>
    python3 - "$1" << 'PYEOF'
import base64, json, sys
exp = int(sys.argv[1])
payload = {"exp": exp, "chatgpt_account_id": "acct-fixture", "sub": "user-fixture"}
b = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
print("eyJhbGciOiJIUzI1NiJ9." + b + ".SIGNATUREPART")
PYEOF
}

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src \
       -o "$BIN" src/plugin_codex_login.c || { fail "native build"; exit 1; }
fi
pass "native binary present"

if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
    pass "src/ui_html.h is in sync with src/ui.html"
else
    fail "src/ui_html.h is stale - run tools/gen_ui.py"
fi

check "ui header is marked generated" \
      "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"

# ---------------------------------------------------------------- --meta
section "discovery metadata"
META=$(BOT_PASSWORD=testpw $BIN --meta)
[ "$META" = '{"name":"codex","desc":"Codex login"}' ] && pass "--meta is exactly the contract string" \
    || fail "--meta mismatch: $META"
META2=$(SX_PLUGIN_META=1 BOT_PASSWORD=testpw $BIN)
check "SX_PLUGIN_META=1 emits the same metadata" '"desc":"Codex login"' "$META2"
check "--meta works with an empty env" '"name":"codex"' "$(env -u BOT_PASSWORD $BIN --meta)"
json_ok "--meta is valid JSON" "$(env -u BOT_PASSWORD $BIN --meta)" \
        'd["name"]=="codex" and len(d["desc"])<=15'
json_ok "--meta title is one word" "$(env -u BOT_PASSWORD $BIN --meta)" \
        'len(d["name"].split())==1'
V=$($BIN --version)
check "--version names the binary" "$ID" "$V"

# ---------------------------------------------------------------- fixtures
FIX=$(mktemp -d 2>/dev/null || mktemp -d -t cxfix)
trap 'rm -rf "$FIX"' EXIT

mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/deep/nested"
export CODEX_LOGIN_BIN="$ROOT/tests/mock_login.sh"
export CODEX_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
export CODEX_PENDING_DIR="$FIX/pend"
export CODEX_ENV_DIR="$FIX/env"
export CODEX_ACCOUNTS_DIR="$FIX/acc"
export CODEX_CREDS_PATH="$FIX/auth.json"
export BOT_PASSWORD=testpw
PWDQ='pwd=testpw'

NOW=$(date +%s)
FUTURE=$((NOW + 7200))
PAST=$((NOW - 3600))
TOK_FUTURE=$(mkjwt "$FUTURE")
TOK_PAST=$(mkjwt "$PAST")

mkcreds() { # mkcreds <path> <access-token> <refresh-or-empty> <last_refresh>
    {
    printf '{\n  "OPENAI_API_KEY": null,\n  "tokens": {\n'
    printf '    "id_token": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmaXh0dXJlIn0.IDSIG",\n'
    printf '    "access_token": "%s",\n' "$2"
    if [ -n "$3" ]; then
        printf '    "refresh_token": "%s",\n' "$3"
    else
        printf '    "refresh_token": "",\n'
    fi
    printf '    "account_id": "acct-fixture"\n  },\n'
    printf '  "last_refresh": "%s"\n}\n' "$4"
    } > "$1"
}

# ---------------------------------------------------------------- auth gate
section "node auth gate"
RAW=$(apiraw "action=status")
check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW"
check "401 body is JSON" '"error":"invalid node password"' "$RAW"
check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")"
check "X-Bot-Password header auth works" '"ok":true' \
      "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")"
check "Bearer auth works" '"ok":true' \
      "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")"
check "wrong password still 401s" "Status: 401 Unauthorized" \
      "$(QUERY_STRING="action=status&pwd=nope" $BIN)"
UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN)
check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")"
check "discovery is never gated" '"name":"codex"' "$(env -u BOT_PASSWORD $BIN --meta)"

# ---------------------------------------------------------------- status: empty
section "status with no credentials"
rm -f "$FIX/auth.json" "$FIX/acc"/*.json "$FIX/pend"/*.json "$FIX/env"/*.txt
OUT=$(api "action=status&$PWDQ")
json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True'
json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False'
json_ok "empty node is not expired" "$OUT" 'd["expired"] is False'
json_ok "empty node has no expiry" "$OUT" 'd["expires_at"]==0 and d["expires_in_sec"]==0'
json_ok "empty node has no refresh token" "$OUT" 'd["has_refresh"] is False'
json_ok "empty node has no pending flow" "$OUT" 'd["pending"] is False'
json_ok "empty node reports the credentials path" "$OUT" 'd["credentials_path"].endswith("auth.json")'
json_ok "empty node has no named accounts" "$OUT" 'd["accounts"]==[]'
json_ok "empty node says the CLI is present (mock)" "$OUT" 'd["cli_present"] is True'

# ---------------------------------------------------------------- status: live
section "status with a live session"
mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-secret-refresh-must-not-leak" "2026-11-12T12:00:00.000000Z"
printf 'PROVIDER=codex\nCODEX_TOKEN_SOURCE=local\nMODEL=gpt-5.5\n' > "$FIX/env/codex.txt"
OUT=$(api "action=status&$PWDQ")
json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True'
json_ok "live session is not expired" "$OUT" 'd["expired"] is False'
json_ok "live session has a refresh token" "$OUT" 'd["has_refresh"] is True'
json_ok "live session countdown is positive and near 2h" "$OUT" \
        '7100 < d["expires_in_sec"] <= 7200'
json_ok "expiry is unix seconds, not milliseconds" "$OUT" \
        '1000000000 < d["expires_at"] < 3000000000'
json_ok "last_refresh is parsed to unix seconds" "$OUT" 'd["last_refresh"] > 1000000000'
json_ok "account id is read from the file" "$OUT" 'd["account_id"]=="acct-fixture"'
json_ok "profile file is detected" "$OUT" 'd["profile"]=="codex" and d["profile_exists"] is True'
json_ok "default account is named default" "$OUT" 'd["account"]=="default"'
check_not "status never returns an access token" 'SIGNATUREPART' "$OUT"
check_not "status never returns a refresh token" 'rt-secret-refresh' "$OUT"
check_not "status never returns the id token" 'eyJhbGciOiJIUzI1NiJ9' "$OUT"
check_not "status never returns the key name access_token" 'access_token' "$OUT"
check_not "status never leaks the fixture secret word" 'MUST-NOT-LEAK' "$OUT"

# ---------------------------------------------------------------- status: expired
section "status with an expired session"
mkcreds "$FIX/auth.json" "$TOK_PAST" "rt-secret-refresh-must-not-leak" "2026-11-10T09:00:00.000000Z"
OUT=$(api "action=status&$PWDQ")
json_ok "expired session is still logged in" "$OUT" 'd["logged_in"] is True'
json_ok "expired session is flagged expired" "$OUT" 'd["expired"] is True'
json_ok "expired session has a negative countdown" "$OUT" 'd["expires_in_sec"] < 0'

# ---------------------------------------------------------------- odd fixtures
section "malformed and unusual fixtures"
printf '{"OPENAI_API_KEY":"legacy-key-value","tokens":{"access_token":"a"}}\n' > "$FIX/auth.json"
OUT=$(api "action=status&$PWDQ")
json_ok "a token with no exp claim is logged in with unknown expiry" "$OUT" \
        'd["logged_in"] is True and d["expires_at"]==0 and d["expired"] is False'
json_ok "a legacy OPENAI_API_KEY is reported as present, not as a token" "$OUT" \
        'd["api_key_present"] is True'
check_not "the legacy key value is never echoed" 'legacy-key-value' "$OUT"

printf 'not json at all\n' > "$FIX/auth.json"
OUT=$(api "action=status&$PWDQ")
json_ok "a non-JSON credentials file is handled, not crashed" "$OUT" \
        'd["ok"] is True and d["logged_in"] is False'

printf '{"somethingElse":true}\n' > "$FIX/auth.json"
OUT=$(api "action=status&$PWDQ")
json_ok "a file with no tokens block is not logged in" "$OUT" 'd["logged_in"] is False'

printf '{"OPENAI_API_KEY":null,"tokens":{"access_token":"","refresh_token":""}}\n' > "$FIX/auth.json"
OUT=$(api "action=status&$PWDQ")
json_ok "an empty access token is not a session" "$OUT" 'd["logged_in"] is False'
json_ok "an empty refresh token is not a refresh token" "$OUT" 'd["has_refresh"] is False'

# a flat file (no tokens wrapper) still counts as a session
printf '{"access_token":"%s","refresh_token":"rt-flat"}\n' "$TOK_FUTURE" > "$FIX/auth.json"
OUT=$(api "action=status&$PWDQ")
json_ok "a flat token file is read as a session" "$OUT" \
        'd["logged_in"] is True and 7100 < d["expires_in_sec"] <= 7200'

# a token whose payload is not base64 at all
printf '{"tokens":{"access_token":"!!!not-a-jwt!!!"}}\n' > "$FIX/auth.json"
OUT=$(api "action=status&$PWDQ")
json_ok "a non-JWT access token is a session with unknown expiry" "$OUT" \
        'd["logged_in"] is True and d["expires_at"]==0'

# ---------------------------------------------------------------- named accounts
section "named accounts"
mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-default" "2026-11-12T12:00:00.000000Z"
mkcreds "$FIX/acc/work.json" "$TOK_FUTURE" "rt-work" "2026-11-12T10:00:00.000000Z"
mkcreds "$FIX/acc/old.json" "$TOK_PAST" "rt-old" "2026-11-01T10:00:00.000000Z"
printf '{"OPENAI_API_KEY":null,"tokens":{"access_token":"","refresh_token":""}}\n' > "$FIX/acc/notoken.json"
OUT=$(api "action=status&$PWDQ")
json_ok "named accounts are listed" "$OUT" 'len(d["accounts"])==3'
json_ok "a valid account is reported valid" "$OUT" \
        '[a for a in d["accounts"] if a["name"]=="work"][0]["expired"] is False'
json_ok "a stale account is reported expired" "$OUT" \
        '[a for a in d["accounts"] if a["name"]=="old"][0]["expired"] is True'
json_ok "an account with no token is reported logged out" "$OUT" \
        '[a for a in d["accounts"] if a["name"]=="notoken"][0]["logged_in"] is False'
json_ok "named accounts are flagged" "$OUT" 'd["named_accounts"] is True'
json_ok "account entries carry their own countdown" "$OUT" \
        '[a for a in d["accounts"] if a["name"]=="work"][0]["expires_in_sec"] > 7000'
check_not "account entries never carry a token" 'SIGNATUREPART' "$OUT"
OUT=$(api "action=accounts&$PWDQ")
json_ok "action=accounts answers the same shape" "$OUT" 'd["ok"] is True and len(d["accounts"])==3'
OUT=$(api "action=status&account=work&$PWDQ")
json_ok "status for a named account reads that file" "$OUT" \
        'd["account"]=="work" and d["logged_in"] is True'
check "named account path is reported" "work.json" "$OUT"
BADNAME=$(api "action=status&account=../etc/passwd&$PWDQ")
json_ok "a path-traversal account name is ignored, not followed" "$BADNAME" \
        'd["ok"] is True and d["account"]=="default" and "/etc" not in d["credentials_path"]'
BADSTART=$(api "action=start&account=..%2Fetc&$PWDQ")
check_not "a traversal name never reaches a path in start" '/etc' "$BADSTART"

# ---------------------------------------------------------------- pending marker
section "pending device flow marker"
rm -f "$FIX/pend"/*.json
OUT=$(api "action=status&$PWDQ")
json_ok "no marker means not pending" "$OUT" 'd["pending"] is False'
printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","interval":5,"created":%s}\n' "$NOW" \
    > "$FIX/pend/codex-default.json"
OUT=$(api "action=status&$PWDQ")
json_ok "a fresh marker means pending" "$OUT" 'd["pending"] is True'
json_ok "the marker age is reported" "$OUT" '0 <= d["pending_age_sec"] < 120'
printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$((NOW - 99999))" \
    > "$FIX/pend/codex-default.json"
OUT=$(api "action=status&$PWDQ")
json_ok "a stale marker is not pending" "$OUT" 'd["pending"] is False'
rm -f "$FIX/pend"/*.json

# ---------------------------------------------------------------- start
section "action=start"
rm -f "$FIX/pend"/*.json
rm -f "$FIX/auth.json"
OUT=$(api "action=start&$PWDQ")
json_ok "start returns ok" "$OUT" 'd["ok"] is True'
json_ok "start returns the device_code flow" "$OUT" 'd["flow"]=="device_code"'
json_ok "start returns the CLI verify_url" "$OUT" 'd["verify_url"].startswith("https://auth.openai.com/")'
json_ok "start returns a user code" "$OUT" 'd["user_code"]=="ABCD-1234"'
json_ok "start returns expires_in" "$OUT" 'd["expires_in"] > 0'
json_ok "start returns a poll interval" "$OUT" 'd["interval"] >= 1'
json_ok "start marks the flow pending" "$OUT" 'd["pending"] is True'
check "start writes the pending marker" "codex-default.json" "$FIX/pend"/*.json 2>/dev/null || \
    pass "start leaves a marker for poll to find"
check_not "start never echoes a token" 'SIGNATUREPART' "$OUT"

# already-logged-in path: the CLI refuses --start when credentials exist.
mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-exists" "2026-11-12T12:00:00.000000Z"
OUT=$(body "$(MOCK_EXISTS=1 QUERY_STRING="action=start&$PWDQ" $BIN)")
json_ok "start on existing creds reports already_logged_in" "$OUT" \
        'd["ok"] is True and d["already_logged_in"] is True'
json_ok "the already-logged-in answer keeps logged_in true" "$OUT" 'd["logged_in"] is True'
json_ok "the already-logged-in answer tells the user how to replace" "$OUT" \
        '"force=1" in d["hint"]'
OUT=$(body "$(MOCK_EXISTS=1 QUERY_STRING="action=start&force=1&$PWDQ" $BIN)")
json_ok "force=1 reaches the CLI as --force" "$OUT" 'd["ok"] is True and d["flow"]=="device_code"' 

# a CLI answer with no user code
OUT=$(body "$(MOCK_NOUSER=1 QUERY_STRING="action=start&$PWDQ" $BIN)")
json_ok "a start with no user code is start_incomplete" "$OUT" 'd["ok"] is False and d["error"]=="start_incomplete"'

# no CLI on the node
OUT=$(body "$(CODEX_LOGIN_BIN=sx-absent-cli-for-tests QUERY_STRING="action=start&$PWDQ" $BIN)")
json_ok "a missing login CLI is cli_unavailable, not a crash" "$OUT" \
        'd["ok"] is False and d["error"]=="cli_unavailable"'

# ---------------------------------------------------------------- poll
section "action=poll"
rm -f "$FIX/pend"/*.json "$FIX/auth.json"
printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","interval":5,"created":%s}\n' "$NOW" \
    > "$FIX/pend/codex-default.json"
OUT=$(api "action=poll&$PWDQ")
json_ok "poll while waiting is ok" "$OUT" 'd["ok"] is True'
json_ok "poll while waiting reports pending" "$OUT" 'd["state"]=="pending"'
json_ok "poll while waiting is not done" "$OUT" 'd.get("logged_in") is not True'
json_ok "poll passes the interval through" "$OUT" 'd["interval"] >= 1'

OUT=$(body "$(MOCK_DONE=1 MOCK_ACCESS_TOKEN="$TOK_FUTURE" QUERY_STRING="action=poll&$PWDQ" $BIN)")
json_ok "poll after approval reports done" "$OUT" 'd["ok"] is True and d["state"]=="done"'
json_ok "poll after approval is logged in" "$OUT" 'd["logged_in"] is True'
json_ok "poll after approval proves the countdown from the file" "$OUT" \
        '7100 < d["expires_in_sec"] <= 7200'
json_ok "poll after approval clears pending" "$OUT" 'd["pending"] is False'
check_not "the done answer never echoes a token" 'SIGNATUREPART' "$OUT"

OUT=$(body "$(MOCK_FAIL=1 QUERY_STRING="action=poll&$PWDQ" $BIN)")
json_ok "a denied device code is a terminal failed state" "$OUT" \
        'd["ok"] is True and d["state"]=="failed"'
json_ok "the failed state carries the CLI error" "$OUT" 'd["error"]=="denied"'
json_ok "the failed state clears pending" "$OUT" 'd["pending"] is False'

OUT=$(body "$(CODEX_LOGIN_BIN=sx-absent-cli-for-tests QUERY_STRING="action=poll&$PWDQ" $BIN)")
json_ok "poll with no CLI is cli_unavailable" "$OUT" 'd["error"]=="cli_unavailable"'

# ---------------------------------------------------------------- cancel
section "action=cancel"
printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$NOW" \
    > "$FIX/pend/codex-default.json"
OUT=$(api "action=cancel&$PWDQ")
json_ok "cancel is ok" "$OUT" 'd["ok"] is True and d["state"]=="cancelled"'
json_ok "cancel clears pending" "$OUT" 'd["pending"] is False'
if [ -f "$FIX/pend/codex-default.json" ]; then fail "cancel removed the marker"; else pass "cancel removed the marker"; fi

printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$NOW" \
    > "$FIX/pend/codex-default.json"
OUT=$(body "$(CODEX_LOGIN_BIN=sx-absent-cli-for-tests QUERY_STRING="action=cancel&$PWDQ" $BIN)")
json_ok "cancel with no CLI still clears the marker" "$OUT" \
        'd["ok"] is True and d["pending"] is False and d["cli_present"] is False'
if [ -f "$FIX/pend/codex-default.json" ]; then fail "cancel without CLI removed the marker"; else pass "cancel without CLI removed the marker"; fi

# ---------------------------------------------------------------- refresh
section "action=refresh"
rm -f "$FIX/auth.json"
OUT=$(api "action=refresh&$PWDQ")
json_ok "refresh with no credentials is no_credentials" "$OUT" \
        'd["ok"] is False and d["error"]=="no_credentials"'

mkcreds "$FIX/auth.json" "$TOK_PAST" "rt-secret-refresh-must-not-leak" "2026-11-10T09:00:00.000000Z"
OUT=$(api "action=refresh&$PWDQ")
json_ok "refresh on an expired token succeeds" "$OUT" 'd["ok"] is True and d["refreshed"] is True'
json_ok "refresh extends the countdown" "$OUT" 'd["expires_in_sec"] > 3600'
json_ok "refresh re-reports logged in" "$OUT" 'd["logged_in"] is True and d["expired"] is False'
check_not "refresh never echoes the CLI's rotated token" 'super-secret-rotated-token-value' "$OUT"
check_not "refresh never echoes the old secret" 'rt-secret-refresh' "$OUT"

OUT=$(body "$(MOCK_FAIL=1 QUERY_STRING="action=refresh&$PWDQ" $BIN)")
json_ok "a failing refresh CLI is reported as failure" "$OUT" \
        'd["ok"] is False and d["error"]=="refresh_failed"'

OUT=$(body "$(CODEX_REFRESH_BIN=sx-absent-cli-for-tests QUERY_STRING="action=refresh&$PWDQ" $BIN)")
json_ok "a missing refresh CLI is cli_unavailable" "$OUT" 'd["error"]=="cli_unavailable"'

# ---------------------------------------------------------------- unknown action
section "unknown action"
RAW=$(apiraw "action=bogus&$PWDQ")
check "unknown action 400s" "Status: 400 Bad Request" "$RAW"
OUT=$(body "$RAW")
json_ok "unknown action names the problem" "$OUT" 'd["ok"] is False and d["error"]=="unknown_action"'

# ---------------------------------------------------------------- format=json
section "format=json"
OUT=$(api "format=json&$PWDQ")
json_ok "format=json alone means status" "$OUT" 'd["ok"] is True and "logged_in" in d'

# ---------------------------------------------------------------- HTML page
section "HTML page"
PAGE=$(body "$(apiraw "$PWDQ")")
check "page is served as HTML" "<!DOCTYPE html>" "$PAGE"
check "page declares the plugin id in the footer" "plugin_codex_login" "$PAGE"
check "page carries the bot theme tokens" "color-scheme:dark" "$PAGE"
check "page carries the theme handoff listener" "sx-theme-request" "$PAGE"
check "page carries the theme prepaint" "data-theme" "$PAGE"
check "page has the status pill" 'id="pill"' "$PAGE"
check "page has the countdown" 'id="count"' "$PAGE"
check "page has the user code display" 'id="userCode"' "$PAGE"
check "page has the copy-and-open button" "Copy Code &amp; Open OpenAI" "$PAGE"
check "page has the polling label" "Waiting for authorization in browser" "$PAGE"
check "page has the cancel button" 'id="btnCancel"' "$PAGE"
check "page has the refresh button" "Refresh Token Now" "$PAGE"
check "page has the start button" "Start Codex Login" "$PAGE"
check "page is fluid down to a phone" "max-width:520px" "$PAGE"
check_not "page loads no external script" '<script src=' "$PAGE"
check_not "page references a CDN" 'cdnjs' "$PAGE"
check_not "page references googleapis" 'googleapis' "$PAGE"
nonascii() { # nonascii <file> - fails when any byte is outside printable ASCII
    if LC_ALL=C grep -qP '[^\x09\x0a\x20-\x7e]' "$1" 2>/dev/null; then
        fail "$2 (non-ASCII bytes present)"; LC_ALL=C grep -oP '[^\x09\x0a\x20-\x7e]' "$1" | head -3 | sed 's/^/       /'
    else pass "$2"
    fi
}
nonascii src/ui.html "the page is pure ASCII"
check "page fetches through the hub-aware router" "'/plugins?plugin='" "$PAGE"
check "page keeps the node password out of the URL path" "X-Bot-Password" "$PAGE"
check "page links to the public source mirror" "plugingit.scorpiox.net" "$PAGE"

# ---------------------------------------------------------------- secret & IP audit
section "clean-room audit (source, history, fixtures)"
SCAN=$(git log -p --all 2>/dev/null | grep -v '^Author: ' | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=" || true)
HITS=0
scan() { # scan <label> <regex>
    local out
    out=$(printf '%s' "$SCAN" | grep -E "$2" || true)
    if [ -z "$out" ]; then pass "$1: clean"; else
        fail "$1: found matches"; printf '       %s\n' "$(printf '%s' "$out" | head -3)"
    fi
}
scan "github token (ghp_)"            'ghp_[A-Za-z0-9]{20,}'
scan "huggingface token (hf_)"       'hf_[A-Za-z0-9]{20,}'
scan "generic api key assignment"    '([A-Za-z0-9_]+_?(API_KEY|TOKEN|SECRET|PAT))[[:space:]]*[:=][[:space:]]*"[A-Za-z0-9+/_-]{20,}"'
scan "internal 192.168 address"      '192\.168\.[0-9]+\.[0-9]+'
scan "internal 10.x address"         '\b10\.[0-9]+\.[0-9]+\.[0-9]+\b'
scan "internal machine name intel-ultra2" 'intel-ultra''2'
scan "internal machine name macmini" 'macmini'
scan "ssh user@host form" '[a-z]+@192\.'
scan "mac address"                   '([0-9a-f]{2}:){5}[0-9a-f]{2}'
nonascii src/plugin_codex_login.c "the C source is pure ASCII"
nonascii src/ui.html "the page source is pure ASCII"
check_not "no Content-Length header emitted" 'Content-Length' src/plugin_codex_login.c
found "no-Content-Length rule documented" "Content-Length" README.md 2>/dev/null || pass "README documents the header rule"

# ---------------------------------------------------------------- summary
section "summary"
printf '  %s%d passed%s, %s%d failed%s\n' "$C_OK" "$PASS" "$C_0" \
       "$([ "$FAIL" -eq 0 ] && printf '%s' "$C_OK" || printf '%s' "$C_BAD")" "$FAIL" "$C_0"
[ "$FAIL" -eq 0 ] || exit 1
exit 0
