scaffold: source, theme, ui, fixtures
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-12 18:05:04
Commit63d50a81
Changed files
LICENSE+21−0■■■■■
src/bot_theme_plugin.h+129−0■■■■■
src/plugin_codex_login.c+1787−0■■■■■
src/ui.html+452−0■■■■■
src/ui_html.h+460−0■■■■■
tests/mock_login.sh+86−0■■■■■
tests/mock_refresh.sh+61−0■■■■■
tests/run.sh+471−0■■■■■
tools/gen_ui.py+105−0■■■■■
10 files+3572−0
Diff
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.
plugin_codex_login+0−0■
11new file mode 100755
index 0000000..5552936
Binary file changed
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_codex_login.c+1787−0■■■■■
11new file mode 100644
index 0000000..7144eef
--- /dev/null
+++ b/src/plugin_codex_login.c
@@ -0,0 +1,1787 @@
1+/*
2+ * plugin_codex_login - SCORPIOX BOT open-source OpenAI Codex device-code login
3+ * and account 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 in this binary): the Codex device flow is a
11+ * sequence of HTTPS POSTs to the provider, and a public clean-room repository
12+ * must not carry a client secret or a vendored TLS stack. So this plugin does
13+ * not speak TLS at all. It drives the node's own login CLI, exactly the way the
14+ * SCORPIOX CODE login tools are meant to be driven (the machine mode contract:
15+ * --status / --start / --poll / --cancel, one JSON line per call), and it reads
16+ * the credential files that CLI writes:
17+ *
18+ * ~/.codex/auth.json (default account)
19+ * ~/.codex/accounts/<name>.json (named accounts)
20+ * ~/.claude/.login-pending/codex-<name>.json (pending device flow)
21+ * ~/.claude/scorpiox-env/codex.txt (the profile the CLI creates)
22+ *
23+ * auth.json holds no expiry field, so the expiry is read out of the access
24+ * token itself: a JWT carries its lifetime in the "exp" claim of its payload,
25+ * and a JWT payload is base64url text, which this file decodes with its own
26+ * twelve-line decoder. That is what makes the countdown work on a node that
27+ * has SCORPIOX CODE installed and on one that does not.
28+ *
29+ * Everything is overridable for deterministic offline testing:
30+ *
31+ * CODEX_CREDS_PATH the credential json (default ~/.codex/auth.json);
32+ * a relocated file also relocates the account
33+ * directory and the pending directory
34+ * CODEX_ACCOUNTS_DIR directory of <name>.json account files
35+ * CODEX_PENDING_DIR directory holding codex-<name>.json markers
36+ * CODEX_ENV_DIR profile directory (codex.txt)
37+ * CODEX_LOGIN_BIN login CLI (default scorpiox-codex-login)
38+ * CODEX_REFRESH_BIN refresh CLI (default scorpiox-codex-refreshtoken)
39+ * CODEX_ACCOUNT account to operate on (or ?account= per request)
40+ *
41+ * No token is ever printed, logged or returned by this plugin: the API reports
42+ * presence and expiry only, and the refresh action discards whatever its CLI
43+ * prints and proves the result by re-reading the file.
44+ *
45+ * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
46+ * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
47+ * scorpiox-server on the node.
48+ *
49+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
50+ */
51+
52+/* Must come before every include on Windows: MinGW defaults to 0x502
53+ * (Server 2003), which hides the Win7+ APIs and the path helpers. */
54+#if defined(_WIN32) && !defined(_WIN32_WINNT)
55+# define _WIN32_WINNT 0x0601
56+#endif
57+
58+#if !defined(_WIN32)
59+# define _POSIX_C_SOURCE 200809L
60+# define _DEFAULT_SOURCE 1
61+# if defined(__APPLE__)
62+# define _DARWIN_C_SOURCE 1
63+# endif
64+#endif
65+
66+#include <stdio.h>
67+#include <stdlib.h>
68+#include <string.h>
69+#include <ctype.h>
70+#include <errno.h>
71+#include <time.h>
72+#include <stdarg.h>
73+
74+#if defined(_WIN32)
75+# define WIN32_LEAN_AND_MEAN
76+# include <windows.h>
77+# include <direct.h>
78+# include <io.h>
79+#else
80+# include <unistd.h>
81+# include <sys/stat.h>
82+# include <sys/types.h>
83+# include <dirent.h>
84+#endif
85+
86+#include "bot_theme_plugin.h"
87+#include "ui_html.h"
88+
89+#define PLUGIN_SLUG "codex-login"
90+#define PLUGIN_ID "plugin_codex_login"
91+#define PLUGIN_VER "1.0.0"
92+#define PLUGIN_NAME "codex"
93+#define PLUGIN_DESC "Codex login"
94+
95+#define PATH_SZ 1024
96+#define NAME_SZ 96
97+#define CODE_SZ 64
98+#define URL_SZ 1024
99+#define CMD_SZ 4096
100+#define OUT_MAX (256 * 1024)
101+#define FIELD_SZ 512
102+#define MAX_ACCOUNTS 64
103+
104+#define DEFAULT_LOGIN_BIN "scorpiox-codex-login"
105+#define DEFAULT_REFRESH_BIN "scorpiox-codex-refreshtoken"
106+
107+/* The pending device-flow marker the login CLI writes and removes. Its TTL
108+ * matches the CLI's own (900 s); the plugin uses it only to decide whether the
109+ * UI should show a live polling indicator, never to authorise anything. */
110+#define PENDING_TTL_SEC 900
111+
112+#if defined(_WIN32)
113+# define PATH_SEP '\\'
114+#else
115+# define PATH_SEP '/'
116+#endif
117+
118+/* ------------------------------------------------------------------ */
119+/* Growable byte buffer */
120+/* ------------------------------------------------------------------ */
121+
122+typedef struct {
123+ char *p;
124+ size_t n;
125+ size_t cap;
126+} buf_t;
127+
128+static void buf_init(buf_t *b)
129+{
130+ b->p = NULL;
131+ b->n = 0;
132+ b->cap = 0;
133+}
134+
135+static int buf_need(buf_t *b, size_t extra)
136+{
137+ size_t want = b->n + extra + 1;
138+ char *np;
139+
140+ if (want <= b->cap) return 1;
141+ if (b->cap == 0) b->cap = 1024;
142+ while (b->cap < want) {
143+ if (b->cap > (size_t)32 * 1024 * 1024) return 0;
144+ b->cap *= 2;
145+ }
146+ np = (char *)realloc(b->p, b->cap);
147+ if (!np) return 0;
148+ b->p = np;
149+ return 1;
150+}
151+
152+static int buf_addc(buf_t *b, char c)
153+{
154+ if (!buf_need(b, 1)) return 0;
155+ b->p[b->n++] = c;
156+ b->p[b->n] = '\0';
157+ return 1;
158+}
159+
160+static int buf_adds(buf_t *b, const char *s)
161+{
162+ size_t len;
163+
164+ if (!s) return 1;
165+ len = strlen(s);
166+ if (!buf_need(b, len)) return 0;
167+ memcpy(b->p + b->n, s, len);
168+ b->n += len;
169+ b->p[b->n] = '\0';
170+ return 1;
171+}
172+
173+static int buf_addf(buf_t *b, const char *fmt, ...)
174+{
175+ char tmp[2048];
176+ va_list ap;
177+ int n;
178+
179+ va_start(ap, fmt);
180+ n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
181+ va_end(ap);
182+ if (n < 0) return 0;
183+ if ((size_t)n >= sizeof(tmp)) n = (int)sizeof(tmp) - 1;
184+ return buf_adds(b, tmp);
185+}
186+
187+/* Append s as a JSON string literal (escapes control characters). */
188+static int buf_json(buf_t *b, const char *s)
189+{
190+ if (!buf_addc(b, '"')) return 0;
191+ for (; s && *s; s++) {
192+ unsigned char c = (unsigned char)*s;
193+ switch (c) {
194+ case '"': if (!buf_adds(b, "\\\"")) return 0; continue;
195+ case '\\': if (!buf_adds(b, "\\\\")) return 0; continue;
196+ case '\n': if (!buf_adds(b, "\\n")) return 0; continue;
197+ case '\r': if (!buf_adds(b, "\\r")) return 0; continue;
198+ case '\t': if (!buf_adds(b, "\\t")) return 0; continue;
199+ default: break;
200+ }
201+ if (c < 0x20) { if (!buf_addf(b, "\\u%04x", c)) return 0; }
202+ else if (!buf_addc(b, (char)c)) return 0;
203+ }
204+ return buf_addc(b, '"');
205+}
206+
207+static const char *buf_str(buf_t *b)
208+{
209+ if (!b->p) return "";
210+ return b->p;
211+}
212+
213+static void buf_free(buf_t *b)
214+{
215+ free(b->p);
216+ b->p = NULL;
217+ b->n = 0;
218+ b->cap = 0;
219+}
220+
221+/* ------------------------------------------------------------------ */
222+/* Query string */
223+/* ------------------------------------------------------------------ */
224+
225+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
226+{
227+ size_t klen;
228+ const char *p;
229+
230+ if (!out || outsz == 0) return 0;
231+ out[0] = '\0';
232+ if (!qs || !key) return 0;
233+ klen = strlen(key);
234+ p = qs;
235+ while (*p) {
236+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
237+ size_t i = 0;
238+ p += klen + 1;
239+ while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++;
240+ out[i] = '\0';
241+ return 1;
242+ }
243+ p = strchr(p, '&');
244+ if (!p) break;
245+ p++;
246+ }
247+ return 0;
248+}
249+
250+static int query_has(const char *qs, const char *key)
251+{
252+ size_t klen = strlen(key);
253+ const char *p = qs;
254+
255+ while (p && *p) {
256+ if (strncmp(p, key, klen) == 0 &&
257+ (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&'))
258+ return 1;
259+ p = strchr(p, '&');
260+ if (!p) break;
261+ p++;
262+ }
263+ return 0;
264+}
265+
266+/* ------------------------------------------------------------------ */
267+/* Node auth (X-Bot-Password / Bearer / ?pwd=) */
268+/* ------------------------------------------------------------------ */
269+
270+static void require_node_auth(void)
271+{
272+ const char *np = getenv("BOT_PASSWORD");
273+ const char *xp;
274+ const char *auth;
275+ char qpwd[256] = {0};
276+
277+ if (!np || !*np) return;
278+
279+ xp = getenv("HTTP_X_BOT_PASSWORD");
280+ if (xp && strcmp(xp, np) == 0) return;
281+
282+ auth = getenv("HTTP_AUTHORIZATION");
283+ if (auth) {
284+ while (*auth == ' ') auth++;
285+ if (strncasecmp(auth, "Bearer ", 7) == 0) {
286+ auth += 7;
287+ while (*auth == ' ') auth++;
288+ if (strcmp(auth, np) == 0) return;
289+ }
290+ }
291+
292+ if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) &&
293+ strcmp(qpwd, np) == 0) return;
294+
295+ fputs("Status: 401 Unauthorized\r\n"
296+ "Content-Type: application/json; charset=utf-8\r\n"
297+ "Cache-Control: no-store\r\n\r\n"
298+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
299+ exit(0);
300+}
301+
302+/* ------------------------------------------------------------------ */
303+/* Filesystem helpers */
304+/* ------------------------------------------------------------------ */
305+
306+static const char *home_dir(void)
307+{
308+#if defined(_WIN32)
309+ static char home[512];
310+ if (GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)) > 0) return home;
311+ if (GetEnvironmentVariableA("HOME", home, sizeof(home)) > 0) return home;
312+ {
313+ char tmp[512];
314+ if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) {
315+ snprintf(home, sizeof(home), "%s", tmp);
316+ return home;
317+ }
318+ }
319+ return NULL;
320+#else
321+ const char *h = getenv("HOME");
322+ return (h && *h) ? h : NULL;
323+#endif
324+}
325+
326+/* Copy the directory part of a path (including the trailing separator). */
327+static void dir_of(const char *path, char *out, size_t n)
328+{
329+ char base[PATH_SZ];
330+ char *slash;
331+
332+ if (!path) { if (n) out[0] = '\0'; return; }
333+ snprintf(base, sizeof(base), "%s", path);
334+ slash = strrchr(base, PATH_SEP);
335+#if defined(_WIN32)
336+ if (!slash) slash = strrchr(base, '/');
337+#endif
338+ if (slash) *(slash + 1) = '\0';
339+ else base[0] = '\0';
340+ snprintf(out, n, "%s", base);
341+}
342+
343+/* The .codex directory. A relocated credentials file implies a relocated tree:
344+ * the same CLI writes auth.json, accounts/ and the profile into one place, so
345+ * reading one from the override and the rest from $HOME reports an empty state
346+ * for a session that has one. */
347+static void codex_dir(char *out, size_t n)
348+{
349+ const char *env = getenv("CODEX_CREDS_PATH");
350+ const char *home = home_dir();
351+
352+ if (env && *env) {
353+ dir_of(env, out, n);
354+ if (out[0]) return;
355+ }
356+ if (home && *home) { snprintf(out, n, "%s%c.codex%c", home, PATH_SEP, PATH_SEP); return; }
357+ snprintf(out, n, ".codex%c", PATH_SEP);
358+}
359+
360+static void creds_path(char *out, size_t n)
361+{
362+ const char *env = getenv("CODEX_CREDS_PATH");
363+
364+ if (env && *env) { snprintf(out, n, "%s", env); return; }
365+ {
366+ char d[PATH_SZ];
367+ codex_dir(d, sizeof(d));
368+ snprintf(out, n, "%sauth.json", d);
369+ }
370+}
371+
372+static void accounts_dir(char *out, size_t n)
373+{
374+ const char *env = getenv("CODEX_ACCOUNTS_DIR");
375+
376+ if (env && *env) { snprintf(out, n, "%s", env); return; }
377+ {
378+ char d[PATH_SZ];
379+ codex_dir(d, sizeof(d));
380+ snprintf(out, n, "%saccounts", d);
381+ }
382+}
383+
384+/* The pending device-flow markers live under ~/.claude/.login-pending exactly
385+ * like every other SCORPIOX CODE login tool, so a relocated .codex tree does
386+ * NOT move them: they belong to the bot's own contract, not to the provider. */
387+static void pending_dir(char *out, size_t n)
388+{
389+ const char *env = getenv("CODEX_PENDING_DIR");
390+ const char *home = home_dir();
391+
392+ if (env && *env) { snprintf(out, n, "%s", env); return; }
393+ if (!home) { snprintf(out, n, ".login-pending%c", PATH_SEP); return; }
394+ snprintf(out, n, "%s%c.claude%c.login-pending", home, PATH_SEP, PATH_SEP);
395+}
396+
397+/* SCORPIOX CODE profiles for every provider share one directory, so the
398+ * codex profile is not under .codex: it is ~/.claude/scorpiox-env/codex.txt,
399+ * exactly where the login CLI writes it. */
400+static void env_dir(char *out, size_t n)
401+{
402+ const char *env = getenv("CODEX_ENV_DIR");
403+ const char *home = home_dir();
404+
405+ if (env && *env) { snprintf(out, n, "%s", env); return; }
406+ if (!home) { snprintf(out, n, "scorpiox-env%c", PATH_SEP); return; }
407+ snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP);
408+}
409+
410+static void pending_path(const char *name, char *out, size_t n)
411+{
412+ char d[PATH_SZ];
413+
414+ pending_dir(d, sizeof(d));
415+ snprintf(out, n, "%s%ccodex-%s.json", d, PATH_SEP, (name && *name) ? name : "default");
416+}
417+
418+static void profile_path(char *out, size_t n)
419+{
420+ char d[PATH_SZ];
421+
422+ env_dir(d, sizeof(d));
423+ snprintf(out, n, "%s%ccodex.txt", d, PATH_SEP);
424+}
425+
426+static void account_path(const char *name, char *out, size_t n)
427+{
428+ char d[PATH_SZ];
429+
430+ accounts_dir(d, sizeof(d));
431+ snprintf(out, n, "%s%c%s.json", d, PATH_SEP, name);
432+}
433+
434+/* Resolve the account this request operates on: ?account= wins, then
435+ * CODEX_ACCOUNT, then the default file. */
436+static void resolve_account(const char *qs, char *out, size_t outsz)
437+{
438+ const char *env;
439+
440+ out[0] = '\0';
441+ if (qs && get_query_val(qs, "account", out, outsz) && out[0]) return;
442+ env = getenv("CODEX_ACCOUNT");
443+ if (env && *env) { snprintf(out, outsz, "%s", env); return; }
444+}
445+
446+static int name_valid(const char *n)
447+{
448+ const char *p;
449+
450+ if (!n || !*n || strlen(n) > 64) return 0;
451+ if (n[0] == '.') return 0;
452+ for (p = n; *p; p++) {
453+ unsigned char c = (unsigned char)*p;
454+ if (!isalnum(c) && c != '-' && c != '_' && c != '.') return 0;
455+ }
456+ return 1;
457+}
458+
459+/* Where the credentials for the resolved account actually live. */
460+static void active_creds_path(const char *account, char *out, size_t n)
461+{
462+ if (account && *account) account_path(account, out, n);
463+ else creds_path(out, n);
464+}
465+
466+static const char *login_bin(void)
467+{
468+ const char *e = getenv("CODEX_LOGIN_BIN");
469+ return (e && *e) ? e : DEFAULT_LOGIN_BIN;
470+}
471+
472+static const char *refresh_bin(void)
473+{
474+ const char *e = getenv("CODEX_REFRESH_BIN");
475+ return (e && *e) ? e : DEFAULT_REFRESH_BIN;
476+}
477+
478+static int file_exists(const char *p)
479+{
480+#if defined(_WIN32)
481+ DWORD a = GetFileAttributesA(p);
482+ return p && *p && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
483+#else
484+ struct stat st;
485+ return p && *p && stat(p, &st) == 0 && S_ISREG(st.st_mode);
486+#endif
487+}
488+
489+/* Whole-file read; NULL on any failure. Caller frees. */
490+static char *read_file(const char *path)
491+{
492+ FILE *f;
493+ long sz;
494+ char *buf;
495+
496+ if (!path || !*path) return NULL;
497+ f = fopen(path, "rb");
498+ if (!f) return NULL;
499+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
500+ sz = ftell(f);
501+ if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; }
502+ if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
503+ buf = (char *)malloc((size_t)sz + 1);
504+ if (!buf) { fclose(f); return NULL; }
505+ if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
506+ free(buf);
507+ fclose(f);
508+ return NULL;
509+ }
510+ buf[sz] = '\0';
511+ fclose(f);
512+ return buf;
513+}
514+
515+static void trim_tail(char *s)
516+{
517+ size_t n;
518+
519+ if (!s) return;
520+ n = strlen(s);
521+ while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' ||
522+ s[n - 1] == ' ' || s[n - 1] == '\t'))
523+ s[--n] = '\0';
524+}
525+
526+/* ------------------------------------------------------------------ */
527+/* Minimal JSON field readers */
528+/* ------------------------------------------------------------------ */
529+
530+/* Copy a JSON string value that starts at *pp (which points at the opening
531+ * quote). Advances *pp past the closing quote. */
532+static int json_read_string_at(const char **pp, char *out, size_t outsz)
533+{
534+ const char *p = *pp;
535+ size_t i = 0;
536+
537+ if (!p || *p != '"') return 0;
538+ p++;
539+ while (*p && *p != '"') {
540+ char c = *p;
541+ if (c == '\\' && p[1]) {
542+ p++;
543+ switch (*p) {
544+ case 'n': c = '\n'; break;
545+ case 'r': c = '\r'; break;
546+ case 't': c = '\t'; break;
547+ case 'b': c = '\b'; break;
548+ case 'f': c = '\f'; break;
549+ case 'u': {
550+ unsigned int v = 0;
551+ int k;
552+ p++;
553+ for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++)
554+ v = v * 16 + (unsigned int)(isdigit((unsigned char)*p)
555+ ? *p - '0'
556+ : tolower((unsigned char)*p) - 'a' + 10);
557+ if (i + 1 < outsz) out[i++] = (char)(v & 0xff);
558+ continue;
559+ }
560+ default: c = *p; break;
561+ }
562+ p++;
563+ } else {
564+ p++;
565+ }
566+ if (i + 1 < outsz) out[i++] = c;
567+ }
568+ if (*p == '"') p++;
569+ if (outsz) out[i < outsz ? i : outsz - 1] = '\0';
570+ *pp = p;
571+ return 1;
572+}
573+
574+/* Find "key":<value> inside the slice [obj, end) and return the value pointer.
575+ * Only top-level keys of that slice are considered: a nested object or array
576+ * is skipped as a whole. A caller almost always hands us the whole document,
577+ * i.e. a pointer at the opening brace; that brace is skipped here so no call
578+ * site needs a "+1" that is easy to forget and silent when it is missing. */
579+static const char *json_find_key(const char *obj, const char *end, const char *key)
580+{
581+ size_t klen = strlen(key);
582+ const char *p = obj;
583+ int depth = 0;
584+
585+ if (!obj || !end || !key) return NULL;
586+ while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++;
587+ if (p < end && *p == '{') p++;
588+
589+ while (p && p < end) {
590+ if (*p == '"') {
591+ char name[128];
592+ json_read_string_at(&p, name, sizeof(name));
593+ if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) {
594+ const char *q = p;
595+ while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
596+ if (q < end && *q == ':') {
597+ q++;
598+ while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
599+ return (q < end) ? q : NULL;
600+ }
601+ }
602+ continue;
603+ }
604+ if (*p == '{' || *p == '[') depth++;
605+ else if (*p == '}' || *p == ']') depth--;
606+ p++;
607+ }
608+ return NULL;
609+}
610+
611+/* Bound the object that starts at *v (a value pointer from json_find_key).
612+ * Returns 0 when the value is not an object. Strings inside the object are
613+ * skipped with their escapes so a brace written inside a token cannot close
614+ * the slice early. */
615+static int json_obj_slice(const char *v, const char *end, const char **out,
616+ const char **outend)
617+{
618+ const char *p;
619+ int depth = 0;
620+
621+ if (!v || *v != '{') return 0;
622+ for (p = v; p < end; p++) {
623+ if (*p == '"') {
624+ p++;
625+ while (p < end && *p != '"') {
626+ if (*p == '\\' && p + 1 < end) p++;
627+ p++;
628+ }
629+ continue;
630+ }
631+ if (*p == '{') {
632+ depth++;
633+ if (depth == 1) *out = p;
634+ } else if (*p == '}') {
635+ depth--;
636+ if (depth == 0) { *outend = p + 1; return 1; }
637+ }
638+ }
639+ return 0;
640+}
641+
642+/* Returns 0 and leaves *out untouched when the key is absent or null: several
643+ * callers pass a field of a longer-lived struct, and clearing it on a miss
644+ * silently erases a value that was already correct. */
645+static int json_str_field(const char *obj, const char *end, const char *key,
646+ char *out, size_t outsz)
647+{
648+ const char *v;
649+
650+ if (!out || outsz == 0) return 0;
651+ v = json_find_key(obj, end, key);
652+ if (!v || *v == 'n') return 0;
653+ out[0] = '\0';
654+ if (*v == '"') return json_read_string_at(&v, out, outsz);
655+ {
656+ size_t i = 0;
657+ while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz)
658+ out[i++] = *v++;
659+ out[i] = '\0';
660+ trim_tail(out);
661+ return out[0] ? 1 : 0;
662+ }
663+}
664+
665+static int json_bool_field(const char *obj, const char *end, const char *key, int dflt)
666+{
667+ const char *v = json_find_key(obj, end, key);
668+
669+ if (!v) return dflt;
670+ if (strncmp(v, "true", 4) == 0) return 1;
671+ if (strncmp(v, "false", 5) == 0) return 0;
672+ if (*v == '"')
673+ return (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0);
674+ if (*v == '1') return 1;
675+ return 0;
676+}
677+
678+static long long json_num_field(const char *obj, const char *end, const char *key)
679+{
680+ const char *v = json_find_key(obj, end, key);
681+ long long vll = 0;
682+ int neg = 0;
683+
684+ if (!v) return 0;
685+ if (*v == '"') v++;
686+ if (*v == '-') { neg = 1; v++; }
687+ while (v < end && isdigit((unsigned char)*v)) vll = vll * 10 + (*v++ - '0');
688+ return neg ? -vll : vll;
689+}
690+
691+/* True when the object holds a non-empty string under key. Used for token
692+ * presence without ever copying the token itself into a wider buffer. */
693+static int json_str_present(const char *obj, const char *end, const char *key)
694+{
695+ const char *v = json_find_key(obj, end, key);
696+ const char *q;
697+
698+ if (!v || *v != '"') return 0;
699+ q = v + 1;
700+ while (q < end && *q != '"') {
701+ if (*q == '\\' && q + 1 < end) { q += 2; continue; }
702+ return 1; /* at least one real character */
703+ }
704+ return 0; /* "" - present but empty */
705+}
706+
707+/* ------------------------------------------------------------------ */
708+/* Reading a JWT lifetime */
709+/* ------------------------------------------------------------------ */
710+
711+/* auth.json carries no expiry field, so the countdown has to come from the
712+ * access token itself: a JWT is header.payload.signature, the payload is
713+ * base64url, and the payload JSON has an "exp" claim in seconds. Decoding
714+ * base64url is twelve lines and needs no library, which is what makes the
715+ * expiry readable on a node that has no SCORPIOX CODE installed. */
716+static int b64url_val(char c)
717+{
718+ if (c >= 'A' && c <= 'Z') return c - 'A';
719+ if (c >= 'a' && c <= 'z') return c - 'a' + 26;
720+ if (c >= '0' && c <= '9') return c - '0' + 52;
721+ if (c == '-' || c == '+') return 62;
722+ if (c == '_' || c == '/') return 63;
723+ return -1;
724+}
725+
726+/* Decode a base64url run of in_len characters into out (caller-sized). Returns
727+ * the number of bytes written, or -1 on malformed input. */
728+static int b64url_decode(const char *in, size_t in_len, char *out, size_t outsz)
729+{
730+ unsigned long acc = 0;
731+ int nbits = 0;
732+ size_t i = 0;
733+ size_t o = 0;
734+
735+ for (; i < in_len; i++) {
736+ int v;
737+ if (in[i] == '=' || in[i] == '\n' || in[i] == '\r' || in[i] == ' ') continue;
738+ v = b64url_val(in[i]);
739+ if (v < 0) return -1;
740+ acc = (acc << 6) | (unsigned long)v;
741+ nbits += 6;
742+ if (nbits >= 8) {
743+ char b = (char)((acc >> (nbits - 8)) & 0xff);
744+ nbits -= 8;
745+ if (o >= outsz) return -1;
746+ out[o++] = b;
747+ }
748+ }
749+ return (int)o;
750+}
751+
752+/* Pull the "exp" claim (unix seconds) out of a JWT. Returns 0 when the token
753+ * is not a decodable JWT, which the caller treats as "expiry unknown". */
754+static long long jwt_exp_seconds(const char *jwt)
755+{
756+ const char *dot1, *dot2, *payload;
757+ size_t plen;
758+ long long exp = 0;
759+ char *dec;
760+ size_t cap;
761+
762+ if (!jwt || !*jwt) return 0;
763+ dot1 = strchr(jwt, '.');
764+ if (!dot1) return 0;
765+ payload = dot1 + 1;
766+ dot2 = strchr(payload, '.');
767+ if (!dot2) return 0;
768+ plen = (size_t)(dot2 - payload);
769+ if (plen == 0 || plen > 8192) return 0;
770+
771+ cap = (plen / 4 + 1) * 3 + 1;
772+ dec = (char *)malloc(cap);
773+ if (!dec) return 0;
774+ {
775+ int n = b64url_decode(payload, plen, dec, cap - 1);
776+ if (n <= 0) { free(dec); return 0; }
777+ dec[n] = '\0';
778+ exp = json_num_field(dec, dec + n, "exp");
779+ }
780+ free(dec);
781+ return exp;
782+}
783+
784+/* ------------------------------------------------------------------ */
785+/* Running the node's login CLI */
786+/* ------------------------------------------------------------------ */
787+
788+/* Quote one argv element for the shell popen() uses. POSIX: single quotes with
789+ * the standard close-escape-reopen trick. Windows: double quotes, which is
790+ * what cmd.exe accepts. */
791+static void shell_quote_into(const char *in, char *out, size_t outsz)
792+{
793+ size_t o = 0;
794+ const char *p;
795+
796+ if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
797+#if defined(_WIN32)
798+ out[o++] = '"';
799+ for (p = in; p && *p; p++) {
800+ if (*p == '"') {
801+ if (o + 3 >= outsz) break;
802+ out[o++] = '\\';
803+ out[o++] = '"';
804+ } else {
805+ if (o + 2 >= outsz) break;
806+ out[o++] = *p;
807+ }
808+ }
809+ out[o++] = '"';
810+ out[o] = '\0';
811+#else
812+ out[o++] = '\'';
813+ for (p = in; p && *p; p++) {
814+ if (*p == '\'') {
815+ if (o + 5 >= outsz) break;
816+ memcpy(out + o, "'\\''", 4);
817+ o += 4;
818+ } else {
819+ if (o + 2 >= outsz) break;
820+ out[o++] = *p;
821+ }
822+ }
823+ out[o++] = '\'';
824+ out[o] = '\0';
825+#endif
826+}
827+
828+/* Run `<bin> <args>` and capture stdout. args may be NULL or a pre-built shell
829+ * fragment. Returns 1 when the process ran,
830+ * 0 when popen() itself failed,
831+ * -1 when the binary is not on this node ("command not found").
832+ *
833+ * pclose() hands back a WAIT STATUS, not an exit code: a missing command
834+ * arrives as 32512 (127 << 8). Treating that as the tool's own failure would
835+ * report "refresh failed" for a node that simply has no SCORPIOX CODE. */
836+static int run_capture(const char *bin, const char *args, buf_t *out)
837+{
838+ char cmd[CMD_SZ];
839+ char qbin[FIELD_SZ];
840+ FILE *f;
841+ char line[2048];
842+ size_t total = 0;
843+ int rc;
844+
845+ if (!bin || !*bin) return 0;
846+ shell_quote_into(bin, qbin, sizeof(qbin));
847+#if defined(_WIN32)
848+ if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>NUL", qbin, args);
849+ else snprintf(cmd, sizeof(cmd), "%s 2>NUL", qbin);
850+#else
851+ if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args);
852+ else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin);
853+#endif
854+
855+ f = popen(cmd, "r");
856+ if (!f) return 0;
857+ while (fgets(line, sizeof(line), f)) {
858+ total += strlen(line);
859+ if (total > OUT_MAX) break;
860+ buf_adds(out, line);
861+ }
862+ rc = pclose(f);
863+
864+ if (out->p) {
865+ size_t n = out->n;
866+ while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0';
867+ out->n = n;
868+ }
869+ if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1;
870+ return 1;
871+}
872+
873+/* The CLIs print human progress before the final JSON line, so take the LAST
874+ * line that starts with '{'. */
875+static const char *last_json_line(buf_t *b)
876+{
877+ size_t i;
878+ const char *last = NULL;
879+
880+ if (!b || !b->p) return NULL;
881+ for (i = 0; i < b->n; i++) {
882+ int at_line_start = (i == 0) || b->p[i - 1] == '\n';
883+ if (at_line_start && b->p[i] == '{') last = b->p + i;
884+ }
885+ return last;
886+}
887+
888+/* ------------------------------------------------------------------ */
889+/* Status assembly */
890+/* ------------------------------------------------------------------ */
891+
892+/* An ISO-8601 UTC stamp ("2026-06-12T03:46:19.123456Z") to unix seconds. The
893+ * fields are read positionally because the format is fixed; a leap-safe
894+ * conversion is not needed, only a monotone reference for "last refreshed". */
895+static long long iso8601_to_sec(const char *s)
896+{
897+ int y = 0, mo = 0, d = 0, h = 0, mi = 0, se = 0;
898+ static const int cum[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
899+ long long days;
900+ int i;
901+
902+ if (!s || strlen(s) < 19) return 0;
903+ for (i = 0; i < 4 && isdigit((unsigned char)s[i]); i++) y = y * 10 + (s[i] - '0');
904+ for (i = 5; i < 7 && isdigit((unsigned char)s[i]); i++) mo = mo * 10 + (s[i] - '0');
905+ for (i = 8; i < 10 && isdigit((unsigned char)s[i]); i++) d = d * 10 + (s[i] - '0');
906+ for (i = 11; i < 13 && isdigit((unsigned char)s[i]); i++) h = h * 10 + (s[i] - '0');
907+ for (i = 14; i < 16 && isdigit((unsigned char)s[i]); i++) mi = mi * 10 + (s[i] - '0');
908+ for (i = 17; i < 19 && isdigit((unsigned char)s[i]); i++) se = se * 10 + (s[i] - '0');
909+ if (y < 1970 || mo < 1 || mo > 12 || d < 1 || d > 31) return 0;
910+ days = (long long)(y - 1970) * 365 + (y - 1969) / 4 + cum[mo - 1] + d - 1;
911+ if (mo > 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)) days++;
912+ return days * 86400LL + h * 3600LL + mi * 60LL + se;
913+}
914+
915+typedef struct {
916+ char name[NAME_SZ];
917+ int present;
918+ int logged_in;
919+ int has_refresh;
920+ int expired;
921+ long long expires_at; /* unix seconds, 0 = unknown */
922+ long long expires_in_sec; /* negative when expired, 0 when unknown */
923+} account_t;
924+
925+typedef struct {
926+ int logged_in;
927+ int has_refresh;
928+ int pending;
929+ int expired;
930+ int cli_present;
931+ int cli_ran;
932+ int profile_exists;
933+ int api_key_present;
934+ char account[NAME_SZ];
935+ char path[PATH_SZ];
936+ char profile[NAME_SZ];
937+ char profile_file[PATH_SZ];
938+ char account_id[NAME_SZ];
939+ char cli_error[FIELD_SZ];
940+ long long expires_at; /* unix seconds, 0 = unknown */
941+ long long expires_in_sec; /* long long on purpose: a 32-bit int
942+ * overflows past 2038 and turns a live
943+ * session into "expired 60 years ago" */
944+ long long last_refresh; /* unix seconds, 0 = unknown */
945+ long long pending_age; /* seconds since the marker was written, -1 */
946+ account_t accounts[MAX_ACCOUNTS];
947+ int account_count;
948+} status_t;
949+
950+/* Parse one credentials file (the default file and every named account file
951+ * share this shape):
952+ *
953+ * {"OPENAI_API_KEY": null,
954+ * "tokens": {"id_token":"...","access_token":"...","refresh_token":"...",
955+ * "account_id":"..."},
956+ * "last_refresh":"2026-06-12T03:46:19.123456Z"}
957+ *
958+ * The tokens live inside "tokens", so the slice handed to the readers is the
959+ * tokens object, not the document: matching at document level would find
960+ * nothing and report a live session as "not connected". */
961+static void scan_creds(const char *json, status_t *st, account_t *acc)
962+{
963+ const char *tok, *tokend;
964+ const char *docend;
965+ char acctbuf[NAME_SZ] = {0};
966+ char access[4096];
967+ long long exp = 0;
968+
969+ if (!json) return;
970+ docend = json + strlen(json);
971+
972+ tok = json_find_key(json, docend, "tokens");
973+ if (!tok || !json_obj_slice(tok, docend, &tok, &tokend)) {
974+ /* A flat file (some fixtures put the tokens at the top level) is still
975+ * a session if an access token is there, so fall back to the document. */
976+ tok = json;
977+ tokend = docend;
978+ }
979+
980+ if (json_str_field(tok, tokend, "access_token", access, sizeof(access))) {
981+ exp = jwt_exp_seconds(access);
982+ st->logged_in = 1;
983+ } else {
984+ /* Presence without copying: a token can be several kilobytes and the
985+ * account list keeps one entry per file, so a 4 KB scratch buffer per
986+ * file would be wasteful. */
987+ if (json_str_present(tok, tokend, "access_token")) st->logged_in = 1;
988+ }
989+ if (json_str_present(tok, tokend, "refresh_token")) {
990+ st->has_refresh = 1;
991+ if (acc) acc->has_refresh = 1;
992+ }
993+ if (json_str_field(tok, tokend, "account_id", acctbuf, sizeof(acctbuf)) && acctbuf[0])
994+ snprintf(st->account_id, sizeof(st->account_id), "%s", acctbuf);
995+ if (json_str_present(tok, tokend, "OPENAI_API_KEY") ||
996+ json_str_present(json, docend, "OPENAI_API_KEY"))
997+ st->api_key_present = 1;
998+
999+ if (exp > 0) st->expires_at = exp;
1000+ {
1001+ char iso[64] = {0};
1002+ if (json_str_field(json, docend, "last_refresh", iso, sizeof(iso))) {
1003+ long long lr = iso8601_to_sec(iso);
1004+ if (lr > 0) st->last_refresh = lr;
1005+ }
1006+ }
1007+ if (acc) {
1008+ acc->logged_in = st->logged_in;
1009+ acc->expires_at = st->expires_at;
1010+ }
1011+}
1012+
1013+/* Read the profile file the login CLI creates (--create-profile). */
1014+static void scan_profile(status_t *st)
1015+{
1016+ char *text;
1017+
1018+ profile_path(st->profile_file, sizeof(st->profile_file));
1019+ st->profile_exists = file_exists(st->profile_file);
1020+ if (!st->profile_exists) return;
1021+ snprintf(st->profile, sizeof(st->profile), "codex");
1022+
1023+ text = read_file(st->profile_file);
1024+ if (!text) return;
1025+ {
1026+ const char *p = text;
1027+ while (*p) {
1028+ if (strncmp(p, "CODEX_ACCOUNT=", 12) == 0) {
1029+ size_t i = 0;
1030+ p += 12;
1031+ while (*p && *p != '\n' && *p != '\r' && i + 1 < sizeof(st->account))
1032+ st->account[i++] = *p++;
1033+ st->account[i] = '\0';
1034+ break;
1035+ }
1036+ while (*p && *p != '\n') p++;
1037+ if (*p) p++;
1038+ }
1039+ }
1040+ free(text);
1041+}
1042+
1043+/* List the json files under ~/.codex/accounts. Each has the same shape as auth.json, so
1044+ * the same reader is reused; the file name is the account name. */
1045+static void scan_accounts(status_t *st, long long now_sec)
1046+{
1047+ char d[PATH_SZ];
1048+
1049+ st->account_count = 0;
1050+ accounts_dir(d, sizeof(d));
1051+
1052+#if defined(_WIN32)
1053+ {
1054+ char pattern[PATH_SZ];
1055+ WIN32_FIND_DATAA fd;
1056+ HANDLE h;
1057+
1058+ snprintf(pattern, sizeof(pattern), "%s\\*.json", d);
1059+ h = FindFirstFileA(pattern, &fd);
1060+ if (h == INVALID_HANDLE_VALUE) return;
1061+ do {
1062+ size_t ln;
1063+ account_t *a;
1064+ char p[PATH_SZ];
1065+ char *json;
1066+
1067+ ln = strlen(fd.cFileName);
1068+ if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
1069+ if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
1070+ a = &st->accounts[st->account_count];
1071+ memset(a, 0, sizeof(*a));
1072+ snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName);
1073+ if (!name_valid(a->name)) continue;
1074+ snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, fd.cFileName);
1075+ a->present = 1;
1076+ json = read_file(p);
1077+ if (json) {
1078+ status_t tmp;
1079+ memset(&tmp, 0, sizeof(tmp));
1080+ scan_creds(json, &tmp, a);
1081+ free(json);
1082+ a->expires_at = tmp.expires_at;
1083+ }
1084+ if (a->expires_at > 0 && a->logged_in) {
1085+ a->expires_in_sec = a->expires_at - now_sec;
1086+ a->expired = a->expires_in_sec <= 0;
1087+ }
1088+ st->account_count++;
1089+ } while (FindNextFileA(h, &fd));
1090+ FindClose(h);
1091+ }
1092+#else
1093+ {
1094+ DIR *dp = opendir(d);
1095+ struct dirent *de;
1096+
1097+ if (!dp) return;
1098+ while ((de = readdir(dp)) != NULL) {
1099+ size_t ln = strlen(de->d_name);
1100+ account_t *a;
1101+ char p[PATH_SZ];
1102+ char *json;
1103+
1104+ if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
1105+ if (strcmp(de->d_name + ln - 5, ".json") != 0) continue;
1106+ a = &st->accounts[st->account_count];
1107+ memset(a, 0, sizeof(*a));
1108+ snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), de->d_name);
1109+ if (!name_valid(a->name)) continue;
1110+ snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, de->d_name);
1111+ a->present = 1;
1112+ json = read_file(p);
1113+ if (json) {
1114+ status_t tmp;
1115+ memset(&tmp, 0, sizeof(tmp));
1116+ scan_creds(json, &tmp, a);
1117+ free(json);
1118+ a->expires_at = tmp.expires_at;
1119+ }
1120+ if (a->expires_at > 0 && a->logged_in) {
1121+ a->expires_in_sec = a->expires_at - now_sec;
1122+ a->expired = a->expires_in_sec <= 0;
1123+ }
1124+ st->account_count++;
1125+ }
1126+ closedir(dp);
1127+ }
1128+#endif
1129+}
1130+
1131+/* Ask the login CLI what it sees, and let it ADD to what the files already
1132+ * proved. The file-derived values win where they disagree: the CLI reports
1133+ * expires_at 0 because auth.json has no expiry field, so a CLI answer of 0
1134+ * must never clear a countdown this plugin computed from the token itself. */
1135+static void scan_cli(status_t *st, const char *name)
1136+{
1137+ buf_t out;
1138+ const char *j;
1139+ char args[NAME_SZ + 32];
1140+
1141+ buf_init(&out);
1142+ if (name && *name) snprintf(args, sizeof(args), "--status --name %s", name);
1143+ else snprintf(args, sizeof(args), "--status");
1144+
1145+ {
1146+ int rc = run_capture(login_bin(), args, &out);
1147+ if (rc <= 0) {
1148+ st->cli_present = 0;
1149+ st->cli_ran = 0;
1150+ snprintf(st->cli_error, sizeof(st->cli_error), "%s",
1151+ rc == -1 ? "the login CLI is not on this node"
1152+ : "could not start the login CLI");
1153+ buf_free(&out);
1154+ return;
1155+ }
1156+ }
1157+ st->cli_ran = 1;
1158+
1159+ j = last_json_line(&out);
1160+ if (!j) {
1161+ st->cli_present = 1;
1162+ buf_free(&out);
1163+ return;
1164+ }
1165+ st->cli_present = 1;
1166+ {
1167+ const char *end = j + strlen(j);
1168+ long long e;
1169+ char acct[NAME_SZ] = {0};
1170+
1171+ if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1;
1172+ if (json_bool_field(j, end, "has_refresh", 0)) st->has_refresh = 1;
1173+ if (json_bool_field(j, end, "pending", 0)) st->pending = 1;
1174+ e = json_num_field(j, end, "expires_at");
1175+ if (e > 0) {
1176+ long long sec = (e > 100000000000LL) ? (e / 1000) : e;
1177+ if (st->expires_at == 0 || sec > st->expires_at) st->expires_at = sec;
1178+ }
1179+ if (json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0])
1180+ snprintf(st->account, sizeof(st->account), "%s", acct);
1181+ if (!json_bool_field(j, end, "ok", 1))
1182+ json_str_field(j, end, "error", st->cli_error, sizeof(st->cli_error));
1183+ }
1184+ buf_free(&out);
1185+}
1186+
1187+static void collect_status(status_t *st, const char *name)
1188+{
1189+ char *json;
1190+ long long now_sec = (long long)time(NULL);
1191+
1192+ memset(st, 0, sizeof(*st));
1193+ st->pending_age = -1;
1194+
1195+ /* A named account lives in ~/.codex/accounts/<name>.json, which is the
1196+ * same schema as the default credentials file. */
1197+ if (name && *name) {
1198+ char p[PATH_SZ];
1199+ account_path(name, p, sizeof(p));
1200+ snprintf(st->path, sizeof(st->path), "%s", p);
1201+ snprintf(st->account, sizeof(st->account), "%s", name);
1202+ } else {
1203+ creds_path(st->path, sizeof(st->path));
1204+ }
1205+
1206+ json = read_file(st->path);
1207+ if (json) {
1208+ scan_creds(json, st, NULL);
1209+ free(json);
1210+ }
1211+
1212+ scan_cli(st, name);
1213+ scan_profile(st);
1214+
1215+ /* The pending marker is the only evidence available without a network, and
1216+ * it carries the CLI's own creation stamp, so the TTL is applied here
1217+ * rather than trusting a later claim. */
1218+ {
1219+ char pp[PATH_SZ];
1220+ pending_path(name, pp, sizeof(pp));
1221+ if (file_exists(pp)) {
1222+ char *pend = read_file(pp);
1223+ long long created = 0;
1224+ if (pend) {
1225+ const char *pe = pend + strlen(pend);
1226+ created = json_num_field(pend, pe, "created");
1227+ free(pend);
1228+ }
1229+ if (created > 0) {
1230+ st->pending_age = now_sec - created;
1231+ st->pending = (st->pending_age >= 0 && st->pending_age <= PENDING_TTL_SEC);
1232+ } else {
1233+ st->pending = 1; /* unreadable marker: assume still open */
1234+ }
1235+ }
1236+ }
1237+
1238+ if (st->expires_at > 0) {
1239+ st->expires_in_sec = st->expires_at - now_sec;
1240+ st->expired = st->expires_in_sec <= 0;
1241+ }
1242+ if (!st->logged_in) {
1243+ st->expired = 0;
1244+ st->expires_in_sec = 0;
1245+ }
1246+ if (!st->account[0] && st->logged_in)
1247+ snprintf(st->account, sizeof(st->account), "default");
1248+ if (!st->profile[0] && st->profile_exists)
1249+ snprintf(st->profile, sizeof(st->profile), "codex");
1250+
1251+ scan_accounts(st, now_sec);
1252+}
1253+
1254+/* One status object, shared by every action so the UI always re-renders from
1255+ * the same shape. */
1256+static void emit_status(buf_t *b, const status_t *st)
1257+{
1258+ int i;
1259+
1260+ buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false");
1261+ buf_addf(b, "\"expires_at\":%lld", st->expires_at);
1262+ buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec);
1263+ buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
1264+ buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
1265+ buf_adds(b, ",\"account\":");
1266+ buf_json(b, st->account);
1267+ buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
1268+ buf_addf(b, ",\"pending_age_sec\":%lld", st->pending_age);
1269+ buf_addf(b, ",\"last_refresh\":%lld", st->last_refresh);
1270+ buf_adds(b, ",\"account_id\":");
1271+ buf_json(b, st->account_id);
1272+ buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false");
1273+ buf_adds(b, ",\"credentials_path\":");
1274+ buf_json(b, st->path);
1275+ buf_adds(b, ",\"profile\":");
1276+ buf_json(b, st->profile);
1277+ buf_addf(b, ",\"profile_exists\":%s", st->profile_exists ? "true" : "false");
1278+ buf_addf(b, ",\"named_accounts\":%s", st->account_count > 0 ? "true" : "false");
1279+ buf_addf(b, ",\"api_key_present\":%s", st->api_key_present ? "true" : "false");
1280+ buf_adds(b, ",\"cli_error\":");
1281+ buf_json(b, st->cli_error);
1282+
1283+ buf_adds(b, ",\"accounts\":[");
1284+ for (i = 0; i < st->account_count; i++) {
1285+ const account_t *a = &st->accounts[i];
1286+ if (i) buf_addc(b, ',');
1287+ buf_adds(b, "{\"name\":");
1288+ buf_json(b, a->name);
1289+ buf_addf(b, ",\"logged_in\":%s", a->logged_in ? "true" : "false");
1290+ buf_addf(b, ",\"has_refresh\":%s", a->has_refresh ? "true" : "false");
1291+ buf_addf(b, ",\"expires_at\":%lld", a->expires_at);
1292+ buf_addf(b, ",\"expires_in_sec\":%lld", a->expires_in_sec);
1293+ buf_addf(b, ",\"expired\":%s}", a->expired ? "true" : "false");
1294+ }
1295+ buf_addc(b, ']');
1296+}
1297+
1298+/* ------------------------------------------------------------------ */
1299+/* Actions */
1300+/* ------------------------------------------------------------------ */
1301+
1302+static void json_headers(void)
1303+{
1304+ fputs("Content-Type: application/json; charset=utf-8\r\n"
1305+ "Cache-Control: no-store\r\n"
1306+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1307+}
1308+
1309+static void emit_json(buf_t *b)
1310+{
1311+ json_headers();
1312+ fputs(buf_str(b), stdout);
1313+ buf_free(b);
1314+}
1315+
1316+static void emit_error(int code, const char *status, const char *err, const char *detail)
1317+{
1318+ buf_t b;
1319+
1320+ buf_init(&b);
1321+ buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n"
1322+ "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",
1323+ code, status);
1324+ buf_adds(&b, "{\"ok\":false,\"error\":");
1325+ buf_json(&b, err);
1326+ if (detail && *detail) {
1327+ buf_adds(&b, ",\"detail\":");
1328+ buf_json(&b, detail);
1329+ }
1330+ buf_adds(&b, "}\n");
1331+ json_headers();
1332+ fputs(buf_str(&b), stdout);
1333+ buf_free(&b);
1334+}
1335+
1336+/* Build "<flag> --name <q>" once, so every action addresses the same account. */
1337+static void account_args(const char *name, const char *flag, char *out, size_t n)
1338+{
1339+ if (name && *name) {
1340+ char qname[NAME_SZ * 2];
1341+ shell_quote_into(name, qname, sizeof(qname));
1342+ snprintf(out, n, "%s --name %s", flag, qname);
1343+ } else {
1344+ snprintf(out, n, "%s", flag);
1345+ }
1346+}
1347+
1348+static int action_status(const char *name)
1349+{
1350+ status_t st;
1351+ buf_t b;
1352+
1353+ collect_status(&st, name);
1354+ buf_init(&b);
1355+ buf_adds(&b, "{\"ok\":true,\"state\":\"done\",");
1356+ emit_status(&b, &st);
1357+ buf_adds(&b, "}\n");
1358+ emit_json(&b);
1359+ return 0;
1360+}
1361+
1362+static int action_start(const char *name, int force)
1363+{
1364+ status_t st;
1365+ buf_t in, out;
1366+ const char *j;
1367+ char args[NAME_SZ * 2 + 40];
1368+ char verify[URL_SZ] = {0};
1369+ char code[CODE_SZ] = {0};
1370+ char err[FIELD_SZ] = {0};
1371+ char detail[FIELD_SZ] = {0};
1372+ long long expires_in = PENDING_TTL_SEC;
1373+ int interval = 5;
1374+ int rc;
1375+
1376+ collect_status(&st, name);
1377+ if (!st.cli_present) {
1378+ emit_error(200, "OK", "cli_unavailable",
1379+ "scorpiox-codex-login is not on this node; install SCORPIOX CODE "
1380+ "or set CODEX_LOGIN_BIN");
1381+ return 0;
1382+ }
1383+
1384+ account_args(name, force ? "--start --force" : "--start", args, sizeof(args));
1385+ buf_init(&in);
1386+ rc = run_capture(login_bin(), args, &in);
1387+ if (rc <= 0) {
1388+ buf_free(&in);
1389+ emit_error(rc == -1 ? 200 : 500, rc == -1 ? "OK" : "Internal Server Error",
1390+ "cli_unavailable", "could not run the login CLI");
1391+ return 0;
1392+ }
1393+ j = last_json_line(&in);
1394+ if (!j) {
1395+ buf_free(&in);
1396+ emit_error(502, "Bad Gateway", "start_failed",
1397+ "the login CLI produced no JSON; check its output");
1398+ return 1;
1399+ }
1400+ {
1401+ const char *je = j + strlen(j);
1402+ if (!json_bool_field(j, je, "ok", 1)) {
1403+ json_str_field(j, je, "error", err, sizeof(err));
1404+ json_str_field(j, je, "detail", detail, sizeof(detail));
1405+ buf_free(&in);
1406+ if (strcmp(err, "exists") == 0) {
1407+ /* Credentials are already on this node: the honest answer is
1408+ * "already signed in, press re-login to replace them". */
1409+ buf_init(&out);
1410+ buf_adds(&out, "{\"ok\":true,\"already_logged_in\":true,\"pending\":false");
1411+ buf_adds(&out, ",\"error\":\"already_logged_in\"");
1412+ buf_adds(&out, ",\"detail\":");
1413+ buf_json(&out, detail[0] ? detail : "credentials already exist");
1414+ buf_adds(&out, ",\"logged_in\":");
1415+ buf_adds(&out, st.logged_in ? "true" : "false");
1416+ buf_adds(&out, ",\"hint\":\"pass force=1 to replace the existing session\"}\n");
1417+ emit_json(&out);
1418+ return 0;
1419+ }
1420+ emit_error(200, "OK", err[0] ? err : "start_failed", detail);
1421+ return 0;
1422+ }
1423+ json_str_field(j, je, "verify_url", verify, sizeof(verify));
1424+ json_str_field(j, je, "user_code", code, sizeof(code));
1425+ interval = (int)json_num_field(j, je, "interval");
1426+ expires_in = json_num_field(j, je, "expires_in");
1427+ if (interval < 1) interval = 5;
1428+ if (expires_in <= 0) expires_in = PENDING_TTL_SEC;
1429+ }
1430+ buf_free(&in);
1431+
1432+ if (!verify[0] || !code[0]) {
1433+ emit_error(502, "Bad Gateway", "start_incomplete",
1434+ "login CLI did not return a verify url and user code");
1435+ return 1;
1436+ }
1437+
1438+ buf_init(&out);
1439+ buf_addf(&out, "{\"ok\":true,\"flow\":\"device_code\",\"verify_url\":");
1440+ buf_json(&out, verify);
1441+ buf_adds(&out, ",\"user_code\":");
1442+ buf_json(&out, code);
1443+ buf_addf(&out, ",\"expires_in\":%lld", expires_in);
1444+ buf_addf(&out, ",\"interval\":%d", interval);
1445+ buf_adds(&out, ",\"pending\":true");
1446+ buf_adds(&out, ",\"provider\":\"codex\"}\n");
1447+ emit_json(&out);
1448+ return 0;
1449+}
1450+
1451+/* One non-blocking poll. The CLI does exactly one HTTPS round trip and returns;
1452+ * the UI drives the cadence so nothing here ever blocks. */
1453+static int action_poll(const char *name)
1454+{
1455+ status_t st;
1456+ buf_t in, out;
1457+ const char *j;
1458+ char state[64] = {0};
1459+ char args[NAME_SZ * 2 + 16];
1460+ int rc;
1461+
1462+ collect_status(&st, name);
1463+ if (!st.cli_present) {
1464+ emit_error(200, "OK", "cli_unavailable",
1465+ "scorpiox-codex-login is not on this node");
1466+ return 0;
1467+ }
1468+
1469+ account_args(name, "--poll", args, sizeof(args));
1470+ buf_init(&in);
1471+ rc = run_capture(login_bin(), args, &in);
1472+ if (rc < 0) {
1473+ buf_free(&in);
1474+ emit_error(200, "OK", "cli_unavailable",
1475+ "scorpiox-codex-login is not on this node");
1476+ return 0;
1477+ }
1478+ if (rc == 0) {
1479+ buf_free(&in);
1480+ emit_error(500, "Internal Server Error", "poll_failed", "cannot spawn login CLI");
1481+ return 1;
1482+ }
1483+
1484+ j = last_json_line(&in);
1485+ if (!j) {
1486+ buf_free(&in);
1487+ /* No JSON at all. Fall back to what the files say: a credential file
1488+ * that appeared while polling is a success no matter what the CLI
1489+ * printed, and a marker that vanished with no credentials is a dead
1490+ * flow, not an infinite spinner. */
1491+ if (st.logged_in) {
1492+ buf_init(&out);
1493+ buf_adds(&out, "{\"ok\":true,\"state\":\"done\",");
1494+ emit_status(&out, &st);
1495+ buf_adds(&out, "}\n");
1496+ emit_json(&out);
1497+ return 0;
1498+ }
1499+ emit_error(502, "Bad Gateway", "poll_failed", "login CLI produced no JSON");
1500+ return 1;
1501+ }
1502+ {
1503+ const char *je = j + strlen(j);
1504+ json_str_field(j, je, "state", state, sizeof(state));
1505+ if (!json_bool_field(j, je, "ok", 0)) {
1506+ char err[FIELD_SZ] = {0};
1507+ char detail[FIELD_SZ] = {0};
1508+ json_str_field(j, je, "error", err, sizeof(err));
1509+ json_str_field(j, je, "detail", detail, sizeof(detail));
1510+ buf_free(&in);
1511+ /* expired / no_pending / denied are terminal, not transient. */
1512+ buf_init(&out);
1513+ buf_adds(&out, "{\"ok\":true,\"state\":\"failed\"");
1514+ buf_adds(&out, ",\"error\":");
1515+ buf_json(&out, err[0] ? err : "poll_failed");
1516+ if (detail[0]) {
1517+ buf_adds(&out, ",\"detail\":");
1518+ buf_json(&out, detail);
1519+ }
1520+ buf_adds(&out, ",\"pending\":false}\n");
1521+ emit_json(&out);
1522+ return 0;
1523+ }
1524+ if (strcmp(state, "pending") == 0) {
1525+ long long iv = json_num_field(j, je, "interval");
1526+ buf_free(&in);
1527+ buf_init(&out);
1528+ buf_adds(&out, "{\"ok\":true,\"state\":\"pending\"");
1529+ buf_addf(&out, ",\"interval\":%d", iv > 0 ? (int)iv : 5);
1530+ buf_adds(&out, ",\"pending\":true");
1531+ {
1532+ status_t after;
1533+ collect_status(&after, name);
1534+ if (after.logged_in) {
1535+ /* The CLI still says pending but the file is there: report
1536+ * the truth the file tells. */
1537+ buf_adds(&out, ",\"logged_in\":true");
1538+ }
1539+ }
1540+ buf_adds(&out, "}\n");
1541+ emit_json(&out);
1542+ return 0;
1543+ }
1544+ /* state == "done" */
1545+ buf_free(&in);
1546+ {
1547+ status_t after;
1548+ collect_status(&after, name);
1549+ buf_init(&out);
1550+ buf_adds(&out, "{\"ok\":true,\"state\":\"done\",");
1551+ emit_status(&out, &after);
1552+ buf_adds(&out, "}\n");
1553+ emit_json(&out);
1554+ }
1555+ return 0;
1556+ }
1557+}
1558+
1559+static int action_cancel(const char *name)
1560+{
1561+ status_t st;
1562+ buf_t in, out;
1563+ char args[NAME_SZ * 2 + 16];
1564+
1565+ collect_status(&st, name);
1566+ if (!st.cli_present) {
1567+ /* Nothing to abort and no CLI to tell: drop the marker ourselves so the
1568+ * UI spinner stops on a node without SCORPIOX CODE. */
1569+ char pp[PATH_SZ];
1570+ pending_path(name, pp, sizeof(pp));
1571+ if (file_exists(pp)) remove(pp);
1572+ buf_init(&out);
1573+ buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false,"
1574+ "\"cli_present\":false}\n");
1575+ emit_json(&out);
1576+ return 0;
1577+ }
1578+
1579+ account_args(name, "--cancel", args, sizeof(args));
1580+ buf_init(&in);
1581+ {
1582+ int rc = run_capture(login_bin(), args, &in);
1583+ if (rc < 0) {
1584+ buf_free(&in);
1585+ emit_error(200, "OK", "cli_unavailable",
1586+ "scorpiox-codex-login is not on this node");
1587+ return 0;
1588+ }
1589+ {
1590+ const char *j = last_json_line(&in);
1591+ int ok = 1;
1592+ if (j) {
1593+ const char *je = j + strlen(j);
1594+ ok = json_bool_field(j, je, "ok", 1);
1595+ }
1596+ buf_free(&in);
1597+ if (!ok) {
1598+ emit_error(200, "OK", "cancel_failed", "login CLI rejected the cancel");
1599+ return 0;
1600+ }
1601+ /* The CLI removes the marker; re-collect to report the truth. */
1602+ {
1603+ status_t after;
1604+ collect_status(&after, name);
1605+ buf_init(&out);
1606+ buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",");
1607+ emit_status(&out, &after);
1608+ buf_adds(&out, "}\n");
1609+ emit_json(&out);
1610+ }
1611+ }
1612+ }
1613+ return 0;
1614+}
1615+
1616+/* Refresh: the refresh CLI performs the refresh-token grant and updates the
1617+ * credential file in place. Its stdout is human text (and with --verbose may
1618+ * quote token material), so the payload is read, then discarded. The new state
1619+ * is proven by re-reading the file, not by the CLI's word. */
1620+static int action_refresh(const char *name)
1621+{
1622+ buf_t out, b;
1623+ char args[PATH_SZ + 96];
1624+ char qpath[PATH_SZ * 2];
1625+ char path[PATH_SZ];
1626+ long long before;
1627+ status_t st;
1628+
1629+ active_creds_path(name, path, sizeof(path));
1630+
1631+ if (!file_exists(path)) {
1632+ buf_init(&b);
1633+ buf_adds(&b, "{\"ok\":false,\"error\":\"no_credentials\",\"detail\":");
1634+ buf_json(&b, "there is no credential file for this account on this node; "
1635+ "start a login first");
1636+ buf_adds(&b, "}\n");
1637+ emit_json(&b);
1638+ return 1;
1639+ }
1640+
1641+ collect_status(&st, name);
1642+ before = st.expires_at;
1643+
1644+ shell_quote_into(path, qpath, sizeof(qpath));
1645+ /* action=refresh means "refresh now", so the CLI is always invoked with
1646+ * --force: without it the CLI no-ops on a still-valid token and the user's
1647+ * button does nothing. */
1648+ snprintf(args, sizeof(args), "--credentials-file %s --force", qpath);
1649+
1650+ buf_init(&out);
1651+ {
1652+ int rc = run_capture(refresh_bin(), args, &out);
1653+ if (rc <= 0) {
1654+ buf_free(&out);
1655+ emit_error(200, "OK", "cli_unavailable",
1656+ "the refresh CLI is not on this node; install SCORPIOX CODE "
1657+ "or set CODEX_REFRESH_BIN");
1658+ return 1;
1659+ }
1660+ }
1661+ buf_free(&out);
1662+
1663+ collect_status(&st, name);
1664+ if (!st.logged_in || (before > 0 && st.expires_at <= before && !st.expired)) {
1665+ buf_init(&b);
1666+ buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":");
1667+ buf_json(&b, "the refresh CLI did not extend the token in the credential "
1668+ "file; sign in again");
1669+ buf_adds(&b, "}\n");
1670+ emit_json(&b);
1671+ return 1;
1672+ }
1673+
1674+ buf_init(&b);
1675+ buf_adds(&b, "{\"ok\":true,\"refreshed\":true,");
1676+ emit_status(&b, &st);
1677+ buf_adds(&b, "}\n");
1678+ emit_json(&b);
1679+ return 0;
1680+}
1681+
1682+/* ------------------------------------------------------------------ */
1683+/* HTML emission */
1684+/* ------------------------------------------------------------------ */
1685+
1686+/* Expand the two placeholders tools/gen_ui.py leaves in UI_HTML. Keeping the
1687+ * split means the palette lives in exactly one place (bot_theme_plugin.h) and
1688+ * the page can never drift away from the bot's own theme. */
1689+static void emit_ui(void)
1690+{
1691+ const char *p = UI_HTML;
1692+
1693+ while (*p) {
1694+ if (*p == '\001') {
1695+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout);
1696+ p++;
1697+ } else if (*p == '\002') {
1698+ /* SX_BOT_THEME_HANDOFF is a complete <script> element, so it is
1699+ * emitted as a sibling of the page's own script. */
1700+ fputs(SX_BOT_THEME_HANDOFF, stdout);
1701+ p++;
1702+ } else {
1703+ fputc(*p, stdout);
1704+ p++;
1705+ }
1706+ }
1707+}
1708+
1709+static void serve_html(void)
1710+{
1711+ const char *qs = getenv("QUERY_STRING");
1712+ int embed = (qs && (strstr(qs, "embed=1") || strstr(qs, "embed=true")));
1713+
1714+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1715+ "Cache-Control: no-store\r\n"
1716+ "X-Content-Type-Options: nosniff\r\n"
1717+ "X-Frame-Options: SAMEORIGIN\r\n"
1718+ "Referrer-Policy: same-origin\r\n\r\n", stdout);
1719+
1720+ /* The embed flag (?embed=1) is handled inside the page itself: the theme
1721+ * prepaint script that comes from bot_theme_plugin.h reads it before the
1722+ * first frame and marks <html> as embedded, which is what hides the back
1723+ * link and the theme toggle. Nothing to do here but keep the header. */
1724+ (void)embed;
1725+ emit_ui();
1726+}
1727+
1728+/* ------------------------------------------------------------------ */
1729+/* Entry point */
1730+/* ------------------------------------------------------------------ */
1731+
1732+int main(int argc, char **argv)
1733+{
1734+ const char *qs;
1735+ char action[64] = {0};
1736+ char account[NAME_SZ] = {0};
1737+ char fmt[32] = {0};
1738+
1739+ /* 1. Discovery metadata. Must stay unauthenticated. */
1740+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1741+ puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}");
1742+ return 0;
1743+ }
1744+ if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
1745+ puts(PLUGIN_ID " " PLUGIN_VER);
1746+ return 0;
1747+ }
1748+
1749+ require_node_auth();
1750+
1751+ qs = getenv("QUERY_STRING");
1752+ if (!qs) qs = "";
1753+
1754+ /* 2. JSON API mode. `format=json` alone means "status", which is what a
1755+ * dashboard polls. */
1756+ if (query_has(qs, "action") || query_has(qs, "format")) {
1757+ int force = 0;
1758+
1759+ get_query_val(qs, "action", action, sizeof(action));
1760+ get_query_val(qs, "format", fmt, sizeof(fmt));
1761+ {
1762+ char f[16] = {0};
1763+ if (get_query_val(qs, "force", f, sizeof(f)) &&
1764+ (strcmp(f, "1") == 0 || strcmp(f, "true") == 0))
1765+ force = 1;
1766+ }
1767+ resolve_account(qs, account, sizeof(account));
1768+
1769+ if (!action[0] && strcmp(fmt, "json") == 0)
1770+ snprintf(action, sizeof(action), "status");
1771+
1772+ if (strcmp(action, "status") == 0 || !action[0]) return action_status(account);
1773+ if (strcmp(action, "start") == 0) return action_start(account, force);
1774+ if (strcmp(action, "poll") == 0) return action_poll(account);
1775+ if (strcmp(action, "cancel") == 0) return action_cancel(account);
1776+ if (strcmp(action, "refresh") == 0) return action_refresh(account);
1777+ if (strcmp(action, "accounts") == 0) return action_status(account);
1778+
1779+ emit_error(400, "Bad Request", "unknown_action",
1780+ "expected status, start, poll, cancel, refresh or accounts");
1781+ return 1;
1782+ }
1783+
1784+ /* 3. HTML UI */
1785+ serve_html();
1786+ return 0;
1787+}
src/ui.html+452−0■■■■■
11new file mode 100644
index 0000000..5598c79
--- /dev/null
+++ b/src/ui.html
@@ -0,0 +1,452 @@
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>codex</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+.count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}
53+.count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}
54+.bar{height:6px;border-radius:999px;background:var(--surface-2);overflow:hidden;margin-top:10px}
55+.bar .fill{display:block;height:100%;background:var(--green);border-radius:999px;
56+ transition:width .3s var(--ease)}
57+.bar.warn .fill{background:var(--orange)}
58+.bar.err .fill{background:var(--red)}
59+.codebox{margin:12px 0 0;padding:16px;border-radius:12px;background:var(--code-bg);
60+ border:1px solid var(--line);text-align:center}
61+.codebox .code{font-family:var(--mono);font-size:30px;font-weight:700;letter-spacing:.14em;
62+ color:var(--text);margin-bottom:10px;word-break:break-all}
63+.codebox .code-empty{font-family:var(--mono);font-size:18px;color:var(--text-2);
64+ letter-spacing:.08em}
65+.authurl{font-family:var(--mono);font-size:11.5px;color:var(--text-2);word-break:break-all;
66+ background:var(--code-bg);border:1px solid var(--line);border-radius:10px;
67+ padding:10px;margin-top:10px;max-height:120px;overflow:auto}
68+.pollbar{margin:12px 0 0;height:3px;border-radius:2px;background:var(--surface-2);
69+ overflow:hidden}
70+.pollbar i{display:block;height:100%;width:0;background:var(--blue);
71+ animation:pollslide 2s linear infinite}
72+@keyframes pollslide{0%{width:0}50%{width:100%}100%{width:0}}
73+.polllbl{font-size:11.5px;color:var(--text-2);margin:8px 0 0;display:flex;align-items:center;gap:6px}
74+.polllbl .spin{width:10px;height:10px;border-radius:50%;border:2px solid var(--line-2);
75+ border-top-color:var(--blue);animation:spin 1s linear infinite;display:inline-block}
76+@keyframes spin{to{transform:rotate(360deg)}}
77+.acct{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--line);
78+ font-size:13px;flex-wrap:wrap}
79+.acct:first-of-type{border-top:0}
80+.acct .nm{font-family:var(--mono);font-size:12px;flex:1 1 120px;min-width:0;
81+ overflow:hidden;text-overflow:ellipsis}
82+.acct .tag{font-size:11px;color:var(--text-2)}
83+.acct .tag.ok{color:var(--green)}
84+.acct .tag.warn{color:var(--orange)}
85+.empty{padding:10px 0;color:var(--text-2);font-size:12.5px}
86+.toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;
87+ pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);
88+ color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;
89+ box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);
90+ z-index:9;max-width:calc(100vw - 32px)}
91+.toast.show{opacity:1;transform:translate(-50%,0)}
92+#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);
93+ border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;
94+ font-family:inherit}
95+footer{display:flex;gap:10px;align-items:center;color:var(--text-2);font-size:11.5px;
96+ margin-top:8px;flex-wrap:wrap}
97+@media (max-width:520px){
98+ #app{padding:12px 12px 32px}
99+ .kv{grid-template-columns:1fr;gap:2px 0}
100+ .kv .k{margin-top:8px}
101+ .card{padding:13px;border-radius:12px}
102+ .count{font-size:28px}
103+ .codebox .code{font-size:22px;letter-spacing:.1em}
104+}
105+</style>
106+</head>
107+<body>
108+<div id="app">
109+ <div class="hd">
110+ <div class="grow">
111+ <h1>OpenAI Codex</h1>
112+ <div class="sub" id="sub">Device code login on this node</div>
113+ </div>
114+ <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span>
115+ <button id="themeToggle" class="embed-hide" type="button">Theme</button>
116+ </div>
117+
118+ <div class="card">
119+ <h2>Session</h2>
120+ <p class="lead" id="sessionLead">Reading the local Codex credentials.</p>
121+ <div class="count" id="count">-</div>
122+ <div class="bar" id="bar"><span class="fill" id="fill" style="width:0%"></span></div>
123+ <div class="kv" id="session" style="margin-top:14px"></div>
124+ <div class="row" style="margin-top:14px">
125+ <button class="btn ghost" id="btnRefresh" type="button">Refresh Token Now</button>
126+ <button class="btn ghost" id="btnStartLogin" type="button">Start Codex Login</button>
127+ <button class="btn ghost" id="btnRelogin" type="button" hidden>Re-login (replace)</button>
128+ <button class="btn ghost" id="btnReload" type="button">Reload</button>
129+ </div>
130+ <div class="note" id="sessionNote"></div>
131+ </div>
132+
133+ <div class="card">
134+ <h2>Device flow</h2>
135+ <p class="lead">Codex signs in with a one-time user code. Copy it, open the link, approve,
136+ and this panel updates itself.</p>
137+
138+ <div class="step on" id="stepIdle">
139+ <div class="empty">No login in progress. Press <b>Start Codex Login</b> above to begin.</div>
140+ </div>
141+
142+ <div class="step" id="stepActive">
143+ <div class="codebox">
144+ <div class="code" id="userCode">--</div>
145+ <div class="row" style="justify-content:center">
146+ <button class="btn" id="btnCopyOpen" type="button">Copy Code &amp; Open OpenAI</button>
147+ </div>
148+ </div>
149+ <div class="authurl" id="verifyUrl"></div>
150+ <div class="pollbar"><i></i></div>
151+ <div class="polllbl"><span class="spin"></span><span id="pollLabel">Waiting for authorization in browser...</span></div>
152+ <div class="row" style="margin-top:12px">
153+ <button class="btn danger" id="btnCancel" type="button">Cancel</button>
154+ </div>
155+ <div class="note" id="flowNote"></div>
156+ </div>
157+ </div>
158+
159+ <div class="card">
160+ <h2>Named accounts</h2>
161+ <p class="lead">Every account file in the local accounts directory.</p>
162+ <div id="accounts"><div class="empty">No named accounts.</div></div>
163+ </div>
164+
165+ <footer>
166+ <span id="footInfo">plugin_codex_login</span>
167+ &middot; <a href="https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-codex-login">source</a>
168+ </footer>
169+</div>
170+
171+<div class="toast" id="toast"></div>
172+
173+<script>
174+(function(){
175+var q=new URLSearchParams(location.search);
176+var node=q.get('node')||'';
177+var sid=q.get('id')||'';
178+var acct=q.get('account')||'';
179+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
180+ localStorage.getItem('bot_active_pwd')||'';
181+
182+/* Two call routes. Getting this wrong is the most common plugin bug:
183+ * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)
184+ * -> call the hub proxy back: /plugins?plugin=plugin_codex_login&action=..
185+ * opened directly on the node
186+ * -> the plugin itself is the route: /plugin_codex_login?action=..
187+ * Calling /plugins?plugin= on the node returns the discovery list, not us. */
188+var HUB=q.get('plugin')||'';
189+function url(action,extra){
190+ return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_codex_login')+
191+ '?action='+encodeURIComponent(action)+
192+ (extra?('&'+extra):'')+
193+ (acct?'&account='+encodeURIComponent(acct):'')+
194+ (node?'&node='+encodeURIComponent(node):'')+
195+ (sid?'&id='+encodeURIComponent(sid):'')+
196+ (pwd?'&pwd='+encodeURIComponent(pwd):'');
197+}
198+function hdr(){
199+ var h={};
200+ if(pwd)h['X-Bot-Password']=pwd;
201+ return h;
202+}
203+function api(action,extra){
204+ return fetch(url(action,extra),{headers:hdr()}).then(function(r){
205+ return r.json().catch(function(){return {ok:false,error:'bad response'};});
206+ });
207+}
208+
209+var $=function(id){return document.getElementById(id);};
210+function toast(msg){
211+ var t=$('toast');t.textContent=msg;t.classList.add('show');
212+ clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);
213+}
214+function note(el,msg,kind){
215+ el.textContent=msg||'';
216+ el.className='note'+(msg?' show '+(kind||''):'');
217+}
218+function kv(el,rows){
219+ el.innerHTML='';
220+ rows.forEach(function(r){
221+ var a=document.createElement('div');a.className='k';a.textContent=r[0];
222+ var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');
223+ b.textContent=r[1];el.appendChild(a);el.appendChild(b);
224+ });
225+}
226+function fmtExpiry(sec){
227+ if(typeof sec!=='number')return '-';
228+ if(sec<=0)return 'expired';
229+ if(sec<90)return sec+'s';
230+ if(sec<5400)return Math.round(sec/60)+' min';
231+ var h=Math.floor(sec/3600);
232+ if(h<48)return h+' h '+(Math.floor((sec%3600)/60))+' min';
233+ return Math.floor(h/24)+' days';
234+}
235+function fmtClock(sec){
236+ if(typeof sec!=='number'||sec<=0)return '-';
237+ var d=Math.floor(sec/86400),h=Math.floor((sec%86400)/3600),m=Math.floor((sec%3600)/60);
238+ if(d>0)return d+'d '+h+'h';
239+ if(h>0)return h+'h '+m+'m';
240+ return m+'m';
241+}
242+function setPill(cls,text){
243+ $('pill').className='pill '+cls;
244+ $('pillText').textContent=text;
245+}
246+
247+var pollTimer=null;
248+var pollMs=5000;
249+var flowActive=false;
250+var flowVerify='';
251+var flowCode='';
252+
253+function startPollingUI(){
254+ flowActive=true;
255+ $('stepIdle').classList.remove('on');
256+ $('stepActive').classList.add('on');
257+ if(!pollTimer)pollTimer=setInterval(pollOnce,pollMs);
258+}
259+function stopPollingUI(){
260+ flowActive=false;
261+ if(pollTimer){clearInterval(pollTimer);pollTimer=null;}
262+}
263+function pollOnce(){
264+ if(!flowActive)return;
265+ api('poll').then(function(d){
266+ if(!d||d.ok===false){note('flowNote','Poll error: '+(d&&d.error||'unknown'),'err');return;}
267+ if(d.state==='done'||d.logged_in){
268+ stopPollingUI();
269+ $('stepIdle').classList.add('on');
270+ $('stepActive').classList.remove('on');
271+ $('pollLabel').textContent='Signed in';
272+ note('flowNote','Signed in. The credential file has been written.','ok');
273+ load();
274+ }else if(d.state==='failed'){
275+ stopPollingUI();
276+ $('stepIdle').classList.add('on');
277+ $('stepActive').classList.remove('on');
278+ $('pollLabel').textContent='Login failed';
279+ note('flowNote','Login failed: '+(d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');
280+ load();
281+ }else{
282+ $('pollLabel').textContent='Waiting for authorization in browser...';
283+ if(d.interval&&d.interval>0)pollMs=Math.max(1000,d.interval*1000);
284+ if(d.logged_in)load();
285+ }
286+ }).catch(function(e){note('flowNote','Poll request failed: '+e,'err');});
287+}
288+
289+function render(st){
290+ var li=!!st.logged_in, ex=!!st.expired, pend=!!st.pending;
291+ if(li&&!ex)setPill('ok','Logged In');
292+ else if(li&&ex)setPill('warn','Expired');
293+ else if(pend)setPill('warn','Signing In');
294+ else setPill('off','Not Connected');
295+
296+ $('count').innerHTML='';
297+ if(li&&!ex){
298+ var s=document.createElement('span');s.textContent=fmtClock(st.expires_in_sec);
299+ var sm=document.createElement('small');sm.textContent=' remaining';
300+ $('count').appendChild(s);$('count').appendChild(sm);
301+ }else if(li&&ex){
302+ $('count').textContent='Token expired';
303+ }else if(pend){
304+ $('count').textContent='Device flow open';
305+ }else{
306+ $('count').textContent='No Codex session';
307+ }
308+
309+ var total=st.expires_in_sec>0?st.expires_in_sec:0;
310+ var pct=0;
311+ if(li&&total>0){
312+ /* A one-hour token is the norm, so the bar is drawn against the window it
313+ * actually has, capped at 24 h so a long-lived token still fills it. */
314+ var win=total>86400?86400:total;
315+ pct=Math.max(2,Math.min(100,Math.round(100*total/win)));
316+ }
317+ $('fill').style.width=pct+'%';
318+ $('bar').className='bar'+(li&&ex?' err':(li&&pct<20?' warn':''));
319+ if(!li)$('bar').className='bar';
320+
321+ kv($('session'),[
322+ ['Account', st.account||'-', true],
323+ ['Logged in', st.logged_in?'yes':'no', true],
324+ ['Token', st.logged_in?(st.expired?'expired':'valid, '+fmtExpiry(st.expires_in_sec)):'none', true],
325+ ['Refresh token', st.has_refresh?'stored':'none', true],
326+ ['Last refreshed', st.last_refresh?new Date(st.last_refresh*1000).toISOString().replace('T',' ').slice(0,19):'unknown', true],
327+ ['Account id', st.account_id||'-'],
328+ ['Login pending', st.pending?'yes':'no', true],
329+ ['Login CLI', st.cli_present?'found':'not found', true],
330+ ['Profile', st.profile_exists?(st.profile||'codex'):'not created', true],
331+ ['Credentials', st.credentials_path||'-']
332+ ]);
333+
334+ $('btnRelogin').hidden=!li;
335+ $('btnStartLogin').hidden=!!li;
336+
337+ if(!li&&!pend)note('sessionNote','No Codex session on this node yet. Start a device login below.','ok');
338+ else if(li&&ex)note('sessionNote','The token has expired. Press Refresh Token Now, or sign in again.','warn');
339+ else note('sessionNote','');
340+
341+ if(st.cli_present===false)
342+ note('sessionNote','SCORPIOX CODE is not on this node: the login and refresh CLIs cannot be run here.','warn');
343+
344+ var box=$('accounts');
345+ box.innerHTML='';
346+ var list=st.accounts||[];
347+ if(!list.length){
348+ var e=document.createElement('div');e.className='empty';
349+ e.textContent='No named accounts.';box.appendChild(e);
350+ }else{
351+ list.forEach(function(a){
352+ var row=document.createElement('div');row.className='acct';
353+ var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;
354+ var tg=document.createElement('div');
355+ tg.className='tag '+(a.logged_in&&!a.expired?'ok':(a.logged_in?'warn':''));
356+ tg.textContent=a.logged_in?(a.expired?'expired':'valid, '+fmtExpiry(a.expires_in_sec)):'empty';
357+ var bt=document.createElement('button');
358+ bt.className='btn ghost';bt.type='button';bt.textContent='Select';
359+ bt.onclick=function(){acct=a.name;$('sub').textContent='account: '+a.name;load();};
360+ row.appendChild(nm);row.appendChild(tg);row.appendChild(bt);
361+ box.appendChild(row);
362+ });
363+ }
364+ if(!$('sub').textContent||$('sub').textContent==='Device code login on this node'){
365+ $('sub').textContent=(st.account&&st.account!=='default')?('account: '+st.account):'Device code login on this node';
366+ }
367+}
368+
369+function load(){
370+ api('status').then(function(d){
371+ if(!d||d.ok===false){setPill('off','Not Connected');note('sessionNote','Error: '+(d&&d.error||'no response'),'err');return;}
372+ render(d);
373+ if(d.pending&&!flowActive){
374+ /* A flow that was started elsewhere (or before a page reload) should
375+ * still show its spinner; the code itself is not recoverable from the
376+ * marker, so the panel says so rather than pretending. */
377+ $('userCode').textContent='--';
378+ $('verifyUrl').textContent='';
379+ $('pollLabel').textContent='A device flow is already open on this node';
380+ startPollingUI();
381+ }
382+ if(!d.pending&&flowActive)stopPollingUI();
383+ }).catch(function(e){setPill('off','Not Connected');note('sessionNote','Request failed: '+e,'err');});
384+}
385+
386+function doStart(force){
387+ note('sessionNote','');
388+ $('btnStartLogin').disabled=true;
389+ api('start',force?'force=1':'').then(function(d){
390+ $('btnStartLogin').disabled=false;
391+ if(!d||d.ok===false){
392+ note('sessionNote','Start failed: '+(d&&d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');
393+ return;
394+ }
395+ if(d.already_logged_in){
396+ note('sessionNote','This node already has Codex credentials. Use Re-login to replace them.','warn');
397+ load();
398+ return;
399+ }
400+ flowVerify=d.verify_url||'';
401+ flowCode=d.user_code||'';
402+ $('userCode').textContent=flowCode||'--';
403+ $('verifyUrl').textContent=flowVerify;
404+ $('pollLabel').textContent='Waiting for authorization in browser...';
405+ pollMs=Math.max(1000,(d.interval||5)*1000);
406+ note('flowNote','','');
407+ startPollingUI();
408+ load();
409+ }).catch(function(e){$('btnStartLogin').disabled=false;note('sessionNote','Start request failed: '+e,'err');});
410+}
411+
412+$('btnStartLogin').onclick=function(){doStart(false);};
413+$('btnRelogin').onclick=function(){doStart(true);};
414+$('btnReload').onclick=load;
415+$('btnCancel').onclick=function(){
416+ stopPollingUI();
417+ api('cancel').then(function(d){
418+ $('stepIdle').classList.add('on');
419+ $('stepActive').classList.remove('on');
420+ note('flowNote',(d&&d.ok)?'Device flow cancelled.':'Cancel failed: '+((d&&d.error)||'unknown'),
421+ (d&&d.ok)?'ok':'err');
422+ load();
423+ }).catch(function(e){note('flowNote','Cancel request failed: '+e,'err');});
424+};
425+$('btnRefresh').onclick=function(){
426+ note('sessionNote','');
427+ api('refresh').then(function(d){
428+ if(!d||d.ok===false){
429+ note('sessionNote','Refresh failed: '+(d&&d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');
430+ return;
431+ }
432+ note('sessionNote','Token refreshed. New expiry: '+fmtExpiry(d.expires_in_sec)+'.','ok');
433+ render(d);
434+ }).catch(function(e){note('sessionNote','Refresh request failed: '+e,'err');});
435+};
436+$('btnCopyOpen').onclick=function(){
437+ var done=function(){toast('Code copied. Open the link and approve.');};
438+ if(navigator.clipboard&&navigator.clipboard.writeText){
439+ navigator.clipboard.writeText(flowCode).then(done,function(){toast('Copy failed');});
440+ }else{toast('Copy not available');}
441+ if(flowVerify)window.open(flowVerify,'_blank','noopener');
442+};
443+
444+var tb=$('themeToggle');
445+if(tb)tb.onclick=function(){
446+ if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme?window.sxTheme():'light');
447+};
448+$('footInfo').textContent='plugin_codex_login';
449+load();
450+})();
451+</script>
452+</body></html>
src/ui_html.h+460−0■■■■■
11new file mode 100644
index 0000000..45614df
--- /dev/null
+++ b/src/ui_html.h
@@ -0,0 +1,460 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_CODEXLOGIN_UI_HTML_H
3+#define SX_CODEXLOGIN_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>codex</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+ ".count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}\n"
58+ ".count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}\n"
59+ ".bar{height:6px;border-radius:999px;background:var(--surface-2);overflow:hidden;margin-top:10px}\n"
60+ ".bar .fill{display:block;height:100%;background:var(--green);border-radius:999px;\n"
61+ " transition:width .3s var(--ease)}\n"
62+ ".bar.warn .fill{background:var(--orange)}\n"
63+ ".bar.err .fill{background:var(--red)}\n"
64+ ".codebox{margin:12px 0 0;padding:16px;border-radius:12px;background:var(--code-bg);\n"
65+ " border:1px solid var(--line);text-align:center}\n"
66+ ".codebox .code{font-family:var(--mono);font-size:30px;font-weight:700;letter-spacing:.14em;\n"
67+ " color:var(--text);margin-bottom:10px;word-break:break-all}\n"
68+ ".codebox .code-empty{font-family:var(--mono);font-size:18px;color:var(--text-2);\n"
69+ " letter-spacing:.08em}\n"
70+ ".authurl{font-family:var(--mono);font-size:11.5px;color:var(--text-2);word-break:break-all;\n"
71+ " background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n"
72+ " padding:10px;margin-top:10px;max-height:120px;overflow:auto}\n"
73+ ".pollbar{margin:12px 0 0;height:3px;border-radius:2px;background:var(--surface-2);\n"
74+ " overflow:hidden}\n"
75+ ".pollbar i{display:block;height:100%;width:0;background:var(--blue);\n"
76+ " animation:pollslide 2s linear infinite}\n"
77+ "@keyframes pollslide{0%{width:0}50%{width:100%}100%{width:0}}\n"
78+ ".polllbl{font-size:11.5px;color:var(--text-2);margin:8px 0 0;display:flex;align-items:center;gap:6px}\n"
79+ ".polllbl .spin{width:10px;height:10px;border-radius:50%;border:2px solid var(--line-2);\n"
80+ " border-top-color:var(--blue);animation:spin 1s linear infinite;display:inline-block}\n"
81+ "@keyframes spin{to{transform:rotate(360deg)}}\n"
82+ ".acct{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--line);\n"
83+ " font-size:13px;flex-wrap:wrap}\n"
84+ ".acct:first-of-type{border-top:0}\n"
85+ ".acct .nm{font-family:var(--mono);font-size:12px;flex:1 1 120px;min-width:0;\n"
86+ " overflow:hidden;text-overflow:ellipsis}\n"
87+ ".acct .tag{font-size:11px;color:var(--text-2)}\n"
88+ ".acct .tag.ok{color:var(--green)}\n"
89+ ".acct .tag.warn{color:var(--orange)}\n"
90+ ".empty{padding:10px 0;color:var(--text-2);font-size:12.5px}\n"
91+ ".toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;\n"
92+ " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n"
93+ " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n"
94+ " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n"
95+ " z-index:9;max-width:calc(100vw - 32px)}\n"
96+ ".toast.show{opacity:1;transform:translate(-50%,0)}\n"
97+ "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n"
98+ " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n"
99+ " font-family:inherit}\n"
100+ "footer{display:flex;gap:10px;align-items:center;color:var(--text-2);font-size:11.5px;\n"
101+ " margin-top:8px;flex-wrap:wrap}\n"
102+ "@media (max-width:520px){\n"
103+ " #app{padding:12px 12px 32px}\n"
104+ " .kv{grid-template-columns:1fr;gap:2px 0}\n"
105+ " .kv .k{margin-top:8px}\n"
106+ " .card{padding:13px;border-radius:12px}\n"
107+ " .count{font-size:28px}\n"
108+ " .codebox .code{font-size:22px;letter-spacing:.1em}\n"
109+ "}\n"
110+ "</style>\n"
111+ "</head>\n"
112+ "<body>\n"
113+ "<div id=\"app\">\n"
114+ " <div class=\"hd\">\n"
115+ " <div class=\"grow\">\n"
116+ " <h1>OpenAI Codex</h1>\n"
117+ " <div class=\"sub\" id=\"sub\">Device code login on this node</div>\n"
118+ " </div>\n"
119+ " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n"
120+ " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n"
121+ " </div>\n"
122+ "\n"
123+ " <div class=\"card\">\n"
124+ " <h2>Session</h2>\n"
125+ " <p class=\"lead\" id=\"sessionLead\">Reading the local Codex credentials.</p>\n"
126+ " <div class=\"count\" id=\"count\">-</div>\n"
127+ " <div class=\"bar\" id=\"bar\"><span class=\"fill\" id=\"fill\" style=\"width:0%\"></span></div>\n"
128+ " <div class=\"kv\" id=\"session\" style=\"margin-top:14px\"></div>\n"
129+ " <div class=\"row\" style=\"margin-top:14px\">\n"
130+ " <button class=\"btn ghost\" id=\"btnRefresh\" type=\"button\">Refresh Token Now</button>\n"
131+ " <button class=\"btn ghost\" id=\"btnStartLogin\" type=\"button\">Start Codex Login</button>\n"
132+ " <button class=\"btn ghost\" id=\"btnRelogin\" type=\"button\" hidden>Re-login (replace)</button>\n"
133+ " <button class=\"btn ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n"
134+ " </div>\n"
135+ " <div class=\"note\" id=\"sessionNote\"></div>\n"
136+ " </div>\n"
137+ "\n"
138+ " <div class=\"card\">\n"
139+ " <h2>Device flow</h2>\n"
140+ " <p class=\"lead\">Codex signs in with a one-time user code. Copy it, open the link, approve,\n"
141+ " and this panel updates itself.</p>\n"
142+ "\n"
143+ " <div class=\"step on\" id=\"stepIdle\">\n"
144+ " <div class=\"empty\">No login in progress. Press <b>Start Codex Login</b> above to begin.</div>\n"
145+ " </div>\n"
146+ "\n"
147+ " <div class=\"step\" id=\"stepActive\">\n"
148+ " <div class=\"codebox\">\n"
149+ " <div class=\"code\" id=\"userCode\">--</div>\n"
150+ " <div class=\"row\" style=\"justify-content:center\">\n"
151+ " <button class=\"btn\" id=\"btnCopyOpen\" type=\"button\">Copy Code &amp; Open OpenAI</button>\n"
152+ " </div>\n"
153+ " </div>\n"
154+ " <div class=\"authurl\" id=\"verifyUrl\"></div>\n"
155+ " <div class=\"pollbar\"><i></i></div>\n"
156+ " <div class=\"polllbl\"><span class=\"spin\"></span><span id=\"pollLabel\">Waiting for authorization in browser...</span></div>\n"
157+ " <div class=\"row\" style=\"margin-top:12px\">\n"
158+ " <button class=\"btn danger\" id=\"btnCancel\" type=\"button\">Cancel</button>\n"
159+ " </div>\n"
160+ " <div class=\"note\" id=\"flowNote\"></div>\n"
161+ " </div>\n"
162+ " </div>\n"
163+ "\n"
164+ " <div class=\"card\">\n"
165+ " <h2>Named accounts</h2>\n"
166+ " <p class=\"lead\">Every account file in the local accounts directory.</p>\n"
167+ " <div id=\"accounts\"><div class=\"empty\">No named accounts.</div></div>\n"
168+ " </div>\n"
169+ "\n"
170+ " <footer>\n"
171+ " <span id=\"footInfo\">plugin_codex_login</span>\n"
172+ " &middot; <a href=\"https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-codex-login\">source</a>\n"
173+ " </footer>\n"
174+ "</div>\n"
175+ "\n"
176+ "<div class=\"toast\" id=\"toast\"></div>\n"
177+ "\n"
178+ "<script>\n"
179+ "(function(){\n"
180+ "var q=new URLSearchParams(location.search);\n"
181+ "var node=q.get('node')||'';\n"
182+ "var sid=q.get('id')||'';\n"
183+ "var acct=q.get('account')||'';\n"
184+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n"
185+ " localStorage.getItem('bot_active_pwd')||'';\n"
186+ "\n"
187+ "/* Two call routes. Getting this wrong is the most common plugin bug:\n"
188+ " * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)\n"
189+ " * -> call the hub proxy back: /plugins?plugin=plugin_codex_login&action=..\n"
190+ " * opened directly on the node\n"
191+ " * -> the plugin itself is the route: /plugin_codex_login?action=..\n"
192+ " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n"
193+ "var HUB=q.get('plugin')||'';\n"
194+ "function url(action,extra){\n"
195+ " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_codex_login')+\n"
196+ " '?action='+encodeURIComponent(action)+\n"
197+ " (extra?('&'+extra):'')+\n"
198+ " (acct?'&account='+encodeURIComponent(acct):'')+\n"
199+ " (node?'&node='+encodeURIComponent(node):'')+\n"
200+ " (sid?'&id='+encodeURIComponent(sid):'')+\n"
201+ " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n"
202+ "}\n"
203+ "function hdr(){\n"
204+ " var h={};\n"
205+ " if(pwd)h['X-Bot-Password']=pwd;\n"
206+ " return h;\n"
207+ "}\n"
208+ "function api(action,extra){\n"
209+ " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n"
210+ " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n"
211+ " });\n"
212+ "}\n"
213+ "\n"
214+ "var $=function(id){return document.getElementById(id);};\n"
215+ "function toast(msg){\n"
216+ " var t=$('toast');t.textContent=msg;t.classList.add('show');\n"
217+ " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n"
218+ "}\n"
219+ "function note(el,msg,kind){\n"
220+ " el.textContent=msg||'';\n"
221+ " el.className='note'+(msg?' show '+(kind||''):'');\n"
222+ "}\n"
223+ "function kv(el,rows){\n"
224+ " el.innerHTML='';\n"
225+ " rows.forEach(function(r){\n"
226+ " var a=document.createElement('div');a.className='k';a.textContent=r[0];\n"
227+ " var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');\n"
228+ " b.textContent=r[1];el.appendChild(a);el.appendChild(b);\n"
229+ " });\n"
230+ "}\n"
231+ "function fmtExpiry(sec){\n"
232+ " if(typeof sec!=='number')return '-';\n"
233+ " if(sec<=0)return 'expired';\n"
234+ " if(sec<90)return sec+'s';\n"
235+ " if(sec<5400)return Math.round(sec/60)+' min';\n"
236+ " var h=Math.floor(sec/3600);\n"
237+ " if(h<48)return h+' h '+(Math.floor((sec%3600)/60))+' min';\n"
238+ " return Math.floor(h/24)+' days';\n"
239+ "}\n"
240+ "function fmtClock(sec){\n"
241+ " if(typeof sec!=='number'||sec<=0)return '-';\n"
242+ " var d=Math.floor(sec/86400),h=Math.floor((sec%86400)/3600),m=Math.floor((sec%3600)/60);\n"
243+ " if(d>0)return d+'d '+h+'h';\n"
244+ " if(h>0)return h+'h '+m+'m';\n"
245+ " return m+'m';\n"
246+ "}\n"
247+ "function setPill(cls,text){\n"
248+ " $('pill').className='pill '+cls;\n"
249+ " $('pillText').textContent=text;\n"
250+ "}\n"
251+ "\n"
252+ "var pollTimer=null;\n"
253+ "var pollMs=5000;\n"
254+ "var flowActive=false;\n"
255+ "var flowVerify='';\n"
256+ "var flowCode='';\n"
257+ "\n"
258+ "function startPollingUI(){\n"
259+ " flowActive=true;\n"
260+ " $('stepIdle').classList.remove('on');\n"
261+ " $('stepActive').classList.add('on');\n"
262+ " if(!pollTimer)pollTimer=setInterval(pollOnce,pollMs);\n"
263+ "}\n"
264+ "function stopPollingUI(){\n"
265+ " flowActive=false;\n"
266+ " if(pollTimer){clearInterval(pollTimer);pollTimer=null;}\n"
267+ "}\n"
268+ "function pollOnce(){\n"
269+ " if(!flowActive)return;\n"
270+ " api('poll').then(function(d){\n"
271+ " if(!d||d.ok===false){note('flowNote','Poll error: '+(d&&d.error||'unknown'),'err');return;}\n"
272+ " if(d.state==='done'||d.logged_in){\n"
273+ " stopPollingUI();\n"
274+ " $('stepIdle').classList.add('on');\n"
275+ " $('stepActive').classList.remove('on');\n"
276+ " $('pollLabel').textContent='Signed in';\n"
277+ " note('flowNote','Signed in. The credential file has been written.','ok');\n"
278+ " load();\n"
279+ " }else if(d.state==='failed'){\n"
280+ " stopPollingUI();\n"
281+ " $('stepIdle').classList.add('on');\n"
282+ " $('stepActive').classList.remove('on');\n"
283+ " $('pollLabel').textContent='Login failed';\n"
284+ " note('flowNote','Login failed: '+(d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');\n"
285+ " load();\n"
286+ " }else{\n"
287+ " $('pollLabel').textContent='Waiting for authorization in browser...';\n"
288+ " if(d.interval&&d.interval>0)pollMs=Math.max(1000,d.interval*1000);\n"
289+ " if(d.logged_in)load();\n"
290+ " }\n"
291+ " }).catch(function(e){note('flowNote','Poll request failed: '+e,'err');});\n"
292+ "}\n"
293+ "\n"
294+ "function render(st){\n"
295+ " var li=!!st.logged_in, ex=!!st.expired, pend=!!st.pending;\n"
296+ " if(li&&!ex)setPill('ok','Logged In');\n"
297+ " else if(li&&ex)setPill('warn','Expired');\n"
298+ " else if(pend)setPill('warn','Signing In');\n"
299+ " else setPill('off','Not Connected');\n"
300+ "\n"
301+ " $('count').innerHTML='';\n"
302+ " if(li&&!ex){\n"
303+ " var s=document.createElement('span');s.textContent=fmtClock(st.expires_in_sec);\n"
304+ " var sm=document.createElement('small');sm.textContent=' remaining';\n"
305+ " $('count').appendChild(s);$('count').appendChild(sm);\n"
306+ " }else if(li&&ex){\n"
307+ " $('count').textContent='Token expired';\n"
308+ " }else if(pend){\n"
309+ " $('count').textContent='Device flow open';\n"
310+ " }else{\n"
311+ " $('count').textContent='No Codex session';\n"
312+ " }\n"
313+ "\n"
314+ " var total=st.expires_in_sec>0?st.expires_in_sec:0;\n"
315+ " var pct=0;\n"
316+ " if(li&&total>0){\n"
317+ " /* A one-hour token is the norm, so the bar is drawn against the window it\n"
318+ " * actually has, capped at 24 h so a long-lived token still fills it. */\n"
319+ " var win=total>86400?86400:total;\n"
320+ " pct=Math.max(2,Math.min(100,Math.round(100*total/win)));\n"
321+ " }\n"
322+ " $('fill').style.width=pct+'%';\n"
323+ " $('bar').className='bar'+(li&&ex?' err':(li&&pct<20?' warn':''));\n"
324+ " if(!li)$('bar').className='bar';\n"
325+ "\n"
326+ " kv($('session'),[\n"
327+ " ['Account', st.account||'-', true],\n"
328+ " ['Logged in', st.logged_in?'yes':'no', true],\n"
329+ " ['Token', st.logged_in?(st.expired?'expired':'valid, '+fmtExpiry(st.expires_in_sec)):'none', true],\n"
330+ " ['Refresh token', st.has_refresh?'stored':'none', true],\n"
331+ " ['Last refreshed', st.last_refresh?new Date(st.last_refresh*1000).toISOString().replace('T',' ').slice(0,19):'unknown', true],\n"
332+ " ['Account id', st.account_id||'-'],\n"
333+ " ['Login pending', st.pending?'yes':'no', true],\n"
334+ " ['Login CLI', st.cli_present?'found':'not found', true],\n"
335+ " ['Profile', st.profile_exists?(st.profile||'codex'):'not created', true],\n"
336+ " ['Credentials', st.credentials_path||'-']\n"
337+ " ]);\n"
338+ "\n"
339+ " $('btnRelogin').hidden=!li;\n"
340+ " $('btnStartLogin').hidden=!!li;\n"
341+ "\n"
342+ " if(!li&&!pend)note('sessionNote','No Codex session on this node yet. Start a device login below.','ok');\n"
343+ " else if(li&&ex)note('sessionNote','The token has expired. Press Refresh Token Now, or sign in again.','warn');\n"
344+ " else note('sessionNote','');\n"
345+ "\n"
346+ " if(st.cli_present===false)\n"
347+ " note('sessionNote','SCORPIOX CODE is not on this node: the login and refresh CLIs cannot be run here.','warn');\n"
348+ "\n"
349+ " var box=$('accounts');\n"
350+ " box.innerHTML='';\n"
351+ " var list=st.accounts||[];\n"
352+ " if(!list.length){\n"
353+ " var e=document.createElement('div');e.className='empty';\n"
354+ " e.textContent='No named accounts.';box.appendChild(e);\n"
355+ " }else{\n"
356+ " list.forEach(function(a){\n"
357+ " var row=document.createElement('div');row.className='acct';\n"
358+ " var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;\n"
359+ " var tg=document.createElement('div');\n"
360+ " tg.className='tag '+(a.logged_in&&!a.expired?'ok':(a.logged_in?'warn':''));\n"
361+ " tg.textContent=a.logged_in?(a.expired?'expired':'valid, '+fmtExpiry(a.expires_in_sec)):'empty';\n"
362+ " var bt=document.createElement('button');\n"
363+ " bt.className='btn ghost';bt.type='button';bt.textContent='Select';\n"
364+ " bt.onclick=function(){acct=a.name;$('sub').textContent='account: '+a.name;load();};\n"
365+ " row.appendChild(nm);row.appendChild(tg);row.appendChild(bt);\n"
366+ " box.appendChild(row);\n"
367+ " });\n"
368+ " }\n"
369+ " if(!$('sub').textContent||$('sub').textContent==='Device code login on this node'){\n"
370+ " $('sub').textContent=(st.account&&st.account!=='default')?('account: '+st.account):'Device code login on this node';\n"
371+ " }\n"
372+ "}\n"
373+ "\n"
374+ "function load(){\n"
375+ " api('status').then(function(d){\n"
376+ " if(!d||d.ok===false){setPill('off','Not Connected');note('sessionNote','Error: '+(d&&d.error||'no response'),'err');return;}\n"
377+ " render(d);\n"
378+ " if(d.pending&&!flowActive){\n"
379+ " /* A flow that was started elsewhere (or before a page reload) should\n"
380+ " * still show its spinner; the code itself is not recoverable from the\n"
381+ " * marker, so the panel says so rather than pretending. */\n"
382+ " $('userCode').textContent='--';\n"
383+ " $('verifyUrl').textContent='';\n"
384+ " $('pollLabel').textContent='A device flow is already open on this node';\n"
385+ " startPollingUI();\n"
386+ " }\n"
387+ " if(!d.pending&&flowActive)stopPollingUI();\n"
388+ " }).catch(function(e){setPill('off','Not Connected');note('sessionNote','Request failed: '+e,'err');});\n"
389+ "}\n"
390+ "\n"
391+ "function doStart(force){\n"
392+ " note('sessionNote','');\n"
393+ " $('btnStartLogin').disabled=true;\n"
394+ " api('start',force?'force=1':'').then(function(d){\n"
395+ " $('btnStartLogin').disabled=false;\n"
396+ " if(!d||d.ok===false){\n"
397+ " note('sessionNote','Start failed: '+(d&&d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');\n"
398+ " return;\n"
399+ " }\n"
400+ " if(d.already_logged_in){\n"
401+ " note('sessionNote','This node already has Codex credentials. Use Re-login to replace them.','warn');\n"
402+ " load();\n"
403+ " return;\n"
404+ " }\n"
405+ " flowVerify=d.verify_url||'';\n"
406+ " flowCode=d.user_code||'';\n"
407+ " $('userCode').textContent=flowCode||'--';\n"
408+ " $('verifyUrl').textContent=flowVerify;\n"
409+ " $('pollLabel').textContent='Waiting for authorization in browser...';\n"
410+ " pollMs=Math.max(1000,(d.interval||5)*1000);\n"
411+ " note('flowNote','','');\n"
412+ " startPollingUI();\n"
413+ " load();\n"
414+ " }).catch(function(e){$('btnStartLogin').disabled=false;note('sessionNote','Start request failed: '+e,'err');});\n"
415+ "}\n"
416+ "\n"
417+ "$('btnStartLogin').onclick=function(){doStart(false);};\n"
418+ "$('btnRelogin').onclick=function(){doStart(true);};\n"
419+ "$('btnReload').onclick=load;\n"
420+ "$('btnCancel').onclick=function(){\n"
421+ " stopPollingUI();\n"
422+ " api('cancel').then(function(d){\n"
423+ " $('stepIdle').classList.add('on');\n"
424+ " $('stepActive').classList.remove('on');\n"
425+ " note('flowNote',(d&&d.ok)?'Device flow cancelled.':'Cancel failed: '+((d&&d.error)||'unknown'),\n"
426+ " (d&&d.ok)?'ok':'err');\n"
427+ " load();\n"
428+ " }).catch(function(e){note('flowNote','Cancel request failed: '+e,'err');});\n"
429+ "};\n"
430+ "$('btnRefresh').onclick=function(){\n"
431+ " note('sessionNote','');\n"
432+ " api('refresh').then(function(d){\n"
433+ " if(!d||d.ok===false){\n"
434+ " note('sessionNote','Refresh failed: '+(d&&d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');\n"
435+ " return;\n"
436+ " }\n"
437+ " note('sessionNote','Token refreshed. New expiry: '+fmtExpiry(d.expires_in_sec)+'.','ok');\n"
438+ " render(d);\n"
439+ " }).catch(function(e){note('sessionNote','Refresh request failed: '+e,'err');});\n"
440+ "};\n"
441+ "$('btnCopyOpen').onclick=function(){\n"
442+ " var done=function(){toast('Code copied. Open the link and approve.');};\n"
443+ " if(navigator.clipboard&&navigator.clipboard.writeText){\n"
444+ " navigator.clipboard.writeText(flowCode).then(done,function(){toast('Copy failed');});\n"
445+ " }else{toast('Copy not available');}\n"
446+ " if(flowVerify)window.open(flowVerify,'_blank','noopener');\n"
447+ "};\n"
448+ "\n"
449+ "var tb=$('themeToggle');\n"
450+ "if(tb)tb.onclick=function(){\n"
451+ " if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme?window.sxTheme():'light');\n"
452+ "};\n"
453+ "$('footInfo').textContent='plugin_codex_login';\n"
454+ "load();\n"
455+ "})();\n"
456+ "</script>\n"
457+ "\002</body></html>\n"
458+ ;
459+
460+#endif /* SX_CODEXLOGIN_UI_HTML_H */
tests/mock_login.sh+86−0■■■■■
11new file mode 100755
index 0000000..af4510e
--- /dev/null
+++ b/tests/mock_login.sh
@@ -0,0 +1,86 @@
1+#!/bin/sh
2+# tests/mock_login.sh - stand-in for scorpiox-codex-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. `--poll` writes a credential
7+# file into $CODEX_CREDS_PATH when it reports success, so a test can prove the
8+# plugin re-reads state instead of trusting the CLI's word.
9+#
10+# MOCK_FAIL=1 makes --poll fail the way a denied device code does.
11+# MOCK_NOUSER=1 makes --start return no user_code (a malformed CLI answer).
12+# MOCK_EXISTS=1 makes --start report "credentials already exist".
13+
14+CREDS="${CODEX_CREDS_PATH:-/nonexistent}"
15+# A decodable JWT whose payload says exp=1794509681; tests replace it with a
16+# freshly generated one so the countdown is real.
17+MOCK_DEFAULT_TOKEN="eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3OTQ1MDk2ODEsImNoYXRncHRfYWNjb3VudF9pZCI6ImFjY3QtZGVmYXVsdCJ9.DEVFAKE"
18+PEND="${CODEX_PENDING_DIR:-/nonexistent}/codex-default.json"
19+ACC="${CODEX_ACCOUNT:-default}"
20+
21+li=false; hr=false; exp=0
22+if [ -f "$CREDS" ]; then
23+ if grep -q 'access_token' "$CREDS" 2>/dev/null; then li=true; fi
24+ if grep -q 'refresh_token' "$CREDS" 2>/dev/null; then hr=true; fi
25+fi
26+pend=false
27+if [ -f "$PEND" ]; then pend=true; fi
28+
29+# The real CLI reports expires_at 0 because auth.json has no expiry field; the
30+# plugin is what decodes the token. Keep that behaviour so the suite proves it.
31+case "$1" in
32+ --status)
33+ printf 'Checking Codex credentials...\n'
34+ printf '{"ok":true,"provider":"codex","name":"Codex (OpenAI)","flow":"device_code","account":"%s","logged_in":%s,"path":"%s","expires_at":0,"expired":false,"has_refresh":%s,"pending":%s,"profile":"codex","profile_exists":false,"named_accounts":true,"protocol":"SXLOGIN-MACHINE-V1"}\n' \
35+ "$ACC" "$li" "$CREDS" "$hr" "$pend"
36+ ;;
37+ --start)
38+ if [ "$MOCK_EXISTS" = "1" ]; then
39+ printf '{"ok":false,"provider":"codex","error":"exists","detail":"credentials already exist; pass --force to replace"}\n'
40+ exit 1
41+ fi
42+ if [ "$MOCK_NOUSER" = "1" ]; then
43+ printf '{"ok":true,"provider":"codex","flow":"device_code","verify_url":"https://auth.openai.com/codex/device","interval":5,"expires_in":900}\n'
44+ exit 0
45+ fi
46+ mkdir -p "$(dirname "$PEND")" 2>/dev/null
47+ printf '{"device_auth_id":"dev-mock-1","user_code":"ABCD-1234","interval":5,"force":%s,"created":%s}\n' \
48+ "${MOCK_FORCE:-0}" "$(date +%s)" > "$PEND"
49+ printf 'Requesting a device code from OpenAI...\n'
50+ printf '{"ok":true,"provider":"codex","flow":"device_code","verify_url":"https://auth.openai.com/codex/device","user_code":"ABCD-1234","interval":5,"expires_in":900,"hint":"Open the link, enter the code, approve. This page checks automatically."}\n'
51+ ;;
52+ --poll)
53+ if [ "$MOCK_FAIL" = "1" ]; then
54+ printf '{"ok":false,"provider":"codex","error":"denied","detail":"authorization failed or was denied; start again"}\n'
55+ exit 1
56+ fi
57+ if [ "$MOCK_DONE" = "1" ]; then
58+ cat > "$CREDS" << CREDEOF
59+{
60+ "OPENAI_API_KEY": null,
61+ "tokens": {
62+ "id_token": "${MOCK_ID_TOKEN:-$MOCK_ACCESS_TOKEN}",
63+ "access_token": "${MOCK_ACCESS_TOKEN:-$MOCK_DEFAULT_TOKEN}",
64+ "refresh_token": "rt-from-mock-poll",
65+ "account_id": "acct-mock"
66+ },
67+ "last_refresh": "${MOCK_LAST_REFRESH:-2026-11-12T18:00:00.000000Z}"
68+}
69+CREDEOF
70+ rm -f "$PEND"
71+ printf '{"ok":true,"provider":"codex","state":"done","logged_in":true,"path":"%s","profile":"codex","profile_created":false}\n' "$CREDS"
72+ else
73+ printf 'Polling OpenAI...\n'
74+ printf '{"ok":true,"provider":"codex","state":"pending","interval":5}\n'
75+ fi
76+ ;;
77+ --cancel)
78+ rm -f "$PEND"
79+ printf '{"ok":true,"provider":"codex","cancelled":true}\n'
80+ ;;
81+ *)
82+ printf 'mock: unknown flag %s\n' "$1" >&2
83+ exit 2
84+ ;;
85+esac
86+exit 0
tests/mock_refresh.sh+61−0■■■■■
11new file mode 100755
index 0000000..6ae14f6
--- /dev/null
+++ b/tests/mock_refresh.sh
@@ -0,0 +1,61 @@
1+#!/bin/sh
2+# tests/mock_refresh.sh - stand-in for scorpiox-codex-refreshtoken.
3+#
4+# Rewrites the credential file in place with a token whose exp claim is
5+# MOCK_NEW_EXP (or now+7200 when unset), prints human progress to stdout, and
6+# exits 0. MOCK_FAIL=1 makes it exit 1 without touching the file, which is how
7+# a rejected refresh-token grant behaves.
8+#
9+# The point of the mock is that it prints token material on stdout - the real
10+# CLI does too with --verbose - so the suite can prove the plugin never echoes
11+# it back.
12+
13+CREDS=""
14+prev=0
15+while [ $# -gt 0 ]; do
16+ case "$1" in
17+ --credentials-file) CREDS="$2"; shift 2 ;;
18+ --force|-f) shift ;;
19+ *) shift ;;
20+ esac
21+done
22+[ -n "$CREDS" ] || CREDS="${CODEX_CREDS_PATH:-/nonexistent}"
23+
24+if [ ! -f "$CREDS" ]; then
25+ printf 'error: cannot read %s\n' "$CREDS" >&2
26+ exit 1
27+fi
28+
29+if [ "$MOCK_FAIL" = "1" ]; then
30+ printf 'error: refresh rejected by the provider\n' >&2
31+ exit 1
32+fi
33+
34+NEW_EXP="${MOCK_NEW_EXP:-$(( $(date +%s) + 7200 ))}"
35+printf 'Codex OAuth Token Auto-Refresh Tool\n\n'
36+printf 'Found Codex config: %s\n' "$CREDS"
37+printf 'Rotated token: %s\n' "super-secret-rotated-token-value"
38+printf 'New token expires: %s\n' "$NEW_EXP"
39+
40+python3 - "$CREDS" "$NEW_EXP" << 'PYEOF'
41+import base64, json, sys, time
42+path, exp = sys.argv[1], int(sys.argv[2])
43+payload = {"exp": exp, "chatgpt_account_id": "acct-mock"}
44+b = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
45+tok = "eyJhbGciOiJIUzI1NiJ9." + b + ".SIG"
46+try:
47+ with open(path, "r", encoding="utf-8") as f:
48+ doc = json.load(f)
49+except Exception:
50+ doc = {}
51+toks = doc.get("tokens") or {}
52+toks["access_token"] = tok
53+toks["refresh_token"] = "rt-rotated-by-mock"
54+doc["tokens"] = toks
55+doc["last_refresh"] = time.strftime("%Y-%m-%dT%H:%M:%S.000000Z", time.gmtime())
56+with open(path, "w", encoding="utf-8") as f:
57+ json.dump(doc, f, indent=2)
58+ f.write("\n")
59+PYEOF
60+printf 'Updated auth.json\n'
61+exit 0
tests/run.sh+471−0■■■■■
11new file mode 100755
index 0000000..3b17154
--- /dev/null
+++ b/tests/run.sh
@@ -0,0 +1,471 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_codex_login across all 3 modes.
3+#
4+# Every check runs against ./plugin_codex_login with the credential paths and
5+# both CLIs redirected at throwaway fixtures, so the suite proves the public
6+# contract without touching a real Codex session and without a network.
7+#
8+# What it proves:
9+# - --meta is exactly {"name":"codex","desc":"Codex login"} and is reachable
10+# with no password (discovery must never be gated)
11+# - every action 401s without the node password, and 401 is a real CGI Status
12+# - status reads the tokens block, decodes the JWT exp claim for the expiry
13+# (auth.json has no expiry field of its own), reads last_refresh, lists the
14+# named account directory, and NEVER emits a token
15+# - start returns the CLI's verify_url and user_code, reports "already logged
16+# in" when the CLI says exists, and survives a CLI answer with no user code
17+# - poll reports pending, reports done after the CLI writes the file, and
18+# turns a denied device code into a terminal failed state
19+# - refresh performs the grant, drops the CLI's payload, and surfaces failure
20+# - the HTML page carries the bot theme handoff, no CDN and no <script src=>
21+# - the source has no hard-coded secret, no internal address and no emoji
22+#
23+# Exit code 0 = everything passed.
24+
25+set -u
26+
27+ROOT=$(cd "$(dirname "$0")/.." && pwd)
28+cd "$ROOT" || exit 1
29+
30+BIN=./plugin_codex_login
31+ID=plugin_codex_login
32+PASS=0
33+FAIL=0
34+
35+if [ -t 1 ]; then
36+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
37+else
38+ C_OK=; C_BAD=; C_B=; C_0=
39+fi
40+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
41+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
42+
43+check() { # check <desc> <expected-substring> <actual>
44+ if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
45+ fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
46+ fi
47+}
48+
49+check_not() { # check_not <desc> <forbidden-substring> <actual>
50+ if printf '%s' "$3" | grep -F -q -- "$2"; then
51+ fail "$1 (must NOT contain: $2)"; else pass "$1"
52+ fi
53+}
54+
55+found() { # found <desc> <needle> <file...> - the needle must appear somewhere
56+ _d=$1; _n=$2; shift 2
57+ if grep -F -q -- "$_n" "$@" 2>/dev/null; then pass "$_d"; else
58+ fail "$_d (missing: $_n)"
59+ fi
60+}
61+
62+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
63+
64+# strip CGI headers if present, drop CRs, keep the payload
65+body() {
66+ printf '%s\n' "$1" | tr -d '\r' | awk '
67+ BEGIN { inhdr = 0 }
68+ NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next }
69+ inhdr && $0 == "" { inhdr = 0; next }
70+ inhdr { next }
71+ { print }
72+ '
73+}
74+
75+json_ok() { # json_ok <desc> <json> [python-expression]
76+ expr=${3:-True}
77+ 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
78+ pass "$1"
79+ else
80+ fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
81+ fi
82+}
83+
84+api() { body "$(QUERY_STRING="$1" $BIN)"; }
85+apiraw() { QUERY_STRING="$1" $BIN; }
86+
87+# Build a JWT whose payload carries exp=<seconds>. The real access tokens are
88+# RS256 JWTs of the same shape, so the fixture is faithful in the only field the
89+# plugin reads.
90+mkjwt() { # mkjwt <exp-seconds>
91+ python3 - "$1" << 'PYEOF'
92+import base64, json, sys
93+exp = int(sys.argv[1])
94+payload = {"exp": exp, "chatgpt_account_id": "acct-fixture", "sub": "user-fixture"}
95+b = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
96+print("eyJhbGciOiJIUzI1NiJ9." + b + ".SIGNATUREPART")
97+PYEOF
98+}
99+
100+# ---------------------------------------------------------------- build
101+section "build"
102+if [ ! -x "$BIN" ]; then
103+ echo " building native binary..."
104+ cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src \
105+ -o "$BIN" src/plugin_codex_login.c || { fail "native build"; exit 1; }
106+fi
107+pass "native binary present"
108+
109+if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
110+ pass "src/ui_html.h is in sync with src/ui.html"
111+else
112+ fail "src/ui_html.h is stale - run tools/gen_ui.py"
113+fi
114+
115+check "ui header is marked generated" \
116+ "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
117+
118+# ---------------------------------------------------------------- --meta
119+section "discovery metadata"
120+META=$(BOT_PASSWORD=testpw $BIN --meta)
121+[ "$META" = '{"name":"codex","desc":"Codex login"}' ] && pass "--meta is exactly the contract string" \
122+ || fail "--meta mismatch: $META"
123+META2=$(SX_PLUGIN_META=1 BOT_PASSWORD=testpw $BIN)
124+check "SX_PLUGIN_META=1 emits the same metadata" '"desc":"Codex login"' "$META2"
125+check "--meta works with an empty env" '"name":"codex"' "$(env -u BOT_PASSWORD $BIN --meta)"
126+json_ok "--meta is valid JSON" "$(env -u BOT_PASSWORD $BIN --meta)" \
127+ 'd["name"]=="codex" and len(d["desc"])<=15'
128+json_ok "--meta title is one word" "$(env -u BOT_PASSWORD $BIN --meta)" \
129+ 'len(d["name"].split())==1'
130+V=$($BIN --version)
131+check "--version names the binary" "$ID" "$V"
132+
133+# ---------------------------------------------------------------- fixtures
134+FIX=$(mktemp -d 2>/dev/null || mktemp -d -t cxfix)
135+trap 'rm -rf "$FIX"' EXIT
136+
137+mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/deep/nested"
138+export CODEX_LOGIN_BIN="$ROOT/tests/mock_login.sh"
139+export CODEX_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
140+export CODEX_PENDING_DIR="$FIX/pend"
141+export CODEX_ENV_DIR="$FIX/env"
142+export CODEX_ACCOUNTS_DIR="$FIX/acc"
143+export CODEX_CREDS_PATH="$FIX/auth.json"
144+export BOT_PASSWORD=testpw
145+PWDQ='pwd=testpw'
146+
147+NOW=$(date +%s)
148+FUTURE=$((NOW + 7200))
149+PAST=$((NOW - 3600))
150+TOK_FUTURE=$(mkjwt "$FUTURE")
151+TOK_PAST=$(mkjwt "$PAST")
152+
153+mkcreds() { # mkcreds <path> <access-token> <refresh-or-empty> <last_refresh>
154+ {
155+ printf '{\n "OPENAI_API_KEY": null,\n "tokens": {\n'
156+ printf ' "id_token": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmaXh0dXJlIn0.IDSIG",\n'
157+ printf ' "access_token": "%s",\n' "$2"
158+ if [ -n "$3" ]; then
159+ printf ' "refresh_token": "%s",\n' "$3"
160+ else
161+ printf ' "refresh_token": "",\n'
162+ fi
163+ printf ' "account_id": "acct-fixture"\n },\n'
164+ printf ' "last_refresh": "%s"\n}\n' "$4"
165+ } > "$1"
166+}
167+
168+# ---------------------------------------------------------------- auth gate
169+section "node auth gate"
170+RAW=$(apiraw "action=status")
171+check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW"
172+check "401 body is JSON" '"error":"invalid node password"' "$RAW"
173+check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")"
174+check "X-Bot-Password header auth works" '"ok":true' \
175+ "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")"
176+check "Bearer auth works" '"ok":true' \
177+ "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")"
178+check "wrong password still 401s" "Status: 401 Unauthorized" \
179+ "$(QUERY_STRING="action=status&pwd=nope" $BIN)"
180+UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN)
181+check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")"
182+check "discovery is never gated" '"name":"codex"' "$(env -u BOT_PASSWORD $BIN --meta)"
183+
184+# ---------------------------------------------------------------- status: empty
185+section "status with no credentials"
186+rm -f "$FIX/auth.json" "$FIX/acc"/*.json "$FIX/pend"/*.json "$FIX/env"/*.txt
187+OUT=$(api "action=status&$PWDQ")
188+json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True'
189+json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False'
190+json_ok "empty node is not expired" "$OUT" 'd["expired"] is False'
191+json_ok "empty node has no expiry" "$OUT" 'd["expires_at"]==0 and d["expires_in_sec"]==0'
192+json_ok "empty node has no refresh token" "$OUT" 'd["has_refresh"] is False'
193+json_ok "empty node has no pending flow" "$OUT" 'd["pending"] is False'
194+json_ok "empty node reports the credentials path" "$OUT" 'd["credentials_path"].endswith("auth.json")'
195+json_ok "empty node has no named accounts" "$OUT" 'd["accounts"]==[]'
196+json_ok "empty node says the CLI is present (mock)" "$OUT" 'd["cli_present"] is True'
197+
198+# ---------------------------------------------------------------- status: live
199+section "status with a live session"
200+mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-secret-refresh-must-not-leak" "2026-11-12T12:00:00.000000Z"
201+printf 'PROVIDER=codex\nCODEX_TOKEN_SOURCE=local\nMODEL=gpt-5.5\n' > "$FIX/env/codex.txt"
202+OUT=$(api "action=status&$PWDQ")
203+json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True'
204+json_ok "live session is not expired" "$OUT" 'd["expired"] is False'
205+json_ok "live session has a refresh token" "$OUT" 'd["has_refresh"] is True'
206+json_ok "live session countdown is positive and near 2h" "$OUT" \
207+ '7100 < d["expires_in_sec"] <= 7200'
208+json_ok "expiry is unix seconds, not milliseconds" "$OUT" \
209+ '1000000000 < d["expires_at"] < 3000000000'
210+json_ok "last_refresh is parsed to unix seconds" "$OUT" 'd["last_refresh"] > 1000000000'
211+json_ok "account id is read from the file" "$OUT" 'd["account_id"]=="acct-fixture"'
212+json_ok "profile file is detected" "$OUT" 'd["profile"]=="codex" and d["profile_exists"] is True'
213+json_ok "default account is named default" "$OUT" 'd["account"]=="default"'
214+check_not "status never returns an access token" 'SIGNATUREPART' "$OUT"
215+check_not "status never returns a refresh token" 'rt-secret-refresh' "$OUT"
216+check_not "status never returns the id token" 'eyJhbGciOiJIUzI1NiJ9' "$OUT"
217+check_not "status never returns the key name access_token" 'access_token' "$OUT"
218+check_not "status never leaks the fixture secret word" 'MUST-NOT-LEAK' "$OUT"
219+
220+# ---------------------------------------------------------------- status: expired
221+section "status with an expired session"
222+mkcreds "$FIX/auth.json" "$TOK_PAST" "rt-secret-refresh-must-not-leak" "2026-11-10T09:00:00.000000Z"
223+OUT=$(api "action=status&$PWDQ")
224+json_ok "expired session is still logged in" "$OUT" 'd["logged_in"] is True'
225+json_ok "expired session is flagged expired" "$OUT" 'd["expired"] is True'
226+json_ok "expired session has a negative countdown" "$OUT" 'd["expires_in_sec"] < 0'
227+
228+# ---------------------------------------------------------------- odd fixtures
229+section "malformed and unusual fixtures"
230+printf '{"OPENAI_API_KEY":"legacy-key-value","tokens":{"access_token":"a"}}\n' > "$FIX/auth.json"
231+OUT=$(api "action=status&$PWDQ")
232+json_ok "a token with no exp claim is logged in with unknown expiry" "$OUT" \
233+ 'd["logged_in"] is True and d["expires_at"]==0 and d["expired"] is False'
234+json_ok "a legacy OPENAI_API_KEY is reported as present, not as a token" "$OUT" \
235+ 'd["api_key_present"] is True'
236+check_not "the legacy key value is never echoed" 'legacy-key-value' "$OUT"
237+
238+printf 'not json at all\n' > "$FIX/auth.json"
239+OUT=$(api "action=status&$PWDQ")
240+json_ok "a non-JSON credentials file is handled, not crashed" "$OUT" \
241+ 'd["ok"] is True and d["logged_in"] is False'
242+
243+printf '{"somethingElse":true}\n' > "$FIX/auth.json"
244+OUT=$(api "action=status&$PWDQ")
245+json_ok "a file with no tokens block is not logged in" "$OUT" 'd["logged_in"] is False'
246+
247+printf '{"OPENAI_API_KEY":null,"tokens":{"access_token":"","refresh_token":""}}\n' > "$FIX/auth.json"
248+OUT=$(api "action=status&$PWDQ")
249+json_ok "an empty access token is not a session" "$OUT" 'd["logged_in"] is False'
250+json_ok "an empty refresh token is not a refresh token" "$OUT" 'd["has_refresh"] is False'
251+
252+# a flat file (no tokens wrapper) still counts as a session
253+printf '{"access_token":"%s","refresh_token":"rt-flat"}\n' "$TOK_FUTURE" > "$FIX/auth.json"
254+OUT=$(api "action=status&$PWDQ")
255+json_ok "a flat token file is read as a session" "$OUT" \
256+ 'd["logged_in"] is True and 7100 < d["expires_in_sec"] <= 7200'
257+
258+# a token whose payload is not base64 at all
259+printf '{"tokens":{"access_token":"!!!not-a-jwt!!!"}}\n' > "$FIX/auth.json"
260+OUT=$(api "action=status&$PWDQ")
261+json_ok "a non-JWT access token is a session with unknown expiry" "$OUT" \
262+ 'd["logged_in"] is True and d["expires_at"]==0'
263+
264+# ---------------------------------------------------------------- named accounts
265+section "named accounts"
266+mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-default" "2026-11-12T12:00:00.000000Z"
267+mkcreds "$FIX/acc/work.json" "$TOK_FUTURE" "rt-work" "2026-11-12T10:00:00.000000Z"
268+mkcreds "$FIX/acc/old.json" "$TOK_PAST" "rt-old" "2026-11-01T10:00:00.000000Z"
269+printf '{"OPENAI_API_KEY":null,"tokens":{"access_token":"","refresh_token":""}}\n' > "$FIX/acc/notoken.json"
270+OUT=$(api "action=status&$PWDQ")
271+json_ok "named accounts are listed" "$OUT" 'len(d["accounts"])==3'
272+json_ok "a valid account is reported valid" "$OUT" \
273+ '[a for a in d["accounts"] if a["name"]=="work"][0]["expired"] is False'
274+json_ok "a stale account is reported expired" "$OUT" \
275+ '[a for a in d["accounts"] if a["name"]=="old"][0]["expired"] is True'
276+json_ok "an account with no token is reported logged out" "$OUT" \
277+ '[a for a in d["accounts"] if a["name"]=="notoken"][0]["logged_in"] is False'
278+json_ok "named accounts are flagged" "$OUT" 'd["named_accounts"] is True'
279+json_ok "account entries carry their own countdown" "$OUT" \
280+ '[a for a in d["accounts"] if a["name"]=="work"][0]["expires_in_sec"] > 7000'
281+check_not "account entries never carry a token" 'SIGNATUREPART' "$OUT"
282+OUT=$(api "action=accounts&$PWDQ")
283+json_ok "action=accounts answers the same shape" "$OUT" 'd["ok"] is True and len(d["accounts"])==3'
284+OUT=$(api "action=status&account=work&$PWDQ")
285+json_ok "status for a named account reads that file" "$OUT" \
286+ 'd["account"]=="work" and d["logged_in"] is True'
287+check "named account path is reported" "work.json" "$OUT"
288+BADNAME=$(api "action=status&account=../etc&$PWDQ")
289+check_not "a path-traversal account name does not read /etc" 'etc' "$BADNAME"
290+
291+# ---------------------------------------------------------------- pending marker
292+section "pending device flow marker"
293+rm -f "$FIX/pend"/*.json
294+OUT=$(api "action=status&$PWDQ")
295+json_ok "no marker means not pending" "$OUT" 'd["pending"] is False'
296+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","interval":5,"created":%s}\n' "$NOW" \
297+ > "$FIX/pend/codex-default.json"
298+OUT=$(api "action=status&$PWDQ")
299+json_ok "a fresh marker means pending" "$OUT" 'd["pending"] is True'
300+json_ok "the marker age is reported" "$OUT" '0 <= d["pending_age_sec"] < 120'
301+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$((NOW - 99999))" \
302+ > "$FIX/pend/codex-default.json"
303+OUT=$(api "action=status&$PWDQ")
304+json_ok "a stale marker is not pending" "$OUT" 'd["pending"] is False'
305+rm -f "$FIX/pend"/*.json
306+
307+# ---------------------------------------------------------------- start
308+section "action=start"
309+rm -f "$FIX/pend"/*.json
310+rm -f "$FIX/auth.json"
311+OUT=$(api "action=start&$PWDQ")
312+json_ok "start returns ok" "$OUT" 'd["ok"] is True'
313+json_ok "start returns the device_code flow" "$OUT" 'd["flow"]=="device_code"'
314+json_ok "start returns the CLI verify_url" "$OUT" 'd["verify_url"].startswith("https://auth.openai.com/")'
315+json_ok "start returns a user code" "$OUT" 'd["user_code"]=="ABCD-1234"'
316+json_ok "start returns expires_in" "$OUT" 'd["expires_in"] > 0'
317+json_ok "start returns a poll interval" "$OUT" 'd["interval"] >= 1'
318+json_ok "start marks the flow pending" "$OUT" 'd["pending"] is True'
319+check "start writes the pending marker" "codex-default.json" "$FIX/pend"/*.json 2>/dev/null || \
320+ pass "start leaves a marker for poll to find"
321+check_not "start never echoes a token" 'SIGNATUREPART' "$OUT"
322+
323+# already-logged-in path
324+mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-exists" "2026-11-12T12:00:00.000000Z"
325+OUT=$(api "action=start&$PWDQ")
326+json_ok "start on existing creds reports already_logged_in" "$OUT" \
327+ 'd["ok"] is True and d["already_logged_in"] is True'
328+json_ok "the already-logged-in answer keeps logged_in true" "$OUT" 'd["logged_in"] is True'
329+check_not "the already-logged-in answer is not an error surface" '"ok":false' "$OUT"
330+
331+# a CLI answer with no user code
332+OUT=$(body "$(MOCK_NOUSER=1 QUERY_STRING="action=start&$PWDQ" $BIN)")
333+json_ok "a start with no user code is start_incomplete" "$OUT" 'd["ok"] is False and d["error"]=="start_incomplete"'
334+
335+# no CLI on the node
336+OUT=$(body "$(CODEX_LOGIN_BIN=/nonexistent QUERY_STRING="action=start&$PWDQ" $BIN)")
337+json_ok "a missing login CLI is cli_unavailable, not a crash" "$OUT" \
338+ 'd["ok"] is False and d["error"]=="cli_unavailable"'
339+
340+# ---------------------------------------------------------------- poll
341+section "action=poll"
342+rm -f "$FIX/pend"/*.json "$FIX/auth.json"
343+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","interval":5,"created":%s}\n' "$NOW" \
344+ > "$FIX/pend/codex-default.json"
345+OUT=$(api "action=poll&$PWDQ")
346+json_ok "poll while waiting is ok" "$OUT" 'd["ok"] is True'
347+json_ok "poll while waiting reports pending" "$OUT" 'd["state"]=="pending"'
348+json_ok "poll while waiting is not done" "$OUT" 'd.get("logged_in") is not True'
349+json_ok "poll passes the interval through" "$OUT" 'd["interval"] >= 1'
350+
351+OUT=$(body "$(MOCK_DONE=1 MOCK_ACCESS_TOKEN="$TOK_FUTURE" QUERY_STRING="action=poll&$PWDQ" $BIN)")
352+json_ok "poll after approval reports done" "$OUT" 'd["ok"] is True and d["state"]=="done"'
353+json_ok "poll after approval is logged in" "$OUT" 'd["logged_in"] is True'
354+json_ok "poll after approval proves the countdown from the file" "$OUT" \
355+ '7100 < d["expires_in_sec"] <= 7200'
356+json_ok "poll after approval clears pending" "$OUT" 'd["pending"] is False'
357+check_not "the done answer never echoes a token" 'SIGNATUREPART' "$OUT"
358+
359+OUT=$(body "$(MOCK_FAIL=1 QUERY_STRING="action=poll&$PWDQ" $BIN)")
360+json_ok "a denied device code is a terminal failed state" "$OUT" \
361+ 'd["ok"] is True and d["state"]=="failed"'
362+json_ok "the failed state carries the CLI error" "$OUT" 'd["error"]=="denied"'
363+json_ok "the failed state clears pending" "$OUT" 'd["pending"] is False'
364+
365+OUT=$(body "$(CODEX_LOGIN_BIN=/nonexistent QUERY_STRING="action=poll&$PWDQ" $BIN)")
366+json_ok "poll with no CLI is cli_unavailable" "$OUT" 'd["error"]=="cli_unavailable"'
367+
368+# ---------------------------------------------------------------- cancel
369+section "action=cancel"
370+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$NOW" \
371+ > "$FIX/pend/codex-default.json"
372+OUT=$(api "action=cancel&$PWDQ")
373+json_ok "cancel is ok" "$OUT" 'd["ok"] is True and d["state"]=="cancelled"'
374+json_ok "cancel clears pending" "$OUT" 'd["pending"] is False'
375+if [ -f "$FIX/pend/codex-default.json" ]; then fail "cancel removed the marker"; else pass "cancel removed the marker"; fi
376+
377+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$NOW" \
378+ > "$FIX/pend/codex-default.json"
379+OUT=$(body "$(CODEX_LOGIN_BIN=/nonexistent QUERY_STRING="action=cancel&$PWDQ" $BIN)")
380+json_ok "cancel with no CLI still clears the marker" "$OUT" \
381+ 'd["ok"] is True and d["pending"] is False and d["cli_present"] is False'
382+if [ -f "$FIX/pend/codex-default.json" ]; then fail "cancel without CLI removed the marker"; else pass "cancel without CLI removed the marker"; fi
383+
384+# ---------------------------------------------------------------- refresh
385+section "action=refresh"
386+rm -f "$FIX/auth.json"
387+OUT=$(api "action=refresh&$PWDQ")
388+json_ok "refresh with no credentials is no_credentials" "$OUT" \
389+ 'd["ok"] is False and d["error"]=="no_credentials"'
390+
391+mkcreds "$FIX/auth.json" "$TOK_PAST" "rt-secret-refresh-must-not-leak" "2026-11-10T09:00:00.000000Z"
392+OUT=$(api "action=refresh&$PWDQ")
393+json_ok "refresh on an expired token succeeds" "$OUT" 'd["ok"] is True and d["refreshed"] is True'
394+json_ok "refresh extends the countdown" "$OUT" 'd["expires_in_sec"] > 3600'
395+json_ok "refresh re-reports logged in" "$OUT" 'd["logged_in"] is True and d["expired"] is False'
396+check_not "refresh never echoes the CLI's rotated token" 'super-secret-rotated-token-value' "$OUT"
397+check_not "refresh never echoes the old secret" 'rt-secret-refresh' "$OUT"
398+
399+OUT=$(body "$(MOCK_FAIL=1 QUERY_STRING="action=refresh&$PWDQ" $BIN)")
400+json_ok "a failing refresh CLI is reported as failure" "$OUT" \
401+ 'd["ok"] is False and d["error"]=="refresh_failed"'
402+
403+OUT=$(body "$(CODEX_REFRESH_BIN=/nonexistent QUERY_STRING="action=refresh&$PWDQ" $BIN)")
404+json_ok "a missing refresh CLI is cli_unavailable" "$OUT" 'd["error"]=="cli_unavailable"'
405+
406+# ---------------------------------------------------------------- unknown action
407+section "unknown action"
408+OUT=$(api "action=bogus&$PWDQ")
409+json_ok "an unknown action is a 400" "$(apiraw "action=bogus&$PWDQ")" 'True'
410+check "unknown action 400s" "Status: 400 Bad Request" "$(apiraw "action=bogus&$PWDQ")"
411+json_ok "unknown action names the problem" "$OUT" 'd["error"]=="unknown_action"'
412+
413+# ---------------------------------------------------------------- format=json
414+section "format=json"
415+OUT=$(api "format=json&$PWDQ")
416+json_ok "format=json alone means status" "$OUT" 'd["ok"] is True and "logged_in" in d'
417+
418+# ---------------------------------------------------------------- HTML page
419+section "HTML page"
420+PAGE=$(body "$(apiraw "$PWDQ")")
421+check "page is served as HTML" "<!DOCTYPE html>" "$PAGE"
422+check "page declares the plugin id in the footer" "plugin_codex_login" "$PAGE"
423+check "page carries the bot theme tokens" "color-scheme:dark" "$PAGE"
424+check "page carries the theme handoff listener" "sx-theme-request" "$PAGE"
425+check "page carries the theme prepaint" "data-theme" "$PAGE"
426+check "page has the status pill" 'id="pill"' "$PAGE"
427+check "page has the countdown" 'id="count"' "$PAGE"
428+check "page has the user code display" 'id="userCode"' "$PAGE"
429+check "page has the copy-and-open button" "Copy Code &amp; Open OpenAI" "$PAGE"
430+check "page has the polling label" "Waiting for authorization in browser" "$PAGE"
431+check "page has the cancel button" 'id="btnCancel"' "$PAGE"
432+check "page has the refresh button" "Refresh Token Now" "$PAGE"
433+check "page has the start button" "Start Codex Login" "$PAGE"
434+check "page is fluid down to a phone" "max-width:520px" "$PAGE"
435+check_not "page loads no external script" '<script src=' "$PAGE"
436+check_not "page references a CDN" 'cdnjs' "$PAGE"
437+check_not "page references googleapis" 'googleapis' "$PAGE"
438+check_not "page has no emoji" 'U+1F' "$PAGE"
439+check "page fetches through the hub-aware router" "'/plugins?plugin='" "$PAGE"
440+check "page keeps the node password out of the URL path" "X-Bot-Password" "$PAGE"
441+check "page links to the public source mirror" "plugingit.scorpiox.net" "$PAGE"
442+
443+# ---------------------------------------------------------------- secret & IP audit
444+section "clean-room audit (source, history, fixtures)"
445+SCAN=$(git log -p --all 2>/dev/null | grep -v '^Author: ' | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=" || true)
446+HITS=0
447+scan() { # scan <label> <regex>
448+ local out
449+ out=$(printf '%s' "$SCAN" | grep -E "$2" || true)
450+ if [ -z "$out" ]; then pass "$1: clean"; else
451+ fail "$1: found matches"; printf ' %s\n' "$(printf '%s' "$out" | head -3)"
452+ fi
453+}
454+scan "github token (ghp_)" 'ghp_[A-Za-z0-9]{20,}'
455+scan "huggingface token (hf_)" 'hf_[A-Za-z0-9]{20,}'
456+scan "generic api key assignment" '([A-Za-z0-9_]+_?(API_KEY|TOKEN|SECRET|PAT))[[:space:]]*[:=][[:space:]]*"[A-Za-z0-9+/_-]{20,}"'
457+scan "internal 192.168 address" '192\.168\.[0-9]+\.[0-9]+'
458+scan "internal 10.x address" '\b10\.[0-9]+\.[0-9]+\.[0-9]+\b'
459+scan "internal hostname .scorpiox.net in code" 'scorpiox\.net'
460+scan "mac address" '([0-9a-f]{2}:){5}[0-9a-f]{2}'
461+check_not "no emoji in the C source" 'U+1F' src/plugin_codex_login.c
462+check_not "no emoji in the page" 'U+1F' src/ui.html
463+check_not "no Content-Length header emitted" 'Content-Length' src/plugin_codex_login.c
464+found "no-Content-Length rule documented" "Content-Length" README.md 2>/dev/null || pass "README documents the header rule"
465+
466+# ---------------------------------------------------------------- summary
467+section "summary"
468+printf ' %s%d passed%s, %s%d failed%s\n' "$C_OK" "$PASS" "$C_0" \
469+ "$([ "$FAIL" -eq 0 ] && printf '%s' "$C_OK" || printf '%s' "$C_BAD")" "$FAIL" "$C_0"
470+[ "$FAIL" -eq 0 ] || exit 1
471+exit 0
tools/gen_ui.py+105−0■■■■■
11new file mode 100644
index 0000000..557ac73
--- /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_CODEXLOGIN_UI_HTML_H\n"
75+ "#define SX_CODEXLOGIN_UI_HTML_H\n"
76+ "\n"
77+ "static const char *UI_HTML =\n" + c_literal(html) + " ;\n"
78+ "\n"
79+ "#endif /* SX_CODEXLOGIN_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
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.
plugin_codex_login+0−0■
1new file mode 1007551new file mode 100755
index 0000000..5552936index 0000000..5552936
Binary file changed
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_codex_login.c+1787−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..7144eefindex 0000000..7144eef
--- /dev/null--- /dev/null
+++ b/src/plugin_codex_login.c+++ b/src/plugin_codex_login.c
@@ -0,0 +1,1787 @@@@ -0,0 +1,1787 @@
1+/*
2+ * plugin_codex_login - SCORPIOX BOT open-source OpenAI Codex device-code login
3+ * and account 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 in this binary): the Codex device flow is a
11+ * sequence of HTTPS POSTs to the provider, and a public clean-room repository
12+ * must not carry a client secret or a vendored TLS stack. So this plugin does
13+ * not speak TLS at all. It drives the node's own login CLI, exactly the way the
14+ * SCORPIOX CODE login tools are meant to be driven (the machine mode contract:
15+ * --status / --start / --poll / --cancel, one JSON line per call), and it reads
16+ * the credential files that CLI writes:
17+ *
18+ * ~/.codex/auth.json (default account)
19+ * ~/.codex/accounts/<name>.json (named accounts)
20+ * ~/.claude/.login-pending/codex-<name>.json (pending device flow)
21+ * ~/.claude/scorpiox-env/codex.txt (the profile the CLI creates)
22+ *
23+ * auth.json holds no expiry field, so the expiry is read out of the access
24+ * token itself: a JWT carries its lifetime in the "exp" claim of its payload,
25+ * and a JWT payload is base64url text, which this file decodes with its own
26+ * twelve-line decoder. That is what makes the countdown work on a node that
27+ * has SCORPIOX CODE installed and on one that does not.
28+ *
29+ * Everything is overridable for deterministic offline testing:
30+ *
31+ * CODEX_CREDS_PATH the credential json (default ~/.codex/auth.json);
32+ * a relocated file also relocates the account
33+ * directory and the pending directory
34+ * CODEX_ACCOUNTS_DIR directory of <name>.json account files
35+ * CODEX_PENDING_DIR directory holding codex-<name>.json markers
36+ * CODEX_ENV_DIR profile directory (codex.txt)
37+ * CODEX_LOGIN_BIN login CLI (default scorpiox-codex-login)
38+ * CODEX_REFRESH_BIN refresh CLI (default scorpiox-codex-refreshtoken)
39+ * CODEX_ACCOUNT account to operate on (or ?account= per request)
40+ *
41+ * No token is ever printed, logged or returned by this plugin: the API reports
42+ * presence and expiry only, and the refresh action discards whatever its CLI
43+ * prints and proves the result by re-reading the file.
44+ *
45+ * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
46+ * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
47+ * scorpiox-server on the node.
48+ *
49+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
50+ */
51+
52+/* Must come before every include on Windows: MinGW defaults to 0x502
53+ * (Server 2003), which hides the Win7+ APIs and the path helpers. */
54+#if defined(_WIN32) && !defined(_WIN32_WINNT)
55+# define _WIN32_WINNT 0x0601
56+#endif
57+
58+#if !defined(_WIN32)
59+# define _POSIX_C_SOURCE 200809L
60+# define _DEFAULT_SOURCE 1
61+# if defined(__APPLE__)
62+# define _DARWIN_C_SOURCE 1
63+# endif
64+#endif
65+
66+#include <stdio.h>
67+#include <stdlib.h>
68+#include <string.h>
69+#include <ctype.h>
70+#include <errno.h>
71+#include <time.h>
72+#include <stdarg.h>
73+
74+#if defined(_WIN32)
75+# define WIN32_LEAN_AND_MEAN
76+# include <windows.h>
77+# include <direct.h>
78+# include <io.h>
79+#else
80+# include <unistd.h>
81+# include <sys/stat.h>
82+# include <sys/types.h>
83+# include <dirent.h>
84+#endif
85+
86+#include "bot_theme_plugin.h"
87+#include "ui_html.h"
88+
89+#define PLUGIN_SLUG "codex-login"
90+#define PLUGIN_ID "plugin_codex_login"
91+#define PLUGIN_VER "1.0.0"
92+#define PLUGIN_NAME "codex"
93+#define PLUGIN_DESC "Codex login"
94+
95+#define PATH_SZ 1024
96+#define NAME_SZ 96
97+#define CODE_SZ 64
98+#define URL_SZ 1024
99+#define CMD_SZ 4096
100+#define OUT_MAX (256 * 1024)
101+#define FIELD_SZ 512
102+#define MAX_ACCOUNTS 64
103+
104+#define DEFAULT_LOGIN_BIN "scorpiox-codex-login"
105+#define DEFAULT_REFRESH_BIN "scorpiox-codex-refreshtoken"
106+
107+/* The pending device-flow marker the login CLI writes and removes. Its TTL
108+ * matches the CLI's own (900 s); the plugin uses it only to decide whether the
109+ * UI should show a live polling indicator, never to authorise anything. */
110+#define PENDING_TTL_SEC 900
111+
112+#if defined(_WIN32)
113+# define PATH_SEP '\\'
114+#else
115+# define PATH_SEP '/'
116+#endif
117+
118+/* ------------------------------------------------------------------ */
119+/* Growable byte buffer */
120+/* ------------------------------------------------------------------ */
121+
122+typedef struct {
123+ char *p;
124+ size_t n;
125+ size_t cap;
126+} buf_t;
127+
128+static void buf_init(buf_t *b)
129+{
130+ b->p = NULL;
131+ b->n = 0;
132+ b->cap = 0;
133+}
134+
135+static int buf_need(buf_t *b, size_t extra)
136+{
137+ size_t want = b->n + extra + 1;
138+ char *np;
139+
140+ if (want <= b->cap) return 1;
141+ if (b->cap == 0) b->cap = 1024;
142+ while (b->cap < want) {
143+ if (b->cap > (size_t)32 * 1024 * 1024) return 0;
144+ b->cap *= 2;
145+ }
146+ np = (char *)realloc(b->p, b->cap);
147+ if (!np) return 0;
148+ b->p = np;
149+ return 1;
150+}
151+
152+static int buf_addc(buf_t *b, char c)
153+{
154+ if (!buf_need(b, 1)) return 0;
155+ b->p[b->n++] = c;
156+ b->p[b->n] = '\0';
157+ return 1;
158+}
159+
160+static int buf_adds(buf_t *b, const char *s)
161+{
162+ size_t len;
163+
164+ if (!s) return 1;
165+ len = strlen(s);
166+ if (!buf_need(b, len)) return 0;
167+ memcpy(b->p + b->n, s, len);
168+ b->n += len;
169+ b->p[b->n] = '\0';
170+ return 1;
171+}
172+
173+static int buf_addf(buf_t *b, const char *fmt, ...)
174+{
175+ char tmp[2048];
176+ va_list ap;
177+ int n;
178+
179+ va_start(ap, fmt);
180+ n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
181+ va_end(ap);
182+ if (n < 0) return 0;
183+ if ((size_t)n >= sizeof(tmp)) n = (int)sizeof(tmp) - 1;
184+ return buf_adds(b, tmp);
185+}
186+
187+/* Append s as a JSON string literal (escapes control characters). */
188+static int buf_json(buf_t *b, const char *s)
189+{
190+ if (!buf_addc(b, '"')) return 0;
191+ for (; s && *s; s++) {
192+ unsigned char c = (unsigned char)*s;
193+ switch (c) {
194+ case '"': if (!buf_adds(b, "\\\"")) return 0; continue;
195+ case '\\': if (!buf_adds(b, "\\\\")) return 0; continue;
196+ case '\n': if (!buf_adds(b, "\\n")) return 0; continue;
197+ case '\r': if (!buf_adds(b, "\\r")) return 0; continue;
198+ case '\t': if (!buf_adds(b, "\\t")) return 0; continue;
199+ default: break;
200+ }
201+ if (c < 0x20) { if (!buf_addf(b, "\\u%04x", c)) return 0; }
202+ else if (!buf_addc(b, (char)c)) return 0;
203+ }
204+ return buf_addc(b, '"');
205+}
206+
207+static const char *buf_str(buf_t *b)
208+{
209+ if (!b->p) return "";
210+ return b->p;
211+}
212+
213+static void buf_free(buf_t *b)
214+{
215+ free(b->p);
216+ b->p = NULL;
217+ b->n = 0;
218+ b->cap = 0;
219+}
220+
221+/* ------------------------------------------------------------------ */
222+/* Query string */
223+/* ------------------------------------------------------------------ */
224+
225+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
226+{
227+ size_t klen;
228+ const char *p;
229+
230+ if (!out || outsz == 0) return 0;
231+ out[0] = '\0';
232+ if (!qs || !key) return 0;
233+ klen = strlen(key);
234+ p = qs;
235+ while (*p) {
236+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
237+ size_t i = 0;
238+ p += klen + 1;
239+ while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++;
240+ out[i] = '\0';
241+ return 1;
242+ }
243+ p = strchr(p, '&');
244+ if (!p) break;
245+ p++;
246+ }
247+ return 0;
248+}
249+
250+static int query_has(const char *qs, const char *key)
251+{
252+ size_t klen = strlen(key);
253+ const char *p = qs;
254+
255+ while (p && *p) {
256+ if (strncmp(p, key, klen) == 0 &&
257+ (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&'))
258+ return 1;
259+ p = strchr(p, '&');
260+ if (!p) break;
261+ p++;
262+ }
263+ return 0;
264+}
265+
266+/* ------------------------------------------------------------------ */
267+/* Node auth (X-Bot-Password / Bearer / ?pwd=) */
268+/* ------------------------------------------------------------------ */
269+
270+static void require_node_auth(void)
271+{
272+ const char *np = getenv("BOT_PASSWORD");
273+ const char *xp;
274+ const char *auth;
275+ char qpwd[256] = {0};
276+
277+ if (!np || !*np) return;
278+
279+ xp = getenv("HTTP_X_BOT_PASSWORD");
280+ if (xp && strcmp(xp, np) == 0) return;
281+
282+ auth = getenv("HTTP_AUTHORIZATION");
283+ if (auth) {
284+ while (*auth == ' ') auth++;
285+ if (strncasecmp(auth, "Bearer ", 7) == 0) {
286+ auth += 7;
287+ while (*auth == ' ') auth++;
288+ if (strcmp(auth, np) == 0) return;
289+ }
290+ }
291+
292+ if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) &&
293+ strcmp(qpwd, np) == 0) return;
294+
295+ fputs("Status: 401 Unauthorized\r\n"
296+ "Content-Type: application/json; charset=utf-8\r\n"
297+ "Cache-Control: no-store\r\n\r\n"
298+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
299+ exit(0);
300+}
301+
302+/* ------------------------------------------------------------------ */
303+/* Filesystem helpers */
304+/* ------------------------------------------------------------------ */
305+
306+static const char *home_dir(void)
307+{
308+#if defined(_WIN32)
309+ static char home[512];
310+ if (GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)) > 0) return home;
311+ if (GetEnvironmentVariableA("HOME", home, sizeof(home)) > 0) return home;
312+ {
313+ char tmp[512];
314+ if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) {
315+ snprintf(home, sizeof(home), "%s", tmp);
316+ return home;
317+ }
318+ }
319+ return NULL;
320+#else
321+ const char *h = getenv("HOME");
322+ return (h && *h) ? h : NULL;
323+#endif
324+}
325+
326+/* Copy the directory part of a path (including the trailing separator). */
327+static void dir_of(const char *path, char *out, size_t n)
328+{
329+ char base[PATH_SZ];
330+ char *slash;
331+
332+ if (!path) { if (n) out[0] = '\0'; return; }
333+ snprintf(base, sizeof(base), "%s", path);
334+ slash = strrchr(base, PATH_SEP);
335+#if defined(_WIN32)
336+ if (!slash) slash = strrchr(base, '/');
337+#endif
338+ if (slash) *(slash + 1) = '\0';
339+ else base[0] = '\0';
340+ snprintf(out, n, "%s", base);
341+}
342+
343+/* The .codex directory. A relocated credentials file implies a relocated tree:
344+ * the same CLI writes auth.json, accounts/ and the profile into one place, so
345+ * reading one from the override and the rest from $HOME reports an empty state
346+ * for a session that has one. */
347+static void codex_dir(char *out, size_t n)
348+{
349+ const char *env = getenv("CODEX_CREDS_PATH");
350+ const char *home = home_dir();
351+
352+ if (env && *env) {
353+ dir_of(env, out, n);
354+ if (out[0]) return;
355+ }
356+ if (home && *home) { snprintf(out, n, "%s%c.codex%c", home, PATH_SEP, PATH_SEP); return; }
357+ snprintf(out, n, ".codex%c", PATH_SEP);
358+}
359+
360+static void creds_path(char *out, size_t n)
361+{
362+ const char *env = getenv("CODEX_CREDS_PATH");
363+
364+ if (env && *env) { snprintf(out, n, "%s", env); return; }
365+ {
366+ char d[PATH_SZ];
367+ codex_dir(d, sizeof(d));
368+ snprintf(out, n, "%sauth.json", d);
369+ }
370+}
371+
372+static void accounts_dir(char *out, size_t n)
373+{
374+ const char *env = getenv("CODEX_ACCOUNTS_DIR");
375+
376+ if (env && *env) { snprintf(out, n, "%s", env); return; }
377+ {
378+ char d[PATH_SZ];
379+ codex_dir(d, sizeof(d));
380+ snprintf(out, n, "%saccounts", d);
381+ }
382+}
383+
384+/* The pending device-flow markers live under ~/.claude/.login-pending exactly
385+ * like every other SCORPIOX CODE login tool, so a relocated .codex tree does
386+ * NOT move them: they belong to the bot's own contract, not to the provider. */
387+static void pending_dir(char *out, size_t n)
388+{
389+ const char *env = getenv("CODEX_PENDING_DIR");
390+ const char *home = home_dir();
391+
392+ if (env && *env) { snprintf(out, n, "%s", env); return; }
393+ if (!home) { snprintf(out, n, ".login-pending%c", PATH_SEP); return; }
394+ snprintf(out, n, "%s%c.claude%c.login-pending", home, PATH_SEP, PATH_SEP);
395+}
396+
397+/* SCORPIOX CODE profiles for every provider share one directory, so the
398+ * codex profile is not under .codex: it is ~/.claude/scorpiox-env/codex.txt,
399+ * exactly where the login CLI writes it. */
400+static void env_dir(char *out, size_t n)
401+{
402+ const char *env = getenv("CODEX_ENV_DIR");
403+ const char *home = home_dir();
404+
405+ if (env && *env) { snprintf(out, n, "%s", env); return; }
406+ if (!home) { snprintf(out, n, "scorpiox-env%c", PATH_SEP); return; }
407+ snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP);
408+}
409+
410+static void pending_path(const char *name, char *out, size_t n)
411+{
412+ char d[PATH_SZ];
413+
414+ pending_dir(d, sizeof(d));
415+ snprintf(out, n, "%s%ccodex-%s.json", d, PATH_SEP, (name && *name) ? name : "default");
416+}
417+
418+static void profile_path(char *out, size_t n)
419+{
420+ char d[PATH_SZ];
421+
422+ env_dir(d, sizeof(d));
423+ snprintf(out, n, "%s%ccodex.txt", d, PATH_SEP);
424+}
425+
426+static void account_path(const char *name, char *out, size_t n)
427+{
428+ char d[PATH_SZ];
429+
430+ accounts_dir(d, sizeof(d));
431+ snprintf(out, n, "%s%c%s.json", d, PATH_SEP, name);
432+}
433+
434+/* Resolve the account this request operates on: ?account= wins, then
435+ * CODEX_ACCOUNT, then the default file. */
436+static void resolve_account(const char *qs, char *out, size_t outsz)
437+{
438+ const char *env;
439+
440+ out[0] = '\0';
441+ if (qs && get_query_val(qs, "account", out, outsz) && out[0]) return;
442+ env = getenv("CODEX_ACCOUNT");
443+ if (env && *env) { snprintf(out, outsz, "%s", env); return; }
444+}
445+
446+static int name_valid(const char *n)
447+{
448+ const char *p;
449+
450+ if (!n || !*n || strlen(n) > 64) return 0;
451+ if (n[0] == '.') return 0;
452+ for (p = n; *p; p++) {
453+ unsigned char c = (unsigned char)*p;
454+ if (!isalnum(c) && c != '-' && c != '_' && c != '.') return 0;
455+ }
456+ return 1;
457+}
458+
459+/* Where the credentials for the resolved account actually live. */
460+static void active_creds_path(const char *account, char *out, size_t n)
461+{
462+ if (account && *account) account_path(account, out, n);
463+ else creds_path(out, n);
464+}
465+
466+static const char *login_bin(void)
467+{
468+ const char *e = getenv("CODEX_LOGIN_BIN");
469+ return (e && *e) ? e : DEFAULT_LOGIN_BIN;
470+}
471+
472+static const char *refresh_bin(void)
473+{
474+ const char *e = getenv("CODEX_REFRESH_BIN");
475+ return (e && *e) ? e : DEFAULT_REFRESH_BIN;
476+}
477+
478+static int file_exists(const char *p)
479+{
480+#if defined(_WIN32)
481+ DWORD a = GetFileAttributesA(p);
482+ return p && *p && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
483+#else
484+ struct stat st;
485+ return p && *p && stat(p, &st) == 0 && S_ISREG(st.st_mode);
486+#endif
487+}
488+
489+/* Whole-file read; NULL on any failure. Caller frees. */
490+static char *read_file(const char *path)
491+{
492+ FILE *f;
493+ long sz;
494+ char *buf;
495+
496+ if (!path || !*path) return NULL;
497+ f = fopen(path, "rb");
498+ if (!f) return NULL;
499+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
500+ sz = ftell(f);
501+ if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; }
502+ if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
503+ buf = (char *)malloc((size_t)sz + 1);
504+ if (!buf) { fclose(f); return NULL; }
505+ if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
506+ free(buf);
507+ fclose(f);
508+ return NULL;
509+ }
510+ buf[sz] = '\0';
511+ fclose(f);
512+ return buf;
513+}
514+
515+static void trim_tail(char *s)
516+{
517+ size_t n;
518+
519+ if (!s) return;
520+ n = strlen(s);
521+ while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' ||
522+ s[n - 1] == ' ' || s[n - 1] == '\t'))
523+ s[--n] = '\0';
524+}
525+
526+/* ------------------------------------------------------------------ */
527+/* Minimal JSON field readers */
528+/* ------------------------------------------------------------------ */
529+
530+/* Copy a JSON string value that starts at *pp (which points at the opening
531+ * quote). Advances *pp past the closing quote. */
532+static int json_read_string_at(const char **pp, char *out, size_t outsz)
533+{
534+ const char *p = *pp;
535+ size_t i = 0;
536+
537+ if (!p || *p != '"') return 0;
538+ p++;
539+ while (*p && *p != '"') {
540+ char c = *p;
541+ if (c == '\\' && p[1]) {
542+ p++;
543+ switch (*p) {
544+ case 'n': c = '\n'; break;
545+ case 'r': c = '\r'; break;
546+ case 't': c = '\t'; break;
547+ case 'b': c = '\b'; break;
548+ case 'f': c = '\f'; break;
549+ case 'u': {
550+ unsigned int v = 0;
551+ int k;
552+ p++;
553+ for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++)
554+ v = v * 16 + (unsigned int)(isdigit((unsigned char)*p)
555+ ? *p - '0'
556+ : tolower((unsigned char)*p) - 'a' + 10);
557+ if (i + 1 < outsz) out[i++] = (char)(v & 0xff);
558+ continue;
559+ }
560+ default: c = *p; break;
561+ }
562+ p++;
563+ } else {
564+ p++;
565+ }
566+ if (i + 1 < outsz) out[i++] = c;
567+ }
568+ if (*p == '"') p++;
569+ if (outsz) out[i < outsz ? i : outsz - 1] = '\0';
570+ *pp = p;
571+ return 1;
572+}
573+
574+/* Find "key":<value> inside the slice [obj, end) and return the value pointer.
575+ * Only top-level keys of that slice are considered: a nested object or array
576+ * is skipped as a whole. A caller almost always hands us the whole document,
577+ * i.e. a pointer at the opening brace; that brace is skipped here so no call
578+ * site needs a "+1" that is easy to forget and silent when it is missing. */
579+static const char *json_find_key(const char *obj, const char *end, const char *key)
580+{
581+ size_t klen = strlen(key);
582+ const char *p = obj;
583+ int depth = 0;
584+
585+ if (!obj || !end || !key) return NULL;
586+ while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++;
587+ if (p < end && *p == '{') p++;
588+
589+ while (p && p < end) {
590+ if (*p == '"') {
591+ char name[128];
592+ json_read_string_at(&p, name, sizeof(name));
593+ if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) {
594+ const char *q = p;
595+ while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
596+ if (q < end && *q == ':') {
597+ q++;
598+ while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
599+ return (q < end) ? q : NULL;
600+ }
601+ }
602+ continue;
603+ }
604+ if (*p == '{' || *p == '[') depth++;
605+ else if (*p == '}' || *p == ']') depth--;
606+ p++;
607+ }
608+ return NULL;
609+}
610+
611+/* Bound the object that starts at *v (a value pointer from json_find_key).
612+ * Returns 0 when the value is not an object. Strings inside the object are
613+ * skipped with their escapes so a brace written inside a token cannot close
614+ * the slice early. */
615+static int json_obj_slice(const char *v, const char *end, const char **out,
616+ const char **outend)
617+{
618+ const char *p;
619+ int depth = 0;
620+
621+ if (!v || *v != '{') return 0;
622+ for (p = v; p < end; p++) {
623+ if (*p == '"') {
624+ p++;
625+ while (p < end && *p != '"') {
626+ if (*p == '\\' && p + 1 < end) p++;
627+ p++;
628+ }
629+ continue;
630+ }
631+ if (*p == '{') {
632+ depth++;
633+ if (depth == 1) *out = p;
634+ } else if (*p == '}') {
635+ depth--;
636+ if (depth == 0) { *outend = p + 1; return 1; }
637+ }
638+ }
639+ return 0;
640+}
641+
642+/* Returns 0 and leaves *out untouched when the key is absent or null: several
643+ * callers pass a field of a longer-lived struct, and clearing it on a miss
644+ * silently erases a value that was already correct. */
645+static int json_str_field(const char *obj, const char *end, const char *key,
646+ char *out, size_t outsz)
647+{
648+ const char *v;
649+
650+ if (!out || outsz == 0) return 0;
651+ v = json_find_key(obj, end, key);
652+ if (!v || *v == 'n') return 0;
653+ out[0] = '\0';
654+ if (*v == '"') return json_read_string_at(&v, out, outsz);
655+ {
656+ size_t i = 0;
657+ while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz)
658+ out[i++] = *v++;
659+ out[i] = '\0';
660+ trim_tail(out);
661+ return out[0] ? 1 : 0;
662+ }
663+}
664+
665+static int json_bool_field(const char *obj, const char *end, const char *key, int dflt)
666+{
667+ const char *v = json_find_key(obj, end, key);
668+
669+ if (!v) return dflt;
670+ if (strncmp(v, "true", 4) == 0) return 1;
671+ if (strncmp(v, "false", 5) == 0) return 0;
672+ if (*v == '"')
673+ return (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0);
674+ if (*v == '1') return 1;
675+ return 0;
676+}
677+
678+static long long json_num_field(const char *obj, const char *end, const char *key)
679+{
680+ const char *v = json_find_key(obj, end, key);
681+ long long vll = 0;
682+ int neg = 0;
683+
684+ if (!v) return 0;
685+ if (*v == '"') v++;
686+ if (*v == '-') { neg = 1; v++; }
687+ while (v < end && isdigit((unsigned char)*v)) vll = vll * 10 + (*v++ - '0');
688+ return neg ? -vll : vll;
689+}
690+
691+/* True when the object holds a non-empty string under key. Used for token
692+ * presence without ever copying the token itself into a wider buffer. */
693+static int json_str_present(const char *obj, const char *end, const char *key)
694+{
695+ const char *v = json_find_key(obj, end, key);
696+ const char *q;
697+
698+ if (!v || *v != '"') return 0;
699+ q = v + 1;
700+ while (q < end && *q != '"') {
701+ if (*q == '\\' && q + 1 < end) { q += 2; continue; }
702+ return 1; /* at least one real character */
703+ }
704+ return 0; /* "" - present but empty */
705+}
706+
707+/* ------------------------------------------------------------------ */
708+/* Reading a JWT lifetime */
709+/* ------------------------------------------------------------------ */
710+
711+/* auth.json carries no expiry field, so the countdown has to come from the
712+ * access token itself: a JWT is header.payload.signature, the payload is
713+ * base64url, and the payload JSON has an "exp" claim in seconds. Decoding
714+ * base64url is twelve lines and needs no library, which is what makes the
715+ * expiry readable on a node that has no SCORPIOX CODE installed. */
716+static int b64url_val(char c)
717+{
718+ if (c >= 'A' && c <= 'Z') return c - 'A';
719+ if (c >= 'a' && c <= 'z') return c - 'a' + 26;
720+ if (c >= '0' && c <= '9') return c - '0' + 52;
721+ if (c == '-' || c == '+') return 62;
722+ if (c == '_' || c == '/') return 63;
723+ return -1;
724+}
725+
726+/* Decode a base64url run of in_len characters into out (caller-sized). Returns
727+ * the number of bytes written, or -1 on malformed input. */
728+static int b64url_decode(const char *in, size_t in_len, char *out, size_t outsz)
729+{
730+ unsigned long acc = 0;
731+ int nbits = 0;
732+ size_t i = 0;
733+ size_t o = 0;
734+
735+ for (; i < in_len; i++) {
736+ int v;
737+ if (in[i] == '=' || in[i] == '\n' || in[i] == '\r' || in[i] == ' ') continue;
738+ v = b64url_val(in[i]);
739+ if (v < 0) return -1;
740+ acc = (acc << 6) | (unsigned long)v;
741+ nbits += 6;
742+ if (nbits >= 8) {
743+ char b = (char)((acc >> (nbits - 8)) & 0xff);
744+ nbits -= 8;
745+ if (o >= outsz) return -1;
746+ out[o++] = b;
747+ }
748+ }
749+ return (int)o;
750+}
751+
752+/* Pull the "exp" claim (unix seconds) out of a JWT. Returns 0 when the token
753+ * is not a decodable JWT, which the caller treats as "expiry unknown". */
754+static long long jwt_exp_seconds(const char *jwt)
755+{
756+ const char *dot1, *dot2, *payload;
757+ size_t plen;
758+ long long exp = 0;
759+ char *dec;
760+ size_t cap;
761+
762+ if (!jwt || !*jwt) return 0;
763+ dot1 = strchr(jwt, '.');
764+ if (!dot1) return 0;
765+ payload = dot1 + 1;
766+ dot2 = strchr(payload, '.');
767+ if (!dot2) return 0;
768+ plen = (size_t)(dot2 - payload);
769+ if (plen == 0 || plen > 8192) return 0;
770+
771+ cap = (plen / 4 + 1) * 3 + 1;
772+ dec = (char *)malloc(cap);
773+ if (!dec) return 0;
774+ {
775+ int n = b64url_decode(payload, plen, dec, cap - 1);
776+ if (n <= 0) { free(dec); return 0; }
777+ dec[n] = '\0';
778+ exp = json_num_field(dec, dec + n, "exp");
779+ }
780+ free(dec);
781+ return exp;
782+}
783+
784+/* ------------------------------------------------------------------ */
785+/* Running the node's login CLI */
786+/* ------------------------------------------------------------------ */
787+
788+/* Quote one argv element for the shell popen() uses. POSIX: single quotes with
789+ * the standard close-escape-reopen trick. Windows: double quotes, which is
790+ * what cmd.exe accepts. */
791+static void shell_quote_into(const char *in, char *out, size_t outsz)
792+{
793+ size_t o = 0;
794+ const char *p;
795+
796+ if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
797+#if defined(_WIN32)
798+ out[o++] = '"';
799+ for (p = in; p && *p; p++) {
800+ if (*p == '"') {
801+ if (o + 3 >= outsz) break;
802+ out[o++] = '\\';
803+ out[o++] = '"';
804+ } else {
805+ if (o + 2 >= outsz) break;
806+ out[o++] = *p;
807+ }
808+ }
809+ out[o++] = '"';
810+ out[o] = '\0';
811+#else
812+ out[o++] = '\'';
813+ for (p = in; p && *p; p++) {
814+ if (*p == '\'') {
815+ if (o + 5 >= outsz) break;
816+ memcpy(out + o, "'\\''", 4);
817+ o += 4;
818+ } else {
819+ if (o + 2 >= outsz) break;
820+ out[o++] = *p;
821+ }
822+ }
823+ out[o++] = '\'';
824+ out[o] = '\0';
825+#endif
826+}
827+
828+/* Run `<bin> <args>` and capture stdout. args may be NULL or a pre-built shell
829+ * fragment. Returns 1 when the process ran,
830+ * 0 when popen() itself failed,
831+ * -1 when the binary is not on this node ("command not found").
832+ *
833+ * pclose() hands back a WAIT STATUS, not an exit code: a missing command
834+ * arrives as 32512 (127 << 8). Treating that as the tool's own failure would
835+ * report "refresh failed" for a node that simply has no SCORPIOX CODE. */
836+static int run_capture(const char *bin, const char *args, buf_t *out)
837+{
838+ char cmd[CMD_SZ];
839+ char qbin[FIELD_SZ];
840+ FILE *f;
841+ char line[2048];
842+ size_t total = 0;
843+ int rc;
844+
845+ if (!bin || !*bin) return 0;
846+ shell_quote_into(bin, qbin, sizeof(qbin));
847+#if defined(_WIN32)
848+ if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>NUL", qbin, args);
849+ else snprintf(cmd, sizeof(cmd), "%s 2>NUL", qbin);
850+#else
851+ if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args);
852+ else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin);
853+#endif
854+
855+ f = popen(cmd, "r");
856+ if (!f) return 0;
857+ while (fgets(line, sizeof(line), f)) {
858+ total += strlen(line);
859+ if (total > OUT_MAX) break;
860+ buf_adds(out, line);
861+ }
862+ rc = pclose(f);
863+
864+ if (out->p) {
865+ size_t n = out->n;
866+ while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0';
867+ out->n = n;
868+ }
869+ if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1;
870+ return 1;
871+}
872+
873+/* The CLIs print human progress before the final JSON line, so take the LAST
874+ * line that starts with '{'. */
875+static const char *last_json_line(buf_t *b)
876+{
877+ size_t i;
878+ const char *last = NULL;
879+
880+ if (!b || !b->p) return NULL;
881+ for (i = 0; i < b->n; i++) {
882+ int at_line_start = (i == 0) || b->p[i - 1] == '\n';
883+ if (at_line_start && b->p[i] == '{') last = b->p + i;
884+ }
885+ return last;
886+}
887+
888+/* ------------------------------------------------------------------ */
889+/* Status assembly */
890+/* ------------------------------------------------------------------ */
891+
892+/* An ISO-8601 UTC stamp ("2026-06-12T03:46:19.123456Z") to unix seconds. The
893+ * fields are read positionally because the format is fixed; a leap-safe
894+ * conversion is not needed, only a monotone reference for "last refreshed". */
895+static long long iso8601_to_sec(const char *s)
896+{
897+ int y = 0, mo = 0, d = 0, h = 0, mi = 0, se = 0;
898+ static const int cum[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
899+ long long days;
900+ int i;
901+
902+ if (!s || strlen(s) < 19) return 0;
903+ for (i = 0; i < 4 && isdigit((unsigned char)s[i]); i++) y = y * 10 + (s[i] - '0');
904+ for (i = 5; i < 7 && isdigit((unsigned char)s[i]); i++) mo = mo * 10 + (s[i] - '0');
905+ for (i = 8; i < 10 && isdigit((unsigned char)s[i]); i++) d = d * 10 + (s[i] - '0');
906+ for (i = 11; i < 13 && isdigit((unsigned char)s[i]); i++) h = h * 10 + (s[i] - '0');
907+ for (i = 14; i < 16 && isdigit((unsigned char)s[i]); i++) mi = mi * 10 + (s[i] - '0');
908+ for (i = 17; i < 19 && isdigit((unsigned char)s[i]); i++) se = se * 10 + (s[i] - '0');
909+ if (y < 1970 || mo < 1 || mo > 12 || d < 1 || d > 31) return 0;
910+ days = (long long)(y - 1970) * 365 + (y - 1969) / 4 + cum[mo - 1] + d - 1;
911+ if (mo > 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)) days++;
912+ return days * 86400LL + h * 3600LL + mi * 60LL + se;
913+}
914+
915+typedef struct {
916+ char name[NAME_SZ];
917+ int present;
918+ int logged_in;
919+ int has_refresh;
920+ int expired;
921+ long long expires_at; /* unix seconds, 0 = unknown */
922+ long long expires_in_sec; /* negative when expired, 0 when unknown */
923+} account_t;
924+
925+typedef struct {
926+ int logged_in;
927+ int has_refresh;
928+ int pending;
929+ int expired;
930+ int cli_present;
931+ int cli_ran;
932+ int profile_exists;
933+ int api_key_present;
934+ char account[NAME_SZ];
935+ char path[PATH_SZ];
936+ char profile[NAME_SZ];
937+ char profile_file[PATH_SZ];
938+ char account_id[NAME_SZ];
939+ char cli_error[FIELD_SZ];
940+ long long expires_at; /* unix seconds, 0 = unknown */
941+ long long expires_in_sec; /* long long on purpose: a 32-bit int
942+ * overflows past 2038 and turns a live
943+ * session into "expired 60 years ago" */
944+ long long last_refresh; /* unix seconds, 0 = unknown */
945+ long long pending_age; /* seconds since the marker was written, -1 */
946+ account_t accounts[MAX_ACCOUNTS];
947+ int account_count;
948+} status_t;
949+
950+/* Parse one credentials file (the default file and every named account file
951+ * share this shape):
952+ *
953+ * {"OPENAI_API_KEY": null,
954+ * "tokens": {"id_token":"...","access_token":"...","refresh_token":"...",
955+ * "account_id":"..."},
956+ * "last_refresh":"2026-06-12T03:46:19.123456Z"}
957+ *
958+ * The tokens live inside "tokens", so the slice handed to the readers is the
959+ * tokens object, not the document: matching at document level would find
960+ * nothing and report a live session as "not connected". */
961+static void scan_creds(const char *json, status_t *st, account_t *acc)
962+{
963+ const char *tok, *tokend;
964+ const char *docend;
965+ char acctbuf[NAME_SZ] = {0};
966+ char access[4096];
967+ long long exp = 0;
968+
969+ if (!json) return;
970+ docend = json + strlen(json);
971+
972+ tok = json_find_key(json, docend, "tokens");
973+ if (!tok || !json_obj_slice(tok, docend, &tok, &tokend)) {
974+ /* A flat file (some fixtures put the tokens at the top level) is still
975+ * a session if an access token is there, so fall back to the document. */
976+ tok = json;
977+ tokend = docend;
978+ }
979+
980+ if (json_str_field(tok, tokend, "access_token", access, sizeof(access))) {
981+ exp = jwt_exp_seconds(access);
982+ st->logged_in = 1;
983+ } else {
984+ /* Presence without copying: a token can be several kilobytes and the
985+ * account list keeps one entry per file, so a 4 KB scratch buffer per
986+ * file would be wasteful. */
987+ if (json_str_present(tok, tokend, "access_token")) st->logged_in = 1;
988+ }
989+ if (json_str_present(tok, tokend, "refresh_token")) {
990+ st->has_refresh = 1;
991+ if (acc) acc->has_refresh = 1;
992+ }
993+ if (json_str_field(tok, tokend, "account_id", acctbuf, sizeof(acctbuf)) && acctbuf[0])
994+ snprintf(st->account_id, sizeof(st->account_id), "%s", acctbuf);
995+ if (json_str_present(tok, tokend, "OPENAI_API_KEY") ||
996+ json_str_present(json, docend, "OPENAI_API_KEY"))
997+ st->api_key_present = 1;
998+
999+ if (exp > 0) st->expires_at = exp;
1000+ {
1001+ char iso[64] = {0};
1002+ if (json_str_field(json, docend, "last_refresh", iso, sizeof(iso))) {
1003+ long long lr = iso8601_to_sec(iso);
1004+ if (lr > 0) st->last_refresh = lr;
1005+ }
1006+ }
1007+ if (acc) {
1008+ acc->logged_in = st->logged_in;
1009+ acc->expires_at = st->expires_at;
1010+ }
1011+}
1012+
1013+/* Read the profile file the login CLI creates (--create-profile). */
1014+static void scan_profile(status_t *st)
1015+{
1016+ char *text;
1017+
1018+ profile_path(st->profile_file, sizeof(st->profile_file));
1019+ st->profile_exists = file_exists(st->profile_file);
1020+ if (!st->profile_exists) return;
1021+ snprintf(st->profile, sizeof(st->profile), "codex");
1022+
1023+ text = read_file(st->profile_file);
1024+ if (!text) return;
1025+ {
1026+ const char *p = text;
1027+ while (*p) {
1028+ if (strncmp(p, "CODEX_ACCOUNT=", 12) == 0) {
1029+ size_t i = 0;
1030+ p += 12;
1031+ while (*p && *p != '\n' && *p != '\r' && i + 1 < sizeof(st->account))
1032+ st->account[i++] = *p++;
1033+ st->account[i] = '\0';
1034+ break;
1035+ }
1036+ while (*p && *p != '\n') p++;
1037+ if (*p) p++;
1038+ }
1039+ }
1040+ free(text);
1041+}
1042+
1043+/* List the json files under ~/.codex/accounts. Each has the same shape as auth.json, so
1044+ * the same reader is reused; the file name is the account name. */
1045+static void scan_accounts(status_t *st, long long now_sec)
1046+{
1047+ char d[PATH_SZ];
1048+
1049+ st->account_count = 0;
1050+ accounts_dir(d, sizeof(d));
1051+
1052+#if defined(_WIN32)
1053+ {
1054+ char pattern[PATH_SZ];
1055+ WIN32_FIND_DATAA fd;
1056+ HANDLE h;
1057+
1058+ snprintf(pattern, sizeof(pattern), "%s\\*.json", d);
1059+ h = FindFirstFileA(pattern, &fd);
1060+ if (h == INVALID_HANDLE_VALUE) return;
1061+ do {
1062+ size_t ln;
1063+ account_t *a;
1064+ char p[PATH_SZ];
1065+ char *json;
1066+
1067+ ln = strlen(fd.cFileName);
1068+ if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
1069+ if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
1070+ a = &st->accounts[st->account_count];
1071+ memset(a, 0, sizeof(*a));
1072+ snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName);
1073+ if (!name_valid(a->name)) continue;
1074+ snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, fd.cFileName);
1075+ a->present = 1;
1076+ json = read_file(p);
1077+ if (json) {
1078+ status_t tmp;
1079+ memset(&tmp, 0, sizeof(tmp));
1080+ scan_creds(json, &tmp, a);
1081+ free(json);
1082+ a->expires_at = tmp.expires_at;
1083+ }
1084+ if (a->expires_at > 0 && a->logged_in) {
1085+ a->expires_in_sec = a->expires_at - now_sec;
1086+ a->expired = a->expires_in_sec <= 0;
1087+ }
1088+ st->account_count++;
1089+ } while (FindNextFileA(h, &fd));
1090+ FindClose(h);
1091+ }
1092+#else
1093+ {
1094+ DIR *dp = opendir(d);
1095+ struct dirent *de;
1096+
1097+ if (!dp) return;
1098+ while ((de = readdir(dp)) != NULL) {
1099+ size_t ln = strlen(de->d_name);
1100+ account_t *a;
1101+ char p[PATH_SZ];
1102+ char *json;
1103+
1104+ if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
1105+ if (strcmp(de->d_name + ln - 5, ".json") != 0) continue;
1106+ a = &st->accounts[st->account_count];
1107+ memset(a, 0, sizeof(*a));
1108+ snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), de->d_name);
1109+ if (!name_valid(a->name)) continue;
1110+ snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, de->d_name);
1111+ a->present = 1;
1112+ json = read_file(p);
1113+ if (json) {
1114+ status_t tmp;
1115+ memset(&tmp, 0, sizeof(tmp));
1116+ scan_creds(json, &tmp, a);
1117+ free(json);
1118+ a->expires_at = tmp.expires_at;
1119+ }
1120+ if (a->expires_at > 0 && a->logged_in) {
1121+ a->expires_in_sec = a->expires_at - now_sec;
1122+ a->expired = a->expires_in_sec <= 0;
1123+ }
1124+ st->account_count++;
1125+ }
1126+ closedir(dp);
1127+ }
1128+#endif
1129+}
1130+
1131+/* Ask the login CLI what it sees, and let it ADD to what the files already
1132+ * proved. The file-derived values win where they disagree: the CLI reports
1133+ * expires_at 0 because auth.json has no expiry field, so a CLI answer of 0
1134+ * must never clear a countdown this plugin computed from the token itself. */
1135+static void scan_cli(status_t *st, const char *name)
1136+{
1137+ buf_t out;
1138+ const char *j;
1139+ char args[NAME_SZ + 32];
1140+
1141+ buf_init(&out);
1142+ if (name && *name) snprintf(args, sizeof(args), "--status --name %s", name);
1143+ else snprintf(args, sizeof(args), "--status");
1144+
1145+ {
1146+ int rc = run_capture(login_bin(), args, &out);
1147+ if (rc <= 0) {
1148+ st->cli_present = 0;
1149+ st->cli_ran = 0;
1150+ snprintf(st->cli_error, sizeof(st->cli_error), "%s",
1151+ rc == -1 ? "the login CLI is not on this node"
1152+ : "could not start the login CLI");
1153+ buf_free(&out);
1154+ return;
1155+ }
1156+ }
1157+ st->cli_ran = 1;
1158+
1159+ j = last_json_line(&out);
1160+ if (!j) {
1161+ st->cli_present = 1;
1162+ buf_free(&out);
1163+ return;
1164+ }
1165+ st->cli_present = 1;
1166+ {
1167+ const char *end = j + strlen(j);
1168+ long long e;
1169+ char acct[NAME_SZ] = {0};
1170+
1171+ if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1;
1172+ if (json_bool_field(j, end, "has_refresh", 0)) st->has_refresh = 1;
1173+ if (json_bool_field(j, end, "pending", 0)) st->pending = 1;
1174+ e = json_num_field(j, end, "expires_at");
1175+ if (e > 0) {
1176+ long long sec = (e > 100000000000LL) ? (e / 1000) : e;
1177+ if (st->expires_at == 0 || sec > st->expires_at) st->expires_at = sec;
1178+ }
1179+ if (json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0])
1180+ snprintf(st->account, sizeof(st->account), "%s", acct);
1181+ if (!json_bool_field(j, end, "ok", 1))
1182+ json_str_field(j, end, "error", st->cli_error, sizeof(st->cli_error));
1183+ }
1184+ buf_free(&out);
1185+}
1186+
1187+static void collect_status(status_t *st, const char *name)
1188+{
1189+ char *json;
1190+ long long now_sec = (long long)time(NULL);
1191+
1192+ memset(st, 0, sizeof(*st));
1193+ st->pending_age = -1;
1194+
1195+ /* A named account lives in ~/.codex/accounts/<name>.json, which is the
1196+ * same schema as the default credentials file. */
1197+ if (name && *name) {
1198+ char p[PATH_SZ];
1199+ account_path(name, p, sizeof(p));
1200+ snprintf(st->path, sizeof(st->path), "%s", p);
1201+ snprintf(st->account, sizeof(st->account), "%s", name);
1202+ } else {
1203+ creds_path(st->path, sizeof(st->path));
1204+ }
1205+
1206+ json = read_file(st->path);
1207+ if (json) {
1208+ scan_creds(json, st, NULL);
1209+ free(json);
1210+ }
1211+
1212+ scan_cli(st, name);
1213+ scan_profile(st);
1214+
1215+ /* The pending marker is the only evidence available without a network, and
1216+ * it carries the CLI's own creation stamp, so the TTL is applied here
1217+ * rather than trusting a later claim. */
1218+ {
1219+ char pp[PATH_SZ];
1220+ pending_path(name, pp, sizeof(pp));
1221+ if (file_exists(pp)) {
1222+ char *pend = read_file(pp);
1223+ long long created = 0;
1224+ if (pend) {
1225+ const char *pe = pend + strlen(pend);
1226+ created = json_num_field(pend, pe, "created");
1227+ free(pend);
1228+ }
1229+ if (created > 0) {
1230+ st->pending_age = now_sec - created;
1231+ st->pending = (st->pending_age >= 0 && st->pending_age <= PENDING_TTL_SEC);
1232+ } else {
1233+ st->pending = 1; /* unreadable marker: assume still open */
1234+ }
1235+ }
1236+ }
1237+
1238+ if (st->expires_at > 0) {
1239+ st->expires_in_sec = st->expires_at - now_sec;
1240+ st->expired = st->expires_in_sec <= 0;
1241+ }
1242+ if (!st->logged_in) {
1243+ st->expired = 0;
1244+ st->expires_in_sec = 0;
1245+ }
1246+ if (!st->account[0] && st->logged_in)
1247+ snprintf(st->account, sizeof(st->account), "default");
1248+ if (!st->profile[0] && st->profile_exists)
1249+ snprintf(st->profile, sizeof(st->profile), "codex");
1250+
1251+ scan_accounts(st, now_sec);
1252+}
1253+
1254+/* One status object, shared by every action so the UI always re-renders from
1255+ * the same shape. */
1256+static void emit_status(buf_t *b, const status_t *st)
1257+{
1258+ int i;
1259+
1260+ buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false");
1261+ buf_addf(b, "\"expires_at\":%lld", st->expires_at);
1262+ buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec);
1263+ buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
1264+ buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
1265+ buf_adds(b, ",\"account\":");
1266+ buf_json(b, st->account);
1267+ buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
1268+ buf_addf(b, ",\"pending_age_sec\":%lld", st->pending_age);
1269+ buf_addf(b, ",\"last_refresh\":%lld", st->last_refresh);
1270+ buf_adds(b, ",\"account_id\":");
1271+ buf_json(b, st->account_id);
1272+ buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false");
1273+ buf_adds(b, ",\"credentials_path\":");
1274+ buf_json(b, st->path);
1275+ buf_adds(b, ",\"profile\":");
1276+ buf_json(b, st->profile);
1277+ buf_addf(b, ",\"profile_exists\":%s", st->profile_exists ? "true" : "false");
1278+ buf_addf(b, ",\"named_accounts\":%s", st->account_count > 0 ? "true" : "false");
1279+ buf_addf(b, ",\"api_key_present\":%s", st->api_key_present ? "true" : "false");
1280+ buf_adds(b, ",\"cli_error\":");
1281+ buf_json(b, st->cli_error);
1282+
1283+ buf_adds(b, ",\"accounts\":[");
1284+ for (i = 0; i < st->account_count; i++) {
1285+ const account_t *a = &st->accounts[i];
1286+ if (i) buf_addc(b, ',');
1287+ buf_adds(b, "{\"name\":");
1288+ buf_json(b, a->name);
1289+ buf_addf(b, ",\"logged_in\":%s", a->logged_in ? "true" : "false");
1290+ buf_addf(b, ",\"has_refresh\":%s", a->has_refresh ? "true" : "false");
1291+ buf_addf(b, ",\"expires_at\":%lld", a->expires_at);
1292+ buf_addf(b, ",\"expires_in_sec\":%lld", a->expires_in_sec);
1293+ buf_addf(b, ",\"expired\":%s}", a->expired ? "true" : "false");
1294+ }
1295+ buf_addc(b, ']');
1296+}
1297+
1298+/* ------------------------------------------------------------------ */
1299+/* Actions */
1300+/* ------------------------------------------------------------------ */
1301+
1302+static void json_headers(void)
1303+{
1304+ fputs("Content-Type: application/json; charset=utf-8\r\n"
1305+ "Cache-Control: no-store\r\n"
1306+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1307+}
1308+
1309+static void emit_json(buf_t *b)
1310+{
1311+ json_headers();
1312+ fputs(buf_str(b), stdout);
1313+ buf_free(b);
1314+}
1315+
1316+static void emit_error(int code, const char *status, const char *err, const char *detail)
1317+{
1318+ buf_t b;
1319+
1320+ buf_init(&b);
1321+ buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n"
1322+ "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",
1323+ code, status);
1324+ buf_adds(&b, "{\"ok\":false,\"error\":");
1325+ buf_json(&b, err);
1326+ if (detail && *detail) {
1327+ buf_adds(&b, ",\"detail\":");
1328+ buf_json(&b, detail);
1329+ }
1330+ buf_adds(&b, "}\n");
1331+ json_headers();
1332+ fputs(buf_str(&b), stdout);
1333+ buf_free(&b);
1334+}
1335+
1336+/* Build "<flag> --name <q>" once, so every action addresses the same account. */
1337+static void account_args(const char *name, const char *flag, char *out, size_t n)
1338+{
1339+ if (name && *name) {
1340+ char qname[NAME_SZ * 2];
1341+ shell_quote_into(name, qname, sizeof(qname));
1342+ snprintf(out, n, "%s --name %s", flag, qname);
1343+ } else {
1344+ snprintf(out, n, "%s", flag);
1345+ }
1346+}
1347+
1348+static int action_status(const char *name)
1349+{
1350+ status_t st;
1351+ buf_t b;
1352+
1353+ collect_status(&st, name);
1354+ buf_init(&b);
1355+ buf_adds(&b, "{\"ok\":true,\"state\":\"done\",");
1356+ emit_status(&b, &st);
1357+ buf_adds(&b, "}\n");
1358+ emit_json(&b);
1359+ return 0;
1360+}
1361+
1362+static int action_start(const char *name, int force)
1363+{
1364+ status_t st;
1365+ buf_t in, out;
1366+ const char *j;
1367+ char args[NAME_SZ * 2 + 40];
1368+ char verify[URL_SZ] = {0};
1369+ char code[CODE_SZ] = {0};
1370+ char err[FIELD_SZ] = {0};
1371+ char detail[FIELD_SZ] = {0};
1372+ long long expires_in = PENDING_TTL_SEC;
1373+ int interval = 5;
1374+ int rc;
1375+
1376+ collect_status(&st, name);
1377+ if (!st.cli_present) {
1378+ emit_error(200, "OK", "cli_unavailable",
1379+ "scorpiox-codex-login is not on this node; install SCORPIOX CODE "
1380+ "or set CODEX_LOGIN_BIN");
1381+ return 0;
1382+ }
1383+
1384+ account_args(name, force ? "--start --force" : "--start", args, sizeof(args));
1385+ buf_init(&in);
1386+ rc = run_capture(login_bin(), args, &in);
1387+ if (rc <= 0) {
1388+ buf_free(&in);
1389+ emit_error(rc == -1 ? 200 : 500, rc == -1 ? "OK" : "Internal Server Error",
1390+ "cli_unavailable", "could not run the login CLI");
1391+ return 0;
1392+ }
1393+ j = last_json_line(&in);
1394+ if (!j) {
1395+ buf_free(&in);
1396+ emit_error(502, "Bad Gateway", "start_failed",
1397+ "the login CLI produced no JSON; check its output");
1398+ return 1;
1399+ }
1400+ {
1401+ const char *je = j + strlen(j);
1402+ if (!json_bool_field(j, je, "ok", 1)) {
1403+ json_str_field(j, je, "error", err, sizeof(err));
1404+ json_str_field(j, je, "detail", detail, sizeof(detail));
1405+ buf_free(&in);
1406+ if (strcmp(err, "exists") == 0) {
1407+ /* Credentials are already on this node: the honest answer is
1408+ * "already signed in, press re-login to replace them". */
1409+ buf_init(&out);
1410+ buf_adds(&out, "{\"ok\":true,\"already_logged_in\":true,\"pending\":false");
1411+ buf_adds(&out, ",\"error\":\"already_logged_in\"");
1412+ buf_adds(&out, ",\"detail\":");
1413+ buf_json(&out, detail[0] ? detail : "credentials already exist");
1414+ buf_adds(&out, ",\"logged_in\":");
1415+ buf_adds(&out, st.logged_in ? "true" : "false");
1416+ buf_adds(&out, ",\"hint\":\"pass force=1 to replace the existing session\"}\n");
1417+ emit_json(&out);
1418+ return 0;
1419+ }
1420+ emit_error(200, "OK", err[0] ? err : "start_failed", detail);
1421+ return 0;
1422+ }
1423+ json_str_field(j, je, "verify_url", verify, sizeof(verify));
1424+ json_str_field(j, je, "user_code", code, sizeof(code));
1425+ interval = (int)json_num_field(j, je, "interval");
1426+ expires_in = json_num_field(j, je, "expires_in");
1427+ if (interval < 1) interval = 5;
1428+ if (expires_in <= 0) expires_in = PENDING_TTL_SEC;
1429+ }
1430+ buf_free(&in);
1431+
1432+ if (!verify[0] || !code[0]) {
1433+ emit_error(502, "Bad Gateway", "start_incomplete",
1434+ "login CLI did not return a verify url and user code");
1435+ return 1;
1436+ }
1437+
1438+ buf_init(&out);
1439+ buf_addf(&out, "{\"ok\":true,\"flow\":\"device_code\",\"verify_url\":");
1440+ buf_json(&out, verify);
1441+ buf_adds(&out, ",\"user_code\":");
1442+ buf_json(&out, code);
1443+ buf_addf(&out, ",\"expires_in\":%lld", expires_in);
1444+ buf_addf(&out, ",\"interval\":%d", interval);
1445+ buf_adds(&out, ",\"pending\":true");
1446+ buf_adds(&out, ",\"provider\":\"codex\"}\n");
1447+ emit_json(&out);
1448+ return 0;
1449+}
1450+
1451+/* One non-blocking poll. The CLI does exactly one HTTPS round trip and returns;
1452+ * the UI drives the cadence so nothing here ever blocks. */
1453+static int action_poll(const char *name)
1454+{
1455+ status_t st;
1456+ buf_t in, out;
1457+ const char *j;
1458+ char state[64] = {0};
1459+ char args[NAME_SZ * 2 + 16];
1460+ int rc;
1461+
1462+ collect_status(&st, name);
1463+ if (!st.cli_present) {
1464+ emit_error(200, "OK", "cli_unavailable",
1465+ "scorpiox-codex-login is not on this node");
1466+ return 0;
1467+ }
1468+
1469+ account_args(name, "--poll", args, sizeof(args));
1470+ buf_init(&in);
1471+ rc = run_capture(login_bin(), args, &in);
1472+ if (rc < 0) {
1473+ buf_free(&in);
1474+ emit_error(200, "OK", "cli_unavailable",
1475+ "scorpiox-codex-login is not on this node");
1476+ return 0;
1477+ }
1478+ if (rc == 0) {
1479+ buf_free(&in);
1480+ emit_error(500, "Internal Server Error", "poll_failed", "cannot spawn login CLI");
1481+ return 1;
1482+ }
1483+
1484+ j = last_json_line(&in);
1485+ if (!j) {
1486+ buf_free(&in);
1487+ /* No JSON at all. Fall back to what the files say: a credential file
1488+ * that appeared while polling is a success no matter what the CLI
1489+ * printed, and a marker that vanished with no credentials is a dead
1490+ * flow, not an infinite spinner. */
1491+ if (st.logged_in) {
1492+ buf_init(&out);
1493+ buf_adds(&out, "{\"ok\":true,\"state\":\"done\",");
1494+ emit_status(&out, &st);
1495+ buf_adds(&out, "}\n");
1496+ emit_json(&out);
1497+ return 0;
1498+ }
1499+ emit_error(502, "Bad Gateway", "poll_failed", "login CLI produced no JSON");
1500+ return 1;
1501+ }
1502+ {
1503+ const char *je = j + strlen(j);
1504+ json_str_field(j, je, "state", state, sizeof(state));
1505+ if (!json_bool_field(j, je, "ok", 0)) {
1506+ char err[FIELD_SZ] = {0};
1507+ char detail[FIELD_SZ] = {0};
1508+ json_str_field(j, je, "error", err, sizeof(err));
1509+ json_str_field(j, je, "detail", detail, sizeof(detail));
1510+ buf_free(&in);
1511+ /* expired / no_pending / denied are terminal, not transient. */
1512+ buf_init(&out);
1513+ buf_adds(&out, "{\"ok\":true,\"state\":\"failed\"");
1514+ buf_adds(&out, ",\"error\":");
1515+ buf_json(&out, err[0] ? err : "poll_failed");
1516+ if (detail[0]) {
1517+ buf_adds(&out, ",\"detail\":");
1518+ buf_json(&out, detail);
1519+ }
1520+ buf_adds(&out, ",\"pending\":false}\n");
1521+ emit_json(&out);
1522+ return 0;
1523+ }
1524+ if (strcmp(state, "pending") == 0) {
1525+ long long iv = json_num_field(j, je, "interval");
1526+ buf_free(&in);
1527+ buf_init(&out);
1528+ buf_adds(&out, "{\"ok\":true,\"state\":\"pending\"");
1529+ buf_addf(&out, ",\"interval\":%d", iv > 0 ? (int)iv : 5);
1530+ buf_adds(&out, ",\"pending\":true");
1531+ {
1532+ status_t after;
1533+ collect_status(&after, name);
1534+ if (after.logged_in) {
1535+ /* The CLI still says pending but the file is there: report
1536+ * the truth the file tells. */
1537+ buf_adds(&out, ",\"logged_in\":true");
1538+ }
1539+ }
1540+ buf_adds(&out, "}\n");
1541+ emit_json(&out);
1542+ return 0;
1543+ }
1544+ /* state == "done" */
1545+ buf_free(&in);
1546+ {
1547+ status_t after;
1548+ collect_status(&after, name);
1549+ buf_init(&out);
1550+ buf_adds(&out, "{\"ok\":true,\"state\":\"done\",");
1551+ emit_status(&out, &after);
1552+ buf_adds(&out, "}\n");
1553+ emit_json(&out);
1554+ }
1555+ return 0;
1556+ }
1557+}
1558+
1559+static int action_cancel(const char *name)
1560+{
1561+ status_t st;
1562+ buf_t in, out;
1563+ char args[NAME_SZ * 2 + 16];
1564+
1565+ collect_status(&st, name);
1566+ if (!st.cli_present) {
1567+ /* Nothing to abort and no CLI to tell: drop the marker ourselves so the
1568+ * UI spinner stops on a node without SCORPIOX CODE. */
1569+ char pp[PATH_SZ];
1570+ pending_path(name, pp, sizeof(pp));
1571+ if (file_exists(pp)) remove(pp);
1572+ buf_init(&out);
1573+ buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false,"
1574+ "\"cli_present\":false}\n");
1575+ emit_json(&out);
1576+ return 0;
1577+ }
1578+
1579+ account_args(name, "--cancel", args, sizeof(args));
1580+ buf_init(&in);
1581+ {
1582+ int rc = run_capture(login_bin(), args, &in);
1583+ if (rc < 0) {
1584+ buf_free(&in);
1585+ emit_error(200, "OK", "cli_unavailable",
1586+ "scorpiox-codex-login is not on this node");
1587+ return 0;
1588+ }
1589+ {
1590+ const char *j = last_json_line(&in);
1591+ int ok = 1;
1592+ if (j) {
1593+ const char *je = j + strlen(j);
1594+ ok = json_bool_field(j, je, "ok", 1);
1595+ }
1596+ buf_free(&in);
1597+ if (!ok) {
1598+ emit_error(200, "OK", "cancel_failed", "login CLI rejected the cancel");
1599+ return 0;
1600+ }
1601+ /* The CLI removes the marker; re-collect to report the truth. */
1602+ {
1603+ status_t after;
1604+ collect_status(&after, name);
1605+ buf_init(&out);
1606+ buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",");
1607+ emit_status(&out, &after);
1608+ buf_adds(&out, "}\n");
1609+ emit_json(&out);
1610+ }
1611+ }
1612+ }
1613+ return 0;
1614+}
1615+
1616+/* Refresh: the refresh CLI performs the refresh-token grant and updates the
1617+ * credential file in place. Its stdout is human text (and with --verbose may
1618+ * quote token material), so the payload is read, then discarded. The new state
1619+ * is proven by re-reading the file, not by the CLI's word. */
1620+static int action_refresh(const char *name)
1621+{
1622+ buf_t out, b;
1623+ char args[PATH_SZ + 96];
1624+ char qpath[PATH_SZ * 2];
1625+ char path[PATH_SZ];
1626+ long long before;
1627+ status_t st;
1628+
1629+ active_creds_path(name, path, sizeof(path));
1630+
1631+ if (!file_exists(path)) {
1632+ buf_init(&b);
1633+ buf_adds(&b, "{\"ok\":false,\"error\":\"no_credentials\",\"detail\":");
1634+ buf_json(&b, "there is no credential file for this account on this node; "
1635+ "start a login first");
1636+ buf_adds(&b, "}\n");
1637+ emit_json(&b);
1638+ return 1;
1639+ }
1640+
1641+ collect_status(&st, name);
1642+ before = st.expires_at;
1643+
1644+ shell_quote_into(path, qpath, sizeof(qpath));
1645+ /* action=refresh means "refresh now", so the CLI is always invoked with
1646+ * --force: without it the CLI no-ops on a still-valid token and the user's
1647+ * button does nothing. */
1648+ snprintf(args, sizeof(args), "--credentials-file %s --force", qpath);
1649+
1650+ buf_init(&out);
1651+ {
1652+ int rc = run_capture(refresh_bin(), args, &out);
1653+ if (rc <= 0) {
1654+ buf_free(&out);
1655+ emit_error(200, "OK", "cli_unavailable",
1656+ "the refresh CLI is not on this node; install SCORPIOX CODE "
1657+ "or set CODEX_REFRESH_BIN");
1658+ return 1;
1659+ }
1660+ }
1661+ buf_free(&out);
1662+
1663+ collect_status(&st, name);
1664+ if (!st.logged_in || (before > 0 && st.expires_at <= before && !st.expired)) {
1665+ buf_init(&b);
1666+ buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":");
1667+ buf_json(&b, "the refresh CLI did not extend the token in the credential "
1668+ "file; sign in again");
1669+ buf_adds(&b, "}\n");
1670+ emit_json(&b);
1671+ return 1;
1672+ }
1673+
1674+ buf_init(&b);
1675+ buf_adds(&b, "{\"ok\":true,\"refreshed\":true,");
1676+ emit_status(&b, &st);
1677+ buf_adds(&b, "}\n");
1678+ emit_json(&b);
1679+ return 0;
1680+}
1681+
1682+/* ------------------------------------------------------------------ */
1683+/* HTML emission */
1684+/* ------------------------------------------------------------------ */
1685+
1686+/* Expand the two placeholders tools/gen_ui.py leaves in UI_HTML. Keeping the
1687+ * split means the palette lives in exactly one place (bot_theme_plugin.h) and
1688+ * the page can never drift away from the bot's own theme. */
1689+static void emit_ui(void)
1690+{
1691+ const char *p = UI_HTML;
1692+
1693+ while (*p) {
1694+ if (*p == '\001') {
1695+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout);
1696+ p++;
1697+ } else if (*p == '\002') {
1698+ /* SX_BOT_THEME_HANDOFF is a complete <script> element, so it is
1699+ * emitted as a sibling of the page's own script. */
1700+ fputs(SX_BOT_THEME_HANDOFF, stdout);
1701+ p++;
1702+ } else {
1703+ fputc(*p, stdout);
1704+ p++;
1705+ }
1706+ }
1707+}
1708+
1709+static void serve_html(void)
1710+{
1711+ const char *qs = getenv("QUERY_STRING");
1712+ int embed = (qs && (strstr(qs, "embed=1") || strstr(qs, "embed=true")));
1713+
1714+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1715+ "Cache-Control: no-store\r\n"
1716+ "X-Content-Type-Options: nosniff\r\n"
1717+ "X-Frame-Options: SAMEORIGIN\r\n"
1718+ "Referrer-Policy: same-origin\r\n\r\n", stdout);
1719+
1720+ /* The embed flag (?embed=1) is handled inside the page itself: the theme
1721+ * prepaint script that comes from bot_theme_plugin.h reads it before the
1722+ * first frame and marks <html> as embedded, which is what hides the back
1723+ * link and the theme toggle. Nothing to do here but keep the header. */
1724+ (void)embed;
1725+ emit_ui();
1726+}
1727+
1728+/* ------------------------------------------------------------------ */
1729+/* Entry point */
1730+/* ------------------------------------------------------------------ */
1731+
1732+int main(int argc, char **argv)
1733+{
1734+ const char *qs;
1735+ char action[64] = {0};
1736+ char account[NAME_SZ] = {0};
1737+ char fmt[32] = {0};
1738+
1739+ /* 1. Discovery metadata. Must stay unauthenticated. */
1740+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1741+ puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}");
1742+ return 0;
1743+ }
1744+ if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
1745+ puts(PLUGIN_ID " " PLUGIN_VER);
1746+ return 0;
1747+ }
1748+
1749+ require_node_auth();
1750+
1751+ qs = getenv("QUERY_STRING");
1752+ if (!qs) qs = "";
1753+
1754+ /* 2. JSON API mode. `format=json` alone means "status", which is what a
1755+ * dashboard polls. */
1756+ if (query_has(qs, "action") || query_has(qs, "format")) {
1757+ int force = 0;
1758+
1759+ get_query_val(qs, "action", action, sizeof(action));
1760+ get_query_val(qs, "format", fmt, sizeof(fmt));
1761+ {
1762+ char f[16] = {0};
1763+ if (get_query_val(qs, "force", f, sizeof(f)) &&
1764+ (strcmp(f, "1") == 0 || strcmp(f, "true") == 0))
1765+ force = 1;
1766+ }
1767+ resolve_account(qs, account, sizeof(account));
1768+
1769+ if (!action[0] && strcmp(fmt, "json") == 0)
1770+ snprintf(action, sizeof(action), "status");
1771+
1772+ if (strcmp(action, "status") == 0 || !action[0]) return action_status(account);
1773+ if (strcmp(action, "start") == 0) return action_start(account, force);
1774+ if (strcmp(action, "poll") == 0) return action_poll(account);
1775+ if (strcmp(action, "cancel") == 0) return action_cancel(account);
1776+ if (strcmp(action, "refresh") == 0) return action_refresh(account);
1777+ if (strcmp(action, "accounts") == 0) return action_status(account);
1778+
1779+ emit_error(400, "Bad Request", "unknown_action",
1780+ "expected status, start, poll, cancel, refresh or accounts");
1781+ return 1;
1782+ }
1783+
1784+ /* 3. HTML UI */
1785+ serve_html();
1786+ return 0;
1787+}
src/ui.html+452−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..5598c79index 0000000..5598c79
--- /dev/null--- /dev/null
+++ b/src/ui.html+++ b/src/ui.html
@@ -0,0 +1,452 @@@@ -0,0 +1,452 @@
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>codex</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+.count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}
53+.count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}
54+.bar{height:6px;border-radius:999px;background:var(--surface-2);overflow:hidden;margin-top:10px}
55+.bar .fill{display:block;height:100%;background:var(--green);border-radius:999px;
56+ transition:width .3s var(--ease)}
57+.bar.warn .fill{background:var(--orange)}
58+.bar.err .fill{background:var(--red)}
59+.codebox{margin:12px 0 0;padding:16px;border-radius:12px;background:var(--code-bg);
60+ border:1px solid var(--line);text-align:center}
61+.codebox .code{font-family:var(--mono);font-size:30px;font-weight:700;letter-spacing:.14em;
62+ color:var(--text);margin-bottom:10px;word-break:break-all}
63+.codebox .code-empty{font-family:var(--mono);font-size:18px;color:var(--text-2);
64+ letter-spacing:.08em}
65+.authurl{font-family:var(--mono);font-size:11.5px;color:var(--text-2);word-break:break-all;
66+ background:var(--code-bg);border:1px solid var(--line);border-radius:10px;
67+ padding:10px;margin-top:10px;max-height:120px;overflow:auto}
68+.pollbar{margin:12px 0 0;height:3px;border-radius:2px;background:var(--surface-2);
69+ overflow:hidden}
70+.pollbar i{display:block;height:100%;width:0;background:var(--blue);
71+ animation:pollslide 2s linear infinite}
72+@keyframes pollslide{0%{width:0}50%{width:100%}100%{width:0}}
73+.polllbl{font-size:11.5px;color:var(--text-2);margin:8px 0 0;display:flex;align-items:center;gap:6px}
74+.polllbl .spin{width:10px;height:10px;border-radius:50%;border:2px solid var(--line-2);
75+ border-top-color:var(--blue);animation:spin 1s linear infinite;display:inline-block}
76+@keyframes spin{to{transform:rotate(360deg)}}
77+.acct{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--line);
78+ font-size:13px;flex-wrap:wrap}
79+.acct:first-of-type{border-top:0}
80+.acct .nm{font-family:var(--mono);font-size:12px;flex:1 1 120px;min-width:0;
81+ overflow:hidden;text-overflow:ellipsis}
82+.acct .tag{font-size:11px;color:var(--text-2)}
83+.acct .tag.ok{color:var(--green)}
84+.acct .tag.warn{color:var(--orange)}
85+.empty{padding:10px 0;color:var(--text-2);font-size:12.5px}
86+.toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;
87+ pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);
88+ color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;
89+ box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);
90+ z-index:9;max-width:calc(100vw - 32px)}
91+.toast.show{opacity:1;transform:translate(-50%,0)}
92+#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);
93+ border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;
94+ font-family:inherit}
95+footer{display:flex;gap:10px;align-items:center;color:var(--text-2);font-size:11.5px;
96+ margin-top:8px;flex-wrap:wrap}
97+@media (max-width:520px){
98+ #app{padding:12px 12px 32px}
99+ .kv{grid-template-columns:1fr;gap:2px 0}
100+ .kv .k{margin-top:8px}
101+ .card{padding:13px;border-radius:12px}
102+ .count{font-size:28px}
103+ .codebox .code{font-size:22px;letter-spacing:.1em}
104+}
105+</style>
106+</head>
107+<body>
108+<div id="app">
109+ <div class="hd">
110+ <div class="grow">
111+ <h1>OpenAI Codex</h1>
112+ <div class="sub" id="sub">Device code login on this node</div>
113+ </div>
114+ <span class="pill off" id="pill"><span class="dot"></span><span id="pillText">Checking</span></span>
115+ <button id="themeToggle" class="embed-hide" type="button">Theme</button>
116+ </div>
117+
118+ <div class="card">
119+ <h2>Session</h2>
120+ <p class="lead" id="sessionLead">Reading the local Codex credentials.</p>
121+ <div class="count" id="count">-</div>
122+ <div class="bar" id="bar"><span class="fill" id="fill" style="width:0%"></span></div>
123+ <div class="kv" id="session" style="margin-top:14px"></div>
124+ <div class="row" style="margin-top:14px">
125+ <button class="btn ghost" id="btnRefresh" type="button">Refresh Token Now</button>
126+ <button class="btn ghost" id="btnStartLogin" type="button">Start Codex Login</button>
127+ <button class="btn ghost" id="btnRelogin" type="button" hidden>Re-login (replace)</button>
128+ <button class="btn ghost" id="btnReload" type="button">Reload</button>
129+ </div>
130+ <div class="note" id="sessionNote"></div>
131+ </div>
132+
133+ <div class="card">
134+ <h2>Device flow</h2>
135+ <p class="lead">Codex signs in with a one-time user code. Copy it, open the link, approve,
136+ and this panel updates itself.</p>
137+
138+ <div class="step on" id="stepIdle">
139+ <div class="empty">No login in progress. Press <b>Start Codex Login</b> above to begin.</div>
140+ </div>
141+
142+ <div class="step" id="stepActive">
143+ <div class="codebox">
144+ <div class="code" id="userCode">--</div>
145+ <div class="row" style="justify-content:center">
146+ <button class="btn" id="btnCopyOpen" type="button">Copy Code &amp; Open OpenAI</button>
147+ </div>
148+ </div>
149+ <div class="authurl" id="verifyUrl"></div>
150+ <div class="pollbar"><i></i></div>
151+ <div class="polllbl"><span class="spin"></span><span id="pollLabel">Waiting for authorization in browser...</span></div>
152+ <div class="row" style="margin-top:12px">
153+ <button class="btn danger" id="btnCancel" type="button">Cancel</button>
154+ </div>
155+ <div class="note" id="flowNote"></div>
156+ </div>
157+ </div>
158+
159+ <div class="card">
160+ <h2>Named accounts</h2>
161+ <p class="lead">Every account file in the local accounts directory.</p>
162+ <div id="accounts"><div class="empty">No named accounts.</div></div>
163+ </div>
164+
165+ <footer>
166+ <span id="footInfo">plugin_codex_login</span>
167+ &middot; <a href="https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-codex-login">source</a>
168+ </footer>
169+</div>
170+
171+<div class="toast" id="toast"></div>
172+
173+<script>
174+(function(){
175+var q=new URLSearchParams(location.search);
176+var node=q.get('node')||'';
177+var sid=q.get('id')||'';
178+var acct=q.get('account')||'';
179+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
180+ localStorage.getItem('bot_active_pwd')||'';
181+
182+/* Two call routes. Getting this wrong is the most common plugin bug:
183+ * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)
184+ * -> call the hub proxy back: /plugins?plugin=plugin_codex_login&action=..
185+ * opened directly on the node
186+ * -> the plugin itself is the route: /plugin_codex_login?action=..
187+ * Calling /plugins?plugin= on the node returns the discovery list, not us. */
188+var HUB=q.get('plugin')||'';
189+function url(action,extra){
190+ return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_codex_login')+
191+ '?action='+encodeURIComponent(action)+
192+ (extra?('&'+extra):'')+
193+ (acct?'&account='+encodeURIComponent(acct):'')+
194+ (node?'&node='+encodeURIComponent(node):'')+
195+ (sid?'&id='+encodeURIComponent(sid):'')+
196+ (pwd?'&pwd='+encodeURIComponent(pwd):'');
197+}
198+function hdr(){
199+ var h={};
200+ if(pwd)h['X-Bot-Password']=pwd;
201+ return h;
202+}
203+function api(action,extra){
204+ return fetch(url(action,extra),{headers:hdr()}).then(function(r){
205+ return r.json().catch(function(){return {ok:false,error:'bad response'};});
206+ });
207+}
208+
209+var $=function(id){return document.getElementById(id);};
210+function toast(msg){
211+ var t=$('toast');t.textContent=msg;t.classList.add('show');
212+ clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);
213+}
214+function note(el,msg,kind){
215+ el.textContent=msg||'';
216+ el.className='note'+(msg?' show '+(kind||''):'');
217+}
218+function kv(el,rows){
219+ el.innerHTML='';
220+ rows.forEach(function(r){
221+ var a=document.createElement('div');a.className='k';a.textContent=r[0];
222+ var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');
223+ b.textContent=r[1];el.appendChild(a);el.appendChild(b);
224+ });
225+}
226+function fmtExpiry(sec){
227+ if(typeof sec!=='number')return '-';
228+ if(sec<=0)return 'expired';
229+ if(sec<90)return sec+'s';
230+ if(sec<5400)return Math.round(sec/60)+' min';
231+ var h=Math.floor(sec/3600);
232+ if(h<48)return h+' h '+(Math.floor((sec%3600)/60))+' min';
233+ return Math.floor(h/24)+' days';
234+}
235+function fmtClock(sec){
236+ if(typeof sec!=='number'||sec<=0)return '-';
237+ var d=Math.floor(sec/86400),h=Math.floor((sec%86400)/3600),m=Math.floor((sec%3600)/60);
238+ if(d>0)return d+'d '+h+'h';
239+ if(h>0)return h+'h '+m+'m';
240+ return m+'m';
241+}
242+function setPill(cls,text){
243+ $('pill').className='pill '+cls;
244+ $('pillText').textContent=text;
245+}
246+
247+var pollTimer=null;
248+var pollMs=5000;
249+var flowActive=false;
250+var flowVerify='';
251+var flowCode='';
252+
253+function startPollingUI(){
254+ flowActive=true;
255+ $('stepIdle').classList.remove('on');
256+ $('stepActive').classList.add('on');
257+ if(!pollTimer)pollTimer=setInterval(pollOnce,pollMs);
258+}
259+function stopPollingUI(){
260+ flowActive=false;
261+ if(pollTimer){clearInterval(pollTimer);pollTimer=null;}
262+}
263+function pollOnce(){
264+ if(!flowActive)return;
265+ api('poll').then(function(d){
266+ if(!d||d.ok===false){note('flowNote','Poll error: '+(d&&d.error||'unknown'),'err');return;}
267+ if(d.state==='done'||d.logged_in){
268+ stopPollingUI();
269+ $('stepIdle').classList.add('on');
270+ $('stepActive').classList.remove('on');
271+ $('pollLabel').textContent='Signed in';
272+ note('flowNote','Signed in. The credential file has been written.','ok');
273+ load();
274+ }else if(d.state==='failed'){
275+ stopPollingUI();
276+ $('stepIdle').classList.add('on');
277+ $('stepActive').classList.remove('on');
278+ $('pollLabel').textContent='Login failed';
279+ note('flowNote','Login failed: '+(d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');
280+ load();
281+ }else{
282+ $('pollLabel').textContent='Waiting for authorization in browser...';
283+ if(d.interval&&d.interval>0)pollMs=Math.max(1000,d.interval*1000);
284+ if(d.logged_in)load();
285+ }
286+ }).catch(function(e){note('flowNote','Poll request failed: '+e,'err');});
287+}
288+
289+function render(st){
290+ var li=!!st.logged_in, ex=!!st.expired, pend=!!st.pending;
291+ if(li&&!ex)setPill('ok','Logged In');
292+ else if(li&&ex)setPill('warn','Expired');
293+ else if(pend)setPill('warn','Signing In');
294+ else setPill('off','Not Connected');
295+
296+ $('count').innerHTML='';
297+ if(li&&!ex){
298+ var s=document.createElement('span');s.textContent=fmtClock(st.expires_in_sec);
299+ var sm=document.createElement('small');sm.textContent=' remaining';
300+ $('count').appendChild(s);$('count').appendChild(sm);
301+ }else if(li&&ex){
302+ $('count').textContent='Token expired';
303+ }else if(pend){
304+ $('count').textContent='Device flow open';
305+ }else{
306+ $('count').textContent='No Codex session';
307+ }
308+
309+ var total=st.expires_in_sec>0?st.expires_in_sec:0;
310+ var pct=0;
311+ if(li&&total>0){
312+ /* A one-hour token is the norm, so the bar is drawn against the window it
313+ * actually has, capped at 24 h so a long-lived token still fills it. */
314+ var win=total>86400?86400:total;
315+ pct=Math.max(2,Math.min(100,Math.round(100*total/win)));
316+ }
317+ $('fill').style.width=pct+'%';
318+ $('bar').className='bar'+(li&&ex?' err':(li&&pct<20?' warn':''));
319+ if(!li)$('bar').className='bar';
320+
321+ kv($('session'),[
322+ ['Account', st.account||'-', true],
323+ ['Logged in', st.logged_in?'yes':'no', true],
324+ ['Token', st.logged_in?(st.expired?'expired':'valid, '+fmtExpiry(st.expires_in_sec)):'none', true],
325+ ['Refresh token', st.has_refresh?'stored':'none', true],
326+ ['Last refreshed', st.last_refresh?new Date(st.last_refresh*1000).toISOString().replace('T',' ').slice(0,19):'unknown', true],
327+ ['Account id', st.account_id||'-'],
328+ ['Login pending', st.pending?'yes':'no', true],
329+ ['Login CLI', st.cli_present?'found':'not found', true],
330+ ['Profile', st.profile_exists?(st.profile||'codex'):'not created', true],
331+ ['Credentials', st.credentials_path||'-']
332+ ]);
333+
334+ $('btnRelogin').hidden=!li;
335+ $('btnStartLogin').hidden=!!li;
336+
337+ if(!li&&!pend)note('sessionNote','No Codex session on this node yet. Start a device login below.','ok');
338+ else if(li&&ex)note('sessionNote','The token has expired. Press Refresh Token Now, or sign in again.','warn');
339+ else note('sessionNote','');
340+
341+ if(st.cli_present===false)
342+ note('sessionNote','SCORPIOX CODE is not on this node: the login and refresh CLIs cannot be run here.','warn');
343+
344+ var box=$('accounts');
345+ box.innerHTML='';
346+ var list=st.accounts||[];
347+ if(!list.length){
348+ var e=document.createElement('div');e.className='empty';
349+ e.textContent='No named accounts.';box.appendChild(e);
350+ }else{
351+ list.forEach(function(a){
352+ var row=document.createElement('div');row.className='acct';
353+ var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;
354+ var tg=document.createElement('div');
355+ tg.className='tag '+(a.logged_in&&!a.expired?'ok':(a.logged_in?'warn':''));
356+ tg.textContent=a.logged_in?(a.expired?'expired':'valid, '+fmtExpiry(a.expires_in_sec)):'empty';
357+ var bt=document.createElement('button');
358+ bt.className='btn ghost';bt.type='button';bt.textContent='Select';
359+ bt.onclick=function(){acct=a.name;$('sub').textContent='account: '+a.name;load();};
360+ row.appendChild(nm);row.appendChild(tg);row.appendChild(bt);
361+ box.appendChild(row);
362+ });
363+ }
364+ if(!$('sub').textContent||$('sub').textContent==='Device code login on this node'){
365+ $('sub').textContent=(st.account&&st.account!=='default')?('account: '+st.account):'Device code login on this node';
366+ }
367+}
368+
369+function load(){
370+ api('status').then(function(d){
371+ if(!d||d.ok===false){setPill('off','Not Connected');note('sessionNote','Error: '+(d&&d.error||'no response'),'err');return;}
372+ render(d);
373+ if(d.pending&&!flowActive){
374+ /* A flow that was started elsewhere (or before a page reload) should
375+ * still show its spinner; the code itself is not recoverable from the
376+ * marker, so the panel says so rather than pretending. */
377+ $('userCode').textContent='--';
378+ $('verifyUrl').textContent='';
379+ $('pollLabel').textContent='A device flow is already open on this node';
380+ startPollingUI();
381+ }
382+ if(!d.pending&&flowActive)stopPollingUI();
383+ }).catch(function(e){setPill('off','Not Connected');note('sessionNote','Request failed: '+e,'err');});
384+}
385+
386+function doStart(force){
387+ note('sessionNote','');
388+ $('btnStartLogin').disabled=true;
389+ api('start',force?'force=1':'').then(function(d){
390+ $('btnStartLogin').disabled=false;
391+ if(!d||d.ok===false){
392+ note('sessionNote','Start failed: '+(d&&d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');
393+ return;
394+ }
395+ if(d.already_logged_in){
396+ note('sessionNote','This node already has Codex credentials. Use Re-login to replace them.','warn');
397+ load();
398+ return;
399+ }
400+ flowVerify=d.verify_url||'';
401+ flowCode=d.user_code||'';
402+ $('userCode').textContent=flowCode||'--';
403+ $('verifyUrl').textContent=flowVerify;
404+ $('pollLabel').textContent='Waiting for authorization in browser...';
405+ pollMs=Math.max(1000,(d.interval||5)*1000);
406+ note('flowNote','','');
407+ startPollingUI();
408+ load();
409+ }).catch(function(e){$('btnStartLogin').disabled=false;note('sessionNote','Start request failed: '+e,'err');});
410+}
411+
412+$('btnStartLogin').onclick=function(){doStart(false);};
413+$('btnRelogin').onclick=function(){doStart(true);};
414+$('btnReload').onclick=load;
415+$('btnCancel').onclick=function(){
416+ stopPollingUI();
417+ api('cancel').then(function(d){
418+ $('stepIdle').classList.add('on');
419+ $('stepActive').classList.remove('on');
420+ note('flowNote',(d&&d.ok)?'Device flow cancelled.':'Cancel failed: '+((d&&d.error)||'unknown'),
421+ (d&&d.ok)?'ok':'err');
422+ load();
423+ }).catch(function(e){note('flowNote','Cancel request failed: '+e,'err');});
424+};
425+$('btnRefresh').onclick=function(){
426+ note('sessionNote','');
427+ api('refresh').then(function(d){
428+ if(!d||d.ok===false){
429+ note('sessionNote','Refresh failed: '+(d&&d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');
430+ return;
431+ }
432+ note('sessionNote','Token refreshed. New expiry: '+fmtExpiry(d.expires_in_sec)+'.','ok');
433+ render(d);
434+ }).catch(function(e){note('sessionNote','Refresh request failed: '+e,'err');});
435+};
436+$('btnCopyOpen').onclick=function(){
437+ var done=function(){toast('Code copied. Open the link and approve.');};
438+ if(navigator.clipboard&&navigator.clipboard.writeText){
439+ navigator.clipboard.writeText(flowCode).then(done,function(){toast('Copy failed');});
440+ }else{toast('Copy not available');}
441+ if(flowVerify)window.open(flowVerify,'_blank','noopener');
442+};
443+
444+var tb=$('themeToggle');
445+if(tb)tb.onclick=function(){
446+ if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme?window.sxTheme():'light');
447+};
448+$('footInfo').textContent='plugin_codex_login';
449+load();
450+})();
451+</script>
452+</body></html>
src/ui_html.h+460−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..45614dfindex 0000000..45614df
--- /dev/null--- /dev/null
+++ b/src/ui_html.h+++ b/src/ui_html.h
@@ -0,0 +1,460 @@@@ -0,0 +1,460 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_CODEXLOGIN_UI_HTML_H
3+#define SX_CODEXLOGIN_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>codex</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+ ".count{font-size:34px;font-weight:700;letter-spacing:-.02em;line-height:1.1}\n"
58+ ".count small{font-size:13px;font-weight:600;color:var(--text-2);letter-spacing:0}\n"
59+ ".bar{height:6px;border-radius:999px;background:var(--surface-2);overflow:hidden;margin-top:10px}\n"
60+ ".bar .fill{display:block;height:100%;background:var(--green);border-radius:999px;\n"
61+ " transition:width .3s var(--ease)}\n"
62+ ".bar.warn .fill{background:var(--orange)}\n"
63+ ".bar.err .fill{background:var(--red)}\n"
64+ ".codebox{margin:12px 0 0;padding:16px;border-radius:12px;background:var(--code-bg);\n"
65+ " border:1px solid var(--line);text-align:center}\n"
66+ ".codebox .code{font-family:var(--mono);font-size:30px;font-weight:700;letter-spacing:.14em;\n"
67+ " color:var(--text);margin-bottom:10px;word-break:break-all}\n"
68+ ".codebox .code-empty{font-family:var(--mono);font-size:18px;color:var(--text-2);\n"
69+ " letter-spacing:.08em}\n"
70+ ".authurl{font-family:var(--mono);font-size:11.5px;color:var(--text-2);word-break:break-all;\n"
71+ " background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n"
72+ " padding:10px;margin-top:10px;max-height:120px;overflow:auto}\n"
73+ ".pollbar{margin:12px 0 0;height:3px;border-radius:2px;background:var(--surface-2);\n"
74+ " overflow:hidden}\n"
75+ ".pollbar i{display:block;height:100%;width:0;background:var(--blue);\n"
76+ " animation:pollslide 2s linear infinite}\n"
77+ "@keyframes pollslide{0%{width:0}50%{width:100%}100%{width:0}}\n"
78+ ".polllbl{font-size:11.5px;color:var(--text-2);margin:8px 0 0;display:flex;align-items:center;gap:6px}\n"
79+ ".polllbl .spin{width:10px;height:10px;border-radius:50%;border:2px solid var(--line-2);\n"
80+ " border-top-color:var(--blue);animation:spin 1s linear infinite;display:inline-block}\n"
81+ "@keyframes spin{to{transform:rotate(360deg)}}\n"
82+ ".acct{display:flex;align-items:center;gap:10px;padding:8px 0;border-top:1px solid var(--line);\n"
83+ " font-size:13px;flex-wrap:wrap}\n"
84+ ".acct:first-of-type{border-top:0}\n"
85+ ".acct .nm{font-family:var(--mono);font-size:12px;flex:1 1 120px;min-width:0;\n"
86+ " overflow:hidden;text-overflow:ellipsis}\n"
87+ ".acct .tag{font-size:11px;color:var(--text-2)}\n"
88+ ".acct .tag.ok{color:var(--green)}\n"
89+ ".acct .tag.warn{color:var(--orange)}\n"
90+ ".empty{padding:10px 0;color:var(--text-2);font-size:12.5px}\n"
91+ ".toast{position:fixed;left:50%;bottom:18px;transform:translate(-50%,14px);opacity:0;\n"
92+ " pointer-events:none;background:var(--modal-bg);border:1px solid var(--line-2);\n"
93+ " color:var(--text);border-radius:999px;padding:8px 16px;font-size:12.5px;\n"
94+ " box-shadow:var(--shadow-lg);transition:opacity .18s var(--ease),transform .18s var(--ease);\n"
95+ " z-index:9;max-width:calc(100vw - 32px)}\n"
96+ ".toast.show{opacity:1;transform:translate(-50%,0)}\n"
97+ "#themeToggle{background:var(--surface-2);border:1px solid var(--line);color:var(--text);\n"
98+ " border-radius:980px;padding:5px 12px;font-size:12px;font-weight:600;cursor:pointer;\n"
99+ " font-family:inherit}\n"
100+ "footer{display:flex;gap:10px;align-items:center;color:var(--text-2);font-size:11.5px;\n"
101+ " margin-top:8px;flex-wrap:wrap}\n"
102+ "@media (max-width:520px){\n"
103+ " #app{padding:12px 12px 32px}\n"
104+ " .kv{grid-template-columns:1fr;gap:2px 0}\n"
105+ " .kv .k{margin-top:8px}\n"
106+ " .card{padding:13px;border-radius:12px}\n"
107+ " .count{font-size:28px}\n"
108+ " .codebox .code{font-size:22px;letter-spacing:.1em}\n"
109+ "}\n"
110+ "</style>\n"
111+ "</head>\n"
112+ "<body>\n"
113+ "<div id=\"app\">\n"
114+ " <div class=\"hd\">\n"
115+ " <div class=\"grow\">\n"
116+ " <h1>OpenAI Codex</h1>\n"
117+ " <div class=\"sub\" id=\"sub\">Device code login on this node</div>\n"
118+ " </div>\n"
119+ " <span class=\"pill off\" id=\"pill\"><span class=\"dot\"></span><span id=\"pillText\">Checking</span></span>\n"
120+ " <button id=\"themeToggle\" class=\"embed-hide\" type=\"button\">Theme</button>\n"
121+ " </div>\n"
122+ "\n"
123+ " <div class=\"card\">\n"
124+ " <h2>Session</h2>\n"
125+ " <p class=\"lead\" id=\"sessionLead\">Reading the local Codex credentials.</p>\n"
126+ " <div class=\"count\" id=\"count\">-</div>\n"
127+ " <div class=\"bar\" id=\"bar\"><span class=\"fill\" id=\"fill\" style=\"width:0%\"></span></div>\n"
128+ " <div class=\"kv\" id=\"session\" style=\"margin-top:14px\"></div>\n"
129+ " <div class=\"row\" style=\"margin-top:14px\">\n"
130+ " <button class=\"btn ghost\" id=\"btnRefresh\" type=\"button\">Refresh Token Now</button>\n"
131+ " <button class=\"btn ghost\" id=\"btnStartLogin\" type=\"button\">Start Codex Login</button>\n"
132+ " <button class=\"btn ghost\" id=\"btnRelogin\" type=\"button\" hidden>Re-login (replace)</button>\n"
133+ " <button class=\"btn ghost\" id=\"btnReload\" type=\"button\">Reload</button>\n"
134+ " </div>\n"
135+ " <div class=\"note\" id=\"sessionNote\"></div>\n"
136+ " </div>\n"
137+ "\n"
138+ " <div class=\"card\">\n"
139+ " <h2>Device flow</h2>\n"
140+ " <p class=\"lead\">Codex signs in with a one-time user code. Copy it, open the link, approve,\n"
141+ " and this panel updates itself.</p>\n"
142+ "\n"
143+ " <div class=\"step on\" id=\"stepIdle\">\n"
144+ " <div class=\"empty\">No login in progress. Press <b>Start Codex Login</b> above to begin.</div>\n"
145+ " </div>\n"
146+ "\n"
147+ " <div class=\"step\" id=\"stepActive\">\n"
148+ " <div class=\"codebox\">\n"
149+ " <div class=\"code\" id=\"userCode\">--</div>\n"
150+ " <div class=\"row\" style=\"justify-content:center\">\n"
151+ " <button class=\"btn\" id=\"btnCopyOpen\" type=\"button\">Copy Code &amp; Open OpenAI</button>\n"
152+ " </div>\n"
153+ " </div>\n"
154+ " <div class=\"authurl\" id=\"verifyUrl\"></div>\n"
155+ " <div class=\"pollbar\"><i></i></div>\n"
156+ " <div class=\"polllbl\"><span class=\"spin\"></span><span id=\"pollLabel\">Waiting for authorization in browser...</span></div>\n"
157+ " <div class=\"row\" style=\"margin-top:12px\">\n"
158+ " <button class=\"btn danger\" id=\"btnCancel\" type=\"button\">Cancel</button>\n"
159+ " </div>\n"
160+ " <div class=\"note\" id=\"flowNote\"></div>\n"
161+ " </div>\n"
162+ " </div>\n"
163+ "\n"
164+ " <div class=\"card\">\n"
165+ " <h2>Named accounts</h2>\n"
166+ " <p class=\"lead\">Every account file in the local accounts directory.</p>\n"
167+ " <div id=\"accounts\"><div class=\"empty\">No named accounts.</div></div>\n"
168+ " </div>\n"
169+ "\n"
170+ " <footer>\n"
171+ " <span id=\"footInfo\">plugin_codex_login</span>\n"
172+ " &middot; <a href=\"https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-codex-login\">source</a>\n"
173+ " </footer>\n"
174+ "</div>\n"
175+ "\n"
176+ "<div class=\"toast\" id=\"toast\"></div>\n"
177+ "\n"
178+ "<script>\n"
179+ "(function(){\n"
180+ "var q=new URLSearchParams(location.search);\n"
181+ "var node=q.get('node')||'';\n"
182+ "var sid=q.get('id')||'';\n"
183+ "var acct=q.get('account')||'';\n"
184+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n"
185+ " localStorage.getItem('bot_active_pwd')||'';\n"
186+ "\n"
187+ "/* Two call routes. Getting this wrong is the most common plugin bug:\n"
188+ " * page served through the hub (bot.scorpiox.net/plugins?plugin=...&node=..)\n"
189+ " * -> call the hub proxy back: /plugins?plugin=plugin_codex_login&action=..\n"
190+ " * opened directly on the node\n"
191+ " * -> the plugin itself is the route: /plugin_codex_login?action=..\n"
192+ " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n"
193+ "var HUB=q.get('plugin')||'';\n"
194+ "function url(action,extra){\n"
195+ " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_codex_login')+\n"
196+ " '?action='+encodeURIComponent(action)+\n"
197+ " (extra?('&'+extra):'')+\n"
198+ " (acct?'&account='+encodeURIComponent(acct):'')+\n"
199+ " (node?'&node='+encodeURIComponent(node):'')+\n"
200+ " (sid?'&id='+encodeURIComponent(sid):'')+\n"
201+ " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n"
202+ "}\n"
203+ "function hdr(){\n"
204+ " var h={};\n"
205+ " if(pwd)h['X-Bot-Password']=pwd;\n"
206+ " return h;\n"
207+ "}\n"
208+ "function api(action,extra){\n"
209+ " return fetch(url(action,extra),{headers:hdr()}).then(function(r){\n"
210+ " return r.json().catch(function(){return {ok:false,error:'bad response'};});\n"
211+ " });\n"
212+ "}\n"
213+ "\n"
214+ "var $=function(id){return document.getElementById(id);};\n"
215+ "function toast(msg){\n"
216+ " var t=$('toast');t.textContent=msg;t.classList.add('show');\n"
217+ " clearTimeout(t._t);t._t=setTimeout(function(){t.classList.remove('show');},2200);\n"
218+ "}\n"
219+ "function note(el,msg,kind){\n"
220+ " el.textContent=msg||'';\n"
221+ " el.className='note'+(msg?' show '+(kind||''):'');\n"
222+ "}\n"
223+ "function kv(el,rows){\n"
224+ " el.innerHTML='';\n"
225+ " rows.forEach(function(r){\n"
226+ " var a=document.createElement('div');a.className='k';a.textContent=r[0];\n"
227+ " var b=document.createElement('div');b.className='v'+(r[2]?' plain':'');\n"
228+ " b.textContent=r[1];el.appendChild(a);el.appendChild(b);\n"
229+ " });\n"
230+ "}\n"
231+ "function fmtExpiry(sec){\n"
232+ " if(typeof sec!=='number')return '-';\n"
233+ " if(sec<=0)return 'expired';\n"
234+ " if(sec<90)return sec+'s';\n"
235+ " if(sec<5400)return Math.round(sec/60)+' min';\n"
236+ " var h=Math.floor(sec/3600);\n"
237+ " if(h<48)return h+' h '+(Math.floor((sec%3600)/60))+' min';\n"
238+ " return Math.floor(h/24)+' days';\n"
239+ "}\n"
240+ "function fmtClock(sec){\n"
241+ " if(typeof sec!=='number'||sec<=0)return '-';\n"
242+ " var d=Math.floor(sec/86400),h=Math.floor((sec%86400)/3600),m=Math.floor((sec%3600)/60);\n"
243+ " if(d>0)return d+'d '+h+'h';\n"
244+ " if(h>0)return h+'h '+m+'m';\n"
245+ " return m+'m';\n"
246+ "}\n"
247+ "function setPill(cls,text){\n"
248+ " $('pill').className='pill '+cls;\n"
249+ " $('pillText').textContent=text;\n"
250+ "}\n"
251+ "\n"
252+ "var pollTimer=null;\n"
253+ "var pollMs=5000;\n"
254+ "var flowActive=false;\n"
255+ "var flowVerify='';\n"
256+ "var flowCode='';\n"
257+ "\n"
258+ "function startPollingUI(){\n"
259+ " flowActive=true;\n"
260+ " $('stepIdle').classList.remove('on');\n"
261+ " $('stepActive').classList.add('on');\n"
262+ " if(!pollTimer)pollTimer=setInterval(pollOnce,pollMs);\n"
263+ "}\n"
264+ "function stopPollingUI(){\n"
265+ " flowActive=false;\n"
266+ " if(pollTimer){clearInterval(pollTimer);pollTimer=null;}\n"
267+ "}\n"
268+ "function pollOnce(){\n"
269+ " if(!flowActive)return;\n"
270+ " api('poll').then(function(d){\n"
271+ " if(!d||d.ok===false){note('flowNote','Poll error: '+(d&&d.error||'unknown'),'err');return;}\n"
272+ " if(d.state==='done'||d.logged_in){\n"
273+ " stopPollingUI();\n"
274+ " $('stepIdle').classList.add('on');\n"
275+ " $('stepActive').classList.remove('on');\n"
276+ " $('pollLabel').textContent='Signed in';\n"
277+ " note('flowNote','Signed in. The credential file has been written.','ok');\n"
278+ " load();\n"
279+ " }else if(d.state==='failed'){\n"
280+ " stopPollingUI();\n"
281+ " $('stepIdle').classList.add('on');\n"
282+ " $('stepActive').classList.remove('on');\n"
283+ " $('pollLabel').textContent='Login failed';\n"
284+ " note('flowNote','Login failed: '+(d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');\n"
285+ " load();\n"
286+ " }else{\n"
287+ " $('pollLabel').textContent='Waiting for authorization in browser...';\n"
288+ " if(d.interval&&d.interval>0)pollMs=Math.max(1000,d.interval*1000);\n"
289+ " if(d.logged_in)load();\n"
290+ " }\n"
291+ " }).catch(function(e){note('flowNote','Poll request failed: '+e,'err');});\n"
292+ "}\n"
293+ "\n"
294+ "function render(st){\n"
295+ " var li=!!st.logged_in, ex=!!st.expired, pend=!!st.pending;\n"
296+ " if(li&&!ex)setPill('ok','Logged In');\n"
297+ " else if(li&&ex)setPill('warn','Expired');\n"
298+ " else if(pend)setPill('warn','Signing In');\n"
299+ " else setPill('off','Not Connected');\n"
300+ "\n"
301+ " $('count').innerHTML='';\n"
302+ " if(li&&!ex){\n"
303+ " var s=document.createElement('span');s.textContent=fmtClock(st.expires_in_sec);\n"
304+ " var sm=document.createElement('small');sm.textContent=' remaining';\n"
305+ " $('count').appendChild(s);$('count').appendChild(sm);\n"
306+ " }else if(li&&ex){\n"
307+ " $('count').textContent='Token expired';\n"
308+ " }else if(pend){\n"
309+ " $('count').textContent='Device flow open';\n"
310+ " }else{\n"
311+ " $('count').textContent='No Codex session';\n"
312+ " }\n"
313+ "\n"
314+ " var total=st.expires_in_sec>0?st.expires_in_sec:0;\n"
315+ " var pct=0;\n"
316+ " if(li&&total>0){\n"
317+ " /* A one-hour token is the norm, so the bar is drawn against the window it\n"
318+ " * actually has, capped at 24 h so a long-lived token still fills it. */\n"
319+ " var win=total>86400?86400:total;\n"
320+ " pct=Math.max(2,Math.min(100,Math.round(100*total/win)));\n"
321+ " }\n"
322+ " $('fill').style.width=pct+'%';\n"
323+ " $('bar').className='bar'+(li&&ex?' err':(li&&pct<20?' warn':''));\n"
324+ " if(!li)$('bar').className='bar';\n"
325+ "\n"
326+ " kv($('session'),[\n"
327+ " ['Account', st.account||'-', true],\n"
328+ " ['Logged in', st.logged_in?'yes':'no', true],\n"
329+ " ['Token', st.logged_in?(st.expired?'expired':'valid, '+fmtExpiry(st.expires_in_sec)):'none', true],\n"
330+ " ['Refresh token', st.has_refresh?'stored':'none', true],\n"
331+ " ['Last refreshed', st.last_refresh?new Date(st.last_refresh*1000).toISOString().replace('T',' ').slice(0,19):'unknown', true],\n"
332+ " ['Account id', st.account_id||'-'],\n"
333+ " ['Login pending', st.pending?'yes':'no', true],\n"
334+ " ['Login CLI', st.cli_present?'found':'not found', true],\n"
335+ " ['Profile', st.profile_exists?(st.profile||'codex'):'not created', true],\n"
336+ " ['Credentials', st.credentials_path||'-']\n"
337+ " ]);\n"
338+ "\n"
339+ " $('btnRelogin').hidden=!li;\n"
340+ " $('btnStartLogin').hidden=!!li;\n"
341+ "\n"
342+ " if(!li&&!pend)note('sessionNote','No Codex session on this node yet. Start a device login below.','ok');\n"
343+ " else if(li&&ex)note('sessionNote','The token has expired. Press Refresh Token Now, or sign in again.','warn');\n"
344+ " else note('sessionNote','');\n"
345+ "\n"
346+ " if(st.cli_present===false)\n"
347+ " note('sessionNote','SCORPIOX CODE is not on this node: the login and refresh CLIs cannot be run here.','warn');\n"
348+ "\n"
349+ " var box=$('accounts');\n"
350+ " box.innerHTML='';\n"
351+ " var list=st.accounts||[];\n"
352+ " if(!list.length){\n"
353+ " var e=document.createElement('div');e.className='empty';\n"
354+ " e.textContent='No named accounts.';box.appendChild(e);\n"
355+ " }else{\n"
356+ " list.forEach(function(a){\n"
357+ " var row=document.createElement('div');row.className='acct';\n"
358+ " var nm=document.createElement('div');nm.className='nm';nm.textContent=a.name;\n"
359+ " var tg=document.createElement('div');\n"
360+ " tg.className='tag '+(a.logged_in&&!a.expired?'ok':(a.logged_in?'warn':''));\n"
361+ " tg.textContent=a.logged_in?(a.expired?'expired':'valid, '+fmtExpiry(a.expires_in_sec)):'empty';\n"
362+ " var bt=document.createElement('button');\n"
363+ " bt.className='btn ghost';bt.type='button';bt.textContent='Select';\n"
364+ " bt.onclick=function(){acct=a.name;$('sub').textContent='account: '+a.name;load();};\n"
365+ " row.appendChild(nm);row.appendChild(tg);row.appendChild(bt);\n"
366+ " box.appendChild(row);\n"
367+ " });\n"
368+ " }\n"
369+ " if(!$('sub').textContent||$('sub').textContent==='Device code login on this node'){\n"
370+ " $('sub').textContent=(st.account&&st.account!=='default')?('account: '+st.account):'Device code login on this node';\n"
371+ " }\n"
372+ "}\n"
373+ "\n"
374+ "function load(){\n"
375+ " api('status').then(function(d){\n"
376+ " if(!d||d.ok===false){setPill('off','Not Connected');note('sessionNote','Error: '+(d&&d.error||'no response'),'err');return;}\n"
377+ " render(d);\n"
378+ " if(d.pending&&!flowActive){\n"
379+ " /* A flow that was started elsewhere (or before a page reload) should\n"
380+ " * still show its spinner; the code itself is not recoverable from the\n"
381+ " * marker, so the panel says so rather than pretending. */\n"
382+ " $('userCode').textContent='--';\n"
383+ " $('verifyUrl').textContent='';\n"
384+ " $('pollLabel').textContent='A device flow is already open on this node';\n"
385+ " startPollingUI();\n"
386+ " }\n"
387+ " if(!d.pending&&flowActive)stopPollingUI();\n"
388+ " }).catch(function(e){setPill('off','Not Connected');note('sessionNote','Request failed: '+e,'err');});\n"
389+ "}\n"
390+ "\n"
391+ "function doStart(force){\n"
392+ " note('sessionNote','');\n"
393+ " $('btnStartLogin').disabled=true;\n"
394+ " api('start',force?'force=1':'').then(function(d){\n"
395+ " $('btnStartLogin').disabled=false;\n"
396+ " if(!d||d.ok===false){\n"
397+ " note('sessionNote','Start failed: '+(d&&d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');\n"
398+ " return;\n"
399+ " }\n"
400+ " if(d.already_logged_in){\n"
401+ " note('sessionNote','This node already has Codex credentials. Use Re-login to replace them.','warn');\n"
402+ " load();\n"
403+ " return;\n"
404+ " }\n"
405+ " flowVerify=d.verify_url||'';\n"
406+ " flowCode=d.user_code||'';\n"
407+ " $('userCode').textContent=flowCode||'--';\n"
408+ " $('verifyUrl').textContent=flowVerify;\n"
409+ " $('pollLabel').textContent='Waiting for authorization in browser...';\n"
410+ " pollMs=Math.max(1000,(d.interval||5)*1000);\n"
411+ " note('flowNote','','');\n"
412+ " startPollingUI();\n"
413+ " load();\n"
414+ " }).catch(function(e){$('btnStartLogin').disabled=false;note('sessionNote','Start request failed: '+e,'err');});\n"
415+ "}\n"
416+ "\n"
417+ "$('btnStartLogin').onclick=function(){doStart(false);};\n"
418+ "$('btnRelogin').onclick=function(){doStart(true);};\n"
419+ "$('btnReload').onclick=load;\n"
420+ "$('btnCancel').onclick=function(){\n"
421+ " stopPollingUI();\n"
422+ " api('cancel').then(function(d){\n"
423+ " $('stepIdle').classList.add('on');\n"
424+ " $('stepActive').classList.remove('on');\n"
425+ " note('flowNote',(d&&d.ok)?'Device flow cancelled.':'Cancel failed: '+((d&&d.error)||'unknown'),\n"
426+ " (d&&d.ok)?'ok':'err');\n"
427+ " load();\n"
428+ " }).catch(function(e){note('flowNote','Cancel request failed: '+e,'err');});\n"
429+ "};\n"
430+ "$('btnRefresh').onclick=function(){\n"
431+ " note('sessionNote','');\n"
432+ " api('refresh').then(function(d){\n"
433+ " if(!d||d.ok===false){\n"
434+ " note('sessionNote','Refresh failed: '+(d&&d.error||'unknown')+(d.detail?(' - '+d.detail):''),'err');\n"
435+ " return;\n"
436+ " }\n"
437+ " note('sessionNote','Token refreshed. New expiry: '+fmtExpiry(d.expires_in_sec)+'.','ok');\n"
438+ " render(d);\n"
439+ " }).catch(function(e){note('sessionNote','Refresh request failed: '+e,'err');});\n"
440+ "};\n"
441+ "$('btnCopyOpen').onclick=function(){\n"
442+ " var done=function(){toast('Code copied. Open the link and approve.');};\n"
443+ " if(navigator.clipboard&&navigator.clipboard.writeText){\n"
444+ " navigator.clipboard.writeText(flowCode).then(done,function(){toast('Copy failed');});\n"
445+ " }else{toast('Copy not available');}\n"
446+ " if(flowVerify)window.open(flowVerify,'_blank','noopener');\n"
447+ "};\n"
448+ "\n"
449+ "var tb=$('themeToggle');\n"
450+ "if(tb)tb.onclick=function(){\n"
451+ " if(window.sxApplyTheme)window.sxApplyTheme(window.sxTheme?window.sxTheme():'light');\n"
452+ "};\n"
453+ "$('footInfo').textContent='plugin_codex_login';\n"
454+ "load();\n"
455+ "})();\n"
456+ "</script>\n"
457+ "\002</body></html>\n"
458+ ;
459+
460+#endif /* SX_CODEXLOGIN_UI_HTML_H */
tests/mock_login.sh+86−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..af4510eindex 0000000..af4510e
--- /dev/null--- /dev/null
+++ b/tests/mock_login.sh+++ b/tests/mock_login.sh
@@ -0,0 +1,86 @@@@ -0,0 +1,86 @@
1+#!/bin/sh
2+# tests/mock_login.sh - stand-in for scorpiox-codex-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. `--poll` writes a credential
7+# file into $CODEX_CREDS_PATH when it reports success, so a test can prove the
8+# plugin re-reads state instead of trusting the CLI's word.
9+#
10+# MOCK_FAIL=1 makes --poll fail the way a denied device code does.
11+# MOCK_NOUSER=1 makes --start return no user_code (a malformed CLI answer).
12+# MOCK_EXISTS=1 makes --start report "credentials already exist".
13+
14+CREDS="${CODEX_CREDS_PATH:-/nonexistent}"
15+# A decodable JWT whose payload says exp=1794509681; tests replace it with a
16+# freshly generated one so the countdown is real.
17+MOCK_DEFAULT_TOKEN="eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3OTQ1MDk2ODEsImNoYXRncHRfYWNjb3VudF9pZCI6ImFjY3QtZGVmYXVsdCJ9.DEVFAKE"
18+PEND="${CODEX_PENDING_DIR:-/nonexistent}/codex-default.json"
19+ACC="${CODEX_ACCOUNT:-default}"
20+
21+li=false; hr=false; exp=0
22+if [ -f "$CREDS" ]; then
23+ if grep -q 'access_token' "$CREDS" 2>/dev/null; then li=true; fi
24+ if grep -q 'refresh_token' "$CREDS" 2>/dev/null; then hr=true; fi
25+fi
26+pend=false
27+if [ -f "$PEND" ]; then pend=true; fi
28+
29+# The real CLI reports expires_at 0 because auth.json has no expiry field; the
30+# plugin is what decodes the token. Keep that behaviour so the suite proves it.
31+case "$1" in
32+ --status)
33+ printf 'Checking Codex credentials...\n'
34+ printf '{"ok":true,"provider":"codex","name":"Codex (OpenAI)","flow":"device_code","account":"%s","logged_in":%s,"path":"%s","expires_at":0,"expired":false,"has_refresh":%s,"pending":%s,"profile":"codex","profile_exists":false,"named_accounts":true,"protocol":"SXLOGIN-MACHINE-V1"}\n' \
35+ "$ACC" "$li" "$CREDS" "$hr" "$pend"
36+ ;;
37+ --start)
38+ if [ "$MOCK_EXISTS" = "1" ]; then
39+ printf '{"ok":false,"provider":"codex","error":"exists","detail":"credentials already exist; pass --force to replace"}\n'
40+ exit 1
41+ fi
42+ if [ "$MOCK_NOUSER" = "1" ]; then
43+ printf '{"ok":true,"provider":"codex","flow":"device_code","verify_url":"https://auth.openai.com/codex/device","interval":5,"expires_in":900}\n'
44+ exit 0
45+ fi
46+ mkdir -p "$(dirname "$PEND")" 2>/dev/null
47+ printf '{"device_auth_id":"dev-mock-1","user_code":"ABCD-1234","interval":5,"force":%s,"created":%s}\n' \
48+ "${MOCK_FORCE:-0}" "$(date +%s)" > "$PEND"
49+ printf 'Requesting a device code from OpenAI...\n'
50+ printf '{"ok":true,"provider":"codex","flow":"device_code","verify_url":"https://auth.openai.com/codex/device","user_code":"ABCD-1234","interval":5,"expires_in":900,"hint":"Open the link, enter the code, approve. This page checks automatically."}\n'
51+ ;;
52+ --poll)
53+ if [ "$MOCK_FAIL" = "1" ]; then
54+ printf '{"ok":false,"provider":"codex","error":"denied","detail":"authorization failed or was denied; start again"}\n'
55+ exit 1
56+ fi
57+ if [ "$MOCK_DONE" = "1" ]; then
58+ cat > "$CREDS" << CREDEOF
59+{
60+ "OPENAI_API_KEY": null,
61+ "tokens": {
62+ "id_token": "${MOCK_ID_TOKEN:-$MOCK_ACCESS_TOKEN}",
63+ "access_token": "${MOCK_ACCESS_TOKEN:-$MOCK_DEFAULT_TOKEN}",
64+ "refresh_token": "rt-from-mock-poll",
65+ "account_id": "acct-mock"
66+ },
67+ "last_refresh": "${MOCK_LAST_REFRESH:-2026-11-12T18:00:00.000000Z}"
68+}
69+CREDEOF
70+ rm -f "$PEND"
71+ printf '{"ok":true,"provider":"codex","state":"done","logged_in":true,"path":"%s","profile":"codex","profile_created":false}\n' "$CREDS"
72+ else
73+ printf 'Polling OpenAI...\n'
74+ printf '{"ok":true,"provider":"codex","state":"pending","interval":5}\n'
75+ fi
76+ ;;
77+ --cancel)
78+ rm -f "$PEND"
79+ printf '{"ok":true,"provider":"codex","cancelled":true}\n'
80+ ;;
81+ *)
82+ printf 'mock: unknown flag %s\n' "$1" >&2
83+ exit 2
84+ ;;
85+esac
86+exit 0
tests/mock_refresh.sh+61−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..6ae14f6index 0000000..6ae14f6
--- /dev/null--- /dev/null
+++ b/tests/mock_refresh.sh+++ b/tests/mock_refresh.sh
@@ -0,0 +1,61 @@@@ -0,0 +1,61 @@
1+#!/bin/sh
2+# tests/mock_refresh.sh - stand-in for scorpiox-codex-refreshtoken.
3+#
4+# Rewrites the credential file in place with a token whose exp claim is
5+# MOCK_NEW_EXP (or now+7200 when unset), prints human progress to stdout, and
6+# exits 0. MOCK_FAIL=1 makes it exit 1 without touching the file, which is how
7+# a rejected refresh-token grant behaves.
8+#
9+# The point of the mock is that it prints token material on stdout - the real
10+# CLI does too with --verbose - so the suite can prove the plugin never echoes
11+# it back.
12+
13+CREDS=""
14+prev=0
15+while [ $# -gt 0 ]; do
16+ case "$1" in
17+ --credentials-file) CREDS="$2"; shift 2 ;;
18+ --force|-f) shift ;;
19+ *) shift ;;
20+ esac
21+done
22+[ -n "$CREDS" ] || CREDS="${CODEX_CREDS_PATH:-/nonexistent}"
23+
24+if [ ! -f "$CREDS" ]; then
25+ printf 'error: cannot read %s\n' "$CREDS" >&2
26+ exit 1
27+fi
28+
29+if [ "$MOCK_FAIL" = "1" ]; then
30+ printf 'error: refresh rejected by the provider\n' >&2
31+ exit 1
32+fi
33+
34+NEW_EXP="${MOCK_NEW_EXP:-$(( $(date +%s) + 7200 ))}"
35+printf 'Codex OAuth Token Auto-Refresh Tool\n\n'
36+printf 'Found Codex config: %s\n' "$CREDS"
37+printf 'Rotated token: %s\n' "super-secret-rotated-token-value"
38+printf 'New token expires: %s\n' "$NEW_EXP"
39+
40+python3 - "$CREDS" "$NEW_EXP" << 'PYEOF'
41+import base64, json, sys, time
42+path, exp = sys.argv[1], int(sys.argv[2])
43+payload = {"exp": exp, "chatgpt_account_id": "acct-mock"}
44+b = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
45+tok = "eyJhbGciOiJIUzI1NiJ9." + b + ".SIG"
46+try:
47+ with open(path, "r", encoding="utf-8") as f:
48+ doc = json.load(f)
49+except Exception:
50+ doc = {}
51+toks = doc.get("tokens") or {}
52+toks["access_token"] = tok
53+toks["refresh_token"] = "rt-rotated-by-mock"
54+doc["tokens"] = toks
55+doc["last_refresh"] = time.strftime("%Y-%m-%dT%H:%M:%S.000000Z", time.gmtime())
56+with open(path, "w", encoding="utf-8") as f:
57+ json.dump(doc, f, indent=2)
58+ f.write("\n")
59+PYEOF
60+printf 'Updated auth.json\n'
61+exit 0
tests/run.sh+471−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..3b17154index 0000000..3b17154
--- /dev/null--- /dev/null
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -0,0 +1,471 @@@@ -0,0 +1,471 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_codex_login across all 3 modes.
3+#
4+# Every check runs against ./plugin_codex_login with the credential paths and
5+# both CLIs redirected at throwaway fixtures, so the suite proves the public
6+# contract without touching a real Codex session and without a network.
7+#
8+# What it proves:
9+# - --meta is exactly {"name":"codex","desc":"Codex login"} and is reachable
10+# with no password (discovery must never be gated)
11+# - every action 401s without the node password, and 401 is a real CGI Status
12+# - status reads the tokens block, decodes the JWT exp claim for the expiry
13+# (auth.json has no expiry field of its own), reads last_refresh, lists the
14+# named account directory, and NEVER emits a token
15+# - start returns the CLI's verify_url and user_code, reports "already logged
16+# in" when the CLI says exists, and survives a CLI answer with no user code
17+# - poll reports pending, reports done after the CLI writes the file, and
18+# turns a denied device code into a terminal failed state
19+# - refresh performs the grant, drops the CLI's payload, and surfaces failure
20+# - the HTML page carries the bot theme handoff, no CDN and no <script src=>
21+# - the source has no hard-coded secret, no internal address and no emoji
22+#
23+# Exit code 0 = everything passed.
24+
25+set -u
26+
27+ROOT=$(cd "$(dirname "$0")/.." && pwd)
28+cd "$ROOT" || exit 1
29+
30+BIN=./plugin_codex_login
31+ID=plugin_codex_login
32+PASS=0
33+FAIL=0
34+
35+if [ -t 1 ]; then
36+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
37+else
38+ C_OK=; C_BAD=; C_B=; C_0=
39+fi
40+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
41+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
42+
43+check() { # check <desc> <expected-substring> <actual>
44+ if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
45+ fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
46+ fi
47+}
48+
49+check_not() { # check_not <desc> <forbidden-substring> <actual>
50+ if printf '%s' "$3" | grep -F -q -- "$2"; then
51+ fail "$1 (must NOT contain: $2)"; else pass "$1"
52+ fi
53+}
54+
55+found() { # found <desc> <needle> <file...> - the needle must appear somewhere
56+ _d=$1; _n=$2; shift 2
57+ if grep -F -q -- "$_n" "$@" 2>/dev/null; then pass "$_d"; else
58+ fail "$_d (missing: $_n)"
59+ fi
60+}
61+
62+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
63+
64+# strip CGI headers if present, drop CRs, keep the payload
65+body() {
66+ printf '%s\n' "$1" | tr -d '\r' | awk '
67+ BEGIN { inhdr = 0 }
68+ NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Referrer-Policy|Content-Security-Policy):/) { inhdr = 1; next }
69+ inhdr && $0 == "" { inhdr = 0; next }
70+ inhdr { next }
71+ { print }
72+ '
73+}
74+
75+json_ok() { # json_ok <desc> <json> [python-expression]
76+ expr=${3:-True}
77+ 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
78+ pass "$1"
79+ else
80+ fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)"
81+ fi
82+}
83+
84+api() { body "$(QUERY_STRING="$1" $BIN)"; }
85+apiraw() { QUERY_STRING="$1" $BIN; }
86+
87+# Build a JWT whose payload carries exp=<seconds>. The real access tokens are
88+# RS256 JWTs of the same shape, so the fixture is faithful in the only field the
89+# plugin reads.
90+mkjwt() { # mkjwt <exp-seconds>
91+ python3 - "$1" << 'PYEOF'
92+import base64, json, sys
93+exp = int(sys.argv[1])
94+payload = {"exp": exp, "chatgpt_account_id": "acct-fixture", "sub": "user-fixture"}
95+b = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
96+print("eyJhbGciOiJIUzI1NiJ9." + b + ".SIGNATUREPART")
97+PYEOF
98+}
99+
100+# ---------------------------------------------------------------- build
101+section "build"
102+if [ ! -x "$BIN" ]; then
103+ echo " building native binary..."
104+ cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -Wno-format-truncation -I src \
105+ -o "$BIN" src/plugin_codex_login.c || { fail "native build"; exit 1; }
106+fi
107+pass "native binary present"
108+
109+if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
110+ pass "src/ui_html.h is in sync with src/ui.html"
111+else
112+ fail "src/ui_html.h is stale - run tools/gen_ui.py"
113+fi
114+
115+check "ui header is marked generated" \
116+ "Generated by tools/gen_ui.py" "$(head -1 src/ui_html.h)"
117+
118+# ---------------------------------------------------------------- --meta
119+section "discovery metadata"
120+META=$(BOT_PASSWORD=testpw $BIN --meta)
121+[ "$META" = '{"name":"codex","desc":"Codex login"}' ] && pass "--meta is exactly the contract string" \
122+ || fail "--meta mismatch: $META"
123+META2=$(SX_PLUGIN_META=1 BOT_PASSWORD=testpw $BIN)
124+check "SX_PLUGIN_META=1 emits the same metadata" '"desc":"Codex login"' "$META2"
125+check "--meta works with an empty env" '"name":"codex"' "$(env -u BOT_PASSWORD $BIN --meta)"
126+json_ok "--meta is valid JSON" "$(env -u BOT_PASSWORD $BIN --meta)" \
127+ 'd["name"]=="codex" and len(d["desc"])<=15'
128+json_ok "--meta title is one word" "$(env -u BOT_PASSWORD $BIN --meta)" \
129+ 'len(d["name"].split())==1'
130+V=$($BIN --version)
131+check "--version names the binary" "$ID" "$V"
132+
133+# ---------------------------------------------------------------- fixtures
134+FIX=$(mktemp -d 2>/dev/null || mktemp -d -t cxfix)
135+trap 'rm -rf "$FIX"' EXIT
136+
137+mkdir -p "$FIX/acc" "$FIX/pend" "$FIX/env" "$FIX/deep/nested"
138+export CODEX_LOGIN_BIN="$ROOT/tests/mock_login.sh"
139+export CODEX_REFRESH_BIN="$ROOT/tests/mock_refresh.sh"
140+export CODEX_PENDING_DIR="$FIX/pend"
141+export CODEX_ENV_DIR="$FIX/env"
142+export CODEX_ACCOUNTS_DIR="$FIX/acc"
143+export CODEX_CREDS_PATH="$FIX/auth.json"
144+export BOT_PASSWORD=testpw
145+PWDQ='pwd=testpw'
146+
147+NOW=$(date +%s)
148+FUTURE=$((NOW + 7200))
149+PAST=$((NOW - 3600))
150+TOK_FUTURE=$(mkjwt "$FUTURE")
151+TOK_PAST=$(mkjwt "$PAST")
152+
153+mkcreds() { # mkcreds <path> <access-token> <refresh-or-empty> <last_refresh>
154+ {
155+ printf '{\n "OPENAI_API_KEY": null,\n "tokens": {\n'
156+ printf ' "id_token": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmaXh0dXJlIn0.IDSIG",\n'
157+ printf ' "access_token": "%s",\n' "$2"
158+ if [ -n "$3" ]; then
159+ printf ' "refresh_token": "%s",\n' "$3"
160+ else
161+ printf ' "refresh_token": "",\n'
162+ fi
163+ printf ' "account_id": "acct-fixture"\n },\n'
164+ printf ' "last_refresh": "%s"\n}\n' "$4"
165+ } > "$1"
166+}
167+
168+# ---------------------------------------------------------------- auth gate
169+section "node auth gate"
170+RAW=$(apiraw "action=status")
171+check "unauthenticated action=status 401s" "Status: 401 Unauthorized" "$RAW"
172+check "401 body is JSON" '"error":"invalid node password"' "$RAW"
173+check "unauthenticated HTML page 401s" "Status: 401 Unauthorized" "$(apiraw "")"
174+check "X-Bot-Password header auth works" '"ok":true' \
175+ "$(body "$(HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=status" $BIN)")"
176+check "Bearer auth works" '"ok":true' \
177+ "$(body "$(HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING="action=status" $BIN)")"
178+check "wrong password still 401s" "Status: 401 Unauthorized" \
179+ "$(QUERY_STRING="action=status&pwd=nope" $BIN)"
180+UNSET_BOT=$(env -u BOT_PASSWORD QUERY_STRING="action=status" $BIN)
181+check "no BOT_PASSWORD set = no gate" '"ok":true' "$(body "$UNSET_BOT")"
182+check "discovery is never gated" '"name":"codex"' "$(env -u BOT_PASSWORD $BIN --meta)"
183+
184+# ---------------------------------------------------------------- status: empty
185+section "status with no credentials"
186+rm -f "$FIX/auth.json" "$FIX/acc"/*.json "$FIX/pend"/*.json "$FIX/env"/*.txt
187+OUT=$(api "action=status&$PWDQ")
188+json_ok "empty node answers ok:true" "$OUT" 'd["ok"] is True'
189+json_ok "empty node is not logged in" "$OUT" 'd["logged_in"] is False'
190+json_ok "empty node is not expired" "$OUT" 'd["expired"] is False'
191+json_ok "empty node has no expiry" "$OUT" 'd["expires_at"]==0 and d["expires_in_sec"]==0'
192+json_ok "empty node has no refresh token" "$OUT" 'd["has_refresh"] is False'
193+json_ok "empty node has no pending flow" "$OUT" 'd["pending"] is False'
194+json_ok "empty node reports the credentials path" "$OUT" 'd["credentials_path"].endswith("auth.json")'
195+json_ok "empty node has no named accounts" "$OUT" 'd["accounts"]==[]'
196+json_ok "empty node says the CLI is present (mock)" "$OUT" 'd["cli_present"] is True'
197+
198+# ---------------------------------------------------------------- status: live
199+section "status with a live session"
200+mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-secret-refresh-must-not-leak" "2026-11-12T12:00:00.000000Z"
201+printf 'PROVIDER=codex\nCODEX_TOKEN_SOURCE=local\nMODEL=gpt-5.5\n' > "$FIX/env/codex.txt"
202+OUT=$(api "action=status&$PWDQ")
203+json_ok "live session is logged in" "$OUT" 'd["logged_in"] is True'
204+json_ok "live session is not expired" "$OUT" 'd["expired"] is False'
205+json_ok "live session has a refresh token" "$OUT" 'd["has_refresh"] is True'
206+json_ok "live session countdown is positive and near 2h" "$OUT" \
207+ '7100 < d["expires_in_sec"] <= 7200'
208+json_ok "expiry is unix seconds, not milliseconds" "$OUT" \
209+ '1000000000 < d["expires_at"] < 3000000000'
210+json_ok "last_refresh is parsed to unix seconds" "$OUT" 'd["last_refresh"] > 1000000000'
211+json_ok "account id is read from the file" "$OUT" 'd["account_id"]=="acct-fixture"'
212+json_ok "profile file is detected" "$OUT" 'd["profile"]=="codex" and d["profile_exists"] is True'
213+json_ok "default account is named default" "$OUT" 'd["account"]=="default"'
214+check_not "status never returns an access token" 'SIGNATUREPART' "$OUT"
215+check_not "status never returns a refresh token" 'rt-secret-refresh' "$OUT"
216+check_not "status never returns the id token" 'eyJhbGciOiJIUzI1NiJ9' "$OUT"
217+check_not "status never returns the key name access_token" 'access_token' "$OUT"
218+check_not "status never leaks the fixture secret word" 'MUST-NOT-LEAK' "$OUT"
219+
220+# ---------------------------------------------------------------- status: expired
221+section "status with an expired session"
222+mkcreds "$FIX/auth.json" "$TOK_PAST" "rt-secret-refresh-must-not-leak" "2026-11-10T09:00:00.000000Z"
223+OUT=$(api "action=status&$PWDQ")
224+json_ok "expired session is still logged in" "$OUT" 'd["logged_in"] is True'
225+json_ok "expired session is flagged expired" "$OUT" 'd["expired"] is True'
226+json_ok "expired session has a negative countdown" "$OUT" 'd["expires_in_sec"] < 0'
227+
228+# ---------------------------------------------------------------- odd fixtures
229+section "malformed and unusual fixtures"
230+printf '{"OPENAI_API_KEY":"legacy-key-value","tokens":{"access_token":"a"}}\n' > "$FIX/auth.json"
231+OUT=$(api "action=status&$PWDQ")
232+json_ok "a token with no exp claim is logged in with unknown expiry" "$OUT" \
233+ 'd["logged_in"] is True and d["expires_at"]==0 and d["expired"] is False'
234+json_ok "a legacy OPENAI_API_KEY is reported as present, not as a token" "$OUT" \
235+ 'd["api_key_present"] is True'
236+check_not "the legacy key value is never echoed" 'legacy-key-value' "$OUT"
237+
238+printf 'not json at all\n' > "$FIX/auth.json"
239+OUT=$(api "action=status&$PWDQ")
240+json_ok "a non-JSON credentials file is handled, not crashed" "$OUT" \
241+ 'd["ok"] is True and d["logged_in"] is False'
242+
243+printf '{"somethingElse":true}\n' > "$FIX/auth.json"
244+OUT=$(api "action=status&$PWDQ")
245+json_ok "a file with no tokens block is not logged in" "$OUT" 'd["logged_in"] is False'
246+
247+printf '{"OPENAI_API_KEY":null,"tokens":{"access_token":"","refresh_token":""}}\n' > "$FIX/auth.json"
248+OUT=$(api "action=status&$PWDQ")
249+json_ok "an empty access token is not a session" "$OUT" 'd["logged_in"] is False'
250+json_ok "an empty refresh token is not a refresh token" "$OUT" 'd["has_refresh"] is False'
251+
252+# a flat file (no tokens wrapper) still counts as a session
253+printf '{"access_token":"%s","refresh_token":"rt-flat"}\n' "$TOK_FUTURE" > "$FIX/auth.json"
254+OUT=$(api "action=status&$PWDQ")
255+json_ok "a flat token file is read as a session" "$OUT" \
256+ 'd["logged_in"] is True and 7100 < d["expires_in_sec"] <= 7200'
257+
258+# a token whose payload is not base64 at all
259+printf '{"tokens":{"access_token":"!!!not-a-jwt!!!"}}\n' > "$FIX/auth.json"
260+OUT=$(api "action=status&$PWDQ")
261+json_ok "a non-JWT access token is a session with unknown expiry" "$OUT" \
262+ 'd["logged_in"] is True and d["expires_at"]==0'
263+
264+# ---------------------------------------------------------------- named accounts
265+section "named accounts"
266+mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-default" "2026-11-12T12:00:00.000000Z"
267+mkcreds "$FIX/acc/work.json" "$TOK_FUTURE" "rt-work" "2026-11-12T10:00:00.000000Z"
268+mkcreds "$FIX/acc/old.json" "$TOK_PAST" "rt-old" "2026-11-01T10:00:00.000000Z"
269+printf '{"OPENAI_API_KEY":null,"tokens":{"access_token":"","refresh_token":""}}\n' > "$FIX/acc/notoken.json"
270+OUT=$(api "action=status&$PWDQ")
271+json_ok "named accounts are listed" "$OUT" 'len(d["accounts"])==3'
272+json_ok "a valid account is reported valid" "$OUT" \
273+ '[a for a in d["accounts"] if a["name"]=="work"][0]["expired"] is False'
274+json_ok "a stale account is reported expired" "$OUT" \
275+ '[a for a in d["accounts"] if a["name"]=="old"][0]["expired"] is True'
276+json_ok "an account with no token is reported logged out" "$OUT" \
277+ '[a for a in d["accounts"] if a["name"]=="notoken"][0]["logged_in"] is False'
278+json_ok "named accounts are flagged" "$OUT" 'd["named_accounts"] is True'
279+json_ok "account entries carry their own countdown" "$OUT" \
280+ '[a for a in d["accounts"] if a["name"]=="work"][0]["expires_in_sec"] > 7000'
281+check_not "account entries never carry a token" 'SIGNATUREPART' "$OUT"
282+OUT=$(api "action=accounts&$PWDQ")
283+json_ok "action=accounts answers the same shape" "$OUT" 'd["ok"] is True and len(d["accounts"])==3'
284+OUT=$(api "action=status&account=work&$PWDQ")
285+json_ok "status for a named account reads that file" "$OUT" \
286+ 'd["account"]=="work" and d["logged_in"] is True'
287+check "named account path is reported" "work.json" "$OUT"
288+BADNAME=$(api "action=status&account=../etc&$PWDQ")
289+check_not "a path-traversal account name does not read /etc" 'etc' "$BADNAME"
290+
291+# ---------------------------------------------------------------- pending marker
292+section "pending device flow marker"
293+rm -f "$FIX/pend"/*.json
294+OUT=$(api "action=status&$PWDQ")
295+json_ok "no marker means not pending" "$OUT" 'd["pending"] is False'
296+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","interval":5,"created":%s}\n' "$NOW" \
297+ > "$FIX/pend/codex-default.json"
298+OUT=$(api "action=status&$PWDQ")
299+json_ok "a fresh marker means pending" "$OUT" 'd["pending"] is True'
300+json_ok "the marker age is reported" "$OUT" '0 <= d["pending_age_sec"] < 120'
301+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$((NOW - 99999))" \
302+ > "$FIX/pend/codex-default.json"
303+OUT=$(api "action=status&$PWDQ")
304+json_ok "a stale marker is not pending" "$OUT" 'd["pending"] is False'
305+rm -f "$FIX/pend"/*.json
306+
307+# ---------------------------------------------------------------- start
308+section "action=start"
309+rm -f "$FIX/pend"/*.json
310+rm -f "$FIX/auth.json"
311+OUT=$(api "action=start&$PWDQ")
312+json_ok "start returns ok" "$OUT" 'd["ok"] is True'
313+json_ok "start returns the device_code flow" "$OUT" 'd["flow"]=="device_code"'
314+json_ok "start returns the CLI verify_url" "$OUT" 'd["verify_url"].startswith("https://auth.openai.com/")'
315+json_ok "start returns a user code" "$OUT" 'd["user_code"]=="ABCD-1234"'
316+json_ok "start returns expires_in" "$OUT" 'd["expires_in"] > 0'
317+json_ok "start returns a poll interval" "$OUT" 'd["interval"] >= 1'
318+json_ok "start marks the flow pending" "$OUT" 'd["pending"] is True'
319+check "start writes the pending marker" "codex-default.json" "$FIX/pend"/*.json 2>/dev/null || \
320+ pass "start leaves a marker for poll to find"
321+check_not "start never echoes a token" 'SIGNATUREPART' "$OUT"
322+
323+# already-logged-in path
324+mkcreds "$FIX/auth.json" "$TOK_FUTURE" "rt-exists" "2026-11-12T12:00:00.000000Z"
325+OUT=$(api "action=start&$PWDQ")
326+json_ok "start on existing creds reports already_logged_in" "$OUT" \
327+ 'd["ok"] is True and d["already_logged_in"] is True'
328+json_ok "the already-logged-in answer keeps logged_in true" "$OUT" 'd["logged_in"] is True'
329+check_not "the already-logged-in answer is not an error surface" '"ok":false' "$OUT"
330+
331+# a CLI answer with no user code
332+OUT=$(body "$(MOCK_NOUSER=1 QUERY_STRING="action=start&$PWDQ" $BIN)")
333+json_ok "a start with no user code is start_incomplete" "$OUT" 'd["ok"] is False and d["error"]=="start_incomplete"'
334+
335+# no CLI on the node
336+OUT=$(body "$(CODEX_LOGIN_BIN=/nonexistent QUERY_STRING="action=start&$PWDQ" $BIN)")
337+json_ok "a missing login CLI is cli_unavailable, not a crash" "$OUT" \
338+ 'd["ok"] is False and d["error"]=="cli_unavailable"'
339+
340+# ---------------------------------------------------------------- poll
341+section "action=poll"
342+rm -f "$FIX/pend"/*.json "$FIX/auth.json"
343+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","interval":5,"created":%s}\n' "$NOW" \
344+ > "$FIX/pend/codex-default.json"
345+OUT=$(api "action=poll&$PWDQ")
346+json_ok "poll while waiting is ok" "$OUT" 'd["ok"] is True'
347+json_ok "poll while waiting reports pending" "$OUT" 'd["state"]=="pending"'
348+json_ok "poll while waiting is not done" "$OUT" 'd.get("logged_in") is not True'
349+json_ok "poll passes the interval through" "$OUT" 'd["interval"] >= 1'
350+
351+OUT=$(body "$(MOCK_DONE=1 MOCK_ACCESS_TOKEN="$TOK_FUTURE" QUERY_STRING="action=poll&$PWDQ" $BIN)")
352+json_ok "poll after approval reports done" "$OUT" 'd["ok"] is True and d["state"]=="done"'
353+json_ok "poll after approval is logged in" "$OUT" 'd["logged_in"] is True'
354+json_ok "poll after approval proves the countdown from the file" "$OUT" \
355+ '7100 < d["expires_in_sec"] <= 7200'
356+json_ok "poll after approval clears pending" "$OUT" 'd["pending"] is False'
357+check_not "the done answer never echoes a token" 'SIGNATUREPART' "$OUT"
358+
359+OUT=$(body "$(MOCK_FAIL=1 QUERY_STRING="action=poll&$PWDQ" $BIN)")
360+json_ok "a denied device code is a terminal failed state" "$OUT" \
361+ 'd["ok"] is True and d["state"]=="failed"'
362+json_ok "the failed state carries the CLI error" "$OUT" 'd["error"]=="denied"'
363+json_ok "the failed state clears pending" "$OUT" 'd["pending"] is False'
364+
365+OUT=$(body "$(CODEX_LOGIN_BIN=/nonexistent QUERY_STRING="action=poll&$PWDQ" $BIN)")
366+json_ok "poll with no CLI is cli_unavailable" "$OUT" 'd["error"]=="cli_unavailable"'
367+
368+# ---------------------------------------------------------------- cancel
369+section "action=cancel"
370+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$NOW" \
371+ > "$FIX/pend/codex-default.json"
372+OUT=$(api "action=cancel&$PWDQ")
373+json_ok "cancel is ok" "$OUT" 'd["ok"] is True and d["state"]=="cancelled"'
374+json_ok "cancel clears pending" "$OUT" 'd["pending"] is False'
375+if [ -f "$FIX/pend/codex-default.json" ]; then fail "cancel removed the marker"; else pass "cancel removed the marker"; fi
376+
377+printf '{"device_auth_id":"dev-1","user_code":"ABCD-1234","created":%s}\n' "$NOW" \
378+ > "$FIX/pend/codex-default.json"
379+OUT=$(body "$(CODEX_LOGIN_BIN=/nonexistent QUERY_STRING="action=cancel&$PWDQ" $BIN)")
380+json_ok "cancel with no CLI still clears the marker" "$OUT" \
381+ 'd["ok"] is True and d["pending"] is False and d["cli_present"] is False'
382+if [ -f "$FIX/pend/codex-default.json" ]; then fail "cancel without CLI removed the marker"; else pass "cancel without CLI removed the marker"; fi
383+
384+# ---------------------------------------------------------------- refresh
385+section "action=refresh"
386+rm -f "$FIX/auth.json"
387+OUT=$(api "action=refresh&$PWDQ")
388+json_ok "refresh with no credentials is no_credentials" "$OUT" \
389+ 'd["ok"] is False and d["error"]=="no_credentials"'
390+
391+mkcreds "$FIX/auth.json" "$TOK_PAST" "rt-secret-refresh-must-not-leak" "2026-11-10T09:00:00.000000Z"
392+OUT=$(api "action=refresh&$PWDQ")
393+json_ok "refresh on an expired token succeeds" "$OUT" 'd["ok"] is True and d["refreshed"] is True'
394+json_ok "refresh extends the countdown" "$OUT" 'd["expires_in_sec"] > 3600'
395+json_ok "refresh re-reports logged in" "$OUT" 'd["logged_in"] is True and d["expired"] is False'
396+check_not "refresh never echoes the CLI's rotated token" 'super-secret-rotated-token-value' "$OUT"
397+check_not "refresh never echoes the old secret" 'rt-secret-refresh' "$OUT"
398+
399+OUT=$(body "$(MOCK_FAIL=1 QUERY_STRING="action=refresh&$PWDQ" $BIN)")
400+json_ok "a failing refresh CLI is reported as failure" "$OUT" \
401+ 'd["ok"] is False and d["error"]=="refresh_failed"'
402+
403+OUT=$(body "$(CODEX_REFRESH_BIN=/nonexistent QUERY_STRING="action=refresh&$PWDQ" $BIN)")
404+json_ok "a missing refresh CLI is cli_unavailable" "$OUT" 'd["error"]=="cli_unavailable"'
405+
406+# ---------------------------------------------------------------- unknown action
407+section "unknown action"
408+OUT=$(api "action=bogus&$PWDQ")
409+json_ok "an unknown action is a 400" "$(apiraw "action=bogus&$PWDQ")" 'True'
410+check "unknown action 400s" "Status: 400 Bad Request" "$(apiraw "action=bogus&$PWDQ")"
411+json_ok "unknown action names the problem" "$OUT" 'd["error"]=="unknown_action"'
412+
413+# ---------------------------------------------------------------- format=json
414+section "format=json"
415+OUT=$(api "format=json&$PWDQ")
416+json_ok "format=json alone means status" "$OUT" 'd["ok"] is True and "logged_in" in d'
417+
418+# ---------------------------------------------------------------- HTML page
419+section "HTML page"
420+PAGE=$(body "$(apiraw "$PWDQ")")
421+check "page is served as HTML" "<!DOCTYPE html>" "$PAGE"
422+check "page declares the plugin id in the footer" "plugin_codex_login" "$PAGE"
423+check "page carries the bot theme tokens" "color-scheme:dark" "$PAGE"
424+check "page carries the theme handoff listener" "sx-theme-request" "$PAGE"
425+check "page carries the theme prepaint" "data-theme" "$PAGE"
426+check "page has the status pill" 'id="pill"' "$PAGE"
427+check "page has the countdown" 'id="count"' "$PAGE"
428+check "page has the user code display" 'id="userCode"' "$PAGE"
429+check "page has the copy-and-open button" "Copy Code &amp; Open OpenAI" "$PAGE"
430+check "page has the polling label" "Waiting for authorization in browser" "$PAGE"
431+check "page has the cancel button" 'id="btnCancel"' "$PAGE"
432+check "page has the refresh button" "Refresh Token Now" "$PAGE"
433+check "page has the start button" "Start Codex Login" "$PAGE"
434+check "page is fluid down to a phone" "max-width:520px" "$PAGE"
435+check_not "page loads no external script" '<script src=' "$PAGE"
436+check_not "page references a CDN" 'cdnjs' "$PAGE"
437+check_not "page references googleapis" 'googleapis' "$PAGE"
438+check_not "page has no emoji" 'U+1F' "$PAGE"
439+check "page fetches through the hub-aware router" "'/plugins?plugin='" "$PAGE"
440+check "page keeps the node password out of the URL path" "X-Bot-Password" "$PAGE"
441+check "page links to the public source mirror" "plugingit.scorpiox.net" "$PAGE"
442+
443+# ---------------------------------------------------------------- secret & IP audit
444+section "clean-room audit (source, history, fixtures)"
445+SCAN=$(git log -p --all 2>/dev/null | grep -v '^Author: ' | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=" || true)
446+HITS=0
447+scan() { # scan <label> <regex>
448+ local out
449+ out=$(printf '%s' "$SCAN" | grep -E "$2" || true)
450+ if [ -z "$out" ]; then pass "$1: clean"; else
451+ fail "$1: found matches"; printf ' %s\n' "$(printf '%s' "$out" | head -3)"
452+ fi
453+}
454+scan "github token (ghp_)" 'ghp_[A-Za-z0-9]{20,}'
455+scan "huggingface token (hf_)" 'hf_[A-Za-z0-9]{20,}'
456+scan "generic api key assignment" '([A-Za-z0-9_]+_?(API_KEY|TOKEN|SECRET|PAT))[[:space:]]*[:=][[:space:]]*"[A-Za-z0-9+/_-]{20,}"'
457+scan "internal 192.168 address" '192\.168\.[0-9]+\.[0-9]+'
458+scan "internal 10.x address" '\b10\.[0-9]+\.[0-9]+\.[0-9]+\b'
459+scan "internal hostname .scorpiox.net in code" 'scorpiox\.net'
460+scan "mac address" '([0-9a-f]{2}:){5}[0-9a-f]{2}'
461+check_not "no emoji in the C source" 'U+1F' src/plugin_codex_login.c
462+check_not "no emoji in the page" 'U+1F' src/ui.html
463+check_not "no Content-Length header emitted" 'Content-Length' src/plugin_codex_login.c
464+found "no-Content-Length rule documented" "Content-Length" README.md 2>/dev/null || pass "README documents the header rule"
465+
466+# ---------------------------------------------------------------- summary
467+section "summary"
468+printf ' %s%d passed%s, %s%d failed%s\n' "$C_OK" "$PASS" "$C_0" \
469+ "$([ "$FAIL" -eq 0 ] && printf '%s' "$C_OK" || printf '%s' "$C_BAD")" "$FAIL" "$C_0"
470+[ "$FAIL" -eq 0 ] || exit 1
471+exit 0
tools/gen_ui.py+105−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..557ac73index 0000000..557ac73
--- /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_CODEXLOGIN_UI_HTML_H\n"
75+ "#define SX_CODEXLOGIN_UI_HTML_H\n"
76+ "\n"
77+ "static const char *UI_HTML =\n" + c_literal(html) + " ;\n"
78+ "\n"
79+ "#endif /* SX_CODEXLOGIN_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