#!/bin/sh
# tests/run.sh - offline checks for plugin_claudecode_login across all 3 modes.
#
# Every check runs against ./plugin_claudecode_login with the credential paths
# and both CLIs redirected at throwaway fixtures, so the suite proves the public
# contract without touching a real Claude session and without a network.
#
# What it proves:
#   - --meta is exactly {"name":"claude","desc":"Claude 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 claudeAiOauth block, the profile file, the named account
#     directory and the CLI JSON, and NEVER emits a token
#   - start returns the CLI's auth_url, finish rejects garbage codes locally,
#     extracts code= out of a pasted redirect URL, and re-reads state afterwards
#   - 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_claudecode_login
ID=plugin_claudecode_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/plugin_claudecode_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":"claude","desc":"Claude 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":"Claude login"' "$META2"
check "--meta works with an empty env" '"name":"claude"' "$(env -u BOT_PASSWORD $BIN --meta)"
json_ok "--meta is valid JSON" "$(env -u BOT_PASSWORD $BIN --meta)" \
        'd["name"]=="claude" and len(d["desc"])<=15'
V=$($BIN --version)
check "--version names the binary" "$ID" "$V"

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

mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/deep/nested"
export CLAUDE_LOGIN_BIN="$ROOT/tests/mock_login.sh"
export CLAUDE_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
export CLAUDE_PENDING_DIR="$FIX/pend"
export CLAUDE_ENV_DIR="$FIX/env"
export CLAUDE_ACCOUNTS_DIR="$FIX/acc"
export CLAUDE_CREDS_PATH="$FIX/.credentials.json"
export BOT_PASSWORD=testpw
PWDQ='pwd=testpw'

NOW=$(date +%s)
FUTURE_MS=$(( (NOW + 7200) * 1000 ))
PAST_MS=$(( (NOW - 3600) * 1000 ))

