#!/bin/sh
# tests/run.sh - offline checks for plugin_copilot_login across all 3 modes.
#
# Every check runs against ./plugin_copilot_login with the credential paths and
# both CLIs redirected at throwaway fixtures, so the suite proves the public
# contract without touching a real Copilot session and without a network.
#
# What it proves:
#   - --meta is exactly {"name":"copilot","desc":"Copilot 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 parses the credentials file, the token cache, config.json, the
#     profile file and the named account directory, and NEVER emits a token
#   - start relays the CLI's device code + user_code, poll reports pending then
#     done, cancel drops the pending flow
#   - 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
chmod +x tests/mock_login.sh tests/mock_refresh.sh 2>/dev/null || true

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

check_empty() { # check_empty <desc> <actual>  - passes only when nothing was found
    if [ -z "$2" ]; then pass "$1"; else
        fail "$1 (must be empty)"; printf '       got: %s\n' "$(printf '%s' "$2" | head -c 400)"
    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 = 0 }
        NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|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() { body "$(QUERY_STRING="$1" $BIN)"; }
apiraw() { QUERY_STRING="$1" $BIN; }

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    gcc -O2 -std=c99 -Wall -Wextra -Wno-format-truncation -I src -o "$BIN" src/$ID.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=$($BIN --meta)
check "meta is the exact one-line contract" '{"name":"copilot","desc":"Copilot login"}' "$META"
check "meta works through SX_PLUGIN_META" '{"name":"copilot"' "$(SX_PLUGIN_META=1 $BIN)"
check "meta is reachable with no password" '{"name":"copilot"' "$(BOT_PASSWORD='' $BIN --meta)"
check_not "meta carries nothing else" 'plugin' "$META"
check "version is reported" "$ID" "$($BIN --version)"

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

mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/mock"
export COPILOT_LOGIN_BIN="$ROOT/tests/mock_login.sh"
export COPILOT_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
export COPILOT_PENDING_DIR="$FIX/pend"
export COPILOT_ENV_DIR="$FIX/env"
export COPILOT_ACCOUNTS_DIR="$FIX/acc"
export COPILOT_CREDS_PATH="$FIX/.credentials.json"
export COPILOT_MOCK_DIR="$FIX/mock"
export BOT_PASSWORD=testpw
PWDQ='pwd=testpw'

NOW=$(date +%s)
FUTURE=$(( NOW + 1800 ))
PAST=$(( NOW - 3600 ))

mkcreds() { # mkcreds <path>
    {
    printf '{\n'
    printf '  "github_token": "gho_SECRETGITHUBTOKENMUSTNOTLEAK0000",\n'
    printf '  "token_type": "bearer",\n'
    printf '  "scope": "read:user",\n'
    printf '  "timestamp": "2026-01-01T00:00:00Z"\n'
    printf '}\n'
    } > "$1"
}

mkcache() { # mkcache <path> <expires_at-seconds>
    printf '{"access_token": "SECRET-JWT-MUST-NOT-LEAK-0000", "expires_at": %s}\n' "$2" > "$1"
}

mkconfig() { # mkconfig <path> <login>
    {
    printf '{\n  "copilotTokens": {\n    "https://github.com:%s": "gho_SECRETGITHUBTOKENMUSTNOTLEAK0000"\n  },\n' "$2"
    printf '  "lastLoggedInUser": {\n    "host": "https://github.com",\n    "login": "%s"\n  }\n}\n' "$2"
    } > "$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")"

# ---------------------------------------------------------------- status: empty
section "status with no credentials"
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 carries a zero countdown" "$OUT" 'd["expires_in_sec"]==0'
json_ok "empty node reports a null user" "$OUT" 'd["user"]==""'
json_ok "copilot has no refresh token" "$OUT" 'd["has_refresh"] is False'
check "empty node reports the credentials path" '"credentials_path"' "$OUT"
check "empty node reports the device flow" '"flow":"device_code"' "$OUT"
check "empty node reports the protocol marker" 'SXLOGIN-MACHINE-V1' "$OUT"
check_not "empty node leaks no token" 'SECRETGITHUBTOKEN' "$OUT"
OUTF=$(api "format=json&$PWDQ")
json_ok "format=json alone means status" "$OUTF" 'd["ok"] is True'

