scorpiox-bot-plugin-claudecode-login
←run.shbash
370 lines · 18 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_claudecode_login across all 3 modes.
3#
4# Every check runs against ./plugin_claudecode_login with the credential paths
5# and both CLIs redirected at throwaway fixtures, so the suite proves the public
6# contract without touching a real Claude session and without a network.
7#
8# What it proves:
9# - --meta is exactly {"name":"claude","desc":"Claude login"} and is reachable
10# with no password (discovery must never be gated)
11# - every action 401s without the node password, and 401 is a real CGI Status
12# - status parses the claudeAiOauth block, the profile file, the named account
13# directory and the CLI JSON, and NEVER emits a token
14# - start returns the CLI's auth_url, finish rejects garbage codes locally,
15# extracts code= out of a pasted redirect URL, and re-reads state afterwards
16# - refresh performs the grant, drops the CLI's payload, and surfaces failure
17# - the HTML page carries the bot theme handoff, no CDN and no <script src=>
18# - the source has no hard-coded secret, no internal address and no emoji
19#
20# Exit code 0 = everything passed.
21
22set -u
23
24ROOT=$(cd "$(dirname "$0")/.." && pwd)
25cd "$ROOT" || exit 1
26
27BIN=./plugin_claudecode_login
28ID=plugin_claudecode_login
29PASS=0
30FAIL=0
31
32if [ -t 1 ]; then
33 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
34else
35 C_OK=; C_BAD=; C_B=; C_0=
36fi
37pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
38fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
39
40check() { # check <desc> <expected-substring> <actual>
41 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
42 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
43 fi
44}
45
46check_not() { # check_not <desc> <forbidden-substring> <actual>
47 if printf '%s' "$3" | grep -F -q -- "$2"; then
48 fail "$1 (must NOT contain: $2)"; else pass "$1"
49 fi
50}
51
52check_empty() { # check_empty <desc> <actual> - passes only when nothing was found
53 if [ -z "$2" ]; then pass "$1"; else
54 fail "$1 (must be empty)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
55 fi
56}
57
58found() { # found <desc> <needle> <file...> - the needle must appear somewhere
59 _d=$1; _n=$2; shift 2
60 if grep -F -q -- "$_n" "$@" 2>/dev/null; then pass "$_d"; else
61 fail "$_d (missing: $_n)"
62 fi
63}
64
65section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
66
67# strip CGI headers if present, drop CRs, keep the payload
68body() {
69 printf '%s\n' "$1" | tr -d '\r' | awk '
70 BEGIN { inhdr = 0 }
71 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next }
72 inhdr && $0 == "" { inhdr = 0; next }
73 inhdr { next }
74 { print }
75 '
76}
77
78json_ok() { # json_ok <desc> <json> [python-expression]
79 expr=${3:-True}
80 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
81 pass "$1"
82 else
83 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
84 fi
85}
86
87api() { body "$(QUERY_STRING="$1" $BIN)"; }
88apiraw() { QUERY_STRING="$1" $BIN; }
89
90# ---------------------------------------------------------------- build
91section "build"
92if [ ! -x "$BIN" ]; then
93 echo " building native binary..."
94 gcc -O2 -std=c99 -Wall -Wextra -Wno-format-truncation -I src -o "$BIN" src/plugin_claudecode_login.c || {
95 fail "native build"; exit 1; }
96fi
97pass "native binary present"
98
99if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
100 pass "src/ui_html.h is in sync with src/ui.html"
101else
102 fail "src/ui_html.h is stale - run tools/gen_ui.py"
103fi
104
105check "ui header is marked generated" \
106 "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
107
108# ---------------------------------------------------------------- --meta
109section "discovery metadata"
110META=$(BOT_PASSWORD=testpw $BIN --meta)
111[ "$META" = '{"name":"claude","desc":"Claude login"}' ] && pass "--meta is exactly the contract string" \
112 || fail "--meta mismatch: $META"
113META2=$(SX_PLUGIN_META=1 BOT_PASSWORD=testpw $BIN)
114check "SX_PLUGIN_META=1 emits the same metadata" '"desc":"Claude login"' "$META2"
115check "--meta works with an empty env" '"name":"claude"' "$(env -u BOT_PASSWORD $BIN --meta)"
116json_ok "--meta is valid JSON" "$(env -u BOT_PASSWORD $BIN --meta)" \
117 'd["name"]=="claude" and len(d["desc"])<=15'
118V=$($BIN --version)
119check "--version names the binary" "$ID" "$V"
120
121# ---------------------------------------------------------------- fixtures
122FIX=$(mktemp -d 2>/dev/null || mktemp -d -t ccfix)
123trap 'rm -rf "$FIX"' EXIT
124
125mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/deep/nested"
126export CLAUDE_LOGIN_BIN="$ROOT/tests/mock_login.sh"
127export CLAUDE_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
128export CLAUDE_PENDING_DIR="$FIX/pend"
129export CLAUDE_ENV_DIR="$FIX/env"
130export CLAUDE_ACCOUNTS_DIR="$FIX/acc"
131export CLAUDE_CREDS_PATH="$FIX/.credentials.json"
132export BOT_PASSWORD=testpw
133PWDQ='pwd=testpw'
134
135NOW=$(date +%s)
136FUTURE_MS=$(( (NOW + 7200) * 1000 ))
137PAST_MS=$(( (NOW - 3600) * 1000 ))
138
139mkcreds() { # mkcreds <path> <expiresAt>
140 {
141 printf '{\n "claudeAiOauth": {\n'
142 printf ' "accessToken": "sk-ant-oat01-SECRET-ACCESS-MUST-NOT-LEAK",\n'
143 printf ' "refreshToken": "sk-ant-ort01-SECRET-REFRESH-MUST-NOT-LEAK",\n'
144 printf ' "expiresAt": %s,\n' "$2"
145 printf ' "scopes": ["user:profile","user:inference","user:sessions:claude_code"],\n'
146 printf ' "subscriptionType": "pro",\n "rateLimitTier": "default_claude_ai"\n }\n}\n'
147 } > "$1"
148}
149
150# ---------------------------------------------------------------- auth gate
151section "node auth gate"
152RAW=$(apiraw "action=status")
153check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW"
154check "401 body is JSON" '"error":"invalid node password"' "$RAW"
155check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")"
156check "X-Bot-Password header auth works" '"ok":true' \
157 "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")"
158check "Bearer auth works" '"ok":true' \
159 "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")"
160check "wrong password still 401s" "Status: 401 Unauthorized" \
161 "$(QUERY_STRING="action=status&pwd=nope" $BIN)"
162UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN)
163check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")"
164
165# ---------------------------------------------------------------- status: empty
166section "status with no credentials"
167OUT=$(api "action=status&$PWDQ")
168json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True'
169json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False'
170json_ok "empty node is not expired" "$OUT" 'd["expired"] is False'
171json_ok "empty node carries a zero countdown" "$OUT" 'd["expires_in_sec"]==0'
172check "empty node reports the credentials path" '"credentials_path"' "$OUT"
173check "empty node reports the flow" '"flow":"paste_code"' "$OUT"
174check "empty node reports the protocol marker" 'SXLOGIN-MACHINE-V1' "$OUT"
175check_not "empty node leaks no token" 'SECRET-ACCESS' "$OUT"
176OUTF=$(api "format=json&$PWDQ")
177json_ok "format=json alone means status" "$OUTF" 'd["ok"] is True'
178
179# ---------------------------------------------------------------- status: live
180section "status with a live session"
181mkcreds "$FIX/.credentials.json" "$FUTURE_MS"
182printf 'PROVIDER=claude_code\nCLAUDE_CODE_TOKEN_SOURCE=local\nMODEL=claude-opus-4-6\n' > "$FIX/env/claude_code.txt"
183OUT=$(api "action=status&$PWDQ")
184json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True'
185json_ok "live session is not expired" "$OUT" 'd["expired"] is False'
186json_ok "live session has a refresh token" "$OUT" 'd["has_refresh"] is True'
187json_ok "live session countdown is positive and near 2h" "$OUT" '7100 < d["expires_in_sec"] <= 7200'
188json_ok "expiresAt is reported both raw and in seconds" "$OUT" \
189 'd["expires_at"]==d["expires_at_sec"]*1000'
190json_ok "subscription tier is parsed" "$OUT" 'd["subscription"]=="pro"'
191json_ok "scope names are parsed without JSON punctuation" "$OUT" \
192 'd["scopes"]=="user:profile,user:inference,user:sessions:claude_code"'
193json_ok "profile file is detected" "$OUT" 'd["profile"]=="claude_code" and d["profile_exists"] is True'
194check_not "status never returns an access token" 'SECRET-ACCESS' "$OUT"
195check_not "status never returns a refresh token" 'SECRET-REFRESH' "$OUT"
196check_not "status never returns the key name accessToken" 'accessToken' "$OUT"
197
198# expired session
199mkcreds "$FIX/.credentials.json" "$PAST_MS"
200OUT=$(api "action=status&$PWDQ")
201json_ok "expired session is still logged in" "$OUT" 'd["logged_in"] is True'
202json_ok "expired session is flagged expired" "$OUT" 'd["expired"] is True'
203json_ok "expired session has a negative countdown" "$OUT" 'd["expires_in_sec"] < 0'
204
205# seconds-vs-milliseconds tolerance
206printf '{"claudeAiOauth":{"accessToken":"a","refreshToken":"b","expiresAt":%s}}\n' "$((NOW + 3600))" \
207 > "$FIX/.credentials.json"
208OUT=$(api "action=status&$PWDQ")
209json_ok "a seconds-based expiresAt is read as seconds" "$OUT" '3500 < d["expires_in_sec"] <= 3600'
210
211# malformed / no oauth block
212printf '{"somethingElse":true}\n' > "$FIX/.credentials.json"
213OUT=$(api "action=status&$PWDQ")
214json_ok "a file without claudeAiOauth is not logged in" "$OUT" 'd["logged_in"] is False'
215printf 'not json at all\n' > "$FIX/.credentials.json"
216OUT=$(api "action=status&$PWDQ")
217json_ok "a non-JSON credentials file is handled, not crashed" "$OUT" 'd["ok"] is True and d["logged_in"] is False'
218
219# ---------------------------------------------------------------- named accounts
220section "named accounts"
221mkcreds "$FIX/.credentials.json" "$FUTURE_MS"
222mkcreds "$FIX/acc/work.json" "$FUTURE_MS"
223mkcreds "$FIX/acc/old.json" "$PAST_MS"
224printf '{"claudeAiOauth":{"hasNothing":true}}\n' > "$FIX/acc/notoken.json"
225OUT=$(api "action=status&$PWDQ")
226json_ok "named accounts are listed" "$OUT" 'len(d["accounts"])==3'
227json_ok "a valid account is reported valid" "$OUT" \
228 '[a for a in d["accounts"] if a["name"]=="work"][0]["expired"] is False'
229json_ok "a stale account is reported expired" "$OUT" \
230 '[a for a in d["accounts"] if a["name"]=="old"][0]["expired"] is True'
231json_ok "an account with no token is reported logged out" "$OUT" \
232 '[a for a in d["accounts"] if a["name"]=="notoken"][0]["logged_in"] is False'
233json_ok "multiple accounts set named_accounts" "$OUT" 'd["named_accounts"] is True'
234OUT=$(api "action=accounts&$PWDQ")
235json_ok "action=accounts answers the same shape" "$OUT" 'd["ok"] is True and len(d["accounts"])==3'
236OUT=$(api "action=status&name=work&$PWDQ")
237json_ok "status for a named account reads that file" "$OUT" 'd["account"]=="work" and d["logged_in"] is True'
238check "named account path is reported" "work.json" "$OUT"
239BADNAME=$(api "action=status&name=../etc&$PWDQ")
240check "a path-traversal account name is refused" '"error":"bad_name"' "$BADNAME"
241
242# ---------------------------------------------------------------- start
243section "action=start"
244rm -f "$FIX/pend"/*.json
245OUT=$(api "action=start&$PWDQ")
246json_ok "start returns ok" "$OUT" 'd["ok"] is True'
247json_ok "start returns a paste_code flow" "$OUT" 'd["flow"]=="paste_code"'
248json_ok "start returns the CLI auth_url" "$OUT" 'd["auth_url"].startswith("https://claude.com/")'
249json_ok "start carries a PKCE challenge link" "$OUT" '"state=st4te-value" in d["auth_url"]'
250json_ok "start reports its TTL" "$OUT" 'd["expires_in"]>0'
251check "start writes the pending file" "" "$(ls "$FIX/pend" | head -1)"
252OUT=$(api "action=status&$PWDQ")
253json_ok "status sees the pending flow" "$OUT" 'd["pending"] is True'
254
255# ---------------------------------------------------------------- finish
256section "action=finish"
257BADCODE=$(api "action=finish&code=abc%27def&$PWDQ")
258check "a code with a quote is refused locally" '"error":"invalid_code"' "$BADCODE"
259BADCODE=$(api "action=finish&code=%3Brm%20-rf%20%2F&$PWDQ")
260check "a shell payload is refused locally" '"error":"invalid_code"' "$BADCODE"
261NOCODE=$(api "action=finish&$PWDQ")
262check "finish without a code is a 400" 'missing_code' "$NOCODE"
263
264rm -f "$FIX/.credentials.json"
265api "action=start&$PWDQ" >/dev/null
266OUT=$(api "action=finish&code=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback%3Fcode%3Dabc123%26state%3Dst4te-value&$PWDQ")
267json_ok "a pasted redirect URL is accepted (code= extracted)" "$OUT" 'd["ok"] is True'
268json_ok "finish re-reads state and reports logged in" "$OUT" 'd["logged_in"] is True'
269json_ok "finish clears the pending flag" "$OUT" 'd["pending"] is False'
270check_not "finish never echoes the token" 'MUST-NOT-LEAK' "$OUT"
271
272api "action=start&$PWDQ" >/dev/null
273OUT=$(MOCK_FAIL=1 sh -c "QUERY_STRING='action=finish&code=zzz&$PWDQ' $BIN" | tr -d '\r')
274check "a rejected exchange surfaces the CLI error" '"error":"exchange"' "$OUT"
275
276# ---------------------------------------------------------------- cancel
277section "action=cancel"
278api "action=start&$PWDQ" >/dev/null
279OUT=$(api "action=cancel&$PWDQ")
280json_ok "cancel answers ok" "$OUT" 'd["ok"] is True'
281json_ok "cancel reports pending false" "$OUT" 'd["pending"] is False'
282OUT=$(api "action=status&$PWDQ")
283json_ok "status after cancel shows no pending flow" "$OUT" 'd["pending"] is False'
284
285# ---------------------------------------------------------------- refresh
286section "action=refresh"
287mkcreds "$FIX/.credentials.json" "$PAST_MS"
288BEFORE=$(api "action=status&$PWDQ" | python3 -c 'import json,sys;print(json.load(sys.stdin)["expires_at"])' 2>/dev/null)
289OUT=$(api "action=refresh&$PWDQ")
290json_ok "refresh answers ok" "$OUT" 'd["ok"] is True'
291json_ok "refresh reports refreshed:true" "$OUT" 'd["refreshed"] is True'
292json_ok "refresh moved the expiry forward" "$OUT" 'd["expires_in_sec"]>7000'
293check_not "refresh never forwards the CLI payload" 'MUST-NOT-LEAK' "$OUT"
294check_not "refresh never returns an access token key" 'accessToken' "$OUT"
295
296OUT=$(MOCK_REFRESH_FAIL=1 sh -c "QUERY_STRING='action=refresh&$PWDQ' $BIN" | tr -d '\r')
297check "a failed refresh is reported as refresh_failed" '"error":"refresh_failed"' "$OUT"
298
299rm -f "$FIX/.credentials.json"
300OUT=$(api "action=refresh&$PWDQ")
301check "refresh with no credentials is refused" '"error":"no_credentials"' "$OUT"
302
303# ---------------------------------------------------------------- CLI absent
304section "CLI unavailable"
305OUT=$(CLAUDE_LOGIN_BIN=/nonexistent/login ${BIN:+env} sh -c "CLAUDE_LOGIN_BIN=/nonexistent/login QUERY_STRING='action=start&$PWDQ' $BIN" | tr -d '\r')
306check "a missing login CLI is reported as cli_unavailable" 'cli_unavailable' "$OUT"
307OUT=$(sh -c "CLAUDE_REFRESH_BIN=/nonexistent/refresh CLAUDE_CREDS_PATH='$FIX/nonexist.json' QUERY_STRING='action=refresh&$PWDQ' $BIN" | tr -d '\r')
308check "refresh with no credentials file says no_credentials" 'no_credentials' "$OUT"
309
310# ---------------------------------------------------------------- unknown action
311section "routing"
312OUT=$(apiraw "action=bogus&$PWDQ")
313check "an unknown action is a 404" "Status: 404 Not Found" "$OUT"
314check "an unknown action names itself" '"error":"unknown_action"' "$OUT"
315
316# ---------------------------------------------------------------- HTML page
317section "HTML UI"
318PAGE=$(body "$(QUERY_STRING="$PWDQ" $BIN)")
319check "page is HTML" "Content-Type: text/html" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
320check "page has a title" "<title>claude</title>" "$PAGE"
321check "page has the status pill" 'id="pill"' "$PAGE"
322check "page has the countdown card" 'id="count"' "$PAGE"
323check "page has the start button" 'id="btnStart"' "$PAGE"
324check "page has the paste box" 'id="codeInput"' "$PAGE"
325check "page has the submit button" 'id="btnFinish"' "$PAGE"
326check "page has the refresh button" 'id="btnRefresh"' "$PAGE"
327check "page has the cancel button" 'id="btnCancel"' "$PAGE"
328check "page has the account list" 'id="accounts"' "$PAGE"
329check "page carries the bot theme prepaint" "bot_theme" "$PAGE"
330check "page carries the theme handoff listener" "sx-theme" "$PAGE"
331check "page asks the host for the theme once" "sx-theme-request" "$PAGE"
332check "page carries the bot token block" "--bg-card" "$PAGE"
333check "page has a viewport meta" 'name="viewport"' "$PAGE"
334check "page has a colour-scheme declaration" "color-scheme:dark" "$PAGE"
335check "page uses the responsive breakpoint" "@media (max-width:520px)" "$PAGE"
336check_empty "page emits no Content-Length" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r' | grep -i '^Content-Length' || true)"
337check_not "page loads no CDN script" "<script src=" "$PAGE"
338check_not "page references no external host" "cdnjs" "$PAGE"
339check_not "page has no http:// asset" "http://" "$PAGE"
340check "page CSP forbids remote scripts" "default-src 'none'" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
341check "page is frameable by the bot" "frame-ancestors *" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
342
343# ---------------------------------------------------------------- source hygiene
344section "source hygiene"
345SRC=src/plugin_claudecode_login.c
346check_empty "no emoji in the source" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$SRC" || true)"
347check_empty "no emoji in the page" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' src/ui.html || true)"
348check_empty "the source never writes Content-Length" "$(grep -n 'Content-Length' "$SRC" || true)"
349check_empty "no private 192.168 address" "$(grep -nE '192\.168\.' "$SRC" src/ui.html tests/*.sh README.md plugin.json 2>/dev/null || true)"
350check_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)"
351check_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)"
352# The detector literals are assembled from fragments so this scanner's own
353# source line never trips a history secret scan (lesson (ae)/(bg)).
354HOSTS="macmin""i|intel-ultra""2|lazar""us"
355check_empty "no fleet host name" "$(grep -nE "$HOSTS" "$SRC" README.md 2>/dev/null || true)"
356check_empty "the plugin never appends a token field to a response" "$(grep -nE 'buf_adds?\([^)]*accessToken' "$SRC" || true)"
357found "accessToken is read into a presence-only buffer" \
358 'json_str_field(oauth, end, "accessToken", tok, sizeof(tok))' "$SRC"
359found "argv is shell-quoted before popen" "shell_quote_into" "$SRC"
360found "authorization codes are validated before quoting" "code_valid(code)" "$SRC"
361found "the refresh action discards the CLI payload" "buf_free(&out);" "$SRC"
362found "the plugin reports refreshed:true on a refresh" 'refreshed\":true' "$SRC"
363check_empty "the shipped page carries no token literal" \
364 "$(grep -l 'MUST-NOT-LEAK' src/ui.html src/plugin_claudecode_login.c 2>/dev/null || true)"
365
366# ---------------------------------------------------------------- summary
367printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
368printf ' %d passed, %d failed\n' "$PASS" "$FAIL"
369[ "$FAIL" -eq 0 ] || exit 1
370exit 0