scorpiox-bot-plugin-claudecode-login
←plugin_claudecode_login.cc
1632 lines · 51 KBHEADBlameDownload
1/*
2 * plugin_claudecode_login - SCORPIOX BOT open-source Claude Code OAuth PKCE
3 * login and session 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 and no OAuth client secret here): a Claude
11 * Code OAuth PKCE code exchange is an HTTPS POST that carries a client
12 * identity. A public clean-room repository must never carry such a secret, so
13 * this plugin does not speak TLS at all. It drives the node's own SCORPIOX CODE
14 * login CLI, exactly the way the machine-mode contract intends
15 * (--status / --start / --finish / --cancel, one JSON line per call), and it
16 * reads only the credential files that CLI writes:
17 *
18 * ~/.claude/.credentials.json (claudeAiOauth block)
19 * ~/.claude/accounts/<name>.json (named accounts)
20 * ~/.claude/.login-pending/claudecode-<name>.json (pending PKCE flow)
21 * ~/.claude/scorpiox-env/claude_code.txt (PROVIDER/MODEL profile)
22 *
23 * Every path and both binaries are overridable for deterministic offline tests:
24 *
25 * CLAUDE_CREDS_PATH credentials file (also anchors the sibling paths)
26 * CLAUDE_ACCOUNTS_DIR directory holding <name>.json account files
27 * CLAUDE_PENDING_DIR directory holding the pending flow files
28 * CLAUDE_ENV_DIR profile directory (claude_code.txt)
29 * CLAUDE_LOGIN_BIN login CLI (default scorpiox-claudecode-login)
30 * CLAUDE_REFRESH_BIN refresh CLI (default scorpiox-claudecode-refreshtoken)
31 *
32 * NO TOKEN IS EVER PRINTED, LOGGED OR RETURNED. Every response reports token
33 * presence and expiry only. The refresh action discards the payload its CLI
34 * prints and reports only success/failure plus the new expiry.
35 *
36 * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
37 * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
38 * scorpiox-server on the node.
39 *
40 * MIT License. Copyright (c) 2026 SCORPIOX INC.
41 */
42
43/* Must come before every include on Windows: MinGW defaults to 0x502
44 * (Server 2003), which hides the Win7+ APIs and the path helpers. */
45#if defined(_WIN32) && !defined(_WIN32_WINNT)
46# define _WIN32_WINNT 0x0601
47#endif
48
49#if !defined(_WIN32)
50# define _POSIX_C_SOURCE 200809L
51# define _DEFAULT_SOURCE 1
52# if defined(__APPLE__)
53# define _DARWIN_C_SOURCE 1
54# endif
55#endif
56
57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
60#include <ctype.h>
61#include <errno.h>
62#include <time.h>
63#include <stdarg.h>
64
65#if defined(_WIN32)
66# define WIN32_LEAN_AND_MEAN
67# include <windows.h>
68# include <direct.h>
69# include <io.h>
70#else
71# include <unistd.h>
72# include <sys/stat.h>
73# include <sys/types.h>
74# include <dirent.h>
75#endif
76
77#include "bot_theme_plugin.h"
78#include "ui_html.h"
79
80#define PLUGIN_SLUG "claudecode-login"
81#define PLUGIN_ID "plugin_claudecode_login"
82#define PLUGIN_VER "1.0.1"
83#define PLUGIN_NAME "claude"
84#define PLUGIN_DESC "Claude login"
85
86#define PATH_SZ 1024
87#define NAME_SZ 96
88#define CODE_MAX 2048
89#define CMD_SZ 4096
90#define OUT_MAX (256 * 1024)
91#define FIELD_SZ 512
92#define MAX_ACCOUNTS 64
93
94#define DEFAULT_LOGIN_BIN "scorpiox-claudecode-login"
95#define DEFAULT_REFRESH_BIN "scorpiox-claudecode-refreshtoken"
96
97#if defined(_WIN32)
98# define PATH_SEP '\\'
99#else
100# define PATH_SEP '/'
101#endif
102
103/* ------------------------------------------------------------------ */
104/* Growable byte buffer */
105/* ------------------------------------------------------------------ */
106
107typedef struct {
108 char *p;
109 size_t n;
110 size_t cap;
111} buf_t;
112
113static void buf_init(buf_t *b)
114{
115 b->p = NULL;
116 b->n = 0;
117 b->cap = 0;
118}
119
120static int buf_need(buf_t *b, size_t extra)
121{
122 size_t want = b->n + extra + 1;
123 char *np;
124
125 if (want <= b->cap) return 1;
126 if (b->cap == 0) b->cap = 1024;
127 while (b->cap < want) {
128 if (b->cap > (size_t)32 * 1024 * 1024) return 0;
129 b->cap *= 2;
130 }
131 np = (char *)realloc(b->p, b->cap);
132 if (!np) return 0;
133 b->p = np;
134 return 1;
135}
136
137static int buf_add(buf_t *b, const char *s, size_t n)
138{
139 if (!buf_need(b, n)) return 0;
140 memcpy(b->p + b->n, s, n);
141 b->n += n;
142 b->p[b->n] = '\0';
143 return 1;
144}
145
146static int buf_adds(buf_t *b, const char *s)
147{
148 return s ? buf_add(b, s, strlen(s)) : 1;
149}
150
151static int buf_addc(buf_t *b, char c)
152{
153 return buf_add(b, &c, 1);
154}
155
156static const char *buf_str(buf_t *b)
157{
158 if (!b->p) return "";
159 return b->p;
160}
161
162static void buf_free(buf_t *b)
163{
164 free(b->p);
165 b->p = NULL;
166 b->n = 0;
167 b->cap = 0;
168}
169
170static int buf_addf(buf_t *b, const char *fmt, ...)
171{
172 char tmp[2048];
173 int n;
174 va_list ap;
175
176 va_start(ap, fmt);
177 n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
178 va_end(ap);
179 if (n < 0) return 0;
180 if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n);
181
182 {
183 char *big = (char *)malloc((size_t)n + 1);
184 int ok;
185 if (!big) return 0;
186 va_start(ap, fmt);
187 vsnprintf(big, (size_t)n + 1, fmt, ap);
188 va_end(ap);
189 ok = buf_add(b, big, (size_t)n);
190 free(big);
191 return ok;
192 }
193}
194
195/* JSON string escape into a buffer (never emits a bare control byte). */
196static int buf_json(buf_t *b, const char *s)
197{
198 const unsigned char *p = (const unsigned char *)(s ? s : "");
199 if (!buf_addc(b, '"')) return 0;
200 for (; *p; p++) {
201 switch (*p) {
202 case '"': if (!buf_adds(b, "\\\"")) return 0; break;
203 case '\\': if (!buf_adds(b, "\\\\")) return 0; break;
204 case '\n': if (!buf_adds(b, "\\n")) return 0; break;
205 case '\r': if (!buf_adds(b, "\\r")) return 0; break;
206 case '\t': if (!buf_adds(b, "\\t")) return 0; break;
207 default:
208 if (*p < 0x20) { if (!buf_addf(b, "\\u%04x", *p)) return 0; }
209 else if (!buf_addc(b, (char)*p)) return 0;
210 }
211 }
212 return buf_addc(b, '"');
213}
214
215/* ------------------------------------------------------------------ */
216/* Query string */
217/* ------------------------------------------------------------------ */
218
219static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
220{
221 size_t klen;
222 const char *p;
223
224 if (!out || outsz == 0) return 0;
225 out[0] = '\0';
226 if (!qs || !key) return 0;
227 klen = strlen(key);
228 p = qs;
229 while (p && *p) {
230 if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
231 size_t i = 0;
232 p += klen + 1;
233 while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++;
234 out[i] = '\0';
235 return 1;
236 }
237 p = strchr(p, '&');
238 if (!p) break;
239 p++;
240 }
241 return 0;
242}
243
244static int query_has(const char *qs, const char *key)
245{
246 size_t klen;
247 const char *p;
248
249 if (!qs || !key) return 0;
250 klen = strlen(key);
251 p = qs;
252 while (p && *p) {
253 if (strncmp(p, key, klen) == 0 &&
254 (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&'))
255 return 1;
256 p = strchr(p, '&');
257 if (!p) break;
258 p++;
259 }
260 return 0;
261}
262
263/* Percent-decode in place (an authorization code arrives from a paste box and
264 * may have been encoded by the browser or the hub proxy). */
265static void url_decode(char *s)
266{
267 char *w;
268 char *r;
269
270 if (!s) return;
271 w = s;
272 r = s;
273 while (*r) {
274 if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) {
275 int hi = isdigit((unsigned char)r[1]) ? r[1] - '0'
276 : tolower((unsigned char)r[1]) - 'a' + 10;
277 int lo = isdigit((unsigned char)r[2]) ? r[2] - '0'
278 : tolower((unsigned char)r[2]) - 'a' + 10;
279 *w++ = (char)((hi << 4) | lo);
280 r += 3;
281 } else if (*r == '+') {
282 *w++ = ' ';
283 r++;
284 } else {
285 *w++ = *r++;
286 }
287 }
288 *w = '\0';
289}
290
291/* ------------------------------------------------------------------ */
292/* Node auth (X-Bot-Password / Bearer / ?pwd=) */
293/* ------------------------------------------------------------------ */
294
295static void require_node_auth(void)
296{
297 const char *np = getenv("BOT_PASSWORD");
298 const char *xp;
299 const char *auth;
300 char qpwd[256] = {0};
301
302 if (!np || !*np) return;
303
304 xp = getenv("HTTP_X_BOT_PASSWORD");
305 if (xp && strcmp(xp, np) == 0) return;
306
307 auth = getenv("HTTP_AUTHORIZATION");
308 if (auth) {
309 while (*auth == ' ') auth++;
310 if (strncasecmp(auth, "Bearer ", 7) == 0) {
311 auth += 7;
312 while (*auth == ' ') auth++;
313 if (strcmp(auth, np) == 0) return;
314 }
315 }
316
317 if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) &&
318 strcmp(qpwd, np) == 0)
319 return;
320
321 fputs("Status: 401 Unauthorized\r\n"
322 "Content-Type: application/json; charset=utf-8\r\n"
323 "Cache-Control: no-store\r\n\r\n"
324 "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
325 exit(0);
326}
327
328/* ------------------------------------------------------------------ */
329/* Paths */
330/* ------------------------------------------------------------------ */
331
332static const char *home_dir(void)
333{
334#if defined(_WIN32)
335 static char home[512];
336 DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home));
337 if (n > 0 && n < sizeof(home)) return home;
338 home[0] = '\0';
339 if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) {
340 char tmp[512];
341 if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) {
342 strncat(home, tmp, sizeof(home) - strlen(home) - 1);
343 return home;
344 }
345 }
346 return NULL;
347#else
348 const char *h = getenv("HOME");
349 return (h && *h) ? h : NULL;
350#endif
351}
352
353/* Copy the directory part of a path (including the trailing separator). */
354static void dir_of(const char *path, char *out, size_t n)
355{
356 char base[PATH_SZ];
357 char *slash;
358
359 if (!path) { if (n) out[0] = '\0'; return; }
360 snprintf(base, sizeof(base), "%s", path);
361 slash = strrchr(base, PATH_SEP);
362#if defined(_WIN32)
363 if (!slash) slash = strrchr(base, '/');
364#endif
365 if (slash) *(slash + 1) = '\0';
366 else base[0] = '\0';
367 snprintf(out, n, "%s", base);
368}
369
370/* A relocated credentials file implies the whole .claude tree is relocated:
371 * the same CLI writes all of these into one directory. Reading one from the
372 * override and the rest from $HOME reports an empty state for a live session. */
373static void claude_dir(char *out, size_t n)
374{
375 const char *env = getenv("CLAUDE_CREDS_PATH");
376 const char *home = home_dir();
377
378 if (env && *env) {
379 dir_of(env, out, n);
380 if (out[0]) return;
381 }
382 if (home && *home) { snprintf(out, n, "%s%c.claude%c", home, PATH_SEP, PATH_SEP); return; }
383 snprintf(out, n, ".claude%c", PATH_SEP);
384}
385
386static void creds_path(char *out, size_t n)
387{
388 const char *env = getenv("CLAUDE_CREDS_PATH");
389
390 if (env && *env) { snprintf(out, n, "%s", env); return; }
391 {
392 char d[PATH_SZ];
393 claude_dir(d, sizeof(d));
394 snprintf(out, n, "%s.credentials.json", d);
395 }
396}
397
398static void accounts_dir(char *out, size_t n)
399{
400 const char *env = getenv("CLAUDE_ACCOUNTS_DIR");
401
402 if (env && *env) { snprintf(out, n, "%s", env); return; }
403 {
404 char d[PATH_SZ];
405 claude_dir(d, sizeof(d));
406 snprintf(out, n, "%saccounts", d);
407 }
408}
409
410static void pending_dir(char *out, size_t n)
411{
412 const char *env = getenv("CLAUDE_PENDING_DIR");
413
414 if (env && *env) { snprintf(out, n, "%s", env); return; }
415 {
416 char d[PATH_SZ];
417 claude_dir(d, sizeof(d));
418 snprintf(out, n, "%s.login-pending", d);
419 }
420}
421
422static void env_dir(char *out, size_t n)
423{
424 const char *env = getenv("CLAUDE_ENV_DIR");
425
426 if (env && *env) { snprintf(out, n, "%s", env); return; }
427 {
428 char d[PATH_SZ];
429 claude_dir(d, sizeof(d));
430 snprintf(out, n, "%s%cscorpiox-env", d, PATH_SEP);
431 }
432}
433
434static void pending_path(const char *name, char *out, size_t n)
435{
436 char d[PATH_SZ];
437 pending_dir(d, sizeof(d));
438 snprintf(out, n, "%s%cclaudecode-%s.json", d, PATH_SEP, (name && *name) ? name : "default");
439}
440
441static void profile_path(char *out, size_t n)
442{
443 char d[PATH_SZ];
444 env_dir(d, sizeof(d));
445 snprintf(out, n, "%s%cclaude_code.txt", d, PATH_SEP);
446}
447
448static void account_path(const char *name, char *out, size_t n)
449{
450 char d[PATH_SZ];
451 accounts_dir(d, sizeof(d));
452 snprintf(out, n, "%s%c%s.json", d, PATH_SEP, name);
453}
454
455static const char *login_bin(void)
456{
457 const char *e = getenv("CLAUDE_LOGIN_BIN");
458 return (e && *e) ? e : DEFAULT_LOGIN_BIN;
459}
460
461static const char *refresh_bin(void)
462{
463 const char *e = getenv("CLAUDE_REFRESH_BIN");
464 return (e && *e) ? e : DEFAULT_REFRESH_BIN;
465}
466
467static int file_exists(const char *p)
468{
469#if defined(_WIN32)
470 DWORD a = GetFileAttributesA(p);
471 return p && a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY);
472#else
473 struct stat st;
474 return p && stat(p, &st) == 0 && S_ISREG(st.st_mode);
475#endif
476}
477
478/* Read a whole file. Returns a malloc'd NUL-terminated buffer or NULL. */
479static char *read_file(const char *path)
480{
481 FILE *f;
482 long sz;
483 char *buf;
484
485 if (!path || !*path) return NULL;
486 f = fopen(path, "rb");
487 if (!f) return NULL;
488 if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
489 sz = ftell(f);
490 if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; }
491 if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
492 buf = (char *)malloc((size_t)sz + 1);
493 if (!buf) { fclose(f); return NULL; }
494 if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
495 free(buf);
496 fclose(f);
497 return NULL;
498 }
499 buf[sz] = '\0';
500 fclose(f);
501 return buf;
502}
503
504/* Trim trailing CR/LF/space in place. */
505static void trim_tail(char *s)
506{
507 size_t n;
508
509 if (!s) return;
510 n = strlen(s);
511 while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' ||
512 s[n - 1] == ' ' || s[n - 1] == '\t'))
513 s[--n] = '\0';
514}
515
516/* Account names are used verbatim in a file name, so they are restricted to a
517 * shell- and path-safe alphabet. */
518static int name_valid(const char *n)
519{
520 const char *p;
521
522 if (!n || !*n || strlen(n) > 64) return 0;
523 if (n[0] == '.') return 0;
524 for (p = n; *p; p++) {
525 unsigned char c = (unsigned char)*p;
526 if (!isalnum(c) && c != '-' && c != '_' && c != '.') return 0;
527 }
528 return 1;
529}
530
531/* ------------------------------------------------------------------ */
532/* Minimal JSON field readers */
533/* ------------------------------------------------------------------ */
534
535/* Copy a JSON string value that starts at *pp (pointing at the opening quote)
536 * and advance *pp past the closing quote. */
537static int json_read_string_at(const char **pp, char *out, size_t outsz)
538{
539 const char *p = *pp;
540 size_t i = 0;
541
542 if (!p || *p != '"') return 0;
543 p++;
544 while (*p && *p != '"') {
545 char c = *p;
546 if (c == '\\' && p[1]) {
547 p++;
548 switch (*p) {
549 case 'n': c = '\n'; break;
550 case 'r': c = '\r'; break;
551 case 't': c = '\t'; break;
552 case 'b': c = '\b'; break;
553 case 'f': c = '\f'; break;
554 case 'u': {
555 unsigned int v = 0;
556 int k;
557 p++;
558 for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++)
559 v = v * 16 + (unsigned int)(isdigit((unsigned char)*p)
560 ? *p - '0'
561 : tolower((unsigned char)*p) - 'a' + 10);
562 if (i + 1 < outsz) out[i++] = (char)(v & 0xff);
563 continue;
564 }
565 default: c = *p; break;
566 }
567 p++;
568 } else {
569 p++;
570 }
571 if (i + 1 < outsz) out[i++] = c;
572 }
573 if (*p == '"') p++;
574 if (outsz) out[i < outsz ? i : outsz - 1] = '\0';
575 *pp = p;
576 return 1;
577}
578
579/* Find "key":<value> among the TOP-LEVEL keys of the slice [obj, end).
580 * A nested object is skipped as a whole.
581 *
582 * A caller almost always hands us a pointer at the opening '{'; that brace is
583 * skipped inside the reader so no call site needs a "+1" that is easy to
584 * forget and completely silent when it is missing. */
585static const char *json_find_key(const char *obj, const char *end, const char *key)
586{
587 size_t klen;
588 const char *p;
589 int depth = 0;
590
591 if (!obj || !end || !key) return NULL;
592 klen = strlen(key);
593 p = obj;
594 while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++;
595 if (p < end && *p == '{') p++;
596
597 while (p && p < end) {
598 if (*p == '"') {
599 char name[128];
600 json_read_string_at(&p, name, sizeof(name));
601 if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) {
602 const char *q = p;
603 while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
604 if (q < end && *q == ':') {
605 q++;
606 while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++;
607 return (q < end) ? q : NULL;
608 }
609 }
610 continue;
611 }
612 if (*p == '{' || *p == '[') depth++;
613 else if (*p == '}' || *p == ']') depth--;
614 p++;
615 }
616 return NULL;
617}
618
619/* Returns 0 and leaves *out untouched when the key is absent or null. That
620 * matters: several callers pass a field of a longer-lived struct, and clearing
621 * it on a miss silently erases a value that was already correct. */
622static int json_str_field(const char *obj, const char *end, const char *key,
623 char *out, size_t outsz)
624{
625 const char *v;
626
627 if (!out || outsz == 0) return 0;
628 v = json_find_key(obj, end, key);
629 if (!v || *v == 'n') return 0;
630 if (*v == '"') return json_read_string_at(&v, out, outsz);
631 {
632 size_t i = 0;
633 out[0] = '\0';
634 while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++;
635 out[i] = '\0';
636 trim_tail(out);
637 return out[0] ? 1 : 0;
638 }
639}
640
641static int json_bool_field(const char *obj, const char *end, const char *key, int dflt)
642{
643 const char *v = json_find_key(obj, end, key);
644
645 if (!v) return dflt;
646 if (strncmp(v, "true", 4) == 0) return 1;
647 if (strncmp(v, "false", 5) == 0) return 0;
648 if (*v == '"') {
649 if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1;
650 return 0;
651 }
652 if (*v == '1') return 1;
653 return 0;
654}
655
656static long long json_num_field(const char *obj, const char *end, const char *key)
657{
658 const char *v = json_find_key(obj, end, key);
659
660 if (!v) return 0;
661 if (*v == '"') v++;
662 return atoll(v);
663}
664
665/* ------------------------------------------------------------------ */
666/* Child processes */
667/* ------------------------------------------------------------------ */
668
669/* Quote one argv element for the shell popen() uses. POSIX: single quotes with
670 * the standard close-escape-reopen trick. Windows: double quotes, which is
671 * what cmd.exe accepts. */
672static void shell_quote_into(const char *in, char *out, size_t outsz)
673{
674 size_t o = 0;
675 const char *p;
676
677 if (outsz < 3) { if (outsz) out[0] = '\0'; return; }
678#if defined(_WIN32)
679 out[o++] = '"';
680 for (p = in; p && *p; p++) {
681 if (*p == '"') {
682 if (o + 3 >= outsz) break;
683 out[o++] = '\\';
684 out[o++] = '"';
685 } else {
686 if (o + 2 >= outsz) break;
687 out[o++] = *p;
688 }
689 }
690 out[o++] = '"';
691 out[o] = '\0';
692#else
693 out[o++] = '\'';
694 for (p = in; p && *p; p++) {
695 if (*p == '\'') {
696 if (o + 5 >= outsz) break;
697 memcpy(out + o, "'\\''", 4);
698 o += 4;
699 } else {
700 if (o + 2 >= outsz) break;
701 out[o++] = *p;
702 }
703 }
704 out[o++] = '\'';
705 out[o] = '\0';
706#endif
707}
708
709/* Is <bin> resolvable on this node? POSIX answers through popen's own 127
710 * ("command not found"). cmd.exe returns 1 for a missing program, which is
711 * indistinguishable from the program's own failure - so on Windows the path is
712 * resolved BEFORE popen with SearchPathA. Without this, a Windows node with no
713 * SCORPIOX CODE reported cli_present:true and "start failed" instead of
714 * cli_unavailable (measured on a real Windows box). */
715static int bin_available(const char *bin)
716{
717 if (!bin || !*bin) return 0;
718#if defined(_WIN32)
719 {
720 char full[MAX_PATH];
721 DWORD n;
722 /* An explicit path is checked directly; a bare name is searched on PATH. */
723 if (strchr(bin, '\\') || strchr(bin, '/') || strchr(bin, ':'))
724 return file_exists(bin);
725 n = SearchPathA(NULL, bin, ".exe", (DWORD)sizeof(full), full, NULL);
726 return n > 0 && n < (DWORD)sizeof(full);
727 }
728#else
729 return 1; /* decided by run_capture's own 127 check */
730#endif
731}
732
733/* Run `<bin> <args>` and capture stdout.
734 * Returns 1 when the process ran,
735 * 0 when popen() itself failed,
736 * -1 when the binary is not on this node ("command not found").
737 *
738 * pclose() hands back a WAIT STATUS, not an exit code: a missing command
739 * arrives as 32512 (127 << 8). Treating that as the tool's own failure would
740 * report "refresh failed" for a node that simply has no SCORPIOX CODE. */
741static int run_capture(const char *bin, const char *args, buf_t *out)
742{
743 char cmd[CMD_SZ];
744 char qbin[FIELD_SZ];
745 FILE *f;
746 char line[2048];
747 size_t total = 0;
748 int rc;
749
750 if (!bin || !*bin) return 0;
751 if (!bin_available(bin)) return -1;
752 shell_quote_into(bin, qbin, sizeof(qbin));
753#if defined(_WIN32)
754 if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>NUL", qbin, args);
755 else snprintf(cmd, sizeof(cmd), "%s 2>NUL", qbin);
756#else
757 if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args);
758 else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin);
759#endif
760
761 f = popen(cmd, "r");
762 if (!f) return 0;
763 while (fgets(line, sizeof(line), f)) {
764 total += strlen(line);
765 if (total > OUT_MAX) break;
766 buf_adds(out, line);
767 }
768 rc = pclose(f);
769
770 if (out->p) {
771 size_t n = out->n;
772 while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0';
773 out->n = n;
774 }
775 if (rc != -1 && ((rc >> 8) & 0xff) == 127) return -1;
776 return 1;
777}
778
779/* The CLIs print human progress before the final JSON line, so take the LAST
780 * line that starts with '{'. */
781static const char *last_json_line(buf_t *b)
782{
783 size_t i;
784 const char *last = NULL;
785
786 if (!b || !b->p) return NULL;
787 for (i = 0; i < b->n; i++) {
788 int at_line_start = (i == 0) || b->p[i - 1] == '\n';
789 if (at_line_start && b->p[i] == '{') last = b->p + i;
790 }
791 return last;
792}
793
794/* ------------------------------------------------------------------ */
795/* Status assembly */
796/* ------------------------------------------------------------------ */
797
798/* expiresAt is milliseconds in the real file, but a hand-written fixture may
799 * carry seconds. Detect by magnitude rather than trusting either form. */
800static long long to_sec(long long v)
801{
802 return (v > 100000000000LL) ? (v / 1000) : v;
803}
804
805typedef struct {
806 char name[NAME_SZ];
807 int present;
808 int logged_in;
809 int has_refresh;
810 int expired;
811 long long expires_at; /* raw value from the file (milliseconds) */
812 long long expires_in_sec; /* negative when expired, 0 when unknown */
813} account_t;
814
815typedef struct {
816 int logged_in;
817 int has_refresh;
818 int pending;
819 int expired;
820 int cli_present;
821 int profile_exists;
822 char account[NAME_SZ];
823 char path[PATH_SZ];
824 char profile[NAME_SZ];
825 char profile_file[PATH_SZ];
826 char subscription[64];
827 char scopes[256];
828 char cli_error[FIELD_SZ];
829 long long expires_at; /* milliseconds since epoch, as stored */
830 long long expires_in_sec; /* seconds; long long, not int: a 32-bit int
831 * overflows for any expiry past 2038 and turns
832 * a live session into "expired 60 years ago" */
833 account_t accounts[MAX_ACCOUNTS];
834 int account_count;
835} status_t;
836
837/* Parse a credentials file: the claudeAiOauth block carries all of it.
838 * A named account file has exactly the same shape. */
839static void scan_creds(const char *json, status_t *st, account_t *acc)
840{
841 const char *oauth;
842 const char *end;
843 char tok[8] = {0};
844 int has_access = 0;
845
846 if (!json) return;
847 oauth = strstr(json, "\"claudeAiOauth\"");
848 /* json_find_key matches TOP-LEVEL keys of the slice it is given, so the
849 * slice must start at the oauth object's opening brace, not at its key
850 * name: starting at "claudeAiOauth" makes the real opening brace look like
851 * a nested object and every field read silently returns absent (a live
852 * session reported as "not connected", while the JSON was valid). */
853 if (oauth) {
854 const char *brace = strchr(oauth, '{');
855 if (brace) oauth = brace;
856 }
857 if (!oauth) return;
858 end = json + strlen(json);
859 if (json_str_field(oauth, end, "accessToken", tok, sizeof(tok))) has_access = 1;
860 memset(tok, 0, sizeof(tok));
861 if (json_str_field(oauth, end, "refreshToken", tok, sizeof(tok))) {
862 st->has_refresh = 1;
863 if (acc) acc->has_refresh = 1;
864 }
865 st->expires_at = json_num_field(oauth, end, "expiresAt");
866 if (acc) acc->expires_at = st->expires_at;
867 json_str_field(oauth, end, "subscriptionType", st->subscription, sizeof(st->subscription));
868 if (!st->scopes[0]) {
869 /* Report the scope NAMES, not the raw JSON array: a copy from the key
870 * name through ']' carried `"scopes": ` into the string and rendered as
871 * `"scopes": ["user:profile"` in the UI. Start at '[' and keep only the
872 * quoted elements, comma-separated. */
873 const char *sc = strstr(oauth, "\"scopes\"");
874 const char *open = sc ? strchr(sc, '[') : NULL;
875 const char *close = open ? strchr(open, ']') : NULL;
876 if (open && close) {
877 size_t o = 0;
878 const char *q = open + 1;
879 while (q < close && o + 1 < sizeof(st->scopes)) {
880 if (*q == '"') {
881 const char *e;
882 q++;
883 e = strchr(q, '"');
884 if (!e || e > close) break;
885 if (o) st->scopes[o++] = ',';
886 while (q < e && o + 1 < sizeof(st->scopes)) st->scopes[o++] = *q++;
887 q = e + 1;
888 } else {
889 q++;
890 }
891 }
892 st->scopes[o] = '\0';
893 }
894 }
895 st->logged_in = st->has_refresh || has_access || st->expires_at > 0;
896 if (acc) acc->logged_in = st->logged_in;
897}
898
899/* Read the profile file written by --create-profile. */
900static void scan_profile(status_t *st)
901{
902 char *text;
903 char line[FIELD_SZ];
904
905 profile_path(st->profile_file, sizeof(st->profile_file));
906 st->profile_exists = file_exists(st->profile_file);
907 if (!st->profile_exists) return;
908 snprintf(st->profile, sizeof(st->profile), "claude_code");
909
910 text = read_file(st->profile_file);
911 if (!text) return;
912 {
913 const char *p = text;
914 while (p && *p) {
915 const char *nl = strchr(p, '\n');
916 size_t len = nl ? (size_t)(nl - p) : strlen(p);
917 if (len > 0 && len < sizeof(line)) {
918 memcpy(line, p, len);
919 line[len] = '\0';
920 trim_tail(line);
921 if (strncmp(line, "PROVIDER=", 9) == 0 && !st->profile[0])
922 snprintf(st->profile, sizeof(st->profile), "%.*s",
923 (int)sizeof(st->profile) - 1, line + 9);
924 }
925 if (!nl) break;
926 p = nl + 1;
927 }
928 }
929 free(text);
930}
931
932/* List the account files in the accounts directory and summarise each one. */
933static void scan_accounts(status_t *st, long long now_sec)
934{
935 char d[PATH_SZ];
936
937 st->account_count = 0;
938 accounts_dir(d, sizeof(d));
939
940#if defined(_WIN32)
941 {
942 char pattern[PATH_SZ];
943 WIN32_FIND_DATAA fd;
944 HANDLE h;
945 snprintf(pattern, sizeof(pattern), "%s\\*.json", d);
946 h = FindFirstFileA(pattern, &fd);
947 if (h == INVALID_HANDLE_VALUE) return;
948 do {
949 size_t ln = strlen(fd.cFileName);
950 if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
951 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
952 {
953 account_t *a = &st->accounts[st->account_count];
954 char p[PATH_SZ];
955 char *json;
956 memset(a, 0, sizeof(*a));
957 snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), fd.cFileName);
958 snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, fd.cFileName);
959 a->present = 1;
960 json = read_file(p);
961 if (json) {
962 status_t tmp;
963 memset(&tmp, 0, sizeof(tmp));
964 scan_creds(json, &tmp, a);
965 free(json);
966 }
967 if (a->expires_at > 0 && a->logged_in) {
968 a->expires_in_sec = to_sec(a->expires_at) - now_sec;
969 a->expired = a->expires_in_sec <= 0;
970 }
971 st->account_count++;
972 }
973 } while (FindNextFileA(h, &fd));
974 FindClose(h);
975 }
976#else
977 {
978 DIR *dp = opendir(d);
979 struct dirent *de;
980 if (!dp) return;
981 while ((de = readdir(dp)) != NULL) {
982 size_t ln = strlen(de->d_name);
983 account_t *a;
984 char p[PATH_SZ];
985 char *json;
986
987 if (ln <= 5 || st->account_count >= MAX_ACCOUNTS) continue;
988 if (strcmp(de->d_name + ln - 5, ".json") != 0) continue;
989 a = &st->accounts[st->account_count];
990 memset(a, 0, sizeof(*a));
991 snprintf(a->name, sizeof(a->name), "%.*s", (int)(ln - 5), de->d_name);
992 snprintf(p, sizeof(p), "%s%c%s", d, PATH_SEP, de->d_name);
993 a->present = 1;
994 json = read_file(p);
995 if (json) {
996 status_t tmp;
997 memset(&tmp, 0, sizeof(tmp));
998 scan_creds(json, &tmp, a);
999 free(json);
1000 }
1001 if (a->expires_at > 0 && a->logged_in) {
1002 a->expires_in_sec = to_sec(a->expires_at) - now_sec;
1003 a->expired = a->expires_in_sec <= 0;
1004 }
1005 st->account_count++;
1006 }
1007 closedir(dp);
1008 }
1009#endif
1010}
1011
1012/* Query the login CLI in machine mode. It is authoritative when present
1013 * (it knows about named accounts, the pending flow and profile creation);
1014 * the credential file is the fallback for a node without SCORPIOX CODE. */
1015static void scan_cli(status_t *st, const char *name)
1016{
1017 buf_t out;
1018 const char *j;
1019 char args[NAME_SZ + 32];
1020
1021 buf_init(&out);
1022 if (name && *name) snprintf(args, sizeof(args), "--status --name %s", name);
1023 else snprintf(args, sizeof(args), "--status");
1024
1025 {
1026 int rc = run_capture(login_bin(), args, &out);
1027 if (rc <= 0) {
1028 st->cli_present = 0;
1029 snprintf(st->cli_error, sizeof(st->cli_error), "%s",
1030 rc == -1 ? "the login CLI is not on this node"
1031 : "could not start the login CLI");
1032 buf_free(&out);
1033 return;
1034 }
1035 }
1036
1037 j = last_json_line(&out);
1038 if (!j) {
1039 st->cli_present = 1;
1040 buf_free(&out);
1041 return;
1042 }
1043 st->cli_present = 1;
1044 {
1045 const char *end = j + strlen(j);
1046 /* The CLI's logged_in is derived from the same file, but it also knows
1047 * about a named account file, so trust it when it says yes. */
1048 if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1;
1049 if (json_bool_field(j, end, "has_refresh", 0)) st->has_refresh = 1;
1050 st->pending = json_bool_field(j, end, "pending", 0);
1051 {
1052 long long e = json_num_field(j, end, "expires_at");
1053 if (e > 0) st->expires_at = e;
1054 }
1055 {
1056 char acct[NAME_SZ] = {0};
1057 if (json_str_field(j, end, "account", acct, sizeof(acct)) && acct[0])
1058 snprintf(st->account, sizeof(st->account), "%s", acct);
1059 }
1060 }
1061 buf_free(&out);
1062}
1063
1064static void collect_status(status_t *st, const char *name)
1065{
1066 char *json;
1067 long long now_sec = (long long)time(NULL);
1068
1069 memset(st, 0, sizeof(*st));
1070
1071 /* A named account lives in ~/.claude/accounts/<name>.json, which is the
1072 * same schema as the default credentials file. */
1073 if (name && *name) {
1074 char p[PATH_SZ];
1075 account_path(name, p, sizeof(p));
1076 snprintf(st->path, sizeof(st->path), "%s", p);
1077 snprintf(st->account, sizeof(st->account), "%s", name);
1078 } else {
1079 creds_path(st->path, sizeof(st->path));
1080 }
1081
1082 json = read_file(st->path);
1083 if (json) {
1084 scan_creds(json, st, NULL);
1085 free(json);
1086 }
1087
1088 scan_cli(st, name);
1089 scan_profile(st);
1090
1091 {
1092 char pp[PATH_SZ];
1093 pending_path(name, pp, sizeof(pp));
1094 if (file_exists(pp)) st->pending = 1;
1095 }
1096
1097 /* expiresAt is milliseconds since the epoch in this file format. Normalise
1098 * to seconds for the countdown; a seconds value (from a hand-written
1099 * fixture) is detected by magnitude and left alone. */
1100 if (st->expires_at > 0) {
1101 long long ms = st->expires_at;
1102 long long sec = (ms > 100000000000LL) ? (ms / 1000) : ms;
1103 st->expires_in_sec = sec - now_sec;
1104 st->expired = st->expires_in_sec <= 0;
1105 }
1106 if (!st->logged_in) {
1107 st->expired = 0;
1108 st->expires_in_sec = 0;
1109 }
1110 if (!st->account[0] && st->logged_in)
1111 snprintf(st->account, sizeof(st->account), "default");
1112 if (!st->profile[0] && st->profile_exists)
1113 snprintf(st->profile, sizeof(st->profile), "claude_code");
1114
1115 scan_accounts(st, now_sec);
1116}
1117
1118/* One status object, shared by every action so the UI always re-renders from
1119 * the same shape. */
1120static void emit_status(buf_t *b, const status_t *st)
1121{
1122 int i;
1123
1124 buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false");
1125 buf_adds(b, "\"expires_at\":");
1126 buf_addf(b, "%lld", st->expires_at);
1127 buf_addf(b, ",\"expires_at_sec\":%lld",
1128 st->expires_at > 100000000000LL ? st->expires_at / 1000 : st->expires_at);
1129 buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec);
1130 buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false");
1131 buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false");
1132 buf_adds(b, ",\"account\":");
1133 buf_json(b, st->account);
1134 buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false");
1135 buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false");
1136 buf_adds(b, ",\"credentials_path\":");
1137 buf_json(b, st->path);
1138 buf_adds(b, ",\"profile\":");
1139 buf_json(b, st->profile);
1140 buf_addf(b, ",\"profile_exists\":%s", st->profile_exists ? "true" : "false");
1141 buf_addf(b, ",\"named_accounts\":%s", st->account_count > 1 ? "true" : "false");
1142 buf_adds(b, ",\"subscription\":");
1143 buf_json(b, st->subscription);
1144 buf_adds(b, ",\"scopes\":");
1145 buf_json(b, st->scopes);
1146
1147 buf_adds(b, ",\"accounts\":[");
1148 for (i = 0; i < st->account_count; i++) {
1149 const account_t *a = &st->accounts[i];
1150 if (i) buf_addc(b, ',');
1151 buf_adds(b, "{\"name\":");
1152 buf_json(b, a->name);
1153 buf_addf(b, ",\"logged_in\":%s", a->logged_in ? "true" : "false");
1154 buf_addf(b, ",\"has_refresh\":%s", a->has_refresh ? "true" : "false");
1155 buf_addf(b, ",\"expires_in_sec\":%lld", a->expires_in_sec);
1156 buf_addf(b, ",\"expired\":%s}", a->expired ? "true" : "false");
1157 }
1158 buf_addc(b, ']');
1159}
1160
1161/* ------------------------------------------------------------------ */
1162/* Actions */
1163/* ------------------------------------------------------------------ */
1164
1165static void json_headers(void)
1166{
1167 fputs("Content-Type: application/json; charset=utf-8\r\n"
1168 "Cache-Control: no-store\r\n"
1169 "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1170}
1171
1172static void emit_error(int code, const char *status, const char *err, const char *detail)
1173{
1174 buf_t b;
1175
1176 buf_init(&b);
1177 buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n"
1178 "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n",
1179 code, status);
1180 buf_adds(&b, "{\"ok\":false,\"error\":");
1181 buf_json(&b, err);
1182 if (detail && *detail) {
1183 buf_adds(&b, ",\"detail\":");
1184 buf_json(&b, detail);
1185 }
1186 buf_adds(&b, "}\n");
1187 fputs(buf_str(&b), stdout);
1188 buf_free(&b);
1189}
1190
1191static int action_status(const char *name)
1192{
1193 status_t st;
1194 buf_t b;
1195
1196 collect_status(&st, name);
1197 buf_init(&b);
1198 buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",");
1199 emit_status(&b, &st);
1200 buf_adds(&b, ",\"flow\":\"paste_code\",\"protocol\":\"SXLOGIN-MACHINE-V1\"}\n");
1201 json_headers();
1202 fputs(buf_str(&b), stdout);
1203 buf_free(&b);
1204 return 0;
1205}
1206
1207static int action_start(const char *name, int force)
1208{
1209 buf_t out, b;
1210 const char *j;
1211 char args[NAME_SZ + 64];
1212 char auth_url[CMD_SZ] = {0};
1213 char flow[64] = {0};
1214 char hint[FIELD_SZ] = {0};
1215 long long expires_in = 0;
1216
1217 if (name && *name) {
1218 const char *nm = name;
1219 char qname[NAME_SZ * 2];
1220 shell_quote_into(nm, qname, sizeof(qname));
1221 snprintf(args, sizeof(args), "--start%s --name %s", force ? " --force" : "", qname);
1222 } else {
1223 snprintf(args, sizeof(args), "--start%s", force ? " --force" : "");
1224 }
1225
1226 buf_init(&out);
1227 {
1228 int rc = run_capture(login_bin(), args, &out);
1229 if (rc <= 0) {
1230 buf_free(&out);
1231 emit_error(200, "OK", "cli_unavailable",
1232 "the login CLI is not on this node; install SCORPIOX CODE or set CLAUDE_LOGIN_BIN");
1233 return 1;
1234 }
1235 }
1236 j = last_json_line(&out);
1237 if (!j) {
1238 emit_error(200, "OK", "start_failed", "the login CLI returned no JSON");
1239 buf_free(&out);
1240 return 1;
1241 }
1242 {
1243 const char *end = j + strlen(j);
1244 json_str_field(j, end, "auth_url", auth_url, sizeof(auth_url));
1245 json_str_field(j, end, "flow", flow, sizeof(flow));
1246 json_str_field(j, end, "hint", hint, sizeof(hint));
1247 expires_in = json_num_field(j, end, "expires_in");
1248 if (!json_bool_field(j, end, "ok", 1) || !auth_url[0]) {
1249 char detail[FIELD_SZ] = {0};
1250 json_str_field(j, end, "error", detail, sizeof(detail));
1251 buf_free(&out);
1252 emit_error(200, "OK", detail[0] ? detail : "start_failed",
1253 "the login CLI did not return an authorization URL");
1254 return 1;
1255 }
1256 }
1257 buf_free(&out);
1258
1259 buf_init(&b);
1260 buf_adds(&b, "{\"ok\":true,\"flow\":");
1261 buf_json(&b, flow[0] ? flow : "paste_code");
1262 buf_adds(&b, ",\"auth_url\":");
1263 buf_json(&b, auth_url);
1264 buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : 600);
1265 buf_adds(&b, ",\"hint\":");
1266 buf_json(&b, hint[0] ? hint
1267 : "Sign in with Claude, then paste the code shown on the callback page.");
1268 buf_adds(&b, "}\n");
1269 json_headers();
1270 fputs(buf_str(&b), stdout);
1271 buf_free(&b);
1272 return 0;
1273}
1274
1275/* Reject anything that cannot be an authorization code. The value reaches a
1276 * shell through run_capture(), so this is the second line of defence behind
1277 * shell_quote_into(). */
1278static int code_valid(const char *code)
1279{
1280 size_t n, i;
1281
1282 if (!code || !(n = strlen(code)) || n > CODE_MAX) return 0;
1283 for (i = 0; i < n; i++) {
1284 unsigned char c = (unsigned char)code[i];
1285 if (c < 0x20 || c == 0x7f || c == '\'' || c == '"' || c == '\\' || c == ';' ||
1286 c == '`' || c == '$' || c == '|' || c == '&' || c == '<' || c == '>')
1287 return 0;
1288 }
1289 return 1;
1290}
1291
1292static int action_finish(const char *raw_code, const char *name, int force)
1293{
1294 char code[CODE_MAX];
1295 char qcode[CODE_MAX + 64];
1296 char args[CODE_MAX + NAME_SZ + 128];
1297 buf_t out, b;
1298 const char *j;
1299
1300 if (!raw_code || !*raw_code) {
1301 emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=...");
1302 return 1;
1303 }
1304 snprintf(code, sizeof(code), "%s", raw_code);
1305 url_decode(code);
1306 trim_tail(code);
1307
1308 /* A user usually pastes the whole redirect address. Extract code= BEFORE
1309 * validating, so a legitimate URL is not refused for carrying state= too.
1310 * Validating first would reject every real paste, because '&' and '=' are
1311 * exactly the characters a bare code never contains. */
1312 {
1313 char *c = strstr(code, "code=");
1314 if (c) {
1315 char extracted[CODE_MAX];
1316 size_t i = 0;
1317 c += 5;
1318 while (*c && *c != '&' && *c != '#' && i + 1 < sizeof(extracted))
1319 extracted[i++] = *c++;
1320 extracted[i] = '\0';
1321 if (i > 0) {
1322 /* An embedded '&' or '#' is expected in a URL, not in a code. */
1323 if (code_valid(extracted)) snprintf(code, sizeof(code), "%s", extracted);
1324 }
1325 }
1326 }
1327 {
1328 char *hash = strchr(code, '#');
1329 if (hash) *hash = '\0';
1330 }
1331 if (!code_valid(code)) {
1332 emit_error(400, "Bad Request", "invalid_code",
1333 "the value is not an authorization code (empty, too long, or contains shell characters)");
1334 return 1;
1335 }
1336
1337 shell_quote_into(code, qcode, sizeof(qcode));
1338 {
1339 char qname[NAME_SZ * 2];
1340 const char *extra = "";
1341 if (name && *name) {
1342 shell_quote_into(name, qname, sizeof(qname));
1343 extra = qname;
1344 }
1345 if (extra[0])
1346 snprintf(args, sizeof(args), "--finish %s --name %s%s",
1347 qcode, extra, force ? " --force" : "");
1348 else
1349 snprintf(args, sizeof(args), "--finish %s%s", qcode, force ? " --force" : "");
1350 }
1351
1352 buf_init(&out);
1353 {
1354 int rc = run_capture(login_bin(), args, &out);
1355 if (rc <= 0) {
1356 buf_free(&out);
1357 emit_error(200, "OK", "cli_unavailable",
1358 "the login CLI is not on this node; install SCORPIOX CODE or set CLAUDE_LOGIN_BIN");
1359 return 1;
1360 }
1361 }
1362 j = last_json_line(&out);
1363 if (!j) {
1364 buf_free(&out);
1365 emit_error(200, "OK", "finish_failed", "the login CLI returned no JSON");
1366 return 1;
1367 }
1368 {
1369 const char *end = j + strlen(j);
1370 if (!json_bool_field(j, end, "ok", 0)) {
1371 char detail[FIELD_SZ] = {0};
1372 json_str_field(j, end, "error", detail, sizeof(detail));
1373 buf_free(&out);
1374 emit_error(200, "OK", detail[0] ? detail : "finish_failed",
1375 "Claude rejected the code, or it has already been used or has expired");
1376 return 1;
1377 }
1378 }
1379 buf_free(&out);
1380
1381 {
1382 status_t st;
1383 collect_status(&st, name);
1384 buf_init(&b);
1385 buf_adds(&b, "{\"ok\":true,\"state\":\"done\",");
1386 emit_status(&b, &st);
1387 buf_adds(&b, "}\n");
1388 json_headers();
1389 fputs(buf_str(&b), stdout);
1390 buf_free(&b);
1391 }
1392 return 0;
1393}
1394
1395static int action_cancel(const char *name)
1396{
1397 buf_t out, b;
1398 char args[NAME_SZ + 32];
1399
1400 if (name && *name) {
1401 char qname[NAME_SZ * 2];
1402 shell_quote_into(name, qname, sizeof(qname));
1403 snprintf(args, sizeof(args), "--cancel --name %s", qname);
1404 } else {
1405 snprintf(args, sizeof(args), "--cancel");
1406 }
1407
1408 buf_init(&out);
1409 run_capture(login_bin(), args, &out);
1410 buf_free(&out);
1411
1412 buf_init(&b);
1413 buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n");
1414 json_headers();
1415 fputs(buf_str(&b), stdout);
1416 buf_free(&b);
1417 return 0;
1418}
1419
1420/* Refresh: the refresh CLI performs the refresh-token grant and updates the
1421 * credentials file in place. Its stdout is human text (and may quote token
1422 * material), so the payload is read, then discarded. The new state is proven
1423 * by re-reading the file, not by the CLI's word. */
1424static int action_refresh(const char *name)
1425{
1426 buf_t out, b;
1427 char args[PATH_SZ + 96];
1428 char qpath[PATH_SZ * 2];
1429 char path[PATH_SZ];
1430 long long before;
1431 status_t st;
1432
1433 if (name && *name) account_path(name, path, sizeof(path));
1434 else creds_path(path, sizeof(path));
1435
1436 if (!file_exists(path)) {
1437 buf_init(&b);
1438 buf_adds(&b, "{\"ok\":false,\"error\":\"no_credentials\",\"detail\":");
1439 buf_json(&b, "there is no credentials file on this node; start a login first");
1440 buf_adds(&b, "}\n");
1441 json_headers();
1442 fputs(buf_str(&b), stdout);
1443 buf_free(&b);
1444 return 1;
1445 }
1446
1447 collect_status(&st, name);
1448 before = st.expires_at;
1449
1450 shell_quote_into(path, qpath, sizeof(qpath));
1451 /* action=refresh means "refresh now", so the CLI is always invoked with
1452 * --force: without it the CLI no-ops on a still-valid token and the user's
1453 * button does nothing. */
1454 snprintf(args, sizeof(args), "--credentials-file %s --force", qpath);
1455
1456 buf_init(&out);
1457 {
1458 int rc = run_capture(refresh_bin(), args, &out);
1459 if (rc <= 0) {
1460 buf_free(&out);
1461 emit_error(200, "OK", "cli_unavailable",
1462 "the refresh CLI is not on this node; install SCORPIOX CODE or set CLAUDE_REFRESH_BIN");
1463 return 1;
1464 }
1465 }
1466 buf_free(&out);
1467
1468 collect_status(&st, name);
1469 if (!st.logged_in || (before > 0 && st.expires_at <= before && !st.expired)) {
1470 buf_init(&b);
1471 buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":");
1472 buf_json(&b, "the refresh CLI did not update the credentials file; sign in again");
1473 buf_adds(&b, "}\n");
1474 json_headers();
1475 fputs(buf_str(&b), stdout);
1476 buf_free(&b);
1477 return 1;
1478 }
1479
1480 buf_init(&b);
1481 buf_adds(&b, "{\"ok\":true,\"refreshed\":true,");
1482 emit_status(&b, &st);
1483 buf_adds(&b, "}\n");
1484 json_headers();
1485 fputs(buf_str(&b), stdout);
1486 buf_free(&b);
1487 return 0;
1488}
1489
1490/* ------------------------------------------------------------------ */
1491/* HTML emission */
1492/* ------------------------------------------------------------------ */
1493
1494/* Expand the two placeholders tools/gen_ui.py leaves in UI_HTML. Keeping the
1495 * split means the palette lives in exactly one place (bot_theme_plugin.h) and
1496 * the page can never drift away from the bot's own theme. */
1497static void emit_ui(void)
1498{
1499 const char *p = UI_HTML;
1500
1501 while (*p) {
1502 if (*p == '\001') {
1503 fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout);
1504 p++;
1505 } else if (*p == '\002') {
1506 /* SX_BOT_THEME_HANDOFF and SX_BOT_THEME_TOGGLE_JS are both complete
1507 * <script>...</script> strings, so they are emitted as siblings.
1508 * Without the toggle macro the page's Theme button is inert: the
1509 * bot owns the theme, but a plugin opened in its own tab needs a
1510 * switch of its own. */
1511 fputs(SX_BOT_THEME_HANDOFF SX_BOT_THEME_TOGGLE_JS, stdout);
1512 p++;
1513 } else {
1514 putchar(*p++);
1515 }
1516 }
1517}
1518
1519/* Read a POST body field of the form "code":"..." (a long code is easier to
1520 * send in a body than in a URL). Guarded on CONTENT_LENGTH so an empty
1521 * inherited stdin can never block. */
1522static int body_field(const char *field, char *out, size_t outsz)
1523{
1524 const char *cl = getenv("CONTENT_LENGTH");
1525 long n = (cl && *cl) ? atol(cl) : 0;
1526 char *body;
1527 size_t len;
1528 int got = 0;
1529
1530 if (n <= 0 || n > (long)(256 * 1024)) return 0;
1531 body = (char *)malloc((size_t)n + 1);
1532 if (!body) return 0;
1533 len = fread(body, 1, (size_t)n, stdin);
1534 body[len] = '\0';
1535 {
1536 char *p = strstr(body, field);
1537 if (p) {
1538 p = strchr(p, ':');
1539 if (p) {
1540 size_t i = 0;
1541 p++;
1542 while (*p == ' ' || *p == '\t') p++;
1543 if (*p == '"') p++;
1544 while (*p && *p != '"' && i + 1 < outsz) out[i++] = *p++;
1545 out[i] = '\0';
1546 got = i > 0;
1547 }
1548 }
1549 }
1550 free(body);
1551 return got;
1552}
1553
1554/* ------------------------------------------------------------------ */
1555/* main */
1556/* ------------------------------------------------------------------ */
1557
1558int main(int argc, char **argv)
1559{
1560 const char *qs;
1561 char action[64] = {0};
1562 char name[NAME_SZ] = {0};
1563 char code[CODE_MAX] = {0};
1564 int force = 0;
1565
1566 /* 1. Discovery metadata. Must stay unauthenticated. */
1567 if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1568 puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}");
1569 return 0;
1570 }
1571 if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) {
1572 puts(PLUGIN_ID " " PLUGIN_VER);
1573 return 0;
1574 }
1575
1576 require_node_auth();
1577
1578 qs = getenv("QUERY_STRING");
1579 if (!qs) qs = "";
1580
1581 get_query_val(qs, "name", name, sizeof(name));
1582 if (name[0] && !name_valid(name)) {
1583 emit_error(400, "Bad Request", "bad_name", "account names use letters, digits, - _ . (max 64)");
1584 return 1;
1585 }
1586 {
1587 char f[8] = {0};
1588 if (get_query_val(qs, "force", f, sizeof(f)))
1589 force = (f[0] == '1' || f[0] == 't' || f[0] == 'T' || f[0] == 'y');
1590 }
1591
1592 /* 2. JSON API mode. `format=json` alone means "status", which is what a
1593 * dashboard polls. */
1594 if (query_has(qs, "action") || query_has(qs, "format")) {
1595 char fmt[32] = {0};
1596
1597 get_query_val(qs, "action", action, sizeof(action));
1598 get_query_val(qs, "format", fmt, sizeof(fmt));
1599 if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status");
1600
1601 if (strcmp(action, "status") == 0 || !action[0]) return action_status(name);
1602 if (strcmp(action, "start") == 0) return action_start(name, force);
1603 if (strcmp(action, "cancel") == 0) return action_cancel(name);
1604 if (strcmp(action, "refresh") == 0) return action_refresh(name);
1605 if (strcmp(action, "accounts") == 0) return action_status(name);
1606 if (strcmp(action, "finish") == 0) {
1607 if (!get_query_val(qs, "code", code, sizeof(code))) {
1608 if (!body_field("\"code\"", code, sizeof(code))) {
1609 emit_error(400, "Bad Request", "missing_code",
1610 "pass the authorization code as &code=...");
1611 return 1;
1612 }
1613 }
1614 return action_finish(code, name, force);
1615 }
1616 emit_error(404, "Not Found", "unknown_action", action);
1617 return 1;
1618 }
1619
1620 /* 3. HTML UI. UI_HTML carries two control bytes: 0x01 is the theme block
1621 * (<style> with the bot tokens) and 0x02 is the handoff script before
1622 * </body>. */
1623 fputs("Content-Type: text/html; charset=utf-8\r\n"
1624 "Cache-Control: no-store\r\n"
1625 "X-Content-Type-Options: nosniff\r\n"
1626 "Referrer-Policy: no-referrer\r\n"
1627 "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
1628 "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
1629 "base-uri 'none'; form-action 'none'; frame-ancestors *\r\n\r\n", stdout);
1630 emit_ui();
1631 return 0;
1632}