# ---------------------------------------------------------------- status: live
section "status with a live session"
mkcreds "$FIX/.credentials.json"
mkconfig "$FIX/config.json" "octocat"
mkcache "$FIX/.copilot-token-cache.json" "$FUTURE"
printf 'PROVIDER=copilot\nCOPILOT_TOKEN_SOURCE=local\nMODEL=claude-sonnet-5\n' > "$FIX/env/copilot.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 countdown is positive and near 30 min" "$OUT" '1700 < d["expires_in_sec"] <= 1800'
json_ok "the token cache is detected" "$OUT" 'd["cache_present"] is True'
json_ok "the GitHub login comes from config.json" "$OUT" 'd["user"]=="octocat"'
json_ok "the scope comes from the credentials file" "$OUT" 'd["scope"]=="read:user"'
json_ok "the profile model is parsed" "$OUT" 'd["profile"]=="claude-sonnet-5"'
json_ok "the profile file is detected" "$OUT" 'd["profile_exists"] is True'
check_not "status never returns a github token" 'SECRETGITHUBTOKEN' "$OUT"
check_not "status never returns a derived JWT" 'SECRET-JWT' "$OUT"
check_not "status never returns the key name github_token" 'github_token' "$OUT"

# ---------------------------------------------------------------- status: expired
section "status with an expired derived token"
mkcache "$FIX/.copilot-token-cache.json" "$PAST"
OUT=$(api "action=status&$PWDQ")
json_ok "an expired derived token is still logged in" "$OUT" 'd["logged_in"] is True'
json_ok "an expired derived token is flagged expired" "$OUT" 'd["expired"] is True'
json_ok "an expired derived token has a negative countdown" "$OUT" 'd["expires_in_sec"]<0'

# ---------------------------------------------------------------- named accounts
section "named accounts"
mkcreds "$FIX/acc/work.json"
mkcreds "$FIX/acc/personal.json"
mkcache "$FIX/.copilot-token-cache.json" "$FUTURE"
OUT=$(api "action=status&$PWDQ")
json_ok "both account files are listed" "$OUT" 'len(d["accounts"])==2'
json_ok "named_accounts is true with more than one" "$OUT" 'd["named_accounts"] is True'
json_ok "each account reports logged_in" "$OUT" 'all(a["logged_in"] for a in d["accounts"])'
OUT=$(api "action=accounts&$PWDQ")
json_ok "action=accounts answers ok" "$OUT" 'd["ok"] is True'
json_ok "action=accounts counts the files" "$OUT" 'd["count"]==2'
check_not "accounts never returns a token" 'SECRETGITHUBTOKEN' "$OUT"
OUT=$(api "action=status&name=work&$PWDQ")
json_ok "a named account is read from its own file" "$OUT" 'd["account"]=="work"'
check "a named account path ends in its file" 'acc/work.json' "$OUT"
BADNAME=$(apiraw "action=status&name=../escape&pwd=testpw" | tr -d '\r')
check "a path-traversal account name is refused" '"error":"bad_name"' "$BADNAME"

