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