scorpiox-bot-plugin-codex-login
←plugin_codex_login.cc
1811 lines · 59 KBHEADBlameDownload
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
122typedef struct {
123 char *p;
124 size_t n;
125 size_t cap;
126} buf_t;
127
128static void buf_init(buf_t *b)
129{
130 b->p = NULL;
131 b->n = 0;
132 b->cap = 0;
133}
134
135static 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
152static 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
160static 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
173static 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). */
188static 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
207static const char *buf_str(buf_t *b)
208{
209 if (!b->p) return "";
210 return b->p;
211}
212
213static 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
225static 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
250static 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
270static 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
306static 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). */
327static 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. */
347static 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
360static 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
372static 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. */
387static 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. */
400static 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
410static 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
418static 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
426static 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. */
436static int name_valid(const char *n)
437{
438 const char *p;
439
440 if (!n || !*n || strlen(n) > 64) return 0;
441 if (n[0] == '.') return 0;
442 for (p = n; *p; p++) {
443 unsigned char c = (unsigned char)*p;
444 if (!isalnum(c) && c != '-' && c != '_' && c != '.') return 0;
445 }
446 return 1;
447}
448
449static void resolve_account(const char *qs, char *out, size_t outsz)
450{
451 const char *env;
452
453 out[0] = '\0';
454 if (qs && get_query_val(qs, "account", out, outsz) && out[0]) {
455 /* A name that is not path-safe is dropped rather than sanitised: the
456 * only thing it can do is name a file, and silently rewriting it would
457 * make the panel report a different account than the one asked for. */
458 if (!name_valid(out)) out[0] = '\0';
459 else return;
460 }
461 env = getenv("CODEX_ACCOUNT");
462 if (env && *env && name_valid(env)) { snprintf(out, outsz, "%s", env); return; }
463}
464
465/* Where the credentials for the resolved account actually live. */
466static void active_creds_path(const char *account, char *out, size_t n)
467{
468 if (account && *account) account_path(account, out, n);
469 else creds_path(out, n);
470}
471
472static const char *login_bin(void)
473{
474 const char *e = getenv("CODEX_LOGIN_BIN");
475 return (e && *e) ? e : DEFAULT_LOGIN_BIN;
476}
477
478static const char *refresh_bin(void)
479{
480 const char *e = getenv("CODEX_REFRESH_BIN");
481 return (e && *e) ? e : DEFAULT_REFRESH_BIN;
482}
483
484static int file_exists(const char *p)
485{
486#if defined(_WIN32)
487 DWORD a = GetFileAttributesA(p);
488 return p && *p && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
489#else
490 struct stat st;
491 return p && *p && stat(p, &st) == 0 && S_ISREG(st.st_mode);
492#endif
493}
494
495/* Whole-file read; NULL on any failure. Caller frees. */
496static char *read_file(const char *path)
497{
498 FILE *f;
499 long sz;
500 char *buf;
501
502 if (!path || !*path) return NULL;
503 f = fopen(path, "rb");
504 if (!f) return NULL;
505 if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
506 sz = ftell(f);
507 if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; }
508 if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
509 buf = (char *)malloc((size_t)sz + 1);
510 if (!buf) { fclose(f); return NULL; }
511 if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
512 free(buf);
513 fclose(f);
514 return NULL;
515 }
516 buf[sz] = '\0';
517 fclose(f);
518 return buf;
519}
520
521static void trim_tail(char *s)
522{
523 size_t n;
524
525 if (!s) return;
526 n = strlen(s);
527 while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' ||
528 s[n - 1] == ' ' || s[n - 1] == '\t'))
529 s[--n] = '\0';
530}
531
532/* ------------------------------------------------------------------ */
533/* Minimal JSON field readers */
534/* ------------------------------------------------------------------ */
535
536/* Copy a JSON string value that starts at *pp (which points at the opening
537 * quote). Advances *pp past the closing quote. */
538static int json_read_string_at(const char **pp, char *out, size_t outsz)
539{
540 const char *p = *pp;
541 size_t i = 0;
542
543 if (!p || *p != '"') return 0;
544 p++;
545 while (*p && *p != '"') {
546 char c = *p;
547 if (c == '\\' && p[1]) {
548 p++;
549 switch (*p) {
550 case 'n': c = '\n'; break;
551 case 'r': c = '\r'; break;
552 case 't': c = '\t'; break;
553 case 'b': c = '\b'; break;
554 case 'f': c = '\f'; break;
555 case 'u': {
556 unsigned int v = 0;
557 int k;
558 p++;
559 for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++)
560 v = v * 16 + (unsigned int)(isdigit((unsigned char)*p)
561 ? *p - '0'
562 : tolower((unsigned char)*p) - 'a' + 10);
563 if (i + 1 < outsz) out[i++] = (char)(v & 0xff);
564 continue;
565 }
566 default: c = *p; break;
567 }
568 p++;
569 } else {
570 p++;
571 }
572 if (i + 1 < outsz) out[i++] = c;
573 }
574 if (*p == '"') p++;
575 if (outsz) out[i < outsz ? i : outsz - 1] = '\0';
576 *pp = p;
577 return 1;
578}
579
580/* Find "key":<value> inside the slice [obj, end) and return the value pointer.
581 * Only top-level keys of that slice are considered: a nested object or array
582 * is skipped as a whole. A caller almost always hands us the whole document,
583 * i.e. a pointer at the opening brace; that brace is skipped here so no call
584 * site needs a "+1" that is easy to forget and silent when it is missing. */
585static const char *json_find_key(const char *obj, const char *end, const char *key)
586{
587 size_t klen = strlen(key);
588 const char *p = obj;
589 int depth = 0;
590
591 if (!obj || !end || !key) return NULL;
592 while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++;
593 if (p < end && *p == '{') p++;
594
595 while (p && p < end) {
596 if (*p == '"') {
597 char name[128];
598 json_read_string_at(&p, name, sizeof(name));
599 if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) {
600 const char *q = p;
601 while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
602 if (q < end && *q == ':') {
603 q++;
604 while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
605 return (q < end) ? q : NULL;
606 }
607 }
608 continue;
609 }
610 if (*p == '{' || *p == '[') depth++;
611 else if (*p == '}' || *p == ']') depth--;
612 p++;
613 }
614 return NULL;
615}
616
617/* Bound the object that starts at *v (a value pointer from json_find_key).
618 * Returns 0 when the value is not an object. Strings inside the object are
619 * skipped with their escapes so a brace written inside a token cannot close
620 * the slice early. */
621static int json_obj_slice(const char *v, const char *end, const char **out,
622 const char **outend)
623{
624 const char *p;
625 int depth = 0;
626
627 if (!v || *v != '{') return 0;
628 for (p = v; p < end; p++) {
629 if (*p == '"') {
630 p++;
631 while (p < end && *p != '"') {
632 if (*p == '\\' && p + 1 < end) p++;
633 p++;
634 }
635 continue;
636 }
637 if (*p == '{') {
638 depth++;
639 if (depth == 1) *out = p;
640 } else if (*p == '}') {
641 depth--;
642 if (depth == 0) { *outend = p + 1; return 1; }
643 }
644 }
645 return 0;
646}
647
648/* Returns 0 and leaves *out untouched when the key is absent or null: several
649 * callers pass a field of a longer-lived struct, and clearing it on a miss
650 * silently erases a value that was already correct. */
651static int json_str_field(const char *obj, const char *end, const char *key,
652 char *out, size_t outsz)
653{
654 const char *v;
655
656 if (!out || outsz == 0) return 0;
657 v = json_find_key(obj, end, key);
658 if (!v || *v == 'n') return 0;
659 out[0] = '\0';
660 if (*v == '"') return json_read_string_at(&v, out, outsz);
661 {
662 size_t i = 0;
663 while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz)
664 out[i++] = *v++;
665 out[i] = '\0';
666 trim_tail(out);
667 return out[0] ? 1 : 0;
668 }
669}
670
671static int json_bool_field(const char *obj, const char *end, const char *key, int dflt)
672{
673 const char *v = json_find_key(obj, end, key);
674
675 if (!v) return dflt;
676 if (strncmp(v, "true", 4) == 0) return 1;
677 if (strncmp(v, "false", 5) == 0) return 0;
678 if (*v == '"')
679 return (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0);
680 if (*v == '1') return 1;
681 return 0;
682}
683
684static long long json_num_field(const char *obj, const char *end, const char *key)
685{
686 const char *v = json_find_key(obj, end, key);
687 long long vll = 0;
688 int neg = 0;
689
690 if (!v) return 0;
691 if (*v == '"') v++;
692 if (*v == '-') { neg = 1; v++; }
693 while (v < end && isdigit((unsigned char)*v)) vll = vll * 10 + (*v++ - '0');
694 return neg ? -vll : vll;
695}
696
697/* True when the object holds a non-empty string under key. Used for token
698 * presence without ever copying the token itself into a wider buffer. */
699static int json_str_present(const char *obj, const char *end, const char *key)
700{
701 const char *v = json_find_key(obj, end, key);
702 const char *q;
703
704 if (!v || *v != '"') return 0;
705 q = v + 1;
706 while (q < end && *q != '"') {
707 if (*q == '\\' && q + 1 < end) { q += 2; continue; }
708 return 1; /* at least one real character */
709 }
710 return 0; /* "" - present but empty */
711}
712
713/* ------------------------------------------------------------------ */
714/* Reading a JWT lifetime */
715/* ------------------------------------------------------------------ */
716
717/* auth.json carries no expiry field, so the countdown has to come from the
718 * access token itself: a JWT is header.payload.signature, the payload is
719 * base64url, and the payload JSON has an "exp" claim in seconds. Decoding
720 * base64url is twelve lines and needs no library, which is what makes the
721 * expiry readable on a node that has no SCORPIOX CODE installed. */
722static int b64url_val(char c)
723{
724 if (c >= 'A' && c <= 'Z') return c - 'A';
725 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
726 if (c >= '0' && c <= '9') return c - '0' + 52;
727 if (c == '-' || c == '+') return 62;
728 if (c == '_' || c == '/') return 63;
729 return -1;
730}
731
732/* Decode a base64url run of in_len characters into out (caller-sized). Returns
733 * the number of bytes written, or -1 on malformed input. */
734static int b64url_decode(const char *in, size_t in_len, char *out, size_t outsz)
735{
736 unsigned long acc = 0;
737 int nbits = 0;
738 size_t i = 0;
739 size_t o = 0;
740
741 for (; i < in_len; i++) {
742 int v;
743 if (in[i] == '=' || in[i] == '\n' || in[i] == '\r' || in[i] == ' ') continue;
744 v = b64url_val(in[i]);
745 if (v < 0) return -1;
746 acc = (acc << 6) | (unsigned long)v;
747 nbits += 6;
748 if (nbits >= 8) {
749 char b = (char)((acc >> (nbits - 8)) & 0xff);
750 nbits -= 8;
751 if (o >= outsz) return -1;
752 out[o++] = b;
753 }
754 }
755 return (int)o;
756}
757
758/* Pull the "exp" claim (unix seconds) out of a JWT. Returns 0 when the token
759 * is not a decodable JWT, which the caller treats as "expiry unknown". */
760static long long jwt_exp_seconds(const char *jwt)
761{
762 const char *dot1, *dot2, *payload;
763 size_t plen;
764 long long exp = 0;
765 char *dec;
766 size_t cap;
767
768 if (!jwt || !*jwt) return 0;
769 dot1 = strchr(jwt, '.');
770 if (!dot1) return 0;
771 payload = dot1 + 1;
772 dot2 = strchr(payload, '.');
773 if (!dot2) return 0;
774 plen = (size_t)(dot2 - payload);
775 if (plen == 0 || plen > 8192) return 0;
776
777 cap = (plen / 4 + 1) * 3 + 1;
778 dec = (char *)malloc(cap);
779 if (!dec) return 0;
780 {
781 int n = b64url_decode(payload, plen, dec, cap - 1);
782 if (n <= 0) { free(dec); return 0; }
783 dec[n] = '\0';
784 exp = json_num_field(dec, dec + n, "exp");
785 }
786 free(dec);
787 return exp;
788}
789
790/* ------------------------------------------------------------------ */
791/* Running the node's login CLI */
792/* ------------------------------------------------------------------ */
793
794/* Quote one argv element for the shell popen() uses. POSIX: single quotes with
795 * the standard close-escape-reopen trick. Windows: double quotes, which is
796 * what cmd.exe accepts. */
797static void shell_quote_into(const char *in, char *out, size_t outsz)
798{
799 size_t o = 0;
800 const char *p;
801
802 if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
803#if defined(_WIN32)
804 out[o++] = '"';
805 for (p = in; p && *p; p++) {
806 if (*p == '"') {
807 if (o + 3 >= outsz) break;
808 out[o++] = '\\';
809 out[o++] = '"';
810 } else {
811 if (o + 2 >= outsz) break;
812 out[o++] = *p;
813 }
814 }
815 out[o++] = '"';
816 out[o] = '\0';
817#else
818 out[o++] = '\'';
819 for (p = in; p && *p; p++) {
820 if (*p == '\'') {
821 if (o + 5 >= outsz) break;
822 memcpy(out + o, "'\\''", 4);
823 o += 4;
824 } else {
825 if (o + 2 >= outsz) break;
826 out[o++] = *p;
827 }
828 }
829 out[o++] = '\'';
830 out[o] = '\0';
831#endif
832}
833
834/* Run `<bin> <args>` and capture stdout. args may be NULL or a pre-built shell
835 * fragment. Returns 1 when the process ran,
836 * 0 when popen() itself failed,
837 * -1 when the binary is not on this node ("command not found").
838 *
839 * pclose() hands back a WAIT STATUS, not an exit code: a missing command
840 * arrives as 32512 (127 << 8) and a non-executable one as 32256 (126 << 8).
841 * Both mean "this node cannot run the tool", which is a different message from
842 * "the tool ran and said no", so both are reported as -1 here. Treating them as
843 * the tool's own failure would say "refresh failed" about a node that simply
844 * has no SCORPIOX CODE installed. */
845static int run_capture(const char *bin, const char *args, buf_t *out)
846{
847 char cmd[CMD_SZ];
848 char qbin[FIELD_SZ];
849 FILE *f;
850 char line[2048];
851 size_t total = 0;
852 int rc;
853
854 if (!bin || !*bin) return 0;
855 shell_quote_into(bin, qbin, sizeof(qbin));
856#if defined(_WIN32)
857 if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>NUL", qbin, args);
858 else snprintf(cmd, sizeof(cmd), "%s 2>NUL", qbin);
859#else
860 if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args);
861 else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin);
862#endif
863
864 f = popen(cmd, "r");
865 if (!f) return 0;
866 while (fgets(line, sizeof(line), f)) {
867 total += strlen(line);
868 if (total > OUT_MAX) break;
869 buf_adds(out, line);
870 }
871 rc = pclose(f);
872
873 if (out->p) {
874 size_t n = out->n;
875 while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0';
876 out->n = n;
877 }
878 if (rc != -1) {
879 int status = (rc >> 8) & 0xff;
880 if (status == 127 || status == 126) return -1;
881 }
882 return 1;
883}
884
885/* The CLIs print human progress before the final JSON line, so take the LAST
886 * line that starts with '{'. */
887static const char *last_json_line(buf_t *b)
888{
889 size_t i;
890 const char *last = NULL;
891
892 if (!b || !b->p) return NULL;
893 for (i = 0; i < b->n; i++) {
894 int at_line_start = (i == 0) || b->p[i - 1] == '\n';
895 if (at_line_start && b->p[i] == '{') last = b->p + i;
896 }
897 return last;
898}
899
900/* ------------------------------------------------------------------ */
901/* Status assembly */
902/* ------------------------------------------------------------------ */
903
904/* An ISO-8601 UTC stamp ("2026-06-12T03:46:19.123456Z") to unix seconds. The
905 * fields are read positionally because the format is fixed; a leap-safe
906 * conversion is not needed, only a monotone reference for "last refreshed". */
907static long long iso8601_to_sec(const char *s)
908{
909 int y = 0, mo = 0, d = 0, h = 0, mi = 0, se = 0;
910 static const int cum[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
911 long long days;
912 int i;
913
914 if (!s || strlen(s) < 19) return 0;
915 for (i = 0; i < 4 && isdigit((unsigned char)s[i]); i++) y = y * 10 + (s[i] - '0');
916 for (i = 5; i < 7 && isdigit((unsigned char)s[i]); i++) mo = mo * 10 + (s[i] - '0');
917 for (i = 8; i < 10 && isdigit((unsigned char)s[i]); i++) d = d * 10 + (s[i] - '0');
918 for (i = 11; i < 13 && isdigit((unsigned char)s[i]); i++) h = h * 10 + (s[i] - '0');
919 for (i = 14; i < 16 && isdigit((unsigned char)s[i]); i++) mi = mi * 10 + (s[i] - '0');
920 for (i = 17; i < 19 && isdigit((unsigned char)s[i]); i++) se = se * 10 + (s[i] - '0');
921 if (y < 1970 || mo < 1 || mo > 12 || d < 1 || d > 31) return 0;
922 days = (long long)(y - 1970) * 365 + (y - 1969) / 4 + cum[mo - 1] + d - 1;
923 if (mo > 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)) days++;
924 return days * 86400LL + h * 3600LL + mi * 60LL + se;
925}
926
927typedef struct {
928 char name[NAME_SZ];
929 int present;
930 int logged_in;
931 int has_refresh;
932 int expired;
933 long long expires_at; /* unix seconds, 0 = unknown */
934 long long expires_in_sec; /* negative when expired, 0 when unknown */
935} account_t;
936
937typedef struct {
938 int logged_in;
939 int has_refresh;
940 int pending;
941 int expired;
942 int cli_present;
943 int cli_ran;
944 int profile_exists;
945 int api_key_present;
946 char account[NAME_SZ];
947 char path[PATH_SZ];
948 char profile[NAME_SZ];
949 char profile_file[PATH_SZ];
950 char account_id[NAME_SZ];
951 char cli_error[FIELD_SZ];
952 long long expires_at; /* unix seconds, 0 = unknown */
953 long long expires_in_sec; /* long long on purpose: a 32-bit int
954 * overflows past 2038 and turns a live
955 * session into "expired 60 years ago" */
956 long long last_refresh; /* unix seconds, 0 = unknown */
957 long long pending_age; /* seconds since the marker was written, -1 */
958 account_t accounts[MAX_ACCOUNTS];
959 int account_count;
960} status_t;
961
962/* Parse one credentials file (the default file and every named account file
963 * share this shape):
964 *
965 * {"OPENAI_API_KEY": null,
966 * "tokens": {"id_token":"...","access_token":"...","refresh_token":"...",
967 * "account_id":"..."},
968 * "last_refresh":"2026-06-12T03:46:19.123456Z"}
969 *
970 * The tokens live inside "tokens", so the slice handed to the readers is the
971 * tokens object, not the document: matching at document level would find
972 * nothing and report a live session as "not connected". */
973static void scan_creds(const char *json, status_t *st, account_t *acc)
974{
975 const char *tok, *tokend;
976 const char *docend;
977 char acctbuf[NAME_SZ] = {0};
978 char access[4096];
979 long long exp = 0;
980
981 if (!json) return;
982 docend = json + strlen(json);
983
984 tok = json_find_key(json, docend, "tokens");
985 if (!tok || !json_obj_slice(tok, docend, &tok, &tokend)) {
986 /* A flat file (some fixtures put the tokens at the top level) is still
987 * a session if an access token is there, so fall back to the document. */
988 tok = json;
989 tokend = docend;
990 }
991
992 /* An empty string is not a session. json_str_field reports a hit for ""
993 * as well, so the length is what decides, not the presence of the key. */
994 if (json_str_field(tok, tokend, "access_token", access, sizeof(access)) &&
995 access[0]) {
996 exp = jwt_exp_seconds(access);
997 st->logged_in = 1;
998 } else if (json_str_present(tok, tokend, "access_token")) {
999 /* A token too long for the scratch buffer still counts: the decoder
1000 * needs only the payload between the first two dots, and a real JWT
1001 * payload never runs past a few hundred bytes, so a truncated copy is
1002 * enough to read the exp claim. */
1003 st->logged_in = 1;
1004 }
1005 if (json_str_present(tok, tokend, "refresh_token")) {
1006 st->has_refresh = 1;
1007 if (acc) acc->has_refresh = 1;
1008 }
1009 if (json_str_field(tok, tokend, "account_id", acctbuf, sizeof(acctbuf)) && acctbuf[0])
1010 snprintf(st->account_id, sizeof(st->account_id), "%s", acctbuf);
1011 if (json_str_present(tok, tokend, "OPENAI_API_KEY") ||
1012 json_str_present(json, docend, "OPENAI_API_KEY"))
1013 st->api_key_present = 1;
1014
1015 if (exp > 0) st->expires_at = exp;
1016 {
1017 char iso[64] = {0};
1018 if (json_str_field(json, docend, "last_refresh", iso, sizeof(iso))) {
1019 long long lr = iso8601_to_sec(iso);
1020 if (lr > 0) st->last_refresh = lr;
1021 }
1022 }
1023 if (acc) {
1024 acc->logged_in = st->logged_in;
1025 acc->expires_at = st->expires_at;
1026 }
1027}
1028
1029/* Read the profile file the login CLI creates (--create-profile). */
1030static void scan_profile(status_t *st)
1031{
1032 char *text;
1033
1034 profile_path(st->profile_file, sizeof(st->profile_file));
1035 st->profile_exists = file_exists(st->profile_file);
1036 if (!st->profile_exists) return;
1037 snprintf(st->profile, sizeof(st->profile), "codex");
1038
1039 text = read_file(st->profile_file);
1040 if (!text) return;
1041 {
1042 const char *p = text;
1043 while (*p) {
1044 if (strncmp(p, "CODEX_ACCOUNT=", 12) == 0) {
1045 size_t i = 0;
1046 p += 12;
1047 while (*p && *p != '\n' && *p != '\r' && i + 1 < sizeof(st->account))
1048 st->account[i++] = *p++;
1049 st->account[i] = '\0';
1050 break;
1051 }
1052 while (*p && *p != '\n') p++;
1053 if (*p) p++;
1054 }
1055 }
1056 free(text);
1057}
1058
1059/* List the json files under ~/.codex/accounts. Each has the same shape as auth.json, so
1060 * the same reader is reused; the file name is the account name. */
1061static void scan_accounts(status_t *st, long long now_sec)
1062{
1063 char d[PATH_SZ];
1064
1065 st->account_count = 0;
1066 accounts_dir(d, sizeof(d));
1067
1068#if defined(_WIN32)
1069 {
1070 char pattern[PATH_SZ];
1071 WIN32_FIND_DATAA fd;
1072 HANDLE h;
1073
1074 snprintf(pattern, sizeof(pattern), "%s\\*.json", d);
1075 h = FindFirstFileA(pattern, &fd);
1076 if (h == INVALID_HANDLE_VALUE) return;
1077 do {
1078 size_t ln;
1079 account_t *a;
1080 char p[PATH_SZ];
1081 char *json;
1082
1083 ln = strlen(fd.cFileName);
1084 if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
1085 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
1086 a = &st->accounts[st->account_count];
1087 memset(a, 0, sizeof(*a));
1088 snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName);
1089 if (!name_valid(a->name)) continue;
1090 snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, fd.cFileName);
1091 a->present = 1;
1092 json = read_file(p);
1093 if (json) {
1094 status_t tmp;
1095 memset(&tmp, 0, sizeof(tmp));
1096 scan_creds(json, &tmp, a);
1097 free(json);
1098 a->expires_at = tmp.expires_at;
1099 }
1100 if (a->expires_at > 0 && a->logged_in) {
1101 a->expires_in_sec = a->expires_at - now_sec;
1102 a->expired = a->expires_in_sec <= 0;
1103 }
1104 st->account_count++;
1105 } while (FindNextFileA(h, &fd));
1106 FindClose(h);
1107 }
1108#else
1109 {
1110 DIR *dp = opendir(d);
1111 struct dirent *de;
1112
1113 if (!dp) return;
1114 while ((de = readdir(dp)) != NULL) {
1115 size_t ln = strlen(de->d_name);
1116 account_t *a;
1117 char p[PATH_SZ];
1118 char *json;
1119
1120 if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
1121 if (strcmp(de->d_name + ln - 5, ".json") != 0) continue;
1122 a = &st->accounts[st->account_count];
1123 memset(a, 0, sizeof(*a));
1124 snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), de->d_name);
1125 if (!name_valid(a->name)) continue;
1126 snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, de->d_name);
1127 a->present = 1;
1128 json = read_file(p);
1129 if (json) {
1130 status_t tmp;
1131 memset(&tmp, 0, sizeof(tmp));
1132 scan_creds(json, &tmp, a);
1133 free(json);
1134 a->expires_at = tmp.expires_at;
1135 }
1136 if (a->expires_at > 0 && a->logged_in) {
1137 a->expires_in_sec = a->expires_at - now_sec;
1138 a->expired = a->expires_in_sec <= 0;
1139 }
1140 st->account_count++;
1141 }
1142 closedir(dp);
1143 }
1144#endif
1145}
1146
1147/* Ask the login CLI what it sees, and let it ADD to what the files already
1148 * proved. The file-derived values win where they disagree: the CLI reports
1149 * expires_at 0 because auth.json has no expiry field, so a CLI answer of 0
1150 * must never clear a countdown this plugin computed from the token itself. */
1151static void scan_cli(status_t *st, const char *name, int file_read)
1152{
1153 buf_t out;
1154 const char *j;
1155 char args[NAME_SZ + 32];
1156
1157 buf_init(&out);
1158 if (name && *name) snprintf(args, sizeof(args), "--status --name %s", name);
1159 else snprintf(args, sizeof(args), "--status");
1160
1161 {
1162 int rc = run_capture(login_bin(), args, &out);
1163 if (rc <= 0) {
1164 st->cli_present = 0;
1165 st->cli_ran = 0;
1166 snprintf(st->cli_error, sizeof(st->cli_error), "%s",
1167 rc == -1 ? "the login CLI is not on this node"
1168 : "could not start the login CLI");
1169 buf_free(&out);
1170 return;
1171 }
1172 }
1173 st->cli_ran = 1;
1174
1175 j = last_json_line(&out);
1176 if (!j) {
1177 st->cli_present = 1;
1178 buf_free(&out);
1179 return;
1180 }
1181 st->cli_present = 1;
1182 {
1183 const char *end = j + strlen(j);
1184 long long e;
1185 char acct[NAME_SZ] = {0};
1186
1187 /* file_read tells the difference between "this node has no readable
1188 * credential file" and "the file is here and says nothing". In the
1189 * second case the file wins: the CLI decides logged_in by grepping for
1190 * the key name, so an empty "access_token": "" reads as a session
1191 * there and as no session in the file. */
1192 if (!file_read) {
1193 if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1;
1194 if (json_bool_field(j, end, "has_refresh", 0)) st->has_refresh = 1;
1195 }
1196 if (json_bool_field(j, end, "pending", 0)) st->pending = 1;
1197 e = json_num_field(j, end, "expires_at");
1198 if (e > 0) {
1199 long long sec = (e > 100000000000LL) ? (e / 1000) : e;
1200 if (st->expires_at == 0 || sec > st->expires_at) st->expires_at = sec;
1201 }
1202 if (!st->account[0] && json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0])
1203 snprintf(st->account, sizeof(st->account), "%s", acct);
1204 if (!json_bool_field(j, end, "ok", 1))
1205 json_str_field(j, end, "error", st->cli_error, sizeof(st->cli_error));
1206 }
1207 buf_free(&out);
1208}
1209
1210static void collect_status(status_t *st, const char *name)
1211{
1212 char *json;
1213 long long now_sec = (long long)time(NULL);
1214 int file_read = 0;
1215
1216 memset(st, 0, sizeof(*st));
1217 st->pending_age = -1;
1218
1219 /* A named account lives in ~/.codex/accounts/<name>.json, which is the
1220 * same schema as the default credentials file. */
1221 if (name && *name) {
1222 char p[PATH_SZ];
1223 account_path(name, p, sizeof(p));
1224 snprintf(st->path, sizeof(st->path), "%s", p);
1225 snprintf(st->account, sizeof(st->account), "%s", name);
1226 } else {
1227 creds_path(st->path, sizeof(st->path));
1228 }
1229
1230 json = read_file(st->path);
1231 if (json) {
1232 scan_creds(json, st, NULL);
1233 free(json);
1234 file_read = 1;
1235 }
1236
1237 scan_cli(st, name, file_read);
1238 scan_profile(st);
1239
1240 /* The pending marker is the only evidence available without a network, and
1241 * it carries the CLI's own creation stamp, so the TTL is applied here
1242 * rather than trusting a later claim. */
1243 {
1244 char pp[PATH_SZ];
1245 pending_path(name, pp, sizeof(pp));
1246 if (file_exists(pp)) {
1247 char *pend = read_file(pp);
1248 long long created = 0;
1249 if (pend) {
1250 const char *pe = pend + strlen(pend);
1251 created = json_num_field(pend, pe, "created");
1252 free(pend);
1253 }
1254 if (created > 0) {
1255 st->pending_age = now_sec - created;
1256 st->pending = (st->pending_age >= 0 && st->pending_age <= PENDING_TTL_SEC);
1257 } else {
1258 st->pending = 1; /* unreadable marker: assume still open */
1259 }
1260 }
1261 }
1262
1263 if (st->expires_at > 0) {
1264 st->expires_in_sec = st->expires_at - now_sec;
1265 st->expired = st->expires_in_sec <= 0;
1266 }
1267 if (!st->logged_in) {
1268 st->expired = 0;
1269 st->expires_in_sec = 0;
1270 }
1271 if (!st->account[0] && st->logged_in)
1272 snprintf(st->account, sizeof(st->account), "default");
1273 if (!st->profile[0] && st->profile_exists)
1274 snprintf(st->profile, sizeof(st->profile), "codex");
1275
1276 scan_accounts(st, now_sec);
1277}
1278
1279/* One status object, shared by every action so the UI always re-renders from
1280 * the same shape. */
1281static void emit_status(buf_t *b, const status_t *st)
1282{
1283 int i;
1284
1285 buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false");
1286 buf_addf(b, "\"expires_at\":%lld", st->expires_at);
1287 buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec);
1288 buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
1289 buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
1290 buf_adds(b, ",\"account\":");
1291 buf_json(b, st->account);
1292 buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
1293 buf_addf(b, ",\"pending_age_sec\":%lld", st->pending_age);
1294 buf_addf(b, ",\"last_refresh\":%lld", st->last_refresh);
1295 buf_adds(b, ",\"account_id\":");
1296 buf_json(b, st->account_id);
1297 buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false");
1298 buf_adds(b, ",\"credentials_path\":");
1299 buf_json(b, st->path);
1300 buf_adds(b, ",\"profile\":");
1301 buf_json(b, st->profile);
1302 buf_addf(b, ",\"profile_exists\":%s", st->profile_exists ? "true" : "false");
1303 buf_addf(b, ",\"named_accounts\":%s", st->account_count > 0 ? "true" : "false");
1304 buf_addf(b, ",\"api_key_present\":%s", st->api_key_present ? "true" : "false");
1305 buf_adds(b, ",\"cli_error\":");
1306 buf_json(b, st->cli_error);
1307
1308 buf_adds(b, ",\"accounts\":[");
1309 for (i = 0; i < st->account_count; i++) {
1310 const account_t *a = &st->accounts[i];
1311 if (i) buf_addc(b, ',');
1312 buf_adds(b, "{\"name\":");
1313 buf_json(b, a->name);
1314 buf_addf(b, ",\"logged_in\":%s", a->logged_in ? "true" : "false");
1315 buf_addf(b, ",\"has_refresh\":%s", a->has_refresh ? "true" : "false");
1316 buf_addf(b, ",\"expires_at\":%lld", a->expires_at);
1317 buf_addf(b, ",\"expires_in_sec\":%lld", a->expires_in_sec);
1318 buf_addf(b, ",\"expired\":%s}", a->expired ? "true" : "false");
1319 }
1320 buf_addc(b, ']');
1321}
1322
1323/* ------------------------------------------------------------------ */
1324/* Actions */
1325/* ------------------------------------------------------------------ */
1326
1327static void json_headers(void)
1328{
1329 fputs("Content-Type: application/json; charset=utf-8\r\n"
1330 "Cache-Control: no-store\r\n"
1331 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1332}
1333
1334static void emit_json(buf_t *b)
1335{
1336 json_headers();
1337 fputs(buf_str(b), stdout);
1338 buf_free(b);
1339}
1340
1341static void emit_error(int code, const char *status, const char *err, const char *detail)
1342{
1343 buf_t b;
1344
1345 buf_init(&b);
1346 buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n"
1347 "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",
1348 code, status);
1349 buf_adds(&b, "{\"ok\":false,\"error\":");
1350 buf_json(&b, err);
1351 if (detail && *detail) {
1352 buf_adds(&b, ",\"detail\":");
1353 buf_json(&b, detail);
1354 }
1355 buf_adds(&b, "}\n");
1356 fputs(buf_str(&b), stdout);
1357 buf_free(&b);
1358}
1359
1360/* Build "<flag> --name <q>" once, so every action addresses the same account. */
1361static void account_args(const char *name, const char *flag, char *out, size_t n)
1362{
1363 if (name && *name) {
1364 char qname[NAME_SZ * 2];
1365 shell_quote_into(name, qname, sizeof(qname));
1366 snprintf(out, n, "%s --name %s", flag, qname);
1367 } else {
1368 snprintf(out, n, "%s", flag);
1369 }
1370}
1371
1372static int action_status(const char *name)
1373{
1374 status_t st;
1375 buf_t b;
1376
1377 collect_status(&st, name);
1378 buf_init(&b);
1379 buf_adds(&b, "{\"ok\":true,\"state\":\"done\",");
1380 emit_status(&b, &st);
1381 buf_adds(&b, "}\n");
1382 emit_json(&b);
1383 return 0;
1384}
1385
1386static int action_start(const char *name, int force)
1387{
1388 status_t st;
1389 buf_t in, out;
1390 const char *j;
1391 char args[NAME_SZ * 2 + 40];
1392 char verify[URL_SZ] = {0};
1393 char code[CODE_SZ] = {0};
1394 char err[FIELD_SZ] = {0};
1395 char detail[FIELD_SZ] = {0};
1396 long long expires_in = PENDING_TTL_SEC;
1397 int interval = 5;
1398 int rc;
1399
1400 collect_status(&st, name);
1401 if (!st.cli_present) {
1402 emit_error(200, "OK", "cli_unavailable",
1403 "scorpiox-codex-login is not on this node; install SCORPIOX CODE "
1404 "or set CODEX_LOGIN_BIN");
1405 return 0;
1406 }
1407
1408 account_args(name, force ? "--start --force" : "--start", args, sizeof(args));
1409 buf_init(&in);
1410 rc = run_capture(login_bin(), args, &in);
1411 if (rc <= 0) {
1412 buf_free(&in);
1413 emit_error(rc == -1 ? 200 : 500, rc == -1 ? "OK" : "Internal Server Error",
1414 "cli_unavailable", "could not run the login CLI");
1415 return 0;
1416 }
1417 j = last_json_line(&in);
1418 if (!j) {
1419 buf_free(&in);
1420 emit_error(502, "Bad Gateway", "start_failed",
1421 "the login CLI produced no JSON; check its output");
1422 return 1;
1423 }
1424 {
1425 const char *je = j + strlen(j);
1426 if (!json_bool_field(j, je, "ok", 1)) {
1427 json_str_field(j, je, "error", err, sizeof(err));
1428 json_str_field(j, je, "detail", detail, sizeof(detail));
1429 buf_free(&in);
1430 if (strcmp(err, "exists") == 0) {
1431 /* Credentials are already on this node: the honest answer is
1432 * "already signed in, press re-login to replace them". */
1433 buf_init(&out);
1434 buf_adds(&out, "{\"ok\":true,\"already_logged_in\":true,\"pending\":false");
1435 buf_adds(&out, ",\"error\":\"already_logged_in\"");
1436 buf_adds(&out, ",\"detail\":");
1437 buf_json(&out, detail[0] ? detail : "credentials already exist");
1438 buf_adds(&out, ",\"logged_in\":");
1439 buf_adds(&out, st.logged_in ? "true" : "false");
1440 buf_adds(&out, ",\"hint\":\"pass force=1 to replace the existing session\"}\n");
1441 emit_json(&out);
1442 return 0;
1443 }
1444 emit_error(200, "OK", err[0] ? err : "start_failed", detail);
1445 return 0;
1446 }
1447 json_str_field(j, je, "verify_url", verify, sizeof(verify));
1448 json_str_field(j, je, "user_code", code, sizeof(code));
1449 interval = (int)json_num_field(j, je, "interval");
1450 expires_in = json_num_field(j, je, "expires_in");
1451 if (interval < 1) interval = 5;
1452 if (expires_in <= 0) expires_in = PENDING_TTL_SEC;
1453 }
1454 buf_free(&in);
1455
1456 if (!verify[0] || !code[0]) {
1457 emit_error(502, "Bad Gateway", "start_incomplete",
1458 "login CLI did not return a verify url and user code");
1459 return 1;
1460 }
1461
1462 buf_init(&out);
1463 buf_addf(&out, "{\"ok\":true,\"flow\":\"device_code\",\"verify_url\":");
1464 buf_json(&out, verify);
1465 buf_adds(&out, ",\"user_code\":");
1466 buf_json(&out, code);
1467 buf_addf(&out, ",\"expires_in\":%lld", expires_in);
1468 buf_addf(&out, ",\"interval\":%d", interval);
1469 buf_adds(&out, ",\"pending\":true");
1470 buf_adds(&out, ",\"provider\":\"codex\"}\n");
1471 emit_json(&out);
1472 return 0;
1473}
1474
1475/* One non-blocking poll. The CLI does exactly one HTTPS round trip and returns;
1476 * the UI drives the cadence so nothing here ever blocks. */
1477static int action_poll(const char *name)
1478{
1479 status_t st;
1480 buf_t in, out;
1481 const char *j;
1482 char state[64] = {0};
1483 char args[NAME_SZ * 2 + 16];
1484 int rc;
1485
1486 collect_status(&st, name);
1487 if (!st.cli_present) {
1488 emit_error(200, "OK", "cli_unavailable",
1489 "scorpiox-codex-login is not on this node");
1490 return 0;
1491 }
1492
1493 account_args(name, "--poll", args, sizeof(args));
1494 buf_init(&in);
1495 rc = run_capture(login_bin(), args, &in);
1496 if (rc < 0) {
1497 buf_free(&in);
1498 emit_error(200, "OK", "cli_unavailable",
1499 "scorpiox-codex-login is not on this node");
1500 return 0;
1501 }
1502 if (rc == 0) {
1503 buf_free(&in);
1504 emit_error(500, "Internal Server Error", "poll_failed", "cannot spawn login CLI");
1505 return 1;
1506 }
1507
1508 j = last_json_line(&in);
1509 if (!j) {
1510 buf_free(&in);
1511 /* No JSON at all. Fall back to what the files say: a credential file
1512 * that appeared while polling is a success no matter what the CLI
1513 * printed, and a marker that vanished with no credentials is a dead
1514 * flow, not an infinite spinner. */
1515 if (st.logged_in) {
1516 buf_init(&out);
1517 buf_adds(&out, "{\"ok\":true,\"state\":\"done\",");
1518 emit_status(&out, &st);
1519 buf_adds(&out, "}\n");
1520 emit_json(&out);
1521 return 0;
1522 }
1523 emit_error(502, "Bad Gateway", "poll_failed", "login CLI produced no JSON");
1524 return 1;
1525 }
1526 {
1527 const char *je = j + strlen(j);
1528 json_str_field(j, je, "state", state, sizeof(state));
1529 if (!json_bool_field(j, je, "ok", 0)) {
1530 char err[FIELD_SZ] = {0};
1531 char detail[FIELD_SZ] = {0};
1532 json_str_field(j, je, "error", err, sizeof(err));
1533 json_str_field(j, je, "detail", detail, sizeof(detail));
1534 buf_free(&in);
1535 /* expired / no_pending / denied are terminal, not transient. */
1536 buf_init(&out);
1537 buf_adds(&out, "{\"ok\":true,\"state\":\"failed\"");
1538 buf_adds(&out, ",\"error\":");
1539 buf_json(&out, err[0] ? err : "poll_failed");
1540 if (detail[0]) {
1541 buf_adds(&out, ",\"detail\":");
1542 buf_json(&out, detail);
1543 }
1544 buf_adds(&out, ",\"pending\":false}\n");
1545 emit_json(&out);
1546 return 0;
1547 }
1548 if (strcmp(state, "pending") == 0) {
1549 long long iv = json_num_field(j, je, "interval");
1550 buf_free(&in);
1551 buf_init(&out);
1552 buf_adds(&out, "{\"ok\":true,\"state\":\"pending\"");
1553 buf_addf(&out, ",\"interval\":%d", iv > 0 ? (int)iv : 5);
1554 buf_adds(&out, ",\"pending\":true");
1555 {
1556 status_t after;
1557 collect_status(&after, name);
1558 if (after.logged_in) {
1559 /* The CLI still says pending but the file is there: report
1560 * the truth the file tells. */
1561 buf_adds(&out, ",\"logged_in\":true");
1562 }
1563 }
1564 buf_adds(&out, "}\n");
1565 emit_json(&out);
1566 return 0;
1567 }
1568 /* state == "done" */
1569 buf_free(&in);
1570 {
1571 status_t after;
1572 collect_status(&after, name);
1573 buf_init(&out);
1574 buf_adds(&out, "{\"ok\":true,\"state\":\"done\",");
1575 emit_status(&out, &after);
1576 buf_adds(&out, "}\n");
1577 emit_json(&out);
1578 }
1579 return 0;
1580 }
1581}
1582
1583static int action_cancel(const char *name)
1584{
1585 status_t st;
1586 buf_t in, out;
1587 char args[NAME_SZ * 2 + 16];
1588
1589 collect_status(&st, name);
1590 if (!st.cli_present) {
1591 /* Nothing to abort and no CLI to tell: drop the marker ourselves so the
1592 * UI spinner stops on a node without SCORPIOX CODE. */
1593 char pp[PATH_SZ];
1594 pending_path(name, pp, sizeof(pp));
1595 if (file_exists(pp)) remove(pp);
1596 buf_init(&out);
1597 buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false,"
1598 "\"cli_present\":false}\n");
1599 emit_json(&out);
1600 return 0;
1601 }
1602
1603 account_args(name, "--cancel", args, sizeof(args));
1604 buf_init(&in);
1605 {
1606 int rc = run_capture(login_bin(), args, &in);
1607 if (rc < 0) {
1608 buf_free(&in);
1609 emit_error(200, "OK", "cli_unavailable",
1610 "scorpiox-codex-login is not on this node");
1611 return 0;
1612 }
1613 {
1614 const char *j = last_json_line(&in);
1615 int ok = 1;
1616 if (j) {
1617 const char *je = j + strlen(j);
1618 ok = json_bool_field(j, je, "ok", 1);
1619 }
1620 buf_free(&in);
1621 if (!ok) {
1622 emit_error(200, "OK", "cancel_failed", "login CLI rejected the cancel");
1623 return 0;
1624 }
1625 /* The CLI removes the marker; re-collect to report the truth. */
1626 {
1627 status_t after;
1628 collect_status(&after, name);
1629 buf_init(&out);
1630 buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",");
1631 emit_status(&out, &after);
1632 buf_adds(&out, "}\n");
1633 emit_json(&out);
1634 }
1635 }
1636 }
1637 return 0;
1638}
1639
1640/* Refresh: the refresh CLI performs the refresh-token grant and updates the
1641 * credential file in place. Its stdout is human text (and with --verbose may
1642 * quote token material), so the payload is read, then discarded. The new state
1643 * is proven by re-reading the file, not by the CLI's word. */
1644static int action_refresh(const char *name)
1645{
1646 buf_t out, b;
1647 char args[PATH_SZ + 96];
1648 char qpath[PATH_SZ * 2];
1649 char path[PATH_SZ];
1650 long long before;
1651 status_t st;
1652
1653 active_creds_path(name, path, sizeof(path));
1654
1655 if (!file_exists(path)) {
1656 buf_init(&b);
1657 buf_adds(&b, "{\"ok\":false,\"error\":\"no_credentials\",\"detail\":");
1658 buf_json(&b, "there is no credential file for this account on this node; "
1659 "start a login first");
1660 buf_adds(&b, "}\n");
1661 emit_json(&b);
1662 return 1;
1663 }
1664
1665 collect_status(&st, name);
1666 before = st.expires_at;
1667
1668 shell_quote_into(path, qpath, sizeof(qpath));
1669 /* action=refresh means "refresh now", so the CLI is always invoked with
1670 * --force: without it the CLI no-ops on a still-valid token and the user's
1671 * button does nothing. */
1672 snprintf(args, sizeof(args), "--credentials-file %s --force", qpath);
1673
1674 buf_init(&out);
1675 {
1676 int rc = run_capture(refresh_bin(), args, &out);
1677 if (rc <= 0) {
1678 buf_free(&out);
1679 emit_error(200, "OK", "cli_unavailable",
1680 "the refresh CLI is not on this node; install SCORPIOX CODE "
1681 "or set CODEX_REFRESH_BIN");
1682 return 1;
1683 }
1684 }
1685 buf_free(&out);
1686
1687 collect_status(&st, name);
1688 if (!st.logged_in || (before > 0 && st.expires_at <= before && !st.expired)) {
1689 buf_init(&b);
1690 buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":");
1691 buf_json(&b, "the refresh CLI did not extend the token in the credential "
1692 "file; sign in again");
1693 buf_adds(&b, "}\n");
1694 emit_json(&b);
1695 return 1;
1696 }
1697
1698 buf_init(&b);
1699 buf_adds(&b, "{\"ok\":true,\"refreshed\":true,");
1700 emit_status(&b, &st);
1701 buf_adds(&b, "}\n");
1702 emit_json(&b);
1703 return 0;
1704}
1705
1706/* ------------------------------------------------------------------ */
1707/* HTML emission */
1708/* ------------------------------------------------------------------ */
1709
1710/* Expand the two placeholders tools/gen_ui.py leaves in UI_HTML. Keeping the
1711 * split means the palette lives in exactly one place (bot_theme_plugin.h) and
1712 * the page can never drift away from the bot's own theme. */
1713static void emit_ui(void)
1714{
1715 const char *p = UI_HTML;
1716
1717 while (*p) {
1718 if (*p == '\001') {
1719 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout);
1720 p++;
1721 } else if (*p == '\002') {
1722 /* SX_BOT_THEME_HANDOFF is a complete <script> element, so it is
1723 * emitted as a sibling of the page's own script. */
1724 fputs(SX_BOT_THEME_HANDOFF, stdout);
1725 p++;
1726 } else {
1727 fputc(*p, stdout);
1728 p++;
1729 }
1730 }
1731}
1732
1733static void serve_html(void)
1734{
1735 const char *qs = getenv("QUERY_STRING");
1736 int embed = (qs && (strstr(qs, "embed=1") || strstr(qs, "embed=true")));
1737
1738 fputs("Content-Type: text/html; charset=utf-8\r\n"
1739 "Cache-Control: no-store\r\n"
1740 "X-Content-Type-Options: nosniff\r\n"
1741 "X-Frame-Options: SAMEORIGIN\r\n"
1742 "Referrer-Policy: same-origin\r\n\r\n", stdout);
1743
1744 /* The embed flag (?embed=1) is handled inside the page itself: the theme
1745 * prepaint script that comes from bot_theme_plugin.h reads it before the
1746 * first frame and marks <html> as embedded, which is what hides the back
1747 * link and the theme toggle. Nothing to do here but keep the header. */
1748 (void)embed;
1749 emit_ui();
1750}
1751
1752/* ------------------------------------------------------------------ */
1753/* Entry point */
1754/* ------------------------------------------------------------------ */
1755
1756int main(int argc, char **argv)
1757{
1758 const char *qs;
1759 char action[64] = {0};
1760 char account[NAME_SZ] = {0};
1761 char fmt[32] = {0};
1762
1763 /* 1. Discovery metadata. Must stay unauthenticated. */
1764 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1765 puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}");
1766 return 0;
1767 }
1768 if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
1769 puts(PLUGIN_ID " " PLUGIN_VER);
1770 return 0;
1771 }
1772
1773 require_node_auth();
1774
1775 qs = getenv("QUERY_STRING");
1776 if (!qs) qs = "";
1777
1778 /* 2. JSON API mode. `format=json` alone means "status", which is what a
1779 * dashboard polls. */
1780 if (query_has(qs, "action") || query_has(qs, "format")) {
1781 int force = 0;
1782
1783 get_query_val(qs, "action", action, sizeof(action));
1784 get_query_val(qs, "format", fmt, sizeof(fmt));
1785 {
1786 char f[16] = {0};
1787 if (get_query_val(qs, "force", f, sizeof(f)) &&
1788 (strcmp(f, "1") == 0 || strcmp(f, "true") == 0))
1789 force = 1;
1790 }
1791 resolve_account(qs, account, sizeof(account));
1792
1793 if (!action[0] && strcmp(fmt, "json") == 0)
1794 snprintf(action, sizeof(action), "status");
1795
1796 if (strcmp(action, "status") == 0 || !action[0]) return action_status(account);
1797 if (strcmp(action, "start") == 0) return action_start(account, force);
1798 if (strcmp(action, "poll") == 0) return action_poll(account);
1799 if (strcmp(action, "cancel") == 0) return action_cancel(account);
1800 if (strcmp(action, "refresh") == 0) return action_refresh(account);
1801 if (strcmp(action, "accounts") == 0) return action_status(account);
1802
1803 emit_error(400, "Bad Request", "unknown_action",
1804 "expected status, start, poll, cancel, refresh or accounts");
1805 return 1;
1806 }
1807
1808 /* 3. HTML UI */
1809 serve_html();
1810 return 0;
1811}