mkcreds() { # mkcreds <path> <expiresAt>
    {
    printf '{\n  "claudeAiOauth": {\n'
    printf '    "accessToken": "sk-ant-oat01-SECRET-ACCESS-MUST-NOT-LEAK",\n'
    printf '    "refreshToken": "sk-ant-ort01-SECRET-REFRESH-MUST-NOT-LEAK",\n'
    printf '    "expiresAt": %s,\n' "$2"
    printf '    "scopes": ["user:profile","user:inference","user:sessions:claude_code"],\n'
    printf '    "subscriptionType": "pro",\n    "rateLimitTier": "default_claude_ai"\n  }\n}\n'
    } > "$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'
check "empty node reports the credentials path" '"credentials_path"' "$OUT"
check "empty node reports the flow" '"flow":"paste_code"' "$OUT"
check "empty node reports the protocol marker" 'SXLOGIN-MACHINE-V1' "$OUT"
check_not "empty node leaks no token" 'SECRET-ACCESS' "$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" "$FUTURE_MS"
printf 'PROVIDER=claude_code\nCLAUDE_CODE_TOKEN_SOURCE=local\nMODEL=claude-opus-4-6\n' > "$FIX/env/claude_code.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 "expiresAt is reported both raw and in seconds" "$OUT" \
        'd["expires_at"]==d["expires_at_sec"]*1000'
json_ok "subscription tier is parsed" "$OUT" 'd["subscription"]=="pro"'
json_ok "scope names are parsed without JSON punctuation" "$OUT" \
        'd["scopes"]=="user:profile,user:inference,user:sessions:claude_code"'
json_ok "profile file is detected" "$OUT" 'd["profile"]=="claude_code" and d["profile_exists"] is True'
check_not "status never returns an access token" 'SECRET-ACCESS' "$OUT"
check_not "status never returns a refresh token" 'SECRET-REFRESH' "$OUT"
check_not "status never returns the key name accessToken" 'accessToken' "$OUT"

# expired session
mkcreds "$FIX/.credentials.json" "$PAST_MS"
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'

# seconds-vs-milliseconds tolerance
printf '{"claudeAiOauth":{"accessToken":"a","refreshToken":"b","expiresAt":%s}}\n' "$((NOW + 3600))" \
    > "$FIX/.credentials.json"
OUT=$(api "action=status&$PWDQ")
json_ok "a seconds-based expiresAt is read as seconds" "$OUT" '3500 < d["expires_in_sec"] <= 3600'

# malformed / no oauth block
printf '{"somethingElse":true}\n' > "$FIX/.credentials.json"
OUT=$(api "action=status&$PWDQ")
json_ok "a file without claudeAiOauth is not logged in" "$OUT" 'd["logged_in"] is False'
printf 'not json at all\n' > "$FIX/.credentials.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'

# ---------------------------------------------------------------- named accounts
section "named accounts"
mkcreds "$FIX/.credentials.json" "$FUTURE_MS"
mkcreds "$FIX/acc/work.json" "$FUTURE_MS"
mkcreds "$FIX/acc/old.json" "$PAST_MS"
printf '{"claudeAiOauth":{"hasNothing":true}}\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 "multiple accounts set named_accounts" "$OUT" 'd["named_accounts"] is True'
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&name=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&name=../etc&$PWDQ")
check "a path-traversal account name is refused" '"error":"bad_name"' "$BADNAME"

# ---------------------------------------------------------------- start
section "action=start"
rm -f "$FIX/pend"/*.json
OUT=$(api "action=start&$PWDQ")
json_ok "start returns ok" "$OUT" 'd["ok"] is True'
json_ok "start returns a paste_code flow" "$OUT" 'd["flow"]=="paste_code"'
json_ok "start returns the CLI auth_url" "$OUT" 'd["auth_url"].startswith("https://claude.com/")'
json_ok "start carries a PKCE challenge link" "$OUT" '"state=st4te-value" in d["auth_url"]'
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'

# ---------------------------------------------------------------- finish
section "action=finish"
BADCODE=$(api "action=finish&code=abc%27def&$PWDQ")
check "a code with a quote is refused locally" '"error":"invalid_code"' "$BADCODE"
BADCODE=$(api "action=finish&code=%3Brm%20-rf%20%2F&$PWDQ")
check "a shell payload is refused locally" '"error":"invalid_code"' "$BADCODE"
NOCODE=$(api "action=finish&$PWDQ")
check "finish without a code is a 400" 'missing_code' "$NOCODE"

rm -f "$FIX/.credentials.json"
api "action=start&$PWDQ" >/dev/null
OUT=$(api "action=finish&code=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback%3Fcode%3Dabc123%26state%3Dst4te-value&$PWDQ")
json_ok "a pasted redirect URL is accepted (code= extracted)" "$OUT" 'd["ok"] is True'
json_ok "finish re-reads state and reports logged in" "$OUT" 'd["logged_in"] is True'
json_ok "finish clears the pending flag" "$OUT" 'd["pending"] is False'
check_not "finish never echoes the token" 'MUST-NOT-LEAK' "$OUT"

api "action=start&$PWDQ" >/dev/null
OUT=$(MOCK_FAIL=1 sh -c "QUERY_STRING='action=finish&code=zzz&$PWDQ' $BIN" | tr -d '\r')
check "a rejected exchange surfaces the CLI error" '"error":"exchange"' "$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"
mkcreds "$FIX/.credentials.json" "$PAST_MS"
BEFORE=$(api "action=status&$PWDQ" | python3 -c 'import json,sys;print(json.load(sys.stdin)["expires_at"])' 2>/dev/null)
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 moved the expiry forward" "$OUT" 'd["expires_in_sec"]>7000'
check_not "refresh never forwards the CLI payload" 'MUST-NOT-LEAK' "$OUT"
check_not "refresh never returns an access token key" 'accessToken' "$OUT"

OUT=$(MOCK_REFRESH_FAIL=1 sh -c "QUERY_STRING='action=refresh&$PWDQ' $BIN" | tr -d '\r')
check "a failed refresh is reported as refresh_failed" '"error":"refresh_failed"' "$OUT"

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

# ---------------------------------------------------------------- CLI absent
section "CLI unavailable"
OUT=$(CLAUDE_LOGIN_BIN=/nonexistent/login ${BIN:+env} sh -c "CLAUDE_LOGIN_BIN=/nonexistent/login QUERY_STRING='action=start&$PWDQ' $BIN" | tr -d '\r')
check "a missing login CLI is reported as cli_unavailable" 'cli_unavailable' "$OUT"
OUT=$(sh -c "CLAUDE_REFRESH_BIN=/nonexistent/refresh CLAUDE_CREDS_PATH='$FIX/nonexist.json' QUERY_STRING='action=refresh&$PWDQ' $BIN" | tr -d '\r')
check "refresh with no credentials file says no_credentials" 'no_credentials' "$OUT"

# ---------------------------------------------------------------- unknown action
section "routing"
OUT=$(apiraw "action=bogus&$PWDQ")
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 UI"
PAGE=$(body "$(QUERY_STRING="$PWDQ" $BIN)")
check "page is HTML" "Content-Type: text/html" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
check "page has a title" "<title>claude</title>" "$PAGE"
check "page has the status pill" 'id="pill"' "$PAGE"
check "page has the countdown card" 'id="count"' "$PAGE"
check "page has the start button" 'id="btnStart"' "$PAGE"
check "page has the paste box" 'id="codeInput"' "$PAGE"
check "page has the submit button" 'id="btnFinish"' "$PAGE"
check "page has the refresh button" 'id="btnRefresh"' "$PAGE"
check "page has the cancel button" 'id="btnCancel"' "$PAGE"
check "page has the account list" 'id="accounts"' "$PAGE"
check "page carries the bot theme prepaint" "bot_theme" "$PAGE"
check "page carries the theme handoff listener" "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_empty "page emits no Content-Length" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r' | 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'" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
check "page is frameable by the bot" "frame-ancestors *" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"

# ---------------------------------------------------------------- source hygiene
section "source hygiene"
SRC=src/plugin_claudecode_login.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 (lesson (ae)/(bg)).
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 "the plugin never appends a token field to a response" "$(grep -nE 'buf_adds?\([^)]*accessToken' "$SRC" || true)"
found "accessToken is read into a presence-only buffer" \
      'json_str_field(oauth, end, "accessToken", tok, sizeof(tok))' "$SRC"
found "argv is shell-quoted before popen" "shell_quote_into" "$SRC"
found "authorization codes are validated before quoting" "code_valid(code)" "$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"
check_empty "the shipped page carries no token literal" \
      "$(grep -l 'MUST-NOT-LEAK' src/ui.html src/plugin_claudecode_login.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
