| 1 | /* |
| 2 | * plugin_antigravity_login - SCORPIOX BOT open-source Google Antigravity |
| 3 | * OAuth 2.0 PKCE login and companion-project manager for your node. |
| 4 | * |
| 5 | * A single clean-room C99 binary that serves THREE modes: |
| 6 | * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata |
| 7 | * 2. ?action=... / ?format=json -> JSON node API |
| 8 | * 3. GET (default) -> responsive HTML UI |
| 9 | * |
| 10 | * DESIGN NOTE (why there is no TLS in this binary): an OAuth 2.0 PKCE code |
| 11 | * exchange is an HTTPS POST with a client identity, and a public clean-room |
| 12 | * repository must not carry an OAuth client secret. So this plugin does not |
| 13 | * speak TLS at all. It drives the node's own login CLI, exactly the way the |
| 14 | * SCORPIOX CODE login tools are meant to be driven (see the machine-mode |
| 15 | * contract: --status / --start / --finish / --cancel, one JSON line per call), |
| 16 | * and it reads the credential and profile files that the CLI writes: |
| 17 | * |
| 18 | * ~/.config/google-accounts/antigravity_accounts.json (refresh tokens) |
| 19 | * ~/.config/google-accounts/selected_account.txt (active email) |
| 20 | * ~/.claude/scorpiox-env/antigravity.txt (project + models) |
| 21 | * ~/.claude/.login-pending/antigravity-default.json (pending flow) |
| 22 | * |
| 23 | * Every one of those paths and both CLIs can be overridden for deterministic |
| 24 | * offline testing: |
| 25 | * |
| 26 | * ANTIGRAVITY_CREDS_PATH accounts json (also used for the sibling files) |
| 27 | * ANTIGRAVITY_LOGIN_BIN the login CLI (default scorpiox-antigravity-login) |
| 28 | * ANTIGRAVITY_TOKEN_BIN the token CLI (default scorpiox-google-fetchtoken) |
| 29 | * ANTIGRAVITY_ENV_DIR the profile dir (default ~/.claude/scorpiox-env) |
| 30 | * |
| 31 | * No token is ever printed, logged or returned by this plugin: the API reports |
| 32 | * presence and expiry only, and the refresh action reports success or the |
| 33 | * failure reason from the token CLI with the payload discarded. |
| 34 | * |
| 35 | * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and |
| 36 | * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under |
| 37 | * scorpiox-server on the node. |
| 38 | * |
| 39 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 40 | */ |
| 41 | |
| 42 | /* Must come before every include on Windows: MinGW defaults to 0x502 |
| 43 | * (Server 2003), which hides the Win7+ APIs and the path helpers. */ |
| 44 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 45 | # define _WIN32_WINNT 0x0601 |
| 46 | #endif |
| 47 | |
| 48 | #if !defined(_WIN32) |
| 49 | # define _POSIX_C_SOURCE 200809L |
| 50 | # define _DEFAULT_SOURCE 1 |
| 51 | # if defined(__APPLE__) |
| 52 | # define _DARWIN_C_SOURCE 1 |
| 53 | # endif |
| 54 | #endif |
| 55 | |
| 56 | #include <stdio.h> |
| 57 | #include <stdlib.h> |
| 58 | #include <string.h> |
| 59 | #include <ctype.h> |
| 60 | #include <errno.h> |
| 61 | #include <time.h> |
| 62 | #include <stdarg.h> |
| 63 | |
| 64 | #if defined(_WIN32) |
| 65 | # define WIN32_LEAN_AND_MEAN |
| 66 | # include <windows.h> |
| 67 | # include <direct.h> |
| 68 | # include <io.h> |
| 69 | #else |
| 70 | # include <unistd.h> |
| 71 | # include <sys/stat.h> |
| 72 | # include <sys/types.h> |
| 73 | #endif |
| 74 | |
| 75 | #include "bot_theme_plugin.h" |
| 76 | #include "ui_html.h" |
| 77 | |
| 78 | #define PLUGIN_SLUG "antigravity-login" |
| 79 | #define PLUGIN_ID "plugin_antigravity_login" |
| 80 | #define PLUGIN_VER "1.0.1" |
| 81 | #define PLUGIN_NAME "google" |
| 82 | #define PLUGIN_DESC "Google login" |
| 83 | |
| 84 | #define PATH_SZ 1024 |
| 85 | #define EMAIL_SZ 256 |
| 86 | #define PROJ_SZ 256 |
| 87 | #define CODE_MAX 2048 |
| 88 | #define CMD_SZ 4096 |
| 89 | #define OUT_MAX (256 * 1024) |
| 90 | #define FIELD_SZ 512 |
| 91 | |
| 92 | #define DEFAULT_LOGIN_BIN "scorpiox-antigravity-login" |
| 93 | #define DEFAULT_TOKEN_BIN "scorpiox-google-fetchtoken" |
| 94 | |
| 95 | /* ------------------------------------------------------------------ */ |
| 96 | /* Growable byte buffer */ |
| 97 | /* ------------------------------------------------------------------ */ |
| 98 | |
| 99 | typedef struct { |
| 100 | char *p; |
| 101 | size_t n; |
| 102 | size_t cap; |
| 103 | } buf_t; |
| 104 | |
| 105 | static void buf_init(buf_t *b) |
| 106 | { |
| 107 | b->p = NULL; |
| 108 | b->n = 0; |
| 109 | b->cap = 0; |
| 110 | } |
| 111 | |
| 112 | static int buf_need(buf_t *b, size_t extra) |
| 113 | { |
| 114 | size_t want = b->n + extra + 1; |
| 115 | char *np; |
| 116 | |
| 117 | if (want <= b->cap) return 1; |
| 118 | if (b->cap == 0) b->cap = 1024; |
| 119 | while (b->cap < want) { |
| 120 | if (b->cap > (size_t)32 * 1024 * 1024) return 0; |
| 121 | b->cap *= 2; |
| 122 | } |
| 123 | np = (char *)realloc(b->p, b->cap); |
| 124 | if (!np) return 0; |
| 125 | b->p = np; |
| 126 | return 1; |
| 127 | } |
| 128 | |
| 129 | static int buf_add(buf_t *b, const char *s, size_t n) |
| 130 | { |
| 131 | if (!buf_need(b, n)) return 0; |
| 132 | memcpy(b->p + b->n, s, n); |
| 133 | b->n += n; |
| 134 | b->p[b->n] = '\0'; |
| 135 | return 1; |
| 136 | } |
| 137 | |
| 138 | static int buf_adds(buf_t *b, const char *s) |
| 139 | { |
| 140 | return s ? buf_add(b, s, strlen(s)) : 1; |
| 141 | } |
| 142 | |
| 143 | static int buf_addc(buf_t *b, char c) |
| 144 | { |
| 145 | return buf_add(b, &c, 1); |
| 146 | } |
| 147 | |
| 148 | static const char *buf_str(buf_t *b) |
| 149 | { |
| 150 | if (!b->p) return ""; |
| 151 | return b->p; |
| 152 | } |
| 153 | |
| 154 | static void buf_free(buf_t *b) |
| 155 | { |
| 156 | free(b->p); |
| 157 | b->p = NULL; |
| 158 | b->n = 0; |
| 159 | b->cap = 0; |
| 160 | } |
| 161 | |
| 162 | static int buf_addf(buf_t *b, const char *fmt, ...) |
| 163 | { |
| 164 | char tmp[2048]; |
| 165 | int n; |
| 166 | va_list ap; |
| 167 | |
| 168 | va_start(ap, fmt); |
| 169 | n = vsnprintf(tmp, sizeof(tmp), fmt, ap); |
| 170 | va_end(ap); |
| 171 | if (n < 0) return 0; |
| 172 | if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n); |
| 173 | |
| 174 | { |
| 175 | char *big = (char *)malloc((size_t)n + 1); |
| 176 | int ok; |
| 177 | if (!big) return 0; |
| 178 | va_start(ap, fmt); |
| 179 | vsnprintf(big, (size_t)n + 1, fmt, ap); |
| 180 | va_end(ap); |
| 181 | ok = buf_add(b, big, (size_t)n); |
| 182 | free(big); |
| 183 | return ok; |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /* JSON string escape into a buffer (never emits a bare control byte). */ |
| 188 | static int buf_json(buf_t *b, const char *s) |
| 189 | { |
| 190 | const unsigned char *p = (const unsigned char *)(s ? s : ""); |
| 191 | if (!buf_addc(b, '"')) return 0; |
| 192 | for (; *p; p++) { |
| 193 | switch (*p) { |
| 194 | case '"': if (!buf_adds(b, "\\\"")) return 0; break; |
| 195 | case '\\': if (!buf_adds(b, "\\\\")) return 0; break; |
| 196 | case '\n': if (!buf_adds(b, "\\n")) return 0; break; |
| 197 | case '\r': if (!buf_adds(b, "\\r")) return 0; break; |
| 198 | case '\t': if (!buf_adds(b, "\\t")) return 0; break; |
| 199 | default: |
| 200 | if (*p < 0x20) { if (!buf_addf(b, "\\u%04x", *p)) return 0; } |
| 201 | else if (!buf_addc(b, (char)*p)) return 0; |
| 202 | } |
| 203 | } |
| 204 | return buf_addc(b, '"'); |
| 205 | } |
| 206 | |
| 207 | /* ------------------------------------------------------------------ */ |
| 208 | /* Query string */ |
| 209 | /* ------------------------------------------------------------------ */ |
| 210 | |
| 211 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 212 | { |
| 213 | size_t klen; |
| 214 | const char *p; |
| 215 | |
| 216 | if (!out || outsz == 0) return 0; |
| 217 | out[0] = '\0'; |
| 218 | if (!qs || !key) return 0; |
| 219 | klen = strlen(key); |
| 220 | p = qs; |
| 221 | while (*p) { |
| 222 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 223 | size_t i = 0; |
| 224 | p += klen + 1; |
| 225 | while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; |
| 226 | out[i] = '\0'; |
| 227 | return 1; |
| 228 | } |
| 229 | p = strchr(p, '&'); |
| 230 | if (!p) break; |
| 231 | p++; |
| 232 | } |
| 233 | return 0; |
| 234 | } |
| 235 | |
| 236 | static int query_has(const char *qs, const char *key) |
| 237 | { |
| 238 | size_t klen = strlen(key); |
| 239 | const char *p = qs; |
| 240 | while (p && *p) { |
| 241 | if (strncmp(p, key, klen) == 0 && (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) |
| 242 | return 1; |
| 243 | p = strchr(p, '&'); |
| 244 | if (!p) break; |
| 245 | p++; |
| 246 | } |
| 247 | return 0; |
| 248 | } |
| 249 | |
| 250 | /* Percent-decode in place (the auth code arrives from a paste box, and a |
| 251 | * browser or the hub proxy may have encoded it). */ |
| 252 | static void url_decode(char *s) |
| 253 | { |
| 254 | char *w = s; |
| 255 | char *r = s; |
| 256 | if (!s) return; |
| 257 | while (*r) { |
| 258 | if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) { |
| 259 | int hi = isdigit((unsigned char)r[1]) ? r[1] - '0' : tolower((unsigned char)r[1]) - 'a' + 10; |
| 260 | int lo = isdigit((unsigned char)r[2]) ? r[2] - '0' : tolower((unsigned char)r[2]) - 'a' + 10; |
| 261 | *w++ = (char)((hi << 4) | lo); |
| 262 | r += 3; |
| 263 | } else if (*r == '+') { |
| 264 | *w++ = ' '; |
| 265 | r++; |
| 266 | } else { |
| 267 | *w++ = *r++; |
| 268 | } |
| 269 | } |
| 270 | *w = '\0'; |
| 271 | } |
| 272 | |
| 273 | /* ------------------------------------------------------------------ */ |
| 274 | /* Node auth (X-Bot-Password / Bearer / ?pwd=) */ |
| 275 | /* ------------------------------------------------------------------ */ |
| 276 | |
| 277 | static void require_node_auth(void) |
| 278 | { |
| 279 | const char *np = getenv("BOT_PASSWORD"); |
| 280 | const char *xp; |
| 281 | const char *auth; |
| 282 | char qpwd[256] = {0}; |
| 283 | |
| 284 | if (!np || !*np) return; |
| 285 | |
| 286 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 287 | if (xp && strcmp(xp, np) == 0) return; |
| 288 | |
| 289 | auth = getenv("HTTP_AUTHORIZATION"); |
| 290 | if (auth) { |
| 291 | while (*auth == ' ') auth++; |
| 292 | if (strncasecmp(auth, "Bearer ", 7) == 0) { |
| 293 | auth += 7; |
| 294 | while (*auth == ' ') auth++; |
| 295 | if (strcmp(auth, np) == 0) return; |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && |
| 300 | strcmp(qpwd, np) == 0) return; |
| 301 | |
| 302 | fputs("Status: 401 Unauthorized\r\n" |
| 303 | "Content-Type: application/json; charset=utf-8\r\n" |
| 304 | "Cache-Control: no-store\r\n\r\n" |
| 305 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 306 | exit(0); |
| 307 | } |
| 308 | |
| 309 | /* ------------------------------------------------------------------ */ |
| 310 | /* Paths */ |
| 311 | /* ------------------------------------------------------------------ */ |
| 312 | |
| 313 | static const char *home_dir(void) |
| 314 | { |
| 315 | #ifdef _WIN32 |
| 316 | static char home[512]; |
| 317 | DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); |
| 318 | if (n > 0 && n < sizeof(home)) return home; |
| 319 | home[0] = '\0'; |
| 320 | if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) { |
| 321 | char tmp[512]; |
| 322 | if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) { |
| 323 | strncat(home, tmp, sizeof(home) - strlen(home) - 1); |
| 324 | return home; |
| 325 | } |
| 326 | } |
| 327 | return NULL; |
| 328 | #else |
| 329 | const char *h = getenv("HOME"); |
| 330 | return (h && *h) ? h : NULL; |
| 331 | #endif |
| 332 | } |
| 333 | |
| 334 | #if defined(_WIN32) |
| 335 | # define PATH_SEP '\\' |
| 336 | #else |
| 337 | # define PATH_SEP '/' |
| 338 | #endif |
| 339 | |
| 340 | /* accounts json: ANTIGRAVITY_CREDS_PATH, else ~/.config/google-accounts/... */ |
| 341 | static void creds_path(char *out, size_t n) |
| 342 | { |
| 343 | const char *env = getenv("ANTIGRAVITY_CREDS_PATH"); |
| 344 | const char *home = home_dir(); |
| 345 | |
| 346 | if (env && *env) { snprintf(out, n, "%s", env); return; } |
| 347 | if (!home) { snprintf(out, n, "antigravity_accounts.json"); return; } |
| 348 | snprintf(out, n, "%s%c.config%cgoogle-accounts%cantigravity_accounts.json", |
| 349 | home, PATH_SEP, PATH_SEP, PATH_SEP); |
| 350 | } |
| 351 | |
| 352 | /* sibling file next to the accounts json (selected_account.txt and friends) */ |
| 353 | static void creds_sibling(const char *name, char *out, size_t n) |
| 354 | { |
| 355 | char base[PATH_SZ]; |
| 356 | char *slash; |
| 357 | char sep = PATH_SEP; |
| 358 | |
| 359 | creds_path(base, sizeof(base)); |
| 360 | slash = strrchr(base, sep); |
| 361 | if (!slash) slash = strrchr(base, '/'); |
| 362 | if (!slash) { snprintf(out, n, "%s", name); return; } |
| 363 | *(slash + 1) = '\0'; |
| 364 | if (strlen(base) + strlen(name) >= n) { snprintf(out, n, "%s", name); return; } |
| 365 | memcpy(out, base, strlen(base) + 1); |
| 366 | strncat(out, name, n - strlen(out) - 1); |
| 367 | } |
| 368 | |
| 369 | static void env_dir(char *out, size_t n) |
| 370 | { |
| 371 | const char *env = getenv("ANTIGRAVITY_ENV_DIR"); |
| 372 | const char *creds = getenv("ANTIGRAVITY_CREDS_PATH"); |
| 373 | const char *home = home_dir(); |
| 374 | |
| 375 | if (env && *env) { snprintf(out, n, "%s", env); return; } |
| 376 | |
| 377 | /* A relocated credential file implies a relocated profile: they are written |
| 378 | * by the same CLI into the same tree, and reading one from the default home |
| 379 | * while the other is overridden makes status report an empty project for a |
| 380 | * session that has one. */ |
| 381 | if (creds && *creds) { |
| 382 | char base[PATH_SZ]; |
| 383 | char *slash; |
| 384 | snprintf(base, sizeof(base), "%s", creds); |
| 385 | slash = strrchr(base, PATH_SEP); |
| 386 | if (!slash) slash = strrchr(base, '/'); |
| 387 | if (slash) { |
| 388 | *(slash + 1) = '\0'; |
| 389 | if (strlen(base) + 16 < n) { snprintf(out, n, "%sscorpiox-env", base); return; } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | if (!home) { snprintf(out, n, "."); return; } |
| 394 | snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP); |
| 395 | } |
| 396 | |
| 397 | static void pending_path(char *out, size_t n) |
| 398 | { |
| 399 | const char *env = getenv("ANTIGRAVITY_PENDING_PATH"); |
| 400 | const char *home = home_dir(); |
| 401 | |
| 402 | if (env && *env) { snprintf(out, n, "%s", env); return; } |
| 403 | if (!home) { snprintf(out, n, "antigravity-default.json"); return; } |
| 404 | snprintf(out, n, "%s%c.claude%c.login-pending%cantigravity-default.json", |
| 405 | home, PATH_SEP, PATH_SEP, PATH_SEP); |
| 406 | } |
| 407 | |
| 408 | static const char *login_bin(void) |
| 409 | { |
| 410 | const char *b = getenv("ANTIGRAVITY_LOGIN_BIN"); |
| 411 | return (b && *b) ? b : DEFAULT_LOGIN_BIN; |
| 412 | } |
| 413 | |
| 414 | static const char *token_bin(void) |
| 415 | { |
| 416 | const char *b = getenv("ANTIGRAVITY_TOKEN_BIN"); |
| 417 | return (b && *b) ? b : DEFAULT_TOKEN_BIN; |
| 418 | } |
| 419 | |
| 420 | static int file_exists(const char *p) |
| 421 | { |
| 422 | #if defined(_WIN32) |
| 423 | DWORD a = GetFileAttributesA(p); |
| 424 | return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); |
| 425 | #else |
| 426 | struct stat st; |
| 427 | return p && stat(p, &st) == 0 && S_ISREG(st.st_mode); |
| 428 | #endif |
| 429 | } |
| 430 | |
| 431 | /* Read a whole file. Returns malloc'd NUL-terminated buffer or NULL. */ |
| 432 | static char *read_file(const char *path) |
| 433 | { |
| 434 | FILE *f; |
| 435 | long sz; |
| 436 | char *buf; |
| 437 | |
| 438 | if (!path || !*path) return NULL; |
| 439 | f = fopen(path, "rb"); |
| 440 | if (!f) return NULL; |
| 441 | if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } |
| 442 | sz = ftell(f); |
| 443 | if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } |
| 444 | if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } |
| 445 | buf = (char *)malloc((size_t)sz + 1); |
| 446 | if (!buf) { fclose(f); return NULL; } |
| 447 | if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { |
| 448 | free(buf); |
| 449 | fclose(f); |
| 450 | return NULL; |
| 451 | } |
| 452 | buf[sz] = '\0'; |
| 453 | fclose(f); |
| 454 | return buf; |
| 455 | } |
| 456 | |
| 457 | /* Trim trailing CR/LF/space in place. */ |
| 458 | static void trim_tail(char *s) |
| 459 | { |
| 460 | size_t n; |
| 461 | if (!s) return; |
| 462 | n = strlen(s); |
| 463 | while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' || s[n - 1] == ' ' || s[n - 1] == '\t')) |
| 464 | s[--n] = '\0'; |
| 465 | } |
| 466 | |
| 467 | /* ------------------------------------------------------------------ */ |
| 468 | /* Minimal JSON field readers */ |
| 469 | /* ------------------------------------------------------------------ */ |
| 470 | |
| 471 | /* Copy a JSON string value that starts at *pp (which points at the opening |
| 472 | * quote). Advances *pp past the closing quote. */ |
| 473 | static int json_read_string_at(const char **pp, char *out, size_t outsz) |
| 474 | { |
| 475 | const char *p = *pp; |
| 476 | size_t i = 0; |
| 477 | |
| 478 | if (!p || *p != '"') return 0; |
| 479 | p++; |
| 480 | while (*p && *p != '"') { |
| 481 | char c = *p; |
| 482 | if (c == '\\' && p[1]) { |
| 483 | p++; |
| 484 | switch (*p) { |
| 485 | case 'n': c = '\n'; break; |
| 486 | case 'r': c = '\r'; break; |
| 487 | case 't': c = '\t'; break; |
| 488 | case 'b': c = '\b'; break; |
| 489 | case 'f': c = '\f'; break; |
| 490 | case 'u': { |
| 491 | unsigned int v = 0; |
| 492 | int k; |
| 493 | p++; |
| 494 | for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) |
| 495 | v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) |
| 496 | ? *p - '0' |
| 497 | : tolower((unsigned char)*p) - 'a' + 10); |
| 498 | if (i + 1 < outsz) out[i++] = (char)(v & 0xff); |
| 499 | continue; |
| 500 | } |
| 501 | default: c = *p; break; |
| 502 | } |
| 503 | p++; |
| 504 | } else { |
| 505 | p++; |
| 506 | } |
| 507 | if (i + 1 < outsz) out[i++] = c; |
| 508 | } |
| 509 | if (*p == '"') p++; |
| 510 | if (outsz) out[i < outsz ? i : outsz - 1] = '\0'; |
| 511 | *pp = p; |
| 512 | return 1; |
| 513 | } |
| 514 | |
| 515 | /* Skip one JSON value (string, number, literal, object, array). */ |
| 516 | static const char *json_skip_value(const char *p) |
| 517 | { |
| 518 | if (!p) return NULL; |
| 519 | while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; |
| 520 | if (*p == '"') { |
| 521 | char tmp[8]; |
| 522 | json_read_string_at(&p, tmp, sizeof(tmp)); |
| 523 | return p; |
| 524 | } |
| 525 | if (*p == '{' || *p == '[') { |
| 526 | char open = *p; |
| 527 | char close = (open == '{') ? '}' : ']'; |
| 528 | int depth = 0; |
| 529 | while (*p) { |
| 530 | if (*p == '"') { |
| 531 | char tmp[8]; |
| 532 | json_read_string_at(&p, tmp, sizeof(tmp)); |
| 533 | continue; |
| 534 | } |
| 535 | if (*p == open) depth++; |
| 536 | else if (*p == close) { |
| 537 | depth--; |
| 538 | if (depth == 0) return p + 1; |
| 539 | } |
| 540 | p++; |
| 541 | } |
| 542 | return p; |
| 543 | } |
| 544 | while (*p && *p != ',' && *p != '}' && *p != ']') p++; |
| 545 | return p; |
| 546 | } |
| 547 | |
| 548 | /* Find "key":<value> anywhere inside the slice [obj, end) and return the |
| 549 | * value pointer. Only top-level keys of that slice are considered: a nested |
| 550 | * object is skipped as a whole. */ |
| 551 | static const char *json_find_key(const char *obj, const char *end, const char *key) |
| 552 | { |
| 553 | size_t klen = strlen(key); |
| 554 | const char *p = obj; |
| 555 | int depth = 0; |
| 556 | |
| 557 | if (!obj || !end || !key) return NULL; |
| 558 | /* A caller almost always hands us the whole object, i.e. a pointer at the |
| 559 | * opening '{'. Skipping it here keeps every call site free of the "+1" |
| 560 | * that is easy to forget and silent when it is missing. */ |
| 561 | while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; |
| 562 | if (p < end && *p == '{') p++; |
| 563 | |
| 564 | while (p && p < end) { |
| 565 | if (*p == '"') { |
| 566 | const char *start = p; |
| 567 | char name[128]; |
| 568 | json_read_string_at(&p, name, sizeof(name)); |
| 569 | if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { |
| 570 | const char *q = p; |
| 571 | while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; |
| 572 | if (q < end && *q == ':') { |
| 573 | q++; |
| 574 | while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; |
| 575 | return (q < end) ? q : NULL; |
| 576 | } |
| 577 | } |
| 578 | (void)start; |
| 579 | continue; |
| 580 | } |
| 581 | if (*p == '{' || *p == '[') depth++; |
| 582 | else if (*p == '}' || *p == ']') depth--; |
| 583 | p++; |
| 584 | } |
| 585 | return NULL; |
| 586 | } |
| 587 | |
| 588 | /* Returns 0 and leaves *out untouched when the key is absent or null. That |
| 589 | * matters: several callers pass a field of a longer-lived struct, and clearing |
| 590 | * it on a miss silently erases a value that was already correct. */ |
| 591 | static int json_str_field(const char *obj, const char *end, const char *key, |
| 592 | char *out, size_t outsz) |
| 593 | { |
| 594 | const char *v; |
| 595 | |
| 596 | if (!out || outsz == 0) return 0; |
| 597 | v = json_find_key(obj, end, key); |
| 598 | if (!v || *v == 'n') return 0; |
| 599 | out[0] = '\0'; |
| 600 | if (*v == '"') return json_read_string_at(&v, out, outsz); |
| 601 | { |
| 602 | size_t i = 0; |
| 603 | while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; |
| 604 | out[i] = '\0'; |
| 605 | trim_tail(out); |
| 606 | return out[0] ? 1 : 0; |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) |
| 611 | { |
| 612 | const char *v = json_find_key(obj, end, key); |
| 613 | if (!v) return dflt; |
| 614 | if (strncmp(v, "true", 4) == 0) return 1; |
| 615 | if (strncmp(v, "false", 5) == 0) return 0; |
| 616 | if (*v == '"') { |
| 617 | if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1; |
| 618 | return 0; |
| 619 | } |
| 620 | if (*v == '1') return 1; |
| 621 | return 0; |
| 622 | } |
| 623 | |
| 624 | static long long json_num_field(const char *obj, const char *end, const char *key) |
| 625 | { |
| 626 | const char *v = json_find_key(obj, end, key); |
| 627 | if (!v) return 0; |
| 628 | if (*v == '"') v++; |
| 629 | return atoll(v); |
| 630 | } |
| 631 | |
| 632 | /* ------------------------------------------------------------------ */ |
| 633 | /* Child processes */ |
| 634 | /* ------------------------------------------------------------------ */ |
| 635 | |
| 636 | /* Single-quote an argv element for the shell that popen uses. A quote inside |
| 637 | * the argument is closed, escaped and reopened, so nothing can break out. */ |
| 638 | static void shell_quote_into(const char *in, char *out, size_t outsz) |
| 639 | { |
| 640 | size_t o = 0; |
| 641 | const char *p; |
| 642 | |
| 643 | if (outsz < 3) { if (outsz) out[0] = '\0'; return; } |
| 644 | out[o++] = '\''; |
| 645 | for (p = in; p && *p; p++) { |
| 646 | if (*p == '\'') { |
| 647 | if (o + 5 >= outsz) break; |
| 648 | memcpy(out + o, "'\\''", 4); |
| 649 | o += 4; |
| 650 | } else { |
| 651 | if (o + 2 >= outsz) break; |
| 652 | out[o++] = *p; |
| 653 | } |
| 654 | } |
| 655 | out[o++] = '\''; |
| 656 | out[o] = '\0'; |
| 657 | } |
| 658 | |
| 659 | /* Run `<bin> <args>` and capture stdout. args may be NULL or a pre-built |
| 660 | * shell fragment. Returns 1 when the process ran, 0 when popen failed. The |
| 661 | * captured text is stored in out (trimmed). */ |
| 662 | static int run_capture(const char *bin, const char *args, buf_t *out) |
| 663 | { |
| 664 | char cmd[CMD_SZ]; |
| 665 | char qbin[FIELD_SZ]; |
| 666 | FILE *f; |
| 667 | char line[2048]; |
| 668 | size_t total = 0; |
| 669 | int rc; |
| 670 | |
| 671 | if (!bin || !*bin) return 0; |
| 672 | shell_quote_into(bin, qbin, sizeof(qbin)); |
| 673 | if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args); |
| 674 | else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin); |
| 675 | |
| 676 | f = popen(cmd, "r"); |
| 677 | if (!f) return 0; |
| 678 | while (fgets(line, sizeof(line), f)) { |
| 679 | total += strlen(line); |
| 680 | if (total > OUT_MAX) break; |
| 681 | buf_adds(out, line); |
| 682 | } |
| 683 | rc = pclose(f); |
| 684 | |
| 685 | if (out->p) { |
| 686 | /* the CLIs print one JSON line last; strip surrounding whitespace */ |
| 687 | size_t n = out->n; |
| 688 | while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0'; |
| 689 | out->n = n; |
| 690 | } |
| 691 | /* pclose() hands back a wait status, not an exit code: "command not |
| 692 | * found" arrives as 32512 (127 << 8). Callers treat that as "the CLI is |
| 693 | * not on this node", which is a different message from "the CLI ran and |
| 694 | * failed". Any other status is the CLI's own and is left to the JSON it |
| 695 | * printed. */ |
| 696 | if (rc != -1 && (rc >> 8) == 127) return -1; |
| 697 | return 1; |
| 698 | } |
| 699 | |
| 700 | /* The login/token CLIs print human progress on stdout before the final JSON |
| 701 | * line, so take the LAST line that starts with '{'. */ |
| 702 | static const char *last_json_line(buf_t *b) |
| 703 | { |
| 704 | size_t i; |
| 705 | const char *last = NULL; |
| 706 | |
| 707 | if (!b || !b->p) return NULL; |
| 708 | for (i = 0; i < b->n; i++) { |
| 709 | int at_line_start = (i == 0) || b->p[i - 1] == '\n'; |
| 710 | if (at_line_start && b->p[i] == '{') last = b->p + i; |
| 711 | } |
| 712 | return last; |
| 713 | } |
| 714 | |
| 715 | /* ------------------------------------------------------------------ */ |
| 716 | /* Status assembly */ |
| 717 | /* ------------------------------------------------------------------ */ |
| 718 | |
| 719 | typedef struct { |
| 720 | int logged_in; |
| 721 | int has_refresh; |
| 722 | int pending; |
| 723 | int expired; |
| 724 | int cli_present; |
| 725 | char email[EMAIL_SZ]; |
| 726 | char account[EMAIL_SZ]; |
| 727 | char project[PROJ_SZ]; |
| 728 | char path[PATH_SZ]; |
| 729 | char profile[PROJ_SZ]; |
| 730 | long long expires_at; /* unix seconds, 0 = unknown */ |
| 731 | /* long long, not int: expires_at - now overflows a 32-bit int for any |
| 732 | * expiry past 2038, which turned a valid session into "expires in |
| 733 | * -1987015054s" in the UI while expired stayed false. */ |
| 734 | long long expires_in_sec; /* negative when expired, 0 when unknown */ |
| 735 | } status_t; |
| 736 | |
| 737 | /* Pull email / refresh_token presence out of the accounts array. |
| 738 | * |
| 739 | * The file is a JSON array of {email, refresh_token}. The selected account |
| 740 | * wins; otherwise the first entry that carries a refresh token. Presence of a |
| 741 | * refresh token is the login signal, and only its presence is recorded - the |
| 742 | * value is never copied. */ |
| 743 | static void scan_accounts(const char *json, const char *selected, status_t *st) |
| 744 | { |
| 745 | const char *p = json; |
| 746 | char first_email[EMAIL_SZ] = {0}; |
| 747 | int first_has = 0; |
| 748 | int found = 0; |
| 749 | |
| 750 | while (p && *p) { |
| 751 | const char *open = strchr(p, '{'); |
| 752 | const char *obj; |
| 753 | const char *end; |
| 754 | char email[EMAIL_SZ] = {0}; |
| 755 | char rt[8] = {0}; |
| 756 | int has_rt; |
| 757 | |
| 758 | if (!open) break; |
| 759 | end = json_skip_value(open); |
| 760 | if (!end || end <= open) break; |
| 761 | /* json_find_key tracks brace depth, so it must start INSIDE the |
| 762 | * object: passing the opening '{' makes every top-level key look |
| 763 | * nested and the whole scan silently returns nothing. */ |
| 764 | obj = open; |
| 765 | |
| 766 | json_str_field(obj, end, "email", email, sizeof(email)); |
| 767 | has_rt = json_str_field(obj, end, "refresh_token", rt, sizeof(rt)); |
| 768 | |
| 769 | if (!first_email[0] && email[0]) { |
| 770 | snprintf(first_email, sizeof(first_email), "%s", email); |
| 771 | first_has = has_rt; |
| 772 | } |
| 773 | if (selected && selected[0] && email[0] && strcmp(email, selected) == 0) { |
| 774 | snprintf(st->email, sizeof(st->email), "%s", email); |
| 775 | st->has_refresh = has_rt; |
| 776 | found = 1; |
| 777 | p = end; |
| 778 | break; |
| 779 | } |
| 780 | p = end; |
| 781 | } |
| 782 | |
| 783 | if (!found) { |
| 784 | if (first_email[0]) snprintf(st->email, sizeof(st->email), "%s", first_email); |
| 785 | st->has_refresh = first_has; |
| 786 | } |
| 787 | st->logged_in = st->has_refresh; |
| 788 | } |
| 789 | |
| 790 | /* Parse GOOGLE_PROJECT_ID / GOOGLE_ACCOUNT out of the profile file. */ |
| 791 | static void scan_profile(const char *text, status_t *st) |
| 792 | { |
| 793 | const char *p = text; |
| 794 | |
| 795 | while (p && *p) { |
| 796 | const char *nl = strchr(p, '\n'); |
| 797 | size_t len = nl ? (size_t)(nl - p) : strlen(p); |
| 798 | char line[FIELD_SZ]; |
| 799 | size_t i; |
| 800 | |
| 801 | if (len > 0 && len < sizeof(line)) { |
| 802 | memcpy(line, p, len); |
| 803 | line[len] = '\0'; |
| 804 | trim_tail(line); |
| 805 | for (i = 0; line[i]; i++) |
| 806 | if (line[i] == '\r') line[i] = ' '; |
| 807 | if (strncmp(line, "GOOGLE_PROJECT_ID=", 18) == 0 && !st->project[0]) { |
| 808 | snprintf(st->project, sizeof(st->project), "%.*s", (int)sizeof(st->project) - 1, line + 18); |
| 809 | } else if (strncmp(line, "GOOGLE_ACCOUNT=", 15) == 0 && !st->account[0]) { |
| 810 | snprintf(st->account, sizeof(st->account), "%.*s", (int)sizeof(st->account) - 1, line + 15); |
| 811 | } |
| 812 | } |
| 813 | if (!nl) break; |
| 814 | p = nl + 1; |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | static void collect_status(status_t *st) |
| 819 | { |
| 820 | char acct[PATH_SZ], sel[PATH_SZ], prof[PATH_SZ], pend[PATH_SZ]; |
| 821 | char *text; |
| 822 | char selected[EMAIL_SZ] = {0}; |
| 823 | long long now = (long long)time(NULL); |
| 824 | |
| 825 | memset(st, 0, sizeof(*st)); |
| 826 | st->profile[0] = '\0'; |
| 827 | |
| 828 | creds_path(acct, sizeof(acct)); |
| 829 | snprintf(st->path, sizeof(st->path), "%s", acct); |
| 830 | |
| 831 | creds_sibling("selected_account.txt", sel, sizeof(sel)); |
| 832 | text = read_file(sel); |
| 833 | if (text) { |
| 834 | trim_tail(text); |
| 835 | snprintf(selected, sizeof(selected), "%s", text); |
| 836 | free(text); |
| 837 | } |
| 838 | |
| 839 | text = read_file(acct); |
| 840 | if (text) { |
| 841 | scan_accounts(text, selected, st); |
| 842 | free(text); |
| 843 | } |
| 844 | |
| 845 | /* The profile file carries the companion project and the account email. */ |
| 846 | env_dir(prof, sizeof(prof)); |
| 847 | { |
| 848 | char pfile[PATH_SZ + 32]; |
| 849 | char *ptext; |
| 850 | if (strlen(prof) + 16 < sizeof(pfile)) |
| 851 | snprintf(pfile, sizeof(pfile), "%s%cantigravity.txt", prof, PATH_SEP); |
| 852 | else |
| 853 | snprintf(pfile, sizeof(pfile), "antigravity.txt"); |
| 854 | ptext = read_file(pfile); |
| 855 | if (ptext) { |
| 856 | scan_profile(ptext, st); |
| 857 | snprintf(st->profile, sizeof(st->profile), "antigravity"); |
| 858 | free(ptext); |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | if (!st->email[0] && st->account[0]) |
| 863 | snprintf(st->email, sizeof(st->email), "%s", st->account); |
| 864 | if (!st->account[0] && st->email[0]) |
| 865 | snprintf(st->account, sizeof(st->account), "%s", st->email); |
| 866 | |
| 867 | /* Pending flow marker (the CLI writes and removes this file). */ |
| 868 | pending_path(pend, sizeof(pend)); |
| 869 | st->pending = file_exists(pend); |
| 870 | |
| 871 | /* Ask the CLI when it is on PATH: it knows the token expiry and the exact |
| 872 | * pending state, and it is the authority on logged_in. The plugin never |
| 873 | * becomes the source of truth about a Google session. */ |
| 874 | { |
| 875 | buf_t out; |
| 876 | buf_init(&out); |
| 877 | if (run_capture(login_bin(), "--status", &out) > 0) { |
| 878 | const char *j = last_json_line(&out); |
| 879 | if (j) { |
| 880 | const char *end = j + strlen(j); |
| 881 | char identity[EMAIL_SZ] = {0}; |
| 882 | long long exp = 0; |
| 883 | |
| 884 | st->cli_present = 1; |
| 885 | json_str_field(j, end, "identity", identity, sizeof(identity)); |
| 886 | json_str_field(j, end, "path", st->path, sizeof(st->path)); |
| 887 | /* The CLI is authoritative, but never a downgrade: if the |
| 888 | * credential file on disk carries a refresh token, the node IS |
| 889 | * signed in and an older CLI build that answers logged_in:false |
| 890 | * must not paint a green session grey. */ |
| 891 | if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1; |
| 892 | if (json_bool_field(j, end, "has_refresh", 0)) { st->has_refresh = 1; st->logged_in = 1; } |
| 893 | /* pending: the marker file is the authority (it is created by |
| 894 | * --start and removed by --finish/--cancel), so a CLI answer is |
| 895 | * only allowed to ADD a pending state, never to clear one. */ |
| 896 | if (json_bool_field(j, end, "pending", 0)) st->pending = 1; |
| 897 | exp = json_num_field(j, end, "expires_at"); |
| 898 | if (exp > 0 && exp < 100000000000LL) exp *= 1000; /* seconds -> ms */ |
| 899 | if (exp > 0) st->expires_at = exp / 1000; |
| 900 | if (identity[0] && !st->email[0]) |
| 901 | snprintf(st->email, sizeof(st->email), "%s", identity); |
| 902 | if (identity[0] && !st->account[0]) |
| 903 | snprintf(st->account, sizeof(st->account), "%s", identity); |
| 904 | } |
| 905 | } |
| 906 | buf_free(&out); |
| 907 | } |
| 908 | |
| 909 | if (st->expires_at > 0) { |
| 910 | st->expires_in_sec = st->expires_at - now; |
| 911 | st->expired = st->expires_at <= now; |
| 912 | } |
| 913 | if (!st->logged_in) { |
| 914 | st->expired = 0; |
| 915 | st->expires_in_sec = 0; |
| 916 | } |
| 917 | } |
| 918 | |
| 919 | /* One status object. Shared by every action's response so the UI can always |
| 920 | * re-render from the same shape. */ |
| 921 | static void emit_status(buf_t *b, const status_t *st) |
| 922 | { |
| 923 | buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false"); |
| 924 | buf_adds(b, "\"email\":"); |
| 925 | buf_json(b, st->email); |
| 926 | buf_addf(b, ",\"account\":"); |
| 927 | buf_json(b, st->account); |
| 928 | buf_addf(b, ",\"project_id\":"); |
| 929 | buf_json(b, st->project); |
| 930 | buf_addf(b, ",\"profile\":"); |
| 931 | buf_json(b, st->profile); |
| 932 | buf_addf(b, ",\"expires_at\":%lld", st->expires_at); |
| 933 | buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec); |
| 934 | buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false"); |
| 935 | buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false"); |
| 936 | buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false"); |
| 937 | buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false"); |
| 938 | buf_addf(b, ",\"credentials_path\":"); |
| 939 | buf_json(b, st->path); |
| 940 | } |
| 941 | |
| 942 | /* ------------------------------------------------------------------ */ |
| 943 | /* Actions */ |
| 944 | /* ------------------------------------------------------------------ */ |
| 945 | |
| 946 | static void json_headers(void) |
| 947 | { |
| 948 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 949 | "Cache-Control: no-store\r\n" |
| 950 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 951 | } |
| 952 | |
| 953 | static void emit_error(int code, const char *status, const char *err, const char *detail) |
| 954 | { |
| 955 | buf_t b; |
| 956 | |
| 957 | buf_init(&b); |
| 958 | buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" |
| 959 | "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", |
| 960 | code, status); |
| 961 | buf_addf(&b, "{\"ok\":false,\"error\":"); |
| 962 | buf_json(&b, err); |
| 963 | if (detail && *detail) { |
| 964 | buf_addf(&b, ",\"detail\":"); |
| 965 | buf_json(&b, detail); |
| 966 | } |
| 967 | buf_addf(&b, "}\n"); |
| 968 | fputs(buf_str(&b), stdout); |
| 969 | buf_free(&b); |
| 970 | } |
| 971 | |
| 972 | static int action_status(void) |
| 973 | { |
| 974 | status_t st; |
| 975 | buf_t b; |
| 976 | |
| 977 | collect_status(&st); |
| 978 | buf_init(&b); |
| 979 | buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\","); |
| 980 | emit_status(&b, &st); |
| 981 | buf_adds(&b, "}\n"); |
| 982 | json_headers(); |
| 983 | fputs(buf_str(&b), stdout); |
| 984 | buf_free(&b); |
| 985 | return 0; |
| 986 | } |
| 987 | |
| 988 | static int action_start(void) |
| 989 | { |
| 990 | buf_t out, b; |
| 991 | const char *j; |
| 992 | char auth_url[CMD_SZ] = {0}; |
| 993 | char flow[64] = {0}; |
| 994 | char hint[512] = {0}; |
| 995 | long long expires_in = 0; |
| 996 | |
| 997 | buf_init(&out); |
| 998 | if (run_capture(login_bin(), "--start", &out) <= 0) { |
| 999 | buf_free(&out); |
| 1000 | emit_error(200, "OK", "cli_unavailable", |
| 1001 | "the login CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_LOGIN_BIN"); |
| 1002 | return 1; |
| 1003 | } |
| 1004 | j = last_json_line(&out); |
| 1005 | if (!j) { |
| 1006 | buf_free(&out); |
| 1007 | emit_error(200, "OK", "start_failed", buf_str(&out)); |
| 1008 | return 1; |
| 1009 | } |
| 1010 | { |
| 1011 | const char *end = j + strlen(j); |
| 1012 | json_str_field(j, end, "auth_url", auth_url, sizeof(auth_url)); |
| 1013 | json_str_field(j, end, "flow", flow, sizeof(flow)); |
| 1014 | json_str_field(j, end, "hint", hint, sizeof(hint)); |
| 1015 | expires_in = json_num_field(j, end, "expires_in"); |
| 1016 | if (!json_bool_field(j, end, "ok", 1) || !auth_url[0]) { |
| 1017 | char detail[FIELD_SZ] = {0}; |
| 1018 | json_str_field(j, end, "error", detail, sizeof(detail)); |
| 1019 | buf_free(&out); |
| 1020 | emit_error(200, "OK", detail[0] ? detail : "start_failed", "the login CLI did not return an authorization URL"); |
| 1021 | return 1; |
| 1022 | } |
| 1023 | } |
| 1024 | buf_free(&out); |
| 1025 | |
| 1026 | buf_init(&b); |
| 1027 | buf_adds(&b, "{\"ok\":true,\"flow\":"); |
| 1028 | buf_json(&b, flow[0] ? flow : "paste_code"); |
| 1029 | buf_adds(&b, ",\"auth_url\":"); |
| 1030 | buf_json(&b, auth_url); |
| 1031 | buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : 900); |
| 1032 | buf_adds(&b, ",\"hint\":"); |
| 1033 | buf_json(&b, hint[0] ? hint |
| 1034 | : "Sign in with Google and approve. The browser lands on antigravity.google - copy the whole address (or just the code) and paste it here."); |
| 1035 | buf_adds(&b, "}\n"); |
| 1036 | json_headers(); |
| 1037 | fputs(buf_str(&b), stdout); |
| 1038 | buf_free(&b); |
| 1039 | return 0; |
| 1040 | } |
| 1041 | |
| 1042 | /* Reject anything that cannot be an authorization code. The value is passed |
| 1043 | * to a shell, so this is the second line of defence behind shell_quote_into. */ |
| 1044 | static int valid_code(const char *code) |
| 1045 | { |
| 1046 | size_t n, i; |
| 1047 | if (!code || !(n = strlen(code)) || n > CODE_MAX) return 0; |
| 1048 | for (i = 0; i < n; i++) { |
| 1049 | unsigned char c = (unsigned char)code[i]; |
| 1050 | if (c < 0x20 || c == 0x7f || c == '\'' || c == '"' || c == '\\' || c == ';' || |
| 1051 | c == '`' || c == '$' || c == '|' || c == '&' || c == '<' || c == '>' || |
| 1052 | c == '\n' || c == '\r') |
| 1053 | return 0; |
| 1054 | } |
| 1055 | return 1; |
| 1056 | } |
| 1057 | |
| 1058 | static int action_finish(const char *raw_code) |
| 1059 | { |
| 1060 | char code[CODE_MAX]; |
| 1061 | char qcode[CODE_MAX + 64]; |
| 1062 | buf_t out, b; |
| 1063 | const char *j; |
| 1064 | |
| 1065 | if (!raw_code) { |
| 1066 | emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=..."); |
| 1067 | return 1; |
| 1068 | } |
| 1069 | snprintf(code, sizeof(code), "%s", raw_code); |
| 1070 | url_decode(code); |
| 1071 | trim_tail(code); |
| 1072 | |
| 1073 | /* The user usually pastes the whole redirect address, which is what the |
| 1074 | * login CLI expects too (its lm_clean_code does the same extraction). Pull |
| 1075 | * out code= before validating, so a legitimate URL is not rejected for |
| 1076 | * carrying a state= parameter alongside it. */ |
| 1077 | { |
| 1078 | char *c = strstr(code, "code="); |
| 1079 | if (c) { |
| 1080 | char extracted[CODE_MAX]; |
| 1081 | size_t i = 0; |
| 1082 | c += 5; |
| 1083 | while (*c && *c != '&' && *c != '#' && i + 1 < sizeof(extracted)) |
| 1084 | extracted[i++] = *c++; |
| 1085 | extracted[i] = '\0'; |
| 1086 | if (i > 0) snprintf(code, sizeof(code), "%s", extracted); |
| 1087 | } |
| 1088 | } |
| 1089 | if (!valid_code(code)) { |
| 1090 | emit_error(400, "Bad Request", "invalid_code", |
| 1091 | "the value is not an authorization code (empty, too long, or contains shell characters)"); |
| 1092 | return 1; |
| 1093 | } |
| 1094 | |
| 1095 | shell_quote_into(code, qcode, sizeof(qcode)); |
| 1096 | { |
| 1097 | char args[CODE_MAX + 128]; |
| 1098 | snprintf(args, sizeof(args), "--finish %s", qcode); |
| 1099 | buf_init(&out); |
| 1100 | if (run_capture(login_bin(), args, &out) <= 0) { |
| 1101 | buf_free(&out); |
| 1102 | emit_error(200, "OK", "cli_unavailable", |
| 1103 | "the login CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_LOGIN_BIN"); |
| 1104 | return 1; |
| 1105 | } |
| 1106 | } |
| 1107 | |
| 1108 | j = last_json_line(&out); |
| 1109 | if (!j) { |
| 1110 | buf_free(&out); |
| 1111 | emit_error(200, "OK", "finish_failed", "the login CLI returned no JSON"); |
| 1112 | return 1; |
| 1113 | } |
| 1114 | if (!json_bool_field(j, (const char *)(j + strlen(j)), "ok", 0)) { |
| 1115 | char detail[FIELD_SZ] = {0}; |
| 1116 | const char *end = j + strlen(j); |
| 1117 | json_str_field(j, end, "error", detail, sizeof(detail)); |
| 1118 | buf_free(&out); |
| 1119 | emit_error(200, "OK", detail[0] ? detail : "finish_failed", |
| 1120 | "Google rejected the code, or the account needs verification in a browser"); |
| 1121 | return 1; |
| 1122 | } |
| 1123 | buf_free(&out); |
| 1124 | |
| 1125 | /* Success: re-read everything so the caller gets the full new state. */ |
| 1126 | { |
| 1127 | status_t st; |
| 1128 | collect_status(&st); |
| 1129 | buf_init(&b); |
| 1130 | buf_adds(&b, "{\"ok\":true,\"state\":\"done\","); |
| 1131 | emit_status(&b, &st); |
| 1132 | buf_adds(&b, "}\n"); |
| 1133 | json_headers(); |
| 1134 | fputs(buf_str(&b), stdout); |
| 1135 | buf_free(&b); |
| 1136 | } |
| 1137 | return 0; |
| 1138 | } |
| 1139 | |
| 1140 | static int action_cancel(void) |
| 1141 | { |
| 1142 | buf_t out, b; |
| 1143 | |
| 1144 | buf_init(&out); |
| 1145 | run_capture(login_bin(), "--cancel", &out); |
| 1146 | buf_free(&out); |
| 1147 | |
| 1148 | buf_init(&b); |
| 1149 | buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n"); |
| 1150 | json_headers(); |
| 1151 | fputs(buf_str(&b), stdout); |
| 1152 | buf_free(&b); |
| 1153 | return 0; |
| 1154 | } |
| 1155 | |
| 1156 | /* Refresh: the token CLI performs the refresh-token grant and prints the |
| 1157 | * access token. We deliberately keep only ok/project and drop the token, so a |
| 1158 | * browser (or a proxy log) can never capture a bearer token from this route. */ |
| 1159 | static int action_refresh(void) |
| 1160 | { |
| 1161 | buf_t out, b; |
| 1162 | const char *j; |
| 1163 | char project[PROJ_SZ] = {0}; |
| 1164 | char err[FIELD_SZ] = {0}; |
| 1165 | int ok = 0; |
| 1166 | |
| 1167 | buf_init(&out); |
| 1168 | if (run_capture(token_bin(), "-local", &out) <= 0) { |
| 1169 | buf_free(&out); |
| 1170 | emit_error(200, "OK", "cli_unavailable", |
| 1171 | "the token CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_TOKEN_BIN"); |
| 1172 | return 1; |
| 1173 | } |
| 1174 | j = last_json_line(&out); |
| 1175 | if (j) { |
| 1176 | const char *end = j + strlen(j); |
| 1177 | char tok[8] = {0}; |
| 1178 | ok = json_bool_field(j, end, "ok", 0); |
| 1179 | json_str_field(j, end, "project_id", project, sizeof(project)); |
| 1180 | (void)json_str_field(j, end, "access_token", tok, sizeof(tok)); /* presence only */ |
| 1181 | if (!ok) json_str_field(j, end, "error", err, sizeof(err)); |
| 1182 | } |
| 1183 | buf_free(&out); |
| 1184 | |
| 1185 | if (!ok) { |
| 1186 | buf_init(&b); |
| 1187 | buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":"); |
| 1188 | buf_json(&b, err[0] ? err : "the token CLI could not refresh the session; sign in again"); |
| 1189 | buf_adds(&b, "}\n"); |
| 1190 | json_headers(); |
| 1191 | fputs(buf_str(&b), stdout); |
| 1192 | buf_free(&b); |
| 1193 | return 1; |
| 1194 | } |
| 1195 | |
| 1196 | { |
| 1197 | status_t st; |
| 1198 | collect_status(&st); |
| 1199 | if (project[0]) snprintf(st.project, sizeof(st.project), "%s", project); |
| 1200 | buf_init(&b); |
| 1201 | buf_adds(&b, "{\"ok\":true,\"refreshed\":true,"); |
| 1202 | emit_status(&b, &st); |
| 1203 | buf_adds(&b, "}\n"); |
| 1204 | json_headers(); |
| 1205 | fputs(buf_str(&b), stdout); |
| 1206 | buf_free(&b); |
| 1207 | } |
| 1208 | return 0; |
| 1209 | } |
| 1210 | |
| 1211 | /* ------------------------------------------------------------------ */ |
| 1212 | /* HTML emission */ |
| 1213 | /* ------------------------------------------------------------------ */ |
| 1214 | |
| 1215 | /* Expand the two placeholders gen_ui.py leaves in UI_HTML. Keeping this split |
| 1216 | * means the palette lives in exactly one place (bot_theme_plugin.h) and the |
| 1217 | * page can never drift away from the bot's own theme. */ |
| 1218 | static void emit_ui(void) |
| 1219 | { |
| 1220 | const char *p = UI_HTML; |
| 1221 | |
| 1222 | while (*p) { |
| 1223 | if (*p == '\001') { |
| 1224 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", stdout); |
| 1225 | p++; |
| 1226 | } else if (*p == '\002') { |
| 1227 | fputs(SX_BOT_THEME_HANDOFF, stdout); |
| 1228 | p++; |
| 1229 | } else { |
| 1230 | putchar(*p++); |
| 1231 | } |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | /* ------------------------------------------------------------------ */ |
| 1236 | /* main */ |
| 1237 | /* ------------------------------------------------------------------ */ |
| 1238 | |
| 1239 | int main(int argc, char **argv) |
| 1240 | { |
| 1241 | const char *qs; |
| 1242 | char action[64] = {0}; |
| 1243 | |
| 1244 | /* 1. Discovery metadata. Must stay unauthenticated. */ |
| 1245 | if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { |
| 1246 | puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); |
| 1247 | return 0; |
| 1248 | } |
| 1249 | if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { |
| 1250 | puts(PLUGIN_ID " " PLUGIN_VER); |
| 1251 | return 0; |
| 1252 | } |
| 1253 | |
| 1254 | require_node_auth(); |
| 1255 | |
| 1256 | qs = getenv("QUERY_STRING"); |
| 1257 | if (!qs) qs = ""; |
| 1258 | |
| 1259 | /* 2. JSON API mode. `format=json` alone means "status", which is what a |
| 1260 | * dashboard polls. */ |
| 1261 | if (query_has(qs, "action") || query_has(qs, "format")) { |
| 1262 | char fmt[32] = {0}; |
| 1263 | char code[CODE_MAX] = {0}; |
| 1264 | |
| 1265 | get_query_val(qs, "action", action, sizeof(action)); |
| 1266 | get_query_val(qs, "format", fmt, sizeof(fmt)); |
| 1267 | |
| 1268 | if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status"); |
| 1269 | |
| 1270 | if (strcmp(action, "status") == 0 || !action[0]) return action_status(); |
| 1271 | if (strcmp(action, "start") == 0) return action_start(); |
| 1272 | if (strcmp(action, "cancel") == 0) return action_cancel(); |
| 1273 | if (strcmp(action, "refresh") == 0) return action_refresh(); |
| 1274 | if (strcmp(action, "finish") == 0) { |
| 1275 | if (!get_query_val(qs, "code", code, sizeof(code))) { |
| 1276 | char body[OUT_MAX]; |
| 1277 | size_t len = 0; |
| 1278 | |
| 1279 | /* POST bodies carry the code too (a long code is easier to |
| 1280 | * send as a body). Guard on CONTENT_LENGTH so an empty |
| 1281 | * inherited stdin never blocks. */ |
| 1282 | { |
| 1283 | const char *cl = getenv("CONTENT_LENGTH"); |
| 1284 | long n = (cl && *cl) ? atol(cl) : 0; |
| 1285 | if (n > 0 && n < (long)sizeof(body)) { |
| 1286 | len = fread(body, 1, (size_t)n, stdin); |
| 1287 | body[len] = '\0'; |
| 1288 | { |
| 1289 | char *p = strstr(body, "\"code\""); |
| 1290 | if (p) { |
| 1291 | p = strchr(p, ':'); |
| 1292 | if (p) { |
| 1293 | p++; |
| 1294 | while (*p == ' ' || *p == '\t' || *p == '"') p++; |
| 1295 | { |
| 1296 | size_t i = 0; |
| 1297 | while (*p && *p != '"' && *p != ',' && *p != '}' && |
| 1298 | i + 1 < sizeof(code)) code[i++] = *p++; |
| 1299 | code[i] = '\0'; |
| 1300 | } |
| 1301 | } |
| 1302 | } |
| 1303 | } |
| 1304 | } |
| 1305 | } |
| 1306 | if (!code[0]) { |
| 1307 | emit_error(400, "Bad Request", "missing_code", |
| 1308 | "pass the authorization code as &code=..."); |
| 1309 | return 1; |
| 1310 | } |
| 1311 | } |
| 1312 | return action_finish(code); |
| 1313 | } |
| 1314 | emit_error(404, "Not Found", "unknown_action", action); |
| 1315 | return 1; |
| 1316 | } |
| 1317 | |
| 1318 | /* 3. HTML UI. The page and its theme arrive from the generated header. |
| 1319 | * UI_HTML carries two control bytes: 0x01 is the theme block (<style> |
| 1320 | * with the bot tokens) and 0x02 is the handoff script before </body>. */ |
| 1321 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 1322 | "Cache-Control: no-store\r\n" |
| 1323 | "X-Content-Type-Options: nosniff\r\n" |
| 1324 | "Referrer-Policy: no-referrer\r\n" |
| 1325 | "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " |
| 1326 | "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " |
| 1327 | "base-uri 'none'; form-action 'none'; frame-ancestors *\r\n\r\n", stdout); |
| 1328 | emit_ui(); |
| 1329 | return 0; |
| 1330 | } |