/* * plugin_claudecode_login - SCORPIOX BOT open-source Claude Code OAuth PKCE * login and session 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 and no OAuth client secret here): a Claude * Code OAuth PKCE code exchange is an HTTPS POST that carries a client * identity. A public clean-room repository must never carry such a secret, so * this plugin does not speak TLS at all. It drives the node's own SCORPIOX CODE * login CLI, exactly the way the machine-mode contract intends * (--status / --start / --finish / --cancel, one JSON line per call), and it * reads only the credential files that CLI writes: * * ~/.claude/.credentials.json (claudeAiOauth block) * ~/.claude/accounts/.json (named accounts) * ~/.claude/.login-pending/claudecode-.json (pending PKCE flow) * ~/.claude/scorpiox-env/claude_code.txt (PROVIDER/MODEL profile) * * Every path and both binaries are overridable for deterministic offline tests: * * CLAUDE_CREDS_PATH credentials file (also anchors the sibling paths) * CLAUDE_ACCOUNTS_DIR directory holding .json account files * CLAUDE_PENDING_DIR directory holding the pending flow files * CLAUDE_ENV_DIR profile directory (claude_code.txt) * CLAUDE_LOGIN_BIN login CLI (default scorpiox-claudecode-login) * CLAUDE_REFRESH_BIN refresh CLI (default scorpiox-claudecode-refreshtoken) * * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. Every response reports token * presence and expiry only. The refresh action discards the payload its CLI * prints and reports only success/failure plus the new expiry. * * 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 "claudecode-login" #define PLUGIN_ID "plugin_claudecode_login" #define PLUGIN_VER "1.0.1" #define PLUGIN_NAME "claude" #define PLUGIN_DESC "Claude login" #define PATH_SZ 1024 #define NAME_SZ 96 #define CODE_MAX 2048 #define CMD_SZ 4096 #define OUT_MAX (256 * 1024) #define FIELD_SZ 512 #define MAX_ACCOUNTS 64 #define DEFAULT_LOGIN_BIN "scorpiox-claudecode-login" #define DEFAULT_REFRESH_BIN "scorpiox-claudecode-refreshtoken" #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_add(buf_t *b, const char *s, size_t n) { if (!buf_need(b, n)) return 0; memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = '\0'; return 1; } static int buf_adds(buf_t *b, const char *s) { return s ? buf_add(b, s, strlen(s)) : 1; } static int buf_addc(buf_t *b, char c) { return buf_add(b, &c, 1); } 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; } static int buf_addf(buf_t *b, const char *fmt, ...) { char tmp[2048]; int n; va_list ap; 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)) return buf_add(b, tmp, (size_t)n); { char *big = (char *)malloc((size_t)n + 1); int ok; if (!big) return 0; va_start(ap, fmt); vsnprintf(big, (size_t)n + 1, fmt, ap); va_end(ap); ok = buf_add(b, big, (size_t)n); free(big); return ok; } } /* JSON string escape into a buffer (never emits a bare control byte). */ static int buf_json(buf_t *b, const char *s) { const unsigned char *p = (const unsigned char *)(s ? s : ""); if (!buf_addc(b, '"')) return 0; for (; *p; p++) { switch (*p) { case '"': if (!buf_adds(b, "\\\"")) return 0; break; case '\\': if (!buf_adds(b, "\\\\")) return 0; break; case '\n': if (!buf_adds(b, "\\n")) return 0; break; case '\r': if (!buf_adds(b, "\\r")) return 0; break; case '\t': if (!buf_adds(b, "\\t")) return 0; break; default: if (*p < 0x20) { if (!buf_addf(b, "\\u%04x", *p)) return 0; } else if (!buf_addc(b, (char)*p)) return 0; } } return buf_addc(b, '"'); } /* ------------------------------------------------------------------ */ /* 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 && *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; const char *p; if (!qs || !key) return 0; klen = strlen(key); 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; } /* Percent-decode in place (an authorization code arrives from a paste box and * may have been encoded by the browser or the hub proxy). */ static void url_decode(char *s) { char *w; char *r; if (!s) return; w = s; r = s; while (*r) { if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) { int hi = isdigit((unsigned char)r[1]) ? r[1] - '0' : tolower((unsigned char)r[1]) - 'a' + 10; int lo = isdigit((unsigned char)r[2]) ? r[2] - '0' : tolower((unsigned char)r[2]) - 'a' + 10; *w++ = (char)((hi << 4) | lo); r += 3; } else if (*r == '+') { *w++ = ' '; r++; } else { *w++ = *r++; } } *w = '\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); } /* ------------------------------------------------------------------ */ /* Paths */ /* ------------------------------------------------------------------ */ static const char *home_dir(void) { #if defined(_WIN32) static char home[512]; DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); if (n > 0 && n < sizeof(home)) return home; home[0] = '\0'; if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) { char tmp[512]; if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) { strncat(home, tmp, sizeof(home) - strlen(home) - 1); 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); } /* A relocated credentials file implies the whole .claude tree is relocated: * the same CLI writes all of these into one directory. Reading one from the * override and the rest from $HOME reports an empty state for a live session. */ static void claude_dir(char *out, size_t n) { const char *env = getenv("CLAUDE_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.claude%c", home, PATH_SEP, PATH_SEP); return; } snprintf(out, n, ".claude%c", PATH_SEP); } static void creds_path(char *out, size_t n) { const char *env = getenv("CLAUDE_CREDS_PATH"); if (env && *env) { snprintf(out, n, "%s", env); return; } { char d[PATH_SZ]; claude_dir(d, sizeof(d)); snprintf(out, n, "%s.credentials.json", d); } } static void accounts_dir(char *out, size_t n) { const char *env = getenv("CLAUDE_ACCOUNTS_DIR"); if (env && *env) { snprintf(out, n, "%s", env); return; } { char d[PATH_SZ]; claude_dir(d, sizeof(d)); snprintf(out, n, "%saccounts", d); } } static void pending_dir(char *out, size_t n) { const char *env = getenv("CLAUDE_PENDING_DIR"); if (env && *env) { snprintf(out, n, "%s", env); return; } { char d[PATH_SZ]; claude_dir(d, sizeof(d)); snprintf(out, n, "%s.login-pending", d); } } static void env_dir(char *out, size_t n) { const char *env = getenv("CLAUDE_ENV_DIR"); if (env && *env) { snprintf(out, n, "%s", env); return; } { char d[PATH_SZ]; claude_dir(d, sizeof(d)); snprintf(out, n, "%s%cscorpiox-env", d, 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%cclaudecode-%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%cclaude_code.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); } static const char *login_bin(void) { const char *e = getenv("CLAUDE_LOGIN_BIN"); return (e && *e) ? e : DEFAULT_LOGIN_BIN; } static const char *refresh_bin(void) { const char *e = getenv("CLAUDE_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 && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); #else struct stat st; return p && stat(p, &st) == 0 && S_ISREG(st.st_mode); #endif } /* Read a whole file. Returns a malloc'd NUL-terminated buffer or NULL. */ 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; } /* Trim trailing CR/LF/space in place. */ 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'; } /* Account names are used verbatim in a file name, so they are restricted to a * shell- and path-safe alphabet. */ 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; } /* ------------------------------------------------------------------ */ /* Minimal JSON field readers */ /* ------------------------------------------------------------------ */ /* Copy a JSON string value that starts at *pp (pointing at the opening quote) * and advance *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": among the TOP-LEVEL keys of the slice [obj, end). * A nested object is skipped as a whole. * * A caller almost always hands us a pointer at the opening '{'; that brace is * skipped inside the reader so no call site needs a "+1" that is easy to * forget and completely silent when it is missing. */ static const char *json_find_key(const char *obj, const char *end, const char *key) { size_t klen; const char *p; int depth = 0; if (!obj || !end || !key) return NULL; klen = strlen(key); p = obj; 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; } /* Returns 0 and leaves *out untouched when the key is absent or null. That * matters: 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; if (*v == '"') return json_read_string_at(&v, out, outsz); { size_t i = 0; out[0] = '\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 == '"') { if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1; return 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); if (!v) return 0; if (*v == '"') v++; return atoll(v); } /* ------------------------------------------------------------------ */ /* Child processes */ /* ------------------------------------------------------------------ */ /* 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 } /* Is resolvable on this node? POSIX answers through popen's own 127 * ("command not found"). cmd.exe returns 1 for a missing program, which is * indistinguishable from the program's own failure - so on Windows the path is * resolved BEFORE popen with SearchPathA. Without this, a Windows node with no * SCORPIOX CODE reported cli_present:true and "start failed" instead of * cli_unavailable (measured on a real Windows box). */ static int bin_available(const char *bin) { if (!bin || !*bin) return 0; #if defined(_WIN32) { char full[MAX_PATH]; DWORD n; /* An explicit path is checked directly; a bare name is searched on PATH. */ if (strchr(bin, '\\') || strchr(bin, '/') || strchr(bin, ':')) return file_exists(bin); n = SearchPathA(NULL, bin, ".exe", (DWORD)sizeof(full), full, NULL); return n > 0 && n < (DWORD)sizeof(full); } #else return 1; /* decided by run_capture's own 127 check */ #endif } /* Run ` ` and capture stdout. * 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). Treating that as the tool's own failure would * report "refresh failed" for a node that simply has no SCORPIOX CODE. */ 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; if (!bin_available(bin)) return -1; 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 && ((rc >> 8) & 0xff) == 127) 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 */ /* ------------------------------------------------------------------ */ /* expiresAt is milliseconds in the real file, but a hand-written fixture may * carry seconds. Detect by magnitude rather than trusting either form. */ static long long to_sec(long long v) { return (v > 100000000000LL) ? (v / 1000) : v; } typedef struct { char name[NAME_SZ]; int present; int logged_in; int has_refresh; int expired; long long expires_at; /* raw value from the file (milliseconds) */ 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 profile_exists; char account[NAME_SZ]; char path[PATH_SZ]; char profile[NAME_SZ]; char profile_file[PATH_SZ]; char subscription[64]; char scopes[256]; char cli_error[FIELD_SZ]; long long expires_at; /* milliseconds since epoch, as stored */ long long expires_in_sec; /* seconds; long long, not int: a 32-bit int * overflows for any expiry past 2038 and turns * a live session into "expired 60 years ago" */ account_t accounts[MAX_ACCOUNTS]; int account_count; } status_t; /* Parse a credentials file: the claudeAiOauth block carries all of it. * A named account file has exactly the same shape. */ static void scan_creds(const char *json, status_t *st, account_t *acc) { const char *oauth; const char *end; char tok[8] = {0}; int has_access = 0; if (!json) return; oauth = strstr(json, "\"claudeAiOauth\""); /* json_find_key matches TOP-LEVEL keys of the slice it is given, so the * slice must start at the oauth object's opening brace, not at its key * name: starting at "claudeAiOauth" makes the real opening brace look like * a nested object and every field read silently returns absent (a live * session reported as "not connected", while the JSON was valid). */ if (oauth) { const char *brace = strchr(oauth, '{'); if (brace) oauth = brace; } if (!oauth) return; end = json + strlen(json); if (json_str_field(oauth, end, "accessToken", tok, sizeof(tok))) has_access = 1; memset(tok, 0, sizeof(tok)); if (json_str_field(oauth, end, "refreshToken", tok, sizeof(tok))) { st->has_refresh = 1; if (acc) acc->has_refresh = 1; } st->expires_at = json_num_field(oauth, end, "expiresAt"); if (acc) acc->expires_at = st->expires_at; json_str_field(oauth, end, "subscriptionType", st->subscription, sizeof(st->subscription)); if (!st->scopes[0]) { /* Report the scope NAMES, not the raw JSON array: a copy from the key * name through ']' carried `"scopes": ` into the string and rendered as * `"scopes": ["user:profile"` in the UI. Start at '[' and keep only the * quoted elements, comma-separated. */ const char *sc = strstr(oauth, "\"scopes\""); const char *open = sc ? strchr(sc, '[') : NULL; const char *close = open ? strchr(open, ']') : NULL; if (open && close) { size_t o = 0; const char *q = open + 1; while (q < close && o + 1 < sizeof(st->scopes)) { if (*q == '"') { const char *e; q++; e = strchr(q, '"'); if (!e || e > close) break; if (o) st->scopes[o++] = ','; while (q < e && o + 1 < sizeof(st->scopes)) st->scopes[o++] = *q++; q = e + 1; } else { q++; } } st->scopes[o] = '\0'; } } st->logged_in = st->has_refresh || has_access || st->expires_at > 0; if (acc) acc->logged_in = st->logged_in; } /* Read the profile file written by --create-profile. */ static void scan_profile(status_t *st) { char *text; char line[FIELD_SZ]; 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), "claude_code"); text = read_file(st->profile_file); if (!text) return; { const char *p = text; while (p && *p) { const char *nl = strchr(p, '\n'); size_t len = nl ? (size_t)(nl - p) : strlen(p); if (len > 0 && len < sizeof(line)) { memcpy(line, p, len); line[len] = '\0'; trim_tail(line); if (strncmp(line, "PROVIDER=", 9) == 0 && !st->profile[0]) snprintf(st->profile, sizeof(st->profile), "%.*s", (int)sizeof(st->profile) - 1, line + 9); } if (!nl) break; p = nl + 1; } } free(text); } /* List the account files in the accounts directory and summarise each one. */ 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 = strlen(fd.cFileName); if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue; if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; { account_t *a = &st->accounts[st->account_count]; char p[PATH_SZ]; char *json; memset(a, 0, sizeof(*a)); snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName); 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); } if (a->expires_at > 0 && a->logged_in) { a->expires_in_sec = to_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); 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); } if (a->expires_at > 0 && a->logged_in) { a->expires_in_sec = to_sec(a->expires_at) - now_sec; a->expired = a->expires_in_sec <= 0; } st->account_count++; } closedir(dp); } #endif } /* Query the login CLI in machine mode. It is authoritative when present * (it knows about named accounts, the pending flow and profile creation); * the credential file is the fallback for a node without SCORPIOX CODE. */ static void scan_cli(status_t *st, const char *name) { 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; 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; } } 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); /* The CLI's logged_in is derived from the same file, but it also knows * about a named account file, so trust it when it says yes. */ 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; st->pending = json_bool_field(j, end, "pending", 0); { long long e = json_num_field(j, end, "expires_at"); if (e > 0) st->expires_at = e; } { char acct[NAME_SZ] = {0}; if (json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0]) snprintf(st->account, sizeof(st->account), "%s", acct); } } buf_free(&out); } static void collect_status(status_t *st, const char *name) { char *json; long long now_sec = (long long)time(NULL); memset(st, 0, sizeof(*st)); /* A named account lives in ~/.claude/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); } scan_cli(st, name); scan_profile(st); { char pp[PATH_SZ]; pending_path(name, pp, sizeof(pp)); if (file_exists(pp)) st->pending = 1; } /* expiresAt is milliseconds since the epoch in this file format. Normalise * to seconds for the countdown; a seconds value (from a hand-written * fixture) is detected by magnitude and left alone. */ if (st->expires_at > 0) { long long ms = st->expires_at; long long sec = (ms > 100000000000LL) ? (ms / 1000) : ms; st->expires_in_sec = sec - 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), "claude_code"); 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_adds(b, "\"expires_at\":"); buf_addf(b, "%lld", st->expires_at); buf_addf(b, ",\"expires_at_sec\":%lld", st->expires_at > 100000000000LL ? st->expires_at / 1000 : 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, ",\"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 > 1 ? "true" : "false"); buf_adds(b, ",\"subscription\":"); buf_json(b, st->subscription); buf_adds(b, ",\"scopes\":"); buf_json(b, st->scopes); 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_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_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); } 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,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\","); emit_status(&b, &st); buf_adds(&b, ",\"flow\":\"paste_code\",\"protocol\":\"SXLOGIN-MACHINE-V1\"}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } static int action_start(const char *name, int force) { buf_t out, b; const char *j; char args[NAME_SZ + 64]; char auth_url[CMD_SZ] = {0}; char flow[64] = {0}; char hint[FIELD_SZ] = {0}; long long expires_in = 0; if (name && *name) { const char *nm = name; char qname[NAME_SZ * 2]; shell_quote_into(nm, qname, sizeof(qname)); snprintf(args, sizeof(args), "--start%s --name %s", force ? " --force" : "", qname); } else { snprintf(args, sizeof(args), "--start%s", force ? " --force" : ""); } buf_init(&out); { int rc = run_capture(login_bin(), args, &out); if (rc <= 0) { buf_free(&out); emit_error(200, "OK", "cli_unavailable", "the login CLI is not on this node; install SCORPIOX CODE or set CLAUDE_LOGIN_BIN"); return 1; } } j = last_json_line(&out); if (!j) { emit_error(200, "OK", "start_failed", "the login CLI returned no JSON"); buf_free(&out); return 1; } { const char *end = j + strlen(j); json_str_field(j, end, "auth_url", auth_url, sizeof(auth_url)); json_str_field(j, end, "flow", flow, sizeof(flow)); json_str_field(j, end, "hint", hint, sizeof(hint)); expires_in = json_num_field(j, end, "expires_in"); if (!json_bool_field(j, end, "ok", 1) || !auth_url[0]) { char detail[FIELD_SZ] = {0}; json_str_field(j, end, "error", detail, sizeof(detail)); buf_free(&out); emit_error(200, "OK", detail[0] ? detail : "start_failed", "the login CLI did not return an authorization URL"); return 1; } } buf_free(&out); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"flow\":"); buf_json(&b, flow[0] ? flow : "paste_code"); buf_adds(&b, ",\"auth_url\":"); buf_json(&b, auth_url); buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : 600); buf_adds(&b, ",\"hint\":"); buf_json(&b, hint[0] ? hint : "Sign in with Claude, then paste the code shown on the callback page."); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } /* Reject anything that cannot be an authorization code. The value reaches a * shell through run_capture(), so this is the second line of defence behind * shell_quote_into(). */ static int code_valid(const char *code) { size_t n, i; if (!code || !(n = strlen(code)) || n > CODE_MAX) return 0; for (i = 0; i < n; i++) { unsigned char c = (unsigned char)code[i]; if (c < 0x20 || c == 0x7f || c == '\'' || c == '"' || c == '\\' || c == ';' || c == '`' || c == '$' || c == '|' || c == '&' || c == '<' || c == '>') return 0; } return 1; } static int action_finish(const char *raw_code, const char *name, int force) { char code[CODE_MAX]; char qcode[CODE_MAX + 64]; char args[CODE_MAX + NAME_SZ + 128]; buf_t out, b; const char *j; if (!raw_code || !*raw_code) { emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=..."); return 1; } snprintf(code, sizeof(code), "%s", raw_code); url_decode(code); trim_tail(code); /* A user usually pastes the whole redirect address. Extract code= BEFORE * validating, so a legitimate URL is not refused for carrying state= too. * Validating first would reject every real paste, because '&' and '=' are * exactly the characters a bare code never contains. */ { char *c = strstr(code, "code="); if (c) { char extracted[CODE_MAX]; size_t i = 0; c += 5; while (*c && *c != '&' && *c != '#' && i + 1 < sizeof(extracted)) extracted[i++] = *c++; extracted[i] = '\0'; if (i > 0) { /* An embedded '&' or '#' is expected in a URL, not in a code. */ if (code_valid(extracted)) snprintf(code, sizeof(code), "%s", extracted); } } } { char *hash = strchr(code, '#'); if (hash) *hash = '\0'; } if (!code_valid(code)) { emit_error(400, "Bad Request", "invalid_code", "the value is not an authorization code (empty, too long, or contains shell characters)"); return 1; } shell_quote_into(code, qcode, sizeof(qcode)); { char qname[NAME_SZ * 2]; const char *extra = ""; if (name && *name) { shell_quote_into(name, qname, sizeof(qname)); extra = qname; } if (extra[0]) snprintf(args, sizeof(args), "--finish %s --name %s%s", qcode, extra, force ? " --force" : ""); else snprintf(args, sizeof(args), "--finish %s%s", qcode, force ? " --force" : ""); } buf_init(&out); { int rc = run_capture(login_bin(), args, &out); if (rc <= 0) { buf_free(&out); emit_error(200, "OK", "cli_unavailable", "the login CLI is not on this node; install SCORPIOX CODE or set CLAUDE_LOGIN_BIN"); return 1; } } j = last_json_line(&out); if (!j) { buf_free(&out); emit_error(200, "OK", "finish_failed", "the login CLI returned no JSON"); return 1; } { const char *end = j + strlen(j); if (!json_bool_field(j, end, "ok", 0)) { char detail[FIELD_SZ] = {0}; json_str_field(j, end, "error", detail, sizeof(detail)); buf_free(&out); emit_error(200, "OK", detail[0] ? detail : "finish_failed", "Claude rejected the code, or it has already been used or has expired"); return 1; } } buf_free(&out); { status_t st; collect_status(&st, name); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"state\":\"done\","); emit_status(&b, &st); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); } return 0; } static int action_cancel(const char *name) { buf_t out, b; char args[NAME_SZ + 32]; if (name && *name) { char qname[NAME_SZ * 2]; shell_quote_into(name, qname, sizeof(qname)); snprintf(args, sizeof(args), "--cancel --name %s", qname); } else { snprintf(args, sizeof(args), "--cancel"); } buf_init(&out); run_capture(login_bin(), args, &out); buf_free(&out); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } /* Refresh: the refresh CLI performs the refresh-token grant and updates the * credentials file in place. Its stdout is human text (and 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; if (name && *name) account_path(name, path, sizeof(path)); else creds_path(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 credentials file on this node; start a login first"); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&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 CLAUDE_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 update the credentials file; sign in again"); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 1; } buf_init(&b); buf_adds(&b, "{\"ok\":true,\"refreshed\":true,"); emit_status(&b, &st); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&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 and SX_BOT_THEME_TOGGLE_JS are both complete * strings, so they are emitted as siblings. * Without the toggle macro the page's Theme button is inert: the * bot owns the theme, but a plugin opened in its own tab needs a * switch of its own. */ fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout); p++; } else { putchar(*p++); } } } /* Read a POST body field of the form "code":"..." (a long code is easier to * send in a body than in a URL). Guarded on CONTENT_LENGTH so an empty * inherited stdin can never block. */ static int body_field(const char *field, char *out, size_t outsz) { const char *cl = getenv("CONTENT_LENGTH"); long n = (cl && *cl) ? atol(cl) : 0; char *body; size_t len; int got = 0; if (n <= 0 || n > (long)(256 * 1024)) return 0; body = (char *)malloc((size_t)n + 1); if (!body) return 0; len = fread(body, 1, (size_t)n, stdin); body[len] = '\0'; { char *p = strstr(body, field); if (p) { p = strchr(p, ':'); if (p) { size_t i = 0; p++; while (*p == ' ' || *p == '\t') p++; if (*p == '"') p++; while (*p && *p != '"' && i + 1 < outsz) out[i++] = *p++; out[i] = '\0'; got = i > 0; } } } free(body); return got; } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *qs; char action[64] = {0}; char name[NAME_SZ] = {0}; char code[CODE_MAX] = {0}; int force = 0; /* 1. Discovery metadata. Must stay unauthenticated. */ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); return 0; } if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { puts(PLUGIN_ID " " PLUGIN_VER); return 0; } require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; get_query_val(qs, "name", name, sizeof(name)); if (name[0] && !name_valid(name)) { emit_error(400, "Bad Request", "bad_name", "account names use letters, digits, - _ . (max 64)"); return 1; } { char f[8] = {0}; if (get_query_val(qs, "force", f, sizeof(f))) force = (f[0] == '1' || f[0] == 't' || f[0] == 'T' || f[0] == 'y'); } /* 2. JSON API mode. `format=json` alone means "status", which is what a * dashboard polls. */ if (query_has(qs, "action") || query_has(qs, "format")) { char fmt[32] = {0}; get_query_val(qs, "action", action, sizeof(action)); get_query_val(qs, "format", fmt, sizeof(fmt)); if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status"); if (strcmp(action, "status") == 0 || !action[0]) return action_status(name); if (strcmp(action, "start") == 0) return action_start(name, force); if (strcmp(action, "cancel") == 0) return action_cancel(name); if (strcmp(action, "refresh") == 0) return action_refresh(name); if (strcmp(action, "accounts") == 0) return action_status(name); if (strcmp(action, "finish") == 0) { if (!get_query_val(qs, "code", code, sizeof(code))) { if (!body_field("\"code\"", code, sizeof(code))) { emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=..."); return 1; } } return action_finish(code, name, force); } emit_error(404, "Not Found", "unknown_action", action); return 1; } /* 3. HTML UI. UI_HTML carries two control bytes: 0x01 is the theme block * (