# ---------------------------------------------------------------- start
section "action=start"
rm -f "$FIX/pend"/*.json "$FIX/mock"/*
rm -f "$FIX/.credentials.json" "$FIX/.copilot-token-cache.json"
OUT=$(api "action=start&$PWDQ")
json_ok "start returns ok" "$OUT" 'd["ok"] is True'
json_ok "start returns a device_code flow" "$OUT" 'd["flow"]=="device_code"'
json_ok "start returns the GitHub verify URL" "$OUT" 'd["verify_url"]=="https://github.com/login/device"'
json_ok "start returns the 8-character user code" "$OUT" 'd["user_code"]=="1234-5678"'
json_ok "start reports the poll interval" "$OUT" 'd["interval"]==5'
json_ok "start reports its TTL" "$OUT" 'd["expires_in"]>0'
check "start writes the pending file" "" "$(ls "$FIX/pend" | head -1)"
OUT=$(api "action=status&$PWDQ")
json_ok "status sees the pending flow" "$OUT" 'd["pending"] is True'
check_not "start never returns a token" 'SECRET' "$OUT"
# A node that already holds credentials: the CLI answers "exists", not "no
# code". The plugin must relay that word, because it is the only hint that
# force=1 (the Re-login button) is what the user needs.
api "action=cancel&$PWDQ" >/dev/null
mkcreds "$FIX/.credentials.json"
OUT=$(api "action=start&$PWDQ")
check "start relays the CLI's exists error verbatim" '"error":"exists"' "$OUT"
check "the exists error tells the user to re-login" 'Re-login' "$OUT"
OUT=$(api "action=start&force=1&$PWDQ")
json_ok "start with force=1 replaces the credentials" "$OUT" 'd["ok"] is True and d["user_code"]=="1234-5678"'
api "action=cancel&$PWDQ" >/dev/null

# ---------------------------------------------------------------- poll
section "action=poll"
rm -f "$FIX/.credentials.json" "$FIX/.copilot-token-cache.json"
api "action=start&$PWDQ" >/dev/null
OUT=$(api "action=poll&$PWDQ")
json_ok "poll answers ok while waiting" "$OUT" 'd["ok"] is True'
json_ok "poll reports the pending state" "$OUT" 'd["state"]=="pending"'
json_ok "poll repeats the interval" "$OUT" 'd["interval"]==5'

: > "$FIX/mock/poll_done"
rm -f "$FIX/.credentials.json"
OUT=$(api "action=poll&$PWDQ")
json_ok "poll reports done after authorization" "$OUT" 'd["ok"] is True and d["state"]=="done"'
json_ok "poll re-reads state and reports logged in" "$OUT" 'd["logged_in"] is True'
check_not "poll never echoes the token" 'SECRETGITHUBTOKEN' "$OUT"

: > "$FIX/mock/poll_denied"
api "action=start&force=1&$PWDQ" >/dev/null
OUT=$(api "action=poll&$PWDQ")
check "a denied authorization surfaces the CLI error" '"error":"denied"' "$OUT"
OUT=$(api "action=poll&$PWDQ")
check "poll without a pending flow is reported" '"error":"no_pending"' "$OUT"

# ---------------------------------------------------------------- cancel
section "action=cancel"
api "action=start&$PWDQ" >/dev/null
OUT=$(api "action=cancel&$PWDQ")
json_ok "cancel answers ok" "$OUT" 'd["ok"] is True'
json_ok "cancel reports pending false" "$OUT" 'd["pending"] is False'
OUT=$(api "action=status&$PWDQ")
json_ok "status after cancel shows no pending flow" "$OUT" 'd["pending"] is False'

# ---------------------------------------------------------------- refresh
section "action=refresh"
rm -f "$FIX/.copilot-token-cache.json"
mkcreds "$FIX/.credentials.json"
OUT=$(api "action=refresh&$PWDQ")
json_ok "refresh answers ok" "$OUT" 'd["ok"] is True'
json_ok "refresh reports refreshed:true" "$OUT" 'd["refreshed"] is True'
json_ok "refresh produced a fresh cache entry" "$OUT" 'd["cache_present"] is True'
json_ok "refresh moved the expiry forward" "$OUT" '1700 < d["expires_in_sec"] <= 1800'
check_not "refresh never forwards the CLI payload" 'MUST-NOT-LEAK' "$OUT"
check_not "refresh never returns an access_token key" 'access_token' "$OUT"

OUT=$(COPILOT_MOCK_FAIL=1 api "action=refresh&$PWDQ")
check "a failed refresh is reported as refresh_failed" '"error":"refresh_failed"' "$OUT"

rm -f "$FIX/.credentials.json" "$FIX/.copilot-token-cache.json"
OUT=$(api "action=refresh&$PWDQ")
check "refresh with no credentials is refused" '"error":"no_credentials"' "$OUT"

# ---------------------------------------------------------------- CLI absent
section "CLI unavailable"
OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=start&$PWDQ")
check "a missing login CLI is reported as cli_unavailable" 'cli_unavailable' "$OUT"
check "the cli_unavailable detail explains the fix" 'COPILOT_LOGIN_BIN' "$OUT"
OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=poll&$PWDQ")
check "poll without a login CLI is cli_unavailable" 'cli_unavailable' "$OUT"
mkcreds "$FIX/.credentials.json"
OUT=$(COPILOT_REFRESH_BIN=/nonexistent/refresh api "action=refresh&$PWDQ")
check "refresh without a refresh CLI is cli_unavailable" 'cli_unavailable' "$OUT"
OUT=$(COPILOT_LOGIN_BIN=/nonexistent/login api "action=status&$PWDQ")
json_ok "status without a login CLI still answers from the files" "$OUT" 'd["ok"] is True'
json_ok "status reports the CLI as absent" "$OUT" 'd["cli_present"] is False'

# ---------------------------------------------------------------- routing
section "routing"
OUT=$(apiraw "action=bogus&$PWDQ" | tr -d '\r')
check "an unknown action is a 404" "Status: 404 Not Found" "$OUT"
check "an unknown action names itself" '"error":"unknown_action"' "$OUT"

# ---------------------------------------------------------------- HTML page
section "HTML page"
PAGE=$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')
check "page is HTML" "Content-Type: text/html" "$PAGE"
check "page carries the bot theme handoff" "sx-theme" "$PAGE"
check "page asks the host for the theme once" "sx-theme-request" "$PAGE"
check "page carries the bot token block" "--bg-card" "$PAGE"
check "page has a viewport meta" 'name="viewport"' "$PAGE"
check "page has a colour-scheme declaration" "color-scheme:dark" "$PAGE"
check "page uses the responsive breakpoint" "@media (max-width:520px)" "$PAGE"
check "page names the plugin route" "/plugin_copilot_login" "$PAGE"
check "page links the GitHub device URL" "https://github.com/login/device" "$PAGE"
check "page has a live polling indicator" "Waiting for GitHub confirmation" "$PAGE"
check "page has the copy-and-open action" "Copy Code" "$PAGE"
check_empty "page emits no Content-Length" "$(printf '%s' "$PAGE" | grep -i '^Content-Length' || true)"
check_not "page loads no CDN script" "<script src=" "$PAGE"
check_not "page references no external host" "cdnjs" "$PAGE"
check_not "page has no http:// asset" "http://" "$PAGE"
check "page CSP forbids remote scripts" "default-src 'none'" "$PAGE"
check "page is frameable by the bot" "frame-ancestors *" "$PAGE"

# ---------------------------------------------------------------- source hygiene
section "source hygiene"
SRC=src/$ID.c
check_empty "no emoji in the source" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$SRC" || true)"
check_empty "no emoji in the page" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' src/ui.html || true)"
check_empty "the source never writes Content-Length" "$(grep -n 'Content-Length' "$SRC" || true)"
check_empty "no private 192.168 address" "$(grep -nE '192\.168\.' "$SRC" src/ui.html tests/*.sh README.md plugin.json 2>/dev/null || true)"
check_empty "no 10.x private address" "$(grep -nE '(^|[^0-9])10\.[0-9]+\.[0-9]+\.[0-9]+' "$SRC" src/ui.html tests/*.sh README.md 2>/dev/null || true)"
check_empty "no credential literal" "$(grep -nE 'ghp_[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{20,}' "$SRC" tests/*.sh README.md 2>/dev/null || true)"
# The detector literals are assembled from fragments so this scanner's own
# source line never trips a history secret scan.
HOSTS="macmin""i|intel-ultra""2|lazar""us"
check_empty "no fleet host name" "$(grep -nE "$HOSTS" "$SRC" README.md 2>/dev/null || true)"
check_empty "no OAuth client secret is shipped" "$(grep -nE '20[0-9]{2}[A-Za-z0-9]{10,}' "$SRC" || true)"
found "the github_token value is never read into a response" 'json_str_field(json, json + strlen(json), "scope"' "$SRC"
found "argv is shell-quoted before popen" "shell_quote_into" "$SRC"
found "the refresh action discards the CLI payload" "buf_free(&out);" "$SRC"
found "the plugin reports refreshed:true on a refresh" 'refreshed\":true' "$SRC"
found "the device code is relayed verbatim" 'json_str_field(j, end, "user_code"' "$SRC"
check_empty "the shipped page carries no token literal" \
      "$(grep -l 'MUST-NOT-LEAK' src/ui.html src/$ID.c 2>/dev/null || true)"

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