/* * plugin_antigravity_login - SCORPIOX BOT open-source Google Antigravity * OAuth 2.0 PKCE login and companion-project manager for your node. * * A single clean-room C99 binary that serves THREE modes: * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata * 2. ?action=... / ?format=json -> JSON node API * 3. GET (default) -> responsive HTML UI * * DESIGN NOTE (why there is no TLS in this binary): an OAuth 2.0 PKCE code * exchange is an HTTPS POST with a client identity, and a public clean-room * repository must not carry an OAuth client secret. So this plugin does not * speak TLS at all. It drives the node's own login CLI, exactly the way the * SCORPIOX CODE login tools are meant to be driven (see the machine-mode * contract: --status / --start / --finish / --cancel, one JSON line per call), * and it reads the credential and profile files that the CLI writes: * * ~/.config/google-accounts/antigravity_accounts.json (refresh tokens) * ~/.config/google-accounts/selected_account.txt (active email) * ~/.claude/scorpiox-env/antigravity.txt (project + models) * ~/.claude/.login-pending/antigravity-default.json (pending flow) * * Every one of those paths and both CLIs can be overridden for deterministic * offline testing: * * ANTIGRAVITY_CREDS_PATH accounts json (also used for the sibling files) * ANTIGRAVITY_LOGIN_BIN the login CLI (default scorpiox-antigravity-login) * ANTIGRAVITY_TOKEN_BIN the token CLI (default scorpiox-google-fetchtoken) * ANTIGRAVITY_ENV_DIR the profile dir (default ~/.claude/scorpiox-env) * * No token is ever printed, logged or returned by this plugin: the API reports * presence and expiry only, and the refresh action reports success or the * failure reason from the token CLI with the payload discarded. * * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under * scorpiox-server on the node. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Must come before every include on Windows: MinGW defaults to 0x502 * (Server 2003), which hides the Win7+ APIs and the path helpers. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 # if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # include #else # include # include # include #endif #include "bot_theme_plugin.h" #include "ui_html.h" #define PLUGIN_SLUG "antigravity-login" #define PLUGIN_ID "plugin_antigravity_login" #define PLUGIN_VER "1.0.1" #define PLUGIN_NAME "google" #define PLUGIN_DESC "Google login" #define PATH_SZ 1024 #define EMAIL_SZ 256 #define PROJ_SZ 256 #define CODE_MAX 2048 #define CMD_SZ 4096 #define OUT_MAX (256 * 1024) #define FIELD_SZ 512 #define DEFAULT_LOGIN_BIN "scorpiox-antigravity-login" #define DEFAULT_TOKEN_BIN "scorpiox-google-fetchtoken" /* ------------------------------------------------------------------ */ /* Growable byte buffer */ /* ------------------------------------------------------------------ */ typedef struct { char *p; size_t n; size_t cap; } buf_t; static void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } static int buf_need(buf_t *b, size_t extra) { size_t want = b->n + extra + 1; char *np; if (want <= b->cap) return 1; if (b->cap == 0) b->cap = 1024; while (b->cap < want) { if (b->cap > (size_t)32 * 1024 * 1024) return 0; b->cap *= 2; } np = (char *)realloc(b->p, b->cap); if (!np) return 0; b->p = np; return 1; } static int buf_add(buf_t *b, const char *s, size_t n) { if (!buf_need(b, n)) return 0; memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = '\0'; return 1; } static int buf_adds(buf_t *b, const char *s) { return s ? buf_add(b, s, strlen(s)) : 1; } static int buf_addc(buf_t *b, char c) { return buf_add(b, &c, 1); } static const char *buf_str(buf_t *b) { if (!b->p) return ""; return b->p; } static void buf_free(buf_t *b) { free(b->p); b->p = NULL; b->n = 0; b->cap = 0; } static int buf_addf(buf_t *b, const char *fmt, ...) { char tmp[2048]; int n; va_list ap; va_start(ap, fmt); n = vsnprintf(tmp, sizeof(tmp), fmt, ap); va_end(ap); if (n < 0) return 0; if ((size_t)n < sizeof(tmp)) return buf_add(b, tmp, (size_t)n); { char *big = (char *)malloc((size_t)n + 1); int ok; if (!big) return 0; va_start(ap, fmt); vsnprintf(big, (size_t)n + 1, fmt, ap); va_end(ap); ok = buf_add(b, big, (size_t)n); free(big); return ok; } } /* JSON string escape into a buffer (never emits a bare control byte). */ static int buf_json(buf_t *b, const char *s) { const unsigned char *p = (const unsigned char *)(s ? s : ""); if (!buf_addc(b, '"')) return 0; for (; *p; p++) { switch (*p) { case '"': if (!buf_adds(b, "\\\"")) return 0; break; case '\\': if (!buf_adds(b, "\\\\")) return 0; break; case '\n': if (!buf_adds(b, "\\n")) return 0; break; case '\r': if (!buf_adds(b, "\\r")) return 0; break; case '\t': if (!buf_adds(b, "\\t")) return 0; break; default: if (*p < 0x20) { if (!buf_addf(b, "\\u%04x", *p)) return 0; } else if (!buf_addc(b, (char)*p)) return 0; } } return buf_addc(b, '"'); } /* ------------------------------------------------------------------ */ /* Query string */ /* ------------------------------------------------------------------ */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); p = qs; while (*p) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { size_t i = 0; p += klen + 1; while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; out[i] = '\0'; return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } static int query_has(const char *qs, const char *key) { size_t klen = strlen(key); const char *p = qs; while (p && *p) { if (strncmp(p, key, klen) == 0 && (p[klen] == '=' || p[klen] == '\0' || p[klen] == '&')) return 1; p = strchr(p, '&'); if (!p) break; p++; } return 0; } /* Percent-decode in place (the auth code arrives from a paste box, and a * browser or the hub proxy may have encoded it). */ static void url_decode(char *s) { char *w = s; char *r = s; if (!s) return; while (*r) { if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) { int hi = isdigit((unsigned char)r[1]) ? r[1] - '0' : tolower((unsigned char)r[1]) - 'a' + 10; int lo = isdigit((unsigned char)r[2]) ? r[2] - '0' : tolower((unsigned char)r[2]) - 'a' + 10; *w++ = (char)((hi << 4) | lo); r += 3; } else if (*r == '+') { *w++ = ' '; r++; } else { *w++ = *r++; } } *w = '\0'; } /* ------------------------------------------------------------------ */ /* Node auth (X-Bot-Password / Bearer / ?pwd=) */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; char qpwd[256] = {0}; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncasecmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Paths */ /* ------------------------------------------------------------------ */ static const char *home_dir(void) { #ifdef _WIN32 static char home[512]; DWORD n = GetEnvironmentVariableA("USERPROFILE", home, sizeof(home)); if (n > 0 && n < sizeof(home)) return home; home[0] = '\0'; if (GetEnvironmentVariableA("HOMEDRIVE", home, sizeof(home)) > 0) { char tmp[512]; if (GetEnvironmentVariableA("HOMEPATH", tmp, sizeof(tmp)) > 0) { strncat(home, tmp, sizeof(home) - strlen(home) - 1); return home; } } return NULL; #else const char *h = getenv("HOME"); return (h && *h) ? h : NULL; #endif } #if defined(_WIN32) # define PATH_SEP '\\' #else # define PATH_SEP '/' #endif /* accounts json: ANTIGRAVITY_CREDS_PATH, else ~/.config/google-accounts/... */ static void creds_path(char *out, size_t n) { const char *env = getenv("ANTIGRAVITY_CREDS_PATH"); const char *home = home_dir(); if (env && *env) { snprintf(out, n, "%s", env); return; } if (!home) { snprintf(out, n, "antigravity_accounts.json"); return; } snprintf(out, n, "%s%c.config%cgoogle-accounts%cantigravity_accounts.json", home, PATH_SEP, PATH_SEP, PATH_SEP); } /* sibling file next to the accounts json (selected_account.txt and friends) */ static void creds_sibling(const char *name, char *out, size_t n) { char base[PATH_SZ]; char *slash; char sep = PATH_SEP; creds_path(base, sizeof(base)); slash = strrchr(base, sep); if (!slash) slash = strrchr(base, '/'); if (!slash) { snprintf(out, n, "%s", name); return; } *(slash + 1) = '\0'; if (strlen(base) + strlen(name) >= n) { snprintf(out, n, "%s", name); return; } memcpy(out, base, strlen(base) + 1); strncat(out, name, n - strlen(out) - 1); } static void env_dir(char *out, size_t n) { const char *env = getenv("ANTIGRAVITY_ENV_DIR"); const char *creds = getenv("ANTIGRAVITY_CREDS_PATH"); const char *home = home_dir(); if (env && *env) { snprintf(out, n, "%s", env); return; } /* A relocated credential file implies a relocated profile: they are written * by the same CLI into the same tree, and reading one from the default home * while the other is overridden makes status report an empty project for a * session that has one. */ if (creds && *creds) { char base[PATH_SZ]; char *slash; snprintf(base, sizeof(base), "%s", creds); slash = strrchr(base, PATH_SEP); if (!slash) slash = strrchr(base, '/'); if (slash) { *(slash + 1) = '\0'; if (strlen(base) + 16 < n) { snprintf(out, n, "%sscorpiox-env", base); return; } } } if (!home) { snprintf(out, n, "."); return; } snprintf(out, n, "%s%c.claude%cscorpiox-env", home, PATH_SEP, PATH_SEP); } static void pending_path(char *out, size_t n) { const char *env = getenv("ANTIGRAVITY_PENDING_PATH"); const char *home = home_dir(); if (env && *env) { snprintf(out, n, "%s", env); return; } if (!home) { snprintf(out, n, "antigravity-default.json"); return; } snprintf(out, n, "%s%c.claude%c.login-pending%cantigravity-default.json", home, PATH_SEP, PATH_SEP, PATH_SEP); } static const char *login_bin(void) { const char *b = getenv("ANTIGRAVITY_LOGIN_BIN"); return (b && *b) ? b : DEFAULT_LOGIN_BIN; } static const char *token_bin(void) { const char *b = getenv("ANTIGRAVITY_TOKEN_BIN"); return (b && *b) ? b : DEFAULT_TOKEN_BIN; } static int file_exists(const char *p) { #if defined(_WIN32) DWORD a = GetFileAttributesA(p); return a != INVALID_FILE_ATTRIBUTES && !(a & FILE_ATTRIBUTE_DIRECTORY); #else struct stat st; return p && stat(p, &st) == 0 && S_ISREG(st.st_mode); #endif } /* Read a whole file. Returns malloc'd NUL-terminated buffer or NULL. */ static char *read_file(const char *path) { FILE *f; long sz; char *buf; if (!path || !*path) return NULL; f = fopen(path, "rb"); if (!f) return NULL; if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; } sz = ftell(f); if (sz < 0 || sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } buf = (char *)malloc((size_t)sz + 1); if (!buf) { fclose(f); return NULL; } if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { free(buf); fclose(f); return NULL; } buf[sz] = '\0'; fclose(f); return buf; } /* Trim trailing CR/LF/space in place. */ static void trim_tail(char *s) { size_t n; if (!s) return; n = strlen(s); while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' || s[n - 1] == ' ' || s[n - 1] == '\t')) s[--n] = '\0'; } /* ------------------------------------------------------------------ */ /* Minimal JSON field readers */ /* ------------------------------------------------------------------ */ /* Copy a JSON string value that starts at *pp (which points at the opening * quote). Advances *pp past the closing quote. */ static int json_read_string_at(const char **pp, char *out, size_t outsz) { const char *p = *pp; size_t i = 0; if (!p || *p != '"') return 0; p++; while (*p && *p != '"') { char c = *p; if (c == '\\' && p[1]) { p++; switch (*p) { case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'u': { unsigned int v = 0; int k; p++; for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) ? *p - '0' : tolower((unsigned char)*p) - 'a' + 10); if (i + 1 < outsz) out[i++] = (char)(v & 0xff); continue; } default: c = *p; break; } p++; } else { p++; } if (i + 1 < outsz) out[i++] = c; } if (*p == '"') p++; if (outsz) out[i < outsz ? i : outsz - 1] = '\0'; *pp = p; return 1; } /* Skip one JSON value (string, number, literal, object, array). */ static const char *json_skip_value(const char *p) { if (!p) return NULL; while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; if (*p == '"') { char tmp[8]; json_read_string_at(&p, tmp, sizeof(tmp)); return p; } if (*p == '{' || *p == '[') { char open = *p; char close = (open == '{') ? '}' : ']'; int depth = 0; while (*p) { if (*p == '"') { char tmp[8]; json_read_string_at(&p, tmp, sizeof(tmp)); continue; } if (*p == open) depth++; else if (*p == close) { depth--; if (depth == 0) return p + 1; } p++; } return p; } while (*p && *p != ',' && *p != '}' && *p != ']') p++; return p; } /* Find "key": anywhere inside the slice [obj, end) and return the * value pointer. Only top-level keys of that slice are considered: a nested * object is skipped as a whole. */ static const char *json_find_key(const char *obj, const char *end, const char *key) { size_t klen = strlen(key); const char *p = obj; int depth = 0; if (!obj || !end || !key) return NULL; /* A caller almost always hands us the whole object, i.e. a pointer at the * opening '{'. Skipping it here keeps every call site free of the "+1" * that is easy to forget and silent when it is missing. */ while (p < end && (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')) p++; if (p < end && *p == '{') p++; while (p && p < end) { if (*p == '"') { const char *start = p; char name[128]; json_read_string_at(&p, name, sizeof(name)); if (depth == 0 && strlen(name) == klen && strcmp(name, key) == 0) { const char *q = p; while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; if (q < end && *q == ':') { q++; while (q < end && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) q++; return (q < end) ? q : NULL; } } (void)start; continue; } if (*p == '{' || *p == '[') depth++; else if (*p == '}' || *p == ']') depth--; p++; } return NULL; } /* Returns 0 and leaves *out untouched when the key is absent or null. That * matters: several callers pass a field of a longer-lived struct, and clearing * it on a miss silently erases a value that was already correct. */ static int json_str_field(const char *obj, const char *end, const char *key, char *out, size_t outsz) { const char *v; if (!out || outsz == 0) return 0; v = json_find_key(obj, end, key); if (!v || *v == 'n') return 0; out[0] = '\0'; if (*v == '"') return json_read_string_at(&v, out, outsz); { size_t i = 0; while (v < end && *v != ',' && *v != '}' && *v != ']' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; trim_tail(out); return out[0] ? 1 : 0; } } static int json_bool_field(const char *obj, const char *end, const char *key, int dflt) { const char *v = json_find_key(obj, end, key); if (!v) return dflt; if (strncmp(v, "true", 4) == 0) return 1; if (strncmp(v, "false", 5) == 0) return 0; if (*v == '"') { if (strncmp(v + 1, "true", 4) == 0 || strncmp(v + 1, "1", 1) == 0) return 1; return 0; } if (*v == '1') return 1; return 0; } static long long json_num_field(const char *obj, const char *end, const char *key) { const char *v = json_find_key(obj, end, key); if (!v) return 0; if (*v == '"') v++; return atoll(v); } /* ------------------------------------------------------------------ */ /* Child processes */ /* ------------------------------------------------------------------ */ /* Single-quote an argv element for the shell that popen uses. A quote inside * the argument is closed, escaped and reopened, so nothing can break out. */ static void shell_quote_into(const char *in, char *out, size_t outsz) { size_t o = 0; const char *p; if (outsz < 3) { if (outsz) out[0] = '\0'; return; } out[o++] = '\''; for (p = in; p && *p; p++) { if (*p == '\'') { if (o + 5 >= outsz) break; memcpy(out + o, "'\\''", 4); o += 4; } else { if (o + 2 >= outsz) break; out[o++] = *p; } } out[o++] = '\''; out[o] = '\0'; } /* Run ` ` and capture stdout. args may be NULL or a pre-built * shell fragment. Returns 1 when the process ran, 0 when popen failed. The * captured text is stored in out (trimmed). */ static int run_capture(const char *bin, const char *args, buf_t *out) { char cmd[CMD_SZ]; char qbin[FIELD_SZ]; FILE *f; char line[2048]; size_t total = 0; int rc; if (!bin || !*bin) return 0; shell_quote_into(bin, qbin, sizeof(qbin)); if (args && *args) snprintf(cmd, sizeof(cmd), "%s %s 2>/dev/null", qbin, args); else snprintf(cmd, sizeof(cmd), "%s 2>/dev/null", qbin); f = popen(cmd, "r"); if (!f) return 0; while (fgets(line, sizeof(line), f)) { total += strlen(line); if (total > OUT_MAX) break; buf_adds(out, line); } rc = pclose(f); if (out->p) { /* the CLIs print one JSON line last; strip surrounding whitespace */ size_t n = out->n; while (n > 0 && isspace((unsigned char)out->p[n - 1])) out->p[--n] = '\0'; out->n = n; } /* pclose() hands back a wait status, not an exit code: "command not * found" arrives as 32512 (127 << 8). Callers treat that as "the CLI is * not on this node", which is a different message from "the CLI ran and * failed". Any other status is the CLI's own and is left to the JSON it * printed. */ if (rc != -1 && (rc >> 8) == 127) return -1; return 1; } /* The login/token CLIs print human progress on stdout before the final JSON * line, so take the LAST line that starts with '{'. */ static const char *last_json_line(buf_t *b) { size_t i; const char *last = NULL; if (!b || !b->p) return NULL; for (i = 0; i < b->n; i++) { int at_line_start = (i == 0) || b->p[i - 1] == '\n'; if (at_line_start && b->p[i] == '{') last = b->p + i; } return last; } /* ------------------------------------------------------------------ */ /* Status assembly */ /* ------------------------------------------------------------------ */ typedef struct { int logged_in; int has_refresh; int pending; int expired; int cli_present; char email[EMAIL_SZ]; char account[EMAIL_SZ]; char project[PROJ_SZ]; char path[PATH_SZ]; char profile[PROJ_SZ]; long long expires_at; /* unix seconds, 0 = unknown */ /* long long, not int: expires_at - now overflows a 32-bit int for any * expiry past 2038, which turned a valid session into "expires in * -1987015054s" in the UI while expired stayed false. */ long long expires_in_sec; /* negative when expired, 0 when unknown */ } status_t; /* Pull email / refresh_token presence out of the accounts array. * * The file is a JSON array of {email, refresh_token}. The selected account * wins; otherwise the first entry that carries a refresh token. Presence of a * refresh token is the login signal, and only its presence is recorded - the * value is never copied. */ static void scan_accounts(const char *json, const char *selected, status_t *st) { const char *p = json; char first_email[EMAIL_SZ] = {0}; int first_has = 0; int found = 0; while (p && *p) { const char *open = strchr(p, '{'); const char *obj; const char *end; char email[EMAIL_SZ] = {0}; char rt[8] = {0}; int has_rt; if (!open) break; end = json_skip_value(open); if (!end || end <= open) break; /* json_find_key tracks brace depth, so it must start INSIDE the * object: passing the opening '{' makes every top-level key look * nested and the whole scan silently returns nothing. */ obj = open; json_str_field(obj, end, "email", email, sizeof(email)); has_rt = json_str_field(obj, end, "refresh_token", rt, sizeof(rt)); if (!first_email[0] && email[0]) { snprintf(first_email, sizeof(first_email), "%s", email); first_has = has_rt; } if (selected && selected[0] && email[0] && strcmp(email, selected) == 0) { snprintf(st->email, sizeof(st->email), "%s", email); st->has_refresh = has_rt; found = 1; p = end; break; } p = end; } if (!found) { if (first_email[0]) snprintf(st->email, sizeof(st->email), "%s", first_email); st->has_refresh = first_has; } st->logged_in = st->has_refresh; } /* Parse GOOGLE_PROJECT_ID / GOOGLE_ACCOUNT out of the profile file. */ static void scan_profile(const char *text, status_t *st) { const char *p = text; while (p && *p) { const char *nl = strchr(p, '\n'); size_t len = nl ? (size_t)(nl - p) : strlen(p); char line[FIELD_SZ]; size_t i; if (len > 0 && len < sizeof(line)) { memcpy(line, p, len); line[len] = '\0'; trim_tail(line); for (i = 0; line[i]; i++) if (line[i] == '\r') line[i] = ' '; if (strncmp(line, "GOOGLE_PROJECT_ID=", 18) == 0 && !st->project[0]) { snprintf(st->project, sizeof(st->project), "%.*s", (int)sizeof(st->project) - 1, line + 18); } else if (strncmp(line, "GOOGLE_ACCOUNT=", 15) == 0 && !st->account[0]) { snprintf(st->account, sizeof(st->account), "%.*s", (int)sizeof(st->account) - 1, line + 15); } } if (!nl) break; p = nl + 1; } } static void collect_status(status_t *st) { char acct[PATH_SZ], sel[PATH_SZ], prof[PATH_SZ], pend[PATH_SZ]; char *text; char selected[EMAIL_SZ] = {0}; long long now = (long long)time(NULL); memset(st, 0, sizeof(*st)); st->profile[0] = '\0'; creds_path(acct, sizeof(acct)); snprintf(st->path, sizeof(st->path), "%s", acct); creds_sibling("selected_account.txt", sel, sizeof(sel)); text = read_file(sel); if (text) { trim_tail(text); snprintf(selected, sizeof(selected), "%s", text); free(text); } text = read_file(acct); if (text) { scan_accounts(text, selected, st); free(text); } /* The profile file carries the companion project and the account email. */ env_dir(prof, sizeof(prof)); { char pfile[PATH_SZ + 32]; char *ptext; if (strlen(prof) + 16 < sizeof(pfile)) snprintf(pfile, sizeof(pfile), "%s%cantigravity.txt", prof, PATH_SEP); else snprintf(pfile, sizeof(pfile), "antigravity.txt"); ptext = read_file(pfile); if (ptext) { scan_profile(ptext, st); snprintf(st->profile, sizeof(st->profile), "antigravity"); free(ptext); } } if (!st->email[0] && st->account[0]) snprintf(st->email, sizeof(st->email), "%s", st->account); if (!st->account[0] && st->email[0]) snprintf(st->account, sizeof(st->account), "%s", st->email); /* Pending flow marker (the CLI writes and removes this file). */ pending_path(pend, sizeof(pend)); st->pending = file_exists(pend); /* Ask the CLI when it is on PATH: it knows the token expiry and the exact * pending state, and it is the authority on logged_in. The plugin never * becomes the source of truth about a Google session. */ { buf_t out; buf_init(&out); if (run_capture(login_bin(), "--status", &out) > 0) { const char *j = last_json_line(&out); if (j) { const char *end = j + strlen(j); char identity[EMAIL_SZ] = {0}; long long exp = 0; st->cli_present = 1; json_str_field(j, end, "identity", identity, sizeof(identity)); json_str_field(j, end, "path", st->path, sizeof(st->path)); /* The CLI is authoritative, but never a downgrade: if the * credential file on disk carries a refresh token, the node IS * signed in and an older CLI build that answers logged_in:false * must not paint a green session grey. */ if (json_bool_field(j, end, "logged_in", 0)) st->logged_in = 1; if (json_bool_field(j, end, "has_refresh", 0)) { st->has_refresh = 1; st->logged_in = 1; } /* pending: the marker file is the authority (it is created by * --start and removed by --finish/--cancel), so a CLI answer is * only allowed to ADD a pending state, never to clear one. */ if (json_bool_field(j, end, "pending", 0)) st->pending = 1; exp = json_num_field(j, end, "expires_at"); if (exp > 0 && exp < 100000000000LL) exp *= 1000; /* seconds -> ms */ if (exp > 0) st->expires_at = exp / 1000; if (identity[0] && !st->email[0]) snprintf(st->email, sizeof(st->email), "%s", identity); if (identity[0] && !st->account[0]) snprintf(st->account, sizeof(st->account), "%s", identity); } } buf_free(&out); } if (st->expires_at > 0) { st->expires_in_sec = st->expires_at - now; st->expired = st->expires_at <= now; } if (!st->logged_in) { st->expired = 0; st->expires_in_sec = 0; } } /* One status object. Shared by every action's response so the UI can always * re-render from the same shape. */ static void emit_status(buf_t *b, const status_t *st) { buf_addf(b, "\"logged_in\":%s,", st->logged_in ? "true" : "false"); buf_adds(b, "\"email\":"); buf_json(b, st->email); buf_addf(b, ",\"account\":"); buf_json(b, st->account); buf_addf(b, ",\"project_id\":"); buf_json(b, st->project); buf_addf(b, ",\"profile\":"); buf_json(b, st->profile); buf_addf(b, ",\"expires_at\":%lld", st->expires_at); buf_addf(b, ",\"expires_in_sec\":%lld", st->expires_in_sec); buf_addf(b, ",\"expired\":%s", st->expired ? "true" : "false"); buf_addf(b, ",\"has_refresh\":%s", st->has_refresh ? "true" : "false"); buf_addf(b, ",\"pending\":%s", st->pending ? "true" : "false"); buf_addf(b, ",\"cli_present\":%s", st->cli_present ? "true" : "false"); buf_addf(b, ",\"credentials_path\":"); buf_json(b, st->path); } /* ------------------------------------------------------------------ */ /* Actions */ /* ------------------------------------------------------------------ */ static void json_headers(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void emit_error(int code, const char *status, const char *err, const char *detail) { buf_t b; buf_init(&b); buf_addf(&b, "Status: %d %s\r\nContent-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n\r\n", code, status); buf_addf(&b, "{\"ok\":false,\"error\":"); buf_json(&b, err); if (detail && *detail) { buf_addf(&b, ",\"detail\":"); buf_json(&b, detail); } buf_addf(&b, "}\n"); fputs(buf_str(&b), stdout); buf_free(&b); } static int action_status(void) { status_t st; buf_t b; collect_status(&st); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\","); emit_status(&b, &st); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } static int action_start(void) { buf_t out, b; const char *j; char auth_url[CMD_SZ] = {0}; char flow[64] = {0}; char hint[512] = {0}; long long expires_in = 0; buf_init(&out); if (run_capture(login_bin(), "--start", &out) <= 0) { buf_free(&out); emit_error(200, "OK", "cli_unavailable", "the login CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_LOGIN_BIN"); return 1; } j = last_json_line(&out); if (!j) { buf_free(&out); emit_error(200, "OK", "start_failed", buf_str(&out)); return 1; } { const char *end = j + strlen(j); json_str_field(j, end, "auth_url", auth_url, sizeof(auth_url)); json_str_field(j, end, "flow", flow, sizeof(flow)); json_str_field(j, end, "hint", hint, sizeof(hint)); expires_in = json_num_field(j, end, "expires_in"); if (!json_bool_field(j, end, "ok", 1) || !auth_url[0]) { char detail[FIELD_SZ] = {0}; json_str_field(j, end, "error", detail, sizeof(detail)); buf_free(&out); emit_error(200, "OK", detail[0] ? detail : "start_failed", "the login CLI did not return an authorization URL"); return 1; } } buf_free(&out); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"flow\":"); buf_json(&b, flow[0] ? flow : "paste_code"); buf_adds(&b, ",\"auth_url\":"); buf_json(&b, auth_url); buf_addf(&b, ",\"expires_in\":%lld", expires_in > 0 ? expires_in : 900); buf_adds(&b, ",\"hint\":"); buf_json(&b, hint[0] ? hint : "Sign in with Google and approve. The browser lands on antigravity.google - copy the whole address (or just the code) and paste it here."); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } /* Reject anything that cannot be an authorization code. The value is passed * to a shell, so this is the second line of defence behind shell_quote_into. */ static int valid_code(const char *code) { size_t n, i; if (!code || !(n = strlen(code)) || n > CODE_MAX) return 0; for (i = 0; i < n; i++) { unsigned char c = (unsigned char)code[i]; if (c < 0x20 || c == 0x7f || c == '\'' || c == '"' || c == '\\' || c == ';' || c == '`' || c == '$' || c == '|' || c == '&' || c == '<' || c == '>' || c == '\n' || c == '\r') return 0; } return 1; } static int action_finish(const char *raw_code) { char code[CODE_MAX]; char qcode[CODE_MAX + 64]; buf_t out, b; const char *j; if (!raw_code) { emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=..."); return 1; } snprintf(code, sizeof(code), "%s", raw_code); url_decode(code); trim_tail(code); /* The user usually pastes the whole redirect address, which is what the * login CLI expects too (its lm_clean_code does the same extraction). Pull * out code= before validating, so a legitimate URL is not rejected for * carrying a state= parameter alongside it. */ { char *c = strstr(code, "code="); if (c) { char extracted[CODE_MAX]; size_t i = 0; c += 5; while (*c && *c != '&' && *c != '#' && i + 1 < sizeof(extracted)) extracted[i++] = *c++; extracted[i] = '\0'; if (i > 0) snprintf(code, sizeof(code), "%s", extracted); } } if (!valid_code(code)) { emit_error(400, "Bad Request", "invalid_code", "the value is not an authorization code (empty, too long, or contains shell characters)"); return 1; } shell_quote_into(code, qcode, sizeof(qcode)); { char args[CODE_MAX + 128]; snprintf(args, sizeof(args), "--finish %s", qcode); buf_init(&out); if (run_capture(login_bin(), args, &out) <= 0) { buf_free(&out); emit_error(200, "OK", "cli_unavailable", "the login CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_LOGIN_BIN"); return 1; } } j = last_json_line(&out); if (!j) { buf_free(&out); emit_error(200, "OK", "finish_failed", "the login CLI returned no JSON"); return 1; } if (!json_bool_field(j, (const char *)(j + strlen(j)), "ok", 0)) { char detail[FIELD_SZ] = {0}; const char *end = j + strlen(j); json_str_field(j, end, "error", detail, sizeof(detail)); buf_free(&out); emit_error(200, "OK", detail[0] ? detail : "finish_failed", "Google rejected the code, or the account needs verification in a browser"); return 1; } buf_free(&out); /* Success: re-read everything so the caller gets the full new state. */ { status_t st; collect_status(&st); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"state\":\"done\","); emit_status(&b, &st); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); } return 0; } static int action_cancel(void) { buf_t out, b; buf_init(&out); run_capture(login_bin(), "--cancel", &out); buf_free(&out); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"state\":\"cancelled\",\"pending\":false}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 0; } /* Refresh: the token CLI performs the refresh-token grant and prints the * access token. We deliberately keep only ok/project and drop the token, so a * browser (or a proxy log) can never capture a bearer token from this route. */ static int action_refresh(void) { buf_t out, b; const char *j; char project[PROJ_SZ] = {0}; char err[FIELD_SZ] = {0}; int ok = 0; buf_init(&out); if (run_capture(token_bin(), "-local", &out) <= 0) { buf_free(&out); emit_error(200, "OK", "cli_unavailable", "the token CLI is not on this node; install SCORPIOX CODE or set ANTIGRAVITY_TOKEN_BIN"); return 1; } j = last_json_line(&out); if (j) { const char *end = j + strlen(j); char tok[8] = {0}; ok = json_bool_field(j, end, "ok", 0); json_str_field(j, end, "project_id", project, sizeof(project)); (void)json_str_field(j, end, "access_token", tok, sizeof(tok)); /* presence only */ if (!ok) json_str_field(j, end, "error", err, sizeof(err)); } buf_free(&out); if (!ok) { buf_init(&b); buf_adds(&b, "{\"ok\":false,\"error\":\"refresh_failed\",\"detail\":"); buf_json(&b, err[0] ? err : "the token CLI could not refresh the session; sign in again"); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); return 1; } { status_t st; collect_status(&st); if (project[0]) snprintf(st.project, sizeof(st.project), "%s", project); buf_init(&b); buf_adds(&b, "{\"ok\":true,\"refreshed\":true,"); emit_status(&b, &st); buf_adds(&b, "}\n"); json_headers(); fputs(buf_str(&b), stdout); buf_free(&b); } return 0; } /* ------------------------------------------------------------------ */ /* HTML emission */ /* ------------------------------------------------------------------ */ /* Expand the two placeholders gen_ui.py leaves in UI_HTML. Keeping this split * means the palette lives in exactly one place (bot_theme_plugin.h) and the * page can never drift away from the bot's own theme. */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { fputs(SX_BOT_THEME_HANDOFF, stdout); p++; } else { putchar(*p++); } } } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *qs; char action[64] = {0}; /* 1. Discovery metadata. Must stay unauthenticated. */ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}"); return 0; } if (argc > 1 && (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0)) { puts(PLUGIN_ID " " PLUGIN_VER); return 0; } require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; /* 2. JSON API mode. `format=json` alone means "status", which is what a * dashboard polls. */ if (query_has(qs, "action") || query_has(qs, "format")) { char fmt[32] = {0}; char code[CODE_MAX] = {0}; get_query_val(qs, "action", action, sizeof(action)); get_query_val(qs, "format", fmt, sizeof(fmt)); if (!action[0] && strcmp(fmt, "json") == 0) snprintf(action, sizeof(action), "status"); if (strcmp(action, "status") == 0 || !action[0]) return action_status(); if (strcmp(action, "start") == 0) return action_start(); if (strcmp(action, "cancel") == 0) return action_cancel(); if (strcmp(action, "refresh") == 0) return action_refresh(); if (strcmp(action, "finish") == 0) { if (!get_query_val(qs, "code", code, sizeof(code))) { char body[OUT_MAX]; size_t len = 0; /* POST bodies carry the code too (a long code is easier to * send as a body). Guard on CONTENT_LENGTH so an empty * inherited stdin never blocks. */ { const char *cl = getenv("CONTENT_LENGTH"); long n = (cl && *cl) ? atol(cl) : 0; if (n > 0 && n < (long)sizeof(body)) { len = fread(body, 1, (size_t)n, stdin); body[len] = '\0'; { char *p = strstr(body, "\"code\""); if (p) { p = strchr(p, ':'); if (p) { p++; while (*p == ' ' || *p == '\t' || *p == '"') p++; { size_t i = 0; while (*p && *p != '"' && *p != ',' && *p != '}' && i + 1 < sizeof(code)) code[i++] = *p++; code[i] = '\0'; } } } } } } if (!code[0]) { emit_error(400, "Bad Request", "missing_code", "pass the authorization code as &code=..."); return 1; } } return action_finish(code); } emit_error(404, "Not Found", "unknown_action", action); return 1; } /* 3. HTML UI. The page and its theme arrive from the generated header. * UI_HTML carries two control bytes: 0x01 is the theme block (