scorpiox-bot-plugin-codex-login
←run.shbash
483 lines · 24 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_codex_login across all 3 modes.
3#
4# Every check runs against ./plugin_codex_login with the credential paths and
5# both CLIs redirected at throwaway fixtures, so the suite proves the public
6# contract without touching a real Codex session and without a network.
7#
8# What it proves:
9# - --meta is exactly {"name":"codex","desc":"Codex 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 reads the tokens block, decodes the JWT exp claim for the expiry
13# (auth.json has no expiry field of its own), reads last_refresh, lists the
14# named account directory, and NEVER emits a token
15# - start returns the CLI's verify_url and user_code, reports "already logged
16# in" when the CLI says exists, and survives a CLI answer with no user code
17# - poll reports pending, reports done after the CLI writes the file, and
18# turns a denied device code into a terminal failed state
19# - refresh performs the grant, drops the CLI's payload, and surfaces failure
20# - the HTML page carries the bot theme handoff, no CDN and no <script src=>
21# - the source has no hard-coded secret, no internal address and no emoji
22#
23# Exit code 0 = everything passed.
24
25set -u
26
27ROOT=$(cd "$(dirname "$0")/.." && pwd)
28cd "$ROOT" || exit 1
29
30BIN=./plugin_codex_login
31ID=plugin_codex_login
32PASS=0
33FAIL=0
34
35if [ -t 1 ]; then
36 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
37else
38 C_OK=; C_BAD=; C_B=; C_0=
39fi
40pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
41fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
42
43check() { # check <desc> <expected-substring> <actual>
44 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
45 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
46 fi
47}
48
49check_not() { # check_not <desc> <forbidden-substring> <actual>
50 if printf '%s' "$3" | grep -F -q -- "$2"; then
51 fail "$1 (must NOT contain: $2)"; else pass "$1"
52 fi
53}
54
55found() { # found <desc> <needle> <file...> - the needle must appear somewhere
56 _d=$1; _n=$2; shift 2
57 if grep -F -q -- "$_n" "$@" 2>/dev/null; then pass "$_d"; else
58 fail "$_d (missing: $_n)"
59 fi
60}
61
62section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
63
64# strip CGI headers if present, drop CRs, keep the payload
65body() {
66 printf '%s\n' "$1" | tr -d '\r' | awk '
67 BEGIN { inhdr = 1 }
68 inhdr && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/ || $0 == "") { next }
69 { inhdr = 0; print }
70 '
71}
72
73json_ok() { # json_ok <desc> <json> [python-expression]
74 expr=${3:-True}
75 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
76 pass "$1"
77 else
78 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
79 fi
80}
81
82api() { body "$(QUERY_STRING="$1" $BIN)"; }
83apiraw() { QUERY_STRING="$1" $BIN; }
84
85# Build a JWT whose payload carries exp=<seconds>. The real access tokens are
86# RS256 JWTs of the same shape, so the fixture is faithful in the only field the
87# plugin reads.
88mkjwt() { # mkjwt <exp-seconds>
89 python3 - "$1" << 'PYEOF'
90import base64, json, sys
91exp = int(sys.argv[1])
92payload = {"exp": exp, "chatgpt_account_id": "acct-fixture", "sub": "user-fixture"}
93b = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
94print("eyJhbGciOiJIUzI1NiJ9." + b + ".SIGNATUREPART")
95PYEOF
96}
97
98# ---------------------------------------------------------------- build
99section "build"
100if [ ! -x "$BIN" ]; then
101 echo " building native binary..."
102 cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src \
103 -o "$BIN" src/plugin_codex_login.c || { fail "native build"; exit 1; }
104fi
105pass "native binary present"
106
107if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
108 pass "src/ui_html.h is in sync with src/ui.html"
109else
110 fail "src/ui_html.h is stale - run tools/gen_ui.py"
111fi
112
113check "ui header is marked generated" \
114 "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
115
116# ---------------------------------------------------------------- --meta
117section "discovery metadata"
118META=$(BOT_PASSWORD=testpw $BIN --meta)
119[ "$META" = '{"name":"codex","desc":"Codex login"}' ] && pass "--meta is exactly the contract string" \
120 || fail "--meta mismatch: $META"
121META2=$(SX_PLUGIN_META=1 BOT_PASSWORD=testpw $BIN)
122check "SX_PLUGIN_META=1 emits the same metadata" '"desc":"Codex login"' "$META2"
123check "--meta works with an empty env" '"name":"codex"' "$(env -u BOT_PASSWORD $BIN --meta)"
124json_ok "--meta is valid JSON" "$(env -u BOT_PASSWORD $BIN --meta)" \
125 'd["name"]=="codex" and len(d["desc"])<=15'
126json_ok "--meta title is one word" "$(env -u BOT_PASSWORD $BIN --meta)" \
127 'len(d["name"].split())==1'
128V=$($BIN --version)
129check "--version names the binary" "$ID" "$V"
130
131# ---------------------------------------------------------------- fixtures
132FIX=$(mktemp -d 2>/dev/null || mktemp -d -t cxfix)
133trap 'rm -rf "$FIX"' EXIT
134
135mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/deep/nested"
136export CODEX_LOGIN_BIN="$ROOT/tests/mock_login.sh"
137export CODEX_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
138export CODEX_PENDING_DIR="$FIX/pend"
139export CODEX_ENV_DIR="$FIX/env"
140export CODEX_ACCOUNTS_DIR="$FIX/acc"
141export CODEX_CREDS_PATH="$FIX/auth.json"
142export BOT_PASSWORD=testpw
143PWDQ='pwd=testpw'
144
145NOW=$(date +%s)
146FUTURE=$((NOW + 7200))
147PAST=$((NOW - 3600))
148TOK_FUTURE=$(mkjwt "$FUTURE")
149TOK_PAST=$(mkjwt "$PAST")
150
151mkcreds() { # mkcreds <path> <access-token> <refresh-or-empty> <last_refresh>
152 {
153 printf '{\n "OPENAI_API_KEY": null,\n "tokens": {\n'
154 printf ' "id_token": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmaXh0dXJlIn0.IDSIG",\n'
155 printf ' "access_token": "%s",\n' "$2"
156 if [ -n "$3" ]; then
157 printf ' "refresh_token": "%s",\n' "$3"
158 else
159 printf ' "refresh_token": "",\n'
160 fi
161 printf ' "account_id": "acct-fixture"\n },\n'
162 printf ' "last_refresh": "%s"\n}\n' "$4"
163 } > "$1"
164}
165
166# ---------------------------------------------------------------- auth gate
167section "node auth gate"
168RAW=$(apiraw "action=status")
169check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW"
170check "401 body is JSON" '"error":"invalid node password"' "$RAW"
171check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")"
172check "X-Bot-Password header auth works" '"ok":true' \
173 "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")"
174check "Bearer auth works" '"ok":true' \
175 "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")"
176check "wrong password still 401s" "Status: 401 Unauthorized" \
177 "$(QUERY_STRING="action=status&pwd=nope" $BIN)"
178UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN)
179check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")"
180check "discovery is never gated" '"name":"codex"' "$(env -u BOT_PASSWORD $BIN --meta)"
181
182# ---------------------------------------------------------------- status: empty
183section "status with no credentials"
184rm -f "$FIX/auth.json" "$FIX/acc"/*.json "$FIX/pend"/*.json "$FIX/env"/*.txt
185OUT=$(api "action=status&$PWDQ")
186json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True'
187json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False'
188json_ok "empty node is not expired" "$OUT" 'd["expired"] is False'
189json_ok "empty node has no expiry" "$OUT" 'd["expires_at"]==0 and d["expires_in_sec"]==0'
190json_ok "empty node has no refresh token" "$OUT" 'd["has_refresh"] is False'
191json_ok "empty node has no pending flow" "$OUT" 'd["pending"] is False'
192json_ok "empty node reports the credentials path" "$OUT" 'd["credentials_path"].endswith("auth.json")'
193json_ok "empty node has no named accounts" "$OUT" 'd["accounts"]==[]'
194json_ok "empty node says the CLI is present (mock)" "$OUT" 'd["cli_present"] is True'
195
196# ---------------------------------------------------------------- status: live
197section "status with a live session"
198mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-secret-refresh-must-not-leak" "2026-11-12T12:00:00.000000Z"
199printf 'PROVIDER=codex\nCODEX_TOKEN_SOURCE=local\nMODEL=gpt-5.5\n' > "$FIX/env/codex.txt"
200OUT=$(api "action=status&$PWDQ")
201json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True'
202json_ok "live session is not expired" "$OUT" 'd["expired"] is False'
203json_ok "live session has a refresh token" "$OUT" 'd["has_refresh"] is True'
204json_ok "live session countdown is positive and near 2h" "$OUT" \
205 '7100 < d["expires_in_sec"] <= 7200'
206json_ok "expiry is unix seconds, not milliseconds" "$OUT" \
207 '1000000000 < d["expires_at"] < 3000000000'
208json_ok "last_refresh is parsed to unix seconds" "$OUT" 'd["last_refresh"] > 1000000000'
209json_ok "account id is read from the file" "$OUT" 'd["account_id"]=="acct-fixture"'
210json_ok "profile file is detected" "$OUT" 'd["profile"]=="codex" and d["profile_exists"] is True'
211json_ok "default account is named default" "$OUT" 'd["account"]=="default"'
212check_not "status never returns an access token" 'SIGNATUREPART' "$OUT"
213check_not "status never returns a refresh token" 'rt-secret-refresh' "$OUT"
214check_not "status never returns the id token" 'eyJhbGciOiJIUzI1NiJ9' "$OUT"
215check_not "status never returns the key name access_token" 'access_token' "$OUT"
216check_not "status never leaks the fixture secret word" 'MUST-NOT-LEAK' "$OUT"
217
218# ---------------------------------------------------------------- status: expired
219section "status with an expired session"
220mkcreds "$FIX/auth.json" "$TOK_PAST" "rt-secret-refresh-must-not-leak" "2026-11-10T09:00:00.000000Z"
221OUT=$(api "action=status&$PWDQ")
222json_ok "expired session is still logged in" "$OUT" 'd["logged_in"] is True'
223json_ok "expired session is flagged expired" "$OUT" 'd["expired"] is True'
224json_ok "expired session has a negative countdown" "$OUT" 'd["expires_in_sec"] < 0'
225
226# ---------------------------------------------------------------- odd fixtures
227section "malformed and unusual fixtures"
228printf '{"OPENAI_API_KEY":"legacy-key-value","tokens":{"access_token":"a"}}\n' > "$FIX/auth.json"
229OUT=$(api "action=status&$PWDQ")
230json_ok "a token with no exp claim is logged in with unknown expiry" "$OUT" \
231 'd["logged_in"] is True and d["expires_at"]==0 and d["expired"] is False'
232json_ok "a legacy OPENAI_API_KEY is reported as present, not as a token" "$OUT" \
233 'd["api_key_present"] is True'
234check_not "the legacy key value is never echoed" 'legacy-key-value' "$OUT"
235
236printf 'not json at all\n' > "$FIX/auth.json"
237OUT=$(api "action=status&$PWDQ")
238json_ok "a non-JSON credentials file is handled, not crashed" "$OUT" \
239 'd["ok"] is True and d["logged_in"] is False'
240
241printf '{"somethingElse":true}\n' > "$FIX/auth.json"
242OUT=$(api "action=status&$PWDQ")
243json_ok "a file with no tokens block is not logged in" "$OUT" 'd["logged_in"] is False'
244
245printf '{"OPENAI_API_KEY":null,"tokens":{"access_token":"","refresh_token":""}}\n' > "$FIX/auth.json"
246OUT=$(api "action=status&$PWDQ")
247json_ok "an empty access token is not a session" "$OUT" 'd["logged_in"] is False'
248json_ok "an empty refresh token is not a refresh token" "$OUT" 'd["has_refresh"] is False'
249
250# a flat file (no tokens wrapper) still counts as a session
251printf '{"access_token":"%s","refresh_token":"rt-flat"}\n' "$TOK_FUTURE" > "$FIX/auth.json"
252OUT=$(api "action=status&$PWDQ")
253json_ok "a flat token file is read as a session" "$OUT" \
254 'd["logged_in"] is True and 7100 < d["expires_in_sec"] <= 7200'
255
256# a token whose payload is not base64 at all
257printf '{"tokens":{"access_token":"!!!not-a-jwt!!!"}}\n' > "$FIX/auth.json"
258OUT=$(api "action=status&$PWDQ")
259json_ok "a non-JWT access token is a session with unknown expiry" "$OUT" \
260 'd["logged_in"] is True and d["expires_at"]==0'
261
262# ---------------------------------------------------------------- named accounts
263section "named accounts"
264mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-default" "2026-11-12T12:00:00.000000Z"
265mkcreds "$FIX/acc/work.json" "$TOK_FUTURE" "rt-work" "2026-11-12T10:00:00.000000Z"
266mkcreds "$FIX/acc/old.json" "$TOK_PAST" "rt-old" "2026-11-01T10:00:00.000000Z"
267printf '{"OPENAI_API_KEY":null,"tokens":{"access_token":"","refresh_token":""}}\n' > "$FIX/acc/notoken.json"
268OUT=$(api "action=status&$PWDQ")
269json_ok "named accounts are listed" "$OUT" 'len(d["accounts"])==3'
270json_ok "a valid account is reported valid" "$OUT" \
271 '[a for a in d["accounts"] if a["name"]=="work"][0]["expired"] is False'
272json_ok "a stale account is reported expired" "$OUT" \
273 '[a for a in d["accounts"] if a["name"]=="old"][0]["expired"] is True'
274json_ok "an account with no token is reported logged out" "$OUT" \
275 '[a for a in d["accounts"] if a["name"]=="notoken"][0]["logged_in"] is False'
276json_ok "named accounts are flagged" "$OUT" 'd["named_accounts"] is True'
277json_ok "account entries carry their own countdown" "$OUT" \
278 '[a for a in d["accounts"] if a["name"]=="work"][0]["expires_in_sec"] > 7000'
279check_not "account entries never carry a token" 'SIGNATUREPART' "$OUT"
280OUT=$(api "action=accounts&$PWDQ")
281json_ok "action=accounts answers the same shape" "$OUT" 'd["ok"] is True and len(d["accounts"])==3'
282OUT=$(api "action=status&account=work&$PWDQ")
283json_ok "status for a named account reads that file" "$OUT" \
284 'd["account"]=="work" and d["logged_in"] is True'
285check "named account path is reported" "work.json" "$OUT"
286BADNAME=$(api "action=status&account=../etc/passwd&$PWDQ")
287json_ok "a path-traversal account name is ignored, not followed" "$BADNAME" \
288 'd["ok"] is True and d["account"]=="default" and "/etc" not in d["credentials_path"]'
289BADSTART=$(api "action=start&account=..%2Fetc&$PWDQ")
290check_not "a traversal name never reaches a path in start" '/etc' "$BADSTART"
291
292# ---------------------------------------------------------------- pending marker
293section "pending device flow marker"
294rm -f "$FIX/pend"/*.json
295OUT=$(api "action=status&$PWDQ")
296json_ok "no marker means not pending" "$OUT" 'd["pending"] is False'
297printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","interval":5,"created":%s}\n' "$NOW" \
298 > "$FIX/pend/codex-default.json"
299OUT=$(api "action=status&$PWDQ")
300json_ok "a fresh marker means pending" "$OUT" 'd["pending"] is True'
301json_ok "the marker age is reported" "$OUT" '0 <= d["pending_age_sec"] < 120'
302printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$((NOW - 99999))" \
303 > "$FIX/pend/codex-default.json"
304OUT=$(api "action=status&$PWDQ")
305json_ok "a stale marker is not pending" "$OUT" 'd["pending"] is False'
306rm -f "$FIX/pend"/*.json
307
308# ---------------------------------------------------------------- start
309section "action=start"
310rm -f "$FIX/pend"/*.json
311rm -f "$FIX/auth.json"
312OUT=$(api "action=start&$PWDQ")
313json_ok "start returns ok" "$OUT" 'd["ok"] is True'
314json_ok "start returns the device_code flow" "$OUT" 'd["flow"]=="device_code"'
315json_ok "start returns the CLI verify_url" "$OUT" 'd["verify_url"].startswith("https://auth.openai.com/")'
316json_ok "start returns a user code" "$OUT" 'd["user_code"]=="ABCD-1234"'
317json_ok "start returns expires_in" "$OUT" 'd["expires_in"] > 0'
318json_ok "start returns a poll interval" "$OUT" 'd["interval"] >= 1'
319json_ok "start marks the flow pending" "$OUT" 'd["pending"] is True'
320check "start writes the pending marker" "codex-default.json" "$FIX/pend"/*.json 2>/dev/null || \
321 pass "start leaves a marker for poll to find"
322check_not "start never echoes a token" 'SIGNATUREPART' "$OUT"
323
324# already-logged-in path: the CLI refuses --start when credentials exist.
325mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-exists" "2026-11-12T12:00:00.000000Z"
326OUT=$(body "$(MOCK_EXISTS=1 QUERY_STRING="action=start&$PWDQ" $BIN)")
327json_ok "start on existing creds reports already_logged_in" "$OUT" \
328 'd["ok"] is True and d["already_logged_in"] is True'
329json_ok "the already-logged-in answer keeps logged_in true" "$OUT" 'd["logged_in"] is True'
330json_ok "the already-logged-in answer tells the user how to replace" "$OUT" \
331 '"force=1" in d["hint"]'
332OUT=$(body "$(MOCK_EXISTS=1 QUERY_STRING="action=start&force=1&$PWDQ" $BIN)")
333json_ok "force=1 reaches the CLI as --force" "$OUT" 'd["ok"] is True and d["flow"]=="device_code"'
334
335# a CLI answer with no user code
336OUT=$(body "$(MOCK_NOUSER=1 QUERY_STRING="action=start&$PWDQ" $BIN)")
337json_ok "a start with no user code is start_incomplete" "$OUT" 'd["ok"] is False and d["error"]=="start_incomplete"'
338
339# no CLI on the node
340OUT=$(body "$(CODEX_LOGIN_BIN=sx-absent-cli-for-tests QUERY_STRING="action=start&$PWDQ" $BIN)")
341json_ok "a missing login CLI is cli_unavailable, not a crash" "$OUT" \
342 'd["ok"] is False and d["error"]=="cli_unavailable"'
343
344# ---------------------------------------------------------------- poll
345section "action=poll"
346rm -f "$FIX/pend"/*.json "$FIX/auth.json"
347printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","interval":5,"created":%s}\n' "$NOW" \
348 > "$FIX/pend/codex-default.json"
349OUT=$(api "action=poll&$PWDQ")
350json_ok "poll while waiting is ok" "$OUT" 'd["ok"] is True'
351json_ok "poll while waiting reports pending" "$OUT" 'd["state"]=="pending"'
352json_ok "poll while waiting is not done" "$OUT" 'd.get("logged_in") is not True'
353json_ok "poll passes the interval through" "$OUT" 'd["interval"] >= 1'
354
355OUT=$(body "$(MOCK_DONE=1 MOCK_ACCESS_TOKEN="$TOK_FUTURE" QUERY_STRING="action=poll&$PWDQ" $BIN)")
356json_ok "poll after approval reports done" "$OUT" 'd["ok"] is True and d["state"]=="done"'
357json_ok "poll after approval is logged in" "$OUT" 'd["logged_in"] is True'
358json_ok "poll after approval proves the countdown from the file" "$OUT" \
359 '7100 < d["expires_in_sec"] <= 7200'
360json_ok "poll after approval clears pending" "$OUT" 'd["pending"] is False'
361check_not "the done answer never echoes a token" 'SIGNATUREPART' "$OUT"
362
363OUT=$(body "$(MOCK_FAIL=1 QUERY_STRING="action=poll&$PWDQ" $BIN)")
364json_ok "a denied device code is a terminal failed state" "$OUT" \
365 'd["ok"] is True and d["state"]=="failed"'
366json_ok "the failed state carries the CLI error" "$OUT" 'd["error"]=="denied"'
367json_ok "the failed state clears pending" "$OUT" 'd["pending"] is False'
368
369OUT=$(body "$(CODEX_LOGIN_BIN=sx-absent-cli-for-tests QUERY_STRING="action=poll&$PWDQ" $BIN)")
370json_ok "poll with no CLI is cli_unavailable" "$OUT" 'd["error"]=="cli_unavailable"'
371
372# ---------------------------------------------------------------- cancel
373section "action=cancel"
374printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$NOW" \
375 > "$FIX/pend/codex-default.json"
376OUT=$(api "action=cancel&$PWDQ")
377json_ok "cancel is ok" "$OUT" 'd["ok"] is True and d["state"]=="cancelled"'
378json_ok "cancel clears pending" "$OUT" 'd["pending"] is False'
379if [ -f "$FIX/pend/codex-default.json" ]; then fail "cancel removed the marker"; else pass "cancel removed the marker"; fi
380
381printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$NOW" \
382 > "$FIX/pend/codex-default.json"
383OUT=$(body "$(CODEX_LOGIN_BIN=sx-absent-cli-for-tests QUERY_STRING="action=cancel&$PWDQ" $BIN)")
384json_ok "cancel with no CLI still clears the marker" "$OUT" \
385 'd["ok"] is True and d["pending"] is False and d["cli_present"] is False'
386if [ -f "$FIX/pend/codex-default.json" ]; then fail "cancel without CLI removed the marker"; else pass "cancel without CLI removed the marker"; fi
387
388# ---------------------------------------------------------------- refresh
389section "action=refresh"
390rm -f "$FIX/auth.json"
391OUT=$(api "action=refresh&$PWDQ")
392json_ok "refresh with no credentials is no_credentials" "$OUT" \
393 'd["ok"] is False and d["error"]=="no_credentials"'
394
395mkcreds "$FIX/auth.json" "$TOK_PAST" "rt-secret-refresh-must-not-leak" "2026-11-10T09:00:00.000000Z"
396OUT=$(api "action=refresh&$PWDQ")
397json_ok "refresh on an expired token succeeds" "$OUT" 'd["ok"] is True and d["refreshed"] is True'
398json_ok "refresh extends the countdown" "$OUT" 'd["expires_in_sec"] > 3600'
399json_ok "refresh re-reports logged in" "$OUT" 'd["logged_in"] is True and d["expired"] is False'
400check_not "refresh never echoes the CLI's rotated token" 'super-secret-rotated-token-value' "$OUT"
401check_not "refresh never echoes the old secret" 'rt-secret-refresh' "$OUT"
402
403OUT=$(body "$(MOCK_FAIL=1 QUERY_STRING="action=refresh&$PWDQ" $BIN)")
404json_ok "a failing refresh CLI is reported as failure" "$OUT" \
405 'd["ok"] is False and d["error"]=="refresh_failed"'
406
407OUT=$(body "$(CODEX_REFRESH_BIN=sx-absent-cli-for-tests QUERY_STRING="action=refresh&$PWDQ" $BIN)")
408json_ok "a missing refresh CLI is cli_unavailable" "$OUT" 'd["error"]=="cli_unavailable"'
409
410# ---------------------------------------------------------------- unknown action
411section "unknown action"
412RAW=$(apiraw "action=bogus&$PWDQ")
413check "unknown action 400s" "Status: 400 Bad Request" "$RAW"
414OUT=$(body "$RAW")
415json_ok "unknown action names the problem" "$OUT" 'd["ok"] is False and d["error"]=="unknown_action"'
416
417# ---------------------------------------------------------------- format=json
418section "format=json"
419OUT=$(api "format=json&$PWDQ")
420json_ok "format=json alone means status" "$OUT" 'd["ok"] is True and "logged_in" in d'
421
422# ---------------------------------------------------------------- HTML page
423section "HTML page"
424PAGE=$(body "$(apiraw "$PWDQ")")
425check "page is served as HTML" "<!DOCTYPE html>" "$PAGE"
426check "page declares the plugin id in the footer" "plugin_codex_login" "$PAGE"
427check "page carries the bot theme tokens" "color-scheme:dark" "$PAGE"
428check "page carries the theme handoff listener" "sx-theme-request" "$PAGE"
429check "page carries the theme prepaint" "data-theme" "$PAGE"
430check "page has the status pill" 'id="pill"' "$PAGE"
431check "page has the countdown" 'id="count"' "$PAGE"
432check "page has the user code display" 'id="userCode"' "$PAGE"
433check "page has the copy-and-open button" "Copy Code &amp; Open OpenAI" "$PAGE"
434check "page has the polling label" "Waiting for authorization in browser" "$PAGE"
435check "page has the cancel button" 'id="btnCancel"' "$PAGE"
436check "page has the refresh button" "Refresh Token Now" "$PAGE"
437check "page has the start button" "Start Codex Login" "$PAGE"
438check "page is fluid down to a phone" "max-width:520px" "$PAGE"
439check_not "page loads no external script" '<script src=' "$PAGE"
440check_not "page references a CDN" 'cdnjs' "$PAGE"
441check_not "page references googleapis" 'googleapis' "$PAGE"
442nonascii() { # nonascii <file> - fails when any byte is outside printable ASCII
443 if LC_ALL=C grep -qP '[^\x09\x0a\x20-\x7e]' "$1" 2>/dev/null; then
444 fail "$2 (non-ASCII bytes present)"; LC_ALL=C grep -oP '[^\x09\x0a\x20-\x7e]' "$1" | head -3 | sed 's/^/ /'
445 else pass "$2"
446 fi
447}
448nonascii src/ui.html "the page is pure ASCII"
449check "page fetches through the hub-aware router" "'/plugins?plugin='" "$PAGE"
450check "page keeps the node password out of the URL path" "X-Bot-Password" "$PAGE"
451check "page links to the public source mirror" "plugingit.scorpiox.net" "$PAGE"
452
453# ---------------------------------------------------------------- secret & IP audit
454section "clean-room audit (source, history, fixtures)"
455SCAN=$(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)
456HITS=0
457scan() { # scan <label> <regex>
458 local out
459 out=$(printf '%s' "$SCAN" | grep -E "$2" || true)
460 if [ -z "$out" ]; then pass "$1: clean"; else
461 fail "$1: found matches"; printf ' %s\n' "$(printf '%s' "$out" | head -3)"
462 fi
463}
464scan "github token (ghp_)" 'ghp_[A-Za-z0-9]{20,}'
465scan "huggingface token (hf_)" 'hf_[A-Za-z0-9]{20,}'
466scan "generic api key assignment" '([A-Za-z0-9_]+_?(API_KEY|TOKEN|SECRET|PAT))[[:space:]]*[:=][[:space:]]*"[A-Za-z0-9+/_-]{20,}"'
467scan "internal 192.168 address" '192\.168\.[0-9]+\.[0-9]+'
468scan "internal 10.x address" '\b10\.[0-9]+\.[0-9]+\.[0-9]+\b'
469scan "internal machine name intel-ultra2" 'intel-ultra''2'
470scan "internal machine name macmini" 'macmini'
471scan "ssh user@host form" '[a-z]+@192\.'
472scan "mac address" '([0-9a-f]{2}:){5}[0-9a-f]{2}'
473nonascii src/plugin_codex_login.c "the C source is pure ASCII"
474nonascii src/ui.html "the page source is pure ASCII"
475check_not "no Content-Length header emitted" 'Content-Length' src/plugin_codex_login.c
476found "no-Content-Length rule documented" "Content-Length" README.md 2>/dev/null || pass "README documents the header rule"
477
478# ---------------------------------------------------------------- summary
479section "summary"
480printf ' %s%d passed%s, %s%d failed%s\n' "$C_OK" "$PASS" "$C_0" \
481 "$([ "$FAIL" -eq 0 ] && printf '%s' "$C_OK" || printf '%s' "$C_BAD")" "$FAIL" "$C_0"
482[ "$FAIL" -eq 0 ] || exit 1
483exit 0