/* * plugin_codex_login - SCORPIOX BOT open-source OpenAI Codex device-code login * and account token manager for your node. * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata * 2. ?action=... / ?format=json -> JSON node API * 3. GET (default) -> responsive HTML UI * * DESIGN NOTE (why there is no TLS in this binary): the Codex device flow is a * sequence of HTTPS POSTs to the provider, and a public clean-room repository * must not carry a client secret or a vendored TLS stack. So this plugin does * not speak TLS at all. It drives the node's own login CLI, exactly the way the * SCORPIOX CODE login tools are meant to be driven (the machine mode contract: * --status / --start / --poll / --cancel, one JSON line per call), and it reads * the credential files that CLI writes: * * ~/.codex/auth.json (default account) * ~/.codex/accounts/.json (named accounts) * ~/.claude/.login-pending/codex-.json (pending device flow) * ~/.claude/scorpiox-env/codex.txt (the profile the CLI creates) * * auth.json holds no expiry field, so the expiry is read out of the access * token itself: a JWT carries its lifetime in the "exp" claim of its payload, * and a JWT payload is base64url text, which this file decodes with its own * twelve-line decoder. That is what makes the countdown work on a node that * has SCORPIOX CODE installed and on one that does not. * * Everything is overridable for deterministic offline testing: * * CODEX_CREDS_PATH the credential json (default ~/.codex/auth.json); * a relocated file also relocates the account * directory and the pending directory * CODEX_ACCOUNTS_DIR directory of .json account files * CODEX_PENDING_DIR directory holding codex-.json markers * CODEX_ENV_DIR profile directory (codex.txt) * CODEX_LOGIN_BIN login CLI (default scorpiox-codex-login) * CODEX_REFRESH_BIN refresh CLI (default scorpiox-codex-refreshtoken) * CODEX_ACCOUNT account to operate on (or ?account= per request) * * No token is ever printed, logged or returned by this plugin: the API reports * presence and expiry only, and the refresh action discards whatever its CLI * prints and proves the result by re-reading the file. * * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under * scorpiox-server on the node. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Must come before every include on Windows: MinGW defaults to 0x502 * (Server 2003), which hides the Win7+ APIs and the path helpers. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 # if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # include #else # include # include # include # include #endif #include "bot_theme_plugin.h" #include "ui_html.h" #define PLUGIN_SLUG "codex-login" #define PLUGIN_ID "plugin_codex_login" #define PLUGIN_VER "1.0.0" #define PLUGIN_NAME "codex" #define PLUGIN_DESC "Codex login" #define PATH_SZ 1024 #define NAME_SZ 96 #define CODE_SZ 64 #define URL_SZ 1024 #define CMD_SZ 4096 #define OUT_MAX (256 * 1024) #define FIELD_SZ 512 #define MAX_ACCOUNTS 64 #define DEFAULT_LOGIN_BIN "scorpiox-codex-login" #define DEFAULT_REFRESH_BIN "scorpiox-codex-refreshtoken" /* The pending device-flow marker the login CLI writes and removes. Its TTL * matches the CLI's own (900 s); the plugin uses it only to decide whether the * UI should show a live polling indicator, never to authorise anything. */ #define PENDING_TTL_SEC 900 #if defined(_WIN32) # define PATH_SEP '\\' #else # define PATH_SEP '/' #endif /* ------------------------------------------------------------------ */ /* Growable byte buffer */ /* ------------------------------------------------------------------ */ typedef struct { char *p; size_t n; size_t cap; } buf_t; static void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } static int buf_need(buf_t *b, size_t extra) { size_t want = b->n + extra + 1; char *np; if (want <= b->cap) return 1; if (b->cap == 0) b->cap = 1024; while (b->cap < want) { if (b->cap > (size_t)32 * 1024 * 1024) return 0; b->cap *= 2; } np = (char *)realloc(b->p, b->cap); if (!np) return 0; b->p = np; return 1; } static int buf_addc(buf_t *b, char c) { if (!buf_need(b, 1)) return 0; b->p[b->n++] = c; b->p[b->n] = '\0'; return 1; } static int buf_adds(buf_t *b, const char *s) { size_t len; if (!s) return 1; len = strlen(s); if (!buf_need(b, len)) return 0; memcpy(b->p + b->n, s, len); b->n += len; b->p[b->n] = '\0'; return 1; } static int buf_addf(buf_t *b, const char *fmt, ...) { char tmp[2048]; va_list ap; int n; va_start(ap, fmt); n = vsnprintf(tmp, sizeof(tmp), fmt, ap); va_end(ap); if (n < 0) return 0; if ((size_t)n >= sizeof(tmp)) n = (int)sizeof(tmp) - 1; return buf_adds(b, tmp); } /* Append s as a JSON string literal (escapes control characters). */ static int buf_json(buf_t *b, const char *s) { if (!buf_addc(b, '"')) return 0; for (; s && *s; s++) { unsigned char c = (unsigned char)*s; switch (c) { case '"': if (!buf_adds(b, "\\\"")) return 0; continue; case '\\': if (!buf_adds(b, "\\\\")) return 0; continue; case '\n': if (!buf_adds(b, "\\n")) return 0; continue; case '\r': if (!buf_adds(b, "\\r")) return 0; continue; case '\t': if (!buf_adds(b, "\\t")) return 0; continue; default: break; } if (c < 0x20) { if (!buf_addf(b, "\\u%04x", c)) return 0; } else if (!buf_addc(b, (char)c)) return 0; } return buf_addc(b, '"'); } static const char *buf_str(buf_t *b) { if (!b->p) return ""; return b->p; } static void buf_free(buf_t *b) { free(b->p); b->p = NULL; b->n = 0; b->cap = 0; } /* ------------------------------------------------------------------ */ /* Query string */ /* ------------------------------------------------------------------ */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); p = qs; while (*p) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { size_t i = 0; p += klen + 1; while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; out[i] = '\0'; return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } static int query_has(const char *qs, const char *key) { size_t klen = strlen(key); const char *p = qs; while (p && *p) { if (strncmp(p, key, klen) == 0 && (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) return 1; p = strchr(p, '&'); if (!p) break; p++; } return 0; } /* ------------------------------------------------------------------ */ /* Node auth (X-Bot-Password / Bearer / ?pwd=) */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; char qpwd[256] = {0}; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncasecmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Filesystem helpers */ /* ------------------------------------------------------------------ */ static const char *home_dir(void) { #if defined(_WIN32) static char home[512]; if (GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)) > 0) return home; if (GetEnvironmentVariableA("HOME", home, sizeof(home)) > 0) return home; { char tmp[512]; if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) { snprintf(home, sizeof(home), "%s", tmp); return home; } } return NULL; #else const char *h = getenv("HOME"); return (h && *h) ? h : NULL; #endif } /* Copy the directory part of a path (including the trailing separator). */ static void dir_of(const char *path, char *out, size_t n) { char base[PATH_SZ]; char *slash; if (!path) { if (n) out[0] = '\0'; return; } snprintf(base, sizeof(base), "%s", path); slash = strrchr(base, PATH_SEP); #if defined(_WIN32) if (!slash) slash = strrchr(base, '/'); #endif if (slash) *(slash + 1) = '\0'; else base[0] = '\0'; snprintf(out, n, "%s", base); } /* The .codex directory. A relocated credentials file implies a relocated tree: * the same CLI writes auth.json, accounts/ and the profile into one place, so * reading one from the override and the rest from $HOME reports an empty state * for a session that has one. */ static void codex_dir(char *out, size_t n) { const char *env = getenv("CODEX_CREDS_PATH"); const char *home = home_dir(); if (env && *env) { dir_of(env, out, n); if (out[0]) return; } if (home && *home) { snprintf(out, n, "%s%c.codex%c", home, PATH_SEP, PATH_SEP); return; } snprintf(out, n, ".codex%c", PATH_SEP); } static void creds_path(char *out, size_t n) { const char *env = getenv("CODEX_CREDS_PATH"); if (env && *env) { snprintf(out, n, "%s", env); return; } { char d[PATH_SZ]; codex_dir(d, sizeof(d)); snprintf(out, n, "%sauth.json", d); } } static void accounts_dir(char *out, size_t n) { const char *env = getenv("CODEX_ACCOUNTS_DIR"); if (env && *env) { snprintf(out, n, "%s", env); return; } { char d[PATH_SZ]; codex_dir(d, sizeof(d)); snprintf(out, n, "%saccounts", d); } } /* The pending device-flow markers live under ~/.claude/.login-pending exactly * like every other SCORPIOX CODE login tool, so a relocated .codex tree does * NOT move them: they belong to the bot's own contract, not to the provider. */ static void pending_dir(char *out, size_t n) { const char *env = getenv("CODEX_PENDING_DIR"); const char *home = home_dir(); if (env && *env) { snprintf(out, n, "%s", env); return; } if (!home) { snprintf(out, n, ".login-pending%c", PATH_SEP); return; } snprintf(out, n, "%s%c.claude%c.login-pending", home, PATH_SEP, PATH_SEP); } /* SCORPIOX CODE profiles for every provider share one directory, so the * codex profile is not under .codex: it is ~/.claude/scorpiox-env/codex.txt, * exactly where the login CLI writes it. */ static void env_dir(char *out, size_t n) { const char *env = getenv("CODEX_ENV_DIR"); const char *home = home_dir(); if (env && *env) { snprintf(out, n, "%s", env); return; } if (!home) { snprintf(out, n, "scorpiox-env%c", PATH_SEP); return; } snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP); } static void pending_path(const char *name, char *out, size_t n) { char d[PATH_SZ]; pending_dir(d, sizeof(d)); snprintf(out, n, "%s%ccodex-%s.json", d, PATH_SEP, (name && *name) ? name : "default"); } static void profile_path(char *out, size_t n) { char d[PATH_SZ]; env_dir(d, sizeof(d)); snprintf(out, n, "%s%ccodex.txt", d, PATH_SEP); } static void account_path(const char *name, char *out, size_t n) { char d[PATH_SZ]; accounts_dir(d, sizeof(d)); snprintf(out, n, "%s%c%s.json", d, PATH_SEP, name); } /* Resolve the account this request operates on: ?account= wins, then * CODEX_ACCOUNT, then the default file. */ static int name_valid(const char *n) { const char *p; if (!n || !*n || strlen(n) > 64) return 0; if (n[0] == '.') return 0; for (p = n; *p; p++) { unsigned char c = (unsigned char)*p; if (!isalnum(c) && c != '-' && c != '_' && c != '.') return 0; } return 1; } static void resolve_account(const char *qs, char *out, size_t outsz) { const char *env; out[0] = '\0'; if (qs && get_query_val(qs, "account", out, outsz) && out[0]) { /* A name that is not path-safe is dropped rather than sanitised: the * only thing it can do is name a file, and silently rewriting it would * make the panel report a different account than the one asked for. */ if (!name_valid(out)) out[0] = '\0'; else return; } env = getenv("CODEX_ACCOUNT"); if (env && *env && name_valid(env)) { snprintf(out, outsz, "%s", env); return; } } /* Where the credentials for the resolved account actually live. */ static void active_creds_path(const char *account, char *out, size_t n) { if (account && *account) account_path(account, out, n); else creds_path(out, n); } static const char *login_bin(void) { const char *e = getenv("CODEX_LOGIN_BIN"); return (e && *e) ? e : DEFAULT_LOGIN_BIN; } static const char *refresh_bin(void) { const char *e = getenv("CODEX_REFRESH_BIN"); return (e && *e) ? e : DEFAULT_REFRESH_BIN; } static int file_exists(const char *p) { #if defined(_WIN32) DWORD a = GetFileAttributesA(p); return p && *p && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); #else struct stat st; return p && *p && stat(p, &st) == 0 && S_ISREG(st.st_mode); #endif } /* Whole-file read; NULL on any failure. Caller frees. */ static char *read_file(const char *path) { FILE *f; long sz; char *buf; if (!path || !*path) return NULL; f = fopen(path, "rb"); if (!f) return NULL; if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } sz = ftell(f); if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } buf = (char *)malloc((size_t)sz + 1); if (!buf) { fclose(f); return NULL; } if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { free(buf); fclose(f); return NULL; } buf[sz] = '\0'; fclose(f); return buf; } static void trim_tail(char *s) { size_t n; if (!s) return; n = strlen(s); while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' || s[n - 1] == ' ' || s[n - 1] == '\t')) s[--n] = '\0'; } /* ------------------------------------------------------------------ */ /* Minimal JSON field readers */ /* ------------------------------------------------------------------ */ /* Copy a JSON string value that starts at *pp (which points at the opening * quote). Advances *pp past the closing quote. */ static int json_read_string_at(const char **pp, char *out, size_t outsz) { const char *p = *pp; size_t i = 0; if (!p || *p != '"') return 0; p++; while (*p && *p != '"') { char c = *p; if (c == '\\' && p[1]) { p++; switch (*p) { case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'u': { unsigned int v = 0; int k; p++; for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) ? *p - '0' : tolower((unsigned char)*p) - 'a' + 10); if (i + 1 < outsz) out[i++] = (char)(v & 0xff); continue; } default: c = *p; break; } p++; } else { p++; } if (i + 1 < outsz) out[i++] = c; } if (*p == '"') p++; if (outsz) out[i < outsz ? i : outsz - 1] = '\0'; *pp = p; return 1; } /* Find "key": inside the slice [obj, end) and return the value pointer. * Only top-level keys of that slice are considered: a nested object or array * is skipped as a whole. A caller almost always hands us the whole document, * i.e. a pointer at the opening brace; that brace is skipped here so no call * site needs a "+1" that is easy to forget and silent when it is missing. */ static const char *json_find_key(const char *obj, const char *end, const char *key) { size_t klen = strlen(key); const char *p = obj; int depth = 0; if (!obj || !end || !key) return NULL; while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; if (p < end && *p == '{') p++; while (p && p < end) { if (*p == '"') { char name[128]; json_read_string_at(&p, name, sizeof(name)); if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { const char *q = p; while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; if (q < end && *q == ':') { q++; while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; return (q < end) ? q : NULL; } } continue; } if (*p == '{' || *p == '[') depth++; else if (*p == '}' || *p == ']') depth--; p++; } return NULL; } /* Bound the object that starts at *v (a value pointer from json_find_key). * Returns 0 when the value is not an object. Strings inside the object are * skipped with their escapes so a brace written inside a token cannot close * the slice early. */ static int json_obj_slice(const char *v, const char *end, const char **out, const char **outend) { const char *p; int depth = 0; if (!v || *v != '{') return 0; for (p = v; p < end; p++) { if (*p == '"') { p++; while (p < end && *p != '"') { if (*p == '\\' && p + 1 < end) p++; p++; } continue; } if (*p == '{') { depth++; if (depth == 1) *out = p; } else if (*p == '}') { depth--; if (depth == 0) { *outend = p + 1; return 1; } } } return 0; } /* Returns 0 and leaves *out untouched when the key is absent or null: several * callers pass a field of a longer-lived struct, and clearing it on a miss * silently erases a value that was already correct. */ static int json_str_field(const char *obj, const char *end, const char *key, char *out, size_t outsz) { const char *v; if (!out || outsz == 0) return 0; v = json_find_key(obj, end, key); if (!v || *v == 'n') return 0; out[0] = '\0'; if (*v == '"') return json_read_string_at(&v, out, outsz); { size_t i = 0; while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; trim_tail(out); return out[0] ? 1 : 0; } } static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) { const char *v = json_find_key(obj, end, key); if (!v) return dflt; if (strncmp(v, "true", 4) == 0) return 1; if (strncmp(v, "false", 5) == 0) return 0; if (*v == '"') return (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0); if (*v == '1') return 1; return 0; } static long long json_num_field(const char *obj, const char *end, const char *key) { const char *v = json_find_key(obj, end, key); long long vll = 0; int neg = 0; if (!v) return 0; if (*v == '"') v++; if (*v == '-') { neg = 1; v++; } while (v < end && isdigit((unsigned char)*v)) vll = vll * 10 + (*v++ - '0'); return neg ? -vll : vll; } /* True when the object holds a non-empty string under key. Used for token * presence without ever copying the token itself into a wider buffer. */ static int json_str_present(const char *obj, const char *end, const char *key) { const char *v = json_find_key(obj, end, key); const char *q; if (!v || *v != '"') return 0; q = v + 1; while (q < end && *q != '"') { if (*q == '\\' && q + 1 < end) { q += 2; continue; } return 1; /* at least one real character */ } return 0; /* "" - present but empty */ } /* ------------------------------------------------------------------ */ /* Reading a JWT lifetime */ /* ------------------------------------------------------------------ */ /* auth.json carries no expiry field, so the countdown has to come from the * access token itself: a JWT is header.payload.signature, the payload is * base64url, and the payload JSON has an "exp" claim in seconds. Decoding * base64url is twelve lines and needs no library, which is what makes the * expiry readable on a node that has no SCORPIOX CODE installed. */ static int b64url_val(char c) { if (c >= 'A' && c <= 'Z') return c - 'A'; if (c >= 'a' && c <= 'z') return c - 'a' + 26; if (c >= '0' && c <= '9') return c - '0' + 52; if (c == '-' || c == '+') return 62; if (c == '_' || c == '/') return 63; return -1; } /* Decode a base64url run of in_len characters into out (caller-sized). Returns * the number of bytes written, or -1 on malformed input. */ static int b64url_decode(const char *in, size_t in_len, char *out, size_t outsz) { unsigned long acc = 0; int nbits = 0; size_t i = 0; size_t o = 0; for (; i < in_len; i++) { int v; if (in[i] == '=' || in[i] == '\n' || in[i] == '\r' || in[i] == ' ') continue; v = b64url_val(in[i]); if (v < 0) return -1; acc = (acc << 6) | (unsigned long)v; nbits += 6; if (nbits >= 8) { char b = (char)((acc >> (nbits - 8)) & 0xff); nbits -= 8; if (o >= outsz) return -1; out[o++] = b; } } return (int)o; } /* Pull the "exp" claim (unix seconds) out of a JWT. Returns 0 when the token * is not a decodable JWT, which the caller treats as "expiry unknown". */ static long long jwt_exp_seconds(const char *jwt) { const char *dot1, *dot2, *payload; size_t plen; long long exp = 0; char *dec; size_t cap; if (!jwt || !*jwt) return 0; dot1 = strchr(jwt, '.'); if (!dot1) return 0; payload = dot1 + 1; dot2 = strchr(payload, '.'); if (!dot2) return 0; plen = (size_t)(dot2 - payload); if (plen == 0 || plen > 8192) return 0; cap = (plen / 4 + 1) * 3 + 1; dec = (char *)malloc(cap); if (!dec) return 0; { int n = b64url_decode(payload, plen, dec, cap - 1); if (n <= 0) { free(dec); return 0; } dec[n] = '\0'; exp = json_num_field(dec, dec + n, "exp"); } free(dec); return exp; } /* ------------------------------------------------------------------ */ /* Running the node's login CLI */ /* ------------------------------------------------------------------ */ /* Quote one argv element for the shell popen() uses. POSIX: single quotes with * the standard close-escape-reopen trick. Windows: double quotes, which is * what cmd.exe accepts. */ static void shell_quote_into(const char *in, char *out, size_t outsz) { size_t o = 0; const char *p; if (outsz < 3) { if (outsz) out[0] = '\0'; return; } #if defined(_WIN32) out[o++] = '"'; for (p = in; p && *p; p++) { if (*p == '"') { if (o + 3 >= outsz) break; out[o++] = '\\'; out[o++] = '"'; } else { if (o + 2 >= outsz) break; out[o++] = *p; } } out[o++] = '"'; out[o] = '\0'; #else out[o++] = '\''; for (p = in; p && *p; p++) { if (*p == '\'') { if (o + 5 >= outsz) break; memcpy(out + o, "'\\''", 4); o += 4; } else { if (o + 2 >= outsz) break; out[o++] = *p; } } out[o++] = '\''; out[o] = '\0'; #endif } /* Run ` ` and capture stdout. args may be NULL or a pre-built shell * fragment. Returns 1 when the process ran, * 0 when popen() itself failed, * -1 when the binary is not on this node ("command not found"). * * pclose() hands back a WAIT STATUS, not an exit code: a missing command * arrives as 32512 (127 << 8) and a non-executable one as 32256 (126 << 8). * Both mean "this node cannot run the tool", which is a different message from * "the tool ran and said no", so both are reported as -1 here. Treating them as * the tool's own failure would say "refresh failed" about a node that simply * has no SCORPIOX CODE installed. */ static int run_capture(const char *bin, const char *args, buf_t *out) { char cmd[CMD_SZ]; char qbin[FIELD_SZ]; FILE *f; char line[2048]; size_t total = 0; int rc; if (!bin || !*bin) return 0; shell_quote_into(bin, qbin, sizeof(qbin)); #if defined(_WIN32) if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>NUL", qbin, args); else snprintf(cmd, sizeof(cmd), "%s 2>NUL", qbin); #else if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args); else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin); #endif f = popen(cmd, "r"); if (!f) return 0; while (fgets(line, sizeof(line), f)) { total += strlen(line); if (total > OUT_MAX) break; buf_adds(out, line); } rc = pclose(f); if (out->p) { size_t n = out->n; while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0'; out->n = n; } if (rc != -1) { int status = (rc >> 8) & 0xff; if (status == 127 || status == 126) return -1; } return 1; } /* The CLIs print human progress before the final JSON line, so take the LAST * line that starts with '{'. */ static const char *last_json_line(buf_t *b) { size_t i; const char *last = NULL; if (!b || !b->p) return NULL; for (i = 0; i < b->n; i++) { int at_line_start = (i == 0) || b->p[i - 1] == '\n'; if (at_line_start && b->p[i] == '{') last = b->p + i; } return last; } /* ------------------------------------------------------------------ */ /* Status assembly */ /* ------------------------------------------------------------------ */ /* An ISO-8601 UTC stamp ("2026-06-12T03:46:19.123456Z") to unix seconds. The * fields are read positionally because the format is fixed; a leap-safe * conversion is not needed, only a monotone reference for "last refreshed". */ static long long iso8601_to_sec(const char *s) { int y = 0, mo = 0, d = 0, h = 0, mi = 0, se = 0; static const int cum[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; long long days; int i; if (!s || strlen(s) < 19) return 0; for (i = 0; i < 4 && isdigit((unsigned char)s[i]); i++) y = y * 10 + (s[i] - '0'); for (i = 5; i < 7 && isdigit((unsigned char)s[i]); i++) mo = mo * 10 + (s[i] - '0'); for (i = 8; i < 10 && isdigit((unsigned char)s[i]); i++) d = d * 10 + (s[i] - '0'); for (i = 11; i < 13 && isdigit((unsigned char)s[i]); i++) h = h * 10 + (s[i] - '0'); for (i = 14; i < 16 && isdigit((unsigned char)s[i]); i++) mi = mi * 10 + (s[i] - '0'); for (i = 17; i < 19 && isdigit((unsigned char)s[i]); i++) se = se * 10 + (s[i] - '0'); if (y < 1970 || mo < 1 || mo > 12 || d < 1 || d > 31) return 0; days = (long long)(y - 1970) * 365 + (y - 1969) / 4 + cum[mo - 1] + d - 1; if (mo > 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)) days++; return days * 86400LL + h * 3600LL + mi * 60LL + se; } typedef struct { char name[NAME_SZ]; int present; int logged_in; int has_refresh; int expired; long long expires_at; /* unix seconds, 0 = unknown */ long long expires_in_sec; /* negative when expired, 0 when unknown */ } account_t; typedef struct { int logged_in; int has_refresh; int pending; int expired; int cli_present; int cli_ran; int profile_exists; int api_key_present; char account[NAME_SZ]; char path[PATH_SZ]; char profile[NAME_SZ]; char profile_file[PATH_SZ]; char account_id[NAME_SZ]; char cli_error[FIELD_SZ]; long long expires_at; /* unix seconds, 0 = unknown */ long long expires_in_sec; /* long long on purpose: a 32-bit int * overflows past 2038 and turns a live * session into "expired 60 years ago" */ long long last_refresh; /* unix seconds, 0 = unknown */ long long pending_age; /* seconds since the marker was written, -1 */ account_t accounts[MAX_ACCOUNTS]; int account_count; } status_t; /* Parse one credentials file (the default file and every named account file * share this shape): * * {"OPENAI_API_KEY": null, * "tokens": {"id_token":"...","access_token":"...","refresh_token":"...", * "account_id":"..."}, * "last_refresh":"2026-06-12T03:46:19.123456Z"} * * The tokens live inside "tokens", so the slice handed to the readers is the * tokens object, not the document: matching at document level would find * nothing and report a live session as "not connected". */ static void scan_creds(const char *json, status_t *st, account_t *acc) { const char *tok, *tokend; const char *docend; char acctbuf[NAME_SZ] = {0}; char access[4096]; long long exp = 0; if (!json) return; docend = json + strlen(json); tok = json_find_key(json, docend, "tokens"); if (!tok || !json_obj_slice(tok, docend, &tok, &tokend)) { /* A flat file (some fixtures put the tokens at the top level) is still * a session if an access token is there, so fall back to the document. */ tok = json; tokend = docend; } /* An empty string is not a session. json_str_field reports a hit for "" * as well, so the length is what decides, not the presence of the key. */ if (json_str_field(tok, tokend, "access_token", access, sizeof(access)) && access[0]) { exp = jwt_exp_seconds(access); st->logged_in = 1; } else if (json_str_present(tok, tokend, "access_token")) { /* A token too long for the scratch buffer still counts: the decoder * needs only the payload between the first two dots, and a real JWT * payload never runs past a few hundred bytes, so a truncated copy is * enough to read the exp claim. */ st->logged_in = 1; } if (json_str_present(tok, tokend, "refresh_token")) { st->has_refresh = 1; if (acc) acc->has_refresh = 1; } if (json_str_field(tok, tokend, "account_id", acctbuf, sizeof(acctbuf)) && acctbuf[0]) snprintf(st->account_id, sizeof(st->account_id), "%s", acctbuf); if (json_str_present(tok, tokend, "OPENAI_API_KEY") || json_str_present(json, docend, "OPENAI_API_KEY")) st->api_key_present = 1; if (exp > 0) st->expires_at = exp; { char iso[64] = {0}; if (json_str_field(json, docend, "last_refresh", iso, sizeof(iso))) { long long lr = iso8601_to_sec(iso); if (lr > 0) st->last_refresh = lr; } } if (acc) { acc->logged_in = st->logged_in; acc->expires_at = st->expires_at; } } /* Read the profile file the login CLI creates (--create-profile). */ static void scan_profile(status_t *st) { char *text; profile_path(st->profile_file, sizeof(st->profile_file)); st->profile_exists = file_exists(st->profile_file); if (!st->profile_exists) return; snprintf(st->profile, sizeof(st->profile), "codex"); text = read_file(st->profile_file); if (!text) return; { const char *p = text; while (*p) { if (strncmp(p, "CODEX_ACCOUNT=", 12) == 0) { size_t i = 0; p += 12; while (*p && *p != '\n' && *p != '\r' && i + 1 < sizeof(st->account)) st->account[i++] = *p++; st->account[i] = '\0'; break; } while (*p && *p != '\n') p++; if (*p) p++; } } free(text); } /* List the json files under ~/.codex/accounts. Each has the same shape as auth.json, so * the same reader is reused; the file name is the account name. */ static void scan_accounts(status_t *st, long long now_sec) { char d[PATH_SZ]; st->account_count = 0; accounts_dir(d, sizeof(d)); #if defined(_WIN32) { char pattern[PATH_SZ]; WIN32_FIND_DATAA fd; HANDLE h; snprintf(pattern, sizeof(pattern), "%s\\*.json", d); h = FindFirstFileA(pattern, &fd); if (h == INVALID_HANDLE_VALUE) return; do { size_t ln; account_t *a; char p[PATH_SZ]; char *json; ln = strlen(fd.cFileName); if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue; if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; a = &st->accounts[st->account_count]; memset(a, 0, sizeof(*a)); snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName); if (!name_valid(a->name)) continue; snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, fd.cFileName); a->present = 1; json = read_file(p); if (json) { status_t tmp; memset(&tmp, 0, sizeof(tmp)); scan_creds(json, &tmp, a); free(json); a->expires_at = tmp.expires_at; } if (a->expires_at > 0 && a->logged_in) { a->expires_in_sec = a->expires_at - now_sec; a->expired = a->expires_in_sec <= 0; } st->account_count++; } while (FindNextFileA(h, &fd)); FindClose(h); } #else { DIR *dp = opendir(d); struct dirent *de; if (!dp) return; while ((de = readdir(dp)) != NULL) { size_t ln = strlen(de->d_name); account_t *a; char p[PATH_SZ]; char *json; if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue; if (strcmp(de->d_name + ln - 5, ".json") != 0) continue; a = &st->accounts[st->account_count]; memset(a, 0, sizeof(*a)); snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), de->d_name); if (!name_valid(a->name)) continue; snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, de->d_name); a->present = 1; json = read_file(p); if (json) { status_t tmp; memset(&tmp, 0, sizeof(tmp)); scan_creds(json, &tmp, a); free(json); a->expires_at = tmp.expires_at; } if (a->expires_at > 0 && a->logged_in) { a->expires_in_sec = a->expires_at - now_sec; a->expired = a->expires_in_sec <= 0; } st->account_count++; } closedir(dp); } #endif } /* Ask the login CLI what it sees, and let it ADD to what the files already * proved. The file-derived values win where they disagree: the CLI reports * expires_at 0 because auth.json has no expiry field, so a CLI answer of 0 * must never clear a countdown this plugin computed from the token itself. */ static void scan_cli(status_t *st, const char *name, int file_read) { buf_t out; const char *j; char args[NAME_SZ + 32]; buf_init(&out); if (name && *name) snprintf(args, sizeof(args), "--status --name %s", name); else snprintf(args, sizeof(args), "--status"); { int rc = run_capture(login_bin(), args, &out); if (rc <= 0) { st->cli_present = 0; st->cli_ran = 0; snprintf(st->cli_error, sizeof(st->cli_error), "%s", rc == -1 ? "the login CLI is not on this node" : "could not start the login CLI"); buf_free(&out); return; } } st->cli_ran = 1; j = last_json_line(&out); if (!j) { st->cli_present = 1; buf_free(&out); return; } st->cli_present = 1; { const char *end = j + strlen(j); long long e; char acct[NAME_SZ] = {0}; /* file_read tells the difference between "this node has no readable * credential file" and "the file is here and says nothing". In the * second case the file wins: the CLI decides logged_in by grepping for * the key name, so an empty "access_token": "" reads as a session * there and as no session in the file. */ if (!file_read) { if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1; if (json_bool_field(j, end, "has_refresh", 0)) st->has_refresh = 1; } if (json_bool_field(j, end, "pending", 0)) st->pending = 1; e = json_num_field(j, end, "expires_at"); if (e > 0) { long long sec = (e > 100000000000LL) ? (e / 1000) : e; if (st->expires_at == 0 || sec > st->expires_at) st->expires_at = sec; } if (!st->account[0] && json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0]) snprintf(st->account, sizeof(st->account), "%s", acct); if (!json_bool_field(j, end, "ok", 1)) json_str_field(j, end, "error", st->cli_error, sizeof(st->cli_error)); } buf_free(&out); } static void collect_status(status_t *st, const char *name) { char *json; long long now_sec = (long long)time(NULL); int file_read = 0; memset(st, 0, sizeof(*st)); st->pending_age = -1; /* A named account lives in ~/.codex/accounts/.json, which is the * same schema as the default credentials file. */ if (name && *name) { char p[PATH_SZ]; account_path(name, p, sizeof(p)); snprintf(st->path, sizeof(st->path), "%s", p); snprintf(st->account, sizeof(st->account), "%s", name); } else { creds_path(st->path, sizeof(st->path)); } json = read_file(st->path); if (json) { scan_creds(json, st, NULL); free(json); file_read = 1; } scan_cli(st, name, file_read); scan_profile(st); /* The pending marker is the only evidence available without a network, and * it carries the CLI's own creation stamp, so the TTL is applied here * rather than trusting a later claim. */ { char pp[PATH_SZ]; pending_path(name, pp, sizeof(pp)); if (file_exists(pp)) { char *pend = read_file(pp); long long created = 0; if (pend) { const char *pe = pend + strlen(pend); created = json_num_field(pend, pe, "created"); free(pend); } if (created > 0) { st->pending_age = now_sec - created; st->pending = (st->pending_age >= 0 && st->pending_age <= PENDING_TTL_SEC); } else { st->pending = 1; /* unreadable marker: assume still open */ } } } if (st->expires_at > 0) { st->expires_in_sec = st->expires_at - now_sec; st->expired = st->expires_in_sec <= 0; } if (!st->logged_in) { st->expired = 0; st->expires_in_sec = 0; } if (!st->account[0] && st->logged_in) snprintf(st->account, sizeof(st->account), "default"); if (!st->profile[0] && st->profile_exists) snprintf(st->profile, sizeof(st->profile), "codex"); scan_accounts(st, now_sec); } /* One status object, shared by every action so the UI always re-renders from * the same shape. */ static void emit_status(buf_t *b, const status_t *st) { int i; buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false"); buf_addf(b, "\"expires_at\":%lld", st->expires_at); buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec); buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false"); buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false"); buf_adds(b, ",\"account\":"); buf_json(b, st->account); buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false"); buf_addf(b, ",\"pending_age_sec\":%lld", st->pending_age); buf_addf(b, ",\"last_refresh\":%lld", st->last_refresh); buf_adds(b, ",\"account_id\":"); buf_json(b, st->account_id); buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false"); buf_adds(b, ",\"credentials_path\":"); buf_json(b, st->path); buf_adds(b, ",\"profile\":"); buf_json(b, st->profile); buf_addf(b, ",\"profile_exists\":%s", st->profile_exists ? "true" : "false"); buf_addf(b, ",\"named_accounts\":%s", st->account_count > 0 ? "true" : "false"); buf_addf(b, ",\"api_key_present\":%s", st->api_key_present ? "true" : "false"); buf_adds(b, ",\"cli_error\":"); buf_json(b, st->cli_error); buf_adds(b, ",\"accounts\":["); for (i = 0; i < st->account_count; i++) { const account_t *a = &st->accounts[i]; if (i) buf_addc(b, ','); buf_adds(b, "{\"name\":"); buf_json(b, a->name); buf_addf(b, ",\"logged_in\":%s", a->logged_in ? "true" : "false"); buf_addf(b, ",\"has_refresh\":%s", a->has_refresh ? "true" : "false"); buf_addf(b, ",\"expires_at\":%lld", a->expires_at); buf_addf(b, ",\"expires_in_sec\":%lld", a->expires_in_sec); buf_addf(b, ",\"expired\":%s}", a->expired ? "true" : "false"); } buf_addc(b, ']'); } /* ------------------------------------------------------------------ */ /* Actions */ /* ------------------------------------------------------------------ */ static void json_headers(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void emit_json(buf_t *b) { json_headers(); fputs(buf_str(b), stdout); buf_free(b); } static void emit_error(int code, const char *status, const char *err, const char *detail) { buf_t b; buf_init(&b); buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", code, status); buf_adds(&b, "{\"ok\":false,\"error\":"); buf_json(&b, err); if (detail && *detail) { buf_adds(&b, ",\"detail\":"); buf_json(&b, detail); } buf_adds(&b, "}\n"); fputs(buf_str(&b), stdout); buf_free(&b); } /* Build " --name " once, so every action addresses the same account. */ static void account_args(const char *name, const char *flag, char *out, size_t n) { if (name && *name) { char qname[NAME_SZ * 2]; shell_quote_into(name, qname, sizeof(qname)); snprintf(out, n, "%s --name %s", flag, qname); } else { snprintf(out, n, "%s", flag); } } static int action_status(const char *name) { status_t st; buf_t b; collect_status(&st, name); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"state\":\"done\","); emit_status(&b, &st); buf_adds(&b, "}\n"); emit_json(&b); return 0; } static int action_start(const char *name, int force) { status_t st; buf_t in, out; const char *j; char args[NAME_SZ * 2 + 40]; char verify[URL_SZ] = {0}; char code[CODE_SZ] = {0}; char err[FIELD_SZ] = {0}; char detail[FIELD_SZ] = {0}; long long expires_in = PENDING_TTL_SEC; int interval = 5; int rc; collect_status(&st, name); if (!st.cli_present) { emit_error(200, "OK", "cli_unavailable", "scorpiox-codex-login is not on this node; install SCORPIOX CODE " "or set CODEX_LOGIN_BIN"); return 0; } account_args(name, force ? "--start --force" : "--start", args, sizeof(args)); buf_init(&in); rc = run_capture(login_bin(), args, &in); if (rc <= 0) { buf_free(&in); emit_error(rc == -1 ? 200 : 500, rc == -1 ? "OK" : "Internal Server Error", "cli_unavailable", "could not run the login CLI"); return 0; } j = last_json_line(&in); if (!j) { buf_free(&in); emit_error(502, "Bad Gateway", "start_failed", "the login CLI produced no JSON; check its output"); return 1; } { const char *je = j + strlen(j); if (!json_bool_field(j, je, "ok", 1)) { json_str_field(j, je, "error", err, sizeof(err)); json_str_field(j, je, "detail", detail, sizeof(detail)); buf_free(&in); if (strcmp(err, "exists") == 0) { /* Credentials are already on this node: the honest answer is * "already signed in, press re-login to replace them". */ buf_init(&out); buf_adds(&out, "{\"ok\":true,\"already_logged_in\":true,\"pending\":false"); buf_adds(&out, ",\"error\":\"already_logged_in\""); buf_adds(&out, ",\"detail\":"); buf_json(&out, detail[0] ? detail : "credentials already exist"); buf_adds(&out, ",\"logged_in\":"); buf_adds(&out, st.logged_in ? "true" : "false"); buf_adds(&out, ",\"hint\":\"pass force=1 to replace the existing session\"}\n"); emit_json(&out); return 0; } emit_error(200, "OK", err[0] ? err : "start_failed", detail); return 0; } json_str_field(j, je, "verify_url", verify, sizeof(verify)); json_str_field(j, je, "user_code", code, sizeof(code)); interval = (int)json_num_field(j, je, "interval"); expires_in = json_num_field(j, je, "expires_in"); if (interval < 1) interval = 5; if (expires_in <= 0) expires_in = PENDING_TTL_SEC; } buf_free(&in); if (!verify[0] || !code[0]) { emit_error(502, "Bad Gateway", "start_incomplete", "login CLI did not return a verify url and user code"); return 1; } buf_init(&out); buf_addf(&out, "{\"ok\":true,\"flow\":\"device_code\",\"verify_url\":"); buf_json(&out, verify); buf_adds(&out, ",\"user_code\":"); buf_json(&out, code); buf_addf(&out, ",\"expires_in\":%lld", expires_in); buf_addf(&out, ",\"interval\":%d", interval); buf_adds(&out, ",\"pending\":true"); buf_adds(&out, ",\"provider\":\"codex\"}\n"); emit_json(&out); return 0; } /* One non-blocking poll. The CLI does exactly one HTTPS round trip and returns; * the UI drives the cadence so nothing here ever blocks. */ static int action_poll(const char *name) { status_t st; buf_t in, out; const char *j; char state[64] = {0}; char args[NAME_SZ * 2 + 16]; int rc; collect_status(&st, name); if (!st.cli_present) { emit_error(200, "OK", "cli_unavailable", "scorpiox-codex-login is not on this node"); return 0; } account_args(name, "--poll", args, sizeof(args)); buf_init(&in); rc = run_capture(login_bin(), args, &in); if (rc < 0) { buf_free(&in); emit_error(200, "OK", "cli_unavailable", "scorpiox-codex-login is not on this node"); return 0; } if (rc == 0) { buf_free(&in); emit_error(500, "Internal Server Error", "poll_failed", "cannot spawn login CLI"); return 1; } j = last_json_line(&in); if (!j) { buf_free(&in); /* No JSON at all. Fall back to what the files say: a credential file * that appeared while polling is a success no matter what the CLI * printed, and a marker that vanished with no credentials is a dead * flow, not an infinite spinner. */ if (st.logged_in) { buf_init(&out); buf_adds(&out, "{\"ok\":true,\"state\":\"done\","); emit_status(&out, &st); buf_adds(&out, "}\n"); emit_json(&out); return 0; } emit_error(502, "Bad Gateway", "poll_failed", "login CLI produced no JSON"); return 1; } { const char *je = j + strlen(j); json_str_field(j, je, "state", state, sizeof(state)); if (!json_bool_field(j, je, "ok", 0)) { char err[FIELD_SZ] = {0}; char detail[FIELD_SZ] = {0}; json_str_field(j, je, "error", err, sizeof(err)); json_str_field(j, je, "detail", detail, sizeof(detail)); buf_free(&in); /* expired / no_pending / denied are terminal, not transient. */ buf_init(&out); buf_adds(&out, "{\"ok\":true,\"state\":\"failed\""); buf_adds(&out, ",\"error\":"); buf_json(&out, err[0] ? err : "poll_failed"); if (detail[0]) { buf_adds(&out, ",\"detail\":"); buf_json(&out, detail); } buf_adds(&out, ",\"pending\":false}\n"); emit_json(&out); return 0; } if (strcmp(state, "pending") == 0) { long long iv = json_num_field(j, je, "interval"); buf_free(&in); buf_init(&out); buf_adds(&out, "{\"ok\":true,\"state\":\"pending\""); buf_addf(&out, ",\"interval\":%d", iv > 0 ? (int)iv : 5); buf_adds(&out, ",\"pending\":true"); { status_t after; collect_status(&after, name); if (after.logged_in) { /* The CLI still says pending but the file is there: report * the truth the file tells. */ buf_adds(&out, ",\"logged_in\":true"); } } buf_adds(&out, "}\n"); emit_json(&out); return 0; } /* state == "done" */ buf_free(&in); { status_t after; collect_status(&after, name); buf_init(&out); buf_adds(&out, "{\"ok\":true,\"state\":\"done\","); emit_status(&out, &after); buf_adds(&out, "}\n"); emit_json(&out); } return 0; } } static int action_cancel(const char *name) { status_t st; buf_t in, out; char args[NAME_SZ * 2 + 16]; collect_status(&st, name); if (!st.cli_present) { /* Nothing to abort and no CLI to tell: drop the marker ourselves so the * UI spinner stops on a node without SCORPIOX CODE. */ char pp[PATH_SZ]; pending_path(name, pp, sizeof(pp)); if (file_exists(pp)) remove(pp); buf_init(&out); buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false," "\"cli_present\":false}\n"); emit_json(&out); return 0; } account_args(name, "--cancel", args, sizeof(args)); buf_init(&in); { int rc = run_capture(login_bin(), args, &in); if (rc < 0) { buf_free(&in); emit_error(200, "OK", "cli_unavailable", "scorpiox-codex-login is not on this node"); return 0; } { const char *j = last_json_line(&in); int ok = 1; if (j) { const char *je = j + strlen(j); ok = json_bool_field(j, je, "ok", 1); } buf_free(&in); if (!ok) { emit_error(200, "OK", "cancel_failed", "login CLI rejected the cancel"); return 0; } /* The CLI removes the marker; re-collect to report the truth. */ { status_t after; collect_status(&after, name); buf_init(&out); buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\","); emit_status(&out, &after); buf_adds(&out, "}\n"); emit_json(&out); } } } return 0; } /* Refresh: the refresh CLI performs the refresh-token grant and updates the * credential file in place. Its stdout is human text (and with --verbose may * quote token material), so the payload is read, then discarded. The new state * is proven by re-reading the file, not by the CLI's word. */ static int action_refresh(const char *name) { buf_t out, b; char args[PATH_SZ + 96]; char qpath[PATH_SZ * 2]; char path[PATH_SZ]; long long before; status_t st; active_creds_path(name, path, sizeof(path)); if (!file_exists(path)) { buf_init(&b); buf_adds(&b, "{\"ok\":false,\"error\":\"no_credentials\",\"detail\":"); buf_json(&b, "there is no credential file for this account on this node; " "start a login first"); buf_adds(&b, "}\n"); emit_json(&b); return 1; } collect_status(&st, name); before = st.expires_at; shell_quote_into(path, qpath, sizeof(qpath)); /* action=refresh means "refresh now", so the CLI is always invoked with * --force: without it the CLI no-ops on a still-valid token and the user's * button does nothing. */ snprintf(args, sizeof(args), "--credentials-file %s --force", qpath); buf_init(&out); { int rc = run_capture(refresh_bin(), args, &out); if (rc <= 0) { buf_free(&out); emit_error(200, "OK", "cli_unavailable", "the refresh CLI is not on this node; install SCORPIOX CODE " "or set CODEX_REFRESH_BIN"); return 1; } } buf_free(&out); collect_status(&st, name); if (!st.logged_in || (before > 0 && st.expires_at <= before && !st.expired)) { buf_init(&b); buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":"); buf_json(&b, "the refresh CLI did not extend the token in the credential " "file; sign in again"); buf_adds(&b, "}\n"); emit_json(&b); return 1; } buf_init(&b); buf_adds(&b, "{\"ok\":true,\"refreshed\":true,"); emit_status(&b, &st); buf_adds(&b, "}\n"); emit_json(&b); return 0; } /* ------------------------------------------------------------------ */ /* HTML emission */ /* ------------------------------------------------------------------ */ /* Expand the two placeholders tools/gen_ui.py leaves in UI_HTML. Keeping the * split means the palette lives in exactly one place (bot_theme_plugin.h) and * the page can never drift away from the bot's own theme. */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { /* SX_BOT_THEME_HANDOFF is a complete