scorpiox-bot-plugin-opencode-login
←run.shbash
600 lines · 28 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_opencode_login across all 3 modes.
3#
4# Every check runs against ./plugin_opencode_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 OpenCode session and without a network.
7#
8# What it proves:
9# - --meta is exactly {"name":"opencode","desc":"OpenCode login"} and is
10# reachable 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 credential json, the pending marker and the CLI answer
13# and never emits a token
14# - start returns the CLI's verify_url + user_code; poll walks pending ->
15# done and re-reads state; a dead flow reports failed, not an infinite
16# spinner; cancel clears the marker
17# - refresh re-reads the token through the token CLI and drops the value
18# - the HTML page carries the bot theme handoff, no CDN and no <script src=>
19# - the source has no hard-coded secret, no internal address and no emoji
20#
21# Exit code 0 = everything passed.
22
23set -u
24
25ROOT=$(cd "$(dirname "$0")/.." && pwd)
26cd "$ROOT" || exit 1
27
28BIN=./plugin_opencode_login
29ID=plugin_opencode_login
30PASS=0
31FAIL=0
32
33# A token planted in the fixtures that must never surface in any response.
34SECRET="oc-mock-access-token-must-not-leak"
35REFRESH_SECRET="oc-mock-refresh-token-must-not-leak"
36DEVICE_SECRET="oc-mock-device-code-must-not-leak"
37
38if [ -t 1 ]; then
39 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
40else
41 C_OK=; C_BAD=; C_B=; C_0=
42fi
43pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
44fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
45
46check() { # check <desc> <expected-substring> <actual>
47 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
48 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
49 fi
50}
51
52check_not() { # check_not <desc> <forbidden-substring> <actual>
53 if printf '%s' "$3" | grep -F -q -- "$2"; then
54 fail "$1 (must NOT contain: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)"
55 else pass "$1"
56 fi
57}
58
59section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
60
61# strip CGI headers if present, drop CRs, keep the payload
62body() {
63 printf '%s\n' "$1" | tr -d '\r' | awk '
64 BEGIN { inhdr = 0 }
65 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next }
66 inhdr && $0 == "" { inhdr = 0; next }
67 inhdr { next }
68 { print }
69 '
70}
71
72json_ok() { # json_ok <desc> <json> [python-expression]
73 expr=${3:-True}
74 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
75 pass "$1"
76 else
77 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
78 fi
79}
80
81api() { body "$(QUERY_STRING="$1" $BIN)"; }
82apiraw() { QUERY_STRING="$1" $BIN; }
83
84# ---------------------------------------------------------------- build
85section "build"
86if [ ! -x "$BIN" ]; then
87 echo " building native binary..."
88 gcc -O2 -std=c99 -Wall -Wextra -I src -o "$BIN" src/plugin_opencode_login.c || {
89 fail "native build"; exit 1; }
90fi
91pass "native binary present"
92
93# generated page header must match src/ui.html
94if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
95 pass "src/ui_html.h is in sync with src/ui.html"
96else
97 fail "src/ui_html.h is stale - run tools/gen_ui.py"
98fi
99
100# the page header must not be hand-edited: it is generated from ui.html
101check "ui header is marked generated" \
102 "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
103
104# ---------------------------------------------------------------- fixtures
105FIX=$(mktemp -d 2>/dev/null || mktemp -d -t ocfix)
106trap 'rm -rf "$FIX"' EXIT
107
108NOW=$(date +%s)
109FUT=$((NOW + 86400))
110PAST=$((NOW - 3600))
111
112mkdir -p "$FIX/none" "$FIX/empty" "$FIX/full" "$FIX/expired" "$FIX/alt/.opencode" "$FIX/alt/.config/opencode" "$FIX/pending" "$FIX/env"
113export OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh"
114export OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh"
115export OPENCODE_PENDING_PATH="$FIX/pending/opencode-default.json"
116export OPENCODE_ENV_DIR="$FIX/env"
117
118# empty credentials file (exists but holds no token)
119: > "$FIX/empty/auth.json"
120
121# a live session: token, refresh token, org, future expiry
122printf '{"access_token":"%s","refresh_token":"%s","token_type":"Bearer","expires_in":2591999,"expires_at":%s,"org_id":"org-mock-42"}\n' \
123 "$SECRET" "$REFRESH_SECRET" "$FUT" > "$FIX/full/auth.json"
124
125# an expired session
126printf '{"access_token":"%s","refresh_token":"%s","token_type":"Bearer","expires_at":%s,"org_id":"org-mock-42"}\n' \
127 "$SECRET" "$REFRESH_SECRET" "$PAST" > "$FIX/expired/auth.json"
128
129# the secondary ~/.opencode/token.json layout the spec names
130printf '{"access_token":"%s","expires_at":%s}\n' "$SECRET" "$FUT" > "$FIX/alt/.opencode/token.json"
131
132# The pending device flow marker is written per section, exactly as the CLI
133# writes it, so a test that expects "nothing pending" never sees a leftover.
134
135# ---------------------------------------------------------------- metadata
136section "--meta / discovery"
137META=$($BIN --meta)
138check "--meta via argv" '"name":"opencode"' "$META"
139check "--meta desc" '"desc":"OpenCode login"' "$META"
140check_not "--meta leaks nothing else" "expires" "$META"
141METAENV=$(SX_PLUGIN_META=1 $BIN)
142check "--meta via SX_PLUGIN_META" '"name":"opencode"' "$METAENV"
143json_ok "--meta is a valid JSON object" "$META" "isinstance(d,dict) and d['name']=='opencode' and d['desc']=='OpenCode login'"
144# 1-word title, 14-char desc (the market contract floor)
145check_not "--meta title is one word" '"name":"opencode login"' "$META"
146DESCLEN=$(printf '%s' "OpenCode login" | wc -c)
147if [ "$DESCLEN" -le 15 ]; then pass "desc fits the 15-char limit ($DESCLEN)"; else fail "desc too long ($DESCLEN)"; fi
148
149VERSION=$($BIN --version)
150check "--version reports the id" "plugin_opencode_login 1.0.0" "$VERSION"
151
152# ---------------------------------------------------------------- auth gate
153section "node auth gate"
154export BOT_PASSWORD=test-node-password
155NOAUTH=$(QUERY_STRING="action=status" $BIN)
156check "unauthenticated status is 401" "Status: 401 Unauthorized" "$NOAUTH"
157check "401 body says invalid node password" "invalid node password" "$NOAUTH"
158check_not "401 does not leak the password" "test-node-password" "$NOAUTH"
159for a in start poll cancel refresh; do
160 check "action=$a is gated" "Status: 401" "$(QUERY_STRING="action=$a" $BIN)"
161done
162check "meta stays open without a password" '"name":"opencode"' "$($BIN --meta)"
163check "password via ?pwd= is accepted" '"ok":true' "$(QUERY_STRING="action=status&pwd=test-node-password" $BIN)"
164check "password via X-Bot-Password is accepted" '"ok":true' \
165 "$(HTTP_X_BOT_PASSWORD=test-node-password QUERY_STRING="action=status" $BIN)"
166check "password via Bearer is accepted" '"ok":true' \
167 "$(HTTP_AUTHORIZATION='Bearer test-node-password' QUERY_STRING="action=status" $BIN)"
168check "wrong password still 401s" "Status: 401" "$(QUERY_STRING="action=status&pwd=wrong" $BIN)"
169BODYAUTH=$(printf '{"a":1}' | CONTENT_LENGTH=9 QUERY_STRING="action=status" $BIN)
170check "a POST body does not bypass the gate" "Status: 401" "$BODYAUTH"
171unset BOT_PASSWORD
172
173# ---------------------------------------------------------------- status: no session
174section "status - no session"
175rm -f "$FIX/pending/opencode-default.json"
176export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
177S=$(api "action=status")
178json_ok "status with no credential file is valid JSON" "$S" "d['ok'] is True and d['logged_in'] is False"
179check "no session reports logged_in false" '"logged_in":false' "$S"
180check "no session reports pending false" '"pending":false' "$S"
181check "no session reports has_refresh false" '"has_refresh":false' "$S"
182check "no session reports expires_at 0" '"expires_at":0' "$S"
183check "no session reports expired false" '"expired":false' "$S"
184check "no session names the CLI protocol" '"protocol":"SXLOGIN-MACHINE-V1"' "$S"
185check "no session reports the CLI present" '"cli_present":true' "$S"
186check "no session reports the token CLI" '"token_cli_present":true' "$S"
187check_not "empty status leaks no token" "$SECRET" "$S"
188
189# ---------------------------------------------------------------- status: empty file
190section "status - empty credential file"
191export OPENCODE_CREDS_PATH="$FIX/empty/auth.json"
192S=$(api "action=status")
193json_ok "empty credential file is not a session" "$S" "d['logged_in'] is False"
194check "empty file still reports a path" "$FIX/empty/auth.json" "$S"
195
196# ---------------------------------------------------------------- status: live session
197section "status - live session"
198rm -f "$FIX/pending/opencode-default.json"
199export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
200S=$(api "action=status")
201json_ok "live session is valid JSON" "$S" "d['ok'] is True and d['logged_in'] is True"
202check "live session reports logged_in true" '"logged_in":true' "$S"
203check "live session reports has_refresh" '"has_refresh":true' "$S"
204check "live session reports expired false" '"expired":false' "$S"
205check "live session carries the org account" '"account":"org-mock-42"' "$S"
206check "live session carries org_id" '"org_id":"org-mock-42"' "$S"
207check "live session carries a username" '"username":"org-mock-42"' "$S"
208json_ok "live session expiry is in the future" "$S" "d['expires_in_sec'] > 80000 and d['expires_at'] > 0"
209check "live session names the profile" '"profile":"superopencode"' "$S"
210check_not "status never prints the access token" "$SECRET" "$S"
211check_not "status never prints the refresh token" "$REFRESH_SECRET" "$S"
212check_not "status never uses the word access_token" "access_token" "$S"
213check_not "status never uses the word refresh_token" "refresh_token" "$S"
214
215# ---------------------------------------------------------------- status: expired
216section "status - expired session"
217rm -f "$FIX/pending/opencode-default.json"
218export OPENCODE_CREDS_PATH="$FIX/expired/auth.json"
219S=$(api "action=status")
220json_ok "expired session is still reported" "$S" "d['logged_in'] is True and d['expired'] is True"
221check "expired session flags expired true" '"expired":true' "$S"
222json_ok "expired session reports a negative window" "$S" "d['expires_in_sec'] < 0"
223check_not "expired status leaks no token" "$SECRET" "$S"
224
225# ---------------------------------------------------------------- status: pending marker
226section "status - pending device flow"
227printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \
228 > "$FIX/pending/opencode-default.json"
229export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
230S=$(api "action=status")
231check "a marker file means pending true" '"pending":true' "$S"
232check "pending reports its age" '"pending_age_sec":' "$S"
233check_not "pending status does not leak the device code" "$DEVICE_SECRET" "$S"
234# a stale marker (older than the CLI's 900 s TTL) must not keep the spinner on
235printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$((NOW - 1200))" \
236 > "$FIX/pending/opencode-default.json"
237S=$(api "action=status")
238json_ok "a stale marker is not pending" "$S" "d['pending'] is False"
239rm -f "$FIX/pending/opencode-default.json"
240
241# ---------------------------------------------------------------- status: format=json
242section "format=json is status"
243rm -f "$FIX/pending/opencode-default.json"
244export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
245S=$(api "format=json")
246json_ok "format=json alone returns a status object" "$S" "d['ok'] is True and 'logged_in' in d"
247S=$(api "action=status&format=json")
248json_ok "action and format together still work" "$S" "d['logged_in'] is True"
249S=$(apiraw "action=unknown")
250check "an unknown action is a 400" "Status: 400 Bad Request" "$S"
251check "unknown action names the valid ones" "expected status, start, poll, cancel or refresh" "$S"
252
253# ---------------------------------------------------------------- status: alt path
254section "secondary credential location"
255rm -f "$FIX/pending/opencode-default.json"
256# No OPENCODE_CREDS_PATH override: the plugin must fall back to
257# $HOME/.opencode/token.json when ~/.config/opencode/auth.json is absent.
258unset OPENCODE_CREDS_PATH
259export HOME="$FIX/alt"
260mkdir -p "$FIX/alt/.config/opencode"
261S=$(api "action=status")
262json_ok "the ~/.opencode/token.json fallback is read" "$S" "d['logged_in'] is True"
263check "the fallback path is reported" "$FIX/alt/.opencode/token.json" "$S"
264check_not "the fallback status leaks no token" "$SECRET" "$S"
265# the primary file wins when both exist
266printf '{"access_token":"%s","expires_at":%s,"org_id":"org-primary"}\n' "$SECRET" "$FUT" \
267 > "$FIX/alt/.config/opencode/auth.json"
268S=$(api "action=status")
269check "the primary credential file wins" "org-primary" "$S"
270export HOME=/root
271export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
272
273# ---------------------------------------------------------------- start
274section "start - device flow"
275rm -f "$FIX/pending/opencode-default.json"
276S=$(api "action=start")
277json_ok "start returns a device_code flow" "$S" "d['ok'] is True and d['flow']=='device_code'"
278check "start hands back the verify url" "https://opencode.ai/console/device" "$S"
279check "start hands back the user code" '"user_code":"ABCD-EFGH"' "$S"
280check "start reports pending true" '"pending":true' "$S"
281json_ok "start reports an expiry window" "$S" "d['expires_in'] >= 60"
282check_not "start does not leak the device code" "$DEVICE_SECRET" "$S"
283check_not "start leaks no token" "$SECRET" "$S"
284
285# start when credentials already exist
286export MOCK_START_FAIL=1
287S=$(api "action=start")
288unset MOCK_START_FAIL
289json_ok "an existing session is reported, not a crash" "$S" "d.get('already_logged_in') is True"
290check "existing session tells the user to re-login" "already_logged_in" "$S"
291check "existing session hints at force" "force=1" "$S"
292S=$(api "action=start&force=1")
293check "force=1 starts over an existing session" '"user_code":"ABCD-EFGH"' "$S"
294export MOCK_START_NETFAIL=1
295S=$(api "action=start")
296unset MOCK_START_NETFAIL
297check "a network failure surfaces as an error" '"error":"network"' "$S"
298
299# ---------------------------------------------------------------- poll
300section "poll - pending then done"
301rm -f "$FIX/pending/opencode-default.json"
302printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \
303 > "$FIX/pending/opencode-default.json"
304export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
305S=$(api "action=poll")
306json_ok "poll while waiting is pending" "$S" "d['ok'] is True and d['state']=='pending'"
307check "pending poll says logged_in false" '"logged_in":false' "$S"
308check "pending poll carries an interval" '"interval":5' "$S"
309check_not "pending poll leaks no secret" "$DEVICE_SECRET" "$S"
310
311# approval: the mock CLI writes the credential file and clears the marker
312export MOCK_APPROVE=1
313rm -f "$FIX/full2" ; mkdir -p "$FIX/full2"
314export OPENCODE_CREDS_PATH="$FIX/full2/auth.json"
315S=$(api "action=poll")
316json_ok "poll after approval is done" "$S" "d['ok'] is True and d['state']=='done' and d['logged_in'] is True"
317check "done poll reports a live session" '"logged_in":true' "$S"
318check "done poll carries the fresh expiry" '"expires_in_sec":' "$S"
319check_not "done poll does not print the token" "$SECRET" "$S"
320check_not "done poll does not print the refresh token" "$REFRESH_SECRET" "$S"
321unset MOCK_APPROVE
322rm -f "$FIX/full2/auth.json"
323
324# a denied flow is terminal
325printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \
326 > "$FIX/pending/opencode-default.json"
327export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
328export MOCK_DENY=1
329S=$(api "action=poll")
330unset MOCK_DENY
331json_ok "a denial is reported as a failed state" "$S" "d['ok'] is True and d['state']=='failed'"
332check "a denial names the error" '"error":"denied"' "$S"
333check "a denial clears pending" '"pending":false' "$S"
334
335# no pending marker at all
336rm -f "$FIX/pending/opencode-default.json"
337export MOCK_NO_PENDING=1
338S=$(api "action=poll")
339unset MOCK_NO_PENDING
340json_ok "polling with nothing pending fails cleanly" "$S" "d['state']=='failed'"
341check "nothing-pending explains itself" "run --start first" "$S"
342
343# ---------------------------------------------------------------- cancel
344section "cancel"
345printf '{"device_code":"%s","interval":5,"force":0,"created":%s}\n' "$DEVICE_SECRET" "$NOW" \
346 > "$FIX/pending/opencode-default.json"
347S=$(api "action=cancel")
348json_ok "cancel succeeds" "$S" "d['ok'] is True and d['state']=='cancelled'"
349check "cancel clears pending" '"pending":false' "$S"
350if [ -f "$FIX/pending/opencode-default.json" ]; then
351 fail "cancel removed the marker file"
352else
353 pass "cancel removed the marker file"
354fi
355check_not "cancel leaks no device code" "$DEVICE_SECRET" "$S"
356
357# ---------------------------------------------------------------- refresh
358section "refresh"
359rm -f "$FIX/pending/opencode-default.json"
360export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
361S=$(api "action=refresh")
362json_ok "refresh succeeds on a live session" "$S" "d['ok'] is True and d['refreshed'] is True"
363check "refresh reports the session again" '"logged_in":true' "$S"
364check "refresh keeps the org account" '"account":"org-mock-42"' "$S"
365check_not "refresh never prints the token" "$SECRET" "$S"
366check_not "refresh never prints the refresh token" "$REFRESH_SECRET" "$S"
367
368# refresh with no session
369export OPENCODE_CREDS_PATH="$FIX/none/auth.json"
370S=$(api "action=refresh")
371json_ok "refresh without a session is a clean error" "$S" "d['ok'] is False and d['error']=='not_logged_in'"
372
373# refresh when the token CLI fails
374export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
375export MOCK_TOKEN_FAIL=1
376S=$(api "action=refresh")
377unset MOCK_TOKEN_FAIL
378json_ok "a failing token CLI is a clean error" "$S" "d['ok'] is False and d['error']=='refresh_failed'"
379check_not "a failing refresh leaks no token" "$SECRET" "$S"
380
381# ---------------------------------------------------------------- missing CLIs
382section "missing CLIs"
383rm -f "$FIX/pending/opencode-default.json"
384export OPENCODE_LOGIN_BIN="$FIX/definitely-not-a-binary"
385export OPENCODE_TOKEN_BIN="$FIX/definitely-not-a-binary"
386export OPENCODE_CREDS_PATH="$FIX/full/auth.json"
387S=$(api "action=status")
388json_ok "status survives a missing login CLI" "$S" "d['ok'] is True"
389check "a missing CLI is reported honestly" '"cli_present":false' "$S"
390check "a missing CLI names itself" '"cli_error":"cli_not_found"' "$S"
391check "the file-derived session is still reported" '"logged_in":true' "$S"
392S=$(apiraw "action=start")
393check "start on a missing CLI is cli_unavailable" '"error":"cli_unavailable"' "$S"
394check_not "start on a missing CLI is not a 500" "Status: 5" "$S"
395S=$(api "action=poll")
396check "poll on a missing CLI is cli_unavailable" '"error":"cli_unavailable"' "$S"
397S=$(api "action=refresh")
398check "refresh on a missing CLI is refresh_unavailable" '"error":"refresh_unavailable"' "$S"
399S=$(api "action=cancel")
400check "cancel on a missing CLI still clears pending" '"pending":false' "$S"
401export OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh"
402export OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh"
403
404# ---------------------------------------------------------------- HTML
405section "HTML UI"
406HTML=$(body "$(QUERY_STRING="" $BIN)")
407check "page is a real document" "<!DOCTYPE html>" "$HTML"
408check "page titles the tool" "<title>opencode</title>" "$HTML"
409check "page has the status pill" 'id="pill"' "$HTML"
410check "page has the user badge" 'id="userBadge"' "$HTML"
411check "page has the start button" 'id="btnStartLogin"' "$HTML"
412check "page has the copy button" 'id="btnCopyOpen"' "$HTML"
413check "page has the user code box" 'id="userCode"' "$HTML"
414check "page has the poll indicator" 'id="pollLabel"' "$HTML"
415check "page has the cancel button" 'id="btnCancel"' "$HTML"
416check "page has the refresh button" 'id="btnRefresh"' "$HTML"
417check "page has the re-login button" 'id="btnRelogin"' "$HTML"
418check "page names the device flow" "Device Flow" "$HTML"
419check "page carries the copy label" "Copy Code" "$HTML"
420check "page uses the bot theme handoff" "sx-theme" "$HTML"
421check "page reads the theme before paint" "data-theme" "$HTML"
422check "page hides its toggle when embedded" "embed-hide" "$HTML"
423check "page uses the two-route API helper" "plugin_opencode_login" "$HTML"
424check "page fluid down to 390px" "max-width:480px" "$HTML"
425check_not "page loads no CDN script" "<script src=" "$HTML"
426check_not "page references no cdnjs" "cdnjs" "$HTML"
427check_not "page makes no third-party fetch" "googleapis.com" "$HTML"
428check_not "page carries no rocket emoji" "\xf0\x9f\x9a\x80" "$HTML"
429check_not "page never mentions a token variable" "access_token" "$HTML"
430check_not "page hardcodes no LAN address" "192.168." "$HTML"
431check_not "page hardcodes no localhost port" "127.0.0.1" "$HTML"
432
433# the served page must be parseable and every JS id must exist in the markup
434if command -v python3 >/dev/null 2>&1; then
435 printf '%s' "$HTML" > "$FIX/page.html"
436 if python3 - "$FIX/page.html" <<'PY'
437import re, sys
438html = open(sys.argv[1], encoding='utf-8').read()
439ids = set(re.findall(r'id="([^"]+)"', html))
440missing = [i for i in re.findall(r"\$\('([^']+)'\)", html) if i not in ids]
441sys.exit(1 if missing else 0)
442PY
443 then pass "every JS element id exists in the markup"
444 else fail "the page JS references an element id that is not in the HTML"; fi
445
446 if python3 - "$FIX/page.html" <<'PY'
447import sys
448html = open(sys.argv[1], encoding='utf-8').read()
449# balanced tags for the containers the page actually builds
450for tag in ("div", "span", "button", "script", "style"):
451 opens = html.count("<%s" % tag)
452 closes = html.count("</%s>" % tag)
453 if opens != closes:
454 sys.stderr.write("%s: %d open vs %d close\n" % (tag, opens, closes))
455 sys.exit(1)
456sys.exit(0)
457PY
458 then pass "the page markup is balanced"
459 else fail "the page markup has unbalanced tags"; fi
460fi
461
462# ---------------------------------------------------------------- source hygiene
463section "source hygiene"
464check_not "source has no GitHub token" "ghp_" "$(cat src/plugin_opencode_login.c)"
465check_not "source has no scorpiox-git PAT" "3ef2c00" "$(cat src/plugin_opencode_login.c)"
466# the needle is split so this file never contains the string it looks for
467check_not "source has no default password" "xbo""xone" "$(cat src/plugin_opencode_login.c src/ui.html tests/mock_login.sh tests/mock_token.sh)"
468check_not "source has no internal address" "192.168." "$(cat src/plugin_opencode_login.c src/ui.html)"
469check_not "source has no 10.x address" "10.0." "$(cat src/plugin_opencode_login.c src/ui.html)"
470check_not "source has no host name" "macmini" "$(cat src/plugin_opencode_login.c src/ui.html)"
471check_not "source has no device secret" "$DEVICE_SECRET" "$(cat src/plugin_opencode_login.c src/ui.html)"
472check_not "no Content-Length header is emitted" "Content-Length" "$(cat src/plugin_opencode_login.c)"
473
474# no emoji anywhere in the shipped sources (byte-level check, not a regex guess)
475if python3 - src/plugin_opencode_login.c src/ui.html src/bot_theme_plugin.h <<'PY'
476import sys, unicodedata
477bad = []
478for path in sys.argv[1:]:
479 for n, line in enumerate(open(path, encoding='utf-8'), 1):
480 for ch in line:
481 o = ord(ch)
482 if o < 0x2000:
483 continue
484 if 0x2190 <= o <= 0x21FF: # arrows are typography, not emoji
485 continue
486 if unicodedata.category(ch) in ('So', 'Sk') or 0x1F000 <= o <= 0x1FAFF:
487 bad.append('%s:%d %r' % (path, n, ch))
488if bad:
489 print('\n'.join(bad[:10]))
490 sys.exit(1)
491PY
492then pass "no emoji in source, page or theme header"
493else fail "emoji found in the shipped sources"; fi
494
495# plugin.json sidecar must carry the market contract
496if command -v python3 >/dev/null 2>&1; then
497 if python3 - plugin.json <<'PY'
498import json, sys
499d = json.load(open(sys.argv[1]))
500want = {
501 "slug": "opencode-login",
502 "id": "plugin_opencode_login",
503 "name": "opencode",
504 "desc": "OpenCode login",
505 "title": "OpenCode Login",
506 "category": "devtools",
507 "license": "MIT",
508}
509for k, v in want.items():
510 if d.get(k) != v:
511 sys.stderr.write("%s: %r != %r\n" % (k, d.get(k), v))
512 sys.exit(1)
513if d.get("capabilities") != ["credentials_read", "oauth_device_flow"]:
514 sys.stderr.write("capabilities wrong\n"); sys.exit(1)
515if "never" not in d.get("trust_notice", "").lower():
516 sys.stderr.write("trust_notice must promise what never leaves the node\n"); sys.exit(1)
517sys.exit(0)
518PY
519 then pass "plugin.json carries the full market contract"
520 else fail "plugin.json does not match the contract"; fi
521fi
522
523# ---------------------------------------------------------------- extra builds
524section "cross-target builds"
525if command -v musl-gcc >/dev/null 2>&1; then
526 if musl-gcc -O2 -std=c99 -static -I src -o "$FIX/musl-bin" src/plugin_opencode_login.c 2>/dev/null; then
527 pass "static musl build"
528 MUSLMETA=$("$FIX/musl-bin" --meta)
529 check "the musl binary reports the same metadata" '"name":"opencode"' "$MUSLMETA"
530 MUSLS=$(HOME=/root QUERY_STRING="action=status" "$FIX/musl-bin" >/dev/null 2>&1 && echo ran)
531 check "the musl binary runs a status call" "ran" "$MUSLS"
532 else fail "static musl build"; fi
533else
534 echo " skip musl-gcc not installed"
535fi
536
537if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
538 if x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -o "$FIX/win-bin.exe" src/plugin_opencode_login.c 2>/dev/null; then
539 pass "MinGW-w64 build"
540 if [ "$(head -c 2 "$FIX/win-bin.exe")" = "MZ" ]; then
541 pass "the Windows build has a real PE header"
542 else fail "the Windows build is not a PE (missing MZ)"; fi
543 else fail "MinGW-w64 build"; fi
544else
545 echo " skip x86_64-w64-mingw32-gcc not installed"
546fi
547
548if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
549 if aarch64-linux-gnu-gcc -O2 -std=c99 -static -I src -o "$FIX/arm-bin" src/plugin_opencode_login.c 2>/dev/null; then
550 pass "static aarch64 build"
551 # an aarch64 ELF cannot be exec'd on an x86_64 host, so the artifact is
552 # verified by its header instead of by running it.
553 if python3 - "$FIX/arm-bin" <<'PY'
554import sys
555b = open(sys.argv[1], "rb").read(20)
556# ELF magic, class 2 (64-bit), little endian; e_machine sits at offset 18
557# (e_type is at 16) and 183 = AArch64.
558ok = b[:4] == b"\x7fELF" and b[4] == 2 and b[5] == 1
559ok = ok and int.from_bytes(b[18:20], "little") == 183
560sys.exit(0 if ok else 1)
561PY
562 then pass "the arm artifact is a little-endian aarch64 ELF"
563 else fail "the arm artifact is not an aarch64 ELF"; fi
564 else fail "static aarch64 build"; fi
565else
566 echo " skip aarch64-linux-gnu-gcc not installed"
567fi
568
569# _FORTIFY_SOURCE=2: a hardened build must still run, because dist packaging on
570# some distros compiles with it defined by default.
571if gcc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$FIX/fortify-bin" src/plugin_opencode_login.c 2>/dev/null; then
572 FORTMETA=$("$FIX/fortify-bin" --meta)
573 check "a _FORTIFY_SOURCE=2 build runs --meta clean" '"name":"opencode"' "$FORTMETA"
574 FORTSTAT=$(OPENCODE_CREDS_PATH="$FIX/full/auth.json" OPENCODE_PENDING_PATH="$FIX/pending/none.json" \
575 OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" \
576 OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" \
577 OPENCODE_ENV_DIR="$FIX/env" \
578 QUERY_STRING="action=status" "$FIX/fortify-bin" | tr -d '\r' | tail -1)
579 check "a _FORTIFY_SOURCE=2 build serves status" '"logged_in":true' "$FORTSTAT"
580 FORTSTART=$(OPENCODE_PENDING_PATH="$FIX/pending/none.json" \
581 OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" \
582 OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" \
583 OPENCODE_ENV_DIR="$FIX/env" \
584 QUERY_STRING="action=start" "$FIX/fortify-bin" | tr -d '\r' | tail -1)
585 check "a _FORTIFY_SOURCE=2 build serves start" '"flow":"device_code"' "$FORTSTART"
586 FORTBAD=$(OPENCODE_PENDING_PATH="$FIX/pending/none.json" \
587 OPENCODE_LOGIN_BIN="$ROOT/tests/mock_login.sh" \
588 OPENCODE_TOKEN_BIN="$ROOT/tests/mock_token.sh" \
589 OPENCODE_ENV_DIR="$FIX/env" \
590 QUERY_STRING="action=zzz" "$FIX/fortify-bin" | tr -d '\r' | head -1)
591 check "a _FORTIFY_SOURCE=2 build rejects a bad action" "Status: 400" "$FORTBAD"
592else
593 fail "_FORTIFY_SOURCE=2 build"
594fi
595
596# ---------------------------------------------------------------- summary
597section "summary"
598printf ' %s%d passed, %d failed%s\n' "$C_B" "$PASS" "$FAIL" "$C_0"
599[ "$FAIL" -eq 0 ] || exit 1
600exit 0