| 1 | /* |
| 2 | * plugin_opencode_login - SCORPIOX BOT open-source OpenCode device-code login |
| 3 | * and account token manager for your node. |
| 4 | * |
| 5 | * A single clean-room C99 binary that serves THREE modes: |
| 6 | * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata |
| 7 | * 2. ?action=... / ?format=json -> JSON node API |
| 8 | * 3. GET (default) -> responsive HTML UI |
| 9 | * |
| 10 | * DESIGN NOTE (why there is no TLS in this binary): the OpenCode device flow |
| 11 | * is a sequence of HTTPS POSTs to the provider, and a public clean-room |
| 12 | * repository must not carry a client secret or a vendored TLS stack. So this |
| 13 | * plugin does not speak TLS at all. It drives the node's own login CLI, exactly |
| 14 | * the way the SCORPIOX CODE login tools are meant to be driven (the machine |
| 15 | * mode contract: --status / --start / --poll / --cancel, one JSON line per |
| 16 | * call), and it reads the credential file that the CLI writes: |
| 17 | * |
| 18 | * ~/.config/opencode/auth.json (access + refresh token) |
| 19 | * ~/.claude/.login-pending/opencode-default.json (pending device flow) |
| 20 | * ~/.claude/scorpiox-env/superopencode.txt (the profile the CLI creates) |
| 21 | * |
| 22 | * Every one of those paths and both CLIs can be overridden for deterministic |
| 23 | * offline testing: |
| 24 | * |
| 25 | * OPENCODE_CREDS_PATH the credential json (default ~/.config/opencode/auth.json) |
| 26 | * OPENCODE_PENDING_PATH the pending-flow marker |
| 27 | * OPENCODE_LOGIN_BIN the login CLI (default scorpiox-opencode-login) |
| 28 | * OPENCODE_TOKEN_BIN the token CLI (default scorpiox-opencode-fetchtoken) |
| 29 | * OPENCODE_ENV_DIR the profile dir (default ~/.claude/scorpiox-env) |
| 30 | * |
| 31 | * No token is ever printed, logged or returned by this plugin: the API reports |
| 32 | * presence and expiry only, and the refresh action reports success or the |
| 33 | * failure reason from the token CLI with the payload discarded. |
| 34 | * |
| 35 | * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and |
| 36 | * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under |
| 37 | * scorpiox-server on the node. |
| 38 | * |
| 39 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 40 | */ |
| 41 | |
| 42 | /* Must come before every include on Windows: MinGW defaults to 0x502 |
| 43 | * (Server 2003), which hides the Win7+ APIs and the path helpers. */ |
| 44 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 45 | # define _WIN32_WINNT 0x0601 |
| 46 | #endif |
| 47 | |
| 48 | #if !defined(_WIN32) |
| 49 | # define _POSIX_C_SOURCE 200809L |
| 50 | # define _DEFAULT_SOURCE 1 |
| 51 | # if defined(__APPLE__) |
| 52 | # define _DARWIN_C_SOURCE 1 |
| 53 | # endif |
| 54 | #endif |
| 55 | |
| 56 | #include <stdio.h> |
| 57 | #include <stdlib.h> |
| 58 | #include <string.h> |
| 59 | #include <ctype.h> |
| 60 | #include <errno.h> |
| 61 | #include <time.h> |
| 62 | #include <stdarg.h> |
| 63 | |
| 64 | #if defined(_WIN32) |
| 65 | # define WIN32_LEAN_AND_MEAN |
| 66 | # include <windows.h> |
| 67 | # include <direct.h> |
| 68 | # include <io.h> |
| 69 | #else |
| 70 | # include <unistd.h> |
| 71 | # include <sys/stat.h> |
| 72 | # include <sys/types.h> |
| 73 | #endif |
| 74 | |
| 75 | #include "bot_theme_plugin.h" |
| 76 | #include "ui_html.h" |
| 77 | |
| 78 | #define PLUGIN_SLUG "opencode-login" |
| 79 | #define PLUGIN_ID "plugin_opencode_login" |
| 80 | #define PLUGIN_VER "1.0.0" |
| 81 | #define PLUGIN_NAME "opencode" |
| 82 | #define PLUGIN_DESC "OpenCode login" |
| 83 | |
| 84 | #define PATH_SZ 1024 |
| 85 | #define LABEL_SZ 256 |
| 86 | #define ORG_SZ 256 |
| 87 | #define CODE_SZ 64 |
| 88 | #define URL_SZ 1024 |
| 89 | #define CMD_SZ 4096 |
| 90 | #define OUT_MAX (256 * 1024) |
| 91 | #define FIELD_SZ 512 |
| 92 | |
| 93 | #define DEFAULT_LOGIN_BIN "scorpiox-opencode-login" |
| 94 | #define DEFAULT_TOKEN_BIN "scorpiox-opencode-fetchtoken" |
| 95 | |
| 96 | /* The device-flow marker the login CLI writes and removes. Its TTL matches the |
| 97 | * CLI's own (900 s); the plugin only uses it to decide whether the UI should |
| 98 | * show a live polling indicator, never to authorise anything. */ |
| 99 | #define PENDING_TTL_SEC 900 |
| 100 | |
| 101 | /* ------------------------------------------------------------------ */ |
| 102 | /* Growable byte buffer */ |
| 103 | /* ------------------------------------------------------------------ */ |
| 104 | |
| 105 | typedef struct { |
| 106 | char *p; |
| 107 | size_t n; |
| 108 | size_t cap; |
| 109 | } buf_t; |
| 110 | |
| 111 | static void buf_init(buf_t *b) |
| 112 | { |
| 113 | b->p = NULL; |
| 114 | b->n = 0; |
| 115 | b->cap = 0; |
| 116 | } |
| 117 | |
| 118 | static int buf_need(buf_t *b, size_t extra) |
| 119 | { |
| 120 | size_t want = b->n + extra + 1; |
| 121 | char *np; |
| 122 | |
| 123 | if (want <= b->cap) return 1; |
| 124 | if (b->cap == 0) b->cap = 1024; |
| 125 | while (b->cap < want) { |
| 126 | if (b->cap > (size_t)32 * 1024 * 1024) return 0; |
| 127 | b->cap *= 2; |
| 128 | } |
| 129 | np = (char *)realloc(b->p, b->cap); |
| 130 | if (!np) return 0; |
| 131 | b->p = np; |
| 132 | return 1; |
| 133 | } |
| 134 | |
| 135 | static int buf_addc(buf_t *b, char c) |
| 136 | { |
| 137 | if (!buf_need(b, 1)) return 0; |
| 138 | b->p[b->n++] = c; |
| 139 | b->p[b->n] = '\0'; |
| 140 | return 1; |
| 141 | } |
| 142 | |
| 143 | static int buf_adds(buf_t *b, const char *s) |
| 144 | { |
| 145 | size_t len; |
| 146 | if (!s) return 1; |
| 147 | len = strlen(s); |
| 148 | if (!buf_need(b, len)) return 0; |
| 149 | memcpy(b->p + b->n, s, len); |
| 150 | b->n += len; |
| 151 | b->p[b->n] = '\0'; |
| 152 | return 1; |
| 153 | } |
| 154 | |
| 155 | static int buf_addf(buf_t *b, const char *fmt, ...) |
| 156 | { |
| 157 | char tmp[2048]; |
| 158 | va_list ap; |
| 159 | int n; |
| 160 | |
| 161 | va_start(ap, fmt); |
| 162 | n = vsnprintf(tmp, sizeof(tmp), fmt, ap); |
| 163 | va_end(ap); |
| 164 | if (n < 0) return 0; |
| 165 | if ((size_t)n >= sizeof(tmp)) n = (int)sizeof(tmp) - 1; |
| 166 | return buf_adds(b, tmp); |
| 167 | } |
| 168 | |
| 169 | /* Append s as a JSON string literal (escapes control characters). */ |
| 170 | static int buf_json(buf_t *b, const char *s) |
| 171 | { |
| 172 | if (!buf_addc(b, '"')) return 0; |
| 173 | for (; s && *s; s++) { |
| 174 | unsigned char c = (unsigned char)*s; |
| 175 | switch (c) { |
| 176 | case '"': if (!buf_adds(b, "\\\"")) return 0; continue; |
| 177 | case '\\': if (!buf_adds(b, "\\\\")) return 0; continue; |
| 178 | case '\n': if (!buf_adds(b, "\\n")) return 0; continue; |
| 179 | case '\r': if (!buf_adds(b, "\\r")) return 0; continue; |
| 180 | case '\t': if (!buf_adds(b, "\\t")) return 0; continue; |
| 181 | default: break; |
| 182 | } |
| 183 | if (c < 0x20) { if (!buf_addf(b, "\\u%04x", c)) return 0; } |
| 184 | else if (!buf_addc(b, (char)c)) return 0; |
| 185 | } |
| 186 | return buf_addc(b, '"'); |
| 187 | } |
| 188 | |
| 189 | static const char *buf_str(buf_t *b) |
| 190 | { |
| 191 | if (!b->p) return ""; |
| 192 | return b->p; |
| 193 | } |
| 194 | |
| 195 | static void buf_free(buf_t *b) |
| 196 | { |
| 197 | free(b->p); |
| 198 | b->p = NULL; |
| 199 | b->n = 0; |
| 200 | b->cap = 0; |
| 201 | } |
| 202 | |
| 203 | /* ------------------------------------------------------------------ */ |
| 204 | /* Query string */ |
| 205 | /* ------------------------------------------------------------------ */ |
| 206 | |
| 207 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 208 | { |
| 209 | size_t klen; |
| 210 | const char *p; |
| 211 | |
| 212 | if (!out || outsz == 0) return 0; |
| 213 | out[0] = '\0'; |
| 214 | if (!qs || !key) return 0; |
| 215 | klen = strlen(key); |
| 216 | p = qs; |
| 217 | while (*p) { |
| 218 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 219 | size_t i = 0; |
| 220 | p += klen + 1; |
| 221 | while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; |
| 222 | out[i] = '\0'; |
| 223 | return 1; |
| 224 | } |
| 225 | p = strchr(p, '&'); |
| 226 | if (!p) break; |
| 227 | p++; |
| 228 | } |
| 229 | return 0; |
| 230 | } |
| 231 | |
| 232 | static int query_has(const char *qs, const char *key) |
| 233 | { |
| 234 | size_t klen = strlen(key); |
| 235 | const char *p = qs; |
| 236 | |
| 237 | while (p && *p) { |
| 238 | if (strncmp(p, key, klen) == 0 && |
| 239 | (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) |
| 240 | return 1; |
| 241 | p = strchr(p, '&'); |
| 242 | if (!p) break; |
| 243 | p++; |
| 244 | } |
| 245 | return 0; |
| 246 | } |
| 247 | |
| 248 | |
| 249 | /* ------------------------------------------------------------------ */ |
| 250 | /* Node auth (X-Bot-Password / Bearer / ?pwd=) */ |
| 251 | /* ------------------------------------------------------------------ */ |
| 252 | |
| 253 | static void require_node_auth(void) |
| 254 | { |
| 255 | const char *np = getenv("BOT_PASSWORD"); |
| 256 | const char *xp; |
| 257 | const char *auth; |
| 258 | char qpwd[256] = {0}; |
| 259 | |
| 260 | if (!np || !*np) return; |
| 261 | |
| 262 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 263 | if (xp && strcmp(xp, np) == 0) return; |
| 264 | |
| 265 | auth = getenv("HTTP_AUTHORIZATION"); |
| 266 | if (auth) { |
| 267 | while (*auth == ' ') auth++; |
| 268 | if (strncasecmp(auth, "Bearer ", 7) == 0) { |
| 269 | auth += 7; |
| 270 | while (*auth == ' ') auth++; |
| 271 | if (strcmp(auth, np) == 0) return; |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && |
| 276 | strcmp(qpwd, np) == 0) return; |
| 277 | |
| 278 | fputs("Status: 401 Unauthorized\r\n" |
| 279 | "Content-Type: application/json; charset=utf-8\r\n" |
| 280 | "Cache-Control: no-store\r\n\r\n" |
| 281 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 282 | exit(0); |
| 283 | } |
| 284 | |
| 285 | /* ------------------------------------------------------------------ */ |
| 286 | /* Paths */ |
| 287 | /* ------------------------------------------------------------------ */ |
| 288 | |
| 289 | static const char *home_dir(void) |
| 290 | { |
| 291 | #ifdef _WIN32 |
| 292 | static char home[512]; |
| 293 | DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); |
| 294 | if (n > 0 && n < sizeof(home)) return home; |
| 295 | home[0] = '\0'; |
| 296 | if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) { |
| 297 | char tmp[512]; |
| 298 | if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) { |
| 299 | strncat(home, tmp, sizeof(home) - strlen(home) - 1); |
| 300 | return home; |
| 301 | } |
| 302 | } |
| 303 | return NULL; |
| 304 | #else |
| 305 | const char *h = getenv("HOME"); |
| 306 | return (h && *h) ? h : NULL; |
| 307 | #endif |
| 308 | } |
| 309 | |
| 310 | #if defined(_WIN32) |
| 311 | # define PATH_SEP '\\' |
| 312 | #else |
| 313 | # define PATH_SEP '/' |
| 314 | #endif |
| 315 | |
| 316 | /* Credential json: OPENCODE_CREDS_PATH, else ~/.config/opencode/auth.json - |
| 317 | * the file the login CLI actually writes. ~/.opencode/token.json is probed as a |
| 318 | * secondary location so a relocated or hand-written install is still seen. */ |
| 319 | static void creds_path(char *out, size_t n) |
| 320 | { |
| 321 | const char *env = getenv("OPENCODE_CREDS_PATH"); |
| 322 | const char *home = home_dir(); |
| 323 | |
| 324 | if (env && *env) { snprintf(out, n, "%s", env); return; } |
| 325 | if (!home) { snprintf(out, n, "auth.json"); return; } |
| 326 | snprintf(out, n, "%s%c.config%copencode%cauth.json", |
| 327 | home, PATH_SEP, PATH_SEP, PATH_SEP); |
| 328 | } |
| 329 | |
| 330 | /* The secondary, spec-named location (only consulted when the primary is |
| 331 | * absent, so a normal install never pays for it). */ |
| 332 | static int creds_path_alt(char *out, size_t n) |
| 333 | { |
| 334 | const char *home = home_dir(); |
| 335 | |
| 336 | if (getenv("OPENCODE_CREDS_PATH")) return 0; /* override wins outright */ |
| 337 | if (!home) return 0; |
| 338 | snprintf(out, n, "%s%c.opencode%ctoken.json", home, PATH_SEP, PATH_SEP); |
| 339 | return 1; |
| 340 | } |
| 341 | |
| 342 | /* The pending device-flow marker written by the login CLI. */ |
| 343 | static void pending_path(char *out, size_t n) |
| 344 | { |
| 345 | const char *env = getenv("OPENCODE_PENDING_PATH"); |
| 346 | const char *home = home_dir(); |
| 347 | |
| 348 | if (env && *env) { snprintf(out, n, "%s", env); return; } |
| 349 | if (!home) { snprintf(out, n, "opencode-default.json"); return; } |
| 350 | snprintf(out, n, "%s%c.claude%c.login-pending%copencode-default.json", |
| 351 | home, PATH_SEP, PATH_SEP, PATH_SEP); |
| 352 | } |
| 353 | |
| 354 | static void env_dir(char *out, size_t n) |
| 355 | { |
| 356 | const char *env = getenv("OPENCODE_ENV_DIR"); |
| 357 | const char *creds = getenv("OPENCODE_CREDS_PATH"); |
| 358 | const char *home = home_dir(); |
| 359 | |
| 360 | if (env && *env) { snprintf(out, n, "%s", env); return; } |
| 361 | |
| 362 | /* A relocated credential file implies a relocated profile: they are written |
| 363 | * by the same CLI into the same tree, and reading one from the default home |
| 364 | * while the other is overridden makes status report a missing profile for a |
| 365 | * session that has one. */ |
| 366 | if (creds && *creds) { |
| 367 | char base[PATH_SZ]; |
| 368 | char *slash; |
| 369 | snprintf(base, sizeof(base), "%s", creds); |
| 370 | slash = strrchr(base, PATH_SEP); |
| 371 | if (!slash) slash = strrchr(base, '/'); |
| 372 | if (slash) { |
| 373 | *(slash + 1) = '\0'; |
| 374 | if (strlen(base) + 16 < n) { snprintf(out, n, "%sscorpiox-env", base); return; } |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | if (!home) { snprintf(out, n, "."); return; } |
| 379 | snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP); |
| 380 | } |
| 381 | |
| 382 | static void profile_path(char *out, size_t n) |
| 383 | { |
| 384 | char d[PATH_SZ]; |
| 385 | |
| 386 | env_dir(d, sizeof(d)); |
| 387 | /* Copy with explicit bounds so a long directory cannot have its tail |
| 388 | * replaced by the filename (snprintf would silently truncate). */ |
| 389 | { |
| 390 | const char *name = "superopencode.txt"; |
| 391 | size_t dl = strlen(d); |
| 392 | if (dl + 1 + strlen(name) >= n) { snprintf(out, n, "%s", name); return; } |
| 393 | memcpy(out, d, dl); |
| 394 | out[dl] = PATH_SEP; |
| 395 | memcpy(out + dl + 1, name, strlen(name) + 1); |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | static const char *login_bin(void) |
| 400 | { |
| 401 | const char *b = getenv("OPENCODE_LOGIN_BIN"); |
| 402 | return (b && *b) ? b : DEFAULT_LOGIN_BIN; |
| 403 | } |
| 404 | |
| 405 | static const char *token_bin(void) |
| 406 | { |
| 407 | const char *b = getenv("OPENCODE_TOKEN_BIN"); |
| 408 | return (b && *b) ? b : DEFAULT_TOKEN_BIN; |
| 409 | } |
| 410 | |
| 411 | static int file_exists(const char *p) |
| 412 | { |
| 413 | #if defined(_WIN32) |
| 414 | DWORD a = GetFileAttributesA(p); |
| 415 | return (a != (DWORD)-1); |
| 416 | #else |
| 417 | struct stat st; |
| 418 | return p && *p && stat(p, &st) == 0; |
| 419 | #endif |
| 420 | } |
| 421 | |
| 422 | /* Whole-file read; NULL on any failure. Caller frees. */ |
| 423 | static char *read_file(const char *path) |
| 424 | { |
| 425 | FILE *f; |
| 426 | long sz; |
| 427 | char *buf; |
| 428 | |
| 429 | if (!path || !*path) return NULL; |
| 430 | f = fopen(path, "rb"); |
| 431 | if (!f) return NULL; |
| 432 | if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } |
| 433 | sz = ftell(f); |
| 434 | if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } |
| 435 | if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } |
| 436 | buf = (char *)malloc((size_t)sz + 1); |
| 437 | if (!buf) { fclose(f); return NULL; } |
| 438 | if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { |
| 439 | free(buf); |
| 440 | fclose(f); |
| 441 | return NULL; |
| 442 | } |
| 443 | buf[sz] = '\0'; |
| 444 | fclose(f); |
| 445 | return buf; |
| 446 | } |
| 447 | |
| 448 | /* Trim trailing CR/LF/space in place. */ |
| 449 | static void trim_tail(char *s) |
| 450 | { |
| 451 | size_t n; |
| 452 | if (!s) return; |
| 453 | n = strlen(s); |
| 454 | while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' || |
| 455 | s[n - 1] == ' ' || s[n - 1] == '\t')) |
| 456 | s[--n] = '\0'; |
| 457 | } |
| 458 | |
| 459 | /* ------------------------------------------------------------------ */ |
| 460 | /* Minimal JSON field readers */ |
| 461 | /* ------------------------------------------------------------------ */ |
| 462 | |
| 463 | /* Copy a JSON string value that starts at *pp (which points at the opening |
| 464 | * quote). Advances *pp past the closing quote. */ |
| 465 | static int json_read_string_at(const char **pp, char *out, size_t outsz) |
| 466 | { |
| 467 | const char *p = *pp; |
| 468 | size_t i = 0; |
| 469 | |
| 470 | if (!p || *p != '"') return 0; |
| 471 | p++; |
| 472 | while (*p && *p != '"') { |
| 473 | char c = *p; |
| 474 | if (c == '\\' && p[1]) { |
| 475 | p++; |
| 476 | switch (*p) { |
| 477 | case 'n': c = '\n'; break; |
| 478 | case 'r': c = '\r'; break; |
| 479 | case 't': c = '\t'; break; |
| 480 | case 'b': c = '\b'; break; |
| 481 | case 'f': c = '\f'; break; |
| 482 | case 'u': { |
| 483 | unsigned int v = 0; |
| 484 | int k; |
| 485 | p++; |
| 486 | for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) |
| 487 | v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) |
| 488 | ? *p - '0' |
| 489 | : tolower((unsigned char)*p) - 'a' + 10); |
| 490 | if (i + 1 < outsz) out[i++] = (char)(v & 0xff); |
| 491 | continue; |
| 492 | } |
| 493 | default: c = *p; break; |
| 494 | } |
| 495 | p++; |
| 496 | } else { |
| 497 | p++; |
| 498 | } |
| 499 | if (i + 1 < outsz) out[i++] = c; |
| 500 | } |
| 501 | if (*p == '"') p++; |
| 502 | if (outsz) out[i < outsz ? i : outsz - 1] = '\0'; |
| 503 | *pp = p; |
| 504 | return 1; |
| 505 | } |
| 506 | |
| 507 | |
| 508 | /* Find "key":<value> anywhere inside the slice [obj, end) and return the |
| 509 | * value pointer. Only top-level keys of that slice are considered: a nested |
| 510 | * object is skipped as a whole. */ |
| 511 | static const char *json_find_key(const char *obj, const char *end, const char *key) |
| 512 | { |
| 513 | size_t klen = strlen(key); |
| 514 | const char *p = obj; |
| 515 | int depth = 0; |
| 516 | |
| 517 | if (!obj || !end || !key) return NULL; |
| 518 | /* A caller almost always hands us the whole object, i.e. a pointer at the |
| 519 | * opening '{'. Skipping it here keeps every call site free of the "+1" |
| 520 | * that is easy to forget and silent when it is missing. */ |
| 521 | while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; |
| 522 | if (p < end && *p == '{') p++; |
| 523 | |
| 524 | while (p && p < end) { |
| 525 | if (*p == '"') { |
| 526 | char name[128]; |
| 527 | json_read_string_at(&p, name, sizeof(name)); |
| 528 | if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { |
| 529 | const char *q = p; |
| 530 | while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; |
| 531 | if (q < end && *q == ':') { |
| 532 | q++; |
| 533 | while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; |
| 534 | return (q < end) ? q : NULL; |
| 535 | } |
| 536 | } |
| 537 | continue; |
| 538 | } |
| 539 | if (*p == '{' || *p == '[') depth++; |
| 540 | else if (*p == '}' || *p == ']') depth--; |
| 541 | p++; |
| 542 | } |
| 543 | return NULL; |
| 544 | } |
| 545 | |
| 546 | /* Returns 0 and leaves *out untouched when the key is absent or null. That |
| 547 | * matters: several callers pass a field of a longer-lived struct, and clearing |
| 548 | * it on a miss silently erases a value that was already correct. */ |
| 549 | static int json_str_field(const char *obj, const char *end, const char *key, |
| 550 | char *out, size_t outsz) |
| 551 | { |
| 552 | const char *v; |
| 553 | |
| 554 | if (!out || outsz == 0) return 0; |
| 555 | v = json_find_key(obj, end, key); |
| 556 | if (!v || *v == 'n') return 0; |
| 557 | out[0] = '\0'; |
| 558 | if (*v == '"') return json_read_string_at(&v, out, outsz); |
| 559 | { |
| 560 | size_t i = 0; |
| 561 | while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; |
| 562 | out[i] = '\0'; |
| 563 | trim_tail(out); |
| 564 | return out[0] ? 1 : 0; |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) |
| 569 | { |
| 570 | const char *v = json_find_key(obj, end, key); |
| 571 | |
| 572 | if (!v) return dflt; |
| 573 | if (strncmp(v, "true", 4) == 0) return 1; |
| 574 | if (strncmp(v, "false", 5) == 0) return 0; |
| 575 | if (*v == '"') { |
| 576 | if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1; |
| 577 | return 0; |
| 578 | } |
| 579 | if (*v == '1') return 1; |
| 580 | return 0; |
| 581 | } |
| 582 | |
| 583 | static long long json_num_field(const char *obj, const char *end, const char *key) |
| 584 | { |
| 585 | const char *v = json_find_key(obj, end, key); |
| 586 | long long vll = 0; |
| 587 | int neg = 0; |
| 588 | |
| 589 | if (!v) return 0; |
| 590 | if (*v == '"') v++; |
| 591 | if (*v == '-') { neg = 1; v++; } |
| 592 | while (isdigit((unsigned char)*v)) { vll = vll * 10 + (*v++ - '0'); } |
| 593 | return neg ? -vll : vll; |
| 594 | } |
| 595 | |
| 596 | /* True when the object contains a non-empty string under key. Used for token |
| 597 | * presence without ever copying the token itself into a wider buffer. */ |
| 598 | static int json_str_present(const char *obj, const char *end, const char *key) |
| 599 | { |
| 600 | const char *v = json_find_key(obj, end, key); |
| 601 | const char *q; |
| 602 | |
| 603 | if (!v) return 0; |
| 604 | if (*v != '"') return 0; |
| 605 | q = v + 1; |
| 606 | while (*q && *q != '"') { |
| 607 | if (*q == '\\' && q[1]) { q += 2; continue; } |
| 608 | return 1; /* at least one real character */ |
| 609 | } |
| 610 | return 0; /* "" - present but empty */ |
| 611 | } |
| 612 | |
| 613 | /* ------------------------------------------------------------------ */ |
| 614 | /* Running the node's login CLI */ |
| 615 | /* ------------------------------------------------------------------ */ |
| 616 | |
| 617 | /* Wrap a string in single quotes for the shell, so a path or a binary name |
| 618 | * containing spaces or punctuation cannot break the command line. */ |
| 619 | static void shell_quote_into(const char *in, char *out, size_t outsz) |
| 620 | { |
| 621 | size_t o = 0; |
| 622 | const char *p; |
| 623 | |
| 624 | if (outsz < 3) { if (outsz) out[0] = '\0'; return; } |
| 625 | out[o++] = '\''; |
| 626 | for (p = in; p && *p; p++) { |
| 627 | if (*p == '\'') { |
| 628 | if (o + 5 >= outsz) break; |
| 629 | memcpy(out + o, "'\\''", 4); |
| 630 | o += 4; |
| 631 | } else { |
| 632 | if (o + 2 >= outsz) break; |
| 633 | out[o++] = *p; |
| 634 | } |
| 635 | } |
| 636 | out[o++] = '\''; |
| 637 | out[o] = '\0'; |
| 638 | } |
| 639 | |
| 640 | /* Run `<bin> <args>` and capture stdout. args may be NULL or a pre-built |
| 641 | * shell fragment. Returns 1 when the process ran, -1 when the binary was not |
| 642 | * found, 0 when popen itself failed. The captured text is stored in out. */ |
| 643 | static int run_capture(const char *bin, const char *args, buf_t *out) |
| 644 | { |
| 645 | char cmd[CMD_SZ]; |
| 646 | char qbin[FIELD_SZ]; |
| 647 | FILE *f; |
| 648 | char line[2048]; |
| 649 | size_t total = 0; |
| 650 | int rc; |
| 651 | |
| 652 | if (!bin || !*bin) return 0; |
| 653 | shell_quote_into(bin, qbin, sizeof(qbin)); |
| 654 | if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args); |
| 655 | else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin); |
| 656 | |
| 657 | f = popen(cmd, "r"); |
| 658 | if (!f) return 0; |
| 659 | while (fgets(line, sizeof(line), f)) { |
| 660 | total += strlen(line); |
| 661 | if (total > OUT_MAX) break; |
| 662 | buf_adds(out, line); |
| 663 | } |
| 664 | rc = pclose(f); |
| 665 | |
| 666 | if (out->p) { |
| 667 | /* the CLIs print one JSON line last; strip surrounding whitespace */ |
| 668 | size_t n = out->n; |
| 669 | while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0'; |
| 670 | out->n = n; |
| 671 | } |
| 672 | /* pclose() hands back a wait status, not an exit code: "command not |
| 673 | * found" arrives as 32512 (127 << 8). Callers treat that as "the CLI is |
| 674 | * not on this node", which is a different message from "the CLI ran and |
| 675 | * failed". Any other status is the CLI's own and is left to the JSON it |
| 676 | * printed. */ |
| 677 | if (rc != -1 && (rc >> 8) == 127) return -1; |
| 678 | return 1; |
| 679 | } |
| 680 | |
| 681 | /* The login CLI prints human progress on stdout before the final JSON line, |
| 682 | * so take the LAST line that starts with '{'. */ |
| 683 | static const char *last_json_line(buf_t *b) |
| 684 | { |
| 685 | size_t i; |
| 686 | const char *last = NULL; |
| 687 | |
| 688 | if (!b || !b->p) return NULL; |
| 689 | for (i = 0; i < b->n; i++) { |
| 690 | int at_line_start = (i == 0) || b->p[i - 1] == '\n'; |
| 691 | if (at_line_start && b->p[i] == '{') last = b->p + i; |
| 692 | } |
| 693 | return last; |
| 694 | } |
| 695 | |
| 696 | /* ------------------------------------------------------------------ */ |
| 697 | /* Status model */ |
| 698 | /* ------------------------------------------------------------------ */ |
| 699 | |
| 700 | typedef struct { |
| 701 | char path[PATH_SZ]; |
| 702 | char account[LABEL_SZ]; |
| 703 | char org[ORG_SZ]; |
| 704 | char profile[LABEL_SZ]; |
| 705 | long long expires_at; /* unix seconds, 0 = unknown */ |
| 706 | int logged_in; |
| 707 | int has_refresh; |
| 708 | int expired; |
| 709 | int pending; |
| 710 | long long pending_age; /* seconds since the marker was written, -1 unknown */ |
| 711 | int profile_exists; |
| 712 | int cli_present; /* 1 when the login CLI ran at all this call */ |
| 713 | int cli_pending_unknown;/* 1 when no marker file exists to TTL-check */ |
| 714 | int cli_ok; /* 1 when the login CLI answered with ok:true */ |
| 715 | int token_bin_present; |
| 716 | char cli_error[FIELD_SZ]; |
| 717 | } status_t; |
| 718 | |
| 719 | /* Normalise an expiry to unix SECONDS. The credential file stores seconds |
| 720 | * (time(NULL) + expires_in); the machine-mode status reports milliseconds. |
| 721 | * A value above 1e11 can only be milliseconds on any realistic date. */ |
| 722 | static long long normalise_expiry(long long v) |
| 723 | { |
| 724 | if (v <= 0) return 0; |
| 725 | if (v > 100000000000LL) return v / 1000; |
| 726 | return v; |
| 727 | } |
| 728 | |
| 729 | static void collect_status(status_t *st) |
| 730 | { |
| 731 | char alt[PATH_SZ]; |
| 732 | char *raw; |
| 733 | const char *end; |
| 734 | long long now = (long long)time(NULL); |
| 735 | |
| 736 | memset(st, 0, sizeof(*st)); |
| 737 | snprintf(st->profile, sizeof(st->profile), "superopencode"); |
| 738 | st->pending_age = -1; |
| 739 | |
| 740 | /* 1. the credential file the CLI writes */ |
| 741 | creds_path(st->path, sizeof(st->path)); |
| 742 | raw = read_file(st->path); |
| 743 | if (!raw && creds_path_alt(alt, sizeof(alt)) && file_exists(alt)) { |
| 744 | free(raw); |
| 745 | raw = read_file(alt); |
| 746 | if (raw) snprintf(st->path, sizeof(st->path), "%s", alt); |
| 747 | } |
| 748 | if (raw) { |
| 749 | end = raw + strlen(raw); |
| 750 | st->logged_in = json_str_present(raw, end, "access_token"); |
| 751 | st->has_refresh = json_str_present(raw, end, "refresh_token"); |
| 752 | st->expires_at = normalise_expiry(json_num_field(raw, end, "expires_at")); |
| 753 | if (!st->expires_at) { |
| 754 | long long ein = json_num_field(raw, end, "expires_in"); |
| 755 | if (ein > 0) st->expires_at = now + ein; |
| 756 | } |
| 757 | if (json_str_field(raw, end, "org_id", st->org, sizeof(st->org))) |
| 758 | snprintf(st->account, sizeof(st->account), "%s", st->org); |
| 759 | free(raw); |
| 760 | } |
| 761 | st->expired = (st->expires_at > 0 && st->expires_at < now); |
| 762 | |
| 763 | /* 2. the pending device-flow marker, owned by the CLI but reported here. |
| 764 | * The marker is the only evidence the plugin can check without a |
| 765 | * network, and it carries the CLI's own creation stamp, so the TTL is |
| 766 | * applied here rather than trusting a later claim. */ |
| 767 | { |
| 768 | char pp[PATH_SZ]; |
| 769 | int marker = 0; |
| 770 | pending_path(pp, sizeof(pp)); |
| 771 | marker = file_exists(pp); |
| 772 | if (marker) { |
| 773 | char *pend = read_file(pp); |
| 774 | long long created = -1; |
| 775 | if (pend) { |
| 776 | const char *pe = pend + strlen(pend); |
| 777 | created = json_num_field(pend, pe, "created"); |
| 778 | free(pend); |
| 779 | } |
| 780 | if (created > 0) { |
| 781 | st->pending_age = now - created; |
| 782 | st->pending = (st->pending_age >= 0 && st->pending_age <= PENDING_TTL_SEC); |
| 783 | } else { |
| 784 | st->pending = 1; /* unreadable marker: assume still open */ |
| 785 | } |
| 786 | } |
| 787 | /* Only when there is no marker at all does the CLI's own pending bit |
| 788 | * get to speak: it reads the same file, so a stale-but-present marker |
| 789 | * must never be revived by it. */ |
| 790 | if (!marker) st->cli_pending_unknown = 1; |
| 791 | } |
| 792 | |
| 793 | /* 3. the profile file the CLI creates */ |
| 794 | { |
| 795 | char prof[PATH_SZ]; |
| 796 | profile_path(prof, sizeof(prof)); |
| 797 | st->profile_exists = file_exists(prof); |
| 798 | } |
| 799 | |
| 800 | /* 4. ask the CLI, and let it ADD to what the files already proved. The |
| 801 | * file-derived booleans win: they are what this node actually has, and |
| 802 | * a stale or partial CLI answer must not erase them. */ |
| 803 | { |
| 804 | buf_t b; |
| 805 | const char *j; |
| 806 | int rc; |
| 807 | |
| 808 | buf_init(&b); |
| 809 | rc = run_capture(login_bin(), "--status", &b); |
| 810 | if (rc < 0) { |
| 811 | st->cli_present = 0; |
| 812 | snprintf(st->cli_error, sizeof(st->cli_error), "cli_not_found"); |
| 813 | } else if (rc == 0) { |
| 814 | st->cli_present = 0; |
| 815 | snprintf(st->cli_error, sizeof(st->cli_error), "cli_spawn_failed"); |
| 816 | } else { |
| 817 | st->cli_present = 1; |
| 818 | j = last_json_line(&b); |
| 819 | if (j) { |
| 820 | const char *je = j + strlen(j); |
| 821 | st->cli_ok = json_bool_field(j, je, "ok", 0); |
| 822 | if (!st->cli_ok) |
| 823 | json_str_field(j, je, "error", st->cli_error, sizeof(st->cli_error)); |
| 824 | if (!st->account[0]) |
| 825 | json_str_field(j, je, "account", st->account, sizeof(st->account)); |
| 826 | if (!st->expires_at) |
| 827 | st->expires_at = normalise_expiry(json_num_field(j, je, "expires_at")); |
| 828 | if (!st->logged_in && json_bool_field(j, je, "logged_in", 0)) |
| 829 | st->logged_in = 1; |
| 830 | if (!st->has_refresh && json_bool_field(j, je, "has_refresh", 0)) |
| 831 | st->has_refresh = 1; |
| 832 | if (!st->pending && st->cli_pending_unknown && |
| 833 | json_bool_field(j, je, "pending", 0)) |
| 834 | st->pending = 1; |
| 835 | if (!st->profile_exists && json_bool_field(j, je, "profile_exists", 0)) |
| 836 | st->profile_exists = 1; |
| 837 | if (!st->path[0]) json_str_field(j, je, "path", st->path, sizeof(st->path)); |
| 838 | } |
| 839 | } |
| 840 | buf_free(&b); |
| 841 | } |
| 842 | st->expired = (st->expires_at > 0 && st->expires_at < (long long)time(NULL)); |
| 843 | |
| 844 | /* 5. is the token CLI on this node at all (used by refresh + the UI) */ |
| 845 | { |
| 846 | buf_t b; |
| 847 | buf_init(&b); |
| 848 | /* run_capture returns 1 when the process actually ran, -1 when the |
| 849 | * binary was not found (exit 127), 0 when popen itself failed. Only |
| 850 | * "it ran" counts as present: usage text, an auth error or an unknown |
| 851 | * flag all mean the CLI is installed here. */ |
| 852 | st->token_bin_present = (run_capture(token_bin(), "--help", &b) == 1); |
| 853 | buf_free(&b); |
| 854 | } |
| 855 | } |
| 856 | |
| 857 | /* ------------------------------------------------------------------ */ |
| 858 | /* JSON emitters */ |
| 859 | /* ------------------------------------------------------------------ */ |
| 860 | |
| 861 | static void emit_json(buf_t *b) |
| 862 | { |
| 863 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 864 | "Cache-Control: no-store\r\n" |
| 865 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 866 | fputs(buf_str(b), stdout); |
| 867 | buf_free(b); |
| 868 | } |
| 869 | |
| 870 | static void emit_error(int code, const char *status, const char *err, const char *detail) |
| 871 | { |
| 872 | buf_t b; |
| 873 | |
| 874 | buf_init(&b); |
| 875 | buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" |
| 876 | "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", |
| 877 | code, status); |
| 878 | buf_addf(&b, "{\"ok\":false,\"error\":"); |
| 879 | buf_json(&b, err); |
| 880 | if (detail && *detail) { |
| 881 | buf_addf(&b, ",\"detail\":"); |
| 882 | buf_json(&b, detail); |
| 883 | } |
| 884 | buf_addf(&b, "}\n"); |
| 885 | /* emit_json() would prepend its own header block again; emit_error has |
| 886 | * already written a Status: line, so flush the buffer directly. */ |
| 887 | fputs(buf_str(&b), stdout); |
| 888 | buf_free(&b); |
| 889 | } |
| 890 | |
| 891 | /* One status payload, shared by ?action=status, ?format=json, the poll "done" |
| 892 | * branch, cancel and refresh so the five can never disagree about what the |
| 893 | * node holds. `prefix` replaces the opening {"ok":true so a caller can lead |
| 894 | * with its own contract fields; NULL means the plain status object. */ |
| 895 | static void emit_status_json(buf_t *b, const status_t *st, const char *prefix) |
| 896 | { |
| 897 | long long now = (long long)time(NULL); |
| 898 | long long left = st->expires_at > 0 ? st->expires_at - now : 0; |
| 899 | |
| 900 | buf_adds(b, prefix ? prefix : "{\"ok\":true"); |
| 901 | buf_adds(b, ",\"provider\":\"opencode\""); |
| 902 | buf_adds(b, ",\"logged_in\":"); buf_adds(b, st->logged_in ? "true" : "false"); |
| 903 | buf_adds(b, ",\"username\":"); buf_json(b, st->account[0] ? st->account : (st->logged_in ? "OpenCode" : "")); |
| 904 | buf_adds(b, ",\"account\":"); buf_json(b, st->account[0] ? st->account : ""); |
| 905 | buf_adds(b, ",\"org_id\":"); buf_json(b, st->org[0] ? st->org : ""); |
| 906 | buf_addf(b, ",\"expires_at\":%lld", st->expires_at); |
| 907 | buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_at > 0 ? left : 0); |
| 908 | buf_adds(b, ",\"expired\":"); buf_adds(b, st->expired ? "true" : "false"); |
| 909 | buf_adds(b, ",\"has_refresh\":");buf_adds(b, st->has_refresh ? "true" : "false"); |
| 910 | buf_adds(b, ",\"pending\":"); buf_adds(b, st->pending ? "true" : "false"); |
| 911 | if (st->pending_age >= 0) buf_addf(b, ",\"pending_age_sec\":%lld", st->pending_age); |
| 912 | buf_adds(b, ",\"profile\":"); buf_json(b, st->profile); |
| 913 | buf_adds(b, ",\"profile_exists\":"); |
| 914 | buf_adds(b, st->profile_exists ? "true" : "false"); |
| 915 | buf_adds(b, ",\"cli_present\":"); |
| 916 | buf_adds(b, st->cli_present ? "true" : "false"); |
| 917 | buf_adds(b, ",\"token_cli_present\":"); |
| 918 | buf_adds(b, st->token_bin_present ? "true" : "false"); |
| 919 | buf_adds(b, ",\"path\":"); buf_json(b, st->path); |
| 920 | if (st->cli_error[0]) { buf_adds(b, ",\"cli_error\":"); buf_json(b, st->cli_error); } |
| 921 | buf_adds(b, ",\"protocol\":\"SXLOGIN-MACHINE-V1\""); |
| 922 | buf_adds(b, ",\"plugin\":\"" PLUGIN_ID "\""); |
| 923 | buf_addf(b, ",\"plugin_version\":\"%s\"", PLUGIN_VER); |
| 924 | buf_adds(b, ",\"now\":"); |
| 925 | buf_addf(b, "%lld", now); |
| 926 | buf_adds(b, "}\n"); |
| 927 | } |
| 928 | |
| 929 | static int action_status(void) |
| 930 | { |
| 931 | status_t st; |
| 932 | buf_t b; |
| 933 | |
| 934 | collect_status(&st); |
| 935 | buf_init(&b); |
| 936 | emit_status_json(&b, &st, NULL); |
| 937 | emit_json(&b); |
| 938 | return 0; |
| 939 | } |
| 940 | |
| 941 | /* ------------------------------------------------------------------ */ |
| 942 | /* Device flow actions */ |
| 943 | /* ------------------------------------------------------------------ */ |
| 944 | |
| 945 | /* Ask the login CLI to begin the device flow. `--force` is appended when the |
| 946 | * caller passes force=1, which is how the UI lets a user re-login over an |
| 947 | * existing session (the CLI refuses to clobber credentials otherwise). */ |
| 948 | static int action_start(void) |
| 949 | { |
| 950 | status_t st; |
| 951 | buf_t in; |
| 952 | buf_t out; |
| 953 | const char *j; |
| 954 | char args[32]; |
| 955 | char verify[URL_SZ] = {0}; |
| 956 | char code[CODE_SZ] = {0}; |
| 957 | int force = 0; |
| 958 | int interval = 5; |
| 959 | long long expires_in = 900; |
| 960 | int rc; |
| 961 | |
| 962 | collect_status(&st); |
| 963 | if (!st.cli_present) { |
| 964 | emit_error(200, "OK", "cli_unavailable", |
| 965 | "scorpiox-opencode-login is not on this node"); |
| 966 | return 0; |
| 967 | } |
| 968 | |
| 969 | force = query_has(getenv("QUERY_STRING"), "force") ? 1 : 0; |
| 970 | |
| 971 | snprintf(args, sizeof(args), "--start%s", force ? " --force" : ""); |
| 972 | |
| 973 | buf_init(&in); |
| 974 | rc = run_capture(login_bin(), args, &in); |
| 975 | if (rc < 0) { |
| 976 | buf_free(&in); |
| 977 | emit_error(200, "OK", "cli_unavailable", |
| 978 | "scorpiox-opencode-login is not on this node"); |
| 979 | return 0; |
| 980 | } |
| 981 | if (rc == 0) { |
| 982 | buf_free(&in); |
| 983 | emit_error(500, "Internal Server Error", "start_failed", "cannot spawn login CLI"); |
| 984 | return 1; |
| 985 | } |
| 986 | |
| 987 | j = last_json_line(&in); |
| 988 | if (!j) { |
| 989 | buf_free(&in); |
| 990 | emit_error(502, "Bad Gateway", "start_failed", "login CLI produced no JSON"); |
| 991 | return 1; |
| 992 | } |
| 993 | { |
| 994 | const char *je = j + strlen(j); |
| 995 | if (!json_bool_field(j, je, "ok", 0)) { |
| 996 | char err[FIELD_SZ] = {0}; |
| 997 | char detail[FIELD_SZ] = {0}; |
| 998 | json_str_field(j, je, "error", err, sizeof(err)); |
| 999 | json_str_field(j, je, "detail", detail, sizeof(detail)); |
| 1000 | buf_free(&in); |
| 1001 | if (strcmp(err, "exists") == 0) { |
| 1002 | /* Credentials are already on this node: the honest answer is |
| 1003 | * "already signed in, press re-login to replace them". */ |
| 1004 | buf_init(&out); |
| 1005 | buf_adds(&out, "{\"ok\":true,\"already_logged_in\":true,\"pending\":false"); |
| 1006 | buf_adds(&out, ",\"error\":\"already_logged_in\""); |
| 1007 | buf_adds(&out, ",\"detail\":"); |
| 1008 | buf_json(&out, detail[0] ? detail : "credentials already exist"); |
| 1009 | buf_adds(&out, ",\"logged_in\":"); |
| 1010 | buf_adds(&out, st.logged_in ? "true" : "false"); |
| 1011 | buf_adds(&out, ",\"hint\":\"pass force=1 to replace the existing session\"}\n"); |
| 1012 | emit_json(&out); |
| 1013 | return 0; |
| 1014 | } |
| 1015 | emit_error(200, "OK", err[0] ? err : "start_failed", detail); |
| 1016 | return 0; |
| 1017 | } |
| 1018 | json_str_field(j, je, "verify_url", verify, sizeof(verify)); |
| 1019 | json_str_field(j, je, "user_code", code, sizeof(code)); |
| 1020 | interval = (int)json_num_field(j, je, "interval"); |
| 1021 | expires_in = json_num_field(j, je, "expires_in"); |
| 1022 | if (interval < 1) interval = 5; |
| 1023 | if (expires_in <= 0) expires_in = PENDING_TTL_SEC; |
| 1024 | } |
| 1025 | buf_free(&in); |
| 1026 | |
| 1027 | if (!verify[0] || !code[0]) { |
| 1028 | emit_error(502, "Bad Gateway", "start_incomplete", |
| 1029 | "login CLI did not return a verify url and user code"); |
| 1030 | return 1; |
| 1031 | } |
| 1032 | |
| 1033 | buf_init(&out); |
| 1034 | buf_addf(&out, "{\"ok\":true,\"flow\":\"device_code\",\"verify_url\":"); |
| 1035 | buf_json(&out, verify); |
| 1036 | buf_adds(&out, ",\"user_code\":"); |
| 1037 | buf_json(&out, code); |
| 1038 | buf_addf(&out, ",\"expires_in\":%lld", expires_in); |
| 1039 | buf_addf(&out, ",\"interval\":%d", interval); |
| 1040 | buf_adds(&out, ",\"pending\":true"); |
| 1041 | buf_adds(&out, ",\"provider\":\"opencode\"}\n"); |
| 1042 | emit_json(&out); |
| 1043 | return 0; |
| 1044 | } |
| 1045 | |
| 1046 | /* One non-blocking poll. The CLI does exactly one HTTPS round trip and |
| 1047 | * returns; the UI drives the cadence so nothing here ever blocks. */ |
| 1048 | static int action_poll(void) |
| 1049 | { |
| 1050 | status_t st; |
| 1051 | buf_t in; |
| 1052 | buf_t out; |
| 1053 | const char *j; |
| 1054 | char state[64] = {0}; |
| 1055 | int rc; |
| 1056 | |
| 1057 | collect_status(&st); |
| 1058 | if (!st.cli_present) { |
| 1059 | emit_error(200, "OK", "cli_unavailable", |
| 1060 | "scorpiox-opencode-login is not on this node"); |
| 1061 | return 0; |
| 1062 | } |
| 1063 | |
| 1064 | buf_init(&in); |
| 1065 | rc = run_capture(login_bin(), "--poll", &in); |
| 1066 | if (rc < 0) { |
| 1067 | buf_free(&in); |
| 1068 | emit_error(200, "OK", "cli_unavailable", |
| 1069 | "scorpiox-opencode-login is not on this node"); |
| 1070 | return 0; |
| 1071 | } |
| 1072 | if (rc == 0) { |
| 1073 | buf_free(&in); |
| 1074 | emit_error(500, "Internal Server Error", "poll_failed", "cannot spawn login CLI"); |
| 1075 | return 1; |
| 1076 | } |
| 1077 | |
| 1078 | j = last_json_line(&in); |
| 1079 | if (!j) { |
| 1080 | buf_free(&in); |
| 1081 | /* No JSON at all. Fall back to what the files say: a credential file |
| 1082 | * that appeared while polling is a success no matter what the CLI |
| 1083 | * printed, and a marker that vanished with no credentials is a dead |
| 1084 | * flow, not an infinite spinner. */ |
| 1085 | if (st.logged_in) { |
| 1086 | buf_init(&out); |
| 1087 | emit_status_json(&out, &st, |
| 1088 | "{\"ok\":true,\"state\":\"done\""); |
| 1089 | emit_json(&out); |
| 1090 | return 0; |
| 1091 | } |
| 1092 | emit_error(502, "Bad Gateway", "poll_failed", "login CLI produced no JSON"); |
| 1093 | return 1; |
| 1094 | } |
| 1095 | { |
| 1096 | const char *je = j + strlen(j); |
| 1097 | json_str_field(j, je, "state", state, sizeof(state)); |
| 1098 | if (!json_bool_field(j, je, "ok", 0)) { |
| 1099 | char err[FIELD_SZ] = {0}; |
| 1100 | char detail[FIELD_SZ] = {0}; |
| 1101 | json_str_field(j, je, "error", err, sizeof(err)); |
| 1102 | json_str_field(j, je, "detail", detail, sizeof(detail)); |
| 1103 | buf_free(&in); |
| 1104 | /* expired / no_pending / denied are terminal, not transient. */ |
| 1105 | buf_init(&out); |
| 1106 | buf_adds(&out, "{\"ok\":true,\"state\":\"failed\""); |
| 1107 | buf_adds(&out, ",\"error\":"); |
| 1108 | buf_json(&out, err[0] ? err : "poll_failed"); |
| 1109 | if (detail[0]) { buf_adds(&out, ",\"detail\":"); buf_json(&out, detail); } |
| 1110 | buf_adds(&out, ",\"logged_in\":"); |
| 1111 | buf_adds(&out, st.logged_in ? "true" : "false"); |
| 1112 | buf_adds(&out, ",\"pending\":false}\n"); |
| 1113 | emit_json(&out); |
| 1114 | return 0; |
| 1115 | } |
| 1116 | if (strcmp(state, "done") == 0 || json_bool_field(j, je, "logged_in", 0)) { |
| 1117 | /* Authorised: re-read the node state from the files so the answer |
| 1118 | * is what this machine actually holds, not what the CLI claims. */ |
| 1119 | status_t fresh; |
| 1120 | collect_status(&fresh); |
| 1121 | buf_init(&out); |
| 1122 | emit_status_json(&out, &fresh, |
| 1123 | "{\"ok\":true,\"state\":\"done\""); |
| 1124 | emit_json(&out); |
| 1125 | return 0; |
| 1126 | } |
| 1127 | { |
| 1128 | int interval = (int)json_num_field(j, je, "interval"); |
| 1129 | if (interval < 1) interval = 5; |
| 1130 | buf_free(&in); |
| 1131 | buf_init(&out); |
| 1132 | buf_addf(&out, "{\"ok\":true,\"state\":\"pending\",\"interval\":%d," |
| 1133 | "\"logged_in\":false,\"pending\":true}\n", interval); |
| 1134 | emit_json(&out); |
| 1135 | return 0; |
| 1136 | } |
| 1137 | } |
| 1138 | } |
| 1139 | |
| 1140 | static int action_cancel(void) |
| 1141 | { |
| 1142 | status_t st; |
| 1143 | buf_t in; |
| 1144 | buf_t out; |
| 1145 | |
| 1146 | collect_status(&st); |
| 1147 | if (!st.cli_present) { |
| 1148 | /* Nothing to abort and no CLI to tell: drop the marker ourselves so |
| 1149 | * the UI spinner stops on a node without SCORPIOX CODE. */ |
| 1150 | char pp[PATH_SZ]; |
| 1151 | pending_path(pp, sizeof(pp)); |
| 1152 | if (file_exists(pp)) remove(pp); |
| 1153 | buf_init(&out); |
| 1154 | buf_adds(&out, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false," |
| 1155 | "\"cli_present\":false}\n"); |
| 1156 | emit_json(&out); |
| 1157 | return 0; |
| 1158 | } |
| 1159 | |
| 1160 | buf_init(&in); |
| 1161 | { |
| 1162 | int rc = run_capture(login_bin(), "--cancel", &in); |
| 1163 | if (rc < 0) { |
| 1164 | buf_free(&in); |
| 1165 | emit_error(200, "OK", "cli_unavailable", |
| 1166 | "scorpiox-opencode-login is not on this node"); |
| 1167 | return 0; |
| 1168 | } |
| 1169 | { |
| 1170 | const char *j = last_json_line(&in); |
| 1171 | int ok = 1; |
| 1172 | if (j) { |
| 1173 | const char *je = j + strlen(j); |
| 1174 | ok = json_bool_field(j, je, "ok", 1); |
| 1175 | } |
| 1176 | buf_free(&in); |
| 1177 | if (!ok) { |
| 1178 | emit_error(200, "OK", "cancel_failed", "login CLI rejected the cancel"); |
| 1179 | return 0; |
| 1180 | } |
| 1181 | /* The CLI removes the marker; re-collect to report the truth. */ |
| 1182 | { |
| 1183 | status_t after; |
| 1184 | collect_status(&after); |
| 1185 | buf_init(&out); |
| 1186 | emit_status_json(&out, &after, |
| 1187 | "{\"ok\":true,\"state\":\"cancelled\""); |
| 1188 | emit_json(&out); |
| 1189 | } |
| 1190 | } |
| 1191 | } |
| 1192 | return 0; |
| 1193 | } |
| 1194 | |
| 1195 | /* Re-read and re-verify the stored token through the node's own token CLI. |
| 1196 | * OpenCode tokens are long-lived; there is no refresh grant on this node, so |
| 1197 | * "refresh" means "ask the CLI for a live token right now and report the new |
| 1198 | * expiry". The token value is read into a throwaway buffer and discarded. */ |
| 1199 | static int action_refresh(void) |
| 1200 | { |
| 1201 | status_t st; |
| 1202 | buf_t in; |
| 1203 | buf_t out; |
| 1204 | const char *j; |
| 1205 | |
| 1206 | collect_status(&st); |
| 1207 | if (!st.token_bin_present) { |
| 1208 | emit_error(200, "OK", "refresh_unavailable", |
| 1209 | "scorpiox-opencode-fetchtoken is not on this node"); |
| 1210 | return 0; |
| 1211 | } |
| 1212 | if (!st.logged_in) { |
| 1213 | emit_error(200, "OK", "not_logged_in", "start a device login first"); |
| 1214 | return 0; |
| 1215 | } |
| 1216 | |
| 1217 | buf_init(&in); |
| 1218 | { |
| 1219 | int rc = run_capture(token_bin(), "-local", &in); |
| 1220 | if (rc <= 0) { |
| 1221 | buf_free(&in); |
| 1222 | emit_error(200, "OK", "refresh_failed", "token CLI could not run"); |
| 1223 | return 1; |
| 1224 | } |
| 1225 | } |
| 1226 | j = last_json_line(&in); |
| 1227 | if (!j) { |
| 1228 | buf_free(&in); |
| 1229 | emit_error(200, "OK", "refresh_failed", "token CLI produced no JSON"); |
| 1230 | return 1; |
| 1231 | } |
| 1232 | { |
| 1233 | const char *je = j + strlen(j); |
| 1234 | long long exp = normalise_expiry(json_num_field(j, je, "expires_at")); |
| 1235 | char org[ORG_SZ] = {0}; |
| 1236 | int has_tok = json_str_present(j, je, "access_token"); |
| 1237 | json_str_field(j, je, "org_id", org, sizeof(org)); |
| 1238 | buf_free(&in); |
| 1239 | if (!has_tok) { |
| 1240 | emit_error(200, "OK", "refresh_failed", "token CLI returned no token"); |
| 1241 | return 1; |
| 1242 | } |
| 1243 | st.expires_at = exp > 0 ? exp : st.expires_at; |
| 1244 | st.expired = (st.expires_at > 0 && st.expires_at < (long long)time(NULL)); |
| 1245 | if (org[0] && !st.org[0]) { |
| 1246 | snprintf(st.org, sizeof(st.org), "%s", org); |
| 1247 | snprintf(st.account, sizeof(st.account), "%s", org); |
| 1248 | } |
| 1249 | buf_init(&out); |
| 1250 | emit_status_json(&out, &st, "{\"ok\":true,\"refreshed\":true"); |
| 1251 | emit_json(&out); |
| 1252 | return 0; |
| 1253 | } |
| 1254 | } |
| 1255 | |
| 1256 | /* ------------------------------------------------------------------ */ |
| 1257 | /* HTML UI */ |
| 1258 | /* ------------------------------------------------------------------ */ |
| 1259 | |
| 1260 | static void serve_html(void) |
| 1261 | { |
| 1262 | const char *qs = getenv("QUERY_STRING"); |
| 1263 | int embed = (qs && (strstr(qs, "embed=1") || strstr(qs, "embed=true"))); |
| 1264 | const char *s; |
| 1265 | |
| 1266 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 1267 | "Cache-Control: no-store\r\n" |
| 1268 | "X-Content-Type-Options: nosniff\r\n" |
| 1269 | "X-Frame-Options: SAMEORIGIN\r\n" |
| 1270 | "Referrer-Policy: same-origin\r\n\r\n", stdout); |
| 1271 | |
| 1272 | /* UI_HTML carries two control-byte placeholders: \001 where the bot theme |
| 1273 | * tokens + prepaint script belong, \002 where the theme handoff script |
| 1274 | * belongs. Splitting on them keeps the page readable in src/ui.html and |
| 1275 | * the theme in one vendored header that can never drift from the bot. */ |
| 1276 | for (s = UI_HTML; *s; ) { |
| 1277 | unsigned char c = (unsigned char)*s; |
| 1278 | if (c == 0x01) { |
| 1279 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout); |
| 1280 | s++; |
| 1281 | } else if (c == 0x02) { |
| 1282 | fputs(SX_BOT_THEME_HANDOFF, stdout); |
| 1283 | s++; |
| 1284 | } else { |
| 1285 | fputc((char)c, stdout); |
| 1286 | s++; |
| 1287 | } |
| 1288 | } |
| 1289 | (void)embed; /* the page reads ?embed=1 itself, before first paint */ |
| 1290 | } |
| 1291 | |
| 1292 | /* ------------------------------------------------------------------ */ |
| 1293 | /* Entry point */ |
| 1294 | /* ------------------------------------------------------------------ */ |
| 1295 | |
| 1296 | int main(int argc, char **argv) |
| 1297 | { |
| 1298 | const char *qs; |
| 1299 | char action[64] = {0}; |
| 1300 | |
| 1301 | /* 1. Discovery metadata. Must stay unauthenticated. */ |
| 1302 | if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { |
| 1303 | puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); |
| 1304 | return 0; |
| 1305 | } |
| 1306 | if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { |
| 1307 | puts(PLUGIN_ID " " PLUGIN_VER); |
| 1308 | return 0; |
| 1309 | } |
| 1310 | |
| 1311 | require_node_auth(); |
| 1312 | |
| 1313 | qs = getenv("QUERY_STRING"); |
| 1314 | if (!qs) qs = ""; |
| 1315 | |
| 1316 | /* 2. JSON API mode. `format=json` alone means "status", which is what a |
| 1317 | * dashboard polls. */ |
| 1318 | if (query_has(qs, "action") || query_has(qs, "format")) { |
| 1319 | char fmt[32] = {0}; |
| 1320 | |
| 1321 | get_query_val(qs, "action", action, sizeof(action)); |
| 1322 | get_query_val(qs, "format", fmt, sizeof(fmt)); |
| 1323 | |
| 1324 | if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status"); |
| 1325 | |
| 1326 | if (strcmp(action, "status") == 0 || !action[0]) return action_status(); |
| 1327 | if (strcmp(action, "start") == 0) return action_start(); |
| 1328 | if (strcmp(action, "poll") == 0) return action_poll(); |
| 1329 | if (strcmp(action, "cancel") == 0) return action_cancel(); |
| 1330 | if (strcmp(action, "refresh") == 0) return action_refresh(); |
| 1331 | |
| 1332 | emit_error(400, "Bad Request", "unknown_action", |
| 1333 | "expected status, start, poll, cancel or refresh"); |
| 1334 | return 1; |
| 1335 | } |
| 1336 | |
| 1337 | /* 3. HTML UI */ |
| 1338 | serve_html(); |
| 1339 | return 0; |
| 1340 | } |