plugin_claudecode_login 1.0.0: clean-room Claude Code OAuth PKCE login and token manager
Single clean-room C99 binary, zero dependencies, no OAuth client secret. Serves --meta discovery, a JSON action API (status/start/finish/cancel/ refresh) and a responsive dark/light HTML UI that carries the SCORPIOX BOT theme tokens and handoff. The plugin drives scorpiox-claudecode-login and scorpiox-claudecode-refreshtoken in machine mode and reads only credential metadata: no token value is ever printed, logged or returned, and the refresh CLI's payload is discarded in favour of a re-read of the file. tests/run.sh: 116 offline assertions, 0 failures.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-12 15:15:23
Commitf99e9db3
Changed files
.gitignore+16−0■■■■■
LICENSE+21−0■■■■■
Makefile+80−0■■■■■
README.md+126−0■■■■■
build.ps1+51−0■■■■■
plugin.json+16−0■■■■■
release-dist.sh+365−0■■■■■
src/bot_theme_plugin.h+129−0■■■■■
src/plugin_claudecode_login.c+1607−0■■■■■
src/ui.html+399−0■■■■■
src/ui_html.h+407−0■■■■■
tests/mock_login.sh+73−0■■■■■
tests/mock_refresh.sh+38−0■■■■■
tests/run.sh+370−0■■■■■
tools/gen_ui.py+105−0■■■■■
15 files+3803−0
Diff
.gitignore+16−0■■■■■
11new file mode 100644
index 0000000..2a8302a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,16 @@
1+# build artifacts
2+/plugin_claudecode_login
3+/plugin_claudecode_login.exe
4+/plugin_claudecode_login.musl
5+/plugin_claudecode_login.arm64
6+/plugin_claudecode_login.macos-arm64
7+/plugin_claudecode_login.macos-x86_64
8+bin/
9+
10+# test scratch
11+*.tmp
12+/tests/fixtures-out/
13+
14+# python tooling
15+__pycache__/
16+*.pyc
LICENSE+21−0■■■■■
11new file mode 100644
index 0000000..ef80120
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+80−0■■■■■
11new file mode 100644
index 0000000..33ce0b6
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,80 @@
1+# plugin_claudecode_login - SCORPIOX BOT open-source Claude Code login for your node
2+#
3+# Targets:
4+# make native build -> ./plugin_claudecode_login
5+# make musl static musl x86_64 -> ./plugin_claudecode_login.musl
6+# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_claudecode_login.arm64
7+# make win64 MinGW-w64 static -> ./plugin_claudecode_login.exe
8+# make macos Apple clang -> ./plugin_claudecode_login (run this on macOS)
9+# make ui regenerate src/ui_html.h from src/ui.html
10+# make test build + run tests/run.sh
11+# make e2e build + run tests/e2e.py (Playwright)
12+# make clean
13+
14+CC ?= cc
15+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src
16+MUSL_CC ?= musl-gcc
17+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static
18+ARM_CC ?= aarch64-linux-gnu-gcc
19+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static
20+WIN_CC ?= x86_64-w64-mingw32-gcc
21+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static
22+SRC := src/plugin_claudecode_login.c
23+UI_SRC := src/ui.html
24+UI_HDR := src/ui_html.h
25+BIN := plugin_claudecode_login
26+EXE := plugin_claudecode_login.exe
27+
28+.PHONY: all native musl arm64 win64 macos ui test e2e clean help
29+
30+all: native
31+
32+$(UI_HDR): $(UI_SRC) tools/gen_ui.py
33+ @echo "==> regenerating $(UI_HDR)"
34+ python3 tools/gen_ui.py
35+
36+ui: $(UI_HDR)
37+
38+native: $(BIN)
39+
40+$(BIN): $(SRC) $(UI_HDR)
41+ @echo "==> native build ($(CC))"
42+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
43+
44+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
45+musl: $(SRC) $(UI_HDR)
46+ @echo "==> static musl build ($(MUSL_CC))"
47+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
48+
49+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
50+arm64: $(SRC) $(UI_HDR)
51+ @echo "==> static arm64 build ($(ARM_CC))"
52+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
53+
54+# Native Win64 static PE - runs on any Windows 10/11 x64 node
55+win64: $(SRC) $(UI_HDR)
56+ @echo "==> MinGW-w64 build ($(WIN_CC))"
57+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
58+
59+# Apple clang build (run this on macOS)
60+macos: $(SRC) $(UI_HDR)
61+ @echo "==> Apple clang build"
62+ clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -o $(BIN) $(SRC)
63+
64+install: $(BIN)
65+ @dest="$${HOME}/.scorpiox/plugins"; [ -d /workspace ] && dest="/workspace/.scorpiox/plugins"; \
66+ mkdir -p "$$dest" && cp $(BIN) "$$dest/$(BIN)" && chmod 0755 "$$dest/$(BIN)" && \
67+ echo "==> installed $$dest/$(BIN)"
68+
69+test: $(BIN)
70+ sh tests/run.sh
71+
72+e2e: $(BIN)
73+ python3 tests/e2e.py
74+
75+clean:
76+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64
77+ rm -rf tests/__pycache__
78+
79+help:
80+ @sed -n '2,16p' $(MAKEFILE_LIST)
README.md+126−0■■■■■
11new file mode 100644
index 0000000..83e783b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,126 @@
1+# plugin_claudecode_login
2+
3+**Claude Code Login** - a SCORPIOX BOT open-source plugin that manages the Claude
4+Code OAuth PKCE session on your node: start a login, submit the authorization
5+code, watch the token expiry, list named accounts, and refresh the token on
6+demand.
7+
8+One clean-room C99 binary, zero dependencies, no OAuth client secret, and no
9+token ever leaves the node - or even leaves the child process that fetched it.
10+
11+```
12+--meta {"name":"claude","desc":"Claude login"}
13+?action=status session state, expiry, accounts (JSON)
14+?action=start begin the PKCE flow -> auth_url
15+?action=finish&code=<code|url> exchange the pasted code
16+?action=cancel drop the pending flow
17+?action=refresh refresh the token now
18+?format=json same as action=status
19+GET (no action) responsive dark/light HTML UI
20+```
21+
22+## Design: the plugin drives the CLI, it never speaks TLS
23+
24+A Claude Code PKCE exchange is an HTTPS POST that carries a client identity. A
25+public clean-room repository can never carry an OAuth client secret, so this
26+plugin does not open a socket at all.
27+
28+Instead it drives the login tools that ship with SCORPIOX CODE through their
29+**machine mode** - the documented, non-interactive contract for callers that
30+cannot hold a TTY:
31+
32+| child process | arguments | purpose |
33+|---|---|---|
34+| `scorpiox-claudecode-login` | `--status`, `--start`, `--finish <code>`, `--cancel` | the PKCE flow |
35+| `scorpiox-claudecode-refreshtoken` | `--credentials-file <path> --force` | the refresh-token grant |
36+
37+Both print human progress on stdout and then exactly one JSON line, so the
38+plugin takes the **last line that starts with `{`** and ignores the rest. The
39+refresh CLI's payload is read into a buffer and then discarded: the response is
40+built from a re-read of the credential file, never from what the CLI printed.
41+
42+The plugin reads only these files, and only metadata out of them:
43+
44+```
45+~/.claude/.credentials.json claudeAiOauth block
46+~/.claude/accounts/<name>.json named accounts (same schema)
47+~/.claude/.login-pending/claudecode-<n>.json pending PKCE state
48+~/.claude/scorpiox-env/claude_code.txt PROVIDER / MODEL profile
49+```
50+
51+`accessToken` and `refreshToken` are read into a small **presence-only** buffer
52+and thrown away. No response contains a token value, a token prefix, or the key
53+name `accessToken`. `tests/run.sh` pins that with fixtures built from realistic
54+token strings.
55+
56+## Environment overrides (all optional, all used by the test suite)
57+
58+| variable | default | meaning |
59+|---|---|---|
60+| `CLAUDE_CREDS_PATH` | `~/.claude/.credentials.json` | credentials file; also anchors the sibling paths |
61+| `CLAUDE_ACCOUNTS_DIR` | `~/.claude/accounts` | named account directory |
62+| `CLAUDE_PENDING_DIR` | `~/.claude/.login-pending` | pending-flow directory |
63+| `CLAUDE_ENV_DIR` | `~/.claude/scorpiox-env` | profile directory |
64+| `CLAUDE_LOGIN_BIN` | `scorpiox-claudecode-login` | login CLI |
65+| `CLAUDE_REFRESH_BIN` | `scorpiox-claudecode-refreshtoken` | refresh CLI |
66+
67+A relocated `CLAUDE_CREDS_PATH` implies a relocated `~/.claude` tree: the same
68+CLI writes all four files into one directory, so reading one from the override
69+and the rest from `$HOME` reports an empty state for a live session.
70+
71+## Auth
72+
73+The node API on `:8150` must never be open to the LAN. `--meta` stays
74+unauthenticated so discovery works; every other route requires
75+`X-Bot-Password`, `Authorization: Bearer <pwd>`, or `?pwd=` when the node has
76+`BOT_PASSWORD` set.
77+
78+```bash
79+curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8150/plugin_claudecode_login
80+# 401
81+```
82+
83+## Build
84+
85+```bash
86+make # native -> ./plugin_claudecode_login
87+make musl # static musl x86_64 (universal Linux artifact)
88+make arm64 # static aarch64 (Raspberry Pi 5 / ARM64 servers)
89+make win64 # MinGW-w64 static PE
90+make macos # Apple clang (run on macOS)
91+make test # build + tests/run.sh
92+make ui # regenerate src/ui_html.h from src/ui.html
93+```
94+
95+`make ui` is required after editing `src/ui.html`: `tools/gen_ui.py` turns the
96+page into a C string with two control-byte placeholders (`0x01` = the bot theme
97+prepaint + token block, `0x02` = the theme handoff script). Keep the palette in
98+`src/bot_theme_plugin.h` only - it is a trimmed copy of the bot's own theme, so
99+the plugin looks like part of the bot in dark and light, in a modal, in the Chat
100+floating window and in its own tab.
101+
102+## Install on a node
103+
104+```bash
105+make install # ~/.scorpiox/plugins, or /workspace/.scorpiox/plugins
106+```
107+
108+or let the marketplace do it - `https://bot.scorpiox.net/settings?sec=plugins`
109+installs a prebuilt binary, `?mode=source` clones this repo and compiles it on
110+the node.
111+
112+## Security notes
113+
114+- Every child-process argument is single-quoted for `popen` (`shell_quote_into`),
115+ and an authorization code is validated against a strict alphabet first, so a
116+ pasted `$(...)` or `;` payload is refused before it can reach a shell.
117+- A pasted redirect URL is accepted: `code=` is extracted before validation, so a
118+ real paste (which always carries `&state=`) is not rejected.
119+- No `Content-Length` header is ever emitted (Caddy 502 rule).
120+- The page loads no CDN, no `<script src=`, no external asset; CSP is
121+ `default-src 'none'` with inline script/style only.
122+- No emoji anywhere in the source, the page or the JSON.
123+
124+## License
125+
126+MIT License. Copyright (c) 2026 SCORPIOX INC.
build.ps1+51−0■■■■■
11new file mode 100644
index 0000000..d907f49
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,51 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_claudecode_login
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_claudecode_login.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+
9+$ErrorActionPreference = "Stop"
10+$ScriptDir = $PSScriptRoot
11+Push-Location $ScriptDir
12+try {
13+ $Src = Join-Path $ScriptDir "src\plugin_claudecode_login.c"
14+ $Out = Join-Path $ScriptDir "plugin_claudecode_login.exe"
15+ $Cc = "x86_64-w64-mingw32-gcc"
16+
17+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
18+
19+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
20+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
21+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
22+ $Cc = "C:\gcc16\bin\gcc.exe"
23+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
24+ $Cc = "gcc"
25+ } else {
26+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
27+ }
28+ }
29+
30+ # Regenerate the page header so the binary always matches src/ui.html.
31+ if (Get-Command python -ErrorAction SilentlyContinue) {
32+ python tools\gen_ui.py
33+ }
34+
35+ Write-Host "==> building plugin_claudecode_login.exe with $Cc"
36+ & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src
37+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
38+
39+ if (-not (Test-Path $Out)) { throw "build produced no output" }
40+
41+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
42+ $bytes = [System.IO.File]::ReadAllBytes($Out)
43+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
44+ throw "output is not a PE executable (missing MZ header)"
45+ }
46+
47+ Write-Host "==> ok: $Out ($($bytes.Length) bytes)"
48+ Write-Host " smoke test: .\plugin_claudecode_login.exe --meta"
49+} finally {
50+ Pop-Location
51+}
plugin.json+16−0■■■■■
11new file mode 100644
index 0000000..ba43dc5
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,16 @@
1+{
2+ "slug": "claudecode-login",
3+ "id": "plugin_claudecode_login",
4+ "title": "Claude Code Login",
5+ "summary": "Zero-dependency Claude Code OAuth PKCE login and session token manager for your node. Starts the PKCE flow, takes the pasted authorization code, runs the exchange through the node's own login CLI, then reports session state, token expiry and the named account files - and refreshes the token on demand. The plugin holds no OAuth client secret and never prints, logs or returns a token: it drives the CLI that ships with SCORPIOX CODE and reads only the credential and profile files that CLI writes.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "capabilities": [
9+ "spawn_login_cli",
10+ "read_credentials_metadata",
11+ "network_via_login_cli"
12+ ],
13+ "trust_notice": "Executes native C code on your node. It runs scorpiox-claudecode-login and scorpiox-claudecode-refreshtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to Claude over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only ~/.claude/.credentials.json, ~/.claude/accounts/, ~/.claude/.login-pending/ and ~/.claude/scorpiox-env/claude_code.txt, and every response reports token presence and expiry only - never a token value.",
14+ "author": "SCORPIOX INC",
15+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-claudecode-login"
16+}
release-dist.sh+365−0■■■■■
11new file mode 100755
index 0000000..5f1bdb8
--- /dev/null
+++ b/release-dist.sh
@@ -0,0 +1,365 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_claudecode_login to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+# ./release-dist.sh --standalone # use this script even if the CLI is installed
27+# # (needed for plugins that link extra Win32 libs,
28+# # which the CLI's fixed link line cannot express)
29+
30+set -euo pipefail
31+
32+SLUG="claudecode-login"
33+ID="plugin_claudecode_login"
34+VERSION="1.0.0"
35+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --standalone) STANDALONE=1 ;;
47+ --dry-run) DRY_RUN=1 ;;
48+ --no-macos) DO_MACOS=0 ;;
49+ --no-mirror) DO_MIRROR=0 ;;
50+ -h|--help) sed -n '2,32p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition - otherwise this file's own detector patterns (and the
90+# test suite's identical checks) read as findings in every historical revision of
91+# them. A real secret on any other line still hits.
92+git log -p --all 2>/dev/null \
93+ | grep -v '^Author: ' \
94+ | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \
95+ > "$SCAN_TMP" || : > "$SCAN_TMP"
96+HITS=0
97+scan() { # scan <label> <regex>
98+ local out
99+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
100+ if [ -n "$out" ]; then
101+ printf ' \033[31mHIT\033[0m %s\n' "$1"
102+ printf '%s\n' "$out" | sed 's/^/ /'
103+ HITS=$((HITS + 1))
104+ else
105+ printf ' ok %s\n' "$1"
106+ fi
107+}
108+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
109+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
110+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
111+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
112+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
113+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
114+scan "hard-coded ssh password" 'sshpass -p [^"$]'
115+P_ROOT="/codebases"
116+P_PICOBOT="${P_ROOT}/pico""bot"
117+P_WT=".work""trees"
118+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
119+scan "run-token env assignment" 'RUNNER_'"PASS="
120+if [ "$HITS" -ne 0 ]; then
121+ die "secret scan found $HITS problem(s) - refusing to publish"
122+fi
123+echo " clean: 0 hits"
124+
125+# ---------------------------------------------------------------- 2. build
126+say "2/7 build targets"
127+
128+# linux-x86_64 (glibc, native)
129+if command -v cc >/dev/null 2>&1; then
130+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed"
131+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
132+else
133+ die "no native cc found"
134+fi
135+
136+# linux-x86_64-musl (fully static - the universal Linux artifact)
137+if command -v musl-gcc >/dev/null 2>&1; then
138+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -Wno-format-truncation -I src -o "$STAGE/$ID.musl" src/$ID.c \
139+ || die "musl build failed"
140+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
141+else
142+ echo " skip linux-x86_64-musl (no musl-gcc)"
143+fi
144+
145+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
146+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
147+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -Wno-format-truncation -I src -o "$STAGE/$ID.arm64" src/$ID.c \
148+ || die "arm64 build failed"
149+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
150+else
151+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
152+fi
153+
154+# windows-x86_64 (static PE)
155+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
156+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -Wno-format-truncation \
157+ -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
158+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
159+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
160+else
161+ echo " skip windows-x86_64 (no MinGW cross compiler)"
162+fi
163+
164+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
165+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
166+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
167+ MAC_USER="${MAC_USER:-$(whoami)}"
168+ MAC_DIR="/tmp/${ID}-mac-$$"
169+ echo " building macOS legs on $MAC_HOST"
170+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
171+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
172+ if [ -n "${MAC_PASS:-}" ]; then
173+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
174+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
175+ fi
176+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
177+ tar -czf "$STAGE/src.tgz" src
178+ if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \
179+ && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then
180+ # Build straight from the uploaded file - no src/ tree on the remote.
181+ for slice in arm64 x86_64; do
182+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
183+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -arch $slice -o $ID.$slice src/$ID.c" \
184+ 2>/dev/null; then
185+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
186+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
187+ else
188+ echo " warn: macos-$slice build failed on $MAC_HOST"
189+ fi
190+ done
191+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
192+ else
193+ echo " warn: could not upload source to $MAC_HOST"
194+ fi
195+ else
196+ echo " warn: cannot reach macOS builder $MAC_HOST"
197+ fi
198+else
199+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
200+fi
201+
202+# ---------------------------------------------------------------- 3. manifest
203+say "3/7 manifest + checksums"
204+
205+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
206+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
207+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
208+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
209+
210+target_meta() { # target_meta <key> <file> <format> <relpath>
211+ local key="$1" file="$2" fmt="$3" rel="$4"
212+ [ -f "$file" ] || return 0
213+ local sha size
214+ sha=$(sha256sum "$file" | awk '{print $1}')
215+ size=$(wc -c < "$file" | tr -d ' ')
216+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
217+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
218+}
219+
220+{
221+ printf '{\n'
222+ printf ' "slug": "%s",\n' "$SLUG"
223+ printf ' "id": "%s",\n' "$ID"
224+ printf ' "name": "claude",\n'
225+ printf ' "desc": "Claude login",\n'
226+ printf ' "title": "Claude Code Login",\n'
227+ printf ' "summary": "Zero-dependency Claude Code OAuth PKCE login and session token manager for your node. Starts the PKCE flow, takes the pasted authorization code, runs the exchange through the node own login CLI, then reports session state, token expiry and the named account files - and refreshes the token on demand. The plugin holds no OAuth client secret and never prints, logs or returns a token: it drives the CLI that ships with SCORPIOX CODE and reads only the credential and profile files that CLI writes.",\n'
228+ printf ' "category": "devtools",\n'
229+ printf ' "version": "%s",\n' "$VERSION"
230+ printf ' "license": "MIT",\n'
231+ printf ' "trust_notice": "Executes native C code on your node. It runs scorpiox-claudecode-login and scorpiox-claudecode-refreshtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to Claude over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only the Claude Code credential file, the named account files, the login-pending marker and the claude_code profile, and every response reports token presence and expiry only - never a token value.",\n'
232+ printf ' "capabilities": ["spawn_login_cli", "read_credentials_metadata", "network_via_login_cli"],\n'
233+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
234+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
235+ printf ' "git_commit": "%s",\n' "$COMMIT"
236+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
237+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
238+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
239+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
240+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
241+ printf ' "targets": {\n'
242+ first=1
243+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
244+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
245+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
246+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
247+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
248+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
249+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
250+ printf '\n }\n}\n'
251+} > "$STAGE/manifest.json"
252+
253+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
254+ || die "generated manifest.json is not valid JSON"
255+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
256+
257+# SHA256SUMS - relative paths, exactly as published
258+( cd "$STAGE"
259+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
260+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
261+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
262+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
263+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
264+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
265+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
266+ true ) > "$STAGE/SHA256SUMS"
267+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
268+
269+# ---------------------------------------------------------------- 4. stage
270+say "4/7 stage tree"
271+PKG="$STAGE/pkg"
272+mkdir -p "$PKG"
273+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
274+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
275+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
276+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
277+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
278+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
279+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
280+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
281+
282+if [ "$DRY_RUN" -eq 1 ]; then
283+ say "dry run - leaving the staging tree in $PKG"
284+ trap - EXIT
285+ exit 0
286+fi
287+
288+# ---------------------------------------------------------------- 5. upload
289+say "5/7 upload to the dist server"
290+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
291+SSH=(ssh -o StrictHostKeyChecking=no)
292+SCP=(scp -o StrictHostKeyChecking=no)
293+if [ -n "$DIST_PASS" ]; then
294+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
295+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
296+fi
297+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
298+
299+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
300+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
301+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
302+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
303+# OpenSSH 9 refuses to scp a bare "." source.
304+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
305+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
306+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
307+ || die "remote extract failed"
308+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
309+
310+# latest.json = copy of this version's manifest
311+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
312+ || die "latest.json update failed"
313+echo " updated bot-plugins/$SLUG/latest.json"
314+
315+# index.json - merge, preserving every sibling <slug>/latest.json
316+say "index.json merge"
317+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
318+import json, os, sys, glob
319+slug = sys.argv[1]
320+entries = {}
321+for p in sorted(glob.glob('*/latest.json')):
322+ s = os.path.dirname(p)
323+ try:
324+ entries[s] = json.load(open(p))
325+ except Exception:
326+ pass
327+index = {
328+ 'ok': True,
329+ 'service': 'bot-plugins-dist',
330+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
331+ 'count': len(entries),
332+ 'slugs': sorted(entries),
333+ 'plugins': [entries[k] for k in sorted(entries)],
334+}
335+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
336+os.replace('index.json.tmp', 'index.json')
337+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
338+PY" || die "index.json merge failed"
339+
340+# ---------------------------------------------------------------- 6. mirror
341+say "6/7 plugingit mirror"
342+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
343+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
344+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
345+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
346+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
347+ echo " mirrored to $PLUGINGIT_REMOTE"
348+else
349+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
350+fi
351+
352+# ---------------------------------------------------------------- 7. verify
353+say "7/7 verify"
354+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
355+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
356+if [ "$CODE" = "200" ]; then
357+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
358+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
359+else
360+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
361+fi
362+
363+printf '\n\033[1mrelease complete\033[0m\n'
364+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
365+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/bot_theme_plugin.h+129−0■■■■■
11new file mode 100644
index 0000000..0dd243b
--- /dev/null
+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/plugin_claudecode_login.c+1607−0■■■■■
11new file mode 100644
index 0000000..c7bad2c
--- /dev/null
+++ b/src/plugin_claudecode_login.c
@@ -0,0 +1,1607 @@
1+/*
2+ * plugin_claudecode_login - SCORPIOX BOT open-source Claude Code OAuth PKCE
3+ * login and session token manager for your node.
4+ *
5+ * A single clean-room C99 binary that serves THREE modes:
6+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
7+ * 2. ?action=... / ?format=json -> JSON node API
8+ * 3. GET (default) -> responsive HTML UI
9+ *
10+ * DESIGN NOTE (why there is no TLS and no OAuth client secret here): a Claude
11+ * Code OAuth PKCE code exchange is an HTTPS POST that carries a client
12+ * identity. A public clean-room repository must never carry such a secret, so
13+ * this plugin does not speak TLS at all. It drives the node's own SCORPIOX CODE
14+ * login CLI, exactly the way the machine-mode contract intends
15+ * (--status / --start / --finish / --cancel, one JSON line per call), and it
16+ * reads only the credential files that CLI writes:
17+ *
18+ * ~/.claude/.credentials.json (claudeAiOauth block)
19+ * ~/.claude/accounts/<name>.json (named accounts)
20+ * ~/.claude/.login-pending/claudecode-<name>.json (pending PKCE flow)
21+ * ~/.claude/scorpiox-env/claude_code.txt (PROVIDER/MODEL profile)
22+ *
23+ * Every path and both binaries are overridable for deterministic offline tests:
24+ *
25+ * CLAUDE_CREDS_PATH credentials file (also anchors the sibling paths)
26+ * CLAUDE_ACCOUNTS_DIR directory holding <name>.json account files
27+ * CLAUDE_PENDING_DIR directory holding the pending flow files
28+ * CLAUDE_ENV_DIR profile directory (claude_code.txt)
29+ * CLAUDE_LOGIN_BIN login CLI (default scorpiox-claudecode-login)
30+ * CLAUDE_REFRESH_BIN refresh CLI (default scorpiox-claudecode-refreshtoken)
31+ *
32+ * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. Every response reports token
33+ * presence and expiry only. The refresh action discards the payload its CLI
34+ * prints and reports only success/failure plus the new expiry.
35+ *
36+ * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
37+ * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
38+ * scorpiox-server on the node.
39+ *
40+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
41+ */
42+
43+/* Must come before every include on Windows: MinGW defaults to 0x502
44+ * (Server 2003), which hides the Win7+ APIs and the path helpers. */
45+#if defined(_WIN32) && !defined(_WIN32_WINNT)
46+# define _WIN32_WINNT 0x0601
47+#endif
48+
49+#if !defined(_WIN32)
50+# define _POSIX_C_SOURCE 200809L
51+# define _DEFAULT_SOURCE 1
52+# if defined(__APPLE__)
53+# define _DARWIN_C_SOURCE 1
54+# endif
55+#endif
56+
57+#include <stdio.h>
58+#include <stdlib.h>
59+#include <string.h>
60+#include <ctype.h>
61+#include <errno.h>
62+#include <time.h>
63+#include <stdarg.h>
64+
65+#if defined(_WIN32)
66+# define WIN32_LEAN_AND_MEAN
67+# include <windows.h>
68+# include <direct.h>
69+# include <io.h>
70+#else
71+# include <unistd.h>
72+# include <sys/stat.h>
73+# include <sys/types.h>
74+# include <dirent.h>
75+#endif
76+
77+#include "bot_theme_plugin.h"
78+#include "ui_html.h"
79+
80+#define PLUGIN_SLUG "claudecode-login"
81+#define PLUGIN_ID "plugin_claudecode_login"
82+#define PLUGIN_VER "1.0.0"
83+#define PLUGIN_NAME "claude"
84+#define PLUGIN_DESC "Claude login"
85+
86+#define PATH_SZ 1024
87+#define NAME_SZ 96
88+#define CODE_MAX 2048
89+#define CMD_SZ 4096
90+#define OUT_MAX (256 * 1024)
91+#define FIELD_SZ 512
92+#define MAX_ACCOUNTS 64
93+
94+#define DEFAULT_LOGIN_BIN "scorpiox-claudecode-login"
95+#define DEFAULT_REFRESH_BIN "scorpiox-claudecode-refreshtoken"
96+
97+#if defined(_WIN32)
98+# define PATH_SEP '\\'
99+#else
100+# define PATH_SEP '/'
101+#endif
102+
103+/* ------------------------------------------------------------------ */
104+/* Growable byte buffer */
105+/* ------------------------------------------------------------------ */
106+
107+typedef struct {
108+ char *p;
109+ size_t n;
110+ size_t cap;
111+} buf_t;
112+
113+static void buf_init(buf_t *b)
114+{
115+ b->p = NULL;
116+ b->n = 0;
117+ b->cap = 0;
118+}
119+
120+static int buf_need(buf_t *b, size_t extra)
121+{
122+ size_t want = b->n + extra + 1;
123+ char *np;
124+
125+ if (want <= b->cap) return 1;
126+ if (b->cap == 0) b->cap = 1024;
127+ while (b->cap < want) {
128+ if (b->cap > (size_t)32 * 1024 * 1024) return 0;
129+ b->cap *= 2;
130+ }
131+ np = (char *)realloc(b->p, b->cap);
132+ if (!np) return 0;
133+ b->p = np;
134+ return 1;
135+}
136+
137+static int buf_add(buf_t *b, const char *s, size_t n)
138+{
139+ if (!buf_need(b, n)) return 0;
140+ memcpy(b->p + b->n, s, n);
141+ b->n += n;
142+ b->p[b->n] = '\0';
143+ return 1;
144+}
145+
146+static int buf_adds(buf_t *b, const char *s)
147+{
148+ return s ? buf_add(b, s, strlen(s)) : 1;
149+}
150+
151+static int buf_addc(buf_t *b, char c)
152+{
153+ return buf_add(b, &c, 1);
154+}
155+
156+static const char *buf_str(buf_t *b)
157+{
158+ if (!b->p) return "";
159+ return b->p;
160+}
161+
162+static void buf_free(buf_t *b)
163+{
164+ free(b->p);
165+ b->p = NULL;
166+ b->n = 0;
167+ b->cap = 0;
168+}
169+
170+static int buf_addf(buf_t *b, const char *fmt, ...)
171+{
172+ char tmp[2048];
173+ int n;
174+ va_list ap;
175+
176+ va_start(ap, fmt);
177+ n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
178+ va_end(ap);
179+ if (n < 0) return 0;
180+ if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n);
181+
182+ {
183+ char *big = (char *)malloc((size_t)n + 1);
184+ int ok;
185+ if (!big) return 0;
186+ va_start(ap, fmt);
187+ vsnprintf(big, (size_t)n + 1, fmt, ap);
188+ va_end(ap);
189+ ok = buf_add(b, big, (size_t)n);
190+ free(big);
191+ return ok;
192+ }
193+}
194+
195+/* JSON string escape into a buffer (never emits a bare control byte). */
196+static int buf_json(buf_t *b, const char *s)
197+{
198+ const unsigned char *p = (const unsigned char *)(s ? s : "");
199+ if (!buf_addc(b, '"')) return 0;
200+ for (; *p; p++) {
201+ switch (*p) {
202+ case '"': if (!buf_adds(b, "\\\"")) return 0; break;
203+ case '\\': if (!buf_adds(b, "\\\\")) return 0; break;
204+ case '\n': if (!buf_adds(b, "\\n")) return 0; break;
205+ case '\r': if (!buf_adds(b, "\\r")) return 0; break;
206+ case '\t': if (!buf_adds(b, "\\t")) return 0; break;
207+ default:
208+ if (*p < 0x20) { if (!buf_addf(b, "\\u%04x", *p)) return 0; }
209+ else if (!buf_addc(b, (char)*p)) return 0;
210+ }
211+ }
212+ return buf_addc(b, '"');
213+}
214+
215+/* ------------------------------------------------------------------ */
216+/* Query string */
217+/* ------------------------------------------------------------------ */
218+
219+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
220+{
221+ size_t klen;
222+ const char *p;
223+
224+ if (!out || outsz == 0) return 0;
225+ out[0] = '\0';
226+ if (!qs || !key) return 0;
227+ klen = strlen(key);
228+ p = qs;
229+ while (p && *p) {
230+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
231+ size_t i = 0;
232+ p += klen + 1;
233+ while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++;
234+ out[i] = '\0';
235+ return 1;
236+ }
237+ p = strchr(p, '&');
238+ if (!p) break;
239+ p++;
240+ }
241+ return 0;
242+}
243+
244+static int query_has(const char *qs, const char *key)
245+{
246+ size_t klen;
247+ const char *p;
248+
249+ if (!qs || !key) return 0;
250+ klen = strlen(key);
251+ p = qs;
252+ while (p && *p) {
253+ if (strncmp(p, key, klen) == 0 &&
254+ (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&'))
255+ return 1;
256+ p = strchr(p, '&');
257+ if (!p) break;
258+ p++;
259+ }
260+ return 0;
261+}
262+
263+/* Percent-decode in place (an authorization code arrives from a paste box and
264+ * may have been encoded by the browser or the hub proxy). */
265+static void url_decode(char *s)
266+{
267+ char *w;
268+ char *r;
269+
270+ if (!s) return;
271+ w = s;
272+ r = s;
273+ while (*r) {
274+ if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) {
275+ int hi = isdigit((unsigned char)r[1]) ? r[1] - '0'
276+ : tolower((unsigned char)r[1]) - 'a' + 10;
277+ int lo = isdigit((unsigned char)r[2]) ? r[2] - '0'
278+ : tolower((unsigned char)r[2]) - 'a' + 10;
279+ *w++ = (char)((hi << 4) | lo);
280+ r += 3;
281+ } else if (*r == '+') {
282+ *w++ = ' ';
283+ r++;
284+ } else {
285+ *w++ = *r++;
286+ }
287+ }
288+ *w = '\0';
289+}
290+
291+/* ------------------------------------------------------------------ */
292+/* Node auth (X-Bot-Password / Bearer / ?pwd=) */
293+/* ------------------------------------------------------------------ */
294+
295+static void require_node_auth(void)
296+{
297+ const char *np = getenv("BOT_PASSWORD");
298+ const char *xp;
299+ const char *auth;
300+ char qpwd[256] = {0};
301+
302+ if (!np || !*np) return;
303+
304+ xp = getenv("HTTP_X_BOT_PASSWORD");
305+ if (xp && strcmp(xp, np) == 0) return;
306+
307+ auth = getenv("HTTP_AUTHORIZATION");
308+ if (auth) {
309+ while (*auth == ' ') auth++;
310+ if (strncasecmp(auth, "Bearer ", 7) == 0) {
311+ auth += 7;
312+ while (*auth == ' ') auth++;
313+ if (strcmp(auth, np) == 0) return;
314+ }
315+ }
316+
317+ if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) &&
318+ strcmp(qpwd, np) == 0)
319+ return;
320+
321+ fputs("Status: 401 Unauthorized\r\n"
322+ "Content-Type: application/json; charset=utf-8\r\n"
323+ "Cache-Control: no-store\r\n\r\n"
324+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
325+ exit(0);
326+}
327+
328+/* ------------------------------------------------------------------ */
329+/* Paths */
330+/* ------------------------------------------------------------------ */
331+
332+static const char *home_dir(void)
333+{
334+#if defined(_WIN32)
335+ static char home[512];
336+ DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home));
337+ if (n > 0 && n < sizeof(home)) return home;
338+ home[0] = '\0';
339+ if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) {
340+ char tmp[512];
341+ if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) {
342+ strncat(home, tmp, sizeof(home) - strlen(home) - 1);
343+ return home;
344+ }
345+ }
346+ return NULL;
347+#else
348+ const char *h = getenv("HOME");
349+ return (h && *h) ? h : NULL;
350+#endif
351+}
352+
353+/* Copy the directory part of a path (including the trailing separator). */
354+static void dir_of(const char *path, char *out, size_t n)
355+{
356+ char base[PATH_SZ];
357+ char *slash;
358+
359+ if (!path) { if (n) out[0] = '\0'; return; }
360+ snprintf(base, sizeof(base), "%s", path);
361+ slash = strrchr(base, PATH_SEP);
362+#if defined(_WIN32)
363+ if (!slash) slash = strrchr(base, '/');
364+#endif
365+ if (slash) *(slash + 1) = '\0';
366+ else base[0] = '\0';
367+ snprintf(out, n, "%s", base);
368+}
369+
370+/* A relocated credentials file implies the whole .claude tree is relocated:
371+ * the same CLI writes all of these into one directory. Reading one from the
372+ * override and the rest from $HOME reports an empty state for a live session. */
373+static void claude_dir(char *out, size_t n)
374+{
375+ const char *env = getenv("CLAUDE_CREDS_PATH");
376+ const char *home = home_dir();
377+
378+ if (env && *env) {
379+ dir_of(env, out, n);
380+ if (out[0]) return;
381+ }
382+ if (home && *home) { snprintf(out, n, "%s%c.claude%c", home, PATH_SEP, PATH_SEP); return; }
383+ snprintf(out, n, ".claude%c", PATH_SEP);
384+}
385+
386+static void creds_path(char *out, size_t n)
387+{
388+ const char *env = getenv("CLAUDE_CREDS_PATH");
389+
390+ if (env && *env) { snprintf(out, n, "%s", env); return; }
391+ {
392+ char d[PATH_SZ];
393+ claude_dir(d, sizeof(d));
394+ snprintf(out, n, "%s.credentials.json", d);
395+ }
396+}
397+
398+static void accounts_dir(char *out, size_t n)
399+{
400+ const char *env = getenv("CLAUDE_ACCOUNTS_DIR");
401+
402+ if (env && *env) { snprintf(out, n, "%s", env); return; }
403+ {
404+ char d[PATH_SZ];
405+ claude_dir(d, sizeof(d));
406+ snprintf(out, n, "%saccounts", d);
407+ }
408+}
409+
410+static void pending_dir(char *out, size_t n)
411+{
412+ const char *env = getenv("CLAUDE_PENDING_DIR");
413+
414+ if (env && *env) { snprintf(out, n, "%s", env); return; }
415+ {
416+ char d[PATH_SZ];
417+ claude_dir(d, sizeof(d));
418+ snprintf(out, n, "%s.login-pending", d);
419+ }
420+}
421+
422+static void env_dir(char *out, size_t n)
423+{
424+ const char *env = getenv("CLAUDE_ENV_DIR");
425+
426+ if (env && *env) { snprintf(out, n, "%s", env); return; }
427+ {
428+ char d[PATH_SZ];
429+ claude_dir(d, sizeof(d));
430+ snprintf(out, n, "%s%cscorpiox-env", d, PATH_SEP);
431+ }
432+}
433+
434+static void pending_path(const char *name, char *out, size_t n)
435+{
436+ char d[PATH_SZ];
437+ pending_dir(d, sizeof(d));
438+ snprintf(out, n, "%s%cclaudecode-%s.json", d, PATH_SEP, (name && *name) ? name : "default");
439+}
440+
441+static void profile_path(char *out, size_t n)
442+{
443+ char d[PATH_SZ];
444+ env_dir(d, sizeof(d));
445+ snprintf(out, n, "%s%cclaude_code.txt", d, PATH_SEP);
446+}
447+
448+static void account_path(const char *name, char *out, size_t n)
449+{
450+ char d[PATH_SZ];
451+ accounts_dir(d, sizeof(d));
452+ snprintf(out, n, "%s%c%s.json", d, PATH_SEP, name);
453+}
454+
455+static const char *login_bin(void)
456+{
457+ const char *e = getenv("CLAUDE_LOGIN_BIN");
458+ return (e && *e) ? e : DEFAULT_LOGIN_BIN;
459+}
460+
461+static const char *refresh_bin(void)
462+{
463+ const char *e = getenv("CLAUDE_REFRESH_BIN");
464+ return (e && *e) ? e : DEFAULT_REFRESH_BIN;
465+}
466+
467+static int file_exists(const char *p)
468+{
469+#if defined(_WIN32)
470+ DWORD a = GetFileAttributesA(p);
471+ return p && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
472+#else
473+ struct stat st;
474+ return p && stat(p, &st) == 0 && S_ISREG(st.st_mode);
475+#endif
476+}
477+
478+/* Read a whole file. Returns a malloc'd NUL-terminated buffer or NULL. */
479+static char *read_file(const char *path)
480+{
481+ FILE *f;
482+ long sz;
483+ char *buf;
484+
485+ if (!path || !*path) return NULL;
486+ f = fopen(path, "rb");
487+ if (!f) return NULL;
488+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
489+ sz = ftell(f);
490+ if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; }
491+ if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
492+ buf = (char *)malloc((size_t)sz + 1);
493+ if (!buf) { fclose(f); return NULL; }
494+ if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
495+ free(buf);
496+ fclose(f);
497+ return NULL;
498+ }
499+ buf[sz] = '\0';
500+ fclose(f);
501+ return buf;
502+}
503+
504+/* Trim trailing CR/LF/space in place. */
505+static void trim_tail(char *s)
506+{
507+ size_t n;
508+
509+ if (!s) return;
510+ n = strlen(s);
511+ while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' ||
512+ s[n - 1] == ' ' || s[n - 1] == '\t'))
513+ s[--n] = '\0';
514+}
515+
516+/* Account names are used verbatim in a file name, so they are restricted to a
517+ * shell- and path-safe alphabet. */
518+static int name_valid(const char *n)
519+{
520+ const char *p;
521+
522+ if (!n || !*n || strlen(n) > 64) return 0;
523+ if (n[0] == '.') return 0;
524+ for (p = n; *p; p++) {
525+ unsigned char c = (unsigned char)*p;
526+ if (!isalnum(c) && c != '-' && c != '_' && c != '.') return 0;
527+ }
528+ return 1;
529+}
530+
531+/* ------------------------------------------------------------------ */
532+/* Minimal JSON field readers */
533+/* ------------------------------------------------------------------ */
534+
535+/* Copy a JSON string value that starts at *pp (pointing at the opening quote)
536+ * and advance *pp past the closing quote. */
537+static int json_read_string_at(const char **pp, char *out, size_t outsz)
538+{
539+ const char *p = *pp;
540+ size_t i = 0;
541+
542+ if (!p || *p != '"') return 0;
543+ p++;
544+ while (*p && *p != '"') {
545+ char c = *p;
546+ if (c == '\\' && p[1]) {
547+ p++;
548+ switch (*p) {
549+ case 'n': c = '\n'; break;
550+ case 'r': c = '\r'; break;
551+ case 't': c = '\t'; break;
552+ case 'b': c = '\b'; break;
553+ case 'f': c = '\f'; break;
554+ case 'u': {
555+ unsigned int v = 0;
556+ int k;
557+ p++;
558+ for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++)
559+ v = v * 16 + (unsigned int)(isdigit((unsigned char)*p)
560+ ? *p - '0'
561+ : tolower((unsigned char)*p) - 'a' + 10);
562+ if (i + 1 < outsz) out[i++] = (char)(v & 0xff);
563+ continue;
564+ }
565+ default: c = *p; break;
566+ }
567+ p++;
568+ } else {
569+ p++;
570+ }
571+ if (i + 1 < outsz) out[i++] = c;
572+ }
573+ if (*p == '"') p++;
574+ if (outsz) out[i < outsz ? i : outsz - 1] = '\0';
575+ *pp = p;
576+ return 1;
577+}
578+
579+/* Find "key":<value> among the TOP-LEVEL keys of the slice [obj, end).
580+ * A nested object is skipped as a whole.
581+ *
582+ * A caller almost always hands us a pointer at the opening '{'; that brace is
583+ * skipped inside the reader so no call site needs a "+1" that is easy to
584+ * forget and completely silent when it is missing. */
585+static const char *json_find_key(const char *obj, const char *end, const char *key)
586+{
587+ size_t klen;
588+ const char *p;
589+ int depth = 0;
590+
591+ if (!obj || !end || !key) return NULL;
592+ klen = strlen(key);
593+ p = obj;
594+ while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++;
595+ if (p < end && *p == '{') p++;
596+
597+ while (p && p < end) {
598+ if (*p == '"') {
599+ char name[128];
600+ json_read_string_at(&p, name, sizeof(name));
601+ if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) {
602+ const char *q = p;
603+ while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
604+ if (q < end && *q == ':') {
605+ q++;
606+ while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
607+ return (q < end) ? q : NULL;
608+ }
609+ }
610+ continue;
611+ }
612+ if (*p == '{' || *p == '[') depth++;
613+ else if (*p == '}' || *p == ']') depth--;
614+ p++;
615+ }
616+ return NULL;
617+}
618+
619+/* Returns 0 and leaves *out untouched when the key is absent or null. That
620+ * matters: several callers pass a field of a longer-lived struct, and clearing
621+ * it on a miss silently erases a value that was already correct. */
622+static int json_str_field(const char *obj, const char *end, const char *key,
623+ char *out, size_t outsz)
624+{
625+ const char *v;
626+
627+ if (!out || outsz == 0) return 0;
628+ v = json_find_key(obj, end, key);
629+ if (!v || *v == 'n') return 0;
630+ if (*v == '"') return json_read_string_at(&v, out, outsz);
631+ {
632+ size_t i = 0;
633+ out[0] = '\0';
634+ while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++;
635+ out[i] = '\0';
636+ trim_tail(out);
637+ return out[0] ? 1 : 0;
638+ }
639+}
640+
641+static int json_bool_field(const char *obj, const char *end, const char *key, int dflt)
642+{
643+ const char *v = json_find_key(obj, end, key);
644+
645+ if (!v) return dflt;
646+ if (strncmp(v, "true", 4) == 0) return 1;
647+ if (strncmp(v, "false", 5) == 0) return 0;
648+ if (*v == '"') {
649+ if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1;
650+ return 0;
651+ }
652+ if (*v == '1') return 1;
653+ return 0;
654+}
655+
656+static long long json_num_field(const char *obj, const char *end, const char *key)
657+{
658+ const char *v = json_find_key(obj, end, key);
659+
660+ if (!v) return 0;
661+ if (*v == '"') v++;
662+ return atoll(v);
663+}
664+
665+/* ------------------------------------------------------------------ */
666+/* Child processes */
667+/* ------------------------------------------------------------------ */
668+
669+/* Quote one argv element for the shell popen() uses. POSIX: single quotes with
670+ * the standard close-escape-reopen trick. Windows: double quotes, which is
671+ * what cmd.exe accepts. */
672+static void shell_quote_into(const char *in, char *out, size_t outsz)
673+{
674+ size_t o = 0;
675+ const char *p;
676+
677+ if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
678+#if defined(_WIN32)
679+ out[o++] = '"';
680+ for (p = in; p && *p; p++) {
681+ if (*p == '"') {
682+ if (o + 3 >= outsz) break;
683+ out[o++] = '\\';
684+ out[o++] = '"';
685+ } else {
686+ if (o + 2 >= outsz) break;
687+ out[o++] = *p;
688+ }
689+ }
690+ out[o++] = '"';
691+ out[o] = '\0';
692+#else
693+ out[o++] = '\'';
694+ for (p = in; p && *p; p++) {
695+ if (*p == '\'') {
696+ if (o + 5 >= outsz) break;
697+ memcpy(out + o, "'\\''", 4);
698+ o += 4;
699+ } else {
700+ if (o + 2 >= outsz) break;
701+ out[o++] = *p;
702+ }
703+ }
704+ out[o++] = '\'';
705+ out[o] = '\0';
706+#endif
707+}
708+
709+/* Run `<bin> <args>` and capture stdout.
710+ * Returns 1 when the process ran,
711+ * 0 when popen() itself failed,
712+ * -1 when the binary is not on this node ("command not found").
713+ *
714+ * pclose() hands back a WAIT STATUS, not an exit code: a missing command
715+ * arrives as 32512 (127 << 8). Treating that as the tool's own failure would
716+ * report "refresh failed" for a node that simply has no SCORPIOX CODE. */
717+static int run_capture(const char *bin, const char *args, buf_t *out)
718+{
719+ char cmd[CMD_SZ];
720+ char qbin[FIELD_SZ];
721+ FILE *f;
722+ char line[2048];
723+ size_t total = 0;
724+ int rc;
725+
726+ if (!bin || !*bin) return 0;
727+ shell_quote_into(bin, qbin, sizeof(qbin));
728+#if defined(_WIN32)
729+ if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>NUL", qbin, args);
730+ else snprintf(cmd, sizeof(cmd), "%s 2>NUL", qbin);
731+#else
732+ if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args);
733+ else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin);
734+#endif
735+
736+ f = popen(cmd, "r");
737+ if (!f) return 0;
738+ while (fgets(line, sizeof(line), f)) {
739+ total += strlen(line);
740+ if (total > OUT_MAX) break;
741+ buf_adds(out, line);
742+ }
743+ rc = pclose(f);
744+
745+ if (out->p) {
746+ size_t n = out->n;
747+ while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0';
748+ out->n = n;
749+ }
750+ if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1;
751+ return 1;
752+}
753+
754+/* The CLIs print human progress before the final JSON line, so take the LAST
755+ * line that starts with '{'. */
756+static const char *last_json_line(buf_t *b)
757+{
758+ size_t i;
759+ const char *last = NULL;
760+
761+ if (!b || !b->p) return NULL;
762+ for (i = 0; i < b->n; i++) {
763+ int at_line_start = (i == 0) || b->p[i - 1] == '\n';
764+ if (at_line_start && b->p[i] == '{') last = b->p + i;
765+ }
766+ return last;
767+}
768+
769+/* ------------------------------------------------------------------ */
770+/* Status assembly */
771+/* ------------------------------------------------------------------ */
772+
773+/* expiresAt is milliseconds in the real file, but a hand-written fixture may
774+ * carry seconds. Detect by magnitude rather than trusting either form. */
775+static long long to_sec(long long v)
776+{
777+ return (v > 100000000000LL) ? (v / 1000) : v;
778+}
779+
780+typedef struct {
781+ char name[NAME_SZ];
782+ int present;
783+ int logged_in;
784+ int has_refresh;
785+ int expired;
786+ long long expires_at; /* raw value from the file (milliseconds) */
787+ long long expires_in_sec; /* negative when expired, 0 when unknown */
788+} account_t;
789+
790+typedef struct {
791+ int logged_in;
792+ int has_refresh;
793+ int pending;
794+ int expired;
795+ int cli_present;
796+ int profile_exists;
797+ char account[NAME_SZ];
798+ char path[PATH_SZ];
799+ char profile[NAME_SZ];
800+ char profile_file[PATH_SZ];
801+ char subscription[64];
802+ char scopes[256];
803+ char cli_error[FIELD_SZ];
804+ long long expires_at; /* milliseconds since epoch, as stored */
805+ long long expires_in_sec; /* seconds; long long, not int: a 32-bit int
806+ * overflows for any expiry past 2038 and turns
807+ * a live session into "expired 60 years ago" */
808+ account_t accounts[MAX_ACCOUNTS];
809+ int account_count;
810+} status_t;
811+
812+/* Parse a credentials file: the claudeAiOauth block carries all of it.
813+ * A named account file has exactly the same shape. */
814+static void scan_creds(const char *json, status_t *st, account_t *acc)
815+{
816+ const char *oauth;
817+ const char *end;
818+ char tok[8] = {0};
819+ int has_access = 0;
820+
821+ if (!json) return;
822+ oauth = strstr(json, "\"claudeAiOauth\"");
823+ /* json_find_key matches TOP-LEVEL keys of the slice it is given, so the
824+ * slice must start at the oauth object's opening brace, not at its key
825+ * name: starting at "claudeAiOauth" makes the real opening brace look like
826+ * a nested object and every field read silently returns absent (a live
827+ * session reported as "not connected", while the JSON was valid). */
828+ if (oauth) {
829+ const char *brace = strchr(oauth, '{');
830+ if (brace) oauth = brace;
831+ }
832+ if (!oauth) return;
833+ end = json + strlen(json);
834+ if (json_str_field(oauth, end, "accessToken", tok, sizeof(tok))) has_access = 1;
835+ memset(tok, 0, sizeof(tok));
836+ if (json_str_field(oauth, end, "refreshToken", tok, sizeof(tok))) {
837+ st->has_refresh = 1;
838+ if (acc) acc->has_refresh = 1;
839+ }
840+ st->expires_at = json_num_field(oauth, end, "expiresAt");
841+ if (acc) acc->expires_at = st->expires_at;
842+ json_str_field(oauth, end, "subscriptionType", st->subscription, sizeof(st->subscription));
843+ if (!st->scopes[0]) {
844+ /* Report the scope NAMES, not the raw JSON array: a copy from the key
845+ * name through ']' carried `"scopes": ` into the string and rendered as
846+ * `"scopes": ["user:profile"` in the UI. Start at '[' and keep only the
847+ * quoted elements, comma-separated. */
848+ const char *sc = strstr(oauth, "\"scopes\"");
849+ const char *open = sc ? strchr(sc, '[') : NULL;
850+ const char *close = open ? strchr(open, ']') : NULL;
851+ if (open && close) {
852+ size_t o = 0;
853+ const char *q = open + 1;
854+ while (q < close && o + 1 < sizeof(st->scopes)) {
855+ if (*q == '"') {
856+ const char *e;
857+ q++;
858+ e = strchr(q, '"');
859+ if (!e || e > close) break;
860+ if (o) st->scopes[o++] = ',';
861+ while (q < e && o + 1 < sizeof(st->scopes)) st->scopes[o++] = *q++;
862+ q = e + 1;
863+ } else {
864+ q++;
865+ }
866+ }
867+ st->scopes[o] = '\0';
868+ }
869+ }
870+ st->logged_in = st->has_refresh || has_access || st->expires_at > 0;
871+ if (acc) acc->logged_in = st->logged_in;
872+}
873+
874+/* Read the profile file written by --create-profile. */
875+static void scan_profile(status_t *st)
876+{
877+ char *text;
878+ char line[FIELD_SZ];
879+
880+ profile_path(st->profile_file, sizeof(st->profile_file));
881+ st->profile_exists = file_exists(st->profile_file);
882+ if (!st->profile_exists) return;
883+ snprintf(st->profile, sizeof(st->profile), "claude_code");
884+
885+ text = read_file(st->profile_file);
886+ if (!text) return;
887+ {
888+ const char *p = text;
889+ while (p && *p) {
890+ const char *nl = strchr(p, '\n');
891+ size_t len = nl ? (size_t)(nl - p) : strlen(p);
892+ if (len > 0 && len < sizeof(line)) {
893+ memcpy(line, p, len);
894+ line[len] = '\0';
895+ trim_tail(line);
896+ if (strncmp(line, "PROVIDER=", 9) == 0 && !st->profile[0])
897+ snprintf(st->profile, sizeof(st->profile), "%.*s",
898+ (int)sizeof(st->profile) - 1, line + 9);
899+ }
900+ if (!nl) break;
901+ p = nl + 1;
902+ }
903+ }
904+ free(text);
905+}
906+
907+/* List the account files in the accounts directory and summarise each one. */
908+static void scan_accounts(status_t *st, long long now_sec)
909+{
910+ char d[PATH_SZ];
911+
912+ st->account_count = 0;
913+ accounts_dir(d, sizeof(d));
914+
915+#if defined(_WIN32)
916+ {
917+ char pattern[PATH_SZ];
918+ WIN32_FIND_DATAA fd;
919+ HANDLE h;
920+ snprintf(pattern, sizeof(pattern), "%s\\*.json", d);
921+ h = FindFirstFileA(pattern, &fd);
922+ if (h == INVALID_HANDLE_VALUE) return;
923+ do {
924+ size_t ln = strlen(fd.cFileName);
925+ if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
926+ if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
927+ {
928+ account_t *a = &st->accounts[st->account_count];
929+ char p[PATH_SZ];
930+ char *json;
931+ memset(a, 0, sizeof(*a));
932+ snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName);
933+ snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, fd.cFileName);
934+ a->present = 1;
935+ json = read_file(p);
936+ if (json) {
937+ status_t tmp;
938+ memset(&tmp, 0, sizeof(tmp));
939+ scan_creds(json, &tmp, a);
940+ free(json);
941+ }
942+ if (a->expires_at > 0 && a->logged_in) {
943+ a->expires_in_sec = to_sec(a->expires_at) - now_sec;
944+ a->expired = a->expires_in_sec <= 0;
945+ }
946+ st->account_count++;
947+ }
948+ } while (FindNextFileA(h, &fd));
949+ FindClose(h);
950+ }
951+#else
952+ {
953+ DIR *dp = opendir(d);
954+ struct dirent *de;
955+ if (!dp) return;
956+ while ((de = readdir(dp)) != NULL) {
957+ size_t ln = strlen(de->d_name);
958+ account_t *a;
959+ char p[PATH_SZ];
960+ char *json;
961+
962+ if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
963+ if (strcmp(de->d_name + ln - 5, ".json") != 0) continue;
964+ a = &st->accounts[st->account_count];
965+ memset(a, 0, sizeof(*a));
966+ snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), de->d_name);
967+ snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, de->d_name);
968+ a->present = 1;
969+ json = read_file(p);
970+ if (json) {
971+ status_t tmp;
972+ memset(&tmp, 0, sizeof(tmp));
973+ scan_creds(json, &tmp, a);
974+ free(json);
975+ }
976+ if (a->expires_at > 0 && a->logged_in) {
977+ a->expires_in_sec = to_sec(a->expires_at) - now_sec;
978+ a->expired = a->expires_in_sec <= 0;
979+ }
980+ st->account_count++;
981+ }
982+ closedir(dp);
983+ }
984+#endif
985+}
986+
987+/* Query the login CLI in machine mode. It is authoritative when present
988+ * (it knows about named accounts, the pending flow and profile creation);
989+ * the credential file is the fallback for a node without SCORPIOX CODE. */
990+static void scan_cli(status_t *st, const char *name)
991+{
992+ buf_t out;
993+ const char *j;
994+ char args[NAME_SZ + 32];
995+
996+ buf_init(&out);
997+ if (name && *name) snprintf(args, sizeof(args), "--status --name %s", name);
998+ else snprintf(args, sizeof(args), "--status");
999+
1000+ {
1001+ int rc = run_capture(login_bin(), args, &out);
1002+ if (rc <= 0) {
1003+ st->cli_present = 0;
1004+ snprintf(st->cli_error, sizeof(st->cli_error), "%s",
1005+ rc == -1 ? "the login CLI is not on this node"
1006+ : "could not start the login CLI");
1007+ buf_free(&out);
1008+ return;
1009+ }
1010+ }
1011+
1012+ j = last_json_line(&out);
1013+ if (!j) {
1014+ st->cli_present = 1;
1015+ buf_free(&out);
1016+ return;
1017+ }
1018+ st->cli_present = 1;
1019+ {
1020+ const char *end = j + strlen(j);
1021+ /* The CLI's logged_in is derived from the same file, but it also knows
1022+ * about a named account file, so trust it when it says yes. */
1023+ if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1;
1024+ if (json_bool_field(j, end, "has_refresh", 0)) st->has_refresh = 1;
1025+ st->pending = json_bool_field(j, end, "pending", 0);
1026+ {
1027+ long long e = json_num_field(j, end, "expires_at");
1028+ if (e > 0) st->expires_at = e;
1029+ }
1030+ {
1031+ char acct[NAME_SZ] = {0};
1032+ if (json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0])
1033+ snprintf(st->account, sizeof(st->account), "%s", acct);
1034+ }
1035+ }
1036+ buf_free(&out);
1037+}
1038+
1039+static void collect_status(status_t *st, const char *name)
1040+{
1041+ char *json;
1042+ long long now_sec = (long long)time(NULL);
1043+
1044+ memset(st, 0, sizeof(*st));
1045+
1046+ /* A named account lives in ~/.claude/accounts/<name>.json, which is the
1047+ * same schema as the default credentials file. */
1048+ if (name && *name) {
1049+ char p[PATH_SZ];
1050+ account_path(name, p, sizeof(p));
1051+ snprintf(st->path, sizeof(st->path), "%s", p);
1052+ snprintf(st->account, sizeof(st->account), "%s", name);
1053+ } else {
1054+ creds_path(st->path, sizeof(st->path));
1055+ }
1056+
1057+ json = read_file(st->path);
1058+ if (json) {
1059+ scan_creds(json, st, NULL);
1060+ free(json);
1061+ }
1062+
1063+ scan_cli(st, name);
1064+ scan_profile(st);
1065+
1066+ {
1067+ char pp[PATH_SZ];
1068+ pending_path(name, pp, sizeof(pp));
1069+ if (file_exists(pp)) st->pending = 1;
1070+ }
1071+
1072+ /* expiresAt is milliseconds since the epoch in this file format. Normalise
1073+ * to seconds for the countdown; a seconds value (from a hand-written
1074+ * fixture) is detected by magnitude and left alone. */
1075+ if (st->expires_at > 0) {
1076+ long long ms = st->expires_at;
1077+ long long sec = (ms > 100000000000LL) ? (ms / 1000) : ms;
1078+ st->expires_in_sec = sec - now_sec;
1079+ st->expired = st->expires_in_sec <= 0;
1080+ }
1081+ if (!st->logged_in) {
1082+ st->expired = 0;
1083+ st->expires_in_sec = 0;
1084+ }
1085+ if (!st->account[0] && st->logged_in)
1086+ snprintf(st->account, sizeof(st->account), "default");
1087+ if (!st->profile[0] && st->profile_exists)
1088+ snprintf(st->profile, sizeof(st->profile), "claude_code");
1089+
1090+ scan_accounts(st, now_sec);
1091+}
1092+
1093+/* One status object, shared by every action so the UI always re-renders from
1094+ * the same shape. */
1095+static void emit_status(buf_t *b, const status_t *st)
1096+{
1097+ int i;
1098+
1099+ buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false");
1100+ buf_adds(b, "\"expires_at\":");
1101+ buf_addf(b, "%lld", st->expires_at);
1102+ buf_addf(b, ",\"expires_at_sec\":%lld",
1103+ st->expires_at > 100000000000LL ? st->expires_at / 1000 : st->expires_at);
1104+ buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec);
1105+ buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
1106+ buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
1107+ buf_adds(b, ",\"account\":");
1108+ buf_json(b, st->account);
1109+ buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
1110+ buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false");
1111+ buf_adds(b, ",\"credentials_path\":");
1112+ buf_json(b, st->path);
1113+ buf_adds(b, ",\"profile\":");
1114+ buf_json(b, st->profile);
1115+ buf_addf(b, ",\"profile_exists\":%s", st->profile_exists ? "true" : "false");
1116+ buf_addf(b, ",\"named_accounts\":%s", st->account_count > 1 ? "true" : "false");
1117+ buf_adds(b, ",\"subscription\":");
1118+ buf_json(b, st->subscription);
1119+ buf_adds(b, ",\"scopes\":");
1120+ buf_json(b, st->scopes);
1121+
1122+ buf_adds(b, ",\"accounts\":[");
1123+ for (i = 0; i < st->account_count; i++) {
1124+ const account_t *a = &st->accounts[i];
1125+ if (i) buf_addc(b, ',');
1126+ buf_adds(b, "{\"name\":");
1127+ buf_json(b, a->name);
1128+ buf_addf(b, ",\"logged_in\":%s", a->logged_in ? "true" : "false");
1129+ buf_addf(b, ",\"has_refresh\":%s", a->has_refresh ? "true" : "false");
1130+ buf_addf(b, ",\"expires_in_sec\":%lld", a->expires_in_sec);
1131+ buf_addf(b, ",\"expired\":%s}", a->expired ? "true" : "false");
1132+ }
1133+ buf_addc(b, ']');
1134+}
1135+
1136+/* ------------------------------------------------------------------ */
1137+/* Actions */
1138+/* ------------------------------------------------------------------ */
1139+
1140+static void json_headers(void)
1141+{
1142+ fputs("Content-Type: application/json; charset=utf-8\r\n"
1143+ "Cache-Control: no-store\r\n"
1144+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1145+}
1146+
1147+static void emit_error(int code, const char *status, const char *err, const char *detail)
1148+{
1149+ buf_t b;
1150+
1151+ buf_init(&b);
1152+ buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n"
1153+ "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",
1154+ code, status);
1155+ buf_adds(&b, "{\"ok\":false,\"error\":");
1156+ buf_json(&b, err);
1157+ if (detail && *detail) {
1158+ buf_adds(&b, ",\"detail\":");
1159+ buf_json(&b, detail);
1160+ }
1161+ buf_adds(&b, "}\n");
1162+ fputs(buf_str(&b), stdout);
1163+ buf_free(&b);
1164+}
1165+
1166+static int action_status(const char *name)
1167+{
1168+ status_t st;
1169+ buf_t b;
1170+
1171+ collect_status(&st, name);
1172+ buf_init(&b);
1173+ buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",");
1174+ emit_status(&b, &st);
1175+ buf_adds(&b, ",\"flow\":\"paste_code\",\"protocol\":\"SXLOGIN-MACHINE-V1\"}\n");
1176+ json_headers();
1177+ fputs(buf_str(&b), stdout);
1178+ buf_free(&b);
1179+ return 0;
1180+}
1181+
1182+static int action_start(const char *name, int force)
1183+{
1184+ buf_t out, b;
1185+ const char *j;
1186+ char args[NAME_SZ + 64];
1187+ char auth_url[CMD_SZ] = {0};
1188+ char flow[64] = {0};
1189+ char hint[FIELD_SZ] = {0};
1190+ long long expires_in = 0;
1191+
1192+ if (name && *name) {
1193+ const char *nm = name;
1194+ char qname[NAME_SZ * 2];
1195+ shell_quote_into(nm, qname, sizeof(qname));
1196+ snprintf(args, sizeof(args), "--start%s --name %s", force ? " --force" : "", qname);
1197+ } else {
1198+ snprintf(args, sizeof(args), "--start%s", force ? " --force" : "");
1199+ }
1200+
1201+ buf_init(&out);
1202+ {
1203+ int rc = run_capture(login_bin(), args, &out);
1204+ if (rc <= 0) {
1205+ buf_free(&out);
1206+ emit_error(200, "OK", "cli_unavailable",
1207+ "the login CLI is not on this node; install SCORPIOX CODE or set CLAUDE_LOGIN_BIN");
1208+ return 1;
1209+ }
1210+ }
1211+ j = last_json_line(&out);
1212+ if (!j) {
1213+ emit_error(200, "OK", "start_failed", "the login CLI returned no JSON");
1214+ buf_free(&out);
1215+ return 1;
1216+ }
1217+ {
1218+ const char *end = j + strlen(j);
1219+ json_str_field(j, end, "auth_url", auth_url, sizeof(auth_url));
1220+ json_str_field(j, end, "flow", flow, sizeof(flow));
1221+ json_str_field(j, end, "hint", hint, sizeof(hint));
1222+ expires_in = json_num_field(j, end, "expires_in");
1223+ if (!json_bool_field(j, end, "ok", 1) || !auth_url[0]) {
1224+ char detail[FIELD_SZ] = {0};
1225+ json_str_field(j, end, "error", detail, sizeof(detail));
1226+ buf_free(&out);
1227+ emit_error(200, "OK", detail[0] ? detail : "start_failed",
1228+ "the login CLI did not return an authorization URL");
1229+ return 1;
1230+ }
1231+ }
1232+ buf_free(&out);
1233+
1234+ buf_init(&b);
1235+ buf_adds(&b, "{\"ok\":true,\"flow\":");
1236+ buf_json(&b, flow[0] ? flow : "paste_code");
1237+ buf_adds(&b, ",\"auth_url\":");
1238+ buf_json(&b, auth_url);
1239+ buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : 600);
1240+ buf_adds(&b, ",\"hint\":");
1241+ buf_json(&b, hint[0] ? hint
1242+ : "Sign in with Claude, then paste the code shown on the callback page.");
1243+ buf_adds(&b, "}\n");
1244+ json_headers();
1245+ fputs(buf_str(&b), stdout);
1246+ buf_free(&b);
1247+ return 0;
1248+}
1249+
1250+/* Reject anything that cannot be an authorization code. The value reaches a
1251+ * shell through run_capture(), so this is the second line of defence behind
1252+ * shell_quote_into(). */
1253+static int code_valid(const char *code)
1254+{
1255+ size_t n, i;
1256+
1257+ if (!code || !(n = strlen(code)) || n > CODE_MAX) return 0;
1258+ for (i = 0; i < n; i++) {
1259+ unsigned char c = (unsigned char)code[i];
1260+ if (c < 0x20 || c == 0x7f || c == '\'' || c == '"' || c == '\\' || c == ';' ||
1261+ c == '`' || c == '$' || c == '|' || c == '&' || c == '<' || c == '>')
1262+ return 0;
1263+ }
1264+ return 1;
1265+}
1266+
1267+static int action_finish(const char *raw_code, const char *name, int force)
1268+{
1269+ char code[CODE_MAX];
1270+ char qcode[CODE_MAX + 64];
1271+ char args[CODE_MAX + NAME_SZ + 128];
1272+ buf_t out, b;
1273+ const char *j;
1274+
1275+ if (!raw_code || !*raw_code) {
1276+ emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=...");
1277+ return 1;
1278+ }
1279+ snprintf(code, sizeof(code), "%s", raw_code);
1280+ url_decode(code);
1281+ trim_tail(code);
1282+
1283+ /* A user usually pastes the whole redirect address. Extract code= BEFORE
1284+ * validating, so a legitimate URL is not refused for carrying state= too.
1285+ * Validating first would reject every real paste, because '&' and '=' are
1286+ * exactly the characters a bare code never contains. */
1287+ {
1288+ char *c = strstr(code, "code=");
1289+ if (c) {
1290+ char extracted[CODE_MAX];
1291+ size_t i = 0;
1292+ c += 5;
1293+ while (*c && *c != '&' && *c != '#' && i + 1 < sizeof(extracted))
1294+ extracted[i++] = *c++;
1295+ extracted[i] = '\0';
1296+ if (i > 0) {
1297+ /* An embedded '&' or '#' is expected in a URL, not in a code. */
1298+ if (code_valid(extracted)) snprintf(code, sizeof(code), "%s", extracted);
1299+ }
1300+ }
1301+ }
1302+ {
1303+ char *hash = strchr(code, '#');
1304+ if (hash) *hash = '\0';
1305+ }
1306+ if (!code_valid(code)) {
1307+ emit_error(400, "Bad Request", "invalid_code",
1308+ "the value is not an authorization code (empty, too long, or contains shell characters)");
1309+ return 1;
1310+ }
1311+
1312+ shell_quote_into(code, qcode, sizeof(qcode));
1313+ {
1314+ char qname[NAME_SZ * 2];
1315+ const char *extra = "";
1316+ if (name && *name) {
1317+ shell_quote_into(name, qname, sizeof(qname));
1318+ extra = qname;
1319+ }
1320+ if (extra[0])
1321+ snprintf(args, sizeof(args), "--finish %s --name %s%s",
1322+ qcode, extra, force ? " --force" : "");
1323+ else
1324+ snprintf(args, sizeof(args), "--finish %s%s", qcode, force ? " --force" : "");
1325+ }
1326+
1327+ buf_init(&out);
1328+ {
1329+ int rc = run_capture(login_bin(), args, &out);
1330+ if (rc <= 0) {
1331+ buf_free(&out);
1332+ emit_error(200, "OK", "cli_unavailable",
1333+ "the login CLI is not on this node; install SCORPIOX CODE or set CLAUDE_LOGIN_BIN");
1334+ return 1;
1335+ }
1336+ }
1337+ j = last_json_line(&out);
1338+ if (!j) {
1339+ buf_free(&out);
1340+ emit_error(200, "OK", "finish_failed", "the login CLI returned no JSON");
1341+ return 1;
1342+ }
1343+ {
1344+ const char *end = j + strlen(j);
1345+ if (!json_bool_field(j, end, "ok", 0)) {
1346+ char detail[FIELD_SZ] = {0};
1347+ json_str_field(j, end, "error", detail, sizeof(detail));
1348+ buf_free(&out);
1349+ emit_error(200, "OK", detail[0] ? detail : "finish_failed",
1350+ "Claude rejected the code, or it has already been used or has expired");
1351+ return 1;
1352+ }
1353+ }
1354+ buf_free(&out);
1355+
1356+ {
1357+ status_t st;
1358+ collect_status(&st, name);
1359+ buf_init(&b);
1360+ buf_adds(&b, "{\"ok\":true,\"state\":\"done\",");
1361+ emit_status(&b, &st);
1362+ buf_adds(&b, "}\n");
1363+ json_headers();
1364+ fputs(buf_str(&b), stdout);
1365+ buf_free(&b);
1366+ }
1367+ return 0;
1368+}
1369+
1370+static int action_cancel(const char *name)
1371+{
1372+ buf_t out, b;
1373+ char args[NAME_SZ + 32];
1374+
1375+ if (name && *name) {
1376+ char qname[NAME_SZ * 2];
1377+ shell_quote_into(name, qname, sizeof(qname));
1378+ snprintf(args, sizeof(args), "--cancel --name %s", qname);
1379+ } else {
1380+ snprintf(args, sizeof(args), "--cancel");
1381+ }
1382+
1383+ buf_init(&out);
1384+ run_capture(login_bin(), args, &out);
1385+ buf_free(&out);
1386+
1387+ buf_init(&b);
1388+ buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n");
1389+ json_headers();
1390+ fputs(buf_str(&b), stdout);
1391+ buf_free(&b);
1392+ return 0;
1393+}
1394+
1395+/* Refresh: the refresh CLI performs the refresh-token grant and updates the
1396+ * credentials file in place. Its stdout is human text (and may quote token
1397+ * material), so the payload is read, then discarded. The new state is proven
1398+ * by re-reading the file, not by the CLI's word. */
1399+static int action_refresh(const char *name)
1400+{
1401+ buf_t out, b;
1402+ char args[PATH_SZ + 96];
1403+ char qpath[PATH_SZ * 2];
1404+ char path[PATH_SZ];
1405+ long long before;
1406+ status_t st;
1407+
1408+ if (name && *name) account_path(name, path, sizeof(path));
1409+ else creds_path(path, sizeof(path));
1410+
1411+ if (!file_exists(path)) {
1412+ buf_init(&b);
1413+ buf_adds(&b, "{\"ok\":false,\"error\":\"no_credentials\",\"detail\":");
1414+ buf_json(&b, "there is no credentials file on this node; start a login first");
1415+ buf_adds(&b, "}\n");
1416+ json_headers();
1417+ fputs(buf_str(&b), stdout);
1418+ buf_free(&b);
1419+ return 1;
1420+ }
1421+
1422+ collect_status(&st, name);
1423+ before = st.expires_at;
1424+
1425+ shell_quote_into(path, qpath, sizeof(qpath));
1426+ /* action=refresh means "refresh now", so the CLI is always invoked with
1427+ * --force: without it the CLI no-ops on a still-valid token and the user's
1428+ * button does nothing. */
1429+ snprintf(args, sizeof(args), "--credentials-file %s --force", qpath);
1430+
1431+ buf_init(&out);
1432+ {
1433+ int rc = run_capture(refresh_bin(), args, &out);
1434+ if (rc <= 0) {
1435+ buf_free(&out);
1436+ emit_error(200, "OK", "cli_unavailable",
1437+ "the refresh CLI is not on this node; install SCORPIOX CODE or set CLAUDE_REFRESH_BIN");
1438+ return 1;
1439+ }
1440+ }
1441+ buf_free(&out);
1442+
1443+ collect_status(&st, name);
1444+ if (!st.logged_in || (before > 0 && st.expires_at <= before && !st.expired)) {
1445+ buf_init(&b);
1446+ buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":");
1447+ buf_json(&b, "the refresh CLI did not update the credentials file; sign in again");
1448+ buf_adds(&b, "}\n");
1449+ json_headers();
1450+ fputs(buf_str(&b), stdout);
1451+ buf_free(&b);
1452+ return 1;
1453+ }
1454+
1455+ buf_init(&b);
1456+ buf_adds(&b, "{\"ok\":true,\"refreshed\":true,");
1457+ emit_status(&b, &st);
1458+ buf_adds(&b, "}\n");
1459+ json_headers();
1460+ fputs(buf_str(&b), stdout);
1461+ buf_free(&b);
1462+ return 0;
1463+}
1464+
1465+/* ------------------------------------------------------------------ */
1466+/* HTML emission */
1467+/* ------------------------------------------------------------------ */
1468+
1469+/* Expand the two placeholders tools/gen_ui.py leaves in UI_HTML. Keeping the
1470+ * split means the palette lives in exactly one place (bot_theme_plugin.h) and
1471+ * the page can never drift away from the bot's own theme. */
1472+static void emit_ui(void)
1473+{
1474+ const char *p = UI_HTML;
1475+
1476+ while (*p) {
1477+ if (*p == '\001') {
1478+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout);
1479+ p++;
1480+ } else if (*p == '\002') {
1481+ /* SX_BOT_THEME_HANDOFF and SX_BOT_THEME_TOGGLE_JS are both complete
1482+ * <script>...</script> strings, so they are emitted as siblings.
1483+ * Without the toggle macro the page's Theme button is inert: the
1484+ * bot owns the theme, but a plugin opened in its own tab needs a
1485+ * switch of its own. */
1486+ fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout);
1487+ p++;
1488+ } else {
1489+ putchar(*p++);
1490+ }
1491+ }
1492+}
1493+
1494+/* Read a POST body field of the form "code":"..." (a long code is easier to
1495+ * send in a body than in a URL). Guarded on CONTENT_LENGTH so an empty
1496+ * inherited stdin can never block. */
1497+static int body_field(const char *field, char *out, size_t outsz)
1498+{
1499+ const char *cl = getenv("CONTENT_LENGTH");
1500+ long n = (cl && *cl) ? atol(cl) : 0;
1501+ char *body;
1502+ size_t len;
1503+ int got = 0;
1504+
1505+ if (n <= 0 || n > (long)(256 * 1024)) return 0;
1506+ body = (char *)malloc((size_t)n + 1);
1507+ if (!body) return 0;
1508+ len = fread(body, 1, (size_t)n, stdin);
1509+ body[len] = '\0';
1510+ {
1511+ char *p = strstr(body, field);
1512+ if (p) {
1513+ p = strchr(p, ':');
1514+ if (p) {
1515+ size_t i = 0;
1516+ p++;
1517+ while (*p == ' ' || *p == '\t') p++;
1518+ if (*p == '"') p++;
1519+ while (*p && *p != '"' && i + 1 < outsz) out[i++] = *p++;
1520+ out[i] = '\0';
1521+ got = i > 0;
1522+ }
1523+ }
1524+ }
1525+ free(body);
1526+ return got;
1527+}
1528+
1529+/* ------------------------------------------------------------------ */
1530+/* main */
1531+/* ------------------------------------------------------------------ */
1532+
1533+int main(int argc, char **argv)
1534+{
1535+ const char *qs;
1536+ char action[64] = {0};
1537+ char name[NAME_SZ] = {0};
1538+ char code[CODE_MAX] = {0};
1539+ int force = 0;
1540+
1541+ /* 1. Discovery metadata. Must stay unauthenticated. */
1542+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1543+ puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}");
1544+ return 0;
1545+ }
1546+ if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
1547+ puts(PLUGIN_ID " " PLUGIN_VER);
1548+ return 0;
1549+ }
1550+
1551+ require_node_auth();
1552+
1553+ qs = getenv("QUERY_STRING");
1554+ if (!qs) qs = "";
1555+
1556+ get_query_val(qs, "name", name, sizeof(name));
1557+ if (name[0] && !name_valid(name)) {
1558+ emit_error(400, "Bad Request", "bad_name", "account names use letters, digits, - _ . (max 64)");
1559+ return 1;
1560+ }
1561+ {
1562+ char f[8] = {0};
1563+ if (get_query_val(qs, "force", f, sizeof(f)))
1564+ force = (f[0] == '1' || f[0] == 't' || f[0] == 'T' || f[0] == 'y');
1565+ }
1566+
1567+ /* 2. JSON API mode. `format=json` alone means "status", which is what a
1568+ * dashboard polls. */
1569+ if (query_has(qs, "action") || query_has(qs, "format")) {
1570+ char fmt[32] = {0};
1571+
1572+ get_query_val(qs, "action", action, sizeof(action));
1573+ get_query_val(qs, "format", fmt, sizeof(fmt));
1574+ if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status");
1575+
1576+ if (strcmp(action, "status") == 0 || !action[0]) return action_status(name);
1577+ if (strcmp(action, "start") == 0) return action_start(name, force);
1578+ if (strcmp(action, "cancel") == 0) return action_cancel(name);
1579+ if (strcmp(action, "refresh") == 0) return action_refresh(name);
1580+ if (strcmp(action, "accounts") == 0) return action_status(name);
1581+ if (strcmp(action, "finish") == 0) {
1582+ if (!get_query_val(qs, "code", code, sizeof(code))) {
1583+ if (!body_field("\"code\"", code, sizeof(code))) {
1584+ emit_error(400, "Bad Request", "missing_code",
1585+ "pass the authorization code as &code=...");
1586+ return 1;
1587+ }
1588+ }
1589+ return action_finish(code, name, force);
1590+ }
1591+ emit_error(404, "Not Found", "unknown_action", action);
1592+ return 1;
1593+ }
1594+
1595+ /* 3. HTML UI. UI_HTML carries two control bytes: 0x01 is the theme block
1596+ * (<style> with the bot tokens) and 0x02 is the handoff script before
1597+ * </body>. */
1598+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1599+ "Cache-Control: no-store\r\n"
1600+ "X-Content-Type-Options: nosniff\r\n"
1601+ "Referrer-Policy: no-referrer\r\n"
1602+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
1603+ "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
1604+ "base-uri 'none'; form-action 'none'; frame-ancestors *\r\n\r\n", stdout);
1605+ emit_ui();
1606+ return 0;
1607+}
src/ui.html+399−0■■■■■
11new file mode 100644
index 0000000..59081e6
--- /dev/null
+++ b/src/ui.html
@@ -0,0 +1,399 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>claude</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0;min-height:100%}
9+body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;
10+ line-height:1.5;-webkit-font-smoothing:antialiased}
11+#app{max-width:840px;margin:0 auto;padding:16px 16px 40px}
12+.hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}
13+.hd .grow{flex:1 1 auto;min-width:0}
14+.hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}
15+.hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;
16+ overflow:hidden;text-overflow:ellipsis}
17+.pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;
18+ padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);
19+ border:1px solid var(--line);white-space:nowrap}
20+.pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}
21+.pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}
22+.pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}
23+.pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}
24+.pill.warn .dot{background:var(--orange)}
25+.pill.off .dot{background:var(--gray)}
26+.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;
27+ padding:16px;margin-bottom:12px}
28+.card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;
29+ text-transform:uppercase;color:var(--text-2)}
30+.card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}
31+.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
32+.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;
33+ font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;
34+ transition:transform .12s var(--ease),opacity .12s}
35+.btn:active{transform:scale(.98)}
36+.btn:disabled{opacity:.5;cursor:default}
37+.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}
38+.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}
39+.btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}
40+a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}
41+.kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}
42+.kv .k{color:var(--text-2);font-size:12px}
43+.kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}
44+.kv .v.plain{font-family:var(--font);font-size:13px}
45+.step{display:none}
46+.step.on{display:block}
47+.hint{margin:10px 0 0;font-size:12px;color:var(--text-2)}
48+.note{font-size:12.5px;margin-top:10px;display:none}
49+.note.show{display:block}
50+.note.err{color:var(--red)}
51+.note.ok{color:var(--green)}
52+.authurl{font-family:var(--mono);font-size:11.5px;color:var(--text-2);word-break:break-all;
53+ background:var(--code-bg);border:1px solid var(--line);border-radius:10px;
54+ padding:10px;margin-top:10px;max-height:120px;overflow:auto}
55+textarea{width:100%;margin-top:10px;min-height:74px;resize:vertical;background:var(--input-bg);
56+ color:var(--text);border:1px solid var(--line);border-radius:10px;padding:10px;
57+ font-family:var(--mono);font-size:12px;outline:none}
58+textarea:focus{border-color:var(--blue)}
59+.count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}
60+.count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}
61+.bar{height:6px;border-radius:999px;background:var(--surface-2);overflow:hidden;margin-top:10px}
62+.bar .fill{display:block;height:100%;background:var(--green);border-radius:999px;
63+ transition:width .3s var(--ease)}
64+.bar.warn .fill{background:var(--orange)}
65+.bar.err .fill{background:var(--red)}
66+.spin{width:12px;height:12px;border-radius:50%;border:2px solid rgba(255,255,255,.35);
67+ border-top-color:#fff;display:none;animation:sp .7s linear infinite}
68+.btn.loading .spin{display:inline-block}
69+@keyframes sp{to{transform:rotate(360deg)}}
70+.acct{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--line);
71+ font-size:13px;flex-wrap:wrap}
72+.acct:first-of-type{border-top:0}
73+.acct .nm{font-family:var(--mono);font-size:12px;flex:1 1 120px;min-width:0;
74+ overflow:hidden;text-overflow:ellipsis}
75+.acct .tag{font-size:11px;color:var(--text-2)}
76+.acct .tag.ok{color:var(--green)}
77+.acct .tag.warn{color:var(--orange)}
78+.empty{padding:10px 0;color:var(--text-2);font-size:12.5px}
79+.toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;
80+ pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);
81+ color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;
82+ box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);
83+ z-index:9;max-width:calc(100vw - 32px)}
84+.toast.show{opacity:1;transform:translate(-50%,0)}
85+#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);
86+ border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;
87+ font-family:inherit}
88+@media (max-width:520px){
89+ #app{padding:12px 12px 32px}
90+ .kv{grid-template-columns:1fr;gap:2px 0}
91+ .kv .k{margin-top:8px}
92+ .card{padding:13px;border-radius:12px}
93+ .count{font-size:28px}
94+}
95+</style>
96+</head>
97+<body>
98+<div id="app">
99+ <div class="hd">
100+ <div class="grow">
101+ <h1>Claude Code</h1>
102+ <div class="sub" id="sub">OAuth PKCE login on this node</div>
103+ </div>
104+ <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span>
105+ <button id="themeToggle" class="embed-hide" type="button">Theme</button>
106+ </div>
107+
108+ <div class="card">
109+ <h2>Session</h2>
110+ <p class="lead" id="sessionLead">Reading the local Claude Code credentials.</p>
111+ <div class="count" id="count">-</div>
112+ <div class="bar" id="bar"><span class="fill" id="fill" style="width:0%"></span></div>
113+ <div class="kv" id="session" style="margin-top:14px"></div>
114+ <div class="row" style="margin-top:14px">
115+ <button class="btn ghost" id="btnRefresh" type="button"><span class="spin"></span>Refresh Token Now</button>
116+ <button class="btn ghost" id="btnReload" type="button">Reload</button>
117+ </div>
118+ <div class="note" id="refreshNote"></div>
119+ </div>
120+
121+ <div class="card">
122+ <h2>OAuth login</h2>
123+ <p class="lead">Sign in with Claude. Nothing leaves this node: the login CLI performs the
124+ exchange and writes the credential file here.</p>
125+
126+ <div class="step on" id="step1">
127+ <div class="row">
128+ <button class="btn" id="btnStart" type="button">Start Claude Login</button>
129+ <button class="btn ghost" id="btnRelogin" type="button">Re-login (replace)</button>
130+ </div>
131+ <p class="hint">This generates a PKCE challenge and an authorization link. No token is
132+ created until you paste the code back.</p>
133+ </div>
134+
135+ <div class="step" id="step2">
136+ <div class="row">
137+ <a class="btn" id="linkOpen" href="#" target="_blank" rel="noopener noreferrer">Open Claude.ai</a>
138+ <button class="btn ghost" id="btnCopy" type="button">Copy link</button>
139+ <button class="btn ghost" id="btnCancel" type="button">Cancel</button>
140+ </div>
141+ <div class="authurl" id="authUrl"></div>
142+ <p class="hint" id="flowHint">After approving, Claude shows an authorization code. Paste the
143+ whole redirect address or just the <span style="font-family:var(--mono)">code=</span> value below.</p>
144+ <textarea id="codeInput" spellcheck="false" autocomplete="off"
145+ placeholder="Paste the authorization code or the full redirect URL"></textarea>
146+ <div class="row" style="margin-top:10px">
147+ <button class="btn" id="btnFinish" type="button">Submit Code</button>
148+ </div>
149+ <div class="note" id="loginNote"></div>
150+ </div>
151+ </div>
152+
153+ <div class="card">
154+ <h2>Named accounts</h2>
155+ <p class="lead">Every account file in the local accounts directory.</p>
156+ <div id="accounts"><div class="empty">No named accounts.</div></div>
157+ </div>
158+</div>
159+
160+<div class="toast" id="toast"></div>
161+
162+<script>
163+var q=new URLSearchParams(location.search);
164+var node=q.get('node')||'';
165+var sid=q.get('id')||'';
166+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
167+ localStorage.getItem('bot_active_pwd')||'';
168+
169+/* Two call routes. Getting this wrong is the most common plugin bug:
170+ * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)
171+ * -> call the hub proxy back: /plugins?plugin=plugin_claudecode_login&action=..
172+ * opened directly on the node
173+ * -> the plugin itself is the route: /plugin_claudecode_login?action=..
174+ * Calling /plugins?plugin= on the node returns the discovery list, not us. */
175+var HUB=q.get('plugin')||'';
176+function url(action,extra){
177+ return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_claudecode_login')+
178+ '?action='+encodeURIComponent(action)+
179+ (extra?('&'+extra):'')+
180+ (node?'&node='+encodeURIComponent(node):'')+
181+ (sid?'&id='+encodeURIComponent(sid):'')+
182+ (pwd?'&pwd='+encodeURIComponent(pwd):'');
183+}
184+function hdr(){
185+ var h={};
186+ if(pwd)h['X-Bot-Password']=pwd;
187+ return h;
188+}
189+function api(action,extra){
190+ return fetch(url(action,extra),{headers:hdr()}).then(function(r){
191+ return r.json().catch(function(){return {ok:false,error:'bad response'};});
192+ });
193+}
194+
195+var $=function(id){return document.getElementById(id);};
196+function toast(msg){
197+ var t=$('toast');t.textContent=msg;t.classList.add('show');
198+ clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);
199+}
200+function note(el,msg,kind){
201+ el.textContent=msg||'';
202+ el.className='note'+(msg?' show '+(kind||''):'');
203+}
204+function kv(el,rows){
205+ el.innerHTML='';
206+ rows.forEach(function(r){
207+ var a=document.createElement('div');a.className='k';a.textContent=r[0];
208+ var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');
209+ b.textContent=r[1];el.appendChild(a);el.appendChild(b);
210+ });
211+}
212+function fmtExpiry(sec){
213+ if(typeof sec!=='number')return '-';
214+ if(sec<=0)return 'expired';
215+ if(sec<90)return sec+'s';
216+ if(sec<5400)return Math.round(sec/60)+' min';
217+ if(sec<172800)return Math.round(sec/3600)+' h';
218+ if(sec<63072000)return Math.round(sec/86400)+' d';
219+ return Math.round(sec/31536000)+' yr';
220+}
221+function countdown(sec){
222+ if(typeof sec!=='number'||sec<=0)return ['-',''];
223+ var d=Math.floor(sec/86400),h=Math.floor((sec%86400)/3600),
224+ m=Math.floor((sec%3600)/60),s=sec%60,u='second';
225+ var v,d2;
226+ if(d>0){v=d;u='day';d2=[h+'h',m+'m'].join(' ');}
227+ else if(h>0){v=h;u='hour';d2=[m+'m'].join(' ');}
228+ else if(m>0){v=m;u='minute';d2=[s+'s'].join(' ');}
229+ else {v=s;d2='';}
230+ return [v+' <small>'+(v===1?u:u+'s')+(d2?' &middot; '+d2:'')+'</small>',''];
231+}
232+function setPill(st){
233+ var p=$('pill'),t=$('pillText');
234+ if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}
235+ else if(st.logged_in){p.className='pill ok';t.textContent='Logged In';}
236+ else if(st.pending){p.className='pill warn';t.textContent='Signing in';}
237+ else {p.className='pill off';t.textContent='Not Connected';}
238+}
239+/* Full token lifetime is 8 h for a Claude Code session; the bar is a share of
240+ * the remaining time, so it is a coarse but honest "how much is left" read.
241+ * A countdown of 0 with a refresh token present is the normal steady state. */
242+var LIFETIME=8*3600;
243+function render(st){
244+ setPill(st);
245+ $('sub').textContent=st.account?st.account:'OAuth PKCE login on this node';
246+
247+ if(st.logged_in){
248+ $('sessionLead').textContent=st.expired
249+ ? 'The session is present but its access token has expired. Use Refresh Token Now.'
250+ : 'This node holds a Claude Code session.';
251+ }else{
252+ $('sessionLead').textContent='No Claude Code session on this node yet. Start a login below.';
253+ }
254+
255+ var c=countdown(st.expires_in_sec);
256+ $('count').innerHTML=st.logged_in?c[0]:'not connected';
257+ var pct=0;
258+ if(st.logged_in&&st.expires_in_sec>0){
259+ pct=Math.max(2,Math.min(100,Math.round(st.expires_in_sec/LIFETIME*100)));
260+ }
261+ $('fill').style.width=pct+'%';
262+ $('bar').className='bar'+(st.expired?' err':(pct<20?' warn':''));
263+ if(!st.logged_in)$('bar').className='bar';
264+
265+ kv($('session'),[
266+ ['Account', st.account||'-', true],
267+ ['Logged in', st.logged_in?'yes':'no', true],
268+ ['Refresh token', st.has_refresh?'stored':'none', true],
269+ ['Token expires', st.logged_in?fmtExpiry(st.expires_in_sec):'-', true],
270+ ['Subscription', st.subscription||'-', true],
271+ ['Login pending', st.pending?'yes':'no', true],
272+ ['Login CLI', st.cli_present?'found':'not found', true],
273+ ['Profile', st.profile_exists?(st.profile||'claude_code'):'not created', true],
274+ ['Credentials', st.credentials_path||'-']
275+ ]);
276+
277+ var box=$('accounts');
278+ box.innerHTML='';
279+ var list=st.accounts||[];
280+ if(!list.length){
281+ var e=document.createElement('div');e.className='empty';
282+ e.textContent='No named accounts.';box.appendChild(e);
283+ }else{
284+ list.forEach(function(a){
285+ var row=document.createElement('div');row.className='acct';
286+ var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;
287+ var tg=document.createElement('div');
288+ tg.className='tag '+(a.logged_in?(a.expired?'warn':'ok'):'');
289+ tg.textContent=a.logged_in?(a.expired?'expired':'valid'):'no token';
290+ row.appendChild(nm);row.appendChild(tg);box.appendChild(row);
291+ });
292+ }
293+
294+ if(st.pending){$('step1').classList.remove('on');$('step2').classList.add('on');}
295+}
296+function load(){
297+ return api('status').then(function(d){
298+ if(d&&d.ok)render(d);
299+ else toast((d&&d.error)||'status failed');
300+ }).catch(function(e){toast('Status failed: '+e.message);});
301+}
302+
303+var authUrl='';
304+function start(force){
305+ var b=force?$('btnRelogin'):$('btnStart');
306+ b.disabled=true;b.textContent='Starting...';
307+ api('start',force?'force=1':'').then(function(d){
308+ b.disabled=false;b.textContent=force?'Re-login (replace)':'Start Claude Login';
309+ if(!d||!d.ok){toast((d&&(d.detail||d.error))||'start failed');return;}
310+ authUrl=d.auth_url||'';
311+ $('authUrl').textContent=authUrl;
312+ $('linkOpen').setAttribute('href',authUrl);
313+ if(d.hint)$('flowHint').textContent=d.hint;
314+ $('step1').classList.remove('on');
315+ $('step2').classList.add('on');
316+ $('codeInput').focus();
317+ }).catch(function(e){
318+ b.disabled=false;b.textContent=force?'Re-login (replace)':'Start Claude Login';
319+ toast('Start failed: '+e.message);
320+ });
321+}
322+
323+function finish(){
324+ var raw=$('codeInput').value.trim();
325+ if(!raw){note($('loginNote'),'Paste the code or the redirect address first.','err');return;}
326+ var b=$('btnFinish');
327+ b.disabled=true;b.textContent='Exchanging...';
328+ note($('loginNote'),'Exchanging the code for a token.');
329+ api('finish','code='+encodeURIComponent(raw)).then(function(d){
330+ b.disabled=false;b.textContent='Submit Code';
331+ if(!d||!d.ok){
332+ note($('loginNote'),(d&&(d.detail||d.error))||'exchange failed','err');
333+ return;
334+ }
335+ note($('loginNote'),'');
336+ $('step2').classList.remove('on');
337+ $('step1').classList.add('on');
338+ $('codeInput').value='';
339+ render(d);
340+ toast('Signed in as '+(d.account||'Claude account'));
341+ }).catch(function(e){
342+ b.disabled=false;b.textContent='Submit Code';
343+ note($('loginNote'),'Exchange failed: '+e.message,'err');
344+ });
345+}
346+
347+function cancel(){
348+ api('cancel').then(function(){
349+ $('step2').classList.remove('on');
350+ $('step1').classList.add('on');
351+ $('codeInput').value='';
352+ note($('loginNote'),'');
353+ toast('Pending login cancelled');
354+ load();
355+ }).catch(function(e){toast('Cancel failed: '+e.message);});
356+}
357+
358+function refreshToken(){
359+ var b=$('btnRefresh');
360+ b.disabled=true;b.classList.add('loading');
361+ b.lastChild.textContent=' Refreshing...';
362+ note($('refreshNote'),'Asking Claude for a new access token...');
363+ api('refresh').then(function(d){
364+ b.disabled=false;b.classList.remove('loading');
365+ b.lastChild.textContent='Refresh Token Now';
366+ if(!d||!d.ok){
367+ note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');
368+ return;
369+ }
370+ note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');
371+ render(d);
372+ }).catch(function(e){
373+ b.disabled=false;b.classList.remove('loading');
374+ b.lastChild.textContent='Refresh Token Now';
375+ note($('refreshNote'),'Refresh failed: '+e.message,'err');
376+ });
377+}
378+
379+function copyLink(){
380+ if(!authUrl)return;
381+ var done=function(){toast('Link copied');};
382+ if(navigator.clipboard&&navigator.clipboard.writeText){
383+ navigator.clipboard.writeText(authUrl).then(done).catch(function(){toast('Copy failed');});
384+ }else{toast('Copy not available');}
385+}
386+
387+$('btnStart').onclick=function(){start(false);};
388+$('btnRelogin').onclick=function(){start(true);};
389+$('btnFinish').onclick=finish;
390+$('btnCancel').onclick=cancel;
391+$('btnRefresh').onclick=refreshToken;
392+$('btnReload').onclick=load;
393+$('btnCopy').onclick=copyLink;
394+$('codeInput').addEventListener('keydown',function(e){
395+ if(e.key==='Enter'&&(e.metaKey||e.ctrlKey)){e.preventDefault();finish();}
396+});
397+load();
398+</script>
399+</body></html>
src/ui_html.h+407−0■■■■■
11new file mode 100644
index 0000000..d3accf2
--- /dev/null
+++ b/src/ui_html.h
@@ -0,0 +1,407 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_CCLOGIN_UI_HTML_H
3+#define SX_CCLOGIN_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n"
9+ "<title>claude</title>\n"
10+ "\001\n"
11+ "<style>\n"
12+ "*{box-sizing:border-box}\n"
13+ "html,body{margin:0;min-height:100%}\n"
14+ "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n"
15+ " line-height:1.5;-webkit-font-smoothing:antialiased}\n"
16+ "#app{max-width:840px;margin:0 auto;padding:16px 16px 40px}\n"
17+ ".hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n"
18+ ".hd .grow{flex:1 1 auto;min-width:0}\n"
19+ ".hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}\n"
20+ ".hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;\n"
21+ " overflow:hidden;text-overflow:ellipsis}\n"
22+ ".pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;\n"
23+ " padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);\n"
24+ " border:1px solid var(--line);white-space:nowrap}\n"
25+ ".pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}\n"
26+ ".pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n"
27+ ".pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}\n"
28+ ".pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n"
29+ ".pill.warn .dot{background:var(--orange)}\n"
30+ ".pill.off .dot{background:var(--gray)}\n"
31+ ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n"
32+ " padding:16px;margin-bottom:12px}\n"
33+ ".card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;\n"
34+ " text-transform:uppercase;color:var(--text-2)}\n"
35+ ".card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}\n"
36+ ".row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\n"
37+ ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;\n"
38+ " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;\n"
39+ " transition:transform .12s var(--ease),opacity .12s}\n"
40+ ".btn:active{transform:scale(.98)}\n"
41+ ".btn:disabled{opacity:.5;cursor:default}\n"
42+ ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n"
43+ ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n"
44+ ".btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}\n"
45+ "a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}\n"
46+ ".kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}\n"
47+ ".kv .k{color:var(--text-2);font-size:12px}\n"
48+ ".kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}\n"
49+ ".kv .v.plain{font-family:var(--font);font-size:13px}\n"
50+ ".step{display:none}\n"
51+ ".step.on{display:block}\n"
52+ ".hint{margin:10px 0 0;font-size:12px;color:var(--text-2)}\n"
53+ ".note{font-size:12.5px;margin-top:10px;display:none}\n"
54+ ".note.show{display:block}\n"
55+ ".note.err{color:var(--red)}\n"
56+ ".note.ok{color:var(--green)}\n"
57+ ".authurl{font-family:var(--mono);font-size:11.5px;color:var(--text-2);word-break:break-all;\n"
58+ " background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n"
59+ " padding:10px;margin-top:10px;max-height:120px;overflow:auto}\n"
60+ "textarea{width:100%;margin-top:10px;min-height:74px;resize:vertical;background:var(--input-bg);\n"
61+ " color:var(--text);border:1px solid var(--line);border-radius:10px;padding:10px;\n"
62+ " font-family:var(--mono);font-size:12px;outline:none}\n"
63+ "textarea:focus{border-color:var(--blue)}\n"
64+ ".count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}\n"
65+ ".count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}\n"
66+ ".bar{height:6px;border-radius:999px;background:var(--surface-2);overflow:hidden;margin-top:10px}\n"
67+ ".bar .fill{display:block;height:100%;background:var(--green);border-radius:999px;\n"
68+ " transition:width .3s var(--ease)}\n"
69+ ".bar.warn .fill{background:var(--orange)}\n"
70+ ".bar.err .fill{background:var(--red)}\n"
71+ ".spin{width:12px;height:12px;border-radius:50%;border:2px solid rgba(255,255,255,.35);\n"
72+ " border-top-color:#fff;display:none;animation:sp .7s linear infinite}\n"
73+ ".btn.loading .spin{display:inline-block}\n"
74+ "@keyframes sp{to{transform:rotate(360deg)}}\n"
75+ ".acct{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--line);\n"
76+ " font-size:13px;flex-wrap:wrap}\n"
77+ ".acct:first-of-type{border-top:0}\n"
78+ ".acct .nm{font-family:var(--mono);font-size:12px;flex:1 1 120px;min-width:0;\n"
79+ " overflow:hidden;text-overflow:ellipsis}\n"
80+ ".acct .tag{font-size:11px;color:var(--text-2)}\n"
81+ ".acct .tag.ok{color:var(--green)}\n"
82+ ".acct .tag.warn{color:var(--orange)}\n"
83+ ".empty{padding:10px 0;color:var(--text-2);font-size:12.5px}\n"
84+ ".toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;\n"
85+ " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n"
86+ " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n"
87+ " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n"
88+ " z-index:9;max-width:calc(100vw - 32px)}\n"
89+ ".toast.show{opacity:1;transform:translate(-50%,0)}\n"
90+ "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n"
91+ " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n"
92+ " font-family:inherit}\n"
93+ "@media (max-width:520px){\n"
94+ " #app{padding:12px 12px 32px}\n"
95+ " .kv{grid-template-columns:1fr;gap:2px 0}\n"
96+ " .kv .k{margin-top:8px}\n"
97+ " .card{padding:13px;border-radius:12px}\n"
98+ " .count{font-size:28px}\n"
99+ "}\n"
100+ "</style>\n"
101+ "</head>\n"
102+ "<body>\n"
103+ "<div id=\"app\">\n"
104+ " <div class=\"hd\">\n"
105+ " <div class=\"grow\">\n"
106+ " <h1>Claude Code</h1>\n"
107+ " <div class=\"sub\" id=\"sub\">OAuth PKCE login on this node</div>\n"
108+ " </div>\n"
109+ " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n"
110+ " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n"
111+ " </div>\n"
112+ "\n"
113+ " <div class=\"card\">\n"
114+ " <h2>Session</h2>\n"
115+ " <p class=\"lead\" id=\"sessionLead\">Reading the local Claude Code credentials.</p>\n"
116+ " <div class=\"count\" id=\"count\">-</div>\n"
117+ " <div class=\"bar\" id=\"bar\"><span class=\"fill\" id=\"fill\" style=\"width:0%\"></span></div>\n"
118+ " <div class=\"kv\" id=\"session\" style=\"margin-top:14px\"></div>\n"
119+ " <div class=\"row\" style=\"margin-top:14px\">\n"
120+ " <button class=\"btn ghost\" id=\"btnRefresh\" type=\"button\"><span class=\"spin\"></span>Refresh Token Now</button>\n"
121+ " <button class=\"btn ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n"
122+ " </div>\n"
123+ " <div class=\"note\" id=\"refreshNote\"></div>\n"
124+ " </div>\n"
125+ "\n"
126+ " <div class=\"card\">\n"
127+ " <h2>OAuth login</h2>\n"
128+ " <p class=\"lead\">Sign in with Claude. Nothing leaves this node: the login CLI performs the\n"
129+ " exchange and writes the credential file here.</p>\n"
130+ "\n"
131+ " <div class=\"step on\" id=\"step1\">\n"
132+ " <div class=\"row\">\n"
133+ " <button class=\"btn\" id=\"btnStart\" type=\"button\">Start Claude Login</button>\n"
134+ " <button class=\"btn ghost\" id=\"btnRelogin\" type=\"button\">Re-login (replace)</button>\n"
135+ " </div>\n"
136+ " <p class=\"hint\">This generates a PKCE challenge and an authorization link. No token is\n"
137+ " created until you paste the code back.</p>\n"
138+ " </div>\n"
139+ "\n"
140+ " <div class=\"step\" id=\"step2\">\n"
141+ " <div class=\"row\">\n"
142+ " <a class=\"btn\" id=\"linkOpen\" href=\"#\" target=\"_blank\" rel=\"noopener noreferrer\">Open Claude.ai</a>\n"
143+ " <button class=\"btn ghost\" id=\"btnCopy\" type=\"button\">Copy link</button>\n"
144+ " <button class=\"btn ghost\" id=\"btnCancel\" type=\"button\">Cancel</button>\n"
145+ " </div>\n"
146+ " <div class=\"authurl\" id=\"authUrl\"></div>\n"
147+ " <p class=\"hint\" id=\"flowHint\">After approving, Claude shows an authorization code. Paste the\n"
148+ " whole redirect address or just the <span style=\"font-family:var(--mono)\">code=</span> value below.</p>\n"
149+ " <textarea id=\"codeInput\" spellcheck=\"false\" autocomplete=\"off\"\n"
150+ " placeholder=\"Paste the authorization code or the full redirect URL\"></textarea>\n"
151+ " <div class=\"row\" style=\"margin-top:10px\">\n"
152+ " <button class=\"btn\" id=\"btnFinish\" type=\"button\">Submit Code</button>\n"
153+ " </div>\n"
154+ " <div class=\"note\" id=\"loginNote\"></div>\n"
155+ " </div>\n"
156+ " </div>\n"
157+ "\n"
158+ " <div class=\"card\">\n"
159+ " <h2>Named accounts</h2>\n"
160+ " <p class=\"lead\">Every account file in the local accounts directory.</p>\n"
161+ " <div id=\"accounts\"><div class=\"empty\">No named accounts.</div></div>\n"
162+ " </div>\n"
163+ "</div>\n"
164+ "\n"
165+ "<div class=\"toast\" id=\"toast\"></div>\n"
166+ "\n"
167+ "<script>\n"
168+ "var q=new URLSearchParams(location.search);\n"
169+ "var node=q.get('node')||'';\n"
170+ "var sid=q.get('id')||'';\n"
171+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n"
172+ " localStorage.getItem('bot_active_pwd')||'';\n"
173+ "\n"
174+ "/* Two call routes. Getting this wrong is the most common plugin bug:\n"
175+ " * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)\n"
176+ " * -> call the hub proxy back: /plugins?plugin=plugin_claudecode_login&action=..\n"
177+ " * opened directly on the node\n"
178+ " * -> the plugin itself is the route: /plugin_claudecode_login?action=..\n"
179+ " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n"
180+ "var HUB=q.get('plugin')||'';\n"
181+ "function url(action,extra){\n"
182+ " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_claudecode_login')+\n"
183+ " '?action='+encodeURIComponent(action)+\n"
184+ " (extra?('&'+extra):'')+\n"
185+ " (node?'&node='+encodeURIComponent(node):'')+\n"
186+ " (sid?'&id='+encodeURIComponent(sid):'')+\n"
187+ " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n"
188+ "}\n"
189+ "function hdr(){\n"
190+ " var h={};\n"
191+ " if(pwd)h['X-Bot-Password']=pwd;\n"
192+ " return h;\n"
193+ "}\n"
194+ "function api(action,extra){\n"
195+ " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n"
196+ " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n"
197+ " });\n"
198+ "}\n"
199+ "\n"
200+ "var $=function(id){return document.getElementById(id);};\n"
201+ "function toast(msg){\n"
202+ " var t=$('toast');t.textContent=msg;t.classList.add('show');\n"
203+ " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n"
204+ "}\n"
205+ "function note(el,msg,kind){\n"
206+ " el.textContent=msg||'';\n"
207+ " el.className='note'+(msg?' show '+(kind||''):'');\n"
208+ "}\n"
209+ "function kv(el,rows){\n"
210+ " el.innerHTML='';\n"
211+ " rows.forEach(function(r){\n"
212+ " var a=document.createElement('div');a.className='k';a.textContent=r[0];\n"
213+ " var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');\n"
214+ " b.textContent=r[1];el.appendChild(a);el.appendChild(b);\n"
215+ " });\n"
216+ "}\n"
217+ "function fmtExpiry(sec){\n"
218+ " if(typeof sec!=='number')return '-';\n"
219+ " if(sec<=0)return 'expired';\n"
220+ " if(sec<90)return sec+'s';\n"
221+ " if(sec<5400)return Math.round(sec/60)+' min';\n"
222+ " if(sec<172800)return Math.round(sec/3600)+' h';\n"
223+ " if(sec<63072000)return Math.round(sec/86400)+' d';\n"
224+ " return Math.round(sec/31536000)+' yr';\n"
225+ "}\n"
226+ "function countdown(sec){\n"
227+ " if(typeof sec!=='number'||sec<=0)return ['-',''];\n"
228+ " var d=Math.floor(sec/86400),h=Math.floor((sec%86400)/3600),\n"
229+ " m=Math.floor((sec%3600)/60),s=sec%60,u='second';\n"
230+ " var v,d2;\n"
231+ " if(d>0){v=d;u='day';d2=[h+'h',m+'m'].join(' ');}\n"
232+ " else if(h>0){v=h;u='hour';d2=[m+'m'].join(' ');}\n"
233+ " else if(m>0){v=m;u='minute';d2=[s+'s'].join(' ');}\n"
234+ " else {v=s;d2='';}\n"
235+ " return [v+' <small>'+(v===1?u:u+'s')+(d2?' &middot; '+d2:'')+'</small>',''];\n"
236+ "}\n"
237+ "function setPill(st){\n"
238+ " var p=$('pill'),t=$('pillText');\n"
239+ " if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}\n"
240+ " else if(st.logged_in){p.className='pill ok';t.textContent='Logged In';}\n"
241+ " else if(st.pending){p.className='pill warn';t.textContent='Signing in';}\n"
242+ " else {p.className='pill off';t.textContent='Not Connected';}\n"
243+ "}\n"
244+ "/* Full token lifetime is 8 h for a Claude Code session; the bar is a share of\n"
245+ " * the remaining time, so it is a coarse but honest \"how much is left\" read.\n"
246+ " * A countdown of 0 with a refresh token present is the normal steady state. */\n"
247+ "var LIFETIME=8*3600;\n"
248+ "function render(st){\n"
249+ " setPill(st);\n"
250+ " $('sub').textContent=st.account?st.account:'OAuth PKCE login on this node';\n"
251+ "\n"
252+ " if(st.logged_in){\n"
253+ " $('sessionLead').textContent=st.expired\n"
254+ " ? 'The session is present but its access token has expired. Use Refresh Token Now.'\n"
255+ " : 'This node holds a Claude Code session.';\n"
256+ " }else{\n"
257+ " $('sessionLead').textContent='No Claude Code session on this node yet. Start a login below.';\n"
258+ " }\n"
259+ "\n"
260+ " var c=countdown(st.expires_in_sec);\n"
261+ " $('count').innerHTML=st.logged_in?c[0]:'not connected';\n"
262+ " var pct=0;\n"
263+ " if(st.logged_in&&st.expires_in_sec>0){\n"
264+ " pct=Math.max(2,Math.min(100,Math.round(st.expires_in_sec/LIFETIME*100)));\n"
265+ " }\n"
266+ " $('fill').style.width=pct+'%';\n"
267+ " $('bar').className='bar'+(st.expired?' err':(pct<20?' warn':''));\n"
268+ " if(!st.logged_in)$('bar').className='bar';\n"
269+ "\n"
270+ " kv($('session'),[\n"
271+ " ['Account', st.account||'-', true],\n"
272+ " ['Logged in', st.logged_in?'yes':'no', true],\n"
273+ " ['Refresh token', st.has_refresh?'stored':'none', true],\n"
274+ " ['Token expires', st.logged_in?fmtExpiry(st.expires_in_sec):'-', true],\n"
275+ " ['Subscription', st.subscription||'-', true],\n"
276+ " ['Login pending', st.pending?'yes':'no', true],\n"
277+ " ['Login CLI', st.cli_present?'found':'not found', true],\n"
278+ " ['Profile', st.profile_exists?(st.profile||'claude_code'):'not created', true],\n"
279+ " ['Credentials', st.credentials_path||'-']\n"
280+ " ]);\n"
281+ "\n"
282+ " var box=$('accounts');\n"
283+ " box.innerHTML='';\n"
284+ " var list=st.accounts||[];\n"
285+ " if(!list.length){\n"
286+ " var e=document.createElement('div');e.className='empty';\n"
287+ " e.textContent='No named accounts.';box.appendChild(e);\n"
288+ " }else{\n"
289+ " list.forEach(function(a){\n"
290+ " var row=document.createElement('div');row.className='acct';\n"
291+ " var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;\n"
292+ " var tg=document.createElement('div');\n"
293+ " tg.className='tag '+(a.logged_in?(a.expired?'warn':'ok'):'');\n"
294+ " tg.textContent=a.logged_in?(a.expired?'expired':'valid'):'no token';\n"
295+ " row.appendChild(nm);row.appendChild(tg);box.appendChild(row);\n"
296+ " });\n"
297+ " }\n"
298+ "\n"
299+ " if(st.pending){$('step1').classList.remove('on');$('step2').classList.add('on');}\n"
300+ "}\n"
301+ "function load(){\n"
302+ " return api('status').then(function(d){\n"
303+ " if(d&&d.ok)render(d);\n"
304+ " else toast((d&&d.error)||'status failed');\n"
305+ " }).catch(function(e){toast('Status failed: '+e.message);});\n"
306+ "}\n"
307+ "\n"
308+ "var authUrl='';\n"
309+ "function start(force){\n"
310+ " var b=force?$('btnRelogin'):$('btnStart');\n"
311+ " b.disabled=true;b.textContent='Starting...';\n"
312+ " api('start',force?'force=1':'').then(function(d){\n"
313+ " b.disabled=false;b.textContent=force?'Re-login (replace)':'Start Claude Login';\n"
314+ " if(!d||!d.ok){toast((d&&(d.detail||d.error))||'start failed');return;}\n"
315+ " authUrl=d.auth_url||'';\n"
316+ " $('authUrl').textContent=authUrl;\n"
317+ " $('linkOpen').setAttribute('href',authUrl);\n"
318+ " if(d.hint)$('flowHint').textContent=d.hint;\n"
319+ " $('step1').classList.remove('on');\n"
320+ " $('step2').classList.add('on');\n"
321+ " $('codeInput').focus();\n"
322+ " }).catch(function(e){\n"
323+ " b.disabled=false;b.textContent=force?'Re-login (replace)':'Start Claude Login';\n"
324+ " toast('Start failed: '+e.message);\n"
325+ " });\n"
326+ "}\n"
327+ "\n"
328+ "function finish(){\n"
329+ " var raw=$('codeInput').value.trim();\n"
330+ " if(!raw){note($('loginNote'),'Paste the code or the redirect address first.','err');return;}\n"
331+ " var b=$('btnFinish');\n"
332+ " b.disabled=true;b.textContent='Exchanging...';\n"
333+ " note($('loginNote'),'Exchanging the code for a token.');\n"
334+ " api('finish','code='+encodeURIComponent(raw)).then(function(d){\n"
335+ " b.disabled=false;b.textContent='Submit Code';\n"
336+ " if(!d||!d.ok){\n"
337+ " note($('loginNote'),(d&&(d.detail||d.error))||'exchange failed','err');\n"
338+ " return;\n"
339+ " }\n"
340+ " note($('loginNote'),'');\n"
341+ " $('step2').classList.remove('on');\n"
342+ " $('step1').classList.add('on');\n"
343+ " $('codeInput').value='';\n"
344+ " render(d);\n"
345+ " toast('Signed in as '+(d.account||'Claude account'));\n"
346+ " }).catch(function(e){\n"
347+ " b.disabled=false;b.textContent='Submit Code';\n"
348+ " note($('loginNote'),'Exchange failed: '+e.message,'err');\n"
349+ " });\n"
350+ "}\n"
351+ "\n"
352+ "function cancel(){\n"
353+ " api('cancel').then(function(){\n"
354+ " $('step2').classList.remove('on');\n"
355+ " $('step1').classList.add('on');\n"
356+ " $('codeInput').value='';\n"
357+ " note($('loginNote'),'');\n"
358+ " toast('Pending login cancelled');\n"
359+ " load();\n"
360+ " }).catch(function(e){toast('Cancel failed: '+e.message);});\n"
361+ "}\n"
362+ "\n"
363+ "function refreshToken(){\n"
364+ " var b=$('btnRefresh');\n"
365+ " b.disabled=true;b.classList.add('loading');\n"
366+ " b.lastChild.textContent=' Refreshing...';\n"
367+ " note($('refreshNote'),'Asking Claude for a new access token...');\n"
368+ " api('refresh').then(function(d){\n"
369+ " b.disabled=false;b.classList.remove('loading');\n"
370+ " b.lastChild.textContent='Refresh Token Now';\n"
371+ " if(!d||!d.ok){\n"
372+ " note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');\n"
373+ " return;\n"
374+ " }\n"
375+ " note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');\n"
376+ " render(d);\n"
377+ " }).catch(function(e){\n"
378+ " b.disabled=false;b.classList.remove('loading');\n"
379+ " b.lastChild.textContent='Refresh Token Now';\n"
380+ " note($('refreshNote'),'Refresh failed: '+e.message,'err');\n"
381+ " });\n"
382+ "}\n"
383+ "\n"
384+ "function copyLink(){\n"
385+ " if(!authUrl)return;\n"
386+ " var done=function(){toast('Link copied');};\n"
387+ " if(navigator.clipboard&&navigator.clipboard.writeText){\n"
388+ " navigator.clipboard.writeText(authUrl).then(done).catch(function(){toast('Copy failed');});\n"
389+ " }else{toast('Copy not available');}\n"
390+ "}\n"
391+ "\n"
392+ "$('btnStart').onclick=function(){start(false);};\n"
393+ "$('btnRelogin').onclick=function(){start(true);};\n"
394+ "$('btnFinish').onclick=finish;\n"
395+ "$('btnCancel').onclick=cancel;\n"
396+ "$('btnRefresh').onclick=refreshToken;\n"
397+ "$('btnReload').onclick=load;\n"
398+ "$('btnCopy').onclick=copyLink;\n"
399+ "$('codeInput').addEventListener('keydown',function(e){\n"
400+ " if(e.key==='Enter'&&(e.metaKey||e.ctrlKey)){e.preventDefault();finish();}\n"
401+ "});\n"
402+ "load();\n"
403+ "</script>\n"
404+ "\002</body></html>\n"
405+ ;
406+
407+#endif /* SX_CCLOGIN_UI_HTML_H */
tests/mock_login.sh+73−0■■■■■
11new file mode 100755
index 0000000..4dfa151
--- /dev/null
+++ b/tests/mock_login.sh
@@ -0,0 +1,73 @@
1+#!/bin/sh
2+# tests/mock_login.sh - stand-in for scorpiox-claudecode-login machine mode.
3+#
4+# Prints exactly the contract shape the real CLI prints (human progress lines
5+# first, one JSON line last), so the plugin's parsers are exercised against the
6+# production layout rather than an invented one. `--finish` writes a credential
7+# file into $CLAUDE_CREDS_PATH so a test can prove the plugin re-reads state.
8+#
9+# MOCK_FAIL=1 makes --finish fail the way Claude does for a used code.
10+
11+CREDS="${CLAUDE_CREDS_PATH:-/nonexistent}"
12+PEND="${CLAUDE_PENDING_DIR:-/nonexistent}/claudecode-default.json"
13+
14+case "$1" in
15+ --status)
16+ _li=false; _hr=false
17+ if [ -f "$CREDS" ] && grep -q 'refreshToken' "$CREDS" 2>/dev/null; then
18+ _li=true; _hr=true
19+ fi
20+ _exp=0
21+ if [ -f "$CREDS" ]; then
22+ _exp=$(sed -n 's/.*"expiresAt"[[:space:]]*:[[:space:]]*\([0-9]*\).*/\1/p' "$CREDS" | head -1)
23+ [ -z "$_exp" ] && _exp=0
24+ fi
25+ printf 'scorpiox-claudecode-login 1.2.3 (SXLOGIN-MACHINE-V1)\n'
26+ printf '{"ok":true,"provider":"claudecode","name":"Claude Code","flow":"paste_code",'
27+ printf '"named_accounts":true,"protocol":"SXLOGIN-MACHINE-V1","account":null,'
28+ printf '"logged_in":%s,"path":"%s","expires_at":%s,'
29+ printf '"expired":false,"has_refresh":%s,"pending":%s,'
30+ printf '"profile":"claude_code","profile_exists":false}\n' \
31+ "$_li" "$CREDS" "$_exp" "$_hr" \
32+ "$([ -f "$PEND" ] && echo true || echo false)"
33+ ;;
34+ --start)
35+ printf 'scorpiox-claudecode-login 1.2.3\n'
36+ printf 'generating PKCE challenge\n'
37+ mkdir -p "$(dirname "$PEND")" 2>/dev/null
38+ printf '{"code_verifier":"verifier-value","state":"st4te-value","created":1}\n' > "$PEND"
39+ printf '{"ok":true,"provider":"claudecode","flow":"paste_code",'
40+ printf '"auth_url":"https://claude.com/cai/oauth/authorize?code=true&client_id=test&state=st4te-value",'
41+ printf '"expires_in":600,"hint":"Sign in, then paste the code shown on the callback page."}\n'
42+ ;;
43+ --finish)
44+ if [ "$MOCK_FAIL" = "1" ]; then
45+ printf '{"ok":false,"provider":"claudecode","error":"exchange","detail":"code already used"}\n'
46+ exit 1
47+ fi
48+ [ -z "$2" ] && { printf '{"ok":false,"error":"no_code"}\n'; exit 1; }
49+ mkdir -p "$(dirname "$CREDS")" 2>/dev/null
50+ _now=$(date +%s)
51+ _exp=$(( (_now + 28800) * 1000 ))
52+ {
53+ printf '{\n "claudeAiOauth": {\n'
54+ printf ' "accessToken": "sk-ant-oat01-MOCK-ACCESS-TOKEN-MUST-NOT-LEAK",\n'
55+ printf ' "refreshToken": "sk-ant-ort01-MOCK-REFRESH-TOKEN-MUST-NOT-LEAK",\n'
56+ printf ' "expiresAt": %s,\n' "$_exp"
57+ printf ' "scopes": ["user:profile","user:inference"],\n'
58+ printf ' "subscriptionType": "pro"\n }\n}\n'
59+ } > "$CREDS"
60+ rm -f "$PEND"
61+ printf 'Login successful\n'
62+ printf '{"ok":true,"provider":"claudecode","logged_in":true,"path":"%s",'
63+ printf '"expires_in":28800,"profile":"claude_code","profile_created":false}\n' "$CREDS"
64+ ;;
65+ --cancel)
66+ rm -f "$PEND"
67+ printf '{"ok":true,"provider":"claudecode","cancelled":true}\n'
68+ ;;
69+ *)
70+ printf '{"ok":false,"error":"usage"}\n'
71+ exit 1
72+ ;;
73+esac
tests/mock_refresh.sh+38−0■■■■■
11new file mode 100755
index 0000000..b291d54
--- /dev/null
+++ b/tests/mock_refresh.sh
@@ -0,0 +1,38 @@
1+#!/bin/sh
2+# tests/mock_refresh.sh - stand-in for scorpiox-claudecode-refreshtoken.
3+#
4+# Mirrors the production program's argument shape (--credentials-file <path>
5+# [--force]) and its behaviour: it rewrites the credentials file in place with a
6+# freshly minted access token and a new expiresAt, and prints human text (which
7+# may include token material) on stdout. The plugin must never forward that.
8+#
9+# MOCK_REFRESH_FAIL=1 exercises the failure path where the file is untouched.
10+
11+CREDS=""
12+FORCE=0
13+while [ $# -gt 0 ]; do
14+ case "$1" in
15+ --credentials-file) shift; CREDS="${1:-}" ;;
16+ --force|-f) FORCE=1 ;;
17+ esac
18+ shift
19+done
20+[ -z "$CREDS" ] && CREDS="${CLAUDE_CREDS_PATH:-/nonexistent}"
21+
22+if [ "$MOCK_REFRESH_FAIL" = "1" ]; then
23+ printf 'error: no refreshToken found in credentials\n' >&2
24+ exit 1
25+fi
26+if [ ! -f "$CREDS" ]; then
27+ printf 'error: cannot read %s\n' "$CREDS" >&2
28+ exit 1
29+fi
30+
31+_now=$(date +%s)
32+_exp=$(( (_now + 28800) * 1000 ))
33+printf 'Claude OAuth Token Auto-Refresh Tool\n\n'
34+printf 'Found Claude config: %s\n' "$CREDS"
35+printf 'Refreshing OAuth token (force=%s)\n' "$FORCE"
36+printf '{"claudeAiOauth":{"accessToken":"sk-ant-oat01-MOCK-REFRESHED-MUST-NOT-LEAK","refreshToken":"sk-ant-ort01-MOCK-REFRESHED","expiresAt":%s,"scopes":["user:profile","user:inference"],"subscriptionType":"pro"}}\n' "$_exp" > "$CREDS"
37+printf 'Token refresh successful\n'
38+exit 0
tests/run.sh+370−0■■■■■
11new file mode 100755
index 0000000..49bb921
--- /dev/null
+++ b/tests/run.sh
@@ -0,0 +1,370 @@
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+
22+set -u
23+
24+ROOT=$(cd "$(dirname "$0")/.." && pwd)
25+cd "$ROOT" || exit 1
26+
27+BIN=./plugin_claudecode_login
28+ID=plugin_claudecode_login
29+PASS=0
30+FAIL=0
31+
32+if [ -t 1 ]; then
33+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
34+else
35+ C_OK=; C_BAD=; C_B=; C_0=
36+fi
37+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
38+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
39+
40+check() { # 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+
46+check_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+
52+check_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+
58+found() { # 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+
65+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
66+
67+# strip CGI headers if present, drop CRs, keep the payload
68+body() {
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+
78+json_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+
87+api() { body "$(QUERY_STRING="$1" $BIN)"; }
88+apiraw() { QUERY_STRING="$1" $BIN; }
89+
90+# ---------------------------------------------------------------- build
91+section "build"
92+if [ ! -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; }
96+fi
97+pass "native binary present"
98+
99+if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
100+ pass "src/ui_html.h is in sync with src/ui.html"
101+else
102+ fail "src/ui_html.h is stale - run tools/gen_ui.py"
103+fi
104+
105+check "ui header is marked generated" \
106+ "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
107+
108+# ---------------------------------------------------------------- --meta
109+section "discovery metadata"
110+META=$(BOT_PASSWORD=testpw $BIN --meta)
111+[ "$META" = '{"name":"claude","desc":"Claude login"}' ] && pass "--meta is exactly the contract string" \
112+ || fail "--meta mismatch: $META"
113+META2=$(SX_PLUGIN_META=1 BOT_PASSWORD=testpw $BIN)
114+check "SX_PLUGIN_META=1 emits the same metadata" '"desc":"Claude login"' "$META2"
115+check "--meta works with an empty env" '"name":"claude"' "$(env -u BOT_PASSWORD $BIN --meta)"
116+json_ok "--meta is valid JSON" "$(env -u BOT_PASSWORD $BIN --meta)" \
117+ 'd["name"]=="claude" and len(d["desc"])<=15'
118+V=$($BIN --version)
119+check "--version names the binary" "$ID" "$V"
120+
121+# ---------------------------------------------------------------- fixtures
122+FIX=$(mktemp -d 2>/dev/null || mktemp -d -t ccfix)
123+trap 'rm -rf "$FIX"' EXIT
124+
125+mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/deep/nested"
126+export CLAUDE_LOGIN_BIN="$ROOT/tests/mock_login.sh"
127+export CLAUDE_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
128+export CLAUDE_PENDING_DIR="$FIX/pend"
129+export CLAUDE_ENV_DIR="$FIX/env"
130+export CLAUDE_ACCOUNTS_DIR="$FIX/acc"
131+export CLAUDE_CREDS_PATH="$FIX/.credentials.json"
132+export BOT_PASSWORD=testpw
133+PWDQ='pwd=testpw'
134+
135+NOW=$(date +%s)
136+FUTURE_MS=$(( (NOW + 7200) * 1000 ))
137+PAST_MS=$(( (NOW - 3600) * 1000 ))
138+
139+mkcreds() { # 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
151+section "node auth gate"
152+RAW=$(apiraw "action=status")
153+check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW"
154+check "401 body is JSON" '"error":"invalid node password"' "$RAW"
155+check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")"
156+check "X-Bot-Password header auth works" '"ok":true' \
157+ "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")"
158+check "Bearer auth works" '"ok":true' \
159+ "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")"
160+check "wrong password still 401s" "Status: 401 Unauthorized" \
161+ "$(QUERY_STRING="action=status&pwd=nope" $BIN)"
162+UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN)
163+check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")"
164+
165+# ---------------------------------------------------------------- status: empty
166+section "status with no credentials"
167+OUT=$(api "action=status&$PWDQ")
168+json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True'
169+json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False'
170+json_ok "empty node is not expired" "$OUT" 'd["expired"] is False'
171+json_ok "empty node carries a zero countdown" "$OUT" 'd["expires_in_sec"]==0'
172+check "empty node reports the credentials path" '"credentials_path"' "$OUT"
173+check "empty node reports the flow" '"flow":"paste_code"' "$OUT"
174+check "empty node reports the protocol marker" 'SXLOGIN-MACHINE-V1' "$OUT"
175+check_not "empty node leaks no token" 'SECRET-ACCESS' "$OUT"
176+OUTF=$(api "format=json&$PWDQ")
177+json_ok "format=json alone means status" "$OUTF" 'd["ok"] is True'
178+
179+# ---------------------------------------------------------------- status: live
180+section "status with a live session"
181+mkcreds "$FIX/.credentials.json" "$FUTURE_MS"
182+printf 'PROVIDER=claude_code\nCLAUDE_CODE_TOKEN_SOURCE=local\nMODEL=claude-opus-4-6\n' > "$FIX/env/claude_code.txt"
183+OUT=$(api "action=status&$PWDQ")
184+json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True'
185+json_ok "live session is not expired" "$OUT" 'd["expired"] is False'
186+json_ok "live session has a refresh token" "$OUT" 'd["has_refresh"] is True'
187+json_ok "live session countdown is positive and near 2h" "$OUT" '7100 < d["expires_in_sec"] <= 7200'
188+json_ok "expiresAt is reported both raw and in seconds" "$OUT" \
189+ 'd["expires_at"]==d["expires_at_sec"]*1000'
190+json_ok "subscription tier is parsed" "$OUT" 'd["subscription"]=="pro"'
191+json_ok "scope names are parsed without JSON punctuation" "$OUT" \
192+ 'd["scopes"]=="user:profile,user:inference,user:sessions:claude_code"'
193+json_ok "profile file is detected" "$OUT" 'd["profile"]=="claude_code" and d["profile_exists"] is True'
194+check_not "status never returns an access token" 'SECRET-ACCESS' "$OUT"
195+check_not "status never returns a refresh token" 'SECRET-REFRESH' "$OUT"
196+check_not "status never returns the key name accessToken" 'accessToken' "$OUT"
197+
198+# expired session
199+mkcreds "$FIX/.credentials.json" "$PAST_MS"
200+OUT=$(api "action=status&$PWDQ")
201+json_ok "expired session is still logged in" "$OUT" 'd["logged_in"] is True'
202+json_ok "expired session is flagged expired" "$OUT" 'd["expired"] is True'
203+json_ok "expired session has a negative countdown" "$OUT" 'd["expires_in_sec"] < 0'
204+
205+# seconds-vs-milliseconds tolerance
206+printf '{"claudeAiOauth":{"accessToken":"a","refreshToken":"b","expiresAt":%s}}\n' "$((NOW + 3600))" \
207+ > "$FIX/.credentials.json"
208+OUT=$(api "action=status&$PWDQ")
209+json_ok "a seconds-based expiresAt is read as seconds" "$OUT" '3500 < d["expires_in_sec"] <= 3600'
210+
211+# malformed / no oauth block
212+printf '{"somethingElse":true}\n' > "$FIX/.credentials.json"
213+OUT=$(api "action=status&$PWDQ")
214+json_ok "a file without claudeAiOauth is not logged in" "$OUT" 'd["logged_in"] is False'
215+printf 'not json at all\n' > "$FIX/.credentials.json"
216+OUT=$(api "action=status&$PWDQ")
217+json_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
220+section "named accounts"
221+mkcreds "$FIX/.credentials.json" "$FUTURE_MS"
222+mkcreds "$FIX/acc/work.json" "$FUTURE_MS"
223+mkcreds "$FIX/acc/old.json" "$PAST_MS"
224+printf '{"claudeAiOauth":{"hasNothing":true}}\n' > "$FIX/acc/notoken.json"
225+OUT=$(api "action=status&$PWDQ")
226+json_ok "named accounts are listed" "$OUT" 'len(d["accounts"])==3'
227+json_ok "a valid account is reported valid" "$OUT" \
228+ '[a for a in d["accounts"] if a["name"]=="work"][0]["expired"] is False'
229+json_ok "a stale account is reported expired" "$OUT" \
230+ '[a for a in d["accounts"] if a["name"]=="old"][0]["expired"] is True'
231+json_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'
233+json_ok "multiple accounts set named_accounts" "$OUT" 'd["named_accounts"] is True'
234+OUT=$(api "action=accounts&$PWDQ")
235+json_ok "action=accounts answers the same shape" "$OUT" 'd["ok"] is True and len(d["accounts"])==3'
236+OUT=$(api "action=status&name=work&$PWDQ")
237+json_ok "status for a named account reads that file" "$OUT" 'd["account"]=="work" and d["logged_in"] is True'
238+check "named account path is reported" "work.json" "$OUT"
239+BADNAME=$(api "action=status&name=../etc&$PWDQ")
240+check "a path-traversal account name is refused" '"error":"bad_name"' "$BADNAME"
241+
242+# ---------------------------------------------------------------- start
243+section "action=start"
244+rm -f "$FIX/pend"/*.json
245+OUT=$(api "action=start&$PWDQ")
246+json_ok "start returns ok" "$OUT" 'd["ok"] is True'
247+json_ok "start returns a paste_code flow" "$OUT" 'd["flow"]=="paste_code"'
248+json_ok "start returns the CLI auth_url" "$OUT" 'd["auth_url"].startswith("https://claude.com/")'
249+json_ok "start carries a PKCE challenge link" "$OUT" '"state=st4te-value" in d["auth_url"]'
250+json_ok "start reports its TTL" "$OUT" 'd["expires_in"]>0'
251+check "start writes the pending file" "" "$(ls "$FIX/pend" | head -1)"
252+OUT=$(api "action=status&$PWDQ")
253+json_ok "status sees the pending flow" "$OUT" 'd["pending"] is True'
254+
255+# ---------------------------------------------------------------- finish
256+section "action=finish"
257+BADCODE=$(api "action=finish&code=abc%27def&$PWDQ")
258+check "a code with a quote is refused locally" '"error":"invalid_code"' "$BADCODE"
259+BADCODE=$(api "action=finish&code=%3Brm%20-rf%20%2F&$PWDQ")
260+check "a shell payload is refused locally" '"error":"invalid_code"' "$BADCODE"
261+NOCODE=$(api "action=finish&$PWDQ")
262+check "finish without a code is a 400" 'missing_code' "$NOCODE"
263+
264+rm -f "$FIX/.credentials.json"
265+api "action=start&$PWDQ" >/dev/null
266+OUT=$(api "action=finish&code=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback%3Fcode%3Dabc123%26state%3Dst4te-value&$PWDQ")
267+json_ok "a pasted redirect URL is accepted (code= extracted)" "$OUT" 'd["ok"] is True'
268+json_ok "finish re-reads state and reports logged in" "$OUT" 'd["logged_in"] is True'
269+json_ok "finish clears the pending flag" "$OUT" 'd["pending"] is False'
270+check_not "finish never echoes the token" 'MUST-NOT-LEAK' "$OUT"
271+
272+api "action=start&$PWDQ" >/dev/null
273+OUT=$(MOCK_FAIL=1 sh -c "QUERY_STRING='action=finish&code=zzz&$PWDQ' $BIN" | tr -d '\r')
274+check "a rejected exchange surfaces the CLI error" '"error":"exchange"' "$OUT"
275+
276+# ---------------------------------------------------------------- cancel
277+section "action=cancel"
278+api "action=start&$PWDQ" >/dev/null
279+OUT=$(api "action=cancel&$PWDQ")
280+json_ok "cancel answers ok" "$OUT" 'd["ok"] is True'
281+json_ok "cancel reports pending false" "$OUT" 'd["pending"] is False'
282+OUT=$(api "action=status&$PWDQ")
283+json_ok "status after cancel shows no pending flow" "$OUT" 'd["pending"] is False'
284+
285+# ---------------------------------------------------------------- refresh
286+section "action=refresh"
287+mkcreds "$FIX/.credentials.json" "$PAST_MS"
288+BEFORE=$(api "action=status&$PWDQ" | python3 -c 'import json,sys;print(json.load(sys.stdin)["expires_at"])' 2>/dev/null)
289+OUT=$(api "action=refresh&$PWDQ")
290+json_ok "refresh answers ok" "$OUT" 'd["ok"] is True'
291+json_ok "refresh reports refreshed:true" "$OUT" 'd["refreshed"] is True'
292+json_ok "refresh moved the expiry forward" "$OUT" 'd["expires_in_sec"]>7000'
293+check_not "refresh never forwards the CLI payload" 'MUST-NOT-LEAK' "$OUT"
294+check_not "refresh never returns an access token key" 'accessToken' "$OUT"
295+
296+OUT=$(MOCK_REFRESH_FAIL=1 sh -c "QUERY_STRING='action=refresh&$PWDQ' $BIN" | tr -d '\r')
297+check "a failed refresh is reported as refresh_failed" '"error":"refresh_failed"' "$OUT"
298+
299+rm -f "$FIX/.credentials.json"
300+OUT=$(api "action=refresh&$PWDQ")
301+check "refresh with no credentials is refused" '"error":"no_credentials"' "$OUT"
302+
303+# ---------------------------------------------------------------- CLI absent
304+section "CLI unavailable"
305+OUT=$(CLAUDE_LOGIN_BIN=/nonexistent/login ${BIN:+env} sh -c "CLAUDE_LOGIN_BIN=/nonexistent/login QUERY_STRING='action=start&$PWDQ' $BIN" | tr -d '\r')
306+check "a missing login CLI is reported as cli_unavailable" 'cli_unavailable' "$OUT"
307+OUT=$(sh -c "CLAUDE_REFRESH_BIN=/nonexistent/refresh CLAUDE_CREDS_PATH='$FIX/nonexist.json' QUERY_STRING='action=refresh&$PWDQ' $BIN" | tr -d '\r')
308+check "refresh with no credentials file says no_credentials" 'no_credentials' "$OUT"
309+
310+# ---------------------------------------------------------------- unknown action
311+section "routing"
312+OUT=$(apiraw "action=bogus&$PWDQ")
313+check "an unknown action is a 404" "Status: 404 Not Found" "$OUT"
314+check "an unknown action names itself" '"error":"unknown_action"' "$OUT"
315+
316+# ---------------------------------------------------------------- HTML page
317+section "HTML UI"
318+PAGE=$(body "$(QUERY_STRING="$PWDQ" $BIN)")
319+check "page is HTML" "Content-Type: text/html" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
320+check "page has a title" "<title>claude</title>" "$PAGE"
321+check "page has the status pill" 'id="pill"' "$PAGE"
322+check "page has the countdown card" 'id="count"' "$PAGE"
323+check "page has the start button" 'id="btnStart"' "$PAGE"
324+check "page has the paste box" 'id="codeInput"' "$PAGE"
325+check "page has the submit button" 'id="btnFinish"' "$PAGE"
326+check "page has the refresh button" 'id="btnRefresh"' "$PAGE"
327+check "page has the cancel button" 'id="btnCancel"' "$PAGE"
328+check "page has the account list" 'id="accounts"' "$PAGE"
329+check "page carries the bot theme prepaint" "bot_theme" "$PAGE"
330+check "page carries the theme handoff listener" "sx-theme" "$PAGE"
331+check "page asks the host for the theme once" "sx-theme-request" "$PAGE"
332+check "page carries the bot token block" "--bg-card" "$PAGE"
333+check "page has a viewport meta" 'name="viewport"' "$PAGE"
334+check "page has a colour-scheme declaration" "color-scheme:dark" "$PAGE"
335+check "page uses the responsive breakpoint" "@media (max-width:520px)" "$PAGE"
336+check_empty "page emits no Content-Length" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r' | grep -i '^Content-Length' || true)"
337+check_not "page loads no CDN script" "<script src=" "$PAGE"
338+check_not "page references no external host" "cdnjs" "$PAGE"
339+check_not "page has no http:// asset" "http://" "$PAGE"
340+check "page CSP forbids remote scripts" "default-src 'none'" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
341+check "page is frameable by the bot" "frame-ancestors *" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
342+
343+# ---------------------------------------------------------------- source hygiene
344+section "source hygiene"
345+SRC=src/plugin_claudecode_login.c
346+check_empty "no emoji in the source" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$SRC" || true)"
347+check_empty "no emoji in the page" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' src/ui.html || true)"
348+check_empty "the source never writes Content-Length" "$(grep -n 'Content-Length' "$SRC" || true)"
349+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)"
350+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)"
351+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)"
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)).
354+HOSTS="macmin""i|intel-ultra""2|lazar""us"
355+check_empty "no fleet host name" "$(grep -nE "$HOSTS" "$SRC" README.md 2>/dev/null || true)"
356+check_empty "the plugin never appends a token field to a response" "$(grep -nE 'buf_adds?\([^)]*accessToken' "$SRC" || true)"
357+found "accessToken is read into a presence-only buffer" \
358+ 'json_str_field(oauth, end, "accessToken", tok, sizeof(tok))' "$SRC"
359+found "argv is shell-quoted before popen" "shell_quote_into" "$SRC"
360+found "authorization codes are validated before quoting" "code_valid(code)" "$SRC"
361+found "the refresh action discards the CLI payload" "buf_free(&out);" "$SRC"
362+found "the plugin reports refreshed:true on a refresh" 'refreshed\":true' "$SRC"
363+check_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
367+printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
368+printf ' %d passed, %d failed\n' "$PASS" "$FAIL"
369+[ "$FAIL" -eq 0 ] || exit 1
370+exit 0
tools/gen_ui.py+105−0■■■■■
11new file mode 100644
index 0000000..514bf68
--- /dev/null
+++ b/tools/gen_ui.py
@@ -0,0 +1,105 @@
1+#!/usr/bin/env python3
2+"""tools/gen_ui.py - compile src/ui.html into src/ui.html.h.
3+
4+The page lives in one readable file (src/ui.html) so it can be diffed and
5+reviewed like any other source. This script turns it into a single C string
6+constant with two control-character placeholders:
7+
8+ 0x01 -> the bot theme prepaint script + <style> + theme tokens
9+ 0x02 -> the bot theme handoff script (just before </body>)
10+
11+main() splits the constant on those bytes and emits the macros from
12+src/bot_theme_plugin.h in their place, so the theme can never drift out of
13+sync with the rest of the bot.
14+
15+ python3 tools/gen_ui.py # write src/ui.html.h
16+ python3 tools/gen_ui.py --check # exit 1 when the header is stale
17+"""
18+
19+import os
20+import sys
21+
22+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23+SRC = os.path.join(ROOT, "src", "ui.html")
24+OUT = os.path.join(ROOT, "src", "ui_html.h")
25+
26+TOKENS = "<!--TOKENS-->"
27+MARK_TOKENS = "\u0001"
28+MARK_HANDOFF = "\u0002"
29+
30+
31+def c_literal(text):
32+ """Escape text for a C string literal, one line per source line."""
33+ out = []
34+ for line in text.splitlines(True):
35+ piece = []
36+ for ch in line:
37+ if ch == "\\":
38+ piece.append("\\\\")
39+ elif ch == '"':
40+ piece.append('\\"')
41+ elif ch == "\n":
42+ piece.append("\\n")
43+ elif ch == "\r":
44+ piece.append("\\r")
45+ elif ch == "\t":
46+ piece.append("\\t")
47+ elif ch == MARK_TOKENS:
48+ piece.append("\\001")
49+ elif ch == MARK_HANDOFF:
50+ piece.append("\\002")
51+ elif ord(ch) < 0x20:
52+ piece.append("\\%03o" % ord(ch))
53+ else:
54+ piece.append(ch)
55+ out.append(' "%s"\n' % "".join(piece))
56+ return "".join(out)
57+
58+
59+def render():
60+ with open(SRC, "r", encoding="utf-8") as f:
61+ html = f.read()
62+
63+ if TOKENS not in html:
64+ raise SystemExit("src/ui.html has no %s placeholder" % TOKENS)
65+ html = html.replace(TOKENS, MARK_TOKENS)
66+
67+ # Handoff script goes right before the closing body tag.
68+ if "</body>" not in html:
69+ raise SystemExit("src/ui.html has no </body>")
70+ html = html.replace("</body>", MARK_HANDOFF + "</body>", 1)
71+
72+ header = (
73+ "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n"
74+ "#ifndef SX_CCLOGIN_UI_HTML_H\n"
75+ "#define SX_CCLOGIN_UI_HTML_H\n"
76+ "\n"
77+ "static const char *UI_HTML =\n" + c_literal(html) + " ;\n"
78+ "\n"
79+ "#endif /* SX_CCLOGIN_UI_HTML_H */\n"
80+ )
81+ return header
82+
83+
84+def main():
85+ header = render()
86+ check = "--check" in sys.argv[1:]
87+ if check:
88+ try:
89+ with open(OUT, "r", encoding="utf-8") as f:
90+ cur = f.read()
91+ except OSError:
92+ cur = ""
93+ if cur != header:
94+ sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n")
95+ return 1
96+ print("src/ui.html.h is up to date")
97+ return 0
98+ with open(OUT, "w", encoding="utf-8") as f:
99+ f.write(header)
100+ print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header)))
101+ return 0
102+
103+
104+if __name__ == "__main__":
105+ sys.exit(main())
0106
.gitignore+16−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..2a8302aindex 0000000..2a8302a
--- /dev/null--- /dev/null
+++ b/.gitignore+++ b/.gitignore
@@ -0,0 +1,16 @@@@ -0,0 +1,16 @@
1+# build artifacts
2+/plugin_claudecode_login
3+/plugin_claudecode_login.exe
4+/plugin_claudecode_login.musl
5+/plugin_claudecode_login.arm64
6+/plugin_claudecode_login.macos-arm64
7+/plugin_claudecode_login.macos-x86_64
8+bin/
9+
10+# test scratch
11+*.tmp
12+/tests/fixtures-out/
13+
14+# python tooling
15+__pycache__/
16+*.pyc
LICENSE+21−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ef80120index 0000000..ef80120
--- /dev/null--- /dev/null
+++ b/LICENSE+++ b/LICENSE
@@ -0,0 +1,21 @@@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+80−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..33ce0b6index 0000000..33ce0b6
--- /dev/null--- /dev/null
+++ b/Makefile+++ b/Makefile
@@ -0,0 +1,80 @@@@ -0,0 +1,80 @@
1+# plugin_claudecode_login - SCORPIOX BOT open-source Claude Code login for your node
2+#
3+# Targets:
4+# make native build -> ./plugin_claudecode_login
5+# make musl static musl x86_64 -> ./plugin_claudecode_login.musl
6+# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_claudecode_login.arm64
7+# make win64 MinGW-w64 static -> ./plugin_claudecode_login.exe
8+# make macos Apple clang -> ./plugin_claudecode_login (run this on macOS)
9+# make ui regenerate src/ui_html.h from src/ui.html
10+# make test build + run tests/run.sh
11+# make e2e build + run tests/e2e.py (Playwright)
12+# make clean
13+
14+CC ?= cc
15+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src
16+MUSL_CC ?= musl-gcc
17+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static
18+ARM_CC ?= aarch64-linux-gnu-gcc
19+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static
20+WIN_CC ?= x86_64-w64-mingw32-gcc
21+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -static
22+SRC := src/plugin_claudecode_login.c
23+UI_SRC := src/ui.html
24+UI_HDR := src/ui_html.h
25+BIN := plugin_claudecode_login
26+EXE := plugin_claudecode_login.exe
27+
28+.PHONY: all native musl arm64 win64 macos ui test e2e clean help
29+
30+all: native
31+
32+$(UI_HDR): $(UI_SRC) tools/gen_ui.py
33+ @echo "==> regenerating $(UI_HDR)"
34+ python3 tools/gen_ui.py
35+
36+ui: $(UI_HDR)
37+
38+native: $(BIN)
39+
40+$(BIN): $(SRC) $(UI_HDR)
41+ @echo "==> native build ($(CC))"
42+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
43+
44+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
45+musl: $(SRC) $(UI_HDR)
46+ @echo "==> static musl build ($(MUSL_CC))"
47+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
48+
49+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
50+arm64: $(SRC) $(UI_HDR)
51+ @echo "==> static arm64 build ($(ARM_CC))"
52+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
53+
54+# Native Win64 static PE - runs on any Windows 10/11 x64 node
55+win64: $(SRC) $(UI_HDR)
56+ @echo "==> MinGW-w64 build ($(WIN_CC))"
57+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
58+
59+# Apple clang build (run this on macOS)
60+macos: $(SRC) $(UI_HDR)
61+ @echo "==> Apple clang build"
62+ clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -o $(BIN) $(SRC)
63+
64+install: $(BIN)
65+ @dest="$${HOME}/.scorpiox/plugins"; [ -d /workspace ] && dest="/workspace/.scorpiox/plugins"; \
66+ mkdir -p "$$dest" && cp $(BIN) "$$dest/$(BIN)" && chmod 0755 "$$dest/$(BIN)" && \
67+ echo "==> installed $$dest/$(BIN)"
68+
69+test: $(BIN)
70+ sh tests/run.sh
71+
72+e2e: $(BIN)
73+ python3 tests/e2e.py
74+
75+clean:
76+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64
77+ rm -rf tests/__pycache__
78+
79+help:
80+ @sed -n '2,16p' $(MAKEFILE_LIST)
README.md+126−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..83e783bindex 0000000..83e783b
--- /dev/null--- /dev/null
+++ b/README.md+++ b/README.md
@@ -0,0 +1,126 @@@@ -0,0 +1,126 @@
1+# plugin_claudecode_login
2+
3+**Claude Code Login** - a SCORPIOX BOT open-source plugin that manages the Claude
4+Code OAuth PKCE session on your node: start a login, submit the authorization
5+code, watch the token expiry, list named accounts, and refresh the token on
6+demand.
7+
8+One clean-room C99 binary, zero dependencies, no OAuth client secret, and no
9+token ever leaves the node - or even leaves the child process that fetched it.
10+
11+```
12+--meta {"name":"claude","desc":"Claude login"}
13+?action=status session state, expiry, accounts (JSON)
14+?action=start begin the PKCE flow -> auth_url
15+?action=finish&code=<code|url> exchange the pasted code
16+?action=cancel drop the pending flow
17+?action=refresh refresh the token now
18+?format=json same as action=status
19+GET (no action) responsive dark/light HTML UI
20+```
21+
22+## Design: the plugin drives the CLI, it never speaks TLS
23+
24+A Claude Code PKCE exchange is an HTTPS POST that carries a client identity. A
25+public clean-room repository can never carry an OAuth client secret, so this
26+plugin does not open a socket at all.
27+
28+Instead it drives the login tools that ship with SCORPIOX CODE through their
29+**machine mode** - the documented, non-interactive contract for callers that
30+cannot hold a TTY:
31+
32+| child process | arguments | purpose |
33+|---|---|---|
34+| `scorpiox-claudecode-login` | `--status`, `--start`, `--finish <code>`, `--cancel` | the PKCE flow |
35+| `scorpiox-claudecode-refreshtoken` | `--credentials-file <path> --force` | the refresh-token grant |
36+
37+Both print human progress on stdout and then exactly one JSON line, so the
38+plugin takes the **last line that starts with `{`** and ignores the rest. The
39+refresh CLI's payload is read into a buffer and then discarded: the response is
40+built from a re-read of the credential file, never from what the CLI printed.
41+
42+The plugin reads only these files, and only metadata out of them:
43+
44+```
45+~/.claude/.credentials.json claudeAiOauth block
46+~/.claude/accounts/<name>.json named accounts (same schema)
47+~/.claude/.login-pending/claudecode-<n>.json pending PKCE state
48+~/.claude/scorpiox-env/claude_code.txt PROVIDER / MODEL profile
49+```
50+
51+`accessToken` and `refreshToken` are read into a small **presence-only** buffer
52+and thrown away. No response contains a token value, a token prefix, or the key
53+name `accessToken`. `tests/run.sh` pins that with fixtures built from realistic
54+token strings.
55+
56+## Environment overrides (all optional, all used by the test suite)
57+
58+| variable | default | meaning |
59+|---|---|---|
60+| `CLAUDE_CREDS_PATH` | `~/.claude/.credentials.json` | credentials file; also anchors the sibling paths |
61+| `CLAUDE_ACCOUNTS_DIR` | `~/.claude/accounts` | named account directory |
62+| `CLAUDE_PENDING_DIR` | `~/.claude/.login-pending` | pending-flow directory |
63+| `CLAUDE_ENV_DIR` | `~/.claude/scorpiox-env` | profile directory |
64+| `CLAUDE_LOGIN_BIN` | `scorpiox-claudecode-login` | login CLI |
65+| `CLAUDE_REFRESH_BIN` | `scorpiox-claudecode-refreshtoken` | refresh CLI |
66+
67+A relocated `CLAUDE_CREDS_PATH` implies a relocated `~/.claude` tree: the same
68+CLI writes all four files into one directory, so reading one from the override
69+and the rest from `$HOME` reports an empty state for a live session.
70+
71+## Auth
72+
73+The node API on `:8150` must never be open to the LAN. `--meta` stays
74+unauthenticated so discovery works; every other route requires
75+`X-Bot-Password`, `Authorization: Bearer <pwd>`, or `?pwd=` when the node has
76+`BOT_PASSWORD` set.
77+
78+```bash
79+curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8150/plugin_claudecode_login
80+# 401
81+```
82+
83+## Build
84+
85+```bash
86+make # native -> ./plugin_claudecode_login
87+make musl # static musl x86_64 (universal Linux artifact)
88+make arm64 # static aarch64 (Raspberry Pi 5 / ARM64 servers)
89+make win64 # MinGW-w64 static PE
90+make macos # Apple clang (run on macOS)
91+make test # build + tests/run.sh
92+make ui # regenerate src/ui_html.h from src/ui.html
93+```
94+
95+`make ui` is required after editing `src/ui.html`: `tools/gen_ui.py` turns the
96+page into a C string with two control-byte placeholders (`0x01` = the bot theme
97+prepaint + token block, `0x02` = the theme handoff script). Keep the palette in
98+`src/bot_theme_plugin.h` only - it is a trimmed copy of the bot's own theme, so
99+the plugin looks like part of the bot in dark and light, in a modal, in the Chat
100+floating window and in its own tab.
101+
102+## Install on a node
103+
104+```bash
105+make install # ~/.scorpiox/plugins, or /workspace/.scorpiox/plugins
106+```
107+
108+or let the marketplace do it - `https://bot.scorpiox.net/settings?sec=plugins`
109+installs a prebuilt binary, `?mode=source` clones this repo and compiles it on
110+the node.
111+
112+## Security notes
113+
114+- Every child-process argument is single-quoted for `popen` (`shell_quote_into`),
115+ and an authorization code is validated against a strict alphabet first, so a
116+ pasted `$(...)` or `;` payload is refused before it can reach a shell.
117+- A pasted redirect URL is accepted: `code=` is extracted before validation, so a
118+ real paste (which always carries `&state=`) is not rejected.
119+- No `Content-Length` header is ever emitted (Caddy 502 rule).
120+- The page loads no CDN, no `<script src=`, no external asset; CSP is
121+ `default-src 'none'` with inline script/style only.
122+- No emoji anywhere in the source, the page or the JSON.
123+
124+## License
125+
126+MIT License. Copyright (c) 2026 SCORPIOX INC.
build.ps1+51−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..d907f49index 0000000..d907f49
--- /dev/null--- /dev/null
+++ b/build.ps1+++ b/build.ps1
@@ -0,0 +1,51 @@@@ -0,0 +1,51 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_claudecode_login
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_claudecode_login.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+
9+$ErrorActionPreference = "Stop"
10+$ScriptDir = $PSScriptRoot
11+Push-Location $ScriptDir
12+try {
13+ $Src = Join-Path $ScriptDir "src\plugin_claudecode_login.c"
14+ $Out = Join-Path $ScriptDir "plugin_claudecode_login.exe"
15+ $Cc = "x86_64-w64-mingw32-gcc"
16+
17+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
18+
19+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
20+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
21+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
22+ $Cc = "C:\gcc16\bin\gcc.exe"
23+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
24+ $Cc = "gcc"
25+ } else {
26+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
27+ }
28+ }
29+
30+ # Regenerate the page header so the binary always matches src/ui.html.
31+ if (Get-Command python -ErrorAction SilentlyContinue) {
32+ python tools\gen_ui.py
33+ }
34+
35+ Write-Host "==> building plugin_claudecode_login.exe with $Cc"
36+ & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src
37+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
38+
39+ if (-not (Test-Path $Out)) { throw "build produced no output" }
40+
41+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
42+ $bytes = [System.IO.File]::ReadAllBytes($Out)
43+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
44+ throw "output is not a PE executable (missing MZ header)"
45+ }
46+
47+ Write-Host "==> ok: $Out ($($bytes.Length) bytes)"
48+ Write-Host " smoke test: .\plugin_claudecode_login.exe --meta"
49+} finally {
50+ Pop-Location
51+}
plugin.json+16−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ba43dc5index 0000000..ba43dc5
--- /dev/null--- /dev/null
+++ b/plugin.json+++ b/plugin.json
@@ -0,0 +1,16 @@@@ -0,0 +1,16 @@
1+{
2+ "slug": "claudecode-login",
3+ "id": "plugin_claudecode_login",
4+ "title": "Claude Code Login",
5+ "summary": "Zero-dependency Claude Code OAuth PKCE login and session token manager for your node. Starts the PKCE flow, takes the pasted authorization code, runs the exchange through the node's own login CLI, then reports session state, token expiry and the named account files - and refreshes the token on demand. The plugin holds no OAuth client secret and never prints, logs or returns a token: it drives the CLI that ships with SCORPIOX CODE and reads only the credential and profile files that CLI writes.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "capabilities": [
9+ "spawn_login_cli",
10+ "read_credentials_metadata",
11+ "network_via_login_cli"
12+ ],
13+ "trust_notice": "Executes native C code on your node. It runs scorpiox-claudecode-login and scorpiox-claudecode-refreshtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to Claude over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only ~/.claude/.credentials.json, ~/.claude/accounts/, ~/.claude/.login-pending/ and ~/.claude/scorpiox-env/claude_code.txt, and every response reports token presence and expiry only - never a token value.",
14+ "author": "SCORPIOX INC",
15+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-claudecode-login"
16+}
release-dist.sh+365−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..5f1bdb8index 0000000..5f1bdb8
--- /dev/null--- /dev/null
+++ b/release-dist.sh+++ b/release-dist.sh
@@ -0,0 +1,365 @@@@ -0,0 +1,365 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_claudecode_login to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+# ./release-dist.sh --standalone # use this script even if the CLI is installed
27+# # (needed for plugins that link extra Win32 libs,
28+# # which the CLI's fixed link line cannot express)
29+
30+set -euo pipefail
31+
32+SLUG="claudecode-login"
33+ID="plugin_claudecode_login"
34+VERSION="1.0.0"
35+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --standalone) STANDALONE=1 ;;
47+ --dry-run) DRY_RUN=1 ;;
48+ --no-macos) DO_MACOS=0 ;;
49+ --no-mirror) DO_MIRROR=0 ;;
50+ -h|--help) sed -n '2,32p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition - otherwise this file's own detector patterns (and the
90+# test suite's identical checks) read as findings in every historical revision of
91+# them. A real secret on any other line still hits.
92+git log -p --all 2>/dev/null \
93+ | grep -v '^Author: ' \
94+ | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \
95+ > "$SCAN_TMP" || : > "$SCAN_TMP"
96+HITS=0
97+scan() { # scan <label> <regex>
98+ local out
99+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
100+ if [ -n "$out" ]; then
101+ printf ' \033[31mHIT\033[0m %s\n' "$1"
102+ printf '%s\n' "$out" | sed 's/^/ /'
103+ HITS=$((HITS + 1))
104+ else
105+ printf ' ok %s\n' "$1"
106+ fi
107+}
108+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
109+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
110+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
111+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
112+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
113+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
114+scan "hard-coded ssh password" 'sshpass -p [^"$]'
115+P_ROOT="/codebases"
116+P_PICOBOT="${P_ROOT}/pico""bot"
117+P_WT=".work""trees"
118+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
119+scan "run-token env assignment" 'RUNNER_'"PASS="
120+if [ "$HITS" -ne 0 ]; then
121+ die "secret scan found $HITS problem(s) - refusing to publish"
122+fi
123+echo " clean: 0 hits"
124+
125+# ---------------------------------------------------------------- 2. build
126+say "2/7 build targets"
127+
128+# linux-x86_64 (glibc, native)
129+if command -v cc >/dev/null 2>&1; then
130+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -Wno-format-truncation -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed"
131+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
132+else
133+ die "no native cc found"
134+fi
135+
136+# linux-x86_64-musl (fully static - the universal Linux artifact)
137+if command -v musl-gcc >/dev/null 2>&1; then
138+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -Wno-format-truncation -I src -o "$STAGE/$ID.musl" src/$ID.c \
139+ || die "musl build failed"
140+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
141+else
142+ echo " skip linux-x86_64-musl (no musl-gcc)"
143+fi
144+
145+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
146+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
147+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -Wno-format-truncation -I src -o "$STAGE/$ID.arm64" src/$ID.c \
148+ || die "arm64 build failed"
149+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
150+else
151+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
152+fi
153+
154+# windows-x86_64 (static PE)
155+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
156+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -Wno-format-truncation \
157+ -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
158+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
159+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
160+else
161+ echo " skip windows-x86_64 (no MinGW cross compiler)"
162+fi
163+
164+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
165+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
166+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
167+ MAC_USER="${MAC_USER:-$(whoami)}"
168+ MAC_DIR="/tmp/${ID}-mac-$$"
169+ echo " building macOS legs on $MAC_HOST"
170+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
171+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
172+ if [ -n "${MAC_PASS:-}" ]; then
173+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
174+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
175+ fi
176+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
177+ tar -czf "$STAGE/src.tgz" src
178+ if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \
179+ && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then
180+ # Build straight from the uploaded file - no src/ tree on the remote.
181+ for slice in arm64 x86_64; do
182+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
183+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src -arch $slice -o $ID.$slice src/$ID.c" \
184+ 2>/dev/null; then
185+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
186+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
187+ else
188+ echo " warn: macos-$slice build failed on $MAC_HOST"
189+ fi
190+ done
191+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
192+ else
193+ echo " warn: could not upload source to $MAC_HOST"
194+ fi
195+ else
196+ echo " warn: cannot reach macOS builder $MAC_HOST"
197+ fi
198+else
199+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
200+fi
201+
202+# ---------------------------------------------------------------- 3. manifest
203+say "3/7 manifest + checksums"
204+
205+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
206+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
207+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
208+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
209+
210+target_meta() { # target_meta <key> <file> <format> <relpath>
211+ local key="$1" file="$2" fmt="$3" rel="$4"
212+ [ -f "$file" ] || return 0
213+ local sha size
214+ sha=$(sha256sum "$file" | awk '{print $1}')
215+ size=$(wc -c < "$file" | tr -d ' ')
216+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
217+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
218+}
219+
220+{
221+ printf '{\n'
222+ printf ' "slug": "%s",\n' "$SLUG"
223+ printf ' "id": "%s",\n' "$ID"
224+ printf ' "name": "claude",\n'
225+ printf ' "desc": "Claude login",\n'
226+ printf ' "title": "Claude Code Login",\n'
227+ printf ' "summary": "Zero-dependency Claude Code OAuth PKCE login and session token manager for your node. Starts the PKCE flow, takes the pasted authorization code, runs the exchange through the node own login CLI, then reports session state, token expiry and the named account files - and refreshes the token on demand. The plugin holds no OAuth client secret and never prints, logs or returns a token: it drives the CLI that ships with SCORPIOX CODE and reads only the credential and profile files that CLI writes.",\n'
228+ printf ' "category": "devtools",\n'
229+ printf ' "version": "%s",\n' "$VERSION"
230+ printf ' "license": "MIT",\n'
231+ printf ' "trust_notice": "Executes native C code on your node. It runs scorpiox-claudecode-login and scorpiox-claudecode-refreshtoken (both from SCORPIOX CODE) as child processes; those binaries are what talk to Claude over TLS. This plugin itself opens no socket and carries no OAuth client secret. It reads only the Claude Code credential file, the named account files, the login-pending marker and the claude_code profile, and every response reports token presence and expiry only - never a token value.",\n'
232+ printf ' "capabilities": ["spawn_login_cli", "read_credentials_metadata", "network_via_login_cli"],\n'
233+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
234+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
235+ printf ' "git_commit": "%s",\n' "$COMMIT"
236+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
237+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
238+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
239+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
240+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
241+ printf ' "targets": {\n'
242+ first=1
243+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
244+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
245+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
246+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
247+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
248+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
249+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
250+ printf '\n }\n}\n'
251+} > "$STAGE/manifest.json"
252+
253+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
254+ || die "generated manifest.json is not valid JSON"
255+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
256+
257+# SHA256SUMS - relative paths, exactly as published
258+( cd "$STAGE"
259+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
260+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
261+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
262+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
263+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
264+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
265+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
266+ true ) > "$STAGE/SHA256SUMS"
267+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
268+
269+# ---------------------------------------------------------------- 4. stage
270+say "4/7 stage tree"
271+PKG="$STAGE/pkg"
272+mkdir -p "$PKG"
273+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
274+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
275+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
276+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
277+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
278+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
279+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
280+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
281+
282+if [ "$DRY_RUN" -eq 1 ]; then
283+ say "dry run - leaving the staging tree in $PKG"
284+ trap - EXIT
285+ exit 0
286+fi
287+
288+# ---------------------------------------------------------------- 5. upload
289+say "5/7 upload to the dist server"
290+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
291+SSH=(ssh -o StrictHostKeyChecking=no)
292+SCP=(scp -o StrictHostKeyChecking=no)
293+if [ -n "$DIST_PASS" ]; then
294+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
295+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
296+fi
297+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
298+
299+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
300+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
301+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
302+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
303+# OpenSSH 9 refuses to scp a bare "." source.
304+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
305+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
306+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
307+ || die "remote extract failed"
308+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
309+
310+# latest.json = copy of this version's manifest
311+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
312+ || die "latest.json update failed"
313+echo " updated bot-plugins/$SLUG/latest.json"
314+
315+# index.json - merge, preserving every sibling <slug>/latest.json
316+say "index.json merge"
317+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
318+import json, os, sys, glob
319+slug = sys.argv[1]
320+entries = {}
321+for p in sorted(glob.glob('*/latest.json')):
322+ s = os.path.dirname(p)
323+ try:
324+ entries[s] = json.load(open(p))
325+ except Exception:
326+ pass
327+index = {
328+ 'ok': True,
329+ 'service': 'bot-plugins-dist',
330+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
331+ 'count': len(entries),
332+ 'slugs': sorted(entries),
333+ 'plugins': [entries[k] for k in sorted(entries)],
334+}
335+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
336+os.replace('index.json.tmp', 'index.json')
337+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
338+PY" || die "index.json merge failed"
339+
340+# ---------------------------------------------------------------- 6. mirror
341+say "6/7 plugingit mirror"
342+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
343+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
344+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
345+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
346+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
347+ echo " mirrored to $PLUGINGIT_REMOTE"
348+else
349+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
350+fi
351+
352+# ---------------------------------------------------------------- 7. verify
353+say "7/7 verify"
354+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
355+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
356+if [ "$CODE" = "200" ]; then
357+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
358+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
359+else
360+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
361+fi
362+
363+printf '\n\033[1mrelease complete\033[0m\n'
364+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
365+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/bot_theme_plugin.h+129−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..0dd243bindex 0000000..0dd243b
--- /dev/null--- /dev/null
+++ b/src/bot_theme_plugin.h+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/plugin_claudecode_login.c+1607−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..c7bad2cindex 0000000..c7bad2c
--- /dev/null--- /dev/null
+++ b/src/plugin_claudecode_login.c+++ b/src/plugin_claudecode_login.c
@@ -0,0 +1,1607 @@@@ -0,0 +1,1607 @@
1+/*
2+ * plugin_claudecode_login - SCORPIOX BOT open-source Claude Code OAuth PKCE
3+ * login and session token manager for your node.
4+ *
5+ * A single clean-room C99 binary that serves THREE modes:
6+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
7+ * 2. ?action=... / ?format=json -> JSON node API
8+ * 3. GET (default) -> responsive HTML UI
9+ *
10+ * DESIGN NOTE (why there is no TLS and no OAuth client secret here): a Claude
11+ * Code OAuth PKCE code exchange is an HTTPS POST that carries a client
12+ * identity. A public clean-room repository must never carry such a secret, so
13+ * this plugin does not speak TLS at all. It drives the node's own SCORPIOX CODE
14+ * login CLI, exactly the way the machine-mode contract intends
15+ * (--status / --start / --finish / --cancel, one JSON line per call), and it
16+ * reads only the credential files that CLI writes:
17+ *
18+ * ~/.claude/.credentials.json (claudeAiOauth block)
19+ * ~/.claude/accounts/<name>.json (named accounts)
20+ * ~/.claude/.login-pending/claudecode-<name>.json (pending PKCE flow)
21+ * ~/.claude/scorpiox-env/claude_code.txt (PROVIDER/MODEL profile)
22+ *
23+ * Every path and both binaries are overridable for deterministic offline tests:
24+ *
25+ * CLAUDE_CREDS_PATH credentials file (also anchors the sibling paths)
26+ * CLAUDE_ACCOUNTS_DIR directory holding <name>.json account files
27+ * CLAUDE_PENDING_DIR directory holding the pending flow files
28+ * CLAUDE_ENV_DIR profile directory (claude_code.txt)
29+ * CLAUDE_LOGIN_BIN login CLI (default scorpiox-claudecode-login)
30+ * CLAUDE_REFRESH_BIN refresh CLI (default scorpiox-claudecode-refreshtoken)
31+ *
32+ * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. Every response reports token
33+ * presence and expiry only. The refresh action discards the payload its CLI
34+ * prints and reports only success/failure plus the new expiry.
35+ *
36+ * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
37+ * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
38+ * scorpiox-server on the node.
39+ *
40+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
41+ */
42+
43+/* Must come before every include on Windows: MinGW defaults to 0x502
44+ * (Server 2003), which hides the Win7+ APIs and the path helpers. */
45+#if defined(_WIN32) && !defined(_WIN32_WINNT)
46+# define _WIN32_WINNT 0x0601
47+#endif
48+
49+#if !defined(_WIN32)
50+# define _POSIX_C_SOURCE 200809L
51+# define _DEFAULT_SOURCE 1
52+# if defined(__APPLE__)
53+# define _DARWIN_C_SOURCE 1
54+# endif
55+#endif
56+
57+#include <stdio.h>
58+#include <stdlib.h>
59+#include <string.h>
60+#include <ctype.h>
61+#include <errno.h>
62+#include <time.h>
63+#include <stdarg.h>
64+
65+#if defined(_WIN32)
66+# define WIN32_LEAN_AND_MEAN
67+# include <windows.h>
68+# include <direct.h>
69+# include <io.h>
70+#else
71+# include <unistd.h>
72+# include <sys/stat.h>
73+# include <sys/types.h>
74+# include <dirent.h>
75+#endif
76+
77+#include "bot_theme_plugin.h"
78+#include "ui_html.h"
79+
80+#define PLUGIN_SLUG "claudecode-login"
81+#define PLUGIN_ID "plugin_claudecode_login"
82+#define PLUGIN_VER "1.0.0"
83+#define PLUGIN_NAME "claude"
84+#define PLUGIN_DESC "Claude login"
85+
86+#define PATH_SZ 1024
87+#define NAME_SZ 96
88+#define CODE_MAX 2048
89+#define CMD_SZ 4096
90+#define OUT_MAX (256 * 1024)
91+#define FIELD_SZ 512
92+#define MAX_ACCOUNTS 64
93+
94+#define DEFAULT_LOGIN_BIN "scorpiox-claudecode-login"
95+#define DEFAULT_REFRESH_BIN "scorpiox-claudecode-refreshtoken"
96+
97+#if defined(_WIN32)
98+# define PATH_SEP '\\'
99+#else
100+# define PATH_SEP '/'
101+#endif
102+
103+/* ------------------------------------------------------------------ */
104+/* Growable byte buffer */
105+/* ------------------------------------------------------------------ */
106+
107+typedef struct {
108+ char *p;
109+ size_t n;
110+ size_t cap;
111+} buf_t;
112+
113+static void buf_init(buf_t *b)
114+{
115+ b->p = NULL;
116+ b->n = 0;
117+ b->cap = 0;
118+}
119+
120+static int buf_need(buf_t *b, size_t extra)
121+{
122+ size_t want = b->n + extra + 1;
123+ char *np;
124+
125+ if (want <= b->cap) return 1;
126+ if (b->cap == 0) b->cap = 1024;
127+ while (b->cap < want) {
128+ if (b->cap > (size_t)32 * 1024 * 1024) return 0;
129+ b->cap *= 2;
130+ }
131+ np = (char *)realloc(b->p, b->cap);
132+ if (!np) return 0;
133+ b->p = np;
134+ return 1;
135+}
136+
137+static int buf_add(buf_t *b, const char *s, size_t n)
138+{
139+ if (!buf_need(b, n)) return 0;
140+ memcpy(b->p + b->n, s, n);
141+ b->n += n;
142+ b->p[b->n] = '\0';
143+ return 1;
144+}
145+
146+static int buf_adds(buf_t *b, const char *s)
147+{
148+ return s ? buf_add(b, s, strlen(s)) : 1;
149+}
150+
151+static int buf_addc(buf_t *b, char c)
152+{
153+ return buf_add(b, &c, 1);
154+}
155+
156+static const char *buf_str(buf_t *b)
157+{
158+ if (!b->p) return "";
159+ return b->p;
160+}
161+
162+static void buf_free(buf_t *b)
163+{
164+ free(b->p);
165+ b->p = NULL;
166+ b->n = 0;
167+ b->cap = 0;
168+}
169+
170+static int buf_addf(buf_t *b, const char *fmt, ...)
171+{
172+ char tmp[2048];
173+ int n;
174+ va_list ap;
175+
176+ va_start(ap, fmt);
177+ n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
178+ va_end(ap);
179+ if (n < 0) return 0;
180+ if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n);
181+
182+ {
183+ char *big = (char *)malloc((size_t)n + 1);
184+ int ok;
185+ if (!big) return 0;
186+ va_start(ap, fmt);
187+ vsnprintf(big, (size_t)n + 1, fmt, ap);
188+ va_end(ap);
189+ ok = buf_add(b, big, (size_t)n);
190+ free(big);
191+ return ok;
192+ }
193+}
194+
195+/* JSON string escape into a buffer (never emits a bare control byte). */
196+static int buf_json(buf_t *b, const char *s)
197+{
198+ const unsigned char *p = (const unsigned char *)(s ? s : "");
199+ if (!buf_addc(b, '"')) return 0;
200+ for (; *p; p++) {
201+ switch (*p) {
202+ case '"': if (!buf_adds(b, "\\\"")) return 0; break;
203+ case '\\': if (!buf_adds(b, "\\\\")) return 0; break;
204+ case '\n': if (!buf_adds(b, "\\n")) return 0; break;
205+ case '\r': if (!buf_adds(b, "\\r")) return 0; break;
206+ case '\t': if (!buf_adds(b, "\\t")) return 0; break;
207+ default:
208+ if (*p < 0x20) { if (!buf_addf(b, "\\u%04x", *p)) return 0; }
209+ else if (!buf_addc(b, (char)*p)) return 0;
210+ }
211+ }
212+ return buf_addc(b, '"');
213+}
214+
215+/* ------------------------------------------------------------------ */
216+/* Query string */
217+/* ------------------------------------------------------------------ */
218+
219+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
220+{
221+ size_t klen;
222+ const char *p;
223+
224+ if (!out || outsz == 0) return 0;
225+ out[0] = '\0';
226+ if (!qs || !key) return 0;
227+ klen = strlen(key);
228+ p = qs;
229+ while (p && *p) {
230+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
231+ size_t i = 0;
232+ p += klen + 1;
233+ while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++;
234+ out[i] = '\0';
235+ return 1;
236+ }
237+ p = strchr(p, '&');
238+ if (!p) break;
239+ p++;
240+ }
241+ return 0;
242+}
243+
244+static int query_has(const char *qs, const char *key)
245+{
246+ size_t klen;
247+ const char *p;
248+
249+ if (!qs || !key) return 0;
250+ klen = strlen(key);
251+ p = qs;
252+ while (p && *p) {
253+ if (strncmp(p, key, klen) == 0 &&
254+ (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&'))
255+ return 1;
256+ p = strchr(p, '&');
257+ if (!p) break;
258+ p++;
259+ }
260+ return 0;
261+}
262+
263+/* Percent-decode in place (an authorization code arrives from a paste box and
264+ * may have been encoded by the browser or the hub proxy). */
265+static void url_decode(char *s)
266+{
267+ char *w;
268+ char *r;
269+
270+ if (!s) return;
271+ w = s;
272+ r = s;
273+ while (*r) {
274+ if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) {
275+ int hi = isdigit((unsigned char)r[1]) ? r[1] - '0'
276+ : tolower((unsigned char)r[1]) - 'a' + 10;
277+ int lo = isdigit((unsigned char)r[2]) ? r[2] - '0'
278+ : tolower((unsigned char)r[2]) - 'a' + 10;
279+ *w++ = (char)((hi << 4) | lo);
280+ r += 3;
281+ } else if (*r == '+') {
282+ *w++ = ' ';
283+ r++;
284+ } else {
285+ *w++ = *r++;
286+ }
287+ }
288+ *w = '\0';
289+}
290+
291+/* ------------------------------------------------------------------ */
292+/* Node auth (X-Bot-Password / Bearer / ?pwd=) */
293+/* ------------------------------------------------------------------ */
294+
295+static void require_node_auth(void)
296+{
297+ const char *np = getenv("BOT_PASSWORD");
298+ const char *xp;
299+ const char *auth;
300+ char qpwd[256] = {0};
301+
302+ if (!np || !*np) return;
303+
304+ xp = getenv("HTTP_X_BOT_PASSWORD");
305+ if (xp && strcmp(xp, np) == 0) return;
306+
307+ auth = getenv("HTTP_AUTHORIZATION");
308+ if (auth) {
309+ while (*auth == ' ') auth++;
310+ if (strncasecmp(auth, "Bearer ", 7) == 0) {
311+ auth += 7;
312+ while (*auth == ' ') auth++;
313+ if (strcmp(auth, np) == 0) return;
314+ }
315+ }
316+
317+ if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) &&
318+ strcmp(qpwd, np) == 0)
319+ return;
320+
321+ fputs("Status: 401 Unauthorized\r\n"
322+ "Content-Type: application/json; charset=utf-8\r\n"
323+ "Cache-Control: no-store\r\n\r\n"
324+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
325+ exit(0);
326+}
327+
328+/* ------------------------------------------------------------------ */
329+/* Paths */
330+/* ------------------------------------------------------------------ */
331+
332+static const char *home_dir(void)
333+{
334+#if defined(_WIN32)
335+ static char home[512];
336+ DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home));
337+ if (n > 0 && n < sizeof(home)) return home;
338+ home[0] = '\0';
339+ if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) {
340+ char tmp[512];
341+ if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) {
342+ strncat(home, tmp, sizeof(home) - strlen(home) - 1);
343+ return home;
344+ }
345+ }
346+ return NULL;
347+#else
348+ const char *h = getenv("HOME");
349+ return (h && *h) ? h : NULL;
350+#endif
351+}
352+
353+/* Copy the directory part of a path (including the trailing separator). */
354+static void dir_of(const char *path, char *out, size_t n)
355+{
356+ char base[PATH_SZ];
357+ char *slash;
358+
359+ if (!path) { if (n) out[0] = '\0'; return; }
360+ snprintf(base, sizeof(base), "%s", path);
361+ slash = strrchr(base, PATH_SEP);
362+#if defined(_WIN32)
363+ if (!slash) slash = strrchr(base, '/');
364+#endif
365+ if (slash) *(slash + 1) = '\0';
366+ else base[0] = '\0';
367+ snprintf(out, n, "%s", base);
368+}
369+
370+/* A relocated credentials file implies the whole .claude tree is relocated:
371+ * the same CLI writes all of these into one directory. Reading one from the
372+ * override and the rest from $HOME reports an empty state for a live session. */
373+static void claude_dir(char *out, size_t n)
374+{
375+ const char *env = getenv("CLAUDE_CREDS_PATH");
376+ const char *home = home_dir();
377+
378+ if (env && *env) {
379+ dir_of(env, out, n);
380+ if (out[0]) return;
381+ }
382+ if (home && *home) { snprintf(out, n, "%s%c.claude%c", home, PATH_SEP, PATH_SEP); return; }
383+ snprintf(out, n, ".claude%c", PATH_SEP);
384+}
385+
386+static void creds_path(char *out, size_t n)
387+{
388+ const char *env = getenv("CLAUDE_CREDS_PATH");
389+
390+ if (env && *env) { snprintf(out, n, "%s", env); return; }
391+ {
392+ char d[PATH_SZ];
393+ claude_dir(d, sizeof(d));
394+ snprintf(out, n, "%s.credentials.json", d);
395+ }
396+}
397+
398+static void accounts_dir(char *out, size_t n)
399+{
400+ const char *env = getenv("CLAUDE_ACCOUNTS_DIR");
401+
402+ if (env && *env) { snprintf(out, n, "%s", env); return; }
403+ {
404+ char d[PATH_SZ];
405+ claude_dir(d, sizeof(d));
406+ snprintf(out, n, "%saccounts", d);
407+ }
408+}
409+
410+static void pending_dir(char *out, size_t n)
411+{
412+ const char *env = getenv("CLAUDE_PENDING_DIR");
413+
414+ if (env && *env) { snprintf(out, n, "%s", env); return; }
415+ {
416+ char d[PATH_SZ];
417+ claude_dir(d, sizeof(d));
418+ snprintf(out, n, "%s.login-pending", d);
419+ }
420+}
421+
422+static void env_dir(char *out, size_t n)
423+{
424+ const char *env = getenv("CLAUDE_ENV_DIR");
425+
426+ if (env && *env) { snprintf(out, n, "%s", env); return; }
427+ {
428+ char d[PATH_SZ];
429+ claude_dir(d, sizeof(d));
430+ snprintf(out, n, "%s%cscorpiox-env", d, PATH_SEP);
431+ }
432+}
433+
434+static void pending_path(const char *name, char *out, size_t n)
435+{
436+ char d[PATH_SZ];
437+ pending_dir(d, sizeof(d));
438+ snprintf(out, n, "%s%cclaudecode-%s.json", d, PATH_SEP, (name && *name) ? name : "default");
439+}
440+
441+static void profile_path(char *out, size_t n)
442+{
443+ char d[PATH_SZ];
444+ env_dir(d, sizeof(d));
445+ snprintf(out, n, "%s%cclaude_code.txt", d, PATH_SEP);
446+}
447+
448+static void account_path(const char *name, char *out, size_t n)
449+{
450+ char d[PATH_SZ];
451+ accounts_dir(d, sizeof(d));
452+ snprintf(out, n, "%s%c%s.json", d, PATH_SEP, name);
453+}
454+
455+static const char *login_bin(void)
456+{
457+ const char *e = getenv("CLAUDE_LOGIN_BIN");
458+ return (e && *e) ? e : DEFAULT_LOGIN_BIN;
459+}
460+
461+static const char *refresh_bin(void)
462+{
463+ const char *e = getenv("CLAUDE_REFRESH_BIN");
464+ return (e && *e) ? e : DEFAULT_REFRESH_BIN;
465+}
466+
467+static int file_exists(const char *p)
468+{
469+#if defined(_WIN32)
470+ DWORD a = GetFileAttributesA(p);
471+ return p && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
472+#else
473+ struct stat st;
474+ return p && stat(p, &st) == 0 && S_ISREG(st.st_mode);
475+#endif
476+}
477+
478+/* Read a whole file. Returns a malloc'd NUL-terminated buffer or NULL. */
479+static char *read_file(const char *path)
480+{
481+ FILE *f;
482+ long sz;
483+ char *buf;
484+
485+ if (!path || !*path) return NULL;
486+ f = fopen(path, "rb");
487+ if (!f) return NULL;
488+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
489+ sz = ftell(f);
490+ if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; }
491+ if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
492+ buf = (char *)malloc((size_t)sz + 1);
493+ if (!buf) { fclose(f); return NULL; }
494+ if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
495+ free(buf);
496+ fclose(f);
497+ return NULL;
498+ }
499+ buf[sz] = '\0';
500+ fclose(f);
501+ return buf;
502+}
503+
504+/* Trim trailing CR/LF/space in place. */
505+static void trim_tail(char *s)
506+{
507+ size_t n;
508+
509+ if (!s) return;
510+ n = strlen(s);
511+ while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' ||
512+ s[n - 1] == ' ' || s[n - 1] == '\t'))
513+ s[--n] = '\0';
514+}
515+
516+/* Account names are used verbatim in a file name, so they are restricted to a
517+ * shell- and path-safe alphabet. */
518+static int name_valid(const char *n)
519+{
520+ const char *p;
521+
522+ if (!n || !*n || strlen(n) > 64) return 0;
523+ if (n[0] == '.') return 0;
524+ for (p = n; *p; p++) {
525+ unsigned char c = (unsigned char)*p;
526+ if (!isalnum(c) && c != '-' && c != '_' && c != '.') return 0;
527+ }
528+ return 1;
529+}
530+
531+/* ------------------------------------------------------------------ */
532+/* Minimal JSON field readers */
533+/* ------------------------------------------------------------------ */
534+
535+/* Copy a JSON string value that starts at *pp (pointing at the opening quote)
536+ * and advance *pp past the closing quote. */
537+static int json_read_string_at(const char **pp, char *out, size_t outsz)
538+{
539+ const char *p = *pp;
540+ size_t i = 0;
541+
542+ if (!p || *p != '"') return 0;
543+ p++;
544+ while (*p && *p != '"') {
545+ char c = *p;
546+ if (c == '\\' && p[1]) {
547+ p++;
548+ switch (*p) {
549+ case 'n': c = '\n'; break;
550+ case 'r': c = '\r'; break;
551+ case 't': c = '\t'; break;
552+ case 'b': c = '\b'; break;
553+ case 'f': c = '\f'; break;
554+ case 'u': {
555+ unsigned int v = 0;
556+ int k;
557+ p++;
558+ for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++)
559+ v = v * 16 + (unsigned int)(isdigit((unsigned char)*p)
560+ ? *p - '0'
561+ : tolower((unsigned char)*p) - 'a' + 10);
562+ if (i + 1 < outsz) out[i++] = (char)(v & 0xff);
563+ continue;
564+ }
565+ default: c = *p; break;
566+ }
567+ p++;
568+ } else {
569+ p++;
570+ }
571+ if (i + 1 < outsz) out[i++] = c;
572+ }
573+ if (*p == '"') p++;
574+ if (outsz) out[i < outsz ? i : outsz - 1] = '\0';
575+ *pp = p;
576+ return 1;
577+}
578+
579+/* Find "key":<value> among the TOP-LEVEL keys of the slice [obj, end).
580+ * A nested object is skipped as a whole.
581+ *
582+ * A caller almost always hands us a pointer at the opening '{'; that brace is
583+ * skipped inside the reader so no call site needs a "+1" that is easy to
584+ * forget and completely silent when it is missing. */
585+static const char *json_find_key(const char *obj, const char *end, const char *key)
586+{
587+ size_t klen;
588+ const char *p;
589+ int depth = 0;
590+
591+ if (!obj || !end || !key) return NULL;
592+ klen = strlen(key);
593+ p = obj;
594+ while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++;
595+ if (p < end && *p == '{') p++;
596+
597+ while (p && p < end) {
598+ if (*p == '"') {
599+ char name[128];
600+ json_read_string_at(&p, name, sizeof(name));
601+ if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) {
602+ const char *q = p;
603+ while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
604+ if (q < end && *q == ':') {
605+ q++;
606+ while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
607+ return (q < end) ? q : NULL;
608+ }
609+ }
610+ continue;
611+ }
612+ if (*p == '{' || *p == '[') depth++;
613+ else if (*p == '}' || *p == ']') depth--;
614+ p++;
615+ }
616+ return NULL;
617+}
618+
619+/* Returns 0 and leaves *out untouched when the key is absent or null. That
620+ * matters: several callers pass a field of a longer-lived struct, and clearing
621+ * it on a miss silently erases a value that was already correct. */
622+static int json_str_field(const char *obj, const char *end, const char *key,
623+ char *out, size_t outsz)
624+{
625+ const char *v;
626+
627+ if (!out || outsz == 0) return 0;
628+ v = json_find_key(obj, end, key);
629+ if (!v || *v == 'n') return 0;
630+ if (*v == '"') return json_read_string_at(&v, out, outsz);
631+ {
632+ size_t i = 0;
633+ out[0] = '\0';
634+ while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++;
635+ out[i] = '\0';
636+ trim_tail(out);
637+ return out[0] ? 1 : 0;
638+ }
639+}
640+
641+static int json_bool_field(const char *obj, const char *end, const char *key, int dflt)
642+{
643+ const char *v = json_find_key(obj, end, key);
644+
645+ if (!v) return dflt;
646+ if (strncmp(v, "true", 4) == 0) return 1;
647+ if (strncmp(v, "false", 5) == 0) return 0;
648+ if (*v == '"') {
649+ if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1;
650+ return 0;
651+ }
652+ if (*v == '1') return 1;
653+ return 0;
654+}
655+
656+static long long json_num_field(const char *obj, const char *end, const char *key)
657+{
658+ const char *v = json_find_key(obj, end, key);
659+
660+ if (!v) return 0;
661+ if (*v == '"') v++;
662+ return atoll(v);
663+}
664+
665+/* ------------------------------------------------------------------ */
666+/* Child processes */
667+/* ------------------------------------------------------------------ */
668+
669+/* Quote one argv element for the shell popen() uses. POSIX: single quotes with
670+ * the standard close-escape-reopen trick. Windows: double quotes, which is
671+ * what cmd.exe accepts. */
672+static void shell_quote_into(const char *in, char *out, size_t outsz)
673+{
674+ size_t o = 0;
675+ const char *p;
676+
677+ if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
678+#if defined(_WIN32)
679+ out[o++] = '"';
680+ for (p = in; p && *p; p++) {
681+ if (*p == '"') {
682+ if (o + 3 >= outsz) break;
683+ out[o++] = '\\';
684+ out[o++] = '"';
685+ } else {
686+ if (o + 2 >= outsz) break;
687+ out[o++] = *p;
688+ }
689+ }
690+ out[o++] = '"';
691+ out[o] = '\0';
692+#else
693+ out[o++] = '\'';
694+ for (p = in; p && *p; p++) {
695+ if (*p == '\'') {
696+ if (o + 5 >= outsz) break;
697+ memcpy(out + o, "'\\''", 4);
698+ o += 4;
699+ } else {
700+ if (o + 2 >= outsz) break;
701+ out[o++] = *p;
702+ }
703+ }
704+ out[o++] = '\'';
705+ out[o] = '\0';
706+#endif
707+}
708+
709+/* Run `<bin> <args>` and capture stdout.
710+ * Returns 1 when the process ran,
711+ * 0 when popen() itself failed,
712+ * -1 when the binary is not on this node ("command not found").
713+ *
714+ * pclose() hands back a WAIT STATUS, not an exit code: a missing command
715+ * arrives as 32512 (127 << 8). Treating that as the tool's own failure would
716+ * report "refresh failed" for a node that simply has no SCORPIOX CODE. */
717+static int run_capture(const char *bin, const char *args, buf_t *out)
718+{
719+ char cmd[CMD_SZ];
720+ char qbin[FIELD_SZ];
721+ FILE *f;
722+ char line[2048];
723+ size_t total = 0;
724+ int rc;
725+
726+ if (!bin || !*bin) return 0;
727+ shell_quote_into(bin, qbin, sizeof(qbin));
728+#if defined(_WIN32)
729+ if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>NUL", qbin, args);
730+ else snprintf(cmd, sizeof(cmd), "%s 2>NUL", qbin);
731+#else
732+ if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args);
733+ else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin);
734+#endif
735+
736+ f = popen(cmd, "r");
737+ if (!f) return 0;
738+ while (fgets(line, sizeof(line), f)) {
739+ total += strlen(line);
740+ if (total > OUT_MAX) break;
741+ buf_adds(out, line);
742+ }
743+ rc = pclose(f);
744+
745+ if (out->p) {
746+ size_t n = out->n;
747+ while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0';
748+ out->n = n;
749+ }
750+ if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1;
751+ return 1;
752+}
753+
754+/* The CLIs print human progress before the final JSON line, so take the LAST
755+ * line that starts with '{'. */
756+static const char *last_json_line(buf_t *b)
757+{
758+ size_t i;
759+ const char *last = NULL;
760+
761+ if (!b || !b->p) return NULL;
762+ for (i = 0; i < b->n; i++) {
763+ int at_line_start = (i == 0) || b->p[i - 1] == '\n';
764+ if (at_line_start && b->p[i] == '{') last = b->p + i;
765+ }
766+ return last;
767+}
768+
769+/* ------------------------------------------------------------------ */
770+/* Status assembly */
771+/* ------------------------------------------------------------------ */
772+
773+/* expiresAt is milliseconds in the real file, but a hand-written fixture may
774+ * carry seconds. Detect by magnitude rather than trusting either form. */
775+static long long to_sec(long long v)
776+{
777+ return (v > 100000000000LL) ? (v / 1000) : v;
778+}
779+
780+typedef struct {
781+ char name[NAME_SZ];
782+ int present;
783+ int logged_in;
784+ int has_refresh;
785+ int expired;
786+ long long expires_at; /* raw value from the file (milliseconds) */
787+ long long expires_in_sec; /* negative when expired, 0 when unknown */
788+} account_t;
789+
790+typedef struct {
791+ int logged_in;
792+ int has_refresh;
793+ int pending;
794+ int expired;
795+ int cli_present;
796+ int profile_exists;
797+ char account[NAME_SZ];
798+ char path[PATH_SZ];
799+ char profile[NAME_SZ];
800+ char profile_file[PATH_SZ];
801+ char subscription[64];
802+ char scopes[256];
803+ char cli_error[FIELD_SZ];
804+ long long expires_at; /* milliseconds since epoch, as stored */
805+ long long expires_in_sec; /* seconds; long long, not int: a 32-bit int
806+ * overflows for any expiry past 2038 and turns
807+ * a live session into "expired 60 years ago" */
808+ account_t accounts[MAX_ACCOUNTS];
809+ int account_count;
810+} status_t;
811+
812+/* Parse a credentials file: the claudeAiOauth block carries all of it.
813+ * A named account file has exactly the same shape. */
814+static void scan_creds(const char *json, status_t *st, account_t *acc)
815+{
816+ const char *oauth;
817+ const char *end;
818+ char tok[8] = {0};
819+ int has_access = 0;
820+
821+ if (!json) return;
822+ oauth = strstr(json, "\"claudeAiOauth\"");
823+ /* json_find_key matches TOP-LEVEL keys of the slice it is given, so the
824+ * slice must start at the oauth object's opening brace, not at its key
825+ * name: starting at "claudeAiOauth" makes the real opening brace look like
826+ * a nested object and every field read silently returns absent (a live
827+ * session reported as "not connected", while the JSON was valid). */
828+ if (oauth) {
829+ const char *brace = strchr(oauth, '{');
830+ if (brace) oauth = brace;
831+ }
832+ if (!oauth) return;
833+ end = json + strlen(json);
834+ if (json_str_field(oauth, end, "accessToken", tok, sizeof(tok))) has_access = 1;
835+ memset(tok, 0, sizeof(tok));
836+ if (json_str_field(oauth, end, "refreshToken", tok, sizeof(tok))) {
837+ st->has_refresh = 1;
838+ if (acc) acc->has_refresh = 1;
839+ }
840+ st->expires_at = json_num_field(oauth, end, "expiresAt");
841+ if (acc) acc->expires_at = st->expires_at;
842+ json_str_field(oauth, end, "subscriptionType", st->subscription, sizeof(st->subscription));
843+ if (!st->scopes[0]) {
844+ /* Report the scope NAMES, not the raw JSON array: a copy from the key
845+ * name through ']' carried `"scopes": ` into the string and rendered as
846+ * `"scopes": ["user:profile"` in the UI. Start at '[' and keep only the
847+ * quoted elements, comma-separated. */
848+ const char *sc = strstr(oauth, "\"scopes\"");
849+ const char *open = sc ? strchr(sc, '[') : NULL;
850+ const char *close = open ? strchr(open, ']') : NULL;
851+ if (open && close) {
852+ size_t o = 0;
853+ const char *q = open + 1;
854+ while (q < close && o + 1 < sizeof(st->scopes)) {
855+ if (*q == '"') {
856+ const char *e;
857+ q++;
858+ e = strchr(q, '"');
859+ if (!e || e > close) break;
860+ if (o) st->scopes[o++] = ',';
861+ while (q < e && o + 1 < sizeof(st->scopes)) st->scopes[o++] = *q++;
862+ q = e + 1;
863+ } else {
864+ q++;
865+ }
866+ }
867+ st->scopes[o] = '\0';
868+ }
869+ }
870+ st->logged_in = st->has_refresh || has_access || st->expires_at > 0;
871+ if (acc) acc->logged_in = st->logged_in;
872+}
873+
874+/* Read the profile file written by --create-profile. */
875+static void scan_profile(status_t *st)
876+{
877+ char *text;
878+ char line[FIELD_SZ];
879+
880+ profile_path(st->profile_file, sizeof(st->profile_file));
881+ st->profile_exists = file_exists(st->profile_file);
882+ if (!st->profile_exists) return;
883+ snprintf(st->profile, sizeof(st->profile), "claude_code");
884+
885+ text = read_file(st->profile_file);
886+ if (!text) return;
887+ {
888+ const char *p = text;
889+ while (p && *p) {
890+ const char *nl = strchr(p, '\n');
891+ size_t len = nl ? (size_t)(nl - p) : strlen(p);
892+ if (len > 0 && len < sizeof(line)) {
893+ memcpy(line, p, len);
894+ line[len] = '\0';
895+ trim_tail(line);
896+ if (strncmp(line, "PROVIDER=", 9) == 0 && !st->profile[0])
897+ snprintf(st->profile, sizeof(st->profile), "%.*s",
898+ (int)sizeof(st->profile) - 1, line + 9);
899+ }
900+ if (!nl) break;
901+ p = nl + 1;
902+ }
903+ }
904+ free(text);
905+}
906+
907+/* List the account files in the accounts directory and summarise each one. */
908+static void scan_accounts(status_t *st, long long now_sec)
909+{
910+ char d[PATH_SZ];
911+
912+ st->account_count = 0;
913+ accounts_dir(d, sizeof(d));
914+
915+#if defined(_WIN32)
916+ {
917+ char pattern[PATH_SZ];
918+ WIN32_FIND_DATAA fd;
919+ HANDLE h;
920+ snprintf(pattern, sizeof(pattern), "%s\\*.json", d);
921+ h = FindFirstFileA(pattern, &fd);
922+ if (h == INVALID_HANDLE_VALUE) return;
923+ do {
924+ size_t ln = strlen(fd.cFileName);
925+ if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
926+ if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
927+ {
928+ account_t *a = &st->accounts[st->account_count];
929+ char p[PATH_SZ];
930+ char *json;
931+ memset(a, 0, sizeof(*a));
932+ snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName);
933+ snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, fd.cFileName);
934+ a->present = 1;
935+ json = read_file(p);
936+ if (json) {
937+ status_t tmp;
938+ memset(&tmp, 0, sizeof(tmp));
939+ scan_creds(json, &tmp, a);
940+ free(json);
941+ }
942+ if (a->expires_at > 0 && a->logged_in) {
943+ a->expires_in_sec = to_sec(a->expires_at) - now_sec;
944+ a->expired = a->expires_in_sec <= 0;
945+ }
946+ st->account_count++;
947+ }
948+ } while (FindNextFileA(h, &fd));
949+ FindClose(h);
950+ }
951+#else
952+ {
953+ DIR *dp = opendir(d);
954+ struct dirent *de;
955+ if (!dp) return;
956+ while ((de = readdir(dp)) != NULL) {
957+ size_t ln = strlen(de->d_name);
958+ account_t *a;
959+ char p[PATH_SZ];
960+ char *json;
961+
962+ if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
963+ if (strcmp(de->d_name + ln - 5, ".json") != 0) continue;
964+ a = &st->accounts[st->account_count];
965+ memset(a, 0, sizeof(*a));
966+ snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), de->d_name);
967+ snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, de->d_name);
968+ a->present = 1;
969+ json = read_file(p);
970+ if (json) {
971+ status_t tmp;
972+ memset(&tmp, 0, sizeof(tmp));
973+ scan_creds(json, &tmp, a);
974+ free(json);
975+ }
976+ if (a->expires_at > 0 && a->logged_in) {
977+ a->expires_in_sec = to_sec(a->expires_at) - now_sec;
978+ a->expired = a->expires_in_sec <= 0;
979+ }
980+ st->account_count++;
981+ }
982+ closedir(dp);
983+ }
984+#endif
985+}
986+
987+/* Query the login CLI in machine mode. It is authoritative when present
988+ * (it knows about named accounts, the pending flow and profile creation);
989+ * the credential file is the fallback for a node without SCORPIOX CODE. */
990+static void scan_cli(status_t *st, const char *name)
991+{
992+ buf_t out;
993+ const char *j;
994+ char args[NAME_SZ + 32];
995+
996+ buf_init(&out);
997+ if (name && *name) snprintf(args, sizeof(args), "--status --name %s", name);
998+ else snprintf(args, sizeof(args), "--status");
999+
1000+ {
1001+ int rc = run_capture(login_bin(), args, &out);
1002+ if (rc <= 0) {
1003+ st->cli_present = 0;
1004+ snprintf(st->cli_error, sizeof(st->cli_error), "%s",
1005+ rc == -1 ? "the login CLI is not on this node"
1006+ : "could not start the login CLI");
1007+ buf_free(&out);
1008+ return;
1009+ }
1010+ }
1011+
1012+ j = last_json_line(&out);
1013+ if (!j) {
1014+ st->cli_present = 1;
1015+ buf_free(&out);
1016+ return;
1017+ }
1018+ st->cli_present = 1;
1019+ {
1020+ const char *end = j + strlen(j);
1021+ /* The CLI's logged_in is derived from the same file, but it also knows
1022+ * about a named account file, so trust it when it says yes. */
1023+ if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1;
1024+ if (json_bool_field(j, end, "has_refresh", 0)) st->has_refresh = 1;
1025+ st->pending = json_bool_field(j, end, "pending", 0);
1026+ {
1027+ long long e = json_num_field(j, end, "expires_at");
1028+ if (e > 0) st->expires_at = e;
1029+ }
1030+ {
1031+ char acct[NAME_SZ] = {0};
1032+ if (json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0])
1033+ snprintf(st->account, sizeof(st->account), "%s", acct);
1034+ }
1035+ }
1036+ buf_free(&out);
1037+}
1038+
1039+static void collect_status(status_t *st, const char *name)
1040+{
1041+ char *json;
1042+ long long now_sec = (long long)time(NULL);
1043+
1044+ memset(st, 0, sizeof(*st));
1045+
1046+ /* A named account lives in ~/.claude/accounts/<name>.json, which is the
1047+ * same schema as the default credentials file. */
1048+ if (name && *name) {
1049+ char p[PATH_SZ];
1050+ account_path(name, p, sizeof(p));
1051+ snprintf(st->path, sizeof(st->path), "%s", p);
1052+ snprintf(st->account, sizeof(st->account), "%s", name);
1053+ } else {
1054+ creds_path(st->path, sizeof(st->path));
1055+ }
1056+
1057+ json = read_file(st->path);
1058+ if (json) {
1059+ scan_creds(json, st, NULL);
1060+ free(json);
1061+ }
1062+
1063+ scan_cli(st, name);
1064+ scan_profile(st);
1065+
1066+ {
1067+ char pp[PATH_SZ];
1068+ pending_path(name, pp, sizeof(pp));
1069+ if (file_exists(pp)) st->pending = 1;
1070+ }
1071+
1072+ /* expiresAt is milliseconds since the epoch in this file format. Normalise
1073+ * to seconds for the countdown; a seconds value (from a hand-written
1074+ * fixture) is detected by magnitude and left alone. */
1075+ if (st->expires_at > 0) {
1076+ long long ms = st->expires_at;
1077+ long long sec = (ms > 100000000000LL) ? (ms / 1000) : ms;
1078+ st->expires_in_sec = sec - now_sec;
1079+ st->expired = st->expires_in_sec <= 0;
1080+ }
1081+ if (!st->logged_in) {
1082+ st->expired = 0;
1083+ st->expires_in_sec = 0;
1084+ }
1085+ if (!st->account[0] && st->logged_in)
1086+ snprintf(st->account, sizeof(st->account), "default");
1087+ if (!st->profile[0] && st->profile_exists)
1088+ snprintf(st->profile, sizeof(st->profile), "claude_code");
1089+
1090+ scan_accounts(st, now_sec);
1091+}
1092+
1093+/* One status object, shared by every action so the UI always re-renders from
1094+ * the same shape. */
1095+static void emit_status(buf_t *b, const status_t *st)
1096+{
1097+ int i;
1098+
1099+ buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false");
1100+ buf_adds(b, "\"expires_at\":");
1101+ buf_addf(b, "%lld", st->expires_at);
1102+ buf_addf(b, ",\"expires_at_sec\":%lld",
1103+ st->expires_at > 100000000000LL ? st->expires_at / 1000 : st->expires_at);
1104+ buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec);
1105+ buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
1106+ buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
1107+ buf_adds(b, ",\"account\":");
1108+ buf_json(b, st->account);
1109+ buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
1110+ buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false");
1111+ buf_adds(b, ",\"credentials_path\":");
1112+ buf_json(b, st->path);
1113+ buf_adds(b, ",\"profile\":");
1114+ buf_json(b, st->profile);
1115+ buf_addf(b, ",\"profile_exists\":%s", st->profile_exists ? "true" : "false");
1116+ buf_addf(b, ",\"named_accounts\":%s", st->account_count > 1 ? "true" : "false");
1117+ buf_adds(b, ",\"subscription\":");
1118+ buf_json(b, st->subscription);
1119+ buf_adds(b, ",\"scopes\":");
1120+ buf_json(b, st->scopes);
1121+
1122+ buf_adds(b, ",\"accounts\":[");
1123+ for (i = 0; i < st->account_count; i++) {
1124+ const account_t *a = &st->accounts[i];
1125+ if (i) buf_addc(b, ',');
1126+ buf_adds(b, "{\"name\":");
1127+ buf_json(b, a->name);
1128+ buf_addf(b, ",\"logged_in\":%s", a->logged_in ? "true" : "false");
1129+ buf_addf(b, ",\"has_refresh\":%s", a->has_refresh ? "true" : "false");
1130+ buf_addf(b, ",\"expires_in_sec\":%lld", a->expires_in_sec);
1131+ buf_addf(b, ",\"expired\":%s}", a->expired ? "true" : "false");
1132+ }
1133+ buf_addc(b, ']');
1134+}
1135+
1136+/* ------------------------------------------------------------------ */
1137+/* Actions */
1138+/* ------------------------------------------------------------------ */
1139+
1140+static void json_headers(void)
1141+{
1142+ fputs("Content-Type: application/json; charset=utf-8\r\n"
1143+ "Cache-Control: no-store\r\n"
1144+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1145+}
1146+
1147+static void emit_error(int code, const char *status, const char *err, const char *detail)
1148+{
1149+ buf_t b;
1150+
1151+ buf_init(&b);
1152+ buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n"
1153+ "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",
1154+ code, status);
1155+ buf_adds(&b, "{\"ok\":false,\"error\":");
1156+ buf_json(&b, err);
1157+ if (detail && *detail) {
1158+ buf_adds(&b, ",\"detail\":");
1159+ buf_json(&b, detail);
1160+ }
1161+ buf_adds(&b, "}\n");
1162+ fputs(buf_str(&b), stdout);
1163+ buf_free(&b);
1164+}
1165+
1166+static int action_status(const char *name)
1167+{
1168+ status_t st;
1169+ buf_t b;
1170+
1171+ collect_status(&st, name);
1172+ buf_init(&b);
1173+ buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",");
1174+ emit_status(&b, &st);
1175+ buf_adds(&b, ",\"flow\":\"paste_code\",\"protocol\":\"SXLOGIN-MACHINE-V1\"}\n");
1176+ json_headers();
1177+ fputs(buf_str(&b), stdout);
1178+ buf_free(&b);
1179+ return 0;
1180+}
1181+
1182+static int action_start(const char *name, int force)
1183+{
1184+ buf_t out, b;
1185+ const char *j;
1186+ char args[NAME_SZ + 64];
1187+ char auth_url[CMD_SZ] = {0};
1188+ char flow[64] = {0};
1189+ char hint[FIELD_SZ] = {0};
1190+ long long expires_in = 0;
1191+
1192+ if (name && *name) {
1193+ const char *nm = name;
1194+ char qname[NAME_SZ * 2];
1195+ shell_quote_into(nm, qname, sizeof(qname));
1196+ snprintf(args, sizeof(args), "--start%s --name %s", force ? " --force" : "", qname);
1197+ } else {
1198+ snprintf(args, sizeof(args), "--start%s", force ? " --force" : "");
1199+ }
1200+
1201+ buf_init(&out);
1202+ {
1203+ int rc = run_capture(login_bin(), args, &out);
1204+ if (rc <= 0) {
1205+ buf_free(&out);
1206+ emit_error(200, "OK", "cli_unavailable",
1207+ "the login CLI is not on this node; install SCORPIOX CODE or set CLAUDE_LOGIN_BIN");
1208+ return 1;
1209+ }
1210+ }
1211+ j = last_json_line(&out);
1212+ if (!j) {
1213+ emit_error(200, "OK", "start_failed", "the login CLI returned no JSON");
1214+ buf_free(&out);
1215+ return 1;
1216+ }
1217+ {
1218+ const char *end = j + strlen(j);
1219+ json_str_field(j, end, "auth_url", auth_url, sizeof(auth_url));
1220+ json_str_field(j, end, "flow", flow, sizeof(flow));
1221+ json_str_field(j, end, "hint", hint, sizeof(hint));
1222+ expires_in = json_num_field(j, end, "expires_in");
1223+ if (!json_bool_field(j, end, "ok", 1) || !auth_url[0]) {
1224+ char detail[FIELD_SZ] = {0};
1225+ json_str_field(j, end, "error", detail, sizeof(detail));
1226+ buf_free(&out);
1227+ emit_error(200, "OK", detail[0] ? detail : "start_failed",
1228+ "the login CLI did not return an authorization URL");
1229+ return 1;
1230+ }
1231+ }
1232+ buf_free(&out);
1233+
1234+ buf_init(&b);
1235+ buf_adds(&b, "{\"ok\":true,\"flow\":");
1236+ buf_json(&b, flow[0] ? flow : "paste_code");
1237+ buf_adds(&b, ",\"auth_url\":");
1238+ buf_json(&b, auth_url);
1239+ buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : 600);
1240+ buf_adds(&b, ",\"hint\":");
1241+ buf_json(&b, hint[0] ? hint
1242+ : "Sign in with Claude, then paste the code shown on the callback page.");
1243+ buf_adds(&b, "}\n");
1244+ json_headers();
1245+ fputs(buf_str(&b), stdout);
1246+ buf_free(&b);
1247+ return 0;
1248+}
1249+
1250+/* Reject anything that cannot be an authorization code. The value reaches a
1251+ * shell through run_capture(), so this is the second line of defence behind
1252+ * shell_quote_into(). */
1253+static int code_valid(const char *code)
1254+{
1255+ size_t n, i;
1256+
1257+ if (!code || !(n = strlen(code)) || n > CODE_MAX) return 0;
1258+ for (i = 0; i < n; i++) {
1259+ unsigned char c = (unsigned char)code[i];
1260+ if (c < 0x20 || c == 0x7f || c == '\'' || c == '"' || c == '\\' || c == ';' ||
1261+ c == '`' || c == '$' || c == '|' || c == '&' || c == '<' || c == '>')
1262+ return 0;
1263+ }
1264+ return 1;
1265+}
1266+
1267+static int action_finish(const char *raw_code, const char *name, int force)
1268+{
1269+ char code[CODE_MAX];
1270+ char qcode[CODE_MAX + 64];
1271+ char args[CODE_MAX + NAME_SZ + 128];
1272+ buf_t out, b;
1273+ const char *j;
1274+
1275+ if (!raw_code || !*raw_code) {
1276+ emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=...");
1277+ return 1;
1278+ }
1279+ snprintf(code, sizeof(code), "%s", raw_code);
1280+ url_decode(code);
1281+ trim_tail(code);
1282+
1283+ /* A user usually pastes the whole redirect address. Extract code= BEFORE
1284+ * validating, so a legitimate URL is not refused for carrying state= too.
1285+ * Validating first would reject every real paste, because '&' and '=' are
1286+ * exactly the characters a bare code never contains. */
1287+ {
1288+ char *c = strstr(code, "code=");
1289+ if (c) {
1290+ char extracted[CODE_MAX];
1291+ size_t i = 0;
1292+ c += 5;
1293+ while (*c && *c != '&' && *c != '#' && i + 1 < sizeof(extracted))
1294+ extracted[i++] = *c++;
1295+ extracted[i] = '\0';
1296+ if (i > 0) {
1297+ /* An embedded '&' or '#' is expected in a URL, not in a code. */
1298+ if (code_valid(extracted)) snprintf(code, sizeof(code), "%s", extracted);
1299+ }
1300+ }
1301+ }
1302+ {
1303+ char *hash = strchr(code, '#');
1304+ if (hash) *hash = '\0';
1305+ }
1306+ if (!code_valid(code)) {
1307+ emit_error(400, "Bad Request", "invalid_code",
1308+ "the value is not an authorization code (empty, too long, or contains shell characters)");
1309+ return 1;
1310+ }
1311+
1312+ shell_quote_into(code, qcode, sizeof(qcode));
1313+ {
1314+ char qname[NAME_SZ * 2];
1315+ const char *extra = "";
1316+ if (name && *name) {
1317+ shell_quote_into(name, qname, sizeof(qname));
1318+ extra = qname;
1319+ }
1320+ if (extra[0])
1321+ snprintf(args, sizeof(args), "--finish %s --name %s%s",
1322+ qcode, extra, force ? " --force" : "");
1323+ else
1324+ snprintf(args, sizeof(args), "--finish %s%s", qcode, force ? " --force" : "");
1325+ }
1326+
1327+ buf_init(&out);
1328+ {
1329+ int rc = run_capture(login_bin(), args, &out);
1330+ if (rc <= 0) {
1331+ buf_free(&out);
1332+ emit_error(200, "OK", "cli_unavailable",
1333+ "the login CLI is not on this node; install SCORPIOX CODE or set CLAUDE_LOGIN_BIN");
1334+ return 1;
1335+ }
1336+ }
1337+ j = last_json_line(&out);
1338+ if (!j) {
1339+ buf_free(&out);
1340+ emit_error(200, "OK", "finish_failed", "the login CLI returned no JSON");
1341+ return 1;
1342+ }
1343+ {
1344+ const char *end = j + strlen(j);
1345+ if (!json_bool_field(j, end, "ok", 0)) {
1346+ char detail[FIELD_SZ] = {0};
1347+ json_str_field(j, end, "error", detail, sizeof(detail));
1348+ buf_free(&out);
1349+ emit_error(200, "OK", detail[0] ? detail : "finish_failed",
1350+ "Claude rejected the code, or it has already been used or has expired");
1351+ return 1;
1352+ }
1353+ }
1354+ buf_free(&out);
1355+
1356+ {
1357+ status_t st;
1358+ collect_status(&st, name);
1359+ buf_init(&b);
1360+ buf_adds(&b, "{\"ok\":true,\"state\":\"done\",");
1361+ emit_status(&b, &st);
1362+ buf_adds(&b, "}\n");
1363+ json_headers();
1364+ fputs(buf_str(&b), stdout);
1365+ buf_free(&b);
1366+ }
1367+ return 0;
1368+}
1369+
1370+static int action_cancel(const char *name)
1371+{
1372+ buf_t out, b;
1373+ char args[NAME_SZ + 32];
1374+
1375+ if (name && *name) {
1376+ char qname[NAME_SZ * 2];
1377+ shell_quote_into(name, qname, sizeof(qname));
1378+ snprintf(args, sizeof(args), "--cancel --name %s", qname);
1379+ } else {
1380+ snprintf(args, sizeof(args), "--cancel");
1381+ }
1382+
1383+ buf_init(&out);
1384+ run_capture(login_bin(), args, &out);
1385+ buf_free(&out);
1386+
1387+ buf_init(&b);
1388+ buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n");
1389+ json_headers();
1390+ fputs(buf_str(&b), stdout);
1391+ buf_free(&b);
1392+ return 0;
1393+}
1394+
1395+/* Refresh: the refresh CLI performs the refresh-token grant and updates the
1396+ * credentials file in place. Its stdout is human text (and may quote token
1397+ * material), so the payload is read, then discarded. The new state is proven
1398+ * by re-reading the file, not by the CLI's word. */
1399+static int action_refresh(const char *name)
1400+{
1401+ buf_t out, b;
1402+ char args[PATH_SZ + 96];
1403+ char qpath[PATH_SZ * 2];
1404+ char path[PATH_SZ];
1405+ long long before;
1406+ status_t st;
1407+
1408+ if (name && *name) account_path(name, path, sizeof(path));
1409+ else creds_path(path, sizeof(path));
1410+
1411+ if (!file_exists(path)) {
1412+ buf_init(&b);
1413+ buf_adds(&b, "{\"ok\":false,\"error\":\"no_credentials\",\"detail\":");
1414+ buf_json(&b, "there is no credentials file on this node; start a login first");
1415+ buf_adds(&b, "}\n");
1416+ json_headers();
1417+ fputs(buf_str(&b), stdout);
1418+ buf_free(&b);
1419+ return 1;
1420+ }
1421+
1422+ collect_status(&st, name);
1423+ before = st.expires_at;
1424+
1425+ shell_quote_into(path, qpath, sizeof(qpath));
1426+ /* action=refresh means "refresh now", so the CLI is always invoked with
1427+ * --force: without it the CLI no-ops on a still-valid token and the user's
1428+ * button does nothing. */
1429+ snprintf(args, sizeof(args), "--credentials-file %s --force", qpath);
1430+
1431+ buf_init(&out);
1432+ {
1433+ int rc = run_capture(refresh_bin(), args, &out);
1434+ if (rc <= 0) {
1435+ buf_free(&out);
1436+ emit_error(200, "OK", "cli_unavailable",
1437+ "the refresh CLI is not on this node; install SCORPIOX CODE or set CLAUDE_REFRESH_BIN");
1438+ return 1;
1439+ }
1440+ }
1441+ buf_free(&out);
1442+
1443+ collect_status(&st, name);
1444+ if (!st.logged_in || (before > 0 && st.expires_at <= before && !st.expired)) {
1445+ buf_init(&b);
1446+ buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":");
1447+ buf_json(&b, "the refresh CLI did not update the credentials file; sign in again");
1448+ buf_adds(&b, "}\n");
1449+ json_headers();
1450+ fputs(buf_str(&b), stdout);
1451+ buf_free(&b);
1452+ return 1;
1453+ }
1454+
1455+ buf_init(&b);
1456+ buf_adds(&b, "{\"ok\":true,\"refreshed\":true,");
1457+ emit_status(&b, &st);
1458+ buf_adds(&b, "}\n");
1459+ json_headers();
1460+ fputs(buf_str(&b), stdout);
1461+ buf_free(&b);
1462+ return 0;
1463+}
1464+
1465+/* ------------------------------------------------------------------ */
1466+/* HTML emission */
1467+/* ------------------------------------------------------------------ */
1468+
1469+/* Expand the two placeholders tools/gen_ui.py leaves in UI_HTML. Keeping the
1470+ * split means the palette lives in exactly one place (bot_theme_plugin.h) and
1471+ * the page can never drift away from the bot's own theme. */
1472+static void emit_ui(void)
1473+{
1474+ const char *p = UI_HTML;
1475+
1476+ while (*p) {
1477+ if (*p == '\001') {
1478+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout);
1479+ p++;
1480+ } else if (*p == '\002') {
1481+ /* SX_BOT_THEME_HANDOFF and SX_BOT_THEME_TOGGLE_JS are both complete
1482+ * <script>...</script> strings, so they are emitted as siblings.
1483+ * Without the toggle macro the page's Theme button is inert: the
1484+ * bot owns the theme, but a plugin opened in its own tab needs a
1485+ * switch of its own. */
1486+ fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout);
1487+ p++;
1488+ } else {
1489+ putchar(*p++);
1490+ }
1491+ }
1492+}
1493+
1494+/* Read a POST body field of the form "code":"..." (a long code is easier to
1495+ * send in a body than in a URL). Guarded on CONTENT_LENGTH so an empty
1496+ * inherited stdin can never block. */
1497+static int body_field(const char *field, char *out, size_t outsz)
1498+{
1499+ const char *cl = getenv("CONTENT_LENGTH");
1500+ long n = (cl && *cl) ? atol(cl) : 0;
1501+ char *body;
1502+ size_t len;
1503+ int got = 0;
1504+
1505+ if (n <= 0 || n > (long)(256 * 1024)) return 0;
1506+ body = (char *)malloc((size_t)n + 1);
1507+ if (!body) return 0;
1508+ len = fread(body, 1, (size_t)n, stdin);
1509+ body[len] = '\0';
1510+ {
1511+ char *p = strstr(body, field);
1512+ if (p) {
1513+ p = strchr(p, ':');
1514+ if (p) {
1515+ size_t i = 0;
1516+ p++;
1517+ while (*p == ' ' || *p == '\t') p++;
1518+ if (*p == '"') p++;
1519+ while (*p && *p != '"' && i + 1 < outsz) out[i++] = *p++;
1520+ out[i] = '\0';
1521+ got = i > 0;
1522+ }
1523+ }
1524+ }
1525+ free(body);
1526+ return got;
1527+}
1528+
1529+/* ------------------------------------------------------------------ */
1530+/* main */
1531+/* ------------------------------------------------------------------ */
1532+
1533+int main(int argc, char **argv)
1534+{
1535+ const char *qs;
1536+ char action[64] = {0};
1537+ char name[NAME_SZ] = {0};
1538+ char code[CODE_MAX] = {0};
1539+ int force = 0;
1540+
1541+ /* 1. Discovery metadata. Must stay unauthenticated. */
1542+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1543+ puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}");
1544+ return 0;
1545+ }
1546+ if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
1547+ puts(PLUGIN_ID " " PLUGIN_VER);
1548+ return 0;
1549+ }
1550+
1551+ require_node_auth();
1552+
1553+ qs = getenv("QUERY_STRING");
1554+ if (!qs) qs = "";
1555+
1556+ get_query_val(qs, "name", name, sizeof(name));
1557+ if (name[0] && !name_valid(name)) {
1558+ emit_error(400, "Bad Request", "bad_name", "account names use letters, digits, - _ . (max 64)");
1559+ return 1;
1560+ }
1561+ {
1562+ char f[8] = {0};
1563+ if (get_query_val(qs, "force", f, sizeof(f)))
1564+ force = (f[0] == '1' || f[0] == 't' || f[0] == 'T' || f[0] == 'y');
1565+ }
1566+
1567+ /* 2. JSON API mode. `format=json` alone means "status", which is what a
1568+ * dashboard polls. */
1569+ if (query_has(qs, "action") || query_has(qs, "format")) {
1570+ char fmt[32] = {0};
1571+
1572+ get_query_val(qs, "action", action, sizeof(action));
1573+ get_query_val(qs, "format", fmt, sizeof(fmt));
1574+ if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status");
1575+
1576+ if (strcmp(action, "status") == 0 || !action[0]) return action_status(name);
1577+ if (strcmp(action, "start") == 0) return action_start(name, force);
1578+ if (strcmp(action, "cancel") == 0) return action_cancel(name);
1579+ if (strcmp(action, "refresh") == 0) return action_refresh(name);
1580+ if (strcmp(action, "accounts") == 0) return action_status(name);
1581+ if (strcmp(action, "finish") == 0) {
1582+ if (!get_query_val(qs, "code", code, sizeof(code))) {
1583+ if (!body_field("\"code\"", code, sizeof(code))) {
1584+ emit_error(400, "Bad Request", "missing_code",
1585+ "pass the authorization code as &code=...");
1586+ return 1;
1587+ }
1588+ }
1589+ return action_finish(code, name, force);
1590+ }
1591+ emit_error(404, "Not Found", "unknown_action", action);
1592+ return 1;
1593+ }
1594+
1595+ /* 3. HTML UI. UI_HTML carries two control bytes: 0x01 is the theme block
1596+ * (<style> with the bot tokens) and 0x02 is the handoff script before
1597+ * </body>. */
1598+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1599+ "Cache-Control: no-store\r\n"
1600+ "X-Content-Type-Options: nosniff\r\n"
1601+ "Referrer-Policy: no-referrer\r\n"
1602+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
1603+ "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
1604+ "base-uri 'none'; form-action 'none'; frame-ancestors *\r\n\r\n", stdout);
1605+ emit_ui();
1606+ return 0;
1607+}
src/ui.html+399−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..59081e6index 0000000..59081e6
--- /dev/null--- /dev/null
+++ b/src/ui.html+++ b/src/ui.html
@@ -0,0 +1,399 @@@@ -0,0 +1,399 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>claude</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0;min-height:100%}
9+body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;
10+ line-height:1.5;-webkit-font-smoothing:antialiased}
11+#app{max-width:840px;margin:0 auto;padding:16px 16px 40px}
12+.hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}
13+.hd .grow{flex:1 1 auto;min-width:0}
14+.hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}
15+.hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;
16+ overflow:hidden;text-overflow:ellipsis}
17+.pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;
18+ padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);
19+ border:1px solid var(--line);white-space:nowrap}
20+.pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}
21+.pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}
22+.pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}
23+.pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}
24+.pill.warn .dot{background:var(--orange)}
25+.pill.off .dot{background:var(--gray)}
26+.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;
27+ padding:16px;margin-bottom:12px}
28+.card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;
29+ text-transform:uppercase;color:var(--text-2)}
30+.card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}
31+.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
32+.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;
33+ font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;
34+ transition:transform .12s var(--ease),opacity .12s}
35+.btn:active{transform:scale(.98)}
36+.btn:disabled{opacity:.5;cursor:default}
37+.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}
38+.btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}
39+.btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}
40+a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}
41+.kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}
42+.kv .k{color:var(--text-2);font-size:12px}
43+.kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}
44+.kv .v.plain{font-family:var(--font);font-size:13px}
45+.step{display:none}
46+.step.on{display:block}
47+.hint{margin:10px 0 0;font-size:12px;color:var(--text-2)}
48+.note{font-size:12.5px;margin-top:10px;display:none}
49+.note.show{display:block}
50+.note.err{color:var(--red)}
51+.note.ok{color:var(--green)}
52+.authurl{font-family:var(--mono);font-size:11.5px;color:var(--text-2);word-break:break-all;
53+ background:var(--code-bg);border:1px solid var(--line);border-radius:10px;
54+ padding:10px;margin-top:10px;max-height:120px;overflow:auto}
55+textarea{width:100%;margin-top:10px;min-height:74px;resize:vertical;background:var(--input-bg);
56+ color:var(--text);border:1px solid var(--line);border-radius:10px;padding:10px;
57+ font-family:var(--mono);font-size:12px;outline:none}
58+textarea:focus{border-color:var(--blue)}
59+.count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}
60+.count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}
61+.bar{height:6px;border-radius:999px;background:var(--surface-2);overflow:hidden;margin-top:10px}
62+.bar .fill{display:block;height:100%;background:var(--green);border-radius:999px;
63+ transition:width .3s var(--ease)}
64+.bar.warn .fill{background:var(--orange)}
65+.bar.err .fill{background:var(--red)}
66+.spin{width:12px;height:12px;border-radius:50%;border:2px solid rgba(255,255,255,.35);
67+ border-top-color:#fff;display:none;animation:sp .7s linear infinite}
68+.btn.loading .spin{display:inline-block}
69+@keyframes sp{to{transform:rotate(360deg)}}
70+.acct{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--line);
71+ font-size:13px;flex-wrap:wrap}
72+.acct:first-of-type{border-top:0}
73+.acct .nm{font-family:var(--mono);font-size:12px;flex:1 1 120px;min-width:0;
74+ overflow:hidden;text-overflow:ellipsis}
75+.acct .tag{font-size:11px;color:var(--text-2)}
76+.acct .tag.ok{color:var(--green)}
77+.acct .tag.warn{color:var(--orange)}
78+.empty{padding:10px 0;color:var(--text-2);font-size:12.5px}
79+.toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;
80+ pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);
81+ color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;
82+ box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);
83+ z-index:9;max-width:calc(100vw - 32px)}
84+.toast.show{opacity:1;transform:translate(-50%,0)}
85+#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);
86+ border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;
87+ font-family:inherit}
88+@media (max-width:520px){
89+ #app{padding:12px 12px 32px}
90+ .kv{grid-template-columns:1fr;gap:2px 0}
91+ .kv .k{margin-top:8px}
92+ .card{padding:13px;border-radius:12px}
93+ .count{font-size:28px}
94+}
95+</style>
96+</head>
97+<body>
98+<div id="app">
99+ <div class="hd">
100+ <div class="grow">
101+ <h1>Claude Code</h1>
102+ <div class="sub" id="sub">OAuth PKCE login on this node</div>
103+ </div>
104+ <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span>
105+ <button id="themeToggle" class="embed-hide" type="button">Theme</button>
106+ </div>
107+
108+ <div class="card">
109+ <h2>Session</h2>
110+ <p class="lead" id="sessionLead">Reading the local Claude Code credentials.</p>
111+ <div class="count" id="count">-</div>
112+ <div class="bar" id="bar"><span class="fill" id="fill" style="width:0%"></span></div>
113+ <div class="kv" id="session" style="margin-top:14px"></div>
114+ <div class="row" style="margin-top:14px">
115+ <button class="btn ghost" id="btnRefresh" type="button"><span class="spin"></span>Refresh Token Now</button>
116+ <button class="btn ghost" id="btnReload" type="button">Reload</button>
117+ </div>
118+ <div class="note" id="refreshNote"></div>
119+ </div>
120+
121+ <div class="card">
122+ <h2>OAuth login</h2>
123+ <p class="lead">Sign in with Claude. Nothing leaves this node: the login CLI performs the
124+ exchange and writes the credential file here.</p>
125+
126+ <div class="step on" id="step1">
127+ <div class="row">
128+ <button class="btn" id="btnStart" type="button">Start Claude Login</button>
129+ <button class="btn ghost" id="btnRelogin" type="button">Re-login (replace)</button>
130+ </div>
131+ <p class="hint">This generates a PKCE challenge and an authorization link. No token is
132+ created until you paste the code back.</p>
133+ </div>
134+
135+ <div class="step" id="step2">
136+ <div class="row">
137+ <a class="btn" id="linkOpen" href="#" target="_blank" rel="noopener noreferrer">Open Claude.ai</a>
138+ <button class="btn ghost" id="btnCopy" type="button">Copy link</button>
139+ <button class="btn ghost" id="btnCancel" type="button">Cancel</button>
140+ </div>
141+ <div class="authurl" id="authUrl"></div>
142+ <p class="hint" id="flowHint">After approving, Claude shows an authorization code. Paste the
143+ whole redirect address or just the <span style="font-family:var(--mono)">code=</span> value below.</p>
144+ <textarea id="codeInput" spellcheck="false" autocomplete="off"
145+ placeholder="Paste the authorization code or the full redirect URL"></textarea>
146+ <div class="row" style="margin-top:10px">
147+ <button class="btn" id="btnFinish" type="button">Submit Code</button>
148+ </div>
149+ <div class="note" id="loginNote"></div>
150+ </div>
151+ </div>
152+
153+ <div class="card">
154+ <h2>Named accounts</h2>
155+ <p class="lead">Every account file in the local accounts directory.</p>
156+ <div id="accounts"><div class="empty">No named accounts.</div></div>
157+ </div>
158+</div>
159+
160+<div class="toast" id="toast"></div>
161+
162+<script>
163+var q=new URLSearchParams(location.search);
164+var node=q.get('node')||'';
165+var sid=q.get('id')||'';
166+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
167+ localStorage.getItem('bot_active_pwd')||'';
168+
169+/* Two call routes. Getting this wrong is the most common plugin bug:
170+ * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)
171+ * -> call the hub proxy back: /plugins?plugin=plugin_claudecode_login&action=..
172+ * opened directly on the node
173+ * -> the plugin itself is the route: /plugin_claudecode_login?action=..
174+ * Calling /plugins?plugin= on the node returns the discovery list, not us. */
175+var HUB=q.get('plugin')||'';
176+function url(action,extra){
177+ return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_claudecode_login')+
178+ '?action='+encodeURIComponent(action)+
179+ (extra?('&'+extra):'')+
180+ (node?'&node='+encodeURIComponent(node):'')+
181+ (sid?'&id='+encodeURIComponent(sid):'')+
182+ (pwd?'&pwd='+encodeURIComponent(pwd):'');
183+}
184+function hdr(){
185+ var h={};
186+ if(pwd)h['X-Bot-Password']=pwd;
187+ return h;
188+}
189+function api(action,extra){
190+ return fetch(url(action,extra),{headers:hdr()}).then(function(r){
191+ return r.json().catch(function(){return {ok:false,error:'bad response'};});
192+ });
193+}
194+
195+var $=function(id){return document.getElementById(id);};
196+function toast(msg){
197+ var t=$('toast');t.textContent=msg;t.classList.add('show');
198+ clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);
199+}
200+function note(el,msg,kind){
201+ el.textContent=msg||'';
202+ el.className='note'+(msg?' show '+(kind||''):'');
203+}
204+function kv(el,rows){
205+ el.innerHTML='';
206+ rows.forEach(function(r){
207+ var a=document.createElement('div');a.className='k';a.textContent=r[0];
208+ var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');
209+ b.textContent=r[1];el.appendChild(a);el.appendChild(b);
210+ });
211+}
212+function fmtExpiry(sec){
213+ if(typeof sec!=='number')return '-';
214+ if(sec<=0)return 'expired';
215+ if(sec<90)return sec+'s';
216+ if(sec<5400)return Math.round(sec/60)+' min';
217+ if(sec<172800)return Math.round(sec/3600)+' h';
218+ if(sec<63072000)return Math.round(sec/86400)+' d';
219+ return Math.round(sec/31536000)+' yr';
220+}
221+function countdown(sec){
222+ if(typeof sec!=='number'||sec<=0)return ['-',''];
223+ var d=Math.floor(sec/86400),h=Math.floor((sec%86400)/3600),
224+ m=Math.floor((sec%3600)/60),s=sec%60,u='second';
225+ var v,d2;
226+ if(d>0){v=d;u='day';d2=[h+'h',m+'m'].join(' ');}
227+ else if(h>0){v=h;u='hour';d2=[m+'m'].join(' ');}
228+ else if(m>0){v=m;u='minute';d2=[s+'s'].join(' ');}
229+ else {v=s;d2='';}
230+ return [v+' <small>'+(v===1?u:u+'s')+(d2?' &middot; '+d2:'')+'</small>',''];
231+}
232+function setPill(st){
233+ var p=$('pill'),t=$('pillText');
234+ if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}
235+ else if(st.logged_in){p.className='pill ok';t.textContent='Logged In';}
236+ else if(st.pending){p.className='pill warn';t.textContent='Signing in';}
237+ else {p.className='pill off';t.textContent='Not Connected';}
238+}
239+/* Full token lifetime is 8 h for a Claude Code session; the bar is a share of
240+ * the remaining time, so it is a coarse but honest "how much is left" read.
241+ * A countdown of 0 with a refresh token present is the normal steady state. */
242+var LIFETIME=8*3600;
243+function render(st){
244+ setPill(st);
245+ $('sub').textContent=st.account?st.account:'OAuth PKCE login on this node';
246+
247+ if(st.logged_in){
248+ $('sessionLead').textContent=st.expired
249+ ? 'The session is present but its access token has expired. Use Refresh Token Now.'
250+ : 'This node holds a Claude Code session.';
251+ }else{
252+ $('sessionLead').textContent='No Claude Code session on this node yet. Start a login below.';
253+ }
254+
255+ var c=countdown(st.expires_in_sec);
256+ $('count').innerHTML=st.logged_in?c[0]:'not connected';
257+ var pct=0;
258+ if(st.logged_in&&st.expires_in_sec>0){
259+ pct=Math.max(2,Math.min(100,Math.round(st.expires_in_sec/LIFETIME*100)));
260+ }
261+ $('fill').style.width=pct+'%';
262+ $('bar').className='bar'+(st.expired?' err':(pct<20?' warn':''));
263+ if(!st.logged_in)$('bar').className='bar';
264+
265+ kv($('session'),[
266+ ['Account', st.account||'-', true],
267+ ['Logged in', st.logged_in?'yes':'no', true],
268+ ['Refresh token', st.has_refresh?'stored':'none', true],
269+ ['Token expires', st.logged_in?fmtExpiry(st.expires_in_sec):'-', true],
270+ ['Subscription', st.subscription||'-', true],
271+ ['Login pending', st.pending?'yes':'no', true],
272+ ['Login CLI', st.cli_present?'found':'not found', true],
273+ ['Profile', st.profile_exists?(st.profile||'claude_code'):'not created', true],
274+ ['Credentials', st.credentials_path||'-']
275+ ]);
276+
277+ var box=$('accounts');
278+ box.innerHTML='';
279+ var list=st.accounts||[];
280+ if(!list.length){
281+ var e=document.createElement('div');e.className='empty';
282+ e.textContent='No named accounts.';box.appendChild(e);
283+ }else{
284+ list.forEach(function(a){
285+ var row=document.createElement('div');row.className='acct';
286+ var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;
287+ var tg=document.createElement('div');
288+ tg.className='tag '+(a.logged_in?(a.expired?'warn':'ok'):'');
289+ tg.textContent=a.logged_in?(a.expired?'expired':'valid'):'no token';
290+ row.appendChild(nm);row.appendChild(tg);box.appendChild(row);
291+ });
292+ }
293+
294+ if(st.pending){$('step1').classList.remove('on');$('step2').classList.add('on');}
295+}
296+function load(){
297+ return api('status').then(function(d){
298+ if(d&&d.ok)render(d);
299+ else toast((d&&d.error)||'status failed');
300+ }).catch(function(e){toast('Status failed: '+e.message);});
301+}
302+
303+var authUrl='';
304+function start(force){
305+ var b=force?$('btnRelogin'):$('btnStart');
306+ b.disabled=true;b.textContent='Starting...';
307+ api('start',force?'force=1':'').then(function(d){
308+ b.disabled=false;b.textContent=force?'Re-login (replace)':'Start Claude Login';
309+ if(!d||!d.ok){toast((d&&(d.detail||d.error))||'start failed');return;}
310+ authUrl=d.auth_url||'';
311+ $('authUrl').textContent=authUrl;
312+ $('linkOpen').setAttribute('href',authUrl);
313+ if(d.hint)$('flowHint').textContent=d.hint;
314+ $('step1').classList.remove('on');
315+ $('step2').classList.add('on');
316+ $('codeInput').focus();
317+ }).catch(function(e){
318+ b.disabled=false;b.textContent=force?'Re-login (replace)':'Start Claude Login';
319+ toast('Start failed: '+e.message);
320+ });
321+}
322+
323+function finish(){
324+ var raw=$('codeInput').value.trim();
325+ if(!raw){note($('loginNote'),'Paste the code or the redirect address first.','err');return;}
326+ var b=$('btnFinish');
327+ b.disabled=true;b.textContent='Exchanging...';
328+ note($('loginNote'),'Exchanging the code for a token.');
329+ api('finish','code='+encodeURIComponent(raw)).then(function(d){
330+ b.disabled=false;b.textContent='Submit Code';
331+ if(!d||!d.ok){
332+ note($('loginNote'),(d&&(d.detail||d.error))||'exchange failed','err');
333+ return;
334+ }
335+ note($('loginNote'),'');
336+ $('step2').classList.remove('on');
337+ $('step1').classList.add('on');
338+ $('codeInput').value='';
339+ render(d);
340+ toast('Signed in as '+(d.account||'Claude account'));
341+ }).catch(function(e){
342+ b.disabled=false;b.textContent='Submit Code';
343+ note($('loginNote'),'Exchange failed: '+e.message,'err');
344+ });
345+}
346+
347+function cancel(){
348+ api('cancel').then(function(){
349+ $('step2').classList.remove('on');
350+ $('step1').classList.add('on');
351+ $('codeInput').value='';
352+ note($('loginNote'),'');
353+ toast('Pending login cancelled');
354+ load();
355+ }).catch(function(e){toast('Cancel failed: '+e.message);});
356+}
357+
358+function refreshToken(){
359+ var b=$('btnRefresh');
360+ b.disabled=true;b.classList.add('loading');
361+ b.lastChild.textContent=' Refreshing...';
362+ note($('refreshNote'),'Asking Claude for a new access token...');
363+ api('refresh').then(function(d){
364+ b.disabled=false;b.classList.remove('loading');
365+ b.lastChild.textContent='Refresh Token Now';
366+ if(!d||!d.ok){
367+ note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');
368+ return;
369+ }
370+ note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');
371+ render(d);
372+ }).catch(function(e){
373+ b.disabled=false;b.classList.remove('loading');
374+ b.lastChild.textContent='Refresh Token Now';
375+ note($('refreshNote'),'Refresh failed: '+e.message,'err');
376+ });
377+}
378+
379+function copyLink(){
380+ if(!authUrl)return;
381+ var done=function(){toast('Link copied');};
382+ if(navigator.clipboard&&navigator.clipboard.writeText){
383+ navigator.clipboard.writeText(authUrl).then(done).catch(function(){toast('Copy failed');});
384+ }else{toast('Copy not available');}
385+}
386+
387+$('btnStart').onclick=function(){start(false);};
388+$('btnRelogin').onclick=function(){start(true);};
389+$('btnFinish').onclick=finish;
390+$('btnCancel').onclick=cancel;
391+$('btnRefresh').onclick=refreshToken;
392+$('btnReload').onclick=load;
393+$('btnCopy').onclick=copyLink;
394+$('codeInput').addEventListener('keydown',function(e){
395+ if(e.key==='Enter'&&(e.metaKey||e.ctrlKey)){e.preventDefault();finish();}
396+});
397+load();
398+</script>
399+</body></html>
src/ui_html.h+407−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..d3accf2index 0000000..d3accf2
--- /dev/null--- /dev/null
+++ b/src/ui_html.h+++ b/src/ui_html.h
@@ -0,0 +1,407 @@@@ -0,0 +1,407 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_CCLOGIN_UI_HTML_H
3+#define SX_CCLOGIN_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n"
9+ "<title>claude</title>\n"
10+ "\001\n"
11+ "<style>\n"
12+ "*{box-sizing:border-box}\n"
13+ "html,body{margin:0;min-height:100%}\n"
14+ "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n"
15+ " line-height:1.5;-webkit-font-smoothing:antialiased}\n"
16+ "#app{max-width:840px;margin:0 auto;padding:16px 16px 40px}\n"
17+ ".hd{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n"
18+ ".hd .grow{flex:1 1 auto;min-width:0}\n"
19+ ".hd h1{margin:0;font-size:18px;font-weight:650;letter-spacing:-.01em}\n"
20+ ".hd .sub{font-size:11.5px;color:var(--text-2);margin-top:2px;white-space:nowrap;\n"
21+ " overflow:hidden;text-overflow:ellipsis}\n"
22+ ".pill{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;font-weight:650;\n"
23+ " padding:4px 10px;border-radius:999px;background:var(--surface-2);color:var(--text-2);\n"
24+ " border:1px solid var(--line);white-space:nowrap}\n"
25+ ".pill .dot{width:7px;height:7px;border-radius:50%;background:var(--gray);flex:0 0 auto}\n"
26+ ".pill.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n"
27+ ".pill.ok .dot{background:var(--green);box-shadow:0 0 0 3px rgba(48,209,88,.15)}\n"
28+ ".pill.warn{color:var(--orange);border-color:rgba(255,159,10,.35)}\n"
29+ ".pill.warn .dot{background:var(--orange)}\n"
30+ ".pill.off .dot{background:var(--gray)}\n"
31+ ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;\n"
32+ " padding:16px;margin-bottom:12px}\n"
33+ ".card h2{margin:0 0 4px;font-size:13px;font-weight:700;letter-spacing:.08em;\n"
34+ " text-transform:uppercase;color:var(--text-2)}\n"
35+ ".card .lead{margin:0 0 12px;font-size:12.5px;color:var(--text-2)}\n"
36+ ".row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\n"
37+ ".btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:7px 16px;\n"
38+ " font-weight:600;font-size:13px;cursor:pointer;font-family:inherit;\n"
39+ " transition:transform .12s var(--ease),opacity .12s}\n"
40+ ".btn:active{transform:scale(.98)}\n"
41+ ".btn:disabled{opacity:.5;cursor:default}\n"
42+ ".btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}\n"
43+ ".btn.ghost:hover{background:var(--surface-hover);border-color:var(--line-2)}\n"
44+ ".btn.danger{background:transparent;color:var(--red);border:1px solid rgba(255,69,58,.35)}\n"
45+ "a.btn{display:inline-flex;align-items:center;gap:6px;text-decoration:none}\n"
46+ ".kv{display:grid;grid-template-columns:132px minmax(0,1fr);gap:6px 12px;font-size:13px}\n"
47+ ".kv .k{color:var(--text-2);font-size:12px}\n"
48+ ".kv .v{font-family:var(--mono);font-size:12px;word-break:break-all}\n"
49+ ".kv .v.plain{font-family:var(--font);font-size:13px}\n"
50+ ".step{display:none}\n"
51+ ".step.on{display:block}\n"
52+ ".hint{margin:10px 0 0;font-size:12px;color:var(--text-2)}\n"
53+ ".note{font-size:12.5px;margin-top:10px;display:none}\n"
54+ ".note.show{display:block}\n"
55+ ".note.err{color:var(--red)}\n"
56+ ".note.ok{color:var(--green)}\n"
57+ ".authurl{font-family:var(--mono);font-size:11.5px;color:var(--text-2);word-break:break-all;\n"
58+ " background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n"
59+ " padding:10px;margin-top:10px;max-height:120px;overflow:auto}\n"
60+ "textarea{width:100%;margin-top:10px;min-height:74px;resize:vertical;background:var(--input-bg);\n"
61+ " color:var(--text);border:1px solid var(--line);border-radius:10px;padding:10px;\n"
62+ " font-family:var(--mono);font-size:12px;outline:none}\n"
63+ "textarea:focus{border-color:var(--blue)}\n"
64+ ".count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}\n"
65+ ".count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}\n"
66+ ".bar{height:6px;border-radius:999px;background:var(--surface-2);overflow:hidden;margin-top:10px}\n"
67+ ".bar .fill{display:block;height:100%;background:var(--green);border-radius:999px;\n"
68+ " transition:width .3s var(--ease)}\n"
69+ ".bar.warn .fill{background:var(--orange)}\n"
70+ ".bar.err .fill{background:var(--red)}\n"
71+ ".spin{width:12px;height:12px;border-radius:50%;border:2px solid rgba(255,255,255,.35);\n"
72+ " border-top-color:#fff;display:none;animation:sp .7s linear infinite}\n"
73+ ".btn.loading .spin{display:inline-block}\n"
74+ "@keyframes sp{to{transform:rotate(360deg)}}\n"
75+ ".acct{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--line);\n"
76+ " font-size:13px;flex-wrap:wrap}\n"
77+ ".acct:first-of-type{border-top:0}\n"
78+ ".acct .nm{font-family:var(--mono);font-size:12px;flex:1 1 120px;min-width:0;\n"
79+ " overflow:hidden;text-overflow:ellipsis}\n"
80+ ".acct .tag{font-size:11px;color:var(--text-2)}\n"
81+ ".acct .tag.ok{color:var(--green)}\n"
82+ ".acct .tag.warn{color:var(--orange)}\n"
83+ ".empty{padding:10px 0;color:var(--text-2);font-size:12.5px}\n"
84+ ".toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;\n"
85+ " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n"
86+ " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n"
87+ " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n"
88+ " z-index:9;max-width:calc(100vw - 32px)}\n"
89+ ".toast.show{opacity:1;transform:translate(-50%,0)}\n"
90+ "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n"
91+ " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n"
92+ " font-family:inherit}\n"
93+ "@media (max-width:520px){\n"
94+ " #app{padding:12px 12px 32px}\n"
95+ " .kv{grid-template-columns:1fr;gap:2px 0}\n"
96+ " .kv .k{margin-top:8px}\n"
97+ " .card{padding:13px;border-radius:12px}\n"
98+ " .count{font-size:28px}\n"
99+ "}\n"
100+ "</style>\n"
101+ "</head>\n"
102+ "<body>\n"
103+ "<div id=\"app\">\n"
104+ " <div class=\"hd\">\n"
105+ " <div class=\"grow\">\n"
106+ " <h1>Claude Code</h1>\n"
107+ " <div class=\"sub\" id=\"sub\">OAuth PKCE login on this node</div>\n"
108+ " </div>\n"
109+ " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n"
110+ " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n"
111+ " </div>\n"
112+ "\n"
113+ " <div class=\"card\">\n"
114+ " <h2>Session</h2>\n"
115+ " <p class=\"lead\" id=\"sessionLead\">Reading the local Claude Code credentials.</p>\n"
116+ " <div class=\"count\" id=\"count\">-</div>\n"
117+ " <div class=\"bar\" id=\"bar\"><span class=\"fill\" id=\"fill\" style=\"width:0%\"></span></div>\n"
118+ " <div class=\"kv\" id=\"session\" style=\"margin-top:14px\"></div>\n"
119+ " <div class=\"row\" style=\"margin-top:14px\">\n"
120+ " <button class=\"btn ghost\" id=\"btnRefresh\" type=\"button\"><span class=\"spin\"></span>Refresh Token Now</button>\n"
121+ " <button class=\"btn ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n"
122+ " </div>\n"
123+ " <div class=\"note\" id=\"refreshNote\"></div>\n"
124+ " </div>\n"
125+ "\n"
126+ " <div class=\"card\">\n"
127+ " <h2>OAuth login</h2>\n"
128+ " <p class=\"lead\">Sign in with Claude. Nothing leaves this node: the login CLI performs the\n"
129+ " exchange and writes the credential file here.</p>\n"
130+ "\n"
131+ " <div class=\"step on\" id=\"step1\">\n"
132+ " <div class=\"row\">\n"
133+ " <button class=\"btn\" id=\"btnStart\" type=\"button\">Start Claude Login</button>\n"
134+ " <button class=\"btn ghost\" id=\"btnRelogin\" type=\"button\">Re-login (replace)</button>\n"
135+ " </div>\n"
136+ " <p class=\"hint\">This generates a PKCE challenge and an authorization link. No token is\n"
137+ " created until you paste the code back.</p>\n"
138+ " </div>\n"
139+ "\n"
140+ " <div class=\"step\" id=\"step2\">\n"
141+ " <div class=\"row\">\n"
142+ " <a class=\"btn\" id=\"linkOpen\" href=\"#\" target=\"_blank\" rel=\"noopener noreferrer\">Open Claude.ai</a>\n"
143+ " <button class=\"btn ghost\" id=\"btnCopy\" type=\"button\">Copy link</button>\n"
144+ " <button class=\"btn ghost\" id=\"btnCancel\" type=\"button\">Cancel</button>\n"
145+ " </div>\n"
146+ " <div class=\"authurl\" id=\"authUrl\"></div>\n"
147+ " <p class=\"hint\" id=\"flowHint\">After approving, Claude shows an authorization code. Paste the\n"
148+ " whole redirect address or just the <span style=\"font-family:var(--mono)\">code=</span> value below.</p>\n"
149+ " <textarea id=\"codeInput\" spellcheck=\"false\" autocomplete=\"off\"\n"
150+ " placeholder=\"Paste the authorization code or the full redirect URL\"></textarea>\n"
151+ " <div class=\"row\" style=\"margin-top:10px\">\n"
152+ " <button class=\"btn\" id=\"btnFinish\" type=\"button\">Submit Code</button>\n"
153+ " </div>\n"
154+ " <div class=\"note\" id=\"loginNote\"></div>\n"
155+ " </div>\n"
156+ " </div>\n"
157+ "\n"
158+ " <div class=\"card\">\n"
159+ " <h2>Named accounts</h2>\n"
160+ " <p class=\"lead\">Every account file in the local accounts directory.</p>\n"
161+ " <div id=\"accounts\"><div class=\"empty\">No named accounts.</div></div>\n"
162+ " </div>\n"
163+ "</div>\n"
164+ "\n"
165+ "<div class=\"toast\" id=\"toast\"></div>\n"
166+ "\n"
167+ "<script>\n"
168+ "var q=new URLSearchParams(location.search);\n"
169+ "var node=q.get('node')||'';\n"
170+ "var sid=q.get('id')||'';\n"
171+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n"
172+ " localStorage.getItem('bot_active_pwd')||'';\n"
173+ "\n"
174+ "/* Two call routes. Getting this wrong is the most common plugin bug:\n"
175+ " * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)\n"
176+ " * -> call the hub proxy back: /plugins?plugin=plugin_claudecode_login&action=..\n"
177+ " * opened directly on the node\n"
178+ " * -> the plugin itself is the route: /plugin_claudecode_login?action=..\n"
179+ " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n"
180+ "var HUB=q.get('plugin')||'';\n"
181+ "function url(action,extra){\n"
182+ " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_claudecode_login')+\n"
183+ " '?action='+encodeURIComponent(action)+\n"
184+ " (extra?('&'+extra):'')+\n"
185+ " (node?'&node='+encodeURIComponent(node):'')+\n"
186+ " (sid?'&id='+encodeURIComponent(sid):'')+\n"
187+ " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n"
188+ "}\n"
189+ "function hdr(){\n"
190+ " var h={};\n"
191+ " if(pwd)h['X-Bot-Password']=pwd;\n"
192+ " return h;\n"
193+ "}\n"
194+ "function api(action,extra){\n"
195+ " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n"
196+ " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n"
197+ " });\n"
198+ "}\n"
199+ "\n"
200+ "var $=function(id){return document.getElementById(id);};\n"
201+ "function toast(msg){\n"
202+ " var t=$('toast');t.textContent=msg;t.classList.add('show');\n"
203+ " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n"
204+ "}\n"
205+ "function note(el,msg,kind){\n"
206+ " el.textContent=msg||'';\n"
207+ " el.className='note'+(msg?' show '+(kind||''):'');\n"
208+ "}\n"
209+ "function kv(el,rows){\n"
210+ " el.innerHTML='';\n"
211+ " rows.forEach(function(r){\n"
212+ " var a=document.createElement('div');a.className='k';a.textContent=r[0];\n"
213+ " var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');\n"
214+ " b.textContent=r[1];el.appendChild(a);el.appendChild(b);\n"
215+ " });\n"
216+ "}\n"
217+ "function fmtExpiry(sec){\n"
218+ " if(typeof sec!=='number')return '-';\n"
219+ " if(sec<=0)return 'expired';\n"
220+ " if(sec<90)return sec+'s';\n"
221+ " if(sec<5400)return Math.round(sec/60)+' min';\n"
222+ " if(sec<172800)return Math.round(sec/3600)+' h';\n"
223+ " if(sec<63072000)return Math.round(sec/86400)+' d';\n"
224+ " return Math.round(sec/31536000)+' yr';\n"
225+ "}\n"
226+ "function countdown(sec){\n"
227+ " if(typeof sec!=='number'||sec<=0)return ['-',''];\n"
228+ " var d=Math.floor(sec/86400),h=Math.floor((sec%86400)/3600),\n"
229+ " m=Math.floor((sec%3600)/60),s=sec%60,u='second';\n"
230+ " var v,d2;\n"
231+ " if(d>0){v=d;u='day';d2=[h+'h',m+'m'].join(' ');}\n"
232+ " else if(h>0){v=h;u='hour';d2=[m+'m'].join(' ');}\n"
233+ " else if(m>0){v=m;u='minute';d2=[s+'s'].join(' ');}\n"
234+ " else {v=s;d2='';}\n"
235+ " return [v+' <small>'+(v===1?u:u+'s')+(d2?' &middot; '+d2:'')+'</small>',''];\n"
236+ "}\n"
237+ "function setPill(st){\n"
238+ " var p=$('pill'),t=$('pillText');\n"
239+ " if(st.logged_in&&st.expired){p.className='pill warn';t.textContent='Expired';}\n"
240+ " else if(st.logged_in){p.className='pill ok';t.textContent='Logged In';}\n"
241+ " else if(st.pending){p.className='pill warn';t.textContent='Signing in';}\n"
242+ " else {p.className='pill off';t.textContent='Not Connected';}\n"
243+ "}\n"
244+ "/* Full token lifetime is 8 h for a Claude Code session; the bar is a share of\n"
245+ " * the remaining time, so it is a coarse but honest \"how much is left\" read.\n"
246+ " * A countdown of 0 with a refresh token present is the normal steady state. */\n"
247+ "var LIFETIME=8*3600;\n"
248+ "function render(st){\n"
249+ " setPill(st);\n"
250+ " $('sub').textContent=st.account?st.account:'OAuth PKCE login on this node';\n"
251+ "\n"
252+ " if(st.logged_in){\n"
253+ " $('sessionLead').textContent=st.expired\n"
254+ " ? 'The session is present but its access token has expired. Use Refresh Token Now.'\n"
255+ " : 'This node holds a Claude Code session.';\n"
256+ " }else{\n"
257+ " $('sessionLead').textContent='No Claude Code session on this node yet. Start a login below.';\n"
258+ " }\n"
259+ "\n"
260+ " var c=countdown(st.expires_in_sec);\n"
261+ " $('count').innerHTML=st.logged_in?c[0]:'not connected';\n"
262+ " var pct=0;\n"
263+ " if(st.logged_in&&st.expires_in_sec>0){\n"
264+ " pct=Math.max(2,Math.min(100,Math.round(st.expires_in_sec/LIFETIME*100)));\n"
265+ " }\n"
266+ " $('fill').style.width=pct+'%';\n"
267+ " $('bar').className='bar'+(st.expired?' err':(pct<20?' warn':''));\n"
268+ " if(!st.logged_in)$('bar').className='bar';\n"
269+ "\n"
270+ " kv($('session'),[\n"
271+ " ['Account', st.account||'-', true],\n"
272+ " ['Logged in', st.logged_in?'yes':'no', true],\n"
273+ " ['Refresh token', st.has_refresh?'stored':'none', true],\n"
274+ " ['Token expires', st.logged_in?fmtExpiry(st.expires_in_sec):'-', true],\n"
275+ " ['Subscription', st.subscription||'-', true],\n"
276+ " ['Login pending', st.pending?'yes':'no', true],\n"
277+ " ['Login CLI', st.cli_present?'found':'not found', true],\n"
278+ " ['Profile', st.profile_exists?(st.profile||'claude_code'):'not created', true],\n"
279+ " ['Credentials', st.credentials_path||'-']\n"
280+ " ]);\n"
281+ "\n"
282+ " var box=$('accounts');\n"
283+ " box.innerHTML='';\n"
284+ " var list=st.accounts||[];\n"
285+ " if(!list.length){\n"
286+ " var e=document.createElement('div');e.className='empty';\n"
287+ " e.textContent='No named accounts.';box.appendChild(e);\n"
288+ " }else{\n"
289+ " list.forEach(function(a){\n"
290+ " var row=document.createElement('div');row.className='acct';\n"
291+ " var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;\n"
292+ " var tg=document.createElement('div');\n"
293+ " tg.className='tag '+(a.logged_in?(a.expired?'warn':'ok'):'');\n"
294+ " tg.textContent=a.logged_in?(a.expired?'expired':'valid'):'no token';\n"
295+ " row.appendChild(nm);row.appendChild(tg);box.appendChild(row);\n"
296+ " });\n"
297+ " }\n"
298+ "\n"
299+ " if(st.pending){$('step1').classList.remove('on');$('step2').classList.add('on');}\n"
300+ "}\n"
301+ "function load(){\n"
302+ " return api('status').then(function(d){\n"
303+ " if(d&&d.ok)render(d);\n"
304+ " else toast((d&&d.error)||'status failed');\n"
305+ " }).catch(function(e){toast('Status failed: '+e.message);});\n"
306+ "}\n"
307+ "\n"
308+ "var authUrl='';\n"
309+ "function start(force){\n"
310+ " var b=force?$('btnRelogin'):$('btnStart');\n"
311+ " b.disabled=true;b.textContent='Starting...';\n"
312+ " api('start',force?'force=1':'').then(function(d){\n"
313+ " b.disabled=false;b.textContent=force?'Re-login (replace)':'Start Claude Login';\n"
314+ " if(!d||!d.ok){toast((d&&(d.detail||d.error))||'start failed');return;}\n"
315+ " authUrl=d.auth_url||'';\n"
316+ " $('authUrl').textContent=authUrl;\n"
317+ " $('linkOpen').setAttribute('href',authUrl);\n"
318+ " if(d.hint)$('flowHint').textContent=d.hint;\n"
319+ " $('step1').classList.remove('on');\n"
320+ " $('step2').classList.add('on');\n"
321+ " $('codeInput').focus();\n"
322+ " }).catch(function(e){\n"
323+ " b.disabled=false;b.textContent=force?'Re-login (replace)':'Start Claude Login';\n"
324+ " toast('Start failed: '+e.message);\n"
325+ " });\n"
326+ "}\n"
327+ "\n"
328+ "function finish(){\n"
329+ " var raw=$('codeInput').value.trim();\n"
330+ " if(!raw){note($('loginNote'),'Paste the code or the redirect address first.','err');return;}\n"
331+ " var b=$('btnFinish');\n"
332+ " b.disabled=true;b.textContent='Exchanging...';\n"
333+ " note($('loginNote'),'Exchanging the code for a token.');\n"
334+ " api('finish','code='+encodeURIComponent(raw)).then(function(d){\n"
335+ " b.disabled=false;b.textContent='Submit Code';\n"
336+ " if(!d||!d.ok){\n"
337+ " note($('loginNote'),(d&&(d.detail||d.error))||'exchange failed','err');\n"
338+ " return;\n"
339+ " }\n"
340+ " note($('loginNote'),'');\n"
341+ " $('step2').classList.remove('on');\n"
342+ " $('step1').classList.add('on');\n"
343+ " $('codeInput').value='';\n"
344+ " render(d);\n"
345+ " toast('Signed in as '+(d.account||'Claude account'));\n"
346+ " }).catch(function(e){\n"
347+ " b.disabled=false;b.textContent='Submit Code';\n"
348+ " note($('loginNote'),'Exchange failed: '+e.message,'err');\n"
349+ " });\n"
350+ "}\n"
351+ "\n"
352+ "function cancel(){\n"
353+ " api('cancel').then(function(){\n"
354+ " $('step2').classList.remove('on');\n"
355+ " $('step1').classList.add('on');\n"
356+ " $('codeInput').value='';\n"
357+ " note($('loginNote'),'');\n"
358+ " toast('Pending login cancelled');\n"
359+ " load();\n"
360+ " }).catch(function(e){toast('Cancel failed: '+e.message);});\n"
361+ "}\n"
362+ "\n"
363+ "function refreshToken(){\n"
364+ " var b=$('btnRefresh');\n"
365+ " b.disabled=true;b.classList.add('loading');\n"
366+ " b.lastChild.textContent=' Refreshing...';\n"
367+ " note($('refreshNote'),'Asking Claude for a new access token...');\n"
368+ " api('refresh').then(function(d){\n"
369+ " b.disabled=false;b.classList.remove('loading');\n"
370+ " b.lastChild.textContent='Refresh Token Now';\n"
371+ " if(!d||!d.ok){\n"
372+ " note($('refreshNote'),(d&&(d.detail||d.error))||'refresh failed','err');\n"
373+ " return;\n"
374+ " }\n"
375+ " note($('refreshNote'),'Token refreshed. Expires in '+fmtExpiry(d.expires_in_sec)+'.','ok');\n"
376+ " render(d);\n"
377+ " }).catch(function(e){\n"
378+ " b.disabled=false;b.classList.remove('loading');\n"
379+ " b.lastChild.textContent='Refresh Token Now';\n"
380+ " note($('refreshNote'),'Refresh failed: '+e.message,'err');\n"
381+ " });\n"
382+ "}\n"
383+ "\n"
384+ "function copyLink(){\n"
385+ " if(!authUrl)return;\n"
386+ " var done=function(){toast('Link copied');};\n"
387+ " if(navigator.clipboard&&navigator.clipboard.writeText){\n"
388+ " navigator.clipboard.writeText(authUrl).then(done).catch(function(){toast('Copy failed');});\n"
389+ " }else{toast('Copy not available');}\n"
390+ "}\n"
391+ "\n"
392+ "$('btnStart').onclick=function(){start(false);};\n"
393+ "$('btnRelogin').onclick=function(){start(true);};\n"
394+ "$('btnFinish').onclick=finish;\n"
395+ "$('btnCancel').onclick=cancel;\n"
396+ "$('btnRefresh').onclick=refreshToken;\n"
397+ "$('btnReload').onclick=load;\n"
398+ "$('btnCopy').onclick=copyLink;\n"
399+ "$('codeInput').addEventListener('keydown',function(e){\n"
400+ " if(e.key==='Enter'&&(e.metaKey||e.ctrlKey)){e.preventDefault();finish();}\n"
401+ "});\n"
402+ "load();\n"
403+ "</script>\n"
404+ "\002</body></html>\n"
405+ ;
406+
407+#endif /* SX_CCLOGIN_UI_HTML_H */
tests/mock_login.sh+73−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..4dfa151index 0000000..4dfa151
--- /dev/null--- /dev/null
+++ b/tests/mock_login.sh+++ b/tests/mock_login.sh
@@ -0,0 +1,73 @@@@ -0,0 +1,73 @@
1+#!/bin/sh
2+# tests/mock_login.sh - stand-in for scorpiox-claudecode-login machine mode.
3+#
4+# Prints exactly the contract shape the real CLI prints (human progress lines
5+# first, one JSON line last), so the plugin's parsers are exercised against the
6+# production layout rather than an invented one. `--finish` writes a credential
7+# file into $CLAUDE_CREDS_PATH so a test can prove the plugin re-reads state.
8+#
9+# MOCK_FAIL=1 makes --finish fail the way Claude does for a used code.
10+
11+CREDS="${CLAUDE_CREDS_PATH:-/nonexistent}"
12+PEND="${CLAUDE_PENDING_DIR:-/nonexistent}/claudecode-default.json"
13+
14+case "$1" in
15+ --status)
16+ _li=false; _hr=false
17+ if [ -f "$CREDS" ] && grep -q 'refreshToken' "$CREDS" 2>/dev/null; then
18+ _li=true; _hr=true
19+ fi
20+ _exp=0
21+ if [ -f "$CREDS" ]; then
22+ _exp=$(sed -n 's/.*"expiresAt"[[:space:]]*:[[:space:]]*\([0-9]*\).*/\1/p' "$CREDS" | head -1)
23+ [ -z "$_exp" ] && _exp=0
24+ fi
25+ printf 'scorpiox-claudecode-login 1.2.3 (SXLOGIN-MACHINE-V1)\n'
26+ printf '{"ok":true,"provider":"claudecode","name":"Claude Code","flow":"paste_code",'
27+ printf '"named_accounts":true,"protocol":"SXLOGIN-MACHINE-V1","account":null,'
28+ printf '"logged_in":%s,"path":"%s","expires_at":%s,'
29+ printf '"expired":false,"has_refresh":%s,"pending":%s,'
30+ printf '"profile":"claude_code","profile_exists":false}\n' \
31+ "$_li" "$CREDS" "$_exp" "$_hr" \
32+ "$([ -f "$PEND" ] && echo true || echo false)"
33+ ;;
34+ --start)
35+ printf 'scorpiox-claudecode-login 1.2.3\n'
36+ printf 'generating PKCE challenge\n'
37+ mkdir -p "$(dirname "$PEND")" 2>/dev/null
38+ printf '{"code_verifier":"verifier-value","state":"st4te-value","created":1}\n' > "$PEND"
39+ printf '{"ok":true,"provider":"claudecode","flow":"paste_code",'
40+ printf '"auth_url":"https://claude.com/cai/oauth/authorize?code=true&client_id=test&state=st4te-value",'
41+ printf '"expires_in":600,"hint":"Sign in, then paste the code shown on the callback page."}\n'
42+ ;;
43+ --finish)
44+ if [ "$MOCK_FAIL" = "1" ]; then
45+ printf '{"ok":false,"provider":"claudecode","error":"exchange","detail":"code already used"}\n'
46+ exit 1
47+ fi
48+ [ -z "$2" ] && { printf '{"ok":false,"error":"no_code"}\n'; exit 1; }
49+ mkdir -p "$(dirname "$CREDS")" 2>/dev/null
50+ _now=$(date +%s)
51+ _exp=$(( (_now + 28800) * 1000 ))
52+ {
53+ printf '{\n "claudeAiOauth": {\n'
54+ printf ' "accessToken": "sk-ant-oat01-MOCK-ACCESS-TOKEN-MUST-NOT-LEAK",\n'
55+ printf ' "refreshToken": "sk-ant-ort01-MOCK-REFRESH-TOKEN-MUST-NOT-LEAK",\n'
56+ printf ' "expiresAt": %s,\n' "$_exp"
57+ printf ' "scopes": ["user:profile","user:inference"],\n'
58+ printf ' "subscriptionType": "pro"\n }\n}\n'
59+ } > "$CREDS"
60+ rm -f "$PEND"
61+ printf 'Login successful\n'
62+ printf '{"ok":true,"provider":"claudecode","logged_in":true,"path":"%s",'
63+ printf '"expires_in":28800,"profile":"claude_code","profile_created":false}\n' "$CREDS"
64+ ;;
65+ --cancel)
66+ rm -f "$PEND"
67+ printf '{"ok":true,"provider":"claudecode","cancelled":true}\n'
68+ ;;
69+ *)
70+ printf '{"ok":false,"error":"usage"}\n'
71+ exit 1
72+ ;;
73+esac
tests/mock_refresh.sh+38−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..b291d54index 0000000..b291d54
--- /dev/null--- /dev/null
+++ b/tests/mock_refresh.sh+++ b/tests/mock_refresh.sh
@@ -0,0 +1,38 @@@@ -0,0 +1,38 @@
1+#!/bin/sh
2+# tests/mock_refresh.sh - stand-in for scorpiox-claudecode-refreshtoken.
3+#
4+# Mirrors the production program's argument shape (--credentials-file <path>
5+# [--force]) and its behaviour: it rewrites the credentials file in place with a
6+# freshly minted access token and a new expiresAt, and prints human text (which
7+# may include token material) on stdout. The plugin must never forward that.
8+#
9+# MOCK_REFRESH_FAIL=1 exercises the failure path where the file is untouched.
10+
11+CREDS=""
12+FORCE=0
13+while [ $# -gt 0 ]; do
14+ case "$1" in
15+ --credentials-file) shift; CREDS="${1:-}" ;;
16+ --force|-f) FORCE=1 ;;
17+ esac
18+ shift
19+done
20+[ -z "$CREDS" ] && CREDS="${CLAUDE_CREDS_PATH:-/nonexistent}"
21+
22+if [ "$MOCK_REFRESH_FAIL" = "1" ]; then
23+ printf 'error: no refreshToken found in credentials\n' >&2
24+ exit 1
25+fi
26+if [ ! -f "$CREDS" ]; then
27+ printf 'error: cannot read %s\n' "$CREDS" >&2
28+ exit 1
29+fi
30+
31+_now=$(date +%s)
32+_exp=$(( (_now + 28800) * 1000 ))
33+printf 'Claude OAuth Token Auto-Refresh Tool\n\n'
34+printf 'Found Claude config: %s\n' "$CREDS"
35+printf 'Refreshing OAuth token (force=%s)\n' "$FORCE"
36+printf '{"claudeAiOauth":{"accessToken":"sk-ant-oat01-MOCK-REFRESHED-MUST-NOT-LEAK","refreshToken":"sk-ant-ort01-MOCK-REFRESHED","expiresAt":%s,"scopes":["user:profile","user:inference"],"subscriptionType":"pro"}}\n' "$_exp" > "$CREDS"
37+printf 'Token refresh successful\n'
38+exit 0
tests/run.sh+370−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..49bb921index 0000000..49bb921
--- /dev/null--- /dev/null
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -0,0 +1,370 @@@@ -0,0 +1,370 @@
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+
22+set -u
23+
24+ROOT=$(cd "$(dirname "$0")/.." && pwd)
25+cd "$ROOT" || exit 1
26+
27+BIN=./plugin_claudecode_login
28+ID=plugin_claudecode_login
29+PASS=0
30+FAIL=0
31+
32+if [ -t 1 ]; then
33+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
34+else
35+ C_OK=; C_BAD=; C_B=; C_0=
36+fi
37+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
38+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
39+
40+check() { # 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+
46+check_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+
52+check_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+
58+found() { # 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+
65+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
66+
67+# strip CGI headers if present, drop CRs, keep the payload
68+body() {
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+
78+json_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+
87+api() { body "$(QUERY_STRING="$1" $BIN)"; }
88+apiraw() { QUERY_STRING="$1" $BIN; }
89+
90+# ---------------------------------------------------------------- build
91+section "build"
92+if [ ! -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; }
96+fi
97+pass "native binary present"
98+
99+if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
100+ pass "src/ui_html.h is in sync with src/ui.html"
101+else
102+ fail "src/ui_html.h is stale - run tools/gen_ui.py"
103+fi
104+
105+check "ui header is marked generated" \
106+ "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
107+
108+# ---------------------------------------------------------------- --meta
109+section "discovery metadata"
110+META=$(BOT_PASSWORD=testpw $BIN --meta)
111+[ "$META" = '{"name":"claude","desc":"Claude login"}' ] && pass "--meta is exactly the contract string" \
112+ || fail "--meta mismatch: $META"
113+META2=$(SX_PLUGIN_META=1 BOT_PASSWORD=testpw $BIN)
114+check "SX_PLUGIN_META=1 emits the same metadata" '"desc":"Claude login"' "$META2"
115+check "--meta works with an empty env" '"name":"claude"' "$(env -u BOT_PASSWORD $BIN --meta)"
116+json_ok "--meta is valid JSON" "$(env -u BOT_PASSWORD $BIN --meta)" \
117+ 'd["name"]=="claude" and len(d["desc"])<=15'
118+V=$($BIN --version)
119+check "--version names the binary" "$ID" "$V"
120+
121+# ---------------------------------------------------------------- fixtures
122+FIX=$(mktemp -d 2>/dev/null || mktemp -d -t ccfix)
123+trap 'rm -rf "$FIX"' EXIT
124+
125+mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/deep/nested"
126+export CLAUDE_LOGIN_BIN="$ROOT/tests/mock_login.sh"
127+export CLAUDE_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
128+export CLAUDE_PENDING_DIR="$FIX/pend"
129+export CLAUDE_ENV_DIR="$FIX/env"
130+export CLAUDE_ACCOUNTS_DIR="$FIX/acc"
131+export CLAUDE_CREDS_PATH="$FIX/.credentials.json"
132+export BOT_PASSWORD=testpw
133+PWDQ='pwd=testpw'
134+
135+NOW=$(date +%s)
136+FUTURE_MS=$(( (NOW + 7200) * 1000 ))
137+PAST_MS=$(( (NOW - 3600) * 1000 ))
138+
139+mkcreds() { # 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
151+section "node auth gate"
152+RAW=$(apiraw "action=status")
153+check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW"
154+check "401 body is JSON" '"error":"invalid node password"' "$RAW"
155+check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")"
156+check "X-Bot-Password header auth works" '"ok":true' \
157+ "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")"
158+check "Bearer auth works" '"ok":true' \
159+ "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")"
160+check "wrong password still 401s" "Status: 401 Unauthorized" \
161+ "$(QUERY_STRING="action=status&pwd=nope" $BIN)"
162+UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN)
163+check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")"
164+
165+# ---------------------------------------------------------------- status: empty
166+section "status with no credentials"
167+OUT=$(api "action=status&$PWDQ")
168+json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True'
169+json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False'
170+json_ok "empty node is not expired" "$OUT" 'd["expired"] is False'
171+json_ok "empty node carries a zero countdown" "$OUT" 'd["expires_in_sec"]==0'
172+check "empty node reports the credentials path" '"credentials_path"' "$OUT"
173+check "empty node reports the flow" '"flow":"paste_code"' "$OUT"
174+check "empty node reports the protocol marker" 'SXLOGIN-MACHINE-V1' "$OUT"
175+check_not "empty node leaks no token" 'SECRET-ACCESS' "$OUT"
176+OUTF=$(api "format=json&$PWDQ")
177+json_ok "format=json alone means status" "$OUTF" 'd["ok"] is True'
178+
179+# ---------------------------------------------------------------- status: live
180+section "status with a live session"
181+mkcreds "$FIX/.credentials.json" "$FUTURE_MS"
182+printf 'PROVIDER=claude_code\nCLAUDE_CODE_TOKEN_SOURCE=local\nMODEL=claude-opus-4-6\n' > "$FIX/env/claude_code.txt"
183+OUT=$(api "action=status&$PWDQ")
184+json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True'
185+json_ok "live session is not expired" "$OUT" 'd["expired"] is False'
186+json_ok "live session has a refresh token" "$OUT" 'd["has_refresh"] is True'
187+json_ok "live session countdown is positive and near 2h" "$OUT" '7100 < d["expires_in_sec"] <= 7200'
188+json_ok "expiresAt is reported both raw and in seconds" "$OUT" \
189+ 'd["expires_at"]==d["expires_at_sec"]*1000'
190+json_ok "subscription tier is parsed" "$OUT" 'd["subscription"]=="pro"'
191+json_ok "scope names are parsed without JSON punctuation" "$OUT" \
192+ 'd["scopes"]=="user:profile,user:inference,user:sessions:claude_code"'
193+json_ok "profile file is detected" "$OUT" 'd["profile"]=="claude_code" and d["profile_exists"] is True'
194+check_not "status never returns an access token" 'SECRET-ACCESS' "$OUT"
195+check_not "status never returns a refresh token" 'SECRET-REFRESH' "$OUT"
196+check_not "status never returns the key name accessToken" 'accessToken' "$OUT"
197+
198+# expired session
199+mkcreds "$FIX/.credentials.json" "$PAST_MS"
200+OUT=$(api "action=status&$PWDQ")
201+json_ok "expired session is still logged in" "$OUT" 'd["logged_in"] is True'
202+json_ok "expired session is flagged expired" "$OUT" 'd["expired"] is True'
203+json_ok "expired session has a negative countdown" "$OUT" 'd["expires_in_sec"] < 0'
204+
205+# seconds-vs-milliseconds tolerance
206+printf '{"claudeAiOauth":{"accessToken":"a","refreshToken":"b","expiresAt":%s}}\n' "$((NOW + 3600))" \
207+ > "$FIX/.credentials.json"
208+OUT=$(api "action=status&$PWDQ")
209+json_ok "a seconds-based expiresAt is read as seconds" "$OUT" '3500 < d["expires_in_sec"] <= 3600'
210+
211+# malformed / no oauth block
212+printf '{"somethingElse":true}\n' > "$FIX/.credentials.json"
213+OUT=$(api "action=status&$PWDQ")
214+json_ok "a file without claudeAiOauth is not logged in" "$OUT" 'd["logged_in"] is False'
215+printf 'not json at all\n' > "$FIX/.credentials.json"
216+OUT=$(api "action=status&$PWDQ")
217+json_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
220+section "named accounts"
221+mkcreds "$FIX/.credentials.json" "$FUTURE_MS"
222+mkcreds "$FIX/acc/work.json" "$FUTURE_MS"
223+mkcreds "$FIX/acc/old.json" "$PAST_MS"
224+printf '{"claudeAiOauth":{"hasNothing":true}}\n' > "$FIX/acc/notoken.json"
225+OUT=$(api "action=status&$PWDQ")
226+json_ok "named accounts are listed" "$OUT" 'len(d["accounts"])==3'
227+json_ok "a valid account is reported valid" "$OUT" \
228+ '[a for a in d["accounts"] if a["name"]=="work"][0]["expired"] is False'
229+json_ok "a stale account is reported expired" "$OUT" \
230+ '[a for a in d["accounts"] if a["name"]=="old"][0]["expired"] is True'
231+json_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'
233+json_ok "multiple accounts set named_accounts" "$OUT" 'd["named_accounts"] is True'
234+OUT=$(api "action=accounts&$PWDQ")
235+json_ok "action=accounts answers the same shape" "$OUT" 'd["ok"] is True and len(d["accounts"])==3'
236+OUT=$(api "action=status&name=work&$PWDQ")
237+json_ok "status for a named account reads that file" "$OUT" 'd["account"]=="work" and d["logged_in"] is True'
238+check "named account path is reported" "work.json" "$OUT"
239+BADNAME=$(api "action=status&name=../etc&$PWDQ")
240+check "a path-traversal account name is refused" '"error":"bad_name"' "$BADNAME"
241+
242+# ---------------------------------------------------------------- start
243+section "action=start"
244+rm -f "$FIX/pend"/*.json
245+OUT=$(api "action=start&$PWDQ")
246+json_ok "start returns ok" "$OUT" 'd["ok"] is True'
247+json_ok "start returns a paste_code flow" "$OUT" 'd["flow"]=="paste_code"'
248+json_ok "start returns the CLI auth_url" "$OUT" 'd["auth_url"].startswith("https://claude.com/")'
249+json_ok "start carries a PKCE challenge link" "$OUT" '"state=st4te-value" in d["auth_url"]'
250+json_ok "start reports its TTL" "$OUT" 'd["expires_in"]>0'
251+check "start writes the pending file" "" "$(ls "$FIX/pend" | head -1)"
252+OUT=$(api "action=status&$PWDQ")
253+json_ok "status sees the pending flow" "$OUT" 'd["pending"] is True'
254+
255+# ---------------------------------------------------------------- finish
256+section "action=finish"
257+BADCODE=$(api "action=finish&code=abc%27def&$PWDQ")
258+check "a code with a quote is refused locally" '"error":"invalid_code"' "$BADCODE"
259+BADCODE=$(api "action=finish&code=%3Brm%20-rf%20%2F&$PWDQ")
260+check "a shell payload is refused locally" '"error":"invalid_code"' "$BADCODE"
261+NOCODE=$(api "action=finish&$PWDQ")
262+check "finish without a code is a 400" 'missing_code' "$NOCODE"
263+
264+rm -f "$FIX/.credentials.json"
265+api "action=start&$PWDQ" >/dev/null
266+OUT=$(api "action=finish&code=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback%3Fcode%3Dabc123%26state%3Dst4te-value&$PWDQ")
267+json_ok "a pasted redirect URL is accepted (code= extracted)" "$OUT" 'd["ok"] is True'
268+json_ok "finish re-reads state and reports logged in" "$OUT" 'd["logged_in"] is True'
269+json_ok "finish clears the pending flag" "$OUT" 'd["pending"] is False'
270+check_not "finish never echoes the token" 'MUST-NOT-LEAK' "$OUT"
271+
272+api "action=start&$PWDQ" >/dev/null
273+OUT=$(MOCK_FAIL=1 sh -c "QUERY_STRING='action=finish&code=zzz&$PWDQ' $BIN" | tr -d '\r')
274+check "a rejected exchange surfaces the CLI error" '"error":"exchange"' "$OUT"
275+
276+# ---------------------------------------------------------------- cancel
277+section "action=cancel"
278+api "action=start&$PWDQ" >/dev/null
279+OUT=$(api "action=cancel&$PWDQ")
280+json_ok "cancel answers ok" "$OUT" 'd["ok"] is True'
281+json_ok "cancel reports pending false" "$OUT" 'd["pending"] is False'
282+OUT=$(api "action=status&$PWDQ")
283+json_ok "status after cancel shows no pending flow" "$OUT" 'd["pending"] is False'
284+
285+# ---------------------------------------------------------------- refresh
286+section "action=refresh"
287+mkcreds "$FIX/.credentials.json" "$PAST_MS"
288+BEFORE=$(api "action=status&$PWDQ" | python3 -c 'import json,sys;print(json.load(sys.stdin)["expires_at"])' 2>/dev/null)
289+OUT=$(api "action=refresh&$PWDQ")
290+json_ok "refresh answers ok" "$OUT" 'd["ok"] is True'
291+json_ok "refresh reports refreshed:true" "$OUT" 'd["refreshed"] is True'
292+json_ok "refresh moved the expiry forward" "$OUT" 'd["expires_in_sec"]>7000'
293+check_not "refresh never forwards the CLI payload" 'MUST-NOT-LEAK' "$OUT"
294+check_not "refresh never returns an access token key" 'accessToken' "$OUT"
295+
296+OUT=$(MOCK_REFRESH_FAIL=1 sh -c "QUERY_STRING='action=refresh&$PWDQ' $BIN" | tr -d '\r')
297+check "a failed refresh is reported as refresh_failed" '"error":"refresh_failed"' "$OUT"
298+
299+rm -f "$FIX/.credentials.json"
300+OUT=$(api "action=refresh&$PWDQ")
301+check "refresh with no credentials is refused" '"error":"no_credentials"' "$OUT"
302+
303+# ---------------------------------------------------------------- CLI absent
304+section "CLI unavailable"
305+OUT=$(CLAUDE_LOGIN_BIN=/nonexistent/login ${BIN:+env} sh -c "CLAUDE_LOGIN_BIN=/nonexistent/login QUERY_STRING='action=start&$PWDQ' $BIN" | tr -d '\r')
306+check "a missing login CLI is reported as cli_unavailable" 'cli_unavailable' "$OUT"
307+OUT=$(sh -c "CLAUDE_REFRESH_BIN=/nonexistent/refresh CLAUDE_CREDS_PATH='$FIX/nonexist.json' QUERY_STRING='action=refresh&$PWDQ' $BIN" | tr -d '\r')
308+check "refresh with no credentials file says no_credentials" 'no_credentials' "$OUT"
309+
310+# ---------------------------------------------------------------- unknown action
311+section "routing"
312+OUT=$(apiraw "action=bogus&$PWDQ")
313+check "an unknown action is a 404" "Status: 404 Not Found" "$OUT"
314+check "an unknown action names itself" '"error":"unknown_action"' "$OUT"
315+
316+# ---------------------------------------------------------------- HTML page
317+section "HTML UI"
318+PAGE=$(body "$(QUERY_STRING="$PWDQ" $BIN)")
319+check "page is HTML" "Content-Type: text/html" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
320+check "page has a title" "<title>claude</title>" "$PAGE"
321+check "page has the status pill" 'id="pill"' "$PAGE"
322+check "page has the countdown card" 'id="count"' "$PAGE"
323+check "page has the start button" 'id="btnStart"' "$PAGE"
324+check "page has the paste box" 'id="codeInput"' "$PAGE"
325+check "page has the submit button" 'id="btnFinish"' "$PAGE"
326+check "page has the refresh button" 'id="btnRefresh"' "$PAGE"
327+check "page has the cancel button" 'id="btnCancel"' "$PAGE"
328+check "page has the account list" 'id="accounts"' "$PAGE"
329+check "page carries the bot theme prepaint" "bot_theme" "$PAGE"
330+check "page carries the theme handoff listener" "sx-theme" "$PAGE"
331+check "page asks the host for the theme once" "sx-theme-request" "$PAGE"
332+check "page carries the bot token block" "--bg-card" "$PAGE"
333+check "page has a viewport meta" 'name="viewport"' "$PAGE"
334+check "page has a colour-scheme declaration" "color-scheme:dark" "$PAGE"
335+check "page uses the responsive breakpoint" "@media (max-width:520px)" "$PAGE"
336+check_empty "page emits no Content-Length" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r' | grep -i '^Content-Length' || true)"
337+check_not "page loads no CDN script" "<script src=" "$PAGE"
338+check_not "page references no external host" "cdnjs" "$PAGE"
339+check_not "page has no http:// asset" "http://" "$PAGE"
340+check "page CSP forbids remote scripts" "default-src 'none'" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
341+check "page is frameable by the bot" "frame-ancestors *" "$(QUERY_STRING="$PWDQ" $BIN | tr -d '\r')"
342+
343+# ---------------------------------------------------------------- source hygiene
344+section "source hygiene"
345+SRC=src/plugin_claudecode_login.c
346+check_empty "no emoji in the source" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$SRC" || true)"
347+check_empty "no emoji in the page" "$(grep -nP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' src/ui.html || true)"
348+check_empty "the source never writes Content-Length" "$(grep -n 'Content-Length' "$SRC" || true)"
349+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)"
350+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)"
351+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)"
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)).
354+HOSTS="macmin""i|intel-ultra""2|lazar""us"
355+check_empty "no fleet host name" "$(grep -nE "$HOSTS" "$SRC" README.md 2>/dev/null || true)"
356+check_empty "the plugin never appends a token field to a response" "$(grep -nE 'buf_adds?\([^)]*accessToken' "$SRC" || true)"
357+found "accessToken is read into a presence-only buffer" \
358+ 'json_str_field(oauth, end, "accessToken", tok, sizeof(tok))' "$SRC"
359+found "argv is shell-quoted before popen" "shell_quote_into" "$SRC"
360+found "authorization codes are validated before quoting" "code_valid(code)" "$SRC"
361+found "the refresh action discards the CLI payload" "buf_free(&out);" "$SRC"
362+found "the plugin reports refreshed:true on a refresh" 'refreshed\":true' "$SRC"
363+check_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
367+printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
368+printf ' %d passed, %d failed\n' "$PASS" "$FAIL"
369+[ "$FAIL" -eq 0 ] || exit 1
370+exit 0
tools/gen_ui.py+105−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..514bf68index 0000000..514bf68
--- /dev/null--- /dev/null
+++ b/tools/gen_ui.py+++ b/tools/gen_ui.py
@@ -0,0 +1,105 @@@@ -0,0 +1,105 @@
1+#!/usr/bin/env python3
2+"""tools/gen_ui.py - compile src/ui.html into src/ui.html.h.
3+
4+The page lives in one readable file (src/ui.html) so it can be diffed and
5+reviewed like any other source. This script turns it into a single C string
6+constant with two control-character placeholders:
7+
8+ 0x01 -> the bot theme prepaint script + <style> + theme tokens
9+ 0x02 -> the bot theme handoff script (just before </body>)
10+
11+main() splits the constant on those bytes and emits the macros from
12+src/bot_theme_plugin.h in their place, so the theme can never drift out of
13+sync with the rest of the bot.
14+
15+ python3 tools/gen_ui.py # write src/ui.html.h
16+ python3 tools/gen_ui.py --check # exit 1 when the header is stale
17+"""
18+
19+import os
20+import sys
21+
22+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23+SRC = os.path.join(ROOT, "src", "ui.html")
24+OUT = os.path.join(ROOT, "src", "ui_html.h")
25+
26+TOKENS = "<!--TOKENS-->"
27+MARK_TOKENS = "\u0001"
28+MARK_HANDOFF = "\u0002"
29+
30+
31+def c_literal(text):
32+ """Escape text for a C string literal, one line per source line."""
33+ out = []
34+ for line in text.splitlines(True):
35+ piece = []
36+ for ch in line:
37+ if ch == "\\":
38+ piece.append("\\\\")
39+ elif ch == '"':
40+ piece.append('\\"')
41+ elif ch == "\n":
42+ piece.append("\\n")
43+ elif ch == "\r":
44+ piece.append("\\r")
45+ elif ch == "\t":
46+ piece.append("\\t")
47+ elif ch == MARK_TOKENS:
48+ piece.append("\\001")
49+ elif ch == MARK_HANDOFF:
50+ piece.append("\\002")
51+ elif ord(ch) < 0x20:
52+ piece.append("\\%03o" % ord(ch))
53+ else:
54+ piece.append(ch)
55+ out.append(' "%s"\n' % "".join(piece))
56+ return "".join(out)
57+
58+
59+def render():
60+ with open(SRC, "r", encoding="utf-8") as f:
61+ html = f.read()
62+
63+ if TOKENS not in html:
64+ raise SystemExit("src/ui.html has no %s placeholder" % TOKENS)
65+ html = html.replace(TOKENS, MARK_TOKENS)
66+
67+ # Handoff script goes right before the closing body tag.
68+ if "</body>" not in html:
69+ raise SystemExit("src/ui.html has no </body>")
70+ html = html.replace("</body>", MARK_HANDOFF + "</body>", 1)
71+
72+ header = (
73+ "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n"
74+ "#ifndef SX_CCLOGIN_UI_HTML_H\n"
75+ "#define SX_CCLOGIN_UI_HTML_H\n"
76+ "\n"
77+ "static const char *UI_HTML =\n" + c_literal(html) + " ;\n"
78+ "\n"
79+ "#endif /* SX_CCLOGIN_UI_HTML_H */\n"
80+ )
81+ return header
82+
83+
84+def main():
85+ header = render()
86+ check = "--check" in sys.argv[1:]
87+ if check:
88+ try:
89+ with open(OUT, "r", encoding="utf-8") as f:
90+ cur = f.read()
91+ except OSError:
92+ cur = ""
93+ if cur != header:
94+ sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n")
95+ return 1
96+ print("src/ui.html.h is up to date")
97+ return 0
98+ with open(OUT, "w", encoding="utf-8") as f:
99+ f.write(header)
100+ print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header)))
101+ return 0
102+
103+
104+if __name__ == "__main__":
105+ sys.exit(main())
0106