/* * plugin_opencode_login - SCORPIOX BOT open-source OpenCode 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 OpenCode 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 file that the CLI writes: * * ~/.config/opencode/auth.json (access + refresh token) * ~/.claude/.login-pending/opencode-default.json (pending device flow) * ~/.claude/scorpiox-env/superopencode.txt (the profile the CLI creates) * * Every one of those paths and both CLIs can be overridden for deterministic * offline testing: * * OPENCODE_CREDS_PATH the credential json (default ~/.config/opencode/auth.json) * OPENCODE_PENDING_PATH the pending-flow marker * OPENCODE_LOGIN_BIN the login CLI (default scorpiox-opencode-login) * OPENCODE_TOKEN_BIN the token CLI (default scorpiox-opencode-fetchtoken) * OPENCODE_ENV_DIR the profile dir (default ~/.claude/scorpiox-env) * * No token is ever printed, logged or returned by this plugin: the API reports * presence and expiry only, and the refresh action reports success or the * failure reason from the token CLI with the payload discarded. * * 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 #endif #include "bot_theme_plugin.h" #include "ui_html.h" #define PLUGIN_SLUG "opencode-login" #define PLUGIN_ID "plugin_opencode_login" #define PLUGIN_VER "1.0.0" #define PLUGIN_NAME "opencode" #define PLUGIN_DESC "OpenCode login" #define PATH_SZ 1024 #define LABEL_SZ 256 #define ORG_SZ 256 #define CODE_SZ 64 #define URL_SZ 1024 #define CMD_SZ 4096 #define OUT_MAX (256 * 1024) #define FIELD_SZ 512 #define DEFAULT_LOGIN_BIN "scorpiox-opencode-login" #define DEFAULT_TOKEN_BIN "scorpiox-opencode-fetchtoken" /* The device-flow marker the login CLI writes and removes. Its TTL matches the * CLI's own (900 s); the plugin only uses it to decide whether the UI should * show a live polling indicator, never to authorise anything. */ #define PENDING_TTL_SEC 900 /* ------------------------------------------------------------------ */ /* 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); } /* ------------------------------------------------------------------ */ /* Paths */ /* ------------------------------------------------------------------ */ static const char *home_dir(void) { #ifdef _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 } #if defined(_WIN32) # define PATH_SEP '\\' #else # define PATH_SEP '/' #endif /* Credential json: OPENCODE_CREDS_PATH, else ~/.config/opencode/auth.json - * the file the login CLI actually writes. ~/.opencode/token.json is probed as a * secondary location so a relocated or hand-written install is still seen. */ static void creds_path(char *out, size_t n) { const char *env = getenv("OPENCODE_CREDS_PATH"); const char *home = home_dir(); if (env && *env) { snprintf(out, n, "%s", env); return; } if (!home) { snprintf(out, n, "auth.json"); return; } snprintf(out, n, "%s%c.config%copencode%cauth.json", home, PATH_SEP, PATH_SEP, PATH_SEP); } /* The secondary, spec-named location (only consulted when the primary is * absent, so a normal install never pays for it). */ static int creds_path_alt(char *out, size_t n) { const char *home = home_dir(); if (getenv("OPENCODE_CREDS_PATH")) return 0; /* override wins outright */ if (!home) return 0; snprintf(out, n, "%s%c.opencode%ctoken.json", home, PATH_SEP, PATH_SEP); return 1; } /* The pending device-flow marker written by the login CLI. */ static void pending_path(char *out, size_t n) { const char *env = getenv("OPENCODE_PENDING_PATH"); const char *home = home_dir(); if (env && *env) { snprintf(out, n, "%s", env); return; } if (!home) { snprintf(out, n, "opencode-default.json"); return; } snprintf(out, n, "%s%c.claude%c.login-pending%copencode-default.json", home, PATH_SEP, PATH_SEP, PATH_SEP); } static void env_dir(char *out, size_t n) { const char *env = getenv("OPENCODE_ENV_DIR"); const char *creds = getenv("OPENCODE_CREDS_PATH"); const char *home = home_dir(); if (env && *env) { snprintf(out, n, "%s", env); return; } /* A relocated credential file implies a relocated profile: they are written * by the same CLI into the same tree, and reading one from the default home * while the other is overridden makes status report a missing profile for a * session that has one. */ if (creds && *creds) { char base[PATH_SZ]; char *slash; snprintf(base, sizeof(base), "%s", creds); slash = strrchr(base, PATH_SEP); if (!slash) slash = strrchr(base, '/'); if (slash) { *(slash + 1) = '\0'; if (strlen(base) + 16 < n) { snprintf(out, n, "%sscorpiox-env", base); return; } } } if (!home) { snprintf(out, n, "."); return; } snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP); } static void profile_path(char *out, size_t n) { char d[PATH_SZ]; env_dir(d, sizeof(d)); /* Copy with explicit bounds so a long directory cannot have its tail * replaced by the filename (snprintf would silently truncate). */ { const char *name = "superopencode.txt"; size_t dl = strlen(d); if (dl + 1 + strlen(name) >= n) { snprintf(out, n, "%s", name); return; } memcpy(out, d, dl); out[dl] = PATH_SEP; memcpy(out + dl + 1, name, strlen(name) + 1); } } static const char *login_bin(void) { const char *b = getenv("OPENCODE_LOGIN_BIN"); return (b && *b) ? b : DEFAULT_LOGIN_BIN; } static const char *token_bin(void) { const char *b = getenv("OPENCODE_TOKEN_BIN"); return (b && *b) ? b : DEFAULT_TOKEN_BIN; } static int file_exists(const char *p) { #if defined(_WIN32) DWORD a = GetFileAttributesA(p); return (a != (DWORD)-1); #else struct stat st; return p && *p && stat(p, &st) == 0; #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; } /* 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'; } /* ------------------------------------------------------------------ */ /* 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": anywhere inside the slice [obj, end) and return the * value pointer. Only top-level keys of that slice are considered: a nested * object is skipped as a whole. */ 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; /* A caller almost always hands us the whole object, i.e. a pointer at the * opening '{'. Skipping it here keeps every call site free of the "+1" * that is easy to forget and silent when it is missing. */ 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; 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 == '"') { 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); long long vll = 0; int neg = 0; if (!v) return 0; if (*v == '"') v++; if (*v == '-') { neg = 1; v++; } while (isdigit((unsigned char)*v)) { vll = vll * 10 + (*v++ - '0'); } return neg ? -vll : vll; } /* True when the object contains 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) return 0; if (*v != '"') return 0; q = v + 1; while (*q && *q != '"') { if (*q == '\\' && q[1]) { q += 2; continue; } return 1; /* at least one real character */ } return 0; /* "" - present but empty */ } /* ------------------------------------------------------------------ */ /* Running the node's login CLI */ /* ------------------------------------------------------------------ */ /* Wrap a string in single quotes for the shell, so a path or a binary name * containing spaces or punctuation cannot break the command line. */ 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; } 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'; } /* Run ` ` and capture stdout. args may be NULL or a pre-built * shell fragment. Returns 1 when the process ran, -1 when the binary was not * found, 0 when popen itself failed. The captured text is stored in out. */ 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 (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args); else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin); 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) { /* the CLIs print one JSON line last; strip surrounding whitespace */ size_t n = out->n; while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0'; out->n = n; } /* pclose() hands back a wait status, not an exit code: "command not * found" arrives as 32512 (127 << 8). Callers treat that as "the CLI is * not on this node", which is a different message from "the CLI ran and * failed". Any other status is the CLI's own and is left to the JSON it * printed. */ if (rc != -1 && (rc >> 8) == 127) return -1; return 1; } /* The login CLI prints human progress on stdout 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 model */ /* ------------------------------------------------------------------ */ typedef struct { char path[PATH_SZ]; char account[LABEL_SZ]; char org[ORG_SZ]; char profile[LABEL_SZ]; long long expires_at; /* unix seconds, 0 = unknown */ int logged_in; int has_refresh; int expired; int pending; long long pending_age; /* seconds since the marker was written, -1 unknown */ int profile_exists; int cli_present; /* 1 when the login CLI ran at all this call */ int cli_pending_unknown;/* 1 when no marker file exists to TTL-check */ int cli_ok; /* 1 when the login CLI answered with ok:true */ int token_bin_present; char cli_error[FIELD_SZ]; } status_t; /* Normalise an expiry to unix SECONDS. The credential file stores seconds * (time(NULL) + expires_in); the machine-mode status reports milliseconds. * A value above 1e11 can only be milliseconds on any realistic date. */ static long long normalise_expiry(long long v) { if (v <= 0) return 0; if (v > 100000000000LL) return v / 1000; return v; } static void collect_status(status_t *st) { char alt[PATH_SZ]; char *raw; const char *end; long long now = (long long)time(NULL); memset(st, 0, sizeof(*st)); snprintf(st->profile, sizeof(st->profile), "superopencode"); st->pending_age = -1; /* 1. the credential file the CLI writes */ creds_path(st->path, sizeof(st->path)); raw = read_file(st->path); if (!raw && creds_path_alt(alt, sizeof(alt)) && file_exists(alt)) { free(raw); raw = read_file(alt); if (raw) snprintf(st->path, sizeof(st->path), "%s", alt); } if (raw) { end = raw + strlen(raw); st->logged_in = json_str_present(raw, end, "access_token"); st->has_refresh = json_str_present(raw, end, "refresh_token"); st->expires_at = normalise_expiry(json_num_field(raw, end, "expires_at")); if (!st->expires_at) { long long ein = json_num_field(raw, end, "expires_in"); if (ein > 0) st->expires_at = now + ein; } if (json_str_field(raw, end, "org_id", st->org, sizeof(st->org))) snprintf(st->account, sizeof(st->account), "%s", st->org); free(raw); } st->expired = (st->expires_at > 0 && st->expires_at < now); /* 2. the pending device-flow marker, owned by the CLI but reported here. * The marker is the only evidence the plugin can check 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]; int marker = 0; pending_path(pp, sizeof(pp)); marker = file_exists(pp); if (marker) { char *pend = read_file(pp); long long created = -1; if (pend) { const char *pe = pend + strlen(pend); created = json_num_field(pend, pe, "created"); free(pend); } if (created > 0) { st->pending_age = now - created; st->pending = (st->pending_age >= 0 && st->pending_age <= PENDING_TTL_SEC); } else { st->pending = 1; /* unreadable marker: assume still open */ } } /* Only when there is no marker at all does the CLI's own pending bit * get to speak: it reads the same file, so a stale-but-present marker * must never be revived by it. */ if (!marker) st->cli_pending_unknown = 1; } /* 3. the profile file the CLI creates */ { char prof[PATH_SZ]; profile_path(prof, sizeof(prof)); st->profile_exists = file_exists(prof); } /* 4. ask the CLI, and let it ADD to what the files already proved. The * file-derived booleans win: they are what this node actually has, and * a stale or partial CLI answer must not erase them. */ { buf_t b; const char *j; int rc; buf_init(&b); rc = run_capture(login_bin(), "--status", &b); if (rc < 0) { st->cli_present = 0; snprintf(st->cli_error, sizeof(st->cli_error), "cli_not_found"); } else if (rc == 0) { st->cli_present = 0; snprintf(st->cli_error, sizeof(st->cli_error), "cli_spawn_failed"); } else { st->cli_present = 1; j = last_json_line(&b); if (j) { const char *je = j + strlen(j); st->cli_ok = json_bool_field(j, je, "ok", 0); if (!st->cli_ok) json_str_field(j, je, "error", st->cli_error, sizeof(st->cli_error)); if (!st->account[0]) json_str_field(j, je, "account", st->account, sizeof(st->account)); if (!st->expires_at) st->expires_at = normalise_expiry(json_num_field(j, je, "expires_at")); if (!st->logged_in && json_bool_field(j, je, "logged_in", 0)) st->logged_in = 1; if (!st->has_refresh && json_bool_field(j, je, "has_refresh", 0)) st->has_refresh = 1; if (!st->pending && st->cli_pending_unknown && json_bool_field(j, je, "pending", 0)) st->pending = 1; if (!st->profile_exists && json_bool_field(j, je, "profile_exists", 0)) st->profile_exists = 1; if (!st->path[0]) json_str_field(j, je, "path", st->path, sizeof(st->path)); } } buf_free(&b); } st->expired = (st->expires_at > 0 && st->expires_at < (long long)time(NULL)); /* 5. is the token CLI on this node at all (used by refresh + the UI) */ { buf_t b; buf_init(&b); /* run_capture returns 1 when the process actually ran, -1 when the * binary was not found (exit 127), 0 when popen itself failed. Only * "it ran" counts as present: usage text, an auth error or an unknown * flag all mean the CLI is installed here. */ st->token_bin_present = (run_capture(token_bin(), "--help", &b) == 1); buf_free(&b); } } /* ------------------------------------------------------------------ */ /* JSON emitters */ /* ------------------------------------------------------------------ */ static void emit_json(buf_t *b) { 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); 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_addf(&b, "{\"ok\":false,\"error\":"); buf_json(&b, err); if (detail && *detail) { buf_addf(&b, ",\"detail\":"); buf_json(&b, detail); } buf_addf(&b, "}\n"); /* emit_json() would prepend its own header block again; emit_error has * already written a Status: line, so flush the buffer directly. */ fputs(buf_str(&b), stdout); buf_free(&b); } /* One status payload, shared by ?action=status, ?format=json, the poll "done" * branch, cancel and refresh so the five can never disagree about what the * node holds. `prefix` replaces the opening {"ok":true so a caller can lead * with its own contract fields; NULL means the plain status object. */ static void emit_status_json(buf_t *b, const status_t *st, const char *prefix) { long long now = (long long)time(NULL); long long left = st->expires_at > 0 ? st->expires_at - now : 0; buf_adds(b, prefix ? prefix : "{\"ok\":true"); buf_adds(b, ",\"provider\":\"opencode\""); buf_adds(b, ",\"logged_in\":"); buf_adds(b, st->logged_in ? "true" : "false"); buf_adds(b, ",\"username\":"); buf_json(b, st->account[0] ? st->account : (st->logged_in ? "OpenCode" : "")); buf_adds(b, ",\"account\":"); buf_json(b, st->account[0] ? st->account : ""); buf_adds(b, ",\"org_id\":"); buf_json(b, st->org[0] ? st->org : ""); buf_addf(b, ",\"expires_at\":%lld", st->expires_at); buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_at > 0 ? left : 0); buf_adds(b, ",\"expired\":"); buf_adds(b, st->expired ? "true" : "false"); buf_adds(b, ",\"has_refresh\":");buf_adds(b, st->has_refresh ? "true" : "false"); buf_adds(b, ",\"pending\":"); buf_adds(b, st->pending ? "true" : "false"); if (st->pending_age >= 0) buf_addf(b, ",\"pending_age_sec\":%lld", st->pending_age); buf_adds(b, ",\"profile\":"); buf_json(b, st->profile); buf_adds(b, ",\"profile_exists\":"); buf_adds(b, st->profile_exists ? "true" : "false"); buf_adds(b, ",\"cli_present\":"); buf_adds(b, st->cli_present ? "true" : "false"); buf_adds(b, ",\"token_cli_present\":"); buf_adds(b, st->token_bin_present ? "true" : "false"); buf_adds(b, ",\"path\":"); buf_json(b, st->path); if (st->cli_error[0]) { buf_adds(b, ",\"cli_error\":"); buf_json(b, st->cli_error); } buf_adds(b, ",\"protocol\":\"SXLOGIN-MACHINE-V1\""); buf_adds(b, ",\"plugin\":\"" PLUGIN_ID "\""); buf_addf(b, ",\"plugin_version\":\"%s\"", PLUGIN_VER); buf_adds(b, ",\"now\":"); buf_addf(b, "%lld", now); buf_adds(b, "}\n"); } static int action_status(void) { status_t st; buf_t b; collect_status(&st); buf_init(&b); emit_status_json(&b, &st, NULL); emit_json(&b); return 0; } /* ------------------------------------------------------------------ */ /* Device flow actions */ /* ------------------------------------------------------------------ */ /* Ask the login CLI to begin the device flow. `--force` is appended when the * caller passes force=1, which is how the UI lets a user re-login over an * existing session (the CLI refuses to clobber credentials otherwise). */ static int action_start(void) { status_t st; buf_t in; buf_t out; const char *j; char args[32]; char verify[URL_SZ] = {0}; char code[CODE_SZ] = {0}; int force = 0; int interval = 5; long long expires_in = 900; int rc; collect_status(&st); if (!st.cli_present) { emit_error(200, "OK", "cli_unavailable", "scorpiox-opencode-login is not on this node"); return 0; } force = query_has(getenv("QUERY_STRING"), "force") ? 1 : 0; snprintf(args, sizeof(args), "--start%s", force ? " --force" : ""); buf_init(&in); rc = run_capture(login_bin(), args, &in); if (rc < 0) { buf_free(&in); emit_error(200, "OK", "cli_unavailable", "scorpiox-opencode-login is not on this node"); return 0; } if (rc == 0) { buf_free(&in); emit_error(500, "Internal Server Error", "start_failed", "cannot spawn login CLI"); return 1; } j = last_json_line(&in); if (!j) { buf_free(&in); emit_error(502, "Bad Gateway", "start_failed", "login CLI produced no JSON"); return 1; } { const char *je = j + strlen(j); 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); 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\":\"opencode\"}\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(void) { status_t st; buf_t in; buf_t out; const char *j; char state[64] = {0}; int rc; collect_status(&st); if (!st.cli_present) { emit_error(200, "OK", "cli_unavailable", "scorpiox-opencode-login is not on this node"); return 0; } buf_init(&in); rc = run_capture(login_bin(), "--poll", &in); if (rc < 0) { buf_free(&in); emit_error(200, "OK", "cli_unavailable", "scorpiox-opencode-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); emit_status_json(&out, &st, "{\"ok\":true,\"state\":\"done\""); 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, ",\"logged_in\":"); buf_adds(&out, st.logged_in ? "true" : "false"); buf_adds(&out, ",\"pending\":false}\n"); emit_json(&out); return 0; } if (strcmp(state, "done") == 0 || json_bool_field(j, je, "logged_in", 0)) { /* Authorised: re-read the node state from the files so the answer * is what this machine actually holds, not what the CLI claims. */ status_t fresh; collect_status(&fresh); buf_init(&out); emit_status_json(&out, &fresh, "{\"ok\":true,\"state\":\"done\""); emit_json(&out); return 0; } { int interval = (int)json_num_field(j, je, "interval"); if (interval < 1) interval = 5; buf_free(&in); buf_init(&out); buf_addf(&out, "{\"ok\":true,\"state\":\"pending\",\"interval\":%d," "\"logged_in\":false,\"pending\":true}\n", interval); emit_json(&out); return 0; } } } static int action_cancel(void) { status_t st; buf_t in; buf_t out; collect_status(&st); 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(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; } buf_init(&in); { int rc = run_capture(login_bin(), "--cancel", &in); if (rc < 0) { buf_free(&in); emit_error(200, "OK", "cli_unavailable", "scorpiox-opencode-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); buf_init(&out); emit_status_json(&out, &after, "{\"ok\":true,\"state\":\"cancelled\""); emit_json(&out); } } } return 0; } /* Re-read and re-verify the stored token through the node's own token CLI. * OpenCode tokens are long-lived; there is no refresh grant on this node, so * "refresh" means "ask the CLI for a live token right now and report the new * expiry". The token value is read into a throwaway buffer and discarded. */ static int action_refresh(void) { status_t st; buf_t in; buf_t out; const char *j; collect_status(&st); if (!st.token_bin_present) { emit_error(200, "OK", "refresh_unavailable", "scorpiox-opencode-fetchtoken is not on this node"); return 0; } if (!st.logged_in) { emit_error(200, "OK", "not_logged_in", "start a device login first"); return 0; } buf_init(&in); { int rc = run_capture(token_bin(), "-local", &in); if (rc <= 0) { buf_free(&in); emit_error(200, "OK", "refresh_failed", "token CLI could not run"); return 1; } } j = last_json_line(&in); if (!j) { buf_free(&in); emit_error(200, "OK", "refresh_failed", "token CLI produced no JSON"); return 1; } { const char *je = j + strlen(j); long long exp = normalise_expiry(json_num_field(j, je, "expires_at")); char org[ORG_SZ] = {0}; int has_tok = json_str_present(j, je, "access_token"); json_str_field(j, je, "org_id", org, sizeof(org)); buf_free(&in); if (!has_tok) { emit_error(200, "OK", "refresh_failed", "token CLI returned no token"); return 1; } st.expires_at = exp > 0 ? exp : st.expires_at; st.expired = (st.expires_at > 0 && st.expires_at < (long long)time(NULL)); if (org[0] && !st.org[0]) { snprintf(st.org, sizeof(st.org), "%s", org); snprintf(st.account, sizeof(st.account), "%s", org); } buf_init(&out); emit_status_json(&out, &st, "{\"ok\":true,\"refreshed\":true"); emit_json(&out); return 0; } } /* ------------------------------------------------------------------ */ /* HTML UI */ /* ------------------------------------------------------------------ */ static void serve_html(void) { const char *qs = getenv("QUERY_STRING"); int embed = (qs && (strstr(qs, "embed=1") || strstr(qs, "embed=true"))); const char *s; fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "X-Frame-Options: SAMEORIGIN\r\n" "Referrer-Policy: same-origin\r\n\r\n", stdout); /* UI_HTML carries two control-byte placeholders: \001 where the bot theme * tokens + prepaint script belong, \002 where the theme handoff script * belongs. Splitting on them keeps the page readable in src/ui.html and * the theme in one vendored header that can never drift from the bot. */ for (s = UI_HTML; *s; ) { unsigned char c = (unsigned char)*s; if (c == 0x01) { fputs(SX_BOT_THEME_PREPAINT "", stdout); s++; } else if (c == 0x02) { fputs(SX_BOT_THEME_HANDOFF, stdout); s++; } else { fputc((char)c, stdout); s++; } } (void)embed; /* the page reads ?embed=1 itself, before first paint */ } /* ------------------------------------------------------------------ */ /* Entry point */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *qs; char action[64] = {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 = ""; /* 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(); if (strcmp(action, "start") == 0) return action_start(); if (strcmp(action, "poll") == 0) return action_poll(); if (strcmp(action, "cancel") == 0) return action_cancel(); if (strcmp(action, "refresh") == 0) return action_refresh(); emit_error(400, "Bad Request", "unknown_action", "expected status, start, poll, cancel or refresh"); return 1; } /* 3. HTML UI */ serve_html(); return 0; }